コード例 #1
0
ファイル: variable.py プロジェクト: regmi/fipy
    def _BinaryOperatorVariable(self, op, other, operatorClass=None, opShape=None, canInline=True, unit=None):
        """
        :Parameters:
          - `op`: the operator function to apply (takes two arguments for `self` and `other`)
          - `other`: the quantity to be operated with
          - `operatorClass`: the `Variable` class that the binary operator should inherit from 
          - `opShape`: the shape that should result from the operation
        """
        if not isinstance(other, Variable):
            from fipy.variables.constant import _Constant
            other = _Constant(value=other)

        opShape, baseClass, other = self._shapeClassAndOther(opShape, operatorClass, other)
        
        if opShape is None or baseClass is None:
            return NotImplemented
    
        for v in [self, other]:
            if not v.getUnit().isDimensionless():
                canInline = False
                
        # obtain a general operator class with the desired base class
        operatorClass = operatorClass or self._OperatorVariableClass(baseClass)
        from fipy.variables import binaryOperatorVariable
        binOp = binaryOperatorVariable._BinaryOperatorVariable(operatorClass)
        
        return binOp(op=op, var=[self, other], opShape=opShape, canInline=canInline, unit=unit, 
                     inlineComment=inline._operatorVariableComment(canInline=canInline))
コード例 #2
0
ファイル: variable.py プロジェクト: regmi/fipy
 def _requires(self, var):
     if isinstance(var, Variable):
         self.requiredVariables.append(var)
         var._requiredBy(self)
         self._markStale()
     else:
         from fipy.variables.constant import _Constant
         var = _Constant(value=var)
         
     return var
コード例 #3
0
ファイル: variable.py プロジェクト: regmi/fipy
 def dot(self, other, opShape=None, operatorClass=None, axis=0):
     if not isinstance(other, Variable):
         from fipy.variables.constant import _Constant
         other = _Constant(value=other)
     if opShape is None:
         opShape = self._broadcastShape(other)
     return self._BinaryOperatorVariable(lambda a,b: numerix.dot(a,b, axis=axis), 
                                         other, 
                                         opShape=opShape[:axis]+opShape[axis+1:],
                                         operatorClass=operatorClass,
                                         canInline=False)
コード例 #4
0
ファイル: meshVariable.py プロジェクト: calbaker/FiPy-2.1.3
 def _globalToLocalValue(self, value):
     if value is not None:
         if not isinstance(value, Variable):
             value = _Constant(value)
         valueShape = value.getShape()
         if valueShape is not () and valueShape[-1] == self._getGlobalNumberOfElements():
             if valueShape[-1] != 0:
                 # workaround for NumPy:ticket:1171
                 value = value[..., self._getGlobalOverlappingIDs()]
                 
         value = value.getValue()
     return value
コード例 #5
0
    def _globalToLocalValue(self, value):
        if value is not None:
            if not isinstance(value, Variable):
                value = _Constant(value)
            valueShape = value.shape
            if valueShape is not (
            ) and valueShape[-1] == self._globalNumberOfElements:
                if valueShape[-1] != 0:
                    # workaround for NumPy:ticket:1171
                    value = value[..., self._globalOverlappingIDs]

            value = value.value
        return value
コード例 #6
0
    def __init__(self, coeff=1., var=None):
        if self.__class__ is CellTerm:
            raise AbstractBaseClassError

        from fipy.variables.variable import Variable

        if not isinstance(coeff, Variable):
            from fipy.variables.constant import _Constant
            coeff = _Constant(value=coeff)

        if isinstance(coeff, FaceVariable):
            raise TypeError("The coefficient can not be a FaceVariable.")

        _NonDiffusionTerm.__init__(self, coeff=coeff, var=var)
        self.coeffVectors = None
        self._var = None
コード例 #7
0
ファイル: cellTerm.py プロジェクト: usnistgov/fipy
    def __init__(self, coeff=1., var=None):
        if self.__class__ is CellTerm:
            raise AbstractBaseClassError

        from fipy.variables.variable import Variable

        if not isinstance(coeff, Variable):
            from fipy.variables.constant import _Constant
            coeff = _Constant(value=coeff)

        if isinstance(coeff, FaceVariable):
             raise TypeError("The coefficient can not be a FaceVariable.")

        _NonDiffusionTerm.__init__(self, coeff=coeff, var=var)
        self.coeffVectors = None
        self._var = None
コード例 #8
0
ファイル: cellTerm.py プロジェクト: regmi/fipy
    def __init__(self, coeff=1.):
        if self.__class__ is CellTerm:
            raise NotImplementedError, "can't instantiate abstract base class"
            
        from fipy.variables.variable import Variable
        if not isinstance(coeff, Variable):
            from fipy.variables.constant import _Constant
            coeff = _Constant(value=coeff)

        from fipy.variables.cellVariable import CellVariable
        if ((isinstance(coeff, CellVariable) and coeff.getRank() != 0)
            or (not isinstance(coeff, CellVariable) and coeff.shape != ())):
                raise TypeError, "The coefficient must be a rank-0 CellVariable or a scalar value."

        Term.__init__(self, coeff=coeff)
        self.coeffVectors = None
        self._var = None
コード例 #9
0
ファイル: meshVariable.py プロジェクト: calbaker/FiPy-2.1.3
 def rdot(self, other, opShape=None, operatorClass=None):
     """
     Return the mesh-element--by--mesh-element (cell-by-cell, face-by-face,
     etc.) scalar product
     
     .. math::
         
        \text{other} \cdot \text{self}
        
     Both `self` and `other` can be of arbitrary rank, and `other` does not
     need to be a `_MeshVariable`.
     """
     if not isinstance(other, Variable):
         from fipy.variables.constant import _Constant
         other = _Constant(value=other)
     opShape, baseClass, other = self._shapeClassAndOther(opShape=None, operatorClass=None, other=other)
     
     return self.__dot(other, self, self._OperatorVariableClass(baseClass))
コード例 #10
0
    def rdot(self, other, opShape=None, operatorClass=None):
        """
        Return the mesh-element--by--mesh-element (cell-by-cell, face-by-face,
        etc.) scalar product
        
        .. math::
            
           \text{other} \cdot \text{self}
           
        Both `self` and `other` can be of arbitrary rank, and `other` does not
        need to be a `_MeshVariable`.
        """
        if not isinstance(other, Variable):
            from fipy.variables.constant import _Constant
            other = _Constant(value=other)
        opShape, baseClass, other = self._shapeClassAndOther(
            opShape=None, operatorClass=None, other=other)

        return self.__dot(other, self, self._OperatorVariableClass(baseClass))
コード例 #11
0
ファイル: meshVariable.py プロジェクト: calbaker/FiPy-2.1.3
    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)
コード例 #12
0
ファイル: variable.py プロジェクト: regmi/fipy
 def __makeVariable(v):
     if not isinstance(v, Variable):
         v = _Constant(v)
     return v
コード例 #13
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)