boxmodel.hh 26.4 KB
Newer Older
Andreas Lauser's avatar
Andreas Lauser committed
1
2
// $Id$
/*****************************************************************************
3
4
 *   Copyright (C) 2008-2010 by Andreas Lauser                               *
 *   Copyright (C) 2008-2010 by Bernd Flemisch                               *
Andreas Lauser's avatar
Andreas Lauser committed
5
6
7
8
 *   Institute of Hydraulic Engineering                                      *
 *   University of Stuttgart, Germany                                        *
 *   email: <givenname>.<name>@iws.uni-stuttgart.de                          *
 *                                                                           *
9
 *   This program is free software: you can redistribute it and/or modify    *
Andreas Lauser's avatar
Andreas Lauser committed
10
 *   it under the terms of the GNU General Public License as published by    *
11
12
 *   the Free Software Foundation, either version 2 of the License, or       *
 *   (at your option) any later version.                                     *
Andreas Lauser's avatar
Andreas Lauser committed
13
 *                                                                           *
14
15
16
17
18
19
20
 *   This program 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 General Public License for more details.                            *
 *                                                                           *
 *   You should have received a copy of the GNU General Public License       *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.   *
Andreas Lauser's avatar
Andreas Lauser committed
21
 *****************************************************************************/
Bernd Flemisch's avatar
Bernd Flemisch committed
22
23
24
25
26
/*!
 * \file
 *
 * \brief Base class for models using box discretization
 */
27
28
#ifndef DUMUX_BOX_MODEL_HH
#define DUMUX_BOX_MODEL_HH
Andreas Lauser's avatar
Andreas Lauser committed
29
30

#include "boxproperties.hh"
Andreas Lauser's avatar
Andreas Lauser committed
31
#include "boxpropertydefaults.hh"
Andreas Lauser's avatar
Andreas Lauser committed
32

33
#include "boxelementvolumevariables.hh"
Andreas Lauser's avatar
Andreas Lauser committed
34
35
36
37
38
39
40
#include "boxlocaljacobian.hh"
#include "boxlocalresidual.hh"

namespace Dumux
{

/*!
41
 * \defgroup BoxModel The core infrastructure of the box scheme
Andreas Lauser's avatar
Andreas Lauser committed
42
43
44
 */
/*!
 * \ingroup BoxModel
45
 * \defgroup BoxModels Physical models and problems which use the box scheme
Andreas Lauser's avatar
Andreas Lauser committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
 */


/*!
 * \ingroup BoxModel
 *
 * \brief The base class for the vertex centered finite volume
 *        discretization scheme.
 */
template<class TypeTag>
class BoxModel
{
    typedef BoxModel<TypeTag> ThisType;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(Model)) Implementation;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(Problem)) Problem;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(GridView)) GridView;

63
64
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(Scalar)) Scalar;
    typedef typename GridView::Grid::ctype CoordScalar;
Andreas Lauser's avatar
Andreas Lauser committed
65
66
67
68
69

    typedef typename GET_PROP_TYPE(TypeTag, PTAG(ElementMapper)) ElementMapper;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(VertexMapper)) VertexMapper;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(DofMapper)) DofMapper;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(SolutionVector)) SolutionVector;
70
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(PrimaryVariables)) PrimaryVariables;
Andreas Lauser's avatar
Andreas Lauser committed
71
72
73
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(JacobianAssembler)) JacobianAssembler;

    enum {
74
        numEq = GET_PROP_VALUE(TypeTag, PTAG(NumEq)),
75
        enableJacobianRecycling  = GET_PROP_VALUE(TypeTag, PTAG(EnableJacobianRecycling)),
76
        dim = GridView::dimension
Andreas Lauser's avatar
Andreas Lauser committed
77
78
    };

79
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(FVElementGeometry)) FVElementGeometry;
Andreas Lauser's avatar
Andreas Lauser committed
80
81
82
83
84
85
86
87
88
89
90
91
92

    typedef typename GET_PROP_TYPE(TypeTag, PTAG(LocalJacobian)) LocalJacobian;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(LocalResidual)) LocalResidual;

    typedef typename GET_PROP_TYPE(TypeTag, PTAG(NewtonMethod)) NewtonMethod;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(NewtonController)) NewtonController;

    typedef typename GridView::template Codim<0>::Entity Element;
    typedef typename GridView::template Codim<0>::Iterator ElementIterator;
    typedef typename GridView::IntersectionIterator IntersectionIterator;
    typedef typename GridView::template Codim<dim>::Entity Vertex;
    typedef typename GridView::template Codim<dim>::Iterator VertexIterator;

93
94
95
    typedef typename Dune::GenericReferenceElements<CoordScalar, dim> ReferenceElements;
    typedef typename Dune::GenericReferenceElement<CoordScalar, dim> ReferenceElement;

Andreas Lauser's avatar
Andreas Lauser committed
96
97
    enum { enablePartialReassemble = GET_PROP_VALUE(TypeTag, PTAG(EnablePartialReassemble)) };

98
99
100
    // copying a model is not a good idea
    BoxModel(const BoxModel &);

Andreas Lauser's avatar
Andreas Lauser committed
101
102
103
104
105
106
107
108
109
110
111
112
public:
    /*!
     * \brief The constructor.
     */
    BoxModel()
    { }

    ~BoxModel()
    { delete jacAsm_;  }

    /*!
     * \brief Apply the initial conditions to the model.
113
114
115
     *
     * \param prob The object representing the problem which needs to
     *             be simulated.
Andreas Lauser's avatar
Andreas Lauser committed
116
117
118
119
     */
    void init(Problem &prob)
    {
        problemPtr_ = &prob;
120

121
        updateBoundaryIndices_();
Andreas Lauser's avatar
Andreas Lauser committed
122

123
        int nDofs = asImp_().numDofs();
Andreas Lauser's avatar
Andreas Lauser committed
124
125
126
127
128
129
130
        uCur_.resize(nDofs);
        uPrev_.resize(nDofs);
        boxVolume_.resize(nDofs);

        localJacobian_.init(problem_());
        jacAsm_ = new JacobianAssembler();
        jacAsm_->init(problem_());
131

132
        asImp_().applyInitialSolution_();
Andreas Lauser's avatar
Andreas Lauser committed
133
134
135
136
137
138
139
140
141

        // also set the solution of the "previous" time step to the
        // initial solution.
        uPrev_ = uCur_;
    }

    /*!
     * \brief Compute the global residual for an arbitrary solution
     *        vector.
142
143
144
     *
     * \param dest Stores the result
     * \param u The solution for which the residual ought to be calculated
Andreas Lauser's avatar
Andreas Lauser committed
145
     */
146
    Scalar globalResidual(SolutionVector &dest,
147
                          const SolutionVector &u)
Andreas Lauser's avatar
Andreas Lauser committed
148
149
150
151
152
153
154
155
156
157
158
    {
        SolutionVector tmp(curSol());
        curSol() = u;
        Scalar res = globalResidual(dest);
        curSol() = tmp;
        return res;
    }

    /*!
     * \brief Compute the global residual for the current solution
     *        vector.
159
160
     *
     * \param dest Stores the result
Andreas Lauser's avatar
Andreas Lauser committed
161
162
163
164
     */
    Scalar globalResidual(SolutionVector &dest)
    {
        dest = 0;
165

Andreas Lauser's avatar
Andreas Lauser committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        ElementIterator elemIt = gridView_().template begin<0>();
        const ElementIterator elemEndIt = gridView_().template end<0>();
        for (; elemIt != elemEndIt; ++elemIt) {
            localResidual().eval(*elemIt);

            for (int i = 0; i < elemIt->template count<dim>(); ++i) {
                int globalI = vertexMapper().map(*elemIt, i, dim);
                dest[globalI] += localResidual().residual(i);
            }
        };

        Scalar result = dest.two_norm();
        /*
        Scalar result = 0;
        for (int i = 0; i < (*tmp).size(); ++i) {
            for (int j = 0; j < numEq; ++j)
                result += std::abs((*tmp)[i][j]);
        }
        */
        return result;
    }

Andreas Lauser's avatar
Andreas Lauser committed
188
    /*!
189
190
191
192
     * \brief Compute the integral over the domain of the storage
     *        terms of all conservation quantities.
     *
     * \param dest Stores the result
Andreas Lauser's avatar
Andreas Lauser committed
193
194
195
196
     */
    void globalStorage(PrimaryVariables &dest)
    {
        dest = 0;
197

Andreas Lauser's avatar
Andreas Lauser committed
198
199
200
201
202
203
204
205
206
        ElementIterator elemIt = gridView_().template begin<0>();
        const ElementIterator elemEndIt = gridView_().template end<0>();
        for (; elemIt != elemEndIt; ++elemIt) {
            localResidual().evalStorage(*elemIt);

            for (int i = 0; i < elemIt->template count<dim>(); ++i)
                dest += localResidual().residual(i);
        };

Bernd Flemisch's avatar
Bernd Flemisch committed
207
208
        if (gridView_().comm().size() > 1)
        	dest = gridView_().comm().sum(dest);
Andreas Lauser's avatar
Andreas Lauser committed
209
210
    }

Andreas Lauser's avatar
Andreas Lauser committed
211
    /*!
Felix Bode's avatar
Felix Bode committed
212
     * \brief Returns the volume \f$\mathrm{[m^3]}\f$ of a given control volume.
213
214
215
     *
     * \param globalIdx The global index of the control volume's
     *                  associated vertex
Andreas Lauser's avatar
Andreas Lauser committed
216
217
218
219
220
221
222
223
     */
    Scalar boxVolume(int globalIdx) const
    { return boxVolume_[globalIdx][0]; }

    /*!
     * \brief Reference to the current solution as a block vector.
     */
    const SolutionVector &curSol() const
224
    { return uCur_; }
Andreas Lauser's avatar
Andreas Lauser committed
225
226
227
228
229

    /*!
     * \brief Reference to the current solution as a block vector.
     */
    SolutionVector &curSol()
230
    { return uCur_; }
Andreas Lauser's avatar
Andreas Lauser committed
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250

    /*!
     * \brief Reference to the previous solution as a block vector.
     */
    const SolutionVector &prevSol() const
    { return uPrev_; }

    /*!
     * \brief Reference to the previous solution as a block vector.
     */
    SolutionVector &prevSol()
    { return uPrev_; }

    /*!
     * \brief Returns the operator assembler for the global jacobian of
     *        the problem.
     */
    JacobianAssembler &jacobianAssembler()
    { return *jacAsm_; }

251
252
253
254
255
256
    /*!
     * \copydoc jacobianAssembler()
     */
    const JacobianAssembler &jacobianAssembler() const
    { return *jacAsm_; }

Andreas Lauser's avatar
Andreas Lauser committed
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
    /*!
     * \brief Returns the local jacobian which calculates the local
     *        stiffness matrix for an arbitrary element.
     *
     * The local stiffness matrices of the element are used by
     * the jacobian assembler to produce a global linerization of the
     * problem.
     */
    LocalJacobian &localJacobian()
    { return localJacobian_; }
    /*!
     * \copydoc localJacobian()
     */
    const LocalJacobian &localJacobian() const
    { return localJacobian_; }

    /*!
     * \brief Returns the local residual function.
     */
    LocalResidual &localResidual()
    { return localJacobian().localResidual(); }
    /*!
     * \copydoc localResidual()
     */
    const LocalResidual &localResidual() const
    { return localJacobian().localResidual(); }

Andreas Lauser's avatar
Andreas Lauser committed
284
285
286
    /*!
     * \brief Returns the relative weight of a primary variable for
     *        calculating relative errors.
287
288
289
     *
     * \param vertIdx The global index of the control volume
     * \param pvIdx The index of the primary variable
Andreas Lauser's avatar
Andreas Lauser committed
290
291
     */
    Scalar primaryVarWeight(int vertIdx, int pvIdx) const
292
    {
293
        return 1.0/std::max(std::abs(this->prevSol()[vertIdx][pvIdx]), 1.0);
294
    }
Andreas Lauser's avatar
Andreas Lauser committed
295
296
297
298
299

    /*!
     * \brief Returns the relative error between two vectors of
     *        primary variables.
     *
300
301
302
303
304
     * \param vertexIdx The global index of the control volume's
     *                  associated vertex
     * \param pv1 The first vector of primary variables
     * \param pv2 The second vector of primary variables
     *
Andreas Lauser's avatar
Andreas Lauser committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
     * \todo The vertexIdx argument is pretty hacky. it is required by
     *       models with pseudo primary variables (i.e. the primary
     *       variable switching models). the clean solution would be
     *       to access the pseudo primary variables from the primary
     *       variables.
     */
    Scalar relativeErrorVertex(int vertexIdx,
                               const PrimaryVariables &pv1,
                               const PrimaryVariables &pv2)
    {
        Scalar result = 0.0;
        for (int j = 0; j < numEq; ++j) {
            Scalar weight = asImp_().primaryVarWeight(vertexIdx, j);
            Scalar eqErr = std::abs(pv1[j] - pv2[j])*weight;

            result = std::max(result, eqErr);
        }
        return result;
    }
324

Andreas Lauser's avatar
Andreas Lauser committed
325
326
    /*!
     * \brief Try to progress the model to the next timestep.
327
328
     *
     * \param solver The non-linear solver
329
     * \param controller The controller which specifies the behaviour
330
     *                   of the non-linear solver
Andreas Lauser's avatar
Andreas Lauser committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
     */
    bool update(NewtonMethod &solver,
                NewtonController &controller)
    {
#if HAVE_VALGRIND
        for (size_t i = 0; i < curSol().size(); ++i)
            Valgrind::CheckDefined(curSol()[i]);
#endif // HAVE_VALGRIND

        asImp_().updateBegin();

        bool converged = solver.execute(controller);
        if (converged)
            asImp_().updateSuccessful();
        else
            asImp_().updateFailed();
347

Andreas Lauser's avatar
Andreas Lauser committed
348
349
350
351
352
#if HAVE_VALGRIND
        for (size_t i = 0; i < curSol().size(); ++i) {
            Valgrind::CheckDefined(curSol()[i]);
        }
#endif // HAVE_VALGRIND
353

Andreas Lauser's avatar
Andreas Lauser committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
        return converged;
    }


    /*!
     * \brief Called by the update() method before it tries to
     *        apply the newton method. This is primary a hook
     *        which the actual model can overload.
     */
    void updateBegin()
    { }


    /*!
     * \brief Called by the update() method if it was
     *        successful. This is primary a hook which the actual
     *        model can overload.
     */
    void updateSuccessful()
373
    { };
Andreas Lauser's avatar
Andreas Lauser committed
374
375
376
377
378
379
380
381
382
383
384
385

    /*!
     * \brief Called by the update() method if it was
     *        unsuccessful. This is primary a hook which the actual
     *        model can overload.
     */
    void updateFailed()
    {
        // Reset the current solution to the one of the
        // previous time step so that we can start the next
        // update at a physically meaningful solution.
        uCur_ = uPrev_;
386
        jacAsm_->reassembleAll();
Andreas Lauser's avatar
Andreas Lauser committed
387
388
    };

389
    /*!
390
391
392
     * \brief Called by the problem if a time integration was
     *        successful, post processing of the solution is done and
     *        the result has been written to disk.
393
     *
394
     * This should prepare the model for the next time integration.
395
396
397
398
399
400
401
     */
    void advanceTimeLevel()
    {
        // make the current solution the previous one.
        uPrev_ = uCur_;
    }

Andreas Lauser's avatar
Andreas Lauser committed
402
403
    /*!
     * \brief Serializes the current state of the model.
404
405
406
407
     *
     * \tparam Restarter The type of the serializer class
     *
     * \param res The serializer object
Andreas Lauser's avatar
Andreas Lauser committed
408
409
410
411
412
413
414
     */
    template <class Restarter>
    void serialize(Restarter &res)
    { res.template serializeEntities<dim>(asImp_(), this->gridView_()); }

    /*!
     * \brief Deserializes the state of the model.
415
416
417
418
     *
     * \tparam Restarter The type of the serializer class
     *
     * \param res The serializer object
Andreas Lauser's avatar
Andreas Lauser committed
419
420
421
422
423
424
425
426
427
428
429
     */
    template <class Restarter>
    void deserialize(Restarter &res)
    {
        res.template deserializeEntities<dim>(asImp_(), this->gridView_());
        prevSol() = curSol();
    }

    /*!
     * \brief Write the current solution for a vertex to a restart
     *        file.
430
431
432
433
434
     *
     * \param outstream The stream into which the vertex data should
     *                  be serialized to
     * \param vert The DUNE Codim<dim> entity which's data should be
     *             serialized
Andreas Lauser's avatar
Andreas Lauser committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
     */
    void serializeEntity(std::ostream &outstream,
                         const Vertex &vert)
    {
        int vertIdx = dofMapper().map(vert);

        // write phase state
        if (!outstream.good()) {
            DUNE_THROW(Dune::IOError,
                       "Could not serialize vertex "
                       << vertIdx);
        }

        for (int eqIdx = 0; eqIdx < numEq; ++eqIdx) {
            outstream << curSol()[vertIdx][eqIdx] << " ";
        }
    };

    /*!
     * \brief Reads the current solution variables for a vertex from a
     *        restart file.
456
457
458
459
460
     *
     * \param instream The stream from which the vertex data should
     *                  be deserialized from
     * \param vert The DUNE Codim<dim> entity which's data should be
     *             deserialized
Andreas Lauser's avatar
Andreas Lauser committed
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
     */
    void deserializeEntity(std::istream &instream,
                           const Vertex &vert)
    {
        int vertIdx = dofMapper().map(vert);
        for (int eqIdx = 0; eqIdx < numEq; ++eqIdx) {
            if (!instream.good())
                DUNE_THROW(Dune::IOError,
                           "Could not deserialize vertex "
                           << vertIdx);
            instream >> curSol()[vertIdx][eqIdx];
        }
    };

    /*!
     * \brief Returns the number of global degrees of freedoms (DOFs)
     */
    size_t numDofs() const
    { return gridView_().size(dim); }

    /*!
     * \brief Mapper for the entities where degrees of freedoms are
     *        defined to indices.
     *
     * This usually means a mapper for vertices.
     */
    const DofMapper &dofMapper() const
    { return problem_().vertexMapper(); };

    /*!
     * \brief Mapper for vertices to indices.
     */
    const VertexMapper &vertexMapper() const
    { return problem_().vertexMapper(); };

    /*!
     * \brief Mapper for elements to indices.
     */
    const ElementMapper &elementMapper() const
    { return problem_().elementMapper(); };

502
    /*!
503
     * \brief Resets the Jacobian matrix assembler, so that the
504
505
     *        boundary types can be altered.
     */
Andreas Lauser's avatar
Andreas Lauser committed
506
507
508
509
510
511
512
513
514
515
516
    void resetJacobianAssembler ()
    {
        delete jacAsm_;
        jacAsm_ = new JacobianAssembler;
        jacAsm_->init(problem_());
    }

    /*!
     * \brief Add the vector fields for analysing the convergence of
     *        the newton method to the a VTK multi writer.
     *
517
518
519
     * \tparam MultiWriter The type of the VTK multi writer
     *
     * \param writer  The VTK multi writer object on which the fields should be added.
Bernd Flemisch's avatar
Bernd Flemisch committed
520
521
     * \param u       The solution function
     * \param deltaU  The delta of the solution function before and after the Newton update
Andreas Lauser's avatar
Andreas Lauser committed
522
523
524
     */
    template <class MultiWriter>
    void addConvergenceVtkFields(MultiWriter &writer,
525
                                 const SolutionVector &u,
Andreas Lauser's avatar
Andreas Lauser committed
526
527
528
529
                                 const SolutionVector &deltaU)
    {
        typedef Dune::BlockVector<Dune::FieldVector<Scalar, 1> > ScalarField;

530
        SolutionVector globalResid(u);
Andreas Lauser's avatar
Andreas Lauser committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        asImp_().globalResidual(globalResid, u);

        // create the required scalar fields
        unsigned numVertices = this->gridView_().size(dim);
        //unsigned numElements = this->gridView_().size(0);

        // global defect of the two auxiliary equations
        ScalarField* def[numEq];
        ScalarField* delta[numEq];
        ScalarField* x[numEq];
        for (int i = 0; i < numEq; ++i) {
            x[i] = writer.template createField<Scalar, 1>(numVertices);
            delta[i] = writer.template createField<Scalar, 1>(numVertices);
            def[i] = writer.template createField<Scalar, 1>(numVertices);
        }

        VertexIterator vIt = this->gridView_().template begin<dim>();
        VertexIterator vEndIt = this->gridView_().template end<dim>();
        for (; vIt != vEndIt; ++ vIt)
        {
            int globalIdx = vertexMapper().map(*vIt);
            for (int i = 0; i < numEq; ++i) {
                (*x[i])[globalIdx] = u[globalIdx][i];
                (*delta[i])[globalIdx] = - deltaU[globalIdx][i];
                (*def[i])[globalIdx] = globalResid[globalIdx][i];
            }
        }

        for (int i = 0; i < numEq; ++i) {
            writer.addVertexData(x[i], (boost::format("x_%i")%i).str().c_str());
            writer.addVertexData(delta[i], (boost::format("delta_%i")%i).str().c_str());
            writer.addVertexData(def[i], (boost::format("defect_%i")%i).str().c_str());
        }

        asImp_().addOutputVtkFields(u, writer);
    }

    /*!
569
     * \brief Add the quantities of a time step which ought to be written to disk.
Andreas Lauser's avatar
Andreas Lauser committed
570
     *
571
     * This should be overwritten by the actual model if any secondary
Andreas Lauser's avatar
Andreas Lauser committed
572
573
574
     * variables should be written out. Read: This should _always_ be
     * overwritten by well behaved models!
     *
575
576
     * \tparam MultiWriter The type of the VTK multi writer
     *
577
578
     * \param sol The global vector of primary variable values.
     * \param writer The VTK multi writer where the fields should be added.
Andreas Lauser's avatar
Andreas Lauser committed
579
580
     */
    template <class MultiWriter>
581
    void addOutputVtkFields(const SolutionVector &sol,
Andreas Lauser's avatar
Andreas Lauser committed
582
583
584
585
586
587
                            MultiWriter &writer)
    {
        typedef Dune::BlockVector<Dune::FieldVector<Scalar, 1> > ScalarField;

        // create the required scalar fields
        unsigned numVertices = this->gridView_().size(dim);
588

Andreas Lauser's avatar
Andreas Lauser committed
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        // global defect of the two auxiliary equations
        ScalarField* x[numEq];
        for (int i = 0; i < numEq; ++i) {
            x[i] = writer.template createField<Scalar, 1>(numVertices);
        }

        VertexIterator vIt = this->gridView_().template begin<dim>();
        VertexIterator vEndIt = this->gridView_().template end<dim>();
        for (; vIt != vEndIt; ++ vIt)
        {
            int globalIdx = vertexMapper().map(*vIt);
            for (int i = 0; i < numEq; ++i) {
                (*x[i])[globalIdx] = sol[globalIdx][i];
            }
        }

        for (int i = 0; i < numEq; ++i)
            writer.addVertexData(x[i], (boost::format("primaryVar%i")%i).str().c_str());
    }

Bernd Flemisch's avatar
Bernd Flemisch committed
609
610
611
612
613
    /*!
     * \brief Reference to the grid view of the spatial domain.
     */
    const GridView &gridView() const
    { return problem_().gridView(); }
Andreas Lauser's avatar
Andreas Lauser committed
614

615
616
617
    /*!
     * \brief Returns true if the vertex with 'globalVertIdx' is
     *        located on the grid's boundary.
618
619
620
     *
     * \param globalVertIdx The global index of the control volume's
     *                      associated vertex
621
622
623
624
625
626
627
     */
    bool onBoundary(int globalVertIdx) const
    { return boundaryIndices_.count(globalVertIdx) > 0; }

    /*!
     * \brief Returns true if a vertex is located on the grid's
     *        boundary.
628
629
630
     *
     * \param vertex The DUNE Codim<dim> entity associated with the
     *               control volume
631
632
633
634
635
636
637
     */
    bool onBoundary(const Vertex &vertex) const
    { return onBoundary(vertexMapper().map(vertex)); }

    /*!
     * \brief Returns true if a vertex is located on the grid's
     *        boundary.
638
639
640
641
     *
     * \param elem A DUNE Codim<0> entity which contains the control
     *             volume's associated vertex.
     * \param vIdx The local vertex index inside elem
642
643
644
645
     */
    bool onBoundary(const Element &elem, int vIdx) const
    { return onBoundary(vertexMapper().map(elem, vIdx, dim)); }

Andreas Lauser's avatar
Andreas Lauser committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
protected:
    /*!
     * \brief A reference to the problem on which the model is applied.
     */
    Problem &problem_()
    { return *problemPtr_; }
    /*!
     * \copydoc problem_()
     */
    const Problem &problem_() const
    { return *problemPtr_; }

    /*!
     * \brief Reference to the grid view of the spatial domain.
     */
    const GridView &gridView_() const
    { return problem_().gridView(); }

664
665
666
    /*!
     * \brief Reference to the local residal object
     */
Andreas Lauser's avatar
Andreas Lauser committed
667
668
669
    LocalResidual &localResidual_()
    { return localJacobian_.localResidual(); }

670
    /*!
671
     * \brief Applies the initial solution for all vertices of the grid.
672
     */
Andreas Lauser's avatar
Andreas Lauser committed
673
674
675
676
677
    void applyInitialSolution_()
    {
        // first set the whole domain to zero
        uCur_ = Scalar(0.0);
        boxVolume_ = Scalar(0.0);
678

Andreas Lauser's avatar
Andreas Lauser committed
679
        FVElementGeometry fvElemGeom;
680

Andreas Lauser's avatar
Andreas Lauser committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        // iterate through leaf grid and evaluate initial
        // condition at the center of each sub control volume
        //
        // TODO: the initial condition needs to be unique for
        // each vertex. we should think about the API...
        ElementIterator it = gridView_().template begin<0>();
        const ElementIterator &eendit = gridView_().template end<0>();
        for (; it != eendit; ++it) {
            // deal with the current element
            fvElemGeom.update(gridView_(), *it);

            // loop over all element vertices, i.e. sub control volumes
            for (int scvIdx = 0; scvIdx < fvElemGeom.numVertices; scvIdx++)
            {
                // map the local vertex index to the global one
                int globalIdx = vertexMapper().map(*it,
                                                   scvIdx,
                                                   dim);

                // let the problem do the dirty work of nailing down
                // the initial solution.
702
                PrimaryVariables initVal;
Andreas Lauser's avatar
Andreas Lauser committed
703
704
705
706
707
708
709
710
                Valgrind::SetUndefined(initVal);
                problem_().initial(initVal,
                                   *it,
                                   fvElemGeom,
                                   scvIdx);
                Valgrind::CheckDefined(initVal);

                // add up the initial values of all sub-control
711
                // volumes. If the initial values disagree for
Andreas Lauser's avatar
Andreas Lauser committed
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
                // different sub control volumes, the initial value
                // will be the arithmetic mean.
                initVal *= fvElemGeom.subContVol[scvIdx].volume;
                boxVolume_[globalIdx] += fvElemGeom.subContVol[scvIdx].volume;
                uCur_[globalIdx] += initVal;
                Valgrind::CheckDefined(uCur_[globalIdx]);
            }
        }
        // divide all primary variables by the volume of their boxes
        int n = gridView_().size(dim);
        for (int i = 0; i < n; ++i) {
            uCur_[i] /= boxVolume(i);
        }
    }

727
728
729
730
731
732
733
734
    /*!
     * \brief Find all indices of boundary vertices.
     *
     * For this we need to loop over all intersections (which is slow
     * in general). If the DUNE grid interface would provide a
     * onBoundary() method for entities this could be done in a much
     * nicer way (actually this would not be necessary)
     */
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
    void updateBoundaryIndices_()
    {
        boundaryIndices_.clear();
        ElementIterator eIt = gridView_().template begin<0>();
        ElementIterator eEndIt = gridView_().template end<0>();
        for (; eIt != eEndIt; ++eIt) {
            Dune::GeometryType geoType = eIt->geometry().type();
            const ReferenceElement &refElem = ReferenceElements::general(geoType);

            IntersectionIterator isIt = gridView_().ibegin(*eIt);
            IntersectionIterator isEndIt = gridView_().iend(*eIt);
            for (; isIt != isEndIt; ++isIt) {
                if (!isIt->boundary())
                    continue;
                // add all vertices on the intersection to the set of
                // boundary vertices
                int faceIdx = isIt->indexInInside();
                int numFaceVerts = refElem.size(faceIdx, 1, dim);
                for (int faceVertIdx = 0;
                     faceVertIdx < numFaceVerts;
                     ++faceVertIdx)
                {
                    int elemVertIdx = refElem.subEntity(faceIdx,
                                                        1,
                                                        faceVertIdx,
                                                        dim);
                    int globalVertIdx = vertexMapper().map(*eIt, elemVertIdx, dim);
                    boundaryIndices_.insert(globalVertIdx);
                }
            }
        }
    }

768
769
770
    /*!
     * \brief Returns whether messages should be printed
     */
Andreas Lauser's avatar
Andreas Lauser committed
771
772
773
774
775
776
777
778
779
780
781
782
    bool verbose_() const
    { return gridView_().comm().rank() == 0; };

    Implementation &asImp_()
    { return *static_cast<Implementation*>(this); }
    const Implementation &asImp_() const
    { return *static_cast<const Implementation*>(this); }

    // the problem we want to solve. defines the constitutive
    // relations, matxerial laws, etc.
    Problem *problemPtr_;

783
784
785
    // the set of all indices of vertices on the boundary
    std::set<int> boundaryIndices_;

Andreas Lauser's avatar
Andreas Lauser committed
786
    // calculates the local jacobian matrix for a given element
787
    LocalJacobian localJacobian_;
Andreas Lauser's avatar
Andreas Lauser committed
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    // Linearizes the problem at the current time step using the
    // local jacobian
    JacobianAssembler *jacAsm_;

    // cur is the current iterative solution, prev the converged
    // solution of the previous time step
    SolutionVector uCur_;
    SolutionVector uPrev_;

    Dune::BlockVector<Dune::FieldVector<Scalar, 1> > boxVolume_;
};
}

#endif