proteus 1.9.1
C/C++/Fortran libraries
Loading...
Searching...
No Matches
TADR.h
Go to the documentation of this file.
1#ifndef TADR_H
2#define TADR_H
3#include <cmath>
4#include <cstdlib>
5#include <iomanip>
6#include <iostream>
7#include <valarray>
8#include <vector>
9#include "CompKernel.h"
10#include "ModelFactory.h"
11#include "ArgumentsDict.h"
12#include "xtensor-python/pyarray.hpp"
13#define nnz nSpace
14
15namespace py = pybind11;
16
17#define POWER_SMOOTHNESS_INDICATOR 2
18#define IS_BETAij_ONE 0
19
20// Cell based methods:
21// * Galerkin (unstabilized)
22// * VMS(SUPG) with BDF1 or BDF2 time integration
23// * Explicit Taylor Galerkin with EV stabilization
24// Edge based methods.
25// Low order via D. Kuzmin's
26// High order methods: Smoothness indicator with MC, EV commutator with MC, D.K with ML
27// Zalesak's FCT
28
29namespace proteus
30{
31 // ImplicitEV=5: backward-Euler implicit edge-based scheme (low-order graph
32 // dissipation, no FCT) modeled on Richards STABILIZATION_TYPE==2. Unlike the
33 // explicit edge-based types (2,3,4) the advection/diffusion are evaluated at
34 // the current Newton iterate and contribute to the Jacobian, so it is NOT
35 // CFL-limited. The Jacobian is assembled in calculateJacobian (a separate
36 // function), NOT inside calculateResidual as Richards does.
37 // Compatible=6: implicit transport driven by the flow model's realized exchanges; see
38 // calculateResidual_compatible.
40 enum class ENTROPY : int { POWER=0, LOG=1};
42 // Power entropy //
43 inline double EPOWER(const double& phi, const double& phiL, const double& phiR)
44 {
45 return 1./2.*std::pow(fabs(phi),2.);
46 }
47 inline double DEPOWER(const double& phi, const double& phiL, const double& phiR)
48 {
49 return fabs(phi)*(phi>=0 ? 1 : -1);
50 }
51 // Log entropy // for level set from 0 to 1
52 inline double ELOG(const double& phi, const double& phiL, const double& phiR)
53 {
54 return std::log(fabs((phi-phiL)*(phiR-phi))+1E-14);
55 }
56 inline double DELOG(const double& phi, const double& phiL, const double& phiR)
57 {
58 return (phiL+phiR-2*phi)*((phi-phiL)*(phiR-phi)>=0 ? 1 : -1)/(fabs((phi-phiL)*(phiR-phi))+1E-14);
59 }
60}
61
62namespace proteus
63{
65 {
66 //The base class defining the interface
67 public:
68 std::valarray<double> FluxCorrectionMatrix;
70 // USE_EDGE_VELOCITY: A_ij = int w_j (rho v).grad(w_i) and its transpose A_ji,
71 // assembled from the flow model's edge velocity; edgeFlux = A - A^T
75 // SCHEME B: boundary flux of the FLUID mass, the counterpart of
76 // boundary_integral (which carries the solute). Advective only -- physical
77 // dispersion moves solute relative to the fluid, it does not move fluid.
78 std::valarray<double> boundary_integral_fluid;
79 // FLOW-MODEL FLUXES: per node, the boundary concentration that inflowing
80 // water carries -- the dS-weighted average of this model's Dirichlet value
81 // over the node's Dirichlet faces (cin_den = 0: no Dirichlet face, the water
82 // enters with the node's own c).
83 std::valarray<double> cin_num, cin_den;
84 std::valarray<double> maxVel,maxEntRes;
85 virtual ~TADR_base(){}
86 virtual void calculateResidual(arguments_dict& args)=0;
87 virtual void calculateJacobian(arguments_dict& args)=0;
88 virtual void invert(arguments_dict& args)=0;
89 virtual void FCTStep(arguments_dict& args)=0;
92 virtual void FCTStep_compatible(arguments_dict& args)=0;
93 };
94
95 template<class CompKernelType,
96 int nSpace,
97 int nQuadraturePoints_element,
98 int nDOF_mesh_trial_element,
99 int nDOF_trial_element,
100 int nDOF_test_element,
101 int nQuadraturePoints_elementBoundary>
102 class TADR : public TADR_base
103 {
104 public:
106 CompKernelType ck;
108 nDOF_test_X_trial_element(nDOF_test_element*nDOF_trial_element),
109 ck()
110 {}
111
112
113
114 inline
115 void calculateCFL(const double& elementDiameter,
116 const double df[nSpace],
117 double& cfl)
118 {
119 double h,nrm_v;
120 h = elementDiameter;
121 nrm_v=0.0;
122 for(int I=0;I<nSpace;I++)
123 nrm_v+=df[I]*df[I];
124 nrm_v = sqrt(nrm_v);
125 cfl = nrm_v/h;
126 }
127
128
129
130 inline
131void evaluateCoefficients(const int rowptr[nSpace],
132 const int colind[nnz],
133 const double v[nSpace],
134 const double alpha_L,
135 const double alpha_T,
136 const double Dm,
137 const double thetaW,
138 const double rho_f,
139 const double rho_s,
140 const double& u,
141 double& rho_out,
142 double& m,
143 double& dm,
144 double f[nSpace],
145 double df[nSpace],
146 double a[nnz],
147 double da[nnz])
148 {
149 const double epsilon = (rho_s - rho_f)/rho_f;
150 rho_out = rho_f*(1.0 + epsilon*u);
151 const double drho_du = rho_f*epsilon;
152 const double rho_transport = rho_out;
153 m = thetaW*rho_transport*u;
154 dm = thetaW*(rho_transport + u*drho_du);
155 double v_mag = 0.0;
156 for (int I=0; I<nSpace; I++)
157 v_mag += v[I]*v[I];
158 v_mag = std::sqrt(v_mag);
159 const double v_pore_mag = (thetaW > 1.0e-8) ? v_mag / thetaW : 0.0;
160
161 double alpha_L_eff = alpha_L;
162 double alpha_T_eff = alpha_T;
163 double v_unit[nSpace] = {0.0};
164 if (v_mag > 1.0e-10)
165 for (int I=0; I<nSpace; I++)
166 v_unit[I] = v[I]/v_mag;
167
168 for (int I=0; I < nSpace; I++)
169 {
170 f[I] = rho_transport*v[I]*u;
171 df[I] = (rho_transport + u*drho_du)*v[I];
172 for (int ii = rowptr[I]; ii < rowptr[I + 1]; ii++)
173 {
174 const int J = colind[ii];
175 const double deltaIJ = (I == J) ? 1.0 : 0.0;
176 const double dispersion_tensor =
177 Dm*deltaIJ +
178 alpha_L_eff*v_unit[I]*v_unit[J]*v_pore_mag +
179 alpha_T_eff*v_pore_mag*(deltaIJ - v_unit[I]*v_unit[J]);
180 a[ii] = thetaW*rho_transport*dispersion_tensor;
181 da[ii] = thetaW*drho_du*dispersion_tensor;
182 }
183
184 }
185 }
186inline
187double inversevaluateCoefficients(const double storage,
188 const double porosity,
189 const double rho_f,
190 const double rho_s)
191 {
192 const double mass_scale = std::max(porosity*rho_f, 1.0e-14);
193 const double epsilon = (rho_s - rho_f)/rho_f;
194 const double rhs = storage/mass_scale;
195 if (std::fabs(epsilon) < 1.0e-14)
196 return rhs;
197 const double discriminant = std::max(1.0 + 4.0*epsilon*rhs, 0.0);
198 const double sqrt_discriminant = std::sqrt(discriminant);
199 if (epsilon > 0.0)
200 return 2.0*rhs/(1.0 + sqrt_discriminant);
201 return (-1.0 + sqrt_discriminant)/(2.0*epsilon);
202 }
203
204inline
206 int* colind,
207 const int& isDOFBoundary,
208 const int& isDiffusiveFluxBoundary,
209 const double n[nSpace],
210 double* bc_a,
211 const double& bc_u,
212 const double& bc_flux,
213 double* a,
214 const double grad_potential[nSpace],
215 const double& u,
216 const double& penalty,
217 double& flux)
218 {
219 double diffusiveVelocityComponent_I;
220 double penaltyFlux;
221 double max_a;
222 if (isDiffusiveFluxBoundary == 1)
223 {
224 flux = bc_flux;
225 }
226 else if (isDOFBoundary == 1)
227 {
228 flux = 0.0;
229 max_a = 0.0;
230 for (int I = 0; I < nSpace; I++)
231 {
232 diffusiveVelocityComponent_I = 0.0;
233 for (int m = rowptr[I]; m < rowptr[I+1]; m++)
234 {
235 diffusiveVelocityComponent_I -= a[m] * grad_potential[colind[m]];
236 max_a = fmax(max_a, a[m]);
237 }
238 flux += diffusiveVelocityComponent_I * n[I];
239 }
240 penaltyFlux = max_a * penalty * (u - bc_u);
241 flux += penaltyFlux;
242 }
243 else
244 {
245 //std::cerr << "warning, diffusion term with no boundary condition set, setting diffusive flux to 0.0" << std::endl;
246 flux = 0.0;
247 }
248 }
249
250 inline
252 int* colind,
253 const int& isDOFBoundary,
254 const int& isDiffusiveFluxBoundary,
255 const double n[nSpace],
256 double* a,
257 const double& v,
258 const double grad_v[nSpace],
259 const double& penalty)
260 {
261 double dvel_I;
262 double tmp = 0.0;
263 double max_a = 0.0;
264 if ((isDiffusiveFluxBoundary == 0) && (isDOFBoundary == 1))
265 {
266 for (int I = 0; I < nSpace; I++)
267 {
268 dvel_I = 0.0;
269 for (int m = rowptr[I]; m < rowptr[I + 1]; m++)
270 {
271 dvel_I -= a[m] * grad_v[colind[m]];
272 max_a = fmax(max_a, a[m]);
273 }
274 tmp += dvel_I * n[I];
275 }
276 tmp += max_a * penalty * v;
277 }
278 return tmp;
279 }
280
281 inline
282 void calculateSubgridError_tau(const double& elementDiameter,
283 const double& dmt,
284 const double df[nSpace],
285 double& cfl,
286 double& tau)
287 {
288 //regular elements
289 double h,nrm_v,oneByAbsdt;
290 h = elementDiameter;
291 nrm_v=0.0;
292 for(int I=0;I<nSpace;I++)
293 nrm_v+=df[I]*df[I];
294 nrm_v = sqrt(nrm_v);
295 cfl = nrm_v/h;
296 oneByAbsdt = fabs(dmt);
297 tau = 1.0/(2.0*nrm_v/h + oneByAbsdt + 1.0e-8);
298 }
299
300 inline
301 void calculateSubgridError_tau(const double& Ct_sge,
302 const double G[nSpace*nSpace],
303 const double& A0,
304 const double Ai[nSpace],
305 double& tau_v,
306 double& cfl)
307 {
308 //metric-based tau for arbitrarily shaped elements
309 double v_d_Gv=0.0;
310 for(int I=0;I<nSpace;I++)
311 {for (int J=0;J<nSpace;J++)
312 v_d_Gv += Ai[I]*G[I*nSpace+J]*Ai[J];
313 v_d_Gv += Ai[I]*G[I*nSpace+I];
314 for(int J=0;J<nSpace;J++)
315 {
316 if(J!=I)
317 v_d_Gv += 2.0*Ai[I]*G[I*nSpace+J];
318 }
319 }
320 tau_v = 1.0/sqrt(Ct_sge*A0*A0 + v_d_Gv + 1.0e-8);
321 }
322
323 inline
324 void calculateNumericalDiffusion(const double& shockCapturingDiffusion,
325 const double& elementDiameter,
326 const double& strong_residual,
327 const double grad_u[nSpace],
328 double& numDiff)
329 {
330 double h,
331 num,
332 den,
333 n_grad_u;
334 h = elementDiameter;
335 n_grad_u = 0.0;
336 for (int I=0;I<nSpace;I++)
337 n_grad_u += grad_u[I]*grad_u[I];
338 num = shockCapturingDiffusion*0.5*h*fabs(strong_residual);
339 den = sqrt(n_grad_u) + 1.0e-8;
340 numDiff = num/den;
341 }
342
343 inline
344 void exteriorNumericalAdvectiveFlux(const int& isDOFBoundary_u,
345 const int& isFluxBoundary_u,
346 const int& forceStrongConditions,
347 const double n[nSpace],
348 const double& bc_flux_u,
349 const double f[nSpace],
350 const double bc_f[nSpace],
351 const double velocity[nSpace],
352 double& flux)
353 {
354
355 double flow=0.0;
356 for (int I=0; I < nSpace; I++)
357 flow += n[I]*velocity[I];
358
359 if (isDOFBoundary_u == 1)
360 {
361 flux = 0.0;
362 if (forceStrongConditions == 1)
363 for (int I=0; I < nSpace; I++) flux += n[I]*bc_f[I];
364 else if (flow >= 0.0)
365 for (int I=0; I < nSpace; I++) flux += n[I]*f[I];
366 else
367 for (int I=0; I < nSpace; I++) flux += n[I]*bc_f[I];
368 }
369 else if (isFluxBoundary_u == 1)
370 {
371 flux = bc_flux_u;
372 }
373 else
374 {
375 flux = 0.0;
376 if (flow >= 0.0)
377 for (int I=0; I < nSpace; I++) flux += n[I]*f[I];
378 // else: open boundary with inflow, no external trace — flux = 0
379 }
380 }
381
382 inline
383 void exteriorNumericalAdvectiveFluxDerivative(const int& isDOFBoundary_u,
384 const int& isFluxBoundary_u,
385 const int& forceStrongConditions,
386 const double n[nSpace],
387 const double velocity[nSpace],
388 double& dflux)
389 {
390 double flow=0.0;
391 for (int I=0; I < nSpace; I++)
392 flow += n[I]*velocity[I];
393
394 dflux=0.0;//default to no flux
395 if (isDOFBoundary_u == 1)
396 {
397 if (forceStrongConditions == 1)
398 {
399 dflux = 0.0;
400 }
401 else if (flow >= 0.0)
402 {
403 dflux = flow;
404 }
405 else
406 {
407 dflux = 0.0;
408 }
409 }
410 else if (isFluxBoundary_u == 1)
411 {
412 dflux = 0.0;
413 }
414 else
415 {
416 if (flow >= 0.0)
417 {
418 dflux = flow;
419 }
420 }
421 }
422inline
423
424 void exteriorNumericalDiffusiveFluxDerivative(const int& isDOFBoundary,
425 const int& isDiffusiveFluxBoundary,
426 const int rowptr[nSpace],
427 const int colind[nnz],
428 const double n[nSpace],
429 const double a[nnz],
430 const double da[nnz],
431 const double grad_psi[nSpace],
432 const double grad_v[nSpace],
433 const double& v,
434 const double penalty,
435 double& fluxJacobian)
436{
437 if (isDiffusiveFluxBoundary == 0 && isDOFBoundary == 1)
438 {
439 fluxJacobian = 0.0;
440 double max_a = 0.0;
441 for (int I = 0; I < nSpace; I++) {
442 for(int m=rowptr[I]; m<rowptr[I+1]; m++)
443 {
444 max_a = fmax(max_a, a[m]);
445 fluxJacobian -= (a[m] * grad_v[colind[m]] + da[m] * v * grad_psi[colind[m]]) * n[I];
446 }
447 fluxJacobian += max_a * penalty * v;
448 }
449 }
450 else
451 {
452 fluxJacobian = 0.0;
453 }
454}
455
456
458 {
459 double dt = args.scalar<double>("dt");
460 xt::pyarray<double>& mesh_trial_ref = args.array<double>("mesh_trial_ref");
461 xt::pyarray<double>& mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
462 xt::pyarray<double>& mesh_dof = args.array<double>("mesh_dof");
463 xt::pyarray<double>& mesh_velocity_dof = args.array<double>("mesh_velocity_dof");
464 double MOVING_DOMAIN = args.scalar<double>("MOVING_DOMAIN");
465 xt::pyarray<int>& mesh_l2g = args.array<int>("mesh_l2g");
466 xt::pyarray<double>& dV_ref = args.array<double>("dV_ref");
467 xt::pyarray<double>& u_trial_ref = args.array<double>("u_trial_ref");
468 xt::pyarray<double>& u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
469 xt::pyarray<double>& u_test_ref = args.array<double>("u_test_ref");
470 xt::pyarray<double>& u_grad_test_ref = args.array<double>("u_grad_test_ref");
471 xt::pyarray<double>& mesh_trial_trace_ref = args.array<double>("mesh_trial_trace_ref");
472 xt::pyarray<double>& mesh_grad_trial_trace_ref = args.array<double>("mesh_grad_trial_trace_ref");
473 xt::pyarray<double>& dS_ref = args.array<double>("dS_ref");
474 xt::pyarray<double>& u_trial_trace_ref = args.array<double>("u_trial_trace_ref");
475 xt::pyarray<double>& u_grad_trial_trace_ref = args.array<double>("u_grad_trial_trace_ref");
476 xt::pyarray<double>& u_test_trace_ref = args.array<double>("u_test_trace_ref");
477 xt::pyarray<double>& u_grad_test_trace_ref = args.array<double>("u_grad_test_trace_ref");
478 xt::pyarray<double>& normal_ref = args.array<double>("normal_ref");
479 xt::pyarray<double>& boundaryJac_ref = args.array<double>("boundaryJac_ref");
480 int nElements_global = args.scalar<int>("nElements_global");
481 double useMetrics = args.scalar<double>("useMetrics");
482 double alphaBDF = args.scalar<double>("alphaBDF");
483 int lag_shockCapturing = args.scalar<int>("lag_shockCapturing");
484 double shockCapturingDiffusion = args.scalar<double>("shockCapturingDiffusion");
485 double sc_uref = args.scalar<double>("sc_uref");
486 double sc_alpha = args.scalar<double>("sc_alpha");
487 xt::pyarray<int>& u_l2g = args.array<int>("u_l2g");
488 xt::pyarray<int>& r_l2g = args.array<int>("r_l2g");
489 xt::pyarray<double>& elementDiameter = args.array<double>("elementDiameter");
490 double degree_polynomial = args.scalar<double>("degree_polynomial");
491 xt::pyarray<double>& u_dof = args.array<double>("u_dof");
492 xt::pyarray<double>& u_dof_old = args.array<double>("u_dof_old");
493 xt::pyarray<double>& velocity = args.array<double>("velocity");
494 xt::pyarray<double>& velocity_old = args.array<double>("velocity_old");
495 xt::pyarray<double>& q_m = args.array<double>("q_m");
496 xt::pyarray<double>& q_u = args.array<double>("q_u");
497 xt::pyarray<double>& q_porosity = args.array<double>("q_porosity");
498 xt::pyarray<double>& q_porosity_old = args.array<double>("q_porosity_old");
499 xt::pyarray<double>& q_rho = args.array<double>("q_rho");
500 xt::pyarray<double>& q_rho_old = args.array<double>("q_rho_old");
501 // OUT: viscosity ratio mu/mu_0 at the quadrature points, for the flow model,
502 // exported the same way as q_rho. omega_max maps u to the solute mass
503 // fraction omega = omega_max*u; 0 gives mu/mu_0 = 1 exactly.
504 xt::pyarray<double>& q_mu = args.array<double>("q_mu");
505 const double omega_max = args.scalar<double>("omega_max");
506
507 xt::pyarray<double>& q_r = args.array<double>("q_r");
508 const double alpha_L = args.scalar<double>("alpha_L");
509 const double alpha_T = args.scalar<double>("alpha_T");
510 const double Dm = args.scalar<double>("Dm");
511 // const int dispersion_type_int = args.scalar<int>("dispersion_type");
512 // const double theta_s = args.scalar<double>("theta_s");
513 // const double theta_r = args.scalar<double>("theta_r");
514 // const double power_law_exponent = args.scalar<double>("power_law_exponent");
515 // const double velocity_exponent = args.scalar<double>("velocity_exponent");
516 const double rho_f = args.scalar<double>("rho_f");
517 const double rho_s = args.scalar<double>("rho_s");
518 int forceStrongConditions = args.scalar<int>("forceStrongConditions");
519 // DISPERSION DISPERSION_TYPE = static_cast<DISPERSION>(dispersion_type_int);
520 xt::pyarray<double>& q_m_betaBDF = args.array<double>("q_m_betaBDF");
521 xt::pyarray<double>& q_dV = args.array<double>("q_dV");
522 xt::pyarray<double>& q_dV_last = args.array<double>("q_dV_last");
523 xt::pyarray<double>& cfl = args.array<double>("cfl");
524 xt::pyarray<double>& edge_based_cfl = args.array<double>("edge_based_cfl");
525 xt::pyarray<double>& q_numDiff_u = args.array<double>("q_numDiff_u");
526 xt::pyarray<double>& q_numDiff_u_last = args.array<double>("q_numDiff_u_last");
527 int offset_u = args.scalar<int>("offset_u");
528 int stride_u = args.scalar<int>("stride_u");
529 xt::pyarray<double>& globalResidual = args.array<double>("globalResidual");
530 int nExteriorElementBoundaries_global = args.scalar<int>("nExteriorElementBoundaries_global");
531 xt::pyarray<int>& exteriorElementBoundariesArray = args.array<int>("exteriorElementBoundariesArray");
532 xt::pyarray<int>& elementBoundaryMaterialTypes = args.array<int>("elementBoundaryMaterialTypes");
533 xt::pyarray<int>& isExteriorBoundaryPhysical = args.array<int>("isExteriorBoundaryPhysical");
534 xt::pyarray<int>& elementBoundaryElementsArray = args.array<int>("elementBoundaryElementsArray");
535 xt::pyarray<int>& elementBoundaryLocalElementBoundariesArray = args.array<int>("elementBoundaryLocalElementBoundariesArray");
536 xt::pyarray<double>& ebqe_velocity_ext = args.array<double>("ebqe_velocity_ext");
537 xt::pyarray<int>& isDOFBoundary_u = args.array<int>("isDOFBoundary_u");
538 xt::pyarray<double>& ebqe_bc_u_ext = args.array<double>("ebqe_bc_u_ext");
539 xt::pyarray<int>& isFluxBoundary_u = args.array<int>("isFluxBoundary_u");
540 xt::pyarray<double>& ebqe_bc_flux_u_ext = args.array<double>("ebqe_bc_flux_u_ext");
541 xt::pyarray<double>& ebqe_bc_diffusiveFlux_u_ext = args.array<double>("ebqe_bc_diffusiveFlux_u_ext");
542 xt::pyarray<double>& ebqe_porosity = args.array<double>("ebqe_porosity");
543 xt::pyarray<double>& ebqe_rho = args.array<double>("ebqe_rho");
544 xt::pyarray<double>& ebqe_mu = args.array<double>("ebqe_mu");
545
546 double epsFact = args.scalar<double>("epsFact");
547 xt::pyarray<double>& ebqe_u = args.array<double>("ebqe_u");
548 xt::pyarray<double>& ebqe_flux = args.array<double>("ebqe_flux");
549 // BOUNDARY-FLUX DIAGNOSTIC. ebqe_flux is the SUM of the advective and
550 // dispersive solute fluxes, which is the one number that cannot answer
551 // "does solute reach this part of the boundary by being carried there, or
552 // only by spreading?". Splitting them is what distinguishes a stagnant
553 // Dirichlet strip (advection ~ 0, dispersion only) from a live one.
554 // ebqe_dS is the quadrature weight, so Python can integrate rather than
555 // sum bare quadrature values. See TADR_BC_DBG in TADR.py.
556 xt::pyarray<double>& ebqe_flux_adv = args.array<double>("ebqe_flux_adv");
557 xt::pyarray<double>& ebqe_dS_ext = args.array<double>("ebqe_dS_ext");
558 int stage = args.scalar<int>("stage");
559 xt::pyarray<double>& uTilde_dof = args.array<double>("uTilde_dof");
560 double cE = args.scalar<double>("cE");
561 double cMax = args.scalar<double>("cMax");
562 double cK = args.scalar<double>("cK");
563 double uL = args.scalar<double>("uL");
564 double uR = args.scalar<double>("uR");
565 int numDOFs = args.scalar<int>("numDOFs");
566 int NNZ = args.scalar<int>("NNZ");
567 xt::pyarray<int>& csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
568 xt::pyarray<int>& csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
569 xt::pyarray<int>& csrRowIndeces_CellLoops = args.array<int>("csrRowIndeces_CellLoops");
570 xt::pyarray<int>& csrColumnOffsets_CellLoops = args.array<int>("csrColumnOffsets_CellLoops");
571 xt::pyarray<int>& csrColumnOffsets_eb_CellLoops = args.array<int>("csrColumnOffsets_eb_CellLoops");
572 xt::pyarray<double>& ML = args.array<double>("ML");
573 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
574 STABILIZATION STABILIZATION_TYPE = static_cast<STABILIZATION>(args.scalar<int>("STABILIZATION_TYPE"));
575 ENTROPY ENTROPY_TYPE = static_cast<ENTROPY>(args.scalar<int>("ENTROPY_TYPE"));
576 //STABILIZATION STABILIZATION_TYPE{args.scalar<int>("STABILIZATION_TYPE")};
577 //ENTROPY ENTROPY_TYPE{args.scalar<int>("ENTROPY_TYPE")};
578 xt::pyarray<double>& uLow = args.array<double>("uLow");
580 // SCHEME B -- the concentration is the RATIO of two masses. //
581 // //
582 // M_dof[i] = (theta*rho)_i is the FLUID mass and m_dof[i] //
583 // = M_dof[i]*u_i the SOLUTE mass, and u = m/M. The identity //
584 // m^L_i - u^n_i M^L_i = dt/ML_i sum_{j!=i} gamma_ij (M_j/theta_j) //
585 // * (u_j - u_i) //
586 // (gamma_ij = d_ij - K_ij >= 0) makes u^L a convex combination of //
587 // {u^n_i, u^n_j} for ANY velocity, divergent or not. //
588 // //
589 // Where M comes from differs by branch, and so does what is //
590 // conserved: //
591 // * EXPLICIT edge-based (STAB 2/3/4): M is CARRIED here and //
592 // advected with EXACTLY the same operator (same K, same graph //
593 // viscosity d) as the solute mass. sum_i ML_i m_i is then //
594 // conserved to round-off, because the operator itself is //
595 // untouched (column sums of K vanish, d is symmetric). //
596 // * ImplicitEV (STAB 5), OPTION C: M is READ FROM RICHARDS every //
597 // step. Boundedness is unchanged (any positive M gives an //
598 // M-matrix), but conservation now holds only up to the //
599 // flow/transport continuity defect -- see the option C note in //
600 // the ImplicitEV branch, and the [TADR-MASS] log. //
601 // //
602 // This replaces the row-sum premise entirely. The previous form //
603 // sum_j (T+D)_ij w_j - sum_j d_ij (w_j - w_i) //
604 // is a convex combination only when sum_j (T+D)_ij = 0, i.e. only //
605 // for a discretely divergence-free velocity -- which Elder's //
606 // velocity_couple is NOT, and physically cannot be: with a //
607 // solution-dependent density the fluid mass equation gives //
608 // div v = -(1/rho)[ d_t(theta rho) + v.grad rho ] != 0. //
609 // Measured in the numpy replica (1D periodic, v = v0(1+A sin 2pi x),//
610 // so every defect is interior): at A=1 the old form reaches //
611 // max u = 7.33 from a u <= 1 IC, this one stays in [0, 0.64] with a //
612 // solute-mass drift of 6.7e-16. //
613 // //
614 // KNOWN SECOND-ORDER MODELLING ERROR: the dispersion stiffness sits //
615 // inside TransportMatrix (see the element assembly), so the fluid //
616 // mass picks up a spurious dispersion of size eps_rho*D. Physically//
617 // dispersion moves solute relative to the fluid and should not move //
618 // the fluid at all. Splitting the dispersion into its own matrix //
619 // acting on u (rather than on w) is the clean fix; it is a separate //
620 // restructuring of the element loop and does NOT affect boundedness //
621 // or conservation, both of which hold for the combined operator //
622 // because the SAME K is applied to m and to M. //
624 xt::pyarray<double>& M_dof = args.array<double>("M_dof");
625 xt::pyarray<double>& M_low = args.array<double>("M_low");
626 // CONTINUITY-DEFECT PROBE (option C only): the fluid flux out of node i under
627 // TADR's OWN operator, which the cancelled solute form assumes balances the
628 // fluid storage. Python pairs it with Richards' M^{n+1} to form the defect.
629 xt::pyarray<double>& fluidResidual = args.array<double>("fluidResidual");
630 // OUT (ImplicitEV only): rho(c_i) at the current iterate, for the flow
631 // model's nodal density. invert() overwrites it with rho of the limited c.
632 xt::pyarray<double>& rho_nodal = args.array<double>("rho_nodal");
633 // FLOW-MODEL FLUXES (ImplicitEV, USE_EDGE_FLUX=1): the water the flow model
634 // actually moved in this step, as rates. edgeFlux[ij] is the mass flux into
635 // row i from column j (antisymmetric), nodalBoundaryFlux[i] the rest of
636 // node i's storage change (boundary exchange + the flow model's Newton
637 // residual). They REPLACE this model's own advection operator, so the fluid
638 // balance the cancelled form assumes is the flow model's, exactly.
639 xt::pyarray<double>& edgeFlux = args.array<double>("edgeFlux");
640 xt::pyarray<double>& nodalBoundaryFlux = args.array<double>("nodalBoundaryFlux");
641 const int USE_EDGE_FLUX = args.scalar<int>("USE_EDGE_FLUX");
642 // EDGE VELOCITY (USE_EDGE_FLUX=1 only): edgeFlux is not read but WRITTEN here,
643 // F_ij = A_ij - A_ji with A_ij = int w_j (rho v).grad(w_i), v the flow model's
644 // edge velocity (q_v) and rho = q_rho_flow, the density that velocity was
645 // divided by. sum_j A_ji = 0, so sum_j F_ij = int rho v.grad(w_i), which the
646 // flow model built to equal its realized edge-flux row sum. The symmetric
647 // part of A is fluid storage, supplied by the carried M instead.
648 // nodalBoundaryFlux is written too: B_i = ML_i (M_low_i - M_dof_i)/dt - sum_j F_ij.
649 const int USE_EDGE_VELOCITY = args.scalar<int>("USE_EDGE_VELOCITY");
650 xt::pyarray<double>& q_rho_flow = args.array<double>("q_rho_flow");
651 // IN (USE_EDGE_FLUX only): nodal source of the CANCELLED form [mass/(volume
652 // time)], added to row i as ML_i*nodalSource_i (lumped). For a conservative
653 // solute source f_s this is f_s - c*f_w: the flow model's water source f_w
654 // reaches this model through B_i with the node's own c and cancels. Zero
655 // unless the deck passes Coefficients(mms_source=...).
656 xt::pyarray<double>& nodalSource = args.array<double>("nodalSource");
657 // Richards' NODAL theta(psi^n). Zero => no flow model. Under ImplicitEV
658 // it no longer recovers rho from M_dof: M_dof is Richards' old-time mass
659 // theta(psi^n)*rho(c^{n-1}) (the mass its previous step produced), not
660 // theta*rho(c^n).
661 xt::pyarray<double>& theta_nodal = args.array<double>("theta_nodal");
662 const int init_M_dof = args.scalar<int>("init_M_dof");
663 // OPTION C: for ImplicitEV, M_dof is Richards' old-time mass, refreshed on
664 // the Python side before this kernel runs. It is the old-time storage
665 // coefficient ONLY; the flux density is rho(c^n) from the EOS at the node
666 // (rho_dof_proj), the same nodal density Richards advects with. There is
667 // no separate M^{n+1} array and no fluid linear system to assemble. M_low is written only by the
668 // explicit edge-based branches, which still advect their own copy.
670 // OPTION C -- why there is no fluid-mass Dirichlet set here. //
671 // //
672 // The fluid mass needs the SAME Dirichlet condition as the //
673 // concentration: rho is a function of u, so where u is strongly //
674 // imposed the density is imposed too and M = theta*rho(u_bc) is the //
675 // only value consistent with the row Python replaces. //
676 // //
677 // Leaving M free there is NOT a small error. The solute flux //
678 // coefficient is gamma_ij*rho_j with rho_j = M_j/theta_j, so an M //
679 // that drifts at a Dirichlet node re-scales every edge leaving that //
680 // node. When M was advected here as its own free unknown, the Elder //
681 // source strip (u pinned to 1, v.n = 0, and the dispersion inside K //
682 // draining M toward the lighter interior with no boundary term to //
683 // hold it) saw M fall to ~4% of theta*rho: the first edge below the //
684 // strip ended up ~25x weaker than the interior edges, the profile //
685 // went 1.000 -> 0.299 -> 0.272 in one cell instead of //
686 // 1.000 -> 0.907 -> 0.836, and the whole benchmark took up 3x too //
687 // little salt (mean u 0.071 vs 0.211 at 20 yr) so convection never //
688 // developed. Invisible in test_tadr (eps_rho = 0 => rho constant //
689 // => M cannot drift) and invisible to the u-bounds, which stayed in //
690 // [0,1] the whole time. //
691 // //
692 // Under option C that whole failure mode is gone by construction: //
693 // ImplicitEV reads M from Richards, which imposes its own flow BCs //
694 // at that strip and whose density is the q_rho this model pushes to //
695 // it -- so M there IS theta*rho(u_bc) without anything pinning it. //
696 // The explicit branches still advect their own M, but they also //
697 // carry the matching fluid boundary flux (boundary_integral_fluid), //
698 // which is what holds it. //
700 xt::pyarray<double>& dLow = args.array<double>("dLow");
701 xt::pyarray<double>& dt_times_dH_minus_dL = args.array<double>("dt_times_dH_minus_dL");
702 xt::pyarray<double>& min_u_bc = args.array<double>("min_u_bc");
703 xt::pyarray<double>& max_u_bc = args.array<double>("max_u_bc");
704 xt::pyarray<double>& quantDOFs = args.array<double>("quantDOFs");
705 // Stage 3 (kinetic dissolution). Adds R_diss = k_d * S_n * S_w *
706 // (c_sat - c) per DOF to the mass update, scaled by theta_w * rho_w
707 // (so it has mass-rate units). When the flow model is single-phase
708 // (Richards), Sn_dof is zeros and R_diss vanishes.
709 xt::pyarray<double>& Sn_dof = args.array<double>("Sn_dof");
710 const double k_d = args.scalar<double>("k_d");
711 const double c_sat = args.scalar<double>("c_sat");
713 xt::pyarray<int>& a_rowptr = args.array<int>("a_rowptr");
714 xt::pyarray<int>& a_colind = args.array<int>("a_colind");
715 //xt::pyarray<double>& D = args.array<double>("D");
716 //initializeDToZero(D);
718 xt::pyarray<int>& isDiffusiveFluxBoundary_u = args.array<int>("isDiffusiveFluxBoundary_u");
719 xt::pyarray<int>& isAdvectiveFluxBoundary_u = args.array<int>("isAdvectiveFluxBoundary_u");
720 xt::pyarray<double>& ebqe_bc_advectiveFlux_u_ext = args.array<double>("ebqe_bc_advectiveFlux_u_ext");
721 xt::pyarray<double>& ebqe_penalty_ext = args.array<double>("ebqe_penalty_ext");
723 double physicalDiffusion = args.scalar<double>("physicalDiffusion");
724 const double eb_adjoint_sigma = args.scalar<double>("eb_adjoint_sigma");
725
726 double meanEntropy = 0., meanOmega = 0., maxEntropy = -1E10, minEntropy = 1E10;
727 const double eps_rho = (rho_s - rho_f)/rho_f;
728 const double zL_mass = uL + eps_rho*uL*uL;
729 const double zR_mass = uR + eps_rho*uR*uR;
730 maxVel.resize(nElements_global, 0.0);
731 maxEntRes.resize(nElements_global, 0.0);
732 double Ct_sge = 4.0;
733 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
734 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
735 STABILIZATION_TYPE==STABILIZATION::Kuzmin or
736 STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
737 {
738 TransportMatrix.resize(NNZ,0.0);
739 DiffusionMatrix.resize(NNZ,0.0);
740 TransposeTransportMatrix.resize(NNZ,0.0);
741 AdvectionMatrix.resize(USE_EDGE_VELOCITY ? NNZ : 0, 0.0);
742 TransposeAdvectionMatrix.resize(USE_EDGE_VELOCITY ? NNZ : 0, 0.0);
743 m_dof.resize(numDOFs,0.0);
744 theta_dof_proj.resize(numDOFs,0.0);
745 rho_dof_proj.resize(numDOFs,0.0);
746 ML_mass_proj.resize(numDOFs,0.0);
747 // ONLY theta is projected from quadrature -- it is a material property
748 // with no nodal value of its own. rho and u are NOT projected: rho is
749 // an explicit function of the nodal u (see the rho_dof_proj assignment
750 // below), and projecting u would apply the (M*u)_i/ML_i smoothing
751 // filter.
752 //
753 // rho MUST be evaluated at the DOF, not projected. The edge-based
754 // scheme recovers the concentration from the stored mass with
755 // ui_mass = inversevaluateCoefficients(m_dof[i], theta_i)
756 // which returns u_dof_old[i] IF AND ONLY IF
757 // rho_dof_proj[i] == rho_f*(1 + eps_rho*u_dof_old[i])
758 // exactly. With a projected (smoothed) rho that identity fails by
759 // O(eps_rho * (rho~ - rho)), so ui_mass != u_dof_old[i] and the whole
760 // edge-based pipeline runs on a field that differs from the one FCT
761 // takes its bounds from (FCTStep reads the true nodal soln=u_dof_old).
762 // Zalesak's precondition m(mini) <= mLow_i <= m(maxi) is then not
763 // guaranteed, and when it fails Rpos clamps to 0 -- which returns
764 // mLow unchanged instead of enforcing the bound.
765 //
766 // It also destroys the steady state: with velocity identically zero
767 // the projected form is NOT a fixed point (numpy replica: 3.1% drift
768 // after one step, 23% after ten). The nodal form is exact.
769 for (int eN=0; eN<nElements_global; eN++)
770 for (int k=0; k<nQuadraturePoints_element; k++)
771 {
772 int eN_k = eN*nQuadraturePoints_element + k,
773 eN_nDOF_trial_element = eN*nDOF_trial_element;
774 double jac[nSpace*nSpace], jacDet, jacInv[nSpace*nSpace], x, y, z, un_k=0.0;
775 ck.calculateMapping_element(eN,
776 k,
777 mesh_dof.data(),
778 mesh_l2g.data(),
779 mesh_trial_ref.data(),
780 mesh_grad_trial_ref.data(),
781 jac,
782 jacDet,
783 jacInv,
784 x,y,z);
785 const double dV = fabs(jacDet)*dV_ref.data()[k];
786 const double theta_k = q_porosity_old.data()[eN_k];
787 (void) un_k;
788 for (int i=0; i<nDOF_test_element; i++)
789 {
790 int eN_i = eN*nDOF_test_element+i;
791 const int gi = u_l2g.data()[eN_i];
792 const double w = u_test_ref.data()[k*nDOF_trial_element+i]*dV;
793 theta_dof_proj[gi] += theta_k*w;
794 ML_mass_proj[gi] += w;
795 }
796 }
797 for (int i=0; i<numDOFs; i++)
798 {
799 if (ML_mass_proj[i] > 1.0e-14)
801 else
802 theta_dof_proj[i] = 1.0;
803 // PREFER THE FLOW MODEL'S NODAL THETA. M_dof_i = theta_i*rho_i was
804 // formed at a DOF, with THAT DOF's soil (freeDOFMaterialTypes); the
805 // quadrature theta above is evaluated per ELEMENT, with the element's
806 // soil, so at a material interface the projection averages two soils
807 // and M_dof/theta is a density Richards never used. (With the vertex
808 // rule the two agree everywhere else, so this only bites interfaces.)
809 // Zero = no flow model: keep the projection.
810 if (theta_nodal.data()[i] > 0.0)
811 theta_dof_proj[i] = theta_nodal.data()[i];
812 // conservative variable at t^n; u AND rho stay nodal, so that
813 // inversevaluateCoefficients(m_dof[i], theta_dof_proj[i]) returns
814 // u_dof_old[i] to round-off (see the note above).
815 const double un_i = u_dof_old.data()[i];
816 // The fluid mass M = theta*rho is NOT re-derived from the EOS
817 // here. init_M_dof=1 only on the first residual call of a deck
818 // with no flow model to read M from (test_tadr), where it is the
819 // one place rho(u) is used for it. Re-seeding M := theta*rho(u)
820 // every step would put the continuity defect back in as a
821 // per-step projection -- measured at -0.98 relative solute mass
822 // over 400 steps in the replica, and -1.1e-2 even at div v == 0.
823 // With a flow model, Python has already put Richards' theta*rho
824 // (ImplicitEV) or the advected value (explicit branches) in
825 // M_dof before this loop runs.
826 if (init_M_dof)
827 M_dof.data()[i] = theta_dof_proj[i]*rho_f*(1.0 + eps_rho*un_i);
828 const double Mi = fmax(M_dof.data()[i], 1.0e-14);
829 // ImplicitEV: rho(c^n) from the EOS at the DOF -- the value Richards'
830 // nodal density is built from (Richards.Coefficients.preStep), so both
831 // models advect with one density. M_dof is storage only here.
832 rho_dof_proj[i] = (STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
833 ? rho_f*(1.0 + eps_rho*un_i)
834 : Mi/theta_dof_proj[i];
835 m_dof[i] = Mi*un_i;
836 }
837 // compute entropy and init global_entropy_residual and boundary_integral
838 psi.resize(numDOFs,0.0);
839 eta.resize(numDOFs,0.0);
840 global_entropy_residual.resize(numDOFs,0.0);
841 boundary_integral.resize(numDOFs,0.0);
842 boundary_integral_fluid.resize(numDOFs,0.0);
844 cin_num.resize(numDOFs,0.0);
845 cin_num = 0.0;
846 cin_den.resize(numDOFs,0.0);
847 cin_den = 0.0;
848 for (int i=0; i<numDOFs; i++)
849 {
850 // NODAL ENTROPY //
851 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) //EV stab
852 {
853 if (ENTROPY_TYPE == ENTROPY::POWER)
854 eta[i] = EPOWER(m_dof[i],uL,uR);
855 else
856 {
857 const double mass_scale_i = fmax(theta_dof_proj[i]*rho_f, 1.0e-14);
858 const double z_i = m_dof[i]/mass_scale_i;
859 eta[i] = ELOG(z_i,zL_mass,zR_mass);
860 }
862 }
863 boundary_integral[i]=0.;
864 }
865 }
866 //
867 //loop over elements to compute volume integrals and load them into element and global residual
868 //
869 //eN is the element index
870 //eN_k is the quadrature point index for a scalar
871 //eN_k_nSpace is the quadrature point index for a vector
872 //eN_i is the element test function index
873 //eN_j is the element trial function index
874 //eN_k_j is the quadrature point index for a trial function
875 //eN_k_i is the quadrature point index for a trial function
876 for(int eN=0;eN<nElements_global;eN++)
877 {
878 //declare local storage for element residual and initialize
879 double
880 elementResidual_u[nDOF_test_element],
881 element_entropy_residual[nDOF_test_element];
882 double elementTransport[nDOF_test_element][nDOF_trial_element];
883 double elementDiffusion[nDOF_test_element][nDOF_trial_element];
884 double elementTransposeTransport[nDOF_test_element][nDOF_trial_element];
885 double elementAdvection[nDOF_test_element][nDOF_trial_element];
886 double elementTransposeAdvection[nDOF_test_element][nDOF_trial_element];
887 for (int i=0;i<nDOF_test_element;i++)
888 {
889 elementResidual_u[i]=0.0;
890 }//i
891 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
892 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
893 STABILIZATION_TYPE==STABILIZATION::Kuzmin or
894 STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
895 {
896 for (int i=0;i<nDOF_test_element;i++)
897 {
898 element_entropy_residual[i]=0.0;
899 for (int j=0;j<nDOF_trial_element;j++)
900 {
901 elementTransport[i][j]=0.0;
902 elementDiffusion[i][j]=0.0;
903 elementTransposeTransport[i][j]=0.0;
904 elementAdvection[i][j]=0.0;
905 elementTransposeAdvection[i][j]=0.0;
906 }
907 }
908 }
909 //loop over quadrature points and compute integrands
910 for (int k=0;k<nQuadraturePoints_element;k++)
911 {
912 //compute indeces and declare local storage
913 int eN_k = eN*nQuadraturePoints_element+k,
914 eN_k_nSpace = eN_k*nSpace,
915 eN_nDOF_trial_element = eN*nDOF_trial_element;
916 //int index_D = eN_k * a_rowptr.data()[nSpace];
917 double
918 entVisc_minus_artComp,
919 u=0.0,un=0.0,
920 grad_u[nSpace],grad_u_old[nSpace],grad_uTilde[nSpace],
921 rho_out=0.0,rho_out_old=0.0,
922 m=0.0,dm=0.0,mn=0.0,dmn=0.0,
923 H=0.0,Hn=0.0,HTilde=0.0,
924 f[nSpace],fn[nSpace],df[nSpace],dfn[nSpace],
926 //a[nSpace], da[nSpace], an[nSpace], dan[nSpace],
927 a[nnz], da[nnz], an[nnz], dan[nnz],
928 m_t=0.0,dm_t=0.0,
929 pdeResidual_u=0.0,
930 Lstar_u[nDOF_test_element],
931 subgridError_u=0.0,
932 tau=0.0,tau0=0.0,tau1=0.0,
933 numDiff0=0.0,numDiff1=0.0,
934 jac[nSpace*nSpace],
935 jacDet,
936 jacInv[nSpace*nSpace],
937 u_grad_trial[nDOF_trial_element*nSpace],
938 u_test_dV[nDOF_trial_element],
939 u_grad_test_dV[nDOF_test_element*nSpace],
940 dV,x,y,z,xt,yt,zt,
941 G[nSpace*nSpace],G_dd_G,tr_G,
942 // for entropy residual
943 aux_entropy_residual=0.0, DENTROPY_un, DENTROPY_uni;//norm_Rv;
944
945 ck.calculateMapping_element(eN,
946 k,
947 mesh_dof.data(),
948 mesh_l2g.data(),
949 mesh_trial_ref.data(),
950 mesh_grad_trial_ref.data(),
951 jac,
952 jacDet,
953 jacInv,
954 x,y,z);
955 ck.calculateMappingVelocity_element(eN,
956 k,
957 mesh_velocity_dof.data(),
958 mesh_l2g.data(),
959 mesh_trial_ref.data(),
960 xt,yt,zt);
961 //get the physical integration weight
962 dV = fabs(jacDet)*dV_ref.data()[k];
963 ck.calculateG(jacInv,G,G_dd_G,tr_G);
964 //get the trial function gradients
965 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k*nDOF_trial_element*nSpace],
966 jacInv,
967 u_grad_trial);
968 //get the solution
969 ck.valFromDOF(u_dof.data(),
970 &u_l2g.data()[eN_nDOF_trial_element],
971 &u_trial_ref.data()[k*nDOF_trial_element],
972 u);
973 ck.valFromDOF(u_dof_old.data(),
974 &u_l2g.data()[eN_nDOF_trial_element],
975 &u_trial_ref.data()[k*nDOF_trial_element],
976 un);
977 //get the solution gradients
978 ck.gradFromDOF(u_dof.data(),
979 &u_l2g.data()[eN_nDOF_trial_element],
980 u_grad_trial,
981 grad_u);
982 ck.gradFromDOF(u_dof_old.data(),
983 &u_l2g.data()[eN_nDOF_trial_element],
984 u_grad_trial,
985 grad_u_old);
986 ck.gradFromDOF(uTilde_dof.data(),
987 &u_l2g.data()[eN_nDOF_trial_element],
988 u_grad_trial,
989 grad_uTilde);
990 //precalculate test function products with integration weights
991 for (int j=0;j<nDOF_trial_element;j++)
992 {
993 u_test_dV[j] = u_test_ref.data()[k*nDOF_trial_element+j]*dV;
994 for (int I=0;I<nSpace;I++)
995 {
996 u_grad_test_dV[j*nSpace+I] = u_grad_trial[j*nSpace+I]*dV;//cek warning won't work for Petrov-Galerkin
997 }
998 }
999
1000 //
1001 //
1002 //calculate pde coefficients at quadrature points
1003
1004 evaluateCoefficients(a_rowptr.data(),
1005 a_colind.data(),
1006 &velocity.data()[eN_k_nSpace],
1007 alpha_L,
1008 alpha_T,
1009 Dm,
1010 q_porosity.data()[eN*nQuadraturePoints_element+k],
1011 rho_f,
1012 rho_s,
1013 u,
1014 rho_out,
1015 m,
1016 dm,
1017 f,
1018 df,
1019 a,
1020 da);
1021 q_rho.data()[eN_k] = rho_out;
1022 // mu/mu_0 = 1 + 1.85 w - 4.1 w^2 + 44.5 w^3, Eq. (9) of Guevara
1023 // Morel and Graf (2023) after Holzbecher (1998), w = omega_max*u
1024 const double omega_k = omega_max*u;
1025 q_mu.data()[eN_k] = 1.0 + omega_k*(1.85 + omega_k*(-4.1 + omega_k*44.5));
1026
1027 evaluateCoefficients(a_rowptr.data(),
1028 a_colind.data(),
1029 &velocity_old.data()[eN_k_nSpace],
1030 alpha_L,
1031 alpha_T,
1032 Dm,
1033 q_porosity_old.data()[eN*nQuadraturePoints_element+k],
1034 rho_f,
1035 rho_s,
1036 un,
1037 rho_out_old,
1038 mn,
1039 dmn,
1040 fn,
1041 dfn,
1042 an,
1043 dan);
1044 //an= &q_a.data()[eN_k * sd_rowptr.data()[nSpace]];
1045
1046 //
1047 //moving mesh
1048 //
1049 double mesh_velocity[3];
1050 mesh_velocity[0] = xt;
1051 mesh_velocity[1] = yt;
1052 mesh_velocity[2] = zt;
1053
1054 for (int I=0;I<nSpace;I++)
1055 {
1056 f[I] -= MOVING_DOMAIN*m*mesh_velocity[I];
1057 df[I] -= MOVING_DOMAIN*dm*mesh_velocity[I];
1058 fn[I] -= MOVING_DOMAIN*mn*mesh_velocity[I];
1059 dfn[I] -= MOVING_DOMAIN*dmn*mesh_velocity[I];
1060 }
1061 //
1062 //calculate time derivative at quadrature points
1063 //
1064 if (q_dV_last.data()[eN_k] <= -100)
1065 q_dV_last.data()[eN_k] = dV;
1066 q_dV.data()[eN_k] = dV;
1067 ck.bdf(alphaBDF,
1068 q_m_betaBDF.data()[eN_k]*q_dV_last.data()[eN_k]/dV,//ensure prior mass integral is correct for m_t with BDF1
1069 m,
1070 dm,
1071 m_t,
1072 dm_t);
1073
1074 const double thetaW_k = std::max(q_porosity_old.data()[eN_k], 1.0e-8);
1075 double dfn_pore[nSpace];
1076 for (int I=0; I<nSpace; I++) dfn_pore[I] = dfn[I] / thetaW_k;
1077
1078 if (STABILIZATION_TYPE==STABILIZATION::TaylorGalerkinEV)
1079 {
1080 double normVel=0., norm_grad_un=0.;
1081 for (int I=0;I<nSpace;I++)
1082 {
1083 Hn += dfn[I]*grad_u_old[I];
1084 HTilde += dfn[I]*grad_uTilde[I];
1085 fn[I] = dfn[I]*un-MOVING_DOMAIN*m*mesh_velocity[I];//cek check this for moving domain
1086 H += dfn[I]*grad_u[I];
1087 normVel += dfn[I]*df[I];
1088 norm_grad_un += grad_u_old[I]*grad_u_old[I];
1089 }
1090 normVel = std::sqrt(normVel);
1091 norm_grad_un = std::sqrt(norm_grad_un)+1E-10;
1092
1093 // calculate CFL
1094 calculateCFL(elementDiameter.data()[eN]/degree_polynomial,dfn_pore,cfl.data()[eN_k]);
1095
1096
1097 // compute max velocity at cell
1098 maxVel[eN] = fmax(normVel,maxVel[eN]);
1099
1100 // Strong entropy residual
1101 double entRes = (EPOWER(u,0,1)-EPOWER(un,0,1))/dt + 0.5*(DEPOWER(u,0,1)*H + DEPOWER(un,0,1)*Hn);
1102 maxEntRes[eN] = fmax(maxEntRes[eN],fabs(entRes));
1103
1104 // Quantities for normalization factor //
1105 meanEntropy += EPOWER(u,0,1)*dV;
1106 meanOmega += dV;
1107 maxEntropy = fmax(maxEntropy,EPOWER(u,0,1));
1108 minEntropy = fmin(minEntropy,EPOWER(u,0,1));
1109
1110 // artificial compression
1111 double hK=elementDiameter.data()[eN]/degree_polynomial;
1112 entVisc_minus_artComp = fmax(1-cK*fmax(un*(1-un),0)/hK/norm_grad_un,0);
1113 }
1114 else if (STABILIZATION_TYPE==STABILIZATION::VMS)
1115 {
1116 //
1117 //calculate subgrid error (strong residual and adjoint)
1118 //
1119 //calculate strong residual
1120 pdeResidual_u = ck.Mass_strong(m_t) + ck.Advection_strong(df,grad_u);
1121 //calculate adjoint
1122 for (int i=0;i<nDOF_test_element;i++)
1123 {
1124 int i_nSpace = i*nSpace;
1125 Lstar_u[i] = ck.Advection_adjoint(df,&u_grad_test_dV[i_nSpace]);
1126 }
1127 //calculate tau and tau*Res
1128 calculateSubgridError_tau(elementDiameter.data()[eN],dm_t,df,cfl.data()[eN_k],tau0);
1130 G,
1131 dm_t,
1132 df,
1133 tau1,
1134 cfl.data()[eN_k]);
1135 tau = useMetrics*tau1+(1.0-useMetrics)*tau0;
1136
1137 subgridError_u = -tau*pdeResidual_u;
1138 //
1139 //calculate shock capturing diffusion
1140 //
1141 ck.calculateNumericalDiffusion(shockCapturingDiffusion,
1142 elementDiameter.data()[eN],
1143 pdeResidual_u,
1144 grad_u,
1145 numDiff0);
1146 ck.calculateNumericalDiffusion(shockCapturingDiffusion,
1147 sc_uref,
1148 sc_alpha,
1149 G,
1150 G_dd_G,
1151 pdeResidual_u,
1152 grad_u,
1153 numDiff1);
1154 q_numDiff_u.data()[eN_k] = useMetrics*numDiff1+(1.0-useMetrics)*numDiff0;
1155 }
1156 else if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity)
1157 {
1158 aux_entropy_residual = m_t;
1159 for (int I=0;I<nSpace;I++)
1160 aux_entropy_residual += dfn[I]*grad_u_old[I];
1161 if (ENTROPY_TYPE==ENTROPY::POWER)
1162 DENTROPY_un = DEPOWER(mn,uL,uR);
1163 else
1164 {
1165 const double mass_scale_k = fmax(q_porosity_old.data()[eN_k]*rho_f, 1.0e-14);
1166 const double z_n = mn/mass_scale_k;
1167 DENTROPY_un = DELOG(z_n,zL_mass,zR_mass)/mass_scale_k;
1168 }
1169 calculateCFL(elementDiameter.data()[eN]/degree_polynomial,dfn_pore,cfl.data()[eN_k]);
1170 }
1171 else
1172 calculateCFL(elementDiameter.data()[eN]/degree_polynomial,dfn_pore,cfl.data()[eN_k]);
1173
1174 for(int i=0;i<nDOF_test_element;i++)
1175 {
1176 int i_nSpace=i*nSpace;
1177 if (STABILIZATION_TYPE==STABILIZATION::TaylorGalerkinEV)
1178 {
1179 if (stage == 1)
1180 elementResidual_u[i] +=
1181 ck.Mass_weak(dt*m_t,u_test_dV[i]) + // time derivative
1182 1./3*dt*(ck.Advection_weak(fn,&u_grad_test_dV[i_nSpace]) +
1183 ck.Diffusion_weak(a_rowptr.data(),a_colind.data(),a,grad_u,&u_grad_test_dV[i_nSpace])+
1184 ck.NumericalDiffusion(physicalDiffusion, grad_u_old, &u_grad_test_dV[i_nSpace])) +
1185 1./9*dt*dt*ck.NumericalDiffusion(Hn,dfn,&u_grad_test_dV[i_nSpace]) +
1186 1./3*dt*entVisc_minus_artComp*ck.NumericalDiffusion(q_numDiff_u_last.data()[eN_k]+physicalDiffusion,
1187 grad_u_old,
1188 &u_grad_test_dV[i_nSpace]);
1189 // TODO: Add part about moving mesh
1190 else //stage 2
1191 elementResidual_u[i] +=
1192 ck.Mass_weak(dt*m_t,u_test_dV[i]) + // time derivative
1193 dt*(ck.Advection_weak(fn,&u_grad_test_dV[i_nSpace]) +
1194 ck.Diffusion_weak(a_rowptr.data(),a_colind.data(),an,grad_u,&u_grad_test_dV[i_nSpace])+
1195 ck.NumericalDiffusion(physicalDiffusion, grad_u_old, &u_grad_test_dV[i_nSpace])) +
1196 0.5*dt*dt*ck.NumericalDiffusion(HTilde,dfn,&u_grad_test_dV[i_nSpace]) +
1197 dt*entVisc_minus_artComp*ck.NumericalDiffusion(q_numDiff_u_last.data()[eN_k]+physicalDiffusion,
1198 grad_u_old,
1199 &u_grad_test_dV[i_nSpace]);
1200 }
1201 else if (STABILIZATION_TYPE==STABILIZATION::VMS)
1202 {
1203 elementResidual_u[i] +=
1204 ck.Mass_weak(m_t,u_test_dV[i]) +
1205 ck.Advection_weak(f,&u_grad_test_dV[i_nSpace]) +
1206 ck.Diffusion_weak(a_rowptr.data(),a_colind.data(),a,grad_u,&u_grad_test_dV[i_nSpace]) +
1207 ck.SubgridError(subgridError_u,Lstar_u[i]) +
1208 ck.NumericalDiffusion(q_numDiff_u_last.data()[eN_k] + physicalDiffusion,//todo add full sparse diffusion terms
1209 grad_u,
1210 &u_grad_test_dV[i_nSpace]);
1211 }
1212 else if(STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
1213 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
1214 STABILIZATION_TYPE==STABILIZATION::Kuzmin or
1215 STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
1216 {
1217 int eN_i=eN*nDOF_test_element+i;
1218 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) // EV stab
1219 {
1220 element_entropy_residual[i] += DENTROPY_un*aux_entropy_residual*u_test_dV[i];
1221 }
1222 elementResidual_u[i] += (u-un)*u_test_dV[i];
1224 // GROUP VARIABLE w = rho(u)*u. //
1225 // //
1226 // The edge-based low-order operator is monotone only if //
1227 // the transport matrix has ZERO ROW SUMS, because the //
1228 // DMP argument (see the comment at the dissipative-term //
1229 // accumulation below) rewrites //
1230 // sum_j T_ij c_j = sum_{j!=i} T_ij (c_j - c_i) //
1231 // which needs sum_j T_ij = 0. Since //
1232 // T_ij = int (df/dvar) phi_j dw_i, //
1233 // the row sum is int (df/dvar) dw_i, and that vanishes //
1234 // by the partition of unity ONLY when df/dvar is //
1235 // constant over the element. //
1236 // //
1237 // With the variable-density flux f = rho(u)*v*u we have //
1238 // df/du = (rho + u drho/du)*v, //
1239 // which DEPENDS ON u -- so assembling T against u leaves //
1240 // a residue (sum_j T_ij)*c_i in the low-order update. //
1241 // That residue is an unbounded source, and it is largest //
1242 // exactly at the front the limiter has to protect //
1243 // (numpy replica: +4.8% overshoot at eps_rho = 0.235, //
1244 // growing monotonically with eps_rho, exactly 0 at //
1245 // eps_rho = 0). //
1246 // //
1247 // The cure is to transport the GROUP VARIABLE //
1248 // w = rho(u)*u, so that f = v*w //
1249 // is LINEAR in w with df/dw = v, the Darcy velocity, //
1250 // which does not depend on the solution. Row sums are //
1251 // then exactly zero and Kuzmin's theory applies verbatim.//
1252 // Storage becomes m = theta*w, so the update base point //
1253 // and the differencing variable are the SAME variable //
1254 // and the low-order update is a true convex combination. //
1255 // w(u) = rho_f*(u + eps_rho*u^2) is strictly increasing //
1256 // for u >= 0, so bounds map through unchanged: //
1257 // w in [w(min u), w(max u)] <=> u in [min u, max u]. //
1258 // //
1259 // Dispersion is rescaled to match: the physical flux is //
1260 // -a grad(u) = -(a/(dw/du)) grad(w), so the tensor seen //
1261 // by the w-operator is a_w = a/(dw/du). a_w is still a //
1262 // positive multiple of the dispersion tensor, and the //
1263 // diffusion operator has zero row sums for free //
1264 // (sum_j grad(phi_j) = 0), so it never broke the DMP. //
1265 // //
1266 // NOTE this changes only the EDGE-BASED assembly. The //
1267 // cell-based branches (Galerkin, VMS, TaylorGalerkinEV) //
1268 // keep df/du, which is what they need. //
1269 // //
1270 // BEHAVIOUR CHANGE beyond the group variable itself: the //
1271 // explicit branches now take the dispersion tensor from //
1272 // `an` (old time) instead of `a` (current iterate), so //
1273 // it matches the time level of both the advection //
1274 // coefficient (velocity_old) and the dwdu used to //
1275 // rescale it. Mixing a current-time `a` with an //
1276 // old-time dwdu would give a rescaling that corresponds //
1277 // to no consistent dispersion at all. //
1279 const bool implicit_ev =
1280 (STABILIZATION_TYPE==STABILIZATION::ImplicitEV);
1281 // dw/du = rho + u*drho/du, at the matching time level
1282 const double drho_du_k = rho_f*eps_rho;
1283 const double dwdu_k = implicit_ev
1284 ? fmax(rho_out + u *drho_du_k, 1.0e-14)
1285 : fmax(rho_out_old + un*drho_du_k, 1.0e-14);
1286 // df/dw = v, the Darcy velocity at the matching level
1287 const double* adv_df = implicit_ev
1288 ? &velocity.data()[eN_k_nSpace]
1289 : &velocity_old.data()[eN_k_nSpace];
1290 double a_w[nnz];
1291 for (int ii=0; ii<a_rowptr.data()[nSpace]; ii++)
1292 a_w[ii] = (implicit_ev ? a[ii] : an[ii])/dwdu_k;
1293 // FLOW-MODEL FLUXES: advection comes from the flow model's
1294 // edge fluxes in the edge loop, so the element matrix is
1295 // the DISPERSION alone, acting on c with a = theta*rho*D
1296 // (no w, no dw/du rescaling) -- and it never touches the
1297 // fluid, which only the flow model's fluxes move. Every
1298 // edge-based branch; the explicit ones take the tensor at
1299 // the old time, the level their fluxes are evaluated at.
1300 const bool edge_flux = USE_EDGE_FLUX;
1301 for(int j=0;j<nDOF_trial_element;j++)
1302 {
1303 int j_nSpace = j*nSpace;
1304 int i_nSpace = i*nSpace;
1305 if (edge_flux)
1306 {
1307 const double Dij = ck.SimpleDiffusionJacobian_weak(a_rowptr.data(),
1308 a_colind.data(),
1309 implicit_ev ? a : an,
1310 &u_grad_trial[j_nSpace],
1311 &u_grad_test_dV[i_nSpace]);
1312 elementTransport[i][j] += Dij;
1313 elementTransposeTransport[i][j] += Dij;
1314 elementDiffusion[i][j] += ck.NumericalDiffusionJacobian(physicalDiffusion/dwdu_k,
1315 &u_grad_trial[j_nSpace],
1316 &u_grad_test_dV[i_nSpace]);
1317 if (USE_EDGE_VELOCITY)
1318 {
1319 // mass flux of the flow model's edge velocity at
1320 // this quadrature point; AdvectionJacobian_weak
1321 // returns -w (q.grad(w_test)) dV, hence the -=.
1322 // THIS step's velocity for every branch: it is
1323 // rebuilt from the step's own flow fluxes, and
1324 // velocity_old is the previous step's.
1325 double q_flow[nSpace];
1326 for (int I=0;I<nSpace;I++)
1327 q_flow[I] = q_rho_flow.data()[eN_k]*velocity.data()[eN_k_nSpace+I];
1328 elementAdvection[i][j] -=
1329 ck.AdvectionJacobian_weak(q_flow,
1330 u_trial_ref.data()[k*nDOF_trial_element+j],
1331 &u_grad_test_dV[i_nSpace]);
1332 elementTransposeAdvection[i][j] -=
1333 ck.AdvectionJacobian_weak(q_flow,
1334 u_trial_ref.data()[k*nDOF_trial_element+i],
1335 &u_grad_test_dV[j_nSpace]);
1336 }
1337 continue;
1338 }
1339 elementTransport[i][j] +=
1340 ck.AdvectionJacobian_weak(adv_df,
1341 u_trial_ref.data()[k*nDOF_trial_element+j],
1342 &u_grad_test_dV[i_nSpace])
1343 +
1344 ck.SimpleDiffusionJacobian_weak(a_rowptr.data(),
1345 a_colind.data(),
1346 a_w,
1347 &u_grad_trial[j_nSpace],
1348 &u_grad_test_dV[i_nSpace]);
1349
1350
1351
1352
1353 elementDiffusion[i][j] += ck.NumericalDiffusionJacobian(physicalDiffusion/dwdu_k,
1354 &u_grad_trial[j_nSpace],
1355 &u_grad_test_dV[i_nSpace]);
1356 elementTransposeTransport[i][j] += ck.AdvectionJacobian_weak(adv_df,
1357 u_trial_ref.data()[k*nDOF_trial_element+i],
1358 &u_grad_test_dV[j_nSpace])+
1359 ck.SimpleDiffusionJacobian_weak(a_rowptr.data(),
1360 a_colind.data(),
1361 a_w,
1362 &u_grad_trial[j_nSpace],
1363 &u_grad_test_dV[i_nSpace]);
1364
1365
1366 }
1367 }
1368 else
1369 {
1370 elementResidual_u[i] +=
1371 ck.Mass_weak(m_t,u_test_dV[i]) +
1372 ck.Advection_weak(f,&u_grad_test_dV[i_nSpace])+
1373 ck.Diffusion_weak(a_rowptr.data(),a_colind.data(),a,grad_u,&u_grad_test_dV[i_nSpace]);
1374 // +
1375 // ck.NumericalDiffusion(physicalDiffusion,//todo add full sparse diffusion terms
1376 // grad_u,
1377 // &u_grad_test_dV[i_nSpace]);
1378 }
1379 }//i
1380 //
1381 //save solution for other models
1382 //
1383 q_u.data()[eN_k] = u;
1384 q_m.data()[eN_k] = m;
1385 //logInteriorState("storeQuadrature", eN, k, x, y, z, u, m, f, a);
1386
1387 }//k
1388 //
1389 //load element into global residual and save element residual
1390 //
1391 for(int i=0;i<nDOF_test_element;i++)
1392 {
1393 int eN_i=eN*nDOF_test_element+i;
1394 int gi = offset_u+stride_u*u_l2g.data()[eN_i]; //global i-th index
1395 globalResidual.data()[gi] += elementResidual_u[i];
1396 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
1397 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
1398 STABILIZATION_TYPE==STABILIZATION::Kuzmin or
1399 STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
1400 {
1401
1402 // distribute entropy_residual
1403 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) // EV Stab
1404 global_entropy_residual[gi] += element_entropy_residual[i];
1405 // distribute transport matrices
1406 for (int j=0;j<nDOF_trial_element;j++)
1407 {
1408 int eN_i_j = eN_i*nDOF_trial_element+j;
1409 TransportMatrix[csrRowIndeces_CellLoops.data()[eN_i] +
1410 csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementTransport[i][j];
1411 DiffusionMatrix[csrRowIndeces_CellLoops.data()[eN_i] +
1412 csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementDiffusion[i][j];
1413 TransposeTransportMatrix[csrRowIndeces_CellLoops.data()[eN_i] +
1414 csrColumnOffsets_CellLoops.data()[eN_i_j]]
1415 += elementTransposeTransport[i][j];
1416 if (USE_EDGE_VELOCITY)
1417 {
1418 AdvectionMatrix[csrRowIndeces_CellLoops.data()[eN_i] +
1419 csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementAdvection[i][j];
1420 TransposeAdvectionMatrix[csrRowIndeces_CellLoops.data()[eN_i] +
1421 csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementTransposeAdvection[i][j];
1422 }
1423 }//j
1424 }//edge-based
1425 }//i
1426 }//eN
1427 //
1428 //loop over exterior element boundaries to calculate surface integrals and load into element and global residuals
1429 //
1430 //ebNE is the Exterior element boundary INdex
1431 //ebN is the element boundary INdex
1432 //eN is the element index
1433 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++)
1434 {
1435 double min_u_bc_local = 1E10, max_u_bc_local = -1E10;
1436 int ebN = exteriorElementBoundariesArray.data()[ebNE],
1437 eN = elementBoundaryElementsArray.data()[ebN*2+0],
1438 ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN*2+0],
1439 eN_nDOF_trial_element = eN*nDOF_trial_element;
1440 const int eN_out = elementBoundaryElementsArray.data()[ebN*2+1];
1441 const int ebFlag = elementBoundaryMaterialTypes.data()[ebN];
1442 // Only integrate true physical exterior boundaries; skip partition/non-physical faces.
1443 if (ebFlag <= 0 || isExteriorBoundaryPhysical.data()[ebNE] == 0 || eN_out >= 0)
1444 {
1445 continue;
1446 }
1447 double elementResidual_u[nDOF_test_element],
1448 elementResidual_fluid[nDOF_test_element], // SCHEME B: fluid mass
1449 fluxTransport[nDOF_test_element][nDOF_trial_element];
1450 for (int i=0;i<nDOF_test_element;i++)
1451 {
1452 elementResidual_u[i]=0.0;
1453 elementResidual_fluid[i]=0.0;
1454 for (int j=0;j<nDOF_trial_element;j++)
1455 fluxTransport[i][j] = 0.0;
1456 }
1457 for (int kb=0;kb<nQuadraturePoints_elementBoundary;kb++)
1458 {
1459 int ebNE_kb = ebNE*nQuadraturePoints_elementBoundary+kb,
1460 ebNE_kb_nSpace = ebNE_kb*nSpace,
1461 ebN_local_kb = ebN_local*nQuadraturePoints_elementBoundary+kb,
1462 ebN_local_kb_nSpace = ebN_local_kb*nSpace;
1463 double u_ext=0.0,
1464 grad_u_ext[nSpace],
1465 m_ext=0.0,
1466 dm_ext=0.0,
1467 f_ext[nSpace],
1468 df_ext[nSpace],
1470
1471 a_ext[nnz],
1472 da_ext[nnz],
1473
1474 bc_a_ext[nnz],
1475 bc_da_ext[nnz],
1476
1478 flux_ext=0.0,
1479 dflux_u_u_ext=0.0,
1480 bc_u_ext=0.0,
1481 bc_m_ext=0.0,
1482 bc_dm_ext=0.0,
1483
1484 flux_adv_ext=0.0,
1485 flux_diff_ext=0.0,
1486 difffluxjacobian_ext=0.0,
1487 bc_f_ext[nSpace],
1488 bc_df_ext[nSpace],
1489 jac_ext[nSpace*nSpace],
1490 jacDet_ext,
1491 jacInv_ext[nSpace*nSpace],
1492 boundaryJac[nSpace*(nSpace-1)],
1493 metricTensor[(nSpace-1)*(nSpace-1)],
1494 metricTensorDetSqrt,
1495 dS,
1496 u_test_dS[nDOF_test_element],
1497 u_grad_trial_trace[nDOF_trial_element*nSpace],
1498 u_grad_test_dS[nDOF_trial_element*nSpace],
1499 normal[nSpace],x_ext,y_ext,z_ext,xt_ext,yt_ext,zt_ext,integralScaling,
1500
1501 G[nSpace*nSpace],G_dd_G,tr_G;
1502
1503 //
1504 //calculate the solution and gradients at quadrature points
1505 //
1506 //compute information about mapping from reference element to physical element
1507 ck.calculateMapping_elementBoundary(eN,
1508 ebN_local,
1509 kb,
1510 ebN_local_kb,
1511 mesh_dof.data(),
1512 mesh_l2g.data(),
1513 mesh_trial_trace_ref.data(),
1514 mesh_grad_trial_trace_ref.data(),
1515 boundaryJac_ref.data(),
1516 jac_ext,
1517 jacDet_ext,
1518 jacInv_ext,
1519 boundaryJac,
1520 metricTensor,
1521 metricTensorDetSqrt,
1522 normal_ref.data(),
1523 normal,
1524 x_ext,y_ext,z_ext);
1525 ck.calculateMappingVelocity_elementBoundary(eN,
1526 ebN_local,
1527 kb,
1528 ebN_local_kb,
1529 mesh_velocity_dof.data(),
1530 mesh_l2g.data(),
1531 mesh_trial_trace_ref.data(),
1532 xt_ext,yt_ext,zt_ext,
1533 normal,
1534 boundaryJac,
1535 metricTensor,
1536 integralScaling);
1537 dS = ((1.0-MOVING_DOMAIN)*metricTensorDetSqrt + MOVING_DOMAIN*integralScaling)*dS_ref.data()[kb];
1538 //get the metric tensor
1539 //cek todo use symmetry
1540 ck.calculateG(jacInv_ext,G,G_dd_G,tr_G);
1541 //compute shape and solution information
1542 //shape
1543 ck.gradTrialFromRef(&u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace*nDOF_trial_element],
1544 jacInv_ext,
1545 u_grad_trial_trace);
1546 //solution and gradients
1547 if (STABILIZATION_TYPE==STABILIZATION::TaylorGalerkinEV) //explicit
1548 {
1549 ck.valFromDOF(u_dof_old.data(),
1550 &u_l2g.data()[eN_nDOF_trial_element],
1551 &u_trial_trace_ref.data()[ebN_local_kb*nDOF_test_element],
1552 u_ext);
1553 ck.gradFromDOF(u_dof_old.data(),
1554 &u_l2g.data()[eN_nDOF_trial_element],
1555 u_grad_trial_trace,
1556 grad_u_ext);
1557 }
1558 else
1559 {
1560 ck.valFromDOF(u_dof.data(),
1561 &u_l2g.data()[eN_nDOF_trial_element],
1562 &u_trial_trace_ref.data()[ebN_local_kb*nDOF_test_element],
1563 u_ext);
1564 ck.gradFromDOF(u_dof.data(),
1565 &u_l2g.data()[eN_nDOF_trial_element],
1566 u_grad_trial_trace,
1567 grad_u_ext);
1568 }
1569 //precalculate test function products with integration weights
1570 for (int j=0;j<nDOF_trial_element;j++)
1571 {
1572 u_test_dS[j] = u_test_trace_ref.data()[ebN_local_kb*nDOF_test_element+j]*dS;
1573 for (int I=0;I<nSpace;I++)
1574 u_grad_test_dS[j*nSpace+I] = u_grad_trial_trace[j*nSpace+I]*dS;//cek hack, using trial
1575
1576 }
1577 //
1578 //load the boundary values
1579 //
1580 bc_u_ext = isDOFBoundary_u.data()[ebNE_kb]*ebqe_bc_u_ext.data()[ebNE_kb]+
1581 (1-isDOFBoundary_u.data()[ebNE_kb])*u_ext;
1582
1583
1584 //
1585 //
1586 //calculate the pde coefficients using the solution and the boundary values for the solution
1587 //
1588 double rho_out_ext=0.0,rho_out_bc=0.0;
1589 evaluateCoefficients(a_rowptr.data(),
1590 a_colind.data(),
1591 &ebqe_velocity_ext.data()[ebNE_kb_nSpace],
1592 alpha_L,
1593 alpha_T,
1594 Dm,
1595 ebqe_porosity.data()[ebNE_kb],
1596 rho_f,
1597 rho_s,
1598 u_ext,
1599 rho_out_ext,
1600 m_ext,
1601 dm_ext,
1602 f_ext,
1603 df_ext,
1604 a_ext,
1605 da_ext);
1606 ebqe_rho.data()[ebNE_kb] = rho_out_ext;
1607 // Eq. (9), as for q_mu
1608 const double omega_ext = omega_max*u_ext;
1609 ebqe_mu.data()[ebNE_kb] = 1.0 + omega_ext*(1.85 + omega_ext*(-4.1 + omega_ext*44.5));
1610
1611 evaluateCoefficients(a_rowptr.data(),
1612 a_colind.data(),
1613 &ebqe_velocity_ext.data()[ebNE_kb_nSpace],
1614 alpha_L,
1615 alpha_T,
1616 Dm,
1617 ebqe_porosity.data()[ebNE_kb],
1618 rho_f,
1619 rho_s,
1620 bc_u_ext,
1621 rho_out_bc,
1622 bc_m_ext,
1623 bc_dm_ext,
1624 bc_f_ext,
1625 bc_df_ext,
1626 bc_a_ext,
1627 bc_da_ext);
1628 //moving mesh
1629 //
1630 double mesh_velocity[3];
1631 mesh_velocity[0] = xt_ext;
1632 mesh_velocity[1] = yt_ext;
1633 mesh_velocity[2] = zt_ext;
1634
1635 for (int I=0;I<nSpace;I++)
1636 {
1637 f_ext[I] -= MOVING_DOMAIN*m_ext*mesh_velocity[I];
1638 df_ext[I] -= MOVING_DOMAIN*dm_ext*mesh_velocity[I];
1639 bc_f_ext[I] -= MOVING_DOMAIN*bc_m_ext*mesh_velocity[I];
1640 bc_df_ext[I] -= MOVING_DOMAIN*bc_dm_ext*mesh_velocity[I];
1641 }
1642 //
1643 //calculate the numerical fluxes
1644 //
1645 exteriorNumericalAdvectiveFlux(isDOFBoundary_u.data()[ebNE_kb],
1646 isFluxBoundary_u.data()[ebNE_kb],
1647 forceStrongConditions,
1648 normal,
1649 ebqe_bc_flux_u_ext.data()[ebNE_kb],
1650 f_ext,
1651 bc_f_ext,
1652 df_ext,
1653 flux_adv_ext);
1654 exteriorNumericalDiffusiveFlux(a_rowptr.data(),
1655 a_colind.data(),
1656 isDOFBoundary_u.data()[ebNE_kb],
1657 isDiffusiveFluxBoundary_u.data()[ebNE_kb],
1658 normal,
1659 a_ext,
1660 bc_u_ext,
1661 ebqe_bc_diffusiveFlux_u_ext.data()[ebNE_kb],
1662 a_ext,
1663 grad_u_ext,
1664 u_ext,
1665 ebqe_penalty_ext.data()[ebNE_kb],
1666 flux_diff_ext);
1667 flux_ext = flux_adv_ext + flux_diff_ext;
1668 double boundary_flow = 0.0;
1669 for (int I=0; I<nSpace; I++)
1670 boundary_flow += normal[I]*df_ext[I];
1671
1673 // GROUP-VARIABLE traces, for the edge-based and ImplicitEV //
1674 // branches. The INTERIOR assembly builds T against //
1675 // w = rho(u)*u (df/dw = v), so every boundary quantity that //
1676 // ends up multiplying w -- the flux Jacobian rows that go //
1677 // into TransportMatrix, the Nitsche adjoint, the upwind //
1678 // penalty -- has to be in w as well. Leaving them in u was //
1679 // what broke the STAB=2 DMP: the boundary rows of T were //
1680 // u-scaled while the interior was w-scaled, so sum_j T_ij //
1681 // stopped vanishing exactly at boundary-adjacent nodes, and //
1682 // uLow overshot in the row below the Dirichlet source strip //
1683 // (max u = 6.58 on Elder). //
1684 // //
1685 // The RESIDUAL flux_ext needs no conversion: f = rho v u //
1686 // = v*w is already the physical flux, and the diffusive //
1687 // flux -a grad(u) = -a_w grad(w) is the same number either //
1688 // way. Only the linearised/penalty pieces are rescaled. //
1690 const double drho_du_b = rho_f*eps_rho;
1691 const double dwdu_ext = fmax(rho_out_ext + u_ext*drho_du_b, 1.0e-14);
1692 const double w_ext = rho_out_ext*u_ext;
1693 const double w_bc_ext = rho_out_bc*bc_u_ext;
1694 // dispersion w.r.t. w: -a grad(u) = -(a/(dw/du)) grad(w)
1695 double a_w_ext[nnz], zero_da_ext[nnz];
1696 for (int ii=0; ii<a_rowptr.data()[nSpace]; ii++)
1697 {
1698 a_w_ext[ii] = a_ext[ii]/dwdu_ext;
1699 // a_w is treated as frozen when differentiating w.r.t. w
1700 // (the explicit branch stores a fixed matrix anyway), so the
1701 // da*v*grad_psi term of the diffusive Jacobian is dropped.
1702 zero_da_ext[ii] = 0.0;
1703 }
1704 // df/dw = v, the Darcy velocity trace (no density factor)
1705 const double* v_w_ext = &ebqe_velocity_ext.data()[ebNE_kb_nSpace];
1706 double boundary_flow_w = 0.0;
1707 for (int I=0; I<nSpace; I++)
1708 boundary_flow_w += normal[I]*v_w_ext[I];
1709
1711 // SCHEME B: advective boundary flux of the FLUID mass, //
1712 // F^f = (v.n) * rho_up, //
1713 // upwinded exactly as the solute flux is. The interior //
1714 // trace of rho comes from the CARRIED fluid mass M/theta //
1715 // (NOT from the EOS) so the boundary sees the same fluid //
1716 // mass the interior transports; on inflow there is no //
1717 // carried M outside the domain, so the EOS value at the BC //
1718 // is the only choice. //
1719 // //
1720 // Why this keeps u bounded at the boundary: the identity //
1721 // subtracts u_i times the fluid flux from the solute flux, //
1722 // F^s - u_i F^f = (v.n) rho_up (u_up - u_i), //
1723 // which on INFLOW ((v.n) < 0) is +|v.n| rho_bc (u_bc - u_i),//
1724 // a convex pull toward u_bc, and on OUTFLOW is ~0 because //
1725 // u_up is the node's own trace. min_u_bc/max_u_bc already //
1726 // include u_bc in the FCT bounds, so the two agree. //
1727 // //
1728 // NO diffusive counterpart: physical dispersion moves solute//
1729 // relative to the fluid, it does not move fluid. This //
1730 // leaves the weak-Dirichlet Nitsche term in the solute //
1731 // equation without a fluid partner -- pre-existing weak-BC //
1732 // behaviour, not a regression, and identically zero on a //
1733 // closed (v.n = 0) boundary. //
1735 // GATED: theta_dof_proj / m_dof are only RESIZED for the branches
1736 // that carry a fluid mass (see the projection block above); the
1737 // cell-based branches leave them at size 0, so touching them here
1738 // unconditionally reads out of bounds.
1739 double flux_fluid_ext = 0.0;
1740 if (STABILIZATION_TYPE == STABILIZATION::EntropyViscosity or
1741 STABILIZATION_TYPE == STABILIZATION::SmoothnessIndicator or
1742 STABILIZATION_TYPE == STABILIZATION::Kuzmin or
1743 STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
1744 {
1745 double rho_trace_ext = 0.0;
1746 for (int j=0;j<nDOF_trial_element;j++)
1747 {
1748 const int gj = u_l2g.data()[eN_nDOF_trial_element+j];
1749 // ImplicitEV: the nodal EOS density, as in the interior
1750 // edge loop (M_dof is storage only there).
1751 rho_trace_ext += u_trial_trace_ref.data()[ebN_local_kb*nDOF_test_element+j]
1752 * ((STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
1753 ? rho_dof_proj[gj]
1754 : (fmax(M_dof.data()[gj], 1.0e-14)
1755 / fmax(theta_dof_proj[gj], 1.0e-14)));
1756 }
1757 const double rho_bc_fluid = rho_f*(1.0 + eps_rho*bc_u_ext);
1758 const double rho_up_fluid = (boundary_flow_w >= 0.0) ? rho_trace_ext
1759 : rho_bc_fluid;
1760 flux_fluid_ext = boundary_flow_w*rho_up_fluid;
1761 }
1762
1763 // ImplicitEV without the flow model's edge fluxes: on an upwinded
1764 // OUTFLOW face the residual applies c_i times the fluid flux to
1765 // row i (see the residual update below), not the trace flux.
1766 const bool outflow_upwind =
1767 STABILIZATION_TYPE == STABILIZATION::ImplicitEV && !USE_EDGE_FLUX &&
1768 boundary_flow_w >= 0.0 &&
1769 ((isDOFBoundary_u.data()[ebNE_kb] == 1 && forceStrongConditions == 0) ||
1770 (isDOFBoundary_u.data()[ebNE_kb] != 1 && isFluxBoundary_u.data()[ebNE_kb] != 1));
1771 // Record the flux the residual applies. On an upwinded outflow face
1772 // sum_i c_i F^f w_i = c_h F^f at each quadrature point, so c_h F^f is
1773 // that flux pointwise. n.f(c_h) = (v.n) rho(c_h) c_h differs from it
1774 // through the density, which F^f freezes at rho(c^n).
1775 const double flux_adv_applied = outflow_upwind ? u_ext*flux_fluid_ext : flux_adv_ext;
1776 ebqe_flux.data()[ebNE_kb] = outflow_upwind ? flux_adv_applied + flux_diff_ext : flux_ext;
1777 // advective/dispersive split + quadrature weight, see the note at
1778 // the ebqe_flux_adv declaration
1779 ebqe_flux_adv.data()[ebNE_kb] = flux_adv_applied;
1780 ebqe_dS_ext.data()[ebNE_kb] = dS;
1781 if (isDOFBoundary_u.data()[ebNE_kb] == 1)
1782 ebqe_u.data()[ebNE_kb] = bc_u_ext;
1783 else if (boundary_flow >= 0.0)
1784 ebqe_u.data()[ebNE_kb] = u_ext;
1785 else
1786 ebqe_u.data()[ebNE_kb] = bc_u_ext;
1787 if (STABILIZATION_TYPE==STABILIZATION::TaylorGalerkinEV)
1788 {
1789 if (stage == 1)
1790 flux_ext *= 1./3*dt;
1791 else
1792 flux_ext *= dt;
1793 }
1794
1795 //
1796 //update residuals
1797 //
1798 for (int i=0;i<nDOF_test_element;i++)
1799 {
1800 // SCHEME B: fluid-mass boundary flux, for every branch that
1801 // transports a fluid mass (the edge-based ones + ImplicitEV).
1802 // The cell-based branches (Galerkin/VMS/TaylorGalerkinEV) do
1803 // not carry M and are untouched.
1804 if (STABILIZATION_TYPE == STABILIZATION::EntropyViscosity or
1805 STABILIZATION_TYPE == STABILIZATION::SmoothnessIndicator or
1806 STABILIZATION_TYPE == STABILIZATION::Kuzmin or
1807 STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
1808 elementResidual_fluid[i] +=
1809 ck.ExteriorElementBoundaryFlux(flux_fluid_ext, u_test_dS[i]);
1810 if (USE_EDGE_FLUX)
1811 {
1812 // FLOW-MODEL FLUXES (every edge-based branch): the advective
1813 // boundary exchange is the flow model's nodalBoundaryFlux
1814 // (edge loop), so only the DISPERSIVE flux stays here, on c.
1815 if (isDOFBoundary_u.data()[ebNE_kb] == 1 &&
1816 isDiffusiveFluxBoundary_u.data()[ebNE_kb] == 0)
1817 {
1818 // WEAK DIRICHLET, bound preserving: a LUMPED penalty
1819 // gamma_i (c_i - g), gamma_i = max_a*penalty*int_e w_i >= 0,
1820 // which pulls c_i toward a w_i-weighted average of g and
1821 // couples to no other DOF. The IIPG terms are dropped on
1822 // these faces: the consistency term -a grad(c).n couples c_i
1823 // to the far nodes of the face's element with a positive
1824 // off-diagonal (it is the dispersive flux through the face,
1825 // whatever c_i is), the consistent-mass penalty couples c_i
1826 // to its boundary neighbours with the wrong sign, and the
1827 // adjoint uses grad(w_i). Each breaks the convex-combination
1828 // form of the low-order row, which put Henry's Dirichlet
1829 // nodes at c = 1.006 and -7e-8. The price is a penalty
1830 // (Robin, -a grad(c).n = gamma (c - g)) instead of a
1831 // consistent BC, O(h) at the boundary since penalty ~ 1/h.
1832 // The explicit branches advance from c^n, so the penalty
1833 // acts on c^n there.
1834 const int gi_d = u_l2g.data()[eN*nDOF_test_element+i];
1835 const double c_d = (STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
1836 ? u_dof.data()[gi_d] : u_dof_old.data()[gi_d];
1837 double max_a = 0.0;
1838 for (int m=0; m<a_rowptr.data()[nSpace]; m++)
1839 max_a = fmax(max_a, a_ext[m]);
1840 elementResidual_u[i] += max_a*ebqe_penalty_ext.data()[ebNE_kb]
1841 *(c_d - bc_u_ext)*u_test_dS[i];
1842 }
1843 else
1844 elementResidual_u[i] += ck.ExteriorElementBoundaryFlux(flux_diff_ext,u_test_dS[i]);
1845 // the concentration inflowing water carries at this node
1846 if (isDOFBoundary_u.data()[ebNE_kb] == 1)
1847 {
1848 const int gi_b = u_l2g.data()[eN*nDOF_test_element+i];
1849 cin_num[gi_b] += bc_u_ext*u_test_dS[i];
1850 cin_den[gi_b] += u_test_dS[i];
1851 }
1852 }
1853 else if (STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
1854 {
1855 // OUTFLOW carries the node's own concentration: on an upwinded
1856 // outflow face the solute flux is c_i times the fluid flux of
1857 // the same face, so B^s_i - c_i B^f_i of the cancelled row is
1858 // exactly zero there. The trace flux n.f(c_h) coupled c_i to
1859 // the other nodes of the face with a positive off-diagonal,
1860 // which broke the M-matrix of the low-order row (Zalesak level
1861 // 4 FCT: c^L = -2.9e-9 at the outflow wall node (0, 0.625)).
1862 // outflow_upwind: decided once per quadrature point, above,
1863 // where the recorded flux is set from the same condition
1864 const double flux_i = outflow_upwind
1865 ? u_dof.data()[u_l2g.data()[eN*nDOF_test_element+i]]*flux_fluid_ext + flux_diff_ext
1866 : flux_ext;
1867 // ImplicitEV also transports the group variable, so its
1868 // boundary_integral must be the adjoint of the w-operator
1869 // (see the GROUP-VARIABLE trace block above).
1870 elementResidual_u[i] += ck.ExteriorElementBoundaryFlux(flux_i,u_test_dS[i])+
1871 ck.ExteriorElementBoundaryDiffusionAdjoint(isDOFBoundary_u.data()[ebNE_kb],
1872 isDiffusiveFluxBoundary_u.data()[ebNE_kb],
1873 eb_adjoint_sigma,
1874 w_ext,
1875 w_bc_ext,
1876 normal,
1877 a_rowptr.data(),
1878 a_colind.data(),
1879 a_w_ext,
1880 &u_grad_test_dS[i*nSpace]);
1881 }
1882 else if (STABILIZATION_TYPE == STABILIZATION::Galerkin or STABILIZATION_TYPE == STABILIZATION::VMS or
1883 STABILIZATION_TYPE == STABILIZATION::TaylorGalerkinEV)
1884 {
1885 // cell-based branches keep the u-form throughout
1886 elementResidual_u[i] += ck.ExteriorElementBoundaryFlux(flux_ext,u_test_dS[i])+
1887 ck.ExteriorElementBoundaryDiffusionAdjoint(isDOFBoundary_u.data()[ebNE_kb],
1888 isDiffusiveFluxBoundary_u.data()[ebNE_kb],
1889 eb_adjoint_sigma,
1890 u_ext,
1891 bc_u_ext,
1892 normal,
1893 a_rowptr.data(),
1894 a_colind.data(),
1895 a_ext,
1896 &u_grad_test_dS[i*nSpace]);
1897 }
1898 else if (STABILIZATION_TYPE == STABILIZATION::EntropyViscosity or
1899 STABILIZATION_TYPE == STABILIZATION::SmoothnessIndicator or
1900 STABILIZATION_TYPE == STABILIZATION::Kuzmin)
1901 {
1902 const double boundaryAdvectiveContribution =
1903 ck.ExteriorElementBoundaryFlux(flux_ext,u_test_dS[i]);
1904 // GROUP VARIABLE: Nitsche adjoint on (w, w_bc) with a_w,
1905 // so it is the adjoint of the SAME operator the interior
1906 // assembles. a_w = a/(dw/du) makes the physical value
1907 // identical; only the variable it is expressed in changes.
1908 const double boundaryDiffusiveContribution =
1909 ck.ExteriorElementBoundaryDiffusionAdjoint(isDOFBoundary_u.data()[ebNE_kb],
1910 isDiffusiveFluxBoundary_u.data()[ebNE_kb],
1911 eb_adjoint_sigma,
1912 w_ext,
1913 w_bc_ext,
1914 normal,
1915 a_rowptr.data(),
1916 a_colind.data(),
1917 a_w_ext,
1918 &u_grad_test_dS[i*nSpace]);
1919 const double boundaryResidualContribution =
1920 boundaryAdvectiveContribution + boundaryDiffusiveContribution;
1921 // df/dw = v, NOT df/du -- these rows go into TransportMatrix,
1922 // which the edge loop multiplies by w_j.
1923 exteriorNumericalAdvectiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],
1924 isFluxBoundary_u.data()[ebNE_kb],
1925 forceStrongConditions,
1926 normal,
1927 v_w_ext,
1928 dflux_u_u_ext);
1929
1930 if (dflux_u_u_ext> 0.0)
1931 {
1932 double boundaryTransportContribution = 0.0;
1933 double boundaryTransportContributionFluid = 0.0; // SCHEME B
1934 for (int j=0;j<nDOF_trial_element;j++)
1935 {
1936 int ebN_local_kb_j=ebN_local_kb*nDOF_trial_element+j;
1937 double advJacobian_ext = 0.0, diffJacobian_ext = 0.0;
1938 exteriorNumericalAdvectiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],
1939 isFluxBoundary_u.data()[ebNE_kb],
1940 forceStrongConditions,
1941 normal,
1942 v_w_ext,
1943 advJacobian_ext);
1944 exteriorNumericalDiffusiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],
1945 isDiffusiveFluxBoundary_u.data()[ebNE_kb],
1946 a_rowptr.data(),
1947 a_colind.data(),
1948 normal,
1949 a_w_ext,
1950 zero_da_ext,
1951 grad_u_ext,
1952 &u_grad_trial_trace[j*nSpace],
1953 u_trial_trace_ref.data()[ebN_local_kb_j],
1954 ebqe_penalty_ext.data()[ebNE_kb],
1955 diffJacobian_ext);
1956 difffluxjacobian_ext = advJacobian_ext*u_trial_trace_ref.data()[ebN_local_kb_j]
1957 + diffJacobian_ext;
1958 const double localFluxTransportContribution =
1959 difffluxjacobian_ext*u_test_dS[i];
1960 fluxTransport[i][j] += localFluxTransportContribution;
1961 // ... and the value it multiplies must be w^n_j, not u^n_j.
1962 // SCHEME B: w^n and rho^n come from the CARRIED masses
1963 // (m_dof = M_dof*u^n, M_dof), not from the EOS -- the
1964 // interior operator acts on exactly those, so an EOS
1965 // value here would make the subtraction below fail to
1966 // cancel what actually went into TransportMatrix.
1967 {
1968 const int gj = u_l2g.data()[eN_nDOF_trial_element+j];
1969 const double theta_j = fmax(theta_dof_proj[gj], 1.0e-14);
1970 const double wn_j = m_dof[gj]/theta_j;
1971 const double rhon_j = fmax(M_dof.data()[gj],1.0e-14)/theta_j;
1972 boundaryTransportContribution += localFluxTransportContribution*wn_j;
1973 boundaryTransportContributionFluid += localFluxTransportContribution*rhon_j;
1974 }
1975 }
1976 elementResidual_u[i] += boundaryResidualContribution - boundaryTransportContribution;
1977 // SCHEME B: the SAME correction on the fluid mass. For
1978 // these branches fluxTransport is loaded into
1979 // TransportMatrix below, so the edge loop's
1980 // sum_j (T+D)_ij rho_j ALREADY contains the linearised
1981 // boundary flux; adding the true boundary flux on top
1982 // without subtracting it back out double-counts it.
1983 // That is exactly what drained the fluid mass to 0.4 in
1984 // test_tadr (it must stay at 1 for rho = theta = 1).
1985 // ImplicitEV does NOT load fluxTransport into T, so it
1986 // takes the unsubtracted flux -- see the i-loop head.
1987 elementResidual_fluid[i] -= boundaryTransportContributionFluid;
1988 }
1989 else
1990 {
1991 elementResidual_u[i] += boundaryResidualContribution;
1992
1993 if (isDOFBoundary_u.data()[ebNE_kb] == 1 && boundary_flow_w < 0.0)
1994 {
1995 // inflow upwind penalty, in the conserved variable
1996 const double upwind_penalty_rate = -boundary_flow_w; // |v.n|
1997 elementResidual_u[i] += upwind_penalty_rate
1998 * (w_ext - w_bc_ext)
1999 * u_test_dS[i];
2000 }
2001 }
2002 }
2003 }//i
2004
2005
2006 const double u_for_bound = isDOFBoundary_u.data()[ebNE_kb]
2007 ? ebqe_bc_u_ext.data()[ebNE_kb]
2008 : ebqe_u.data()[ebNE_kb];
2009 min_u_bc_local = fmin(u_for_bound, min_u_bc_local);
2010 max_u_bc_local = fmax(u_for_bound, max_u_bc_local);
2011 }//kb
2012 //
2013 //update the element and global residual storage
2014 //
2015 for (int i=0;i<nDOF_test_element;i++)
2016 {
2017 int eN_i = eN*nDOF_test_element+i;
2018 int gi = offset_u+stride_u*u_l2g.data()[eN_i]; //global i-th index
2019 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or STABILIZATION_TYPE==STABILIZATION::Kuzmin)
2020 {
2021 globalResidual.data()[gi] += dt*elementResidual_u[i];
2022 boundary_integral[gi] += elementResidual_u[i];
2023 boundary_integral_fluid[gi] += elementResidual_fluid[i]; // SCHEME B
2024 min_u_bc[gi] = fmin(min_u_bc_local,min_u_bc[gi]);
2025 max_u_bc[gi] = fmax(max_u_bc_local,max_u_bc[gi]);
2026 for (int j=0;j<nDOF_trial_element;j++)
2027 {
2028 int ebN_i_j = ebN*4*nDOF_test_X_trial_element + i*nDOF_trial_element + j;
2029 TransportMatrix[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_eb_CellLoops.data()[ebN_i_j]]
2030 += fluxTransport[i][j];
2031 TransposeTransportMatrix[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_eb_CellLoops.data()[ebN_i_j]]
2032 += fluxTransport[j][i];
2033 }//j
2034 }
2035 else if (STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
2036 {
2037 // Implicit boundary: stash the consistent boundary residual in
2038 // boundary_integral (the edge loop adds + boundary_integral[i]
2039 // and OVERWRITES globalResidual[i], so we must NOT add here).
2040 // The boundary flux Jacobian is assembled in calculateJacobian.
2041 boundary_integral[gi] += elementResidual_u[i];
2042 boundary_integral_fluid[gi] += elementResidual_fluid[i]; // SCHEME B
2043 // FCT bounds at the boundary (used by the explicit FCT
2044 // post-step when FCT=True; harmless otherwise).
2045 min_u_bc[gi] = fmin(min_u_bc_local,min_u_bc[gi]);
2046 max_u_bc[gi] = fmax(max_u_bc_local,max_u_bc[gi]);
2047 }
2048 else
2049 {
2050 globalResidual.data()[offset_u+stride_u*r_l2g.data()[eN_i]] += elementResidual_u[i];
2051 }
2052 }//i
2053 }//ebNE
2054 if (STABILIZATION_TYPE==STABILIZATION::TaylorGalerkinEV)
2055 {
2056 meanEntropy /= meanOmega;
2057 double norm_factor = fmax(fabs(maxEntropy - meanEntropy), fabs(meanEntropy-minEntropy));
2058 for(int eN=0;eN<nElements_global;eN++)
2059 {
2060 double hK=elementDiameter.data()[eN]/degree_polynomial;
2061 double linear_viscosity = cMax*hK*maxVel[eN];
2062 double entropy_viscosity = cE*hK*hK*maxEntRes[eN]/norm_factor;
2063 for (int k=0;k<nQuadraturePoints_element;k++)
2064 {
2065 int eN_k = eN*nQuadraturePoints_element+k;
2066 q_numDiff_u.data()[eN_k] = fmin(linear_viscosity,entropy_viscosity);
2067 }
2068 }
2069 }
2070 //edge based stabilization, advecting with the flow model's fluxes
2071 else if (USE_EDGE_FLUX and
2072 (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
2073 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
2074 STABILIZATION_TYPE==STABILIZATION::Kuzmin))
2075 {
2077 // EXPLICIT edge-based stage with the FLOW MODEL'S FLUXES. //
2078 // One forward-Euler step from (c^n, M^n) = (u_dof_old, M_dof) to //
2079 // M^{n+1} = M_low, which Python set to M_dof plus the flow //
2080 // model's storage change, so that //
2081 // ML_i (M^{n+1}_i - M^n_i)/dt = sum_j F_ij + B_i exactly. //
2082 // The conservative solute update //
2083 // ML_i (M^{n+1} c^{n+1} - M^n c^n)_i/dt //
2084 // = sum_{j!=i} [F_ij (c_i + c_j)/2 + (d_ij - D_ij)(c_j - c_i)] //
2085 // + B_i c_up - (boundary dispersion) + sources //
2086 // minus c^n_i times that fluid balance is the CANCELLED form //
2087 // ML_i M^{n+1}_i (c^{n+1}_i - c^n_i)/dt //
2088 // = sum_{j!=i} (d_ij - K_ij)(c_j - c_i) //
2089 // + max(B_i,0)(c_in - c_i) - (boundary dispersion) + ... //
2090 // with K_ij = -F_ij/2 + D_ij, which is what is assembled below. //
2091 // It is the conservative update rewritten, so solute mass is //
2092 // conserved to round-off; with d = dLow = max(0,K_ij,K_ji) every //
2093 // gamma_ij = dLow_ij - K_ij >= 0, and c^L is a convex combination //
2094 // of c^n_i, its neighbours and c_in when //
2095 // dt (sum_j gamma_ij + max(B_i,0)) <= ML_i M^{n+1}_i, //
2096 // which is the edge_based_cfl written here. The high-order state //
2097 // replaces dLow by the branch's d^H; FCT limits the difference. //
2098 // Same operator as the ImplicitEV edge-flux branch, evaluated at //
2099 // c^n instead of c^{n+1}. The fluid mass is not advanced here: M //
2100 // is the flow model's, carried by Python (RKEV.updateStage and //
2101 // Coefficients.postStep). //
2103 // INDICATORS, on c (the variable the operator acts on).
2104 // * EV: there is no velocity to form d_t eta + v.grad eta with, so
2105 // the residual is the entropy commutator of the centered edge flux,
2106 // R_i = sum_{j!=i} (F_ij/2) [(eta_j - eta_i) - eta'_i (c_j - c_i)],
2107 // the edge form of eta'(c) v.grad c - v.grad eta(c) (Guermond,
2108 // Nazarov, Popov, Tomas, SISC 2018): zero for c linear along every
2109 // edge, O(F) at a discontinuity. Normalized as the element-based
2110 // residual is, by 2 cE over the local entropy range.
2111 // * SI/Kuzmin: the smoothness indicator on c.
2112 int ij = 0;
2113 for (int i=0; i<numDOFs; i++)
2114 {
2115 const double ci = u_dof_old.data()[i];
2116 const double eta_i = (ENTROPY_TYPE == ENTROPY::POWER) ? EPOWER(ci,uL,uR) : ELOG(ci,uL,uR);
2117 const double deta_i = (ENTROPY_TYPE == ENTROPY::POWER) ? DEPOWER(ci,uL,uR) : DELOG(ci,uL,uR);
2118 double etaMaxi = eta_i, etaMini = eta_i, entropy_residual = 0.0;
2119 double alpha_numerator = 0., alpha_denominator = 0.;
2120 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
2121 {
2122 const int j = csrColumnOffsets_DofLoops.data()[offset];
2123 const double cj = u_dof_old.data()[j];
2124 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity && i != j)
2125 {
2126 const double eta_j = (ENTROPY_TYPE == ENTROPY::POWER) ? EPOWER(cj,uL,uR) : ELOG(cj,uL,uR);
2127 etaMaxi = fmax(etaMaxi, eta_j);
2128 etaMini = fmin(etaMini, eta_j);
2129 const double Fij = USE_EDGE_VELOCITY
2131 : edgeFlux.data()[ij];
2132 entropy_residual += 0.5*Fij*((eta_j - eta_i) - deta_i*(cj - ci));
2133 }
2134 alpha_numerator += ci - cj;
2135 alpha_denominator += fabs(ci - cj);
2136 ij += 1;
2137 }
2138 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity)
2139 {
2140 global_entropy_residual[i] = (etaMaxi == etaMini) ? 0.0
2141 : 2*cE*entropy_residual/(etaMaxi - etaMini);
2142 quantDOFs.data()[i] = fabs(global_entropy_residual[i]);
2143 }
2144 const double alphai = alpha_numerator/(alpha_denominator+1E-15);
2145 if (STABILIZATION_TYPE!=STABILIZATION::EntropyViscosity)
2146 quantDOFs.data()[i] = alphai;
2147 psi[i] = (POWER_SMOOTHNESS_INDICATOR==0) ? 1.0 : std::pow(alphai,POWER_SMOOTHNESS_INDICATOR);
2148 }
2149 // EDGE LOOP: low- and high-order stage, cancelled form.
2150 ij = 0;
2151 for (int i=0; i<numDOFs; i++)
2152 {
2153 const double ci = u_dof_old.data()[i];
2154 const double MLi = ML.data()[i];
2155 const double Mnew_i = fmax(M_low.data()[i], 1.0e-14);
2156 const double theta_i = fmax(theta_dof_proj[i], 1.0e-14);
2157 double low_term = 0.0, high_term = 0.0, sum_gamma = 0.0;
2158 double ith_flux_term_fluid = 0.0; // -sum_j F_ij, for the defect probe
2159 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
2160 {
2161 const int j = csrColumnOffsets_DofLoops.data()[offset];
2162 if (i != j)
2163 {
2164 const double cj = u_dof_old.data()[j];
2165 const double Fij = USE_EDGE_VELOCITY
2167 : edgeFlux.data()[ij];
2168 if (USE_EDGE_VELOCITY)
2169 edgeFlux.data()[ij] = Fij;
2170 const double Kij = -0.5*Fij + TransportMatrix[ij] + DiffusionMatrix[ij];
2171 const double Kji = 0.5*Fij + TransposeTransportMatrix[ij] + DiffusionMatrix[ij];
2172 const double dLowij = fmax(0.0, fmax(Kij, Kji));
2173 // artificial compression, as in the branch below
2174 const double solij = 0.5*(ci + cj);
2175 const double Compij = cK*fmax(solij*(1.0-solij),0.0)/(fabs(ci-cj)+1E-14);
2176 const double dHij = (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity)
2177 ? fmin(dLowij, fmax(fabs(global_entropy_residual[i]),
2178 fabs(global_entropy_residual[j])))*fmax(1.0-Compij,0.0)
2179 : dLowij*fmax(psi[i],psi[j])*fmax(1.0-Compij,0.0);
2180 const double gamma = dLowij - Kij; // >= 0 by construction
2181 low_term += gamma*(cj - ci);
2182 high_term += (dHij - Kij)*(cj - ci);
2183 sum_gamma += gamma;
2184 ith_flux_term_fluid -= Fij;
2185 dLow.data()[ij] = dLowij;
2186 dt_times_dH_minus_dL.data()[ij] = dt*(dHij - dLowij);
2187 }
2188 else
2189 {
2190 dLow.data()[ij] = 0.0;
2191 dt_times_dH_minus_dL.data()[ij] = 0.0;
2192 if (USE_EDGE_VELOCITY)
2193 edgeFlux.data()[ij] = 0.0;
2194 }
2195 ij += 1;
2196 }
2197 // The flow model's boundary exchange; with the edge velocity it is
2198 // what the assembled F leaves of the carried mass change.
2199 if (USE_EDGE_VELOCITY)
2200 nodalBoundaryFlux.data()[i] = MLi*(M_low.data()[i] - M_dof.data()[i])/dt
2201 + ith_flux_term_fluid;
2202 const double B_i = nodalBoundaryFlux.data()[i];
2203 const double c_in = (cin_den[i] > 0.0) ? cin_num[i]/cin_den[i] : ci;
2204 // Stage-3 kinetic dissolution source, as in the ImplicitEV edge-flux
2205 // branch (solute only; the fluid is the flow model's)
2206 const double S_n_i = Sn_dof.data()[i];
2207 const double R_diss_i = theta_i*rho_f*(1.0 + eps_rho*ci)*k_d*S_n_i*(c_sat - ci);
2208 const double rhs_rest = - boundary_integral[i]
2209 + fmax(B_i, 0.0)*(c_in - ci)
2210 + MLi*R_diss_i
2211 + MLi*nodalSource.data()[i];
2212 const double scale = dt/(MLi*Mnew_i);
2213 uLow.data()[i] = ci + scale*(low_term + rhs_rest);
2214 globalResidual.data()[i] = ci + scale*(high_term + rhs_rest);
2215 edge_based_cfl.data()[i] = (sum_gamma + fmax(B_i, 0.0))/(MLi*Mnew_i);
2216 // the flow model's fluid flux, so the continuity defect against the
2217 // carried M^{n+1} is round-off by construction
2218 fluidResidual.data()[i] = ith_flux_term_fluid - B_i;
2219 }
2220 }
2221 //edge based stabilization
2222 else if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
2223 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
2224 STABILIZATION_TYPE==STABILIZATION::Kuzmin)
2225 {
2227 // COMPUTE SMOOTHNESS INDICATOR and NORMALIZE ENTROPY RESIDUAL //
2229 // NOTE: see NCLS.h for a different but equivalent implementation of this.
2230 //cek todo: can these loops over numDOFs be collapsed?
2231 int ij = 0;
2232 for (int i=0; i<numDOFs; i++)
2233 {
2234 double etaMaxi, etaMini;
2235 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) //EV
2236 {
2237 // For eta min and max
2238 etaMaxi = fabs(eta[i]);
2239 etaMini = fabs(eta[i]);
2240 }
2241 // for smoothness indicator //
2242 double alpha_numerator = 0., alpha_denominator = 0.;
2243 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
2244 { // First loop in j (sparsity pattern)
2245 int j = csrColumnOffsets_DofLoops.data()[offset];
2246 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) //EV Stabilization
2247 {
2248 // COMPUTE ETA MIN AND ETA MAX //
2249 etaMaxi = fmax(etaMaxi,fabs(eta[j]));
2250 etaMini = fmin(etaMini,fabs(eta[j]));
2251 }
2252 // Sense smoothness on the GROUP VARIABLE w = rho(u)*u = m/theta,
2253 // the variable the edge operator actually transports. Using m
2254 // instead folds the porosity jump at a material interface into
2255 // the smoothness sensor, which drives psi -> 1 (and so the full
2256 // low-order viscosity) across an interface even where the
2257 // transported field is perfectly smooth.
2258 const double wi = m_dof[i]/fmax(theta_dof_proj[i], 1.0e-14);
2259 const double wj = m_dof[j]/fmax(theta_dof_proj[j], 1.0e-14);
2260 alpha_numerator += wi - wj;
2261 alpha_denominator += fabs(wi - wj);
2262 //update ij
2263 ij+=1;
2264 }
2265 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) //EV Stab
2266 {
2267 // Normalize entropy residual
2268 global_entropy_residual[i] *= etaMini == etaMaxi ? 0. : 2*cE/(etaMaxi-etaMini);
2269 quantDOFs[i] = fabs(global_entropy_residual[i]);
2270 }
2271
2272 double alphai = alpha_numerator/(alpha_denominator+1E-15);
2273 quantDOFs[i] = alphai;
2274
2275
2277 psi[i] = 1.0;
2278 else
2279 psi[i] = std::pow(alphai,POWER_SMOOTHNESS_INDICATOR); //NOTE: they use alpha^2 in the paper
2280 }
2282 // ** LOOP IN DOFs FOR EDGE BASED TERMS ** //
2284 // DMP diagnostic, Coefficients(diagnostics=("dmp",)) (off by default,
2285 // and the branch is a single bool test when off).
2286 const bool TADR_DMP_DBG = args.scalar<int>("DMP_DIAGNOSTICS") != 0;
2287 // total lines emitted over the whole run, so the first violation is
2288 // captured and the log does not explode over ~12000 substeps x 64 ranks
2289 static int dbg_budget = 40;
2290 int dbg_reported = 0, dbg_argmax_coef = -1;
2291 double dbg_global_max_coef = -1.0e300, dbg_global_min_gamma = 1.0e300;
2292 ij=0;
2293 for (int i=0; i<numDOFs; i++)
2294 {
2295 const double mi_mass = m_dof[i];
2296 const double theta_i = fmax(theta_dof_proj[i], 1.0e-14);
2297 // SCHEME B: u is the RATIO of the two transported masses, so the
2298 // EOS inverse is not used here at all. m_dof[i] = M_dof[i]*u^n_i
2299 // was set from the carried fluid mass above, so this returns
2300 // u^n_i exactly (no projection/EOS round-trip, which is what
2301 // used to break the FCT seam).
2302 const double Mi_fluid = fmax(M_dof.data()[i], 1.0e-14);
2303 const double ui_mass = mi_mass/Mi_fluid;
2304 const double rhoi_fluid = Mi_fluid/theta_i;
2305 // GROUP VARIABLE w = rho(u)*u = m/theta. This is what the
2306 // transport matrix now acts on (see the assembly comment in the
2307 // element loop), so every flux and dissipation difference below is
2308 // taken in w, and the storage is simply m = theta*w.
2309 const double wi_mass = mi_mass/theta_i;
2310 double ith_dissipative_term_mass = 0;
2311 double ith_low_order_dissipative_term_mass = 0;
2312 double ith_flux_term_mass = 0;
2313 // SCHEME B: the SAME operator, applied to the fluid mass. These
2314 // must mirror their solute counterparts term for term -- any
2315 // asymmetry between the two breaks the cancellation that makes
2316 // u = m/M a convex combination.
2317 double ith_flux_term_fluid = 0;
2318 double ith_low_order_dissipative_term_fluid = 0;
2319 // --- DMP diagnostic accumulators (diagnostics "dmp") ---
2320 // gamma_ij = dLow_ij - T_ij - D_ij is the coefficient of
2321 // (w_j - w_i) in the low-order update. The update is a convex
2322 // combination iff every gamma_ij >= 0 AND
2323 // coef_i = dt*sum_j gamma_ij/(theta_i*ML_i) <= 1.
2324 // dLow_from_transpose counts edges where dLow is set by |T_ji|
2325 // rather than |T_ij| -- i.e. by the OTHER row, which for an edge
2326 // touching the boundary carries the boundary flux Jacobian.
2327 double dbg_sum_gamma = 0.0, dbg_min_gamma = 1.0e300;
2328 double dbg_max_dLow = 0.0, dbg_max_absT = 0.0, dbg_max_absTt = 0.0;
2329 int dbg_n_from_transpose = 0;
2330 // Row sum of the high-order graph viscosity, dLii = -sum_{j!=i} dLij.
2331 // Feeds edge_based_cfl below.
2332 double dLii = 0.;
2333
2334 // loop over the sparsity pattern of the i-th DOF
2335 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
2336 {
2337 int j = csrColumnOffsets_DofLoops.data()[offset];
2338 const double mj_mass = m_dof[j];
2339 const double theta_j = fmax(theta_dof_proj[j], 1.0e-14);
2340 const double Mj_fluid = fmax(M_dof.data()[j], 1.0e-14);
2341 const double uj_mass = mj_mass/Mj_fluid;
2342 const double wj_mass = mj_mass/theta_j;
2343 const double rhoj_fluid = Mj_fluid/theta_j;
2344 double dLowij, dLij, dEVij, dHij;
2345
2346 ith_flux_term_mass += (TransportMatrix[ij] + DiffusionMatrix[ij])*wj_mass;
2347 ith_flux_term_fluid += (TransportMatrix[ij] + DiffusionMatrix[ij])*rhoj_fluid;
2348
2349 if (i != j)
2350 {
2351 double solij = 0.5*(ui_mass+uj_mass);
2352 double Compij = cK*fmax(solij*(1.0-solij),0.0)/(fabs(ui_mass-uj_mass)+1E-14);
2353 // MINIMAL Kuzmin graph viscosity, built from the COMBINED
2354 // operator K = T + D. The old max(|K_ij|,|K_ji|) is an
2355 // over-estimate: T carries the dispersion stiffness (see
2356 // the element assembly, ck.SimpleDiffusionJacobian_weak
2357 // goes into elementTransport, not into elementDiffusion),
2358 // and for a symmetric negative off-diagonal entry
2359 // max(|K_ij|,|K_ji|) - K_ij = -2 K_ij applies the physical
2360 // dispersion TWICE. Verified in the numpy replica at
2361 // v = 0: ratio to the exact D/h is 2.000 with the old
2362 // form, 1.000 with this one. max(0,K_ij,K_ji) is still
2363 // symmetric (so the FCT antidiffusive flux stays
2364 // antisymmetric and the scheme stays conservative) and
2365 // still gives gamma_ij = dLow - K_ij >= 0 by definition,
2366 // including for positive off-diagonals on obtuse elements.
2367 // Where the mesh Peclet number allows it this collapses to
2368 // dLow = 0, i.e. central differencing with the physical
2369 // dispersion only -- no artificial diffusion at all.
2370 {
2371 const double Kij = TransportMatrix[ij] + DiffusionMatrix[ij];
2372 const double Kji = TransposeTransportMatrix[ij] + DiffusionMatrix[ij];
2373 dLowij = fmax(0.0, fmax(Kij, Kji));
2374 }
2375
2376 dLij = dLowij*fmax(psi[i],psi[j]); // Approach by JLG & BP
2377
2378 if (STABILIZATION_TYPE==STABILIZATION::EntropyViscosity) //EV Stab
2379 {
2380 // high-order (entropy viscosity) dissipative operator
2381 dEVij = fmax(fabs(global_entropy_residual[i]),fabs(global_entropy_residual[j]));
2382 dHij = fmin(dLowij,dEVij) * fmax(1.0-Compij,0.0); // artificial compression
2383 }
2384 else // smoothness based indicator
2385 {
2386 dHij = dLij * fmax(1.0-Compij,0.0); // artificial compression
2387 }
2388 // Dissipative terms. The DIFFERENCES are taken in the GROUP
2389 // VARIABLE w = rho(u)*u -- the same variable the transport
2390 // matrix now acts on -- so the pair telescopes into the
2391 // monotone operator:
2392 // sum_j (T+D)_ij w_j - sum_{j!=i} dLow_ij (w_j - w_i)
2393 // = -sum_{j!=i} (dLow_ij - T_ij - D_ij)(w_j - w_i)
2394 // with dLow_ij - T_ij - D_ij >= 0 because dLow_ij >= |T_ij|,
2395 // i.e. an M-matrix. The rewrite of the left side into the
2396 // right side is valid ONLY because T now has zero row sums
2397 // (df/dw = v, independent of the solution); differencing
2398 // against u with the u-assembled T left a residue
2399 // (sum_j T_ij)*c_i that broke boundedness at every
2400 // rho_s != rho_f.
2401 //
2402 // It must NOT be replaced by -sum max(0,-T_ij)(w_j - w_i):
2403 // for the skew-symmetric advection matrix that is exactly
2404 // HALF the upwind flux.
2405 ith_dissipative_term_mass += dHij*(wj_mass-wi_mass);
2406 ith_low_order_dissipative_term_mass += dLowij*(wj_mass-wi_mass);
2407 // SAME dLow on the fluid mass -- symmetric, so it is
2408 // conservative, and identical between the two equations,
2409 // which is what the convex-combination identity needs.
2410 ith_low_order_dissipative_term_fluid += dLowij*(rhoj_fluid-rhoi_fluid);
2411 {
2412 const double aT = fabs(TransportMatrix[ij]);
2413 const double aTt = fabs(TransposeTransportMatrix[ij]);
2414 const double gam = dLowij - TransportMatrix[ij] - DiffusionMatrix[ij];
2415 dbg_sum_gamma += gam;
2416 dbg_min_gamma = fmin(dbg_min_gamma, gam);
2417 dbg_max_dLow = fmax(dbg_max_dLow, dLowij);
2418 dbg_max_absT = fmax(dbg_max_absT, aT);
2419 dbg_max_absTt = fmax(dbg_max_absTt, aTt);
2420 if (aTt > aT) dbg_n_from_transpose += 1;
2421 }
2422 //dHij - dLij. This matrix is needed during FCT step
2423 dt_times_dH_minus_dL[ij] = dt*(dHij - dLowij);
2424
2425 dLii -= dLij;
2426 dLow[ij] = dLowij;
2427
2428 }
2429 else //i==j
2430 {
2431 // NOTE: this is incorrect. Indeed, dLii = -sum_{j!=i}(dLij) and similarly for dCii.
2432 // However, it is irrelevant since during the FCT step we do (dL-dC)*(solnj-solni)
2433 dt_times_dH_minus_dL[ij]=0;
2434 dLow[ij]=0;
2435 }
2436 //update ij
2437 ij+=1;
2438 }
2439 double mi = ML.data()[i];
2440 // boundary_integral was assembled from m-space fluxes (rho*v*u and
2441 // a=theta*rho*Disp); no dmdu_i lifting is needed.
2442 const double boundary_integral_mass = boundary_integral[i];
2443 // compute edge_based_cfl
2444 // In the group variable the low-order update is
2445 // w_i^L = w_i + dt/(theta_i*mi) sum_{j!=i} gamma_ij (w_j - w_i),
2446 // a convex combination of {w_i, w_j} as long as
2447 // dt/(theta_i*mi) sum_j gamma_ij <= 1, gamma_ij = dLow-T-D.
2448 // So the storage Jacobian that has to divide 2|dLii|/mi is just
2449 // theta_i (dm/dw = theta), NOT the old dm/du = theta*(rho+u drho/du).
2450 // Using dm/du here was also one-sided: it is evaluated at node i,
2451 // while the undershoot bound needs the stencil minimum, which made
2452 // dt up to 19% too permissive at eps_rho = 0.235. theta_i has no
2453 // such solution dependence, so the bound is now exact.
2454 // theta_i = 1 recovers the original 2|dLii|/mi.
2455 edge_based_cfl.data()[i] = 2.*fabs(dLii)/(mi * theta_i);
2456
2457 // Stage 3 kinetic dissolution source at node i (mass-rate form):
2458 // R_diss_i = theta_w_i * rho_w(u_i) * k_d * S_n_i * (c_sat - u_i)
2459 // Added directly to mLow_i / mHigh_i since the lumped-mass time
2460 // discretization gives dm/dt = R_diss with no further scaling.
2461 // Sign of (c_sat - u_i) ensures R_diss > 0 when undersaturated
2462 // (dissolution) and < 0 when supersaturated (exsolution).
2463 // The S_w (interfacial-area) factor a_gw ~ S_n*S_w was dropped:
2464 // it makes R_diss vanish at S_n = 1, so a gas pool stops
2465 // dissolving once it consolidates. theta_w is kept so the CO2
2466 // still goes into the brine that exists (theta_w > 0 down to
2467 // residual S_wr). MUST stay consistent with mphase_co2.h.
2468 const double S_n_i = Sn_dof.data()[i];
2469 const double rho_w_i = rho_f * (1.0 + ((rho_s - rho_f)/rho_f) * ui_mass);
2470 const double R_diss_i = theta_i * rho_w_i * k_d * S_n_i
2471 * (c_sat - ui_mass);
2472
2473 const double mLow_i = mi_mass - dt/mi*(ith_flux_term_mass
2474 + boundary_integral_mass
2475 - ith_low_order_dissipative_term_mass)
2476 + dt * R_diss_i;
2477 // SCHEME B: advance the fluid mass with the SAME operator, then
2478 // take the concentration as the ratio. R_diss is added to BOTH:
2479 // dissolved CO2 mass joins the aqueous phase, so it raises the
2480 // solute mass and the fluid mass by the same amount, and
2481 // (m+d)/(M+d) stays in [u, 1] for d >= 0. (k_d = 0 by default,
2482 // so this is inert unless kinetic dissolution is switched on;
2483 // for EXSOLUTION, d < 0, the bound is not guaranteed.)
2484 const double MLow_i = fmax(M_dof.data()[i]
2485 - dt/mi*(ith_flux_term_fluid
2487 - ith_low_order_dissipative_term_fluid)
2488 + dt * R_diss_i,
2489 1.0e-14);
2490 M_low.data()[i] = MLow_i;
2491 uLow[i] = mLow_i/MLow_i;
2492
2493 // --- DMP diagnostic: report the first few violating nodes ---
2494 // Distinguishes the three possible causes in one run:
2495 // min_gamma < 0 -> a coefficient is negative (not an M-matrix)
2496 // coef > 1 -> dt exceeds the LOCAL stability limit
2497 // both fine, still >1 -> the violation is not from this update
2498 if (TADR_DMP_DBG && uLow[i] > 1.0 + 1.0e-10 && dbg_reported < 6 && dbg_budget > 0)
2499 {
2500 const double coef = dt*dbg_sum_gamma/fmax(theta_i*mi, 1.0e-300);
2501 std::cout << "TADR_DMP i=" << i
2502 << " uLow=" << uLow[i]
2503 << " wi=" << wi_mass
2504 << " theta=" << theta_i
2505 << " ML=" << mi
2506 << " dt=" << dt
2507 << " min_gamma=" << dbg_min_gamma
2508 << " coef=" << coef
2509 << " max_dLow=" << dbg_max_dLow
2510 << " max|T_ij|=" << dbg_max_absT
2511 << " max|T_ji|=" << dbg_max_absTt
2512 << " n_dLow_from_transpose=" << dbg_n_from_transpose
2513 << " bndry_int=" << boundary_integral_mass
2514 << std::endl;
2515 dbg_reported += 1; dbg_budget -= 1;
2516 }
2517 if (TADR_DMP_DBG)
2518 {
2519 const double coef = dt*dbg_sum_gamma/fmax(theta_i*mi, 1.0e-300);
2520 if (coef > dbg_global_max_coef) { dbg_global_max_coef = coef; dbg_argmax_coef = i; }
2521 if (dbg_min_gamma < dbg_global_min_gamma) dbg_global_min_gamma = dbg_min_gamma;
2522 }
2523
2524 // update residual
2525 if (LUMPED_MASS_MATRIX==1)
2526 {
2527 const double mHigh_i = mi_mass - dt/mi*(ith_flux_term_mass
2528 + boundary_integral_mass
2529 - ith_dissipative_term_mass)
2530 + dt * R_diss_i;
2531 // SCHEME B: the fluid mass is a single state, advanced ONCE
2532 // with the low-order operator. Only the SOLUTE mass carries
2533 // a high-order counterpart and gets the FCT treatment, so the
2534 // high-order concentration divides by the same MLow_i. Using
2535 // two different denominators for solH and uLow would make the
2536 // antidiffusive flux inconsistent with the bounds.
2537 globalResidual.data()[i] = mHigh_i/MLow_i;
2538 // Probe the HIGH-order solution too. uLow is known bounded;
2539 // if this one violates while uLow does not, the archived field
2540 // is the high-order solution and the FCT/low-order result is
2541 // being discarded downstream of FCTStep.
2542 if (TADR_DMP_DBG && globalResidual.data()[i] > 1.0 + 1.0e-10 && dbg_budget > 0)
2543 {
2544 std::cout << "TADR_DMP_HIGH i=" << i
2545 << " solH=" << globalResidual.data()[i]
2546 << " uLow=" << uLow[i]
2547 << " theta=" << theta_i
2548 << std::endl;
2549 dbg_budget -= 1;
2550 }
2551 }
2552 else
2553 globalResidual.data()[i] += dt*(ith_flux_term_mass - ith_dissipative_term_mass - R_diss_i);//cek todo: shouldn't this have boundaryIntegral?
2554 }//i
2555 if (TADR_DMP_DBG && dbg_reported > 0)
2556 std::cout << "TADR_DMP_SUMMARY dt=" << dt
2557 << " max_coef=" << dbg_global_max_coef
2558 << " at_dof=" << dbg_argmax_coef
2559 << " min_gamma_anywhere=" << dbg_global_min_gamma
2560 << " (coef<=1 and gamma>=0 => convex combination)"
2561 << std::endl;
2562 }//edge-based
2563 else if (STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
2564 {
2566 // IMPLICIT edge-based scheme (backward Euler, low-order graph //
2567 // dissipation, no FCT). Mirrors Richards STABILIZATION_TYPE==2 //
2568 // but evaluates the advection/diffusion at the CURRENT Newton //
2569 // iterate (u_dof) so they contribute to the Jacobian (assembled //
2570 // separately in calculateJacobian) and the scheme is NOT //
2571 // CFL-limited. Per-DOF residual: //
2572 // //
2573 // R_i = ML_i*(m_i^{n+1} - m_i^n)/dt //
2574 // + sum_j (T_ij + D_ij)*c_j (consistent flux) //
2575 // - sum_{j!=i} dLow_ij*(m_j^{n+1}-m_i^{n+1}) (graph diss) //
2576 // + boundary_integral_i (0 for closed BCs) //
2577 // - ML_i*R_diss_i (dissolution) //
2578 // //
2579 // m^{n+1}_i = theta_i*rho(c_i)*c_i (nodal, porosity lagged to //
2580 // theta_dof_proj); m^n_i = m_dof[i] (old projected mass). //
2581 // The advection coefficient in T uses the CURRENT-time velocity //
2582 // (q_v, refreshed from mphase_co2 before TADR solves) and the //
2583 // current iterate u -- fully implicit backward Euler. //
2584 // //
2585 // LOW-ORDER FLUX: the FULL-SPEED Kuzmin operator, identical in //
2586 // form to the one the explicit edge-based branch builds for uLow,//
2587 // but in the GROUP VARIABLE w = rho(u)*u and at the current //
2588 // Newton iterate: //
2589 // //
2590 // F_i = sum_j (T_ij + D_ij) w_j //
2591 // - sum_{j!=i} dLow_ij (w_j - w_i), //
2592 // dLow_ij = max(|T_ij|, |T_ji|) (symmetric) //
2593 // //
2594 // which telescopes to -sum_{j!=i} (dLow - T - D)_ij (w_j - w_i) //
2595 // with (dLow - T - D)_ij >= 0, i.e. an M-matrix (monotone, DMP), //
2596 // and is conservative because dLow is SYMMETRIC. //
2597 // //
2598 // THIS REPLACES the old F_i = -sum_{j!=i} a_ij (c_j - c_i) with//
2599 // a_ij = max(0,-T_ij)*(rho_up/rho_f) + max(0,-D_ij). That form //
2600 // is also an M-matrix, but for the skew-symmetric P1 advection //
2601 // matrix it is EXACTLY HALF the Kuzmin coefficient: on an edge //
2602 // with T_ij < 0 it applies |T_ij| where the Kuzmin operator //
2603 // applies dLow_ij - T_ij = 2|T_ij|. Verified node-for-node in a //
2604 // numpy replica (ratio 0.500 at every node). The consequence is //
2605 // not extra diffusion but HALVED TRANSPORT SPEED -- the scheme //
2606 // advects the front at half the physical rate, which is why the //
2607 // Elder plume reached the bottom later than it should. It also //
2608 // meant the FCT post-step antidiffused the symmetric dLow it //
2609 // never actually applied, a factor-2 mismatch. //
2610 // //
2611 // dLow[ij] (symmetric) is stashed for the FCT post-step and is //
2612 // now ALSO what calculateJacobian differentiates, so residual //
2613 // and Jacobian use one and the same operator. //
2614 // m^{n+1}_i=theta_i*rho(c_i)*c_i (nodal, porosity lagged); //
2615 // m^n_i=m_dof[i]. boundary_integral stays 0 (closed system); //
2616 // implicit boundary flux is a TODO. //
2619 // SCHEME B, implicit form. //
2620 // //
2621 // The fluid mass is KNOWN before the solute solve -- under //
2622 // option C it is Richards' theta*rho, supplied in M_dof -- and //
2623 // the solute is solved implicitly for u against it. Writing //
2624 // the two conservative equations //
2625 // ML(M^{n+1}u^{n+1} - M^n u^n)/dt + sum_j K_ij rho^n_j u^{n+1}_j
2626 // - sum_j d_ij rho^n_j (u^{n+1}_j - u^{n+1}_i) + B^s = 0 //
2627 // ML(M^{n+1} - M^n)/dt + sum_j K_ij rho^n_j //
2628 // - sum_j d_ij (rho^n_j - rho^n_i) + B^f = 0 //
2629 // and subtracting u^{n+1}_i times the second from the first //
2630 // cancels every row-sum term and leaves //
2631 // ML M^n (u_i - u^n_i)/dt //
2632 // - sum_{j!=i} gamma_ij rho^n_j (u_j - u_i) //
2633 // + (B^s_i - u_i B^f_i) - ML R_diss_i = 0 //
2634 // with gamma_ij = d_ij - K_ij >= 0. That is an M-matrix with a //
2635 // positive diagonal, so backward Euler is UNCONDITIONALLY //
2636 // bounded -- no CFL, and no divergence-free assumption on v. //
2637 // //
2638 // The cancellation is REVERSIBLE, so solving this form for u is //
2639 // algebraically identical to solving the two conservative //
2640 // equations -- PROVIDED the M it is handed satisfies the second //
2641 // one. Under option C it does not exactly (it satisfies //
2642 // Richards' continuity instead), and that gap, not the //
2643 // cancellation, is where conservation is lost. See the option //
2644 // C note below. //
2645 // //
2646 // This replaces BOTH the half-upwind stopgap (a_ij = //
2647 // max(0,-T_ij), bounded but exactly HALF the physical transport //
2648 // speed) and the full-speed consistent form that preceded it //
2649 // (correct speed, but max u = 4.25 on Elder from a u <= 1 IC). //
2650 // gamma_ij is the FULL-SPEED coefficient: for a skew T it is //
2651 // exactly 2*max(0,-T_ij), i.e. twice the stopgap. //
2653 // --- fluid mass: OPTION C, read from the flow model --------------
2654 //
2655 // There is no fluid system assembled or solved here any more. M_dof
2656 // arrives already holding Richards' old-time mass, refreshed on the
2657 // Python side (TADR.LevelModel._refreshFluidMassFromFlow) before this
2658 // kernel runs, and it serves as the old-time storage coefficient M^n_i
2659 // ONLY. Richards evaluates it with the OLD density (the mass its
2660 // previous step produced), so it is theta(psi^n)*rho(c^{n-1}), not
2661 // theta*rho(c^n), and M_j/theta_j is no longer this step's density. The flux density is
2662 // rho_j = rho(c^n_j) from the EOS at the node (rho_dof_proj), which is
2663 // exactly the nodal density Richards advected with this step.
2664 //
2665 // What this replaces: the fluid mass used to be advanced here as its
2666 // own unknown. Explicitly it inherited an explicit CFL (past it M
2667 // went NEGATIVE, rho = M/theta flipped sign, the solute off-diagonals
2668 // -gamma_ij*rho_j turned POSITIVE and boundedness died -- replica at
2669 // 10x the limit: min M = -6.5e52, max u = 2.2e25). Implicitly it
2670 // needed a linear solve, and the sub-cycler that supplied one cost
2671 // S = 100+ matvec + ghost-scatter collectives per step on the 20 yr
2672 // Elder run. Richards is already solving this equation; solving a
2673 // second, slightly different copy of it was the expensive part.
2674 //
2675 // WHAT IT COSTS. The cancelled solute form below is algebraically
2676 // equivalent to the conservative pair only when M satisfies THIS
2677 // model's discrete fluid equation (same K, same d, same B^f).
2678 // Richards' m satisfies Richards' discrete continuity equation
2679 // instead. The gap is the flow/transport continuity defect, which on
2680 // the 20 yr Elder run grew monotonically from 1.4e-16 to 3.6e-2. So
2681 // conservation here is to that defect, NOT to round-off; the
2682 // [TADR-MASS] log reports the consequence every step.
2683 //
2684 // BOUNDEDNESS is untouched and still unconditional: the form below is
2685 // an M-matrix for ANY strictly positive M and rho, since gamma_ij >= 0,
2686 // rho_j = rho(c^n_j) > 0, and M^n > 0 whenever Richards keeps theta*rho
2687 // positive. The cancellation needs the SAME rho in the solute and the
2688 // fluid flux, not rho = M/theta.
2689 //
2690 // --- solute: implicit, in the cancelled (bounded) form ---------
2691 int ij=0;
2692 for (int i=0; i<numDOFs; i++)
2693 {
2694 const double ci = u_dof.data()[i];
2695 const double theta_i = fmax(theta_dof_proj[i], 1.0e-14);
2696 const double Mn_i = fmax(M_dof.data()[i], 1.0e-14);
2697 const double un_i = m_dof[i]/Mn_i; // = u_dof_old[i] exactly
2698 const double MLi = ML.data()[i];
2699 const double rho_i = rho_dof_proj[i];
2700
2701 double ith_upwind_flux_term_mass = 0.0;
2702 double ith_flux_term_fluid = 0.0; // continuity-defect probe
2703 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
2704 {
2705 int j = csrColumnOffsets_DofLoops.data()[offset];
2706 // rho(c^n_j) from the EOS at the node -- the same nodal density
2707 // Richards advected with. The solute flux and the fluid flux
2708 // below use this ONE density, which is what the cancellation
2709 // needs.
2710 const double rhoj = rho_dof_proj[j];
2711 if (USE_EDGE_FLUX)
2712 {
2713 // FLOW-MODEL FLUXES: K_ij = A_ij + D_ij with A_ij = -F_ij/2,
2714 // F the flow model's mass flux into i from j (F_ji = -F_ij,
2715 // so A_ji = +F_ij/2), and D the dispersion on c assembled in
2716 // the element loop. F is already a mass flux, so there is
2717 // no rho_j factor. The same graph viscosity then gives
2718 // gamma_ij = max(F_ij,0) + (dispersion part): upwinding on
2719 // the flow model's own fluxes.
2720 if (i != j)
2721 {
2722 const double cj = u_dof.data()[j];
2723 const double Fij = USE_EDGE_VELOCITY
2725 : edgeFlux.data()[ij];
2726 // calculateJacobian reads the flux the residual applied
2727 if (USE_EDGE_VELOCITY)
2728 edgeFlux.data()[ij] = Fij;
2729 const double Kij = -0.5*Fij + TransportMatrix[ij] + DiffusionMatrix[ij];
2730 const double Kji = 0.5*Fij + TransposeTransportMatrix[ij] + DiffusionMatrix[ij];
2731 const double dLow_ij = fmax(0.0, fmax(Kij, Kji));
2732 const double gamma = dLow_ij - Kij; // >= 0 by construction
2733 ith_upwind_flux_term_mass += -gamma*(cj - ci);
2734 ith_flux_term_fluid -= Fij;
2735 dLow.data()[ij] = dLow_ij;
2736 dt_times_dH_minus_dL.data()[ij] = dt*(0.0 - dLow_ij);
2737 }
2738 else
2739 {
2740 dLow.data()[ij] = 0.0;
2741 dt_times_dH_minus_dL.data()[ij] = 0.0;
2742 // A_ii - A_ii
2743 if (USE_EDGE_VELOCITY)
2744 edgeFlux.data()[ij] = 0.0;
2745 }
2746 ij += 1;
2747 continue;
2748 }
2749 // Fluid flux, assembled EXACTLY as the explicit branch does it:
2750 // K over every j (diagonal included), dLow only off-diagonal.
2751 ith_flux_term_fluid += (TransportMatrix[ij] + DiffusionMatrix[ij])*rhoj;
2752 if (i != j)
2753 {
2754 const double cj = u_dof.data()[j];
2755 const double Kij = TransportMatrix[ij] + DiffusionMatrix[ij];
2756 const double Kji = TransposeTransportMatrix[ij] + DiffusionMatrix[ij];
2757 const double dLow_ij = fmax(0.0, fmax(Kij, Kji));
2758 const double gamma = dLow_ij - Kij; // >= 0 by construction
2759 ith_upwind_flux_term_mass += -gamma*rhoj*(cj - ci);
2760 ith_flux_term_fluid -= dLow_ij*(rhoj - rho_i);
2761 // dLow (symmetric) is what the FCT post-step antidiffuses;
2762 // it must be the viscosity the residual ACTUALLY applied,
2763 // which is now the case (the half-upwind form applied a_ij
2764 // while FCT removed dLow -- a factor-2 mismatch).
2765 dLow.data()[ij] = dLow_ij;
2766 dt_times_dH_minus_dL.data()[ij] = dt*(0.0 - dLow_ij);
2767 }
2768 else
2769 {
2770 dLow.data()[ij] = 0.0;
2771 dt_times_dH_minus_dL.data()[ij] = 0.0;
2772 }
2773 ij += 1;
2774 }
2775 // Stage-3 kinetic dissolution source (mass-rate form); MUST match
2776 // mphase_co2.h and the explicit edge-based branch above.
2777 const double S_n_i = Sn_dof.data()[i];
2778 const double rho_w_i = rho_f*(1.0 + ((rho_s - rho_f)/rho_f)*ci);
2779 const double R_diss_i = theta_i * rho_w_i * k_d * S_n_i * (c_sat - ci);
2780 // Exported for the flow model: at the converged iterate this is
2781 // rho(c^{n+1}_i), the nodal density Richards uses next step.
2782 rho_nodal.data()[i] = rho_w_i;
2783
2784 if (USE_EDGE_FLUX)
2785 {
2786 // The flow model's boundary exchange. Outflow (B < 0) leaves
2787 // with c_i and cancels against the fluid equation; inflow
2788 // brings the boundary concentration, a convex pull toward it.
2789 // With the edge velocity, B_i is what the assembled F leaves of
2790 // the carried mass change (ith_flux_term_fluid = -sum_j F_ij).
2791 if (USE_EDGE_VELOCITY)
2792 nodalBoundaryFlux.data()[i] = MLi*(M_low.data()[i] - M_dof.data()[i])/dt
2793 + ith_flux_term_fluid;
2794 const double B_i = nodalBoundaryFlux.data()[i];
2795 const double c_in = (cin_den[i] > 0.0) ? cin_num[i]/cin_den[i] : ci;
2796 globalResidual.data()[i] = MLi*Mn_i*(ci - un_i)/dt
2797 + ith_upwind_flux_term_mass
2799 - fmax(B_i, 0.0)*(c_in - ci)
2800 - MLi*R_diss_i
2801 - MLi*nodalSource.data()[i];
2802 // the flow model's fluid flux, so the continuity defect against
2803 // the carried M^{n+1} is round-off by construction
2804 fluidResidual.data()[i] = ith_flux_term_fluid - B_i;
2805 continue;
2806 }
2807 globalResidual.data()[i] = MLi*Mn_i*(ci - un_i)/dt
2808 + ith_upwind_flux_term_mass
2811 - MLi*R_diss_i;
2812 // Everything in TADR's fluid equation EXCEPT the storage term; the
2813 // storage needs M^{n+1}, which only the flow model has.
2814 fluidResidual.data()[i] = ith_flux_term_fluid
2816 - MLi*R_diss_i;
2817 }//i
2818 }//implicit edge-based
2819 }
2820
2822 {
2823 int numDOFs = args.scalar<int>("numDOFs");
2824 xt::pyarray<double>& mIn = args.array<double>("mIn");
2825 xt::pyarray<double>& uOut = args.array<double>("uOut");
2826 xt::pyarray<double>& nodal_porosity = args.array<double>("nodal_porosity");
2827 xt::pyarray<double>& M_dof_fct = args.array<double>("M_dof_fct");
2828 xt::pyarray<double>& M_low_fct = args.array<double>("M_low_fct");
2829 // OUT (ImplicitEV only): the residual left rho of the UNLIMITED iterate here;
2830 // the flow model must see rho of the limited c.
2831 xt::pyarray<double>& rho_nodal = args.array<double>("rho_nodal");
2832 const double rho_f = args.scalar<double>("rho_f");
2833 const double rho_s = args.scalar<double>("rho_s");
2834 STABILIZATION STABILIZATION_TYPE = static_cast<STABILIZATION>(args.scalar<int>("STABILIZATION_TYPE"));
2835 const bool implicitM = (STABILIZATION_TYPE == STABILIZATION::ImplicitEV);
2836 // ImplicitEV with the flow model's fluxes carries M^{n+1} in M_low; without
2837 // them it has no new-time mass and uses M^n. Must match FCTStep.
2838 const bool newM_is_old = implicitM && !args.scalar<int>("USE_EDGE_FLUX");
2839 // The scheme-B branches limited S = M*c, so the inverse is a division by the
2840 // SAME new-time mass -- no EOS round-trip. Must match FCTStep's useM set.
2841 if (implicitM or
2842 STABILIZATION_TYPE == STABILIZATION::EntropyViscosity or
2843 STABILIZATION_TYPE == STABILIZATION::SmoothnessIndicator or
2844 STABILIZATION_TYPE == STABILIZATION::Kuzmin)
2845 for (int i=0; i<numDOFs; i++)
2846 uOut.data()[i] = mIn.data()[i]/fmax((newM_is_old ? M_dof_fct : M_low_fct).data()[i], 1.0e-14);
2847 else
2848 for (int i=0; i<numDOFs; i++)
2849 uOut.data()[i] = inversevaluateCoefficients(mIn.data()[i], nodal_porosity.data()[i], rho_f, rho_s);
2850 if (implicitM)
2851 for (int i=0; i<numDOFs; i++)
2852 rho_nodal.data()[i] = rho_f*(1.0 + ((rho_s - rho_f)/rho_f)*uOut.data()[i]);
2853 }
2854
2855
2857 {
2858 xt::pyarray<double>& mesh_trial_ref = args.array<double>("mesh_trial_ref");
2859 xt::pyarray<double>& mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
2860 xt::pyarray<double>& mesh_dof = args.array<double>("mesh_dof");
2861 xt::pyarray<double>& mesh_velocity_dof = args.array<double>("mesh_velocity_dof");
2862 double MOVING_DOMAIN = args.scalar<double>("MOVING_DOMAIN");
2863 xt::pyarray<int>& mesh_l2g = args.array<int>("mesh_l2g");
2864 xt::pyarray<double>& dV_ref = args.array<double>("dV_ref");
2865 xt::pyarray<double>& u_trial_ref = args.array<double>("u_trial_ref");
2866 xt::pyarray<double>& u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
2867 xt::pyarray<double>& u_test_ref = args.array<double>("u_test_ref");
2868 xt::pyarray<double>& u_grad_test_ref = args.array<double>("u_grad_test_ref");
2869 xt::pyarray<double>& mesh_trial_trace_ref = args.array<double>("mesh_trial_trace_ref");
2870 xt::pyarray<double>& mesh_grad_trial_trace_ref = args.array<double>("mesh_grad_trial_trace_ref");
2871 xt::pyarray<double>& dS_ref = args.array<double>("dS_ref");
2872 xt::pyarray<double>& u_trial_trace_ref = args.array<double>("u_trial_trace_ref");
2873 xt::pyarray<double>& u_grad_trial_trace_ref = args.array<double>("u_grad_trial_trace_ref");
2874 xt::pyarray<double>& u_test_trace_ref = args.array<double>("u_test_trace_ref");
2875 xt::pyarray<double>& u_grad_test_trace_ref = args.array<double>("u_grad_test_trace_ref");
2876 xt::pyarray<double>& normal_ref = args.array<double>("normal_ref");
2877 xt::pyarray<double>& boundaryJac_ref = args.array<double>("boundaryJac_ref");
2878 int nElements_global = args.scalar<int>("nElements_global");
2879 double useMetrics = args.scalar<double>("useMetrics");
2880 double alphaBDF = args.scalar<double>("alphaBDF");
2881 int lag_shockCapturing = args.scalar<int>("lag_shockCapturing");
2882 double shockCapturingDiffusion = args.scalar<double>("shockCapturingDiffusion");
2883 xt::pyarray<int>& u_l2g = args.array<int>("u_l2g");
2884 xt::pyarray<int>& r_l2g = args.array<int>("r_l2g");
2885 xt::pyarray<double>& elementDiameter = args.array<double>("elementDiameter");
2886 xt::pyarray<double>& u_dof = args.array<double>("u_dof");
2887 xt::pyarray<double>& velocity = args.array<double>("velocity");
2888 xt::pyarray<double>& q_porosity = args.array<double>("q_porosity");
2889 xt::pyarray<double>& q_rho = args.array<double>("q_rho");
2890 xt::pyarray<double>& q_m_betaBDF = args.array<double>("q_m_betaBDF");
2891 xt::pyarray<double>& cfl = args.array<double>("cfl");
2892 xt::pyarray<double>& q_numDiff_u_last = args.array<double>("q_numDiff_u_last");
2893 xt::pyarray<int>& csrRowIndeces_u_u = args.array<int>("csrRowIndeces_u_u");
2894 xt::pyarray<int>& csrColumnOffsets_u_u = args.array<int>("csrColumnOffsets_u_u");
2895 xt::pyarray<double>& globalJacobian = args.array<double>("globalJacobian");
2896 int nExteriorElementBoundaries_global = args.scalar<int>("nExteriorElementBoundaries_global");
2897 xt::pyarray<int>& exteriorElementBoundariesArray = args.array<int>("exteriorElementBoundariesArray");
2898 xt::pyarray<int>& elementBoundaryMaterialTypes = args.array<int>("elementBoundaryMaterialTypes");
2899 xt::pyarray<int>& isExteriorBoundaryPhysical = args.array<int>("isExteriorBoundaryPhysical");
2900 xt::pyarray<int>& elementBoundaryElementsArray = args.array<int>("elementBoundaryElementsArray");
2901 xt::pyarray<int>& elementBoundaryLocalElementBoundariesArray = args.array<int>("elementBoundaryLocalElementBoundariesArray");
2902 xt::pyarray<double>& ebqe_velocity_ext = args.array<double>("ebqe_velocity_ext");
2903 xt::pyarray<int>& isDOFBoundary_u = args.array<int>("isDOFBoundary_u");
2904 xt::pyarray<double>& ebqe_bc_u_ext = args.array<double>("ebqe_bc_u_ext");
2905 xt::pyarray<int>& isFluxBoundary_u = args.array<int>("isFluxBoundary_u");
2906 xt::pyarray<double>& ebqe_bc_flux_u_ext = args.array<double>("ebqe_bc_flux_u_ext");
2907 xt::pyarray<double>& ebqe_porosity = args.array<double>("ebqe_porosity");
2908 xt::pyarray<double>& ebqe_rho = args.array<double>("ebqe_rho");
2909 xt::pyarray<int>& csrColumnOffsets_eb_u_u = args.array<int>("csrColumnOffsets_eb_u_u");
2910 STABILIZATION STABILIZATION_TYPE = static_cast<STABILIZATION>(args.scalar<int>("STABILIZATION_TYPE"));
2911// ENTROPY ENTROPY_TYPE = static_cast<ENTROPY>(args.scalar<int>("ENTROPY_TYPE"));
2912// STABILIZATION STABILIZATION_TYPE{args.scalar<int>("STABILIZATION_TYPE")};
2913 double physicalDiffusion = args.scalar<double>("physicalDiffusion");
2914 const double alpha_L = args.scalar<double>("alpha_L");
2915 const double alpha_T = args.scalar<double>("alpha_T");
2916 const double Dm = args.scalar<double>("Dm");
2917 int forceStrongConditions = args.scalar<int>("forceStrongConditions");
2918 // const int dispersion_type_int = args.scalar<int>("dispersion_type");
2919 // const double theta_s = args.scalar<double>("theta_s");
2920 // const double theta_r = args.scalar<double>("theta_r");
2921 // const double power_law_exponent = args.scalar<double>("power_law_exponent");
2922 // const double velocity_exponent = args.scalar<double>("velocity_exponent");
2923 const double rho_f = args.scalar<double>("rho_f");
2924 const double rho_s = args.scalar<double>("rho_s");
2925
2926 // DISPERSION DISPERSION_TYPE = static_cast<DISPERSION>(dispersion_type_int);
2927
2928
2929 double Ct_sge = 4.0;
2930
2931
2932
2934 xt::pyarray<int>& a_rowptr = args.array<int>("a_rowptr");
2935 xt::pyarray<int>& a_colind = args.array<int>("a_colind");
2936 //xt::pyarray<double>& D = args.array<double>("D");
2938 xt::pyarray<int>& isDiffusiveFluxBoundary_u = args.array<int>("isDiffusiveFluxBoundary_u");
2939 xt::pyarray<double>& ebqe_penalty_ext = args.array<double>("ebqe_penalty_ext");
2940
2942 // ImplicitEV (STAB=5): assemble the implicit edge-based Jacobian in //
2943 // THIS function (unlike Richards, which builds it inside the //
2944 // residual). It reads the transport/diffusion matrices and nodal //
2945 // projections (theta_dof_proj) that the immediately preceding //
2946 // calculateResidual call filled -- Proteus Newton evaluates F(u) //
2947 // then J(u) at the same iterate -- plus the frozen per-edge upwind //
2948 // coefficient a_ij the residual stashed in dLow[ij]. Single-comp P1 //
2949 // => the DOF-loop CSR coincides with the matrix CSR, so globalJacobian//
2950 // is indexed by the same running offset 'ij' as the residual //
2951 // (identical to the Richards STAB==2 convention). //
2952 // //
2953 // Differentiating the upwind flux F_i = sum_{j!=i} -a_ij*(c_j-c_i) //
2954 // with a_ij frozen gives a clean M-matrix: //
2955 // J_ij = -a_ij (j != i, <= 0) //
2956 // J_ii = ML_i*dmdu_i/dt + sum_{j!=i} a_ij - ML_i*dRdiss_i/dc_i //
2957 // dmdu_i = theta_i*(rho(c_i)+c_i*drho_du), rho(c)=rho_f(1+eps*c). //
2958 // a_ij carries the upwind density/diffusion weighting; freezing it //
2959 // (and the O(eps) rho_up dependence) is the only inexactness //
2960 // (standard inexact-Newton, as Richards freezes Kr/psi). //
2962 if (STABILIZATION_TYPE==STABILIZATION::ImplicitEV)
2963 {
2964 const double dt = args.scalar<double>("dt");
2965 const int numDOFs = args.scalar<int>("numDOFs");
2966 xt::pyarray<double>& ML = args.array<double>("ML");
2967 xt::pyarray<double>& dLow = args.array<double>("dLow");
2968 xt::pyarray<double>& Sn_dof = args.array<double>("Sn_dof");
2969 const double k_d = args.scalar<double>("k_d");
2970 const double c_sat = args.scalar<double>("c_sat");
2971 xt::pyarray<int>& csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
2972 xt::pyarray<int>& csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
2973 // OPTION C: the old-time fluid mass, read from Richards. The
2974 // immediately preceding calculateResidual filled theta_dof_proj,
2975 // rho_dof_proj and boundary_integral_fluid (all class members), and
2976 // Proteus Newton evaluates F(u) then J(u) at the same iterate, so they
2977 // are current.
2978 xt::pyarray<double>& M_dof = args.array<double>("M_dof");
2979 // FLOW-MODEL FLUXES, see calculateResidual; cin_num/cin_den are the
2980 // members the preceding residual call filled.
2981 xt::pyarray<double>& edgeFlux = args.array<double>("edgeFlux");
2982 xt::pyarray<double>& nodalBoundaryFlux = args.array<double>("nodalBoundaryFlux");
2983 const int USE_EDGE_FLUX = args.scalar<int>("USE_EDGE_FLUX");
2984 const double drho_du = rho_s - rho_f;
2985 // SCHEME B Jacobian, matching the cancelled residual term for term:
2986 // R_i = ML M^n_i (c_i - c^n_i)/dt
2987 // - sum_{j!=i} gamma_ij rho^n_j (c_j - c_i)
2988 // + B^s_i - c_i B^f_i - ML R_diss_i
2989 // so
2990 // J_ij = -gamma_ij rho^n_j (j != i, <= 0)
2991 // J_ii = ML M^n_i/dt + sum_j gamma_ij rho^n_j
2992 // - B^f_i - ML dR_diss/dc_i
2993 // gamma_ij = dLow_ij - K_ij >= 0 and rho^n_j > 0, so this is an
2994 // M-matrix UNCONDITIONALLY -- it does not depend on the row sums,
2995 // on dt, or on the velocity being divergence free. gamma and rho^n
2996 // are frozen under differentiation (rho^n = rho(c^n) is genuinely
2997 // independent of the iterate: it is evaluated from the old-time
2998 // concentration, so freezing it is EXACT here, not an inexact-Newton
2999 // approximation).
3000 int ij=0;
3001 for (int i=0; i<numDOFs; i++)
3002 {
3003 const double ci = u_dof.data()[i];
3004 const double theta_i = fmax(theta_dof_proj[i], 1.0e-14);
3005 const double rho_ci = rho_f*(1.0 + (drho_du/rho_f)*ci);
3006 const double MLi = ML.data()[i];
3007 const double Mn_i = fmax(M_dof.data()[i], 1.0e-14);
3008 const double S_n_i = Sn_dof.data()[i];
3009 // dR_diss_i/dc_i = theta_i*k_d*S_n_i*[ drho_du*(c_sat-c_i) - rho(c_i) ]
3010 const double dRdiss_dci = theta_i*k_d*S_n_i*( drho_du*(c_sat - ci) - rho_ci );
3011
3012 int diag_ij = -1;
3013 double sum_gamma_rho = 0.0;
3014 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
3015 {
3016 int j = csrColumnOffsets_DofLoops.data()[offset];
3017 if (i != j)
3018 {
3019 // rho(c^n_j) at the node, matching the residual's flux
3020 // coefficient; the flow-model fluxes are mass fluxes (rho 1)
3021 const double rhoj = USE_EDGE_FLUX ? 1.0 : rho_dof_proj[j];
3022 const double Fij = USE_EDGE_FLUX ? edgeFlux.data()[ij] : 0.0;
3023 const double Kij = -0.5*Fij + TransportMatrix[ij] + DiffusionMatrix[ij];
3024 const double Kji = 0.5*Fij + TransposeTransportMatrix[ij] + DiffusionMatrix[ij];
3025 const double dLow_ij = fmax(0.0, fmax(Kij, Kji));
3026 const double gamma = dLow_ij - Kij;
3027 globalJacobian.data()[ij] += -gamma*rhoj;
3028 sum_gamma_rho += gamma*rhoj;
3029 }
3030 else
3031 diag_ij = ij;
3032 ij += 1;
3033 }
3034 // inflow at a node with a boundary concentration: d/dc_i of
3035 // -max(B_i,0)*(c_in - c_i); zero where c_in is c_i itself
3036 const double dBoundary_dci = USE_EDGE_FLUX
3037 ? ((cin_den[i] > 0.0) ? fmax(nodalBoundaryFlux.data()[i], 0.0) : 0.0)
3039 globalJacobian.data()[diag_ij] += MLi*Mn_i/dt
3040 + sum_gamma_rho
3041 + dBoundary_dci
3042 - MLi*dRdiss_dci;
3043 }//i
3044
3045 //
3046 // Implicit boundary flux Jacobian: d(boundary flux)/du -> globalJacobian
3047 // so the boundary is implicit (like Richards), consistent with the
3048 // boundary residual the calculateResidual ImplicitEV path stashes in
3049 // boundary_integral. fluxJacobian accumulates over the face
3050 // quadrature and is loaded ONCE per face (the residual side likewise
3051 // distributes once). For closed BCs (zero adv/diff flux, no
3052 // Dirichlet) every term here is identically 0.
3053 //
3054 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++)
3055 {
3056 int ebN = exteriorElementBoundariesArray.data()[ebNE];
3057 const int eN_out = elementBoundaryElementsArray.data()[ebN*2+1];
3058 const int ebFlag = elementBoundaryMaterialTypes.data()[ebN];
3059 if (ebFlag <= 0 || isExteriorBoundaryPhysical.data()[ebNE] == 0 || eN_out >= 0)
3060 continue;
3061 int eN = elementBoundaryElementsArray.data()[ebN*2+0],
3062 ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN*2+0],
3063 eN_nDOF_trial_element = eN*nDOF_trial_element;
3064 double fluxJacobian_u_u[nDOF_test_element][nDOF_trial_element];
3065 for (int i=0;i<nDOF_test_element;i++)
3066 for (int j=0;j<nDOF_trial_element;j++)
3067 fluxJacobian_u_u[i][j]=0.0;
3068 for (int kb=0;kb<nQuadraturePoints_elementBoundary;kb++)
3069 {
3070 int ebNE_kb = ebNE*nQuadraturePoints_elementBoundary+kb,
3071 ebNE_kb_nSpace = ebNE_kb*nSpace,
3072 ebN_local_kb = ebN_local*nQuadraturePoints_elementBoundary+kb,
3073 ebN_local_kb_nSpace = ebN_local_kb*nSpace;
3074 double u_ext=0.0, grad_u_ext[nSpace], m_ext=0.0, dm_ext=0.0,
3075 f_ext[nSpace], df_ext[nSpace], a_ext[nnz], da_ext[nnz],
3076 bc_a_ext[nnz], bc_da_ext[nnz], difffluxjacobian_ext=0.0,
3077 bc_u_ext=0.0, bc_m_ext=0.0, bc_dm_ext=0.0,
3078 bc_f_ext[nSpace], bc_df_ext[nSpace],
3079 jac_ext[nSpace*nSpace], jacDet_ext, jacInv_ext[nSpace*nSpace],
3080 boundaryJac[nSpace*(nSpace-1)], metricTensor[(nSpace-1)*(nSpace-1)],
3081 metricTensorDetSqrt, dS, u_test_dS[nDOF_test_element],
3082 u_grad_trial_trace[nDOF_trial_element*nSpace],
3083 u_grad_test_dS[nDOF_trial_element*nSpace], normal[nSpace],
3084 x_ext,y_ext,z_ext,xt_ext,yt_ext,zt_ext,integralScaling,
3085 G[nSpace*nSpace],G_dd_G,tr_G;
3086 ck.calculateMapping_elementBoundary(eN,ebN_local,kb,ebN_local_kb,mesh_dof.data(),mesh_l2g.data(),mesh_trial_trace_ref.data(),mesh_grad_trial_trace_ref.data(),boundaryJac_ref.data(),jac_ext,jacDet_ext,jacInv_ext,boundaryJac,metricTensor,metricTensorDetSqrt,normal_ref.data(),normal,x_ext,y_ext,z_ext);
3087 ck.calculateMappingVelocity_elementBoundary(eN,ebN_local,kb,ebN_local_kb,mesh_velocity_dof.data(),mesh_l2g.data(),mesh_trial_trace_ref.data(),xt_ext,yt_ext,zt_ext,normal,boundaryJac,metricTensor,integralScaling);
3088 dS = ((1.0-MOVING_DOMAIN)*metricTensorDetSqrt + MOVING_DOMAIN*integralScaling)*dS_ref.data()[kb];
3089 ck.calculateG(jacInv_ext,G,G_dd_G,tr_G);
3090 ck.gradTrialFromRef(&u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace*nDOF_trial_element],jacInv_ext,u_grad_trial_trace);
3091 ck.valFromDOF(u_dof.data(),&u_l2g.data()[eN_nDOF_trial_element],&u_trial_trace_ref.data()[ebN_local_kb*nDOF_test_element],u_ext);
3092 ck.gradFromDOF(u_dof.data(),&u_l2g.data()[eN_nDOF_trial_element],u_grad_trial_trace,grad_u_ext);
3093 for (int j=0;j<nDOF_trial_element;j++)
3094 {
3095 u_test_dS[j] = u_test_trace_ref.data()[ebN_local_kb*nDOF_test_element+j]*dS;
3096 for (int I=0;I<nSpace;I++)
3097 u_grad_test_dS[j*nSpace+I]= u_grad_trial_trace[j*nSpace+I]*dS;
3098 }
3099 bc_u_ext = isDOFBoundary_u.data()[ebNE_kb]*ebqe_bc_u_ext.data()[ebNE_kb]+(1-isDOFBoundary_u.data()[ebNE_kb])*u_ext;
3100 double rho_out_ext=0.0,rho_out_bc=0.0;
3101 evaluateCoefficients(a_rowptr.data(),a_colind.data(),&ebqe_velocity_ext.data()[ebNE_kb_nSpace],alpha_L,alpha_T,Dm,ebqe_porosity.data()[ebNE_kb],rho_f,rho_s,u_ext,rho_out_ext,m_ext,dm_ext,f_ext,df_ext,a_ext,da_ext);
3102 evaluateCoefficients(a_rowptr.data(),a_colind.data(),&ebqe_velocity_ext.data()[ebNE_kb_nSpace],alpha_L,alpha_T,Dm,ebqe_porosity.data()[ebNE_kb],rho_f,rho_s,bc_u_ext,rho_out_bc,bc_m_ext,bc_dm_ext,bc_f_ext,bc_df_ext,bc_a_ext,bc_da_ext);
3103 double mesh_velocity[3]; mesh_velocity[0]=xt_ext; mesh_velocity[1]=yt_ext; mesh_velocity[2]=zt_ext;
3104 for (int I=0;I<nSpace;I++)
3105 {
3106 f_ext[I] -= MOVING_DOMAIN*m_ext*mesh_velocity[I];
3107 df_ext[I] -= MOVING_DOMAIN*dm_ext*mesh_velocity[I];
3108 bc_f_ext[I] -= MOVING_DOMAIN*bc_m_ext*mesh_velocity[I];
3109 bc_df_ext[I] -= MOVING_DOMAIN*bc_dm_ext*mesh_velocity[I];
3110 }
3111 // GROUP VARIABLE: the ImplicitEV boundary residual is now the
3112 // adjoint of the w-operator, so differentiate w.r.t. w (using
3113 // df/dw = v and a_w) and apply the chain rule dw/dc at the end.
3114 // dw/dc is frozen at the quadrature trace -- the same inexact-
3115 // Newton simplification used for the interior a_ij.
3116 const double drho_du_jb = rho_f*((rho_s - rho_f)/rho_f);
3117 const double dwdu_ext_j = fmax(rho_out_ext + u_ext*drho_du_jb, 1.0e-14);
3118 double a_w_ext_j[nnz], zero_da_ext_j[nnz];
3119 for (int ii=0; ii<a_rowptr.data()[nSpace]; ii++)
3120 { a_w_ext_j[ii] = a_ext[ii]/dwdu_ext_j; zero_da_ext_j[ii] = 0.0; }
3121 const double* v_w_ext_j = &ebqe_velocity_ext.data()[ebNE_kb_nSpace];
3122 // Upwinded outflow face of calculateResidual: the solute flux is
3123 // c_i (v.n) rho_trace with rho_trace from the frozen nodal
3124 // rho(c^n), so its derivative is diagonal and replaces the
3125 // consistent trace derivative (v.n) dw/du w_j.
3126 double flow_w_j = 0.0;
3127 for (int I=0;I<nSpace;I++)
3128 flow_w_j += normal[I]*v_w_ext_j[I];
3129 const bool outflow_upwind_j = flow_w_j >= 0.0 &&
3130 ((isDOFBoundary_u.data()[ebNE_kb] == 1 && forceStrongConditions == 0) ||
3131 (isDOFBoundary_u.data()[ebNE_kb] != 1 && isFluxBoundary_u.data()[ebNE_kb] != 1));
3132 double rho_trace_j = 0.0;
3133 if (outflow_upwind_j && !USE_EDGE_FLUX)
3134 for (int j=0;j<nDOF_trial_element;j++)
3135 rho_trace_j += u_trial_trace_ref.data()[ebN_local_kb*nDOF_test_element+j]
3136 * rho_dof_proj[u_l2g.data()[eN_nDOF_trial_element+j]];
3137 for (int i=0;i<nDOF_test_element;i++)
3138 for (int j=0;j<nDOF_trial_element;j++)
3139 {
3140 int ebN_local_kb_j=ebN_local_kb*nDOF_trial_element+j;
3141 double advJacobian_ext = 0.0, diffJacobian_ext = 0.0;
3142 if (USE_EDGE_FLUX)
3143 {
3144 // FLOW-MODEL FLUXES: only the dispersive flux is left
3145 // at the boundary, and it acts on c directly. On a
3146 // weak-Dirichlet face that is the lumped penalty
3147 // gamma_i (c_i - g) of calculateResidual: diagonal only,
3148 // with a = theta*rho(c)*D frozen as zero_da freezes it
3149 // in the IIPG Jacobian this replaces. A flux BC is
3150 // data and a free face carries none.
3151 if (j == i &&
3152 isDOFBoundary_u.data()[ebNE_kb] == 1 &&
3153 isDiffusiveFluxBoundary_u.data()[ebNE_kb] == 0)
3154 {
3155 double max_a = 0.0;
3156 for (int m=0; m<a_rowptr.data()[nSpace]; m++)
3157 max_a = fmax(max_a, a_ext[m]);
3158 fluxJacobian_u_u[i][j] += max_a*ebqe_penalty_ext.data()[ebNE_kb]*u_test_dS[i];
3159 }
3160 continue;
3161 }
3162 if (outflow_upwind_j)
3163 {
3164 if (j == i)
3165 fluxJacobian_u_u[i][j] += flow_w_j*rho_trace_j*u_test_dS[i];
3166 }
3167 else
3168 exteriorNumericalAdvectiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],isFluxBoundary_u.data()[ebNE_kb],forceStrongConditions,normal,v_w_ext_j,advJacobian_ext);
3169 exteriorNumericalDiffusiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],isDiffusiveFluxBoundary_u.data()[ebNE_kb],a_rowptr.data(),a_colind.data(),normal,a_w_ext_j,zero_da_ext_j,grad_u_ext,&u_grad_trial_trace[j*nSpace],u_trial_trace_ref.data()[ebN_local_kb_j],ebqe_penalty_ext.data()[ebNE_kb],diffJacobian_ext);
3170 difffluxjacobian_ext = (advJacobian_ext*u_trial_trace_ref.data()[ebN_local_kb_j] + diffJacobian_ext)*dwdu_ext_j;
3171 fluxJacobian_u_u[i][j] += difffluxjacobian_ext*u_test_dS[i];
3172 }//j
3173 }//kb
3174 for (int i=0;i<nDOF_test_element;i++)
3175 {
3176 int eN_i = eN*nDOF_test_element+i;
3177 for (int j=0;j<nDOF_trial_element;j++)
3178 {
3179 int ebN_i_j = ebN*4*nDOF_test_X_trial_element + i*nDOF_trial_element + j;
3180 globalJacobian.data()[csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_eb_u_u.data()[ebN_i_j]] += fluxJacobian_u_u[i][j];
3181 }//j
3182 }//i
3183 }//ebNE
3184 return; // skip the element/boundary Jacobian loops below
3185 }
3186
3187 //
3188 //loop over elements to compute volume integrals and load them into the element Jacobians and global Jacobian
3189 //
3190 for(int eN=0;eN<nElements_global;eN++)
3191 {
3192 double elementJacobian_u_u[nDOF_test_element][nDOF_trial_element];
3193 for (int i=0;i<nDOF_test_element;i++)
3194 for (int j=0;j<nDOF_trial_element;j++)
3195 {
3196 elementJacobian_u_u[i][j]=0.0;
3197 }
3198 for (int k=0;k<nQuadraturePoints_element;k++)
3199 {
3200 int eN_k = eN*nQuadraturePoints_element+k, //index to a scalar at a quadrature point
3201 eN_k_nSpace = eN_k*nSpace,
3202 eN_nDOF_trial_element = eN*nDOF_trial_element; //index to a vector at a quadrature point
3203
3204 //declare local storage
3205 double u=0.0,
3206 grad_u[nSpace],
3207 m=0.0,dm=0.0,
3208 f[nSpace],df[nSpace],
3209 a[nnz],da[nnz],
3210
3211 m_t=0.0,dm_t=0.0,
3212 dpdeResidual_u_u[nDOF_trial_element],
3213 Lstar_u[nDOF_test_element],
3214 dsubgridError_u_u[nDOF_trial_element],
3215 tau=0.0,tau0=0.0,tau1=0.0,
3216 jac[nSpace*nSpace],
3217 jacDet,
3218 jacInv[nSpace*nSpace],
3219 u_grad_trial[nDOF_trial_element*nSpace],
3220 dV,
3221 u_test_dV[nDOF_test_element],
3222 u_grad_test_dV[nDOF_test_element*nSpace],
3223 x,y,z,xt,yt,zt,
3224 G[nSpace*nSpace],G_dd_G,tr_G;
3225 //
3226 //calculate solution and gradients at quadrature points
3227 //
3228 //get jacobian, etc for mapping reference element
3229 ck.calculateMapping_element(eN,
3230 k,
3231 mesh_dof.data(),
3232 mesh_l2g.data(),
3233 mesh_trial_ref.data(),
3234 mesh_grad_trial_ref.data(),
3235 jac,
3236 jacDet,
3237 jacInv,
3238 x,y,z);
3239 ck.calculateMappingVelocity_element(eN,
3240 k,
3241 mesh_velocity_dof.data(),
3242 mesh_l2g.data(),
3243 mesh_trial_ref.data(),
3244 xt,yt,zt);
3245 //get the physical integration weight
3246 dV = fabs(jacDet)*dV_ref.data()[k];
3247 ck.calculateG(jacInv,G,G_dd_G,tr_G);
3248 //get the trial function gradients
3249 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k*nDOF_trial_element*nSpace],jacInv,u_grad_trial);
3250 //get the solution
3251 ck.valFromDOF(u_dof.data(),&u_l2g.data()[eN_nDOF_trial_element],&u_trial_ref.data()[k*nDOF_trial_element],u);
3252 //get the solution gradients
3253 ck.gradFromDOF(u_dof.data(),&u_l2g.data()[eN_nDOF_trial_element],u_grad_trial,grad_u);
3254 //precalculate test function products with integration weights
3255 for (int j=0;j<nDOF_trial_element;j++)
3256 {
3257 u_test_dV[j] = u_test_ref.data()[k*nDOF_trial_element+j]*dV;
3258 for (int I=0;I<nSpace;I++)
3259 {
3260 u_grad_test_dV[j*nSpace+I] = u_grad_trial[j*nSpace+I]*dV;//cek warning won't work for Petrov-Galerkin
3261 }
3262 }
3263 //
3264 //calculate pde coefficients and derivatives at quadrature points
3265 //
3266
3267 double rho_out=0.0;
3268 evaluateCoefficients(a_rowptr.data(),
3269 a_colind.data(),
3270 &velocity.data()[eN_k_nSpace],
3271 alpha_L,
3272 alpha_T,
3273 Dm,
3274 q_porosity.data()[eN*nQuadraturePoints_element+k],
3275 rho_f,
3276 rho_s,
3277 u,
3278 rho_out,
3279 m,
3280 dm,
3281 f,
3282 df,
3283 a,
3284 da);
3285 //
3286 //moving mesh
3287 //
3288 double mesh_velocity[3];
3289 mesh_velocity[0] = xt;
3290 mesh_velocity[1] = yt;
3291 mesh_velocity[2] = zt;
3292
3293 for(int I=0;I<nSpace;I++)
3294 {
3295 f[I] -= MOVING_DOMAIN*m*mesh_velocity[I];
3296 df[I] -= MOVING_DOMAIN*dm*mesh_velocity[I];
3297 }
3298 //
3299 //calculate time derivatives
3300 //
3301 ck.bdf(alphaBDF,
3302 q_m_betaBDF.data()[eN_k],//since m_t isn't used, we don't have to correct mass
3303 m,
3304 dm,
3305 m_t,
3306 dm_t);
3307 if (STABILIZATION_TYPE == STABILIZATION::VMS)
3308 {
3309 //
3310 //calculate subgrid error contribution to the Jacobian (strong residual, adjoint, jacobian of strong residual)
3311 //
3312 //calculate the adjoint times the test functions
3313 for (int i=0;i<nDOF_test_element;i++)
3314 {
3315 int i_nSpace = i*nSpace;
3316 Lstar_u[i]=ck.Advection_adjoint(df,&u_grad_test_dV[i_nSpace]);
3317 }
3318 //calculate the Jacobian of strong residual
3319 for (int j=0;j<nDOF_trial_element;j++)
3320 {
3321 int j_nSpace = j*nSpace;
3322 dpdeResidual_u_u[j]= ck.MassJacobian_strong(dm_t,u_trial_ref.data()[k*nDOF_trial_element+j]) +
3323 ck.AdvectionJacobian_strong(df,&u_grad_trial[j_nSpace]);
3324 }
3325 //tau and tau*Res
3326 calculateSubgridError_tau(elementDiameter.data()[eN],
3327 dm_t,
3328 df,
3329 cfl.data()[eN_k],
3330 tau0);
3331
3333 G,
3334 dm_t,
3335 df,
3336 tau1,
3337 cfl.data()[eN_k]);
3338 tau = useMetrics*tau1+(1.0-useMetrics)*tau0;
3339
3340 for(int j=0;j<nDOF_trial_element;j++)
3341 dsubgridError_u_u[j] = -tau*dpdeResidual_u_u[j];
3342 }
3343 for(int i=0;i<nDOF_test_element;i++)
3344 {
3345 for(int j=0;j<nDOF_trial_element;j++)
3346 {
3347 int j_nSpace = j*nSpace;
3348 int i_nSpace = i*nSpace;
3349 if (STABILIZATION_TYPE==STABILIZATION::Galerkin)
3350 {
3351 elementJacobian_u_u[i][j] +=
3352 ck.MassJacobian_weak(dm_t,
3353 u_trial_ref.data()[k*nDOF_trial_element+j],
3354 u_test_dV[i]) +
3355 ck.AdvectionJacobian_weak(df,
3356 u_trial_ref.data()[k*nDOF_trial_element+j],
3357 &u_grad_test_dV[i_nSpace]) +
3358 ck.DiffusionJacobian_weak(a_rowptr.data(),a_colind.data(),a,da,
3359 grad_u,&u_grad_test_dV[i_nSpace],1.0,
3360 u_trial_ref.data()[k*nDOF_trial_element+j],&u_grad_trial[j_nSpace])
3361 +
3362 ck.NumericalDiffusionJacobian(physicalDiffusion,
3363 &u_grad_trial[j_nSpace],
3364 &u_grad_test_dV[i_nSpace]); //implicit
3365 }
3366 else if (STABILIZATION_TYPE==STABILIZATION::VMS)
3367 {
3368 elementJacobian_u_u[i][j] +=
3369 ck.MassJacobian_weak(dm_t,
3370 u_trial_ref.data()[k*nDOF_trial_element+j],
3371 u_test_dV[i]) +
3372 ck.AdvectionJacobian_weak(df,
3373 u_trial_ref.data()[k*nDOF_trial_element+j],
3374 &u_grad_test_dV[i_nSpace]) +
3375 ck.DiffusionJacobian_weak(a_rowptr.data(),a_colind.data(),a,da,
3376 grad_u,&u_grad_test_dV[i_nSpace],1.0,
3377 u_trial_ref.data()[k*nDOF_trial_element+j],&u_grad_trial[j_nSpace])+
3378
3379 ck.SubgridErrorJacobian(dsubgridError_u_u[j],Lstar_u[i]) +
3380 ck.NumericalDiffusionJacobian(q_numDiff_u_last.data()[eN_k] + physicalDiffusion,
3381 &u_grad_trial[j_nSpace],
3382 &u_grad_test_dV[i_nSpace]); //implicit
3383 }
3384 else if (STABILIZATION_TYPE==STABILIZATION::TaylorGalerkinEV or
3385 STABILIZATION_TYPE==STABILIZATION::EntropyViscosity or
3386 STABILIZATION_TYPE==STABILIZATION::SmoothnessIndicator or
3387 STABILIZATION_TYPE==STABILIZATION::Kuzmin)
3388 {
3389 elementJacobian_u_u[i][j] +=
3390 ck.MassJacobian_weak(1.0,
3391 u_trial_ref.data()[k*nDOF_trial_element+j],
3392 u_test_dV[i]);
3393 }
3394 }//j
3395 }//i
3396 }//k
3397 //
3398 //load into element Jacobian into global Jacobian
3399 //
3400 for (int i=0;i<nDOF_test_element;i++)
3401 {
3402 int eN_i = eN*nDOF_test_element+i;
3403 for (int j=0;j<nDOF_trial_element;j++)
3404 {
3405 int eN_i_j = eN_i*nDOF_trial_element+j;
3406 globalJacobian.data()[csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_u_u.data()[eN_i_j]] += elementJacobian_u_u[i][j];
3407 }//j
3408 }//i
3409 }//elements
3410 //
3411 //loop over exterior element boundaries to compute the surface integrals and load them into the global Jacobian
3412 //
3413 if (STABILIZATION_TYPE==STABILIZATION::VMS or STABILIZATION_TYPE==STABILIZATION::Galerkin)
3414 {
3415 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++)
3416 {
3417 int ebN = exteriorElementBoundariesArray.data()[ebNE];
3418 const int eN_out = elementBoundaryElementsArray.data()[ebN*2+1];
3419 const int ebFlag = elementBoundaryMaterialTypes.data()[ebN];
3420 if (ebFlag <= 0 || isExteriorBoundaryPhysical.data()[ebNE] == 0 || eN_out >= 0)
3421 continue;
3422 int eN = elementBoundaryElementsArray.data()[ebN*2+0],
3423 ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN*2+0],
3424 eN_nDOF_trial_element = eN*nDOF_trial_element;
3425 double fluxJacobian_u_u[nDOF_test_element][nDOF_trial_element];
3426 for (int i=0;i<nDOF_test_element;i++)
3427 for (int j=0;j<nDOF_trial_element;j++)
3428 {
3429 fluxJacobian_u_u[i][j]=0.0;
3430 }
3431 for (int kb=0;kb<nQuadraturePoints_elementBoundary;kb++)
3432 {
3433 int ebNE_kb = ebNE*nQuadraturePoints_elementBoundary+kb,
3434 ebNE_kb_nSpace = ebNE_kb*nSpace,
3435 ebN_local_kb = ebN_local*nQuadraturePoints_elementBoundary+kb,
3436 ebN_local_kb_nSpace = ebN_local_kb*nSpace;
3437 double u_ext=0.0,
3438 grad_u_ext[nSpace],
3439 m_ext=0.0,
3440 dm_ext=0.0,
3441 f_ext[nSpace],
3442 df_ext[nSpace],
3443
3444 a_ext[nnz],
3445 da_ext[nnz],
3446 bc_a_ext[nnz],
3447 bc_da_ext[nnz],
3448
3449 dflux_u_u_ext=0.0,
3450 difffluxjacobian_ext=0.0,
3451 bc_u_ext=0.0,
3452 //bc_grad_u_ext[nSpace],
3453 bc_m_ext=0.0,
3454 bc_dm_ext=0.0,
3455 bc_f_ext[nSpace],
3456 bc_df_ext[nSpace],
3458 diffusiveFluxJacobian_u_u[nDOF_trial_element],
3460 jac_ext[nSpace*nSpace],
3461 jacDet_ext,
3462 jacInv_ext[nSpace*nSpace],
3463 boundaryJac[nSpace*(nSpace-1)],
3464 metricTensor[(nSpace-1)*(nSpace-1)],
3465 metricTensorDetSqrt,
3466 dS,
3467 u_test_dS[nDOF_test_element],
3468 u_grad_trial_trace[nDOF_trial_element*nSpace],
3469 u_grad_test_dS[nDOF_trial_element*nSpace],
3470 normal[nSpace],x_ext,y_ext,z_ext,xt_ext,yt_ext,zt_ext,integralScaling,
3471 //
3472 G[nSpace*nSpace],G_dd_G,tr_G;
3473
3474 //
3475 //calculate the solution and gradients at quadrature points
3476 //
3477 ck.calculateMapping_elementBoundary(eN,
3478 ebN_local,
3479 kb,
3480 ebN_local_kb,
3481 mesh_dof.data(),
3482 mesh_l2g.data(),
3483 mesh_trial_trace_ref.data(),
3484 mesh_grad_trial_trace_ref.data(),
3485 boundaryJac_ref.data(),
3486 jac_ext,
3487 jacDet_ext,
3488 jacInv_ext,
3489 boundaryJac,
3490 metricTensor,
3491 metricTensorDetSqrt,
3492 normal_ref.data(),
3493 normal,
3494 x_ext,y_ext,z_ext);
3495 ck.calculateMappingVelocity_elementBoundary(eN,
3496 ebN_local,
3497 kb,
3498 ebN_local_kb,
3499 mesh_velocity_dof.data(),
3500 mesh_l2g.data(),
3501 mesh_trial_trace_ref.data(),
3502 xt_ext,yt_ext,zt_ext,
3503 normal,
3504 boundaryJac,
3505 metricTensor,
3506 integralScaling);
3507 dS = ((1.0-MOVING_DOMAIN)*metricTensorDetSqrt + MOVING_DOMAIN*integralScaling)*dS_ref.data()[kb];
3508 ck.calculateG(jacInv_ext,G,G_dd_G,tr_G);
3509 //compute shape and solution information
3510 //shape
3511 ck.gradTrialFromRef(&u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace*nDOF_trial_element],jacInv_ext,u_grad_trial_trace);
3512 //solution and gradients
3513 ck.valFromDOF(u_dof.data(),&u_l2g.data()[eN_nDOF_trial_element],&u_trial_trace_ref.data()[ebN_local_kb*nDOF_test_element],u_ext);
3514 ck.gradFromDOF(u_dof.data(),&u_l2g.data()[eN_nDOF_trial_element],u_grad_trial_trace,grad_u_ext);
3515 //precalculate test function products with integration weights
3516 for (int j=0;j<nDOF_trial_element;j++)
3517 {
3518 u_test_dS[j] = u_test_trace_ref.data()[ebN_local_kb*nDOF_test_element+j]*dS;
3519 for (int I=0;I<nSpace;I++)
3520 {
3521 u_grad_test_dS[j*nSpace+I]= u_grad_trial_trace[j*nSpace+I]*dS;
3522 }
3523 }
3524 //
3525 //load the boundary values
3526 //
3527 bc_u_ext = isDOFBoundary_u.data()[ebNE_kb]*ebqe_bc_u_ext.data()[ebNE_kb]+(1-isDOFBoundary_u.data()[ebNE_kb])*u_ext;
3528
3529 //
3530 //
3531 //calculate the internal and external trace of the pde coefficients
3532 //
3533
3534 double rho_out_ext=0.0,rho_out_bc=0.0;
3535 evaluateCoefficients(a_rowptr.data(),
3536 a_colind.data(),
3537 &ebqe_velocity_ext.data()[ebNE_kb_nSpace],
3538 alpha_L,
3539 alpha_T,
3540 Dm,
3541 ebqe_porosity.data()[ebNE_kb],
3542 rho_f,
3543 rho_s,
3544 u_ext,
3545 rho_out_ext,
3546 m_ext,
3547 dm_ext,
3548 f_ext,
3549 df_ext,
3550 a_ext,
3551 da_ext
3552 );
3553
3554 evaluateCoefficients(a_rowptr.data(),
3555 a_colind.data(),
3556 &ebqe_velocity_ext.data()[ebNE_kb_nSpace],
3557 alpha_L,
3558 alpha_T,
3559 Dm,
3560 ebqe_porosity.data()[ebNE_kb],
3561 rho_f,
3562 rho_s,
3563 bc_u_ext,
3564 rho_out_bc,
3565 bc_m_ext,
3566 bc_dm_ext,
3567 bc_f_ext,
3568 bc_df_ext,
3569 bc_a_ext,
3570 bc_da_ext);
3571 //
3572 //moving domain
3573 //
3574 double mesh_velocity[3];
3575 mesh_velocity[0] = xt_ext;
3576 mesh_velocity[1] = yt_ext;
3577 mesh_velocity[2] = zt_ext;
3578 for (int I=0;I<nSpace;I++)
3579 {
3580 f_ext[I] -= MOVING_DOMAIN*m_ext*mesh_velocity[I];
3581 df_ext[I] -= MOVING_DOMAIN*dm_ext*mesh_velocity[I];
3582 bc_f_ext[I] -= MOVING_DOMAIN*bc_m_ext*mesh_velocity[I];
3583 bc_df_ext[I] -= MOVING_DOMAIN*bc_dm_ext*mesh_velocity[I];
3584 }
3585 //
3586 //calculate the numerical fluxes
3587 //
3588 //
3589 //calculate the flux jacobian
3590 //
3591 for (int i=0;i<nDOF_test_element;i++)
3592 for (int j=0;j<nDOF_trial_element;j++)
3593 {
3594 int ebN_local_kb_j=ebN_local_kb*nDOF_trial_element+j;
3595
3596 double advJacobian_ext = 0.0, diffJacobian_ext = 0.0;
3597 exteriorNumericalAdvectiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],
3598 isFluxBoundary_u.data()[ebNE_kb],
3599 forceStrongConditions,
3600 normal,
3601 df_ext,
3602 advJacobian_ext);
3603 exteriorNumericalDiffusiveFluxDerivative(isDOFBoundary_u.data()[ebNE_kb],
3604 isDiffusiveFluxBoundary_u.data()[ebNE_kb],
3605 a_rowptr.data(),
3606 a_colind.data(),
3607 normal,
3608 a_ext,
3609 da_ext,
3610 grad_u_ext,
3611 &u_grad_trial_trace[j*nSpace],
3612 u_trial_trace_ref.data()[ebN_local_kb_j],
3613 ebqe_penalty_ext.data()[ebNE_kb],
3614 diffJacobian_ext);
3615 difffluxjacobian_ext = advJacobian_ext*u_trial_trace_ref.data()[ebN_local_kb_j]
3616 + diffJacobian_ext;
3617 fluxJacobian_u_u[i][j] += difffluxjacobian_ext*u_test_dS[i];
3618 }//j
3619
3620 //
3621 //update the global Jacobian from the flux Jacobian
3622 //
3623 for (int i=0;i<nDOF_test_element;i++)
3624 {
3625 int eN_i = eN*nDOF_test_element+i;
3626 for (int j=0;j<nDOF_trial_element;j++)
3627 {
3628 int ebN_i_j = ebN*4*nDOF_test_X_trial_element + i*nDOF_trial_element + j;
3629 globalJacobian.data()[csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_eb_u_u.data()[ebN_i_j]] += fluxJacobian_u_u[i][j];
3630//
3631 }//j
3632 }//i
3633 }//kb
3634 }//ebNE
3635 }//VMS and Galerkin
3636 }//computeJacobian
3637
3639 {
3640 double dt = args.scalar<double>("dt");
3641 int NNZ = args.scalar<int>("NNZ");
3642 int numDOFs = args.scalar<int>("numDOFs");
3643 xt::pyarray<double>& lumped_mass_matrix = args.array<double>("lumped_mass_matrix");
3644 xt::pyarray<double>& soln = args.array<double>("soln");
3645 xt::pyarray<double>& solH = args.array<double>("solH");
3646 xt::pyarray<double>& uLow = args.array<double>("uLow");
3647 xt::pyarray<double>& dLow = args.array<double>("dLow");
3648 xt::pyarray<double>& limited_solution = args.array<double>("limited_solution");
3649 // bc_mask: 0.0 at Dirichlet DOFs, 1.0 elsewhere. Mirrors mphase_co2's
3650 // pattern. Multiplied into the antidiffusive flux correction below so
3651 // Dirichlet DOFs stay at their low-order value (which already carries the
3652 // Nitsche BC contribution from the boundary residual) instead of being
3653 // antidiffused past the BC value.
3654 xt::pyarray<double>& bc_mask = args.array<double>("bc_mask");
3655 xt::pyarray<int>& csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
3656 xt::pyarray<int>& csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
3657 xt::pyarray<double>& MassMatrix = args.array<double>("MassMatrix");
3658 xt::pyarray<double>& dt_times_dH_minus_dL = args.array<double>("dt_times_dH_minus_dL");
3659 xt::pyarray<double>& min_u_bc = args.array<double>("min_u_bc");
3660 xt::pyarray<double>& max_u_bc = args.array<double>("max_u_bc");
3661 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
3662 // projection arrays replacing nodal_porosity
3663 xt::pyarray<double>& q_porosity_old_fct = args.array<double>("q_porosity_old_fct");
3664 xt::pyarray<double>& q_rho_fct = args.array<double>("q_rho_fct");
3665 xt::pyarray<double>& q_dV_fct = args.array<double>("q_dV_fct");
3666 xt::pyarray<int>& u_l2g_fct = args.array<int>("u_l2g_fct");
3667 xt::pyarray<double>& u_test_ref_fct = args.array<double>("u_test_ref_fct");
3668 xt::pyarray<double>& theta_dof_out = args.array<double>("theta_dof_out");
3669 xt::pyarray<double>& M_dof_fct = args.array<double>("M_dof_fct");
3670 xt::pyarray<double>& M_low_fct = args.array<double>("M_low_fct");
3671 xt::pyarray<double>& theta_nodal_fct = args.array<double>("theta_nodal");
3672 int nElements_global_fct = args.scalar<int>("nElements_global_fct");
3673 int nQuadraturePoints_element_fct = args.scalar<int>("nQuadraturePoints_element_fct");
3674 int nDOF_trial_element_fct = args.scalar<int>("nDOF_trial_element_fct");
3675 const double rho_f = args.scalar<double>("rho_f");
3676 const double rho_s = args.scalar<double>("rho_s");
3677// STABILIZATION STABILIZATION_TYPE{args.scalar<int>("STABILIZATION_TYPE")};
3678 STABILIZATION STABILIZATION_TYPE = static_cast<STABILIZATION>(args.scalar<int>("STABILIZATION_TYPE"));
3679// ENTROPY ENTROPY_TYPE = static_cast<ENTROPY>(args.scalar<int>("ENTROPY_TYPE"));
3680 // --- L2 projection: quadrature → DOF ---
3681 std::vector<double> theta_dof(numDOFs, 0.0);
3682 std::vector<double> rho_dof(numDOFs, 0.0);
3683 std::vector<double> ML_proj(numDOFs, 0.0);
3684 for (int eN = 0; eN < nElements_global_fct; eN++) {
3685 for (int k = 0; k < nQuadraturePoints_element_fct; k++) {
3686 const int eN_k = eN * nQuadraturePoints_element_fct + k;
3687 const double dV_k = q_dV_fct.data()[eN_k];
3688 const double theta_k = q_porosity_old_fct.data()[eN_k];
3689 const double rho_k = q_rho_fct.data()[eN_k];
3690 for (int i = 0; i < nDOF_trial_element_fct; i++) {
3691 const int gi = u_l2g_fct.data()[eN * nDOF_trial_element_fct + i];
3692 const double w = u_test_ref_fct.data()[k * nDOF_trial_element_fct + i] * dV_k;
3693 theta_dof[gi] += theta_k * w;
3694 rho_dof[gi] += rho_k * w;
3695 ML_proj[gi] += w;
3696 }
3697 }
3698 }
3699 for (int i = 0; i < numDOFs; i++) {
3700 if (ML_proj[i] > 1.0e-14) { theta_dof[i] /= ML_proj[i]; rho_dof[i] /= ML_proj[i]; }
3701 else { theta_dof[i] = 1.0; rho_dof[i] = rho_f; }
3702 // Same substitution as the residual: the group variable w = m/theta below has
3703 // to divide by the theta the residual's rho_j came from, or the antidiffusion
3704 // does not undo the viscosity that was applied. Zero = no flow model.
3705 if (theta_nodal_fct.data()[i] > 0.0) theta_dof[i] = theta_nodal_fct.data()[i];
3706 }
3707 // PARALLEL. The limiter is L_ij = min(Rpos_i, Rneg_j), so an owned row i reads
3708 // the ratio of a column j that may be a ghost, and a ratio is built from its
3709 // row's sparsity, lumped mass and bounds -- all INCOMPLETE at a ghost DOF, whose
3710 // element star is only partly on this rank. The two ranks sharing a cut edge
3711 // then apply different L_ij, F_ij = -F_ji is lost and the correction makes or
3712 // destroys mass along the partition. The owners' ratios cross the cut in the
3713 // middle of the limiter (as in Richards.h):
3714 // fct_pass = 1 -> FluxCorrectionMatrix and the local ratios Rpos/Rneg
3715 // [Python forward-inserts Rpos/Rneg, owner -> ghost]
3716 // fct_pass = 2 -> apply the limiter
3717 // fct_pass = 0 -> both back to back, the serial path.
3718 // Rpos/Rneg are owned by Python so they can be scattered; FluxCorrectionMatrix
3719 // is a member and survives between the two calls, so only pass 1 may resize
3720 // it: valarray::resize overwrites every element with the fill value.
3721 const int fct_pass = args.scalar<int>("fct_pass");
3722 const bool doPass1 = (fct_pass != 2);
3723 const bool doPass2 = (fct_pass != 1);
3724 xt::pyarray<double>& Rpos = args.array<double>("Rpos");
3725 xt::pyarray<double>& Rneg = args.array<double>("Rneg");
3726 if (doPass1)
3727 FluxCorrectionMatrix.resize(NNZ,0.0);
3728 // The scheme-B branches advance S = M*c (m_dof[i] = M_i*u^n_i), so the limiter
3729 // must use that same mass; STAB 0/1 carry the EOS mass and keep it. STAB 2/3/4
3730 // carry M themselves and divide the new-time states by M_low = M^{n+1}; STAB=5
3731 // reads Richards' M^n and uses it at both time levels (the cancelled form),
3732 // unless it advects with the flow model's fluxes, in which case it carries
3733 // M^{n+1} in M_low as well.
3734 const bool useM = (STABILIZATION_TYPE == STABILIZATION::EntropyViscosity or
3735 STABILIZATION_TYPE == STABILIZATION::SmoothnessIndicator or
3736 STABILIZATION_TYPE == STABILIZATION::Kuzmin or
3737 STABILIZATION_TYPE == STABILIZATION::ImplicitEV);
3738 const bool implicitM = (STABILIZATION_TYPE == STABILIZATION::ImplicitEV);
3739 // ImplicitEV with the flow model's fluxes: M_low is the carried M^{n+1}, and
3740 // the operator dLow acts on c itself (the fluxes are already mass fluxes).
3741 const int USE_EDGE_FLUX = args.scalar<int>("USE_EDGE_FLUX");
3742 const bool newM_is_old = implicitM && !USE_EDGE_FLUX;
3743 int ij=0;
3744 //PASS 1: loop over nodes (i)
3745 if (doPass1)
3746 for (int i=0; i<numDOFs; i++)
3747 {
3748 //read some vectors
3749 double solHi = solH.data()[i];
3750 double solni = soln.data()[i];
3751 const double lumped_volume = lumped_mass_matrix.data()[i];
3752 double uLowi = uLow.data()[i];
3753 const double theta_i = theta_dof[i];
3754 const double Mi_old = fmax(M_dof_fct.data()[i], 1.0e-14);
3755 const double Mi_new = newM_is_old ? Mi_old : fmax(M_low_fct.data()[i], 1.0e-14);
3756 double mLowi = useM ? Mi_new*uLowi : theta_i*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*uLowi)*uLowi;
3757 double solHmi = useM ? Mi_new*solHi : theta_i*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*solHi)*solHi;
3758 double solnmi = useM ? Mi_old*solni : theta_i*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*solni)*solni;
3759 double uDotLowi = (mLowi - solnmi)/dt;
3760 // GROUP VARIABLE w = rho(u)*u = m/theta. dt_times_dH_minus_dL and dLow
3761 // are coefficients of the w-operator (the transport matrix is assembled
3762 // against w), so the DISSIPATION part of the antidiffusive flux must
3763 // difference w, not m. The consistent-MASS part stays in m -- it is
3764 // M~_ij times d(m)/dt and carries its own theta.
3765 // ImplicitEV: M_dof is storage only (Richards' old-time mass), so
3766 // M/theta is not the density the residual applied dLow with; that is
3767 // rho(c^n) at the node, and soln IS c^n.
3768 // With the flow model's fluxes every branch's dLow acts on c itself.
3769 const double solnwi = USE_EDGE_FLUX ? solni
3770 : (implicitM ? rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*solni)*solni
3771 : solnmi/theta_i);
3772 const double wLowi = USE_EDGE_FLUX ? uLowi : mLowi/theta_i;
3773 double mini=min_u_bc.data()[i], maxi=max_u_bc.data()[i]; // init min/max with value at BCs (NOTE: if no boundary then min=1E10, max=-1E10)
3774 double Pposi=0, Pnegi=0;
3775 // Loop over neighbors (j)
3776 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
3777 {
3778 assert(offset == ij); // (CSR matrix consistency)
3779 int j = csrColumnOffsets_DofLoops.data()[offset];
3780 double solnj = soln.data()[j];
3781 double uLowj = uLow.data()[j];
3783 // COMPUTE THE BOUNDS //
3785
3786 // Explicit paths bound against soln (as VOF.h/VOF3P.h do);
3787 // ImplicitEV, whose limiter works on mass, bounds against uLow.
3788 const double bound_j =
3789 (STABILIZATION_TYPE == STABILIZATION::ImplicitEV) ? uLowj : solnj;
3790 mini = fmin(mini,bound_j);
3791 maxi = fmax(maxi,bound_j);
3792 const double theta_j = theta_dof[j];
3793 const double Mj_old = fmax(M_dof_fct.data()[j], 1.0e-14);
3794 const double Mj_new = newM_is_old ? Mj_old : fmax(M_low_fct.data()[j], 1.0e-14);
3795 double mLowj = useM ? Mj_new*uLowj : theta_j*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*uLowj)*uLowj;
3796 double solHmj = useM ? Mj_new*solH.data()[j] : theta_j*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*solH.data()[j])*solH.data()[j];
3797 double solnmj = useM ? Mj_old*solnj : theta_j*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*solnj)*solnj;
3798 double uDotLowj = (mLowj - solnmj)/dt;
3799 const double solnwj = USE_EDGE_FLUX ? solnj
3800 : (implicitM ? rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*solnj)*solnj
3801 : solnmj/theta_j); // group variable, old time
3802 const double wLowj = USE_EDGE_FLUX ? uLowj : mLowj/theta_j; // group variable, low order
3803 // i-th row of flux correction matrix
3804 if (STABILIZATION_TYPE == STABILIZATION::Kuzmin)
3805 {
3806 // Explicit Kuzmin antidiffusive flux: consistent-mass correction +
3807 // full removal of the symmetric graph viscosity dLow*(w_i-w_j).
3808 FluxCorrectionMatrix[ij] = dt*(MassMatrix.data()[ij]*(uDotLowi-uDotLowj)
3809 + dLow.data()[ij]*(wLowi-wLowj));
3810 }
3811 else if (STABILIZATION_TYPE == STABILIZATION::ImplicitEV)
3812 {
3813 // Standard Kuzmin implicit FEM-FCT antidiffusive flux:
3814 // F_ij = M~_ij[(m_j^H - m_j^n) - (m_i^H - m_i^n)]
3815 // + dt (d^H - d^L)_ij (m_j^n - m_i^n)
3816 // For ImplicitEV the Newton solve gives the low-order implicit
3817 // solution, so the high-order state is taken as m^H := m^L (uLow):
3818 // first term -M~_ij[(m_j^L-m_j^n)-(m_i^L-m_i^n)]
3819 // = dt*MC_ij*(uDotLow_i - uDotLow_j) (consistent mass)
3820 // second term dt_times_dH_minus_dL_ij*(m_j^n - m_i^n)
3821 // with dt_times_dH_minus_dL = dt*(d^H-d^L) = -dt*dLow.
3822 // The dissipation antidiffusion now acts on the OLD-time mass m^n
3823 // (solnm), matching the textbook Kuzmin form and the STAB=2
3824 // (EntropyViscosity) `else` branch below. The previous code used the
3825 // diffused low-order m^L here and threw away most of dLow via the Comp
3826 // throttle, so the front stayed under-sharpened. solnm carries the
3827 // density nonlinearity m^s(c)=theta*rho_f*(c + eps c^2); the inverse
3828 // c = 2r/(1+sqrt(1+4 eps r)) is applied in invert().
3829 // With the flow model's edge fluxes, dLow acts on c itself and was
3830 // applied implicitly to c^{n+1}, so its antidiffusion has to difference
3831 // c^{n+1} = uLow, not c^n. On c^n it is a forward-Euler correction of a
3832 // backward-Euler step: unlimited it is unstable (coupled MMS, N=40: c
3833 // overshoots to 0.93 against an exact maximum of 0.80), and limited it
3834 // costs the max-norm rate (test/salinity/mms_coupled/MMS_PLAN.md).
3835 const double dw_ij = USE_EDGE_FLUX ? (uLowj - uLowi) : (solnwj - solnwi);
3836 FluxCorrectionMatrix[ij] = dt*MassMatrix.data()[ij]*(uDotLowi-uDotLowj)
3837 + dt_times_dH_minus_dL.data()[ij]*dw_ij;
3838 }
3839 else
3840 {
3841 double ML_minus_MC =
3842 (LUMPED_MASS_MATRIX == 1 ? 0. : (i==j ? 1. : 0.)*lumped_volume - MassMatrix.data()[ij]);
3843 FluxCorrectionMatrix[ij] = ML_minus_MC * (solHmj-solnmj - (solHmi-solnmi))
3844 + dt_times_dH_minus_dL.data()[ij]*(solnwj-solnwi);
3845 }
3846 Pposi += FluxCorrectionMatrix[ij]*((FluxCorrectionMatrix[ij] > 0) ? 1. : 0.);
3847 Pnegi += FluxCorrectionMatrix[ij]*((FluxCorrectionMatrix[ij] < 0) ? 1. : 0.);
3848 ij+=1;
3849 }//j
3850 // Bounds on the DERIVED variable c, mapped to the mass being limited.
3851 const double Qposi = lumped_volume*((useM ? Mi_new*maxi : theta_i*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*maxi)*maxi) - mLowi);
3852 const double Qnegi = lumped_volume*((useM ? Mi_new*mini : theta_i*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*mini)*mini) - mLowi);
3853 Rpos.data()[i] = ((Pposi==0) ? 1. : fmax(0.0, fmin(1.0,Qposi/Pposi)));
3854 Rneg.data()[i] = ((Pnegi==0) ? 1. : fmax(0.0, fmin(1.0,Qnegi/Pnegi)));
3855 }//i
3856 ij=0;
3857 //PASS 2: apply the limiter
3858 if (doPass2)
3859 for (int i=0; i<numDOFs; i++)
3860 {
3861 double ith_Limiter_times_FluxCorrectionMatrix = 0.;
3862 double Rposi = Rpos.data()[i], Rnegi = Rneg.data()[i];
3863 const double lumped_volume = lumped_mass_matrix.data()[i];
3864 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
3865 {
3866 assert(offset == ij); // (CSR matrix consistency
3867 int j = csrColumnOffsets_DofLoops.data()[offset];
3868 double Lij = 1;
3869 Lij = ((FluxCorrectionMatrix[ij]>0) ? fmin(Rposi,Rneg.data()[j]) : fmin(Rnegi,Rpos.data()[j]));
3870 ith_Limiter_times_FluxCorrectionMatrix += Lij * FluxCorrectionMatrix[ij];
3871 ij+=1;
3872 }
3873 const double uLowi = uLow.data()[i];
3874 const double theta_i = theta_dof[i];
3875 const double mLowi = useM ? fmax((newM_is_old ? M_dof_fct : M_low_fct).data()[i], 1.0e-14)*uLowi
3876 : theta_i*rho_f*(1.0 + ((rho_s-rho_f)/rho_f)*uLowi)*uLowi;
3877 // bc_mask.data()[i] is 0 at Dirichlet DOFs (freeze at mLow) and 1 elsewhere.
3878 limited_solution.data()[i] = mLowi + bc_mask.data()[i] * (1./lumped_volume * ith_Limiter_times_FluxCorrectionMatrix);
3879 theta_dof_out.data()[i] = theta_dof[i];
3880 }
3881 }//FCTStep
3882
3884 // STABILIZATION_TYPE=Compatible: transport driven by the realized //
3885 // fluid exchanges of the flow step (Barua & Kees, Sec. 2.2). //
3886 // //
3887 // Flow exports, per step, the antisymmetric edge exchanges //
3888 // Fhat_ij = E_ij (fluid mass rate into i from j) and the nodal //
3889 // masses m^n, m^{n+1}. The transport carries the storage //
3890 // M^{n+1} = M^n + (m^{n+1} - m^n), M^0 = m^0, //
3891 // and B_i = M_L,i (M^{n+1}_i - M^n_i)/dt - sum_j Fhat_ij closes the //
3892 // fluid balance exactly (boundary exchange plus solver residual). //
3893 // Low order (backward Euler), cancelled form at free nodes: //
3894 // R_i = M_L,i M^n_i (c_i - c^n_i)/dt - sum_j gamma_ij (c_j - c_i) //
3895 // - B^+_i (c_in,i - c_i), //
3896 // gamma_ij = max(Fhat_ij,0) + max(0, -d_ij - |Fhat_ij|/2) >= 0, //
3897 // d_ij = int theta rho_T(c_h) D(v_h) grad w_j . grad w_i, so a //
3898 // constant c is reproduced exactly whatever the flow does. Strong //
3899 // Dirichlet rows: R_i = c_i - c_D,i. The Jacobian (computeJacobian) //
3900 // freezes gamma (Picard in the dispersion's rho_T(c)). //
3903 {
3904 const double dt = args.scalar<double>("dt");
3905 const int numDOFs = args.scalar<int>("numDOFs");
3906 const int nElements_global = args.scalar<int>("nElements_global");
3907 xt::pyarray<double>& mesh_trial_ref = args.array<double>("mesh_trial_ref");
3908 xt::pyarray<double>& mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
3909 xt::pyarray<double>& mesh_dof = args.array<double>("mesh_dof");
3910 xt::pyarray<int>& mesh_l2g = args.array<int>("mesh_l2g");
3911 xt::pyarray<double>& dV_ref = args.array<double>("dV_ref");
3912 xt::pyarray<double>& u_trial_ref = args.array<double>("u_trial_ref");
3913 xt::pyarray<double>& u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
3914 xt::pyarray<int>& u_l2g = args.array<int>("u_l2g");
3915 xt::pyarray<int>& r_l2g = args.array<int>("r_l2g");
3916 xt::pyarray<int>& a_rowptr = args.array<int>("a_rowptr");
3917 xt::pyarray<int>& a_colind = args.array<int>("a_colind");
3918 const double alpha_L = args.scalar<double>("alpha_L");
3919 const double alpha_T = args.scalar<double>("alpha_T");
3920 const double Dm = args.scalar<double>("Dm");
3921 const double rho_f = args.scalar<double>("rho_f");
3922 const double rho_s = args.scalar<double>("rho_s");
3923 xt::pyarray<double>& q_porosity = args.array<double>("q_porosity");
3924 xt::pyarray<double>& q_velocity_dispersion = args.array<double>("q_velocity_dispersion");
3925 xt::pyarray<double>& u_dof = args.array<double>("u_dof");
3926 xt::pyarray<double>& u_dof_old = args.array<double>("u_dof_old");
3927 xt::pyarray<int>& csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
3928 xt::pyarray<int>& csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
3929 xt::pyarray<int>& csrRowIndeces_CellLoops = args.array<int>("csrRowIndeces_CellLoops");
3930 xt::pyarray<int>& csrColumnOffsets_CellLoops = args.array<int>("csrColumnOffsets_CellLoops");
3931 xt::pyarray<double>& ML = args.array<double>("ML");
3932 xt::pyarray<double>& Fhat = args.array<double>("Fhat");
3933 xt::pyarray<double>& Mn = args.array<double>("Mn");
3934 xt::pyarray<double>& B = args.array<double>("B");
3935 xt::pyarray<double>& cin = args.array<double>("cin");
3936 xt::pyarray<double>& bc_mask = args.array<double>("bc_mask");
3937 xt::pyarray<double>& cD = args.array<double>("cD");
3938 xt::pyarray<double>& dDispersion = args.array<double>("dDispersion");
3939 xt::pyarray<double>& globalResidual = args.array<double>("globalResidual");
3940 const int computeJacobian = args.scalar<int>("computeJacobian");
3941 xt::pyarray<double>& globalJacobian = args.array<double>("globalJacobian");
3942 std::valarray<double> c(numDOFs), cn(numDOFs);
3943 for (int eN=0; eN<nElements_global; eN++)
3944 for (int j=0; j<nDOF_trial_element; j++)
3945 {
3946 const int eN_j = eN*nDOF_trial_element + j;
3947 c[r_l2g.data()[eN_j]] = u_dof.data()[u_l2g.data()[eN_j]];
3948 cn[r_l2g.data()[eN_j]] = u_dof_old.data()[u_l2g.data()[eN_j]];
3949 }
3950 // dispersion matrix d_ij(c)
3951 std::fill(dDispersion.begin(), dDispersion.end(), 0.0);
3952 for (int eN=0; eN<nElements_global; eN++)
3953 {
3954 double elementDispersion[nDOF_test_element][nDOF_trial_element];
3955 for (int i=0; i<nDOF_test_element; i++)
3956 for (int j=0; j<nDOF_trial_element; j++)
3957 elementDispersion[i][j] = 0.0;
3958 for (int k=0; k<nQuadraturePoints_element; k++)
3959 {
3960 const int eN_k = eN*nQuadraturePoints_element + k;
3961 double jac[nSpace*nSpace], jacDet, jacInv[nSpace*nSpace], x, y, z;
3962 double u_grad_trial[nDOF_trial_element*nSpace], u_grad_test_dV[nDOF_test_element*nSpace];
3963 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
3964 jac, jacDet, jacInv, x, y, z);
3965 const double dV = fabs(jacDet)*dV_ref.data()[k];
3966 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k*nDOF_trial_element*nSpace], jacInv, u_grad_trial);
3967 double u = 0.0;
3968 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN*nDOF_trial_element], &u_trial_ref.data()[k*nDOF_trial_element], u);
3969 for (int j=0; j<nDOF_trial_element; j++)
3970 for (int I=0; I<nSpace; I++)
3971 u_grad_test_dV[j*nSpace+I] = u_grad_trial[j*nSpace+I]*dV;
3972 double rho_out, m, dm, f[nSpace], df[nSpace], a[nnz], da[nnz];
3973 evaluateCoefficients(a_rowptr.data(), a_colind.data(), &q_velocity_dispersion.data()[eN_k*nSpace],
3974 alpha_L, alpha_T, Dm, q_porosity.data()[eN_k], rho_f, rho_s, u,
3975 rho_out, m, dm, f, df, a, da);
3976 for (int i=0; i<nDOF_test_element; i++)
3977 for (int j=0; j<nDOF_trial_element; j++)
3978 elementDispersion[i][j] += ck.SimpleDiffusionJacobian_weak(a_rowptr.data(), a_colind.data(), a,
3979 &u_grad_trial[j*nSpace], &u_grad_test_dV[i*nSpace]);
3980 }
3981 for (int i=0; i<nDOF_test_element; i++)
3982 {
3983 const int eN_i = eN*nDOF_test_element + i;
3984 for (int j=0; j<nDOF_trial_element; j++)
3985 dDispersion.data()[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i*nDOF_trial_element + j]]
3986 += elementDispersion[i][j];
3987 }
3988 }
3989 // edge loop
3990 for (int i=0; i<numDOFs; i++)
3991 {
3992 if (bc_mask.data()[i] == 0.0)
3993 {
3994 globalResidual.data()[i] = c[i] - cD.data()[i];
3995 if (computeJacobian)
3996 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
3997 globalJacobian.data()[offset] = (csrColumnOffsets_DofLoops.data()[offset] == i) ? 1.0 : 0.0;
3998 continue;
3999 }
4000 const double Bpos = fmax(B.data()[i], 0.0);
4001 const double storage = ML.data()[i]*Mn.data()[i]/dt;
4002 double res = storage*(c[i] - cn[i]) - Bpos*(cin.data()[i] - c[i]);
4003 double jac_ii = storage + Bpos;
4004 int ii = -1;
4005 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
4006 {
4007 const int j = csrColumnOffsets_DofLoops.data()[offset];
4008 if (j == i)
4009 {
4010 ii = offset;
4011 continue;
4012 }
4013 const double F = Fhat.data()[offset];
4014 const double gamma = fmax(F, 0.0) + fmax(0.0, -dDispersion.data()[offset] - 0.5*fabs(F));
4015 res -= gamma*(c[j] - c[i]);
4016 jac_ii += gamma;
4017 if (computeJacobian)
4018 globalJacobian.data()[offset] = -gamma;
4019 }
4020 globalResidual.data()[i] = res;
4021 if (computeJacobian)
4022 globalJacobian.data()[ii] = jac_ii;
4023 }
4024 }
4025
4026 // Piecewise constant mass flux q_h with int q_h . grad w_i = sum_j E_ij (Sec. 2.2, compatibility
4027 // conditions). Each edge exchange is split among the elements sharing the edge in proportion to
4028 // |K^e_ij|, K^e the element Laplacian (equal shares where every |K^e_ij| vanishes); within a simplex
4029 // the d+1 element moments then sum to zero and determine q_e uniquely. Used for the dispersion only.
4031 {
4032 const int nElements_global = args.scalar<int>("nElements_global");
4033 xt::pyarray<double>& mesh_trial_ref = args.array<double>("mesh_trial_ref");
4034 xt::pyarray<double>& mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
4035 xt::pyarray<double>& mesh_dof = args.array<double>("mesh_dof");
4036 xt::pyarray<int>& mesh_l2g = args.array<int>("mesh_l2g");
4037 xt::pyarray<double>& dV_ref = args.array<double>("dV_ref");
4038 xt::pyarray<double>& u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
4039 xt::pyarray<int>& csrRowIndeces_CellLoops = args.array<int>("csrRowIndeces_CellLoops");
4040 xt::pyarray<int>& csrColumnOffsets_CellLoops = args.array<int>("csrColumnOffsets_CellLoops");
4041 xt::pyarray<double>& Espatial = args.array<double>("Espatial");
4042 xt::pyarray<double>& edgeWeight = args.array<double>("edgeWeight");
4043 xt::pyarray<double>& edgeCount = args.array<double>("edgeCount");
4044 xt::pyarray<double>& element_q = args.array<double>("element_q");
4045 std::vector<double> gradInt(nElements_global*nDOF_trial_element*nSpace, 0.0), K(nElements_global*nDOF_test_X_trial_element, 0.0);
4046 for (int eN=0; eN<nElements_global; eN++)
4047 for (int k=0; k<nQuadraturePoints_element; k++)
4048 {
4049 double jac[nSpace*nSpace], jacDet, jacInv[nSpace*nSpace], x, y, z, u_grad_trial[nDOF_trial_element*nSpace];
4050 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
4051 jac, jacDet, jacInv, x, y, z);
4052 const double dV = fabs(jacDet)*dV_ref.data()[k];
4053 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k*nDOF_trial_element*nSpace], jacInv, u_grad_trial);
4054 for (int i=0; i<nDOF_trial_element; i++)
4055 {
4056 for (int I=0; I<nSpace; I++)
4057 gradInt[(eN*nDOF_trial_element + i)*nSpace + I] += u_grad_trial[i*nSpace+I]*dV;
4058 for (int j=0; j<nDOF_trial_element; j++)
4059 for (int I=0; I<nSpace; I++)
4060 K[eN*nDOF_test_X_trial_element + i*nDOF_trial_element + j] += u_grad_trial[i*nSpace+I]*u_grad_trial[j*nSpace+I]*dV;
4061 }
4062 }
4063 std::fill(edgeWeight.begin(), edgeWeight.end(), 0.0);
4064 std::fill(edgeCount.begin(), edgeCount.end(), 0.0);
4065 for (int eN=0; eN<nElements_global; eN++)
4066 for (int i=0; i<nDOF_test_element; i++)
4067 {
4068 const int eN_i = eN*nDOF_test_element + i;
4069 for (int j=0; j<nDOF_trial_element; j++)
4070 {
4071 const int ij = csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i*nDOF_trial_element + j];
4072 edgeWeight.data()[ij] += fabs(K[eN*nDOF_test_X_trial_element + i*nDOF_trial_element + j]);
4073 edgeCount.data()[ij] += 1.0;
4074 }
4075 }
4076 for (int eN=0; eN<nElements_global; eN++)
4077 {
4078 double r[nDOF_test_element];
4079 for (int i=0; i<nDOF_test_element; i++)
4080 {
4081 const int eN_i = eN*nDOF_test_element + i;
4082 r[i] = 0.0;
4083 for (int j=0; j<nDOF_trial_element; j++)
4084 {
4085 if (j == i)
4086 continue;
4087 const int ij = csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i*nDOF_trial_element + j];
4088 const double Ke = fabs(K[eN*nDOF_test_X_trial_element + i*nDOF_trial_element + j]);
4089 const double share = (edgeWeight.data()[ij] > 0.0) ? Ke/edgeWeight.data()[ij] : 1.0/edgeCount.data()[ij];
4090 r[i] += share*Espatial.data()[ij];
4091 }
4092 }
4093 // least squares G q = r, G_iI = int_e d w_i / d x_I
4094 double A[nSpace][nSpace+1];
4095 for (int I=0; I<nSpace; I++)
4096 {
4097 for (int J=0; J<nSpace; J++)
4098 {
4099 A[I][J] = 0.0;
4100 for (int i=0; i<nDOF_test_element; i++)
4101 A[I][J] += gradInt[(eN*nDOF_trial_element + i)*nSpace + I]*gradInt[(eN*nDOF_trial_element + i)*nSpace + J];
4102 }
4103 A[I][nSpace] = 0.0;
4104 for (int i=0; i<nDOF_test_element; i++)
4105 A[I][nSpace] += gradInt[(eN*nDOF_trial_element + i)*nSpace + I]*r[i];
4106 }
4107 for (int I=0; I<nSpace; I++)
4108 {
4109 int p = I;
4110 for (int J=I+1; J<nSpace; J++)
4111 if (fabs(A[J][I]) > fabs(A[p][I]))
4112 p = J;
4113 for (int J=0; J<=nSpace; J++)
4114 std::swap(A[I][J], A[p][J]);
4115 for (int J=I+1; J<nSpace; J++)
4116 {
4117 const double f = A[J][I]/A[I][I];
4118 for (int L=I; L<=nSpace; L++)
4119 A[J][L] -= f*A[I][L];
4120 }
4121 }
4122 for (int I=nSpace-1; I>=0; I--)
4123 {
4124 double s = A[I][nSpace];
4125 for (int J=I+1; J<nSpace; J++)
4126 s -= A[I][J]*element_q.data()[eN*nSpace + J];
4127 element_q.data()[eN*nSpace + I] = s/A[I][I];
4128 }
4129 }
4130 }
4131
4132 // Zalesak limiting of the solute mass S = M c with concentration bounds (Algorithm 3).
4133 // f_ij = dt m_ij (Sdot_i - Sdot_j) - dt nu_ij (c^n_j - c^n_i), nu_ij = max(0, |Fhat_ij|/2 + d_ij),
4134 // S^{n+1}_i = M^{n+1}_i c^L_i + (1/M_L,i) sum_j alpha_ij f_ij, c^{n+1}_i = S^{n+1}_i / M^{n+1}_i,
4135 // with S^max/min_i = M^{n+1}_i max/min_{j in N_i} c^L_j. Dirichlet nodes keep c_D (R^+- = 1 there).
4136 // limitedFluxMatrix_ij = alpha_ij f_ij (row i) for the solute budget.
4138 {
4139 const double dt = args.scalar<double>("dt");
4140 const int numDOFs = args.scalar<int>("numDOFs");
4141 xt::pyarray<int>& csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
4142 xt::pyarray<int>& csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
4143 xt::pyarray<double>& ML = args.array<double>("ML");
4144 xt::pyarray<double>& MC = args.array<double>("MC");
4145 xt::pyarray<double>& Mn = args.array<double>("Mn");
4146 xt::pyarray<double>& Mnp1 = args.array<double>("Mnp1");
4147 xt::pyarray<double>& cn = args.array<double>("cn");
4148 xt::pyarray<double>& cL = args.array<double>("cL");
4149 xt::pyarray<double>& Fhat = args.array<double>("Fhat");
4150 xt::pyarray<double>& dDispersion = args.array<double>("dDispersion");
4151 xt::pyarray<double>& bc_mask = args.array<double>("bc_mask");
4152 xt::pyarray<double>& Rpos = args.array<double>("Rpos");
4153 xt::pyarray<double>& Rneg = args.array<double>("Rneg");
4154 xt::pyarray<double>& FluxCorrectionMatrix = args.array<double>("FluxCorrectionMatrix");
4155 xt::pyarray<double>& limitedFluxMatrix = args.array<double>("limitedFluxMatrix");
4156 xt::pyarray<double>& c_new = args.array<double>("c_new");
4157 std::vector<double> SL(numDOFs), SdotL(numDOFs);
4158 for (int i=0; i<numDOFs; i++)
4159 {
4160 SL[i] = Mnp1.data()[i]*cL.data()[i];
4161 SdotL[i] = (SL[i] - Mn.data()[i]*cn.data()[i])/dt;
4162 }
4163 for (int i=0; i<numDOFs; i++)
4164 {
4165 double cmax = cL.data()[i], cmin = cL.data()[i], Ppos = 0.0, Pneg = 0.0;
4166 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
4167 {
4168 const int j = csrColumnOffsets_DofLoops.data()[offset];
4169 cmax = fmax(cmax, cL.data()[j]);
4170 cmin = fmin(cmin, cL.data()[j]);
4171 double f = 0.0;
4172 if (j != i)
4173 {
4174 const double nu = fmax(0.0, 0.5*fabs(Fhat.data()[offset]) + dDispersion.data()[offset]);
4175 f = dt*MC.data()[offset]*(SdotL[i] - SdotL[j]) - dt*nu*(cn.data()[j] - cn.data()[i]);
4176 }
4177 FluxCorrectionMatrix.data()[offset] = f;
4178 Ppos += fmax(f, 0.0);
4179 Pneg += fmin(f, 0.0);
4180 }
4181 if (bc_mask.data()[i] == 0.0)
4182 {
4183 Rpos.data()[i] = 1.0;
4184 Rneg.data()[i] = 1.0;
4185 continue;
4186 }
4187 const double Qpos = ML.data()[i]*(Mnp1.data()[i]*cmax - SL[i]);
4188 const double Qneg = ML.data()[i]*(Mnp1.data()[i]*cmin - SL[i]);
4189 Rpos.data()[i] = (Ppos == 0.0) ? 1.0 : fmax(0.0, fmin(1.0, Qpos/Ppos));
4190 Rneg.data()[i] = (Pneg == 0.0) ? 1.0 : fmax(0.0, fmin(1.0, Qneg/Pneg));
4191 }
4192 for (int i=0; i<numDOFs; i++)
4193 {
4194 double sum = 0.0;
4195 for (int offset=csrRowIndeces_DofLoops.data()[i]; offset<csrRowIndeces_DofLoops.data()[i+1]; offset++)
4196 {
4197 const int j = csrColumnOffsets_DofLoops.data()[offset];
4198 const double f = FluxCorrectionMatrix.data()[offset];
4199 double alpha = (f > 0.0) ? fmin(Rpos.data()[i], Rneg.data()[j]) : fmin(Rneg.data()[i], Rpos.data()[j]);
4200 if (bc_mask.data()[i] == 0.0 && bc_mask.data()[j] == 0.0)
4201 alpha = 0.0;
4202 limitedFluxMatrix.data()[offset] = alpha*f;
4203 sum += alpha*f;
4204 }
4205 if (bc_mask.data()[i] == 0.0)
4206 c_new.data()[i] = cL.data()[i];
4207 else
4208 c_new.data()[i] = (SL[i] + sum/ML.data()[i])/Mnp1.data()[i];
4209 }
4210 }
4211 };//TADR
4212
4213inline TADR_base* newTADR(int nSpaceIn,
4214 int nQuadraturePoints_elementIn,
4215 int nDOF_mesh_trial_elementIn,
4216 int nDOF_trial_elementIn,
4217 int nDOF_test_elementIn,
4218 int nQuadraturePoints_elementBoundaryIn,
4219 int CompKernelFlag)
4220{
4221 if (nSpaceIn == 1)
4223 nQuadraturePoints_elementIn,
4224 nDOF_mesh_trial_elementIn,
4225 nDOF_trial_elementIn,
4226 nDOF_test_elementIn,
4227 nQuadraturePoints_elementBoundaryIn,
4228 CompKernelFlag);
4229 else if (nSpaceIn == 2)
4231 nQuadraturePoints_elementIn,
4232 nDOF_mesh_trial_elementIn,
4233 nDOF_trial_elementIn,
4234 nDOF_test_elementIn,
4235 nQuadraturePoints_elementBoundaryIn,
4236 CompKernelFlag);
4237 else
4239 nQuadraturePoints_elementIn,
4240 nDOF_mesh_trial_elementIn,
4241 nDOF_trial_elementIn,
4242 nDOF_test_elementIn,
4243 nQuadraturePoints_elementBoundaryIn,
4244 CompKernelFlag);
4245}
4246}//proteus
4247#endif
Int n
Definition Headers.h:28
Double sum
Definition Headers.h:85
Double L
Definition Headers.h:72
Double r
Definition Headers.h:83
Double H
Definition Headers.h:65
Double * B
Definition Headers.h:41
Double s
Definition Headers.h:84
Double u
Definition Headers.h:89
Int num
Definition Headers.h:32
Double * z
Definition Headers.h:49
Double v
Definition Headers.h:95
#define cMax
Definition NCLS3P.h:11
#define cE
Definition NCLS3P.h:10
std::valarray< double > theta_dof_proj
Definition TADR.h:74
std::valarray< double > m_dof
Definition TADR.h:74
std::valarray< double > boundary_integral
Definition TADR.h:73
std::valarray< double > eta
Definition TADR.h:73
std::valarray< double > DiffusionMatrix
Definition TADR.h:69
std::valarray< double > maxEntRes
Definition TADR.h:84
virtual void calculateResidual(arguments_dict &args)=0
virtual void FCTStep_compatible(arguments_dict &args)=0
std::valarray< double > ML_mass_proj
Definition TADR.h:74
std::valarray< double > cin_den
Definition TADR.h:83
std::valarray< double > TransposeTransportMatrix
Definition TADR.h:69
virtual void FCTStep(arguments_dict &args)=0
std::valarray< double > maxVel
Definition TADR.h:84
std::valarray< double > AdvectionMatrix
Definition TADR.h:72
virtual void calculateJacobian(arguments_dict &args)=0
virtual void invert(arguments_dict &args)=0
virtual void reconstructFlux_compatible(arguments_dict &args)=0
virtual ~TADR_base()
Definition TADR.h:85
virtual void calculateResidual_compatible(arguments_dict &args)=0
std::valarray< double > TransportMatrix
Definition TADR.h:69
std::valarray< double > TransposeAdvectionMatrix
Definition TADR.h:72
std::valarray< double > cin_num
Definition TADR.h:83
std::valarray< double > FluxCorrectionMatrix
Definition TADR.h:68
std::valarray< double > boundary_integral_fluid
Definition TADR.h:78
std::valarray< double > rho_dof_proj
Definition TADR.h:74
std::valarray< double > global_entropy_residual
Definition TADR.h:73
std::valarray< double > psi
Definition TADR.h:73
double inversevaluateCoefficients(const double storage, const double porosity, const double rho_f, const double rho_s)
Definition TADR.h:187
void calculateResidual(arguments_dict &args)
Definition TADR.h:457
void FCTStep_compatible(arguments_dict &args)
Definition TADR.h:4137
double ExteriorNumericalDiffusiveFluxJacobian(int *rowptr, int *colind, const int &isDOFBoundary, const int &isDiffusiveFluxBoundary, const double n[nSpace], double *a, const double &v, const double grad_v[nSpace], const double &penalty)
Definition TADR.h:251
void reconstructFlux_compatible(arguments_dict &args)
Definition TADR.h:4030
void calculateResidual_compatible(arguments_dict &args)
Definition TADR.h:3902
void exteriorNumericalAdvectiveFluxDerivative(const int &isDOFBoundary_u, const int &isFluxBoundary_u, const int &forceStrongConditions, const double n[nSpace], const double velocity[nSpace], double &dflux)
Definition TADR.h:383
void calculateJacobian(arguments_dict &args)
Definition TADR.h:2856
void exteriorNumericalDiffusiveFluxDerivative(const int &isDOFBoundary, const int &isDiffusiveFluxBoundary, const int rowptr[nSpace], const int colind[nnz], const double n[nSpace], const double a[nnz], const double da[nnz], const double grad_psi[nSpace], const double grad_v[nSpace], const double &v, const double penalty, double &fluxJacobian)
Definition TADR.h:424
const int nDOF_test_X_trial_element
Definition TADR.h:105
void calculateSubgridError_tau(const double &Ct_sge, const double G[nSpace *nSpace], const double &A0, const double Ai[nSpace], double &tau_v, double &cfl)
Definition TADR.h:301
void exteriorNumericalAdvectiveFlux(const int &isDOFBoundary_u, const int &isFluxBoundary_u, const int &forceStrongConditions, const double n[nSpace], const double &bc_flux_u, const double f[nSpace], const double bc_f[nSpace], const double velocity[nSpace], double &flux)
Definition TADR.h:344
void FCTStep(arguments_dict &args)
Definition TADR.h:3638
void exteriorNumericalDiffusiveFlux(int *rowptr, int *colind, const int &isDOFBoundary, const int &isDiffusiveFluxBoundary, const double n[nSpace], double *bc_a, const double &bc_u, const double &bc_flux, double *a, const double grad_potential[nSpace], const double &u, const double &penalty, double &flux)
Definition TADR.h:205
void invert(arguments_dict &args)
Definition TADR.h:2821
void calculateSubgridError_tau(const double &elementDiameter, const double &dmt, const double df[nSpace], double &cfl, double &tau)
Definition TADR.h:282
void calculateNumericalDiffusion(const double &shockCapturingDiffusion, const double &elementDiameter, const double &strong_residual, const double grad_u[nSpace], double &numDiff)
Definition TADR.h:324
CompKernelType ck
Definition TADR.h:106
void evaluateCoefficients(const int rowptr[nSpace], const int colind[nnz], const double v[nSpace], const double alpha_L, const double alpha_T, const double Dm, const double thetaW, const double rho_f, const double rho_s, const double &u, double &rho_out, double &m, double &dm, double f[nSpace], double df[nSpace], double a[nnz], double da[nnz])
Definition TADR.h:131
void calculateCFL(const double &elementDiameter, const double df[nSpace], double &cfl)
Definition TADR.h:115
double df(double C, double b, double a, int q, int r)
#define c(i)
Definition jf.h:21
#define w(x)
Definition jf.h:22
#define POWER_SMOOTHNESS_INDICATOR
Definition m_comp_co2.h:22
#define nnz
Definition m_comp_co2.h:19
Definition ADR.h:21
TADR_base * newTADR(int nSpaceIn, int nQuadraturePoints_elementIn, int nDOF_mesh_trial_elementIn, int nDOF_trial_elementIn, int nDOF_test_elementIn, int nQuadraturePoints_elementBoundaryIn, int CompKernelFlag)
Definition TADR.h:4213
double DEPOWER(const double &phi, const double &phiL, const double &phiR)
Definition TADR.h:47
double phi(const double &g, const double &h, const double &hL, const double &hR, const double &uL, const double &uR)
Definition SW2DCV.h:62
Model_Base * chooseAndAllocateDiscretization(int nSpaceIn, int nQuadraturePoints_elementIn, int nDOF_mesh_trial_elementIn, int nDOF_trial_elementIn, int nDOF_test_elementIn, int nDOF_v_trial_elementIn, int nDOF_v_test_elementIn, int nQuadraturePoints_elementBoundaryIn, int CompKernelFlag)
ENTROPY
Definition TADR.h:40
double DELOG(const double &phi, const double &phiL, const double &phiR)
Definition TADR.h:56
double ELOG(const double &phi, const double &phiL, const double &phiR)
Definition TADR.h:52
double EPOWER(const double &phi, const double &phiL, const double &phiR)
Definition TADR.h:43
Model_Base * chooseAndAllocateDiscretization1D(int nSpaceIn, int nQuadraturePoints_elementIn, int nDOF_mesh_trial_elementIn, int nDOF_trial_elementIn, int nDOF_test_elementIn, int nQuadraturePoints_elementBoundaryIn, int CompKernelFlag)
Model_Base * chooseAndAllocateDiscretization2D(int nSpaceIn, int nQuadraturePoints_elementIn, int nDOF_mesh_trial_elementIn, int nDOF_trial_elementIn, int nDOF_test_elementIn, int nDOF_v_trial_elementIn, int nDOF_v_test_elementIn, int nQuadraturePoints_elementBoundaryIn, int CompKernelFlag)
DISPERSION
Definition TADR.h:41
double f(const double &g, const double &h, const double &hZ)
Definition SW2DCV.h:58
T & scalar(const std::string &key)
xt::pyarray< T > & array(const std::string &key)