forked from OPM/opm-models
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfvbasediscretization.hh
1913 lines (1641 loc) · 71.7 KB
/
fvbasediscretization.hh
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
// vi: set et ts=4 sw=4 sts=4:
/*
This file is part of the Open Porous Media project (OPM).
OPM 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.
OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>.
Consult the COPYING file in the top-level source directory of this
module for the precise wording of the license and the list of
copyright holders.
*/
/*!
* \file
*
* \copydoc Ewoms::FvBaseDiscretization
*/
#ifndef EWOMS_FV_BASE_DISCRETIZATION_HH
#define EWOMS_FV_BASE_DISCRETIZATION_HH
#include <opm/material/densead/Math.hpp>
#include "fvbaseproperties.hh"
#include "fvbaselinearizer.hh"
#include "fvbasefdlocallinearizer.hh"
#include "fvbaseadlocallinearizer.hh"
#include "fvbaselocalresidual.hh"
#include "fvbaseelementcontext.hh"
#include "fvbaseboundarycontext.hh"
#include "fvbaseconstraintscontext.hh"
#include "fvbaseconstraints.hh"
#include "fvbasediscretization.hh"
#include "fvbasegradientcalculator.hh"
#include "fvbasenewtonmethod.hh"
#include "fvbaseprimaryvariables.hh"
#include "fvbaseintensivequantities.hh"
#include "fvbaseextensivequantities.hh"
#include "baseauxiliarymodule.hh"
#include <ewoms/parallel/gridcommhandles.hh>
#include <ewoms/parallel/threadmanager.hh>
#include <ewoms/linear/nullborderlistmanager.hh>
#include <ewoms/common/simulator.hh>
#include <ewoms/common/alignedallocator.hh>
#include <ewoms/common/timer.hh>
#include <ewoms/common/timerguard.hh>
#include <ewoms/linear/matrixblock.hh>
#include <opm/material/common/MathToolbox.hpp>
#include <opm/material/common/Valgrind.hpp>
#include <opm/material/common/Unused.hpp>
#include <opm/material/common/Exceptions.hpp>
#include <dune/common/version.hh>
#include <dune/common/fvector.hh>
#include <dune/common/fmatrix.hh>
#include <dune/istl/bvector.hh>
#if HAVE_DUNE_FEM
#if DUNE_VERSION_NEWER(DUNE_FEM, 2,6)
#include <dune/fem/space/common/adaptationmanager.hh>
#else
#include <dune/fem/space/common/adaptmanager.hh>
#endif
#include <dune/fem/space/common/restrictprolongtuple.hh>
#include <dune/fem/function/blockvectorfunction.hh>
#include <dune/fem/misc/capabilities.hh>
#endif
#include <limits>
#include <list>
#include <sstream>
#include <string>
#include <vector>
namespace Ewoms {
template<class TypeTag>
class FvBaseDiscretization;
} // namespace Ewoms
BEGIN_PROPERTIES
//! Set the default type for the time manager
SET_TYPE_PROP(FvBaseDiscretization, Simulator, Ewoms::Simulator<TypeTag>);
//! Mapper for the grid view's vertices.
#if DUNE_VERSION_NEWER(DUNE_GRID, 2,6)
SET_TYPE_PROP(FvBaseDiscretization, VertexMapper,
Dune::MultipleCodimMultipleGeomTypeMapper<typename GET_PROP_TYPE(TypeTag, GridView)>);
#else
SET_TYPE_PROP(FvBaseDiscretization, VertexMapper,
Dune::MultipleCodimMultipleGeomTypeMapper<typename GET_PROP_TYPE(TypeTag, GridView), Dune::MCMGVertexLayout>);
#endif
//! Mapper for the grid view's elements.
#if DUNE_VERSION_NEWER(DUNE_GRID, 2,6)
SET_TYPE_PROP(FvBaseDiscretization, ElementMapper,
Dune::MultipleCodimMultipleGeomTypeMapper<typename GET_PROP_TYPE(TypeTag, GridView)>);
#else
SET_TYPE_PROP(FvBaseDiscretization, ElementMapper,
Dune::MultipleCodimMultipleGeomTypeMapper<typename GET_PROP_TYPE(TypeTag, GridView), Dune::MCMGElementLayout>);
#endif
//! marks the border indices (required for the algebraic overlap stuff)
SET_PROP(FvBaseDiscretization, BorderListCreator)
{
typedef typename GET_PROP_TYPE(TypeTag, DofMapper) DofMapper;
typedef typename GET_PROP_TYPE(TypeTag, GridView) GridView;
public:
typedef Ewoms::Linear::NullBorderListCreator<GridView, DofMapper> type;
};
SET_TYPE_PROP(FvBaseDiscretization, DiscLocalResidual, Ewoms::FvBaseLocalResidual<TypeTag>);
SET_TYPE_PROP(FvBaseDiscretization, DiscIntensiveQuantities, Ewoms::FvBaseIntensiveQuantities<TypeTag>);
SET_TYPE_PROP(FvBaseDiscretization, DiscExtensiveQuantities, Ewoms::FvBaseExtensiveQuantities<TypeTag>);
//! Calculates the gradient of any quantity given the index of a flux approximation point
SET_TYPE_PROP(FvBaseDiscretization, GradientCalculator, Ewoms::FvBaseGradientCalculator<TypeTag>);
//! The maximum allowed number of timestep divisions for the
//! Newton solver
SET_INT_PROP(FvBaseDiscretization, MaxTimeStepDivisions, 10);
/*!
* \brief A vector of quanties, each for one equation.
*/
SET_TYPE_PROP(FvBaseDiscretization, EqVector,
Dune::FieldVector<typename GET_PROP_TYPE(TypeTag, Scalar),
GET_PROP_VALUE(TypeTag, NumEq)>);
/*!
* \brief A vector for mass/energy rates.
*
* E.g. Neumann fluxes or source terms
*/
SET_TYPE_PROP(FvBaseDiscretization, RateVector,
typename GET_PROP_TYPE(TypeTag, EqVector));
/*!
* \brief Type of object for specifying boundary conditions.
*/
SET_TYPE_PROP(FvBaseDiscretization, BoundaryRateVector,
typename GET_PROP_TYPE(TypeTag, RateVector));
/*!
* \brief The class which represents constraints.
*/
SET_TYPE_PROP(FvBaseDiscretization, Constraints, Ewoms::FvBaseConstraints<TypeTag>);
/*!
* \brief The type for storing a residual for an element.
*/
SET_TYPE_PROP(FvBaseDiscretization, ElementEqVector,
Dune::BlockVector<typename GET_PROP_TYPE(TypeTag, EqVector)>);
/*!
* \brief The type for storing a residual for the whole grid.
*/
SET_TYPE_PROP(FvBaseDiscretization, GlobalEqVector,
Dune::BlockVector<typename GET_PROP_TYPE(TypeTag, EqVector)>);
/*!
* \brief An object representing a local set of primary variables.
*/
SET_TYPE_PROP(FvBaseDiscretization, PrimaryVariables, Ewoms::FvBasePrimaryVariables<TypeTag>);
/*!
* \brief The type of a solution for the whole grid at a fixed time.
*/
SET_TYPE_PROP(FvBaseDiscretization, SolutionVector,
Dune::BlockVector<typename GET_PROP_TYPE(TypeTag, PrimaryVariables)>);
/*!
* \brief The class representing intensive quantities.
*
* This should almost certainly be overloaded by the model...
*/
SET_TYPE_PROP(FvBaseDiscretization, IntensiveQuantities, Ewoms::FvBaseIntensiveQuantities<TypeTag>);
/*!
* \brief The element context
*/
SET_TYPE_PROP(FvBaseDiscretization, ElementContext, Ewoms::FvBaseElementContext<TypeTag>);
SET_TYPE_PROP(FvBaseDiscretization, BoundaryContext, Ewoms::FvBaseBoundaryContext<TypeTag>);
SET_TYPE_PROP(FvBaseDiscretization, ConstraintsContext, Ewoms::FvBaseConstraintsContext<TypeTag>);
/*!
* \brief The OpenMP threads manager
*/
SET_TYPE_PROP(FvBaseDiscretization, ThreadManager, Ewoms::ThreadManager<TypeTag>);
SET_INT_PROP(FvBaseDiscretization, ThreadsPerProcess, 1);
SET_BOOL_PROP(FvBaseDiscretization, UseLinearizationLock, true);
/*!
* \brief Linearizer for the global system of equations.
*/
SET_TYPE_PROP(FvBaseDiscretization, Linearizer, Ewoms::FvBaseLinearizer<TypeTag>);
//! use an unlimited time step size by default
SET_SCALAR_PROP(FvBaseDiscretization, MaxTimeStepSize, std::numeric_limits<Scalar>::infinity());
//! By default, accept any time step larger than zero
SET_SCALAR_PROP(FvBaseDiscretization, MinTimeStepSize, 0.0);
//! Disable grid adaptation by default
SET_BOOL_PROP(FvBaseDiscretization, EnableGridAdaptation, false);
//! By default, write the simulation output to the current working directory
SET_STRING_PROP(FvBaseDiscretization, OutputDir, ".");
//! Enable the VTK output by default
SET_BOOL_PROP(FvBaseDiscretization, EnableVtkOutput, true);
//! By default, write the VTK output to asynchronously to disk
//!
//! This has only an effect if EnableVtkOutput is true
SET_BOOL_PROP(FvBaseDiscretization, EnableAsyncVtkOutput, true);
//! Set the format of the VTK output to ASCII by default
SET_INT_PROP(FvBaseDiscretization, VtkOutputFormat, Dune::VTK::ascii);
// disable caching the storage term by default
SET_BOOL_PROP(FvBaseDiscretization, EnableStorageCache, false);
// disable constraints by default
SET_BOOL_PROP(FvBaseDiscretization, EnableConstraints, false);
// by default, disable the intensive quantity cache. If the intensive quantities are
// relatively cheap to calculate, the cache basically does not yield any performance
// impact because of the intensive quantity cache will cause additional pressure on the
// CPU caches...
SET_BOOL_PROP(FvBaseDiscretization, EnableIntensiveQuantityCache, false);
// do not use thermodynamic hints by default. If you enable this, make sure to also
// enable the intensive quantity cache above to avoid getting an exception...
SET_BOOL_PROP(FvBaseDiscretization, EnableThermodynamicHints, false);
// if the deflection of the newton method is large, we do not need to solve the linear
// approximation accurately. Assuming that the value for the current solution is quite
// close to the final value, a reduction of 3 orders of magnitude in the defect should be
// sufficient...
SET_SCALAR_PROP(FvBaseDiscretization, LinearSolverTolerance, 1e-3);
// use default initialization based on rule-of-thumb of Newton tolerance
SET_SCALAR_PROP(FvBaseDiscretization, LinearSolverAbsTolerance, -1.);
//! Set the history size of the time discretization to 2 (for implicit euler)
SET_INT_PROP(FvBaseDiscretization, TimeDiscHistorySize, 2);
//! Most models use extensive quantities for their storage term (so far, only the Stokes
//! model does), so we disable this by default.
SET_BOOL_PROP(FvBaseDiscretization, ExtensiveStorageTerm, false);
// use volumetric residuals is default
SET_BOOL_PROP(FvBaseDiscretization, UseVolumetricResidual, true);
//! eWoms is mainly targeted at research, so experimental features are enabled by
//! default.
SET_BOOL_PROP(FvBaseDiscretization, EnableExperiments, true);
END_PROPERTIES
namespace Ewoms {
/*!
* \ingroup FiniteVolumeDiscretizations
*
* \brief The base class for the finite volume discretization schemes.
*/
template<class TypeTag>
class FvBaseDiscretization
{
typedef typename GET_PROP_TYPE(TypeTag, Model) Implementation;
typedef typename GET_PROP_TYPE(TypeTag, Discretization) Discretization;
typedef typename GET_PROP_TYPE(TypeTag, Simulator) Simulator;
typedef typename GET_PROP_TYPE(TypeTag, Grid) Grid;
typedef typename GET_PROP_TYPE(TypeTag, GridView) GridView;
typedef typename GET_PROP_TYPE(TypeTag, Scalar) Scalar;
typedef typename GET_PROP_TYPE(TypeTag, Evaluation) Evaluation;
typedef typename GET_PROP_TYPE(TypeTag, ElementMapper) ElementMapper;
typedef typename GET_PROP_TYPE(TypeTag, VertexMapper) VertexMapper;
typedef typename GET_PROP_TYPE(TypeTag, DofMapper) DofMapper;
typedef typename GET_PROP_TYPE(TypeTag, SolutionVector) SolutionVector;
typedef typename GET_PROP_TYPE(TypeTag, GlobalEqVector) GlobalEqVector;
typedef typename GET_PROP_TYPE(TypeTag, EqVector) EqVector;
typedef typename GET_PROP_TYPE(TypeTag, RateVector) RateVector;
typedef typename GET_PROP_TYPE(TypeTag, BoundaryRateVector) BoundaryRateVector;
typedef typename GET_PROP_TYPE(TypeTag, PrimaryVariables) PrimaryVariables;
typedef typename GET_PROP_TYPE(TypeTag, Linearizer) Linearizer;
typedef typename GET_PROP_TYPE(TypeTag, ElementContext) ElementContext;
typedef typename GET_PROP_TYPE(TypeTag, BoundaryContext) BoundaryContext;
typedef typename GET_PROP_TYPE(TypeTag, IntensiveQuantities) IntensiveQuantities;
typedef typename GET_PROP_TYPE(TypeTag, ExtensiveQuantities) ExtensiveQuantities;
typedef typename GET_PROP_TYPE(TypeTag, GradientCalculator) GradientCalculator;
typedef typename GET_PROP_TYPE(TypeTag, Stencil) Stencil;
typedef typename GET_PROP_TYPE(TypeTag, DiscBaseOutputModule) DiscBaseOutputModule;
typedef typename GET_PROP_TYPE(TypeTag, GridCommHandleFactory) GridCommHandleFactory;
typedef typename GET_PROP_TYPE(TypeTag, NewtonMethod) NewtonMethod;
typedef typename GET_PROP_TYPE(TypeTag, ThreadManager) ThreadManager;
typedef typename GET_PROP_TYPE(TypeTag, LocalLinearizer) LocalLinearizer;
typedef typename GET_PROP_TYPE(TypeTag, LocalResidual) LocalResidual;
enum {
numEq = GET_PROP_VALUE(TypeTag, NumEq),
historySize = GET_PROP_VALUE(TypeTag, TimeDiscHistorySize),
};
typedef std::vector<IntensiveQuantities, Ewoms::aligned_allocator<IntensiveQuantities, alignof(IntensiveQuantities)> > IntensiveQuantitiesVector;
typedef typename GridView::template Codim<0>::Entity Element;
typedef typename GridView::template Codim<0>::Iterator ElementIterator;
typedef Opm::MathToolbox<Evaluation> Toolbox;
typedef Dune::FieldVector<Evaluation, numEq> VectorBlock;
typedef Dune::FieldVector<Evaluation, numEq> EvalEqVector;
typedef typename LocalResidual::LocalEvalBlockVector LocalEvalBlockVector;
class BlockVectorWrapper
{
protected:
SolutionVector blockVector_;
public:
BlockVectorWrapper(const std::string& name OPM_UNUSED, const size_t size)
: blockVector_(size)
{}
SolutionVector& blockVector()
{ return blockVector_; }
const SolutionVector& blockVector() const
{ return blockVector_; }
};
#if HAVE_DUNE_FEM
typedef typename GET_PROP_TYPE(TypeTag, DiscreteFunctionSpace) DiscreteFunctionSpace;
// discrete function storing solution data
typedef Dune::Fem::ISTLBlockVectorDiscreteFunction<DiscreteFunctionSpace, PrimaryVariables> DiscreteFunction;
// problem restriction and prolongation operator for adaptation
typedef typename GET_PROP_TYPE(TypeTag, Problem) Problem;
typedef typename Problem :: RestrictProlongOperator ProblemRestrictProlongOperator;
// discrete function restriction and prolongation operator for adaptation
typedef Dune::Fem::RestrictProlongDefault< DiscreteFunction > DiscreteFunctionRestrictProlong;
typedef Dune::Fem::RestrictProlongTuple< DiscreteFunctionRestrictProlong, ProblemRestrictProlongOperator > RestrictProlong;
// adaptation classes
typedef Dune::Fem::AdaptationManager<Grid, RestrictProlong > AdaptationManager;
#else
typedef BlockVectorWrapper DiscreteFunction;
typedef size_t DiscreteFunctionSpace;
#endif
// copying a discretization object is not a good idea
FvBaseDiscretization(const FvBaseDiscretization& );
public:
// this constructor required to be explicitly specified because
// we've defined a constructor above which deletes all implicitly
// generated constructors in C++.
FvBaseDiscretization(Simulator& simulator)
: simulator_(simulator)
, gridView_(simulator.gridView())
#if DUNE_VERSION_NEWER(DUNE_GRID, 2,6)
, elementMapper_(gridView_, Dune::mcmgElementLayout())
, vertexMapper_(gridView_, Dune::mcmgVertexLayout())
#else
, elementMapper_(gridView_)
, vertexMapper_(gridView_)
#endif
, newtonMethod_(simulator)
, localLinearizer_(ThreadManager::maxThreads())
, linearizer_(new Linearizer())
#if HAVE_DUNE_FEM
, space_( simulator.vanguard().gridPart() )
#else
, space_( asImp_().numGridDof() )
#endif
, enableGridAdaptation_( EWOMS_GET_PARAM(TypeTag, bool, EnableGridAdaptation) )
, enableIntensiveQuantityCache_(EWOMS_GET_PARAM(TypeTag, bool, EnableIntensiveQuantityCache))
, enableStorageCache_(EWOMS_GET_PARAM(TypeTag, bool, EnableStorageCache))
, enableThermodynamicHints_(EWOMS_GET_PARAM(TypeTag, bool, EnableThermodynamicHints))
{
#if HAVE_DUNE_FEM
if (enableGridAdaptation_ && !Dune::Fem::Capabilities::isLocallyAdaptive<Grid>::v)
throw std::invalid_argument("Grid adaptation enabled, but chosen Grid is not capable"
" of adaptivity");
#else
if (enableGridAdaptation_)
throw std::invalid_argument("Grid adaptation currently requires the presence of the "
"dune-fem module");
#endif
bool isEcfv = std::is_same<Discretization, EcfvDiscretization<TypeTag> >::value;
if (enableGridAdaptation_ && !isEcfv)
throw std::invalid_argument("Grid adaptation currently only works for the "
"element-centered finite volume discretization (is: "
+Dune::className<Discretization>()+")");
enableStorageCache_ = EWOMS_GET_PARAM(TypeTag, bool, EnableStorageCache);
size_t numDof = asImp_().numGridDof();
for (unsigned timeIdx = 0; timeIdx < historySize; ++timeIdx) {
solution_[timeIdx].reset(new DiscreteFunction("solution", space_));
if (storeIntensiveQuantities()) {
intensiveQuantityCache_[timeIdx].resize(numDof);
intensiveQuantityCacheUpToDate_[timeIdx].resize(numDof, /*value=*/false);
}
if (enableStorageCache_)
storageCache_[timeIdx].resize(numDof);
}
resizeAndResetIntensiveQuantitiesCache_();
asImp_().registerOutputModules_();
}
~FvBaseDiscretization()
{
// delete all output modules
auto modIt = outputModules_.begin();
const auto& modEndIt = outputModules_.end();
for (; modIt != modEndIt; ++modIt)
delete *modIt;
delete linearizer_;
}
/*!
* \brief Register all run-time parameters for the model.
*/
static void registerParameters()
{
Linearizer::registerParameters();
LocalLinearizer::registerParameters();
LocalResidual::registerParameters();
GradientCalculator::registerParameters();
IntensiveQuantities::registerParameters();
ExtensiveQuantities::registerParameters();
NewtonMethod::registerParameters();
// register runtime parameters of the output modules
Ewoms::VtkPrimaryVarsModule<TypeTag>::registerParameters();
EWOMS_REGISTER_PARAM(TypeTag, bool, EnableGridAdaptation, "Enable adaptive grid refinement/coarsening");
EWOMS_REGISTER_PARAM(TypeTag, bool, EnableVtkOutput, "Global switch for turning on writing VTK files");
EWOMS_REGISTER_PARAM(TypeTag, bool, EnableThermodynamicHints, "Enable thermodynamic hints");
EWOMS_REGISTER_PARAM(TypeTag, bool, EnableIntensiveQuantityCache, "Turn on caching of intensive quantities");
EWOMS_REGISTER_PARAM(TypeTag, bool, EnableStorageCache, "Store previous storage terms and avoid re-calculating them.");
EWOMS_REGISTER_PARAM(TypeTag, std::string, OutputDir, "The directory to which result files are written");
}
/*!
* \brief Apply the initial conditions to the model.
*/
void finishInit()
{
// initialize the volume of the finite volumes to zero
size_t numDof = asImp_().numGridDof();
dofTotalVolume_.resize(numDof);
std::fill(dofTotalVolume_.begin(), dofTotalVolume_.end(), 0.0);
ElementContext elemCtx(simulator_);
gridTotalVolume_ = 0.0;
// iterate through the grid and evaluate the initial condition
ElementIterator elemIt = gridView_.template begin</*codim=*/0>();
const ElementIterator& elemEndIt = gridView_.template end</*codim=*/0>();
for (; elemIt != elemEndIt; ++elemIt) {
const Element& elem = *elemIt;
const bool isInteriorElement = elem.partitionType() == Dune::InteriorEntity;
// ignore everything which is not in the interior if the
// current process' piece of the grid
if (!isInteriorElement)
continue;
// deal with the current element
elemCtx.updateStencil(elem);
const auto& stencil = elemCtx.stencil(/*timeIdx=*/0);
// loop over all element vertices, i.e. sub control volumes
for (unsigned dofIdx = 0; dofIdx < elemCtx.numPrimaryDof(/*timeIdx=*/0); dofIdx++) {
// map the local degree of freedom index to the global one
unsigned globalIdx = elemCtx.globalSpaceIndex(dofIdx, /*timeIdx=*/0);
Scalar dofVolume = stencil.subControlVolume(dofIdx).volume();
dofTotalVolume_[globalIdx] += dofVolume;
if (isInteriorElement)
gridTotalVolume_ += dofVolume;
}
}
// determine which DOFs should be considered to lie fully in the interior of the
// local process grid partition: those which do not have a non-zero volume
// before taking the peer processes into account...
isLocalDof_.resize(numDof);
for (unsigned dofIdx = 0; dofIdx < numDof; ++dofIdx)
isLocalDof_[dofIdx] = (dofTotalVolume_[dofIdx] != 0.0);
// add the volumes of the DOFs on the process boundaries
const auto sumHandle =
GridCommHandleFactory::template sumHandle<Scalar>(dofTotalVolume_,
asImp_().dofMapper());
gridView_.communicate(*sumHandle,
Dune::InteriorBorder_All_Interface,
Dune::ForwardCommunication);
// sum up the volumes of the grid partitions
gridTotalVolume_ = gridView_.comm().sum(gridTotalVolume_);
linearizer_->init(simulator_);
for (unsigned threadId = 0; threadId < ThreadManager::maxThreads(); ++threadId)
localLinearizer_[threadId].init(simulator_);
resizeAndResetIntensiveQuantitiesCache_();
if (storeIntensiveQuantities()) {
// invalidate all cached intensive quantities
for (unsigned timeIdx = 0; timeIdx < historySize; ++ timeIdx)
invalidateIntensiveQuantitiesCache(timeIdx);
}
newtonMethod_.finishInit();
}
/*!
* \brief Returns whether the grid ought to be adapted to the solution during the simulation.
*/
bool enableGridAdaptation() const
{ return enableGridAdaptation_; }
/*!
* \brief Applies the initial solution for all degrees of freedom to which the model
* applies.
*/
void applyInitialSolution()
{
// first set the whole domain to zero
SolutionVector& uCur = asImp_().solution(/*timeIdx=*/0);
uCur = Scalar(0.0);
ElementContext elemCtx(simulator_);
// iterate through the grid and evaluate the initial condition
ElementIterator elemIt = gridView_.template begin</*codim=*/0>();
const ElementIterator& elemEndIt = gridView_.template end</*codim=*/0>();
for (; elemIt != elemEndIt; ++elemIt) {
const Element& elem = *elemIt;
// ignore everything which is not in the interior if the
// current process' piece of the grid
if (elem.partitionType() != Dune::InteriorEntity)
continue;
// deal with the current element
elemCtx.updateStencil(elem);
// loop over all element vertices, i.e. sub control volumes
for (unsigned dofIdx = 0; dofIdx < elemCtx.numPrimaryDof(/*timeIdx=*/0); dofIdx++)
{
// map the local degree of freedom index to the global one
unsigned globalIdx = elemCtx.globalSpaceIndex(dofIdx, /*timeIdx=*/0);
// let the problem do the dirty work of nailing down
// the initial solution.
simulator_.problem().initial(uCur[globalIdx], elemCtx, dofIdx, /*timeIdx=*/0);
asImp_().supplementInitialSolution_(uCur[globalIdx], elemCtx, dofIdx, /*timeIdx=*/0);
uCur[globalIdx].checkDefined();
}
}
// synchronize the ghost DOFs (if necessary)
asImp_().syncOverlap();
simulator_.problem().initialSolutionApplied();
// also set the solutions of the "previous" time steps to the initial solution.
for (unsigned timeIdx = 1; timeIdx < historySize; ++timeIdx)
solution(timeIdx) = solution(/*timeIdx=*/0);
#ifndef NDEBUG
for (unsigned timeIdx = 0; timeIdx < historySize; ++timeIdx) {
const auto& sol = solution(timeIdx);
for (unsigned dofIdx = 0; dofIdx < sol.size(); ++dofIdx)
sol[dofIdx].checkDefined();
}
#endif // NDEBUG
}
/*!
* \brief Allows to improve the performance by prefetching all data which is
* associated with a given element.
*/
void prefetch(const Element& elem OPM_UNUSED) const
{
// do nothing by default
}
/*!
* \brief Returns the newton method object
*/
NewtonMethod& newtonMethod()
{ return newtonMethod_; }
/*!
* \copydoc newtonMethod()
*/
const NewtonMethod& newtonMethod() const
{ return newtonMethod_; }
/*!
* \brief Return the thermodynamic hint for a entity on the grid at given time.
*
* The hint is defined as a IntensiveQuantities object which is supposed to be
* "close" to the IntensiveQuantities of the current solution. It can be used as a
* good starting point for non-linear solvers when having to solve non-linear
* relations while updating the intensive quantities. (This may yield a major
* performance boost depending on how the physical models require.)
*
* \attention If no up-to date intensive quantities are available, or if hints have been
* disabled, this method will return 0.
*
* \param globalIdx The global space index for the entity where a hint is requested.
* \param timeIdx The index used by the time discretization.
*/
const IntensiveQuantities* thermodynamicHint(unsigned globalIdx, unsigned timeIdx) const
{
if (!enableThermodynamicHints_)
return 0;
// the intensive quantities cache doubles as thermodynamic hint
return cachedIntensiveQuantities(globalIdx, timeIdx);
}
/*!
* \brief Return the cached intensive quantities for a entity on the
* grid at given time.
*
* \attention If no up-to date intensive quantities are available,
* this method will return 0.
*
* \param globalIdx The global space index for the entity where a
* hint is requested.
* \param timeIdx The index used by the time discretization.
*/
const IntensiveQuantities* cachedIntensiveQuantities(unsigned globalIdx, unsigned timeIdx) const
{
if (!enableIntensiveQuantityCache_ ||
!intensiveQuantityCacheUpToDate_[timeIdx][globalIdx])
return 0;
if (timeIdx > 0 && enableStorageCache_)
// with the storage cache enabled, only the intensive quantities for the most
// recent time step are cached!
return 0;
return &intensiveQuantityCache_[timeIdx][globalIdx];
}
/*!
* \brief Update the intensive quantity cache for a entity on the grid at given time.
*
* \param intQuants The IntensiveQuantities object hint for a given degree of freedom.
* \param globalIdx The global space index for the entity where a
* hint is to be set.
* \param timeIdx The index used by the time discretization.
*/
void updateCachedIntensiveQuantities(const IntensiveQuantities& intQuants,
unsigned globalIdx,
unsigned timeIdx) const
{
if (!storeIntensiveQuantities())
return;
intensiveQuantityCache_[timeIdx][globalIdx] = intQuants;
intensiveQuantityCacheUpToDate_[timeIdx][globalIdx] = true;
}
/*!
* \brief Invalidate the cache for a given intensive quantities object.
*
* \param globalIdx The global space index for the entity where a
* hint is to be set.
* \param timeIdx The index used by the time discretization.
*/
void setIntensiveQuantitiesCacheEntryValidity(unsigned globalIdx,
unsigned timeIdx,
bool newValue) const
{
if (!storeIntensiveQuantities())
return;
intensiveQuantityCacheUpToDate_[timeIdx][globalIdx] = newValue;
}
/*!
* \brief Invalidate the whole intensive quantity cache for time index.
*
* \param timeIdx The index used by the time discretization.
*/
void invalidateIntensiveQuantitiesCache(unsigned timeIdx) const
{
if (storeIntensiveQuantities()) {
std::fill(intensiveQuantityCacheUpToDate_[timeIdx].begin(),
intensiveQuantityCacheUpToDate_[timeIdx].end(),
/*value=*/false);
}
}
/*!
* \brief Move the intensive quantities for a given time index to the back.
*
* This method should only be called by the time discretization.
*
* \param numSlots The number of time step slots for which the
* hints should be shifted.
*/
void shiftIntensiveQuantityCache(unsigned numSlots = 1)
{
if (!storeIntensiveQuantities())
return;
if (enableStorageCache()) {
// if the storage term is cached, the intensive quantities of the previous
// time steps do not need to be accessed, and we can thus spare ourselves to
// copy the objects for the intensive quantities.
return;
}
assert(numSlots > 0);
for (unsigned timeIdx = 0; timeIdx < historySize - numSlots; ++ timeIdx) {
intensiveQuantityCache_[timeIdx + numSlots] = intensiveQuantityCache_[timeIdx];
intensiveQuantityCacheUpToDate_[timeIdx + numSlots] = intensiveQuantityCacheUpToDate_[timeIdx];
}
// the cache for the most recent time indices do not need to be invalidated
// because the solution for them did not change (TODO: that assumes that there is
// no post-processing of the solution after a time step! fix it?)
}
/*!
* \brief Returns true iff the storage term is cached.
*
* Be aware that calling the *CachedStorage() methods if the storage cache is
* disabled will crash the program.
*/
bool enableStorageCache() const
{ return enableStorageCache_; }
/*!
* \brief Retrieve an entry of the cache for the storage term.
*
* This is supposed to represent a DOF's total amount of conservation quantities per
* volume unit at a given time. The user is responsible for making sure that the
* value of this is correct and that it can be used before this method is called.
*
* \param globalDofIdx The index of the relevant degree of freedom in a grid-global vector
* \param timeIdx The relevant index for the time discretization
*/
const EqVector& cachedStorage(unsigned globalIdx, unsigned timeIdx) const
{
assert(enableStorageCache_);
return storageCache_[timeIdx][globalIdx];
}
/*!
* \brief Set an entry of the cache for the storage term.
*
* This is supposed to represent a DOF's total amount of conservation quantities per
* volume unit at a given time. The user is responsible for making sure that the
* storage cache is enabled before this method is called.
*
* \param globalDofIdx The index of the relevant degree of freedom in a grid-global vector
* \param timeIdx The relevant index for the time discretization
* \param value The new value of the cache for the storage term
*/
void updateCachedStorage(unsigned globalIdx, unsigned timeIdx, const EqVector& value) const
{
assert(enableStorageCache_);
storageCache_[timeIdx][globalIdx] = value;
}
/*!
* \brief Compute the global residual for an arbitrary solution
* vector.
*
* \param dest Stores the result
* \param u The solution for which the residual ought to be calculated
*/
Scalar globalResidual(GlobalEqVector& dest,
const SolutionVector& u) const
{
SolutionVector tmp(asImp_().solution(/*timeIdx=*/0));
mutableSolution(/*timeIdx=*/0) = u;
Scalar res = asImp_().globalResidual(dest);
mutableSolution(/*timeIdx=*/0) = tmp;
return res;
}
/*!
* \brief Compute the global residual for the current solution
* vector.
*
* \param dest Stores the result
*/
Scalar globalResidual(GlobalEqVector& dest) const
{
dest = 0;
std::mutex mutex;
ThreadedEntityIterator<GridView, /*codim=*/0> threadedElemIt(gridView_);
#ifdef _OPENMP
#pragma omp parallel
#endif
{
// Attention: the variables below are thread specific and thus cannot be
// moved in front of the #pragma!
unsigned threadId = ThreadManager::threadId();
ElementContext elemCtx(simulator_);
ElementIterator elemIt = threadedElemIt.beginParallel();
LocalEvalBlockVector residual, storageTerm;
for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
const Element& elem = *elemIt;
if (elem.partitionType() != Dune::InteriorEntity)
continue;
elemCtx.updateAll(elem);
residual.resize(elemCtx.numDof(/*timeIdx=*/0));
storageTerm.resize(elemCtx.numPrimaryDof(/*timeIdx=*/0));
asImp_().localResidual(threadId).eval(residual, elemCtx);
size_t numPrimaryDof = elemCtx.numPrimaryDof(/*timeIdx=*/0);
mutex.lock();
for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx) {
unsigned globalI = elemCtx.globalSpaceIndex(dofIdx, /*timeIdx=*/0);
for (unsigned eqIdx = 0; eqIdx < numEq; ++ eqIdx)
dest[globalI][eqIdx] += Toolbox::value(residual[dofIdx][eqIdx]);
}
mutex.unlock();
}
}
// add up the residuals on the process borders
const auto sumHandle =
GridCommHandleFactory::template sumHandle<EqVector>(dest, asImp_().dofMapper());
gridView_.communicate(*sumHandle,
Dune::InteriorBorder_InteriorBorder_Interface,
Dune::ForwardCommunication);
// calculate the square norm of the residual. this is not
// entirely correct, since the residual for the finite volumes
// which are on the boundary are counted once for every
// process. As often in life: shit happens (, we don't care)...
Scalar result2 = dest.two_norm2();
result2 = asImp_().gridView().comm().sum(result2);
return std::sqrt(result2);
}
/*!
* \brief Compute the integral over the domain of the storage
* terms of all conservation quantities.
*
* \copydetails Doxygen::storageParam
*/
void globalStorage(EqVector& storage, unsigned timeIdx = 0) const
{
storage = 0;
std::mutex mutex;
ThreadedEntityIterator<GridView, /*codim=*/0> threadedElemIt(gridView());
#ifdef _OPENMP
#pragma omp parallel
#endif
{
// Attention: the variables below are thread specific and thus cannot be
// moved in front of the #pragma!
unsigned threadId = ThreadManager::threadId();
ElementContext elemCtx(simulator_);
ElementIterator elemIt = threadedElemIt.beginParallel();
LocalEvalBlockVector elemStorage;
// in this method, we need to disable the storage cache because we want to
// evaluate the storage term for other time indices than the most recent one
elemCtx.setEnableStorageCache(false);
for (; !threadedElemIt.isFinished(elemIt); elemIt = threadedElemIt.increment()) {
const Element& elem = *elemIt;
if (elem.partitionType() != Dune::InteriorEntity)
continue; // ignore ghost and overlap elements
elemCtx.updateStencil(elem);
elemCtx.updatePrimaryIntensiveQuantities(timeIdx);
size_t numPrimaryDof = elemCtx.numPrimaryDof(timeIdx);
elemStorage.resize(numPrimaryDof);
localResidual(threadId).evalStorage(elemStorage, elemCtx, timeIdx);
mutex.lock();
for (unsigned dofIdx = 0; dofIdx < numPrimaryDof; ++dofIdx)
for (unsigned eqIdx = 0; eqIdx < numEq; ++eqIdx)
storage[eqIdx] += Toolbox::value(elemStorage[dofIdx][eqIdx]);
mutex.unlock();
}
}
storage = gridView_.comm().sum(storage);
}
/*!
* \brief Ensure that the difference between the storage terms of the last and of the
* current time step is consistent with the source and boundary terms.
*
* This method is purely intented for debugging purposes. If the program is compiled
* with optimizations enabled, it becomes a no-op.
*/
void checkConservativeness(Scalar OPM_OPTIM_UNUSED tolerance = -1, bool OPM_OPTIM_UNUSED verbose=false) const
{
#ifndef NDEBUG
Scalar totalBoundaryArea(0.0);
Scalar totalVolume(0.0);
EvalEqVector totalRate(0.0);
// take the newton tolerance times the total volume of the grid if we're not
// given an explicit tolerance...
if (tolerance <= 0) {
tolerance =
simulator_.model().newtonMethod().tolerance()
* simulator_.model().gridTotalVolume()
* 1000;
}
// we assume the implicit Euler time discretization for now...
assert(historySize == 2);
EqVector storageBeginTimeStep(0.0);
globalStorage(storageBeginTimeStep, /*timeIdx=*/1);
EqVector storageEndTimeStep(0.0);
globalStorage(storageEndTimeStep, /*timeIdx=*/0);
// calculate the rate at the boundary and the source rate
ElementContext elemCtx(simulator_);
elemCtx.setEnableStorageCache(false);
auto eIt = simulator_.gridView().template begin</*codim=*/0>();
const auto& elemEndIt = simulator_.gridView().template end</*codim=*/0>();
for (; eIt != elemEndIt; ++eIt) {
if (eIt->partitionType() != Dune::InteriorEntity)
continue; // ignore ghost and overlap elements
elemCtx.updateAll(*eIt);
// handle the boundary terms
if (elemCtx.onBoundary()) {
BoundaryContext boundaryCtx(elemCtx);
for (unsigned faceIdx = 0; faceIdx < boundaryCtx.numBoundaryFaces(/*timeIdx=*/0); ++faceIdx) {
BoundaryRateVector values;
simulator_.problem().boundary(values,
boundaryCtx,
faceIdx,
/*timeIdx=*/0);
Opm::Valgrind::CheckDefined(values);
unsigned dofIdx = boundaryCtx.interiorScvIndex(faceIdx, /*timeIdx=*/0);
const auto& insideIntQuants = elemCtx.intensiveQuantities(dofIdx, /*timeIdx=*/0);
Scalar bfArea =
boundaryCtx.boundarySegmentArea(faceIdx, /*timeIdx=*/0)
* insideIntQuants.extrusionFactor();
for (unsigned i = 0; i < values.size(); ++i)
values[i] *= bfArea;
totalBoundaryArea += bfArea;
for (unsigned eqIdx = 0; eqIdx < numEq; ++eqIdx)
totalRate[eqIdx] += values[eqIdx];
}
}
// deal with the source terms
for (unsigned dofIdx = 0; dofIdx < elemCtx.numPrimaryDof(/*timeIdx=*/0); ++ dofIdx) {
RateVector values;
simulator_.problem().source(values,
elemCtx,
dofIdx,