-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathConvectionDispersionOperator.cpp
790 lines (678 loc) · 31 KB
/
ConvectionDispersionOperator.cpp
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
// =============================================================================
// CADET
//
// Copyright © 2008-2021: The CADET Authors
// Please see the AUTHORS and CONTRIBUTORS file.
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the GNU Public License v3.0 (or, at
// your option, any later version) which accompanies this distribution, and
// is available at http://www.gnu.org/licenses/gpl.html
// =============================================================================
#include "model/parts/ConvectionDispersionOperator.hpp"
#include "cadet/Exceptions.hpp"
#include "Stencil.hpp"
#include "ParamReaderHelper.hpp"
#include "AdUtils.hpp"
#include "SimulationTypes.hpp"
#include "model/parts/ConvectionDispersionKernel.hpp"
#include "SensParamUtil.hpp"
#include "LoggingUtils.hpp"
#include "Logging.hpp"
#include <algorithm>
namespace cadet
{
namespace model
{
namespace parts
{
/**
* @brief Creates a ConvectionDispersionOperatorBase
*/
ConvectionDispersionOperatorBase::ConvectionDispersionOperatorBase() : _stencilMemory(sizeof(active) * Weno::maxStencilSize()),
_wenoDerivatives(new double[Weno::maxStencilSize()]), _weno()
{
}
ConvectionDispersionOperatorBase::~ConvectionDispersionOperatorBase() CADET_NOEXCEPT
{
delete[] _wenoDerivatives;
}
/**
* @brief Reads parameters and allocates memory
* @details Has to be called once before the operator is used.
* @param [in] paramProvider Parameter provider for reading parameters
* @param [in] nComp Number of components
* @param [in] nCol Number of axial cells
* @return @c true if configuration went fine, @c false otherwise
*/
bool ConvectionDispersionOperatorBase::configureModelDiscretization(IParameterProvider& paramProvider, unsigned int nComp, unsigned int nCol, unsigned int strideCell)
{
_nComp = nComp;
_nCol = nCol;
_strideCell = strideCell;
paramProvider.pushScope("discretization");
// Read WENO settings and apply them
paramProvider.pushScope("weno");
_weno.order(paramProvider.getInt("WENO_ORDER"));
_weno.boundaryTreatment(paramProvider.getInt("BOUNDARY_MODEL"));
_wenoEpsilon = paramProvider.getDouble("WENO_EPS");
paramProvider.popScope();
paramProvider.popScope();
return true;
}
/**
* @brief Reads model parameters
* @details Only reads parameters that do not affect model structure (e.g., discretization).
* @param [in] unitOpIdx Unit operation id of the owning unit operation model
* @param [in] paramProvider Parameter provider for reading parameters
* @param [out] parameters Map in which local parameters are inserted
* @return @c true if configuration went fine, @c false otherwise
*/
bool ConvectionDispersionOperatorBase::configure(UnitOpIdx unitOpIdx, IParameterProvider& paramProvider, std::unordered_map<ParameterId, active*>& parameters)
{
// Read geometry parameters
_colLength = paramProvider.getDouble("COL_LENGTH");
// Read cross section area or set to -1
_crossSection = -1.0;
if (paramProvider.exists("CROSS_SECTION_AREA"))
{
_crossSection = paramProvider.getDouble("CROSS_SECTION_AREA");
}
// Read section dependent parameters (transport)
// Read VELOCITY
_velocity.clear();
if (paramProvider.exists("VELOCITY"))
{
readScalarParameterOrArray(_velocity, paramProvider, "VELOCITY", 1);
}
readScalarParameterOrArray(_colDispersion, paramProvider, "COL_DISPERSION", 1);
if (paramProvider.exists("COL_DISPERSION_MULTIPLEX"))
{
const int mode = paramProvider.getInt("COL_DISPERSION_MULTIPLEX");
if (mode == 0)
// Comp-indep, sec-indep
_dispersionCompIndep = true;
else if (mode == 1)
// Comp-dep, sec-indep
_dispersionCompIndep = false;
else if (mode == 2)
// Comp-indep, sec-dep
_dispersionCompIndep = true;
else if (mode == 3)
// Comp-dep, sec-dep
_dispersionCompIndep = false;
if (!_dispersionCompIndep && (_colDispersion.size() % _nComp != 0))
throw InvalidParameterException("Number of elements in field COL_DISPERSION is not a positive multiple of NCOMP (" + std::to_string(_nComp) + ")");
if ((mode == 0) && (_colDispersion.size() != 1))
throw InvalidParameterException("Number of elements in field COL_DISPERSION inconsistent with COL_DISPERSION_MULTIPLEX (should be 1)");
if ((mode == 1) && (_colDispersion.size() != _nComp))
throw InvalidParameterException("Number of elements in field COL_DISPERSION inconsistent with COL_DISPERSION_MULTIPLEX (should be " + std::to_string(_nComp) + ")");
}
else
{
// Infer component dependence of COL_DISPERSION:
// size not divisible by NCOMP -> component independent
_dispersionCompIndep = ((_colDispersion.size() % _nComp) != 0);
}
// Expand _colDispersion to make it component dependent
if (_dispersionCompIndep)
{
std::vector<active> expanded(_colDispersion.size() * _nComp);
for (std::size_t i = 0; i < _colDispersion.size(); ++i)
std::fill(expanded.begin() + i * _nComp, expanded.begin() + (i + 1) * _nComp, _colDispersion[i]);
_colDispersion = std::move(expanded);
}
if (_velocity.empty() && (_crossSection <= 0.0))
{
throw InvalidParameterException("At least one of CROSS_SECTION_AREA and VELOCITY has to be set");
}
// Add parameters to map
if (_dispersionCompIndep)
{
if (_colDispersion.size() > _nComp)
{
// Register only the first item in each section
for (std::size_t i = 0; i < _colDispersion.size() / _nComp; ++i)
parameters[makeParamId(hashString("COL_DISPERSION"), unitOpIdx, CompIndep, ParTypeIndep, BoundStateIndep, ReactionIndep, i)] = &_colDispersion[i * _nComp];
}
else
{
// We have only one parameter
parameters[makeParamId(hashString("COL_DISPERSION"), unitOpIdx, CompIndep, ParTypeIndep, BoundStateIndep, ReactionIndep, SectionIndep)] = &_colDispersion[0];
}
}
else
registerParam2DArray(parameters, _colDispersion, [=](bool multi, unsigned int sec, unsigned int comp) { return makeParamId(hashString("COL_DISPERSION"), unitOpIdx, comp, ParTypeIndep, BoundStateIndep, ReactionIndep, multi ? sec : SectionIndep); }, _nComp);
registerScalarSectionDependentParam(hashString("VELOCITY"), parameters, _velocity, unitOpIdx, ParTypeIndep);
parameters[makeParamId(hashString("COL_LENGTH"), unitOpIdx, CompIndep, ParTypeIndep, BoundStateIndep, ReactionIndep, SectionIndep)] = &_colLength;
parameters[makeParamId(hashString("CROSS_SECTION_AREA"), unitOpIdx, CompIndep, ParTypeIndep, BoundStateIndep, ReactionIndep, SectionIndep)] = &_crossSection;
return true;
}
/**
* @brief Notifies the operator that a discontinuous section transition is in progress
* @details In addition to changing flow direction internally, if necessary, the function returns whether
* the flow direction has changed.
* @param [in] t Current time point
* @param [in] secIdx Index of the new section that is about to be integrated
* @return @c true if flow direction has changed, otherwise @c false
*/
bool ConvectionDispersionOperatorBase::notifyDiscontinuousSectionTransition(double t, unsigned int secIdx)
{
double prevVelocity = static_cast<double>(_curVelocity);
// If we don't have cross section area, velocity is given by parameter
if (_crossSection <= 0.0)
_curVelocity = getSectionDependentScalar(_velocity, secIdx);
else if (!_velocity.empty())
{
if (secIdx > 0)
{
const double dir = static_cast<double>(getSectionDependentScalar(_velocity, secIdx - 1));
if (dir < 0.0)
prevVelocity *= -1.0;
}
// We have both cross section area and interstitial flow rate
// _curVelocity has already been set to the network flow rate in setFlowRates()
// the direction of the flow (i.e., sign of _curVelocity) is given by _velocity
const double dir = static_cast<double>(getSectionDependentScalar(_velocity, secIdx));
if (dir < 0.0)
_curVelocity *= -1.0;
}
return (prevVelocity * static_cast<double>(_curVelocity) < 0.0);
}
/**
* @brief Sets the flow rates for the current time section
* @details The flow rates may change due to valve switches.
* @param [in] in Total volumetric inlet flow rate
* @param [in] out Total volumetric outlet flow rate
* @param [in] colPorosity Porosity used for computing interstitial velocity from volumetric flow rate
*/
void ConvectionDispersionOperatorBase::setFlowRates(const active& in, const active& out, const active& colPorosity) CADET_NOEXCEPT
{
// If we have cross section area, interstitial velocity is given by network flow rates
if (_crossSection > 0.0)
_curVelocity = in / (_crossSection * colPorosity);
}
/**
* @brief Computes the residual of the transport equations
* @param [in] t Current time point
* @param [in] secIdx Index of the current section
* @param [in] y Pointer to unit operation's state vector
* @param [in] yDot Pointer to unit operation's time derivative state vector
* @param [out] res Pointer to unit operation's residual vector
* @param [in] jac Matrix that holds the Jacobian
* @return @c 0 on success, @c -1 on non-recoverable error, and @c +1 on recoverable error
*/
int ConvectionDispersionOperatorBase::residual(double t, unsigned int secIdx, double const* y, double const* yDot, double* res, linalg::BandMatrix& jac)
{
// Reset Jacobian
jac.setAll(0.0);
return residualImpl<double, double, double, linalg::BandMatrix::RowIterator, true>(t, secIdx, y, yDot, res, jac.row(0));
}
int ConvectionDispersionOperatorBase::residual(double t, unsigned int secIdx, double const* y, double const* yDot, double* res, WithoutParamSensitivity)
{
return residualImpl<double, double, double, linalg::BandMatrix::RowIterator, false>(t, secIdx, y, yDot, res, linalg::BandMatrix::RowIterator());
}
int ConvectionDispersionOperatorBase::residual(double t, unsigned int secIdx, active const* y, double const* yDot, active* res, WithoutParamSensitivity)
{
return residualImpl<active, active, double, linalg::BandMatrix::RowIterator, false>(t, secIdx, y, yDot, res, linalg::BandMatrix::RowIterator());
}
int ConvectionDispersionOperatorBase::residual(double t, unsigned int secIdx, double const* y, double const* yDot, active* res, linalg::BandMatrix& jac)
{
// Reset Jacobian
jac.setAll(0.0);
return residualImpl<double, active, active, linalg::BandMatrix::RowIterator, true>(t, secIdx, y, yDot, res, jac.row(0));
}
int ConvectionDispersionOperatorBase::residual(double t, unsigned int secIdx, double const* y, double const* yDot, active* res, WithParamSensitivity)
{
return residualImpl<double, active, active, linalg::BandMatrix::RowIterator, false>(t, secIdx, y, yDot, res, linalg::BandMatrix::RowIterator());
}
int ConvectionDispersionOperatorBase::residual(double t, unsigned int secIdx, active const* y, double const* yDot, active* res, WithParamSensitivity)
{
return residualImpl<active, active, active, linalg::BandMatrix::RowIterator, false>(t, secIdx, y, yDot, res, linalg::BandMatrix::RowIterator());
}
template <typename StateType, typename ResidualType, typename ParamType, typename RowIteratorType, bool wantJac>
int ConvectionDispersionOperatorBase::residualImpl(double t, unsigned int secIdx, StateType const* y, double const* yDot, ResidualType* res, RowIteratorType jacBegin)
{
const ParamType u = static_cast<ParamType>(_curVelocity);
active const* const d_c = getSectionDependentSlice(_colDispersion, _nComp, secIdx);
const ParamType h = static_cast<ParamType>(_colLength) / static_cast<double>(_nCol);
// const int strideCell = strideColCell();
convdisp::FlowParameters<ParamType> fp{
u,
d_c,
h,
_wenoDerivatives,
&_weno,
&_stencilMemory,
_wenoEpsilon,
strideColCell(),
_nComp,
_nCol,
0u,
_nComp
};
return convdisp::residualKernel<StateType, ResidualType, ParamType, RowIteratorType, wantJac>(SimulationTime{t, secIdx}, y, yDot, res, jacBegin, fp);
}
/**
* @brief Multiplies the time derivative Jacobian @f$ \frac{\partial F}{\partial \dot{y}}\left(t, y, \dot{y}\right) @f$ with a given vector
* @details The operation @f$ z = \frac{\partial F}{\partial \dot{y}} x @f$ is performed.
* The matrix-vector multiplication is performed matrix-free (i.e., no matrix is explicitly formed).
*
* Note that this function only performs multiplication with the Jacobian of the (axial) transport equations.
* The input vectors are assumed to point to the beginning (including inlet DOFs) of the respective unit operation's arrays.
* @param [in] simTime Simulation time information (time point, section index, pre-factor of time derivatives)
* @param [in] sDot Vector @f$ x @f$ that is transformed by the Jacobian @f$ \frac{\partial F}{\partial \dot{y}} @f$
* @param [out] ret Vector @f$ z @f$ which stores the result of the operation
*/
void ConvectionDispersionOperatorBase::multiplyWithDerivativeJacobian(const SimulationTime& simTime, double const* sDot, double* ret) const
{
double* localRet = ret + offsetC();
double const* localSdot = sDot + offsetC();
const int gapCell = strideColCell() - static_cast<int>(_nComp) * strideColComp();
for (unsigned int i = 0; i < _nCol; ++i, localRet += gapCell, localSdot += gapCell)
{
for (unsigned int j = 0; j < _nComp; ++j, ++localRet, ++localSdot)
{
*localRet = (*localSdot);
}
}
}
/**
* @brief Adds the derivatives with respect to @f$ \dot{y} @f$ of @f$ F(t, y, \dot{y}) @f$ to the Jacobian
* @details This functions computes
* @f[ \begin{align*} \text{_jacCdisc} = \text{_jacCdisc} + \alpha \frac{\partial F}{\partial \dot{y}}. \end{align*} @f]
* The factor @f$ \alpha @f$ is useful when constructing the linear system in the time integration process.
* @param [in] alpha Factor in front of @f$ \frac{\partial F}{\partial \dot{y}} @f$
*/
void ConvectionDispersionOperatorBase::addTimeDerivativeToJacobian(double alpha, linalg::FactorizableBandMatrix& jacDisc)
{
const int gapCell = strideColCell() - static_cast<int>(_nComp) * strideColComp();
linalg::FactorizableBandMatrix::RowIterator jac = jacDisc.row(0);
for (unsigned int i = 0; i < _nCol; ++i, jac += gapCell)
{
for (unsigned int j = 0; j < _nComp; ++j, ++jac)
{
// Add time derivative to main diagonal
jac[0] += alpha;
}
}
}
unsigned int ConvectionDispersionOperatorBase::jacobianLowerBandwidth() const CADET_NOEXCEPT
{
// Note that we have to increase the lower bandwidth by 1 because the WENO stencil is applied to the
// right cell face (lower + 1 + upper) and to the left cell face (shift the stencil by -1 because influx of cell i
// is outflux of cell i-1)
// We also have to make sure that there's at least one sub and super diagonal for the dispersion term
return std::max(_weno.lowerBandwidth() + 1u, 1u) * strideColCell();
}
unsigned int ConvectionDispersionOperatorBase::jacobianUpperBandwidth() const CADET_NOEXCEPT
{
// We have to make sure that there's at least one sub and super diagonal for the dispersion term
return std::max(_weno.upperBandwidth(), 1u) * strideColCell();
}
unsigned int ConvectionDispersionOperatorBase::jacobianDiscretizedBandwidth() const CADET_NOEXCEPT
{
// When flow direction is changed, the bandwidths of the Jacobian swap.
// Hence, we have to reserve memory such that the swapped Jacobian can fit into the matrix.
return std::max(jacobianLowerBandwidth(), jacobianUpperBandwidth());
}
bool ConvectionDispersionOperatorBase::setParameter(const ParameterId& pId, double value)
{
// We only need to do something if COL_DISPERSION is component independent
if (!_dispersionCompIndep)
return false;
if ((pId.name != hashString("COL_DISPERSION")) || (pId.component != CompIndep) || (pId.boundState != BoundStateIndep) || (pId.reaction != ReactionIndep) || (pId.particleType != ParTypeIndep))
return false;
if (_colDispersion.size() > _nComp)
{
// Section dependent
if (pId.section == SectionIndep)
return false;
for (unsigned int i = 0; i < _nComp; ++i)
_colDispersion[pId.section * _nComp + i].setValue(value);
}
else
{
// Section independent
if (pId.section != SectionIndep)
return false;
for (unsigned int i = 0; i < _nComp; ++i)
_colDispersion[i].setValue(value);
}
return true;
}
bool ConvectionDispersionOperatorBase::setSensitiveParameterValue(const std::unordered_set<active*>& sensParams, const ParameterId& pId, double value)
{
// We only need to do something if COL_DISPERSION is component independent
if (!_dispersionCompIndep)
return false;
if ((pId.name != hashString("COL_DISPERSION")) || (pId.component != CompIndep) || (pId.boundState != BoundStateIndep) || (pId.reaction != ReactionIndep) || (pId.particleType != ParTypeIndep))
return false;
if (_colDispersion.size() > _nComp)
{
// Section dependent
if (pId.section == SectionIndep)
return false;
if (!contains(sensParams, &_colDispersion[pId.section * _nComp]))
return false;
for (unsigned int i = 0; i < _nComp; ++i)
_colDispersion[pId.section * _nComp + i].setValue(value);
}
else
{
// Section independent
if (pId.section != SectionIndep)
return false;
if (!contains(sensParams, &_colDispersion[0]))
return false;
for (unsigned int i = 0; i < _nComp; ++i)
_colDispersion[i].setValue(value);
}
return true;
}
bool ConvectionDispersionOperatorBase::setSensitiveParameter(std::unordered_set<active*>& sensParams, const ParameterId& pId, unsigned int adDirection, double adValue)
{
// We only need to do something if COL_DISPERSION is component independent
if (!_dispersionCompIndep)
return false;
if ((pId.name != hashString("COL_DISPERSION")) || (pId.component != CompIndep) || (pId.boundState != BoundStateIndep) || (pId.reaction != ReactionIndep) || (pId.particleType != ParTypeIndep))
return false;
if (_colDispersion.size() > _nComp)
{
// Section dependent
if (pId.section == SectionIndep)
return false;
sensParams.insert(&_colDispersion[pId.section * _nComp]);
for (unsigned int i = 0; i < _nComp; ++i)
_colDispersion[pId.section * _nComp + i].setADValue(adDirection, adValue);
}
else
{
// Section independent
if (pId.section != SectionIndep)
return false;
sensParams.insert(&_colDispersion[0]);
for (unsigned int i = 0; i < _nComp; ++i)
_colDispersion[i].setADValue(adDirection, adValue);
}
return true;
}
/**
* @brief Creates a ConvectionDispersionOperator
*/
ConvectionDispersionOperator::ConvectionDispersionOperator()
{
}
ConvectionDispersionOperator::~ConvectionDispersionOperator() CADET_NOEXCEPT
{
}
/**
* @brief Returns the number of AD directions required for computing the Jacobian
* @details Band compression is used to minimize the amount of AD directions.
* @return Number of required AD directions
*/
int ConvectionDispersionOperator::requiredADdirs() const CADET_NOEXCEPT
{
return _jacC.stride();
}
/**
* @brief Reads parameters and allocates memory
* @details Has to be called once before the operator is used.
* @param [in] unitOpIdx Unit operation id of the owning unit operation model
* @param [in] paramProvider Parameter provider for reading parameters
* @param [out] parameters Map in which local parameters are inserted
* @param [in] nComp Number of components
* @param [in] nCol Number of axial cells
* @return @c true if configuration went fine, @c false otherwise
*/
bool ConvectionDispersionOperator::configureModelDiscretization(IParameterProvider& paramProvider, unsigned int nComp, unsigned int nCol)
{
const bool retVal = _baseOp.configureModelDiscretization(paramProvider, nComp, nCol, nComp);
// Allocate memory
const unsigned int lb = _baseOp.jacobianLowerBandwidth();
const unsigned int ub = _baseOp.jacobianUpperBandwidth();
const unsigned int mb = _baseOp.jacobianDiscretizedBandwidth();
// Allocate matrices such that bandwidths can be switched (backwards flow support)
_jacC.resize(nCol * nComp, lb, ub);
_jacCdisc.resize(nCol * nComp, mb, mb);
_jacCdisc.repartition(lb, ub);
return retVal;
}
/**
* @brief Reads model parameters
* @details Only reads parameters that do not affect model structure (e.g., discretization).
* @param [in] unitOpIdx Unit operation id of the owning unit operation model
* @param [in] paramProvider Parameter provider for reading parameters
* @param [out] parameters Map in which local parameters are inserted
* @return @c true if configuration went fine, @c false otherwise
*/
bool ConvectionDispersionOperator::configure(UnitOpIdx unitOpIdx, IParameterProvider& paramProvider, std::unordered_map<ParameterId, active*>& parameters)
{
return _baseOp.configure(unitOpIdx, paramProvider, parameters);
}
/**
* @brief Notifies the operator that a discontinuous section transition is in progress
* @details In addition to changing flow direction internally, if necessary, the function returns whether
* the flow direction has changed.
* @param [in] t Current time point
* @param [in] secIdx Index of the new section that is about to be integrated
* @param [in,out] adJac Jacobian information for AD (AD vectors for residual and state, direction offset)
* @return @c true if flow direction has changed, otherwise @c false
*/
bool ConvectionDispersionOperator::notifyDiscontinuousSectionTransition(double t, unsigned int secIdx, const AdJacobianParams& adJac)
{
const bool hasChanged = _baseOp.notifyDiscontinuousSectionTransition(t, secIdx);
// Check whether flow direction has changed and we need to update AD vectors
// Exit if we do not need to setup (secIdx == 0) or change (prevU and u differ in sign) matrices
if ((secIdx != 0) && !hasChanged)
return false;
const unsigned int lb = _baseOp.jacobianLowerBandwidth();
const unsigned int ub = _baseOp.jacobianUpperBandwidth();
const double u = static_cast<double>(_baseOp.currentVelocity());
if (u >= 0.0)
{
// Forwards flow
// Repartition column bulk Jacobians
_jacC.repartition(lb, ub);
_jacCdisc.repartition(lb, ub);
}
else
{
// Backwards flow
// Repartition column bulk Jacobians
_jacC.repartition(ub, lb);
_jacCdisc.repartition(ub, lb);
}
// Update AD seed vectors since Jacobian structure has changed (bulk block bandwidths)
prepareADvectors(adJac);
return true;
}
/**
* @brief Sets the AD seed vectors for the bulk transport variables
* @param [in,out] adJac Jacobian information for AD (AD vectors for residual and state, direction offset)
*/
void ConvectionDispersionOperator::prepareADvectors(const AdJacobianParams& adJac) const
{
// Early out if AD is disabled
if (!adJac.adY)
return;
// Get bandwidths of blocks
const unsigned int lowerColBandwidth = _jacC.lowerBandwidth();
const unsigned int upperColBandwidth = _jacC.upperBandwidth();
// Column block
ad::prepareAdVectorSeedsForBandMatrix(adJac.adY + offsetC(), adJac.adDirOffset, _baseOp.nComp() * _baseOp.nCol(), lowerColBandwidth, upperColBandwidth, lowerColBandwidth);
}
/**
* @brief Sets the flow rates for the current time section
* @details The flow rates may change due to valve switches.
* @param [in] in Total volumetric inlet flow rate
* @param [in] out Total volumetric outlet flow rate
* @param [in] colPorosity Porosity used for computing interstitial velocity from volumetric flow rate
*/
void ConvectionDispersionOperator::setFlowRates(const active& in, const active& out, const active& colPorosity) CADET_NOEXCEPT
{
_baseOp.setFlowRates(in, out, colPorosity);
}
/**
* @brief Computes the residual of the transport equations
* @param [in] t Current time point
* @param [in] secIdx Index of the current section
* @param [in] y Pointer to unit operation's state vector
* @param [in] yDot Pointer to unit operation's time derivative state vector
* @param [out] res Pointer to unit operation's residual vector
* @param [in] wantJac Determines whether analytic Jacobian is computed
* @return @c 0 on success, @c -1 on non-recoverable error, and @c +1 on recoverable error
*/
int ConvectionDispersionOperator::residual(double t, unsigned int secIdx, double const* y, double const* yDot, double* res, bool wantJac, WithoutParamSensitivity)
{
if (wantJac)
return _baseOp.residual(t, secIdx, y, yDot, res, _jacC);
else
return _baseOp.residual(t, secIdx, y, yDot, res, WithoutParamSensitivity());
}
int ConvectionDispersionOperator::residual(double t, unsigned int secIdx, active const* y, double const* yDot, active* res, bool wantJac, WithoutParamSensitivity)
{
return _baseOp.residual(t, secIdx, y, yDot, res, WithoutParamSensitivity());
}
int ConvectionDispersionOperator::residual(double t, unsigned int secIdx, active const* y, double const* yDot, active* res, bool wantJac, WithParamSensitivity)
{
return _baseOp.residual(t, secIdx, y, yDot, res, WithParamSensitivity());
}
int ConvectionDispersionOperator::residual(double t, unsigned int secIdx, double const* y, double const* yDot, active* res, bool wantJac, WithParamSensitivity)
{
if (wantJac)
return _baseOp.residual(t, secIdx, y, yDot, res, _jacC);
else
return _baseOp.residual(t, secIdx, y, yDot, res, WithParamSensitivity());
}
/**
* @brief Multiplies the time derivative Jacobian @f$ \frac{\partial F}{\partial \dot{y}}\left(t, y, \dot{y}\right) @f$ with a given vector
* @details The operation @f$ z = \frac{\partial F}{\partial \dot{y}} x @f$ is performed.
* The matrix-vector multiplication is performed matrix-free (i.e., no matrix is explicitly formed).
*
* Note that this function only performs multiplication with the Jacobian of the (axial) transport equations.
* The input vectors are assumed to point to the beginning (including inlet DOFs) of the respective unit operation's arrays.
* @param [in] simTime Simulation time information (time point, section index, pre-factor of time derivatives)
* @param [in] sDot Vector @f$ x @f$ that is transformed by the Jacobian @f$ \frac{\partial F}{\partial \dot{y}} @f$
* @param [out] ret Vector @f$ z @f$ which stores the result of the operation
*/
void ConvectionDispersionOperator::multiplyWithDerivativeJacobian(const SimulationTime& simTime, double const* sDot, double* ret) const
{
_baseOp.multiplyWithDerivativeJacobian(simTime, sDot, ret);
}
/**
* @brief Extracts the system Jacobian from band compressed AD seed vectors
* @details The input vectors are assumed to point to the beginning (including inlet DOFs) of the respective unit operation's arrays.
* @param [in] adRes Residual vector of AD datatypes with band compressed seed vectors
* @param [in] adDirOffset Number of AD directions used for non-Jacobian purposes (e.g., parameter sensitivities)
*/
void ConvectionDispersionOperator::extractJacobianFromAD(active const* const adRes, unsigned int adDirOffset)
{
ad::extractBandedJacobianFromAd(adRes + offsetC(), adDirOffset, _jacC.lowerBandwidth(), _jacC);
}
#ifdef CADET_CHECK_ANALYTIC_JACOBIAN
/**
* @brief Compares the analytical Jacobian with a Jacobian derived by AD
* @details The analytical Jacobian is assumed to be stored in the corresponding band matrices.
* The input vectors are assumed to point to the beginning (including inlet DOFs) of the respective unit operation's arrays.
* @param [in] adRes Residual vector of AD datatypes with band compressed seed vectors
* @param [in] adDirOffset Number of AD directions used for non-Jacobian purposes (e.g., parameter sensitivities)
* @return Maximum elementwise absolute difference between analytic and AD Jacobian
*/
double ConvectionDispersionOperator::checkAnalyticJacobianAgainstAd(active const* const adRes, unsigned int adDirOffset) const
{
// Column
const double maxDiffCol = ad::compareBandedJacobianWithAd(adRes + offsetC(), adDirOffset, _jacC.lowerBandwidth(), _jacC);
LOG(Debug) << "-> Col block diff: " << maxDiffCol;
return maxDiffCol;
}
#endif
/**
* @brief Assembles the axial transport Jacobian @f$ J_0 @f$ of the time-discretized equations
* @details The system \f[ \left( \frac{\partial F}{\partial y} + \alpha \frac{\partial F}{\partial \dot{y}} \right) x = b \f]
* has to be solved. The system Jacobian of the original equations,
* \f[ \frac{\partial F}{\partial y}, \f]
* is already computed (by AD or manually in residualImpl() with @c wantJac = true). This function is responsible
* for adding
* \f[ \alpha \frac{\partial F}{\partial \dot{y}} \f]
* to the system Jacobian, which yields the Jacobian of the time-discretized equations
* \f[ F\left(t, y_0, \sum_{k=0}^N \alpha_k y_k \right) = 0 \f]
* when a BDF method is used. The time integrator needs to solve this equation for @f$ y_0 @f$, which requires
* the solution of the linear system mentioned above (@f$ \alpha_0 = \alpha @f$ given in @p alpha).
*
* @param [in] alpha Value of \f$ \alpha \f$ (arises from BDF time discretization)
*/
void ConvectionDispersionOperator::assembleDiscretizedJacobian(double alpha)
{
// Copy normal matrix over to factorizable matrix
_jacCdisc.copyOver(_jacC);
// Add time derivatives
addTimeDerivativeToJacobian(alpha);
}
/**
* @brief Adds the derivatives with respect to @f$ \dot{y} @f$ of @f$ F(t, y, \dot{y}) @f$ to the Jacobian
* @details This functions computes
* @f[ \begin{align*} \text{_jacCdisc} = \text{_jacCdisc} + \alpha \frac{\partial F}{\partial \dot{y}}. \end{align*} @f]
* The factor @f$ \alpha @f$ is useful when constructing the linear system in the time integration process.
* @param [in] alpha Factor in front of @f$ \frac{\partial F}{\partial \dot{y}} @f$
*/
void ConvectionDispersionOperator::addTimeDerivativeToJacobian(double alpha)
{
_baseOp.addTimeDerivativeToJacobian(alpha, _jacCdisc);
}
/**
* @brief Assembles and factorizes the time discretized Jacobian
* @details See assembleDiscretizedJacobian() for assembly of the time discretized Jacobian.
* @param [in] alpha Factor in front of @f$ \frac{\partial F}{\partial \dot{y}} @f$
* @return @c true if factorization went fine, otherwise @c false
*/
bool ConvectionDispersionOperator::assembleAndFactorizeDiscretizedJacobian(double alpha)
{
assembleDiscretizedJacobian(alpha);
return _jacCdisc.factorize();
}
/**
* @brief Solves a (previously factorized) equation system
* @details The (time discretized) Jacobian matrix has to be factorized before calling this function.
* Note that the given right hand side vector @p rhs is not shifted by the inlet DOFs. That
* is, it is assumed to point directly to the first axial DOF.
*
* @param [in,out] rhs On entry, right hand side of the equation system. On exit, solution of the system.
* @return @c true if the system was solved correctly, otherwise @c false
*/
bool ConvectionDispersionOperator::solveDiscretizedJacobian(double* rhs) const
{
return _jacCdisc.solve(rhs);
}
/**
* @brief Solves a system with the time derivative Jacobian and given right hand side
* @details Note that the given right hand side vector @p rhs is not shifted by the inlet DOFs. That
* is, it is assumed to point directly to the first axial DOF.
* @param [in] simTime Simulation time information (time point, section index, pre-factor of time derivatives)
* @param [in,out] rhs On entry, right hand side. On exit, solution of the system.
* @return @c true if the system was solved correctly, @c false otherwise
*/
bool ConvectionDispersionOperator::solveTimeDerivativeSystem(const SimulationTime& simTime, double* const rhs)
{
// Assemble
_jacCdisc.setAll(0.0);
addTimeDerivativeToJacobian(1.0);
// Factorize
const bool result = _jacCdisc.factorize();
if (!result)
{
LOG(Error) << "Factorize() failed for bulk block";
return false;
}
// Solve
const bool result2 = _jacCdisc.solve(rhs);
if (!result2)
{
LOG(Error) << "Solve() failed for bulk block";
return false;
}
return true;
}
} // namespace parts
} // namespace model
} // namespace cadet