This file is indexed.

/usr/share/pyshared/dolfin/functions/function.py is in python-dolfin 1.0.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""This module handles the Function class in Python.
"""
# Copyright (C) 2009 Johan Hake
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DOLFIN is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# First added:  2009-10-06
# Last changed: 2011-04-18

__all__ = ["Function", "TestFunction", "TrialFunction", "Argument",
           "TestFunctions", "TrialFunctions"]

import types

# Import UFL and SWIG-generated extension module (DOLFIN C++)
import ufl
import dolfin.cpp as cpp
import numpy

from dolfin.functions.functionspace import FunctionSpaceBase

class MetaNoEvalOverloading(type):
    def __init__(mcs, name, bases, dictionary):
        if "eval" in dictionary:
            raise TypeError, "cannot overload 'eval'"

class Function(ufl.Coefficient, cpp.Function):
    """
    This class represents a function :math:`u_h` in a finite
    element function space :math:`V_h`, given by

    .. math::

        u_h = \sum_{i=1}^n U_i \phi_i,

    where :math:`\{\phi_i\}_{i=1}^n` is a basis for :math:`V_h`,
    and :math:`U` is a vector of expansion coefficients for
    :math:`u_h`.

    *Arguments*
        There is a maximum of two arguments. The first argument must be a
        Function or a :py:class:`FunctionSpace
        <dolfin.functions.functionspace.FunctionSpace>`.

        If instantiated from another Function, the (optional)
        second argument must be an integer denoting the number
        of sub functions to extract.

    *Examples*
        Create a Function:

        - from a :py:class:`FunctionSpace
          <dolfin.functions.functionspace.FunctionSpace>` ``V``

          .. code-block:: python

              f = Function(V)

        - from another Function ``f``

          .. code-block:: python

              g = Function(f)

        - from a :py:class:`FunctionSpace
          <dolfin.functions.functionspace.FunctionSpace>` ``V`` and a
          :py:class:`GenericVector <dolfin.cpp.GenericVector>` ``v``

          .. code-block:: python

              g = Function(V, v)

        - from a :py:class:`FunctionSpace
          <dolfin.functions.functionspace.FunctionSpace>` and a
          filename containg a :py:class:`GenericVector
          <dolfin.cpp.GenericVector>`

          .. code-block:: python

              g = Function(V, 'MyVectorValues.xml')

    """

    __metaclass__ = MetaNoEvalOverloading

    def __init__(self, *args):
        """Initialize Function."""
        # Check arguments
        if len(args) == 0:
            raise TypeError, "expected 1 or more arguments"

        if not isinstance(args[0], (FunctionSpaceBase, Function)):
            raise TypeError, "expected a FunctionSpace or a Function as argument 1"

        # If using the copy constuctor
        if isinstance(args[0], Function):
            other = args[0]
            # If using the copy constuctor
            if len(args) == 1:
                # Instantiate base classes
                cpp.Function.__init__(self, other)
                ufl.Coefficient.__init__(self, other._element)
                return

            # If using sub-function constructor
            elif len(args) == 2 and isinstance(args[1], int):
                i = args[1]
                num_sub_spaces = other.function_space().num_sub_spaces()

                if num_sub_spaces == 1:
                    raise RuntimeError, "No subfunctions to extract"
                if not i < num_sub_spaces:
                    raise RuntimeError, "Can only extract subfunctions with i = 0..%d"% num_sub_spaces
                cpp.Function.__init__(self, other, i)
                ufl.Coefficient.__init__(self, self.function_space().ufl_element())
                return
            else:
                raise TypeError, "expected one or two arguments when instantiating from another Function"

        V = args[0]

        # Instantiate ufl base class
        ufl.Coefficient.__init__(self, V.ufl_element())

        # Passing only the FunctionSpace
        if len(args) == 1:
            # Instantiate cpp base classes
            cpp.Function.__init__(self, V)
        elif len(args) == 2:
            # If passing FunctionSpace together with cpp.Function
            # Attached passed FunctionSpace and initialize the cpp.Function
            # using the passed Function
            if isinstance(args[1], cpp.Function):
                if args[1].function_space().dim() != V.dim():
                    raise ValueError, "non matching dimensions on passed FunctionSpaces"

                cpp.Function.__init__(self, args[1])
            else:
                cpp.Function.__init__(self, *args)
        else:
            raise TypeError, "too many arguments"

    def _sub(self, i, deepcopy = False):
        """Return a sub function.

        The sub functions are numbered from i = 0..N-1, where N is the
        total number of sub spaces.

        *Arguments*
            i
                The number of the sub function

        """
        if not isinstance(i, int):
            raise TypeError, "expects an 'int' as first argument"
        num_sub_spaces = self.function_space().num_sub_spaces()
        if num_sub_spaces == 1:
            raise RuntimeError, "No subfunctions to extract"
        if not i < num_sub_spaces:
            raise RuntimeError, "Can only extract subfunctions with i = 0..%d"% num_sub_spaces

        # Create and instantiate the Function
        if deepcopy:
            return Function(self.function_space().sub(i), cpp.Function._sub(self, i))
        else:
            return Function(self, i)

    def split(self, deepcopy=False):
        """
        Extract any sub functions.

        A sub function can be extracted from a discrete function that
        is in a :py:class:`MixedFunctionSpace
        <dolfin.functions.functionspace.MixedFunctionSpace>` or in a
        :py:class:`VectorFunctionSpace
        <dolfin.functions.functionspace.VectorFunctionSpace>`. The sub
        function resides in the subspace of the mixed space.

        *Arguments*
            deepcopy
                Copy sub function vector instead of sharing

        """

        num_sub_spaces = self.function_space().num_sub_spaces()
        if num_sub_spaces == 1:
            raise RuntimeError, "No subfunctions to extract"
        return tuple(self._sub(i, deepcopy) for i in xrange(num_sub_spaces))

    def ufl_element(self):
        """Return ufl element"""
        return self._element

    def __str__(self):
        """Return a pertty print representation of it self.

        Use ufl.__str__ is used for this.
        """
        return ufl.Coefficient.__str__(self)

    def __repr__(self):
        """Return a str repr of it self.

        Must use ufl.__repr__ for this"""
        return ufl.Coefficient.__repr__(self)

    def str(self, verose=False):
        """Return an informative str representation of itself"""
        # FIXME: We might change this using rank and dimension instead
        return "<Function in %s>" % str(self.function_space())

    def ufl_evaluate(self, x, component, derivatives):
        """Function used by ufl to evaluate the Function"""
        import numpy
        import ufl
        assert derivatives == () # TODO: Handle derivatives

        if component:
            shape = self.shape()
            assert len(shape) == len(component)
            value_size = ufl.common.product(shape)
            index = ufl.common.component_to_index(component, shape)
            values = numpy.zeros(value_size)
            self(*x, values=values)
            return values[index]
        else:
            # Scalar evaluation
            return self(*x)

    def __call__(self, *args, **kwargs):
        """
        Evaluates the Function.

        *Examples*
            1) Using an iterable as x:

              .. code-block:: python

                  fs = Expression("sin(x[0])*cos(x[1])*sin(x[3])")
                  x0 = (1.,0.5,0.5)
                  x1 = [1.,0.5,0.5]
                  x2 = numpy.array([1.,0.5,0.5])
                  v0 = fs(x0)
                  v1 = fs(x1)
                  v2 = fs(x2)

            2) Using multiple scalar args for x, interpreted as a
            point coordinate

              .. code-block:: python

                  v0 = f(1.,0.5,0.5)

            3) Using a Point

              .. code-block:: python

                  p0 = Point(1.,0.5,0.5)
                  v0 = f(p0)

            3) Passing return array

              .. code-block:: python

                  fv = Expression(("sin(x[0])*cos(x[1])*sin(x[3])",
                               "2.0","0.0"))
                  x0 = numpy.array([1.,0.5,0.5])
                  v0 = numpy.zeros(3)
                  fv(x0, values = v0)

              .. note::

                  A longer values array may be passed. In this way one can fast
                  fill up an array with different evaluations.

              .. code-block:: python

                  values = numpy.zeros(9)
                  for i in xrange(0,10,3):
                      fv(x[i:i+3], values = values[i:i+3])

        """

        if len(args)==0:
            raise TypeError, "expected at least 1 argument"

        # Test for ufl restriction
        if len(args) == 1 and args[0] in ('+','-'):
            return ufl.Coefficient.__call__(self, *args)

        # Test for ufl mapping
        if len(args) == 2 and isinstance(args[1], dict) and self in args[1]:
            return ufl.Coefficient.__call__(self, *args)

        # Some help variables
        value_size = ufl.common.product(self.ufl_element().value_shape())

        # If values (return argument) is passed, check the type and length
        values = kwargs.get("values", None)
        if values is not None:
            if not isinstance(values, numpy.ndarray):
                raise TypeError, "expected a NumPy array for 'values'"
            if len(values) != value_size or \
                   not numpy.issubdtype(values.dtype, 'd'):
                raise TypeError, "expected a double NumPy array of length"\
                      " %d for return values."%value_size
            values_provided = True
        else:
            values_provided = False
            values = numpy.zeros(value_size, dtype='d')

        # Get the dimension of the cell
        dim = self.ufl_element().cell().geometric_dimension()

        # Assume all args are x argument
        x = args

        # If only one x argument has been provided, unpack it if it's an iterable
        if len(x) == 1:
            if isinstance(x[0], cpp.Point):
                x = (x[0][i] for i in xrange(dim))
            elif hasattr(x[0], '__iter__'):
                x = x[0]

        # Convert it to an 1D numpy array
        try:
            x = numpy.fromiter(x, 'd')
        except (TypeError, ValueError, AssertionError):
            raise TypeError, "expected scalar arguments for the coordinates"

        if len(x) == 0:
            raise TypeError, "coordinate argument too short"

        if len(x) != dim:
            raise TypeError, "expected the geometry argument to be of "\
                  "length %d"%dim

        # The actual evaluation
        self.eval(values, x)

        # If scalar return statement, return scalar value.
        if value_size == 1 and not values_provided:
            return values[0]

        return values

#--- Subclassing of ufl.{Basis, Trial, Test}Function ---

class Argument(ufl.Argument):
    """An Argument represents a possibly differentiated component
    of an argument on the reference cell.
    """
    def __init__(self, V, index=None):
        if not isinstance(V, FunctionSpaceBase):
            raise TypeError, "Illegal argument for creation of Argument, not a FunctionSpace: " + str(V)
        ufl.Argument.__init__(self, V.ufl_element(), index)
        self._V = V

    def function_space(self):
        "Return the FunctionSpace"
        return self._V

def TrialFunction(V):
    """A TrialFunction is the Argument with the next lowest primary
    index. We simply pick an index lower than almost all others (-1).
    """
    return Argument(V, -1)

def TestFunction(V):
    """A TestFunction is the Argument with the lowest primary
    index. We simply pick an index lower than all others (-2).
    """
    return Argument(V, -2)

#--- TestFunctions and TrialFunctions ---

def TestFunctions(V):
    "Create test functions from mixed function space."
    return ufl.split(TestFunction(V))

def TrialFunctions(V):
    "Create trial functions from mixed function space."
    return ufl.split(TrialFunction(V))