LCOV - code coverage report
Current view: top level - solvers/navier_stokes/cpu - solver_explicit_euler.c (source / functions) Coverage Total Hit
Test: coverage.info Lines: 87.4 % 412 360
Test Date: 2026-10-05 04:47:18 Functions: 100.0 % 12 12

            Line data    Source code
       1              : #include "cfd/core/cfd_status.h"
       2              : #include "cfd/core/filesystem.h"
       3              : #include "cfd/core/grid.h"
       4              : #include "cfd/core/indexing.h"
       5              : #include "cfd/core/math_utils.h"
       6              : #include "cfd/core/memory.h"
       7              : 
       8              : 
       9              : #include "cfd/solvers/energy_solver.h"
      10              : #include "cfd/solvers/navier_stokes_solver.h"
      11              : #include "cfd/solvers/turbulence_solver.h"
      12              : 
      13              : #include "../../energy/energy_solver_internal.h"
      14              : #include "../../turbulence/turbulence_solver_internal.h"
      15              : #include "../boundary_copy_utils.h"
      16              : #include "../ns_convection_internal.h"
      17              : 
      18              : #include <math.h>
      19              : #include <stdio.h>
      20              : #include <string.h>
      21              : 
      22              : 
      23              : #ifndef M_PI
      24              : #define M_PI 3.14159265358979323846
      25              : #endif
      26              : 
      27              : // Physical stability limits for numerical computation
      28              : #define MAX_DERIVATIVE_LIMIT        100.0   // Maximum allowed first derivative magnitude (1/s)
      29              : #define MAX_SECOND_DERIVATIVE_LIMIT 1000.0  // Maximum allowed second derivative magnitude (1/s²)
      30              : #define MAX_VELOCITY_LIMIT          100.0   // Maximum allowed velocity magnitude (m/s)
      31              : #define MAX_DIVERGENCE_LIMIT        10.0    // Maximum allowed velocity divergence (1/s)
      32              : 
      33              : // Initial condition constants
      34              : #define INIT_U_BASE   1.0
      35              : #define INIT_U_VAR    0.1
      36              : #define INIT_V_VAR    0.05
      37              : #define INIT_PRESSURE 1.0
      38              : #define INIT_DENSITY  1.0
      39              : #define INIT_TEMP     300.0
      40              : 
      41              : // Perturbation constants
      42              : #define PERTURB_CENTER_X    1.0
      43              : #define PERTURB_CENTER_Y    0.5
      44              : #define PERTURB_RADIUS      0.2
      45              : #define PERTURB_WIDTH_SQ    0.02
      46              : #define PERTURB_MAG         0.1
      47              : #define PERTURB_GRAD_FACTOR 2.0
      48              : 
      49              : // Time stepping and stability constants
      50              : #define VELOCITY_EPSILON      1e-20
      51              : #define SPEED_EPSILON         1e-10
      52              : #define DT_MAX_LIMIT          0.01
      53              : #define DT_MIN_LIMIT          1e-6
      54              : /* One definition lives in navier_stokes_solver.h (NS_EULER_DT_LIMIT). */
      55              : #define DT_CONSERVATIVE_LIMIT NS_EULER_DT_LIMIT
      56              : 
      57              : // Update limits
      58              : #define UPDATE_LIMIT           1.0
      59              : #define PRESSURE_UPDATE_FACTOR 0.1
      60              : 
      61              : // Helper function to initialize ns_solver_params_t with default values
      62          682 : ns_solver_params_t ns_solver_params_default(void) {
      63          682 :     ns_solver_params_t params = {.dt = DEFAULT_TIME_STEP,
      64              :                             .cfl = DEFAULT_CFL_NUMBER,
      65              :                             .gamma = DEFAULT_GAMMA,
      66              :                             .mu = DEFAULT_VISCOSITY,
      67              :                             .k = DEFAULT_THERMAL_CONDUCTIVITY,
      68              :                             .max_iter = DEFAULT_MAX_ITERATIONS,
      69              :                             .tolerance = DEFAULT_TOLERANCE,
      70              :                             .source_amplitude_u = DEFAULT_SOURCE_AMPLITUDE_U,
      71              :                             .source_amplitude_v = DEFAULT_SOURCE_AMPLITUDE_V,
      72              :                             .source_decay_rate = DEFAULT_SOURCE_DECAY_RATE,
      73              :                             .pressure_coupling = DEFAULT_PRESSURE_COUPLING,
      74              :                             .alpha = 0.0,
      75              :                             .beta = 0.0,
      76              :                             .T_ref = 0.0,
      77              :                             .gravity = {0.0, 0.0, 0.0},
      78              :                             .heat_source_func = NULL,
      79              :                             .heat_source_context = NULL,
      80              :                             .thermal_bc = {0},
      81              :                             .turb_model = TURB_MODEL_NONE,
      82              :                             .turb_bc = {0},
      83              :                             .pressure_solver = NS_PRESSURE_SOLVER_DEFAULT,
      84              :                             .convection_scheme = NS_CONVECTION_SCHEME_CENTRAL,
      85              :                             .viscous_scheme = NS_VISCOUS_SCHEME_EXPLICIT};
      86          682 :     return params;
      87              : }
      88          664 : flow_field* flow_field_create(size_t nx, size_t ny, size_t nz) {
      89          664 :     if (nx == 0 || ny == 0 || nz == 0) {
      90            3 :         cfd_set_error(CFD_ERROR_INVALID, "Flow field dimensions must be positive");
      91            3 :         return NULL;
      92              :     }
      93              : 
      94          661 :     flow_field* field = (flow_field*)cfd_calloc(1, sizeof(flow_field));
      95          661 :     if (field == NULL) {
      96              :         return NULL;
      97              :     }
      98              : 
      99          661 :     field->nx = nx;
     100          661 :     field->ny = ny;
     101          661 :     field->nz = nz;
     102              : 
     103          661 :     size_t total = nx * ny * nz;
     104              : 
     105              :     // Allocate 32-byte aligned memory for flow variables (optimized for SIMD operations)
     106          661 :     field->u = (double*)cfd_aligned_calloc(total, sizeof(double));
     107          661 :     field->v = (double*)cfd_aligned_calloc(total, sizeof(double));
     108          661 :     field->w = (double*)cfd_aligned_calloc(total, sizeof(double));
     109          661 :     field->p = (double*)cfd_aligned_calloc(total, sizeof(double));
     110          661 :     field->rho = (double*)cfd_aligned_calloc(total, sizeof(double));
     111          661 :     field->T = (double*)cfd_aligned_calloc(total, sizeof(double));
     112          661 :     field->turb_k = (double*)cfd_aligned_calloc(total, sizeof(double));
     113          661 :     field->turb_eps = (double*)cfd_aligned_calloc(total, sizeof(double));
     114          661 :     field->turb_nu_tilde = (double*)cfd_aligned_calloc(total, sizeof(double));
     115          661 :     field->nu_t = (double*)cfd_aligned_calloc(total, sizeof(double));
     116              : 
     117          661 :     if (!field->u || !field->v || !field->w || !field->p || !field->rho || !field->T ||
     118          661 :         !field->turb_k || !field->turb_eps || !field->turb_nu_tilde || !field->nu_t) {
     119            0 :         flow_field_destroy(field);
     120            0 :         return NULL;
     121              :     }
     122              : 
     123              :     return field;
     124              : }
     125              : 
     126          664 : void flow_field_destroy(flow_field* field) {
     127          664 :     if (field != NULL) {
     128          661 :         cfd_aligned_free(field->u);
     129          661 :         cfd_aligned_free(field->v);
     130          661 :         cfd_aligned_free(field->w);
     131          661 :         cfd_aligned_free(field->p);
     132          661 :         cfd_aligned_free(field->rho);
     133          661 :         cfd_aligned_free(field->T);
     134          661 :         cfd_aligned_free(field->turb_k);
     135          661 :         cfd_aligned_free(field->turb_eps);
     136          661 :         cfd_aligned_free(field->turb_nu_tilde);
     137          661 :         cfd_aligned_free(field->nu_t);
     138          661 :         cfd_free(field);
     139              :     }
     140          664 : }
     141              : 
     142          123 : void initialize_flow_field(flow_field* field, const grid* grid) {
     143          123 :     size_t nx = field->nx;
     144          123 :     size_t ny = field->ny;
     145          123 :     size_t nz = field->nz;
     146          123 :     size_t plane = nx * ny;
     147              : 
     148          246 :     for (size_t k = 0; k < nz; k++) {
     149          123 :         size_t base = k * plane;
     150         1266 :         for (size_t j = 0; j < ny; j++) {
     151        12532 :             for (size_t i = 0; i < nx; i++) {
     152        11389 :                 size_t idx = base + IDX_2D(i, j, nx);
     153        11389 :                 double x = grid->x[i];
     154        11389 :                 double y = grid->y[j];
     155              : 
     156        11389 :                 field->u[idx] =
     157        11389 :                     INIT_U_BASE + (INIT_U_VAR * sin(M_PI * y));
     158        11389 :                 field->v[idx] = INIT_V_VAR * sin(2.0 * M_PI * x);
     159        11389 :                 field->w[idx] = 0.0;
     160        11389 :                 field->p[idx] = INIT_PRESSURE;
     161        11389 :                 field->rho[idx] = INIT_DENSITY;
     162        11389 :                 field->T[idx] = INIT_TEMP;
     163              : 
     164        11389 :                 double cx = PERTURB_CENTER_X, cy = PERTURB_CENTER_Y;
     165        11389 :                 double r = sqrt(((x - cx) * (x - cx)) + ((y - cy) * (y - cy)));
     166        11389 :                 if (r < PERTURB_RADIUS) {
     167          668 :                     field->p[idx] += PERTURB_MAG * exp(-r * r / PERTURB_WIDTH_SQ);
     168          668 :                     double dp_dx = -PERTURB_MAG * PERTURB_GRAD_FACTOR * (x - cx) / PERTURB_WIDTH_SQ *
     169          668 :                                    exp(-r * r / PERTURB_WIDTH_SQ);
     170          668 :                     double dp_dy = -PERTURB_MAG * PERTURB_GRAD_FACTOR * (y - cy) / PERTURB_WIDTH_SQ *
     171          668 :                                    exp(-r * r / PERTURB_WIDTH_SQ);
     172          668 :                     field->u[idx] += -PERTURB_MAG * dp_dx;
     173          668 :                     field->v[idx] += -PERTURB_MAG * dp_dy;
     174              :                 }
     175              :             }
     176              :         }
     177              :     }
     178          123 : }
     179              : 
     180              : /* ---------------------------------------------------------------------------
     181              :  * Time-step stability constraints
     182              :  *
     183              :  * Each returns the largest stable dt for one physical process, or INFINITY when
     184              :  * that process imposes no limit, so callers compose them with a plain minimum.
     185              :  * A solver that treats a term implicitly simply leaves its constraint out.
     186              :  * ------------------------------------------------------------------------- */
     187              : 
     188              : /** Smallest spacing over the active dimensions. */
     189           70 : double ns_grid_min_spacing(const grid* grid) {
     190           70 :     double dmin = min_double(grid->dx[0], grid->dy[0]);
     191         2492 :     for (size_t i = 0; i < grid->nx - 1; i++) {
     192         2422 :         dmin = min_double(dmin, grid->dx[i]);
     193              :     }
     194         2492 :     for (size_t j = 0; j < grid->ny - 1; j++) {
     195         2422 :         dmin = min_double(dmin, grid->dy[j]);
     196              :     }
     197           70 :     if (grid->nz > 1 && grid->dz) {
     198          196 :         for (size_t k = 0; k < grid->nz - 1; k++) {
     199          184 :             dmin = min_double(dmin, grid->dz[k]);
     200              :         }
     201              :     }
     202           70 :     return dmin;
     203              : }
     204              : 
     205              : /** Advective/acoustic CFL limit: cfl * dmin / max_speed. */
     206           39 : double ns_dt_convective(const flow_field* field, const grid* grid,
     207              :                         const ns_solver_params_t* params) {
     208           39 :     double max_speed = 0.0;
     209           39 :     int has_w = (grid->nz > 1 && field->w);
     210              : 
     211              :     // Sweep every cell, not just the k = 0 plane: a 3D field whose fastest
     212              :     // flow sits at k > 0 would otherwise set dt from one slice and exceed the
     213              :     // CFL limit everywhere else. Matches ns_dt_viscous(), which already walks
     214              :     // nx*ny*nz.
     215           39 :     const size_t total = field->nx * field->ny * field->nz;
     216       125104 :     for (size_t n = 0; n < total; n++) {
     217       125065 :         double u_speed = fabs(field->u[n]);
     218       125065 :         double v_speed = fabs(field->v[n]);
     219       125065 :         double sound_speed = sqrt(params->gamma * field->p[n] / field->rho[n]);
     220              : 
     221              :         // Optimized velocity magnitude calculation - avoid sqrt when possible
     222       125065 :         double vel_mag_sq = (u_speed * u_speed) + (v_speed * v_speed);
     223       125065 :         if (has_w) {
     224        39437 :             double w_speed = fabs(field->w[n]);
     225        39437 :             vel_mag_sq += w_speed * w_speed;
     226              :         }
     227       125065 :         double vel_mag = (vel_mag_sq > VELOCITY_EPSILON) ? sqrt(vel_mag_sq) : 0.0;
     228       125065 :         double local_speed = vel_mag + sound_speed;
     229       125065 :         max_speed = max_double(max_speed, local_speed);
     230              :     }
     231              : 
     232              :     // Prevent division by zero and ensure reasonable time step
     233           39 :     if (max_speed < SPEED_EPSILON) {
     234            1 :         max_speed = 1.0;  // Use default if speeds are too small
     235              :     }
     236              : 
     237           39 :     return params->cfl * ns_grid_min_spacing(grid) / max_speed;
     238              : }
     239              : 
     240              : /**
     241              :  * Viscous diffusion limit: dt < dmin^2 / (2 * nu_eff * ndim).
     242              :  *
     243              :  * Applies to the molecular viscosity as well as any eddy viscosity. It scales
     244              :  * as dmin^2 against the convective limit's dmin, so it becomes the binding
     245              :  * constraint as grids refine: at Re=100 on a 129x129 unit cavity it is already
     246              :  * several times tighter than the CFL limit.
     247              :  */
     248           37 : double ns_dt_viscous(const flow_field* field, const grid* grid,
     249              :                      const ns_solver_params_t* params) {
     250           37 :     size_t total = field->nx * field->ny * field->nz;
     251           37 :     double nu_t_max = 0.0;
     252           37 :     double rho_min = field->rho[0];
     253              : 
     254       122924 :     for (size_t n = 0; n < total; n++) {
     255       122887 :         rho_min = min_double(rho_min, field->rho[n]);
     256              :     }
     257              :     /* Eddy viscosity counts only when a model is active and has run; it can
     258              :      * exceed the molecular value by orders of magnitude. */
     259           37 :     if (params->turb_model != TURB_MODEL_NONE && field->nu_t) {
     260            0 :         for (size_t n = 0; n < total; n++) {
     261            0 :             nu_t_max = max_double(nu_t_max, field->nu_t[n]);
     262              :         }
     263              :     }
     264              : 
     265              :     /* Minimum density gives the largest (most restrictive) local nu; floor it
     266              :      * like the kernels do (local_nu) rather than substituting 1.0, which would
     267              :      * overestimate the stable dt at low densities. */
     268           37 :     double rho_ref = max_double(rho_min, 1e-10);
     269           37 :     double nu_eff_max = params->mu / rho_ref + nu_t_max;
     270           37 :     if (nu_eff_max <= 0.0) {
     271              :         return INFINITY;  /* inviscid: no diffusive limit */
     272              :     }
     273              : 
     274           31 :     int ndim = (grid->nz > 1) ? 3 : 2;
     275           31 :     double dmin = ns_grid_min_spacing(grid);
     276           31 :     return params->cfl * (dmin * dmin) / (2.0 * nu_eff_max * ndim);
     277              : }
     278              : 
     279              : /** Thermal diffusion limit: dt < dmin^2 / (2 * alpha * ndim). */
     280           39 : double ns_dt_thermal(const flow_field* field, const grid* grid,
     281              :                      const ns_solver_params_t* params) {
     282           39 :     (void)field;
     283           39 :     if (params->alpha <= 0.0) {
     284              :         return INFINITY;  /* energy equation inactive */
     285              :     }
     286            0 :     int ndim = (grid->nz > 1) ? 3 : 2;
     287            0 :     double dmin = ns_grid_min_spacing(grid);
     288            0 :     return params->cfl * (dmin * dmin) / (2.0 * params->alpha * ndim);
     289              : }
     290              : 
     291           39 : void compute_time_step(flow_field* field, const grid* grid, ns_solver_params_t* params) {
     292           39 :     double dt_stable = ns_dt_convective(field, grid, params);
     293              :     /* An implicit viscous scheme removes the diffusion limit; that is its point */
     294           39 :     if (params->viscous_scheme == NS_VISCOUS_SCHEME_EXPLICIT) {
     295           37 :         dt_stable = min_double(dt_stable, ns_dt_viscous(field, grid, params));
     296              :     }
     297           39 :     dt_stable = min_double(dt_stable, ns_dt_thermal(field, grid, params));
     298              : 
     299              :     // Limit time step to reasonable bounds
     300           39 :     params->dt = max_double(DT_MIN_LIMIT, min_double(DT_MAX_LIMIT, dt_stable));
     301           39 : }
     302        13210 : void apply_boundary_conditions(flow_field* field, const grid* grid) {
     303        13210 :     (void)grid;
     304        13210 :     size_t nx = field->nx;
     305        13210 :     size_t ny = field->ny;
     306        13210 :     size_t nz = field->nz;
     307        13210 :     size_t plane = nx * ny;
     308              : 
     309              :     /* Apply periodic BCs in x and y for each z-plane */
     310        26975 :     for (size_t k = 0; k < nz; k++) {
     311        13765 :         size_t base = k * plane;
     312              : 
     313              :         /* x-direction periodic */
     314       933497 :         for (size_t j = 0; j < ny; j++) {
     315       919732 :             size_t left = base + IDX_2D(0, j, nx);
     316       919732 :             size_t right = base + IDX_2D(nx - 1, j, nx);
     317       919732 :             size_t src_left = base + IDX_2D(nx - 2, j, nx);
     318       919732 :             size_t src_right = base + IDX_2D(1, j, nx);
     319              : 
     320       919732 :             field->u[left] = field->u[src_left];
     321       919732 :             field->v[left] = field->v[src_left];
     322       919732 :             field->w[left] = field->w[src_left];
     323       919732 :             field->p[left] = field->p[src_left];
     324       919732 :             field->rho[left] = field->rho[src_left];
     325       919732 :             field->T[left] = field->T[src_left];
     326              : 
     327       919732 :             field->u[right] = field->u[src_right];
     328       919732 :             field->v[right] = field->v[src_right];
     329       919732 :             field->w[right] = field->w[src_right];
     330       919732 :             field->p[right] = field->p[src_right];
     331       919732 :             field->rho[right] = field->rho[src_right];
     332       919732 :             field->T[right] = field->T[src_right];
     333              :         }
     334              : 
     335              :         /* y-direction periodic */
     336       978836 :         for (size_t i = 0; i < nx; i++) {
     337       965071 :             size_t bot = base + i;
     338       965071 :             size_t top = base + IDX_2D(i, ny - 1, nx);
     339       965071 :             size_t src_bot = base + IDX_2D(i, ny - 2, nx);
     340       965071 :             size_t src_top = base + IDX_2D(i, 1, nx);
     341              : 
     342       965071 :             field->u[bot] = field->u[src_bot];
     343       965071 :             field->v[bot] = field->v[src_bot];
     344       965071 :             field->w[bot] = field->w[src_bot];
     345       965071 :             field->p[bot] = field->p[src_bot];
     346       965071 :             field->rho[bot] = field->rho[src_bot];
     347       965071 :             field->T[bot] = field->T[src_bot];
     348              : 
     349       965071 :             field->u[top] = field->u[src_top];
     350       965071 :             field->v[top] = field->v[src_top];
     351       965071 :             field->w[top] = field->w[src_top];
     352       965071 :             field->p[top] = field->p[src_top];
     353       965071 :             field->rho[top] = field->rho[src_top];
     354       965071 :             field->T[top] = field->T[src_top];
     355              :         }
     356              :     }
     357              : 
     358              :     /* z-direction periodic (only when nz > 1) */
     359        13210 :     if (nz > 1) {
     360           90 :         size_t front_base = 0;
     361           90 :         size_t back_base = (nz - 1) * plane;
     362           90 :         size_t src_front = (nz - 2) * plane;
     363           90 :         size_t src_back = 1 * plane;
     364              : 
     365          960 :         for (size_t j = 0; j < ny; j++) {
     366        10080 :             for (size_t i = 0; i < nx; i++) {
     367         9210 :                 size_t off = IDX_2D(i, j, nx);
     368              : 
     369         9210 :                 field->u[front_base + off] = field->u[src_front + off];
     370         9210 :                 field->v[front_base + off] = field->v[src_front + off];
     371         9210 :                 field->w[front_base + off] = field->w[src_front + off];
     372         9210 :                 field->p[front_base + off] = field->p[src_front + off];
     373         9210 :                 field->rho[front_base + off] = field->rho[src_front + off];
     374         9210 :                 field->T[front_base + off] = field->T[src_front + off];
     375              : 
     376         9210 :                 field->u[back_base + off] = field->u[src_back + off];
     377         9210 :                 field->v[back_base + off] = field->v[src_back + off];
     378         9210 :                 field->w[back_base + off] = field->w[src_back + off];
     379         9210 :                 field->p[back_base + off] = field->p[src_back + off];
     380         9210 :                 field->rho[back_base + off] = field->rho[src_back + off];
     381         9210 :                 field->T[back_base + off] = field->T[src_back + off];
     382              :             }
     383              :         }
     384              :     }
     385        13210 : }
     386              : 
     387              : // Helper function to compute source terms consistently across all solvers
     388    157821370 : void compute_source_terms(double x, double y, double z, int iter, double dt,
     389              :                           const ns_solver_params_t* params,
     390              :                           double* source_u, double* source_v, double* source_w) {
     391              :     // Use custom source function if provided
     392    157821370 :     if (params->source_func) {
     393    126418056 :         double t = iter * dt;
     394    126418056 :         params->source_func(x, y, z, t, params->source_context, source_u, source_v, source_w);
     395    126418056 :         return;
     396              :     }
     397              : 
     398              :     // Default source term implementation (no default w-source)
     399     31403314 :     *source_u =
     400     31403314 :         params->source_amplitude_u * sin(M_PI * y) * exp(-params->source_decay_rate * iter * dt);
     401     31403314 :     *source_v = params->source_amplitude_v * sin(2.0 * M_PI * x) *
     402     31403314 :                 exp(-params->source_decay_rate * iter * dt);
     403     31403314 :     *source_w = 0.0;
     404              : }
     405              : 
     406              : // Internal explicit Euler implementation
     407              : // This is called by the solver registry - not part of public API
     408         6414 : cfd_status_t explicit_euler_impl(flow_field* field, const grid* grid, const ns_solver_params_t* params) {
     409         6414 :     if (field->nx < 3 || field->ny < 3 || (field->nz > 1 && field->nz < 3)) {
     410              :         return CFD_ERROR_INVALID;
     411              :     }
     412              : 
     413         6414 :     size_t nx = field->nx;
     414         6414 :     size_t ny = field->ny;
     415         6414 :     size_t nz = field->nz;
     416              : 
     417              :     /* Reject non-uniform z-spacing (solver uses constant inv_2dz/inv_dz2) */
     418         6414 :     if (nz > 1 && grid->dz) {
     419          141 :         for (size_t k = 1; k < nz - 1; k++) {
     420          118 :             if (fabs(grid->dz[k] - grid->dz[0]) > 1e-14) {
     421              :                 return CFD_ERROR_INVALID;
     422              :             }
     423              :         }
     424              :     }
     425              : 
     426         6414 :     size_t plane = nx * ny;
     427         6414 :     size_t total = plane * nz;
     428         6414 :     size_t bytes = total * sizeof(double);
     429              : 
     430              :     /* Branch-free 3D constants: when nz==1, stride_z=0, inv_2dz=0, inv_dz2=0
     431              :      * so all z-terms vanish, producing identical results to 2D. */
     432         6414 :     size_t stride_z = (nz > 1) ? plane : 0;
     433         6414 :     size_t k_start = (nz > 1) ? 1 : 0;
     434         6414 :     size_t k_end   = (nz > 1) ? (nz - 1) : 1;
     435         6414 :     double inv_2dz = (nz > 1 && grid->dz) ? 1.0 / (2.0 * grid->dz[0]) : 0.0;
     436           23 :     double inv_dz2 = (nz > 1 && grid->dz) ? 1.0 / (grid->dz[0] * grid->dz[0]) : 0.0;
     437         6414 :     double inv_dz  = 2.0 * inv_2dz;
     438         6414 :     const int upwind = (params->convection_scheme == NS_CONVECTION_SCHEME_UPWIND);
     439              : 
     440         6414 :     double* u_new = (double*)cfd_calloc(total, sizeof(double));
     441         6414 :     double* v_new = (double*)cfd_calloc(total, sizeof(double));
     442         6414 :     double* w_new = (double*)cfd_calloc(total, sizeof(double));
     443         6414 :     double* p_new = (double*)cfd_calloc(total, sizeof(double));
     444         6414 :     double* rho_new = (double*)cfd_calloc(total, sizeof(double));
     445         6414 :     int needs_T_ws = (params->alpha > 0.0 || params->beta != 0.0);
     446         6414 :     double* T_energy_ws = needs_T_ws
     447            6 :         ? (double*)cfd_calloc(total, sizeof(double)) : NULL;
     448         6414 :     const int turb_on = (params->turb_model != TURB_MODEL_NONE);
     449        12828 :     double* turb_ws = turb_on
     450         6414 :         ? (double*)cfd_calloc(TURB_WORKSPACE_SIZE(total), sizeof(double)) : NULL;
     451              : 
     452         6414 :     if (!u_new || !v_new || !w_new || !p_new || !rho_new ||
     453         6414 :         (needs_T_ws && !T_energy_ws) || (turb_on && !turb_ws)) {
     454            0 :         cfd_free(u_new); cfd_free(v_new); cfd_free(w_new);
     455            0 :         cfd_free(p_new); cfd_free(rho_new); cfd_free(T_energy_ws);
     456            0 :         cfd_free(turb_ws);
     457            0 :         return CFD_ERROR_NOMEM;
     458              :     }
     459              : 
     460         6414 :     memcpy(u_new, field->u, bytes);
     461         6414 :     memcpy(v_new, field->v, bytes);
     462         6414 :     memcpy(w_new, field->w, bytes);
     463         6414 :     memcpy(p_new, field->p, bytes);
     464         6414 :     memcpy(rho_new, field->rho, bytes);
     465              : 
     466         6414 :     double conservative_dt = fmin(params->dt, DT_CONSERVATIVE_LIMIT);
     467              : 
     468        12940 :     for (int iter = 0; iter < params->max_iter; iter++) {
     469        13151 :         for (size_t k = k_start; k < k_end; k++) {
     470       449034 :             for (size_t j = 1; j < ny - 1; j++) {
     471     45015138 :                 for (size_t i = 1; i < nx - 1; i++) {
     472     44572727 :                     size_t idx = k * stride_z + IDX_2D(i, j, nx);
     473              : 
     474     44572727 :                     if (field->rho[idx] <= 1e-10) {
     475         2548 :                         continue;
     476              :                     }
     477     44570179 :                     if (fabs(grid->dx[i]) < 1e-10 || fabs(grid->dy[j]) < 1e-10) {
     478            0 :                         continue;
     479              :                     }
     480              : 
     481     44570179 :                     double u_c = field->u[idx];
     482     44570179 :                     double v_c = field->v[idx];
     483     44570179 :                     double w_c = field->w[idx];
     484              : 
     485              :                     /* First derivatives (central differences) */
     486     44570179 :                     double du_dx = (field->u[idx + 1] - field->u[idx - 1]) / (2.0 * grid->dx[i]);
     487     44570179 :                     double du_dy = (field->u[idx + nx] - field->u[idx - nx]) / (2.0 * grid->dy[j]);
     488     44570179 :                     double du_dz = (field->u[idx + stride_z] - field->u[idx - stride_z]) * inv_2dz;
     489              : 
     490     44570179 :                     double dv_dx = (field->v[idx + 1] - field->v[idx - 1]) / (2.0 * grid->dx[i]);
     491     44570179 :                     double dv_dy = (field->v[idx + nx] - field->v[idx - nx]) / (2.0 * grid->dy[j]);
     492     44570179 :                     double dv_dz = (field->v[idx + stride_z] - field->v[idx - stride_z]) * inv_2dz;
     493              : 
     494     44570179 :                     double dw_dx = (field->w[idx + 1] - field->w[idx - 1]) / (2.0 * grid->dx[i]);
     495     44570179 :                     double dw_dy = (field->w[idx + nx] - field->w[idx - nx]) / (2.0 * grid->dy[j]);
     496     44570179 :                     double dw_dz = (field->w[idx + stride_z] - field->w[idx - stride_z]) * inv_2dz;
     497              : 
     498              :                     /* Pressure gradients */
     499     44570179 :                     double dp_dx = (field->p[idx + 1] - field->p[idx - 1]) / (2.0 * grid->dx[i]);
     500     44570179 :                     double dp_dy = (field->p[idx + nx] - field->p[idx - nx]) / (2.0 * grid->dy[j]);
     501     44570179 :                     double dp_dz = (field->p[idx + stride_z] - field->p[idx - stride_z]) * inv_2dz;
     502              : 
     503              :                     /* Second derivatives (viscous terms) */
     504     44570179 :                     double d2u_dx2 = (field->u[idx + 1] - 2.0 * u_c + field->u[idx - 1]) /
     505     44570179 :                                      (grid->dx[i] * grid->dx[i]);
     506     44570179 :                     double d2u_dy2 = (field->u[idx + nx] - 2.0 * u_c + field->u[idx - nx]) /
     507     44570179 :                                      (grid->dy[j] * grid->dy[j]);
     508     44570179 :                     double d2u_dz2 = (field->u[idx + stride_z] - 2.0 * u_c +
     509              :                                       field->u[idx - stride_z]) * inv_dz2;
     510              : 
     511     44570179 :                     double d2v_dx2 = (field->v[idx + 1] - 2.0 * v_c + field->v[idx - 1]) /
     512              :                                      (grid->dx[i] * grid->dx[i]);
     513     44570179 :                     double d2v_dy2 = (field->v[idx + nx] - 2.0 * v_c + field->v[idx - nx]) /
     514              :                                      (grid->dy[j] * grid->dy[j]);
     515     44570179 :                     double d2v_dz2 = (field->v[idx + stride_z] - 2.0 * v_c +
     516              :                                       field->v[idx - stride_z]) * inv_dz2;
     517              : 
     518     44570179 :                     double d2w_dx2 = (field->w[idx + 1] - 2.0 * w_c + field->w[idx - 1]) /
     519              :                                      (grid->dx[i] * grid->dx[i]);
     520     44570179 :                     double d2w_dy2 = (field->w[idx + nx] - 2.0 * w_c + field->w[idx - nx]) /
     521              :                                      (grid->dy[j] * grid->dy[j]);
     522     44570179 :                     double d2w_dz2 = (field->w[idx + stride_z] - 2.0 * w_c +
     523              :                                       field->w[idx - stride_z]) * inv_dz2;
     524              : 
     525     44570179 :                     double nu = params->mu / fmax(field->rho[idx], 1e-10);
     526     44570179 :                     nu = fmin(nu, 1.0);
     527              : 
     528              :                     /* Clamp derivatives */
     529     44570179 :                     du_dx = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, du_dx));
     530     44570179 :                     du_dy = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, du_dy));
     531     44570179 :                     du_dz = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, du_dz));
     532     44570179 :                     dv_dx = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dv_dx));
     533     44570179 :                     dv_dy = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dv_dy));
     534     44570179 :                     dv_dz = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dv_dz));
     535     44570179 :                     dw_dx = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dw_dx));
     536     44570179 :                     dw_dy = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dw_dy));
     537     44570179 :                     dw_dz = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dw_dz));
     538     44570179 :                     dp_dx = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dp_dx));
     539     44570179 :                     dp_dy = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dp_dy));
     540     44570179 :                     dp_dz = fmax(-MAX_DERIVATIVE_LIMIT, fmin(MAX_DERIVATIVE_LIMIT, dp_dz));
     541     44570179 :                     d2u_dx2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2u_dx2));
     542     44570179 :                     d2u_dy2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2u_dy2));
     543     44570179 :                     d2u_dz2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2u_dz2));
     544     44570179 :                     d2v_dx2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2v_dx2));
     545     44570179 :                     d2v_dy2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2v_dy2));
     546     44570179 :                     d2v_dz2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2v_dz2));
     547     44570179 :                     d2w_dx2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2w_dx2));
     548     44570179 :                     d2w_dy2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2w_dy2));
     549     44570179 :                     d2w_dz2 = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, d2w_dz2));
     550              : 
     551              :                     /* Convective derivatives: the clamped central ones, or
     552              :                      * first-order upwind. The divergence below stays central. */
     553     44570179 :                     ns_conv_derivs_t cd = {du_dx, du_dy, du_dz, dv_dx, dv_dy, dv_dz,
     554              :                                            dw_dx, dw_dy, dw_dz};
     555     44570179 :                     if (upwind) {
     556        14880 :                         ns_upwind_conv_derivs(field->u, field->v, field->w, idx,
     557              :                                               idx - 1, idx + 1, idx - nx, idx + nx,
     558              :                                               idx - stride_z, idx + stride_z,
     559              :                                               grid->dx[i], grid->dy[j], inv_dz, &cd);
     560        14880 :                         ns_clamp_conv_derivs(&cd, MAX_DERIVATIVE_LIMIT);
     561              :                     }
     562              : 
     563              :                     /* Source terms */
     564     44570179 :                     double x = grid->x[i];
     565     44570179 :                     double y = grid->y[j];
     566     44570179 :                     double z = (nz > 1 && grid->z) ? grid->z[k] : 0.0;
     567     44570179 :                     double source_u, source_v, source_w;
     568     44570179 :                     compute_source_terms(x, y, z, iter, conservative_dt, params,
     569              :                                          &source_u, &source_v, &source_w);
     570              : 
     571              :                     /* Boussinesq buoyancy source */
     572     44570179 :                     energy_compute_buoyancy(field->T[idx], params,
     573              :                                             &source_u, &source_v, &source_w);
     574              : 
     575              :                     /* Viscous terms: laminar constant-nu Laplacian, or conservative
     576              :                      * face-averaged effective viscosity div((nu + nu_t) grad u)
     577              :                      * when a turbulence model is active. The z-term keeps the
     578              :                      * laminar nu (turbulence is 2D-only; vanishes when nz == 1). */
     579     44570179 :                     double visc_u, visc_v, visc_w;
     580     44570179 :                     if (!turb_on) {
     581     44570179 :                         visc_u = nu * (d2u_dx2 + d2u_dy2 + d2u_dz2);
     582     44570179 :                         visc_v = nu * (d2v_dx2 + d2v_dy2 + d2v_dz2);
     583     44570179 :                         visc_w = nu * (d2w_dx2 + d2w_dy2 + d2w_dz2);
     584              :                     } else {
     585            0 :                         const double* nu_t = field->nu_t;
     586              :                         /* Face-averaged nu_eff = nu + nu_t (nu_t already bounded by
     587              :                          * the realizability clamp; the flux clamp below caps it) */
     588            0 :                         double nu_xp = nu + 0.5 * (nu_t[idx] + nu_t[idx + 1]);
     589            0 :                         double nu_xm = nu + 0.5 * (nu_t[idx] + nu_t[idx - 1]);
     590            0 :                         double nu_yp = nu + 0.5 * (nu_t[idx] + nu_t[idx + nx]);
     591            0 :                         double nu_ym = nu + 0.5 * (nu_t[idx] + nu_t[idx - nx]);
     592            0 :                         double inv_dxi2 = 1.0 / (grid->dx[i] * grid->dx[i]);
     593            0 :                         double inv_dyj2 = 1.0 / (grid->dy[j] * grid->dy[j]);
     594              : 
     595            0 :                         double t_u_x = (nu_xp * (field->u[idx + 1] - u_c) -
     596            0 :                                         nu_xm * (u_c - field->u[idx - 1])) * inv_dxi2;
     597            0 :                         double t_u_y = (nu_yp * (field->u[idx + nx] - u_c) -
     598            0 :                                         nu_ym * (u_c - field->u[idx - nx])) * inv_dyj2;
     599            0 :                         double t_v_x = (nu_xp * (field->v[idx + 1] - v_c) -
     600            0 :                                         nu_xm * (v_c - field->v[idx - 1])) * inv_dxi2;
     601            0 :                         double t_v_y = (nu_yp * (field->v[idx + nx] - v_c) -
     602            0 :                                         nu_ym * (v_c - field->v[idx - nx])) * inv_dyj2;
     603            0 :                         double t_w_x = (nu_xp * (field->w[idx + 1] - w_c) -
     604            0 :                                         nu_xm * (w_c - field->w[idx - 1])) * inv_dxi2;
     605            0 :                         double t_w_y = (nu_yp * (field->w[idx + nx] - w_c) -
     606            0 :                                         nu_ym * (w_c - field->w[idx - nx])) * inv_dyj2;
     607              : 
     608              :                         /* Same safety clamp as the laminar second derivatives */
     609            0 :                         t_u_x = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, t_u_x));
     610            0 :                         t_u_y = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, t_u_y));
     611            0 :                         t_v_x = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, t_v_x));
     612            0 :                         t_v_y = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, t_v_y));
     613            0 :                         t_w_x = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, t_w_x));
     614            0 :                         t_w_y = fmax(-MAX_SECOND_DERIVATIVE_LIMIT, fmin(MAX_SECOND_DERIVATIVE_LIMIT, t_w_y));
     615              : 
     616            0 :                         visc_u = t_u_x + t_u_y + nu * d2u_dz2;
     617            0 :                         visc_v = t_v_x + t_v_y + nu * d2v_dz2;
     618            0 :                         visc_w = t_w_x + t_w_y + nu * d2w_dz2;
     619              :                     }
     620              : 
     621              :                     /* u-momentum */
     622     44570179 :                     double du = conservative_dt *
     623     44570179 :                         (-u_c * cd.du_dx - v_c * cd.du_dy - w_c * cd.du_dz
     624     44570179 :                          - dp_dx / field->rho[idx]
     625     44570179 :                          + visc_u
     626     44570179 :                          + source_u);
     627              : 
     628              :                     /* v-momentum */
     629     44570179 :                     double dv = conservative_dt *
     630     44570179 :                         (-u_c * cd.dv_dx - v_c * cd.dv_dy - w_c * cd.dv_dz
     631     44570179 :                          - dp_dy / field->rho[idx]
     632     44570179 :                          + visc_v
     633     44570179 :                          + source_v);
     634              : 
     635              :                     /* w-momentum */
     636     44570179 :                     double dw = conservative_dt *
     637     44570179 :                         (-u_c * cd.dw_dx - v_c * cd.dw_dy - w_c * cd.dw_dz
     638     44570179 :                          - dp_dz / field->rho[idx]
     639     44570179 :                          + visc_w
     640     44570179 :                          + source_w);
     641              : 
     642     44570179 :                     du = fmax(-UPDATE_LIMIT, fmin(UPDATE_LIMIT, du));
     643     44570179 :                     dv = fmax(-UPDATE_LIMIT, fmin(UPDATE_LIMIT, dv));
     644     44570179 :                     dw = fmax(-UPDATE_LIMIT, fmin(UPDATE_LIMIT, dw));
     645              : 
     646     44570179 :                     u_new[idx] = fmax(-MAX_VELOCITY_LIMIT, fmin(MAX_VELOCITY_LIMIT, u_c + du));
     647     44570179 :                     v_new[idx] = fmax(-MAX_VELOCITY_LIMIT, fmin(MAX_VELOCITY_LIMIT, v_c + dv));
     648     44570179 :                     w_new[idx] = fmax(-MAX_VELOCITY_LIMIT, fmin(MAX_VELOCITY_LIMIT, w_c + dw));
     649              : 
     650              :                     /* Pressure update from divergence */
     651     44570179 :                     double divergence = du_dx + dv_dy + dw_dz;
     652     44570179 :                     divergence = fmax(-MAX_DIVERGENCE_LIMIT, fmin(MAX_DIVERGENCE_LIMIT, divergence));
     653     44570179 :                     double dp = -PRESSURE_UPDATE_FACTOR * conservative_dt * field->rho[idx] * divergence;
     654     44570179 :                     dp = fmax(-UPDATE_LIMIT, fmin(UPDATE_LIMIT, dp));
     655     44570179 :                     p_new[idx] = field->p[idx] + dp;
     656              : 
     657     44570179 :                     rho_new[idx] = field->rho[idx];
     658              :                 }
     659              :             }
     660              :         }
     661              : 
     662              :         /* Copy new solution */
     663         6528 :         memcpy(field->u, u_new, bytes);
     664         6528 :         memcpy(field->v, v_new, bytes);
     665         6528 :         memcpy(field->w, w_new, bytes);
     666         6528 :         memcpy(field->p, p_new, bytes);
     667         6528 :         memcpy(field->rho, rho_new, bytes);
     668              : 
     669              :         /* Energy equation: advance temperature using updated velocity */
     670              :         {
     671         6528 :             cfd_status_t energy_status = energy_step_explicit_with_workspace(
     672              :                 field, grid, params, conservative_dt,
     673              :                 iter * conservative_dt, T_energy_ws, total);
     674         6528 :             if (energy_status != CFD_SUCCESS) {
     675            0 :                 cfd_free(u_new); cfd_free(v_new); cfd_free(w_new);
     676            0 :                 cfd_free(p_new); cfd_free(rho_new); cfd_free(T_energy_ws);
     677            0 :                 cfd_free(turb_ws);
     678            0 :                 return energy_status;
     679              :             }
     680              :         }
     681              : 
     682              :         /* Save caller velocity BCs, apply periodic BCs, restore velocity BCs.
     683              :          * Then apply configured thermal BCs (overwrites periodic T values). */
     684         6528 :         copy_boundary_velocities_3d(u_new, v_new, w_new,
     685         6528 :                                     field->u, field->v, field->w, nx, ny, nz);
     686         6528 :         apply_boundary_conditions(field, grid);
     687         6528 :         copy_boundary_velocities_3d(field->u, field->v, field->w,
     688              :                                     u_new, v_new, w_new, nx, ny, nz);
     689         6528 :         cfd_status_t bc_status = energy_apply_thermal_bcs(field, params);
     690         6528 :         if (bc_status != CFD_SUCCESS) {
     691            0 :             cfd_free(u_new); cfd_free(v_new); cfd_free(w_new);
     692            0 :             cfd_free(p_new); cfd_free(rho_new); cfd_free(T_energy_ws);
     693            0 :             cfd_free(turb_ws);
     694            0 :             return bc_status;
     695              :         }
     696              : 
     697              :         /* Turbulence transport: advance k-eps/SA with the updated velocity,
     698              :          * then apply turbulence BCs (including wall functions) */
     699              :         {
     700         6528 :             cfd_status_t turb_status = turbulence_step_explicit_with_workspace(
     701              :                 field, grid, params, conservative_dt, iter * conservative_dt,
     702              :                 turb_ws, turb_on ? TURB_WORKSPACE_SIZE(total) : 0);
     703         6528 :             if (turb_status == CFD_SUCCESS) {
     704         6528 :                 turb_status = turbulence_apply_bcs(field, grid, params);
     705              :             }
     706         6528 :             if (turb_status != CFD_SUCCESS) {
     707            0 :                 cfd_free(u_new); cfd_free(v_new); cfd_free(w_new);
     708            0 :                 cfd_free(p_new); cfd_free(rho_new); cfd_free(T_energy_ws);
     709            0 :                 cfd_free(turb_ws);
     710            0 :                 return turb_status;
     711              :             }
     712              :         }
     713              : 
     714              :         /* NaN/Inf check */
     715     46393315 :         int has_nan = 0;
     716     46393315 :         for (size_t n = 0; n < total; n++) {
     717     46386789 :             if (!isfinite(field->u[n]) || !isfinite(field->v[n]) ||
     718     46386789 :                 !isfinite(field->w[n]) || !isfinite(field->p[n])) {
     719              :                 has_nan = 1;
     720              :                 break;
     721              :             }
     722              :         }
     723         6528 :         if (has_nan) {
     724            2 :             cfd_free(u_new); cfd_free(v_new); cfd_free(w_new);
     725            2 :             cfd_free(p_new); cfd_free(rho_new); cfd_free(T_energy_ws);
     726            2 :             cfd_free(turb_ws);
     727            2 :             cfd_set_error(CFD_ERROR_DIVERGED,
     728              :                           "NaN/Inf detected in explicit_euler step");
     729            2 :             return CFD_ERROR_DIVERGED;
     730              :         }
     731              :     }
     732              : 
     733         6412 :     cfd_free(u_new); cfd_free(v_new); cfd_free(w_new);
     734         6412 :     cfd_free(p_new); cfd_free(rho_new); cfd_free(T_energy_ws);
     735         6412 :     cfd_free(turb_ws);
     736              : 
     737         6412 :     return CFD_SUCCESS;
     738              : }
        

Generated by: LCOV version 2.0-1