LCOV - code coverage report
Current view: top level - api - simulation_api.c (source / functions) Coverage Total Hit
Test: coverage.info Lines: 79.5 % 312 248
Test Date: 2026-10-05 04:47:18 Functions: 100.0 % 22 22

            Line data    Source code
       1              : #include "cfd/api/simulation_api.h"
       2              : #include "cfd/core/cfd_status.h"
       3              : #include "cfd/core/derived_fields.h"
       4              : #include "cfd/core/grid.h"
       5              : #include "cfd/core/memory.h"
       6              : #include "cfd/io/checkpoint.h"
       7              : #include "cfd/io/output_registry.h"
       8              : #include "cfd/solvers/navier_stokes_solver.h"
       9              : 
      10              : #include "../solvers/turbulence/turbulence_solver_internal.h"
      11              : 
      12              : #include "cfd/core/cfd_init.h"
      13              : #include <math.h>
      14              : #include <stdio.h>
      15              : #include <stdlib.h>
      16              : #include <string.h>
      17              : 
      18              : // simulation_data struct is defined in simulation_api.h
      19              : 
      20              : // Default solver type used when none is specified
      21              : #define DEFAULT_SOLVER_TYPE NS_SOLVER_TYPE_EXPLICIT_EULER
      22              : 
      23              : // Ensure registry is initialized
      24              : // Internal helper to create simulation with a specific solver
      25           90 : static simulation_data* create_simulation_with_solver(size_t nx, size_t ny, size_t nz,
      26              :                                                        double xmin, double xmax,
      27              :                                                        double ymin, double ymax,
      28              :                                                        double zmin, double zmax,
      29              :                                                        const char* solver_type) {
      30              :     // Lazy initialization of library
      31           90 :     if (!cfd_is_initialized()) {
      32            7 :         if (cfd_init() != CFD_SUCCESS) {
      33            0 :             cfd_set_error(CFD_ERROR, "Failed to initialize CFD library");
      34            0 :             return NULL;
      35              :         }
      36              :     }
      37              : 
      38           90 :     if (nx == 0 || ny == 0 || nz == 0) {
      39            2 :         cfd_set_error(CFD_ERROR_INVALID, "Simulation grid dimensions must be positive");
      40            2 :         return NULL;
      41              :     }
      42           88 :     if (xmax <= xmin || ymax <= ymin || (nz > 1 && zmax <= zmin)) {
      43            2 :         cfd_set_error(CFD_ERROR_INVALID, "Simulation bounds invalid");
      44            2 :         return NULL;
      45              :     }
      46              : 
      47           86 :     simulation_data* sim_data = (simulation_data*)cfd_malloc(sizeof(simulation_data));
      48           86 :     if (!sim_data) {
      49              :         return NULL;
      50              :     }
      51              : 
      52              :     // Initialize base output directory
      53           86 :     snprintf(sim_data->output_base_dir, sizeof(sim_data->output_base_dir), "../../artifacts");
      54              : 
      55              :     // Create and initialize grid
      56           86 :     sim_data->grid = grid_create(nx, ny, nz, xmin, xmax, ymin, ymax, zmin, zmax);
      57           86 :     if (!sim_data->grid) {
      58            0 :         cfd_free(sim_data);
      59            0 :         return NULL;
      60              :     }
      61           86 :     grid_initialize_uniform(sim_data->grid);
      62              : 
      63              :     // Create flow_field
      64           86 :     sim_data->field = flow_field_create(nx, ny, nz);
      65           86 :     if (!sim_data->field) {
      66            0 :         grid_destroy(sim_data->grid);
      67            0 :         cfd_free(sim_data);
      68            0 :         return NULL;
      69              :     }
      70           86 :     initialize_flow_field(sim_data->field, sim_data->grid);
      71              : 
      72              :     // Initialize solver parameters with defaults
      73           86 :     sim_data->params = ns_solver_params_default();
      74           86 :     sim_data->params.dt = 0.001;
      75           86 :     sim_data->params.cfl = 0.2;
      76           86 :     sim_data->params.mu = 0.01;
      77           86 :     sim_data->params.max_iter = 1;
      78              : 
      79              :     // Initialize stats
      80           86 :     sim_data->last_stats = ns_solver_stats_default();
      81              : 
      82              :     // Create output registry
      83           86 :     sim_data->outputs = output_registry_create();
      84           86 :     if (!sim_data->outputs) {
      85            0 :         flow_field_destroy(sim_data->field);
      86            0 :         grid_destroy(sim_data->grid);
      87            0 :         cfd_free(sim_data);
      88            0 :         return NULL;
      89              :     }
      90           86 :     sim_data->run_prefix = NULL;
      91           86 :     sim_data->current_time = 0.0;
      92              : 
      93              :     // Initialize NSSolver Registry
      94           86 :     sim_data->registry = cfd_registry_create();
      95           86 :     if (!sim_data->registry) {
      96            0 :         output_registry_destroy(sim_data->outputs);
      97            0 :         flow_field_destroy(sim_data->field);
      98            0 :         grid_destroy(sim_data->grid);
      99            0 :         cfd_free(sim_data);
     100            0 :         return NULL;
     101              :     }
     102           86 :     cfd_registry_register_defaults(sim_data->registry);
     103              : 
     104              :     // Create and initialize the solver
     105           86 :     sim_data->solver = cfd_solver_create(sim_data->registry, solver_type);
     106           86 :     if (!sim_data->solver) {
     107              :         // Failed to create solver - cleanup and return NULL
     108            1 :         cfd_registry_destroy(sim_data->registry);
     109            1 :         output_registry_destroy(sim_data->outputs);
     110            1 :         flow_field_destroy(sim_data->field);
     111            1 :         grid_destroy(sim_data->grid);
     112            1 :         cfd_free(sim_data);
     113            1 :         return NULL;
     114              :     }
     115              : 
     116           85 :     cfd_status_t init_status = solver_init(sim_data->solver, sim_data->grid, &sim_data->params);
     117           85 :     if (init_status != CFD_SUCCESS) {
     118              :         // Keep a message the solver recorded; otherwise record the status so the
     119              :         // caller can tell why no simulation was returned.
     120            1 :         if (cfd_get_last_status() != init_status) {
     121            0 :             cfd_set_error(init_status, "init_simulation: solver init failed");
     122              :         }
     123            1 :         free_simulation(sim_data);
     124            1 :         return NULL;
     125              :     }
     126              : 
     127              :     return sim_data;
     128              : }
     129              : 
     130              : // Initialize simulation with default solver
     131           76 : simulation_data* init_simulation(size_t nx, size_t ny, size_t nz,
     132              :                                   double xmin, double xmax,
     133              :                                   double ymin, double ymax,
     134              :                                   double zmin, double zmax) {
     135           76 :     return create_simulation_with_solver(nx, ny, nz, xmin, xmax, ymin, ymax, zmin, zmax,
     136              :                                           DEFAULT_SOLVER_TYPE);
     137              : }
     138              : 
     139              : // Initialize simulation with a specific solver type
     140           14 : simulation_data* init_simulation_with_solver(size_t nx, size_t ny, size_t nz,
     141              :                                               double xmin, double xmax,
     142              :                                               double ymin, double ymax,
     143              :                                               double zmin, double zmax,
     144              :                                               const char* solver_type) {
     145           14 :     if (!solver_type) {
     146            1 :         solver_type = DEFAULT_SOLVER_TYPE;
     147              :     }
     148           14 :     return create_simulation_with_solver(nx, ny, nz, xmin, xmax, ymin, ymax, zmin, zmax,
     149              :                                           solver_type);
     150              : }
     151              : 
     152              : // Set the solver for an existing simulation
     153            3 : void simulation_set_solver(simulation_data* sim_data, struct NSSolver* solver) {
     154            3 :     if (!sim_data || !solver) {
     155            2 :         cfd_set_error(CFD_ERROR_INVALID, "Invalid arguments for simulation_set_solver");
     156            2 :         return;
     157              :     }
     158              : 
     159              :     // Destroy existing solver
     160            1 :     if (sim_data->solver) {
     161            1 :         solver_destroy(sim_data->solver);
     162              :     }
     163              : 
     164            1 :     sim_data->solver = solver;
     165            1 :     solver_init(solver, sim_data->grid, &sim_data->params);
     166              : }
     167              : 
     168              : // Set the solver by type name
     169            6 : int simulation_set_solver_by_name(simulation_data* sim_data, const char* solver_type) {
     170            6 :     if (!sim_data || !solver_type) {
     171            4 :         cfd_set_error(CFD_ERROR_INVALID, "Invalid arguments for simulation solver");
     172            4 :         return -1;
     173              :     }
     174              : 
     175            2 :     struct NSSolver* solver = cfd_solver_create(sim_data->registry, solver_type);
     176            2 :     if (!solver) {
     177              :         return -1;
     178              :     }
     179              : 
     180            1 :     simulation_set_solver(sim_data, solver);
     181            1 :     return 0;
     182              : }
     183              : 
     184              : // Get the current solver
     185            2 : struct NSSolver* simulation_get_solver(simulation_data* sim_data) {
     186            2 :     return sim_data ? sim_data->solver : NULL;
     187              : }
     188              : 
     189              : // Get statistics from the last solve
     190            3 : const ns_solver_stats_t* simulation_get_stats(const simulation_data* sim_data) {
     191            3 :     return sim_data ? &sim_data->last_stats : NULL;
     192              : }
     193              : 
     194              : // Run simulation step
     195           29 : cfd_status_t run_simulation_step(simulation_data* sim_data) {
     196           29 :     if (!sim_data || !sim_data->solver) {
     197              :         return CFD_ERROR_INVALID;
     198              :     }
     199              : 
     200              :     /* Stats describe this call only: a call refused before dispatch would
     201              :      * otherwise leave the previous one's behind. */
     202           28 :     sim_data->last_stats = ns_solver_stats_default();
     203           56 :     cfd_status_t status = solver_step(sim_data->solver, sim_data->field, sim_data->grid,
     204           28 :                                        &sim_data->params, &sim_data->last_stats);
     205           28 :     if (status != CFD_SUCCESS) {
     206              :         return status;
     207              :     }
     208              : 
     209              :     /* Advance by what the solver actually integrated, not by what we asked
     210              :      * for. The explicit-Euler kernels clamp their own step to
     211              :      * NS_EULER_DT_LIMIT, so accumulating params.dt would run current_time far
     212              :      * ahead of the physical time simulated. Both solver_step() and
     213              :      * solver_solve() seed dt_used with params.dt before dispatch, so it is
     214              :      * always populated even for solvers that do not override it. */
     215           23 :     sim_data->current_time += sim_data->last_stats.dt_used;
     216           23 :     return CFD_SUCCESS;
     217              : }
     218              : 
     219            9 : cfd_status_t run_simulation_solve(simulation_data* sim_data) {
     220            9 :     if (!sim_data || !sim_data->solver) {
     221              :         return CFD_ERROR_INVALID;
     222              :     }
     223              : 
     224              :     /* Reset first: current_time advances below even on failure, by the
     225              :      * iterations a failed solve did run, and a call refused before dispatch
     226              :      * (a bad dt or viscous scheme) runs none, so the previous call's stats
     227              :      * must not be counted again. */
     228            9 :     sim_data->last_stats = ns_solver_stats_default();
     229           18 :     cfd_status_t status = solver_solve(sim_data->solver, sim_data->field, sim_data->grid,
     230            9 :                                         &sim_data->params, &sim_data->last_stats);
     231              : 
     232              :     /* Same reasoning as run_simulation_step(): the per-iteration step the
     233              :      * solver actually took, times the iterations it reports. */
     234            9 :     sim_data->current_time += sim_data->last_stats.dt_used * sim_data->last_stats.iterations;
     235              : 
     236            9 :     return status;
     237              : }
     238              : 
     239              : // Free simulation data
     240              : // Free simulation data
     241           88 : void free_simulation(simulation_data* sim_data) {
     242           88 :     if (!sim_data) {
     243              :         return;
     244              :     }
     245              : 
     246           88 :     if (sim_data->solver) {
     247           88 :         solver_destroy(sim_data->solver);
     248           88 :         sim_data->solver = NULL;
     249              :     }
     250              : 
     251           88 :     if (sim_data->registry) {
     252           88 :         cfd_registry_destroy(sim_data->registry);
     253           88 :         sim_data->registry = NULL;
     254              :     }
     255              : 
     256           88 :     if (sim_data->outputs) {
     257           88 :         output_registry_destroy(sim_data->outputs);
     258           88 :         sim_data->outputs = NULL;
     259              :     }
     260              : 
     261           88 :     if (sim_data->run_prefix) {
     262            6 :         cfd_free(sim_data->run_prefix);
     263            6 :         sim_data->run_prefix = NULL;
     264              :     }
     265              : 
     266           88 :     flow_field_destroy(sim_data->field);
     267           88 :     grid_destroy(sim_data->grid);
     268           88 :     cfd_free(sim_data);
     269              : }
     270              : 
     271              : //=============================================================================
     272              : // RESTART / CHECKPOINT
     273              : //=============================================================================
     274              : 
     275            5 : cfd_status_t save_simulation_checkpoint(const simulation_data* sim_data, const char* path) {
     276            5 :     if (!sim_data || !path) {
     277            0 :         cfd_set_error(CFD_ERROR_INVALID, "save_simulation_checkpoint: NULL argument");
     278            0 :         return CFD_ERROR_INVALID;
     279              :     }
     280            5 :     if (!sim_data->grid || !sim_data->field || !sim_data->solver) {
     281            0 :         cfd_set_error(CFD_ERROR_INVALID, "save_simulation_checkpoint: simulation not initialized");
     282            0 :         return CFD_ERROR_INVALID;
     283              :     }
     284              : 
     285            5 :     const char* solver_name = sim_data->solver->name ? sim_data->solver->name : "";
     286            5 :     return cfd_checkpoint_write(path, sim_data->grid, sim_data->field, &sim_data->params,
     287            5 :                                 sim_data->current_time, solver_name, sim_data->run_prefix,
     288            5 :                                 sim_data->output_base_dir);
     289              : }
     290              : 
     291            3 : simulation_data* load_simulation_from_checkpoint(const char* path) {
     292            3 :     if (!path) {
     293            0 :         cfd_set_error(CFD_ERROR_INVALID, "load_simulation_from_checkpoint: NULL path");
     294            0 :         return NULL;
     295              :     }
     296            3 :     if (!cfd_is_initialized()) {
     297            0 :         if (cfd_init() != CFD_SUCCESS) {
     298            0 :             cfd_set_error(CFD_ERROR, "Failed to initialize CFD library");
     299            0 :             return NULL;
     300              :         }
     301              :     }
     302              : 
     303            3 :     grid* g = NULL;
     304            3 :     flow_field* f = NULL;
     305            3 :     ns_solver_params_t params;
     306            3 :     double current_time = 0.0;
     307            3 :     char solver_name[128] = {0};
     308            3 :     char run_prefix[256] = {0};
     309            3 :     char output_base_dir[512] = {0};
     310              : 
     311            3 :     cfd_status_t st = cfd_checkpoint_read(path, &g, &f, &params, &current_time, solver_name,
     312              :                                           sizeof(solver_name), run_prefix, sizeof(run_prefix),
     313              :                                           output_base_dir, sizeof(output_base_dir));
     314            3 :     if (st != CFD_SUCCESS) {
     315              :         return NULL;
     316              :     }
     317              : 
     318            3 :     simulation_data* sim_data = (simulation_data*)cfd_malloc(sizeof(simulation_data));
     319            3 :     if (!sim_data) {
     320            0 :         grid_destroy(g);
     321            0 :         flow_field_destroy(f);
     322            0 :         return NULL;
     323              :     }
     324              : 
     325              :     // Initialize every owned pointer up front so free_simulation() is a safe
     326              :     // cleanup from any failure point below.
     327            3 :     sim_data->grid = g;
     328            3 :     sim_data->field = f;
     329            3 :     sim_data->solver = NULL;
     330            3 :     sim_data->registry = NULL;
     331            3 :     sim_data->outputs = NULL;
     332            3 :     sim_data->run_prefix = NULL;
     333            3 :     sim_data->params = params;  // custom callbacks remain NULL (documented contract)
     334            3 :     sim_data->last_stats = ns_solver_stats_default();
     335            3 :     sim_data->current_time = current_time;
     336            3 :     snprintf(sim_data->output_base_dir, sizeof(sim_data->output_base_dir), "%s",
     337            3 :              output_base_dir[0] ? output_base_dir : "../../artifacts");
     338              : 
     339            3 :     sim_data->outputs = output_registry_create();
     340            3 :     if (!sim_data->outputs) {
     341            0 :         free_simulation(sim_data);
     342            0 :         return NULL;
     343              :     }
     344              : 
     345            3 :     sim_data->registry = cfd_registry_create();
     346            3 :     if (!sim_data->registry) {
     347            0 :         free_simulation(sim_data);
     348            0 :         return NULL;
     349              :     }
     350            3 :     cfd_registry_register_defaults(sim_data->registry);
     351              : 
     352            3 :     sim_data->solver = cfd_solver_create(sim_data->registry, solver_name);
     353            3 :     if (!sim_data->solver) {
     354            0 :         cfd_set_error(CFD_ERROR_NOT_FOUND, "load_simulation_from_checkpoint: solver not registered");
     355            0 :         free_simulation(sim_data);
     356            0 :         return NULL;
     357              :     }
     358              : 
     359            3 :     if (solver_init(sim_data->solver, sim_data->grid, &sim_data->params) != CFD_SUCCESS) {
     360            0 :         free_simulation(sim_data);
     361            0 :         return NULL;
     362              :     }
     363              : 
     364            3 :     if (run_prefix[0] != '\0') {
     365            0 :         size_t len = strlen(run_prefix) + 1;
     366            0 :         sim_data->run_prefix = (char*)cfd_malloc(len);
     367            0 :         if (!sim_data->run_prefix) {
     368              :             // Dropping the prefix would silently change output paths relative to
     369              :             // the checkpoint; fail hard rather than return a partially-restored sim.
     370            0 :             free_simulation(sim_data);
     371            0 :             return NULL;
     372              :         }
     373            0 :         snprintf(sim_data->run_prefix, len, "%s", run_prefix);
     374              :     }
     375              : 
     376              :     return sim_data;
     377              : }
     378              : 
     379            3 : cfd_status_t restore_simulation_checkpoint(simulation_data* sim_data, const char* path) {
     380            3 :     if (!sim_data || !path) {
     381            0 :         cfd_set_error(CFD_ERROR_INVALID, "restore_simulation_checkpoint: NULL argument");
     382            0 :         return CFD_ERROR_INVALID;
     383              :     }
     384            3 :     if (!sim_data->registry) {
     385            0 :         cfd_set_error(CFD_ERROR_INVALID, "restore_simulation_checkpoint: simulation not initialized");
     386            0 :         return CFD_ERROR_INVALID;
     387              :     }
     388              : 
     389            3 :     grid* new_grid = NULL;
     390            3 :     flow_field* new_field = NULL;
     391            3 :     ns_solver_params_t new_params;
     392            3 :     double current_time = 0.0;
     393            3 :     char solver_name[128] = {0};
     394            3 :     char run_prefix[256] = {0};
     395            3 :     char output_base_dir[512] = {0};
     396              : 
     397            3 :     cfd_status_t st = cfd_checkpoint_read(path, &new_grid, &new_field, &new_params, &current_time,
     398              :                                           solver_name, sizeof(solver_name), run_prefix,
     399              :                                           sizeof(run_prefix), output_base_dir,
     400              :                                           sizeof(output_base_dir));
     401            3 :     if (st != CFD_SUCCESS) {
     402              :         return st;
     403              :     }
     404              : 
     405              :     // Recreate the solver by name before tearing down old state, so a bad name
     406              :     // leaves the existing simulation untouched.
     407            3 :     ns_solver_t* new_solver = cfd_solver_create(sim_data->registry, solver_name);
     408            3 :     if (!new_solver) {
     409            0 :         grid_destroy(new_grid);
     410            0 :         flow_field_destroy(new_field);
     411            0 :         cfd_set_error(CFD_ERROR_NOT_FOUND, "restore_simulation_checkpoint: solver not registered");
     412            0 :         return CFD_ERROR_NOT_FOUND;
     413              :     }
     414              : 
     415              :     // Preserve the caller's custom callbacks; checkpoints cannot store them.
     416            3 :     new_params.source_func = sim_data->params.source_func;
     417            3 :     new_params.source_context = sim_data->params.source_context;
     418            3 :     new_params.heat_source_func = sim_data->params.heat_source_func;
     419            3 :     new_params.heat_source_context = sim_data->params.heat_source_context;
     420              :     // Same reason, and the same silent-physics-change if dropped: the learned
     421              :     // closure is a caller-owned context, so the checkpoint stores no trace of it.
     422            3 :     new_params.turb_closure = sim_data->params.turb_closure;
     423              :     // And each segment's inflow profile, matched by position in the array, which
     424              :     // the checkpoint preserves -- but only onto a segment the checkpoint marks as
     425              :     // profiled (DIRICHLET with NaN values, see checkpoint.h). Attaching one to a
     426              :     // segment saved with constant values would silently replace those values.
     427            5 :     for (size_t n = 0; n < new_params.turb_bc.n_segments &&
     428            2 :                        n < sim_data->params.turb_bc.n_segments; n++) {
     429            2 :         ns_turbulence_bc_segment_t* seg = &new_params.turb_bc.segments[n];
     430            4 :         if (turb_segment_profile_detached(seg)) {
     431            1 :             seg->profile = sim_data->params.turb_bc.segments[n].profile;
     432            1 :             seg->profile_user_data = sim_data->params.turb_bc.segments[n].profile_user_data;
     433              :         }
     434              :     }
     435              : 
     436              :     // Initialize the new solver against the new grid/params *before* touching the
     437              :     // old state, so a failed init leaves the existing simulation untouched and
     438              :     // only frees the freshly allocated state.
     439            3 :     cfd_status_t init_st = solver_init(new_solver, new_grid, &new_params);
     440            3 :     if (init_st != CFD_SUCCESS) {
     441            0 :         solver_destroy(new_solver);
     442            0 :         grid_destroy(new_grid);
     443            0 :         flow_field_destroy(new_field);
     444            0 :         return init_st;
     445              :     }
     446              : 
     447              :     // Init succeeded — swap in new state and release the old.
     448            3 :     if (sim_data->solver) {
     449            3 :         solver_destroy(sim_data->solver);
     450              :     }
     451            3 :     grid_destroy(sim_data->grid);
     452            3 :     flow_field_destroy(sim_data->field);
     453            3 :     sim_data->grid = new_grid;
     454            3 :     sim_data->field = new_field;
     455            3 :     sim_data->solver = new_solver;
     456            3 :     sim_data->params = new_params;
     457            3 :     sim_data->current_time = current_time;
     458              : 
     459              :     // Allocate the new prefix before releasing the old one, so an allocation
     460              :     // failure leaves the existing prefix (and output behavior) intact.
     461            3 :     if (run_prefix[0] != '\0') {
     462            0 :         size_t len = strlen(run_prefix) + 1;
     463            0 :         char* new_prefix = (char*)cfd_malloc(len);
     464            0 :         if (new_prefix) {
     465            0 :             snprintf(new_prefix, len, "%s", run_prefix);
     466            0 :             cfd_free(sim_data->run_prefix);
     467            0 :             sim_data->run_prefix = new_prefix;
     468              :         }
     469            3 :     } else if (sim_data->run_prefix) {
     470            0 :         cfd_free(sim_data->run_prefix);
     471            0 :         sim_data->run_prefix = NULL;
     472              :     }
     473            3 :     snprintf(sim_data->output_base_dir, sizeof(sim_data->output_base_dir), "%s",
     474            3 :              output_base_dir[0] ? output_base_dir : "../../artifacts");
     475              : 
     476              :     // The output registry caches its run directory after first use; invalidate it
     477              :     // so the restored run prefix / base directory take effect on the next output.
     478            3 :     if (sim_data->outputs) {
     479            3 :         output_registry_reset_run_dir(sim_data->outputs);
     480              :     }
     481              : 
     482              :     return CFD_SUCCESS;
     483              : }
     484              : 
     485              : // Static list of available solver names (const strings have static lifetime)
     486              : // This avoids use-after-free issues with dynamically created registries
     487              : static const char* const s_solver_names[] = {
     488              :     NS_SOLVER_TYPE_EXPLICIT_EULER,
     489              :     NS_SOLVER_TYPE_EXPLICIT_EULER_OPTIMIZED,
     490              :     NS_SOLVER_TYPE_PROJECTION,
     491              :     NS_SOLVER_TYPE_PROJECTION_OPTIMIZED,
     492              :     NS_SOLVER_TYPE_EXPLICIT_EULER_GPU,
     493              :     NS_SOLVER_TYPE_PROJECTION_GPU,
     494              : #ifdef CFD_ENABLE_OPENMP
     495              :     NS_SOLVER_TYPE_EXPLICIT_EULER_OMP,
     496              :     NS_SOLVER_TYPE_PROJECTION_OMP,
     497              : #endif
     498              : };
     499              : 
     500              : static const int s_solver_count = (int)(sizeof(s_solver_names) / sizeof(s_solver_names[0]));
     501              : 
     502              : // NSSolver discovery and listing
     503            6 : int simulation_list_solvers(const char** names, int max_count) {
     504            6 :     if (names && max_count > 0) {
     505            5 :         int fill_count = (s_solver_count < max_count) ? s_solver_count : max_count;
     506           39 :         for (int i = 0; i < fill_count; i++) {
     507           34 :             names[i] = s_solver_names[i];
     508              :         }
     509              :     }
     510            6 :     return s_solver_count;
     511              : }
     512              : 
     513            3 : int simulation_has_solver(const char* solver_type) {
     514            3 :     if (!solver_type) {
     515              :         return 0;
     516              :     }
     517           13 :     for (int i = 0; i < s_solver_count; i++) {
     518           12 :         if (strcmp(s_solver_names[i], solver_type) == 0) {
     519              :             return 1;
     520              :         }
     521              :     }
     522              :     return 0;
     523              : }
     524              : 
     525              : 
     526              : //=============================================================================
     527              : // OUTPUT REGISTRY API
     528              : //=============================================================================
     529              : 
     530              : // Register output for automatic generation
     531           15 : void simulation_register_output(simulation_data* sim_data, output_field_type field_type,
     532              :                                 int interval, const char* prefix) {
     533           15 :     if (!sim_data || !sim_data->outputs) {
     534            2 :         cfd_set_error(CFD_ERROR_INVALID, "Invalid simulation data");
     535            2 :         return;
     536              :     }
     537           13 :     output_registry_add(sim_data->outputs, field_type, interval, prefix);
     538              : }
     539              : 
     540              : // Clear all registered outputs
     541            8 : void simulation_clear_outputs(simulation_data* sim_data) {
     542            8 :     if (!sim_data || !sim_data->outputs) {
     543              :         return;
     544              :     }
     545            7 :     output_registry_clear(sim_data->outputs);
     546              : }
     547              : 
     548              : // Set base output directory
     549            2 : void simulation_set_output_dir(simulation_data* sim_data, const char* base_dir) {
     550            2 :     if (sim_data && base_dir && strlen(base_dir) > 0) {
     551            2 :         snprintf(sim_data->output_base_dir, sizeof(sim_data->output_base_dir), "%s", base_dir);
     552              :     }
     553            2 : }
     554              : 
     555              : // Set run name prefix
     556           10 : void simulation_set_run_prefix(simulation_data* sim_data, const char* prefix) {
     557           10 :     if (!sim_data) {
     558              :         return;
     559              :     }
     560              : 
     561              :     // Free existing prefix
     562            9 :     if (sim_data->run_prefix) {
     563            2 :         cfd_free(sim_data->run_prefix);
     564            2 :         sim_data->run_prefix = NULL;
     565              :     }
     566              : 
     567              :     // Set new prefix
     568            9 :     if (prefix) {
     569            8 :         size_t len = strlen(prefix) + 1;
     570            8 :         sim_data->run_prefix = (char*)cfd_malloc(len);
     571            8 :         if (sim_data->run_prefix) {
     572            8 :             snprintf(sim_data->run_prefix, len, "%s", prefix);
     573              :         }
     574              :     }
     575              : }
     576              : 
     577              : //=============================================================================
     578              : // AUTOMATIC OUTPUT GENERATION
     579              : //=============================================================================
     580              : 
     581              : // Check if any output type that uses velocity magnitude is registered
     582            9 : static int needs_velocity_magnitude(const output_registry* outputs) {
     583           17 :     return output_registry_has_type(outputs, OUTPUT_VELOCITY_MAGNITUDE) ||
     584           15 :            output_registry_has_type(outputs, OUTPUT_CSV_TIMESERIES) ||
     585           23 :            output_registry_has_type(outputs, OUTPUT_CSV_CENTERLINE) ||
     586            7 :            output_registry_has_type(outputs, OUTPUT_CSV_STATISTICS);
     587              : }
     588              : 
     589              : // Check if any output type that uses statistics is registered
     590            9 : static int needs_statistics(const output_registry* outputs) {
     591           17 :     return output_registry_has_type(outputs, OUTPUT_CSV_TIMESERIES) ||
     592            8 :            output_registry_has_type(outputs, OUTPUT_CSV_STATISTICS);
     593              : }
     594              : 
     595              : // Automatically write all registered outputs for current step
     596           11 : void simulation_write_outputs(simulation_data* sim_data, int step) {
     597           11 :     if (!sim_data || !sim_data->outputs) {
     598            2 :         cfd_set_error(CFD_ERROR_INVALID, "Invalid arguments for simulation_write_outputs");
     599            2 :         return;
     600              :     }
     601              : 
     602              :     // Get run directory (creates it if needed)
     603            9 :     const char* run_dir =
     604           18 :         output_registry_get_run_dir(sim_data->outputs, sim_data->output_base_dir,
     605            9 :                                     sim_data->run_prefix, sim_data->grid->nx, sim_data->grid->ny);
     606              : 
     607              :     // Compute derived fields only when needed
     608            9 :     derived_fields* derived = NULL;
     609            9 :     int compute_vel_mag = needs_velocity_magnitude(sim_data->outputs);
     610            9 :     int compute_stats = needs_statistics(sim_data->outputs);
     611              : 
     612            9 :     if (compute_vel_mag || compute_stats) {
     613           14 :         derived = derived_fields_create(sim_data->grid->nx, sim_data->grid->ny,
     614            7 :                                             sim_data->grid->nz);
     615            7 :         if (derived) {
     616              :             // Compute velocity magnitude if needed (CSV outputs)
     617            7 :             if (compute_vel_mag) {
     618            7 :                 derived_fields_compute_velocity_magnitude(derived, sim_data->field);
     619              :             }
     620              :             // Compute statistics if needed (CSV timeseries or statistics outputs)
     621            7 :             if (compute_stats) {
     622            6 :                 derived_fields_compute_statistics(derived, sim_data->field);
     623              :             }
     624              :         }
     625              :     }
     626              : 
     627              :     // Write all registered outputs with pre-computed derived fields
     628            9 :     output_registry_write_outputs(sim_data->outputs, run_dir, step, sim_data->current_time,
     629            9 :                                   sim_data->field, derived, sim_data->grid, &sim_data->params,
     630            9 :                                   &sim_data->last_stats);
     631              : 
     632              :     // Clean up derived fields
     633            9 :     if (derived) {
     634            7 :         derived_fields_destroy(derived);
     635              :     }
     636              : }
        

Generated by: LCOV version 2.0-1