proteus 1.9.1
C/C++/Fortran libraries
Loading...
Searching...
No Matches
m_comp_co2.h
Go to the documentation of this file.
1// Two-component (H2O/CO2) compositional two-phase flow kernel.
2//
3// Co-authored-by: Claude Opus 5 <noreply@anthropic.com> and abarua_ce
4#ifndef MPHASE_CO2_H
5#define MPHASE_CO2_H
6#include <cmath>
7#include <iostream>
8#include <stdexcept>
9#include <valarray>
10#include "CompKernel.h"
11#include "ModelFactory.h"
13#include "xtensor-python/pyarray.hpp"
14#include "../pskRelations.h"
15// Compositional CO2-brine EOS + analytic (p,z) flash (P3). Standalone headers
16// in global namespace ::m_comp_co2 (distinct from proteus::m_comp_co2 below);
17// call sites use the fully-qualified ::m_comp_co2::flash:: form.
18#include "co2_brine_flash.h"
19#define nnz nSpace
20
21namespace py = pybind11;
22#define POWER_SMOOTHNESS_INDICATOR 2
23#define IS_BETAij_ONE 0
24#define GLOBAL_FCT 0
25namespace proteus
26{
27enum class STABILIZATION : int {
32};
33
34namespace m_comp_co2
35{
36//cek todo: revisit entry for mass transport form
37// Power entropy //
38inline double ENTROPY(const double &phi, const double &phiL, const double &phiR)
39{
40 return 1. / 2. * std::pow(fabs(phi), 2.);
41}
42inline double DENTROPY(const double &phi, const double &phiL, const double &phiR)
43{
44 return fabs(phi) * (phi >= 0 ? 1 : -1);
45}
46// Log entropy // for level set from 0 to 1
47inline double ENTROPY_LOG(const double &phi, const double &phiL, const double &phiR)
48{
49 return std::log(fabs((phi - phiL) * (phiR - phi)) + 1E-14);
50}
51inline double DENTROPY_LOG(const double &phi, const double &phiL, const double &phiR)
52{
53 return (phiL + phiR - 2 * phi) * ((phi - phiL) * (phiR - phi) >= 0 ? 1 : -1) / (fabs((phi - phiL) * (phiR - phi)) + 1E-14);
54}
55} // namespace m_comp_co2
56} // namespace proteus
57namespace proteus
58{
59namespace m_comp_co2
60{
62 //The base class defining the interface
63public:
64 virtual ~M_comp_co2_base() { double anb_seepage_flux = 1e-16; }
65 virtual void calculateResidual(arguments_dict &args) = 0;
66 virtual void calculateJacobian(arguments_dict &args) = 0;
67 virtual void invert(arguments_dict &args) = 0;
68 virtual void FCTStep(arguments_dict &args) = 0;
69 virtual void kth_FCT_step(arguments_dict &args) = 0;
71 virtual void calculateMassMatrix(arguments_dict &args) = 0;
72 virtual void dissolutionFlash(arguments_dict &args) = 0;
73 virtual void calculateFlashFields(arguments_dict &args) = 0;
74};
75
76template <class CompKernelType, int nSpace, int nQuadraturePoints_element, int nDOF_mesh_trial_element, int nDOF_trial_element, int nDOF_test_element, int nQuadraturePoints_elementBoundary>
78public:
80 CompKernelType ck;
81 std::vector<double> rho_dof_member;
82 std::vector<double> rho_n_phi_dof_member;
84 // Compositional (p,z) state for the flash. Isothermal / fixed-salinity per
85 // solve. T_C_member is now wired through argsDict["T_C"] and set (like
86 // PSK_TYPE_member) at every top-level entry point from Coefficients.T_C, so
87 // temperature can be changed from the input deck without recompiling. The
88 // 20.0 default is only the pre-first-entry fallback. m_NaCl is still fixed
89 // (SP2005 salting-out is TODO); wire it the same way if salinity is needed.
90 double T_C_member = 20.0; // temperature [degC] (default; overwritten from argsDict["T_C"])
91 double m_NaCl_member = 0.0; // salinity [mol/kg] (SP2005 salting-out is TODO)
92 bool immiscible_member = false;
93 // Per-rock closure output: min / max over the rocks at each node of S_r,
94 // from the last residual evaluation (Newton's last one is at the converged
95 // state); NaN at one-rock nodes. Copied out by calculateFlashFields.
97 M_comp_co2() : nDOF_test_X_trial_element(nDOF_test_element * nDOF_trial_element), ck() { }
98 //
99 // Closure functions vgm_/bc_*_from_Se expect wetting effective saturation
100 // S_e = (S_w - S_wr)/(1 - S_wr) = (1 - u_n - S_wr)/(1 - S_wr).
101 // dS_e/du_n = -1/(1 - S_wr) (negative); the sign flip propagates through
102 // every chain rule (k_rw, theta_w, p_c) when caller uses dSe_du_n.
103 inline void evaluateCoefficients_from_Se(const int rowptr[nSpace], const int colind[nnz],
104 const double rho0, const double rho_transport, const double beta,
105 const double gravity[nSpace],
106 const double alpha, const double n_vg,
107 const double thetaR, const double thetaSR,
108 const double KWs[nnz],
109 const double &u_w, const double &u_n,
110 double &m, double &dm_du_w, double &dm_du_n,
111 double f[nSpace], double df_du_w[nSpace], double df_du_n[nSpace],
112 double a[nnz], double da_du_w[nnz], double da_du_n[nnz],
113 double as[nnz],
114 double &kr, double &dkr_du_w, double &dkr_du_n,
115 double &thetaW_out)
116 {
117 const double phi = thetaR + thetaSR; // == thetaS
118 const double S_wr = thetaR / phi; // residual S_w
119 const double one_m_Sr = 1.0 - S_wr; // = thetaSR/phi
120 // Se in wetting form, expressed in terms of u_n = S_n.
121 const double Se_raw = (1.0 - u_n - S_wr) / one_m_Sr;
122 // at the clips Se is held constant, so dSe/du_n=0.
123 // Without this, the closure's DthetaW_DSe (returned regardless of
124 // clipping) gets multiplied by +-1/(1-S_wr) and produces a non-zero (0,1)
125 // mass Jacobian entry in the infeasible-u_n region, which tricks Newton
126 // into overshooting further past saturation/residual.
127 double Se, dSe_du_n;
128 if (Se_raw <= 0.0) { Se = 0.0; dSe_du_n = 0.0; }
129 else if (Se_raw >= 1.0) { Se = 1.0; dSe_du_n = 0.0; }
130 else { Se = Se_raw; dSe_du_n = -1.0 / one_m_Sr; }
131
132 double thetaW, DthetaW_DSe, KWr, DKWr_DSe;
133 if (PSK_TYPE_member == 1) {
135 Se, alpha, n_vg, thetaR, thetaSR,
136 thetaW, DthetaW_DSe, KWr, DKWr_DSe);
137 } else {
139 Se, alpha, n_vg, thetaR, thetaSR,
140 thetaW, DthetaW_DSe, KWr, DKWr_DSe);
141 }
142 thetaW_out = thetaW;
143 // Density: rho_w(p_w) = rho_transport * exp(beta * p_w); beta in 1/Pa.
144 const double rhom = rho_transport * exp(beta * u_w);
145 const double drhom = beta * rhom;
146 // component-0 (H2O) accumulation, compositional (p,z) form:
147 // m_0 = phi * N * (1 - z), N = rho_g*S_g + rho_a*(1-S_g)
148 // u_w = p [Pa], u_n = z [-]. Flash gives S_g, rho_a, rho_g + (p,z) derivs.
149 // NOTE (P3c complete): the phase-based flux coeffs (f, kr) computed below are
150 // NO LONGER used for the H2O residual -- calculateResidual assembles the
151 // compositional flux F_0 directly. `a` (and rhom/thetaW) is retained only
152 // for the water-phase Darcy velocity projection (q_velocity) + diagnostics.
153 {
154 const double p_cl = fmax(u_w, 1.0e2);
157 const double Sa = 1.0 - fs.S_g;
158 const double N = fs.rho_g*fs.S_g + fs.rho_a*Sa;
159 const double dN_dp = fs.drho_g_dp*fs.S_g + fs.rho_g*fs.dS_g_dp
160 + fs.drho_a_dp*Sa - fs.rho_a*fs.dS_g_dp;
161 const double dN_dz = fs.drho_g_dz*fs.S_g + fs.rho_g*fs.dS_g_dz
162 + fs.drho_a_dz*Sa - fs.rho_a*fs.dS_g_dz;
163 m = phi * N * (1.0 - u_n);
164 dm_du_w = phi * (1.0 - u_n) * dN_dp;
165 dm_du_n = phi * ((1.0 - u_n) * dN_dz - N);
166 }
167 // Chain-rule factor for k_rw and downstream Se-derivatives.
168 const double DKWr_Du_n = DKWr_DSe * dSe_du_n;
169 for (int I = 0; I < nSpace; I++) {
170 f[I] = 0.0;
171 df_du_w[I] = 0.0;
172 df_du_n[I] = 0.0;
173 for (int ii = rowptr[I]; ii < rowptr[I + 1]; ii++) {
174 // Diffusion tensor a_w = rho_w * k_rw * (K/mu_w).
175 a[ii] = rhom * KWr * KWs[ii];
176 da_du_w[ii] = drhom * KWr * KWs[ii];
177 da_du_n[ii] = rhom * DKWr_Du_n * KWs[ii];
178 // Gravity flux f_w = rho_w^2 * k_rw * (K/mu_w) * g (pressure form;
179 // no /rho0 factor).
180 f[I] += rhom * rhom * KWr * KWs[ii] * gravity[colind[ii]];
181 df_du_w[I] += 2.0 * drhom * rhom * KWr * KWs[ii] * gravity[colind[ii]];
182 df_du_n[I] += rhom * rhom * DKWr_Du_n * KWs[ii] * gravity[colind[ii]];
183 as[ii] = rhom * KWs[ii];
184 kr = KWr;
185 dkr_du_w = 0.0; // k_rw depends on S_w (= 1-u_n) only
186 dkr_du_n = DKWr_Du_n;
187 }
188 }
189 }
190
191 // ---------------------------------------------------------------------------
192 // Component-1 (CO2) per-node closure -- the symmetric analog of
193 // evaluateCoefficients_from_Se for the gas/CO2 equation. Where the comp-0
194 // evaluator returns the wetting accumulation + tensor (a,f,kr), this returns
195 // the flash+psk PRIMITIVES that BOTH compositional CO2 flux forms are built
196 // from, all with analytic d/d{p,z}:
197 // * QP / tensor form (calculateResidual STAB=0, calculateJacobian):
198 // F_1 = rho_g*Y*u_g + rho_a*X*u_a,
199 // u_a = -(krw*KWs)(grad p - rho_a_mass g),
200 // u_g = -(krn*KWs/mu_n)(grad p + pcp*grad S_a - rho_g_mass g).
201 // * edge / scalar-mobility form (calculateResidual_entropy_viscosity P2):
202 // F_1 = tau*lam_g_up*gate*dPhi_g + tau*lam_a_up*dPhi_a,
203 // lam_g = (1/mu_n)*rho_g*Y*krn, lam_a = rho_a*X*krw.
204 // Conventions match the verified inline kernels: krn already carries krn_end
205 // (so the edge mobility uses cg = 1/mu_n); krw is the bare wetting relperm;
206 // KWs = K/mu_w is applied by the caller; gas molar density rho_g is treated
207 // as z-independent in rho_g_mass (drho_g/dz ~ 0, as in eftest / P2).
208 // Primary vars u_w = p [Pa], u_n = z [-]; PSK_TYPE_member / T_C_member /
209 // m_NaCl_member are read from the class state (set at every entry point).
210 // FD-verified standalone in comp1_closure_test.cpp; the lam/pc/rgm/ram values
211 // match the eftest-verified CO2 closure (COMP_CO2=true) to round-off.
213 double S_g, dS_g_dp, dS_g_dz; // flash gas saturation (gate + grad S_a)
214 double N, m, dm_dp, dm_dz; // total molar density N; accumulation m_1 = phi*N*z
215 double krw, dkrw_dp, dkrw_dz; // wetting relperm (aqueous Darcy)
216 double krn, dkrn_dp, dkrn_dz; // nonwetting relperm * krn_end (gas Darcy)
217 double pc, dpc_dp, dpc_dz, pcp; // capillary pressure; pcp = dp_c/dS_a (QP cross term)
218 double rho_g, rho_a, Y, X; // flash phase props (QP weights)
221 double rgm, drgm_dp, drgm_dz; // rho_g_mass = rho_g * Mbar_g (gravity)
222 double ram, dram_dp, dram_dz; // rho_a_mass = rho_a * Mbar_a (gravity)
223 double lam_g, dlam_g_dp, dlam_g_dz; // gas molar mobility (1/mu_n)*rho_g*Y*krn (edge)
224 double lam_a, dlam_a_dp, dlam_a_dz; // aqueous molar mobility rho_a*X*krw (edge)
225 };
226
227 inline Comp1Closure evaluateCoefficients_comp1(const double alpha, const double n_vg, const double bc_Se_min,
228 const double thetaR, const double thetaSR,
229 const double krn_end, const double mu_n,
230 const double u_w, const double u_n)
231 {
232 Comp1Closure o;
233 const double phi = thetaR + thetaSR; // == thetaS
234 const double S_wr = thetaR / phi;
235 const double one_m_Sr = 1.0 - S_wr;
236 const double cg = 1.0 / mu_n; // krn_end folded into krn below
238 const double p_cl = fmax(u_w, 1.0e2);
241 o.S_g = f.S_g; o.dS_g_dp = f.dS_g_dp; o.dS_g_dz = f.dS_g_dz;
242 o.rho_g = f.rho_g; o.rho_a = f.rho_a; o.Y = f.Y; o.X = f.X;
243 o.drho_g_dp = f.drho_g_dp; o.drho_g_dz = f.drho_g_dz;
244 o.drho_a_dp = f.drho_a_dp; o.drho_a_dz = f.drho_a_dz;
245 o.dY_dp = f.dY_dp; o.dY_dz = f.dY_dz; o.dX_dp = f.dX_dp; o.dX_dz = f.dX_dz;
246 // accumulation m_1 = phi*N*z, N = rho_g*S_g + rho_a*S_a.
247 const double Sa = 1.0 - f.S_g;
248 o.N = f.rho_g*f.S_g + f.rho_a*Sa;
249 const double dN_dp = f.drho_g_dp*f.S_g + f.rho_g*f.dS_g_dp + f.drho_a_dp*Sa - f.rho_a*f.dS_g_dp;
250 const double dN_dz = f.drho_g_dz*f.S_g + f.rho_g*f.dS_g_dz + f.drho_a_dz*Sa - f.rho_a*f.dS_g_dz;
251 o.m = phi * o.N * u_n;
252 o.dm_dp = phi * dN_dp * u_n;
253 o.dm_dz = phi * (dN_dz * u_n + o.N); // d(phi*N*z)/dz
254 // wetting effective saturation from S_a; clipped derivatives.
255 const double Se_raw = (Sa - S_wr) / one_m_Sr;
256 double Se, dSe_dp, dSe_dz;
257 if (Se_raw <= 0.0) { Se = 0.0; dSe_dp = 0.0; dSe_dz = 0.0; }
258 else if (Se_raw >= 1.0) { Se = 1.0; dSe_dp = 0.0; dSe_dz = 0.0; }
259 else { Se = Se_raw; dSe_dp = -f.dS_g_dp/one_m_Sr; dSe_dz = -f.dS_g_dz/one_m_Sr; }
260 double krn=0,dkrn=0,krw=0,dkrw=0,thW=0,DthW=0,pc=0,dpc_dSe=0,d2pc=0;
261 if (PSK_TYPE_member == 1) {
262 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se, alpha, n_vg, krn, dkrn);
263 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se, alpha, n_vg, thetaR, thetaSR, thW, DthW, krw, dkrw);
264 proteus::m_comp_co2::psk::bc_pc_from_Se(Se, alpha, n_vg, bc_Se_min, pc, dpc_dSe, d2pc);
265 } else {
266 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se, alpha, n_vg, krn, dkrn);
267 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se, alpha, n_vg, thetaR, thetaSR, thW, DthW, krw, dkrw);
268 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se, alpha, n_vg, pc, dpc_dSe, d2pc);
269 }
270 krn *= krn_end; // fold krn_end into the relperm
271 dkrn *= krn_end;
272 o.krw = krw; o.dkrw_dp = dkrw*dSe_dp; o.dkrw_dz = dkrw*dSe_dz;
273 o.krn = krn; o.dkrn_dp = dkrn*dSe_dp; o.dkrn_dz = dkrn*dSe_dz;
274 o.pc = pc; o.dpc_dp = dpc_dSe*dSe_dp; o.dpc_dz = dpc_dSe*dSe_dz;
275 o.pcp = dpc_dSe / one_m_Sr; // dp_c/dS_a (QP capillary cross term)
276 const double Mbar_g = f.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-f.Y)*::m_comp_co2::eos::M_H2O_KG;
277 const double Mbar_a = f.X*::m_comp_co2::eos::M_CO2_KG + (1.0-f.X)*::m_comp_co2::eos::M_H2O_KG;
278 o.rgm = f.rho_g*Mbar_g; o.ram = f.rho_a*Mbar_a;
279 o.drgm_dp = f.drho_g_dp*Mbar_g + f.rho_g*f.dY_dp*dMm;
280 o.drgm_dz = f.drho_g_dz*Mbar_g + f.rho_g*f.dY_dz*dMm; // drho_g/dz ~ 0
281 o.dram_dp = f.drho_a_dp*Mbar_a + f.rho_a*f.dX_dp*dMm;
282 o.dram_dz = f.drho_a_dz*Mbar_a + f.rho_a*f.dX_dz*dMm;
283 // gas molar mobility lam_g = cg*rho_g*Y*krn (krn already carries krn_end).
284 o.lam_g = cg*f.rho_g*f.Y*o.krn;
285 o.dlam_g_dp = cg*(f.drho_g_dp*f.Y*o.krn + f.rho_g*f.dY_dp*o.krn + f.rho_g*f.Y*o.dkrn_dp);
286 o.dlam_g_dz = cg*(f.drho_g_dz*f.Y*o.krn + f.rho_g*f.dY_dz*o.krn + f.rho_g*f.Y*o.dkrn_dz);
287 // aqueous molar mobility lam_a = rho_a*X*krw.
288 o.lam_a = f.rho_a*f.X*o.krw;
289 o.dlam_a_dp = f.drho_a_dp*f.X*o.krw + f.rho_a*f.dX_dp*o.krw + f.rho_a*f.X*o.dkrw_dp;
290 o.dlam_a_dz = f.drho_a_dz*f.X*o.krw + f.rho_a*f.dX_dz*o.krw + f.rho_a*f.X*o.dkrw_dz;
291 return o;
292 }
293
294 // Inversion routines (vgm_invert_analytic / vgm_invert_newton) are not used by
295 // this module; the maintained copies live in proteus/pskRelations.h.
296
297 inline void calculateCFL(const double &elementDiameter, const double df[nSpace], double &cfl)
298 {
299 double h, nrm_v;
300 h = elementDiameter;
301 nrm_v = 0.0;
302 for (int I = 0; I < nSpace; I++) nrm_v += df[I] * df[I];
303 nrm_v = sqrt(nrm_v);
304 cfl = nrm_v / h;
305 }
306
307 inline void calculateSubgridError_tau(const double &elementDiameter, const double &dmt, const double dH[nSpace], double &cfl, double &tau)
308 {
309 double h, nrm_v, oneByAbsdt;
310 h = elementDiameter;
311 nrm_v = 0.0;
312 for (int I = 0; I < nSpace; I++) nrm_v += dH[I] * dH[I];
313 nrm_v = sqrt(nrm_v);
314 cfl = nrm_v / h;
315 oneByAbsdt = fabs(dmt);
316 tau = 1.0 / (2.0 * nrm_v / h + oneByAbsdt + 1.0e-8);
317 }
318
319 inline void calculateSubgridError_tau(const double &Ct_sge, const double G[nSpace * nSpace], const double &A0, const double Ai[nSpace], double &tau_v, double &cfl)
320 {
321 double v_d_Gv = 0.0;
322 for (int I = 0; I < nSpace; I++)
323 for (int J = 0; J < nSpace; J++) v_d_Gv += Ai[I] * G[I * nSpace + J] * Ai[J];
324 tau_v = 1.0 / sqrt(Ct_sge * A0 * A0 + v_d_Gv);
325 }
326
327 inline void calculateNumericalDiffusion(const double &shockCapturingDiffusion, const double &elementDiameter, const double &strong_residual, const double grad_u[nSpace], double &numDiff)
328 {
329 double h, num, den, n_grad_u;
330 h = elementDiameter;
331 n_grad_u = 0.0;
332 for (int I = 0; I < nSpace; I++) n_grad_u += grad_u[I] * grad_u[I];
333 num = shockCapturingDiffusion * 0.5 * h * fabs(strong_residual);
334 den = sqrt(n_grad_u) + 1.0e-8;
335 numDiff = num / den;
336 }
337
338 inline void exteriorNumericalFlux(const double &bc_flux, int rowptr[nSpace], int colind[nnz], int isSeepageFace, int &isDOFBoundary, double n[nSpace], double bc_u, double K[nnz], double grad_psi[nSpace], double u, double K_rho_g[nSpace], double penalty, double &flux)
339 {
340 double v_I, bc_u_seepage = 0.0;
341 if (isSeepageFace || isDOFBoundary) {
342 flux = 0.0;
343 for (int I = 0; I < nSpace; I++) {
344 //gravity
345 v_I = K_rho_g[I];
346 //pressure head
347 for (int m = rowptr[I]; m < rowptr[I + 1]; m++) { v_I -= K[m] * grad_psi[colind[m]]; }
348 flux += v_I * n[I];
349 }
350 if (isSeepageFace) bc_u = bc_u_seepage;
351 flux += penalty * (u - bc_u);
352 //flux -= penalty * bc_u;
353 if (isSeepageFace) {
354 if (flux > 0.0) {
355 isDOFBoundary = 1;
356 bc_u = bc_u_seepage;
357 } else {
358 isDOFBoundary = 0;
359 flux = 0.0;
360 }
361 }
362 } else flux = bc_flux;
363 }
364
365 void exteriorNumericalFluxJacobian(const int rowptr[nSpace], const int colind[nnz], const int isDOFBoundary, const double n[nSpace], const double K[nnz], const double dK[nnz], const double grad_psi[nSpace], const double grad_v[nSpace], const double dK_rho_g[nSpace], const double v, const double penalty, double &fluxJacobian)
366 {
367 if (isDOFBoundary) {
368 fluxJacobian = 0.0;
369 for (int I = 0; I < nSpace; I++) {
370 //gravity
371 fluxJacobian += dK_rho_g[I] * v * n[I];
372 //pressure head
373 for (int m = rowptr[I]; m < rowptr[I + 1]; m++) { fluxJacobian -= (K[m] * grad_v[colind[m]] + dK[m] * v * grad_psi[colind[m]]) * n[I]; }
374 }
375 //Dirichlet penalty
376 fluxJacobian += penalty * v;
377 } else fluxJacobian = 0.0;
378 }
379
380inline void exteriorNumericalFlux2(const double &bc_flux, int rowptr[nSpace], int colind[nnz], int isSeepageFace, int &isDOFBoundary, double n[nSpace], double bc_u, double K[nnz], double grad_psi[nSpace], double u, double K_rho_g[nSpace], double penalty, double &flux, double &bflux)
381 {
382 double v_I, bc_u_seepage = 0.0;
383 if (isSeepageFace || isDOFBoundary) {
384 flux = 0.0;
385 bflux = 0.0;
386 for (int I = 0; I < nSpace; I++) {
387 //gravity
388 v_I = K_rho_g[I];
389 //pressure head
390 for (int m = rowptr[I]; m < rowptr[I + 1]; m++) { v_I -= K[m] * grad_psi[colind[m]]; }
391 flux += v_I * n[I];
392 }
393 if (isSeepageFace) bc_u = bc_u_seepage;
394 flux += penalty * (u - bc_u);
395 bflux += penalty * (u - bc_u);
396 if (isSeepageFace) {
397 if (flux > 0.0) {
398 isDOFBoundary = 1;
399 } else {
400 isDOFBoundary = 0;
401 flux = 0.0;
402 bflux = 0.0;
403 }
404 }
405 } else {
406 flux = bc_flux;
407 bflux = bc_flux;
408 }
409 }
410
411 void exteriorNumericalFluxJacobian2(const int rowptr[nSpace], const int colind[nnz], const int isDOFBoundary, const double n[nSpace], const double Ks[nnz], const double K[nnz], const double dK[nnz], const double grad_psi[nSpace], const double grad_v[nSpace], const double dK_rho_g[nSpace], const double v, const double penalty, double &fluxJacobian, double &bfluxJacobian)
412 {
413 if (isDOFBoundary) {
414 fluxJacobian = 0.0;
415 bfluxJacobian = 0.0;
416 for (int I = 0; I < nSpace; I++) {
417 for (int m = rowptr[I]; m < rowptr[I + 1]; m++) {
418 fluxJacobian -= Ks[m] * grad_v[colind[m]] * n[I];
419 }
420 }
421 //Dirichlet penalty
422 bfluxJacobian = penalty * v;
423 } else {
424 fluxJacobian = 0.0;
425 bfluxJacobian = 0.0;
426 }
427 }
428
429 double seepagefluxcalculator(double anb_seepage_flux, int isSeepageFace, double dS, double flux_ext)
430 {
431 if (isSeepageFace) { anb_seepage_flux += flux_ext * dS; }
432 return anb_seepage_flux;
433 }
434
436 {
437 xt::pyarray<double> &mesh_trial_ref = args.array<double>("mesh_trial_ref");
438 xt::pyarray<double> &mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
439 xt::pyarray<double> &mesh_dof = args.array<double>("mesh_dof");
440 xt::pyarray<double> &mesh_velocity_dof = args.array<double>("mesh_velocity_dof");
441 double MOVING_DOMAIN = args.scalar<double>("MOVING_DOMAIN");
442 xt::pyarray<int> &mesh_l2g = args.array<int>("mesh_l2g");
443 xt::pyarray<double> &dV_ref = args.array<double>("dV_ref");
444 xt::pyarray<double> &u_trial_ref = args.array<double>("u_trial_ref");
445 xt::pyarray<double> &u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
446 xt::pyarray<double> &u_test_ref = args.array<double>("u_test_ref");
447 xt::pyarray<double> &u_grad_test_ref = args.array<double>("u_grad_test_ref");
448 xt::pyarray<double> &mesh_trial_trace_ref = args.array<double>("mesh_trial_trace_ref");
449 xt::pyarray<double> &mesh_grad_trial_trace_ref = args.array<double>("mesh_grad_trial_trace_ref");
450 xt::pyarray<double> &dS_ref = args.array<double>("dS_ref");
451 xt::pyarray<double> &u_trial_trace_ref = args.array<double>("u_trial_trace_ref");
452 xt::pyarray<double> &u_grad_trial_trace_ref = args.array<double>("u_grad_trial_trace_ref");
453 xt::pyarray<double> &u_test_trace_ref = args.array<double>("u_test_trace_ref");
454 xt::pyarray<double> &u_grad_test_trace_ref = args.array<double>("u_grad_test_trace_ref");
455 xt::pyarray<double> &normal_ref = args.array<double>("normal_ref");
456 xt::pyarray<double> &boundaryJac_ref = args.array<double>("boundaryJac_ref");
457 int nElements_global = args.scalar<int>("nElements_global");
458 xt::pyarray<double> &ebqe_penalty_ext = args.array<double>("ebqe_penalty_ext");
459 xt::pyarray<int> &elementMaterialTypes = args.array<int>("elementMaterialTypes");
460 xt::pyarray<int> &isSeepageFace = args.array<int>("isSeepageFace");
461 xt::pyarray<int> &a_rowptr = args.array<int>("a_rowptr");
462 xt::pyarray<int> &a_colind = args.array<int>("a_colind");
463 double rho = args.scalar<double>("rho");
464 double beta = args.scalar<double>("beta");
465
467 xt::pyarray<double> &q_rho = args.array<double>("q_rho");
468 xt::pyarray<double> &ebqe_rho = args.array<double>("ebqe_rho");
469
470 xt::pyarray<double> &gravity = args.array<double>("gravity");
471 xt::pyarray<double> &alpha = args.array<double>("alpha");
472 xt::pyarray<double> &n = args.array<double>("n");
473 xt::pyarray<double> &thetaR = args.array<double>("thetaR");
474 xt::pyarray<double> &thetaSR = args.array<double>("thetaSR");
475 xt::pyarray<double> &KWs = args.array<double>("KWs");
476 xt::pyarray<double> &krn_end = args.array<double>("krn_end");
477 xt::pyarray<double> &S_gr = args.array<double>("S_gr");
478 xt::pyarray<double> &bc_Se_min = args.array<double>("bc_Se_min");
479 double mu_n = args.scalar<double>("mu_n");
480 double useMetrics = args.scalar<double>("useMetrics");
481 double alphaBDF = args.scalar<double>("alphaBDF");
482 int lag_shockCapturing = args.scalar<int>("lag_shockCapturing");
483 double shockCapturingDiffusion = args.scalar<double>("shockCapturingDiffusion");
484 double sc_uref = args.scalar<double>("sc_uref");
485 double sc_alpha = args.scalar<double>("sc_alpha");
486 xt::pyarray<int> &u_l2g = args.array<int>("u_l2g");
487 xt::pyarray<double> &elementDiameter = args.array<double>("elementDiameter");
488 xt::pyarray<double> &u_dof = args.array<double>("u_dof");
489 xt::pyarray<double> &u_dof_old = args.array<double>("u_dof_old");
490 xt::pyarray<double> &velocity = args.array<double>("velocity");
491 xt::pyarray<double> &q_m = args.array<double>("q_m");
492 xt::pyarray<double> &q_theta = args.array<double>("q_theta");
493 xt::pyarray<double> &q_u = args.array<double>("q_u");
494 xt::pyarray<double> &q_dV = args.array<double>("q_dV");
495 xt::pyarray<double> &q_m_betaBDF = args.array<double>("q_m_betaBDF");
496 xt::pyarray<double> &cfl = args.array<double>("cfl");
497 xt::pyarray<double> &q_numDiff_u = args.array<double>("q_numDiff_u");
498 xt::pyarray<double> &q_numDiff_u_last = args.array<double>("q_numDiff_u_last");
499 int offset_u = args.scalar<int>("offset_u");
500 int stride_u = args.scalar<int>("stride_u");
501 // component-1 (S_n) mass equation args.
502 // Used in the dedicated component-1 element loop appended at the end
503 // of this function. Not consumed by the existing component-0 logic.
504 const double dt = args.scalar<double>("dt");
505 xt::pyarray<double> &u_dof_n = args.array<double>("u_dof_n");
506 xt::pyarray<double> &u_dof_n_old = args.array<double>("u_dof_n_old");
507 // gas-phase density (linear EOS). rho_n is the reference density and
508 // p_ref_n the reference pressure: rho_n_local(p_n) = rho_n*p_n/p_ref_n
509 // when p_ref_n > 0; constant rho_n otherwise.
510 const double rho_n = args.scalar<double>("rho_n");
511 const double p_ref_n = args.scalar<double>("p_ref_n");
512 const bool rho_n_compressible = (p_ref_n > 0.0);
513 const double c_n = rho_n_compressible ? (rho_n / p_ref_n) : 0.0;
514 const int offset_n = args.scalar<int>("offset_n");
515 const int stride_n = args.scalar<int>("stride_n");
516 // Stage 3b: gas-side kinetic dissolution sink. R_diss = k_d * S_n *
517 // (1 - S_n) * theta_w * rho_w(c) * (c_sat - c) is subtracted from the
518 // gas-equation residual at each quadrature point. c is read from TADR's
519 // u[0].dof aliased Python-side and passed in as c_dof. k_d=0 disables
520 // the sink (legacy behavior).
521 xt::pyarray<double> &c_dof = args.array<double>("c_dof");
522 const double k_d = args.scalar<double>("k_d");
523 const double c_sat = args.scalar<double>("c_sat");
524 // CO2 injection: per-node source field (built Python-side, schedule-gated).
525 // Applied like R_diss but with opposite sign -- a source, not a sink.
526 // All-zero array when no injection is configured.
527 xt::pyarray<double> &injection_dof = args.array<double>("injection_dof");
528 xt::pyarray<double> &globalResidual = args.array<double>("globalResidual");
529 int nExteriorElementBoundaries_global = args.scalar<int>("nExteriorElementBoundaries_global");
530 xt::pyarray<int> &exteriorElementBoundariesArray = args.array<int>("exteriorElementBoundariesArray");
531 xt::pyarray<int> &elementBoundaryElementsArray = args.array<int>("elementBoundaryElementsArray");
532 xt::pyarray<int> &elementBoundaryLocalElementBoundariesArray = args.array<int>("elementBoundaryLocalElementBoundariesArray");
533 xt::pyarray<double> &ebqe_velocity_ext = args.array<double>("ebqe_velocity_ext");
534 xt::pyarray<int> &isDOFBoundary_u = args.array<int>("isDOFBoundary_u");
535 xt::pyarray<double> &ebqe_bc_u_ext = args.array<double>("ebqe_bc_u_ext");
536 // component-1 (S_n) boundary arrays.
537 xt::pyarray<int> &isDOFBoundary_n = args.array<int>("isDOFBoundary_n");
538 xt::pyarray<double> &ebqe_bc_u_n_ext = args.array<double>("ebqe_bc_u_n_ext");
539 xt::pyarray<int> &isFluxBoundary_u = args.array<int>("isFluxBoundary_u");
540 xt::pyarray<double> &ebqe_bc_flux_ext = args.array<double>("ebqe_bc_flux_ext");
541 xt::pyarray<double> &ebqe_phi = args.array<double>("ebqe_phi");
542 double epsFact = args.scalar<double>("epsFact");
543 xt::pyarray<double> &ebqe_u = args.array<double>("ebqe_u");
544 xt::pyarray<double> &ebqe_theta = args.array<double>("ebqe_theta");
545 xt::pyarray<double> &ebqe_flux = args.array<double>("ebqe_flux");
546 // VMS
547 double VMS = args.scalar<double>("VMS");
548 // PARAMETERS FOR EDGE BASED STABILIZATION
549 double cE = args.scalar<double>("cE");
550 double cK = args.scalar<double>("cK");
551 // PARAMETERS FOR LOG BASED ENTROPY FUNCTION
552 double uL = args.scalar<double>("uL");
553 double uR = args.scalar<double>("uR");
554 // PARAMETERS FOR EDGE VISCOSITY
555 int numDOFs = args.scalar<int>("numDOFs");
556 // numDOFs is the compact component-0 free-DOF count used by the stabilized
557 // DOF loops. Full-matrix slots are recovered from offset/stride-aware CSR
558 // indexing against the interleaved global matrix.
559 int numDOFs_u = args.scalar<int>("numDOFs_u");
560 int NNZ = args.scalar<int>("NNZ");
561 xt::pyarray<int> &csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
562 xt::pyarray<int> &csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
563 xt::pyarray<int> &csrRowIndeces_Full = args.array<int>("csrRowIndeces_Full");
564 xt::pyarray<int> &csrColumnOffsets_Full = args.array<int>("csrColumnOffsets_Full");
565 xt::pyarray<int> &csrRowIndeces_CellLoops = args.array<int>("csrRowIndeces_CellLoops");
566 xt::pyarray<int> &csrColumnOffsets_CellLoops = args.array<int>("csrColumnOffsets_CellLoops");
567 xt::pyarray<int> &csrColumnOffsets_eb_CellLoops = args.array<int>("csrColumnOffsets_eb_CellLoops");
568 // C matrices
569 xt::pyarray<double> &Cx = args.array<double>("Cx");
570 xt::pyarray<double> &Cy = args.array<double>("Cy");
571 xt::pyarray<double> &Cz = args.array<double>("Cz");
572 xt::pyarray<double> &CTx = args.array<double>("CTx");
573 xt::pyarray<double> &CTy = args.array<double>("CTy");
574 xt::pyarray<double> &CTz = args.array<double>("CTz");
575 xt::pyarray<double> &ML = args.array<double>("ML");
576 xt::pyarray<double> &delta_x_ij = args.array<double>("delta_x_ij");
577 // PARAMETERS FOR 1st or 2nd ORDER MPP METHOD
578 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
579 STABILIZATION STABILIZATION_TYPE{static_cast<STABILIZATION>(args.scalar<int>("STABILIZATION_TYPE"))};
580 int ENTROPY_TYPE = args.scalar<int>("ENTROPY_TYPE");
581 // PSK closure selector for evaluateCoefficients (read from argsDict).
582 PSK_TYPE_member = args.scalar<int>("PSK_TYPE");
583 immiscible_member = (args.scalar<int>("immiscible") != 0);
584 T_C_member = args.scalar<double>("T_C"); // temperature [degC] from input
585 // FOR FCT
586 xt::pyarray<double> &dLow = args.array<double>("dLow");
587 xt::pyarray<double> &fluxMatrix = args.array<double>("fluxMatrix");
588 // AUX QUANTITIES OF INTEREST
589 xt::pyarray<double> &quantDOFs = args.array<double>("quantDOFs");
590
591 assert(a_rowptr.data()[nSpace] == nnz);
592 assert(a_rowptr.data()[nSpace] == nSpace);
593 //cek should this be read in?
594 double Ct_sge = 4.0;
595
596 xt::pyarray<double> &anb_seepage_flux_n = args.array<double>("anb_seepage_flux_n");
597
598 xt::pyarray<double> &velocity_couple = args.array<double>("velocity_couple");
599 xt::pyarray<double> &ebqe_velocity_ext_couple = args.array<double>("ebqe_velocity_ext_couple");
600
601 // xt::pyarray<double> &q_x = args.array<double>("q_x");
602 // xt::pyarray<double> &ebqe_x = args.array<double>("ebqe_x");
603
604 //double anb_seepage_flux=0.0;
605 double &anb_seepage_flux(args.scalar<double>("anb_seepage_flux"));
606 xt::pyarray<double> &q_velocity = args.array<double>("q_velocity");
607 anb_seepage_flux = 0.0;
608
609 //loop over elements to compute volume integrals and load them into element and global residual
610 //
611 //eN is the element index
612 //eN_k is the quadrature point index for a scalar
613 //eN_k_nSpace is the quadrature point index for a vector
614 //eN_i is the element test function index
615 //eN_j is the element trial function index
616 //eN_k_j is the quadrature point index for a trial function
617 //eN_k_i is the quadrature point index for a trial function
618 for (int eN = 0; eN < nElements_global; eN++) {
619 //declare local storage for element residual and initialize
620 double elementResidual_u[nDOF_test_element];
621 for (int i = 0; i < nDOF_test_element; i++) { elementResidual_u[i] = 0.0; } //i
622 //loop over quadrature points and compute integrands
623 for (int k = 0; k < nQuadraturePoints_element; k++) {
624 //compute indeces and declare local storage
625 int eN_k = eN * nQuadraturePoints_element + k, eN_k_nSpace = eN_k * nSpace, eN_nDOF_trial_element = eN * nDOF_trial_element;
626 double u = 0.0, grad_u[nSpace], grad_u_old[nSpace], m = 0.0, dm = 0.0, f[nSpace], df[nSpace], a[nnz], da[nnz], as[nnz], m_t = 0.0, dm_t = 0.0, pdeResidual_u = 0.0, tau = 0.0, tau0 = 0.0, tau1 = 0.0, numDiff0 = 0.0, numDiff1 = 0.0, jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], u_grad_trial[nDOF_trial_element * nSpace], u_test_dV[nDOF_trial_element], u_grad_test_dV[nDOF_test_element * nSpace], dV, x, y, z, xt, yt, zt, G[nSpace * nSpace], G_dd_G, tr_G, norm_Rv;
627 //
628 //compute solution and gradients at quadrature points
629 //
630 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), mesh_grad_trial_ref.data(), jac, jacDet, jacInv, x, y, z);
631 ck.calculateMappingVelocity_element(eN, k, mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), xt, yt, zt);
632 //get the physical integration weight
633 dV = fabs(jacDet) * dV_ref.data()[k];
634 q_dV.data()[eN_k] = dV;
635 ck.calculateG(jacInv, G, G_dd_G, tr_G);
636 //get the trial function gradients
637 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace], jacInv, u_grad_trial);
638 //get the solution
639 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], &u_trial_ref.data()[k * nDOF_trial_element], u);
640 //get the solution gradients
641 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial, grad_u);
642 // P3c: gradient of z (comp-1 DOF) at this QP -- the comp-0 component flux
643 // needs grad S_a = -(dSg/dp grad p + dSg/dz grad z).
644 double grad_u_n[nSpace];
645 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial, grad_u_n);
646
647 // //populate q_x
648 // const int eN_k_3d = eN_k * 3;
649 // q_x.data()[eN_k_3d + 0] = x;
650 // q_x.data()[eN_k_3d + 1] = y;
651 // q_x.data()[eN_k_3d + 2] = z;
652
653 //precalculate test function products with integration weights
654 for (int j = 0; j < nDOF_trial_element; j++) {
655 u_test_dV[j] = u_test_ref.data()[k * nDOF_trial_element + j] * dV;
656 for (int I = 0; I < nSpace; I++) {
657 u_grad_test_dV[j * nSpace + I] = u_grad_trial[j * nSpace + I] * dV; //cek warning won't work for Petrov-Galerkin
658 }
659 }
660 //
661 //calculate pde coefficients at quadrature points
662 //
663 double Kr, dKr, thetaW;
664 const double rho_local = q_rho.data()[eN_k];
665 const double rho_velocity = std::fabs(rho_local) > 1.0e-12 ? rho_local : rho;
666 // Cross-derivatives (dm_du_n, df_du_n, da_du_n, dkr_du_n) are unused in
667 // the residual; the (0,1) Jacobian cross-block consumes them elsewhere.
668 double dm_du_n_qp = 0.0, dkr_du_n_qp = 0.0;
669 double df_du_n_qp[nSpace];
670 double da_du_n_qp[nnz];
671 for (int I = 0; I < nSpace; I++) df_du_n_qp[I] = 0.0;
672 for (int ii = 0; ii < nnz; ii++) da_du_n_qp[ii] = 0.0;
673 double u_n_qp = 0.0;
674 ck.valFromDOF(u_dof_n.data(),
675 &u_l2g.data()[eN_nDOF_trial_element],
676 &u_trial_ref.data()[k * nDOF_trial_element], u_n_qp);
677 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_local, beta, gravity.data(),
678 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
679 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
680 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], u, u_n_qp,
681 m, dm, dm_du_n_qp, f, df, df_du_n_qp, a, da, da_du_n_qp,
682 as, Kr, dKr, dkr_du_n_qp, thetaW);
683 q_theta.data()[eN_k] = thetaW;
684
685
686 for (int I = 0; I < nSpace; ++I) {
687 q_velocity.data()[eN_k_nSpace + I] = grad_u[I];
688 }
689 // Darcy Velocity
690 double pressure_gradient[nSpace];
691 for (int J=0; J<nSpace; ++J)
692 pressure_gradient[J] = grad_u[J] - rho_velocity * gravity.data()[J];
693 // q_w = -(a/rho_w) * (grad p_w - rho_w g) = -(k_rw K/mu_w) * (grad p_w - rho_w g).
694 for (int I=0; I<nSpace; ++I) {
695 double acc = 0.0;
696 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I+1]; ++ii) {
697 const int J = a_colind.data()[ii];
698 acc += (a[ii] / rho_velocity) * pressure_gradient[J];
699 }
700 velocity.data()[eN_k_nSpace + I] = -acc;
701 velocity_couple.data()[eN_k_nSpace + I] = -acc ;
702 }
703 //
704 // Compositional H2O accumulation m_0 = phi*N*(1-z), N = rho_g*S_g +
705 // rho_a*S_a (overrides the phase-based m from evaluateCoefficients_from_Se;
706 // (p,z) formulation -- consistent with the (0,0)/(0,1) mass Jacobian).
707 {
708 const int mat0 = elementMaterialTypes.data()[eN];
709 const double phi0_m = thetaR.data()[mat0] + thetaSR.data()[mat0];
710 const double p0_m = fmax(u, 1.0e2);
713 const double Nm = fsm.rho_g*fsm.S_g + fsm.rho_a*(1.0 - fsm.S_g);
714 const double dNm_dp = fsm.drho_g_dp*fsm.S_g + fsm.rho_g*fsm.dS_g_dp
715 + fsm.drho_a_dp*(1.0-fsm.S_g) - fsm.rho_a*fsm.dS_g_dp;
716 m = phi0_m * Nm * (1.0 - u_n_qp);
717 dm = phi0_m * dNm_dp * (1.0 - u_n_qp); // d m_0/dp (used by bdf/subgrid only)
718 }
719 //
720 //calculate time derivative at quadrature points
721 //
722 ck.bdf(alphaBDF, q_m_betaBDF.data()[eN_k], m, dm, m_t, dm_t);
723 //
724 //calculate subgrid error (strong residual and adjoint)
725 //
726 //calculate strong residual
727 // pdeResidual_u = ck.Mass_strong(m_t) + ck.Advection_strong(df, grad_u);
728 // //calculate adjoint
729 // for (int i = 0; i < nDOF_test_element; i++) {
730 // int i_nSpace = i * nSpace;
731 // Lstar_u[i] = ck.Advection_adjoint(df, &u_grad_test_dV[i_nSpace]);
732 // }
733 // //calculate tau and tau*Res
734 // calculateSubgridError_tau(elementDiameter[eN], dm_t, df, cfl[eN_k], tau0);
735 // calculateSubgridError_tau(Ct_sge, G, dm_t, df, tau1, cfl[eN_k]);
736
737 // tau = useMetrics * tau1 + (1.0 - useMetrics) * tau0;
738
739 // subgridError_u = -tau * pdeResidual_u;
740 // //
741 // //calculate shock capturing diffusion
742 // //
743 // ck.calculateNumericalDiffusion(shockCapturingDiffusion, elementDiameter[eN], pdeResidual_u, grad_u, numDiff0);
744 // ck.calculateNumericalDiffusion(shockCapturingDiffusion, sc_uref, sc_alpha, G, G_dd_G, pdeResidual_u, grad_u, numDiff1);
745 // q_numDiff_u[eN_k] = useMetrics * numDiff1 + (1.0 - useMetrics) * numDiff0;
746 // ===== P3c: component H2O molar flux F_0 = rho_g*(1-Y)*u_g + rho_a*(1-X)*u_a =====
747 // Same two phase Darcy velocities as the comp-1 flux, weighted by the H2O
748 // mole fractions (1-Y) in gas, (1-X) in aqueous. Props from the flash
749 // saturation S_g (S_a = 1 - S_g); psk closures take wetting Se_a0.
750 const int mat_eN0 = elementMaterialTypes.data()[eN];
751 const double alpha_eN0 = alpha.data()[mat_eN0];
752 const double n_vg_eN0 = n.data()[mat_eN0];
753 const double krn_end0 = krn_end.data()[mat_eN0];
754 const double *KWs_eN0 = &KWs.data()[mat_eN0 * nnz];
755 const double phi0 = thetaR.data()[mat_eN0] + thetaSR.data()[mat_eN0];
756 const double S_wr0 = thetaR.data()[mat_eN0] / phi0;
757 const double one_m_Sr0 = 1.0 - S_wr0;
758 const double Se_trap_L771 = 1.0 - S_gr.data()[mat_eN0] / one_m_Sr0; // gas-only residual trapping
759 const double p_cl0 = fmax(u, 1.0e2);
762 const double Se_a0 = fmin(fmax((1.0 - fs0.S_g - S_wr0) / one_m_Sr0, 0.0), 1.0);
763 double KWr0 = 0.0, DKWr0 = 0.0, thW0 = 0.0, DthW0 = 0.0;
764 double KNr0 = 0.0, DKNr0 = 0.0, pc0 = 0.0, dpc_dSe0 = 0.0, d2pc0 = 0.0;
765 if (PSK_TYPE_member == 1) {
766 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0,
767 thetaR.data()[mat_eN0], thetaSR.data()[mat_eN0], thW0, DthW0, KWr0, DKWr0);
768 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0, KNr0, DKNr0, Se_trap_L771);
769 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_a0, alpha_eN0, n_vg_eN0, bc_Se_min.data()[mat_eN0], pc0, dpc_dSe0, d2pc0);
770 } else {
771 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0,
772 thetaR.data()[mat_eN0], thetaSR.data()[mat_eN0], thW0, DthW0, KWr0, DKWr0);
773 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0, KNr0, DKNr0, Se_trap_L771);
774 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_a0, alpha_eN0, n_vg_eN0, pc0, dpc_dSe0, d2pc0);
775 }
776 KNr0 *= krn_end0;
777 const double pcp0 = dpc_dSe0 / one_m_Sr0;
778 const double Mbar_g0 = fs0.Y*::m_comp_co2::eos::M_CO2_KG + (1.0 - fs0.Y)*::m_comp_co2::eos::M_H2O_KG;
779 const double Mbar_a0 = fs0.X*::m_comp_co2::eos::M_CO2_KG + (1.0 - fs0.X)*::m_comp_co2::eos::M_H2O_KG;
780 const double rho_g_mass0 = fs0.rho_g*Mbar_g0;
781 const double rho_a_mass0 = fs0.rho_a*Mbar_a0;
782 double F0[nSpace];
783 for (int I = 0; I < nSpace; I++) {
784 double ua = 0.0, ug = 0.0;
785 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
786 const int J = a_colind.data()[ii];
787 const double gradSa_J = -(fs0.dS_g_dp*grad_u[J] + fs0.dS_g_dz*grad_u_n[J]);
788 const double gp_a = grad_u[J] - rho_a_mass0*gravity.data()[J];
789 const double gp_g = grad_u[J] + pcp0*gradSa_J - rho_g_mass0*gravity.data()[J];
790 ua -= (KWr0*KWs_eN0[ii]) * gp_a;
791 ug -= (KNr0*KWs_eN0[ii]/mu_n) * gp_g;
792 }
793 F0[I] = fs0.rho_g*(1.0 - fs0.Y)*ug + fs0.rho_a*(1.0 - fs0.X)*ua;
794 }
795 //
796 //update element residual
797 //
798 for (int i = 0; i < nDOF_test_element; i++) {
799 int eN_k_i = eN_k * nDOF_test_element + i, eN_k_i_nSpace = eN_k_i * nSpace, i_nSpace = i * nSpace;
800 // P3c: mass + component flux (divergence form, -= F_0 . grad N_i).
801 elementResidual_u[i] += ck.Mass_weak(m_t, u_test_dV[i]) + VMS * ck.NumericalDiffusion(q_numDiff_u_last[eN_k], grad_u, &u_grad_test_dV[i_nSpace]);
802 for (int I = 0; I < nSpace; I++)
803 elementResidual_u[i] -= F0[I] * u_grad_test_dV[i_nSpace + I];
804 } //i
805 //
806 q_m.data()[eN_k] = m;
807 q_u.data()[eN_k] = u;
808 }
809 //
810 //load element into global residual and save element residual
811 //
812 for (int i = 0; i < nDOF_test_element; i++) {
813 int eN_i = eN * nDOF_test_element + i;
814
815 globalResidual.data()[offset_u + stride_u * u_l2g.data()[eN_i]] += elementResidual_u[i];
816 } //i
817 } //elements
818 //
819 //loop over exterior element boundaries to calculate surface integrals and load into element and global residuals
820 //
821 //ebNE is the Exterior element boundary INdex
822 //ebN is the element boundary INdex
823 //eN is the element index
824 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++) {
825 int ebN = exteriorElementBoundariesArray.data()[ebNE], eN = elementBoundaryElementsArray.data()[ebN * 2 + 0], ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN * 2 + 0], eN_nDOF_trial_element = eN * nDOF_trial_element;
826 double elementResidual_u[nDOF_test_element];
827 for (int i = 0; i < nDOF_test_element; i++) { elementResidual_u[i] = 0.0; }
828 for (int kb = 0; kb < nQuadraturePoints_elementBoundary; kb++) {
829 int ebNE_kb = ebNE * nQuadraturePoints_elementBoundary + kb, ebNE_kb_nSpace = ebNE_kb * nSpace, ebN_local_kb = ebN_local * nQuadraturePoints_elementBoundary + kb, ebN_local_kb_nSpace = ebN_local_kb * nSpace;
830 double u_ext = 0.0, grad_u_ext[nSpace], m_ext = 0.0, dm_ext = 0.0, f_ext[nSpace], df_ext[nSpace], a_ext[nnz], da_ext[nnz], as_ext[nnz], flux_ext = 0.0,
831 //anb_seepage_flux=0.0, // for flux calculation
832 bc_u_ext = 0.0, bc_grad_u_ext[nSpace], bc_m_ext = 0.0, bc_dm_ext = 0.0, bc_f_ext[nSpace], bc_df_ext[nSpace], bc_a_ext[nnz], bc_da_ext[nnz], bc_as_ext[nnz], jac_ext[nSpace * nSpace], jacDet_ext, jacInv_ext[nSpace * nSpace], boundaryJac[nSpace * (nSpace - 1)], metricTensor[(nSpace - 1) * (nSpace - 1)], metricTensorDetSqrt, dS, u_test_dS[nDOF_test_element], u_grad_trial_trace[nDOF_trial_element * nSpace], normal[3], x_ext, y_ext, z_ext, xt_ext, yt_ext, zt_ext, integralScaling, G[nSpace * nSpace], G_dd_G, tr_G;
833 //
834 //calculate the solution and gradients at quadrature points
835 //
836 //compute information about mapping from reference element to physical element
837 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,
838 normal_ref.data(), normal, x_ext, y_ext, z_ext);
839 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);
840 dS = ((1.0 - MOVING_DOMAIN) * metricTensorDetSqrt + MOVING_DOMAIN * integralScaling) * dS_ref.data()[kb];
841 //get the metric tensor
842 //cek todo use symmetry
843 ck.calculateG(jacInv_ext, G, G_dd_G, tr_G);
844 //compute shape and solution information
845 //shape
846 ck.gradTrialFromRef(&u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace * nDOF_trial_element], jacInv_ext, u_grad_trial_trace);
847 //solution and gradient
848 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);
849 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial_trace, grad_u_ext);
850
851 //populate ebqe_x
852 // const int ebNE_kb_3d = ebNE_kb * 3;
853 // ebqe_x.data()[ebNE_kb_3d + 0] = x_ext;
854 // ebqe_x.data()[ebNE_kb_3d + 1] = y_ext;
855 // ebqe_x.data()[ebNE_kb_3d + 2] = z_ext;
856
857 //precalculate test function products with integration weights
858 for (int j = 0; j < nDOF_trial_element; j++) { u_test_dS[j] = u_test_trace_ref.data()[ebN_local_kb * nDOF_test_element + j] * dS; }
859 //
860 //load the boundary values
861 //
862 bc_u_ext = isDOFBoundary_u.data()[ebNE_kb] * ebqe_bc_u_ext.data()[ebNE_kb] + (1 - isDOFBoundary_u.data()[ebNE_kb]) * u_ext;
863 //
864 //calculate the pde coefficients using the solution and the boundary values for the solution
865 //
866 const double rho_ext = ebqe_rho.data()[ebNE_kb];
867 const double rho_velocity_ext = std::fabs(rho_ext) > 1.0e-12 ? rho_ext : rho;
868 double Kr, dKr, thetaW_ext, thetaW_bc;
869 // Boundary closure cross-derivatives wrt u_n; (0,1) boundary Jacobian
870 // is not assembled here.
871 double dm_du_n_ext = 0.0, dkr_du_n_ext = 0.0;
872 double df_du_n_ext[nSpace];
873 double da_du_n_ext[nnz];
874 double bc_dm_du_n = 0.0, bc_dkr_du_n = 0.0;
875 double bc_df_du_n[nSpace];
876 double bc_da_du_n[nnz];
877 for (int I = 0; I < nSpace; I++) { df_du_n_ext[I] = 0.0; bc_df_du_n[I] = 0.0; }
878 for (int ii = 0; ii < nnz; ii++) { da_du_n_ext[ii] = 0.0; bc_da_du_n[ii] = 0.0; }
879 double u_n_ext_qp = 0.0;
880 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
881 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], u_n_ext_qp);
882 // Component-1 boundary Dirichlet via the standard
883 // mask = isDOFBoundary_n * bc + (1 - isDOFBoundary_n) * interior.
884 const double bc_u_n_ext_qp = isDOFBoundary_n.data()[ebNE_kb] * ebqe_bc_u_n_ext.data()[ebNE_kb]
885 + (1 - isDOFBoundary_n.data()[ebNE_kb]) * u_n_ext_qp;
886 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
887 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
888 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
889 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], u_ext, u_n_ext_qp,
890 m_ext, dm_ext, dm_du_n_ext, f_ext, df_ext, df_du_n_ext, a_ext, da_ext, da_du_n_ext,
891 as_ext, Kr, dKr, dkr_du_n_ext, thetaW_ext);
892 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
893 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
894 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
895 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], bc_u_ext, bc_u_n_ext_qp,
896 bc_m_ext, bc_dm_ext, bc_dm_du_n, bc_f_ext, bc_df_ext, bc_df_du_n, bc_a_ext, bc_da_ext, bc_da_du_n,
897 bc_as_ext, Kr, dKr, bc_dkr_du_n, thetaW_bc);
898 ebqe_theta.data()[ebNE_kb] = thetaW_ext;
899
900 //
901 //Calculate Darcy velocity on exterior face : v_ext = -(a_ext/rho) * (grad_u_ext + gravity) ---
902 //
903 double ext_pressure_gradient[nSpace];
904 for (int J=0; J<nSpace; ++J)
905 ext_pressure_gradient[J] = grad_u_ext[J] - rho_velocity_ext * gravity.data()[J];
906
907 for (int I=0; I<nSpace; ++I) {
908 double acc = 0.0;
909 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I+1]; ++ii) {
910 const int J = a_colind.data()[ii];
911 acc += (a_ext[ii] / rho_velocity_ext) * ext_pressure_gradient[J];
912 }
913 ebqe_velocity_ext.data()[ebNE_kb_nSpace + I] = -acc;
914 ebqe_velocity_ext_couple.data()[ebNE_kb_nSpace + I] = -acc ; // store vector at this boundary qp
915 }
916
917
918 //
919 // ===== P3c boundary: compositional comp-0 (H2O) flux F_0 . n =====
920 // Richards-style Nitsche trace flux on a pressure-Dirichlet (or seepage)
921 // face: flux = F_0.n + penalty*(p - p_BC); no-flow faces keep bc_flux.
922 // F_0 mirrors the interior H2O flux; FD-verified in boundary0_test.cpp.
923 {
924 double grad_u_n_ext[nSpace];
925 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
926 u_grad_trial_trace, grad_u_n_ext);
927 const int mat_b = elementMaterialTypes.data()[eN];
928 const double alpha_b = alpha.data()[mat_b];
929 const double n_vg_b = n.data()[mat_b];
930 const double krn_end_b = krn_end.data()[mat_b];
931 const double *KWs_b = &KWs.data()[mat_b * nnz];
932 const double phi_b = thetaR.data()[mat_b] + thetaSR.data()[mat_b];
933 const double S_wr_b = thetaR.data()[mat_b] / phi_b;
934 const double one_m_Sr_b = 1.0 - S_wr_b;
935 const double Se_trap_L956 = 1.0 - S_gr.data()[mat_b] / one_m_Sr_b; // gas-only residual trapping
936 const double p_clb = fmax(u_ext, 1.0e2);
939 const double Se_ab = fmin(fmax((1.0 - fsb.S_g - S_wr_b)/one_m_Sr_b, 0.0), 1.0);
940 double KWrb=0,DKWrb=0,thWb=0,DthWb=0,KNrb=0,DKNrb=0,pcb=0,dpc_dSeb=0,d2pcb=0;
941 if (PSK_TYPE_member == 1) {
942 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_ab, alpha_b, n_vg_b, thetaR.data()[mat_b], thetaSR.data()[mat_b], thWb, DthWb, KWrb, DKWrb);
943 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_ab, alpha_b, n_vg_b, KNrb, DKNrb, Se_trap_L956);
944 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_ab, alpha_b, n_vg_b, bc_Se_min.data()[mat_b], pcb, dpc_dSeb, d2pcb);
945 } else {
946 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_ab, alpha_b, n_vg_b, thetaR.data()[mat_b], thetaSR.data()[mat_b], thWb, DthWb, KWrb, DKWrb);
947 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_ab, alpha_b, n_vg_b, KNrb, DKNrb, Se_trap_L956);
948 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_ab, alpha_b, n_vg_b, pcb, dpc_dSeb, d2pcb);
949 }
950 KNrb *= krn_end_b;
951 const double pcpb = dpc_dSeb / one_m_Sr_b;
952 const double Mbar_gb = fsb.Y*::m_comp_co2::eos::M_CO2_KG + (1.0 - fsb.Y)*::m_comp_co2::eos::M_H2O_KG;
953 const double Mbar_ab = fsb.X*::m_comp_co2::eos::M_CO2_KG + (1.0 - fsb.X)*::m_comp_co2::eos::M_H2O_KG;
954 const double rho_g_mass_b = fsb.rho_g*Mbar_gb;
955 const double rho_a_mass_b = fsb.rho_a*Mbar_ab;
956 double F0n = 0.0;
957 for (int I = 0; I < nSpace; I++) {
958 double ua = 0.0, ug = 0.0;
959 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I+1]; ii++) {
960 const int J = a_colind.data()[ii];
961 const double gradSa_J = -(fsb.dS_g_dp*grad_u_ext[J] + fsb.dS_g_dz*grad_u_n_ext[J]);
962 const double gp_a = grad_u_ext[J] - rho_a_mass_b*gravity.data()[J];
963 const double gp_g = grad_u_ext[J] + pcpb*gradSa_J - rho_g_mass_b*gravity.data()[J];
964 ua -= (KWrb*KWs_b[ii]) * gp_a;
965 ug -= (KNrb*KWs_b[ii]/mu_n) * gp_g;
966 }
967 F0n += (fsb.rho_g*(1.0 - fsb.Y)*ug + fsb.rho_a*(1.0 - fsb.X)*ua) * normal[I];
968 }
969 const int isSeep = isSeepageFace.data()[ebNE];
970 if (isSeep || isDOFBoundary_u.data()[ebNE_kb]) {
971 const double bc_u_pen = isSeep ? 0.0 : bc_u_ext;
972 flux_ext = F0n + ebqe_penalty_ext.data()[ebNE_kb] * (u_ext - bc_u_pen);
973 if (isSeep && flux_ext <= 0.0) flux_ext = 0.0; // closed unless outflow
974 } else {
975 flux_ext = ebqe_bc_flux_ext[ebNE_kb]; // no-flow / prescribed flux
976 }
977 }
978 ebqe_flux.data()[ebNE_kb] = flux_ext;
979
980 anb_seepage_flux = seepagefluxcalculator(anb_seepage_flux, isSeepageFace.data()[ebNE], dS, flux_ext);
981 anb_seepage_flux_n.data()[0] = anb_seepage_flux;
982 ebqe_u.data()[ebNE_kb] = u_ext;
983 //
984 //update residuals
985 //
986 for (int i = 0; i < nDOF_test_element; i++) {
987 elementResidual_u[i] += ck.ExteriorElementBoundaryFlux(flux_ext, u_test_dS[i]);
988 } //i
989 } //kb
990
991 //
992 //update the element and global residual storage
993 //
994 for (int i = 0; i < nDOF_test_element; i++) {
995 int eN_i = eN * nDOF_test_element + i;
996 globalResidual.data()[offset_u + stride_u * u_l2g.data()[eN_i]] += elementResidual_u[i];
997 } //i
998 } //ebNE
999
1000 // ============================================================================
1001 // component-1 (S_n) gas-mass equation.
1002 //
1003 // d(phi*rho_n*S_n)/dt + div F_n = 0
1004 // m_n = phi * rho_n * u_n
1005 // m_n_old = phi * rho_n * u_n_old
1006 //
1007 // Gas Darcy flux F_n = -(K/mu_n) k_rn (grad p_n - rho_n g)
1008 // = -(K/mu_n) k_rn (grad p_w + dp_c/dS_n grad S_n - rho_n g)
1009 // Splitting into Proteus form for u_w = p_w, u_n = S_n:
1010 // f_n = rho_n^2 * k_rn * (K/mu_n) * g (gravity advection)
1011 // a_n = rho_n * k_rn * (K/mu_n) (diffusion against grad u_w)
1012 // a_n_pc = rho_n * k_rn * (K/mu_n) * dp_c/dS_n (capillary diffusion against grad u_n)
1013 // At u_n = 0 (fully wet) the closure returns k_rn = 0 -> all flux contributions
1014 // vanish, so this loop should reproduce the single-phase result for the
1015 // Bioswale.
1016 for (int eN = 0; eN < nElements_global; eN++) {
1017 const int mat_eN = elementMaterialTypes.data()[eN];
1018 const double phi_eN = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
1019 const double alpha_eN = alpha.data()[mat_eN];
1020 const double krn_end_eN = krn_end.data()[mat_eN];
1021 const double n_vg_eN = n.data()[mat_eN];
1022 const double *KWs_eN = &KWs.data()[mat_eN * nnz];
1023 double elementResidual_n[nDOF_test_element];
1024 // Row-sum lumped weight per node: M_lump[i] = int N_i dV over the element.
1025 // Used to apply the CO2 injection source as a pure diagonal contribution
1026 // at the port nodes (no smearing onto neighbor basis functions), which
1027 // matches the localised disk source and avoids exciting the BC closure
1028 // on rim nodes where k_rn is still zero.
1029 double lumped_w_n[nDOF_test_element];
1030 for (int i = 0; i < nDOF_test_element; i++) {
1031 elementResidual_n[i] = 0.0;
1032 lumped_w_n[i] = 0.0;
1033 }
1034 for (int k = 0; k < nQuadraturePoints_element; k++) {
1035 const int eN_k = eN * nQuadraturePoints_element + k;
1036 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
1037 double jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], x_q, y_q, z_q;
1038 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(),
1039 mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
1040 jac, jacDet, jacInv, x_q, y_q, z_q);
1041 const double dV = std::fabs(jacDet) * dV_ref.data()[k];
1042 // Trial gradients in physical coords (used for grad u_w and grad N_i).
1043 double u_grad_trial_qp[nDOF_trial_element * nSpace];
1044 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace],
1045 jacInv, u_grad_trial_qp);
1046 // Saturation u_n and old at QP.
1047 double u_n = 0.0, u_n_old = 0.0;
1048 ck.valFromDOF(u_dof_n.data(),
1049 &u_l2g.data()[eN_nDOF_trial_element],
1050 &u_trial_ref.data()[k * nDOF_trial_element], u_n);
1051 ck.valFromDOF(u_dof_n_old.data(),
1052 &u_l2g.data()[eN_nDOF_trial_element],
1053 &u_trial_ref.data()[k * nDOF_trial_element], u_n_old);
1054 // Wetting-pressure value and gradient at QP. u_w (and u_w_old) feed
1055 // the linear EOS rho_n(p_n) = c_n*(u_w + p_c(u_n)).
1056 double u_w_qp = 0.0, u_w_qp_old = 0.0;
1057 ck.valFromDOF(u_dof.data(),
1058 &u_l2g.data()[eN_nDOF_trial_element],
1059 &u_trial_ref.data()[k * nDOF_trial_element], u_w_qp);
1060 ck.valFromDOF(u_dof_old.data(),
1061 &u_l2g.data()[eN_nDOF_trial_element],
1062 &u_trial_ref.data()[k * nDOF_trial_element], u_w_qp_old);
1063 double grad_u_w[nSpace];
1064 ck.gradFromDOF(u_dof.data(),
1065 &u_l2g.data()[eN_nDOF_trial_element],
1066 u_grad_trial_qp, grad_u_w);
1067 // Saturation gradient at QP (Step 3d: needed for p_c(S_n) flux contribution).
1068 double grad_u_n[nSpace];
1069 ck.gradFromDOF(u_dof_n.data(),
1070 &u_l2g.data()[eN_nDOF_trial_element],
1071 u_grad_trial_qp, grad_u_n);
1072 // Rock pore fraction and residual wetting saturation; consumed by the
1073 // compositional flux F_1 below (Se_a = (S_a - S_wr)/(1 - S_wr)).
1074 // P3c (complete): the gas relperm / capillary / linear-gas-EOS closures
1075 // that used to be evaluated here -- phase-based, keyed on u_n as S_n --
1076 // are removed. The F_1 block recomputes every saturation-dependent
1077 // property from the FLASH saturation S_g, so nothing downstream reads a
1078 // phase-based k_rn(u_n), p_c(u_n) or rho_n(p_n) any more.
1079 const double phi_loc = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
1080 const double S_wr_loc = thetaR.data()[mat_eN] / phi_loc;
1081 const double one_m_Sr_loc = 1.0 - S_wr_loc;
1082 const double Se_trap_L1103 = 1.0 - S_gr.data()[mat_eN] / one_m_Sr_loc; // gas-only residual trapping
1083 // component-1 (CO2) accumulation, compositional (p,z) form:
1084 // m_1 = phi * N * z, N = rho_g*S_g + rho_a*(1-S_g), z = u_n.
1085 const double p_cl = fmax(u_w_qp, 1.0e2);
1086 const double p_cl_old = fmax(u_w_qp_old, 1.0e2);
1091 const double N_cur = fs_n.rho_g*fs_n.S_g + fs_n.rho_a*(1.0 - fs_n.S_g);
1092 const double N_old = fs_n_old.rho_g*fs_n_old.S_g
1093 + fs_n_old.rho_a*(1.0 - fs_n_old.S_g);
1094 const double m_n = phi_eN * N_cur * u_n;
1095 const double m_n_old = phi_eN * N_old * u_n_old;
1096 const double m_n_t = (m_n - m_n_old) / dt;
1097 // ===== P3c: component CO2 molar flux F_1 = rho_g*Y*u_g + rho_a*X*u_a =====
1098 // Saturation-dependent props are recomputed from the FLASH saturation S_g
1099 // (NOT u_n, which is now z). S_a = 1 - S_g; psk closures take wetting Se_a.
1100 const double S_a_qp = 1.0 - fs_n.S_g;
1101 const double Se_a = fmin(fmax((S_a_qp - S_wr_loc) / one_m_Sr_loc, 0.0), 1.0);
1102 double KWr_a = 0.0, DKWr_a = 0.0, thW_a = 0.0, DthW_a = 0.0;
1103 double KNr_a = 0.0, DKNr_a = 0.0;
1104 double pc_a = 0.0, dpc_dSe_a = 0.0, d2pc_a = 0.0;
1105 if (PSK_TYPE_member == 1) {
1106 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_a, alpha_eN, n_vg_eN,
1107 thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_a, DthW_a, KWr_a, DKWr_a);
1108 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_a, alpha_eN, n_vg_eN, KNr_a, DKNr_a, Se_trap_L1103);
1109 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_a, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc_a, dpc_dSe_a, d2pc_a);
1110 } else {
1111 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_a, alpha_eN, n_vg_eN,
1112 thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_a, DthW_a, KWr_a, DKWr_a);
1113 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_a, alpha_eN, n_vg_eN, KNr_a, DKNr_a, Se_trap_L1103);
1114 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_a, alpha_eN, n_vg_eN, pc_a, dpc_dSe_a, d2pc_a);
1115 }
1116 KNr_a *= krn_end_eN;
1117 // p_c'(S_a) = dp_c/dSe * dSe/dS_a = dpc_dSe_a / (1 - S_wr).
1118 const double pcp_a = dpc_dSe_a / one_m_Sr_loc;
1119 // phase mass densities for gravity (molar density * mean molar mass):
1120 const double Mbar_g = fs_n.Y*::m_comp_co2::eos::M_CO2_KG
1121 + (1.0 - fs_n.Y)*::m_comp_co2::eos::M_H2O_KG;
1122 const double Mbar_a = fs_n.X*::m_comp_co2::eos::M_CO2_KG
1123 + (1.0 - fs_n.X)*::m_comp_co2::eos::M_H2O_KG;
1124 const double rho_g_mass = fs_n.rho_g*Mbar_g;
1125 const double rho_a_mass = fs_n.rho_a*Mbar_a;
1126 // u_a = -(K krw/mu_w)(grad p_a - rho_a_mass g), p_a = u_w
1127 // u_g = -(K krg/mu_g)(grad p_g - rho_g_mass g), p_g = u_w + p_c(S_a)
1128 // grad p_g = grad u_w + p_c'(S_a) grad S_a, grad S_a = -(dSg/dp grad u_w + dSg/dz grad u_n)
1129 // KWs = K/mu_w (aqueous base); mu_n = mu_g/mu_w so KWs/mu_n = K/mu_g.
1130 double F1[nSpace];
1131 for (int I = 0; I < nSpace; I++) {
1132 double ua = 0.0, ug = 0.0;
1133 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
1134 const int J = a_colind.data()[ii];
1135 const double gradSa_J = -(fs_n.dS_g_dp*grad_u_w[J] + fs_n.dS_g_dz*grad_u_n[J]);
1136 const double gp_a = grad_u_w[J] - rho_a_mass*gravity.data()[J];
1137 const double gp_g = grad_u_w[J] + pcp_a*gradSa_J - rho_g_mass*gravity.data()[J];
1138 ua -= (KWr_a*KWs_eN[ii]) * gp_a;
1139 ug -= (KNr_a*KWs_eN[ii]/mu_n) * gp_g;
1140 }
1141 F1[I] = fs_n.rho_g*fs_n.Y*ug + fs_n.rho_a*fs_n.X*ua;
1142 }
1143 // Dissolution is handled thermodynamically by the inline flash (aqueous
1144 // CO2 = rho_a*X advected in F_1); the old kinetic R_diss sink is removed.
1145 // Residual integration: mass + component CO2 flux (- injection, lumped).
1146 for (int i = 0; i < nDOF_test_element; i++) {
1147 const double test_i = u_test_ref.data()[k * nDOF_test_element + i];
1148 // Mass contribution.
1149 elementResidual_n[i] += m_n_t * test_i * dV;
1150 lumped_w_n[i] += test_i * dV;
1151 for (int I = 0; I < nSpace; I++) {
1152 elementResidual_n[i] -= F1[I] * u_grad_trial_qp[i * nSpace + I] * dV;
1153 }
1154 }
1155 }
1156 // Row-sum lumped CO2 injection: subtract Q_inj at port nodes only.
1157 for (int i = 0; i < nDOF_test_element; i++) {
1158 const int gi = u_l2g.data()[eN * nDOF_test_element + i];
1159 elementResidual_n[i] -= injection_dof.data()[gi] * lumped_w_n[i];
1160 }
1161 for (int i = 0; i < nDOF_test_element; i++) {
1162 const int eN_i = eN * nDOF_test_element + i;
1163 globalResidual.data()[offset_n + stride_n * u_l2g.data()[eN_i]] += elementResidual_n[i];
1164 }
1165 }
1166
1167 // ============================================================================
1168 // Comp-1 (CO2 / z) exterior boundary loop -- STAB=0 path. COMPOSITIONAL.
1169 //
1170 // P3c STATUS: BOUNDARY PORTED (2026-06-06). Slot 1 is the overall CO2
1171 // composition z, NOT a saturation. Computes the compositional molar CO2
1172 // trace flux F_1.n = rho_g*Y*u_g + rho_a*X*u_a, mirroring the FD-verified
1173 // interior element flux (~line 1152) and the STAB=2 boundary loop; every
1174 // saturation-dependent property is recomputed from the FLASH saturation
1175 // S_g(p,z). The surface term from div(F_1) by parts is +(F_1.n) N_i dS.
1176 // isDir_n : F_1.n = consistent compositional flux
1177 // + penalty*(z - z_BC) [Nitsche]
1178 // not isDir_n : F_1.n = 0 (no-flow / closed -- no spurious boundary flux)
1179 // so STAB=0 and STAB=2 now enforce identical compositional comp-1 BCs.
1180 // McWhorter-Sunada drives this via getDBC_z at the inlet (z_BC = z(S_n_BC)).
1181 // Jacobian is the matching (1,1)/(1,0) blocks in calculateJacobian.
1182 // ============================================================================
1183 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++) {
1184 const int ebN = exteriorElementBoundariesArray.data()[ebNE];
1185 const int eN = elementBoundaryElementsArray.data()[ebN * 2 + 0];
1186 const int ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN * 2 + 0];
1187 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
1188 const int mat_eN = elementMaterialTypes.data()[eN];
1189 const double phi_eN = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
1190 const double alpha_eN = alpha.data()[mat_eN];
1191 const double krn_end_eN = krn_end.data()[mat_eN];
1192 const double n_vg_eN = n.data()[mat_eN];
1193 const double *KWs_eN = &KWs.data()[mat_eN * nnz];
1194 const double S_wr_loc = thetaR.data()[mat_eN] / phi_eN;
1195 const double one_m_Sr_loc = 1.0 - S_wr_loc;
1196 const double Se_trap_L1235 = 1.0 - S_gr.data()[mat_eN] / one_m_Sr_loc; // gas-only residual trapping
1197
1198 double elementResidual_n_eb[nDOF_test_element];
1199 for (int i = 0; i < nDOF_test_element; i++) elementResidual_n_eb[i] = 0.0;
1200
1201 for (int kb = 0; kb < nQuadraturePoints_elementBoundary; kb++) {
1202 const int ebNE_kb = ebNE * nQuadraturePoints_elementBoundary + kb;
1203 const int ebN_local_kb = ebN_local * nQuadraturePoints_elementBoundary + kb;
1204 const int ebN_local_kb_nSpace = ebN_local_kb * nSpace;
1205
1206 double jac_ext[nSpace * nSpace], jacDet_ext, jacInv_ext[nSpace * nSpace];
1207 double boundaryJac_b[nSpace * (nSpace - 1)];
1208 double metricTensor_b[(nSpace - 1) * (nSpace - 1)];
1209 double metricTensorDetSqrt_b, dS_eb, normal_b[3];
1210 double xt_b, yt_b, zt_b, integralScaling_b;
1211 double x_eb, y_eb, z_eb;
1212 ck.calculateMapping_elementBoundary(eN, ebN_local, kb, ebN_local_kb,
1213 mesh_dof.data(), mesh_l2g.data(), mesh_trial_trace_ref.data(),
1214 mesh_grad_trial_trace_ref.data(), boundaryJac_ref.data(),
1215 jac_ext, jacDet_ext, jacInv_ext, boundaryJac_b, metricTensor_b,
1216 metricTensorDetSqrt_b, normal_ref.data(), normal_b,
1217 x_eb, y_eb, z_eb);
1218 ck.calculateMappingVelocity_elementBoundary(eN, ebN_local, kb, ebN_local_kb,
1219 mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_trace_ref.data(),
1220 xt_b, yt_b, zt_b, normal_b, boundaryJac_b, metricTensor_b,
1221 integralScaling_b);
1222 dS_eb = ((1.0 - MOVING_DOMAIN) * metricTensorDetSqrt_b
1223 + MOVING_DOMAIN * integralScaling_b) * dS_ref.data()[kb];
1224
1225 double u_grad_trial_trace_b[nDOF_trial_element * nSpace];
1226 ck.gradTrialFromRef(
1227 &u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace * nDOF_trial_element],
1228 jacInv_ext, u_grad_trial_trace_b);
1229 double u_w_ext_b = 0.0, u_n_ext_b = 0.0;
1230 double grad_u_w_ext_b[nSpace], grad_u_n_ext_b[nSpace];
1231 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element],
1232 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element],
1233 u_w_ext_b);
1234 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
1235 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element],
1236 u_n_ext_b);
1237 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element],
1238 u_grad_trial_trace_b, grad_u_w_ext_b);
1239 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
1240 u_grad_trial_trace_b, grad_u_n_ext_b);
1241
1242 const int isDir_n = isDOFBoundary_n.data()[ebNE_kb];
1243 const double bc_u_n_ext_b = isDir_n * ebqe_bc_u_n_ext.data()[ebNE_kb]
1244 + (1 - isDir_n) * u_n_ext_b;
1245
1246 // ====================================================================
1247 // P3c boundary (STAB=0): compositional comp-1 (CO2) trace flux F_1.n.
1248 // Slot 1 is the overall CO2 composition z, NOT a saturation. Mirrors
1249 // the FD-verified interior element flux F_1 = rho_g*Y*u_g + rho_a*X*u_a
1250 // (~line 1152) and the STAB=2 boundary loop; every saturation-dependent
1251 // property is recomputed from the FLASH saturation S_g(p,z) (psk
1252 // closures on the wetting Se_a = (1-S_g-S_wr)/(1-S_wr)). Consistent flux
1253 // on Dirichlet-z faces + a Nitsche penalty driving z at the trace toward
1254 // bc_u_n_ext_b (= z_BC; McWhorter-Sunada inlet); no-flow faces contribute
1255 // nothing (closed-box conservation). Jacobian is in calculateJacobian.
1256 // ====================================================================
1257 const double p_clb = fmax(u_w_ext_b, 1.0e2);
1260 const double Se_ab = fmin(fmax((1.0 - fsb.S_g - S_wr_loc)/one_m_Sr_loc, 0.0), 1.0);
1261 double KWr_b=0,DKWr_b=0,thW_b=0,DthW_b=0,KNr_b=0,DKNr_b=0,pc_b=0,dpc_dSe_b=0,d2pc_b=0;
1262 if (PSK_TYPE_member == 1) {
1263 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_ab, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_b, DthW_b, KWr_b, DKWr_b);
1264 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_ab, alpha_eN, n_vg_eN, KNr_b, DKNr_b, Se_trap_L1235);
1265 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_ab, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc_b, dpc_dSe_b, d2pc_b);
1266 } else {
1267 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_ab, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_b, DthW_b, KWr_b, DKWr_b);
1268 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_ab, alpha_eN, n_vg_eN, KNr_b, DKNr_b, Se_trap_L1235);
1269 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_ab, alpha_eN, n_vg_eN, pc_b, dpc_dSe_b, d2pc_b);
1270 }
1271 KNr_b *= krn_end_eN;
1272 const double pcpb = dpc_dSe_b / one_m_Sr_loc;
1273 const double Mbar_gb = fsb.Y*::m_comp_co2::eos::M_CO2_KG + (1.0 - fsb.Y)*::m_comp_co2::eos::M_H2O_KG;
1274 const double Mbar_ab = fsb.X*::m_comp_co2::eos::M_CO2_KG + (1.0 - fsb.X)*::m_comp_co2::eos::M_H2O_KG;
1275 const double rho_g_mass_b = fsb.rho_g*Mbar_gb;
1276 const double rho_a_mass_b = fsb.rho_a*Mbar_ab;
1277 double F_n_dot_n = 0.0;
1278 for (int I = 0; I < nSpace; I++) {
1279 double ua = 0.0, ug = 0.0;
1280 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
1281 const int J = a_colind.data()[ii];
1282 const double gradSa_J = -(fsb.dS_g_dp*grad_u_w_ext_b[J] + fsb.dS_g_dz*grad_u_n_ext_b[J]);
1283 const double gp_a = grad_u_w_ext_b[J] - rho_a_mass_b*gravity.data()[J];
1284 const double gp_g = grad_u_w_ext_b[J] + pcpb*gradSa_J - rho_g_mass_b*gravity.data()[J];
1285 ua -= (KWr_b*KWs_eN[ii]) * gp_a;
1286 ug -= (KNr_b*KWs_eN[ii]/mu_n) * gp_g;
1287 }
1288 F_n_dot_n += (fsb.rho_g*fsb.Y*ug + fsb.rho_a*fsb.X*ua) * normal_b[I];
1289 }
1290 if (isDir_n) {
1291 // IIPG penalty scaled by the local comp-1 diffusion magnitude a_n
1292 // (= rho_g*Y*krn/mu_n + rho_a*X*krw, times a representative K/mu_w).
1293 // The framework penalty is const/h, UNSCALED by the coefficient; for
1294 // comp-1 the ~1e4 molar density makes the bare penalty ~1e4x too weak
1295 // to enforce z=z_BC, so the inlet floats (the McWhorter-Sunada
1296 // convergence killer). Coefficient treated frozen in the Jacobian.
1297 double Kw_rep = 0.0;
1298 for (int ii = 0; ii < nnz; ii++) Kw_rep = fmax(Kw_rep, fabs(KWs_eN[ii]));
1299 const double a_n_scale = (fsb.rho_g*fsb.Y*KNr_b/mu_n
1300 + fsb.rho_a*fsb.X*KWr_b) * Kw_rep;
1301 const double pen_eff = ebqe_penalty_ext.data()[ebNE_kb] * a_n_scale;
1302 F_n_dot_n += pen_eff * (u_n_ext_b - bc_u_n_ext_b); // Nitsche, drives z->z_BC
1303 } else {
1304 F_n_dot_n = 0.0; // no-flow
1305 }
1306
1307 for (int i = 0; i < nDOF_test_element; i++) {
1308 const double test_i_dS = u_test_trace_ref.data()[
1309 ebN_local_kb * nDOF_test_element + i] * dS_eb;
1310 elementResidual_n_eb[i] += F_n_dot_n * test_i_dS;
1311 }
1312 } // kb
1313
1314 for (int i = 0; i < nDOF_test_element; i++) {
1315 const int gi = u_l2g.data()[eN * nDOF_test_element + i];
1316 globalResidual.data()[offset_n + stride_n * gi] += elementResidual_n_eb[i];
1317 }
1318 } // ebNE
1319 }
1320
1322 {
1323 xt::pyarray<double> &mesh_trial_ref = args.array<double>("mesh_trial_ref");
1324 xt::pyarray<double> &mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
1325 xt::pyarray<double> &mesh_dof = args.array<double>("mesh_dof");
1326 xt::pyarray<double> &mesh_velocity_dof = args.array<double>("mesh_velocity_dof");
1327 double MOVING_DOMAIN = args.scalar<double>("MOVING_DOMAIN");
1328 xt::pyarray<int> &mesh_l2g = args.array<int>("mesh_l2g");
1329 xt::pyarray<double> &dV_ref = args.array<double>("dV_ref");
1330 xt::pyarray<double> &u_trial_ref = args.array<double>("u_trial_ref");
1331 xt::pyarray<double> &u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
1332 xt::pyarray<double> &u_test_ref = args.array<double>("u_test_ref");
1333 xt::pyarray<double> &u_grad_test_ref = args.array<double>("u_grad_test_ref");
1334 xt::pyarray<double> &mesh_trial_trace_ref = args.array<double>("mesh_trial_trace_ref");
1335 xt::pyarray<double> &mesh_grad_trial_trace_ref = args.array<double>("mesh_grad_trial_trace_ref");
1336 xt::pyarray<double> &dS_ref = args.array<double>("dS_ref");
1337 xt::pyarray<double> &u_trial_trace_ref = args.array<double>("u_trial_trace_ref");
1338 xt::pyarray<double> &u_grad_trial_trace_ref = args.array<double>("u_grad_trial_trace_ref");
1339 xt::pyarray<double> &u_test_trace_ref = args.array<double>("u_test_trace_ref");
1340 xt::pyarray<double> &u_grad_test_trace_ref = args.array<double>("u_grad_test_trace_ref");
1341 xt::pyarray<double> &normal_ref = args.array<double>("normal_ref");
1342 xt::pyarray<double> &boundaryJac_ref = args.array<double>("boundaryJac_ref");
1343 int nElements_global = args.scalar<int>("nElements_global");
1344 xt::pyarray<double> &ebqe_penalty_ext = args.array<double>("ebqe_penalty_ext");
1345 xt::pyarray<int> &elementMaterialTypes = args.array<int>("elementMaterialTypes");
1346 xt::pyarray<int> &isSeepageFace = args.array<int>("isSeepageFace");
1347 xt::pyarray<int> &a_rowptr = args.array<int>("a_rowptr");
1348 xt::pyarray<int> &a_colind = args.array<int>("a_colind");
1349 double rho = args.scalar<double>("rho");
1350 double beta = args.scalar<double>("beta");
1351
1353 xt::pyarray<double> &q_rho = args.array<double>("q_rho");
1354 xt::pyarray<double> &ebqe_rho = args.array<double>("ebqe_rho");
1356 // Stage 3b: gas-side kinetic dissolution sink reads (residual-only at
1357 // this stage; the Jacobian contribution -d(R_diss)/du_n is small
1358 // (proportional to k_d * dt) and we approximate it as zero in the
1359 // initial port -- Newton recovers it through outer iteration since the
1360 // sink is also bounded. Promote to a proper Jacobian contribution if
1361 // Newton stalls in the FluidFlower setup.
1362 xt::pyarray<double> &c_dof_jac = args.array<double>("c_dof");
1363 const double k_d_jac = args.scalar<double>("k_d");
1364 const double c_sat_jac = args.scalar<double>("c_sat");
1365
1366 xt::pyarray<double> &gravity = args.array<double>("gravity");
1367 xt::pyarray<double> &alpha = args.array<double>("alpha");
1368 xt::pyarray<double> &n = args.array<double>("n");
1369 xt::pyarray<double> &thetaR = args.array<double>("thetaR");
1370 xt::pyarray<double> &thetaSR = args.array<double>("thetaSR");
1371 xt::pyarray<double> &KWs = args.array<double>("KWs");
1372 xt::pyarray<double> &krn_end = args.array<double>("krn_end");
1373 xt::pyarray<double> &S_gr = args.array<double>("S_gr");
1374 xt::pyarray<double> &bc_Se_min = args.array<double>("bc_Se_min");
1375 double mu_n = args.scalar<double>("mu_n");
1376 double useMetrics = args.scalar<double>("useMetrics");
1377 double alphaBDF = args.scalar<double>("alphaBDF");
1378 int lag_shockCapturing = args.scalar<int>("lag_shockCapturing");
1379 double shockCapturingDiffusion = args.scalar<double>("shockCapturingDiffusion");
1380 // VMS
1381 double VMS = args.scalar<double>("VMS");
1382 xt::pyarray<int> &u_l2g = args.array<int>("u_l2g");
1383 xt::pyarray<double> &elementDiameter = args.array<double>("elementDiameter");
1384 xt::pyarray<double> &u_dof = args.array<double>("u_dof");
1385 // component-1 saturation DOFs (needed by the gas-eq
1386 // Jacobian element loop appended at the end of this function).
1387 xt::pyarray<double> &u_dof_n = args.array<double>("u_dof_n");
1388 xt::pyarray<double> &velocity = args.array<double>("velocity");
1389 xt::pyarray<double> &q_m_betaBDF = args.array<double>("q_m_betaBDF");
1390 xt::pyarray<double> &cfl = args.array<double>("cfl");
1391 xt::pyarray<double> &q_numDiff_u = args.array<double>("q_numDiff_u");
1392 xt::pyarray<double> &q_numDiff_u_last = args.array<double>("q_numDiff_u_last");
1393 xt::pyarray<int> &csrRowIndeces_u_u = args.array<int>("csrRowIndeces_u_u");
1394 xt::pyarray<int> &csrColumnOffsets_u_u = args.array<int>("csrColumnOffsets_u_u");
1395 xt::pyarray<double> &globalJacobian = args.array<double>("globalJacobian");
1396 // component-1 (S_n) Jacobian args. Used by
1397 // the dedicated component-1 element loop appended at the end of this
1398 // function. (1,1) block is the consistent mass matrix / dt; (0,1) and
1399 // (1,0) cross-blocks are zero in Step 1.
1400 const double dt_n = args.scalar<double>("dt");
1401 // gas-phase density (linear EOS rho_n*p_n/p_ref_n when p_ref_n>0,
1402 // constant rho_n otherwise). c_n = drho_n/dp_n is constant for the
1403 // linear EOS and drives the new (1,1)/(1,0) compressibility terms.
1404 const double rho_n = args.scalar<double>("rho_n");
1405 const double p_ref_n = args.scalar<double>("p_ref_n");
1406 const bool rho_n_compressible = (p_ref_n > 0.0);
1407 const double c_n = rho_n_compressible ? (rho_n / p_ref_n) : 0.0;
1408 xt::pyarray<int> &csrRowIndeces_n_n = args.array<int>("csrRowIndeces_n_n");
1409 // (1,0) cross-block CSR maps for the gas-eq diffusion
1410 // against grad u_w. Currently allocated by the framework but unused by
1411 // the C++ assembly - 3c.2/3c.3 will write into them.
1412 xt::pyarray<int> &csrRowIndeces_n_w = args.array<int>("csrRowIndeces_n_w");
1413 xt::pyarray<int> &csrColumnOffsets_n_n = args.array<int>("csrColumnOffsets_n_n");
1414 xt::pyarray<int> &csrColumnOffsets_n_w = args.array<int>("csrColumnOffsets_n_w");
1415 // Exterior-boundary CSR column offsets for the comp-1 boundary Jacobian
1416 // loop ported from calculateResidual_entropy_viscosity (STAB=0 comp-1
1417 // Dirichlet enforcement). Added to getJacobian's argsDict in Python.
1418 xt::pyarray<int> &csrColumnOffsets_eb_n_n = args.array<int>("csrColumnOffsets_eb_n_n");
1419 xt::pyarray<int> &csrColumnOffsets_eb_n_w = args.array<int>("csrColumnOffsets_eb_n_w");
1420 // (0,1) cross-block CSR maps for the wetting eq.
1421 // J_{wv,ij} = (dm/du_n)*N_i*N_j + (df/du_n)*grad N_i*N_j
1422 // + (da/du_n)*grad u_w*grad N_i*N_j
1423 // The wetting equation row index is offset_u + stride_u * dof, and the column
1424 // index is offset_n + stride_n * dof.
1425 xt::pyarray<int> &csrRowIndeces_w_n = args.array<int>("csrRowIndeces_w_n");
1426 xt::pyarray<int> &csrColumnOffsets_w_n = args.array<int>("csrColumnOffsets_w_n");
1427 // (0,1) cross-block boundary CSR for the wetting-eq
1428 // exterior-flux Jacobian.
1429 xt::pyarray<int> &csrColumnOffsets_eb_w_n = args.array<int>("csrColumnOffsets_eb_w_n");
1430 // PSK closure selector for evaluateCoefficients (read from argsDict).
1431 PSK_TYPE_member = args.scalar<int>("PSK_TYPE");
1432 immiscible_member = (args.scalar<int>("immiscible") != 0);
1433 T_C_member = args.scalar<double>("T_C"); // temperature [degC] from input
1434 int nExteriorElementBoundaries_global = args.scalar<int>("nExteriorElementBoundaries_global");
1435 xt::pyarray<int> &exteriorElementBoundariesArray = args.array<int>("exteriorElementBoundariesArray");
1436 xt::pyarray<int> &elementBoundaryElementsArray = args.array<int>("elementBoundaryElementsArray");
1437 xt::pyarray<int> &elementBoundaryLocalElementBoundariesArray = args.array<int>("elementBoundaryLocalElementBoundariesArray");
1438 xt::pyarray<double> &ebqe_velocity_ext = args.array<double>("ebqe_velocity_ext");
1439 xt::pyarray<int> &isDOFBoundary_u = args.array<int>("isDOFBoundary_u");
1440 xt::pyarray<double> &ebqe_bc_u_ext = args.array<double>("ebqe_bc_u_ext");
1441 // component-1 (S_n) boundary arrays.
1442 xt::pyarray<int> &isDOFBoundary_n = args.array<int>("isDOFBoundary_n");
1443 xt::pyarray<double> &ebqe_bc_u_n_ext = args.array<double>("ebqe_bc_u_n_ext");
1444 xt::pyarray<int> &isFluxBoundary_u = args.array<int>("isFluxBoundary_u");
1445 xt::pyarray<double> &ebqe_bc_flux_ext = args.array<double>("ebqe_bc_flux_ext");
1446 xt::pyarray<int> &csrColumnOffsets_eb_u_u = args.array<int>("csrColumnOffsets_eb_u_u");
1447 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
1448 assert(a_rowptr.data()[nSpace] == nnz);
1449 assert(a_rowptr.data()[nSpace] == nSpace);
1450 double Ct_sge = 4.0;
1451
1452 //
1453 //loop over elements to compute volume integrals and load them into the element Jacobians and global Jacobian
1454 //
1455 for (int eN = 0; eN < nElements_global; eN++) {
1456 double elementJacobian_u_u[nDOF_test_element][nDOF_trial_element];
1457 // (0,1) cross-block element storage.
1458 double elementJacobian_u_n[nDOF_test_element][nDOF_trial_element];
1459 for (int i = 0; i < nDOF_test_element; i++) {
1460 for (int j = 0; j < nDOF_trial_element; j++) {
1461 elementJacobian_u_u[i][j] = 0.0;
1462 elementJacobian_u_n[i][j] = 0.0;
1463 }
1464 }
1465 for (int k = 0; k < nQuadraturePoints_element; k++) {
1466 int eN_k = eN * nQuadraturePoints_element + k, //index to a scalar at a quadrature point
1467 eN_k_nSpace = eN_k * nSpace,
1468 eN_nDOF_trial_element = eN * nDOF_trial_element; //index to a vector at a quadrature point
1469
1470 //declare local storage
1471 double u = 0.0, grad_u[nSpace], m = 0.0, dm = 0.0, f[nSpace], df[nSpace], a[nnz], da[nnz], as[nnz], m_t = 0.0, dm_t = 0.0, dpdeResidual_u_u[nDOF_trial_element], Lstar_u[nDOF_test_element], dsubgridError_u_u[nDOF_trial_element], tau = 0.0, tau0 = 0.0, tau1 = 0.0, jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], u_grad_trial[nDOF_trial_element * nSpace], dV, u_test_dV[nDOF_test_element], u_grad_test_dV[nDOF_test_element * nSpace], x, y, z, xt, yt, zt, G[nSpace * nSpace], G_dd_G, tr_G;
1472 //
1473 //calculate solution and gradients at quadrature points
1474 //
1475 //get jacobian, etc for mapping reference element
1476 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), mesh_grad_trial_ref.data(), jac, jacDet, jacInv, x, y, z);
1477 ck.calculateMappingVelocity_element(eN, k, mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), xt, yt, zt);
1478 //get the physical integration weight
1479 dV = fabs(jacDet) * dV_ref.data()[k];
1480 ck.calculateG(jacInv, G, G_dd_G, tr_G);
1481 //get the trial function gradients
1482 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace], jacInv, u_grad_trial);
1483 //get the solution
1484 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], &u_trial_ref.data()[k * nDOF_trial_element], u);
1485 //get the solution gradients
1486 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial, grad_u);
1487 //precalculate test function products with integration weights
1488 for (int j = 0; j < nDOF_trial_element; j++) {
1489 u_test_dV[j] = u_test_ref.data()[k * nDOF_trial_element + j] * dV;
1490 for (int I = 0; I < nSpace; I++) {
1491 u_grad_test_dV[j * nSpace + I] = u_grad_trial[j * nSpace + I] * dV; //cek warning won't work for Petrov-Galerkin
1492 }
1493 }
1494 //
1495 // Compositional (p,z) H2O-equation Jacobian (P3c). Residual:
1496 // R^w_i = (phi*N*(1-z))_t * N_i dV + VMS num.diff - F_0.gradN_i dV,
1497 // F_0 = rho_g*(1-Y)*u_g + rho_a*(1-X)*u_a. Differentiate wrt the
1498 // primaries p=u_w (->(0,0)) and z=u_n (->(0,1)) and their gradients,
1499 // chain-ruled through the analytic flash. FD-verified in
1500 // flux_jac_test.cpp. (u is p, grad_u is grad p at this QP.)
1501 //
1502 const int mat_eN0 = elementMaterialTypes.data()[eN];
1503 const double alpha_eN0 = alpha.data()[mat_eN0];
1504 const double n_vg_eN0 = n.data()[mat_eN0];
1505 const double krn_end_eN0 = krn_end.data()[mat_eN0];
1506 const double *KWs_eN0 = &KWs.data()[mat_eN0 * nnz];
1507 const double phi_eN0 = thetaR.data()[mat_eN0] + thetaSR.data()[mat_eN0];
1508 const double S_wr_loc0 = thetaR.data()[mat_eN0] / phi_eN0;
1509 const double one_m_Sr0 = 1.0 - S_wr_loc0;
1510 const double Se_trap_L1547 = 1.0 - S_gr.data()[mat_eN0] / one_m_Sr0; // gas-only residual trapping
1511 double u_n_qp = 0.0, grad_u_n[nSpace];
1512 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
1513 &u_trial_ref.data()[k * nDOF_trial_element], u_n_qp);
1514 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
1515 u_grad_trial, grad_u_n);
1516 const double p_cl0 = fmax(u, 1.0e2);
1519 const double S_g0 = fs0.S_g, Sa0 = 1.0 - S_g0;
1520 // accumulation m_0 = phi*N*(1-z), N = rho_g*S_g + rho_a*S_a:
1521 const double N0 = fs0.rho_g*S_g0 + fs0.rho_a*Sa0;
1522 const double dN0_dp = fs0.drho_g_dp*S_g0 + fs0.rho_g*fs0.dS_g_dp
1523 + fs0.drho_a_dp*Sa0 - fs0.rho_a*fs0.dS_g_dp;
1524 const double dN0_dz = fs0.drho_g_dz*S_g0 + fs0.rho_g*fs0.dS_g_dz
1525 + fs0.drho_a_dz*Sa0 - fs0.rho_a*fs0.dS_g_dz;
1526 const double dm0_dp = phi_eN0 * dN0_dp * (1.0 - u_n_qp);
1527 const double dm0_dz = phi_eN0 * (dN0_dz * (1.0 - u_n_qp) - N0);
1528 // wetting effective saturation from the flash saturation + (p,z) derivs.
1529 const double Se_raw0 = (Sa0 - S_wr_loc0) / one_m_Sr0;
1530 double Se_a0, dSe0_dp, dSe0_dz;
1531 if (Se_raw0 <= 0.0) { Se_a0 = 0.0; dSe0_dp = 0.0; dSe0_dz = 0.0; }
1532 else if (Se_raw0 >= 1.0) { Se_a0 = 1.0; dSe0_dp = 0.0; dSe0_dz = 0.0; }
1533 else { Se_a0 = Se_raw0; dSe0_dp = -fs0.dS_g_dp/one_m_Sr0; dSe0_dz = -fs0.dS_g_dz/one_m_Sr0; }
1534 double KWr0=0.0, DKWr0=0.0, thW0=0.0, DthW0=0.0, KNr0=0.0, DKNr0=0.0;
1535 double pc0=0.0, dpc_dSe0=0.0, d2pc0=0.0;
1536 if (PSK_TYPE_member == 1) {
1537 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0,
1538 thetaR.data()[mat_eN0], thetaSR.data()[mat_eN0], thW0, DthW0, KWr0, DKWr0);
1539 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0, KNr0, DKNr0, Se_trap_L1547);
1540 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_a0, alpha_eN0, n_vg_eN0, bc_Se_min.data()[mat_eN0], pc0, dpc_dSe0, d2pc0);
1541 } else {
1542 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0,
1543 thetaR.data()[mat_eN0], thetaSR.data()[mat_eN0], thW0, DthW0, KWr0, DKWr0);
1544 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_a0, alpha_eN0, n_vg_eN0, KNr0, DKNr0, Se_trap_L1547);
1545 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_a0, alpha_eN0, n_vg_eN0, pc0, dpc_dSe0, d2pc0);
1546 }
1547 KNr0 *= krn_end_eN0; DKNr0 *= krn_end_eN0;
1548 const double pcp0 = dpc_dSe0 / one_m_Sr0; // pc'(S_a)
1549 const double dpcp0_dp = (d2pc0 / one_m_Sr0) * dSe0_dp;
1550 const double dpcp0_dz = (d2pc0 / one_m_Sr0) * dSe0_dz;
1552 const double Mbar_g0 = fs0.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fs0.Y)*::m_comp_co2::eos::M_H2O_KG;
1553 const double Mbar_a0 = fs0.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fs0.X)*::m_comp_co2::eos::M_H2O_KG;
1554 const double rho_g_mass0 = fs0.rho_g*Mbar_g0, rho_a_mass0 = fs0.rho_a*Mbar_a0;
1555 const double drgm0_dp = fs0.drho_g_dp*Mbar_g0 + fs0.rho_g*fs0.dY_dp*dMm0;
1556 const double drgm0_dz = fs0.rho_g*fs0.dY_dz*dMm0;
1557 const double dram0_dp = fs0.drho_a_dp*Mbar_a0 + fs0.rho_a*fs0.dX_dp*dMm0;
1558 const double dram0_dz = fs0.drho_a_dz*Mbar_a0 + fs0.rho_a*fs0.dX_dz*dMm0;
1559 // H2O transport coefficients Ag=rho_g*(1-Y), Aa=rho_a*(1-X) + (p,z) derivs.
1560 const double Ag0 = fs0.rho_g*(1.0-fs0.Y), Aa0 = fs0.rho_a*(1.0-fs0.X);
1561 const double dAg0_dp = fs0.drho_g_dp*(1.0-fs0.Y) - fs0.rho_g*fs0.dY_dp;
1562 const double dAg0_dz = - fs0.rho_g*fs0.dY_dz;
1563 const double dAa0_dp = fs0.drho_a_dp*(1.0-fs0.X) - fs0.rho_a*fs0.dX_dp;
1564 const double dAa0_dz = fs0.drho_a_dz*(1.0-fs0.X) - fs0.rho_a*fs0.dX_dz;
1565 // per-direction Darcy velocities + value-block partials (gradients fixed).
1566 double ug0[nSpace], ua0[nSpace];
1567 double dug0_dp[nSpace], dug0_dz[nSpace], dua0_dp[nSpace], dua0_dz[nSpace];
1568 for (int I = 0; I < nSpace; I++) {
1569 double ugI=0.0, uaI=0.0, dugp=0.0, dugz=0.0, duap=0.0, duaz=0.0;
1570 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
1571 const int J = a_colind.data()[ii];
1572 const double Kii = KWs_eN0[ii];
1573 const double Mob_g = KNr0*Kii/mu_n, Mob_a = KWr0*Kii;
1574 const double dMobg_dp = (DKNr0*Kii/mu_n)*dSe0_dp, dMobg_dz = (DKNr0*Kii/mu_n)*dSe0_dz;
1575 const double dMoba_dp = (DKWr0*Kii)*dSe0_dp, dMoba_dz = (DKWr0*Kii)*dSe0_dz;
1576 const double gJ = gravity.data()[J];
1577 const double gradSa = -(fs0.dS_g_dp*grad_u[J] + fs0.dS_g_dz*grad_u_n[J]);
1578 const double gp_a = grad_u[J] - rho_a_mass0*gJ;
1579 const double gp_g = grad_u[J] + pcp0*gradSa - rho_g_mass0*gJ;
1580 ugI -= Mob_g*gp_g; uaI -= Mob_a*gp_a;
1581 const double dgradSa_dp = -(fs0.d2S_g_dp2 *grad_u[J] + fs0.d2S_g_dpdz*grad_u_n[J]);
1582 const double dgradSa_dz = -(fs0.d2S_g_dpdz*grad_u[J] + fs0.d2S_g_dz2 *grad_u_n[J]);
1583 const double dgpg_dp = dpcp0_dp*gradSa + pcp0*dgradSa_dp - drgm0_dp*gJ;
1584 const double dgpg_dz = dpcp0_dz*gradSa + pcp0*dgradSa_dz - drgm0_dz*gJ;
1585 dugp -= dMobg_dp*gp_g + Mob_g*dgpg_dp;
1586 dugz -= dMobg_dz*gp_g + Mob_g*dgpg_dz;
1587 duap -= dMoba_dp*gp_a + Mob_a*(-dram0_dp*gJ);
1588 duaz -= dMoba_dz*gp_a + Mob_a*(-dram0_dz*gJ);
1589 }
1590 ug0[I]=ugI; ua0[I]=uaI;
1591 dug0_dp[I]=dugp; dug0_dz[I]=dugz; dua0_dp[I]=duap; dua0_dz[I]=duaz;
1592 }
1593 // Assemble (0,0) [d/dp] and (0,1) [d/dz].
1594 // dR^w_i/d(p_j) = alphaBDF*dm0/dp * N_j N_i dV
1595 // - [ (dF_0/dp)_val N_j + (dF_0/dgrad_p).gradN_j ].gradN_i dV
1596 // + VMS num.diff
1597 for (int i = 0; i < nDOF_test_element; i++) {
1598 const int i_nSpace = i * nSpace;
1599 double Sval_p = 0.0, Sval_z = 0.0;
1600 for (int I = 0; I < nSpace; I++) {
1601 const double gNiI = u_grad_trial[i_nSpace + I];
1602 Sval_p += (dAg0_dp*ug0[I] + Ag0*dug0_dp[I] + dAa0_dp*ua0[I] + Aa0*dua0_dp[I]) * gNiI;
1603 Sval_z += (dAg0_dz*ug0[I] + Ag0*dug0_dz[I] + dAa0_dz*ua0[I] + Aa0*dua0_dz[I]) * gNiI;
1604 }
1605 for (int j = 0; j < nDOF_trial_element; j++) {
1606 const int j_nSpace = j * nSpace;
1607 const double trial_j = u_trial_ref.data()[k * nDOF_trial_element + j];
1608 double Sgrad_p = 0.0, Sgrad_z = 0.0;
1609 for (int I = 0; I < nSpace; I++) {
1610 const double gNiI = u_grad_trial[i_nSpace + I];
1611 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
1612 const int J = a_colind.data()[ii];
1613 const double Kii = KWs_eN0[ii];
1614 const double Mob_g = KNr0*Kii/mu_n, Mob_a = KWr0*Kii;
1615 const double gNjJ = u_grad_trial[j_nSpace + J];
1616 const double dFdgp = Ag0*(-Mob_g*(1.0 - pcp0*fs0.dS_g_dp)) + Aa0*(-Mob_a);
1617 const double dFdgz = Ag0*(-Mob_g*(-pcp0*fs0.dS_g_dz));
1618 Sgrad_p += dFdgp * gNjJ * gNiI;
1619 Sgrad_z += dFdgz * gNjJ * gNiI;
1620 }
1621 }
1622 elementJacobian_u_u[i][j] += alphaBDF * dm0_dp * trial_j * u_test_dV[i];
1623 elementJacobian_u_u[i][j] -= (Sval_p * trial_j + Sgrad_p) * dV;
1624 elementJacobian_u_u[i][j] += VMS * ck.NumericalDiffusionJacobian(
1625 q_numDiff_u_last[eN_k], &u_grad_trial[j_nSpace], &u_grad_test_dV[i_nSpace]);
1626 elementJacobian_u_n[i][j] += alphaBDF * dm0_dz * trial_j * u_test_dV[i];
1627 elementJacobian_u_n[i][j] -= (Sval_z * trial_j + Sgrad_z) * dV;
1628 }
1629 }
1630 } //k
1631 //
1632 //load into element Jacobian into global Jacobian
1633 //
1634 for (int i = 0; i < nDOF_test_element; i++) {
1635 int eN_i = eN * nDOF_test_element + i;
1636 for (int j = 0; j < nDOF_trial_element; j++) {
1637 int eN_i_j = eN_i * nDOF_trial_element + j;
1638 globalJacobian.data()[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_u_u[eN_i_j]] += elementJacobian_u_u[i][j];
1639 // load (0,1) cross-block coupling the wetting eq to S_n through
1640 // dm/du_n, df/du_n, da/du_n.
1641 globalJacobian.data()[csrRowIndeces_w_n.data()[eN_i] + csrColumnOffsets_w_n.data()[eN_i_j]] += elementJacobian_u_n[i][j];
1642 } //j
1643 } //i
1644 } //elements
1645 //
1646 //loop over exterior element boundaries to compute the surface integrals and load them into the global Jacobian
1647 //
1648 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++) {
1649 int ebN = exteriorElementBoundariesArray.data()[ebNE];
1650 int eN = elementBoundaryElementsArray.data()[ebN * 2 + 0], ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN * 2 + 0], eN_nDOF_trial_element = eN * nDOF_trial_element;
1651 for (int kb = 0; kb < nQuadraturePoints_elementBoundary; kb++) {
1652 int ebNE_kb = ebNE * nQuadraturePoints_elementBoundary + kb, ebNE_kb_nSpace = ebNE_kb * nSpace, ebN_local_kb = ebN_local * nQuadraturePoints_elementBoundary + kb, ebN_local_kb_nSpace = ebN_local_kb * nSpace;
1653
1654 double u_ext = 0.0, grad_u_ext[nSpace], m_ext = 0.0, dm_ext = 0.0, f_ext[nSpace], df_ext[nSpace], a_ext[nnz], da_ext[nnz], as_ext[nnz], dflux_u_u_ext = 0.0, bc_u_ext = 0.0,
1655 //bc_grad_u_ext[nSpace],
1656 bc_m_ext = 0.0, bc_dm_ext = 0.0, bc_f_ext[nSpace], bc_df_ext[nSpace], bc_a_ext[nnz], bc_da_ext[nnz], bc_as_ext[nnz], fluxJacobian_u_u[nDOF_trial_element], jac_ext[nSpace * nSpace], jacDet_ext, jacInv_ext[nSpace * nSpace], boundaryJac[nSpace * (nSpace - 1)], metricTensor[(nSpace - 1) * (nSpace - 1)], metricTensorDetSqrt, dS, u_test_dS[nDOF_test_element], u_grad_trial_trace[nDOF_trial_element * nSpace], normal[3], x_ext, y_ext, z_ext, xt_ext, yt_ext, zt_ext, integralScaling, G[nSpace * nSpace], G_dd_G, tr_G;
1657 //
1658 //calculate the solution and gradients at quadrature points
1659 //
1660 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,
1661 normal_ref.data(), normal, x_ext, y_ext, z_ext);
1662 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);
1663 dS = ((1.0 - MOVING_DOMAIN) * metricTensorDetSqrt + MOVING_DOMAIN * integralScaling) * dS_ref.data()[kb];
1664 ck.calculateG(jacInv_ext, G, G_dd_G, tr_G);
1665 //compute shape and solution information
1666 //shape
1667 ck.gradTrialFromRef(&u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace * nDOF_trial_element], jacInv_ext, u_grad_trial_trace);
1668 //solution and gradients
1669 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);
1670 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial_trace, grad_u_ext);
1671 //precalculate test function products with integration weights
1672 for (int j = 0; j < nDOF_trial_element; j++) { u_test_dS[j] = u_test_trace_ref.data()[ebN_local_kb * nDOF_test_element + j] * dS; }
1673 //
1674 //load the boundary values
1675 //
1676 bc_u_ext = isDOFBoundary_u.data()[ebNE_kb] * ebqe_bc_u_ext.data()[ebNE_kb] + (1 - isDOFBoundary_u.data()[ebNE_kb]) * u_ext;
1677 //
1678 //calculate the internal and external trace of the pde coefficients
1679 //
1680 double Kr, dKr, thetaW, thetaW_bc;
1681 const double rho_ext = ebqe_rho.data()[ebNE_kb];
1682 // Boundary closure for the wetting-equation Jacobian. (0,1) boundary
1683 // contribution is not assembled here.
1684 double dm_du_n_ext = 0.0, dkr_du_n_ext = 0.0;
1685 double df_du_n_ext[nSpace];
1686 double da_du_n_ext[nnz];
1687 double bc_dm_du_n = 0.0, bc_dkr_du_n = 0.0;
1688 double bc_df_du_n[nSpace];
1689 double bc_da_du_n[nnz];
1690 for (int I = 0; I < nSpace; I++) { df_du_n_ext[I] = 0.0; bc_df_du_n[I] = 0.0; }
1691 for (int ii = 0; ii < nnz; ii++) { da_du_n_ext[ii] = 0.0; bc_da_du_n[ii] = 0.0; }
1692 // u_n_ext_qp & bc_u_n_ext_qp held at outer scope for the (0,1) boundary
1693 // Jacobian assembly below.
1694 double u_n_ext_qp_outer = 0.0;
1695 double bc_u_n_ext_qp_outer = 0.0;
1696 {
1697 double u_n_ext_qp = 0.0;
1698 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
1699 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], u_n_ext_qp);
1700 const double bc_u_n_ext_qp = isDOFBoundary_n.data()[ebNE_kb] * ebqe_bc_u_n_ext.data()[ebNE_kb]
1701 + (1 - isDOFBoundary_n.data()[ebNE_kb]) * u_n_ext_qp;
1702 u_n_ext_qp_outer = u_n_ext_qp;
1703 bc_u_n_ext_qp_outer = bc_u_n_ext_qp;
1704 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
1705 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
1706 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
1707 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], u_ext, u_n_ext_qp,
1708 m_ext, dm_ext, dm_du_n_ext, f_ext, df_ext, df_du_n_ext, a_ext, da_ext, da_du_n_ext,
1709 as_ext, Kr, dKr, dkr_du_n_ext, thetaW);
1710 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
1711 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
1712 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
1713 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], bc_u_ext, bc_u_n_ext_qp,
1714 bc_m_ext, bc_dm_ext, bc_dm_du_n, bc_f_ext, bc_df_ext, bc_df_du_n, bc_a_ext, bc_da_ext, bc_da_du_n,
1715 bc_as_ext, Kr, dKr, bc_dkr_du_n, thetaW_bc);
1716 }
1717 //
1718 // ===== P3c boundary: compositional comp-0 (H2O) flux Jacobian =====
1719 // d(flux_0)/d(p_j) -> fluxJacobian_u_u, d(flux_0)/d(z_j) -> fluxJacobian_u_n,
1720 // where flux_0 = F_0.n + penalty*(p - p_BC). Mirrors the interior comp-0
1721 // flux Jacobian (grad N_i -> normal, + penalty*trial_j); the F_0 value/grad
1722 // partials are FD-verified (boundary0_test.cpp / flux_jac_test.cpp).
1723 // Nonzero only on Dirichlet-p faces; no-flow faces contribute 0.
1724 double fluxJacobian_u_n[nDOF_trial_element];
1725 for (int j = 0; j < nDOF_trial_element; j++) { fluxJacobian_u_u[j] = 0.0; fluxJacobian_u_n[j] = 0.0; }
1726 if (isDOFBoundary_u.data()[ebNE_kb]) {
1727 double grad_u_n_ext[nSpace];
1728 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
1729 u_grad_trial_trace, grad_u_n_ext);
1730 const int mat_b = elementMaterialTypes.data()[eN];
1731 const double alpha_b = alpha.data()[mat_b];
1732 const double n_vg_b = n.data()[mat_b];
1733 const double krn_end_b = krn_end.data()[mat_b];
1734 const double *KWs_b = &KWs.data()[mat_b * nnz];
1735 const double phi_b = thetaR.data()[mat_b] + thetaSR.data()[mat_b];
1736 const double S_wr_b = thetaR.data()[mat_b] / phi_b;
1737 const double one_m_Sr_b = 1.0 - S_wr_b;
1738 const double Se_trap_L1775 = 1.0 - S_gr.data()[mat_b] / one_m_Sr_b; // gas-only residual trapping
1739 const double p_clb = fmax(u_ext, 1.0e2);
1742 const double Sab = 1.0 - fsb.S_g;
1743 const double Se_rawb = (Sab - S_wr_b)/one_m_Sr_b;
1744 double Se_ab, dSeb_dp, dSeb_dz;
1745 if (Se_rawb<=0.0){Se_ab=0.0;dSeb_dp=0.0;dSeb_dz=0.0;}
1746 else if (Se_rawb>=1.0){Se_ab=1.0;dSeb_dp=0.0;dSeb_dz=0.0;}
1747 else {Se_ab=Se_rawb;dSeb_dp=-fsb.dS_g_dp/one_m_Sr_b;dSeb_dz=-fsb.dS_g_dz/one_m_Sr_b;}
1748 double KWrb=0,DKWrb=0,thWb=0,DthWb=0,KNrb=0,DKNrb=0,pcb=0,dpc_dSeb=0,d2pcb=0;
1749 if (PSK_TYPE_member == 1) {
1750 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_ab, alpha_b, n_vg_b, thetaR.data()[mat_b], thetaSR.data()[mat_b], thWb, DthWb, KWrb, DKWrb);
1751 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_ab, alpha_b, n_vg_b, KNrb, DKNrb, Se_trap_L1775);
1752 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_ab, alpha_b, n_vg_b, bc_Se_min.data()[mat_b], pcb, dpc_dSeb, d2pcb);
1753 } else {
1754 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_ab, alpha_b, n_vg_b, thetaR.data()[mat_b], thetaSR.data()[mat_b], thWb, DthWb, KWrb, DKWrb);
1755 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_ab, alpha_b, n_vg_b, KNrb, DKNrb, Se_trap_L1775);
1756 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_ab, alpha_b, n_vg_b, pcb, dpc_dSeb, d2pcb);
1757 }
1758 KNrb *= krn_end_b; DKNrb *= krn_end_b;
1759 const double pcpb = dpc_dSeb / one_m_Sr_b;
1760 const double dpcpb_dp = (d2pcb / one_m_Sr_b) * dSeb_dp;
1761 const double dpcpb_dz = (d2pcb / one_m_Sr_b) * dSeb_dz;
1763 const double Mbar_gb = fsb.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb.Y)*::m_comp_co2::eos::M_H2O_KG;
1764 const double Mbar_ab = fsb.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb.X)*::m_comp_co2::eos::M_H2O_KG;
1765 const double rgmb = fsb.rho_g*Mbar_gb, ramb = fsb.rho_a*Mbar_ab;
1766 const double drgmb_dp = fsb.drho_g_dp*Mbar_gb + fsb.rho_g*fsb.dY_dp*dMmb;
1767 const double drgmb_dz = fsb.rho_g*fsb.dY_dz*dMmb;
1768 const double dramb_dp = fsb.drho_a_dp*Mbar_ab + fsb.rho_a*fsb.dX_dp*dMmb;
1769 const double dramb_dz = fsb.drho_a_dz*Mbar_ab + fsb.rho_a*fsb.dX_dz*dMmb;
1770 const double Agb = fsb.rho_g*(1.0-fsb.Y), Aab = fsb.rho_a*(1.0-fsb.X);
1771 const double dAgb_dp = fsb.drho_g_dp*(1.0-fsb.Y) - fsb.rho_g*fsb.dY_dp;
1772 const double dAgb_dz = - fsb.rho_g*fsb.dY_dz;
1773 const double dAab_dp = fsb.drho_a_dp*(1.0-fsb.X) - fsb.rho_a*fsb.dX_dp;
1774 const double dAab_dz = fsb.drho_a_dz*(1.0-fsb.X) - fsb.rho_a*fsb.dX_dz;
1775 double ugb[nSpace], uab[nSpace], dugb_dp[nSpace], dugb_dz[nSpace], duab_dp[nSpace], duab_dz[nSpace];
1776 for (int I=0;I<nSpace;I++){
1777 double ugI=0,uaI=0,dugp=0,dugz=0,duap=0,duaz=0;
1778 for (int ii=a_rowptr.data()[I];ii<a_rowptr.data()[I+1];ii++){
1779 const int J=a_colind.data()[ii];
1780 const double Kii=KWs_b[ii];
1781 const double Mob_g=KNrb*Kii/mu_n, Mob_a=KWrb*Kii;
1782 const double dMobg_dp=(DKNrb*Kii/mu_n)*dSeb_dp, dMobg_dz=(DKNrb*Kii/mu_n)*dSeb_dz;
1783 const double dMoba_dp=(DKWrb*Kii)*dSeb_dp, dMoba_dz=(DKWrb*Kii)*dSeb_dz;
1784 const double gJ=gravity.data()[J];
1785 const double gradSa=-(fsb.dS_g_dp*grad_u_ext[J]+fsb.dS_g_dz*grad_u_n_ext[J]);
1786 const double gp_a=grad_u_ext[J]-ramb*gJ;
1787 const double gp_g=grad_u_ext[J]+pcpb*gradSa-rgmb*gJ;
1788 ugI-=Mob_g*gp_g; uaI-=Mob_a*gp_a;
1789 const double dgradSa_dp=-(fsb.d2S_g_dp2*grad_u_ext[J]+fsb.d2S_g_dpdz*grad_u_n_ext[J]);
1790 const double dgradSa_dz=-(fsb.d2S_g_dpdz*grad_u_ext[J]+fsb.d2S_g_dz2*grad_u_n_ext[J]);
1791 const double dgpg_dp=dpcpb_dp*gradSa+pcpb*dgradSa_dp-drgmb_dp*gJ;
1792 const double dgpg_dz=dpcpb_dz*gradSa+pcpb*dgradSa_dz-drgmb_dz*gJ;
1793 dugp-=dMobg_dp*gp_g+Mob_g*dgpg_dp;
1794 dugz-=dMobg_dz*gp_g+Mob_g*dgpg_dz;
1795 duap-=dMoba_dp*gp_a+Mob_a*(-dramb_dp*gJ);
1796 duaz-=dMoba_dz*gp_a+Mob_a*(-dramb_dz*gJ);
1797 }
1798 ugb[I]=ugI;uab[I]=uaI;dugb_dp[I]=dugp;dugb_dz[I]=dugz;duab_dp[I]=duap;duab_dz[I]=duaz;
1799 }
1800 const double penb = ebqe_penalty_ext.data()[ebNE_kb];
1801 for (int j=0;j<nDOF_trial_element;j++){
1802 const int j_nSpace = j*nSpace;
1803 const double trial_j = u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element + j];
1804 double accp=0.0, accz=0.0;
1805 for (int I=0;I<nSpace;I++){
1806 const double nI = normal[I];
1807 const double valp = dAgb_dp*ugb[I]+Agb*dugb_dp[I]+dAab_dp*uab[I]+Aab*duab_dp[I];
1808 const double valz = dAgb_dz*ugb[I]+Agb*dugb_dz[I]+dAab_dz*uab[I]+Aab*duab_dz[I];
1809 double gradp=0.0, gradz=0.0;
1810 for (int ii=a_rowptr.data()[I];ii<a_rowptr.data()[I+1];ii++){
1811 const int J=a_colind.data()[ii];
1812 const double Kii=KWs_b[ii];
1813 const double Mob_g=KNrb*Kii/mu_n, Mob_a=KWrb*Kii;
1814 const double gNjJ = u_grad_trial_trace[j_nSpace + J];
1815 const double dFdgp = Agb*(-Mob_g*(1.0 - pcpb*fsb.dS_g_dp)) + Aab*(-Mob_a);
1816 const double dFdgz = Agb*(-Mob_g*(-pcpb*fsb.dS_g_dz));
1817 gradp += dFdgp*gNjJ;
1818 gradz += dFdgz*gNjJ;
1819 }
1820 accp += nI*(valp*trial_j + gradp);
1821 accz += nI*(valz*trial_j + gradz);
1822 }
1823 fluxJacobian_u_u[j] = accp + penb*trial_j;
1824 fluxJacobian_u_n[j] = accz;
1825 }
1826 }
1827 //
1828 //update the global Jacobian from the flux Jacobian
1829 //
1830 for (int i = 0; i < nDOF_test_element; i++) {
1831 int eN_i = eN * nDOF_test_element + i;
1832 for (int j = 0; j < nDOF_trial_element; j++) {
1833 int ebN_i_j = ebN * 4 * nDOF_test_X_trial_element + i * nDOF_trial_element + j;
1834 globalJacobian.data()[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += fluxJacobian_u_u[j] * u_test_dS[i];
1835 // (0,1) cross-block boundary contribution (nonzero only on
1836 // Dirichlet faces for u_w).
1837 globalJacobian.data()[csrRowIndeces_w_n.data()[eN_i] + csrColumnOffsets_eb_w_n.data()[ebN_i_j]] += fluxJacobian_u_n[j] * u_test_dS[i];
1838 } //j
1839 } //i
1840 } //kb
1841 } //ebNE
1842
1843 // ============================================================================
1844 // Compositional (p,z) component-1 (CO2) Jacobian -- accumulation + component
1845 // molar flux F_1 = rho_g*Y*u_g + rho_a*X*u_a, all flash-derived. u_w = p,
1846 // u_n = z (overall CO2 mole fraction; NOT a saturation).
1847 //
1848 // m_1 = phi*N*z, N = rho_g*S_g + rho_a*S_a (S_g, rho_a, rho_g from flash)
1849 //
1850 // J_(1,1)[i,j] = dm_1/dz/dt * N_i N_j dV
1851 // - [ (dF_1/dz)_val N_j + (dF_1/dgrad_z).gradN_j ].gradN_i dV
1852 // J_(1,0)[i,j] = dm_1/dp/dt * N_i N_j dV
1853 // - [ (dF_1/dp)_val N_j + (dF_1/dgrad_p).gradN_j ].gradN_i dV
1854 //
1855 // (0,1) cross-block (wetting eq dependence on z) is assembled in the element
1856 // loop above. Per-QP flux partials FD-verified in flux_jac_test.cpp.
1857 // ============================================================================
1858 for (int eN = 0; eN < nElements_global; eN++) {
1859 const int mat_eN = elementMaterialTypes.data()[eN];
1860 const double phi_eN = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
1861 const double alpha_eN = alpha.data()[mat_eN];
1862 const double krn_end_eN = krn_end.data()[mat_eN];
1863 const double n_vg_eN = n.data()[mat_eN];
1864 const double *KWs_eN = &KWs.data()[mat_eN * nnz];
1865 // dm_n_du_n is no longer hoisted: ρ_n depends on the Newton iterate
1866 // through the linear EOS, so phi*ρ_n*S_n derivative is QP-local.
1867 double elementJacobian_n_n[nDOF_test_element][nDOF_trial_element];
1868 double elementJacobian_n_w[nDOF_test_element][nDOF_trial_element];
1869 for (int i = 0; i < nDOF_test_element; i++)
1870 for (int j = 0; j < nDOF_trial_element; j++) {
1871 elementJacobian_n_n[i][j] = 0.0;
1872 elementJacobian_n_w[i][j] = 0.0;
1873 }
1874 for (int k = 0; k < nQuadraturePoints_element; k++) {
1875 const int eN_k = eN * nQuadraturePoints_element + k;
1876 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
1877 double jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], x_q, y_q, z_q;
1878 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(),
1879 mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
1880 jac, jacDet, jacInv, x_q, y_q, z_q);
1881 const double dV = std::fabs(jacDet) * dV_ref.data()[k];
1882 // Trial gradients in physical coords.
1883 double u_grad_trial_qp[nDOF_trial_element * nSpace];
1884 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace],
1885 jacInv, u_grad_trial_qp);
1886 // Saturation u_n at QP.
1887 double u_n = 0.0;
1888 ck.valFromDOF(u_dof_n.data(),
1889 &u_l2g.data()[eN_nDOF_trial_element],
1890 &u_trial_ref.data()[k * nDOF_trial_element], u_n);
1891 // Wetting-pressure value (for linear EOS) and gradient at QP.
1892 double u_w_qp = 0.0;
1893 ck.valFromDOF(u_dof.data(),
1894 &u_l2g.data()[eN_nDOF_trial_element],
1895 &u_trial_ref.data()[k * nDOF_trial_element], u_w_qp);
1896 double grad_u_w[nSpace];
1897 ck.gradFromDOF(u_dof.data(),
1898 &u_l2g.data()[eN_nDOF_trial_element],
1899 u_grad_trial_qp, grad_u_w);
1900 // Step 3d: saturation gradient at QP for the capillary diffusion term.
1901 double grad_u_n[nSpace];
1902 ck.gradFromDOF(u_dof_n.data(),
1903 &u_l2g.data()[eN_nDOF_trial_element],
1904 u_grad_trial_qp, grad_u_n);
1905 // =====================================================================
1906 // Compositional (p,z) CO2-equation Jacobian (P3c). The flux is the
1907 // component molar flux F_1 = rho_g*Y*u_g + rho_a*X*u_a assembled in the
1908 // residual; here we differentiate it (and the accumulation m_1=phi*N*z)
1909 // wrt the primaries (p=u_w, z=u_n) AND their gradients, chain-ruled
1910 // through the analytic flash. Formulas FD-verified in flux_jac_test.cpp.
1911 // =====================================================================
1912 const double p_cl_j = fmax(u_w_qp, 1.0e2);
1915 const double S_g_j = fs_j.S_g, Sa_j = 1.0 - S_g_j;
1916 // accumulation m_1 = phi*N*z, N = rho_g*S_g + rho_a*S_a:
1917 const double N_j = fs_j.rho_g*S_g_j + fs_j.rho_a*Sa_j;
1918 const double dN_dp_j = fs_j.drho_g_dp*S_g_j + fs_j.rho_g*fs_j.dS_g_dp
1919 + fs_j.drho_a_dp*Sa_j - fs_j.rho_a*fs_j.dS_g_dp;
1920 const double dN_dz_j = fs_j.drho_g_dz*S_g_j + fs_j.rho_g*fs_j.dS_g_dz
1921 + fs_j.drho_a_dz*Sa_j - fs_j.rho_a*fs_j.dS_g_dz;
1922 const double dm_n_du_n = phi_eN * (dN_dz_j * u_n + N_j); // d m_1/dz
1923 const double dm_n_du_w = phi_eN * (dN_dp_j * u_n); // d m_1/dp
1924 // wetting effective saturation from the FLASH saturation + (p,z) derivs.
1925 const double S_wr_loc = thetaR.data()[mat_eN] / phi_eN;
1926 const double one_m_Sr_loc = 1.0 - S_wr_loc;
1927 const double Se_trap_L1965 = 1.0 - S_gr.data()[mat_eN] / one_m_Sr_loc; // gas-only residual trapping
1928 const double Se_raw_j = (Sa_j - S_wr_loc) / one_m_Sr_loc;
1929 double Se_a, dSe_dp, dSe_dz;
1930 if (Se_raw_j <= 0.0) { Se_a = 0.0; dSe_dp = 0.0; dSe_dz = 0.0; }
1931 else if (Se_raw_j >= 1.0) { Se_a = 1.0; dSe_dp = 0.0; dSe_dz = 0.0; }
1932 else { Se_a = Se_raw_j; dSe_dp = -fs_j.dS_g_dp/one_m_Sr_loc; dSe_dz = -fs_j.dS_g_dz/one_m_Sr_loc; }
1933 double KWr_a=0.0, DKWr_a=0.0, thW_a=0.0, DthW_a=0.0, KNr_a=0.0, DKNr_a=0.0;
1934 double pc_a=0.0, dpc_dSe_a=0.0, d2pc_a=0.0;
1935 if (PSK_TYPE_member == 1) {
1936 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_a, alpha_eN, n_vg_eN,
1937 thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_a, DthW_a, KWr_a, DKWr_a);
1938 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_a, alpha_eN, n_vg_eN, KNr_a, DKNr_a, Se_trap_L1965);
1939 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_a, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc_a, dpc_dSe_a, d2pc_a);
1940 } else {
1941 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_a, alpha_eN, n_vg_eN,
1942 thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_a, DthW_a, KWr_a, DKWr_a);
1943 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_a, alpha_eN, n_vg_eN, KNr_a, DKNr_a, Se_trap_L1965);
1944 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_a, alpha_eN, n_vg_eN, pc_a, dpc_dSe_a, d2pc_a);
1945 }
1946 KNr_a *= krn_end_eN; DKNr_a *= krn_end_eN;
1947 const double pcp_a = dpc_dSe_a / one_m_Sr_loc; // pc'(S_a)
1948 const double dpcp_dp = (d2pc_a / one_m_Sr_loc) * dSe_dp; // d pc'(S_a)/dp
1949 const double dpcp_dz = (d2pc_a / one_m_Sr_loc) * dSe_dz;
1950 // mass densities for gravity (molar density * mean molar mass) + derivs.
1952 const double Mbar_g = fs_j.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fs_j.Y)*::m_comp_co2::eos::M_H2O_KG;
1953 const double Mbar_a = fs_j.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fs_j.X)*::m_comp_co2::eos::M_H2O_KG;
1954 const double rho_g_mass = fs_j.rho_g*Mbar_g, rho_a_mass = fs_j.rho_a*Mbar_a;
1955 const double drgm_dp = fs_j.drho_g_dp*Mbar_g + fs_j.rho_g*fs_j.dY_dp*dMm;
1956 const double drgm_dz = fs_j.rho_g*fs_j.dY_dz*dMm;
1957 const double dram_dp = fs_j.drho_a_dp*Mbar_a + fs_j.rho_a*fs_j.dX_dp*dMm;
1958 const double dram_dz = fs_j.drho_a_dz*Mbar_a + fs_j.rho_a*fs_j.dX_dz*dMm;
1959 // CO2 transport coefficients Ag=rho_g*Y, Aa=rho_a*X + (p,z) derivatives.
1960 const double Ag = fs_j.rho_g*fs_j.Y, Aa = fs_j.rho_a*fs_j.X;
1961 const double dAg_dp = fs_j.drho_g_dp*fs_j.Y + fs_j.rho_g*fs_j.dY_dp;
1962 const double dAg_dz = fs_j.rho_g*fs_j.dY_dz;
1963 const double dAa_dp = fs_j.drho_a_dp*fs_j.X + fs_j.rho_a*fs_j.dX_dp;
1964 const double dAa_dz = fs_j.drho_a_dz*fs_j.X + fs_j.rho_a*fs_j.dX_dz;
1965 // per-direction Darcy velocities ug[I], ua[I] + their value-block partials
1966 // (gradients held fixed). Mobilities carry the 1/mu_n (gas) factor.
1967 double ug[nSpace], ua[nSpace];
1968 double dug_dp[nSpace], dug_dz[nSpace], dua_dp[nSpace], dua_dz[nSpace];
1969 for (int I = 0; I < nSpace; I++) {
1970 double ugI=0.0, uaI=0.0, dugp=0.0, dugz=0.0, duap=0.0, duaz=0.0;
1971 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
1972 const int J = a_colind.data()[ii];
1973 const double Kii = KWs_eN[ii];
1974 const double Mob_g = KNr_a*Kii/mu_n, Mob_a = KWr_a*Kii;
1975 const double dMobg_dp = (DKNr_a*Kii/mu_n)*dSe_dp, dMobg_dz = (DKNr_a*Kii/mu_n)*dSe_dz;
1976 const double dMoba_dp = (DKWr_a*Kii)*dSe_dp, dMoba_dz = (DKWr_a*Kii)*dSe_dz;
1977 const double gJ = gravity.data()[J];
1978 const double gradSa = -(fs_j.dS_g_dp*grad_u_w[J] + fs_j.dS_g_dz*grad_u_n[J]);
1979 const double gp_a = grad_u_w[J] - rho_a_mass*gJ;
1980 const double gp_g = grad_u_w[J] + pcp_a*gradSa - rho_g_mass*gJ;
1981 ugI -= Mob_g*gp_g; uaI -= Mob_a*gp_a;
1982 const double dgradSa_dp = -(fs_j.d2S_g_dp2 *grad_u_w[J] + fs_j.d2S_g_dpdz*grad_u_n[J]);
1983 const double dgradSa_dz = -(fs_j.d2S_g_dpdz*grad_u_w[J] + fs_j.d2S_g_dz2 *grad_u_n[J]);
1984 const double dgpg_dp = dpcp_dp*gradSa + pcp_a*dgradSa_dp - drgm_dp*gJ;
1985 const double dgpg_dz = dpcp_dz*gradSa + pcp_a*dgradSa_dz - drgm_dz*gJ;
1986 dugp -= dMobg_dp*gp_g + Mob_g*dgpg_dp;
1987 dugz -= dMobg_dz*gp_g + Mob_g*dgpg_dz;
1988 duap -= dMoba_dp*gp_a + Mob_a*(-dram_dp*gJ);
1989 duaz -= dMoba_dz*gp_a + Mob_a*(-dram_dz*gJ);
1990 }
1991 ug[I]=ugI; ua[I]=uaI;
1992 dug_dp[I]=dugp; dug_dz[I]=dugz; dua_dp[I]=duap; dua_dz[I]=duaz;
1993 }
1994 // (Kinetic R_diss dissolution sink removed -- dissolution is now handled
1995 // thermodynamically by the inline flash, so there is no sink Jacobian.)
1996 // Assemble per (i, j). Residual: R^c_i = m_1_t*N_i*dV - F_1.gradN_i*dV.
1997 // Flux Jacobian (chain rule through the flash):
1998 // dR^c_i/d(z_j) = -[ (dF_1/dz)_val * N_j + (dF_1/dgrad_z) . gradN_j ] . gradN_i dV -> (1,1)
1999 // dR^c_i/d(p_j) = -[ (dF_1/dp)_val * N_j + (dF_1/dgrad_p) . gradN_j ] . gradN_i dV -> (1,0)
2000 for (int i = 0; i < nDOF_test_element; i++) {
2001 const double test_i = u_test_ref.data()[k * nDOF_test_element + i];
2002 // value-block scalars: sum_I (dF_1/dval) * gradN_i[I] (val = p, z)
2003 double Sval_p = 0.0, Sval_z = 0.0;
2004 for (int I = 0; I < nSpace; I++) {
2005 const double gNiI = u_grad_trial_qp[i * nSpace + I];
2006 Sval_p += (dAg_dp*ug[I] + Ag*dug_dp[I] + dAa_dp*ua[I] + Aa*dua_dp[I]) * gNiI;
2007 Sval_z += (dAg_dz*ug[I] + Ag*dug_dz[I] + dAa_dz*ua[I] + Aa*dua_dz[I]) * gNiI;
2008 }
2009 for (int j = 0; j < nDOF_trial_element; j++) {
2010 const double trial_j = u_trial_ref.data()[k * nDOF_trial_element + j];
2011 // gradient-block scalars: sum_{I,ii} (dF_1[I]/dgrad_var[J]) gradN_j[J] gradN_i[I]
2012 double Sgrad_p = 0.0, Sgrad_z = 0.0;
2013 for (int I = 0; I < nSpace; I++) {
2014 const double gNiI = u_grad_trial_qp[i * nSpace + I];
2015 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
2016 const int J = a_colind.data()[ii];
2017 const double Kii = KWs_eN[ii];
2018 const double Mob_g = KNr_a*Kii/mu_n, Mob_a = KWr_a*Kii;
2019 const double gNjJ = u_grad_trial_qp[j * nSpace + J];
2020 // d ug[I]/d grad_p[J] = -Mob_g*(1 - pcp*dSg_dp); d ua[I]/d grad_p[J] = -Mob_a
2021 const double dFdgp = Ag*(-Mob_g*(1.0 - pcp_a*fs_j.dS_g_dp)) + Aa*(-Mob_a);
2022 // d ug[I]/d grad_z[J] = -Mob_g*(-pcp*dSg_dz); d ua[I]/d grad_z[J] = 0
2023 const double dFdgz = Ag*(-Mob_g*(-pcp_a*fs_j.dS_g_dz));
2024 Sgrad_p += dFdgp * gNjJ * gNiI;
2025 Sgrad_z += dFdgz * gNjJ * gNiI;
2026 }
2027 }
2028 // (1,1): accumulation (implicit BDF) + CO2 flux d/dz.
2029 elementJacobian_n_n[i][j] += (dm_n_du_n * test_i * trial_j * dV) / dt_n;
2030 elementJacobian_n_n[i][j] -= (Sval_z * trial_j + Sgrad_z) * dV;
2031 // (1,0): accumulation d/dp + CO2 flux d/dp.
2032 elementJacobian_n_w[i][j] += (dm_n_du_w * test_i * trial_j * dV) / dt_n;
2033 elementJacobian_n_w[i][j] -= (Sval_p * trial_j + Sgrad_p) * dV;
2034 }
2035 }
2036 }
2037 for (int i = 0; i < nDOF_test_element; i++) {
2038 const int eN_i = eN * nDOF_test_element + i;
2039 for (int j = 0; j < nDOF_trial_element; j++) {
2040 const int eN_i_j = eN_i * nDOF_trial_element + j;
2041 globalJacobian.data()[csrRowIndeces_n_n.data()[eN_i] + csrColumnOffsets_n_n.data()[eN_i_j]]
2042 += elementJacobian_n_n[i][j];
2043 globalJacobian.data()[csrRowIndeces_n_w.data()[eN_i] + csrColumnOffsets_n_w.data()[eN_i_j]]
2044 += elementJacobian_n_w[i][j];
2045 }
2046 }
2047 }
2048
2049 // ============================================================================
2050 // Comp-1 (CO2 / z) exterior boundary Jacobian -- STAB=0 path. COMPOSITIONAL.
2051 // Matching Jacobian for the compositional F_1.n boundary residual term in
2052 // calculateResidual. Mirrors the FD-verified interior comp-1 flux Jacobian
2053 // (~line 1942) chain-ruled through the analytic flash, with the interior
2054 // gradN_i replaced by the boundary normal n_I:
2055 // (1,1): d(F_1.n)/dz (value-block * trial_j + grad-block . gradN_j)
2056 // + Nitsche penalty * trial_j (Dirichlet faces only)
2057 // (1,0): d(F_1.n)/dp (value-block * trial_j + grad-block . gradN_j)
2058 // Gated on isDir_n: no-flow faces contribute nothing (matches the residual).
2059 // ============================================================================
2060 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++) {
2061 const int ebN = exteriorElementBoundariesArray.data()[ebNE];
2062 const int eN = elementBoundaryElementsArray.data()[ebN * 2 + 0];
2063 const int ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN * 2 + 0];
2064 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
2065 const int mat_eN = elementMaterialTypes.data()[eN];
2066 const double phi_eN = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
2067 const double alpha_eN = alpha.data()[mat_eN];
2068 const double krn_end_eN = krn_end.data()[mat_eN];
2069 const double n_vg_eN = n.data()[mat_eN];
2070 const double *KWs_eN = &KWs.data()[mat_eN * nnz];
2071 const double S_wr_loc = thetaR.data()[mat_eN] / phi_eN;
2072 const double one_m_Sr_loc = 1.0 - S_wr_loc;
2073 const double Se_trap_L2110 = 1.0 - S_gr.data()[mat_eN] / one_m_Sr_loc; // gas-only residual trapping
2074
2075 double elementJacobian_n_n_eb[nDOF_test_element][nDOF_trial_element];
2076 double elementJacobian_n_w_eb[nDOF_test_element][nDOF_trial_element];
2077 for (int i = 0; i < nDOF_test_element; i++)
2078 for (int j = 0; j < nDOF_trial_element; j++) {
2079 elementJacobian_n_n_eb[i][j] = 0.0;
2080 elementJacobian_n_w_eb[i][j] = 0.0;
2081 }
2082
2083 for (int kb = 0; kb < nQuadraturePoints_elementBoundary; kb++) {
2084 const int ebNE_kb = ebNE * nQuadraturePoints_elementBoundary + kb;
2085 const int ebN_local_kb = ebN_local * nQuadraturePoints_elementBoundary + kb;
2086 const int ebN_local_kb_nSpace = ebN_local_kb * nSpace;
2087
2088 double jac_ext[nSpace * nSpace], jacDet_ext, jacInv_ext[nSpace * nSpace];
2089 double boundaryJac_b[nSpace * (nSpace - 1)];
2090 double metricTensor_b[(nSpace - 1) * (nSpace - 1)];
2091 double metricTensorDetSqrt_b, dS_eb, normal_b[3];
2092 double xt_b, yt_b, zt_b, integralScaling_b;
2093 double x_eb, y_eb, z_eb;
2094 ck.calculateMapping_elementBoundary(eN, ebN_local, kb, ebN_local_kb,
2095 mesh_dof.data(), mesh_l2g.data(), mesh_trial_trace_ref.data(),
2096 mesh_grad_trial_trace_ref.data(), boundaryJac_ref.data(),
2097 jac_ext, jacDet_ext, jacInv_ext, boundaryJac_b, metricTensor_b,
2098 metricTensorDetSqrt_b, normal_ref.data(), normal_b,
2099 x_eb, y_eb, z_eb);
2100 ck.calculateMappingVelocity_elementBoundary(eN, ebN_local, kb, ebN_local_kb,
2101 mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_trace_ref.data(),
2102 xt_b, yt_b, zt_b, normal_b, boundaryJac_b, metricTensor_b,
2103 integralScaling_b);
2104 dS_eb = ((1.0 - MOVING_DOMAIN) * metricTensorDetSqrt_b
2105 + MOVING_DOMAIN * integralScaling_b) * dS_ref.data()[kb];
2106
2107 double u_grad_trial_trace_b[nDOF_trial_element * nSpace];
2108 ck.gradTrialFromRef(
2109 &u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace * nDOF_trial_element],
2110 jacInv_ext, u_grad_trial_trace_b);
2111 double u_w_ext_b = 0.0, u_n_ext_b = 0.0;
2112 double grad_u_w_ext_b[nSpace], grad_u_n_ext_b[nSpace];
2113 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element],
2114 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], u_w_ext_b);
2115 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
2116 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], u_n_ext_b);
2117 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element],
2118 u_grad_trial_trace_b, grad_u_w_ext_b);
2119 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
2120 u_grad_trial_trace_b, grad_u_n_ext_b);
2121
2122 const int isDir_n = isDOFBoundary_n.data()[ebNE_kb];
2123 const double penalty = ebqe_penalty_ext.data()[ebNE_kb];
2124
2125 // ====================================================================
2126 // P3c boundary (STAB=0): compositional comp-1 (CO2) flux Jacobian.
2127 // Matches the F_1.n residual boundary; mirrors the FD-verified interior
2128 // comp-1 Jacobian (~line 1942) chain-ruled through the analytic flash,
2129 // with the interior gradN_i replaced by the boundary normal n_I:
2130 // (1,1) d(F_1.n)/dz + Nitsche penalty * trial_j (Dirichlet faces),
2131 // (1,0) d(F_1.n)/dp.
2132 // ====================================================================
2133 const double p_clb = fmax(u_w_ext_b, 1.0e2);
2136 const double Sa_b = 1.0 - fsb.S_g;
2137 const double Se_raw_b = (Sa_b - S_wr_loc) / one_m_Sr_loc;
2138 double Se_b, dSe_dp_b, dSe_dz_b;
2139 if (Se_raw_b <= 0.0) { Se_b = 0.0; dSe_dp_b = 0.0; dSe_dz_b = 0.0; }
2140 else if (Se_raw_b >= 1.0) { Se_b = 1.0; dSe_dp_b = 0.0; dSe_dz_b = 0.0; }
2141 else { Se_b = Se_raw_b; dSe_dp_b = -fsb.dS_g_dp/one_m_Sr_loc; dSe_dz_b = -fsb.dS_g_dz/one_m_Sr_loc; }
2142 double KWr_b=0,DKWr_b=0,thW_b=0,DthW_b=0,KNr_b=0,DKNr_b=0,pc_b=0,dpc_dSe_b=0,d2pc_b=0;
2143 if (PSK_TYPE_member == 1) {
2144 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_b, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_b, DthW_b, KWr_b, DKWr_b);
2145 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_b, alpha_eN, n_vg_eN, KNr_b, DKNr_b, Se_trap_L2110);
2146 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_b, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc_b, dpc_dSe_b, d2pc_b);
2147 } else {
2148 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_b, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_b, DthW_b, KWr_b, DKWr_b);
2149 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_b, alpha_eN, n_vg_eN, KNr_b, DKNr_b, Se_trap_L2110);
2150 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_b, alpha_eN, n_vg_eN, pc_b, dpc_dSe_b, d2pc_b);
2151 }
2152 KNr_b *= krn_end_eN; DKNr_b *= krn_end_eN;
2153 const double pcp_b = dpc_dSe_b / one_m_Sr_loc;
2154 const double dpcp_dp_b = (d2pc_b / one_m_Sr_loc) * dSe_dp_b;
2155 const double dpcp_dz_b = (d2pc_b / one_m_Sr_loc) * dSe_dz_b;
2157 const double Mbar_g_b = fsb.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb.Y)*::m_comp_co2::eos::M_H2O_KG;
2158 const double Mbar_a_b = fsb.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb.X)*::m_comp_co2::eos::M_H2O_KG;
2159 const double rho_g_mass_b = fsb.rho_g*Mbar_g_b, rho_a_mass_b = fsb.rho_a*Mbar_a_b;
2160 const double drgm_dp_b = fsb.drho_g_dp*Mbar_g_b + fsb.rho_g*fsb.dY_dp*dMm_b;
2161 const double drgm_dz_b = fsb.rho_g*fsb.dY_dz*dMm_b;
2162 const double dram_dp_b = fsb.drho_a_dp*Mbar_a_b + fsb.rho_a*fsb.dX_dp*dMm_b;
2163 const double dram_dz_b = fsb.drho_a_dz*Mbar_a_b + fsb.rho_a*fsb.dX_dz*dMm_b;
2164 const double Ag = fsb.rho_g*fsb.Y, Aa = fsb.rho_a*fsb.X;
2165 const double dAg_dp = fsb.drho_g_dp*fsb.Y + fsb.rho_g*fsb.dY_dp;
2166 const double dAg_dz = fsb.rho_g*fsb.dY_dz;
2167 const double dAa_dp = fsb.drho_a_dp*fsb.X + fsb.rho_a*fsb.dX_dp;
2168 const double dAa_dz = fsb.drho_a_dz*fsb.X + fsb.rho_a*fsb.dX_dz;
2169 double ug_b[nSpace], ua_b[nSpace];
2170 double dug_dp_b[nSpace], dug_dz_b[nSpace], dua_dp_b[nSpace], dua_dz_b[nSpace];
2171 for (int I = 0; I < nSpace; I++) {
2172 double ugI=0.0, uaI=0.0, dugp=0.0, dugz=0.0, duap=0.0, duaz=0.0;
2173 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
2174 const int J = a_colind.data()[ii];
2175 const double Kii = KWs_eN[ii];
2176 const double Mob_g = KNr_b*Kii/mu_n, Mob_a = KWr_b*Kii;
2177 const double dMobg_dp = (DKNr_b*Kii/mu_n)*dSe_dp_b, dMobg_dz = (DKNr_b*Kii/mu_n)*dSe_dz_b;
2178 const double dMoba_dp = (DKWr_b*Kii)*dSe_dp_b, dMoba_dz = (DKWr_b*Kii)*dSe_dz_b;
2179 const double gJ = gravity.data()[J];
2180 const double gradSa = -(fsb.dS_g_dp*grad_u_w_ext_b[J] + fsb.dS_g_dz*grad_u_n_ext_b[J]);
2181 const double gp_a = grad_u_w_ext_b[J] - rho_a_mass_b*gJ;
2182 const double gp_g = grad_u_w_ext_b[J] + pcp_b*gradSa - rho_g_mass_b*gJ;
2183 ugI -= Mob_g*gp_g; uaI -= Mob_a*gp_a;
2184 const double dgradSa_dp = -(fsb.d2S_g_dp2 *grad_u_w_ext_b[J] + fsb.d2S_g_dpdz*grad_u_n_ext_b[J]);
2185 const double dgradSa_dz = -(fsb.d2S_g_dpdz*grad_u_w_ext_b[J] + fsb.d2S_g_dz2 *grad_u_n_ext_b[J]);
2186 const double dgpg_dp = dpcp_dp_b*gradSa + pcp_b*dgradSa_dp - drgm_dp_b*gJ;
2187 const double dgpg_dz = dpcp_dz_b*gradSa + pcp_b*dgradSa_dz - drgm_dz_b*gJ;
2188 dugp -= dMobg_dp*gp_g + Mob_g*dgpg_dp;
2189 dugz -= dMobg_dz*gp_g + Mob_g*dgpg_dz;
2190 duap -= dMoba_dp*gp_a + Mob_a*(-dram_dp_b*gJ);
2191 duaz -= dMoba_dz*gp_a + Mob_a*(-dram_dz_b*gJ);
2192 }
2193 ug_b[I]=ugI; ua_b[I]=uaI;
2194 dug_dp_b[I]=dugp; dug_dz_b[I]=dugz; dua_dp_b[I]=duap; dua_dz_b[I]=duaz;
2195 }
2196 // value-block scalars dotted with the normal (interior gradN_i -> n_I).
2197 double Sval_p_b = 0.0, Sval_z_b = 0.0;
2198 for (int I = 0; I < nSpace; I++) {
2199 Sval_p_b += (dAg_dp*ug_b[I] + Ag*dug_dp_b[I] + dAa_dp*ua_b[I] + Aa*dua_dp_b[I]) * normal_b[I];
2200 Sval_z_b += (dAg_dz*ug_b[I] + Ag*dug_dz_b[I] + dAa_dz*ua_b[I] + Aa*dua_dz_b[I]) * normal_b[I];
2201 }
2202 // IIPG penalty scaled by the comp-1 diffusion magnitude a_n (frozen
2203 // coefficient) -- MUST match the residual loop in calculateResidual.
2204 double Kw_rep = 0.0;
2205 for (int ii = 0; ii < nnz; ii++) Kw_rep = fmax(Kw_rep, fabs(KWs_eN[ii]));
2206 const double a_n_scale = (Ag*KNr_b/mu_n + Aa*KWr_b) * Kw_rep;
2207 const double pen_eff = penalty * a_n_scale;
2208
2209 for (int i = 0; i < nDOF_test_element; i++) {
2210 const double test_i_dS = u_test_trace_ref.data()[
2211 ebN_local_kb * nDOF_test_element + i] * dS_eb;
2212 for (int j = 0; j < nDOF_trial_element; j++) {
2213 const double trial_j_b = u_trial_trace_ref.data()[
2214 ebN_local_kb * nDOF_test_element + j];
2215 double Sgrad_p_b = 0.0, Sgrad_z_b = 0.0;
2216 for (int I = 0; I < nSpace; I++) {
2217 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
2218 const int J = a_colind.data()[ii];
2219 const double Kii = KWs_eN[ii];
2220 const double Mob_g = KNr_b*Kii/mu_n, Mob_a = KWr_b*Kii;
2221 const double gNjJ = u_grad_trial_trace_b[j * nSpace + J];
2222 const double dFdgp = Ag*(-Mob_g*(1.0 - pcp_b*fsb.dS_g_dp)) + Aa*(-Mob_a);
2223 const double dFdgz = Ag*(-Mob_g*(-pcp_b*fsb.dS_g_dz));
2224 Sgrad_p_b += dFdgp * gNjJ * normal_b[I];
2225 Sgrad_z_b += dFdgz * gNjJ * normal_b[I];
2226 }
2227 }
2228 double jac_nn = Sval_z_b * trial_j_b + Sgrad_z_b;
2229 double jac_nw = Sval_p_b * trial_j_b + Sgrad_p_b;
2230 if (isDir_n) {
2231 jac_nn += pen_eff * trial_j_b;
2232 } else {
2233 jac_nn = 0.0;
2234 jac_nw = 0.0;
2235 }
2236 elementJacobian_n_n_eb[i][j] += jac_nn * test_i_dS;
2237 elementJacobian_n_w_eb[i][j] += jac_nw * test_i_dS;
2238 }
2239 }
2240 } // kb
2241
2242 for (int i = 0; i < nDOF_test_element; i++) {
2243 const int eN_i = eN * nDOF_test_element + i;
2244 for (int j = 0; j < nDOF_trial_element; j++) {
2245 const int ebN_i_j = ebN * 4 * nDOF_test_X_trial_element
2246 + i * nDOF_trial_element + j;
2247 globalJacobian.data()[csrRowIndeces_n_n.data()[eN_i]
2248 + csrColumnOffsets_eb_n_n.data()[ebN_i_j]] += elementJacobian_n_n_eb[i][j];
2249 globalJacobian.data()[csrRowIndeces_n_w.data()[eN_i]
2250 + csrColumnOffsets_eb_n_w.data()[ebN_i_j]] += elementJacobian_n_w_eb[i][j];
2251 }
2252 }
2253 } // ebNE
2254 } //computeJacobian
2255
2256
2257
2258 // ============================================================================
2259 // FCTStep -- Zalesak FCT limiter, component- and pass-dispatched (ONE function).
2260 //
2261 // if component == 0 (wetting, p_w) / else component == 1 (non-wetting, S_n);
2262 // within each, if pass == 1 / else pass == 2.
2263 //
2264 // Split into two passes for MPI parallel-correctness: the limiter is
2265 // mass-conservative only if both ranks sharing an edge compute the SAME
2266 // L_ij, which needs Rpos/Rneg consistent for BOTH endpoints. With 1-layer
2267 // overlap a ghost DOF's stencil is incomplete, so pass 1 computes Rpos/Rneg
2268 // locally, Python ghost-scatters them, then pass 2 applies the limiter.
2269 // In serial the scatter is a no-op.
2270 //
2271 // pass 1: inputs -> FluxCorrectionMatrix, Rpos, Rneg
2272 // [Python: scatter_forward Rpos, Rneg]
2273 // pass 2: Rpos, Rneg, FluxCorrectionMatrix -> limited_solution, fluxCorrection
2274 //
2275 // comp-0 indexes MC / dt_times_fH_minus_fL by the FULL CSR offset (via
2276 // full_offset_from_compact); comp-1 indexes MC_n / dt_times_fH_minus_fL_n by
2277 // the COMPACT comp-1 CSR position directly.
2278 // ============================================================================
2280 {
2281 const int component = args.scalar<int>("component");
2282 const int pass = args.scalar<int>("pass");
2283
2284 if (component == 0) {
2285 // ======================= wetting (p_w) =======================
2286 if (pass == 1) {
2287 int numDOFs = args.scalar<int>("numDOFs");
2288 double dt = args.scalar<double>("dt");
2289 xt::pyarray<double> &ML = args.array<double>("ML");
2290 xt::pyarray<double> &mn = args.array<double>("mn");
2291 xt::pyarray<double> &mLow = args.array<double>("mLow");
2292 xt::pyarray<double> &mDotLow = args.array<double>("mDotLow");
2293 xt::pyarray<int> &csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
2294 xt::pyarray<int> &csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
2295 xt::pyarray<int> &csrRowIndeces_Full = args.array<int>("csrRowIndeces_Full");
2296 xt::pyarray<int> &csrColumnOffsets_Full = args.array<int>("csrColumnOffsets_Full");
2297 xt::pyarray<double> &MC = args.array<double>("MC");
2298 xt::pyarray<double> &dt_times_fH_minus_fL = args.array<double>("dt_times_fH_minus_fL");
2299 xt::pyarray<double> &min_m_bc = args.array<double>("min_m_bc");
2300 xt::pyarray<double> &max_m_bc = args.array<double>("max_m_bc");
2301 xt::pyarray<double> &FluxCorrectionMatrix = args.array<double>("FluxCorrectionMatrix");
2302 xt::pyarray<double> &Rpos = args.array<double>("Rpos");
2303 xt::pyarray<double> &Rneg = args.array<double>("Rneg");
2304 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
2305 int MONOLITHIC = args.scalar<int>("MONOLITHIC");
2306 const int offset_u = args.scalar<int>("offset_u");
2307 const int stride_u = args.scalar<int>("stride_u");
2308 auto full_offset_from_compact = [&](int i_compact, int j_compact) -> int {
2309 const int full_i = offset_u + stride_u * i_compact;
2310 const int full_j = offset_u + stride_u * j_compact;
2311 for (int offset = csrRowIndeces_Full.at(full_i); offset < csrRowIndeces_Full.at(full_i + 1); ++offset)
2312 if (csrColumnOffsets_Full.at(offset) == full_j) return offset;
2313 return -1;
2314 };
2315 int ij = 0;
2316 for (int i = 0; i < numDOFs; i++) {
2317 double mini = min_m_bc.at(i);
2318 double maxi = max_m_bc.at(i);
2319 double Pposi = 0.0, Pnegi = 0.0;
2320 for (int offset = csrRowIndeces_DofLoops.at(i); offset < csrRowIndeces_DofLoops.at(i + 1); offset++) {
2321 int j = csrColumnOffsets_DofLoops.at(offset);
2322 const int full_offset = full_offset_from_compact(i, j);
2323 assert(full_offset >= 0);
2324 if (GLOBAL_FCT == 0) {
2325 if (MONOLITHIC == 0) { mini = fmin(mini, mLow.at(j)); maxi = fmax(maxi, mLow.at(j)); }
2326 else { mini = fmin(mini, mn.at(j)); maxi = fmax(maxi, mn.at(j)); }
2327 }
2328 if (MONOLITHIC == 0) {
2329 FluxCorrectionMatrix.at(ij) = (LUMPED_MASS_MATRIX == 1 ? 0. : 1.) * dt
2330 * MC.at(full_offset) * (mDotLow.at(i) - mDotLow.at(j))
2331 + dt_times_fH_minus_fL.at(full_offset);
2332 } else {
2333 FluxCorrectionMatrix.at(ij) = dt_times_fH_minus_fL.at(full_offset);
2334 }
2335 Pposi += FluxCorrectionMatrix.at(ij) * ((FluxCorrectionMatrix.at(ij) > 0) ? 1. : 0.);
2336 Pnegi += FluxCorrectionMatrix.at(ij) * ((FluxCorrectionMatrix.at(ij) < 0) ? 1. : 0.);
2337 ij += 1;
2338 }
2339 double Qposi, Qnegi;
2340 if (MONOLITHIC == 0) {
2341 Qposi = ML.at(i) * (maxi - mLow.at(i));
2342 Qnegi = ML.at(i) * (mini - mLow.at(i));
2343 } else {
2344 const double gamma = 10.0 * ML.at(i);
2345 Qposi = fmin(0.5 * ML.at(i) * (1.0 - mn.at(i)), gamma * (maxi - mn.at(i)));
2346 Qnegi = fmax(0.5 * ML.at(i) * (0.0 - mn.at(i)), gamma * (mini - mn.at(i)));
2347 }
2348 Rpos.at(i) = ((Pposi == 0.0) ? 1.0 : fmin(1.0, Qposi / Pposi));
2349 Rneg.at(i) = ((Pnegi == 0.0) ? 1.0 : fmin(1.0, Qnegi / Pnegi));
2350 }
2351 } else {
2352 // comp-0 pass 2
2353 xt::pyarray<double> &bc_mask = args.array<double>("bc_mask");
2354 int numDOFs = args.scalar<int>("numDOFs");
2355 double dt = args.scalar<double>("dt");
2356 xt::pyarray<double> &ML = args.array<double>("ML");
2357 xt::pyarray<double> &mn = args.array<double>("mn");
2358 xt::pyarray<double> &mLow = args.array<double>("mLow");
2359 xt::pyarray<int> &csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
2360 xt::pyarray<int> &csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
2361 xt::pyarray<int> &csrRowIndeces_Full = args.array<int>("csrRowIndeces_Full");
2362 xt::pyarray<int> &csrColumnOffsets_Full = args.array<int>("csrColumnOffsets_Full");
2363 xt::pyarray<double> &MC = args.array<double>("MC");
2364 xt::pyarray<double> &FluxCorrectionMatrix = args.array<double>("FluxCorrectionMatrix");
2365 xt::pyarray<double> &Rpos = args.array<double>("Rpos");
2366 xt::pyarray<double> &Rneg = args.array<double>("Rneg");
2367 xt::pyarray<double> &fluxCorrection = args.array<double>("fluxCorrection");
2368 xt::pyarray<double> &limited_solution = args.array<double>("limited_solution");
2369 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
2370 int MONOLITHIC = args.scalar<int>("MONOLITHIC");
2371 const int offset_u = args.scalar<int>("offset_u");
2372 const int stride_u = args.scalar<int>("stride_u");
2373 auto full_offset_from_compact = [&](int i_compact, int j_compact) -> int {
2374 const int full_i = offset_u + stride_u * i_compact;
2375 const int full_j = offset_u + stride_u * j_compact;
2376 for (int offset = csrRowIndeces_Full.at(full_i); offset < csrRowIndeces_Full.at(full_i + 1); ++offset)
2377 if (csrColumnOffsets_Full.at(offset) == full_j) return offset;
2378 return -1;
2379 };
2380 int ij = 0;
2381 for (int i = 0; i < numDOFs; i++) {
2382 double ith_Limiter_times_FluxCorrectionMatrix = 0.0;
2383 const double beta_ij = 1.0;
2384 const double mDot_i = (mLow.at(i) - mn.at(i)) / dt;
2385 for (int offset = csrRowIndeces_DofLoops.at(i); offset < csrRowIndeces_DofLoops.at(i + 1); offset++) {
2386 int j = csrColumnOffsets_DofLoops.at(offset);
2387 const int full_offset = full_offset_from_compact(i, j);
2388 assert(full_offset >= 0);
2389 const double alpha_fA = ((FluxCorrectionMatrix.at(ij) > 0.0)
2390 ? fmin(Rpos.at(i), Rneg.at(j)) : fmin(Rneg.at(i), Rpos.at(j)))
2391 * FluxCorrectionMatrix.at(ij);
2392 if (MONOLITHIC == 0) {
2393 ith_Limiter_times_FluxCorrectionMatrix += alpha_fA;
2394 } else {
2395 const double mDot_j = (mLow.at(j) - mn.at(j)) / dt;
2396 const double alpha_dot = fmin(1.0, beta_ij * fabs(alpha_fA) / MC.at(full_offset)
2397 / fmax(1.0e-8, fabs(mDot_i - mDot_j)));
2398 ith_Limiter_times_FluxCorrectionMatrix += alpha_fA
2399 + (LUMPED_MASS_MATRIX == 1 ? 0. : 1.) * dt * alpha_dot
2400 * MC.at(full_offset) * (mDot_i - mDot_j);
2401 }
2402 ij += 1;
2403 }
2404 fluxCorrection.at(i) = -ith_Limiter_times_FluxCorrectionMatrix * bc_mask.at(i) / dt;
2405 limited_solution.at(i) = mLow.at(i)
2406 + 1.0 / ML.at(i) * ith_Limiter_times_FluxCorrectionMatrix * bc_mask.at(i);
2407 }
2408 }
2409 } else {
2410 // ===================== non-wetting (S_n) =====================
2411 if (pass == 1) {
2412 int numDOFs_n = args.scalar<int>("numDOFs_n");
2413 double dt = args.scalar<double>("dt");
2414 xt::pyarray<double> &ML_n = args.array<double>("ML_n");
2415 xt::pyarray<double> &MC_n = args.array<double>("MC_n");
2416 xt::pyarray<double> &mLow_n = args.array<double>("mLow_n");
2417 xt::pyarray<double> &mDotLow_n = args.array<double>("mDotLow_n");
2418 xt::pyarray<double> &dt_times_fH_minus_fL_n = args.array<double>("dt_times_fH_minus_fL_n");
2419 xt::pyarray<double> &min_m_bc_n = args.array<double>("min_m_bc_n");
2420 xt::pyarray<double> &max_m_bc_n = args.array<double>("max_m_bc_n");
2421 xt::pyarray<double> &FluxCorrectionMatrix_n = args.array<double>("FluxCorrectionMatrix_n");
2422 xt::pyarray<double> &Rpos_n = args.array<double>("Rpos_n");
2423 xt::pyarray<double> &Rneg_n = args.array<double>("Rneg_n");
2424 xt::pyarray<int> &csrRowIndeces_n_DofLoops = args.array<int>("csrRowIndeces_n_DofLoops");
2425 xt::pyarray<int> &csrColumnOffsets_n_DofLoops = args.array<int>("csrColumnOffsets_n_DofLoops");
2426 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
2427 int ij = 0;
2428 for (int i = 0; i < numDOFs_n; i++) {
2429 double mini = min_m_bc_n.at(i);
2430 double maxi = max_m_bc_n.at(i);
2431 double Pposi = 0.0, Pnegi = 0.0;
2432 for (int offset = csrRowIndeces_n_DofLoops.at(i);
2433 offset < csrRowIndeces_n_DofLoops.at(i + 1); offset++) {
2434 const int j = csrColumnOffsets_n_DofLoops.at(offset);
2435 if (GLOBAL_FCT == 0) {
2436 mini = std::fmin(mini, mLow_n.at(j));
2437 maxi = std::fmax(maxi, mLow_n.at(j));
2438 }
2439 FluxCorrectionMatrix_n.at(ij) =
2440 (LUMPED_MASS_MATRIX == 1 ? 0.0 : 1.0)
2441 * dt * MC_n.at(offset) * (mDotLow_n.at(i) - mDotLow_n.at(j))
2442 + dt_times_fH_minus_fL_n.at(offset);
2443 Pposi += (FluxCorrectionMatrix_n.at(ij) > 0.0) ? FluxCorrectionMatrix_n.at(ij) : 0.0;
2444 Pnegi += (FluxCorrectionMatrix_n.at(ij) < 0.0) ? FluxCorrectionMatrix_n.at(ij) : 0.0;
2445 ij += 1;
2446 }
2447 const double Qposi = ML_n.at(i) * (maxi - mLow_n.at(i));
2448 const double Qnegi = ML_n.at(i) * (mini - mLow_n.at(i));
2449 Rpos_n.at(i) = (Pposi == 0.0) ? 1.0 : std::fmin(1.0, Qposi / Pposi);
2450 Rneg_n.at(i) = (Pnegi == 0.0) ? 1.0 : std::fmin(1.0, Qnegi / Pnegi);
2451 }
2452 } else {
2453 // comp-1 pass 2
2454 int numDOFs_n = args.scalar<int>("numDOFs_n");
2455 double dt = args.scalar<double>("dt");
2456 xt::pyarray<double> &ML_n = args.array<double>("ML_n");
2457 xt::pyarray<double> &mLow_n = args.array<double>("mLow_n");
2458 xt::pyarray<double> &FluxCorrectionMatrix_n = args.array<double>("FluxCorrectionMatrix_n");
2459 xt::pyarray<double> &Rpos_n = args.array<double>("Rpos_n");
2460 xt::pyarray<double> &Rneg_n = args.array<double>("Rneg_n");
2461 xt::pyarray<double> &fluxCorrection_n = args.array<double>("fluxCorrection_n");
2462 xt::pyarray<double> &limited_solution_n = args.array<double>("limited_solution_n");
2463 xt::pyarray<double> &bc_mask_n = args.array<double>("bc_mask_n");
2464 xt::pyarray<int> &csrRowIndeces_n_DofLoops = args.array<int>("csrRowIndeces_n_DofLoops");
2465 xt::pyarray<int> &csrColumnOffsets_n_DofLoops = args.array<int>("csrColumnOffsets_n_DofLoops");
2466 int ij = 0;
2467 for (int i = 0; i < numDOFs_n; i++) {
2468 double ith_Limited_FCM = 0.0;
2469 for (int offset = csrRowIndeces_n_DofLoops.at(i);
2470 offset < csrRowIndeces_n_DofLoops.at(i + 1); offset++) {
2471 const int j = csrColumnOffsets_n_DofLoops.at(offset);
2472 const double alpha_fA =
2473 ((FluxCorrectionMatrix_n.at(ij) > 0.0)
2474 ? std::fmin(Rpos_n.at(i), Rneg_n.at(j))
2475 : std::fmin(Rneg_n.at(i), Rpos_n.at(j)))
2476 * FluxCorrectionMatrix_n.at(ij);
2477 ith_Limited_FCM += alpha_fA;
2478 ij += 1;
2479 }
2480 fluxCorrection_n.at(i) = -ith_Limited_FCM * bc_mask_n.at(i) / dt;
2481 limited_solution_n.at(i) = mLow_n.at(i)
2482 + (1.0 / ML_n.at(i)) * ith_Limited_FCM * bc_mask_n.at(i);
2483 }
2484 }
2485 }
2486 }
2487
2488
2490 {
2491 int NNZ = args.scalar<int>("NNZ"); //number on non-zero entries on sparsity pattern
2492 int numDOFs = args.scalar<int>("numDOFs"); //number of DOFs
2493 int num_fct_iter = args.scalar<int>("num_fct_iter");
2494 double dt = args.scalar<double>("dt");
2495 xt::pyarray<double> &lumped_mass_matrix = args.array<double>("lumped_mass_matrix"); //lumped mass matrix (as vector)
2496 xt::pyarray<double> &soln = args.array<double>("soln"); //DOFs of solution at time tn
2497 xt::pyarray<double> &pn = args.array<double>("pn"); //DOFs of solution at time tn
2498 xt::pyarray<double> &solH = args.array<double>("solH"); //DOFs of high order solution at tnp1
2499 xt::pyarray<double> &uLow = args.array<double>("uLow");
2500 xt::pyarray<double> &uDotLow = args.array<double>("uDotLow");
2501 xt::pyarray<double> &dLow = args.array<double>("dLow");
2502 xt::pyarray<double> &solLim = args.array<double>("limited_solution");
2503 xt::pyarray<double> &MC = args.array<double>("MC");
2504 xt::pyarray<double> &ML = args.array<double>("ML");
2505 xt::pyarray<double> &FluxMatrix = args.array<double>("FluxMatrix");
2506 xt::pyarray<double> &limitedFlux = args.array<double>("limited_Flux");
2507 xt::pyarray<int> &csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops"); //csr row indeces
2508 xt::pyarray<int> &csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops"); //csr column offsets
2509 xt::pyarray<double> &MassMatrix = args.array<double>("MassMatrix"); //mass matrix
2510 xt::pyarray<double> &dt_times_fH_minus_fL = args.array<double>("dt_times_fH_minus_fL"); //low minus high order dissipative matrices
2511 xt::pyarray<double> &min_m_bc = args.array<double>("min_m_bc"); //min/max value at BCs. If DOF is not at boundary then min=1E10, max=-1E10
2512 xt::pyarray<double> &max_m_bc = args.array<double>("max_m_bc");
2513 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
2514 int MONOLITHIC = args.scalar<int>("MONOLITHIC");
2515 double Rpos[numDOFs], Rneg[numDOFs];
2516 int ij = 0;
2517
2519 // ********** COMPUTE LOW ORDER SOLUTION ********** //
2521 if (num_fct_iter == 0) { // No FCT for global bounds
2522 for (int i = 0; i < numDOFs; i++) { solLim.data()[i] = uLow.data()[i]; }
2523 } else // do FCT iterations (with global bounds) on low order solution
2524 {
2525 for (int iter = 0; iter < num_fct_iter; iter++) {
2526 ij = 0;
2527 for (int i = 0; i < numDOFs; i++) {
2528 double maxi = 1.0, Pposi = 0;
2529 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) {
2530 int j = csrColumnOffsets_DofLoops.data()[offset];
2531 // compute Flux correction
2532 double Fluxij = FluxMatrix.data()[ij] - limitedFlux.data()[ij];
2533 Pposi += Fluxij * ((Fluxij > 0) ? 1. : 0.);
2534 // update ij
2535 ij += 1;
2536 }
2537 // compute Q vectors
2538 double mi = ML.data()[i];
2539 double solLimi = solLim.data()[i];
2540 double Qposi = mi * (maxi - solLimi);
2541 // compute R vectors
2542 Rpos[i] = ((Pposi == 0) ? 1. : fmin(1.0, Qposi / Pposi));
2543 }
2544 ij = 0;
2545 for (int i = 0; i < numDOFs; i++) {
2546 double ith_Limiter_times_FluxCorrectionMatrix = 0.;
2547 double Rposi = Rpos[i];
2548 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) {
2549 int j = csrColumnOffsets_DofLoops.data()[offset];
2550 // Flux Correction
2551 double Fluxij = FluxMatrix.data()[ij] - limitedFlux.data()[ij];
2552 // compute limiter
2553 double Lij = 1.0;
2554 Lij = (Fluxij > 0 ? Rposi : Rpos[j]);
2555 // compute limited flux
2556 ith_Limiter_times_FluxCorrectionMatrix += Lij * Fluxij;
2557
2558 // update limited flux
2559 limitedFlux.data()[ij] = Lij * Fluxij;
2560
2561 //update FluxMatrix
2562 FluxMatrix.data()[ij] = Fluxij;
2563
2564 //update ij
2565 ij += 1;
2566 }
2567 //update limited solution
2568 double mi = ML.data()[i];
2569 }
2570 }
2571 }
2572
2573 // ***************************************** //
2574 // ********** HIGH ORDER SOLUTION ********** //
2575 // ***************************************** //
2576 ij = 0;
2577 for (int i = 0; i < numDOFs; i++) {
2578 double mini = soln.data()[i], maxi = soln.data()[i];
2579 double Pposi = 0, Pnegi = 0.;
2580 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) {
2581 int j = csrColumnOffsets_DofLoops.data()[offset];
2582 // compute local bounds //
2583 mini = fmin(mini, soln.data()[j]);
2584 maxi = fmax(maxi, soln.data()[j]);
2585 // compute P vectors //
2586 double fij = (MC.data()[ij] * (uDotLow.data()[i] - uDotLow.data()[j]) / dt + dLow.data()[ij] * (uLow.data()[i] - uLow.data()[j]));
2587 Pposi += fij * (fij > 0 ? 1. : 0.);
2588 Pnegi += fij * (fij < 0 ? 1. : 0.);
2589 //update ij
2590 ij += 1;
2591 }
2592 // compute Q vectors //
2593 double mi = ML.data()[i];
2594 double Qposi = mi * (maxi - solLim.data()[i]);
2595 double Qnegi = mi * (mini - solLim.data()[i]);
2596 // compute R vectors //
2597 Rpos[i] = ((Pposi == 0) ? 1. : fmin(1.0, Qposi / Pposi));
2598 Rneg[i] = ((Pnegi == 0) ? 1. : fmin(1.0, Qnegi / Pnegi));
2599 }
2600
2601 // COMPUTE LIMITERS //
2602 ij = 0;
2603 for (int i = 0; i < numDOFs; i++) {
2604 double ith_limited_flux_correction = 0;
2605 double Rposi = Rpos[i];
2606 double Rnegi = Rneg[i];
2607 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) {
2608 int j = csrColumnOffsets_DofLoops.data()[offset];
2609 // compute flux correction
2610 double fij = (MC.data()[ij] * (uDotLow.data()[i] - uDotLow.data()[j]) / dt + dLow.data()[ij] * (uLow.data()[i] - uLow.data()[j]));
2611
2612 // compute limiters
2613 double Lij = 1.0;
2614 Lij = fij > 0 ? fmin(Rposi, Rneg[j]) : fmin(Rnegi, Rpos[j]);
2615 // compute ith_limited_flux_correction
2616 ith_limited_flux_correction += Lij * fij;
2617 ij += 1;
2618 }
2619 double mi = ML.data()[i];
2620 solLim[i] += 1. / mi * ith_limited_flux_correction;
2621 }
2622 }
2623
2625 {
2626 xt::pyarray<double> &globalJacobian = args.array<double>("globalJacobian");
2627 double Theta = args.scalar<double>("Theta");
2628 double Theta_h = args.scalar<double>("Theta_h");
2629 xt::pyarray<double> &bc_mask = args.array<double>("bc_mask");
2630 double dt = args.scalar<double>("dt");
2631 xt::pyarray<double> &mesh_trial_ref = args.array<double>("mesh_trial_ref");
2632 xt::pyarray<double> &mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
2633 xt::pyarray<double> &mesh_dof = args.array<double>("mesh_dof");
2634 xt::pyarray<double> &mesh_velocity_dof = args.array<double>("mesh_velocity_dof");
2635 double MOVING_DOMAIN = args.scalar<double>("MOVING_DOMAIN");
2636 xt::pyarray<int> &mesh_l2g = args.array<int>("mesh_l2g");
2637 xt::pyarray<double> &dV_ref = args.array<double>("dV_ref");
2638 xt::pyarray<double> &u_trial_ref = args.array<double>("u_trial_ref");
2639 xt::pyarray<double> &u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
2640 xt::pyarray<double> &u_test_ref = args.array<double>("u_test_ref");
2641 xt::pyarray<double> &u_grad_test_ref = args.array<double>("u_grad_test_ref");
2642 xt::pyarray<double> &mesh_trial_trace_ref = args.array<double>("mesh_trial_trace_ref");
2643 xt::pyarray<double> &mesh_grad_trial_trace_ref = args.array<double>("mesh_grad_trial_trace_ref");
2644 xt::pyarray<double> &dS_ref = args.array<double>("dS_ref");
2645 xt::pyarray<double> &u_trial_trace_ref = args.array<double>("u_trial_trace_ref");
2646
2647 xt::pyarray<double> &u_grad_trial_trace_ref = args.array<double>("u_grad_trial_trace_ref");
2648 xt::pyarray<double> &u_test_trace_ref = args.array<double>("u_test_trace_ref");
2649 xt::pyarray<double> &u_grad_test_trace_ref = args.array<double>("u_grad_test_trace_ref");
2650 xt::pyarray<double> &normal_ref = args.array<double>("normal_ref");
2651 xt::pyarray<double> &boundaryJac_ref = args.array<double>("boundaryJac_ref");
2652 int nElements_global = args.scalar<int>("nElements_global");
2653 xt::pyarray<double> &ebqe_penalty_ext = args.array<double>("ebqe_penalty_ext");
2654 xt::pyarray<int> &elementMaterialTypes = args.array<int>("elementMaterialTypes");
2655 xt::pyarray<int> &isSeepageFace = args.array<int>("isSeepageFace");
2656 xt::pyarray<int> &a_rowptr = args.array<int>("a_rowptr");
2657 xt::pyarray<int> &a_colind = args.array<int>("a_colind");
2658 double rho = args.scalar<double>("rho");
2659 double beta = args.scalar<double>("beta");
2661 xt::pyarray<double> &q_rho = args.array<double>("q_rho");
2662 xt::pyarray<double> &ebqe_rho = args.array<double>("ebqe_rho");
2664
2665
2666 xt::pyarray<double> &gravity = args.array<double>("gravity");
2667 xt::pyarray<double> &alpha = args.array<double>("alpha");
2668 xt::pyarray<double> &n = args.array<double>("n");
2669 xt::pyarray<double> &thetaR = args.array<double>("thetaR");
2670 xt::pyarray<double> &thetaSR = args.array<double>("thetaSR");
2671 xt::pyarray<double> &KWs = args.array<double>("KWs");
2672 xt::pyarray<double> &krn_end = args.array<double>("krn_end");
2673 xt::pyarray<double> &S_gr = args.array<double>("S_gr");
2674 xt::pyarray<double> &bc_Se_min = args.array<double>("bc_Se_min");
2675 double mu_n = args.scalar<double>("mu_n");
2676 double useMetrics = args.scalar<double>("useMetrics");
2677 double alphaBDF = args.scalar<double>("alphaBDF");
2678 int lag_shockCapturing = args.scalar<int>("lag_shockCapturing");
2679 double shockCapturingDiffusion = args.scalar<double>("shockCapturingDiffusion");
2680 double sc_uref = args.scalar<double>("sc_uref");
2681 double sc_alpha = args.scalar<double>("sc_alpha");
2682 xt::pyarray<int> &u_l2g = args.array<int>("u_l2g");
2683 // Component-1 (z) element-to-DOF map (comp-1's own femSpace.dofMap.l2g). On
2684 // the shared P1 mesh it equals u_l2g element-wise.
2685 xt::pyarray<int> &u_l2g_n = args.array<int>("u_l2g_n");
2686 xt::pyarray<int> &r_l2g = args.array<int>("r_l2g");
2687 xt::pyarray<double> &elementDiameter = args.array<double>("elementDiameter");
2688 int degree_polynomial = args.scalar<int>("degree_polynomial");
2689 xt::pyarray<double> &u_dof = args.array<double>("u_dof");
2690 xt::pyarray<double> &u_dof_old = args.array<double>("u_dof_old");
2691 xt::pyarray<double> &velocity = args.array<double>("velocity");
2692 xt::pyarray<double> &q_m = args.array<double>("q_m");
2693 xt::pyarray<double> &q_theta = args.array<double>("q_theta");
2694 xt::pyarray<double> &q_u = args.array<double>("q_u");
2695 xt::pyarray<double> &q_dV = args.array<double>("q_dV");
2696 xt::pyarray<double> &q_m_betaBDF = args.array<double>("q_m_betaBDF");
2697 xt::pyarray<double> &cfl = args.array<double>("cfl");
2698 xt::pyarray<double> &q_numDiff_u = args.array<double>("q_numDiff_u");
2699 xt::pyarray<double> &q_numDiff_u_last = args.array<double>("q_numDiff_u_last");
2700 int offset_u = args.scalar<int>("offset_u");
2701 int stride_u = args.scalar<int>("stride_u");
2702 // component-1 (S_n) mass equation args.
2703 // (dt is already declared at the top of this function for the EV path.)
2704 xt::pyarray<double> &u_dof_n = args.array<double>("u_dof_n");
2705 xt::pyarray<double> &u_dof_n_old = args.array<double>("u_dof_n_old");
2706 // gas-phase density: EXPONENTIAL EOS mirroring comp-0's slightly-compressible
2707 // water (rho_w = rho*exp(beta*u_w)). rho_n is the reference density at
2708 // p_n = 0 (gauge = atmospheric); p_ref_n is the e-folding pressure scale:
2709 // rho_n(p_n) = rho_n * exp(p_n / p_ref_n), p_n = u_w + p_c,
2710 // drho_n/dp_n = rho_n(p_n) / p_ref_n (state-dependent, NOT a constant).
2711 // beta_n = 1/p_ref_n is the constant gas compressibility. CO2 near
2712 // atmospheric in a lab rig is ideal-gas-like (rho ~ P_abs), so p_ref_n ~
2713 // atmospheric in head ~ 10.3 m gives beta_n ~ 0.1 /m. p_ref_n <= 0 ->
2714 // incompressible (constant rho_n). Exponential (vs the old linear c_n*p_n)
2715 // keeps rho_n = rho_n at gauge p_n = 0 rather than collapsing to 0.
2716 const double rho_n = args.scalar<double>("rho_n");
2717 const double p_ref_n = args.scalar<double>("p_ref_n");
2718 const bool rho_n_compressible = (p_ref_n > 0.0);
2719 const double inv_p_ref_n = rho_n_compressible ? (1.0 / p_ref_n) : 0.0;
2720 const int offset_n = args.scalar<int>("offset_n");
2721 const int stride_n = args.scalar<int>("stride_n");
2722 // Consistent (Galerkin) point-source injection (MOOSE DiracKernel form):
2723 // R^c_i -= Q_port * N_i(x_p) on the element containing the port.
2724 // sum_i N_i = 1 (partition of unity) -> total injected mass is EXACT and
2725 // mesh-independent; no elementMass lumping. Solution-independent => zero
2726 // Jacobian (same as the lumped path). inj_point_mode==0 keeps the legacy
2727 // lumped volumetric-disk source (injection_dof) byte-identical.
2728 const int inj_point_mode = args.scalar<int>("inj_point_mode");
2729 const int inj_n_ports = args.scalar<int>("inj_n_ports");
2730 xt::pyarray<int> &inj_element = args.array<int>("inj_element"); // containing elem id / rank (-1 if absent)
2731 xt::pyarray<double> &inj_weight = args.array<double>("inj_weight"); // N_i(x_p), [port*nDOF_test_element + i]
2732 xt::pyarray<double> &inj_rate = args.array<double>("inj_rate"); // Q_port * ramp(t) [mol/(s*m_depth)]
2733 // Stage 3b: gas-side kinetic dissolution sink. R_diss = k_d * S_n *
2734 // (1 - S_n) * theta_w * rho_w(c) * (c_sat - c) is subtracted from the
2735 // gas-equation residual at each quadrature point. c is read from TADR's
2736 // u[0].dof aliased Python-side and passed in as c_dof. k_d=0 disables
2737 // the sink (legacy behavior).
2738 xt::pyarray<double> &c_dof = args.array<double>("c_dof");
2739 const double k_d = args.scalar<double>("k_d");
2740 const double c_sat = args.scalar<double>("c_sat");
2741 // CO2 injection: per-node source field (built Python-side, schedule-gated).
2742 // Applied like R_diss but with opposite sign -- a source, not a sink.
2743 // All-zero array when no injection is configured.
2744 xt::pyarray<double> &injection_dof = args.array<double>("injection_dof");
2745 xt::pyarray<double> &globalResidual = args.array<double>("globalResidual");
2746 int nExteriorElementBoundaries_global = args.scalar<int>("nExteriorElementBoundaries_global");
2747 xt::pyarray<int> &exteriorElementBoundariesArray = args.array<int>("exteriorElementBoundariesArray");
2748 xt::pyarray<int> &elementBoundaryElementsArray = args.array<int>("elementBoundaryElementsArray");
2749 xt::pyarray<int> &elementBoundaryLocalElementBoundariesArray = args.array<int>("elementBoundaryLocalElementBoundariesArray");
2750 xt::pyarray<double> &ebqe_velocity_ext = args.array<double>("ebqe_velocity_ext");
2751 xt::pyarray<int> &isDOFBoundary_u = args.array<int>("isDOFBoundary_u");
2752 xt::pyarray<double> &ebqe_bc_u_ext = args.array<double>("ebqe_bc_u_ext");
2753 // component-1 (S_n) boundary arrays.
2754 xt::pyarray<int> &isDOFBoundary_n = args.array<int>("isDOFBoundary_n");
2755 xt::pyarray<double> &ebqe_bc_u_n_ext = args.array<double>("ebqe_bc_u_n_ext");
2756 xt::pyarray<int> &isFluxBoundary_u = args.array<int>("isFluxBoundary_u");
2757 xt::pyarray<double> &ebqe_bc_flux_ext = args.array<double>("ebqe_bc_flux_ext");
2758 xt::pyarray<double> &ebqe_phi = args.array<double>("ebqe_phi");
2759 double epsFact = args.scalar<double>("epsFact");
2760 xt::pyarray<double> &ebqe_u = args.array<double>("ebqe_u");
2761 xt::pyarray<double> &ebqe_theta = args.array<double>("ebqe_theta");
2762 xt::pyarray<double> &ebqe_flux = args.array<double>("ebqe_flux");
2763 // PARAMETERS FOR EDGE BASED STABILIZATION
2764 double cE = args.scalar<double>("cE");
2765 double cK = args.scalar<double>("cK");
2766 // PARAMETERS FOR LOG BASED ENTROPY FUNCTION
2767 double uL = args.scalar<double>("uL");
2768 double uR = args.scalar<double>("uR");
2769 // PARAMETERS FOR EDGE VISCOSITY
2770 int numDOFs = args.scalar<int>("numDOFs");
2771 // numDOFs is the compact component-0 free-DOF count used by the stabilized
2772 // DOF loops. Full matrix slots are recovered from the interleaved global
2773 // CSR using offset/stride-aware indexing.
2774 int numDOFs_u = args.scalar<int>("numDOFs_u");
2775 int NNZ = args.scalar<int>("NNZ");
2776 xt::pyarray<int> &csrRowIndeces_DofLoops = args.array<int>("csrRowIndeces_DofLoops");
2777 xt::pyarray<int> &csrColumnOffsets_DofLoops = args.array<int>("csrColumnOffsets_DofLoops");
2778 xt::pyarray<int> &csrRowIndeces_Full = args.array<int>("csrRowIndeces_Full");
2779 xt::pyarray<int> &csrColumnOffsets_Full = args.array<int>("csrColumnOffsets_Full");
2780 xt::pyarray<int> &csrRowIndeces_CellLoops = args.array<int>("csrRowIndeces_CellLoops");
2781 xt::pyarray<int> &csrColumnOffsets_CellLoops = args.array<int>("csrColumnOffsets_CellLoops");
2782 xt::pyarray<int> &csrColumnOffsets_eb_CellLoops = args.array<int>("csrColumnOffsets_eb_CellLoops");
2783 // C matrices
2784 xt::pyarray<double> &Cx = args.array<double>("Cx");
2785 xt::pyarray<double> &Cy = args.array<double>("Cy");
2786 xt::pyarray<double> &Cz = args.array<double>("Cz");
2787 xt::pyarray<double> &CTx = args.array<double>("CTx");
2788 xt::pyarray<double> &CTy = args.array<double>("CTy");
2789 xt::pyarray<double> &CTz = args.array<double>("CTz");
2790 xt::pyarray<double> &ML = args.array<double>("ML");
2791 xt::pyarray<double> &MC = args.array<double>("MC");
2792
2793 xt::pyarray<double> &delta_x_ij = args.array<double>("delta_x_ij");
2794 // PARAMETERS FOR 1st or 2nd ORDER MPP METHOD
2795 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
2796 STABILIZATION STABILIZATION_TYPE{static_cast<STABILIZATION>(args.scalar<int>("STABILIZATION_TYPE"))};
2797
2798 int ENTROPY_TYPE = args.scalar<int>("ENTROPY_TYPE");
2799 PSK_TYPE_member = args.scalar<int>("PSK_TYPE");
2800 immiscible_member = (args.scalar<int>("immiscible") != 0);
2801 T_C_member = args.scalar<double>("T_C"); // temperature [degC] from input
2802 // FOR FCT
2803 xt::pyarray<double> &dLow = args.array<double>("dLow");
2804 xt::pyarray<double> &fluxMatrix = args.array<double>("fluxMatrix");
2805 xt::pyarray<double> &mDotLow = args.array<double>("mDotLow");
2806 xt::pyarray<double> &mLow = args.array<double>("mLow");
2807 xt::pyarray<double> &dt_times_fH_minus_fL = args.array<double>("dt_times_fH_minus_fL");
2808 xt::pyarray<double> &min_m_bc = args.array<double>("min_m_bc");
2809 xt::pyarray<double> &max_m_bc = args.array<double>("max_m_bc");
2810 // AUX QUANTITIES OF INTEREST
2811 xt::pyarray<double> &quantDOFs = args.array<double>("quantDOFs");
2812 xt::pyarray<double> &mn = args.array<double>("mn");
2813 xt::pyarray<double> &fluxCorrection = args.array<double>("fluxCorrection");
2814 xt::pyarray<double> &limited_solution = args.array<double>("limited_solution");
2815 xt::pyarray<int> &freeDOFMaterialTypes = args.array<int>("freeDOFMaterialTypes");
2816 xt::pyarray<int> &freeDOFToNode_u = args.array<int>("freeDOFToNode_u");
2817 // Per-comp-1-DOF volume material (mesh node index == comp-1 DOF index, since
2818 // gas has no Dirichlet). Used by the nodal closure-eval block below to
2819 // evaluate krn / p_c / rho_n with the node's actual sand parameters --
2820 // exact at the node, so dkrn/dS_n and dp_c/dS_n in the Jacobian match the
2821 // lambda used in the residual (needed for quadratic Newton / the mass-leak fix).
2822 xt::pyarray<int> &nodeMaterialTypes_n = args.array<int>("nodeMaterialTypes_n");
2823 // Coarsest incident capillary entry pressure p_d=1/alpha [head] per mesh
2824 // node, for the comp-1 element-side capillary entry-pressure barrier.
2825 xt::pyarray<double> &node_pd_min = args.array<double>("node_pd_min");
2826 // Full gas saturation 1-S_wr of the coarsest incident medium per node (the
2827 // saturation the coarse pool fills to against a seal); anchors the valve.
2828 xt::pyarray<double> &node_Sn_max = args.array<double>("node_Sn_max");
2829 // DIAGNOSTIC (mass-creation hunt): gas_diag[0]=max|T_ij - T_ji| (tau
2830 // symmetry), [1]=max|T_ij| (scale), [2]=sum_ij F_ij (flux imbalance ->
2831 // net mass created/destroyed by the edge flux), [3]=sum_ij|F_ij| (scale).
2832 xt::pyarray<double> &gas_diag = args.array<double>("gas_diag");
2833
2834 xt::pyarray<double> &velocity_couple = args.array<double>("velocity_couple");
2835 xt::pyarray<double> &ebqe_velocity_ext_couple = args.array<double>("ebqe_velocity_ext_couple");
2836 // xt::pyarray<double> &q_x = args.array<double>("q_x");
2837 // xt::pyarray<double> &ebqe_x = args.array<double>("ebqe_x");
2838
2839 xt::pyarray<double> &anb_seepage_flux_n = args.array<double>("anb_seepage_flux_n");
2840 xt::pyarray<double> &q_velocity = args.array<double>("q_velocity");
2841 double &anb_seepage_flux(args.scalar<double>("anb_seepage_flux"));
2842 anb_seepage_flux = 0.0;
2843 xt::pyarray<int> &csrRowIndeces_u_u = args.array<int>("csrRowIndeces_u_u");
2844 xt::pyarray<int> &csrColumnOffsets_u_u = args.array<int>("csrColumnOffsets_u_u");
2845 xt::pyarray<int> &csrColumnOffsets_eb_u_u = args.array<int>("csrColumnOffsets_eb_u_u");
2846 // CSR maps for the (1,1) Jacobian block. Used by the
2847 // dedicated component-1 element loop appended at the end to assemble
2848 // the gas-side mass-matrix Jacobian / dt.
2849 xt::pyarray<int> &csrRowIndeces_n_n = args.array<int>("csrRowIndeces_n_n");
2850 // (1,0) cross-block CSR maps for the gas-eq diffusion
2851 // against grad u_w. Currently allocated by the framework but unused by
2852 // the C++ assembly - 3c.2/3c.3 will write into them.
2853 xt::pyarray<int> &csrRowIndeces_n_w = args.array<int>("csrRowIndeces_n_w");
2854 xt::pyarray<int> &csrColumnOffsets_n_n = args.array<int>("csrColumnOffsets_n_n");
2855 xt::pyarray<int> &csrColumnOffsets_n_w = args.array<int>("csrColumnOffsets_n_w");
2856 // P1: comp-0 (H2O) (0,0) and (0,1) block CSR maps -- the framework's
2857 // authoritative (row,col)->flat-nzval offsets for the water equation's
2858 // dependence on p (w_w) and z (w_n). Used by the Richards-style block
2859 // scatter of the two-sided water flux Jacobian (replaces the Full-CSR
2860 // column search that dropped the (0,1) off-diagonal coupling).
2861 xt::pyarray<int> &csrRowIndeces_w_w = args.array<int>("csrRowIndeces_w_w");
2862 xt::pyarray<int> &csrColumnOffsets_w_w = args.array<int>("csrColumnOffsets_w_w");
2863 xt::pyarray<int> &csrRowIndeces_w_n = args.array<int>("csrRowIndeces_w_n");
2864 xt::pyarray<int> &csrColumnOffsets_w_n = args.array<int>("csrColumnOffsets_w_n");
2865 // Comp-1 boundary CSR maps used by the exterior boundary loop appended
2866 // at the end of this routine.
2867 xt::pyarray<int> &csrColumnOffsets_eb_n_n = args.array<int>("csrColumnOffsets_eb_n_n");
2868 xt::pyarray<int> &csrColumnOffsets_eb_n_w = args.array<int>("csrColumnOffsets_eb_n_w");
2869 // COMPONENT-1 (m_n = phi*rho_n*u_n) EV plumbing. Mirrors the comp-0
2870 // EV scaffolding: a compact DOF graph (csrRowIndeces_n_DofLoops), per-edge
2871 // dLow_n / dEV_n storage, and per-DOF mLow_n / mDotLow_n. Sensor / sensor
2872 // bounds (u_n_L, u_n_R) operate on S_n; the stabilization itself acts on
2873 // m_n through chain rule dm_n/du_n = -phi*rho_n.
2874 int numDOFs_n = args.scalar<int>("numDOFs_n");
2875 int NNZ_n = args.scalar<int>("NNZ_n");
2876 xt::pyarray<int> &csrRowIndeces_n_DofLoops = args.array<int>("csrRowIndeces_n_DofLoops");
2877 xt::pyarray<int> &csrColumnOffsets_n_DofLoops = args.array<int>("csrColumnOffsets_n_DofLoops");
2878 xt::pyarray<double> &dLow_n = args.array<double>("dLow_n");
2879 xt::pyarray<double> &dEV_n = args.array<double>("dEV_n");
2880 xt::pyarray<double> &fluxMatrix_n = args.array<double>("fluxMatrix_n");
2881 xt::pyarray<double> &mLow_n = args.array<double>("mLow_n");
2882 xt::pyarray<double> &mDotLow_n = args.array<double>("mDotLow_n");
2883 double u_n_L = args.scalar<double>("u_n_L");
2884 double u_n_R = args.scalar<double>("u_n_R");
2885 xt::pyarray<double> &mn_n = args.array<double>("mn_n"); // m_n at t^n (numDOFs_u)
2886 xt::pyarray<double> &quantDOFs_n = args.array<double>("quantDOFs_n"); // sensor scratch (numDOFs_u)
2887 // Per-node gas-residual BUDGET (mass-creation hunt). Each gas-equation
2888 // residual contribution is accumulated into its own slot at the node i it
2889 // is scattered to, so Python can sum over OWNED nodes only and MPI-reduce
2890 // (parallel-exact, no overlap double-count -- the owned-node pattern, like
2891 // mLow_n/mn_n). Layout is term-major, size 6*numDOFs_n:
2892 // [0]=accumulation (m_n - mn_n)/dt [1]=interior upwind flux -sum F
2893 // [2]=dissolution sink +R_diss [3]=injection -Q_inj
2894 // [4]=exterior boundary flux [5]=TOTAL scattered residual (~0 @ conv)
2895 // At convergence slot5~0, so slot0 = -(slot1+slot2+slot3+slot4). If the gas
2896 // mass grows yet slots 1+4 (the only non-telescoping, non-source terms) sum
2897 // to ~0, the creation is POST-kernel (FCT/inversion/coupling); if slot1 or
2898 // slot4 is the culprit it shows up here directly -- including a per-rank
2899 // boundary leak (slot4 != 0 on a partition that mis-tags an interior face).
2900 xt::pyarray<double> &gas_budget_node = args.array<double>("gas_budget_node");
2901 // Comp-1 FCT plumbing read here so the gate at the end of this routine
2902 // can call FCTStep_n with all args present.
2903 xt::pyarray<double> &dt_times_fH_minus_fL_n = args.array<double>("dt_times_fH_minus_fL_n");
2904 xt::pyarray<double> &fluxCorrection_n = args.array<double>("fluxCorrection_n");
2905 int FCT_n = args.scalar<int>("FCT_n");
2906 // ===== Per-rock nodal closure (Z_ACROSS_ROCK_INTERFACES.md Sec. 3) =====
2907 // At a node shared by several rocks the flash's S_g is the pore-volume
2908 // average of the per-rock gas saturations: substituting c_r, w_r into the
2909 // design's G(pi) = 0 gives
2910 // sum_r W_ir S_r(pi_i) = W_i S_g(p_i, z_i), W_i = sum_r W_ir,
2911 // one capillary pressure pi_i per node, S_r = the inverse of rock r's
2912 // bc_pc_from_Se (bc_Se_from_pc). dS_r/d(p,z) follow from the
2913 // implicit-function theorem. Storage needs only W_i (it is W_i N z for
2914 // CO2 and W_i N (1-z) for H2O), so the S_r cache is read by the flux loops
2915 // only. One-rock nodes keep the flash's S_g (node_multi = 0), so the
2916 // closure changes nothing away from rock interfaces. Built for the current
2917 // iterate and the old time level. 1D prototype:
2918 // test/m_comp_co2/verification/rock_interface_1d/column_1d.py.
2919 const int per_rock = args.scalar<int>("per_rock_closure");
2920 xt::pyarray<double> &node_rock_W = args.array<double>("node_rock_W"); // [node][rock]
2921 const int nRock = args.scalar<int>("nRockTypes");
2922 std::vector<char> node_multi;
2923 std::vector<double> node_W; // W_i = sum_r W_ir
2924 std::vector<double> rS, rS_dp, rS_dz; // [node * nRock + rock], current
2925 std::vector<double> rS_o, rS_dz_o; // old time level
2926 if (per_rock) {
2927 node_multi.assign(numDOFs_n, 0);
2928 node_W.assign(numDOFs_n, 0.0);
2929 rS.assign(numDOFs_n * nRock, 0.0); rS_dp.assign(numDOFs_n * nRock, 0.0);
2930 rS_dz.assign(numDOFs_n * nRock, 0.0);
2931 rS_o.assign(numDOFs_n * nRock, 0.0); rS_dz_o.assign(numDOFs_n * nRock, 0.0);
2932 for (int i = 0; i < numDOFs_n; i++) {
2933 const double *Wi = &node_rock_W.data()[i * nRock];
2934 int n_r = 0;
2935 for (int r = 0; r < nRock; r++) {
2936 node_W[i] += Wi[r];
2937 if (Wi[r] > 0.0) n_r++;
2938 }
2939 if (n_r < 2) continue;
2940 node_multi[i] = 1;
2941 // Bracket for pi: gas first enters the coarsest rock at its p_d; above
2942 // the largest pc(S_e = 0) every rock is at its S_e = 0 cap.
2943 double pi_lo = 1.0e300, pi_hi = 0.0;
2944 for (int r = 0; r < nRock; r++) {
2945 if (Wi[r] <= 0.0) continue;
2946 double pc0, dpc0, d2pc0;
2947 proteus::m_comp_co2::psk::bc_pc_from_Se(0.0, alpha.data()[r], n.data()[r], bc_Se_min.data()[r], pc0, dpc0, d2pc0);
2948 pi_lo = std::min(pi_lo, 1.0 / alpha.data()[r]);
2949 pi_hi = std::max(pi_hi, pc0);
2950 }
2951 for (int lvl = 0; lvl < 2; lvl++) {
2952 const double p_i = fmax((lvl == 0 ? u_dof.data()[i] : u_dof_old.data()[i]), 1.0e2);
2953 const double z_i = (lvl == 0 ? u_dof_n.data()[i] : u_dof_n_old.data()[i]);
2956 const double target = node_W[i] * f.S_g;
2957 // H(pi) = sum_r W_ir S_r(pi) - W_i S_g and dH/dpi; S_r = (1 - S_wr,r)(1 - S_e,r).
2958 auto H = [&](const double pi, double &dH) {
2959 double s = 0.0;
2960 dH = 0.0;
2961 for (int r = 0; r < nRock; r++) {
2962 if (Wi[r] <= 0.0) continue;
2963 const double om = thetaSR.data()[r] / (thetaR.data()[r] + thetaSR.data()[r]);
2964 double Se, dSe;
2965 proteus::m_comp_co2::psk::bc_Se_from_pc(pi, alpha.data()[r], n.data()[r], bc_Se_min.data()[r], Se, dSe);
2966 s += Wi[r] * om * (1.0 - Se);
2967 dH -= Wi[r] * om * dSe;
2968 }
2969 return s - target;
2970 };
2971 double pi = pi_lo, dH = 0.0;
2972 bool capped = false;
2973 if (target <= 0.0) {
2974 pi = pi_lo; // single-phase node: every S_r = 0
2975 } else if (H(pi_hi, dH) < 0.0) {
2976 capped = true; // branch (d): beyond every rock's S_e = 0
2977 } else {
2978 // Safeguarded Newton from the low end of the bracket; bisection
2979 // whenever the step leaves it. 1e-15 relative resolves S_r to roundoff.
2980 double a = pi_lo, b = pi_hi;
2981 for (int it = 0; it < 200; it++) {
2982 const double h = H(pi, dH);
2983 if (h < 0.0) a = pi; else b = pi;
2984 if (std::fabs(h) <= 1.0e-15 * target || b - a <= 1.0e-15 * b) break;
2985 const double pn = (dH > 0.0) ? pi - h / dH : 0.5 * (a + b);
2986 pi = (pn > a && pn < b) ? pn : 0.5 * (a + b);
2987 }
2988 H(pi, dH);
2989 }
2990 for (int r = 0; r < nRock; r++) {
2991 if (Wi[r] <= 0.0) continue;
2992 const int o = i * nRock + r;
2993 const double om = thetaSR.data()[r] / (thetaR.data()[r] + thetaSR.data()[r]);
2994 double S_r, dS_dp, dS_dz;
2995 if (capped) {
2996 // The kernel clamps S_e at 0, so this excess changes no k_r or
2997 // p_c; spread it uniformly so sum_r W_ir S_r = W_i S_g still holds.
2998 double h_hi = H(pi_hi, dH);
2999 S_r = om - h_hi / node_W[i];
3000 dS_dp = f.dS_g_dp; dS_dz = f.dS_g_dz;
3001 } else {
3002 double Se, dSe;
3003 proteus::m_comp_co2::psk::bc_Se_from_pc(pi, alpha.data()[r], n.data()[r], bc_Se_min.data()[r], Se, dSe);
3004 S_r = (target <= 0.0) ? 0.0 : om * (1.0 - Se);
3005 // dpi/d(p,z) = W_i dS_g/d(p,z) / dH/dpi; with dH = 0 (flat at the
3006 // root, measure zero) fall back to the average's derivative.
3007 const double dSr_dpi = -om * dSe;
3008 if (target > 0.0 && dH > 0.0) {
3009 dS_dp = dSr_dpi * node_W[i] * f.dS_g_dp / dH;
3010 dS_dz = dSr_dpi * node_W[i] * f.dS_g_dz / dH;
3011 } else if (target > 0.0) {
3012 dS_dp = f.dS_g_dp; dS_dz = f.dS_g_dz;
3013 } else {
3014 dS_dp = 0.0; dS_dz = 0.0;
3015 }
3016 }
3017 if (lvl == 0) { rS[o] = S_r; rS_dp[o] = dS_dp; rS_dz[o] = dS_dz; }
3018 else { rS_o[o] = S_r; rS_dz_o[o] = dS_dz; }
3019 }
3020 }
3021 }
3022 Sg_rock_min_member.assign(numDOFs_n, std::nan(""));
3023 Sg_rock_max_member.assign(numDOFs_n, std::nan(""));
3024 for (int i = 0; i < numDOFs_n; i++) {
3025 if (!node_multi[i]) continue;
3026 double s_lo = 1.0e300, s_hi = -1.0e300;
3027 for (int r = 0; r < nRock; r++) {
3028 if (node_rock_W.data()[i * nRock + r] <= 0.0) continue;
3029 s_lo = std::min(s_lo, rS[i * nRock + r]);
3030 s_hi = std::max(s_hi, rS[i * nRock + r]);
3031 }
3032 Sg_rock_min_member[i] = s_lo;
3033 Sg_rock_max_member[i] = s_hi;
3034 }
3035 }
3036 // double Rpos[numDOFs], Rneg[numDOFs];
3037 std::vector<double> Rpos(numDOFs, 0.0), Rneg(numDOFs, 0.0);
3038 std::vector<double> TransportMatrix(NNZ, 0.0),
3039 TransportMatrixConsistent(NNZ, 0.0),
3040 TransportMatrixn(NNZ, 0.0),
3041 TransportMatrixConsistentn(NNZ, 0.0);
3042 //double FluxCorrectionMatrix[NNZ];
3043 // NOTE: This function follows a different (but equivalent) implementation of the smoothness based indicator than NCLS.h
3044 // Allocate space for the transport matrices
3045 // This is used for first order KUZMIN'S METHOD
3046 // double TransportMatrix[NNZ], TransportMatrixConsistent[NNZ];
3047 // double TransportMatrixn[NNZ], TransportMatrixConsistentn[NNZ];
3048 std::valarray<double> u_free_dof(numDOFs);
3049 std::valarray<double> u_free_dof_old(numDOFs);
3050 std::valarray<double> ML2(numDOFs);
3051 // Lumped L2 projection buffers for density
3052 std::vector<double> rho_dof(numDOFs, 0.0);
3053 std::vector<double> ML_rho(numDOFs, 0.0);
3054 std::fill(velocity_couple.data(), velocity_couple.data() + velocity_couple.size(), 0.0);
3055 std::fill(ebqe_velocity_ext_couple.data(), ebqe_velocity_ext_couple.data() + ebqe_velocity_ext_couple.size(), 0.0);
3056 auto full_offset_from_compact = [&](int i_compact, int j_compact) -> int
3057 {
3058 const int full_i = offset_u + stride_u * i_compact;
3059 const int full_j = offset_u + stride_u * j_compact;
3060 for (int offset = csrRowIndeces_Full.data()[full_i]; offset < csrRowIndeces_Full.data()[full_i + 1]; ++offset)
3061 if (csrColumnOffsets_Full.data()[offset] == full_j) return offset;
3062 return -1;
3063 };
3064
3065 for (int eN = 0; eN < nElements_global; eN++)
3066 for (int j = 0; j < nDOF_trial_element; j++) {
3067 int eN_nDOF_trial_element = eN * nDOF_trial_element;
3068 u_free_dof[r_l2g.data()[eN_nDOF_trial_element + j]] = u_dof.data()[u_l2g.data()[eN_nDOF_trial_element + j]];
3069 u_free_dof_old[r_l2g.data()[eN_nDOF_trial_element + j]] = u_dof_old.data()[u_l2g.data()[eN_nDOF_trial_element + j]];
3070 }
3071 for (int i = 0; i < NNZ; i++) {
3072 TransportMatrix[i] = 0.;
3073 TransportMatrixConsistent[i] = 0.;
3074 TransportMatrixn[i] = 0.;
3075 TransportMatrixConsistentn[i] = 0.;
3076 }
3077
3078 // Project quadrature density to nodal DOFs before constructing nodal
3079 // stabilization potentials so Phi uses a true nodal density field.
3080 for (int eN = 0; eN < nElements_global; eN++) {
3081 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
3082 for (int k = 0; k < nQuadraturePoints_element; k++) {
3083 const int eN_k = eN * nQuadraturePoints_element + k;
3084 double jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], x, y, z;
3085 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(),
3086 mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
3087 jac, jacDet, jacInv, x, y, z);
3088 const double dV = fabs(jacDet) * dV_ref.data()[k];
3089 for (int i = 0; i < nDOF_test_element; i++) {
3090 const int eN_i = eN * nDOF_test_element + i;
3091 const int free_gi = r_l2g.data()[eN_i];
3092 const double u_test_dV = u_test_ref.data()[k * nDOF_trial_element + i] * dV;
3093 rho_dof[free_gi] += q_rho.data()[eN_k] * u_test_dV;
3094 ML_rho[free_gi] += u_test_dV;
3095 }
3096 }
3097 }
3098 for (int i = 0; i < numDOFs; ++i) {
3099 if (ML_rho[i] > 0.0) rho_dof[i] /= ML_rho[i];
3100 else rho_dof[i] = rho;
3101 }
3102 // Cache the projected, salinity-coupled density for use in invert() so
3103 // the m -> u inversion is consistent with the forward residual.
3104 rho_dof_member = rho_dof;
3105
3106 // -------- Comp-1: lumped L2 projections for the upwind potential flux --------
3107 // rho_n_phi_dof, rho_w_dof: as before -- invert(COMPONENT=1) and R_diss.
3108 // pc_dof, dpc_dof, krn_dof, dkrn_dof, rho_n_dof: nodal closure values
3109
3110 std::vector<double> rho_n_phi_dof(numDOFs_n, 0.0);
3111 // Old-time phi*N for the accumulation old mass m_c_old = (phi*N_old)*z_old.
3112 std::vector<double> rho_n_phi_dof_old(numDOFs_n, 0.0);
3113 // Lumped nodal phi*dN/dz and phi*dN/dp -- the compositional accumulation
3114 // Jacobian needs dm_c/dz = phi*(dN/dz*z + N) and dm_c/dp = phi*dN/dp*z.
3115 std::vector<double> dphiN_dz_dof(numDOFs_n, 0.0);
3116 std::vector<double> dphiN_dp_dof(numDOFs_n, 0.0);
3117 std::vector<double> rho_w_dof(numDOFs_n, 0.0);
3118 std::vector<double> rho_n_dof(numDOFs_n, 0.0);
3119 std::vector<double> pc_dof(numDOFs_n, 0.0);
3120 std::vector<double> dpc_dof(numDOFs_n, 0.0);
3121 std::vector<double> krn_dof(numDOFs_n, 0.0);
3122 std::vector<double> dkrn_dof(numDOFs_n, 0.0);
3123 std::vector<double> rho_n_dof_old(numDOFs_n, 0.0);
3124 std::vector<double> pc_dof_old(numDOFs_n, 0.0);
3125 std::vector<double> krn_dof_old(numDOFs_n, 0.0);
3126 // Uncapped Brooks-Corey p_c (+ dp_c/dS_n and old-time sibling), used ONLY on
3127 // material-interface edges for entry-pressure capillary breakthrough.
3128 std::vector<double> pc_uncap_dof(numDOFs_n, 0.0);
3129 std::vector<double> dpc_uncap_dof(numDOFs_n, 0.0);
3130 std::vector<double> pc_uncap_dof_old(numDOFs_n, 0.0);
3131 std::vector<double> ML_n(numDOFs_n, 0.0);
3132 for (int eN = 0; eN < nElements_global; eN++) {
3133 const int mat_eN_proj = elementMaterialTypes.data()[eN];
3134 const double phi_eN = thetaR.data()[mat_eN_proj] + thetaSR.data()[mat_eN_proj];
3135 const double alpha_eN_p = alpha.data()[mat_eN_proj];
3136 const double n_vg_eN_p = n.data()[mat_eN_proj];
3137 const double krn_end_p = krn_end.data()[mat_eN_proj];
3138 const double S_wr_p = thetaR.data()[mat_eN_proj] / phi_eN;
3139 const double one_m_Sr_p = 1.0 - S_wr_p;
3140 const double Se_trap_L3043 = 1.0 - S_gr.data()[mat_eN_proj] / one_m_Sr_p; // gas-only residual trapping
3141 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
3142 for (int k = 0; k < nQuadraturePoints_element; k++) {
3143 double jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], x_p, y_p, z_p;
3144 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(),
3145 mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
3146 jac, jacDet, jacInv, x_p, y_p, z_p);
3147 const double dV = std::fabs(jacDet) * dV_ref.data()[k];
3148 // Current iterate values at QP.
3149 double u_w_p = 0.0, u_n_p = 0.0;
3150 ck.valFromDOF(u_dof.data(),
3151 &u_l2g.data()[eN_nDOF_trial_element],
3152 &u_trial_ref.data()[k * nDOF_trial_element], u_w_p);
3153 ck.valFromDOF(u_dof_n.data(),
3154 &u_l2g_n.data()[eN_nDOF_trial_element],
3155 &u_trial_ref.data()[k * nDOF_trial_element], u_n_p);
3156 // Closure at current iterate -- Se, p_c, dp_c/dS_n, k_rn, dk_rn/dS_n.
3157 const double Se_p_raw = (1.0 - u_n_p - S_wr_p) / one_m_Sr_p;
3158 double Se_p, dSe_du_n_p;
3159 if (Se_p_raw <= 0.0) { Se_p = 0.0; dSe_du_n_p = 0.0; }
3160 else if (Se_p_raw >= 1.0) { Se_p = 1.0; dSe_du_n_p = 0.0; }
3161 else { Se_p = Se_p_raw; dSe_du_n_p = -1.0 / one_m_Sr_p; }
3162 double pc_p = 0.0, dpc_dSe_p = 0.0, d2pc_p_unused = 0.0;
3163 if (PSK_TYPE_member == 1)
3164 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_p, alpha_eN_p, n_vg_eN_p, bc_Se_min.data()[mat_eN_proj], pc_p, dpc_dSe_p, d2pc_p_unused);
3165 else
3166 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_p, alpha_eN_p, n_vg_eN_p, pc_p, dpc_dSe_p, d2pc_p_unused);
3167 const double dpc_dSn_p = dpc_dSe_p * dSe_du_n_p;
3168 double krn_p = 0.0, dkrn_dSe_p = 0.0;
3169 if (PSK_TYPE_member == 1)
3170 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_p, alpha_eN_p, n_vg_eN_p, krn_p, dkrn_dSe_p, Se_trap_L3043);
3171 else
3172 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_p, alpha_eN_p, n_vg_eN_p, krn_p, dkrn_dSe_p, Se_trap_L3043);
3173 krn_p = krn_p * krn_end_p / mu_n;
3174 const double dkrn_dSn_p = dkrn_dSe_p * krn_end_p * dSe_du_n_p / mu_n;
3175 const double rho_n_p = rho_n_compressible ? (rho_n * exp(fmin((u_w_p + pc_p) * inv_p_ref_n, 50.0))) : rho_n;
3176 const double phi_rho_n_qp = phi_eN * rho_n_p;
3177 // Old-time-level values for the (1-Theta) part of the edge flux.
3178 double u_w_p_old = 0.0, u_n_p_old = 0.0;
3179 ck.valFromDOF(u_dof_old.data(),
3180 &u_l2g.data()[eN_nDOF_trial_element],
3181 &u_trial_ref.data()[k * nDOF_trial_element], u_w_p_old);
3182 ck.valFromDOF(u_dof_n_old.data(),
3183 &u_l2g_n.data()[eN_nDOF_trial_element],
3184 &u_trial_ref.data()[k * nDOF_trial_element], u_n_p_old);
3185 const double Se_p_old_raw = (1.0 - u_n_p_old - S_wr_p) / one_m_Sr_p;
3186 double Se_p_old;
3187 if (Se_p_old_raw <= 0.0) Se_p_old = 0.0;
3188 else if (Se_p_old_raw >= 1.0) Se_p_old = 1.0;
3189 else Se_p_old = Se_p_old_raw;
3190 double pc_p_old = 0.0, dpc_p_old_unused = 0.0, d2pc_p_old_unused = 0.0;
3191 if (PSK_TYPE_member == 1)
3192 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_p_old, alpha_eN_p, n_vg_eN_p, bc_Se_min.data()[mat_eN_proj], pc_p_old, dpc_p_old_unused, d2pc_p_old_unused);
3193 else
3194 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_p_old, alpha_eN_p, n_vg_eN_p, pc_p_old, dpc_p_old_unused, d2pc_p_old_unused);
3195 double krn_p_old = 0.0, dkrn_p_old_unused = 0.0;
3196 if (PSK_TYPE_member == 1)
3197 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_p_old, alpha_eN_p, n_vg_eN_p, krn_p_old, dkrn_p_old_unused, Se_trap_L3043);
3198 else
3199 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_p_old, alpha_eN_p, n_vg_eN_p, krn_p_old, dkrn_p_old_unused, Se_trap_L3043);
3200 krn_p_old = krn_p_old * krn_end_p / mu_n;
3201 const double rho_n_p_old = rho_n_compressible ? (rho_n * exp(fmin((u_w_p_old + pc_p_old) * inv_p_ref_n, 50.0))) : rho_n;
3202 // TADR brine density at this QP.
3203 const int eN_k_proj = eN * nQuadraturePoints_element + k;
3204 const double rho_w_qp_proj = q_rho.data()[eN_k_proj];
3205 const double p_cl_pr = fmax(u_w_p, 1.0e2);
3206 const double p_cl_pr_old = fmax(u_w_p_old, 1.0e2);
3211 const double Sa_pr = 1.0 - fs_pr.S_g;
3212 const double N_pr = fs_pr.rho_g*fs_pr.S_g + fs_pr.rho_a*Sa_pr;
3213 const double dN_dp_pr = fs_pr.drho_g_dp*fs_pr.S_g + fs_pr.rho_g*fs_pr.dS_g_dp
3214 + fs_pr.drho_a_dp*Sa_pr - fs_pr.rho_a*fs_pr.dS_g_dp;
3215 const double dN_dz_pr = fs_pr.drho_g_dz*fs_pr.S_g + fs_pr.rho_g*fs_pr.dS_g_dz
3216 + fs_pr.drho_a_dz*Sa_pr - fs_pr.rho_a*fs_pr.dS_g_dz;
3217 const double N_pr_old = fs_pr_old.rho_g*fs_pr_old.S_g
3218 + fs_pr_old.rho_a*(1.0 - fs_pr_old.S_g);
3219 const double phiN_qp = phi_eN * N_pr;
3220 const double phiN_old_qp = phi_eN * N_pr_old;
3221 const double dphiN_dz_qp = phi_eN * dN_dz_pr;
3222 const double dphiN_dp_qp = phi_eN * dN_dp_pr;
3223 for (int i = 0; i < nDOF_test_element; i++) {
3224 const int eN_i = eN * nDOF_test_element + i;
3225 const int gi = u_l2g_n.data()[eN_i]; // comp-1 DOF (lumped phi*N projection)
3226 const double u_test_dV = u_test_ref.data()[k * nDOF_trial_element + i] * dV;
3227 // P1: phi*N (and derivatives) for the compositional CO2 accumulation.
3228 rho_n_phi_dof[gi] += phiN_qp * u_test_dV;
3229 rho_n_phi_dof_old[gi] += phiN_old_qp * u_test_dV;
3230 dphiN_dz_dof[gi] += dphiN_dz_qp * u_test_dV;
3231 dphiN_dp_dof[gi] += dphiN_dp_qp * u_test_dV;
3232 // Phase-based closures below still feed the (P2) upwind flux pass.
3233 rho_w_dof[gi] += rho_w_qp_proj * u_test_dV;
3234 rho_n_dof[gi] += rho_n_p * u_test_dV;
3235 pc_dof[gi] += pc_p * u_test_dV;
3236 dpc_dof[gi] += dpc_dSn_p * u_test_dV;
3237 krn_dof[gi] += krn_p * u_test_dV;
3238 dkrn_dof[gi] += dkrn_dSn_p * u_test_dV;
3239 rho_n_dof_old[gi] += rho_n_p_old * u_test_dV;
3240 pc_dof_old[gi] += pc_p_old * u_test_dV;
3241 krn_dof_old[gi] += krn_p_old * u_test_dV;
3242 ML_n[gi] += u_test_dV;
3243 }
3244 }
3245 }
3246 // Normalize over ALL comp-1 nodes (numDOFs_n), not numDOFs_u -- the arrays
3247 // and the projection above span every mesh node, including the top-boundary
3248 // p_w-Dirichlet nodes that are absent from the comp-0 free-DOF count.
3249 for (int i = 0; i < numDOFs_n; ++i) {
3250 if (ML_n[i] > 0.0) {
3251 rho_n_phi_dof[i] /= ML_n[i];
3252 rho_n_phi_dof_old[i] /= ML_n[i];
3253 dphiN_dz_dof[i] /= ML_n[i];
3254 dphiN_dp_dof[i] /= ML_n[i];
3255 rho_w_dof[i] /= ML_n[i];
3256 rho_n_dof[i] /= ML_n[i];
3257 pc_dof[i] /= ML_n[i];
3258 dpc_dof[i] /= ML_n[i];
3259 krn_dof[i] /= ML_n[i];
3260 dkrn_dof[i] /= ML_n[i];
3261 rho_n_dof_old[i] /= ML_n[i];
3262 pc_dof_old[i] /= ML_n[i];
3263 krn_dof_old[i] /= ML_n[i];
3264 } else {
3265 rho_n_phi_dof[i] = thetaR.data()[0] + thetaSR.data()[0]; // fallback
3266 rho_n_phi_dof_old[i] = thetaR.data()[0] + thetaSR.data()[0]; // fallback
3267 rho_w_dof[i] = rho; // fallback
3268 rho_n_dof[i] = rho_n; // fallback
3269 rho_n_dof_old[i] = rho_n;
3270 // pc, dpc, krn, dkrn default to 0 -- only nodes with no element
3271 // contributions ever hit this branch.
3272 }
3273 rho_n_phi_dof[i] = std::max(rho_n_phi_dof[i], 1.0e-16);
3274 }
3275 rho_n_phi_dof_member = rho_n_phi_dof;
3276
3277 // compute entropy and init global_entropy_residual and boundary_integral
3278 double psi[numDOFs], eta[numDOFs], global_entropy_residual[numDOFs], boundary_integral[numDOFs];
3279 for (int i = 0; i < numDOFs; i++) {
3280 // NODAL ENTROPY //
3281 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) //EV stab
3282 {
3283 double solni = 1.0 * u_free_dof_old[i];
3284 eta[i] = ENTROPY_TYPE == 1 ? ENTROPY(solni, uL, uR) : ENTROPY_LOG(solni, uL, uR);
3285 global_entropy_residual[i] = 0.;
3286 }
3287 boundary_integral[i] = 0.;
3288 ML2[i] = 0.0;
3289 }
3290
3292 // ** LOOP IN CELLS FOR CELL BASED TERMS ** //
3294 // HERE WE COMPUTE:
3295 // * Time derivative term. u_t
3296 // * cell based CFL (for reference)
3297 // * Entropy residual
3298 // * Transport matrices
3299
3300 for (int eN = 0; eN < nElements_global; eN++) {
3301 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
3302 const int eN_nDOF_mesh_trial_element = eN * nDOF_mesh_trial_element;
3303 //declare local storage for local contributions and initialize
3304 double elementResidual_u[nDOF_test_element], element_entropy_residual[nDOF_test_element], Phi[nDOF_trial_element], Phi_n[nDOF_trial_element];
3305 double elementTransport[nDOF_test_element][nDOF_trial_element], elementTransportConsistent[nDOF_test_element][nDOF_trial_element];
3306 double elementTransportn[nDOF_test_element][nDOF_trial_element], elementTransportConsistentn[nDOF_test_element][nDOF_trial_element];
3307 for (int j = 0; j < nDOF_trial_element; j++) {
3308 const int u_gj = u_l2g.data()[eN_nDOF_trial_element + j];
3309 const int free_gj = r_l2g.data()[eN_nDOF_trial_element + j];
3310 const int x_gj = mesh_l2g.data()[eN_nDOF_mesh_trial_element + j];
3311 const double rho_node_j = rho_dof[free_gj];
3312 Phi[j] = u_dof.data()[u_gj];
3313 Phi_n[j] = u_dof_old.data()[u_gj];
3314 for (int I = 0; I < nSpace; I++) {
3315 // Pressure form: grad(p) - rho_w g (no /rho0 factor).
3316 Phi[j] -= rho_node_j * mesh_dof.data()[x_gj * 3 + I] * gravity[I];
3317 Phi_n[j] -= rho_node_j * mesh_dof.data()[x_gj * 3 + I] * gravity[I];
3318 }
3319 }
3320 for (int i = 0; i < nDOF_test_element; i++) {
3321 elementResidual_u[i] = 0.0;
3322 element_entropy_residual[i] = 0.0;
3323 for (int j = 0; j < nDOF_trial_element; j++) {
3324 elementTransport[i][j] = 0.0;
3325 elementTransportConsistent[i][j] = 0.0;
3326 elementTransportn[i][j] = 0.0;
3327 elementTransportConsistentn[i][j] = 0.0;
3328 }
3329 }
3330 //loop over quadrature points and compute integrands
3331 for (int k = 0; k < nQuadraturePoints_element; k++) {
3332 //compute indeces and declare local storage
3333 int eN_k = eN * nQuadraturePoints_element + k, eN_k_nSpace = eN_k * nSpace;
3334 double
3335 // for entropy residual
3336 aux_entropy_residual = 0.,
3337 DENTROPY_un, DENTROPY_uni,
3338 //for mass matrix contributions
3339 u = 0.0, un = 0.0, grad_phi[nSpace], grad_phi_n[nSpace], grad_u_velocity[nSpace], velocity_loc[nSpace], u_test_dV[nDOF_trial_element], u_grad_trial[nDOF_trial_element * nSpace], u_grad_test_dV[nDOF_test_element * nSpace],
3340 //for general use
3341 jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], dV, x, y, z, xt, yt, zt, m, dm, f[nSpace], df[nSpace], a[nnz], da[nnz], as[nnz], mn, dmn, fn[nSpace], dfn[nSpace], an[nnz], dan[nnz], asn[nnz];
3342 //get the physical integration weight
3343 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), mesh_grad_trial_ref.data(), jac, jacDet, jacInv, x, y, z);
3344 ck.calculateMappingVelocity_element(eN, k, mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), xt, yt, zt);
3345 dV = fabs(jacDet) * dV_ref.data()[k];
3346 //get the solution (of Newton's solver). To compute time derivative term
3347 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], &u_trial_ref.data()[k * nDOF_trial_element], u);
3348 //get the solution at quad point at tn and tnm1 for entropy viscosity
3349 ck.valFromDOF(u_dof_old.data(), &u_l2g.data()[eN_nDOF_trial_element], &u_trial_ref.data()[k * nDOF_trial_element], un);
3350 //get the solution gradients at tn for entropy viscosity
3351 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace], jacInv, u_grad_trial);
3352 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial, grad_u_velocity);
3353
3354 //populate q_x
3355 // const int eN_k_3d = eN_k * 3;
3356 // q_x.data()[eN_k_3d + 0] = x;
3357 // q_x.data()[eN_k_3d + 1] = y;
3358 // q_x.data()[eN_k_3d + 2] = z;
3359 //precalculate test function products with integration weights for mass matrix terms
3360 for (int I = 0; I < nSpace; I++) {
3361 grad_phi[I] = 0.0;
3362 grad_phi_n[I] = 0.0;
3363 }
3364 for (int j = 0; j < nDOF_trial_element; j++) {
3365 u_test_dV[j] = u_test_ref.data()[k * nDOF_trial_element + j] * dV;
3366 for (int I = 0; I < nSpace; I++) {
3367 grad_phi_n[I] += Phi_n[j] * u_grad_trial[j * nSpace + I];
3368 grad_phi[I] += Phi[j] * u_grad_trial[j * nSpace + I];
3369 u_grad_test_dV[j * nSpace + I] = u_grad_trial[j * nSpace + I] * dV; //cek warning won't work for Petrov-Galerkin
3370 }
3371 }
3372 //
3373 //calculate pde coefficients at quadrature points
3374 //
3375 double Kr, dKr, Krn, dKrn, thetaW, thetaWn;
3376 const double rho_local = q_rho.data()[eN_k];
3377 const double rho_velocity = std::fabs(rho_local) > 1.0e-12 ? rho_local : rho;
3378
3379 // Cross-derivative buffers are filled by _from_Se but ignored downstream;
3380 // the EV residual only uses (mn, fn, an) and (m, f, a).
3381 double dm_du_n_qp_n = 0.0, dkr_du_n_qp_n = 0.0;
3382 double dm_du_n_qp = 0.0, dkr_du_n_qp = 0.0;
3383 double df_du_n_qp_n[nSpace], df_du_n_qp[nSpace];
3384 double da_du_n_qp_n[nnz], da_du_n_qp[nnz];
3385 for (int I = 0; I < nSpace; I++) { df_du_n_qp_n[I] = 0.0; df_du_n_qp[I] = 0.0; }
3386 for (int ii = 0; ii < nnz; ii++) { da_du_n_qp_n[ii] = 0.0; da_du_n_qp[ii] = 0.0; }
3387 double u_n_qp = 0.0, u_n_qp_old = 0.0;
3388 ck.valFromDOF(u_dof_n.data(),
3389 &u_l2g.data()[eN_nDOF_trial_element],
3390 &u_trial_ref.data()[k * nDOF_trial_element], u_n_qp);
3391 ck.valFromDOF(u_dof_n_old.data(),
3392 &u_l2g.data()[eN_nDOF_trial_element],
3393 &u_trial_ref.data()[k * nDOF_trial_element], u_n_qp_old);
3394 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_local, beta, gravity.data(),
3395 alpha.data()[elementMaterialTypes[eN]], n.data()[elementMaterialTypes[eN]],
3396 thetaR.data()[elementMaterialTypes[eN]], thetaSR.data()[elementMaterialTypes[eN]],
3397 &KWs.data()[elementMaterialTypes[eN] * nnz], un, u_n_qp_old,
3398 mn, dmn, dm_du_n_qp_n, fn, dfn, df_du_n_qp_n, an, dan, da_du_n_qp_n,
3399 asn, Krn, dKrn, dkr_du_n_qp_n, thetaWn);
3400 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_local, beta, gravity.data(),
3401 alpha.data()[elementMaterialTypes[eN]], n.data()[elementMaterialTypes[eN]],
3402 thetaR.data()[elementMaterialTypes[eN]], thetaSR.data()[elementMaterialTypes[eN]],
3403 &KWs.data()[elementMaterialTypes[eN] * nnz], u, u_n_qp,
3404 m, dm, dm_du_n_qp, f, df, df_du_n_qp, a, da, da_du_n_qp,
3405 as, Kr, dKr, dkr_du_n_qp, thetaW);
3406 q_theta.data()[eN_k] = thetaW;
3407
3408 // Darcy velocity for coupling should use the direct FE gradient of the
3409 // pressure head. The Phi-based gradients are only for stabilization.
3410 for (int I = 0; I < nSpace; ++I) {
3411 q_velocity.data()[eN_k_nSpace + I] = grad_u_velocity[I];
3412 }
3413
3414 double pressure_gradient[nSpace];
3415 for (int J = 0; J < nSpace; ++J)
3416 pressure_gradient[J] = grad_u_velocity[J] - rho_velocity * gravity.data()[J];
3417
3418 for (int I = 0; I < nSpace; ++I) {
3419 double acc = 0.0;
3420 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I+1]; ++ii) {
3421 const int J = a_colind.data()[ii];
3422 acc += (a[ii] / rho_velocity) * pressure_gradient[J];
3423 }
3424 velocity.data()[eN_k_nSpace + I] = -acc;
3425 velocity_couple.data()[eN_k_nSpace + I] = -acc;
3426 }
3427 // static int debug_ev_prints = 0;
3428 // if (debug_ev_prints < 6 && eN < 2 && k < 2)
3429 // {
3430 // std::cout << "[Richards EV fixed] eN=" << eN
3431 // << " k=" << k
3432 // << " u=" << u
3433 // << " un=" << un
3434 // << " grad_phi=(" << grad_phi[0];
3435 // for (int I = 1; I < nSpace; ++I)
3436 // std::cout << "," << grad_phi[I];
3437 // std::cout << ") grad_u_velocity=(" << grad_u_velocity[0];
3438 // for (int I = 1; I < nSpace; ++I)
3439 // std::cout << "," << grad_u_velocity[I];
3440 // std::cout << ") velocity_couple=(" << velocity_couple.data()[eN_k_nSpace + 0];
3441 // for (int I = 1; I < nSpace; ++I)
3442 // std::cout << "," << velocity_couple.data()[eN_k_nSpace + I];
3443 // std::cout << ")" << std::endl;
3444 // for (int j = 0; j < nDOF_trial_element; ++j)
3445 // {
3446 // const int u_gj = u_l2g.data()[eN_nDOF_trial_element + j];
3447 // const int x_gj = mesh_l2g.data()[eN_nDOF_mesh_trial_element + j];
3448 // const int free_gj = r_l2g.data()[eN_nDOF_trial_element + j];
3449 // std::cout << " [EV fixed dof] j=" << j
3450 // << " mapped_u=" << u_dof.data()[u_gj]
3451 // << " mapped_u_old=" << u_dof_old.data()[u_gj]
3452 // << " free_material=" << freeDOFMaterialTypes.data()[free_gj]
3453 // << " mapped_x=(" << mesh_dof.data()[x_gj * 3 + 0]
3454 // << "," << mesh_dof.data()[x_gj * 3 + 1]
3455 // << "," << mesh_dof.data()[x_gj * 3 + 2]
3456 // << ") Phi=" << Phi[j]
3457 // << " Phi_n=" << Phi_n[j]
3458 // << std::endl;
3459 // }
3460 // debug_ev_prints++;
3461 // }
3462 // if (nSpace != 2) {std::cout << "WARNING nSpace=" << nSpace << std::endl;}
3463 //
3464 //moving mesh
3465 //
3466 double mesh_velocity[3];
3467 mesh_velocity[0] = xt;
3468 mesh_velocity[1] = yt;
3469 mesh_velocity[2] = zt;
3470 //relative velocity at tn
3471 for (int I = 0; I < nSpace; I++) {
3472 f[I] -= MOVING_DOMAIN * m * mesh_velocity[I];
3473 velocity_loc[I] = df[I] * (2.0 * dm * dm / (dm * dm + fmax(1.0e-16, dm * dm)));
3474 }
3476 // CALCULATE CELL BASED CFL //
3478 calculateCFL(elementDiameter.data()[eN] / degree_polynomial, velocity_loc, cfl.data()[eN_k]);
3480 // CALCULATE ENTROPY RESIDUAL AT QUAD POINT //
3482 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) // EV stab
3483 {
3484 for (int I = 0; I < nSpace; I++) aux_entropy_residual += velocity_loc[I] * grad_phi_n[I];
3485 DENTROPY_un = ENTROPY_TYPE == 1 ? DENTROPY(un, uL, uR) : DENTROPY_LOG(un, uL, uR);
3486 }
3488 // ith-LOOP //
3490 for (int i = 0; i < nDOF_test_element; i++) {
3491 // VECTOR OF ENTROPY RESIDUAL //
3492 int eN_i = eN * nDOF_test_element + i;
3493 ML2[r_l2g.data()[eN_i]] += u_test_dV[i];
3494 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) // EV stab
3495 {
3496 double uni = u_dof_old.data()[u_l2g.data()[eN_i]];
3497 DENTROPY_uni = ENTROPY_TYPE == 1 ? DENTROPY(uni, uL, uR) : DENTROPY_LOG(uni, uL, uR);
3498 element_entropy_residual[i] += (DENTROPY_un - DENTROPY_uni) * aux_entropy_residual * u_test_dV[i];
3499 }
3500
3501 elementResidual_u[i] += m * u_test_dV[i];
3503 // j-th LOOP // To construct transport matrices
3505
3506 for (int j = 0; j < nDOF_trial_element; j++) {
3507 int j_nSpace = j * nSpace;
3508 int i_nSpace = i * nSpace;
3509 elementTransport[i][j] += ck.SimpleDiffusionJacobian_weak(a_rowptr.data(), a_colind.data(), as, &u_grad_trial[j_nSpace], &u_grad_test_dV[i_nSpace]);
3510 elementTransportConsistent[i][j] += ck.SimpleDiffusionJacobian_weak(a_rowptr.data(), a_colind.data(), a, &u_grad_trial[j_nSpace], &u_grad_test_dV[i_nSpace]);
3511 elementTransportn[i][j] += ck.SimpleDiffusionJacobian_weak(a_rowptr.data(), a_colind.data(), asn, &u_grad_trial[j_nSpace], &u_grad_test_dV[i_nSpace]);
3512 elementTransportConsistentn[i][j] += ck.SimpleDiffusionJacobian_weak(a_rowptr.data(), a_colind.data(), an, &u_grad_trial[j_nSpace], &u_grad_test_dV[i_nSpace]);
3513 }
3514 } //i
3515 //save solution for other models
3516 q_u.data()[eN_k] = u;
3517 q_m.data()[eN_k] = m;
3518 }
3520 // DISTRIBUTE // load cell based element into global residual
3522 for (int i = 0; i < nDOF_test_element; i++) {
3523 int eN_i = eN * nDOF_test_element + i;
3524 int gi = r_l2g.data()[eN_i];
3525 // distribute entropy_residual
3526 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) // EV Stab
3527 global_entropy_residual[gi] += element_entropy_residual[i];
3528 // distribute transport matrices
3529 for (int j = 0; j < nDOF_trial_element; j++) {
3530 int eN_i_j = eN_i * nDOF_trial_element + j;
3531 TransportMatrix[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementTransport[i][j];
3532 TransportMatrixConsistent[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementTransportConsistent[i][j];
3533 TransportMatrixn[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementTransportn[i][j];
3534 TransportMatrixConsistentn[csrRowIndeces_CellLoops.data()[eN_i] + csrColumnOffsets_CellLoops.data()[eN_i_j]] += elementTransportConsistentn[i][j];
3535 } //j
3536 } //i
3537
3538 } //elementsxw
3539
3540 // double s = 0.0, sabs = 0.0;
3541 // double vmin = 1e300, vmax = -1e300;
3542 // size_t n_nonzero = 0;
3543
3544 // for (size_t i = 0; i < velocity.size(); i++) {
3545 // double v = velocity.data()[i];
3546 // s += v;
3547 // sabs += std::abs(v);
3548 // vmin = std::min(vmin, v);
3549 // vmax = std::max(vmax, v);
3550 // if (std::abs(v) > 1e-14) n_nonzero++;
3551 // }
3552
3553 // std::cout << "[after compute] size=" << velocity.size()
3554 // << " nnz=" << n_nonzero
3555 // << " min=" << vmin << " max=" << vmax
3556 // << " sumabs=" << sabs << std::endl;
3557
3558 //loop over exterior element boundaries to calculate surface integrals and load into element and global residuals
3559 //
3560 //ebNE is the Exterior element boundary INdex
3561 //ebN is the element boundary INdex
3562 //eN is the element index
3563 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++) {
3564 int ebN = exteriorElementBoundariesArray.data()[ebNE], eN = elementBoundaryElementsArray.data()[ebN * 2 + 0], ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN * 2 + 0], eN_nDOF_trial_element = eN * nDOF_trial_element;
3565 double elementResidual_u[nDOF_test_element];
3566 for (int i = 0; i < nDOF_test_element; i++) { elementResidual_u[i] = 0.0; }
3567 for (int kb = 0; kb < nQuadraturePoints_elementBoundary; kb++) {
3568 int ebNE_kb = ebNE * nQuadraturePoints_elementBoundary + kb, ebNE_kb_nSpace = ebNE_kb * nSpace, ebN_local_kb = ebN_local * nQuadraturePoints_elementBoundary + kb, ebN_local_kb_nSpace = ebN_local_kb * nSpace;
3569 double u_ext = 0.0, un_ext, grad_u_ext[nSpace], m_ext = 0.0, dm_ext = 0.0, f_ext[nSpace], df_ext[nSpace], a_ext[nnz], da_ext[nnz], as_ext[nnz],
3570 mn_ext = 0.0, dmn_ext = 0.0, fn_ext[nSpace], dfn_ext[nSpace], an_ext[nnz], dan_ext[nnz], asn_ext[nnz], flux_ext = 0.0, bflux_ext = 0.0,
3571 //anb_seepage_flux=0.0, // for flux calculation
3572 bc_u_ext = 0.0, bc_grad_u_ext[nSpace], bc_m_ext = 0.0, bc_dm_ext = 0.0, bc_f_ext[nSpace], bc_df_ext[nSpace], bc_a_ext[nnz], bc_da_ext[nnz], bc_as_ext[nnz], jac_ext[nSpace * nSpace], jacDet_ext, jacInv_ext[nSpace * nSpace], boundaryJac[nSpace * (nSpace - 1)], metricTensor[(nSpace - 1) * (nSpace - 1)], metricTensorDetSqrt, dS, u_test_dS[nDOF_test_element], u_grad_trial_trace[nDOF_trial_element * nSpace], normal[3], x_ext, y_ext, z_ext, xt_ext, yt_ext, zt_ext, integralScaling, G[nSpace * nSpace], G_dd_G, tr_G, fluxJacobian_u_u[nDOF_trial_element], bfluxJacobian_u_u[nDOF_trial_element], fluxJacobian_un_un[nDOF_trial_element];
3573 //
3574 //calculate the solution and gradients at quadrature points
3575 //
3576 //compute information about mapping from reference element to physical element
3577 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,
3578 normal_ref.data(), normal, x_ext, y_ext, z_ext);
3579 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);
3580 dS = ((1.0 - MOVING_DOMAIN) * metricTensorDetSqrt + MOVING_DOMAIN * integralScaling) * dS_ref.data()[kb];
3581 //get the metric tensor
3582 //cek todo use symmetry
3583 ck.calculateG(jacInv_ext, G, G_dd_G, tr_G);
3584 //compute shape and solution information
3585 //shape
3586 ck.gradTrialFromRef(&u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace * nDOF_trial_element], jacInv_ext, u_grad_trial_trace);
3587 //solution and gradient
3588 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);
3589 ck.valFromDOF(u_dof_old.data(), &u_l2g.data()[eN_nDOF_trial_element], &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], un_ext);
3590 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial_trace, grad_u_ext);
3591
3592 //populate ebqe_x
3593 // const int ebNE_kb_3d = ebNE_kb * 3;
3594 // ebqe_x.data()[ebNE_kb_3d + 0] = x_ext;
3595 // ebqe_x.data()[ebNE_kb_3d + 1] = y_ext;
3596 // ebqe_x.data()[ebNE_kb_3d + 2] = z_ext;
3597
3598
3599 //precalculate test function products with integration weights
3600 for (int j = 0; j < nDOF_trial_element; j++) { u_test_dS[j] = u_test_trace_ref.data()[ebN_local_kb * nDOF_test_element + j] * dS; }
3601 //
3602 //load the boundary values
3603 //
3604 bc_u_ext = isDOFBoundary_u.data()[ebNE_kb] * ebqe_bc_u_ext.data()[ebNE_kb] + (1 - isDOFBoundary_u.data()[ebNE_kb]) * u_ext;
3605 //
3606 //calculate the pde coefficients using the solution and the boundary values for the solution
3607 //
3608 double bc_Kr, bc_dKr,bc_Kr_ext, bc_dKr_ext, bc_Krn, bc_dKrn, thetaW_ext, thetaWn_ext, thetaW_bc_ext;
3609 const double rho_ext = ebqe_rho.data()[ebNE_kb];
3610 const double rho_velocity_ext = std::fabs(rho_ext) > 1.0e-12 ? rho_ext : rho;
3611
3612 // EV exterior boundary closure.
3613 double dm_du_n_ext = 0.0, dkr_du_n_ext = 0.0;
3614 double dmn_du_n_ext = 0.0, dkrn_du_n_ext = 0.0;
3615 double bc_dm_du_n = 0.0, bc_dkr_du_n = 0.0;
3616 double df_du_n_ext[nSpace], dfn_du_n_ext[nSpace], bc_df_du_n[nSpace];
3617 double da_du_n_ext[nnz], dan_du_n_ext[nnz], bc_da_du_n[nnz];
3618 for (int I = 0; I < nSpace; I++) {
3619 df_du_n_ext[I] = 0.0; dfn_du_n_ext[I] = 0.0; bc_df_du_n[I] = 0.0;
3620 }
3621 for (int ii = 0; ii < nnz; ii++) {
3622 da_du_n_ext[ii] = 0.0; dan_du_n_ext[ii] = 0.0; bc_da_du_n[ii] = 0.0;
3623 }
3624 double u_n_ext_qp = 0.0, u_n_ext_qp_old = 0.0;
3625 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
3626 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], u_n_ext_qp);
3627 ck.valFromDOF(u_dof_n_old.data(), &u_l2g.data()[eN_nDOF_trial_element],
3628 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element], u_n_ext_qp_old);
3629 const double bc_u_n_ext_qp = isDOFBoundary_n.data()[ebNE_kb] * ebqe_bc_u_n_ext.data()[ebNE_kb]
3630 + (1 - isDOFBoundary_n.data()[ebNE_kb]) * u_n_ext_qp;
3631 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
3632 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
3633 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
3634 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], u_ext, u_n_ext_qp,
3635 m_ext, dm_ext, dm_du_n_ext, f_ext, df_ext, df_du_n_ext, a_ext, da_ext, da_du_n_ext,
3636 as_ext, bc_Kr, bc_dKr, dkr_du_n_ext, thetaW_ext);
3637 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
3638 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
3639 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
3640 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], un_ext, u_n_ext_qp_old,
3641 mn_ext, dmn_ext, dmn_du_n_ext, fn_ext, dfn_ext, dfn_du_n_ext, an_ext, dan_ext, dan_du_n_ext,
3642 asn_ext, bc_Krn, bc_dKrn, dkrn_du_n_ext, thetaWn_ext);
3643 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_ext, beta, gravity.data(),
3644 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
3645 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
3646 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], bc_u_ext, bc_u_n_ext_qp,
3647 bc_m_ext, bc_dm_ext, bc_dm_du_n, bc_f_ext, bc_df_ext, bc_df_du_n, bc_a_ext, bc_da_ext, bc_da_du_n,
3648 bc_as_ext, bc_Kr_ext, bc_dKr_ext, bc_dkr_du_n, thetaW_bc_ext);
3649 ebqe_theta.data()[ebNE_kb] = thetaW_ext;
3650
3651 //
3652 //Calculate Darcy Velocity at external faces
3653 //
3654
3655 // double darcy_velocity_loc_ext[nSpace];
3656 // for (int I = 0; I < nSpace; I++) { darcy_velocity_loc_ext[I] = 0.0; }
3657
3658 // for (int I = 0; I < nSpace; I++) {
3659 // for (int J = 0; J < nSpace; J++) { darcy_velocity_loc_ext[I] -= bc_Kr * KWs.data()[elementMaterialTypes[eN] * nSpace * nSpace + I * nSpace + J] * (grad_u_ext[J]+ gravity.data()[J]); }
3660 // }
3661 // for (int I = 0; I < nSpace; I++) { ebqe_velocity_ext_couple.data()[ebNE_kb_nSpace + I] = darcy_velocity_loc_ext[I] ; }
3662
3663 double ext_pressure_gradient[nSpace];
3664 for (int J = 0; J < nSpace; ++J)
3665 ext_pressure_gradient[J] = grad_u_ext[J] - rho_velocity_ext * gravity.data()[J];
3666
3667 for (int I = 0; I < nSpace; ++I) {
3668 double acc = 0.0;
3669 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I+1]; ++ii) {
3670 const int J = a_colind.data()[ii];
3671 acc += (a_ext[ii] / rho_velocity_ext) * ext_pressure_gradient[J];
3672 }
3673 ebqe_velocity_ext.data()[ebNE_kb_nSpace + I] = -acc;
3674 ebqe_velocity_ext_couple.data()[ebNE_kb_nSpace + I] = -acc;
3675 }
3676 bool useConsistentFlux=false;
3677 double grad_u_n_ext_b[nSpace];
3678 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
3679 u_grad_trial_trace, grad_u_n_ext_b);
3680 const int mat_b0 = elementMaterialTypes.data()[eN];
3681 const double alpha_b0 = alpha.data()[mat_b0];
3682 const double n_vg_b0 = n.data()[mat_b0];
3683 const double krn_end_b0 = krn_end.data()[mat_b0];
3684 const double *KWs_b0 = &KWs.data()[mat_b0 * nnz];
3685 const double phi_b0 = thetaR.data()[mat_b0] + thetaSR.data()[mat_b0];
3686 const double S_wr_b0 = thetaR.data()[mat_b0] / phi_b0;
3687 const double one_m_Sr_b0 = 1.0 - S_wr_b0;
3688 const double Se_trap_L3616 = 1.0 - S_gr.data()[mat_b0] / one_m_Sr_b0; // gas-only residual trapping
3689 const double p_clb0 = fmax(u_ext, 1.0e2);
3692 double Sgb0 = fsb0.S_g, dSgb0_dp = fsb0.dS_g_dp, dSgb0_dz = fsb0.dS_g_dz;
3693 // Per-rock closure: with vertex (Lobatto) boundary quadrature this point is
3694 // a face vertex; at an interface node read this element's rock's S_r.
3695 if (per_rock) {
3696 int a_v = -1;
3697 for (int a = 0; a < nDOF_trial_element; a++)
3698 if (u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element + a] > 1.0 - 1.0e-12) a_v = a;
3699 if (a_v < 0)
3700 throw std::runtime_error("m_comp_co2: per_rock_closure needs vertex (Lobatto) boundary quadrature");
3701 const int gv = u_l2g.data()[eN_nDOF_trial_element + a_v];
3702 if (node_multi[gv]) {
3703 const int o = gv * nRock + mat_b0;
3704 Sgb0 = rS[o]; dSgb0_dp = rS_dp[o]; dSgb0_dz = rS_dz[o];
3705 }
3706 }
3707 const double Sab0 = 1.0 - Sgb0;
3708 const double Se_rawb0 = (Sab0 - S_wr_b0)/one_m_Sr_b0;
3709 double Se_ab0, dSeb0_dp, dSeb0_dz;
3710 if (Se_rawb0<=0.0){Se_ab0=0.0;dSeb0_dp=0.0;dSeb0_dz=0.0;}
3711 else if (Se_rawb0>=1.0){Se_ab0=1.0;dSeb0_dp=0.0;dSeb0_dz=0.0;}
3712 else {Se_ab0=Se_rawb0;dSeb0_dp=-dSgb0_dp/one_m_Sr_b0;dSeb0_dz=-dSgb0_dz/one_m_Sr_b0;}
3713 double KWrb0=0,DKWrb0=0,thWb0=0,DthWb0=0,KNrb0=0,DKNrb0=0,pcb0=0,dpc_dSeb0=0,d2pcb0=0;
3714 if (PSK_TYPE_member == 1) {
3715 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_ab0, alpha_b0, n_vg_b0, thetaR.data()[mat_b0], thetaSR.data()[mat_b0], thWb0, DthWb0, KWrb0, DKWrb0);
3716 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_ab0, alpha_b0, n_vg_b0, KNrb0, DKNrb0, Se_trap_L3616);
3717 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_ab0, alpha_b0, n_vg_b0, bc_Se_min.data()[mat_b0], pcb0, dpc_dSeb0, d2pcb0);
3718 } else {
3719 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_ab0, alpha_b0, n_vg_b0, thetaR.data()[mat_b0], thetaSR.data()[mat_b0], thWb0, DthWb0, KWrb0, DKWrb0);
3720 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_ab0, alpha_b0, n_vg_b0, KNrb0, DKNrb0, Se_trap_L3616);
3721 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_ab0, alpha_b0, n_vg_b0, pcb0, dpc_dSeb0, d2pcb0);
3722 }
3723 KNrb0 *= krn_end_b0; DKNrb0 *= krn_end_b0;
3724 const double pcpb0 = dpc_dSeb0/one_m_Sr_b0;
3725 const double dpcpb0_dp = (d2pcb0/one_m_Sr_b0)*dSeb0_dp;
3726 const double dpcpb0_dz = (d2pcb0/one_m_Sr_b0)*dSeb0_dz;
3728 const double Mbar_gb0 = fsb0.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb0.Y)*::m_comp_co2::eos::M_H2O_KG;
3729 const double Mbar_ab0 = fsb0.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb0.X)*::m_comp_co2::eos::M_H2O_KG;
3730 const double rgmb0 = fsb0.rho_g*Mbar_gb0, ramb0 = fsb0.rho_a*Mbar_ab0;
3731 const double drgmb0_dp = fsb0.drho_g_dp*Mbar_gb0 + fsb0.rho_g*fsb0.dY_dp*dMmb0;
3732 const double drgmb0_dz = fsb0.rho_g*fsb0.dY_dz*dMmb0;
3733 const double dramb0_dp = fsb0.drho_a_dp*Mbar_ab0 + fsb0.rho_a*fsb0.dX_dp*dMmb0;
3734 const double dramb0_dz = fsb0.drho_a_dz*Mbar_ab0 + fsb0.rho_a*fsb0.dX_dz*dMmb0;
3735 const double Agb0 = fsb0.rho_g*(1.0-fsb0.Y), Aab0 = fsb0.rho_a*(1.0-fsb0.X);
3736 const double dAgb0_dp = fsb0.drho_g_dp*(1.0-fsb0.Y) - fsb0.rho_g*fsb0.dY_dp;
3737 const double dAgb0_dz = - fsb0.rho_g*fsb0.dY_dz;
3738 const double dAab0_dp = fsb0.drho_a_dp*(1.0-fsb0.X) - fsb0.rho_a*fsb0.dX_dp;
3739 const double dAab0_dz = fsb0.drho_a_dz*(1.0-fsb0.X) - fsb0.rho_a*fsb0.dX_dz;
3740 double F0n_b = 0.0;
3741 double valp_b[nSpace], valz_b[nSpace];
3742 for (int I=0;I<nSpace;I++){
3743 double ugI=0,uaI=0,dugp=0,dugz=0,duap=0,duaz=0;
3744 for (int ii=a_rowptr.data()[I];ii<a_rowptr.data()[I+1];ii++){
3745 const int J=a_colind.data()[ii];
3746 const double Kii=KWs_b0[ii];
3747 const double Mob_g=KNrb0*Kii/mu_n, Mob_a=KWrb0*Kii;
3748 const double dMobg_dp=(DKNrb0*Kii/mu_n)*dSeb0_dp, dMobg_dz=(DKNrb0*Kii/mu_n)*dSeb0_dz;
3749 const double dMoba_dp=(DKWrb0*Kii)*dSeb0_dp, dMoba_dz=(DKWrb0*Kii)*dSeb0_dz;
3750 const double gJ=gravity.data()[J];
3751 const double gradSa=-(dSgb0_dp*grad_u_ext[J]+dSgb0_dz*grad_u_n_ext_b[J]);
3752 const double gp_a=grad_u_ext[J]-ramb0*gJ;
3753 const double gp_g=grad_u_ext[J]+pcpb0*gradSa-rgmb0*gJ;
3754 ugI-=Mob_g*gp_g; uaI-=Mob_a*gp_a;
3755 const double dgradSa_dp=-(fsb0.d2S_g_dp2*grad_u_ext[J]+fsb0.d2S_g_dpdz*grad_u_n_ext_b[J]);
3756 const double dgradSa_dz=-(fsb0.d2S_g_dpdz*grad_u_ext[J]+fsb0.d2S_g_dz2*grad_u_n_ext_b[J]);
3757 const double dgpg_dp=dpcpb0_dp*gradSa+pcpb0*dgradSa_dp-drgmb0_dp*gJ;
3758 const double dgpg_dz=dpcpb0_dz*gradSa+pcpb0*dgradSa_dz-drgmb0_dz*gJ;
3759 dugp-=dMobg_dp*gp_g+Mob_g*dgpg_dp;
3760 dugz-=dMobg_dz*gp_g+Mob_g*dgpg_dz;
3761 duap-=dMoba_dp*gp_a+Mob_a*(-dramb0_dp*gJ);
3762 duaz-=dMoba_dz*gp_a+Mob_a*(-dramb0_dz*gJ);
3763 }
3764 F0n_b += (Agb0*ugI + Aab0*uaI) * normal[I];
3765 valp_b[I] = (dAgb0_dp*ugI + Agb0*dugp + dAab0_dp*uaI + Aab0*duap);
3766 valz_b[I] = (dAgb0_dz*ugI + Agb0*dugz + dAab0_dz*uaI + Aab0*duaz);
3767 }
3768 const double penb0 = ebqe_penalty_ext.data()[ebNE_kb];
3769 (void)valz_b;
3770 {
3771 const int isSeep = isSeepageFace.data()[ebNE];
3772 if (isSeep || isDOFBoundary_u.data()[ebNE_kb]) {
3773 const double bc_u_pen = isSeep ? 0.0 : bc_u_ext;
3774 const double pen_term = penb0*(u_ext - bc_u_pen);
3775 flux_ext = F0n_b + pen_term; // consistent -> TransportMatrix*
3776 bflux_ext = pen_term; // penalty -> globalResidual
3777 if (isSeep && flux_ext <= 0.0) { flux_ext = 0.0; bflux_ext = 0.0; }
3778 } else {
3779 flux_ext = ebqe_bc_flux_ext[ebNE_kb];
3780 bflux_ext = ebqe_bc_flux_ext[ebNE_kb];
3781 }
3782 }
3783
3784 ebqe_flux.data()[ebNE_kb] = flux_ext;
3785
3786 anb_seepage_flux = seepagefluxcalculator(anb_seepage_flux, isSeepageFace.data()[ebNE], dS, flux_ext);
3787 anb_seepage_flux_n.data()[0] = anb_seepage_flux;
3788 ebqe_u.data()[ebNE_kb] = u_ext;
3789 //
3790 //update residuals
3791 //
3792 for (int i = 0; i < nDOF_test_element; i++) {
3793 if (useConsistentFlux) {
3794 elementResidual_u[i] += ck.ExteriorElementBoundaryFlux(flux_ext, u_test_dS[i]);
3795 } else {
3796 elementResidual_u[i] += ck.ExteriorElementBoundaryFlux(bflux_ext, u_test_dS[i]);
3797 }
3798 } //i
3799 for (int j = 0; j < nDOF_trial_element; j++) {
3800 if (useConsistentFlux) {
3801 exteriorNumericalFluxJacobian(a_rowptr.data(), a_colind.data(), isDOFBoundary_u.data()[ebNE_kb], normal, a_ext, da_ext, grad_u_ext, &u_grad_trial_trace[j * nSpace], df_ext, u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element + j],
3802 ebqe_penalty_ext.data()[ebNE_kb], //penalty,
3803 fluxJacobian_u_u[j]);
3804 } else {
3805 // P3c boundary (STAB=2): compositional comp-0 flux Jacobian.
3806 // Consistent d(F_0.n)/d(p_j) -> fluxJacobian_u_u (TransportMatrix*);
3807 // penalty -> bfluxJacobian_u_u (globalJacobian). value/grad blocks
3808 // reuse valp_b + the stored flash/psk state (FD-verified, b0test).
3809 // (0,1) cross-block not assembled here (matches the original).
3810 if (isDOFBoundary_u.data()[ebNE_kb]) {
3811 const double trial_j = u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element + j];
3812 double accp = 0.0;
3813 for (int I=0;I<nSpace;I++){
3814 accp += normal[I]*valp_b[I]*trial_j;
3815 for (int ii=a_rowptr.data()[I];ii<a_rowptr.data()[I+1];ii++){
3816 const int J=a_colind.data()[ii];
3817 const double Kii=KWs_b0[ii];
3818 const double Mob_g=KNrb0*Kii/mu_n, Mob_a=KWrb0*Kii;
3819 const double dFdgp = Agb0*(-Mob_g*(1.0 - pcpb0*dSgb0_dp)) + Aab0*(-Mob_a);
3820 accp += normal[I]*dFdgp*u_grad_trial_trace[j*nSpace + J];
3821 }
3822 }
3823 fluxJacobian_u_u[j] = accp; // consistent (no penalty)
3824 bfluxJacobian_u_u[j] = penb0*trial_j; // penalty
3825 } else {
3826 fluxJacobian_u_u[j] = 0.0;
3827 bfluxJacobian_u_u[j] = 0.0;
3828 }
3829 }
3830 exteriorNumericalFluxJacobian(a_rowptr.data(), a_colind.data(),
3831 isDOFBoundary_u.data()[ebNE_kb], normal,
3832 asn_ext, dan_ext, grad_u_ext,
3833 &u_grad_trial_trace[j * nSpace], dfn_ext,
3834 u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element + j],
3835 ebqe_penalty_ext.data()[ebNE_kb],
3836 fluxJacobian_un_un[j]);
3837 } //j
3838 //
3839 //update the element and global residual storage
3840 //
3841 for (int i = 0; i < nDOF_test_element; i++) {
3842 int eN_i = eN * nDOF_test_element + i;
3843 for (int j = 0; j < nDOF_trial_element; j++) {
3844 int ebN_i_j = ebN * 4 * nDOF_test_X_trial_element + i * nDOF_trial_element + j;
3845 if (useConsistentFlux) {
3846 globalJacobian.data()[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += fluxJacobian_u_u[j] * u_test_dS[i];
3847 } else {
3848 globalJacobian.data()[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += bfluxJacobian_u_u[j] * u_test_dS[i];
3849 TransportMatrix[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += fluxJacobian_u_u[j] * u_test_dS[i];
3850 TransportMatrixConsistent[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += fluxJacobian_u_u[j] * u_test_dS[i];
3851 TransportMatrixn[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += fluxJacobian_un_un[j] * u_test_dS[i];
3852 TransportMatrixConsistentn[csrRowIndeces_u_u[eN_i] + csrColumnOffsets_eb_u_u[ebN_i_j]] += fluxJacobian_un_un[j] * u_test_dS[i];
3853 }
3854 } //j
3855 } //i
3856 } //kb
3857 for (int i = 0; i < nDOF_test_element; i++) {
3858 int eN_i = eN * nDOF_test_element + i;
3859 globalResidual.data()[offset_u + stride_u * u_l2g.data()[eN_i]] += elementResidual_u[i];
3860 }//i
3861 } //ebNE
3863 // COMPUTE SMOOTHNESS INDICATOR and NORMALIZE ENTROPY RESIDUAL //
3865 // NOTE: see NCLS.h for a different but equivalent implementation of this.
3866 std::vector<double> cflux(numDOFs, 0.0);
3867 for (int i = 0; i < numDOFs_u; i++) {
3868 double gi[nSpace], Cij[nSpace], xi[nSpace], etaMaxi, etaMini;
3869 const int node_i = freeDOFToNode_u.data()[i];
3870 double solni = u_free_dof_old[i];
3871 for (int I = 0; I < nSpace; I++) {
3872 solni -= rho_dof[i] * gravity.data()[I] * mesh_dof.data()[node_i * 3 + I];
3873 }
3874 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) //EV Stabilization
3875 {
3876 // For eta min and max
3877 etaMaxi = fabs(eta[i]);
3878 etaMini = fabs(eta[i]);
3879 }
3880 // initialize gi and compute xi
3881 for (int I = 0; I < nSpace; I++) {
3882 gi[I] = 0.;
3883 xi[I] = mesh_dof.data()[node_i * 3 + I];
3884 }
3885 // for smoothness indicator //
3886 double alpha_numerator_pos = 0., alpha_numerator_neg = 0., alpha_denominator_pos = 0., alpha_denominator_neg = 0.;
3887 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) { // First loop in j (sparsity pattern)
3888 int j = csrColumnOffsets_DofLoops.data()[offset];
3889 const int full_offset = full_offset_from_compact(i, j);
3890 assert(full_offset >= 0);
3891 const int node_j = freeDOFToNode_u.data()[j];
3892 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) //EV Stabilization
3893 {
3894 // COMPUTE ETA MIN AND ETA MAX //
3895 etaMaxi = fmax(etaMaxi, fabs(eta[j]));
3896 etaMini = fmin(etaMini, fabs(eta[j]));
3897 }
3898 double solnj = u_free_dof_old[j];
3899 for (int I = 0; I < nSpace; I++) {
3900 solnj -= rho_dof[j] * gravity.data()[I] * mesh_dof.data()[node_j * 3 + I];
3901 }
3902 // Update Cij matrices
3903 Cij[0] = Cx[full_offset];
3904#if nSpace == 2
3905 Cij[1] = Cy[full_offset];
3906#endif
3907#if nSpace == 3
3908 Cij[2] = Cz[full_offset];
3909#endif
3910 // COMPUTE gi VECTOR. gi=1/mi*sum_j(Cij*solj)
3911 for (int I = 0; I < nSpace; I++) gi[I] += Cij[I] * solnj;
3912
3913 // COMPUTE numerator and denominator of smoothness indicator
3914 double alpha_num = solni - solnj;
3915 if (alpha_num >= 0.) {
3916 alpha_numerator_pos += alpha_num;
3917 alpha_denominator_pos += alpha_num;
3918 } else {
3919 alpha_numerator_neg += alpha_num;
3920 alpha_denominator_neg += fabs(alpha_num);
3921 }
3922 }
3923 // scale g vector by lumped mass matrix
3924 //double mass_matrix_error = abs(ML.data()[i] - ML2[i]);
3925 //if (mass_matrix_error > 1.0e-16) std::cout << mass_matrix_error<<" ML " << ML.data()[i] << '\t' << ML2[i] << std::endl;
3926 for (int I = 0; I < nSpace; I++) gi[I] /= ML.data()[i];
3927 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) //EV Stab
3928 {
3929 // Normalizae entropy residual
3930 global_entropy_residual[i] *= etaMini == etaMaxi ? 0. : 2 * cE / (etaMaxi - etaMini);
3931 quantDOFs.data()[i] = fabs(global_entropy_residual[i]);
3932 }
3933
3934 // Now that I have the gi vectors, I can use them for the current i-th DOF
3935 double SumPos = 0., SumNeg = 0.;
3936 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) { // second loop in j (sparsity pattern)
3937 int j = csrColumnOffsets_DofLoops.data()[offset];
3938 const int full_offset = full_offset_from_compact(i, j);
3939 assert(full_offset >= 0);
3940 // compute gi*(xi-xj)
3941 double gi_times_x = 0.;
3942 for (int I = 0; I < nSpace; I++) {
3943 gi_times_x += gi[I] * delta_x_ij.data()[full_offset * 3 + I];
3944 }
3945 // compute the positive and negative part of gi*(xi-xj)
3946 SumPos += gi_times_x > 0 ? gi_times_x : 0;
3947 SumNeg += gi_times_x < 0 ? gi_times_x : 0;
3948 }
3949 double sigmaPosi = fmin(1., (fabs(SumNeg) + 1E-15) / (SumPos + 1E-15));
3950 double sigmaNegi = fmin(1., (SumPos + 1E-15) / (fabs(SumNeg) + 1E-15));
3951 double alpha_numi = fabs(sigmaPosi * alpha_numerator_pos + sigmaNegi * alpha_numerator_neg);
3952 double alpha_deni = sigmaPosi * alpha_denominator_pos + sigmaNegi * alpha_denominator_neg;
3953 if (IS_BETAij_ONE == 1) {
3954 alpha_numi = fabs(alpha_numerator_pos + alpha_numerator_neg);
3955 alpha_deni = alpha_denominator_pos + alpha_denominator_neg;
3956 }
3957 double alphai = alpha_numi / (alpha_deni + 1E-15);
3958 quantDOFs.data()[i] = alphai;
3959
3960 if (POWER_SMOOTHNESS_INDICATOR == 0) psi[i] = 1.0;
3961 else psi[i] = std::pow(alphai, POWER_SMOOTHNESS_INDICATOR); //NOTE: they use alpha^2 in the paper
3962 }
3963 std::vector<double> w_lam_g(numDOFs_u, 0.0), w_lam_a(numDOFs_u, 0.0);
3964 std::vector<double> w_dlam_g_dp(numDOFs_u, 0.0), w_dlam_g_dz(numDOFs_u, 0.0);
3965 std::vector<double> w_dlam_a_dp(numDOFs_u, 0.0), w_dlam_a_dz(numDOFs_u, 0.0);
3966 std::vector<double> w_pc(numDOFs_u, 0.0), w_dpc_dp(numDOFs_u, 0.0), w_dpc_dz(numDOFs_u, 0.0);
3967 std::vector<double> w_rgm(numDOFs_u, 0.0), w_ram(numDOFs_u, 0.0);
3968 std::vector<double> w_drgm_dp(numDOFs_u, 0.0), w_drgm_dz(numDOFs_u, 0.0);
3969 std::vector<double> w_dram_dp(numDOFs_u, 0.0), w_dram_dz(numDOFs_u, 0.0);
3970 std::vector<double> w_lam_g_old(numDOFs_u, 0.0), w_lam_a_old(numDOFs_u, 0.0);
3971 std::vector<double> w_pc_old(numDOFs_u, 0.0);
3972 std::vector<double> w_rgm_old(numDOFs_u, 0.0), w_ram_old(numDOFs_u, 0.0);
3973 {
3975 for (int i = 0; i < numDOFs_u; i++) {
3976 const int node_i = freeDOFToNode_u.data()[i];
3977 const int mat_i = freeDOFMaterialTypes.data()[i];
3978 const double alpha_i = alpha.data()[mat_i];
3979 const double n_vg_i = n.data()[mat_i];
3980 const double krn_end_i= krn_end.data()[mat_i];
3981 const double phi_i = thetaR.data()[mat_i] + thetaSR.data()[mat_i];
3982 const double S_wr_i = thetaR.data()[mat_i] / phi_i;
3983 const double one_m_Sr_i = 1.0 - S_wr_i;
3984 const double Se_trap_L3923 = 1.0 - S_gr.data()[mat_i] / one_m_Sr_i; // gas-only residual trapping
3985 const double cg_i = krn_end_i / mu_n;
3986 // --- current iterate ---
3987 const double p_cl = fmax(u_free_dof[i], 1.0e2);
3990 const double Sa = 1.0 - f.S_g;
3991 const double Se_raw = (Sa - S_wr_i) / one_m_Sr_i;
3992 double Se, dSe_dp, dSe_dz;
3993 if (Se_raw <= 0.0) { Se = 0.0; dSe_dp = 0.0; dSe_dz = 0.0; }
3994 else if (Se_raw >= 1.0) { Se = 1.0; dSe_dp = 0.0; dSe_dz = 0.0; }
3995 else { Se = Se_raw; dSe_dp = -f.dS_g_dp/one_m_Sr_i; dSe_dz = -f.dS_g_dz/one_m_Sr_i; }
3996 double krn=0,dkrn=0,krw=0,dkrw=0,thW=0,DthW=0,pc=0,dpc_dSe=0,d2pc=0;
3997 if (PSK_TYPE_member == 1) {
3998 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se, alpha_i, n_vg_i, krn, dkrn, Se_trap_L3923);
3999 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se, alpha_i, n_vg_i, thetaR.data()[mat_i], thetaSR.data()[mat_i], thW, DthW, krw, dkrw);
4000 proteus::m_comp_co2::psk::bc_pc_from_Se(Se, alpha_i, n_vg_i, bc_Se_min.data()[mat_i], pc, dpc_dSe, d2pc);
4001 } else {
4002 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se, alpha_i, n_vg_i, krn, dkrn, Se_trap_L3923);
4003 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se, alpha_i, n_vg_i, thetaR.data()[mat_i], thetaSR.data()[mat_i], thW, DthW, krw, dkrw);
4004 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se, alpha_i, n_vg_i, pc, dpc_dSe, d2pc);
4005 }
4006 w_pc[i] = pc; w_dpc_dp[i] = dpc_dSe*dSe_dp; w_dpc_dz[i] = dpc_dSe*dSe_dz;
4007 const double Mg = f.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-f.Y)*::m_comp_co2::eos::M_H2O_KG;
4008 const double Ma = f.X*::m_comp_co2::eos::M_CO2_KG + (1.0-f.X)*::m_comp_co2::eos::M_H2O_KG;
4009 w_rgm[i] = f.rho_g*Mg; w_ram[i] = f.rho_a*Ma;
4010 w_drgm_dp[i] = f.drho_g_dp*Mg + f.rho_g*f.dY_dp*dMm_w; w_drgm_dz[i] = f.rho_g*f.dY_dz*dMm_w;
4011 w_dram_dp[i] = f.drho_a_dp*Ma + f.rho_a*f.dX_dp*dMm_w; w_dram_dz[i] = f.drho_a_dz*Ma + f.rho_a*f.dX_dz*dMm_w;
4012 // H2O molar mobilities: gas weight (1-Y), aqueous weight (1-X).
4013 const double yw = 1.0 - f.Y, dyw_dp = -f.dY_dp, dyw_dz = -f.dY_dz;
4014 const double xw = 1.0 - f.X, dxw_dp = -f.dX_dp, dxw_dz = -f.dX_dz;
4015 w_lam_g[i] = cg_i*f.rho_g*yw*krn;
4016 w_dlam_g_dp[i] = cg_i*(f.drho_g_dp*yw*krn + f.rho_g*dyw_dp*krn + f.rho_g*yw*dkrn*dSe_dp);
4017 w_dlam_g_dz[i] = cg_i*( f.rho_g*dyw_dz*krn + f.rho_g*yw*dkrn*dSe_dz);
4018 w_lam_a[i] = f.rho_a*xw*krw;
4019 w_dlam_a_dp[i] = f.drho_a_dp*xw*krw + f.rho_a*dxw_dp*krw + f.rho_a*xw*dkrw*dSe_dp;
4020 w_dlam_a_dz[i] = f.drho_a_dz*xw*krw + f.rho_a*dxw_dz*krw + f.rho_a*xw*dkrw*dSe_dz;
4021 // --- old time level (frozen; feeds the (1-Theta) part, no derivatives) ---
4022 const double p_cl_o = fmax(u_free_dof_old[i], 1.0e2);
4025 const double Sa_o = 1.0 - fo.S_g;
4026 const double Se_o_raw = (Sa_o - S_wr_i) / one_m_Sr_i;
4027 const double Se_o = Se_o_raw <= 0.0 ? 0.0 : (Se_o_raw >= 1.0 ? 1.0 : Se_o_raw);
4028 double krn_o=0,dkrn_o=0,krw_o=0,dkrw_o=0,thW_o=0,DthW_o=0,pc_o=0,dpc_o=0,d2pc_o=0;
4029 if (PSK_TYPE_member == 1) {
4030 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_o, alpha_i, n_vg_i, krn_o, dkrn_o, Se_trap_L3923);
4031 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_o, alpha_i, n_vg_i, thetaR.data()[mat_i], thetaSR.data()[mat_i], thW_o, DthW_o, krw_o, dkrw_o);
4032 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_o, alpha_i, n_vg_i, bc_Se_min.data()[mat_i], pc_o, dpc_o, d2pc_o);
4033 } else {
4034 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_o, alpha_i, n_vg_i, krn_o, dkrn_o, Se_trap_L3923);
4035 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_o, alpha_i, n_vg_i, thetaR.data()[mat_i], thetaSR.data()[mat_i], thW_o, DthW_o, krw_o, dkrw_o);
4036 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_o, alpha_i, n_vg_i, pc_o, dpc_o, d2pc_o);
4037 }
4038 w_pc_old[i] = pc_o;
4039 const double Mg_o = fo.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fo.Y)*::m_comp_co2::eos::M_H2O_KG;
4040 const double Ma_o = fo.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fo.X)*::m_comp_co2::eos::M_H2O_KG;
4041 w_rgm_old[i] = fo.rho_g*Mg_o; w_ram_old[i] = fo.rho_a*Ma_o;
4042 w_lam_g_old[i] = cg_i*fo.rho_g*(1.0-fo.Y)*krn_o;
4043 w_lam_a_old[i] = fo.rho_a*(1.0-fo.X)*krw_o;
4044 }
4045 }
4047 // ** LOOP IN DOFs FOR EDGE BASED TERMS ** //
4049 // only iterate component-0 DOFs here. Component 1
4050 // (trivial gas eq) is assembled by the dedicated element loop appended
4051 // at the end of this function.
4052 for (int i = 0; i < numDOFs_u; i++) {
4053 int ii = -1;
4054 double sum_abs_dt_times_fH_minus_fL = 0.0, MLi = ML.data()[i];
4055 double Kr, dKr, Krn, dKrn;
4056 double J_ii = 0.0;
4057 double ith_dissipative_term = 0;
4058 double ith_low_order_dissipative_term = 0;
4059 double ith_flux_term = 0;
4060 double ith_consistent_flux_term = 0;
4061 double dLii = 0.;
4062 double m, dm, f[nSpace], df[nSpace], a[nnz], da[nnz], as[nnz];
4063 double dmn, fn[nSpace], dfn[nSpace], an[nnz], dan[nnz], asn[nnz];
4064 // Cross-derivatives used by the (0,1) coupling wired into the low-order
4065 // wetting operator below: dm/du_n is added to the lumped-mass coupling
4066 // (row_w, col_n_i), and dkr/du_n[upwind] is added to the Kuzmin upwind
4067 // term at (row_w, col_n_upwind). The 'n_old' variants describe the
4068 // frozen time history -- they don't contribute to the Jacobian.
4069 double dm_du_n_fct, dkr_du_n_fct, df_du_n_fct[nSpace], da_du_n_fct[nnz];
4070 double dmn_du_n_fct, dkrn_du_n_fct, dfn_du_n_fct[nSpace], dan_du_n_fct[nnz];
4071
4072 const double rho_i = rho_dof[i];
4073 const int node_i = freeDOFToNode_u.data()[i];
4074
4075 double thetaW_tmp = 0.0;
4076 // loop over the sparsity pattern of the i-th DOF
4077 for (int offset = csrRowIndeces_DofLoops.data()[i]; offset < csrRowIndeces_DofLoops.data()[i + 1]; offset++) {
4078 int j = csrColumnOffsets_DofLoops.data()[offset];
4079 const int full_offset = full_offset_from_compact(i, j);
4080 assert(full_offset >= 0);
4081 if (i == j) ii = full_offset;
4082 const double rho_j = rho_dof[j];
4083 const int node_j = freeDOFToNode_u.data()[j];
4084 const double rho_edge = 0.5 * (rho_i + rho_j);
4085 // ===== P3c: compositional H2O edge flux F_0 = F_g^w + F_a^w =====
4086 // Replaces the single-phase Kuzmin wetting flux fL = krw*tau*delta_phi.
4087 // F_g^w = tau * lam_g^w_up * dPhi_g, lam_g^w = (krn_end/mu_n)*rho_g*(1-Y)*krn
4088 // F_a^w = tau * lam_a^w_up * dPhi_a, lam_a^w = rho_a*(1-X)*krw
4089 // dPhi_g = d(p+pc) - rho_g_mass_edge*g.dx, dPhi_a = dp - rho_a_mass_edge*g.dx
4090 // The two-phase potentials, mobilities and densities come from the
4091 // per-free-DOF flash cache (w_*) built above; node closures use the
4092 // single-nodal rock freeDOFMaterialTypes[i] (comp-0 skeleton kept).
4093 // BARE transmissibility tau = -TransportMatrix[ij]/rho_edge strips the
4094 // rho_w baked into as=rhom*KWs (TransportMatrix = int rhom*KWs gg) so
4095 // density/mobility live in lam^w/dPhi (the memory's tau/rho_edge option).
4096 // No high-order term, no EV graph dissipation, no capillary entry-pressure
4097 // gate (comp-0 gas branch carries only water vapor 1-Y ~ tiny; the DOF-graph
4098 // loop has no per-element context for the two-sided barrier). comp-0 FCT
4099 // is a pass-through: dt_times_fH_minus_fL is zeroed and never consumed
4100 // (postStep runs only FCTStep(component=1)).
4101 dt_times_fH_minus_fL.data()[full_offset] = 0.0;
4102 if (i == j) continue; // ii captured above; no self-flux
4103 const double tau = fmax(0.0, -TransportMatrix[full_offset]) / rho_edge;
4104 if (tau == 0.0) continue;
4105 double g_dot_dx = 0.0;
4106 for (int I = 0; I < nSpace; I++)
4107 g_dot_dx += gravity.data()[I]
4108 * (mesh_dof.data()[node_j * 3 + I] - mesh_dof.data()[node_i * 3 + I]);
4109 // ---- gas branch (water vapor, ungated) ----
4110 const double rgm_edge = 0.5 * (w_rgm[i] + w_rgm[j]);
4111 const double rgm_edge_old = 0.5 * (w_rgm_old[i] + w_rgm_old[j]);
4112 const double dPhi_g = (u_free_dof[j] + w_pc[j]) - (u_free_dof[i] + w_pc[i])
4113 - rgm_edge * g_dot_dx;
4114 const double dPhi_g_old = (u_free_dof_old[j] + w_pc_old[j]) - (u_free_dof_old[i] + w_pc_old[i])
4115 - rgm_edge_old * g_dot_dx;
4116 const bool up_i_g = (dPhi_g <= 0.0);
4117 const bool up_i_g_old = (dPhi_g_old <= 0.0);
4118 const double lam_g_up = up_i_g ? w_lam_g[i] : w_lam_g[j];
4119 const double lam_g_up_old = up_i_g_old ? w_lam_g_old[i] : w_lam_g_old[j];
4120 const double Fg = Theta * tau * lam_g_up * dPhi_g
4121 + (1.0 - Theta) * tau * lam_g_up_old * dPhi_g_old;
4122 // ---- aqueous branch (H2O in brine, no gate) ----
4123 const double ram_edge = 0.5 * (w_ram[i] + w_ram[j]);
4124 const double ram_edge_old = 0.5 * (w_ram_old[i] + w_ram_old[j]);
4125 const double dPhi_a = u_free_dof[j] - u_free_dof[i] - ram_edge * g_dot_dx;
4126 const double dPhi_a_old = u_free_dof_old[j] - u_free_dof_old[i] - ram_edge_old * g_dot_dx;
4127 const bool up_i_a = (dPhi_a <= 0.0);
4128 const bool up_i_a_old = (dPhi_a_old <= 0.0);
4129 const double lam_a_up = up_i_a ? w_lam_a[i] : w_lam_a[j];
4130 const double lam_a_up_old = up_i_a_old ? w_lam_a_old[i] : w_lam_a_old[j];
4131 const double Fa = Theta * tau * lam_a_up * dPhi_a
4132 + (1.0 - Theta) * tau * lam_a_up_old * dPhi_a_old;
4133 // R_w[i] -= F_0 (the residual subtracts ith_flux_term below). Same +sign
4134 // convention as the old fL (~ +delta_phi = p_j - p_i).
4135 // P1: the single-nodal-rock comp-0 water flux is RETIRED here -- it is now
4136 // assembled TWO-SIDED per element-side (elementMaterialTypes[eN]) in the
4137 // comp-1 element loop below (elementResidual_w + full-CSR scatter). Keeping
4138 // ith_flux_term = 0 makes this loop comp-0 ACCUMULATION-ONLY:
4139 // R_w[i] = MLi*(m-mn)/dt. (The w_* per-DOF cache above is now unused by the
4140 // residual; left in place for this correctness pass, TODO: drop for speed.)
4141 (void)Fg; (void)Fa;
4142 // ===== Theta-part Jacobian wrt (p_i,z_i,p_j,z_j). Mirrors comp-1 (eftest). =====
4143 const double ddPhig_dpi = -1.0 - w_dpc_dp[i] - 0.5 * w_drgm_dp[i] * g_dot_dx;
4144 const double ddPhig_dzi = - w_dpc_dz[i] - 0.5 * w_drgm_dz[i] * g_dot_dx;
4145 const double ddPhig_dpj = +1.0 + w_dpc_dp[j] - 0.5 * w_drgm_dp[j] * g_dot_dx;
4146 const double ddPhig_dzj = + w_dpc_dz[j] - 0.5 * w_drgm_dz[j] * g_dot_dx;
4147 const double ddPhia_dpi = -1.0 - 0.5 * w_dram_dp[i] * g_dot_dx;
4148 const double ddPhia_dzi = - 0.5 * w_dram_dz[i] * g_dot_dx;
4149 const double ddPhia_dpj = +1.0 - 0.5 * w_dram_dp[j] * g_dot_dx;
4150 const double ddPhia_dzj = - 0.5 * w_dram_dz[j] * g_dot_dx;
4151 const double Tt = Theta * tau;
4152 double dF_dpi = 0.0, dF_dzi = 0.0, dF_dpj = 0.0, dF_dzj = 0.0;
4153 // gas potential part (all four DOFs)
4154 dF_dpi += Tt*lam_g_up*ddPhig_dpi; dF_dzi += Tt*lam_g_up*ddPhig_dzi;
4155 dF_dpj += Tt*lam_g_up*ddPhig_dpj; dF_dzj += Tt*lam_g_up*ddPhig_dzj;
4156 // gas mobility part (upstream node only)
4157 if (up_i_g) { dF_dpi += Tt*w_dlam_g_dp[i]*dPhi_g; dF_dzi += Tt*w_dlam_g_dz[i]*dPhi_g; }
4158 else { dF_dpj += Tt*w_dlam_g_dp[j]*dPhi_g; dF_dzj += Tt*w_dlam_g_dz[j]*dPhi_g; }
4159 // aqueous potential part (all four DOFs)
4160 dF_dpi += Tt*lam_a_up*ddPhia_dpi; dF_dzi += Tt*lam_a_up*ddPhia_dzi;
4161 dF_dpj += Tt*lam_a_up*ddPhia_dpj; dF_dzj += Tt*lam_a_up*ddPhia_dzj;
4162 // aqueous mobility part (upstream node only)
4163 if (up_i_a) { dF_dpi += Tt*w_dlam_a_dp[i]*dPhi_a; dF_dzi += Tt*w_dlam_a_dz[i]*dPhi_a; }
4164 else { dF_dpj += Tt*w_dlam_a_dp[j]*dPhi_a; dF_dzj += Tt*w_dlam_a_dz[j]*dPhi_a; }
4165 // P1: the comp-0 flux Jacobian is RETIRED here too -- its (0,0)/(0,1)
4166 // blocks are assembled two-sided in the element loop below. J_ii stays 0,
4167 // so globalJacobian[ii] below carries only the mass diagonal MLi*dm/dt.
4168 (void)dF_dpi; (void)dF_dpj; (void)dF_dzi; (void)dF_dzj;
4169 }
4170 mDotLow.data()[i] = ith_flux_term/MLi;
4171 cflux[i] = ith_consistent_flux_term;
4172 // Final per-DOF coefficient evaluations at (u_w, u_n) and (u_w_old, u_n_old):
4173 // m -> mLow.data()[i] (current low-order mass)
4174 // mn -> mn.data()[i] (time-history mass for the dt difference)
4175 // dm_du_n_fct -> consumed by the (0,1) lumped-mass coupling below.
4176 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_i, beta, gravity.data(),
4177 alpha.data()[freeDOFMaterialTypes.data()[i]],
4178 n.data()[freeDOFMaterialTypes.data()[i]], thetaR.data()[freeDOFMaterialTypes.data()[i]], thetaSR.data()[freeDOFMaterialTypes.data()[i]], &KWs.data()[freeDOFMaterialTypes.data()[i] * nnz],
4179 u_free_dof[i], u_dof_n.data()[node_i],
4180 m, dm, dm_du_n_fct, f, df, df_du_n_fct, a, da, da_du_n_fct, as, Kr, dKr, dkr_du_n_fct, thetaW_tmp);
4181 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, rho_i, beta, gravity.data(),
4182 alpha.data()[freeDOFMaterialTypes.data()[i]],
4183 n.data()[freeDOFMaterialTypes.data()[i]], thetaR.data()[freeDOFMaterialTypes.data()[i]], thetaSR.data()[freeDOFMaterialTypes.data()[i]], &KWs.data()[freeDOFMaterialTypes.data()[i] * nnz],
4184 u_free_dof_old[i], u_dof_n_old.data()[node_i],
4185 mn.data()[i], dmn, dmn_du_n_fct, fn, dfn, dfn_du_n_fct, an, dan, dan_du_n_fct, asn, Krn, dKrn, dkrn_du_n_fct, thetaW_tmp);
4186 if (per_rock && node_multi[node_i]) {
4187 // H2O storage on the node's pore volume W_i (Sec. 4), as the CO2
4188 // storage already is: MLi * phi(first element visited) -> W_i. At a
4189 // one-rock node the two agree (up to roundoff), so they are left as is.
4190 const int mat_s = freeDOFMaterialTypes.data()[i];
4191 const double s_W = node_W[node_i] / (MLi * (thetaR.data()[mat_s] + thetaSR.data()[mat_s]));
4192 m *= s_W; dm *= s_W; dm_du_n_fct *= s_W; mn.data()[i] *= s_W;
4193 }
4194 mLow.data()[i] = m;
4195 globalResidual.data()[offset_u + stride_u * i] += bc_mask.data()[i] * (MLi * (m - mn.data()[i]) / dt - ith_flux_term);
4196 globalJacobian.data()[ii] += bc_mask.data()[i] * (MLi * dm / dt + J_ii) + (1.0 - bc_mask.data()[i]);
4197 // (0,1) cross-block: lumped-mass contribution MLi * dm/du_n / dt on the
4198 // (row_w=i, col_n=node_i) entry. This complements the per-edge
4199 // dkr/du_n * max(0,-T) * delta_phi contributions wired into (row_w=i,
4200 // col_n=upwind_node) inside the j-loop above. Together they make the
4201 // low-order operator fully consistent with d R_w / d u_n.
4202 {
4203 const int row_w = offset_u + stride_u * i;
4204 const int col_n = offset_n + stride_n * node_i;
4205 int off_wv = -1;
4206 for (int o = csrRowIndeces_Full.data()[row_w];
4207 o < csrRowIndeces_Full.data()[row_w + 1]; o++) {
4208 if (csrColumnOffsets_Full.data()[o] == col_n) { off_wv = o; break; }
4209 }
4210 if (off_wv >= 0) {
4211 globalJacobian.data()[off_wv] += bc_mask.data()[i] * MLi * dm_du_n_fct / dt;
4212 }
4213 }
4214 }
4215 // FCT limiter execution.
4216 //
4217 // Two operating modes:
4218 // * STABILIZATION_TYPE == Implicit_FCT (Richards-style, in-Newton FCT):
4219 // comp-0's fluxCorrection is injected into globalResidual so
4220 // Newton sees the limited residual. This is the legacy path; it
4221 // relies on small enough alpha-derivative deviations to converge.
4222 // * FCT_n == 1 with STABILIZATION_TYPE == EntropyViscosity (TADR-style
4223 // defect-correction):
4224 // Newton solves the LOW-ORDER R_low cleanly (no Zalesak
4225 // contribution to globalResidual). The limiter is computed here
4226 // so limited_solution_n and fluxCorrection_n are available, but
4227 // the actual scatter to self.u[1].dof happens in Python after
4228 // Newton convergence (Coefficients.postStep). This matches TADR /
4229 // Richards Newton.solve flow where FCT is a post-step.
4230 //
4231 // FCTStep is NOT called here. Both components' FCT run as a Python-
4232 // orchestrated post-step (Coefficients.postStep -> LevelModel.FCTStep):
4233 // FCTStep(component, pass=1) -> ghost-scatter Rpos/Rneg -> FCTStep(pass=2),
4234 // which is the requirement for MPI-parallel mass conservation. This
4235 // routine just leaves the comp-0 and comp-1 FCT predictor arrays
4236 // (mLow, mDotLow, dt_times_fH_minus_fL, dLow, min/max_m_bc, ...) populated
4237 // from the converged iterate.
4238 if (STABILIZATION_TYPE == STABILIZATION::Implicit_FCT) {
4239 // Legacy in-Newton injection (kept for STAB=Implicit_FCT only; the
4240 // Python Coefficients class rejects Implicit_FCT, so this is dead).
4241 for (int i = 0; i < numDOFs; i++) {
4242 globalResidual.data()[offset_u + stride_u * i] += fluxCorrection.data()[i];
4243 }
4244 for (int i_n = 0; i_n < numDOFs_n; i_n++) {
4245 globalResidual.data()[offset_n + stride_n * i_n] += fluxCorrection_n.data()[i_n];
4246 }
4247 }
4248
4249 // ============================================================================
4250 // Component-1 (S_n) -- upwind gas-potential flux on the conserved m_n.
4251 //
4252 // The gas equation is recast in potential form:
4253 // d(phi*rho_n*S_n)/dt + div F_n = source/sink
4254 // F_n = -lambda_n K grad(Phi_n)
4255 // Phi_n = u_w + p_c(S_n) - rho_n g . x
4256 // lambda_n(S_n,p_n) = rho_n(p_n) * k_rn(S_n) / mu_n
4257 // Darcy, capillary, and buoyancy collapse into the single edge flux.
4258 // ============================================================================
4259
4260 // -------- Per-DOF nodal CO2 mass (m_c, mc_old for the lumped mass). --------
4261 // rho_n_phi_dof (= lumped phi*N) and ML_n were projected above for the
4262 // invert(COMPONENT=1) path; reuse them here. Compositional (p,z):
4263 // m_c = (phi*N) * z (= u_n). invert: z = m_c / (phi*N).
4264 std::vector<double> m_n_DOF(numDOFs_n, 0.0);
4265 std::vector<double> mn_n_DOF(numDOFs_n, 0.0);
4266 for (int i_n = 0; i_n < numDOFs_n; i_n++) {
4267 const double sat = u_dof_n.data()[i_n]; // z at DOF i (current)
4268 const double sat_old = u_dof_n_old.data()[i_n]; // z at DOF i (t^n)
4269 m_n_DOF[i_n] = rho_n_phi_dof[i_n] * sat;
4270 mn_n_DOF[i_n] = rho_n_phi_dof_old[i_n] * sat_old; // old mass uses OLD phi*N
4271 mn_n.data()[i_n] = mn_n_DOF[i_n]; // diagnostic
4272 quantDOFs_n.data()[i_n] = 0.0; // reset
4273 }
4274
4275 double diag_sumF = 0.0, diag_absF = 0.0;
4276
4277 // Zero the per-node gas-residual budget (6 slots, term-major over numDOFs_n).
4278 const bool have_gas_budget = (gas_budget_node.size() >= (size_t)(6 * numDOFs_n));
4279 if (have_gas_budget)
4280 for (int s = 0; s < 6 * numDOFs_n; ++s) gas_budget_node.data()[s] = 0.0;
4281
4282 std::vector<double> psi_n(numDOFs_n, 1.0);
4283 if (STABILIZATION_TYPE == STABILIZATION::EV_Stab) {
4284 for (int i_n = 0; i_n < numDOFs_n; i_n++) {
4285 const double zi = u_dof_n_old.data()[i_n];
4286 double num = 0.0, den = 0.0;
4287 for (int offset = csrRowIndeces_n_DofLoops.data()[i_n];
4288 offset < csrRowIndeces_n_DofLoops.data()[i_n + 1]; offset++) {
4289 const int j_n = csrColumnOffsets_n_DofLoops.data()[offset];
4290 if (j_n == i_n) continue;
4291 const double d = zi - u_dof_n_old.data()[j_n];
4292 num += d;
4293 den += fabs(d);
4294 }
4295 const double alpha_i = fabs(num) / (den + 1.0e-15);
4296 psi_n[i_n] = (POWER_SMOOTHNESS_INDICATOR == 0)
4297 ? 1.0 : std::pow(alpha_i, POWER_SMOOTHNESS_INDICATOR);
4298 }
4299 }
4300 std::vector<int> node_iface(numDOFs_n, 0);
4301 {
4302 std::vector<int> node_mat0(numDOFs_n, -1);
4303 for (int eN = 0; eN < nElements_global; eN++) {
4304 const int mat_eN_if = elementMaterialTypes.data()[eN];
4305 for (int a = 0; a < nDOF_trial_element; a++) {
4306 const int gN = u_l2g.data()[eN * nDOF_trial_element + a];
4307 if (node_mat0[gN] < 0) node_mat0[gN] = mat_eN_if;
4308 else if (node_mat0[gN] != mat_eN_if) node_iface[gN] = 1;
4309 }
4310 }
4311 }
4312 auto comp1_offset = [&](int i_n, int j_n) -> int {
4313 for (int off = csrRowIndeces_n_DofLoops.data()[i_n];
4314 off < csrRowIndeces_n_DofLoops.data()[i_n + 1]; ++off)
4315 if (csrColumnOffsets_n_DofLoops.data()[off] == j_n) return off;
4316 return -1;
4317 };
4318 for (int off = 0; off < NNZ_n; ++off) {
4319 dLow_n.data()[off] = 0.0;
4320 dEV_n.data()[off] = 0.0;
4321 dt_times_fH_minus_fL_n.data()[off] = 0.0;
4322 }
4323 std::vector<double> node_Kdiag(numDOFs_n, 0.0);
4324
4325 for (int eN = 0; eN < nElements_global; eN++) {
4326 const int mat_eN = elementMaterialTypes.data()[eN];
4327 const double phi_eN = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
4328 const double alpha_eN = alpha.data()[mat_eN];
4329 const double krn_end_eN = krn_end.data()[mat_eN];
4330 const double n_vg_eN = n.data()[mat_eN];
4331 const double *KWs_eN = &KWs.data()[mat_eN * nnz];
4332 // dm_n_du_n is no longer hoisted: when rho_n is compressible the
4333 // per-DOF lumped diagonal is taken from rho_n_phi_dof, so the
4334 // (1,1) lumped contribution lives inside the per-i loop below.
4335 double elementResidual_n[nDOF_test_element];
4336 // P1: comp-0 (H2O) two-sided water flux residual assembled in THIS element
4337 // loop (replaces the single-nodal-rock DOF-graph water flux). Its (0,0)/
4338 // (0,1) Jacobian scatters directly into globalJacobian via the full CSR
4339 // inside the edge loop (same mapping the DOF-graph loop used).
4340 double elementResidual_w[nDOF_test_element];
4341 double elementMass_n[nDOF_test_element];
4342 double u_n_local[nDOF_trial_element];
4343 double u_n_old_local[nDOF_trial_element];
4344 double elementJacobian_n_n[nDOF_test_element][nDOF_trial_element];
4345 double elementJacobian_n_w[nDOF_test_element][nDOF_trial_element];
4346 // P1 (Richards-style block assembly): the comp-0 (H2O) water-flux
4347 // Jacobian collects into dedicated element arrays and scatters via the
4348 // framework's (0,0)/(0,1) block CSR maps (csr*_w_w / csr*_w_n) with the
4349 // element-local eN_i_j offset -- EXACTLY mirroring the comp-1 (1,1)/(1,0)
4350 // scatter below and Richards.h's direct globalJacobian[ij] write. This
4351 // replaces the old Full-CSR column SEARCH (col==col_n_j ...), which
4352 // silently dropped the (0,1) off-diagonal water<-neighbor-z coupling when
4353 // the hand-computed column index didn't match the matrix layout (the
4354 // "structural misses" in the FD Jacobian probe -> stalled Newton).
4355 double elementJacobian_w_w[nDOF_test_element][nDOF_trial_element];
4356 double elementJacobian_w_n[nDOF_test_element][nDOF_trial_element];
4357 // elementTransport_n collects the mobility-free gas transmissibility
4358 // tau_ij = int K . grad N_j . grad N_i dV
4359 // consumed by the post-element-loop upwind potential-flux edge pass.
4360 // NO rho_n, NO k_rn, NO p_c factors -- those go into lambda_up and
4361 // delta_Phi at the edge level.
4362 double elementTransport_n[nDOF_test_element][nDOF_trial_element];
4363 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
4364 for (int i = 0; i < nDOF_test_element; i++) {
4365 elementResidual_n[i] = 0.0;
4366 elementResidual_w[i] = 0.0;
4367 elementMass_n[i] = 0.0;
4368 for (int j = 0; j < nDOF_trial_element; j++) {
4369 elementJacobian_n_n[i][j] = 0.0;
4370 elementJacobian_n_w[i][j] = 0.0;
4371 elementJacobian_w_w[i][j] = 0.0;
4372 elementJacobian_w_n[i][j] = 0.0;
4373 elementTransport_n[i][j] = 0.0;
4374 }
4375 }
4376 for (int j = 0; j < nDOF_trial_element; j++) {
4377 u_n_local[j] = u_dof_n.data()[u_l2g_n.data()[eN_nDOF_trial_element + j]];
4378 u_n_old_local[j] = u_dof_n_old.data()[u_l2g_n.data()[eN_nDOF_trial_element + j]];
4379 }
4380 for (int k = 0; k < nQuadraturePoints_element; k++) {
4381 double jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], x_q, y_q, z_q;
4382 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(),
4383 mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
4384 jac, jacDet, jacInv, x_q, y_q, z_q);
4385 const double dV = std::fabs(jacDet) * dV_ref.data()[k];
4386 double u_grad_trial_qp[nDOF_trial_element * nSpace];
4387 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace],
4388 jacInv, u_grad_trial_qp);
4389 // Cell loop only accumulates:
4390 // elementMass_n[i] = int N_i dV (lumped row volume, consumed
4391 // below by time-derivative,
4392 // R_diss, Q_inj at element scope)
4393 // elementTransport_n[i][j] = int K . grad N_j . grad N_i dV
4394 // (tau_ij used by the
4395 // post-element-loop upwind
4396 // potential-flux edge pass)
4397 // No closure evaluation, no flux residual, no coefficient sensitivities:
4398 // those collapse into the edge flux F_ij = tau_ij * lambda_up * delta_Phi.
4399 for (int i = 0; i < nDOF_test_element; i++) {
4400 const double test_i = u_test_ref.data()[k * nDOF_test_element + i];
4401 elementMass_n[i] += test_i * dV;
4402 for (int j = 0; j < nDOF_trial_element; j++) {
4403 double K_trial_ij = 0.0;
4404 for (int I = 0; I < nSpace; I++) {
4405 const double grad_Ni_I = u_grad_trial_qp[i * nSpace + I];
4406 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
4407 const int J = a_colind.data()[ii];
4408 K_trial_ij += KWs_eN[ii] * u_grad_trial_qp[j * nSpace + J] * grad_Ni_I;
4409 }
4410 }
4411 elementTransport_n[i][j] += K_trial_ij * dV;
4412 }
4413 }
4414 } // end QP loop
4415
4416 // -------- Lumped mass: ML_n[i] * (m_c - mc_old)/dt on the diagonal. --------
4417 // Applied at element level so it sums to the global lumped mass.
4418 // Compositional (p,z): m_c = (phi*N)*z, with phi*N (and d/dz, d/dp) taken
4419 // from the lumped projections rho_n_phi_dof / dphiN_dz_dof / dphiN_dp_dof.
4420 // dm_c/dz = phi*N + z*phi*dN/dz (1,1) diagonal
4421 // dm_c/dp = z*phi*dN/dp (1,0) diagonal
4422 // Accumulation Jacobian formulas FD-verified in kernel_math_test.cpp (kmtest).
4423 for (int i = 0; i < nDOF_test_element; i++) {
4424 const int gi = u_l2g_n.data()[eN * nDOF_test_element + i]; // comp-1 DOF
4425 node_Kdiag[gi] += fmax(0.0, elementTransport_n[i][i]); // K-weighted nodal conductance
4426 const double phiN_i = rho_n_phi_dof[gi]; // lumped phi*N (current)
4427 const double phiN_old_i= rho_n_phi_dof_old[gi]; // lumped phi*N (t^n)
4428 const double z_i = u_n_local[i];
4429 const double m_n_loc = phiN_i * z_i; // m_c
4430 const double m_n_old_loc = phiN_old_i * u_n_old_local[i]; // m_c_old
4431 elementResidual_n[i] += elementMass_n[i] * (m_n_loc - m_n_old_loc) / dt;
4432 if (have_gas_budget)
4433 gas_budget_node.data()[0 * numDOFs_n + gi] += elementMass_n[i] * (m_n_loc - m_n_old_loc) / dt;
4434 // (1,1): dm_c/dz = phi*N + z*phi*dN/dz.
4435 elementJacobian_n_n[i][i] += elementMass_n[i] * (phiN_i + z_i * dphiN_dz_dof[gi]) / dt;
4436 // (1,0): dm_c/dp = z*phi*dN/dp.
4437 elementJacobian_n_w[i][i] += elementMass_n[i] * (z_i * dphiN_dp_dof[gi]) / dt;
4438 if (inj_point_mode == 0) {
4439 const double Q_inj_n = injection_dof.data()[gi];
4440 elementResidual_n[i] -= elementMass_n[i] * Q_inj_n;
4441 if (have_gas_budget)
4442 gas_budget_node.data()[3 * numDOFs_n + gi] -= elementMass_n[i] * Q_inj_n;
4443 }
4444 }
4445
4446 if (inj_point_mode == 1) {
4447 for (int p = 0; p < inj_n_ports; p++) {
4448 if (inj_element.data()[p] == eN && inj_rate.data()[p] != 0.0) {
4449 const double qp = inj_rate.data()[p];
4450 for (int i = 0; i < nDOF_test_element; i++) {
4451 const double w = inj_weight.data()[p * nDOF_test_element + i];
4452 elementResidual_n[i] -= qp * w;
4453 if (have_gas_budget) {
4454 const int gii = u_l2g_n.data()[eN * nDOF_test_element + i]; // comp-1 DOF
4455 gas_budget_node.data()[3 * numDOFs_n + gii] -= qp * w;
4456 }
4457 }
4458 }
4459 }
4460 }
4461
4462 {
4463 const double S_wr_eN = thetaR.data()[mat_eN] / phi_eN;
4464 const double one_m_Sr_eN = 1.0 - S_wr_eN;
4465 const double Se_trap_L4415 = 1.0 - S_gr.data()[mat_eN] / one_m_Sr_eN; // gas-only residual trapping
4466 // Capillary entry pressure of THIS element's rock, p_d_e = 1/alpha [head].
4467 // The barrier below charges the gas flux the entry-pressure JUMP
4468 // (p_d_e - p_d_coarsest_neighbor) when gas crosses an edge INTO this
4469 // element from a coarser-medium (lower p_d) node.
4470 const double p_d_e = (alpha_eN > 0.0) ? (1.0 / alpha_eN) : 0.0;
4471 // P2 (compositional): per-node closure for the TWO-PHASE CO2 edge flux
4472 // F_1 = F_g + F_a, F_g = tau*lam_g_up*gate*dPhi_g, F_a = tau*lam_a_up*dPhi_a
4473 // lam_g = (krn_end/mu_n)*rho_g*Y*krn, lam_a = rho_a*X*krw (molar)
4474 // dPhi_g = d(p+pc) - rho_g_mass_edge*g.dx, dPhi_a = dp - rho_a_mass_edge*g.dx
4475 // All flash-derived; FD-verified in edge_flux_test.cpp.
4476 int gN_e[nDOF_trial_element]; // mesh-node id (p, geometry)
4477 int zN_e[nDOF_trial_element]; // comp-1 z-DOF
4478 double uw_e[nDOF_trial_element], uw_old_e[nDOF_trial_element];
4479 double pc_e[nDOF_trial_element], pc_old_e[nDOF_trial_element];
4480 double dpc_dp_e[nDOF_trial_element], dpc_dz_e[nDOF_trial_element];
4481 double lam_g_e[nDOF_trial_element], lam_a_e[nDOF_trial_element];
4482 double lam_g_old_e[nDOF_trial_element], lam_a_old_e[nDOF_trial_element];
4483 double dlam_g_dp_e[nDOF_trial_element], dlam_g_dz_e[nDOF_trial_element];
4484 double dlam_a_dp_e[nDOF_trial_element], dlam_a_dz_e[nDOF_trial_element];
4485 // P1: H2O-weighted molar mobilities for the two-sided comp-0 water flux.
4486 // lam_g^w = cg*rho_g*(1-Y)*krn, lam_a^w = rho_a*(1-X)*krw -- same flash /
4487 // krn / krw primitives as the CO2 mobilities, weights flipped Y->(1-Y),
4488 // X->(1-X), no gate. FD-verified in comp0_elem_test.cpp (c0etest).
4489 double lwg_e[nDOF_trial_element], lwa_e[nDOF_trial_element];
4490 double lwg_old_e[nDOF_trial_element], lwa_old_e[nDOF_trial_element];
4491 double dlwg_dp_e[nDOF_trial_element], dlwg_dz_e[nDOF_trial_element];
4492 double dlwa_dp_e[nDOF_trial_element], dlwa_dz_e[nDOF_trial_element];
4493 double rgm_e[nDOF_trial_element], ram_e[nDOF_trial_element];
4494 double rgm_old_e[nDOF_trial_element], ram_old_e[nDOF_trial_element];
4495 double drgm_dp_e[nDOF_trial_element], drgm_dz_e[nDOF_trial_element];
4496 double dram_dp_e[nDOF_trial_element], dram_dz_e[nDOF_trial_element];
4497 double Sg_e[nDOF_trial_element], Sg_old_e[nDOF_trial_element];
4498 double dSg_dp_e[nDOF_trial_element], dSg_dz_e[nDOF_trial_element];
4499 double dlg_dz_o[nDOF_trial_element], dla_dz_o[nDOF_trial_element], dpc_dz_o[nDOF_trial_element]; // old-time z-derivs for lagged graph viscosity
4500 const double cg_eN = krn_end_eN / mu_n;
4502 for (int a = 0; a < nDOF_trial_element; a++) {
4503 const int gN = u_l2g.data()[eN_nDOF_trial_element + a]; // mesh node: p + geometry
4504 const int zN = u_l2g_n.data()[eN_nDOF_trial_element + a]; // comp-1 z-DOF
4505 gN_e[a] = gN;
4506 zN_e[a] = zN;
4507 const double p_a = u_dof.data()[gN];
4508 const double z_a = u_dof_n.data()[zN]; // u_n = z (compositional)
4509 const double p_a_o = u_dof_old.data()[gN];
4510 const double z_a_o = u_dof_n_old.data()[zN];
4511 uw_e[a] = p_a; uw_old_e[a] = p_a_o;
4512 // --- current iterate: flash + closures ---
4513 const double p_cl = fmax(p_a, 1.0e2);
4516 // Gas saturation of THIS element's rock at the vertex: the per-rock
4517 // closure's S_r at interface nodes, the flash's S_g elsewhere.
4518 double Sg_v = f.S_g, dSg_dp_v = f.dS_g_dp, dSg_dz_v = f.dS_g_dz;
4519 if (per_rock && node_multi[zN]) {
4520 const int o = zN * nRock + mat_eN;
4521 Sg_v = rS[o]; dSg_dp_v = rS_dp[o]; dSg_dz_v = rS_dz[o];
4522 }
4523 Sg_e[a] = Sg_v; dSg_dp_e[a] = dSg_dp_v; dSg_dz_e[a] = dSg_dz_v;
4524 const double Sa = 1.0 - Sg_v;
4525 const double Se_raw = (Sa - S_wr_eN) / one_m_Sr_eN;
4526 double Se, dSe_dp, dSe_dz;
4527 if (Se_raw <= 0.0) { Se = 0.0; dSe_dp = 0.0; dSe_dz = 0.0; }
4528 else if (Se_raw >= 1.0) { Se = 1.0; dSe_dp = 0.0; dSe_dz = 0.0; }
4529 else { Se = Se_raw; dSe_dp = -dSg_dp_v/one_m_Sr_eN; dSe_dz = -dSg_dz_v/one_m_Sr_eN; }
4530 double krn=0,dkrn=0,krw=0,dkrw=0,thW=0,DthW=0,pc=0,dpc_dSe=0,d2pc=0;
4531 if (PSK_TYPE_member == 1) {
4532 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se, alpha_eN, n_vg_eN, krn, dkrn, Se_trap_L4415);
4533 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW, DthW, krw, dkrw);
4534 proteus::m_comp_co2::psk::bc_pc_from_Se(Se, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc, dpc_dSe, d2pc);
4535 } else {
4536 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se, alpha_eN, n_vg_eN, krn, dkrn, Se_trap_L4415);
4537 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW, DthW, krw, dkrw);
4538 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se, alpha_eN, n_vg_eN, pc, dpc_dSe, d2pc);
4539 }
4540 pc_e[a] = pc; dpc_dp_e[a] = dpc_dSe*dSe_dp; dpc_dz_e[a] = dpc_dSe*dSe_dz;
4541 const double Mg = f.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-f.Y)*::m_comp_co2::eos::M_H2O_KG;
4542 const double Ma = f.X*::m_comp_co2::eos::M_CO2_KG + (1.0-f.X)*::m_comp_co2::eos::M_H2O_KG;
4543 rgm_e[a] = f.rho_g*Mg; ram_e[a] = f.rho_a*Ma;
4544 drgm_dp_e[a] = f.drho_g_dp*Mg + f.rho_g*f.dY_dp*dMm_e; drgm_dz_e[a] = f.rho_g*f.dY_dz*dMm_e;
4545 dram_dp_e[a] = f.drho_a_dp*Ma + f.rho_a*f.dX_dp*dMm_e; dram_dz_e[a] = f.drho_a_dz*Ma + f.rho_a*f.dX_dz*dMm_e;
4546 // molar mobilities lam_g = cg*rho_g*Y*krn, lam_a = rho_a*X*krw
4547 lam_g_e[a] = cg_eN*f.rho_g*f.Y*krn;
4548 dlam_g_dp_e[a] = cg_eN*(f.drho_g_dp*f.Y*krn + f.rho_g*f.dY_dp*krn + f.rho_g*f.Y*dkrn*dSe_dp);
4549 dlam_g_dz_e[a] = cg_eN*( f.rho_g*f.dY_dz*krn + f.rho_g*f.Y*dkrn*dSe_dz);
4550 lam_a_e[a] = f.rho_a*f.X*krw;
4551 dlam_a_dp_e[a] = f.drho_a_dp*f.X*krw + f.rho_a*f.dX_dp*krw + f.rho_a*f.X*dkrw*dSe_dp;
4552 dlam_a_dz_e[a] = f.drho_a_dz*f.X*krw + f.rho_a*f.dX_dz*krw + f.rho_a*f.X*dkrw*dSe_dz;
4553 // P1: H2O-weighted siblings (1-Y),(1-X) -- same krn/krw/dSe, no gate.
4554 {
4555 const double yw=1.0-f.Y, dyw_dp=-f.dY_dp, dyw_dz=-f.dY_dz;
4556 const double xw=1.0-f.X, dxw_dp=-f.dX_dp, dxw_dz=-f.dX_dz;
4557 lwg_e[a] = cg_eN*f.rho_g*yw*krn;
4558 dlwg_dp_e[a] = cg_eN*(f.drho_g_dp*yw*krn + f.rho_g*dyw_dp*krn + f.rho_g*yw*dkrn*dSe_dp);
4559 dlwg_dz_e[a] = cg_eN*( f.rho_g*dyw_dz*krn + f.rho_g*yw*dkrn*dSe_dz);
4560 lwa_e[a] = f.rho_a*xw*krw;
4561 dlwa_dp_e[a] = f.drho_a_dp*xw*krw + f.rho_a*dxw_dp*krw + f.rho_a*xw*dkrw*dSe_dp;
4562 dlwa_dz_e[a] = f.drho_a_dz*xw*krw + f.rho_a*dxw_dz*krw + f.rho_a*xw*dkrw*dSe_dz;
4563 }
4564 // --- old time level (frozen; feeds the (1-Theta) part, no derivatives) ---
4565 const double p_cl_o = fmax(p_a_o, 1.0e2);
4568 double Sg_v_o = fo.S_g, dSg_dz_v_o = fo.dS_g_dz;
4569 if (per_rock && node_multi[zN]) {
4570 const int o = zN * nRock + mat_eN;
4571 Sg_v_o = rS_o[o]; dSg_dz_v_o = rS_dz_o[o];
4572 }
4573 Sg_old_e[a] = Sg_v_o;
4574 const double Sa_o = 1.0 - Sg_v_o;
4575 const double Se_o_raw = (Sa_o - S_wr_eN) / one_m_Sr_eN;
4576 const double Se_o = Se_o_raw <= 0.0 ? 0.0 : (Se_o_raw >= 1.0 ? 1.0 : Se_o_raw);
4577 double krn_o=0,dkrn_o=0,krw_o=0,dkrw_o=0,thW_o=0,DthW_o=0,pc_o=0,dpc_o=0,d2pc_o=0;
4578 if (PSK_TYPE_member == 1) {
4579 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_o, alpha_eN, n_vg_eN, krn_o, dkrn_o, Se_trap_L4415);
4580 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_o, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_o, DthW_o, krw_o, dkrw_o);
4581 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_o, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc_o, dpc_o, d2pc_o);
4582 } else {
4583 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_o, alpha_eN, n_vg_eN, krn_o, dkrn_o, Se_trap_L4415);
4584 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_o, alpha_eN, n_vg_eN, thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_o, DthW_o, krw_o, dkrw_o);
4585 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_o, alpha_eN, n_vg_eN, pc_o, dpc_o, d2pc_o);
4586 }
4587 pc_old_e[a] = pc_o;
4588 const double Mg_o = fo.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fo.Y)*::m_comp_co2::eos::M_H2O_KG;
4589 const double Ma_o = fo.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fo.X)*::m_comp_co2::eos::M_H2O_KG;
4590 rgm_old_e[a] = fo.rho_g*Mg_o; ram_old_e[a] = fo.rho_a*Ma_o;
4591 lam_g_old_e[a] = cg_eN*fo.rho_g*fo.Y*krn_o;
4592 lam_a_old_e[a] = fo.rho_a*fo.X*krw_o;
4593 lwg_old_e[a] = cg_eN*fo.rho_g*(1.0-fo.Y)*krn_o; // P1: H2O old-time
4594 lwa_old_e[a] = fo.rho_a*(1.0-fo.X)*krw_o;
4595 const double dSe_o = (Se_o_raw>0.0 && Se_o_raw<1.0) ? -dSg_dz_v_o/one_m_Sr_eN : 0.0;
4596 dlg_dz_o[a] = cg_eN*(fo.rho_g*fo.dY_dz*krn_o + fo.rho_g*fo.Y*dkrn_o*dSe_o);
4597 dla_dz_o[a] = fo.drho_a_dz*fo.X*krw_o + fo.rho_a*fo.dX_dz*krw_o + fo.rho_a*fo.X*dkrw_o*dSe_o;
4598 dpc_dz_o[a] = dpc_o*dSe_o;
4599 }
4600 // Edge pair flux. tau^e is symmetric and lambda_up picks the same
4601 // physical upstream node for (i,j) and (j,i), so F^e_ij = -F^e_ji
4602 // (per-element conservation; summing the <=2 elements sharing an edge
4603 // reconstructs the full two-sided edge flux).
4604 for (int i = 0; i < nDOF_test_element; i++) {
4605 for (int j = 0; j < nDOF_trial_element; j++) {
4606 if (i == j) continue;
4607 const double tau = fmax(0.0, -elementTransport_n[i][j]);
4608 if (tau == 0.0) continue;
4609 double g_dot_dx = 0.0;
4610 for (int I = 0; I < nSpace; I++) {
4611 g_dot_dx += gravity.data()[I] * (mesh_dof.data()[gN_e[j] * 3 + I]
4612 - mesh_dof.data()[gN_e[i] * 3 + I]);
4613 }
4614 // ===================== GAS branch (free CO2, gated) ================
4615 // lam_g = rho_g*Y*krn*krn_end/mu_n ; dPhi_g = d(p+pc) - rho_g_mass*g.dx
4616 const double rgm_edge = 0.5 * (rgm_e[i] + rgm_e[j]);
4617 const double rgm_edge_old = 0.5 * (rgm_old_e[i] + rgm_old_e[j]);
4618 const double dPhi_g = (uw_e[j] + pc_e[j]) - (uw_e[i] + pc_e[i])
4619 - rgm_edge * g_dot_dx;
4620 const double dPhi_g_old = (uw_old_e[j] + pc_old_e[j]) - (uw_old_e[i] + pc_old_e[i])
4621 - rgm_edge_old * g_dot_dx;
4622 const bool up_i_g = (dPhi_g <= 0.0);
4623 const bool up_i_g_old = (dPhi_g_old <= 0.0);
4624 const double lam_g_up = up_i_g ? lam_g_e[i] : lam_g_e[j];
4625 const double lam_g_up_old = up_i_g_old ? lam_g_old_e[i] : lam_g_old_e[j];
4626 // GATE-FREE gas branch -- the capillary entry-pressure valve is DELETED.
4627 // With one z (hence one S_g) per node, a node shared by several rocks
4628 // does not represent the capillary-pressure jump; see
4629 // Z_ACROSS_ROCK_INTERFACES.md. No node_pd_min / node_Sn_max valve, no
4630 // gate Jacobian, no smoothstep.
4631 const double Fg = Theta * tau * lam_g_up * dPhi_g
4632 + (1.0 - Theta) * tau * lam_g_up_old * dPhi_g_old;
4633 // ================= AQUEOUS branch (dissolved CO2, no gate) =========
4634 // lam_a = rho_a*X*krw ; dPhi_a = dp - rho_a_mass*g.dx
4635 const double ram_edge = 0.5 * (ram_e[i] + ram_e[j]);
4636 const double ram_edge_old = 0.5 * (ram_old_e[i] + ram_old_e[j]);
4637 const double dPhi_a = uw_e[j] - uw_e[i] - ram_edge * g_dot_dx;
4638 const double dPhi_a_old = uw_old_e[j] - uw_old_e[i] - ram_edge_old * g_dot_dx;
4639 const bool up_i_a = (dPhi_a <= 0.0);
4640 const bool up_i_a_old = (dPhi_a_old <= 0.0);
4641 const double lam_a_up = up_i_a ? lam_a_e[i] : lam_a_e[j];
4642 const double lam_a_up_old = up_i_a_old ? lam_a_old_e[i] : lam_a_old_e[j];
4643 const double Fa = Theta * tau * lam_a_up * dPhi_a
4644 + (1.0 - Theta) * tau * lam_a_up_old * dPhi_a_old;
4645 // R_n[i] -= F_g + F_a.
4646 elementResidual_n[i] -= Fg + Fa;
4647 if (have_gas_budget)
4648 gas_budget_node.data()[1 * numDOFs_n + zN_e[i]] -= Fg + Fa;
4649 diag_sumF += Fg + Fa;
4650 diag_absF += std::fabs(Fg + Fa);
4651 // ===== Theta-part Jacobian wrt (p_i,z_i,p_j,z_j). FD-verified. =====
4652 const double ddPhig_dpi = -1.0 - dpc_dp_e[i] - 0.5 * drgm_dp_e[i] * g_dot_dx;
4653 const double ddPhig_dzi = - dpc_dz_e[i] - 0.5 * drgm_dz_e[i] * g_dot_dx;
4654 const double ddPhig_dpj = +1.0 + dpc_dp_e[j] - 0.5 * drgm_dp_e[j] * g_dot_dx;
4655 const double ddPhig_dzj = + dpc_dz_e[j] - 0.5 * drgm_dz_e[j] * g_dot_dx;
4656 const double ddPhia_dpi = -1.0 - 0.5 * dram_dp_e[i] * g_dot_dx;
4657 const double ddPhia_dzi = - 0.5 * dram_dz_e[i] * g_dot_dx;
4658 const double ddPhia_dpj = +1.0 - 0.5 * dram_dp_e[j] * g_dot_dx;
4659 const double ddPhia_dzj = - 0.5 * dram_dz_e[j] * g_dot_dx;
4660 const double Tt = Theta * tau;
4661 double dF_dpi = 0.0, dF_dzi = 0.0, dF_dpj = 0.0, dF_dzj = 0.0;
4662 // gas potential part (all four DOFs) -- gate-free
4663 dF_dpi += Tt*lam_g_up*ddPhig_dpi; dF_dzi += Tt*lam_g_up*ddPhig_dzi;
4664 dF_dpj += Tt*lam_g_up*ddPhig_dpj; dF_dzj += Tt*lam_g_up*ddPhig_dzj;
4665 // gas mobility part (upstream node only)
4666 if (up_i_g) { dF_dpi += Tt*dlam_g_dp_e[i]*dPhi_g; dF_dzi += Tt*dlam_g_dz_e[i]*dPhi_g; }
4667 else { dF_dpj += Tt*dlam_g_dp_e[j]*dPhi_g; dF_dzj += Tt*dlam_g_dz_e[j]*dPhi_g; }
4668 // (gate Jacobian removed with the gate)
4669 // aqueous potential part (all four DOFs)
4670 dF_dpi += Tt*lam_a_up*ddPhia_dpi; dF_dzi += Tt*lam_a_up*ddPhia_dzi;
4671 dF_dpj += Tt*lam_a_up*ddPhia_dpj; dF_dzj += Tt*lam_a_up*ddPhia_dzj;
4672 // aqueous mobility part (upstream node only)
4673 if (up_i_a) { dF_dpi += Tt*dlam_a_dp_e[i]*dPhi_a; dF_dzi += Tt*dlam_a_dz_e[i]*dPhi_a; }
4674 else { dF_dpj += Tt*dlam_a_dp_e[j]*dPhi_a; dF_dzj += Tt*dlam_a_dz_e[j]*dPhi_a; }
4675 // dR_n[i]/dx = -dF/dx. (1,1) = z columns, (1,0) = p columns.
4676 elementJacobian_n_n[i][i] += -dF_dzi;
4677 elementJacobian_n_n[i][j] += -dF_dzj;
4678 elementJacobian_n_w[i][i] += -dF_dpi;
4679 elementJacobian_n_w[i][j] += -dF_dpj;
4680 // ===== P1: comp-0 (H2O) two-sided water flux F_0^e = F_g^w + F_a^w.
4681 // Reuses THIS edge's dPhi_g/dPhi_a/tau and the SAME upstream switches
4682 // (phase potentials are composition-independent); only the mobilities
4683 // change to the H2O weights lwg=cg*rho_g*(1-Y)*krn, lwa=rho_a*(1-X)*krw.
4684 // NO gate (matches the verified comp-0 kernel c0test/c0etest; the
4685 // (1-Y) gas branch is water vapor ~ 0 anyway). R_w[i] -= F_0^e and the
4686 // (0,0)/(0,1) Jacobian scatter into comp-0 rows via the full CSR -- the
4687 // SAME mapping the retired single-nodal DOF-graph water loop used. The
4688 // water MASS + Dirichlet identity stay in the DOF-graph accumulation.
4689 {
4690 const double lwg_up = up_i_g ? lwg_e[i] : lwg_e[j];
4691 const double lwg_up_old = up_i_g_old ? lwg_old_e[i] : lwg_old_e[j];
4692 const double lwa_up = up_i_a ? lwa_e[i] : lwa_e[j];
4693 const double lwa_up_old = up_i_a_old ? lwa_old_e[i] : lwa_old_e[j];
4694 const double Fwg = Theta * tau * lwg_up * dPhi_g
4695 + (1.0 - Theta) * tau * lwg_up_old * dPhi_g_old;
4696 const double Fwa = Theta * tau * lwa_up * dPhi_a
4697 + (1.0 - Theta) * tau * lwa_up_old * dPhi_a_old;
4698 elementResidual_w[i] -= Fwg + Fwa;
4699 // Theta-part Jacobian wrt (p_i,z_i,p_j,z_j) (gate=1, no gate deriv).
4700 double dFw_dpi=0.0, dFw_dzi=0.0, dFw_dpj=0.0, dFw_dzj=0.0;
4701 dFw_dpi += Tt*lwg_up*ddPhig_dpi; dFw_dzi += Tt*lwg_up*ddPhig_dzi;
4702 dFw_dpj += Tt*lwg_up*ddPhig_dpj; dFw_dzj += Tt*lwg_up*ddPhig_dzj;
4703 if (up_i_g) { dFw_dpi += Tt*dlwg_dp_e[i]*dPhi_g; dFw_dzi += Tt*dlwg_dz_e[i]*dPhi_g; }
4704 else { dFw_dpj += Tt*dlwg_dp_e[j]*dPhi_g; dFw_dzj += Tt*dlwg_dz_e[j]*dPhi_g; }
4705 dFw_dpi += Tt*lwa_up*ddPhia_dpi; dFw_dzi += Tt*lwa_up*ddPhia_dzi;
4706 dFw_dpj += Tt*lwa_up*ddPhia_dpj; dFw_dzj += Tt*lwa_up*ddPhia_dzj;
4707 if (up_i_a) { dFw_dpi += Tt*dlwa_dp_e[i]*dPhi_a; dFw_dzi += Tt*dlwa_dz_e[i]*dPhi_a; }
4708 else { dFw_dpj += Tt*dlwa_dp_e[j]*dPhi_a; dFw_dzj += Tt*dlwa_dz_e[j]*dPhi_a; }
4709 // Richards-style block scatter: accumulate into the element
4710 // (0,0)/(0,1) arrays; the end-of-element loop loads them into the
4711 // global Jacobian via the framework's csr*_w_w / csr*_w_n block
4712 // maps (eN_i_j offset), so the off-diagonal water<-neighbor-z
4713 // slot is ALWAYS hit (no column search, no dropped coupling).
4714 // Dirichlet mask uses the comp-0 free-DOF tag of the test node.
4715 const int fi = r_l2g.data()[eN_nDOF_trial_element + i];
4716 const double mwi = bc_mask.data()[fi];
4717 elementJacobian_w_w[i][i] += mwi * (-dFw_dpi);
4718 elementJacobian_w_w[i][j] += mwi * (-dFw_dpj);
4719 elementJacobian_w_n[i][i] += mwi * (-dFw_dzi);
4720 elementJacobian_w_n[i][j] += mwi * (-dFw_dzj);
4721 }
4722 // Consistent STAB=2: lagged, PHASE-SPLIT graph viscosity on z.
4723 // Split into a GAS part and an AQUEOUS (dissolved-CO2) part so each
4724 // is gated like the flux branch it stabilizes:
4725 // * gas part -> multiplied by gate_old, so it vanishes across a
4726 // sand->seal entry-pressure jump and does NOT diffuse free CO2
4727 // through the seal (gas pools & spreads laterally as intended).
4728 // * aqueous part -> NOT gated. The aqueous flux Fa = tau*lam_a*dPhi_a
4729 // has no gate (dissolved CO2 freely crosses the interface with the
4730 // brine), so its stabilization must stay ON across interfaces too.
4731 // Gating it (the old `*gate_old` on the whole dvg) switched off all
4732 // z-dissipation exactly at sand interfaces, leaving the ungated
4733 // aqueous advection unstabilized -> interface-aligned z (=> c)
4734 // fingers in the dissolved tongues. This split removes them while
4735 // preserving the seal barrier for the gas.
4736 // Old-time coeff => constant in Newton => the +d/-d Jacobian is exact;
4737 // antisymmetric => global CO2 mass conserved.
4738 const double si_g = std::fabs(dlg_dz_o[i])*std::fabs(dPhi_g_old)
4739 + std::fabs(lam_g_old_e[i])*std::fabs(dpc_dz_o[i]);
4740 const double si_a = std::fabs(dla_dz_o[i])*std::fabs(dPhi_a_old);
4741 const double sj_g = std::fabs(dlg_dz_o[j])*std::fabs(dPhi_g_old)
4742 + std::fabs(lam_g_old_e[j])*std::fabs(dpc_dz_o[j]);
4743 const double sj_a = std::fabs(dla_dz_o[j])*std::fabs(dPhi_a_old);
4744 const double psi_edge = fmax(psi_n[zN_e[i]], psi_n[zN_e[j]]);
4745 const double dEV = tau * ( cE*psi_edge*fmax(si_g,sj_g)
4746 + cE*psi_edge*fmax(si_a,sj_a) );
4747 const double dLow = tau * ( fmax(si_g,sj_g) + fmax(si_a,sj_a) );
4748 const double dHi = fmin(dEV, dLow); // high-order target, clamped <= dLow
4749 const double dResid = (FCT_n == 1) ? dLow : dEV;
4750 if (dResid > 0.0) {
4751 const double Fv = dResid*(u_dof_n.data()[zN_e[j]] - u_dof_n.data()[zN_e[i]]);
4752 elementResidual_n[i] -= Fv;
4753 elementJacobian_n_n[i][i] += dResid;
4754 elementJacobian_n_n[i][j] -= dResid;
4755 }
4756 if (FCT_n == 1) {
4757 const int off_n = comp1_offset(zN_e[i], zN_e[j]);
4758 if (off_n >= 0) {
4759 const double dz = u_dof_n.data()[zN_e[j]] - u_dof_n.data()[zN_e[i]];
4760 dLow_n.data()[off_n] += dLow;
4761 dEV_n.data()[off_n] += dHi;
4762 dt_times_fH_minus_fL_n.data()[off_n] += dt * (dLow - dHi) * dz;
4763 }
4764 }
4765 }
4766 }
4767 }
4768
4769 // -------- Distribute element arrays to global storage. --------
4770 for (int i = 0; i < nDOF_test_element; i++) {
4771 const int eN_i = eN * nDOF_test_element + i;
4772 const int gi = u_l2g_n.data()[eN_i]; // comp-1 DOF (residual + budget)
4773 globalResidual.data()[offset_n + stride_n * gi] += elementResidual_n[i];
4774 if (have_gas_budget)
4775 gas_budget_node.data()[5 * numDOFs_n + gi] += elementResidual_n[i];
4776 // P1: comp-0 (H2O) two-sided water flux residual (Dirichlet-masked).
4777 const int fi_w = r_l2g.data()[eN_nDOF_trial_element + i];
4778 globalResidual.data()[offset_u + stride_u * fi_w] += bc_mask.data()[fi_w] * elementResidual_w[i];
4779 for (int j = 0; j < nDOF_trial_element; j++) {
4780 const int eN_i_j = eN_i * nDOF_trial_element + j;
4781 globalJacobian.data()[csrRowIndeces_n_n.data()[eN_i] + csrColumnOffsets_n_n.data()[eN_i_j]]
4782 += elementJacobian_n_n[i][j];
4783 globalJacobian.data()[csrRowIndeces_n_w.data()[eN_i] + csrColumnOffsets_n_w.data()[eN_i_j]]
4784 += elementJacobian_n_w[i][j];
4785 globalJacobian.data()[csrRowIndeces_w_w.data()[eN_i] + csrColumnOffsets_w_w.data()[eN_i_j]]
4786 += elementJacobian_w_w[i][j];
4787 globalJacobian.data()[csrRowIndeces_w_n.data()[eN_i] + csrColumnOffsets_w_n.data()[eN_i_j]]
4788 += elementJacobian_w_n[i][j];
4789 }
4790 }
4791 }
4792
4793 for (int i_n = 0; i_n < numDOFs_n; i_n++) {
4794 mLow_n.data()[i_n] = m_n_DOF[i_n];
4795 mDotLow_n.data()[i_n] = (m_n_DOF[i_n] - mn_n.data()[i_n]) / dt;
4796 }
4797
4798 // DIAG: net gas-flux imbalance (Python prints + MPI-reduces). The T-asymmetry
4799 // probes [0]/[1] retired with the DOF-graph loop; [2]=sum F, [3]=sum|F|.
4800 if (gas_diag.size() >= 4) {
4801 gas_diag.data()[0] = 0.0;
4802 gas_diag.data()[1] = 0.0;
4803 gas_diag.data()[2] = diag_sumF;
4804 gas_diag.data()[3] = diag_absF;
4805 }
4806
4807
4808 // ============================================================================
4809 // Comp-1 (CO2 / z) exterior boundary loop -- STAB=2 path. COMPOSITIONAL.
4810 //
4811 // P3c STATUS: BOUNDARY PORTED (2026-06-06). Slot 1 is the overall CO2
4812 // composition z, NOT a saturation. This loop computes the compositional
4813 // molar CO2 trace flux F_1.n, mirroring the FD-verified interior element
4814 // flux (calculateResidual / calculateJacobian, lines ~1119/1942):
4815 // F_1 = rho_g*Y*u_g + rho_a*X*u_a,
4816 // u_a = -(K krw/mu_w)(grad p - rho_a_mass g), p_a = p
4817 // u_g = -(K krg/mu_g)(grad p + pc'(S_a) grad S_a - rho_g_mass g),
4818 // grad S_a = -(dSg/dp grad p + dSg/dz grad z),
4819 // with every saturation-dependent property recomputed from the FLASH
4820 // saturation S_g(p,z) (psk closures take the wetting Se_a = (1-S_g-S_wr)/
4821 // (1-S_wr)). The surface term from integrating div(F_1) by parts is
4822 // +(F_1.n) N_i dS, so the residual mirrors the interior with gradN_i -> n.
4823 //
4824 // BC handling: a Nitsche-style penalty drives z at the trace toward the
4825 // prescribed bc_u_n_ext_b (= z_BC) on Dirichlet-z faces (isDir_n != 0;
4826 // McWhorter-Sunada inlet). No-Dirichlet faces are no-flow (F_1.n = 0) so a
4827 // closed box conserves mass.
4828 //
4829 // Jacobian contributions (chain rule through the analytic flash; interior
4830 // gradN_i replaced by the boundary normal n_I):
4831 // (1,1) self : d(F_1.n)/dz (value-block * trial_j + grad-block . gradN_j)
4832 // + Dirichlet penalty * trial_j.
4833 // (1,0) cross : d(F_1.n)/dp (value-block * trial_j + grad-block . gradN_j).
4834 //
4835 // NOTE: structurally a consistent CG/Nitsche trace flux (lambda at the
4836 // trace, no upwind), not the interior edge-based upwind potential flux. A
4837 // ghost-node TPFA boundary (F_b = tau_b lambda_up (Phi_BC - Phi_trace)) is
4838 // the eventual sharper form; see [[m_comp_co2_stab2_upwind_potential_flux]].
4839 // Closure dispatch uses PSK_TYPE_member set at the top of this routine.
4840 // ============================================================================
4841 for (int ebNE = 0; ebNE < nExteriorElementBoundaries_global; ebNE++) {
4842 const int ebN = exteriorElementBoundariesArray.data()[ebNE];
4843 const int eN = elementBoundaryElementsArray.data()[ebN * 2 + 0];
4844 const int ebN_local = elementBoundaryLocalElementBoundariesArray.data()[ebN * 2 + 0];
4845 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
4846 const int mat_eN = elementMaterialTypes.data()[eN];
4847 const double phi_eN = thetaR.data()[mat_eN] + thetaSR.data()[mat_eN];
4848 const double alpha_eN = alpha.data()[mat_eN];
4849 const double krn_end_eN = krn_end.data()[mat_eN];
4850 const double n_vg_eN = n.data()[mat_eN];
4851 const double *KWs_eN = &KWs.data()[mat_eN * nnz];
4852 const double S_wr_loc = thetaR.data()[mat_eN] / phi_eN;
4853 const double one_m_Sr_loc = 1.0 - S_wr_loc;
4854 const double Se_trap_L4846 = 1.0 - S_gr.data()[mat_eN] / one_m_Sr_loc; // gas-only residual trapping
4855
4856 double elementResidual_n_eb[nDOF_test_element];
4857 double elementJacobian_n_n_eb[nDOF_test_element][nDOF_trial_element];
4858 double elementJacobian_n_w_eb[nDOF_test_element][nDOF_trial_element];
4859 for (int i = 0; i < nDOF_test_element; i++) {
4860 elementResidual_n_eb[i] = 0.0;
4861 for (int j = 0; j < nDOF_trial_element; j++) {
4862 elementJacobian_n_n_eb[i][j] = 0.0;
4863 elementJacobian_n_w_eb[i][j] = 0.0;
4864 }
4865 }
4866
4867 for (int kb = 0; kb < nQuadraturePoints_elementBoundary; kb++) {
4868 const int ebNE_kb = ebNE * nQuadraturePoints_elementBoundary + kb;
4869 const int ebN_local_kb = ebN_local * nQuadraturePoints_elementBoundary + kb;
4870 const int ebN_local_kb_nSpace = ebN_local_kb * nSpace;
4871
4872 double jac_ext[nSpace * nSpace], jacDet_ext, jacInv_ext[nSpace * nSpace];
4873 double boundaryJac_b[nSpace * (nSpace - 1)];
4874 double metricTensor_b[(nSpace - 1) * (nSpace - 1)];
4875 double metricTensorDetSqrt_b, dS_eb, normal_b[3];
4876 double xt_b, yt_b, zt_b, integralScaling_b;
4877 double x_eb, y_eb, z_eb;
4878 ck.calculateMapping_elementBoundary(eN, ebN_local, kb, ebN_local_kb,
4879 mesh_dof.data(), mesh_l2g.data(), mesh_trial_trace_ref.data(),
4880 mesh_grad_trial_trace_ref.data(), boundaryJac_ref.data(),
4881 jac_ext, jacDet_ext, jacInv_ext, boundaryJac_b, metricTensor_b,
4882 metricTensorDetSqrt_b, normal_ref.data(), normal_b,
4883 x_eb, y_eb, z_eb);
4884 ck.calculateMappingVelocity_elementBoundary(eN, ebN_local, kb, ebN_local_kb,
4885 mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_trace_ref.data(),
4886 xt_b, yt_b, zt_b, normal_b, boundaryJac_b, metricTensor_b,
4887 integralScaling_b);
4888 dS_eb = ((1.0 - MOVING_DOMAIN) * metricTensorDetSqrt_b
4889 + MOVING_DOMAIN * integralScaling_b) * dS_ref.data()[kb];
4890
4891 // Trace solution and gradients.
4892 double u_grad_trial_trace_b[nDOF_trial_element * nSpace];
4893 ck.gradTrialFromRef(
4894 &u_grad_trial_trace_ref.data()[ebN_local_kb_nSpace * nDOF_trial_element],
4895 jacInv_ext, u_grad_trial_trace_b);
4896 double u_w_ext_b = 0.0, u_n_ext_b = 0.0;
4897 double grad_u_w_ext_b[nSpace], grad_u_n_ext_b[nSpace];
4898 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element],
4899 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element],
4900 u_w_ext_b);
4901 ck.valFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
4902 &u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element],
4903 u_n_ext_b);
4904 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element],
4905 u_grad_trial_trace_b, grad_u_w_ext_b);
4906 ck.gradFromDOF(u_dof_n.data(), &u_l2g.data()[eN_nDOF_trial_element],
4907 u_grad_trial_trace_b, grad_u_n_ext_b);
4908
4909 // Dirichlet target for u_n (no-op when isDOFBoundary_n == 0).
4910 const int isDir_n = isDOFBoundary_n.data()[ebNE_kb];
4911 const double bc_u_n_ext_b = isDir_n * ebqe_bc_u_n_ext.data()[ebNE_kb]
4912 + (1 - isDir_n) * u_n_ext_b;
4913
4914
4915 const double p_clb = fmax(u_w_ext_b, 1.0e2);
4918 double S_g_b = fsb.S_g, dSgb_dp = fsb.dS_g_dp, dSgb_dz = fsb.dS_g_dz;
4919 // Per-rock closure: with vertex (Lobatto) boundary quadrature this point is
4920 // a face vertex; at an interface node read this element's rock's S_r.
4921 if (per_rock) {
4922 int a_v = -1;
4923 for (int a = 0; a < nDOF_trial_element; a++)
4924 if (u_trial_trace_ref.data()[ebN_local_kb * nDOF_test_element + a] > 1.0 - 1.0e-12) a_v = a;
4925 if (a_v < 0)
4926 throw std::runtime_error("m_comp_co2: per_rock_closure needs vertex (Lobatto) boundary quadrature");
4927 const int gv = u_l2g.data()[eN_nDOF_trial_element + a_v];
4928 if (node_multi[gv]) {
4929 const int o = gv * nRock + mat_eN;
4930 S_g_b = rS[o]; dSgb_dp = rS_dp[o]; dSgb_dz = rS_dz[o];
4931 }
4932 }
4933 const double Sa_b = 1.0 - S_g_b;
4934 // wetting effective saturation from the FLASH saturation + (p,z) derivs.
4935 const double Se_raw_b = (Sa_b - S_wr_loc) / one_m_Sr_loc;
4936 double Se_b, dSe_dp_b, dSe_dz_b;
4937 if (Se_raw_b <= 0.0) { Se_b = 0.0; dSe_dp_b = 0.0; dSe_dz_b = 0.0; }
4938 else if (Se_raw_b >= 1.0) { Se_b = 1.0; dSe_dp_b = 0.0; dSe_dz_b = 0.0; }
4939 else { Se_b = Se_raw_b; dSe_dp_b = -dSgb_dp/one_m_Sr_loc; dSe_dz_b = -dSgb_dz/one_m_Sr_loc; }
4940 double KWr_b=0.0, DKWr_b=0.0, thW_b=0.0, DthW_b=0.0, KNr_b=0.0, DKNr_b=0.0;
4941 double pc_b=0.0, dpc_dSe_b=0.0, d2pc_b=0.0;
4942 if (PSK_TYPE_member == 1) {
4943 proteus::m_comp_co2::psk::bc_wetting_from_Se(Se_b, alpha_eN, n_vg_eN,
4944 thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_b, DthW_b, KWr_b, DKWr_b);
4945 proteus::m_comp_co2::psk::bc_kr_nonwetting_from_Se(Se_b, alpha_eN, n_vg_eN, KNr_b, DKNr_b, Se_trap_L4846);
4946 proteus::m_comp_co2::psk::bc_pc_from_Se(Se_b, alpha_eN, n_vg_eN, bc_Se_min.data()[mat_eN], pc_b, dpc_dSe_b, d2pc_b);
4947 } else {
4948 proteus::m_comp_co2::psk::vgm_wetting_from_Se(Se_b, alpha_eN, n_vg_eN,
4949 thetaR.data()[mat_eN], thetaSR.data()[mat_eN], thW_b, DthW_b, KWr_b, DKWr_b);
4950 proteus::m_comp_co2::psk::vgm_kr_nonwetting_from_Se(Se_b, alpha_eN, n_vg_eN, KNr_b, DKNr_b, Se_trap_L4846);
4951 proteus::m_comp_co2::psk::vgm_pc_from_Se(Se_b, alpha_eN, n_vg_eN, pc_b, dpc_dSe_b, d2pc_b);
4952 }
4953 KNr_b *= krn_end_eN; DKNr_b *= krn_end_eN;
4954 const double pcp_b = dpc_dSe_b / one_m_Sr_loc; // pc'(S_a)
4955 const double dpcp_dp_b = (d2pc_b / one_m_Sr_loc) * dSe_dp_b; // d pc'(S_a)/dp
4956 const double dpcp_dz_b = (d2pc_b / one_m_Sr_loc) * dSe_dz_b;
4957 // mass densities for gravity (molar density * mean molar mass) + derivs.
4959 const double Mbar_g_b = fsb.Y*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb.Y)*::m_comp_co2::eos::M_H2O_KG;
4960 const double Mbar_a_b = fsb.X*::m_comp_co2::eos::M_CO2_KG + (1.0-fsb.X)*::m_comp_co2::eos::M_H2O_KG;
4961 const double rho_g_mass_b = fsb.rho_g*Mbar_g_b, rho_a_mass_b = fsb.rho_a*Mbar_a_b;
4962 const double drgm_dp_b = fsb.drho_g_dp*Mbar_g_b + fsb.rho_g*fsb.dY_dp*dMm_b;
4963 const double drgm_dz_b = fsb.rho_g*fsb.dY_dz*dMm_b;
4964 const double dram_dp_b = fsb.drho_a_dp*Mbar_a_b + fsb.rho_a*fsb.dX_dp*dMm_b;
4965 const double dram_dz_b = fsb.drho_a_dz*Mbar_a_b + fsb.rho_a*fsb.dX_dz*dMm_b;
4966 // CO2 transport coefficients Ag=rho_g*Y, Aa=rho_a*X + (p,z) derivatives.
4967 const double Ag = fsb.rho_g*fsb.Y, Aa = fsb.rho_a*fsb.X;
4968 const double dAg_dp = fsb.drho_g_dp*fsb.Y + fsb.rho_g*fsb.dY_dp;
4969 const double dAg_dz = fsb.rho_g*fsb.dY_dz;
4970 const double dAa_dp = fsb.drho_a_dp*fsb.X + fsb.rho_a*fsb.dX_dp;
4971 const double dAa_dz = fsb.drho_a_dz*fsb.X + fsb.rho_a*fsb.dX_dz;
4972 // per-direction Darcy velocities ug[I], ua[I] + value-block partials
4973 // (gradients held fixed). Mobilities carry the 1/mu_n (gas) factor.
4974 double ug_b[nSpace], ua_b[nSpace];
4975 double dug_dp_b[nSpace], dug_dz_b[nSpace], dua_dp_b[nSpace], dua_dz_b[nSpace];
4976 for (int I = 0; I < nSpace; I++) {
4977 double ugI=0.0, uaI=0.0, dugp=0.0, dugz=0.0, duap=0.0, duaz=0.0;
4978 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
4979 const int J = a_colind.data()[ii];
4980 const double Kii = KWs_eN[ii];
4981 const double Mob_g = KNr_b*Kii/mu_n, Mob_a = KWr_b*Kii;
4982 const double dMobg_dp = (DKNr_b*Kii/mu_n)*dSe_dp_b, dMobg_dz = (DKNr_b*Kii/mu_n)*dSe_dz_b;
4983 const double dMoba_dp = (DKWr_b*Kii)*dSe_dp_b, dMoba_dz = (DKWr_b*Kii)*dSe_dz_b;
4984 const double gJ = gravity.data()[J];
4985 const double gradSa = -(dSgb_dp*grad_u_w_ext_b[J] + dSgb_dz*grad_u_n_ext_b[J]);
4986 const double gp_a = grad_u_w_ext_b[J] - rho_a_mass_b*gJ;
4987 const double gp_g = grad_u_w_ext_b[J] + pcp_b*gradSa - rho_g_mass_b*gJ;
4988 ugI -= Mob_g*gp_g; uaI -= Mob_a*gp_a;
4989 const double dgradSa_dp = -(fsb.d2S_g_dp2 *grad_u_w_ext_b[J] + fsb.d2S_g_dpdz*grad_u_n_ext_b[J]);
4990 const double dgradSa_dz = -(fsb.d2S_g_dpdz*grad_u_w_ext_b[J] + fsb.d2S_g_dz2 *grad_u_n_ext_b[J]);
4991 const double dgpg_dp = dpcp_dp_b*gradSa + pcp_b*dgradSa_dp - drgm_dp_b*gJ;
4992 const double dgpg_dz = dpcp_dz_b*gradSa + pcp_b*dgradSa_dz - drgm_dz_b*gJ;
4993 dugp -= dMobg_dp*gp_g + Mob_g*dgpg_dp;
4994 dugz -= dMobg_dz*gp_g + Mob_g*dgpg_dz;
4995 duap -= dMoba_dp*gp_a + Mob_a*(-dram_dp_b*gJ);
4996 duaz -= dMoba_dz*gp_a + Mob_a*(-dram_dz_b*gJ);
4997 }
4998 ug_b[I]=ugI; ua_b[I]=uaI;
4999 dug_dp_b[I]=dugp; dug_dz_b[I]=dugz; dua_dp_b[I]=duap; dua_dz_b[I]=duaz;
5000 }
5001
5002 // F_1 . n at this QP (consistent flux, before the penalty term which
5003 // depends only on the test-function row).
5004 double F_n_dot_n = 0.0;
5005 for (int I = 0; I < nSpace; I++) {
5006 F_n_dot_n += (Ag*ug_b[I] + Aa*ua_b[I]) * normal_b[I];
5007 }
5008 // value-block scalars dotted with the normal (interior gradN_i -> n_I).
5009 double Sval_p_b = 0.0, Sval_z_b = 0.0;
5010 for (int I = 0; I < nSpace; I++) {
5011 Sval_p_b += (dAg_dp*ug_b[I] + Ag*dug_dp_b[I] + dAa_dp*ua_b[I] + Aa*dua_dp_b[I]) * normal_b[I];
5012 Sval_z_b += (dAg_dz*ug_b[I] + Ag*dug_dz_b[I] + dAa_dz*ua_b[I] + Aa*dua_dz_b[I]) * normal_b[I];
5013 }
5014 // IIPG penalty scaled by the comp-1 diffusion magnitude a_n (= rho_g*Y*
5015 // krn/mu_n + rho_a*X*krw, times a representative K/mu_w; frozen in the
5016 // Jacobian). The bare framework penalty (const/h) is ~1e4x too weak vs
5017 // the molar-density-scaled comp-1 equation, so z floats off the BC.
5018 double Kw_rep = 0.0;
5019 for (int ii = 0; ii < nnz; ii++) Kw_rep = fmax(Kw_rep, fabs(KWs_eN[ii]));
5020 const double a_n_scale = (Ag*KNr_b/mu_n + Aa*KWr_b) * Kw_rep;
5021 const double penalty = ebqe_penalty_ext.data()[ebNE_kb] * a_n_scale;
5022 if (isDir_n) {
5023 // Nitsche penalty drives z at the trace toward the prescribed BC.
5024 F_n_dot_n += penalty * (u_n_ext_b - bc_u_n_ext_b);
5025 } else {
5026 // No Dirichlet on z => no-flow / closed boundary for the CO2 eq.
5027 // The consistent interior-trace flux must NOT be applied here: it
5028 // is generally nonzero (gravity + capillary at the trace) and would
5029 // inject a spurious boundary flux that breaks mass conservation on
5030 // a closed box. This mirrors STAB=0's calculateResidual, whose
5031 // exterior loop adds nothing to the gas equation. Only true
5032 // Dirichlet faces get the consistent flux + Nitsche penalty.
5033 F_n_dot_n = 0.0;
5034 }
5035
5036 for (int i = 0; i < nDOF_test_element; i++) {
5037 const double test_i_dS = u_test_trace_ref.data()[
5038 ebN_local_kb * nDOF_test_element + i] * dS_eb;
5039 // Residual contribution: +(F_1.n) N_i dS.
5040 elementResidual_n_eb[i] += F_n_dot_n * test_i_dS;
5041 // Jacobian (per trial j). d(F_1.n)/du_j = value-block * trial_j +
5042 // gradient-block . gradN_j, the interior chain rule with gradN_i->n.
5043 for (int j = 0; j < nDOF_trial_element; j++) {
5044 const double trial_j_b = u_trial_trace_ref.data()[
5045 ebN_local_kb * nDOF_test_element + j];
5046 // gradient-block scalars dotted with the normal:
5047 // sum_{I,ii} (dF_1[I]/dgrad_var[J]) gradN_j[J] n_I.
5048 double Sgrad_p_b = 0.0, Sgrad_z_b = 0.0;
5049 for (int I = 0; I < nSpace; I++) {
5050 for (int ii = a_rowptr.data()[I]; ii < a_rowptr.data()[I + 1]; ii++) {
5051 const int J = a_colind.data()[ii];
5052 const double Kii = KWs_eN[ii];
5053 const double Mob_g = KNr_b*Kii/mu_n, Mob_a = KWr_b*Kii;
5054 const double gNjJ = u_grad_trial_trace_b[j * nSpace + J];
5055 // d ug[I]/d grad_p[J] = -Mob_g*(1 - pcp*dSg_dp); d ua[I]/d grad_p[J] = -Mob_a
5056 const double dFdgp = Ag*(-Mob_g*(1.0 - pcp_b*dSgb_dp)) + Aa*(-Mob_a);
5057 // d ug[I]/d grad_z[J] = -Mob_g*(-pcp*dSg_dz); d ua[I]/d grad_z[J] = 0
5058 const double dFdgz = Ag*(-Mob_g*(-pcp_b*dSgb_dz));
5059 Sgrad_p_b += dFdgp * gNjJ * normal_b[I];
5060 Sgrad_z_b += dFdgz * gNjJ * normal_b[I];
5061 }
5062 }
5063 // (1,1) self: d(F_1.n)/dz ; (1,0) cross: d(F_1.n)/dp.
5064 double jac_nn = Sval_z_b * trial_j_b + Sgrad_z_b;
5065 double jac_nw = Sval_p_b * trial_j_b + Sgrad_p_b;
5066 // Same no-flow gate as the residual: only Dirichlet faces
5067 // contribute a boundary flux (consistent flux + Nitsche penalty).
5068 if (isDir_n) {
5069 jac_nn += penalty * trial_j_b;
5070 } else {
5071 jac_nn = 0.0;
5072 jac_nw = 0.0;
5073 }
5074 elementJacobian_n_n_eb[i][j] += jac_nn * test_i_dS;
5075 elementJacobian_n_w_eb[i][j] += jac_nw * test_i_dS;
5076 }
5077 }
5078 } // kb
5079
5080 // Scatter element-boundary contributions to global storage.
5081 for (int i = 0; i < nDOF_test_element; i++) {
5082 const int eN_i = eN * nDOF_test_element + i;
5083 const int gi = u_l2g.data()[eN_i];
5084 globalResidual.data()[offset_n + stride_n * gi] += elementResidual_n_eb[i];
5085 if (have_gas_budget) {
5086 gas_budget_node.data()[4 * numDOFs_n + gi] += elementResidual_n_eb[i];
5087 gas_budget_node.data()[5 * numDOFs_n + gi] += elementResidual_n_eb[i];
5088 }
5089 for (int j = 0; j < nDOF_trial_element; j++) {
5090 const int ebN_i_j = ebN * 4 * nDOF_test_X_trial_element
5091 + i * nDOF_trial_element + j;
5092 globalJacobian.data()[csrRowIndeces_n_n.data()[eN_i]
5093 + csrColumnOffsets_eb_n_n.data()[ebN_i_j]]
5094 += elementJacobian_n_n_eb[i][j];
5095 globalJacobian.data()[csrRowIndeces_n_w.data()[eN_i]
5096 + csrColumnOffsets_eb_n_w.data()[ebN_i_j]]
5097 += elementJacobian_n_w_eb[i][j];
5098 }
5099 }
5100 } // ebNE
5101 }
5102
5104 {
5105 xt::pyarray<int> &a_rowptr = args.array<int>("a_rowptr");
5106 xt::pyarray<int> &a_colind = args.array<int>("a_colind");
5107 double rho = args.scalar<double>("rho"); // freshwater reference (fallback)
5108 double beta = args.scalar<double>("beta");
5109 xt::pyarray<double> &gravity = args.array<double>("gravity");
5110 xt::pyarray<double> &alpha = args.array<double>("alpha");
5111 xt::pyarray<double> &n = args.array<double>("n");
5112 xt::pyarray<double> &thetaR = args.array<double>("thetaR");
5113 xt::pyarray<double> &thetaSR = args.array<double>("thetaSR");
5114 xt::pyarray<double> &KWs = args.array<double>("KWs");
5115 xt::pyarray<double> &krn_end = args.array<double>("krn_end");
5116 xt::pyarray<double> &S_gr = args.array<double>("S_gr");
5117 double mu_n = args.scalar<double>("mu_n");
5118 xt::pyarray<int> &elementMaterialTypes = args.array<int>("elementMaterialTypes");
5119 xt::pyarray<int> &freeDOFMaterialTypes = args.array<int>("freeDOFMaterialTypes");
5120 int numDOFs = args.scalar<int>("numDOFs");
5121 xt::pyarray<double> &mIn = args.array<double>("limited_solution");
5122 xt::pyarray<double> &pOut = args.array<double>("u_dof");
5123 int USE_NEWTON_INVERT = args.scalar<int>("USE_NEWTON_INVERT");
5124 const int PSK_TYPE = args.scalar<int>("PSK_TYPE");
5125 const int COMPONENT = args.scalar<int>("COMPONENT");
5126
5127 if (COMPONENT == 1) {
5128 // -------- Component-1 inverse (compositional): m_c -> u_n = z. --------
5129 // m_c = (phi*N)*z => z = m_c / (phi*N). rho_n_phi_dof_member caches the
5130 // lumped phi*N built by the residual / MassMatrix. Clamp z to [0,1]
5131 // (overall CO2 mole fraction), NOT a saturation range.
5132 const int numDOFs_u = static_cast<int>(pOut.size());
5133 const bool have_rho_n_phi = (rho_n_phi_dof_member.size() ==
5134 static_cast<std::size_t>(numDOFs_u));
5135 // Fallback divisor (safety net only -- the residual/MassMatrix always
5136 // populate the cache first). A representative aqueous-rich molar density
5137 // keeps the magnitude sane if an orphan node ever reaches here.
5138 const int mat0 = elementMaterialTypes.data()[0];
5139 const double phi_mat = thetaR.data()[mat0] + thetaSR.data()[mat0];
5140 const double phiN_fallback = phi_mat * 5.0e4; // ~brine molar density [mol/m^3]
5141 for (int i = 0; i < numDOFs_u; i++) {
5142 const double phiN_i = have_rho_n_phi ? rho_n_phi_dof_member[i]
5143 : phiN_fallback;
5144 double z = mIn.data()[i] / std::max(phiN_i, 1.0e-16);
5145 // Safety clamp to [0,1]. A correct conservative FCT keeps
5146 // limited_solution_n in-bounds, so this should not trigger; it guards
5147 // against round-off / misconfiguration.
5148 if (z < 0.0) z = 0.0;
5149 if (z > 1.0) z = 1.0;
5150 pOut.data()[i] = z;
5151 }
5152 return;
5153 }
5154
5155 // -------- Component-0 inverse: m_w -> p_w (Richards-style, 2-stage). --------
5156 // m_w = rho_w(p_w) * thetaW(Se(S_n)), rho_w(p_w) = rho * exp(beta*p_w).
5157 // "Ill-posed for p_w ALONE" only means: you cannot recover p_w without S_n.
5158 // But S_n is the OTHER primary variable -- always available -- so:
5159 // stage 1: rho_w = m_w / thetaW(Se(S_n)) (S_n known => thetaW known)
5160 // stage 2: p_w = ln(rho_w / rho) / beta (analytic inverse of EOS)
5161 // Well-posed whenever beta != 0 and thetaW > 0 (always: S_n <= 1-S_wr).
5162 // The (limited) S_n field is passed as "u_dof_n".
5163 if (COMPONENT == 0) {
5164 if (beta == 0.0)
5165 throw std::runtime_error(
5166 "m_comp_co2::invert COMPONENT=0: beta == 0 makes rho_w(p_w) "
5167 "constant, so m_w carries no p_w information. Use beta > 0.");
5168 xt::pyarray<double> &u_dof_n = args.array<double>("u_dof_n");
5169 const int numDOFs_w = static_cast<int>(pOut.size());
5170 // Material 0 fallback -- matches the COMPONENT==1 convention above.
5171 const int mat0 = elementMaterialTypes.data()[0];
5172 const double alpha0 = alpha.data()[mat0];
5173 const double n_vg0 = n.data()[mat0];
5174 const double thetaR0 = thetaR.data()[mat0];
5175 const double thetaSR0 = thetaSR.data()[mat0];
5176 const double S_wr0 = thetaR0 / (thetaR0 + thetaSR0);
5177 const double one_m_Sr = 1.0 - S_wr0;
5178 for (int i = 0; i < numDOFs_w; i++) {
5179 const double S_n = u_dof_n.data()[i];
5180 double Se = (1.0 - S_n - S_wr0) / one_m_Sr;
5181 if (Se < 0.0) Se = 0.0; else if (Se > 1.0) Se = 1.0;
5182 double thetaW, DthetaW_DSe, KWr, DKWr_DSe;
5183 if (PSK_TYPE == 1)
5185 Se, alpha0, n_vg0, thetaR0, thetaSR0, thetaW, DthetaW_DSe, KWr, DKWr_DSe);
5186 else
5188 Se, alpha0, n_vg0, thetaR0, thetaSR0, thetaW, DthetaW_DSe, KWr, DKWr_DSe);
5189 const double rho_w = (thetaW > 1.0e-14) ? mIn.data()[i] / thetaW : rho;
5190 pOut.data()[i] = std::log(std::max(rho_w / rho, 1.0e-300)) / beta;
5191 }
5192 (void)a_rowptr; (void)a_colind; (void)gravity; (void)KWs;
5193 (void)freeDOFMaterialTypes; (void)numDOFs; (void)USE_NEWTON_INVERT;
5194 return;
5195 }
5196
5197 throw std::runtime_error(
5198 "m_comp_co2::invert: COMPONENT must be 0 (m_w -> p_w) or 1 (m_n -> S_n).");
5199 }
5200
5202 {
5203 //element
5204 double dt = args.scalar<double>("dt");
5205 xt::pyarray<double> &mesh_trial_ref = args.array<double>("mesh_trial_ref");
5206 xt::pyarray<double> &mesh_grad_trial_ref = args.array<double>("mesh_grad_trial_ref");
5207 xt::pyarray<double> &mesh_dof = args.array<double>("mesh_dof");
5208 xt::pyarray<double> &mesh_velocity_dof = args.array<double>("mesh_velocity_dof");
5209 double MOVING_DOMAIN = args.scalar<double>("MOVING_DOMAIN");
5210 xt::pyarray<int> &mesh_l2g = args.array<int>("mesh_l2g");
5211 xt::pyarray<double> &dV_ref = args.array<double>("dV_ref");
5212 xt::pyarray<double> &u_trial_ref = args.array<double>("u_trial_ref");
5213 xt::pyarray<double> &u_grad_trial_ref = args.array<double>("u_grad_trial_ref");
5214 xt::pyarray<double> &u_test_ref = args.array<double>("u_test_ref");
5215 xt::pyarray<double> &u_grad_test_ref = args.array<double>("u_grad_test_ref");
5216 //element boundary
5217 xt::pyarray<double> &mesh_trial_trace_ref = args.array<double>("mesh_trial_trace_ref");
5218 xt::pyarray<double> &mesh_grad_trial_trace_ref = args.array<double>("mesh_grad_trial_trace_ref");
5219 xt::pyarray<double> &dS_ref = args.array<double>("dS_ref");
5220 xt::pyarray<double> &u_trial_trace_ref = args.array<double>("u_trial_trace_ref");
5221 xt::pyarray<double> &u_grad_trial_trace_ref = args.array<double>("u_grad_trial_trace_ref");
5222 xt::pyarray<double> &u_test_trace_ref = args.array<double>("u_test_trace_ref");
5223 xt::pyarray<double> &u_grad_test_trace_ref = args.array<double>("u_grad_test_trace_ref");
5224 xt::pyarray<double> &normal_ref = args.array<double>("normal_ref");
5225 xt::pyarray<double> &boundaryJac_ref = args.array<double>("boundaryJac_ref");
5226 //physics
5227 int nElements_global = args.scalar<int>("nElements_global");
5228 //new
5229 xt::pyarray<double> &ebqe_penalty_ext = args.array<double>("ebqe_penalty_ext");
5230 xt::pyarray<int> &elementMaterialTypes = args.array<int>("elementMaterialTypes");
5231 xt::pyarray<int> &isSeepageFace = args.array<int>("isSeepageFace");
5232 xt::pyarray<int> &a_rowptr = args.array<int>("a_rowptr");
5233 xt::pyarray<int> &a_colind = args.array<int>("a_colind");
5234 double rho = args.scalar<double>("rho");
5235 double beta = args.scalar<double>("beta");
5236 // gas-phase reference density and reference pressure for the linear EOS
5237 // rho_n_local(p_n) = rho_n * p_n / p_ref_n (p_ref_n>0) or constant rho_n.
5238 const double rho_n_mm = args.scalar<double>("rho_n");
5239 const double p_ref_n = args.scalar<double>("p_ref_n");
5240 const bool rho_n_compressible = (p_ref_n > 0.0);
5241
5242 xt::pyarray<double> &q_rho = args.array<double>("q_rho");
5243
5244 xt::pyarray<double> &gravity = args.array<double>("gravity");
5245 xt::pyarray<double> &alpha = args.array<double>("alpha");
5246 xt::pyarray<double> &n = args.array<double>("n");
5247 xt::pyarray<double> &thetaR = args.array<double>("thetaR");
5248 xt::pyarray<double> &thetaSR = args.array<double>("thetaSR");
5249 xt::pyarray<double> &KWs = args.array<double>("KWs");
5250 xt::pyarray<double> &krn_end = args.array<double>("krn_end");
5251 xt::pyarray<double> &S_gr = args.array<double>("S_gr");
5252 double mu_n = args.scalar<double>("mu_n");
5253 //end new
5254 double useMetrics = args.scalar<double>("useMetrics");
5255 double alphaBDF = args.scalar<double>("alphaBDF");
5256 int lag_shockCapturing = args.scalar<int>("lag_shockCapturing");
5257 double shockCapturingDiffusion = args.scalar<double>("shockCapturingDiffusion");
5258 xt::pyarray<int> &u_l2g = args.array<int>("u_l2g");
5259 // Comp-1 (z) map -- MUST match the residual's u_l2g_n so the mass / (1,1)
5260 // tangent is assembled on the same DOFs.
5261 xt::pyarray<int> &u_l2g_n = args.array<int>("u_l2g_n");
5262 xt::pyarray<int> &r_l2g = args.array<int>("r_l2g");
5263 xt::pyarray<double> &elementDiameter = args.array<double>("elementDiameter");
5264 int degree_polynomial = args.scalar<int>("degree_polynomial");
5265 xt::pyarray<double> &u_dof = args.array<double>("u_dof");
5266 // u_dof_n always present in argsDict (getJacobian sets it from
5267 // self.u[1].dof in m_comp_co2.py).
5268 xt::pyarray<double> &u_dof_n = args.array<double>("u_dof_n");
5269 xt::pyarray<double> &velocity = args.array<double>("velocity");
5270 xt::pyarray<double> &q_m_betaBDF = args.array<double>("q_m_betaBDF");
5271 xt::pyarray<double> &cfl = args.array<double>("cfl");
5272 xt::pyarray<double> &q_numDiff_u_last = args.array<double>("q_numDiff_u_last");
5273 xt::pyarray<int> &csrRowIndeces_u_u = args.array<int>("csrRowIndeces_u_u");
5274 xt::pyarray<int> &csrColumnOffsets_u_u = args.array<int>("csrColumnOffsets_u_u");
5275 xt::pyarray<int> &csrRowIndeces_n_n = args.array<int>("csrRowIndeces_n_n");
5276 // (1,0) cross-block CSR maps for the gas-eq diffusion
5277 // against grad u_w. Currently allocated by the framework but unused by
5278 // the C++ assembly - 3c.2/3c.3 will write into them.
5279 xt::pyarray<int> &csrRowIndeces_n_w = args.array<int>("csrRowIndeces_n_w");
5280 xt::pyarray<int> &csrColumnOffsets_n_n = args.array<int>("csrColumnOffsets_n_n");
5281 xt::pyarray<int> &csrColumnOffsets_n_w = args.array<int>("csrColumnOffsets_n_w");
5282 xt::pyarray<double> &globalJacobian = args.array<double>("globalJacobian");
5283 xt::pyarray<double> &delta_x_ij = args.array<double>("delta_x_ij");
5284 int nExteriorElementBoundaries_global = args.scalar<int>("nExteriorElementBoundaries_global");
5285 xt::pyarray<int> &exteriorElementBoundariesArray = args.array<int>("exteriorElementBoundariesArray");
5286 xt::pyarray<int> &elementBoundaryElementsArray = args.array<int>("elementBoundaryElementsArray");
5287 xt::pyarray<int> &elementBoundaryLocalElementBoundariesArray = args.array<int>("elementBoundaryLocalElementBoundariesArray");
5288 xt::pyarray<double> &ebqe_velocity_ext = args.array<double>("ebqe_velocity_ext");
5289 xt::pyarray<int> &isDOFBoundary_u = args.array<int>("isDOFBoundary_u");
5290 xt::pyarray<double> &ebqe_bc_u_ext = args.array<double>("ebqe_bc_u_ext");
5291 // component-1 (S_n) boundary arrays.
5292 xt::pyarray<int> &isDOFBoundary_n = args.array<int>("isDOFBoundary_n");
5293 xt::pyarray<double> &ebqe_bc_u_n_ext = args.array<double>("ebqe_bc_u_n_ext");
5294 xt::pyarray<int> &isFluxBoundary_u = args.array<int>("isFluxBoundary_u");
5295 xt::pyarray<double> &ebqe_bc_flux_ext = args.array<double>("ebqe_bc_flux_ext");
5296 xt::pyarray<int> &csrColumnOffsets_eb_u_u = args.array<int>("csrColumnOffsets_eb_u_u");
5297 int LUMPED_MASS_MATRIX = args.scalar<int>("LUMPED_MASS_MATRIX");
5298 // PSK closure selector for evaluateCoefficients (read from argsDict).
5299 PSK_TYPE_member = args.scalar<int>("PSK_TYPE");
5300 immiscible_member = (args.scalar<int>("immiscible") != 0);
5301 T_C_member = args.scalar<double>("T_C"); // temperature [degC] from input
5302 double Ct_sge = 4.0;
5303 //
5304 //loop over elements to compute volume integrals and load them into the element Jacobians and global Jacobian
5305 //
5306 for (int eN = 0; eN < nElements_global; eN++) {
5307 double elementJacobian_u_u[nDOF_test_element][nDOF_trial_element];
5308 for (int i = 0; i < nDOF_test_element; i++)
5309 for (int j = 0; j < nDOF_trial_element; j++) { elementJacobian_u_u[i][j] = 0.0; }
5310 for (int k = 0; k < nQuadraturePoints_element; k++) {
5311 int eN_k = eN * nQuadraturePoints_element + k, //index to a scalar at a quadrature point
5312 eN_k_nSpace = eN_k * nSpace,
5313 eN_nDOF_trial_element = eN * nDOF_trial_element; //index to a vector at a quadrature point
5314 //declare local storage
5315 double u = 0.0, grad_u[nSpace], m = 0.0, dm = 0.0, f[nSpace], df[nSpace], a[nnz], da[nnz], as[nnz], m_t = 0.0, dm_t = 0.0, dpdeResidual_u_u[nDOF_trial_element], Lstar_u[nDOF_test_element], dsubgridError_u_u[nDOF_trial_element], tau = 0.0, tau0 = 0.0, tau1 = 0.0, jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], u_grad_trial[nDOF_trial_element * nSpace], dV, u_test_dV[nDOF_test_element], u_grad_test_dV[nDOF_test_element * nSpace], x, y, z, xt, yt, zt,
5316 G[nSpace * nSpace], G_dd_G, tr_G;
5317
5318 //get jacobian, etc for mapping reference element
5319 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), mesh_grad_trial_ref.data(), jac, jacDet, jacInv, x, y, z);
5320 ck.calculateMappingVelocity_element(eN, k, mesh_velocity_dof.data(), mesh_l2g.data(), mesh_trial_ref.data(), xt, yt, zt);
5321 //get the physical integration weight
5322 dV = fabs(jacDet) * dV_ref.data()[k];
5323 ck.calculateG(jacInv, G, G_dd_G, tr_G);
5324 //get the trial function gradients
5325 ck.gradTrialFromRef(&u_grad_trial_ref.data()[k * nDOF_trial_element * nSpace], jacInv, u_grad_trial);
5326 //get the solution
5327 ck.valFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], &u_trial_ref.data()[k * nDOF_trial_element], u);
5328 //get the solution gradients
5329 ck.gradFromDOF(u_dof.data(), &u_l2g.data()[eN_nDOF_trial_element], u_grad_trial, grad_u);
5330 //precalculate test function products with integration weights
5331 for (int j = 0; j < nDOF_trial_element; j++) {
5332 u_test_dV[j] = u_test_ref.data()[k * nDOF_trial_element + j] * dV;
5333 for (int I = 0; I < nSpace; I++) {
5334 u_grad_test_dV[j * nSpace + I] = u_grad_trial[j * nSpace + I] * dV; //cek warning won't work for Petrov-Galerkin
5335 }
5336 }
5337 //
5338 //calculate pde coefficients and derivatives at quadrature points
5339 //
5340 double Kr, dKr, thetaW;
5341 //const double rho_local = q_rho.data()[eN_k];
5342 // NOTE: the cek hack at line ~3170 (`dm = 1.0`) and the dm_t=1.0
5343 // override at the Jacobian assembly below make the final mass matrix
5344 // output independent of the coefficients here (result is just
5345 // M = integral N_i N_j dV regardless). Coefficient call is kept for
5346 // moving-mesh / VMS consistency.
5347 double dm_du_n_mm = 0.0, dkr_du_n_mm = 0.0;
5348 double df_du_n_mm[nSpace], da_du_n_mm[nnz];
5349 for (int I = 0; I < nSpace; I++) df_du_n_mm[I] = 0.0;
5350 for (int ii = 0; ii < nnz; ii++) da_du_n_mm[ii] = 0.0;
5351 double u_n_qp = 0.0;
5352 ck.valFromDOF(u_dof_n.data(),
5353 &u_l2g_n.data()[eN_nDOF_trial_element],
5354 &u_trial_ref.data()[k * nDOF_trial_element], u_n_qp);
5355 evaluateCoefficients_from_Se(a_rowptr.data(), a_colind.data(), rho, q_rho.data()[eN_k], beta, gravity.data(),
5356 alpha.data()[elementMaterialTypes.data()[eN]], n.data()[elementMaterialTypes.data()[eN]],
5357 thetaR.data()[elementMaterialTypes.data()[eN]], thetaSR.data()[elementMaterialTypes.data()[eN]],
5358 &KWs.data()[elementMaterialTypes.data()[eN] * nnz], u, u_n_qp,
5359 m, dm, dm_du_n_mm, f, df, df_du_n_mm, a, da, da_du_n_mm,
5360 as, Kr, dKr, dkr_du_n_mm, thetaW);
5361 //
5362 //moving mesh
5363 //
5364 double mesh_velocity[3];
5365 mesh_velocity[0] = xt;
5366 mesh_velocity[1] = yt;
5367 mesh_velocity[2] = zt;
5368 for (int I = 0; I < nSpace; I++) {
5369 f[I] -= MOVING_DOMAIN * m * mesh_velocity[I];
5370 df[I] -= MOVING_DOMAIN * dm * mesh_velocity[I];
5371 }
5372 //
5373 //calculate time derivatives
5374 //
5375 //cek hack
5376 dm = 1.0;
5377 ck.bdf(alphaBDF,
5378 q_m_betaBDF.data()[eN_k], //since m_t isn't used, we don't have to correct mass
5379 m, dm, m_t, dm_t);
5380 //
5381 //calculate subgrid error contribution to the Jacobian (strong residual, adjoint, jacobian of strong residual)
5382 //
5383 //calculate the adjoint times the test functions
5384 for (int i = 0; i < nDOF_test_element; i++) {
5385 int i_nSpace = i * nSpace;
5386 Lstar_u[i] = ck.Advection_adjoint(df, &u_grad_test_dV[i_nSpace]);
5387 }
5388 //calculate the Jacobian of strong residual
5389 for (int j = 0; j < nDOF_trial_element; j++) {
5390 int j_nSpace = j * nSpace;
5391 dpdeResidual_u_u[j] = ck.MassJacobian_strong(dm_t, u_trial_ref.data()[k * nDOF_trial_element + j]) + ck.AdvectionJacobian_strong(df, &u_grad_trial[j_nSpace]);
5392 }
5393 //tau and tau*Res
5394 calculateSubgridError_tau(elementDiameter.data()[eN], dm_t, df, cfl.data()[eN_k], tau0);
5395
5396 calculateSubgridError_tau(Ct_sge, G, dm_t, df, tau1, cfl.data()[eN_k]);
5397 tau = useMetrics * tau1 + (1.0 - useMetrics) * tau0;
5398
5399 for (int j = 0; j < nDOF_trial_element; j++) dsubgridError_u_u[j] = -tau * dpdeResidual_u_u[j];
5400 for (int i = 0; i < nDOF_test_element; i++) {
5401 for (int j = 0; j < nDOF_trial_element; j++) {
5402 if (LUMPED_MASS_MATRIX == 1) {
5403 if (i == j) elementJacobian_u_u[i][j] += u_test_dV[i];
5404 } else {
5405 int j_nSpace = j * nSpace;
5406 int i_nSpace = i * nSpace;
5407 dm_t = 1.0; //we are solving for continuum density explicitly
5408 elementJacobian_u_u[i][j] += ck.MassJacobian_weak(dm_t, u_trial_ref.data()[k * nDOF_trial_element + j], u_test_dV[i]);
5409 }
5410 } //j
5411 } //i
5412 } //k
5413 //
5414 //load into element Jacobian into global Jacobian
5415 //
5416 for (int i = 0; i < nDOF_test_element; i++) {
5417 int eN_i = eN * nDOF_test_element + i;
5418 int I = u_l2g.data()[eN_i];
5419 for (int j = 0; j < nDOF_trial_element; j++) {
5420 int eN_i_j = eN_i * nDOF_trial_element + j;
5421 int J = u_l2g.data()[eN * nDOF_trial_element + j];
5422 //globalJacobian.data()[csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_u_u.data()[eN_i_j]] += elementJacobian_u_u[i][j];
5423 delta_x_ij.data()[3 * (csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_u_u.data()[eN_i_j]) + 0] = mesh_dof.data()[I * 3 + 0] - mesh_dof.data()[J * 3 + 0];
5424 delta_x_ij.data()[3 * (csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_u_u.data()[eN_i_j]) + 1] = mesh_dof.data()[I * 3 + 1] - mesh_dof.data()[J * 3 + 1];
5425 delta_x_ij.data()[3 * (csrRowIndeces_u_u.data()[eN_i] + csrColumnOffsets_u_u.data()[eN_i_j]) + 2] = mesh_dof.data()[I * 3 + 2] - mesh_dof.data()[J * 3 + 2];
5426 } //j
5427 } //i
5428 } //elements
5429 // (1,1) block: unit consistent mass / dt. Used by the time integrator.
5430 // Also refresh the cached nodal phi*rho_n so invert(COMPONENT=1) sees the
5431 // correct projection if mass-matrix assembly runs more recently than the
5432 // residual.
5433 const int numDOFs_u_mm = static_cast<int>(u_dof.size());
5434 // These are indexed by the comp-1 DOF (u_l2g_n), so they are sized by the
5435 // comp-1 DOF count u_dof_n.size(), not the comp-0 count u_dof.size().
5436 const int numDOFs_n_mm = static_cast<int>(u_dof_n.size());
5437 std::vector<double> rho_n_phi_mm(numDOFs_n_mm, 0.0);
5438 std::vector<double> ML_n_mm(numDOFs_n_mm, 0.0);
5439 for (int eN = 0; eN < nElements_global; eN++) {
5440 double elementJacobian_n_n[nDOF_test_element][nDOF_trial_element];
5441 for (int i = 0; i < nDOF_test_element; i++)
5442 for (int j = 0; j < nDOF_trial_element; j++) { elementJacobian_n_n[i][j] = 0.0; }
5443 const int mat_eN_mm = elementMaterialTypes.data()[eN];
5444 const double phi_eN_mm = thetaR.data()[mat_eN_mm] + thetaSR.data()[mat_eN_mm];
5445 const double alpha_eN_mm = alpha.data()[mat_eN_mm];
5446 const double n_vg_eN_mm = n.data()[mat_eN_mm];
5447 const double S_wr_mm = thetaR.data()[mat_eN_mm] / phi_eN_mm;
5448 const double one_m_Sr_mm = 1.0 - S_wr_mm;
5449 for (int k = 0; k < nQuadraturePoints_element; k++) {
5450 const int eN_nDOF_trial_element = eN * nDOF_trial_element;
5451 double jac[nSpace * nSpace], jacDet, jacInv[nSpace * nSpace], x, y, z;
5452 ck.calculateMapping_element(eN, k, mesh_dof.data(), mesh_l2g.data(),
5453 mesh_trial_ref.data(), mesh_grad_trial_ref.data(),
5454 jac, jacDet, jacInv, x, y, z);
5455 const double dV = fabs(jacDet) * dV_ref.data()[k];
5456 // P1 (compositional): project phi*N (total molar density * porosity) from
5457 // the flash, IDENTICAL to the residual's rho_n_phi_dof, so invert(COMP=1)
5458 // recovers z = m_c/(phi*N) consistently. N = rho_g*S_g + rho_a*S_a.
5459 double u_w_p = 0.0, u_n_p = 0.0;
5460 ck.valFromDOF(u_dof.data(),
5461 &u_l2g.data()[eN_nDOF_trial_element],
5462 &u_trial_ref.data()[k * nDOF_trial_element], u_w_p);
5463 ck.valFromDOF(u_dof_n.data(),
5464 &u_l2g_n.data()[eN_nDOF_trial_element],
5465 &u_trial_ref.data()[k * nDOF_trial_element], u_n_p);
5466 const double p_cl_mm = fmax(u_w_p, 1.0e2);
5469 const double phi_rho_n_qp = phi_eN_mm * (fs_mm.rho_g*fs_mm.S_g
5470 + fs_mm.rho_a*(1.0 - fs_mm.S_g));
5471 for (int i = 0; i < nDOF_test_element; i++) {
5472 const double test_i = u_test_ref.data()[k * nDOF_test_element + i];
5473 const int gi = u_l2g_n.data()[eN * nDOF_test_element + i]; // comp-1 DOF
5474 rho_n_phi_mm[gi] += phi_rho_n_qp * test_i * dV;
5475 ML_n_mm[gi] += test_i * dV;
5476 for (int j = 0; j < nDOF_trial_element; j++) {
5477 const double trial_j = u_trial_ref.data()[k * nDOF_trial_element + j];
5478 elementJacobian_n_n[i][j] += (test_i * trial_j * dV) / dt;
5479 }
5480 }
5481 }
5482 for (int i = 0; i < nDOF_test_element; i++) {
5483 const int eN_i = eN * nDOF_test_element + i;
5484 for (int j = 0; j < nDOF_trial_element; j++) {
5485 const int eN_i_j = eN_i * nDOF_trial_element + j;
5486 const int full_offset = csrRowIndeces_n_n.data()[eN_i] + csrColumnOffsets_n_n.data()[eN_i_j];
5487 if (std::fabs(globalJacobian.data()[full_offset]) < 1.0e-14)
5488 globalJacobian.data()[full_offset] += elementJacobian_n_n[i][j];
5489 }
5490 }
5491 }
5492 for (int i = 0; i < numDOFs_n_mm; ++i) {
5493 if (ML_n_mm[i] > 0.0) rho_n_phi_mm[i] /= ML_n_mm[i];
5494 else rho_n_phi_mm[i] = thetaR.data()[0] + thetaSR.data()[0];
5495 rho_n_phi_mm[i] = std::max(rho_n_phi_mm[i], 1.0e-16);
5496 }
5497 rho_n_phi_dof_member = rho_n_phi_mm;
5498 } //computeMassMatrix
5499
5501 {
5502 xt::pyarray<double> &c_dof = args.array<double>("c_dof"); // c (in/out)
5503 xt::pyarray<double> &Sn_dof = args.array<double>("Sn_dof"); // S_n (in/out)
5504 const double rho_n = args.scalar<double>("rho_n");
5505 const double X_sat = args.scalar<double>("X_sat");
5506 const double c_sat = args.scalar<double>("c_sat");
5507 const double k_d = args.scalar<double>("k_d"); // dissolution rate [1/time]
5508 const double dt = args.scalar<double>("dt"); // step size
5509 const int numDOFs = args.scalar<int>("numDOFs");
5510 if (X_sat <= 0.0 || k_d <= 0.0)
5511 return; // dissolution disabled
5512 const double a = X_sat / c_sat; // dissolved CO2 per unit c
5513 for (int i = 0; i < numDOFs; i++)
5514 {
5515 const double Sn = Sn_dof.data()[i];
5516 const double c = c_dof.data()[i];
5517 if (Sn > 0.0 && c < c_sat)
5518 {
5519 const double M = rho_n * Sn + a * (1.0 - Sn) * c;
5520 const double c_eq = (M <= X_sat) ? (M / a) : c_sat; // gas-limited; in [c, c_sat]
5521 const double r = k_d * Sn * dt;
5522 const double frac = (r > 0.0) ? r / (1.0 + r) : 0.0;
5523 const double c_new = c + frac * (c_eq - c); // in [c, c_eq]
5524 const double denom = rho_n - a * c_new; // > 0 since a*c_new <= X_sat < rho_n
5525 double Sn_new = (denom != 0.0) ? (M - a * c_new) / denom : Sn;
5526 if (Sn_new < 0.0) Sn_new = 0.0; // safety (denom>0 keeps it >=0)
5527 c_dof.data()[i] = c_new;
5528 Sn_dof.data()[i] = Sn_new;
5529 }
5530 }
5531 // --- PART 2: rebuild TADR's quadrature old-mass from the flashed fields ---
5532 xt::pyarray<double> &q_m_tadr = args.array<double>("q_m_tadr"); // TADR q[('m',0)] (out)
5533 xt::pyarray<int> &u_l2g = args.array<int>("u_l2g");
5534 xt::pyarray<double> &u_trial_ref = args.array<double>("u_trial_ref");
5535 xt::pyarray<int> &elementMaterialTypes = args.array<int>("elementMaterialTypes");
5536 xt::pyarray<double> &thetaR = args.array<double>("thetaR");
5537 xt::pyarray<double> &thetaSR = args.array<double>("thetaSR");
5538 const double rho_f = args.scalar<double>("rho_f");
5539 const double rho_s = args.scalar<double>("rho_s");
5540 const int nElements_global = args.scalar<int>("nElements_global");
5541 // Renamed (nQP_flash / nDOF_flash) to avoid shadowing the struct's
5542 // template parameters nQuadraturePoints_element / nDOF_trial_element.
5543 // These come from Python (derived from q[('m',0)].shape and the l2g),
5544 // so the q_m_tadr write stays in bounds.
5545 const int nQP_flash = args.scalar<int>("nQuadraturePoints_element");
5546 const int nDOF_flash = args.scalar<int>("nDOF_trial_element");
5547 const double eps = (rho_f != 0.0) ? (rho_s - rho_f) / rho_f : 0.0;
5548 for (int eN = 0; eN < nElements_global; eN++)
5549 {
5550 const int mat = elementMaterialTypes.data()[eN];
5551 const double phi_eN = thetaR.data()[mat] + thetaSR.data()[mat];
5552 const int eN_nDOF = eN * nDOF_flash;
5553 for (int k = 0; k < nQP_flash; k++)
5554 {
5555 double c_k = 0.0, Sn_k = 0.0;
5556 ck.valFromDOF(c_dof.data(), &u_l2g.data()[eN_nDOF],
5557 &u_trial_ref.data()[k * nDOF_flash], c_k);
5558 ck.valFromDOF(Sn_dof.data(), &u_l2g.data()[eN_nDOF],
5559 &u_trial_ref.data()[k * nDOF_flash], Sn_k);
5560 const double thetaW = phi_eN * (1.0 - Sn_k);
5561 const double rho = rho_f * (1.0 + eps * c_k);
5562 q_m_tadr.data()[eN * nQP_flash + k] = thetaW * rho * c_k;
5563 }
5564 }
5565 } //dissolutionFlash
5566
5567 // ---- Post-step derived-field export ---------------------------------------
5568 // Per-node value-only flash of the PRIMARY (p,z) state into the three
5569 // human-facing compositional fields that the archiver writes to the XDMF:
5570 // Sg = free-gas saturation (FlashState.S_g)
5571 // X = CO2 mole fraction dissolved in brine (FlashState.X)
5572 // c = brine CO2 MASS concentration [kg/m^3] = rho_a * X * M_CO2
5574 {
5575 xt::pyarray<double> &p_dof = args.array<double>("p_dof"); // comp-0 (pressure) [Pa]
5576 xt::pyarray<double> &z_dof = args.array<double>("z_dof"); // comp-1 (overall CO2 mole frac)
5577 xt::pyarray<double> &Sg_dof = args.array<double>("Sg_dof"); // out: gas saturation
5578 xt::pyarray<double> &X_dof = args.array<double>("X_dof"); // out: CO2 mole frac in brine
5579 xt::pyarray<double> &c_dof = args.array<double>("c_dof"); // out: brine CO2 mass conc [kg/m^3]
5580 const int numDOFs = args.scalar<int>("numDOFs");
5581 immiscible_member = (args.scalar<int>("immiscible") != 0);
5582 T_C_member = args.scalar<double>("T_C"); // temperature [degC] from input
5583 const double M_CO2 = 0.04401; // CO2 molar mass [kg/mol]
5584 for (int i = 0; i < numDOFs; i++)
5585 {
5586 const double p_i = (p_dof.data()[i] > 1.0e2) ? p_dof.data()[i] : 1.0e2;
5587 double z_i = z_dof.data()[i];
5588 if (z_i < 1.0e-12) z_i = 1.0e-12; // match plot-side clamp
5589 if (z_i > 1.0 - 1.0e-12) z_i = 1.0 - 1.0e-12;
5594 Sg_dof.data()[i] = fs.S_g;
5595 X_dof.data()[i] = (fs.X > 0.0) ? fs.X : 0.0;
5596 c_dof.data()[i] = (fs.rho_a * fs.X > 0.0) ? fs.rho_a * fs.X * M_CO2 : 0.0;
5597 }
5598 // Per-rock closure: min / max of S_r over the rocks at each node (the
5599 // flash's S_g at one-rock nodes and before the first residual).
5600 if (args.scalar<int>("per_rock_closure")) {
5601 xt::pyarray<double> &Sg_min = args.array<double>("Sg_rock_min_dof");
5602 xt::pyarray<double> &Sg_max = args.array<double>("Sg_rock_max_dof");
5603 const bool have = (static_cast<int>(Sg_rock_min_member.size()) >= numDOFs);
5604 for (int i = 0; i < numDOFs; i++) {
5605 const bool multi = have && !std::isnan(Sg_rock_min_member[i]);
5606 Sg_min.data()[i] = multi ? Sg_rock_min_member[i] : Sg_dof.data()[i];
5607 Sg_max.data()[i] = multi ? Sg_rock_max_member[i] : Sg_dof.data()[i];
5608 }
5609 }
5610 } //calculateFlashFields
5611}; //M_comp_co2
5612
5613inline M_comp_co2_base *newm_comp_co2(int nSpaceIn, int nQuadraturePoints_elementIn, int nDOF_mesh_trial_elementIn, int nDOF_trial_elementIn, int nDOF_test_elementIn, int nQuadraturePoints_elementBoundaryIn, int CompKernelFlag)
5614{
5615 if (nSpaceIn == 1)
5616 return proteus::chooseAndAllocateDiscretization1D<M_comp_co2_base, M_comp_co2, CompKernel>(nSpaceIn, nQuadraturePoints_elementIn, nDOF_mesh_trial_elementIn, nDOF_trial_elementIn, nDOF_test_elementIn, nQuadraturePoints_elementBoundaryIn, CompKernelFlag);
5617 else if (nSpaceIn == 2)
5618 return proteus::chooseAndAllocateDiscretization2D<M_comp_co2_base, M_comp_co2, CompKernel>(nSpaceIn, nQuadraturePoints_elementIn, nDOF_mesh_trial_elementIn, nDOF_trial_elementIn, nDOF_test_elementIn, nQuadraturePoints_elementBoundaryIn, CompKernelFlag);
5619 else {
5620 assert(nSpaceIn == 3);
5621 return proteus::chooseAndAllocateDiscretization<M_comp_co2_base, M_comp_co2, CompKernel>(nSpaceIn, nQuadraturePoints_elementIn, nDOF_mesh_trial_elementIn, nDOF_trial_elementIn, nDOF_test_elementIn, nQuadraturePoints_elementBoundaryIn, CompKernelFlag);
5622 }
5623}
5624} // namespace m_comp_co2
5625} // namespace proteus
5626#endif
Int n
Definition Headers.h:28
#define pi
Definition Headers.h:2
Double r
Definition Headers.h:83
Double H
Definition Headers.h:65
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
Double psi
Definition Headers.h:78
#define cE
Definition NCLS3P.h:10
virtual void calculateResidual_entropy_viscosity(arguments_dict &args)=0
virtual void calculateMassMatrix(arguments_dict &args)=0
virtual void FCTStep(arguments_dict &args)=0
virtual void calculateJacobian(arguments_dict &args)=0
virtual void dissolutionFlash(arguments_dict &args)=0
virtual void calculateFlashFields(arguments_dict &args)=0
virtual void kth_FCT_step(arguments_dict &args)=0
virtual void calculateResidual(arguments_dict &args)=0
virtual void invert(arguments_dict &args)=0
void calculateResidual_entropy_viscosity(arguments_dict &args)
std::vector< double > rho_n_phi_dof_member
Definition m_comp_co2.h:82
void calculateJacobian(arguments_dict &args)
void calculateFlashFields(arguments_dict &args)
std::vector< double > Sg_rock_max_member
Definition m_comp_co2.h:96
void exteriorNumericalFlux(const double &bc_flux, int rowptr[nSpace], int colind[nnz], int isSeepageFace, int &isDOFBoundary, double n[nSpace], double bc_u, double K[nnz], double grad_psi[nSpace], double u, double K_rho_g[nSpace], double penalty, double &flux)
Definition m_comp_co2.h:338
void calculateNumericalDiffusion(const double &shockCapturingDiffusion, const double &elementDiameter, const double &strong_residual, const double grad_u[nSpace], double &numDiff)
Definition m_comp_co2.h:327
void evaluateCoefficients_from_Se(const int rowptr[nSpace], const int colind[nnz], const double rho0, const double rho_transport, const double beta, const double gravity[nSpace], const double alpha, const double n_vg, const double thetaR, const double thetaSR, const double KWs[nnz], const double &u_w, const double &u_n, double &m, double &dm_du_w, double &dm_du_n, double f[nSpace], double df_du_w[nSpace], double df_du_n[nSpace], double a[nnz], double da_du_w[nnz], double da_du_n[nnz], double as[nnz], double &kr, double &dkr_du_w, double &dkr_du_n, double &thetaW_out)
Definition m_comp_co2.h:103
void invert(arguments_dict &args)
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 m_comp_co2.h:319
void exteriorNumericalFluxJacobian(const int rowptr[nSpace], const int colind[nnz], const int isDOFBoundary, const double n[nSpace], const double K[nnz], const double dK[nnz], const double grad_psi[nSpace], const double grad_v[nSpace], const double dK_rho_g[nSpace], const double v, const double penalty, double &fluxJacobian)
Definition m_comp_co2.h:365
void calculateCFL(const double &elementDiameter, const double df[nSpace], double &cfl)
Definition m_comp_co2.h:297
void dissolutionFlash(arguments_dict &args)
void calculateMassMatrix(arguments_dict &args)
void exteriorNumericalFluxJacobian2(const int rowptr[nSpace], const int colind[nnz], const int isDOFBoundary, const double n[nSpace], const double Ks[nnz], const double K[nnz], const double dK[nnz], const double grad_psi[nSpace], const double grad_v[nSpace], const double dK_rho_g[nSpace], const double v, const double penalty, double &fluxJacobian, double &bfluxJacobian)
Definition m_comp_co2.h:411
void FCTStep(arguments_dict &args)
void calculateResidual(arguments_dict &args)
Definition m_comp_co2.h:435
std::vector< double > rho_dof_member
Definition m_comp_co2.h:81
void exteriorNumericalFlux2(const double &bc_flux, int rowptr[nSpace], int colind[nnz], int isSeepageFace, int &isDOFBoundary, double n[nSpace], double bc_u, double K[nnz], double grad_psi[nSpace], double u, double K_rho_g[nSpace], double penalty, double &flux, double &bflux)
Definition m_comp_co2.h:380
void calculateSubgridError_tau(const double &elementDiameter, const double &dmt, const double dH[nSpace], double &cfl, double &tau)
Definition m_comp_co2.h:307
std::vector< double > Sg_rock_min_member
Definition m_comp_co2.h:96
void kth_FCT_step(arguments_dict &args)
double seepagefluxcalculator(double anb_seepage_flux, int isSeepageFace, double dS, double flux_ext)
Definition m_comp_co2.h:429
Comp1Closure evaluateCoefficients_comp1(const double alpha, const double n_vg, const double bc_Se_min, const double thetaR, const double thetaSR, const double krn_end, const double mu_n, const double u_w, const double u_n)
Definition m_comp_co2.h:227
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
#define GLOBAL_FCT
Definition m_comp_co2.h:24
#define IS_BETAij_ONE
Definition m_comp_co2.h:23
constexpr double M_H2O_KG
constexpr double M_CO2_KG
FlashState flashPZ(double p_Pa, double z, double T_C, double=0.0, double eps=EPS_Z, bool immiscible=false)
constexpr double EPS_Z
void vgm_kr_nonwetting_from_Se(const double Se_w, const double, const double n_vg, double &KNr, double &DKNr_DSe, const double Se_trap=1.0)
void bc_pc_from_Se(const double Se, const double alpha, const double lam, const double Se_min_pc, double &pc, double &Dpc_DSe, double &D2pc_DSe2)
void bc_wetting_from_Se(const double Se, const double, const double lam, const double thetaR, const double thetaSR, double &thetaW, double &DthetaW_DSe, double &KWr, double &DKWr_DSe)
void bc_kr_nonwetting_from_Se(const double Se_w, const double, const double lam, double &KNr, double &DKNr_DSe, const double Se_trap=1.0)
void bc_Se_from_pc(const double pc, const double alpha, const double lam, const double Se_min_pc, double &Se, double &DSe_Dpc)
void vgm_pc_from_Se(const double Se, const double alpha, const double n_vg, double &pc, double &Dpc_DSe, double &D2pc_DSe2)
void vgm_wetting_from_Se(const double Se, const double, const double n_vg, const double thetaR, const double thetaSR, double &thetaW, double &DthetaW_DSe, double &KWr, double &DKWr_DSe)
double ENTROPY(const double &phi, const double &phiL, const double &phiR)
Definition m_comp_co2.h:38
double DENTROPY(const double &phi, const double &phiL, const double &phiR)
Definition m_comp_co2.h:42
M_comp_co2_base * newm_comp_co2(int nSpaceIn, int nQuadraturePoints_elementIn, int nDOF_mesh_trial_elementIn, int nDOF_trial_elementIn, int nDOF_test_elementIn, int nQuadraturePoints_elementBoundaryIn, int CompKernelFlag)
double DENTROPY_LOG(const double &phi, const double &phiL, const double &phiR)
Definition m_comp_co2.h:51
double ENTROPY_LOG(const double &phi, const double &phiL, const double &phiR)
Definition m_comp_co2.h:47
Definition ADR.h:21
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)
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)
double f(const double &g, const double &h, const double &hZ)
Definition SW2DCV.h:58
Richards free-function PSK closures (moved here from proteus/richards/psk_models.h).
T & scalar(const std::string &key)
xt::pyarray< T > & array(const std::string &key)