newtoncontroller.hh 24.5 KB
Newer Older
Andreas Lauser's avatar
Andreas Lauser committed
1
// $Id$
2
/****************************************************************************
Andreas Lauser's avatar
Andreas Lauser committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 *   Copyright (C) 2008-2010 by Andreas Lauser                               *
 *   Copyright (C) 2008-2010 by Bernd Flemisch                               *
 *   Institute of Hydraulic Engineering                                      *
 *   University of Stuttgart, Germany                                        *
 *   email: <givenname>.<name>@iws.uni-stuttgart.de                          *
 *                                                                           *
 *   This program is free software; you can redistribute it and/or modify    *
 *   it under the terms of the GNU General Public License as published by    *
 *   the Free Software Foundation; either version 2 of the License, or       *
 *   (at your option) any later version, as long as this copyright notice    *
 *   is included in its original form.                                       *
 *                                                                           *
 *   This program is distributed WITHOUT ANY WARRANTY.                       *
 *****************************************************************************/
17
/*!
Andreas Lauser's avatar
Andreas Lauser committed
18
 * \file
19
 * \brief Reference implementation of a controller class for the Newton solver.
Andreas Lauser's avatar
Andreas Lauser committed
20
 *
21
 * Usually this controller should be sufficient.
Andreas Lauser's avatar
Andreas Lauser committed
22
 */
23
24
25
#ifndef DUMUX_NEWTON_CONTROLLER_HH
#define DUMUX_NEWTON_CONTROLLER_HH

26
#include <dumux/io/vtkmultiwriter.hh>
27
#include <dumux/common/exceptions.hh>
28
#include <dumux/common/math.hh>
29
30
31

#include <dumux/common/pardiso.hh>

Andreas Lauser's avatar
Andreas Lauser committed
32
#include <dumux/io/vtkmultiwriter.hh>
33
34
35

#if HAVE_DUNE_PDELAB

Andreas Lauser's avatar
Andreas Lauser committed
36
#include <dumux/common/pdelabpreconditioner.hh>
Andreas Lauser's avatar
Andreas Lauser committed
37

38
39
40
41
42
43
44
45
46
47
48
#else // ! HAVE_DUNE_PDELAB

#include <dune/istl/overlappingschwarz.hh>
#include <dune/istl/schwarz.hh>
#include <dune/istl/preconditioners.hh>
#include <dune/istl/solvers.hh>
#include <dune/istl/owneroverlapcopy.hh>
#include <dune/istl/io.hh>

#endif // HAVE_DUNE_PDELAB

49
50
51
52
53

namespace Dumux
{
namespace Properties
{
54
//! Specifies the implementation of the Newton controller
Andreas Lauser's avatar
Andreas Lauser committed
55
56
NEW_PROP_TAG(NewtonController);

57
//! Specifies the type of the actual Newton method
Andreas Lauser's avatar
Andreas Lauser committed
58
59
NEW_PROP_TAG(NewtonMethod);

60
//! Specifies the type of a solution
Andreas Lauser's avatar
Andreas Lauser committed
61
62
NEW_PROP_TAG(SolutionVector);

63
//! Specifies the type of a vector of primary variables at a degree of freedom
Andreas Lauser's avatar
Andreas Lauser committed
64
65
NEW_PROP_TAG(PrimaryVariables);

66
//! Specifies the type of a global Jacobian matrix
Andreas Lauser's avatar
Andreas Lauser committed
67
68
NEW_PROP_TAG(JacobianMatrix);

69
//! Specifies the type of the Jacobian matrix assembler
Andreas Lauser's avatar
Andreas Lauser committed
70
71
72
73
74
NEW_PROP_TAG(JacobianAssembler);

//! specifies the type of the time manager
NEW_PROP_TAG(TimeManager);

75
76
77
78
79
80
81
/*!
 * \brief Specifies the verbosity of the linear solver
 *
 * By default it is 0, i.e. it doesn't print anything. Setting this
 * property to 1 prints aggregated convergence rates, 2 prints the
 * convergence rate of every iteration of the scheme.
 */
82
83
84
85
86
87
NEW_PROP_TAG(NewtonLinearSolverVerbosity);

//! specifies whether the convergence rate and the global residual
//! gets written out to disk for every newton iteration (default is false)
NEW_PROP_TAG(NewtonWriteConvergence);

88
89
//! Specifies whether time step size should be increased during the
//! Newton methods first few iterations
Andreas Lauser's avatar
Andreas Lauser committed
90
91
NEW_PROP_TAG(EnableTimeStepRampUp);

92
//! Specifies whether the Jacobian matrix should only be reassembled
Andreas Lauser's avatar
Andreas Lauser committed
93
94
95
//! if the current solution deviates too much from the evaluation point
NEW_PROP_TAG(EnablePartialReassemble);

96
97
98
99
100
101
102
103
/*!
 * \brief Specifies whether the update should be done using the line search
 *        method instead of the plain Newton method. 
 *
 * Whether this property has any effect depends on wether the line
 * search method is implemented for the actual model's Newton
 * controller's update() method. By default line search is not used.
 */
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
NEW_PROP_TAG(NewtonUseLineSearch);

SET_PROP_DEFAULT(NewtonLinearSolverVerbosity)
{public:
    static const int value = 0;
};

SET_PROP_DEFAULT(NewtonWriteConvergence)
{public:
    static const bool value = false;
};

SET_PROP_DEFAULT(NewtonUseLineSearch)
{public:
    static const bool value = false;
};
};

122
//! \cond INTERNAL
123
124
125
126
/*!
 * \brief Writes the intermediate solutions during 
 *        the Newton scheme
 */
127
128
129
130
131
132
template <class TypeTag, bool enable>
struct NewtonConvergenceWriter
{
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(GridView)) GridView;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(NewtonController)) NewtonController;

Andreas Lauser's avatar
Andreas Lauser committed
133
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(SolutionVector)) SolutionVector;
134
135
136
    typedef Dumux::VtkMultiWriter<GridView>  VtkMultiWriter;

    NewtonConvergenceWriter(NewtonController &ctl)
Andreas Lauser's avatar
Andreas Lauser committed
137
        : ctl_(ctl)
138
    {
139
        timeStepIndex_ = 0;
140
141
142
143
144
145
146
147
148
        iteration_ = 0;
        vtkMultiWriter_ = new VtkMultiWriter("convergence");
    }

    ~NewtonConvergenceWriter()
    { delete vtkMultiWriter_; };

    void beginTimestep()
    {
149
        ++timeStepIndex_;
150
151
152
153
154
155
        iteration_ = 0;
    };

    void beginIteration(const GridView &gv)
    {
        ++ iteration_;
156
        vtkMultiWriter_->beginTimestep(timeStepIndex_ + iteration_ / 100.0,
Andreas Lauser's avatar
Andreas Lauser committed
157
                                       gv);
158
159
    };

160
    void writeFields(const SolutionVector &uLastIter,
161
162
                     const SolutionVector &deltaU)
    {
163
        ctl_.method().model().addConvergenceVtkFields(*vtkMultiWriter_, uLastIter, deltaU);
164
165
166
    };

    void endIteration()
Andreas Lauser's avatar
Andreas Lauser committed
167
    { vtkMultiWriter_->endTimestep(); };
168
169
170

    void endTimestep()
    {
171
        ++timeStepIndex_;
172
173
174
175
        iteration_ = 0;
    };

private:
176
    int timeStepIndex_;
177
178
179
180
181
    int iteration_;
    VtkMultiWriter *vtkMultiWriter_;
    NewtonController &ctl_;
};

182
183
184
185
186
187
188
/*!
 * \brief Writes the intermediate solutions during 
 *        the Newton scheme. 
 *
 * This is the dummy specialization for the case where we don't want
 * to do anything.
 */
189
190
191
192
193
template <class TypeTag>
struct NewtonConvergenceWriter<TypeTag, false>
{
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(GridView)) GridView;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(NewtonController)) NewtonController;
Andreas Lauser's avatar
Andreas Lauser committed
194
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(SolutionVector)) SolutionVector;
195
196
197
198
199
200
201
202
203
204
205
206

    typedef Dumux::VtkMultiWriter<GridView>  VtkMultiWriter;

    NewtonConvergenceWriter(NewtonController &ctl)
    {};

    void beginTimestep()
    { };

    void beginIteration(const GridView &gv)
    { };

207
    void writeFields(const SolutionVector &uLastIter,
Andreas Lauser's avatar
Andreas Lauser committed
208
                     const SolutionVector &deltaU)
209
210
211
212
213
214
215
216
    { };

    void endIteration()
    { };

    void endTimestep()
    { };
};
217
//! \endcond
218
219

/*!
220
221
 * \brief A reference implementation of a newton controller specific
 *        for the box scheme.
Andreas Lauser's avatar
Andreas Lauser committed
222
 *
223
224
225
 * If you want to specialize only some methods but are happy with the
 * defaults of the reference controller, derive your controller from
 * this class and simply overload the required methods.
Andreas Lauser's avatar
Andreas Lauser committed
226
 */
227
228
229
template <class TypeTag>
class NewtonController
{
Andreas Lauser's avatar
Andreas Lauser committed
230
231
232
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(Scalar)) Scalar;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(NewtonController)) Implementation;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(GridView)) GridView;
233

Andreas Lauser's avatar
Andreas Lauser committed
234
235
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(Problem)) Problem;
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(Model)) Model;
236
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(NewtonMethod)) NewtonMethod;
Bernd Flemisch's avatar
Bernd Flemisch committed
237
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(JacobianMatrix)) JacobianMatrix;
238
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(TimeManager)) TimeManager;
239

Andreas Lauser's avatar
Andreas Lauser committed
240
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(JacobianAssembler)) JacobianAssembler;
Andreas Lauser's avatar
Andreas Lauser committed
241
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(SolutionVector)) SolutionVector;
Andreas Lauser's avatar
Andreas Lauser committed
242
    typedef typename GET_PROP_TYPE(TypeTag, PTAG(PrimaryVariables)) PrimaryVariables;
243
244
245

    typedef NewtonConvergenceWriter<TypeTag, GET_PROP_VALUE(TypeTag, PTAG(NewtonWriteConvergence))>  ConvergenceWriter;

246
    enum { enableTimeStepRampUp = GET_PROP_VALUE(TypeTag, PTAG(EnableTimeStepRampUp)) };
Andreas Lauser's avatar
Andreas Lauser committed
247
248
    enum { enablePartialReassemble = GET_PROP_VALUE(TypeTag, PTAG(EnablePartialReassemble)) };

249
public:
250
251
252
    /*!
     * \brief Constructor
     */
253
    NewtonController()
Andreas Lauser's avatar
Andreas Lauser committed
254
255
        : endIterMsgStream_(std::ostringstream::out),
          convergenceWriter_(asImp_())
256
257
258
    {
        numSteps_ = 0;

Andreas Lauser's avatar
Andreas Lauser committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
        this->setRelTolerance(1e-8);
        this->rampUpSteps_ = 0;

        if (enableTimeStepRampUp) {
            this->rampUpSteps_ = 9;
            
            // the ramp-up steps are not counting
            this->setTargetSteps(10);
            this->setMaxSteps(12);
        }
        else {
            this->setTargetSteps(10);
            this->setMaxSteps(18);
        }
273
274
275
    };

    /*!
276
     * \brief Set the maximum acceptable difference for convergence of
277
278
279
280
281
     *        any primary variable between two iterations.
     *
     * \param tolerance The maximum relative error between two Newton
     *                  iterations at which the scheme is considered
     *                  finished
282
283
284
285
286
287
288
     */
    void setRelTolerance(Scalar tolerance)
    { tolerance_ = tolerance; }

    /*!
     * \brief Set the number of iterations at which the Newton method
     *        should aim at.
289
290
291
292
293
294
     *
     * This is used to control the time step size. The heuristic used
     * is to scale the last time step size by the deviation of the
     * number of iterations used from the target steps.
     *
     * \param targetSteps Number of iterations which are considered "optimal"
295
296
297
298
299
300
301
     */
    void setTargetSteps(int targetSteps)
    { targetSteps_ = targetSteps; }

    /*!
     * \brief Set the number of iterations after which the Newton
     *        method gives up.
302
303
     *
     * \param maxSteps Number of iterations after we give up
304
305
306
     */
    void setMaxSteps(int maxSteps)
    { maxSteps_ = maxSteps; }
307
    
Andreas Lauser's avatar
Andreas Lauser committed
308
309
310
311
312
313
314
315
316
317
318
319
320
    /*!
     * \brief Returns the number of iterations used for the time step
     *        ramp-up.
     */
    Scalar rampUpSteps() const
    { return enableTimeStepRampUp?rampUpSteps_:0; }

    /*!
     * \brief Returns whether the time-step ramp-up is still happening
     */
    bool inRampUp() const
    { return numSteps_ < rampUpSteps(); }

321
    /*!
Andreas Lauser's avatar
Andreas Lauser committed
322
     * \brief Returns true if another iteration should be done.
323
324
     *
     * \param u The current solution
Andreas Lauser's avatar
Andreas Lauser committed
325
     */
326
    bool newtonProceed(const SolutionVector &uCurrentIter)
327
    {
Andreas Lauser's avatar
Andreas Lauser committed
328
        if (numSteps_ < rampUpSteps() + 2)
329
            return true; // we always do at least two iterations
Andreas Lauser's avatar
Andreas Lauser committed
330
331
332
        else if (asImp_().newtonConverged())
            return false; // we are below the desired tolerance
        else if (numSteps_ >= rampUpSteps() + maxSteps_) {
333
            // we have exceeded the allowed number of steps.  if the
334
            // relative error was reduced by a factor of at least 4,
335
336
            // we proceed even if we are above the maximum number of
            // steps
Andreas Lauser's avatar
Andreas Lauser committed
337
            return error_*4.0 < lastError_;
338
339
        }

340
        return true;
341
342
343
    }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
344
345
346
     * \brief Returns true iff the error of the solution is below the
     *        tolerance.
     */
347
348
    bool newtonConverged() const
    {
349
        return error_ <= tolerance_;
350
351
352
    }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
353
354
     * \brief Called before the newton method is applied to an
     *        non-linear system of equations.
355
356
357
     *
     * \param method The object where the NewtonMethod is executed
     * \param u The initial solution
Andreas Lauser's avatar
Andreas Lauser committed
358
     */
359
    void newtonBegin(NewtonMethod &method, const SolutionVector &u)
360
    {
Andreas Lauser's avatar
Andreas Lauser committed
361
        method_ = &method;
362
363
        numSteps_ = 0;

Andreas Lauser's avatar
Andreas Lauser committed
364
365
366
367
368
369
370
371
372
373
374
375
        model_().jacobianAssembler().reassembleAll();
        dtInitial_ = timeManager_().timeStepSize();
        if (enableTimeStepRampUp) {
            rampUpDelta_ = 
                timeManager_().timeStepSize() 
                /
                rampUpSteps()
                *
                2;

            // reduce initial time step size for ramp-up.
            timeManager_().setTimeStepSize(rampUpDelta_);
376
377
        }

378
379
380
381
        convergenceWriter_.beginTimestep();
    }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
382
383
     * \brief Indidicates the beginning of a newton iteration.
     */
384
385
386
387
    void newtonBeginStep()
    { lastError_ = error_; }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
388
389
390
     * \brief Returns the number of steps done since newtonBegin() was
     *        called.
     */
391
392
393
394
    int newtonNumSteps()
    { return numSteps_; }

    /*!
395
396
397
398
399
400
     * \brief Update the relative error of the solution compared to
     *        the previous iteration.
     *
     * The relative error can be seen as a norm of the difference
     * between the current and the next iteration.
     *
401
     * \param uLastIter The current iterative solution
402
     * \param deltaU The difference between the current and the next solution
Andreas Lauser's avatar
Andreas Lauser committed
403
     */
404
    void newtonUpdateRelError(const SolutionVector &uLastIter,
405
406
407
408
409
410
411
412
                              const SolutionVector &deltaU)
    {
        // calculate the relative error as the maximum relative
        // deflection in any degree of freedom.
        typedef typename SolutionVector::block_type FV;
        error_ = 0;

        int idxI = -1;
Andreas Lauser's avatar
Andreas Lauser committed
413
        int aboveTol = 0;
414
415
        for (int i = 0; i < int(uLastIter.size()); ++i) {
            PrimaryVariables uNewI = uLastIter[i];
Andreas Lauser's avatar
Andreas Lauser committed
416
417
418
            uNewI -= deltaU[i];
            Scalar vertErr = 
                model_().relativeErrorVertex(i,
419
                                             uLastIter[i],
Andreas Lauser's avatar
Andreas Lauser committed
420
                                             uNewI);
421
            
Andreas Lauser's avatar
Andreas Lauser committed
422
423
424
425
426
427
            if (vertErr > tolerance_)
                ++aboveTol;
            if (vertErr > error_) {
                idxI = i;
                error_ = vertErr;
            }
428
        }
429

Andreas Lauser's avatar
Andreas Lauser committed
430
        error_ = gridView_().comm().max(error_);
431
432
433
    }

    /*!
434
     * \brief Solve the linear system of equations \f$\mathbf{A}x - b = 0\f$.
Andreas Lauser's avatar
Andreas Lauser committed
435
436
437
     *
     * Throws Dumux::NumericalProblem if the linear solver didn't
     * converge.
438
439
     *
     * \param A The matrix of the linear system of equations
440
     * \param x The vector which solves the linear system
441
     * \param b The right hand side of the linear system
Andreas Lauser's avatar
Andreas Lauser committed
442
     */
Bernd Flemisch's avatar
Bernd Flemisch committed
443
444
    template <class Vector>
    void newtonSolveLinear(const JacobianMatrix &A,
445
                           Vector &x,
446
                           const Vector &b)
447
448
449
450
451
452
453
454
455
    {
        // if the deflection of the newton method is large, we do not
        // need to solve the linear approximation accurately. Assuming
        // that the initial value for the delta vector u is quite
        // close to the final value, a reduction of 6 orders of
        // magnitude in the defect should be sufficient...
        Scalar residReduction = 1e-6;

        try {
456
            solveLinear_(A, x, b, residReduction);
457

Andreas Lauser's avatar
Andreas Lauser committed
458
459
460
            // make sure all processes converged
            int converged = 1;
            gridView_().comm().min(converged);
461

Andreas Lauser's avatar
Andreas Lauser committed
462
463
464
465
            if (!converged) {
                DUNE_THROW(NumericalProblem,
                           "A process threw MatrixBlockError");
            }
466
467
468
469
        }
        catch (Dune::MatrixBlockError e) {
            // make sure all processes converged
            int converged = 0;
Andreas Lauser's avatar
Andreas Lauser committed
470
            gridView_().comm().min(converged);
471
472
473
474
475
476
477
478
479
480
481

            Dumux::NumericalProblem p;
            std::string msg;
            std::ostringstream ms(msg);
            ms << e.what() << "M=" << A[e.r][e.c];
            p.message(ms.str());
            throw p;
        }
    }

    /*!
482
     * \brief Update the current solution with a delta vector.
Andreas Lauser's avatar
Andreas Lauser committed
483
484
     *
     * The error estimates required for the newtonConverged() and
485
     * newtonProceed() methods should be updated inside this method.
Andreas Lauser's avatar
Andreas Lauser committed
486
487
488
     *
     * Different update strategies, such as line search and chopped
     * updates can be implemented. The default behaviour is just to
489
     * subtract deltaU from uLastIter, i.e.
490
     * \f[ u^{k+1} = u^k - \Delta u^k \f]
Andreas Lauser's avatar
Andreas Lauser committed
491
     *
492
493
     * \param uCurrentIter The solution vector after the current iteration
     * \param uLastIter The solution vector after the last iteration
Andreas Lauser's avatar
Andreas Lauser committed
494
495
496
497
     * \param deltaU The delta as calculated from solving the linear
     *               system of equations. This parameter also stores
     *               the updated solution.
     */
498
499
500
    void newtonUpdate(SolutionVector &uCurrentIter,
                      const SolutionVector &uLastIter,
                      const SolutionVector &deltaU)
501
    {
502
        writeConvergence_(uLastIter, deltaU);
503

504
        newtonUpdateRelError(uLastIter, deltaU);
Andreas Lauser's avatar
Andreas Lauser committed
505
506
507
508

        // compute the vertex and element colors for partial
        // reassembly
        if (enablePartialReassemble) {
509
510
            Scalar reassembleTol = Dumux::geometricMean(error_, 0.1*tolerance_);
            reassembleTol = std::max(reassembleTol, 0.1*tolerance_);
511
            this->model_().jacobianAssembler().updateDiscrepancy(uLastIter, deltaU);
Andreas Lauser's avatar
Andreas Lauser committed
512
            this->model_().jacobianAssembler().computeColors(reassembleTol);
513
        }
514

515
516
        uCurrentIter = uLastIter;
        uCurrentIter -= deltaU;
Andreas Lauser's avatar
Andreas Lauser committed
517
    }
518

519
    /*!
Andreas Lauser's avatar
Andreas Lauser committed
520
     * \brief Indicates that one newton iteration was finished.
521
522
     *
     * \param u The solution after the current iteration
523
     * \param uLastIter The solution at the beginning of the current iteration
Andreas Lauser's avatar
Andreas Lauser committed
524
     */
525
526
    void newtonEndStep(const SolutionVector &uCurrentIter, 
                       const SolutionVector &uLastIter)
527
528
    {
        ++numSteps_;
Andreas Lauser's avatar
Andreas Lauser committed
529
530
531
532
533
534
535
536
537

        Scalar realError = error_;
        if (inRampUp() && error_ < 1.0) {
            // change time step size
            Scalar dt = timeManager_().timeStepSize();
            dt += rampUpDelta_;
            timeManager_().setTimeStepSize(dt);

            endIterMsg() << ", dt=" << timeManager_().timeStepSize() << ", ddt=" << rampUpDelta_;
538
        }
539

Andreas Lauser's avatar
Andreas Lauser committed
540
        if (verbose())
541
            std::cout << "\rNewton iteration " << numSteps_ << " done: "
Andreas Lauser's avatar
Andreas Lauser committed
542
                      << "error=" << realError << endIterMsg().str() << "\n";
543
544
545
546
        endIterMsgStream_.str("");
    }

    /*!
547
548
     * \brief Indicates that we're done solving the non-linear system
     *        of equations.
Andreas Lauser's avatar
Andreas Lauser committed
549
     */
550
551
552
553
554
555
    void newtonEnd()
    {
        convergenceWriter_.endTimestep();
    }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
556
557
558
559
     * \brief Called if the newton method broke down.
     *
     * This method is called _after_ newtonEnd()
     */
560
561
    void newtonFail()
    {
Andreas Lauser's avatar
Andreas Lauser committed
562
        timeManager_().setTimeStepSize(dtInitial_);
563
564
565
566
        numSteps_ = targetSteps_*2;
    }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
567
568
569
570
     * \brief Called when the newton method was sucessful.
     *
     * This method is called _after_ newtonEnd()
     */
571
572
573
574
    void newtonSucceed()
    { }

    /*!
575
576
     * \brief Suggest a new time stepsize based on the old time step
     *        size.
Andreas Lauser's avatar
Andreas Lauser committed
577
578
579
580
581
     *
     * The default behaviour is to suggest the old time step size
     * scaled by the ratio between the target iterations and the
     * iterations required to actually solve the last time step.
     */
582
583
    Scalar suggestTimeStepSize(Scalar oldTimeStep) const
    {
Andreas Lauser's avatar
Andreas Lauser committed
584
585
586
        if (enableTimeStepRampUp)
            return oldTimeStep; 

587
        Scalar n = numSteps_;
Andreas Lauser's avatar
Andreas Lauser committed
588
589
        n -= rampUpSteps();

590
591
592
593
594
        // be agressive reducing the timestep size but
        // conservative when increasing it. the rationale is
        // that we want to avoid failing in the next newton
        // iteration which would require another linearization
        // of the problem.
595
596
        if (n > targetSteps_) {
            Scalar percent = (n - targetSteps_)/targetSteps_;
597
598
599
600
601
            return oldTimeStep/(1.0 + percent);
        }
        else {
            /*Scalar percent = (Scalar(1))/targetSteps_;
              return oldTimeStep*(1 + percent);
Andreas Lauser's avatar
Andreas Lauser committed
602
            */
603
            Scalar percent = (targetSteps_ - n)/targetSteps_;
604
605
606
607
608
            return oldTimeStep*(1.0 + percent/1.2);
        }
    }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
609
610
611
     * \brief Returns a reference to the current newton method
     *        which is controlled by this controller.
     */
612
613
614
615
    NewtonMethod &method()
    { return *method_; }

    /*!
Andreas Lauser's avatar
Andreas Lauser committed
616
617
618
     * \brief Returns a reference to the current newton method
     *        which is controlled by this controller.
     */
619
620
621
    const NewtonMethod &method() const
    { return *method_; }

Andreas Lauser's avatar
Andreas Lauser committed
622
623
624
    std::ostringstream &endIterMsg()
    { return endIterMsgStream_; }

625
    /*!
Andreas Lauser's avatar
Andreas Lauser committed
626
627
     * \brief Returns true iff the newton method ought to be chatty.
     */
628
    bool verbose() const
Andreas Lauser's avatar
Andreas Lauser committed
629
    { return gridView_().comm().rank() == 0; }
630

Andreas Lauser's avatar
Andreas Lauser committed
631
protected:
632
    /*!
Andreas Lauser's avatar
Andreas Lauser committed
633
634
635
636
     * \brief Returns a reference to the grid view.
     */
    const GridView &gridView_() const
    { return problem_().gridView(); }
637

Andreas Lauser's avatar
Andreas Lauser committed
638
639
640
641
642
643
644
645
646
647
648
649
    /*!
     * \brief Returns a reference to the problem.
     */
    Problem &problem_()
    { return method_->problem(); }

    /*!
     * \brief Returns a reference to the problem.
     */
    const Problem &problem_() const
    { return method_->problem(); }

650
651
652
653
654
655
    /*!
     * \brief Returns a reference to the time manager.
     */
    TimeManager &timeManager_()
    { return problem_().timeManager(); }

Andreas Lauser's avatar
Andreas Lauser committed
656
657
658
659
660
661
    /*!
     * \brief Returns a reference to the time manager.
     */
    const TimeManager &timeManager_() const
    { return problem_().timeManager(); }

Andreas Lauser's avatar
Andreas Lauser committed
662
663
664
665
666
667
668
669
670
671
672
    /*!
     * \brief Returns a reference to the problem.
     */
    Model &model_()
    { return problem_().model(); }

    /*!
     * \brief Returns a reference to the problem.
     */
    const Model &model_() const
    { return problem_().model(); }
673
674
675
676
677
678
679
680
681
682

    // returns the actual implementation for the cotroller we do
    // it this way in order to allow "poor man's virtual methods",
    // i.e. methods of subclasses which can be called by the base
    // class.
    Implementation &asImp_()
    { return *static_cast<Implementation*>(this); }
    const Implementation &asImp_() const
    { return *static_cast<const Implementation*>(this); }

683
    void writeConvergence_(const SolutionVector &uLastIter,
684
685
                           const SolutionVector &deltaU)
    {
Andreas Lauser's avatar
Andreas Lauser committed
686
        convergenceWriter_.beginIteration(this->gridView_());
687
        convergenceWriter_.writeFields(uLastIter, deltaU);
688
689
690
        convergenceWriter_.endIteration();
    };

691
692
693
694
695
    /*!
     * \brief Actually invoke the linear solver 
     *
     * Usually we use the solvers from DUNE-ISTL.
     */
Bernd Flemisch's avatar
Bernd Flemisch committed
696
697
    template <class Vector>
    void solveLinear_(const JacobianMatrix &A,
698
699
                      Vector &x,
                      const Vector &b,
700
701
702
                      Scalar residReduction)
    {
        int verbosity = GET_PROP_VALUE(TypeTag, PTAG(NewtonLinearSolverVerbosity));
Andreas Lauser's avatar
Andreas Lauser committed
703
        if (gridView_().comm().rank() != 0)
704
705
            verbosity = 0;

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
#if ! HAVE_DUNE_PDELAB
       typedef Dune::SeqILU0<JacobianMatrix, Vector, Vector> Preconditioner;
       Preconditioner precond(A, 1.0);

       typedef Dune::MatrixAdapter<JacobianMatrix,Vector,Vector> MatrixAdapter;
       MatrixAdapter operatorA(A);

       typedef Dune::BiCGSTABSolver<Vector> Solver;
       Solver solver(operatorA, precond, residReduction, 500, verbosity);
//        typedef Dune::RestartedGMResSolver<Vector> Solver;
//        Solver solver(operatorA, precond, residReduction, 50, 500, verbosity);

       Dune::InverseOperatorResult result;

        Vector bTmp(b);
       solver.apply(x, bTmp, result);

       if (!result.converged)
               DUNE_THROW(Dumux::NumericalProblem,
                               "Solving the linear system of equations did not converge.");
#else // HAVE_DUNE_PDELAB

728
#if HAVE_PARDISO
729
        typedef Dumux::PDELab::ISTLBackend_NoOverlap_Loop_Pardiso<TypeTag> Solver;
Andreas Lauser's avatar
Andreas Lauser committed
730
        Solver solver(problem_(), 500, verbosity);
731
732
#else // !HAVE_PARDISO
#if HAVE_MPI
733
//        typedef Dune::PDELab::ISTLBackend_NOVLP_BCGS_NOPREC<GridFunctionSpace> Solver;
Andreas Lauser's avatar
Andreas Lauser committed
734
//        Solver solver(model_().jacobianAssembler().gridFunctionSpace(), 50000, verbosity);
735
        typedef Dumux::PDELab::ISTLBackend_NoOverlap_BCGS_ILU<TypeTag> Solver;
Andreas Lauser's avatar
Andreas Lauser committed
736
        Solver solver(problem_(), 500, verbosity);
737
#else
Andreas Lauser's avatar
Andreas Lauser committed
738
        typedef Dune::PDELab::ISTLBackend_SEQ_BCGS_SSOR Solver;
739
740
741
742
        Solver solver(500, verbosity);
#endif // HAVE_MPI
#endif // HAVE_PARDISO

Andreas Lauser's avatar
Andreas Lauser committed
743
        //    Solver solver(model_().jacobianAssembler().gridFunctionSpace(), 500, verbosity);
744
745
        Vector bTmp(b);
        solver.apply(A, x, bTmp, residReduction);
746
747
748
749

        if (!solver.result().converged)
            DUNE_THROW(Dumux::NumericalProblem,
                       "Solving the linear system of equations did not converge.");
750
#endif // HAVE_DUNE_PDELAB
751
752
753
754
755

        // make sure the solver didn't produce a nan or an inf
        // somewhere. this should never happen but for some strange
        // reason it happens anyway.
        Scalar xNorm2 = x.two_norm2();
Andreas Lauser's avatar
Andreas Lauser committed
756
        gridView_().comm().sum(xNorm2);
757
758
759
760
761
762
763
764
765
766
767
768
769
        if (std::isnan(xNorm2) || !std::isfinite(xNorm2))
            DUNE_THROW(Dumux::NumericalProblem,
                       "The linear solver produced a NaN or inf somewhere.");
    }

    std::ostringstream endIterMsgStream_;

    NewtonMethod *method_;

    ConvergenceWriter convergenceWriter_;

    Scalar error_;
    Scalar lastError_;
770
    Scalar tolerance_;
771

772
773
    // number of iterations for the time-step ramp-up
    Scalar rampUpSteps_;
Andreas Lauser's avatar
Andreas Lauser committed
774
775
776
777
    // the increase of the time step size during the rampup
    Scalar rampUpDelta_;

    Scalar dtInitial_; // initial time step size
778

779
    // optimal number of iterations we want to achive
780
    int targetSteps_;
781
    // maximum number of iterations we do before giving up
782
    int maxSteps_;
783
    // actual number of steps done so far
784
    int numSteps_;
785
};
Andreas Lauser's avatar
Andreas Lauser committed
786
} // namespace Dumux
787
788

#endif