This file is indexed.

/usr/share/pyshared/viper/viper_dolfin.py is in python-viper 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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/env python

# Copyright (C) 2006-2011 Ola Skavhaug and Simula Research Laboratory
#
# This file is part of Viper.
#
# Viper 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.
#
# Viper 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 Viper. If not, see <http://www.gnu.org/licenses/>.

__cite__      = """Ola Skavhaug, Viper Visualization Software,
http://www.fenicsproject.org"""
__version__ = "1.0.0"

__doc__ = """
Viper for DOLFIN

A simple mesh plotter and run--time visualization module for plotting and
saving simulation data. Adjusted Viper for plotting native DOLFIN data
structures like dolfin::Mesh, dolfin::MeshFunction, and dolfin::Function.

Citation: %s

""" % __cite__

from viper import Viper as ViperBase
import dolfin
from dolfin.cpp import Mesh, MeshFunctionInt, MeshFunctionUInt, MeshFunctionBool, MeshFunctionDouble, GenericFunction, Function, Expression, FunctionSpace, FunctionPlotData
import numpy
import vtk

import ffc

_plotter = None

plottable = [('mesh',             (Mesh,)),
             ('genericfunction',  (GenericFunction,)),
             ('functionplotdata', (FunctionPlotData,)),
             ('meshfunction',     tuple(eval("MeshFunction%s" % t) for t in ["Int", "UInt", "Double", "Bool"]))]

class Viper(ViperBase):
    """A custom Viper sub-class for visualizing meshes and fields in Dolfin."""

    def __init__(self, data, *args, **kwargs):
        self._update = self.update
        self.update = self.dolfin_update
        kwargs["rescale"] = kwargs.get("rescale", True)
        self.initcommon(kwargs)
        self.warpscalar = True
        self.lutfile = kwargs.get("lutfile", "gauss_120.lut")
        self.plot(data, *args, **kwargs)


    def parse_input(self, args, kwargs):
        if len(args) == 1 and isinstance(args[0], str):
            lst = [s.strip() for s in args[0].split(",")]
            ar = []
            kw = {}
            for l in lst:
                if "=" in l:
                    (k,v) = l.split("=")
                    kw[k] = eval(v)
                else:
                    ar.append(eval(l))
            return ar, kw
        return args, kwargs

    def plot(self, data, *args, **kwargs):
        args, kwargs = self.parse_input(args, kwargs)
        if "noninteractive" in args: kwargs["interactive"] = False

        for plottype, classes in plottable:
            if isinstance(data, classes):
                self.plottype = plottype
                plot_method = getattr(self, "plot_%s" % plottype)
                plot_method(data, *args, **kwargs)
                return

        raise TypeError("Type not supported for plotting, %s" % str(type(data)))

    def plot_mesh(self, data, *args, **kwargs):
        self.rescale = False
        self.mesh = data
        self.vtkgrid = self.make_vtk_grid(self.mesh)
        self.filter = self.vtkgrid
        self.x = numpy.zeros(self.mesh.num_vertices())
        (self.iren, self.renWin, self.ren) = self.simple_plotter(self.filter, self.x.min(), self.x.max(), wireframe=True)
        self._update(self.x)
        self.renWin.Render()
        if kwargs.get("interactive", True):
            self.interactive()

    def plot_genericfunction(self, data, *args, **kwargs):
        if isinstance(data, Expression):
            self.mesh = kwargs.get("mesh")
            if self.mesh is None or not isinstance(self.mesh, Mesh):
                raise TypeError, "expected a mesh as kwargs when plotting Expression"
        elif isinstance(data, Function):
            self.mesh = data.function_space().mesh()
        else:
            raise TypeError, "Do not know how to plot the GenericFunction"
        self.vtkgrid = self.make_vtk_grid(self.mesh)
        self.filter = self.vtkgrid

        self.warpscalar = kwargs.get("warpscalar", True)
        self.rescale = kwargs.get("rescale", False)
        self.mode = kwargs.get("mode", "auto")
        wireframe=kwargs.get("wireframe", False)
        self.pts = kwargs.get("eval_pts", None)
        (dpn, rank) = self._dofs_pr_node(data)
        if self.mode == "auto":
            if dpn == 1:
                if self.mesh.cells().shape[1] == 2:
                    self.mode = "scalar_xy"
                else:
                    self.mode = "scalar"
            elif dpn == self.mesh.geometry().dim():
                self.mode = "vector"
            else:
                raise RuntimeError, "Can't plot function with %d dofs pr node" % dpn

        if self.pts is None:
            nno = self.mesh.num_vertices()
            self.x = numpy.zeros(nno*dpn)
            data.compute_vertex_values(self.x, self.mesh)
            coords = self.mesh.coordinates()
        else:
            """Only arbitrary point evaluation for vector valued functions."""
            assert self.mode == "vector"
            nno = len(self.pts)
            self.x = numpy.zeros((nno,dpn))
            v = numpy.zeros(dpn, dtype='d')
            for (i, point) in enumerate(self.pts):
                data.eval(v, point)
                self.x[i,:] = v[:]
            self.x = self.x.transpose().copy()
            self.x.shape = nno*dpn,
            coords = numpy.array(self.pts)
            coords.shape = (len(self.pts), len(self.pts[0]))

        vmin = kwargs.get("vmin", self.x.min())
        vmax = kwargs.get("vmax", self.x.max())

        assert vmax >= vmin, "Empty range, please specify vmin and/or vmax"

        if self.mode == "scalar":
            minmax = self.x.max() - self.x.min()
            if self.warpscalar and minmax > 0 and self.mesh.geometry().dim() < 3:
                self.filter = self.warp_scalar(self.x, minmax)
                #self.__warping = True
            (self.iren, self.renWin, self.ren) = self.simple_plotter(self.filter, vmin, vmax, wireframe=wireframe)
        elif self.mode == "scalar_xy":
            xx = self.mesh.coordinates()
            (self.iren, self.renWin, self.ren) = self.plot_xy(xx, self.x, ".-",
                                                              vmin=kwargs.get("vmin", None),
                                                              vmax=kwargs.get("vmax", None))
        elif self.mode in ("vector", "displacement"):
            self.x.shape = (dpn, nno)
            self.x = self.vec3d(self.x.transpose().copy())

            if  self.mode == "vector":
                (self.iren, self.renWin, self.ren) = self.vector_plotter(coords, self.x, vmin, vmax, wireframe=False)
            else:
                self.displacement = self.x.copy()
                # Use vector norms for scalar coloring
                self.x = numpy.sqrt(self.x[:,0]**2 + self.x[:,1]**2 + self.x[:,2]**2)
                self.filter = self.warp_vector(self.displacement)
                (self.iren, self.renWin, self.ren) = self.simple_plotter(self.filter, vmin, vmax, wireframe=wireframe)

        self.iren.Initialize()
        self._update(self.x)
        self.renWin.Render()
        if kwargs.get("interactive", True):
            self.interactive()

    def plot_functionplotdata(self, data, *args, **kwargs):
        self.mesh = data.mesh
        self.vtkgrid = self.make_vtk_grid(self.mesh)
        self.filter = self.vtkgrid

        self.warpscalar = kwargs.get("warpscalar", True)
        self.rescale = kwargs.get("rescale", False)
        self.mode = kwargs.get("mode", "auto")
        wireframe=kwargs.get("wireframe", False)
        self.pts = kwargs.get("eval_pts", None)
        rank = data.rank
        dpn = 1
        if rank > 0:
            dpn = self.mesh.geometry().dim()
        if self.mode == "auto":
            if dpn == 1:
                if self.mesh.cells().shape[1] == 2:
                    self.mode = "scalar_xy"
                else:
                    self.mode = "scalar"
            elif dpn == self.mesh.geometry().dim():
                self.mode = "vector"
            else:
                raise RuntimeError, "Can't plot function with %d dofs pr node" % dpn

        nno = self.mesh.num_vertices()
        self.x = numpy.zeros(nno*dpn)
        self.x = data.vertex_values().array().copy()
        coords = self.mesh.coordinates()

        vmin = kwargs.get("vmin", self.x.min())
        vmax = kwargs.get("vmax", self.x.max())

        assert vmax >= vmin, "Empty range, please specify vmin and/or vmax"

        if self.mode == "scalar":
            minmax = self.x.max() - self.x.min()
            if self.warpscalar and minmax > 0 and self.mesh.geometry().dim() < 3:
                self.filter = self.warp_scalar(self.x, minmax)
                #self.__warping = True
            (self.iren, self.renWin, self.ren) = self.simple_plotter(self.filter, vmin, vmax, wireframe=wireframe)
        elif self.mode == "scalar_xy":
            xx = self.mesh.coordinates()
            (self.iren, self.renWin, self.ren) = self.plot_xy(xx, self.x, ".-",
                                                              vmin=kwargs.get("vmin", None),
                                                              vmax=kwargs.get("vmax", None))
        elif self.mode in ("vector", "displacement"):
            self.x.shape = (dpn, nno)
            self.x = self.vec3d(self.x.transpose().copy())

            if  self.mode == "vector":
                (self.iren, self.renWin, self.ren) = self.vector_plotter(coords, self.x, vmin, vmax, wireframe=False)
            else:
                self.displacement = self.x.copy()
                # Use vector norms for scalar coloring
                self.x = numpy.sqrt(self.x[:,0]**2 + self.x[:,1]**2 + self.x[:,2]**2)
                self.filter = self.warp_vector(self.displacement)
                (self.iren, self.renWin, self.ren) = self.simple_plotter(self.filter, vmin, vmax, wireframe=False)

        self.iren.Initialize()
        self._update(self.x)
        self.renWin.Render()
        if kwargs.get("interactive", True):
            self.interactive()

    def plot_meshfunction(self, data, *args, **kwargs):
        self.mesh = data.mesh()
        mesh_dim = self.mesh.topology().dim()
        dim = data.dim()
        size = data.size()
        values = data.array()
        self.vtkgrid = self.make_vtk_grid(self.mesh)
        self.filter = self.vtkgrid
        self.x = numpy.array(values, dtype='d')
        if str(values.dtype).count("int"):
            self.lutfile = ""
        if dim in (0, mesh_dim-1, mesh_dim):
            if dim==mesh_dim: # meshfunction over cells
                self.vertex_plot = False
                self.lutfile = ""
            elif dim==mesh_dim-1: # meshfunction over faces
                # Create a vertex valued meshfunction and plot that
                self.mesh.init(dim)
                vertices = type(data)(self.mesh, 0)
                vertex_values = vertices.array()
                vertex_values[:] = 0
                con20 = self.mesh.topology()(dim,0)
                for facet in xrange(self.mesh.num_faces()):
                    if values[facet]:
                        vertex_values[con20(facet)] = values[facet]
                self.plot_meshfunction(vertices, *args, **kwargs)
                return

            (self.iren, self.renWin, self.ren) = self.simple_plotter(self.filter, self.x.min(), self.x.max(), wireframe=False)
        else:
            raise RuntimeError, "Only vertex, facets and cell valued meshfunctions can be plotted"
        self.iren.Initialize()
        self._update(self.x)
        self.renWin.Render()
        if kwargs.get("interactive", True):
            self.interactive()

    def _dofs_pr_node(self, f):
        rank = f.value_rank()
        dpn = 1
        for i in xrange(rank):
            dpn *= f.value_dimension(i)
        return dpn, rank

    def add_polygon(self, polygon, idx=0):
        assert isinstance(polygon, (list, tuple))
        numpoints = len(polygon)
        assert isinstance(polygon[0], (list, tuple, numpy.ndarray))
        points2d = False
        if len(polygon[0]) == 2:
            points2d = True
        points = vtk.vtkPoints()
        points.SetNumberOfPoints(numpoints)
        for i in xrange(numpoints):
            point = list(polygon[i])
            if points2d:
                point.append(0.0)
            points.InsertPoint(i, *point)
        line = vtk.vtkPolyLine()
        line.GetPointIds().SetNumberOfIds(numpoints)
        for i in xrange(numpoints):
            line.GetPointIds().SetId(i, i)
        grid = vtk.vtkUnstructuredGrid()
        grid.Allocate(1, 1)
        grid.InsertNextCell(line.GetCellType(),
                            line.GetPointIds())
        grid.SetPoints(points)

        extract = vtk.vtkGeometryFilter()
        extract.SetInput(grid)
        extract.GetOutput().ReleaseDataFlagOn()
        self.polygon_data.AddInput(extract.GetOutput())

        actor = self.polygon_actors[idx]
        mapper = actor.GetMapper()
        if mapper is None:
            mapper = vtk.vtkPolyDataMapper()
            actor.SetMapper(mapper)

        mapper.SetInput(self.polygon_data.GetOutput())
        actor.GetProperty().SetColor(0, 0, 1)
        actor.GetProperty().SetLineWidth(1)

        self.ren.AddActor(actor)

    def dolfin_update(self, data, **kwargs):

        # Prepare data to viper internal format
        if self.plottype == "mesh":
            self.mesh = data
            self.vtkgrid = self.make_vtk_grid(self.mesh)
            self.filter = self.vtkgrid
            self.update_scalar_mapper(self.filter)
            self.x = numpy.zeros(self.mesh.num_vertices())
        elif self.plottype == "genericfunction":
            (dpn, rank) = self._dofs_pr_node(data)
            if self.pts is None:
                nno = self.mesh.num_vertices()
                self.x = numpy.zeros(nno*dpn)
                data.compute_vertex_values(self.x, self.mesh)
            else:
                nno = len(self.pts)
                self.x = numpy.zeros((nno,dpn))
                v = numpy.zeros(dpn, dtype='d')
                for (i, point) in enumerate(self.pts):
                    data.eval(v, point)
                    self.x[i,:] = v[:]
                self.x = self.x.transpose().copy()
                self.x.shape = nno*dpn,

            if self.mode == "scalar":
                minmax = self.x.max() - self.x.min()
                if self.warpscalar and minmax > 0 and  self.mesh.geometry().dim() < 3:
                    self.filter = self.warp_scalar(self.x, minmax)
            if self.mode in ("vector", "displacement"):
                self.x.shape = (dpn, nno)
                self.x = self.vec3d(self.x.transpose().copy())
                if self.mode == "displacement":
                    self.displacement[:] = self.x.copy()
                    self.x = numpy.sqrt(self.x[:,0]**2 + self.x[:,1]**2 + self.x[:,2]**2)
        elif self.plottype == "meshfunction":
            self.mesh = data.mesh()
            self.vtkgrid = self.make_vtk_grid(self.mesh)
            self.filter = self.vtkgrid
            self.update_scalar_mapper(self.filter)
            self.x = numpy.array(data.array(), dtype='d')
        else:
            print "Unknown plottype %s. Can't update" % (self.plottype,)

        # Update title if given
        if 'title' in kwargs:
            self.title = str(kwargs['title'])

        # Plot data
        self._update(self.x)

class PlotManager(object):
    def __init__(self):
        import random
        self.random = random
        self.reset()

    def figure(self, index):
        self.index = index

    def reset(self):
        self.plots = {}
        self.index = None # By default, use automatic plotting

    def plot(self, plot_object, *args, **kwargs):
        if self.index is None:
            return self.autoplot(plot_object, *args, **kwargs)
        return self.figureplot(plot_object, *args, **kwargs)

    def autoplot(self, plot_object, *args, **kwargs):
        for (idx, (plotter,obj)) in self.plots.items():
            if obj is plot_object:
                plotter.update(plot_object, **kwargs)
                return plotter
        idx = self.random.randint(0,10000)
        keys = self.plots.keys()
        while idx in keys:
            idx = self.random.randint(0,10000)

        kwargs["interactive"] = False
        plotter = Viper(plot_object, *args, **kwargs)
        self.plots[idx] = (plotter, plot_object)
        return plotter

    def figureplot(self, plot_object, *args, **kwargs):
        if self.plots.has_key(self.index):
            (plotter, obj) = self.plots[self.index]
            plotter.update(plot_object, **kwargs)
            self.plots[self.index] = (plotter, plot_object)
            return plotter

        kwargs["interactive"] = False
        plotter = Viper(plot_object, *args, **kwargs)
        self.plots[self.index] = (plotter, plot_object)
        return plotter

    def interactive(self):
        if len(self.plots) > 0:
            k = self.plots.keys()[0]
            self.plots[k][0].interactive()

def figure(index):
    global _plotter
    if _plotter is None:
        _plotter = PlotManager()
    _plotter.figure(index)

def plot(data, *args, **kwargs):
    global _plotter
    if _plotter is None:
        _plotter = PlotManager()
    n_old_plots = len(_plotter.plots)

    interactive = False
    if kwargs.has_key("interactive"):
        interactive = kwargs["interactive"]
        kwargs["interactive"] = False
    fig = _plotter.plot(data, **kwargs)

    if n_old_plots > 0 and kwargs.get('autoposition', True):
        x, y   = fig.window_size
        nx, ny = n_old_plots%3, n_old_plots//3
        fig.renWin.SetPosition(nx*x, ny*y)
        # The actual positioning seems to be indeterministic, but at least
        # they don't overlap (completely).
        #print (nx*x,ny*y), fig.renWin.GetPosition()

    if interactive:
        _plotter.interactive()
    return fig

def update(data):
    print "Not implemented"
    return
    global _viper
    if _viper != None:
        _viper.update(data)
        return _viper
    print "No plot object, cannot update"

def interactive():
    global _plotter
    if _plotter is None:
        print "No plot object, interaction not possible"
        return
    _plotter.interactive()

def save_plot(u, filename="plot.png"):
    v = Viper(u, interactive=False)
    v.init_writer()
    v.write_png(filename)