From fa990415ce7ab9a52c5f876df7c1809d9d90db56 Mon Sep 17 00:00:00 2001 From: Prithwish Mukherjee Date: Wed, 2 Dec 2026 08:48:38 +0530 Subject: [PATCH] junk: Add exp sol. --- .../finite_wing_angle_ramp_transient.json | 39 + .../cases/finite_wing_low_re.json | 28 + .../cases/heated_rectangular_plate.json | 21 + .../cases/lid_driven_cavity_re100.json | 48 + .../cases/lid_driven_cavity_re100_steady.json | 45 + .../lid_driven_cavity_re100_transient.json | 61 + .../lid_driven_cavity_re100_workflow.json | 48 + Exp_solver_dev_tr/cases/turek_hron_fsi1.json | 30 + .../docs/data_externalization_guide.md | 268 ++++ Exp_solver_dev_tr/docs/using_the_solver.md | 880 +++++++++++++ .../compare_externalization_strategies.py | 244 ++++ .../examples/end_to_end_examples.py | 414 +++++++ .../examples/poll_shared_snapshots.py | 43 + .../examples/run_externalized_case.py | 347 ++++++ .../examples/run_finite_wing_case.py | 161 +++ .../run_finite_wing_transient_case.py | 131 ++ Exp_solver_dev_tr/examples/run_fsi_case.py | 147 +++ .../examples/run_heat_transfer_case.py | 136 +++ Exp_solver_dev_tr/examples/run_user_case.py | 286 +++++ Exp_solver_dev_tr/src/fsi/__init__.py | 13 + Exp_solver_dev_tr/src/fsi/solver.py | 714 +++++++++++ Exp_solver_dev_tr/src/fsi/visualization.py | 246 ++++ Exp_solver_dev_tr/src/fvm/__init__.py | 127 ++ .../src/fvm/boundary_conditions.py | 113 ++ Exp_solver_dev_tr/src/fvm/case_definition.py | 429 +++++++ Exp_solver_dev_tr/src/fvm/checkpoint.py | 368 ++++++ .../src/fvm/externalization/__init__.py | 32 + .../src/fvm/externalization/grpc_transport.py | 263 ++++ .../src/fvm/externalization/model.py | 196 +++ .../externalization/snapshot_service.proto | 10 + .../src/fvm/externalization/store.py | 216 ++++ .../src/fvm/externalization/strategies.py | 288 +++++ .../src/fvm/externalization/visualization.py | 230 ++++ Exp_solver_dev_tr/src/fvm/fields.py | 84 ++ Exp_solver_dev_tr/src/fvm/integration.py | 307 +++++ Exp_solver_dev_tr/src/fvm/mesh.py | 174 +++ Exp_solver_dev_tr/src/fvm/momentum.py | 475 +++++++ Exp_solver_dev_tr/src/fvm/operators.py | 418 +++++++ Exp_solver_dev_tr/src/fvm/postprocessing.py | 743 +++++++++++ .../src/fvm/pressure_correction.py | 217 ++++ Exp_solver_dev_tr/src/fvm/projection.py | 162 +++ .../src/fvm/schemas/case-v1.schema.json | 157 +++ Exp_solver_dev_tr/src/fvm/simulation.py | 674 ++++++++++ Exp_solver_dev_tr/src/fvm3d/__init__.py | 22 + Exp_solver_dev_tr/src/fvm3d/solver.py | 1086 +++++++++++++++++ Exp_solver_dev_tr/src/fvm3d/visualization.py | 575 +++++++++ .../src/heat_transfer/__init__.py | 13 + Exp_solver_dev_tr/src/heat_transfer/solver.py | 356 ++++++ .../src/heat_transfer/visualization.py | 215 ++++ .../tests/test_boundary_conditions.py | 74 ++ Exp_solver_dev_tr/tests/test_checkpoint.py | 151 +++ .../tests/test_externalization.py | 289 +++++ Exp_solver_dev_tr/tests/test_fields.py | 71 ++ Exp_solver_dev_tr/tests/test_fsi_solver.py | 153 +++ Exp_solver_dev_tr/tests/test_fvm3d.py | 245 ++++ Exp_solver_dev_tr/tests/test_heat_transfer.py | 222 ++++ Exp_solver_dev_tr/tests/test_integration.py | 251 ++++ Exp_solver_dev_tr/tests/test_mesh.py | 64 + Exp_solver_dev_tr/tests/test_momentum.py | 173 +++ Exp_solver_dev_tr/tests/test_operators.py | 183 +++ .../tests/test_postprocessing.py | 192 +++ .../tests/test_pressure_correction.py | 101 ++ Exp_solver_dev_tr/tests/test_projection.py | 103 ++ .../tests/test_run_externalized_case.py | 111 ++ Exp_solver_dev_tr/tests/test_simulation.py | 377 ++++++ Exp_solver_dev_tr/tests/test_user_workflow.py | 102 ++ 66 files changed, 15162 insertions(+) create mode 100644 Exp_solver_dev_tr/cases/finite_wing_angle_ramp_transient.json create mode 100644 Exp_solver_dev_tr/cases/finite_wing_low_re.json create mode 100644 Exp_solver_dev_tr/cases/heated_rectangular_plate.json create mode 100644 Exp_solver_dev_tr/cases/lid_driven_cavity_re100.json create mode 100644 Exp_solver_dev_tr/cases/lid_driven_cavity_re100_steady.json create mode 100644 Exp_solver_dev_tr/cases/lid_driven_cavity_re100_transient.json create mode 100644 Exp_solver_dev_tr/cases/lid_driven_cavity_re100_workflow.json create mode 100644 Exp_solver_dev_tr/cases/turek_hron_fsi1.json create mode 100644 Exp_solver_dev_tr/docs/data_externalization_guide.md create mode 100644 Exp_solver_dev_tr/docs/using_the_solver.md create mode 100644 Exp_solver_dev_tr/examples/compare_externalization_strategies.py create mode 100644 Exp_solver_dev_tr/examples/end_to_end_examples.py create mode 100644 Exp_solver_dev_tr/examples/poll_shared_snapshots.py create mode 100644 Exp_solver_dev_tr/examples/run_externalized_case.py create mode 100644 Exp_solver_dev_tr/examples/run_finite_wing_case.py create mode 100644 Exp_solver_dev_tr/examples/run_finite_wing_transient_case.py create mode 100644 Exp_solver_dev_tr/examples/run_fsi_case.py create mode 100644 Exp_solver_dev_tr/examples/run_heat_transfer_case.py create mode 100644 Exp_solver_dev_tr/examples/run_user_case.py create mode 100644 Exp_solver_dev_tr/src/fsi/__init__.py create mode 100644 Exp_solver_dev_tr/src/fsi/solver.py create mode 100644 Exp_solver_dev_tr/src/fsi/visualization.py create mode 100644 Exp_solver_dev_tr/src/fvm/__init__.py create mode 100644 Exp_solver_dev_tr/src/fvm/boundary_conditions.py create mode 100644 Exp_solver_dev_tr/src/fvm/case_definition.py create mode 100644 Exp_solver_dev_tr/src/fvm/checkpoint.py create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/__init__.py create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/grpc_transport.py create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/model.py create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/snapshot_service.proto create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/store.py create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/strategies.py create mode 100644 Exp_solver_dev_tr/src/fvm/externalization/visualization.py create mode 100644 Exp_solver_dev_tr/src/fvm/fields.py create mode 100644 Exp_solver_dev_tr/src/fvm/integration.py create mode 100644 Exp_solver_dev_tr/src/fvm/mesh.py create mode 100644 Exp_solver_dev_tr/src/fvm/momentum.py create mode 100644 Exp_solver_dev_tr/src/fvm/operators.py create mode 100644 Exp_solver_dev_tr/src/fvm/postprocessing.py create mode 100644 Exp_solver_dev_tr/src/fvm/pressure_correction.py create mode 100644 Exp_solver_dev_tr/src/fvm/projection.py create mode 100644 Exp_solver_dev_tr/src/fvm/schemas/case-v1.schema.json create mode 100644 Exp_solver_dev_tr/src/fvm/simulation.py create mode 100644 Exp_solver_dev_tr/src/fvm3d/__init__.py create mode 100644 Exp_solver_dev_tr/src/fvm3d/solver.py create mode 100644 Exp_solver_dev_tr/src/fvm3d/visualization.py create mode 100644 Exp_solver_dev_tr/src/heat_transfer/__init__.py create mode 100644 Exp_solver_dev_tr/src/heat_transfer/solver.py create mode 100644 Exp_solver_dev_tr/src/heat_transfer/visualization.py create mode 100644 Exp_solver_dev_tr/tests/test_boundary_conditions.py create mode 100644 Exp_solver_dev_tr/tests/test_checkpoint.py create mode 100644 Exp_solver_dev_tr/tests/test_externalization.py create mode 100644 Exp_solver_dev_tr/tests/test_fields.py create mode 100644 Exp_solver_dev_tr/tests/test_fsi_solver.py create mode 100644 Exp_solver_dev_tr/tests/test_fvm3d.py create mode 100644 Exp_solver_dev_tr/tests/test_heat_transfer.py create mode 100644 Exp_solver_dev_tr/tests/test_integration.py create mode 100644 Exp_solver_dev_tr/tests/test_mesh.py create mode 100644 Exp_solver_dev_tr/tests/test_momentum.py create mode 100644 Exp_solver_dev_tr/tests/test_operators.py create mode 100644 Exp_solver_dev_tr/tests/test_postprocessing.py create mode 100644 Exp_solver_dev_tr/tests/test_pressure_correction.py create mode 100644 Exp_solver_dev_tr/tests/test_projection.py create mode 100644 Exp_solver_dev_tr/tests/test_run_externalized_case.py create mode 100644 Exp_solver_dev_tr/tests/test_simulation.py create mode 100644 Exp_solver_dev_tr/tests/test_user_workflow.py diff --git a/Exp_solver_dev_tr/cases/finite_wing_angle_ramp_transient.json b/Exp_solver_dev_tr/cases/finite_wing_angle_ramp_transient.json new file mode 100644 index 0000000000000..720df36e63857 --- /dev/null +++ b/Exp_solver_dev_tr/cases/finite_wing_angle_ramp_transient.json @@ -0,0 +1,39 @@ +{ + "case_id": "finite_wing_angle_ramp_transient", + "description": "Transient low-Re flow past a finite wing as angle of attack ramps from 0 to 5 degrees over 5 seconds.", + "settings": { + "length_x": 10.0, + "length_y": 3.0, + "length_z": 3.0, + "nx": 80, + "ny": 25, + "nz": 25, + "density": 1.0, + "dynamic_viscosity": 0.001, + "wing_leading_edge_x": 2.0, + "wing_chord": 1.0, + "wing_span": 1.5, + "wing_thickness": 0.12, + "angle_of_attack_degrees": 0.0, + "inlet_speed": 1.0, + "inlet_velocity_x": null, + "inlet_velocity_y": null, + "cfl_limit": 0.25, + "pressure_tolerance": 1e-8, + "max_pressure_iterations": 1000 + }, + "transient": { + "end_time": 5.0, + "time_step_cap": 0.01, + "minimum_time_step": 1e-8, + "outlet_sponge_length": 2.0, + "angle_of_attack_schedule": [ + [0.0, 0.0], + [1.0, 1.0], + [2.0, 2.0], + [3.0, 3.0], + [4.0, 4.0], + [5.0, 5.0] + ] + } +} diff --git a/Exp_solver_dev_tr/cases/finite_wing_low_re.json b/Exp_solver_dev_tr/cases/finite_wing_low_re.json new file mode 100644 index 0000000000000..9ac38dd912054 --- /dev/null +++ b/Exp_solver_dev_tr/cases/finite_wing_low_re.json @@ -0,0 +1,28 @@ +{ + "case_id": "finite_wing_low_re", + "description": "Steady low-Re flow past a finite rectangular wing with configurable angle of attack.", + "settings": { + "length_x": 6.0, + "length_y": 3.0, + "length_z": 3.0, + "nx": 48, + "ny": 25, + "nz": 25, + "density": 1.0, + "dynamic_viscosity": 0.001, + "wing_leading_edge_x": 1.5, + "wing_chord": 1.0, + "wing_span": 1.5, + "wing_thickness": 0.12, + "angle_of_attack_degrees": 5.0, + "inlet_speed": 1.0, + "inlet_velocity_x": null, + "inlet_velocity_y": null, + "pseudo_time_step_cap": 0.005, + "minimum_pseudo_time_step": 1e-8, + "max_iterations": 200, + "cfl_limit": 0.25, + "pressure_tolerance": 1e-8, + "max_pressure_iterations": 1000 + } +} diff --git a/Exp_solver_dev_tr/cases/heated_rectangular_plate.json b/Exp_solver_dev_tr/cases/heated_rectangular_plate.json new file mode 100644 index 0000000000000..040d4c86ba3f2 --- /dev/null +++ b/Exp_solver_dev_tr/cases/heated_rectangular_plate.json @@ -0,0 +1,21 @@ +{ + "case_id": "heated_rectangular_plate", + "description": "Steady plate heating with optional convective cooling on side edges.", + "settings": { + "width": 1.0, + "height": 1.0, + "nx": 50, + "ny": 50, + "thermal_conductivity": 10.0, + "left_temperature_c": null, + "right_temperature_c": null, + "bottom_temperature_c": 0.0, + "top_temperature_c": 100.0, + "max_iterations": 10000, + "residual_tolerance": 1e-8, + "relaxation_factor": 1.7, + "convection_enabled": true, + "convection_heat_transfer_coefficient_w_m2_k": 25.0, + "ambient_temperature_c": 20.0 + } +} diff --git a/Exp_solver_dev_tr/cases/lid_driven_cavity_re100.json b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100.json new file mode 100644 index 0000000000000..34d75341eca42 --- /dev/null +++ b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100.json @@ -0,0 +1,48 @@ +{ + "schema_version": "1.0", + "case_id": "lid_driven_cavity_re100", + "description": "Transient Re=100 lid-driven cavity contract example for setup-software integration.", + "units": "SI", + "physics": { + "model": "incompressible_laminar", + "transient": true + }, + "domain": { + "type": "rectangle", + "width_m": 1.0, + "height_m": 1.0 + }, + "mesh": { + "type": "uniform_cartesian", + "nx": 16, + "ny": 16 + }, + "material": { + "type": "newtonian_fluid", + "density_kg_m3": 1.0, + "dynamic_viscosity_pa_s": 0.01 + }, + "initial_conditions": { + "u_m_s": 0.0, + "v_m_s": 0.0, + "pressure_pa": 0.0 + }, + "boundary_conditions": { + "west": {"type": "no_slip_wall"}, + "east": {"type": "no_slip_wall"}, + "south": {"type": "no_slip_wall"}, + "north": {"type": "moving_wall", "velocity_m_s": [1.0, 0.0]}, + "pressure_correction": "homogeneous_neumann" + }, + "solver": { + "max_time_step_s": 0.001, + "minimum_time_step_s": 1e-12, + "max_steps": 3, + "cfl_limit": 0.5, + "velocity_tolerance_m_s": 1e-14, + "continuity_tolerance_s_inv": 1e-8, + "mass_tolerance_m2_s": 1e-10, + "momentum_residual_tolerance": 1e-10, + "pressure_residual_tolerance": 1e-10 + } +} \ No newline at end of file diff --git a/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_steady.json b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_steady.json new file mode 100644 index 0000000000000..692662e6c3ac3 --- /dev/null +++ b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_steady.json @@ -0,0 +1,45 @@ +{ + "schema_version": "1.0", + "case_id": "lid_driven_cavity_re100_steady", + "description": "Steady 64x64 Re=100 lid-driven cavity solved with fixed pseudo-time iterations.", + "units": "SI", + "physics": { + "model": "incompressible_laminar", + "transient": false + }, + "domain": { + "type": "rectangle", + "width_m": 1.0, + "height_m": 1.0 + }, + "mesh": { + "type": "uniform_cartesian", + "nx": 128, + "ny": 128 + }, + "material": { + "type": "newtonian_fluid", + "density_kg_m3": 1.0, + "dynamic_viscosity_pa_s": 0.01 + }, + "initial_conditions": { + "u_m_s": 0.0, + "v_m_s": 0.0, + "pressure_pa": 0.0 + }, + "boundary_conditions": { + "west": {"type": "no_slip_wall"}, + "east": {"type": "no_slip_wall"}, + "south": {"type": "no_slip_wall"}, + "north": {"type": "moving_wall", "velocity_m_s": [1.0, 0.0]}, + "pressure_correction": "homogeneous_neumann" + }, + "solver": { + "max_steps": 10000, + "velocity_tolerance_m_s": 1e-6, + "continuity_tolerance_s_inv": 1e-8, + "mass_tolerance_m2_s": 1e-10, + "momentum_residual_tolerance": 1e-10, + "pressure_residual_tolerance": 1e-10 + } +} \ No newline at end of file diff --git a/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_transient.json b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_transient.json new file mode 100644 index 0000000000000..415bf86f38298 --- /dev/null +++ b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_transient.json @@ -0,0 +1,61 @@ +{ + "schema_version": "1.0", + "case_id": "lid_driven_cavity_re100_transient", + "description": "Transient 64x64 Re=100 cavity with a linearly accelerating top plate.", + "units": "SI", + "physics": { + "model": "incompressible_laminar", + "transient": true + }, + "domain": { + "type": "rectangle", + "width_m": 1.0, + "height_m": 1.0 + }, + "mesh": { + "type": "uniform_cartesian", + "nx": 16, + "ny": 16 + }, + "material": { + "type": "newtonian_fluid", + "density_kg_m3": 1.0, + "dynamic_viscosity_pa_s": 0.01 + }, + "initial_conditions": { + "u_m_s": 0.0, + "v_m_s": 0.0, + "pressure_pa": 0.0 + }, + "boundary_conditions": { + "west": {"type": "no_slip_wall"}, + "east": {"type": "no_slip_wall"}, + "south": {"type": "no_slip_wall"}, + "north": { + "type": "moving_wall", + "velocity_profile": [ + {"time_s": 0.0, "velocity_m_s": [0.0, 0.0]}, + {"time_s": 1.0, "velocity_m_s": [1.0, 0.0]}, + {"time_s": 2.0, "velocity_m_s": [2.0, 0.0]}, + {"time_s": 3.0, "velocity_m_s": [3.0, 0.0]}, + {"time_s": 4.0, "velocity_m_s": [4.0, 0.0]}, + {"time_s": 5.0, "velocity_m_s": [4.0, 0.0]}, + {"time_s": 6.0, "velocity_m_s": [4.0, 0.0]} + ] + }, + "pressure_correction": "homogeneous_neumann" + }, + "solver": { + "max_time_step_s": 0.01, + "minimum_time_step_s": 1e-12, + "max_steps": 10000, + "cfl_limit": 0.5, + "velocity_tolerance_m_s": 1e-6, + "continuity_tolerance_s_inv": 1e-8, + "mass_tolerance_m2_s": 1e-10, + "momentum_residual_tolerance": 1e-10, + "pressure_residual_tolerance": 1e-10, + "end_time_s": 6.0, + "max_inner_iterations_per_time_step": 1000 + } +} \ No newline at end of file diff --git a/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_workflow.json b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_workflow.json new file mode 100644 index 0000000000000..dec6e1aad4377 --- /dev/null +++ b/Exp_solver_dev_tr/cases/lid_driven_cavity_re100_workflow.json @@ -0,0 +1,48 @@ +{ + "schema_version": "1.0", + "case_id": "lid_driven_cavity_re100_user_workflow", + "description": "Converged 16x16 Re=100 cavity example for the solver user guide.", + "units": "SI", + "physics": { + "model": "incompressible_laminar", + "transient": true + }, + "domain": { + "type": "rectangle", + "width_m": 1.0, + "height_m": 1.0 + }, + "mesh": { + "type": "uniform_cartesian", + "nx": 64, + "ny": 64 + }, + "material": { + "type": "newtonian_fluid", + "density_kg_m3": 1.0, + "dynamic_viscosity_pa_s": 0.01 + }, + "initial_conditions": { + "u_m_s": 0.0, + "v_m_s": 0.0, + "pressure_pa": 0.0 + }, + "boundary_conditions": { + "west": {"type": "no_slip_wall"}, + "east": {"type": "no_slip_wall"}, + "south": {"type": "no_slip_wall"}, + "north": {"type": "moving_wall", "velocity_m_s": [1.0, 0.0]}, + "pressure_correction": "homogeneous_neumann" + }, + "solver": { + "max_time_step_s": 0.01, + "minimum_time_step_s": 1e-12, + "max_steps": 10000, + "cfl_limit": 0.5, + "velocity_tolerance_m_s": 1e-6, + "continuity_tolerance_s_inv": 1e-8, + "mass_tolerance_m2_s": 1e-10, + "momentum_residual_tolerance": 1e-10, + "pressure_residual_tolerance": 1e-10 + } +} \ No newline at end of file diff --git a/Exp_solver_dev_tr/cases/turek_hron_fsi1.json b/Exp_solver_dev_tr/cases/turek_hron_fsi1.json new file mode 100644 index 0000000000000..7c85bea3af1f3 --- /dev/null +++ b/Exp_solver_dev_tr/cases/turek_hron_fsi1.json @@ -0,0 +1,30 @@ +{ + "case_id": "turek_hron_fsi1", + "description": "Channel flow past a fixed cylinder with a flexible cantilever beam.", + "settings": { + "width": 2.5, + "height": 0.41, + "nx": 120, + "ny": 24, + "fluid_density": 1000.0, + "dynamic_viscosity": 1.0, + "inlet_mean_speed": 1.0, + "cylinder_center_x": 0.2, + "cylinder_center_y": 0.2, + "cylinder_radius": 0.05, + "beam_root_x": 0.25, + "beam_root_y": 0.2, + "beam_length": 0.35, + "beam_thickness": 0.02, + "beam_density": 10000.0, + "youngs_modulus": 1400000.0, + "beam_elements": 12, + "time_step": 0.001, + "max_steps": 100, + "end_time": null, + "minimum_time_step": 1e-12, + "cfl_limit": 0.4, + "coupling_tolerance": 1e-6, + "max_inner_iterations_per_time_step": 200 + } +} diff --git a/Exp_solver_dev_tr/docs/data_externalization_guide.md b/Exp_solver_dev_tr/docs/data_externalization_guide.md new file mode 100644 index 0000000000000..4e19b65522f2c --- /dev/null +++ b/Exp_solver_dev_tr/docs/data_externalization_guide.md @@ -0,0 +1,268 @@ +# Comparing the Four Data Externalization Strategies + +This guide is for anyone who wants to understand the four ways the solver can +save its results. + +## What is data externalization? + +While solving a case, the solver produces useful information such as velocity, +pressure, mesh coordinates, and progress measurements. A **snapshot** is a +saved copy of that information for a selected completed solver step. + +**Data externalization** means moving those snapshots out of the solver's +calculation flow so that another program can save, share, or display them. The +solver still calculates the answer; the selected strategy controls how the +snapshots are delivered and stored. + +The four strategies all send the same kind of snapshot. The sampling interval +controls how often one is created; the selected strategy controls how it is +delivered and how much the solver waits. + +## The four strategies in everyday terms + +### 1. Synchronous file export (`sync`) + +For each selected step, the solver prepares and saves that step's snapshot to +a file. It waits for the file write to finish before continuing. + +Think of it as a person making a copy of each page before starting the next +page. + +- **Good for:** small runs, straightforward local use, and a simple baseline. +- **Trade-off:** file preparation and writing time is directly part of the + solver's step time. +- **Data safety:** the snapshot is saved before the solver continues. + +### 2. Shared-folder spool (`shared`) + +The solver saves each selected snapshot to a shared folder. A separate **poller** +periodically checks that folder and copies newly arrived snapshots to the +destination store. + +Think of it as putting completed pages in an inbox; another person checks the +inbox every so often and files the pages elsewhere. In the comparison program, +the poller runs independently from the solver in a background thread. The +included `poll_shared_snapshots.py` tool can also be run as a separate process. + +- **Good for:** separating the solver from a later file-processing or + storage tool. +- **Trade-off:** the solver still has to write each snapshot to the shared + folder. The poller's interval also affects how quickly the destination gets + updated. +- **Data safety:** the source spool is retained for replay; it can use + additional disk space and should be managed. + +### 3. Background queue (`async`) + +The solver puts each selected snapshot into a short in-memory line (a **queue**). A +background worker takes snapshots from that line and writes them to files while +the solver continues. + +Think of leaving completed pages in a tray for another person to file. + +- **Good for:** reducing the time the solver spends waiting on local file + writing. +- **Trade-off:** if the worker cannot keep up, the queue fills and the solver + must wait for room. +- **Data safety:** queued snapshots are written when the run closes normally. + A sudden process or machine failure can lose snapshots that have not yet + reached a file. + +### 4. gRPC streaming (`grpc`) + +gRPC is a standard way for separate programs to exchange messages. The +solver-side client sends selected snapshots as a stream to a gRPC service, which +receives and saves them. In the local comparison demo, both client and service +run on the same computer; a future deployment could place the service on +another machine. + +Think of sending pages along a delivery route to a separate filing office. + +- **Good for:** creating a service boundary between the solver and an + externalization service. +- **Trade-off:** preparing and sending snapshots takes time; network conditions + matter when the service is remote. +- **Data safety:** the client waits for the service to finish the stream and + acknowledge it when the run closes. +- **Security note:** the local demo uses an insecure loopback connection. + Network deployments need TLS and appropriate authentication and + authorization. + +## What does backpressure mean? + +The `async` and `grpc` strategies use a **bounded queue**: a waiting line with +a fixed maximum size. Bounding the line prevents it from growing forever and +using all available memory. + +**Backpressure** is what happens when the line is full. The solver pauses +publishing snapshots until the worker or service makes room. This implementation +does not silently throw away snapshots to avoid the pause. + +For example, with a queue size of 8, up to 8 snapshots can wait to be processed. +If the next snapshot arrives while all 8 spaces are occupied, the solver waits +for one space to become free. Increasing the queue can absorb short bursts, but +it does not make a permanently slower storage service faster. + +## Choose how often snapshots are sent + +The default is every 10 completed solver steps, plus the final step if it does +not land on that interval. For example, a 23-step run saves steps 10, 20, and +23. Set the interval to 1 to externalize every step: + +```powershell +python examples/run_externalized_case.py ` + --case path/to/your-case.json ` + --strategy async ` + --snapshot-every 1 +``` + +In the comparison runner, use the same option: + +```powershell +python examples/compare_externalization_strategies.py ` + --steps 100 ` + --snapshot-every 10 +``` + +A larger interval means fewer snapshots to serialize, write, queue, or transfer. +This can reduce storage and network traffic, ease queue pressure, and reduce +waiting, especially for synchronous file output. It does not reduce the +solver's numerical work, and the speedup may be small when solving dominates +the runtime. The trade-off is a less detailed live view and fewer saved +intermediate states. The final state is always externalized. + +## Other useful terms + +| Term | Plain-language meaning | +| --- | --- | +| **Solver step** | One completed calculation update. | +| **Snapshot** | The fields and progress information saved after a step. | +| **Producer** | The part that creates and sends snapshots; here, the solver-side adapter. | +| **Consumer / worker** | The part that receives snapshots and writes or forwards them. | +| **Spool** | A temporary holding area, such as the shared folder used by `shared`. | +| **Polling interval** | How often the shared-folder poller checks for new snapshots. | +| **Publish time** | Time spent by the solver-side strategy handing off snapshots. | +| **Externalization time** | Time spent writing snapshots downstream. For background strategies, this work can overlap with solving. | +| **Solver time** | Time spent running the backend, including the strategy's solver-side publish work. It is not just the numerical calculation time. | +| **Total time** | Solver time plus draining or closing the externalizer so pending work is completed. | +| **Snapshot count** | Number of snapshots successfully externalized. With sampling, this is lower than the completed step count; it includes interval steps and the final step. | +| **Bytes written** | Approximate size of the snapshot data. Small differences between runs are normal. | +| **Converged** | Whether the solver met its numerical stopping criteria. A timing run can finish its step limit without converging. | + +`externalize_seconds` is not always extra time after `solver_seconds`. For +`async` and `grpc`, writing can happen while the solver continues, so the two +durations overlap. Compare `total_seconds` for elapsed time until all +externalization work is drained. Compare `solver_seconds` and `publish_seconds` +to understand how much work is on the solver's path. + +## Run a local comparison + +Open PowerShell in the project folder. Install the project and its dependencies +if you have not already done so: + +```powershell +python -m pip install -e . +``` + +Run all four strategies against the same case: + +```powershell +python examples/compare_externalization_strategies.py --steps 100 --snapshot-every 10 +``` + +The comparison program runs the solver separately for each strategy. By +default, it uses the steady lid-driven cavity case and writes output under +`results/externalization_poc/`. + +The default step limit is only 4, to make the first run quick. Use a larger +limit, such as 100 or 500, for a more useful timing sample. A larger limit does +not guarantee convergence; check the `converged` column in the report. +The default snapshot interval is 10 steps. Use `--snapshot-every 1` when you +want every solver step saved, and use the same interval for every strategy in +a fair performance comparison. With the default four-step cap, only the final +step is saved because the run does not reach step 10. + +### Choose a case, strategy, or output folder + +To compare a different case, pass its JSON file: + +```powershell +python examples/compare_externalization_strategies.py ` + --case cases/lid_driven_cavity_re100_transient.json ` + --steps 100 +``` + +To run just one strategy, add `--strategy` with one of `sync`, `shared`, +`async`, or `grpc`: + +```powershell +python examples/compare_externalization_strategies.py ` + --strategy grpc ` + --steps 100 +``` + +To keep a separate report for another trial, choose a different output folder: + +```powershell +python examples/compare_externalization_strategies.py ` + --steps 100 ` + --output results/externalization_trial_2 +``` + +The `--queue-size` option sets the maximum waiting line for `async` and `grpc` +(default: 8). The `--poll-interval` option sets how often `shared` checks its +spool in seconds (default: 0.1). For example: + +```powershell +python examples/compare_externalization_strategies.py ` + --steps 100 ` + --queue-size 16 ` + --poll-interval 0.5 +``` + +## Read the comparison output + +The output folder contains: + +- `benchmark.csv` and `benchmark.json`: one summary row per strategy. +- A separate folder for each strategy, containing the snapshots and a + `final_snapshot.png` visualization made from the saved data. +- For `shared`, both the source spool and the poller's destination snapshots. + +You can open `benchmark.csv` in a spreadsheet program. Check these items: + +1. **Same amount of work:** compare rows with the same case and step count. +2. **All data arrived:** compare `snapshot_count` with the expected number of + interval snapshots plus the final step, not directly with `steps`. +3. **Solver impact:** compare `solver_seconds` and `publish_seconds`. +4. **End-to-end wait:** compare `total_seconds`; it includes the time to finish + pending writes or transfers. +5. **Numerical result:** check `converged`. A capped, non-converged run is + useful for measuring data delivery, but it is not a validated final + simulation result. + +For a presentation-quality comparison, run each strategy several times using +the same case, mesh, step limit, output location type, and computer. Give each +trial a separate `--output` folder so its report is preserved. Avoid running +other heavy applications during the trials. The measurements are local POC +results: in particular, the local gRPC result does not predict performance +over a cloud network. + +## Run the shared-folder poller separately + +The comparison program starts the shared-folder poller for you. To run the +consumer as a separate process, start it with the matching shared and +destination folders: + +```powershell +python examples/poll_shared_snapshots.py ` + --shared results/my_run/shared ` + --destination results/my_run/snapshots ` + --interval 1 +``` + +Stop it with **Ctrl+C** after the solver has finished. It performs a final +check before exiting. The producer and consumer must point to the same shared +folder for this arrangement to work. A Python example that configures the +solver-side producer is in the +[solver guide](./using_the_solver.md#10-compare-data-externalization-strategies). diff --git a/Exp_solver_dev_tr/docs/using_the_solver.md b/Exp_solver_dev_tr/docs/using_the_solver.md new file mode 100644 index 0000000000000..68b2394aac959 --- /dev/null +++ b/Exp_solver_dev_tr/docs/using_the_solver.md @@ -0,0 +1,880 @@ +# Using the Independent FVM Solver + +This guide walks through a complete lid-driven cavity run: define the case, +validate it, solve it, inspect the output files, plot the fields, and compare +the centerline velocities with the Re=100 Ghia reference. + +The same JSON handoff can be generated by a CFD setup application. The setup +application does not need to import solver code: it writes the versioned case +document, invokes the backend, then reads the returned summary and artifacts. + +## 1. Supported Problem Scope + +Case schema version `1.0` currently supports: + +- 2D incompressible, laminar flow of a constant-property Newtonian fluid in + either steady-state or transient mode. +- A rectangular domain with a uniform Cartesian mesh. +- Uniform initial `u`, `v`, and pressure values. +- No-slip and tangential moving-wall boundaries with constant velocity or a + piecewise-linear time/velocity profile. +- Homogeneous Neumann pressure-correction boundaries. +- The M3-M6 transient projection solver and M7 post-processing tools. + +This is deliberately narrower than a general CFD setup system. Inlets/outlets, +compressible or turbulent models, spatially varying materials, nonuniform or +unstructured meshes, and additional boundary types are rejected by schema +version 1.0. Extend the schema and adapter with tests before sending those +features from a setup application. + +## First Fluid-Structure Interaction Solver + +The separate `fsi` package contains a small, transient +Turek-Hron-style channel case: a parabolic water inlet, a fixed circular +cylinder, and a flexible beam attached behind the cylinder. The beam has a +clamped root and a free tip. The fluid is advanced on a staggered Cartesian +grid with a pressure projection; the cylinder and beam are represented by +immersed-boundary methods. The fixed cylinder uses direct forcing; the beam +uses a simplified, regularized transverse quadratic-drag load with an equal +and opposite force applied to the fluid. Beam bending uses linear +Euler-Bernoulli finite elements and Newmark average-acceleration integration. + +### Run the user case + +```powershell +python -m pip install -e ".[test]" +python examples/run_fsi_case.py +``` + +The runner reads [`cases/turek_hron_fsi1.json`](../cases/turek_hron_fsi1.json), +executes the coupled solve, and writes these images to +`results/fsi_turek_hron/`: + +- `fsi_fields.png`: speed contours and streamlines, pressure contours, fixed + cylinder, and undeformed/deformed beam shapes. The beam shape is magnified + for display when needed; the scale is printed in the figure title, while + solver results remain in actual SI coordinates. +- `fsi_history.png`: beam-tip displacement and velocity by iteration. + +The case can stop at an iteration limit (`max_steps`), a physical end time +(`end_time`, seconds), or whichever comes first when both are set. At least one +limit must be set. `max_steps` is an outer physical-step count; each step runs a +bounded fluid/beam coupling loop and advances only when its residual meets +`coupling_tolerance`. The default cap is 200 inner iterations per physical +step. If that cap is exhausted, the solver stops with +`time_step_not_converged` instead of advancing to another physical time step. + +Use `--steps` to override the case's iteration limit and `--end-time` to +override its physical end time. Supplying only `--end-time` removes the case's +`max_steps` limit; supplying both command-line options stops at whichever +limit comes first. The solver reduces its step size for stability and shortens +the final step to land exactly on `end_time`. It records the physical time for +every completed step. To watch every completed step, choose live mode: + +```powershell +python examples/run_fsi_case.py --case cases/turek_hron_fsi1.json --steps 250 --nx 160 --ny 32 --mode live +python examples/run_fsi_case.py --case cases/turek_hron_fsi1.json --end-time 0.25 --mode live +python examples/run_fsi_case.py --case cases/turek_hron_fsi1.json --steps 250 --end-time 0.25 +``` + +Live mode refreshes the exact same speed/streamline, pressure, and two-panel +beam-history plots after every iteration. The live figures stay open until +closed and are saved as the same `fsi_fields.png` and `fsi_history.png` files +as save mode. It requires an interactive Matplotlib backend. `--mode save` is +the default and writes only the final plots; add `--show` to open those final +plots. `--show` is unnecessary in live mode because its windows open +automatically. `--output PATH` changes the plot directory. The script prints +mesh spacing, iterations, elapsed simulation time, maximum speed/divergence, +beam-tip displacement, and saved plot paths. `--nx` and `--ny` override the +case file; otherwise edit those fields directly in the JSON file. + +### Understand and edit the case + +The user case uses a 2.5 m long by 0.41 m high channel, a 0.05 m-radius +cylinder centered at `(0.2, 0.2)` m, and a 0.35 m long, 0.02 m thick beam +rooted at the cylinder's downstream side. Fluid and structure properties, +inlet speed, time-step cap, and number of steps are all specified in the +case's `settings` object in SI units. Set `end_time` to a positive number of +seconds or `null` to disable that limit. The case includes +`minimum_time_step`, `coupling_tolerance`, and +`max_inner_iterations_per_time_step` controls. `minimum_time_step` prevents +unreasonably small stability-limited steps; reduce it only when appropriate +for the case. + +The default mesh is uniform Cartesian with `nx = 120` and `ny = 24`; each +setting is a number of cells, not a number of nodes. For this domain, +`dx = width / nx = 2.5 / 120 = 0.02083 m` and +`dy = height / ny = 0.41 / 24 = 0.01708 m`. The beam uses 12 finite elements, +independently of the fluid mesh. A finer fluid grid can better resolve the +cylinder and beam but costs more per time step. The solver limits each +effective step to its advection and explicit-diffusion stability bounds. + +The configuration fields correspond directly to `FSISettings`; for example, +the same setup can be built in Python and visualized without the CLI: + +```python +from fsi import FSISettings, FSISolver, plot_fsi_result + +settings = FSISettings(nx=120, ny=24, max_steps=None, end_time=0.25) +result = FSISolver(settings).run() +plots = plot_fsi_result(result, "results/fsi_turek_hron") +print(plots["fields"], plots["history"]) +``` + +`plot_fsi_result` returns paths for the two saved PNGs. Pass `show=True` to +display them as well. The solver result also exposes staggered `u` and `v`, +cell-centered pressure, final beam coordinates/velocity, and per-step +diagnostics including physical time, inner iteration count, and coupling +residual. `FSIResult.converged` indicates whether every completed physical step +converged; `termination_reason` distinguishes reaching the end-time limit, +reaching the step limit, and coupling non-convergence. An optional solver +observer receives copied fluid and beam arrays after each completed physical +step; `LiveFSIPlotter` uses that observer interface for live display. + +This is an initial benchmark-oriented reference solver, not a validated +Turek-Hron FSI1/FSI2 implementation: the fluid/structure update is partitioned +and weakly coupled, the beam load is a simplified drag model rather than a +resolved surface-traction integral, the beam model assumes small transverse +deflection, and the current solver does not export through the FVM +data-externalization pipeline. Treat coarse-grid outputs as qualitative until +independently verified against benchmark reference data. + +## Basic Heat-Transfer Solver + +The separate `heat_transfer` package solves **steady two-dimensional +conduction** in a rectangular plate. It uses a uniform cell-centered mesh and +a finite-volume balance for constant thermal conductivity. An edge can have a +prescribed temperature or be set to `null`. With convection disabled, a `null` +edge is insulated. With convection enabled, each `null` edge exchanges heat +with the ambient using a convective heat-transfer coefficient; fixed +temperature edges remain fixed. This is surface convection (a Robin boundary +condition), not bulk fluid flow. The model does not include internal heat +generation, radiation, or time-dependent temperatures. + +### Run the user case + +```powershell +python -m pip install -e ".[test]" +python examples/run_heat_transfer_case.py +``` + +The runner reads +[`cases/heated_rectangular_plate.json`](../cases/heated_rectangular_plate.json), +solves the plate, and writes `results/heat_plate/heat_plate.png`. The plot shows +the cell temperature field in degrees Celsius and heat-flux vectors in W/m^2. +Override the mesh or choose another case/output directory with: + +```powershell +python examples/run_heat_transfer_case.py --nx 80 --ny 40 +python examples/run_heat_transfer_case.py --case path/to/plate.json --output results/my_plate --show +``` + +For a live view, use: + +```powershell +python examples/run_heat_transfer_case.py --mode live +``` + +This is a steady-state problem, so live mode shows the iterative solution +converging to steady state; the iterations are numerical solver iterations, +not physical time steps. The temperature plot and heat-flux vectors refresh +after every iteration, and the final view is also saved to +`heat_plate.png`. Live mode requires an interactive Matplotlib backend. The +default `--mode save` runs without opening a window; add `--show` to display +its final plot. + +### Understand and edit the case + +The included case is a 1 m by 1 m square plate with thermal conductivity +`10 W/(m K)`. The top edge is held at `100 °C`, the bottom at `0 °C`, and the +left and right edges are `null`. The mesh has 50 cells in each direction, so +the cell sizes are `dx = width / nx = 0.02 m` and +`dy = height / ny = 0.02 m`. Temperatures and material properties can be +changed in the JSON file; `nx` and `ny` set the number of cells. + +The case has `convection_enabled: false` by default, so its `null` side edges +are insulated. To see the effect of convection, change it to `true` and rerun +the same case, saving the two runs to separate directories if you want to +compare their plots: + +```powershell +python examples/run_heat_transfer_case.py --output results/plate_insulated +# Set convection_enabled to true in the case JSON, then run: +python examples/run_heat_transfer_case.py --output results/plate_convection +``` + +The side edges will then exchange heat with the ambient at `20 °C`, using +`convection_heat_transfer_coefficient_w_m2_k: 25.0`. These convection inputs +are ignored while the flag is false. When enabled, both the coefficient and +`ambient_temperature_c` are required, finite values, and positive for the +coefficient. Convection is applied only to edges whose temperature is `null`; +fixed-temperature edges are not changed. + +At a convective edge, the discretization accounts for both conduction from the +cell center to the plate surface and heat transfer from the surface to the +ambient. The plot title identifies whether the run used conduction only or +conduction plus surface convection. + +The linear system is solved iteratively. `max_iterations` caps the number of +solver sweeps, `residual_tolerance` sets the normalized linear-residual target, +and `relaxation_factor` controls successive over-relaxation (between 0 and 2). +The CLI reports whether the tolerance was reached. + +The same solver can be called from Python: + +```python +from heat_transfer import HeatSettings, HeatSolver, LiveHeatPlotter, plot_heat_result + +settings = HeatSettings(nx=50, ny=50, top_temperature_c=100.0) +plotter = LiveHeatPlotter(settings, "results/heat_plate") +result = HeatSolver(settings).run(observer=plotter) +plot_path = plotter.finish(result) +print(plot_path) +``` + +For a non-live run, omit the observer and plot the final result: + +```python +result = HeatSolver(settings).run() +plot_path = plot_heat_result(result, "results/heat_plate") +``` + +The result contains cell-centered temperatures, x/y conductive heat-flux +components, and cell-center coordinates. For a useful basic verification, +opposing fixed temperatures with the other two edges insulated produce a +linear temperature profile between those edges. + +## 3D External Flow: Finite Rectangular Wing + +The `fvm3d` package adds a steady, incompressible, low-Reynolds-number +projection solver for external flow around a finite rectangular wing. Internal +pseudo-time steps numerically march the flow toward a steady solution; they +are not physical time, and the solver has no physical end-time input. The wing +chord is along x, the surface normal is y, and the finite span is along z. The +angle of attack is represented in the wing-fixed frame by the incoming +velocity: positive angles have a negative y velocity component. The solver +accepts angles from -5 to 20 degrees and computes the other inlet components +from exactly one supplied input: `inlet_speed`, `inlet_velocity_x`, or +`inlet_velocity_y`. For example, if specifying `inlet_velocity_x`, set the +other two velocity inputs to `null`. + +### Run the user case + +```powershell +python -m pip install -e ".[test]" +python examples/run_finite_wing_case.py +``` + +The case runs 200 steady iterations by default. Change `max_iterations` in the +case JSON or pass `--iterations N` to control the run length. Live mode updates +all three plots after every iteration: + +```powershell +python examples/run_finite_wing_case.py --mode live +python examples/run_finite_wing_case.py --mode live --iterations 40 +``` + +Live mode requires an interactive Matplotlib backend. It leaves the final +windows open until they are closed and saves the final images to the output +directory. Save mode writes the final images without opening windows; add +`--show` to display those final plots. + +The runner reads +[`cases/finite_wing_low_re.json`](../cases/finite_wing_low_re.json) and saves +three plots under `results/finite_wing_low_re/`: + +- `finite_wing_midspan.png`: speed and streamlines in the wing's mid-span + plane. +- `finite_wing_tip_vorticity.png`: streamwise-vorticity slices at several + downstream locations. The red/blue field shows opposite-signed vortex cores; + black cross-plane streamlines show the induced circulation, with the uniform + inlet component removed so the rotation is easier to distinguish. +- `finite_wing_3d_streamlines.png`: 3D streamlines seeded just behind the wing + and traced downstream through the wake. Coordinates are rotated to align + with the freestream, and lines are colored by streamwise vorticity to + highlight the wingtip wake. + +Change the angle in the case file or override it on the command line. The +velocity components are recalculated from the selected speed input and the +new angle: + +```powershell +python examples/run_finite_wing_case.py --angle-of-attack 10 +python examples/run_finite_wing_case.py --angle-of-attack -3 --iterations 40 --output results/wing_minus_3deg +``` + +`--nx`, `--ny`, and `--nz` override the 3D cell counts. The reported +chord-based Reynolds number is calculated from the resolved inlet speed, +density, dynamic viscosity, and wing chord. For the included case, these +values give `Re = 1000`. + +The example uses a 6 m x 3 m x 3 m domain and a 1 m chord by 1.5 m span wing. +Its 48 x 25 x 25 uniform grid represents the wing as a voxelized thin +rectangular solid. Refine the mesh and increase the far-field distances to +check sensitivity; the default is intended to make the flow structure +inspectable, not to provide grid-independent coefficients. This is a laminar +demonstrator, not a high-Reynolds-number RANS model or a validated aerodynamic +benchmark. It resolves qualitative tip-vortex development but does not claim +aircraft-design accuracy. + +### Transient Case: Angle-of-Attack Ramp + +The separate +[`finite_wing_angle_ramp_transient.json`](../cases/finite_wing_angle_ramp_transient.json) +case starts at 0 degrees and ramps linearly to 5 degrees over 5 physical +seconds. Its schedule explicitly sets 0, 1, 2, 3, 4, and 5 degrees at times +0, 1, 2, 3, 4, and 5 seconds, respectively; the freestream speed remains +1 m/s. Run the case from the project root: + +```powershell +python examples/run_finite_wing_transient_case.py +python examples/run_finite_wing_transient_case.py --mode live +``` + +The transient runner updates the inlet direction at every physical time step +and writes the same three plots as the steady case. Its +10 m downstream domain and 2 m outlet damping layer give the wake room to +convect before it reaches the fixed-freestream outlet. The time-step cap, +outlet damping length, and end time are in the JSON file. The live option +refreshes all plots after every physical step and requires an interactive +Matplotlib backend. The transient flow is still a low-Re laminar demonstrator, +not a validated aerodynamic benchmark. + +## 2. Install and Run the Complete Example + +From the project root, install the package and its test tools: + +```powershell +python -m pip install -e ".[test]" +``` + +Run the dedicated user workflow: + +```powershell +python examples/run_user_case.py +``` + +The default case is +[`cases/lid_driven_cavity_re100_steady.json`](../cases/lid_driven_cavity_re100_steady.json). +It uses fixed pseudo-time increments to reach the configured steady-state +criteria. The reported count is iterations; pseudo-time is not physical elapsed +time. A separate transient example is +[`cases/lid_driven_cavity_re100_transient.json`](../cases/lid_driven_cavity_re100_transient.json), +which ramps the lid from 0 to 4 m/s over four seconds and holds that speed +through its six-second end time. + +Run the steady default or select the transient case explicitly: + +```powershell +python examples/run_user_case.py +python examples/run_user_case.py --case cases/lid_driven_cavity_re100_transient.json --output results/lid_driven_cavity_transient +``` + +To run another schema-v1 case and choose an output directory: + +```powershell +python examples/run_user_case.py --case path/to/setup-export.json --output results/my_case +``` + +The command has two visualization modes. The default `save` mode writes the +geometry and final-result PNGs without opening windows. `live` mode opens the +geometry window before the solve, updates speed/pressure/convergence windows +after every time step, and still saves the same PNGs and data files. Select it +with an interactive Matplotlib backend: + +```powershell +python examples/run_user_case.py --mode save +python examples/run_user_case.py --mode live +``` + +The live windows stay open at the final state until closed. `--live` remains a +short alias for `--mode live`. Headless systems should use `save` mode; it +preserves the geometry, final-field, centerline, and convergence PNGs without +requiring a display server. + +The command returns exit code `0` for a converged simulation and `2` if the +case reached its maximum step count without converging. In either case, it +writes available fields and diagnostics so a capped run can be inspected. + +## 3. Define the Problem + +The complete JSON structure is in the example case linked above. Its main +sections are: + +| Section | Purpose | +| --- | --- | +| `schema_version`, `case_id` | Contract version and stable setup identifier | +| `units` | Unit system; version 1.0 requires SI | +| `physics` | Incompressible laminar model and `transient` mode selector | +| `domain`, `mesh` | Rectangle dimensions and uniform cell counts | +| `material` | Density and dynamic viscosity | +| `initial_conditions` | Uniform initial velocity and pressure | +| `boundary_conditions` | One supported velocity-wall type per side and pressure-correction condition | +| `solver` | Fixed pseudo-time step or transient time-step cap, CFL limit, step limits, and tolerances | + +For example, the Re=100 case uses the following key values: + +```json +{ + "domain": {"type": "rectangle", "width_m": 1.0, "height_m": 1.0}, + "mesh": {"type": "uniform_cartesian", "nx": 16, "ny": 16}, + "material": { + "type": "newtonian_fluid", + "density_kg_m3": 1.0, + "dynamic_viscosity_pa_s": 0.01 + }, + "initial_conditions": {"u_m_s": 0.0, "v_m_s": 0.0, "pressure_pa": 0.0}, + "boundary_conditions": { + "west": {"type": "no_slip_wall"}, + "east": {"type": "no_slip_wall"}, + "south": {"type": "no_slip_wall"}, + "north": {"type": "moving_wall", "velocity_m_s": [1.0, 0.0]}, + "pressure_correction": "homogeneous_neumann" + } +} +``` + +The JSON Schema requires all top-level sections and `solver.max_steps`; other +solver controls use defaults. Set `physics.transient` to `false` for steady-state +iteration. In steady mode, the solver selects one conservative fixed pseudo-time +step at startup, capped by `max_time_step_s` if supplied. For finite transients, +include `end_time_s`; the solver uses CFL-limited physical steps and converges +each step before advancing. `max_inner_iterations_per_time_step` bounds that +inner convergence loop. Copy a full case and update the mesh, material, wall +data, and mode-specific solver settings together. For the square cavity, + +`Re = density * lid_speed * cavity_width / dynamic_viscosity`. + +Thus `rho=1 kg/m^3`, `U=1 m/s`, `L=1 m`, and `mu=0.01 Pa.s` give Re=100. +The solver does not infer a benchmark Reynolds number from a case ID; it uses +the physical values in the document. + +## 4. Validate and Run From Python + +A setup application can validate its generated mapping before launching the +backend. Schema errors identify the offending JSON path, and unsupported +features are rejected before numerical work begins. + +```python +import json +from pathlib import Path + +from fvm import PythonFVMBackend, validate_case_document + +case_path = Path("cases/lid_driven_cavity_re100_workflow.json") +case_document = json.loads(case_path.read_text(encoding="utf-8")) +validate_case_document(case_document) + +run = PythonFVMBackend().run( + case_document, + output_directory=Path("results/lid_driven_cavity_re100"), +) +print(run.summary["status"]) +print(run.summary["steps"], run.summary["final_time_s"]) +``` + +The file-based variant performs loading and validation for you: + +```python +from fvm import PythonFVMBackend + +run = PythonFVMBackend().run_file( + "cases/lid_driven_cavity_re100_workflow.json", + output_directory="results/lid_driven_cavity_re100", +) +``` + +`run.simulation` contains the solver-native fields and history. For steady +cases, `final_time_s` is `null` and `final_pseudo_time_s` is reported separately. +For transient cases, `final_time_s` is physical simulation time. `run.summary` +is a JSON-compatible integration result intended for setup software. The +backend is independent of the calling application's classes and APIs. + +Applications that need custom per-step visualization can use the observer +instead of the CLI's plotting helper. It is called once after each full +predictor/pressure/projection step and receives read-only-by-contract defensive +copies, so observer code cannot change the run state: + +```python +def show_step(diagnostics, velocity, pressure): + print( + diagnostics.step, + diagnostics.time, + diagnostics.max_divergence_after, + ) + +run = PythonFVMBackend().run_file( + "cases/lid_driven_cavity_re100_workflow.json", + step_observer=show_step, +) +``` + +## 5. Check Convergence Before Trusting a Result + +Steady cases stop when velocity change, continuity, mass balance, and linear +solver tolerances pass. Transient cases apply the same criteria inside every +physical time step and stop if a step cannot converge within its configured +inner-iteration limit. Inspect the result status and final history entry: + +```python +last_step = run.simulation.history[-1] +print("converged:", run.simulation.converged) +print("termination:", run.simulation.termination_reason) +print("max divergence:", last_step.max_divergence_after) +print("global mass imbalance:", last_step.global_mass_imbalance) +print("velocity change:", last_step.velocity_change) +``` + +In steady mode, the solver selects a fixed pseudo-time step once at startup and +caps it to honor the CFL limit; the chosen step remains constant throughout the +run. In transient mode, `max_time_step_s` is a cap, and each step is reduced as +needed to honor the explicit-convection CFL limit. A `time_step_not_converged` result +means the solver stopped at that physical step; increase +`max_inner_iterations_per_time_step` or adjust tolerances before trusting the +trajectory. `maximum_steps_reached` means the steady run did not converge or a +transient run did not reach `end_time_s`. + +## 6. Read the Output Artifacts + +The output directory contains: + +| File | Contents | +| --- | --- | +| `case.json` | Canonical validated case document consumed by the backend | +| `checkpoints/` | Optional restart files and `latest.json` manifest when checkpointing is enabled | +| `summary.json` | Case ID, schema/backend versions, status, Reynolds number, extrema, and final conservation/residual metrics | +| `fields.npz` | Coordinates, pressure, face-centered `u`/`v`, and cell-centered `u`/`v` arrays | +| `metadata.json` | Mesh, solver settings, temporal mode, convergence state, physical/pseudo-time, and extrema | +| `history.csv` | Per-step time or pseudo-time, CFL, inner-iteration count, velocity change, continuity, mass imbalance, and linear residuals | +| `ghia_re100.json` | Interior-point Ghia profile values, RMS errors, and benchmark eligibility | +| `geometry.png` | Domain outline, uniform mesh, and moving-wall direction | +| `cavity_fields.png` | Final velocity magnitude, pressure, and streamlines | +| `ghia_profiles.png` | Computed centerline profiles against Ghia reference points | +| `convergence_history.png` | Velocity change, divergence, and pressure residual over time | + +Open the compressed field arrays with NumPy: + +```python +import numpy as np + +with np.load("results/lid_driven_cavity_re100/fields.npz") as fields: + pressure = fields["pressure"] + u_faces = fields["u_faces"] + v_faces = fields["v_faces"] + u_cells = fields["u_cell_centers"] + v_cells = fields["v_cell_centers"] +``` + +Pressure is cell-centered with shape `(ny, nx)`. Face velocities have shapes +`u=(ny, nx+1)` and `v=(ny+1, nx)`. Cell-centered velocity arrays in the export +are interpolated for plotting and do not replace the staggered solution fields. + +## 7. Save and Resume Checkpoints + +Checkpointing is optional and separate from result export. The case JSON is the +problem definition; a checkpoint is the solver state needed to continue that +case. `fields.npz`, `metadata.json`, and `history.csv` are post-processing +outputs and are not restart inputs. Checkpoint cadence, retention, and restart +selection are runtime options (`--checkpoint-every`, `--retain-checkpoints`, +and `--restart`); the version 1.0 case schema remains unchanged. + +Start a run with a checkpoint every 100 completed steps: + +```powershell +python examples/run_user_case.py ` + --case cases/lid_driven_cavity_re100_transient.json ` + --output results/cavity_restart ` + --checkpoint-every 100 ` + --retain-checkpoints 5 +``` + +The output workspace contains: + +| File | Purpose | +| --- | --- | +| `case.json` | Canonical copy of the validated case used for this run; also readable as a case input | +| `checkpoints/checkpoint_00000100.npz` | Compressed pressure, staggered velocity, saved case configuration, time/step state, and complete diagnostics history | +| `checkpoints/latest.json` | Atomic pointer to the most recently committed checkpoint, including its SHA-256 digest | +| `fields.npz`, `metadata.json`, `history.csv` | Final result and monitoring exports; useful for analysis, but not sufficient to resume | + +The solver writes periodic checkpoints only at complete step boundaries. It +also writes the final safe state on normal completion. A failed finite-transient +inner solve is not treated as a completed physical step, so it does not replace +the last safe checkpoint. If the process is forcibly terminated, recovery starts +from the latest committed checkpoint and may repeat work since that checkpoint. +An incomplete write cannot replace the previous `latest.json` target. + +Resume from the latest checkpoint in the same workspace: + +```powershell +python examples/run_user_case.py ` + --case results/cavity_restart/case.json ` + --output results/cavity_restart ` + --checkpoint-every 100 ` + --restart latest +``` + +To resume a particular checkpoint instead, pass its filename: + +```powershell +python examples/run_user_case.py ` + --case results/cavity_restart/case.json ` + --output results/cavity_restart ` + --checkpoint-every 100 ` + --restart checkpoint_00000100.npz +``` + +`--restart` requires `--checkpoint-every`, so the continued run keeps producing +recovery points. `--retain-checkpoints` defaults to 5; older files are removed +only after a newer checkpoint and its manifest have been committed. + +On restart, the mesh, material, boundary conditions, initial case definition, +and numerical controls must match the saved case. You may increase `solver.max_steps` +and, for a finite transient, increase `solver.end_time_s`; reducing either is +rejected. For example, copy the case to a new JSON file, increase the applicable +run limit, then pass that file with `--case`. `max_steps` is the total global +step limit, not an additional-step count: to continue checkpoint step 1,000 to +step 2,000, set `max_steps` to 2,000. All other case fields must remain +unchanged. Checkpoints include the configuration that produced them, so the +case file can be validated before any solver step is advanced. + +The same workflow is available through the Python backend: + +```python +from fvm import PythonFVMBackend + +backend = PythonFVMBackend() +first_run = backend.run_file( + "cases/lid_driven_cavity_re100_transient.json", + output_directory="results/cavity_restart", + checkpoint_every=100, +) + +continued_run = backend.run_file( + "results/cavity_restart/case.json", + output_directory="results/cavity_restart", + checkpoint_every=100, + restart="latest", +) +``` + +This example resumes an interrupted run with its original limits. To continue +after a configured step or end-time limit, pass a copied case with the relevant +limit increased as described above; do not change its other fields. + +For a selected file, use `restart="checkpoint_00000100.npz"`. The backend also +accepts an absolute checkpoint path. The Python API and CLI use the same +checkpoint directory and file format. + +## 8. Interpret the Ghia Comparison and Visuals + +The workflow interpolates the staggered velocities onto `x=0.5` and `y=0.5`, +then computes RMS errors at Ghia's interior Re=100 sample coordinates. Wall +endpoints are excluded, including the discontinuous moving-lid corners. The +reference data source and DOI are documented in +[`src/fvm/postprocessing.py`](../src/fvm/postprocessing.py). + +`ghia_re100.json` includes `benchmark_valid`. It is true only when the +simulation reports convergence and the run matches the square Re=100 benchmark +assumptions. A short, capped run can still produce plots and RMS values for +diagnosis, but those numbers are not a benchmark pass. The 16 by 16 example is +for learning the workflow; use the optional grid-study API and compare +successively refined, converged runs before making grid-independence claims. + +The live plot updates on every solver step when `--live` is enabled. Saved PNGs +show the starting geometry and final state. The PNGs can also be regenerated/customized through +`plot_cavity_fields`, `plot_ghia_comparison`, and +`plot_convergence_history` in `fvm.postprocessing`. + +## 9. Adapt This Workflow + +For another problem supported by schema version 1.0: + +1. Copy the case JSON and assign a unique `case_id`. +2. Set rectangle dimensions, uniform mesh counts, fluid properties, and + initial fields in SI units. +3. Assign one supported wall condition to each side. Moving-wall velocity + must be tangential to its side. +4. Choose steady fixed pseudo-time or transient physical-time controls. For a + transient, define `end_time_s` and optionally a tabulated wall velocity + profile; its points must have increasing `time_s` values and tangential + velocity components. +5. Validate the document, run it through `PythonFVMBackend`, and inspect the + convergence status before comparing results. +6. Use the exported fields and diagnostics or add problem-specific post- + processing around `run.simulation`. + +For capabilities outside that list, extend the versioned schema and adapter +with focused tests and documentation rather than encoding extra meanings in +existing fields. This keeps the setup-software interface explicit and lets +both projects evolve independently. + +## 10. Compare Data Externalization Strategies + +For a plain-language explanation of the strategies and a step-by-step user +comparison guide, see +[`data_externalization_guide.md`](./data_externalization_guide.md). + +The solver's numerical loop remains responsible only for solving. The existing +completed-step observer is the boundary to a separate `fvm.externalization` +package: it captures an immutable, versioned `StepSnapshot` and passes it to a +selected transport. Snapshots contain mesh coordinates, pressure, staggered +velocities, and step diagnostics. They are compressed NumPy archives written +without pickle; the common `SnapshotStore` commits each file atomically. A +consumer or visualization tool can read the snapshots without importing solver +classes. The store partitions files under validated run-ID directories, so +independent runs do not collide on step numbers. + +The included local strategies are: + +| Strategy | Data path | Solver-side cost | Useful when | +| --- | --- | --- | --- | +| `sync` | Write each snapshot directly to the result store | Includes full file serialization and write time | Small cases, simplest reliable local export | +| `shared` | Write an atomic snapshot to a shared-folder spool; a separate poller copies it on its schedule | Spool write only; the poller's processing is decoupled | Larger runs or a separately deployed externalizer | +| `async` | Enqueue into a bounded in-process queue; a worker writes snapshots | Queue handoff until the bounded queue fills; close drains the queue | Local runs where some storage latency can be overlapped | +| `grpc` | Bounded client queue and streaming gRPC to a snapshot service | Queue handoff plus any backpressure from the bounded stream | A service boundary that can later move to another host | + +These are delivery paths, not a promise of zero solver overhead. Shared-folder +and gRPC producers still serialize snapshots and enqueue/write them locally. +The async and gRPC queues are bounded and apply backpressure rather than +silently dropping snapshots. Background write/transport failures are surfaced +when publishing or closing. The shared-folder spool retains source files for +replay; monitor and manage its disk use separately from the solver output. + +Install the package (gRPC dependencies are part of the project install), then +run all four strategies against the same case: + +```powershell +python examples/compare_externalization_strategies.py --steps 4 +python examples/compare_externalization_strategies.py ` + --case cases/lid_driven_cavity_re100_transient.json ` + --strategy grpc ` + --steps 20 ` + --snapshot-every 1 +``` + +The default POC caps each run to four steps so it completes quickly; set +`--steps` to compare longer runs. By default snapshots are externalized every +10 completed steps, with the final step always included; use +`--snapshot-every 1` to publish every step. Each strategy writes its snapshots +and a `final_snapshot.png` under +`results/externalization_poc///`. Each run store contains +atomic `latest.json` pointers beside its step archives. The +`benchmark.csv` and `benchmark.json` report solver wall time, total time +(including drain/close), producer publish time, downstream externalization +time, bytes, completed steps, snapshot interval/count, and wall time per +solver step. This is a local measurement, not a cloud performance claim: run +multiple repetitions on the same host and compare +the same case, mesh, step budget, and filesystem before presenting conclusions. +With the default four-step cap, only the final snapshot is saved because the +run does not reach step 10. + +The shared-folder consumer is independently runnable: + +```powershell +python examples/poll_shared_snapshots.py ` + --shared results/my_run/shared ` + --destination results/my_run/snapshots ` + --interval 1 +``` + +Wire a strategy to the existing backend without changing the solver itself: + +```python +from fvm import PythonFVMBackend +from fvm.externalization import ( + SharedFolderExternalizer, + create_step_observer, +) + +externalizer = SharedFolderExternalizer("results/my_run/shared") +observer = create_step_observer( + externalizer, "my-run", snapshot_every=10 +) +try: + run = PythonFVMBackend().run_file( + "cases/lid_driven_cavity_re100_workflow.json", + step_observer=observer, + ) + if run.simulation.history: + observer.publish_final_step( + run.simulation.history[-1], + run.simulation.velocity, + run.simulation.pressure, + ) +finally: + externalizer.close() +``` + +`snapshot_every` defaults to 10. The observer publishes steps divisible by +that interval; call `publish_final_step` after the run to make sure the final +state is stored even when it falls between intervals. Set `snapshot_every=1` +to publish every step. + +The other strategies implement the same `publish(snapshot)` / `close()` +contract. `GrpcSnapshotServer` is a local demonstration service; it uses +insecure transport on loopback by default. The server's `start(credentials=...)` +and client's `GrpcExternalizer(credentials=...)` accept gRPC TLS credentials. +The client stream has no deadline by default, so long solves are not cut off +while snapshots are being published; set `timeout_seconds` when a bounded +stream lifetime is required. +Before deploying across a network, configure authentication/authorization, +resource limits, retry/idempotency policy, and a durable cloud-backed +`SnapshotStore`. The gRPC wire contract is defined in +[`src/fvm/externalization/snapshot_service.proto`](../src/fvm/externalization/snapshot_service.proto). +Snapshot files are stored under `//step_.npz`, with an +atomic `latest.json` pointer per run. + +Visualization can consume a snapshot directory independently of solver state: + +```python +from fvm.externalization import SnapshotStore, plot_latest_snapshot + +plot_latest_snapshot( + SnapshotStore("results/my_run/snapshots"), + "results/my_run/latest.png", +) +``` + +Implement a new transport by satisfying the small `Externalizer` protocol and +keeping the existing `StepSnapshot` schema stable. This keeps solver +responsibility, transport implementation, storage, and visualization +separately replaceable. + +### Run a case and plot each externalized step + +Use the separate example when you want to run your case with one strategy and +create plots from the saved snapshots: + +```powershell +python examples/run_externalized_case.py ` + --case path/to/your-case.json ` + --strategy async +``` + +Choose `sync`, `shared`, `async`, or `grpc` with `--strategy`. The default is +`sync`. By default it externalizes every 10 solver steps plus the final step; +set `--snapshot-every 1` for every step. The script saves one PNG per +externalized snapshot under +`results/externalized_case///step_plots/` and a +`final_result.png` beside that folder. Each plot is loaded from the selected +strategy's externalized snapshot store, not from the solver's in-memory result. +For a shorter demonstration without editing the case, add `--max-steps 4`. +The case's configured step limit is used when that option is omitted. + +Add `--mode live` to display snapshots as they become available in that store: + +```powershell +python examples/run_externalized_case.py ` + --case path/to/your-case.json ` + --strategy async ` + --mode live +``` + +Live mode needs an interactive Matplotlib backend. The solver runs in the +background while the viewer reads committed snapshots from the store; it does +not plot from the solver callback. It keeps one plotter window open, updates the +field panels in place, and appends each step to the convergence history. The +`shared` view can therefore lag by the polling interval. The final plot stays +open until you close it, after which the per-step PNGs and `final_result.png` +are saved. \ No newline at end of file diff --git a/Exp_solver_dev_tr/examples/compare_externalization_strategies.py b/Exp_solver_dev_tr/examples/compare_externalization_strategies.py new file mode 100644 index 0000000000000..cb12acacce8d3 --- /dev/null +++ b/Exp_solver_dev_tr/examples/compare_externalization_strategies.py @@ -0,0 +1,244 @@ +"""Compare local solver-step externalization strategies on the same case. + +Run from the repository root: + python examples/compare_externalization_strategies.py --steps 4 +""" + +from __future__ import annotations + +import argparse +import csv +import json +from pathlib import Path +import threading +from time import perf_counter +from uuid import uuid4 + +from fvm import PythonFVMBackend, load_case_file +from fvm.externalization import ( + AsyncFileExternalizer, + GrpcExternalizer, + GrpcSnapshotServer, + SharedFolderExternalizer, + SharedFolderPoller, + SnapshotStore, + SynchronousFileExternalizer, + create_step_observer, + plot_latest_snapshot, +) + + +ROOT = Path(__file__).resolve().parents[1] +STRATEGIES = ("sync", "shared", "async", "grpc") + + +def build_argument_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Measure solver and local externalization timings." + ) + parser.add_argument( + "--case", + type=Path, + default=ROOT / "cases" / "lid_driven_cavity_re100_steady.json", + help="Case JSON to run for every strategy.", + ) + parser.add_argument( + "--output", + type=Path, + default=ROOT / "results" / "externalization_poc", + help="Directory for strategy output, plots, and benchmark.csv.", + ) + parser.add_argument( + "--strategy", + choices=(*STRATEGIES, "all"), + default="all", + help="Run one strategy or all four (default: all).", + ) + parser.add_argument( + "--steps", + type=int, + default=4, + help="Maximum solver steps per strategy (default: 4).", + ) + parser.add_argument( + "--snapshot-every", + type=int, + default=10, + help="Externalize every N completed steps and always the final step (default: 10).", + ) + parser.add_argument( + "--queue-size", + type=int, + default=8, + help="Bounded in-memory queue size for async and gRPC strategies.", + ) + parser.add_argument( + "--poll-interval", + type=float, + default=0.1, + help="Independent shared-folder poll interval in seconds.", + ) + return parser + + +def _run_strategy( + strategy: str, + case_document: dict[str, object], + output: Path, + queue_size: int, + poll_interval: float, + snapshot_every: int, +) -> dict[str, object]: + run_id = f"{case_document['case_id']}-{uuid4().hex[:8]}" + strategy_output = output / strategy / run_id + store_directory = strategy_output / "snapshots" + poller: SharedFolderPoller | None = None + poller_thread: threading.Thread | None = None + poller_stop: threading.Event | None = None + poller_errors: list[Exception] = [] + grpc_server: GrpcSnapshotServer | None = None + + if strategy == "sync": + externalizer = SynchronousFileExternalizer(store_directory) + elif strategy == "shared": + shared_directory = strategy_output / "shared" + poller = SharedFolderPoller(shared_directory, store_directory) + poller_stop = threading.Event() + + def poll_until_stopped() -> None: + try: + poller.run(poll_interval, poller_stop) + except Exception as error: + poller_errors.append(error) + + poller_thread = threading.Thread( + target=poll_until_stopped, + name=f"snapshot-poller-{strategy}", + daemon=True, + ) + poller_thread.start() + externalizer = SharedFolderExternalizer(shared_directory) + elif strategy == "async": + externalizer = AsyncFileExternalizer(store_directory, queue_size=queue_size) + else: + grpc_server = GrpcSnapshotServer(store_directory) + externalizer = GrpcExternalizer( + grpc_server.start(), queue_size=queue_size + ) + + started = perf_counter() + try: + observer = create_step_observer( + externalizer, run_id, snapshot_every=snapshot_every + ) + run = PythonFVMBackend().run( + case_document, + step_observer=observer, + ) + if run.simulation.history: + observer.publish_final_step( + run.simulation.history[-1], + run.simulation.velocity, + run.simulation.pressure, + ) + solver_seconds = perf_counter() - started + finally: + try: + externalizer.close() + finally: + if poller_stop is not None and poller_thread is not None: + poller_stop.set() + poller_thread.join() + if poller_errors: + raise RuntimeError("shared-folder polling failed") from poller_errors[0] + if grpc_server is not None: + grpc_server.stop() + total_seconds = perf_counter() - started + + if poller is not None: + snapshot_count = poller.snapshots + externalize_seconds = poller.externalize_seconds + bytes_written = poller.bytes_written + else: + snapshot_count = externalizer.metrics.snapshots + externalize_seconds = externalizer.metrics.externalize_seconds + bytes_written = externalizer.metrics.bytes_written + expected_snapshot_count = run.simulation.steps // snapshot_every + if run.simulation.steps % snapshot_every: + expected_snapshot_count += 1 + if snapshot_count != expected_snapshot_count: + raise RuntimeError( + f"{strategy} externalized {snapshot_count} snapshots for " + f"{run.simulation.steps} completed steps at interval {snapshot_every}" + ) + + plot_latest_snapshot( + SnapshotStore(store_directory), strategy_output / "final_snapshot.png" + ) + return { + "strategy": strategy, + "steps": run.simulation.steps, + "snapshot_every": snapshot_every, + "converged": run.simulation.converged, + "solver_seconds": solver_seconds, + "total_seconds": total_seconds, + "publish_seconds": externalizer.metrics.publish_seconds, + "externalize_seconds": externalize_seconds, + "bytes_written": bytes_written, + "snapshot_count": snapshot_count, + "seconds_per_step": ( + total_seconds / run.simulation.steps if run.simulation.steps else 0.0 + ), + } + + +def main() -> int: + arguments = build_argument_parser().parse_args() + if arguments.steps <= 0: + raise SystemExit("--steps must be positive") + if arguments.queue_size <= 0: + raise SystemExit("--queue-size must be positive") + if arguments.poll_interval <= 0.0: + raise SystemExit("--poll-interval must be positive") + if arguments.snapshot_every <= 0: + raise SystemExit("--snapshot-every must be positive") + + case_document = load_case_file(arguments.case).to_mapping() + solver_config = case_document["solver"] + solver_config["max_steps"] = min(solver_config["max_steps"], arguments.steps) + strategies = STRATEGIES if arguments.strategy == "all" else (arguments.strategy,) + arguments.output.mkdir(parents=True, exist_ok=True) + rows = [ + _run_strategy( + strategy, + case_document, + arguments.output, + arguments.queue_size, + arguments.poll_interval, + arguments.snapshot_every, + ) + for strategy in strategies + ] + + report_path = arguments.output / "benchmark.csv" + with report_path.open("w", newline="", encoding="utf-8") as report_file: + writer = csv.DictWriter(report_file, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + (arguments.output / "benchmark.json").write_text( + json.dumps(rows, indent=2), encoding="utf-8" + ) + print("strategy steps snapshots solver(s) total(s) externalize(s) bytes") + for row in rows: + print( + f"{row['strategy']:<12} {row['steps']:>5} " + f"{row['snapshot_count']:>9} " + f"{row['solver_seconds']:>9.4f} {row['total_seconds']:>8.4f} " + f"{row['externalize_seconds']:>14.4f} {row['bytes_written']}" + ) + print(f"Benchmark report: {report_path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Exp_solver_dev_tr/examples/end_to_end_examples.py b/Exp_solver_dev_tr/examples/end_to_end_examples.py new file mode 100644 index 0000000000000..008febc8495a5 --- /dev/null +++ b/Exp_solver_dev_tr/examples/end_to_end_examples.py @@ -0,0 +1,414 @@ +"""End-to-end examples for the staged development of the independent FVM solver. + +Run this file from the project root with ``python examples/end_to_end_examples.py``. +The examples are ordered to show the current workflow: + +1. Construct mesh, pressure, and staggered velocity fields. +2. Assign boundary conditions to each physical side. +3. Inspect the resulting geometry and field locations. +4. Exercise M2 operators with manufactured fields and compare to exact values. +5. Assemble and solve one M3 momentum-prediction step for cavity setups. +6. Solve the M4 pressure correction and report its compatibility and residual. +7. Apply the M5 correction, update pressure, and check continuity and mass. +8. Run M6 transient steps with a CFL cap and explicit convergence status. +9. Export fields/history and generate M7 plots and Ghia diagnostics. +10. Load a versioned setup-software case through the M8 backend adapter. + +The cavity setup examples stop after configuration. The manufactured case +checks M2 operators; M3 solves the momentum predictor; M4 solves pressure +correction; M5 applies it and checks conservation; M6 runs the transient loop; +M7 exports and plots results and evaluates the Ghia profiles. The default M6 +run is intentionally short, so its Ghia errors are diagnostic rather than a +claim of benchmark validation. M8 demonstrates the separate setup-software +boundary: a JSON contract is validated, translated, executed, and exported +without importing any setup-framework code. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from fvm import ( + BOUNDARY_NAMES, + BoundaryConditions, + CartesianMesh, + MovingWall, + MomentumPredictor, + MomentumPrediction, + NoSlipWall, + PressureCorrectionResult, + PressureCorrectionSolver, + ProjectionCorrector, + PythonFVMBackend, + ScalarField, + SimulationResult, + TransientSolver, + VectorField, + ZeroGradient, + convection_operator, + diffusion_operator, + divergence, + compare_ghia_re100, + export_ghia_comparison, + export_simulation_result, + face_gradient, + interpolate_to_faces, + plot_cavity_fields, + plot_convergence_history, + plot_ghia_comparison, + velocity_extrema, +) + + +@dataclass(frozen=True, slots=True) +class ExampleSetup: + """Mesh, fields, and boundary conditions for one configured example. + + This is a lightweight container for demonstrations, not the versioned case + input format planned for setup-software integration. + """ + + name: str + mesh: CartesianMesh + pressure: ScalarField + velocity: VectorField + boundary_conditions: BoundaryConditions + + +def _cavity_setup(name: str, nx: int, ny: int, lid_velocity: float) -> ExampleSetup: + """Build the mesh, zero fields, and side conditions for a unit-square cavity. + + All walls are stationary except the north wall when ``lid_velocity`` is + nonzero. Pressure uses zero-gradient conditions on all sides. These + conditions are stored here. M3 applies velocity wall values in its + predictor, while M4/M5 enforce pressure-correction and continuity behavior. + """ + mesh = CartesianMesh(nx=nx, ny=ny, width=1.0, height=1.0) + pressure = ScalarField(mesh, name="pressure") + velocity = VectorField(mesh, name="velocity") + conditions = BoundaryConditions() + + for side in BOUNDARY_NAMES: + if side == "north" and lid_velocity != 0.0: + conditions.set("velocity", side, MovingWall((lid_velocity, 0.0))) + else: + conditions.set("velocity", side, NoSlipWall()) + conditions.set("pressure", side, ZeroGradient()) + + return ExampleSetup(name, mesh, pressure, velocity, conditions) + + +def stationary_cavity() -> ExampleSetup: + """Create a zero-flow baseline with all four walls stationary.""" + return _cavity_setup("stationary cavity", nx=32, ny=32, lid_velocity=0.0) + + +def lid_driven_cavity_re100() -> ExampleSetup: + """Create the 64 by 64 Re=100 cavity mesh and boundary setup. + + The Re=100 material values are rho=1 kg/m^3 and mu=0.01 Pa.s. The project + does not yet define material models, so these values are passed directly to + the momentum predictor in the M3 example. + """ + return _cavity_setup("lid-driven cavity Re=100", nx=64, ny=64, lid_velocity=1.0) + + +def staggered_grid_demonstration() -> ExampleSetup: + """Create a non-square mesh to make MAC shapes and coordinates visible.""" + mesh = CartesianMesh(nx=4, ny=2, width=2.0, height=1.0) + pressure = ScalarField(mesh, name="pressure") + velocity = VectorField(mesh, name="velocity") + conditions = BoundaryConditions() + + for side in BOUNDARY_NAMES: + conditions.set("velocity", side, NoSlipWall()) + conditions.set("pressure", side, ZeroGradient()) + + return ExampleSetup( + "rectangular staggered-grid demonstration", + mesh, + pressure, + velocity, + conditions, + ) + + +def finite_volume_operator_demonstration() -> None: + """Run M2 operators and compare each result with its analytic solution. + + The linear field checks interpolation and gradients, ``x^2 + y^2`` checks + the Laplacian, and ``u=x, v=y`` checks divergence and conservative upwind + convection of a constant scalar. + """ + mesh = CartesianMesh(nx=16, ny=12, width=2.0, height=1.5) + cell_x, cell_y = mesh.cell_center_coordinates + u_x, u_y = mesh.u_face_coordinates + v_x, v_y = mesh.v_face_coordinates + + linear = ScalarField(mesh, name="linear") + linear.set_values(2.0 * cell_x + 3.0 * cell_y) + linear_boundaries = { + "west": 3.0 * mesh.y_cell_centers, + "east": 2.0 * mesh.width + 3.0 * mesh.y_cell_centers, + "south": 2.0 * mesh.x_cell_centers, + "north": 2.0 * mesh.x_cell_centers + 3.0 * mesh.height, + } + interpolated_x, interpolated_y = interpolate_to_faces(linear, linear_boundaries) + gradient_x, gradient_y = face_gradient(linear, linear_boundaries) + interpolation_error = max( + float(np.max(np.abs(interpolated_x - (2.0 * u_x + 3.0 * u_y)))), + float(np.max(np.abs(interpolated_y - (2.0 * v_x + 3.0 * v_y)))), + ) + gradient_error = max( + float(np.max(np.abs(gradient_x - 2.0))), + float(np.max(np.abs(gradient_y - 3.0))), + ) + + quadratic = ScalarField(mesh, name="quadratic") + quadratic.set_values(cell_x**2 + cell_y**2) + quadratic_boundaries = { + "west": mesh.y_cell_centers**2, + "east": mesh.width**2 + mesh.y_cell_centers**2, + "south": mesh.x_cell_centers**2, + "north": mesh.x_cell_centers**2 + mesh.height**2, + } + laplacian = diffusion_operator(quadratic, boundary_values=quadratic_boundaries) + laplacian_error = float(np.max(np.abs(laplacian - 4.0))) + + expanding_velocity = VectorField(mesh) + expanding_velocity.set_values(u_x, v_y) + velocity_divergence = divergence(expanding_velocity) + constant = ScalarField(mesh, name="constant", initial_value=2.0) + convective_divergence = convection_operator( + constant, + expanding_velocity, + scheme="upwind", + boundary_values={side: 2.0 for side in BOUNDARY_NAMES}, + ) + divergence_error = float(np.max(np.abs(velocity_divergence - 2.0))) + convection_error = float(np.max(np.abs(convective_divergence - 4.0))) + + print("\nM2 manufactured-field operator demonstration") + print(f" interpolation max error for linear field: {interpolation_error:.3e}") + print(f" face-gradient max error for linear field: {gradient_error:.3e}") + print(f" diffusion max error for x^2 + y^2: {laplacian_error:.3e}") + print(f" divergence max error for u=x, v=y: {divergence_error:.3e}") + print(f" upwind convection max error for constant scalar: {convection_error:.3e}") + + +def momentum_prediction_demonstration() -> tuple[MomentumPrediction, ScalarField]: + """Assemble and solve one momentum predictor step for two cavity cases. + + The stationary case should remain exactly at rest. The lid-driven case + creates a nonzero intermediate velocity through tangential wall diffusion. + Neither result has undergone pressure correction, so it is not yet a + divergence-free Navier-Stokes time step. + """ + predictor = MomentumPredictor(density=1.0, viscosity=0.01, time_step=0.001) + + stationary = stationary_cavity() + rest_prediction = predictor.predict( + stationary.velocity, stationary.pressure, stationary.boundary_conditions + ) + + cavity = lid_driven_cavity_re100() + assembly = predictor.assemble(cavity.velocity, cavity.pressure, cavity.boundary_conditions) + lid_prediction = predictor.solve(assembly) + + max_u = float(np.max(np.abs(lid_prediction.velocity.u.values))) + max_v = float(np.max(np.abs(lid_prediction.velocity.v.values))) + print("\nM3 one-step momentum prediction") + print( + " stationary cavity max speed: " + f"{max(np.max(np.abs(rest_prediction.velocity.u.values)), np.max(np.abs(rest_prediction.velocity.v.values))):.3e}" + ) + print(f" lid-driven sparse system sizes: {assembly.u_matrix.shape}, {assembly.v_matrix.shape}") + print(f" predicted max |u|: {max_u:.3e}; max |v|: {max_v:.3e}") + print( + " relative linear residuals: " + f"u={lid_prediction.u_relative_residual:.3e}, " + f"v={lid_prediction.v_relative_residual:.3e}" + ) + return lid_prediction, cavity.pressure + + +def pressure_correction_demonstration( + prediction: MomentumPrediction, +) -> PressureCorrectionResult: + """Solve M4 for a predictor result, leaving velocity unchanged.""" + solver = PressureCorrectionSolver(density=1.0, time_step=0.001) + assembly = solver.assemble(prediction.velocity) + result = solver.solve(assembly) + divergence_before = divergence(prediction.velocity) + + print("\nM4 pressure-correction solve") + print(f" net outward boundary flux: {result.net_boundary_flux:.3e}") + print(f" max predicted divergence: {np.max(np.abs(divergence_before)):.3e}") + print(f" max |pressure correction|: {np.max(np.abs(result.correction.values)):.3e}") + print(f" relative linear residual: {result.relative_residual:.3e}") + print(" predicted velocity is unchanged by the pressure solve") + return result + + +def velocity_correction_demonstration( + prediction: MomentumPrediction, + pressure: ScalarField, + pressure_correction: PressureCorrectionResult, +) -> None: + """Apply M5 and report divergence and global mass before/after correction.""" + corrector = ProjectionCorrector(density=1.0, time_step=0.001) + result = corrector.project(prediction.velocity, pressure, pressure_correction) + + print("\nM5 velocity and pressure correction") + print(f" max divergence before: {result.max_divergence_before:.3e}") + print(f" max divergence after: {result.max_divergence_after:.3e}") + print(f" global mass imbalance: {result.global_mass_imbalance:.3e}") + print(f" max |updated pressure|: {np.max(np.abs(result.pressure.values)):.3e}") + + +def transient_simulation_demonstration() -> SimulationResult: + """Run M6 on a rest case and a short, deliberately bounded cavity case.""" + stationary = stationary_cavity() + stationary_solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.01, + max_steps=5, + ) + rest_result = stationary_solver.run( + stationary.velocity, + stationary.pressure, + stationary.boundary_conditions, + ) + + cavity = lid_driven_cavity_re100() + cavity_solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=3, + cfl_limit=0.5, + velocity_tolerance=1e-14, + ) + cavity_result = cavity_solver.run( + cavity.velocity, + cavity.pressure, + cavity.boundary_conditions, + ) + final_step = cavity_result.history[-1] + + print("\nM6 transient execution") + print( + " stationary cavity: " + f"{rest_result.termination_reason} after {rest_result.steps} step(s), " + f"max divergence={rest_result.history[-1].max_divergence_after:.3e}" + ) + print( + f" lid-driven cavity: {cavity_result.termination_reason} after " + f"{cavity_result.steps} steps, t={cavity_result.final_time:.3e} s" + ) + print( + f" last step dt={final_step.time_step:.3e} s, CFL={final_step.cfl_number:.3f}, " + f"velocity change={final_step.velocity_change:.3e} m/s" + ) + print( + f" max divergence={final_step.max_divergence_after:.3e}, " + f"global mass imbalance={final_step.global_mass_imbalance:.3e}" + ) + return cavity_result + + +def postprocessing_demonstration(simulation: SimulationResult) -> None: + """Export the run and generate field, profile, and convergence visuals.""" + output_directory = Path("results") / "m7_preview" + comparison = compare_ghia_re100(simulation) + extrema = velocity_extrema(simulation.velocity) + + export_simulation_result(simulation, output_directory) + export_ghia_comparison(comparison, output_directory / "ghia_re100.json") + plot_cavity_fields(simulation, output_directory / "fields.png") + plot_ghia_comparison(comparison, output_directory / "ghia_profiles.png") + plot_convergence_history(simulation, output_directory / "convergence.png") + + print("\nM7 post-processing") + print(f" benchmark eligible: {comparison.benchmark_valid}") + print( + f" Ghia Re=100 centerline RMS: u={comparison.u_rms_error:.3e}, " + f"v={comparison.v_rms_error:.3e}" + ) + print( + f" max cell-centered speed: {extrema.maximum_speed:.3e} m/s at " + f"({extrema.maximum_speed_location[0]:.3f}, " + f"{extrema.maximum_speed_location[1]:.3f}) m" + ) + print(f" fields, metadata, history, reports, and plots: {output_directory}") + print(" grid study API: run_lid_driven_grid_study() for 16/32/64/128 cells") + + +def setup_backend_integration_demonstration() -> None: + """Run the canonical JSON case through the setup-facing M8 backend.""" + case_path = Path("cases") / "lid_driven_cavity_re100.json" + output_directory = Path("results") / "m8_backend" + run = PythonFVMBackend().run_file(case_path, output_directory) + + print("\nM8 setup-software backend integration") + print(f" case ID: {run.case_id}; schema: {run.summary['schema_version']}") + print( + f" backend: {run.summary['backend']}; status: {run.summary['status']}; " + f"Re={run.summary['reynolds_number']:.1f}" + ) + print(f" solver artifacts: {run.artifact_directory}") + + +def _describe(example: ExampleSetup) -> None: + """Print the mesh, array shapes, and stored velocity boundary conditions.""" + mesh = example.mesh + print(f"\n{example.name}") + print(f" domain: {mesh.width:g} m x {mesh.height:g} m") + print(f" cells: {mesh.nx} x {mesh.ny}; total area: {mesh.cell_areas.sum():g} m^2") + print(f" pressure shape: {example.pressure.values.shape}") + print(f" u shape: {example.velocity.u.values.shape}") + print(f" v shape: {example.velocity.v.values.shape}") + print(f" velocity boundaries: {dict(example.boundary_conditions.for_field('velocity'))}") + + if example.name == "rectangular staggered-grid demonstration": + cell_x, cell_y = mesh.cell_center_coordinates + u_x, u_y = mesh.u_face_coordinates + v_x, v_y = mesh.v_face_coordinates + print(f" first pressure center: ({cell_x[0, 0]:g}, {cell_y[0, 0]:g}) m") + print(f" first u location: ({u_x[0, 0]:g}, {u_y[0, 0]:g}) m") + print(f" first v location: ({v_x[0, 0]:g}, {v_y[0, 0]:g}) m") + + +def main() -> None: + """Run setup, solver stages, post-processing, and M8 backend integration. + + Future end-to-end solver examples should follow the same readable order: + construct case, inspect fields, execute the supported numerical steps, and + report verification quantities. + """ + examples = ( + stationary_cavity(), + lid_driven_cavity_re100(), + staggered_grid_demonstration(), + ) + for example in examples: + _describe(example) + + # Keep numerical verification after setup output so each example's inputs + # are visible before its computed operator checks. + finite_volume_operator_demonstration() + prediction, pressure = momentum_prediction_demonstration() + pressure_correction = pressure_correction_demonstration(prediction) + velocity_correction_demonstration(prediction, pressure, pressure_correction) + simulation = transient_simulation_demonstration() + postprocessing_demonstration(simulation) + setup_backend_integration_demonstration() + print("\nRun the full grid-refinement study separately when ready for validation.") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Exp_solver_dev_tr/examples/poll_shared_snapshots.py b/Exp_solver_dev_tr/examples/poll_shared_snapshots.py new file mode 100644 index 0000000000000..278ceb75df6ec --- /dev/null +++ b/Exp_solver_dev_tr/examples/poll_shared_snapshots.py @@ -0,0 +1,43 @@ +"""Run the independent shared-folder snapshot consumer. + +Example: + python examples/poll_shared_snapshots.py --shared results/poc/shared \ + --destination results/poc/snapshots +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import threading + +from fvm.externalization import SharedFolderPoller + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Poll a shared snapshot directory and externalize new steps." + ) + parser.add_argument("--shared", type=Path, required=True) + parser.add_argument("--destination", type=Path, required=True) + parser.add_argument("--interval", type=float, default=1.0) + arguments = parser.parse_args() + if arguments.interval <= 0.0: + parser.error("--interval must be positive") + + poller = SharedFolderPoller(arguments.shared, arguments.destination) + stop = threading.Event() + try: + poller.run(arguments.interval, stop) + except KeyboardInterrupt: + stop.set() + poller.poll_once() + print( + f"Externalized {poller.snapshots} snapshots " + f"({poller.bytes_written} bytes)" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Exp_solver_dev_tr/examples/run_externalized_case.py b/Exp_solver_dev_tr/examples/run_externalized_case.py new file mode 100644 index 0000000000000..ecae49b2c0745 --- /dev/null +++ b/Exp_solver_dev_tr/examples/run_externalized_case.py @@ -0,0 +1,347 @@ +"""Run one case with a selected externalization strategy and plot its snapshots. + +Run from the repository root: + python examples/run_externalized_case.py --case path/to/case.json + python examples/run_externalized_case.py --case path/to/case.json --strategy grpc + python examples/run_externalized_case.py --case path/to/case.json --mode live +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import threading +from uuid import uuid4 + +from fvm import BackendRun, PythonFVMBackend, load_case_file +from fvm.externalization import ( + AsyncFileExternalizer, + GrpcExternalizer, + GrpcSnapshotServer, + LiveSnapshotPlotter, + SharedFolderExternalizer, + SharedFolderPoller, + SnapshotStore, + SynchronousFileExternalizer, + create_step_observer, + plot_snapshot, +) + + +ROOT = Path(__file__).resolve().parents[1] +STRATEGIES = ("sync", "shared", "async", "grpc") + + +def build_argument_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Run a case, externalize selected steps, and plot the " + "persisted snapshots." + ) + ) + parser.add_argument( + "--case", + type=Path, + default=ROOT / "cases" / "lid_driven_cavity_re100_steady.json", + help="Case JSON to run (default: steady Re=100 cavity).", + ) + parser.add_argument( + "--strategy", + choices=STRATEGIES, + default="sync", + help="Snapshot delivery strategy (default: sync).", + ) + parser.add_argument( + "--mode", + choices=("save", "live"), + default="save", + help=( + "save: write per-step PNGs after the run (default); live: display " + "snapshots as they appear in the externalized store" + ), + ) + parser.add_argument( + "--output", + type=Path, + default=ROOT / "results" / "externalized_case", + help="Directory for snapshots and plots.", + ) + parser.add_argument( + "--max-steps", + type=int, + help="Optional step cap for a shorter demo; case settings are used otherwise.", + ) + parser.add_argument( + "--snapshot-every", + type=int, + default=10, + help="Externalize every N completed steps and always the final step (default: 10).", + ) + parser.add_argument( + "--queue-size", + type=int, + default=8, + help="Bounded queue size for async and gRPC (default: 8).", + ) + parser.add_argument( + "--poll-interval", + type=float, + default=0.1, + help="Shared-folder poll interval in seconds (default: 0.1).", + ) + return parser + + +def _run( + case_document: dict[str, object], + output_path: Path, + strategy: str, + queue_size: int, + poll_interval: float, + snapshot_every: int, + run_id: str, +) -> tuple[BackendRun, Path, str]: + strategy_output = output_path / strategy / run_id + snapshot_directory = strategy_output / "snapshots" + + poller: SharedFolderPoller | None = None + poller_thread: threading.Thread | None = None + poller_stop: threading.Event | None = None + poller_errors: list[Exception] = [] + grpc_server: GrpcSnapshotServer | None = None + + if strategy == "sync": + externalizer = SynchronousFileExternalizer(snapshot_directory) + elif strategy == "shared": + shared_directory = strategy_output / "shared" + poller = SharedFolderPoller(shared_directory, snapshot_directory) + poller_stop = threading.Event() + + def poll_until_stopped() -> None: + try: + poller.run(poll_interval, poller_stop) + except Exception as error: + poller_errors.append(error) + + externalizer = SharedFolderExternalizer(shared_directory) + poller_thread = threading.Thread( + target=poll_until_stopped, + name="externalized-case-poller", + daemon=True, + ) + poller_thread.start() + elif strategy == "async": + externalizer = AsyncFileExternalizer(snapshot_directory, queue_size=queue_size) + else: + grpc_server = GrpcSnapshotServer(snapshot_directory) + externalizer = GrpcExternalizer( + grpc_server.start(), queue_size=queue_size + ) + + try: + observer = create_step_observer( + externalizer, run_id, snapshot_every=snapshot_every + ) + backend_run = PythonFVMBackend().run( + case_document, + step_observer=observer, + ) + if backend_run.simulation.history: + observer.publish_final_step( + backend_run.simulation.history[-1], + backend_run.simulation.velocity, + backend_run.simulation.pressure, + ) + finally: + try: + externalizer.close() + finally: + try: + if poller_stop is not None and poller_thread is not None: + poller_stop.set() + poller_thread.join() + finally: + if grpc_server is not None: + grpc_server.stop() + + if poller_errors: + raise RuntimeError("shared-folder polling failed") from poller_errors[0] + return backend_run, snapshot_directory, run_id + + +def _run_live( + case_document: dict[str, object], + output_path: Path, + strategy: str, + queue_size: int, + poll_interval: float, + snapshot_every: int, + run_id: str, +) -> tuple[BackendRun, Path, str]: + """Run off the GUI thread and display only committed externalized snapshots.""" + import matplotlib + + if matplotlib.get_backend().lower() in {"agg", "pdf", "svg", "ps", "template"}: + raise RuntimeError( + "live mode needs an interactive Matplotlib backend; use " + "--mode save to write static PNGs without windows" + ) + + snapshot_directory = output_path / strategy / run_id / "snapshots" + store = SnapshotStore(snapshot_directory, run_id=run_id) + worker_result: list[tuple[BackendRun, Path, str]] = [] + worker_errors: list[Exception] = [] + + def run_solver() -> None: + try: + worker_result.append( + _run( + case_document, + output_path, + strategy, + queue_size, + poll_interval, + snapshot_every, + run_id, + ) + ) + except Exception as error: + worker_errors.append(error) + + worker = threading.Thread( + target=run_solver, + name="externalized-case-solver", + daemon=False, + ) + plotter = LiveSnapshotPlotter() + last_step = 0 + worker.start() + try: + while worker.is_alive() or store.latest_step_for(run_id) > last_step: + found_snapshot = False + for snapshot in store.iter_after(last_step, run_id): + found_snapshot = True + plotter.update(snapshot) + last_step = snapshot.step + if not found_snapshot: + plotter.wait_for_events(0.05) + worker.join() + if worker_errors: + raise RuntimeError( + f"solver or externalization failed in live mode: {worker_errors[0]}" + ) from worker_errors[0] + if not worker_result: + raise RuntimeError("live solver worker completed without a result") + plotter.finish() + finally: + if worker.is_alive(): + worker.join() + plotter.close() + + return worker_result[0] + + +def _save_snapshot_plots( + store: SnapshotStore, + simulation_steps: int, + snapshot_every: int, + plots_directory: Path, + final_plot: Path, +) -> int: + import matplotlib.pyplot as plt + + plots_directory.mkdir(parents=True, exist_ok=True) + snapshot_count = 0 + final_snapshot = None + for snapshot in store.iter_after(): + plot_snapshot( + snapshot, + plots_directory / f"step_{snapshot.step:08d}.png", + ) + plt.close() + final_snapshot = snapshot + snapshot_count += 1 + + expected_snapshot_count = simulation_steps // snapshot_every + if simulation_steps % snapshot_every: + expected_snapshot_count += 1 + if snapshot_count != expected_snapshot_count: + raise RuntimeError( + f"externalized {snapshot_count} snapshots for " + f"{simulation_steps} completed steps at interval {snapshot_every}" + ) + if final_snapshot is None: + raise RuntimeError("the solver completed without externalizing any snapshots") + + plot_snapshot(final_snapshot, final_plot) + plt.close() + return snapshot_count + + +def main() -> int: + arguments = build_argument_parser().parse_args() + if arguments.max_steps is not None and arguments.max_steps <= 0: + raise SystemExit("--max-steps must be positive") + if arguments.queue_size <= 0: + raise SystemExit("--queue-size must be positive") + if arguments.poll_interval <= 0.0: + raise SystemExit("--poll-interval must be positive") + if arguments.snapshot_every <= 0: + raise SystemExit("--snapshot-every must be positive") + + case_path = ( + arguments.case + if arguments.case.is_absolute() + else Path.cwd() / arguments.case + ) + output_path = ( + arguments.output + if arguments.output.is_absolute() + else Path.cwd() / arguments.output + ) + case_document = load_case_file(case_path).to_mapping() + if arguments.max_steps is not None: + solver_config = case_document["solver"] + solver_config["max_steps"] = min( + solver_config["max_steps"], arguments.max_steps + ) + + # Pass the validated mapping so an optional demo step cap does not require + # modifying the user's case file on disk. + run_id = f"run-{uuid4().hex}" + runner = _run_live if arguments.mode == "live" else _run + backend_run, snapshot_directory, run_id = runner( + case_document, + output_path, + arguments.strategy, + arguments.queue_size, + arguments.poll_interval, + arguments.snapshot_every, + run_id, + ) + store = SnapshotStore(snapshot_directory, run_id=run_id) + strategy_output = output_path / arguments.strategy / run_id + plots_directory = strategy_output / "step_plots" + final_plot = output_path / arguments.strategy / run_id / "final_result.png" + snapshot_count = _save_snapshot_plots( + store, + backend_run.simulation.steps, + arguments.snapshot_every, + plots_directory, + final_plot, + ) + + print(f"Case: {backend_run.case_id}") + print(f"Strategy: {arguments.strategy}") + print(f"Mode: {arguments.mode}") + print(f"Snapshots plotted: {snapshot_count}") + print(f"Snapshot interval: every {arguments.snapshot_every} steps plus final") + print(f"Snapshot store: {snapshot_directory}") + print(f"Per-step plots: {plots_directory}") + print(f"Final result plot: {final_plot}") + print(f"Converged: {backend_run.simulation.converged}") + return 0 if backend_run.simulation.converged else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/Exp_solver_dev_tr/examples/run_finite_wing_case.py b/Exp_solver_dev_tr/examples/run_finite_wing_case.py new file mode 100644 index 0000000000000..374bb6f25b4ed --- /dev/null +++ b/Exp_solver_dev_tr/examples/run_finite_wing_case.py @@ -0,0 +1,161 @@ +"""Run the steady 3D finite-wing external-flow reference case. + +Quick start (from the project root):: + + python -m pip install -e ".[test]" + python examples/run_finite_wing_case.py + python examples/run_finite_wing_case.py --mode live + +The default case, ``cases/finite_wing_low_re.json``, iterates an incompressible, +laminar steady-flow solution around a finite rectangular wing. Internal +pseudo-time steps are numerical only; the user controls the run with an +iteration count, not a physical end time. The solver writes a mid-span speed/streamline plot, downstream +streamwise-vorticity slices, and a 3D streamline view seeded through the wake. + +Angle of attack is accepted from -5 to 20 degrees. Set exactly one of +``inlet_speed``, ``inlet_velocity_x``, or ``inlet_velocity_y`` in the case; +the other velocity components are calculated from the angle. Positive angle +of attack uses a negative y component in the wing-fixed coordinate system. + +Use ``--case PATH`` to load another case, ``--angle-of-attack DEG`` to override +the case angle, ``--nx N --ny N --nz N`` to change the mesh, and +``--iterations N`` to set the iteration count. Use ``--mode live`` to update +all final-result plots after every iteration; live mode requires an +interactive Matplotlib backend. + +This compact educational solver is intended to show qualitative low-Re +finite-wing flow structure. The wing is voxelized on a uniform grid; the +solution is not a validated aerodynamic benchmark or a high-Re turbulence +calculation. +""" + +from __future__ import annotations + +import argparse +import json +from dataclasses import replace +from pathlib import Path +from typing import Any + +from fvm3d import ( + FiniteWingSettings, + FiniteWingSolver, + LiveFiniteWingPlotter, + plot_finite_wing_result, +) + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CASE = PROJECT_ROOT / "cases" / "finite_wing_low_re.json" +DEFAULT_OUTPUT = PROJECT_ROOT / "results" / "finite_wing_low_re" + + +def _read_case(path: Path) -> tuple[str, str, FiniteWingSettings]: + """Load case metadata and validated solver settings from JSON.""" + with path.open("r", encoding="utf-8") as case_file: + document: Any = json.load(case_file) + if not isinstance(document, dict): + raise ValueError("the case document must be a JSON object") + case_id = document.get("case_id") + description = document.get("description") + settings_data = document.get("settings") + if not isinstance(case_id, str) or not case_id.strip(): + raise ValueError("the case must define a non-empty string case_id") + if not isinstance(description, str): + raise ValueError("the case must define a string description") + if not isinstance(settings_data, dict): + raise ValueError("the case must define settings as a JSON object") + return case_id, description, FiniteWingSettings(**settings_data) + + +def main() -> None: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--case", type=Path, default=DEFAULT_CASE, help="JSON case file") + parser.add_argument( + "--output", + type=Path, + default=DEFAULT_OUTPUT, + help="directory for 3D flow visualizations", + ) + parser.add_argument( + "--angle-of-attack", + type=float, + help="override the angle of attack in degrees (-5 to 20)", + ) + parser.add_argument( + "--iterations", type=int, help="override the steady solver iteration count" + ) + parser.add_argument("--nx", type=int, help="override x cell count") + parser.add_argument("--ny", type=int, help="override y cell count") + parser.add_argument("--nz", type=int, help="override z cell count") + parser.add_argument( + "--mode", + choices=("save", "live"), + default="save", + help="save final plots or update all plots after every iteration", + ) + parser.add_argument( + "--show", + action="store_true", + help="display final plots in save mode (live mode keeps its windows open)", + ) + args = parser.parse_args() + if args.iterations is not None and args.iterations < 1: + parser.error("--iterations must be positive") + if args.mode == "live" and args.show: + parser.error("--show cannot be combined with --mode live") + for name in ("nx", "ny", "nz"): + value = getattr(args, name) + if value is not None and value < 4: + parser.error(f"--{name} must be at least 4") + if args.angle_of_attack is not None and not -5.0 <= args.angle_of_attack <= 20.0: + parser.error("--angle-of-attack must be between -5 and 20 degrees") + + case_id, description, settings = _read_case(args.case) + changes = { + name: value + for name, value in ( + ("angle_of_attack_degrees", args.angle_of_attack), + ("max_iterations", args.iterations), + ("nx", args.nx), + ("ny", args.ny), + ("nz", args.nz), + ) + if value is not None + } + if changes: + settings = replace(settings, **changes) + + if args.mode == "live": + live_plotter = LiveFiniteWingPlotter(settings, args.output) + result = FiniteWingSolver(settings).run(observer=live_plotter) + plots = live_plotter.finish(result) + else: + result = FiniteWingSolver(settings).run() + plots = plot_finite_wing_result(result, args.output, show=args.show) + inlet_x, inlet_y, inlet_z = settings.inlet_velocity + final = result.history[-1] + print(f"Case: {case_id} | {description}") + print(f"Mesh: {settings.nx} x {settings.ny} x {settings.nz} cells") + print( + f"Inlet velocity: ({inlet_x:.6g}, {inlet_y:.6g}, {inlet_z:.6g}) m/s; " + f"Re_chord={settings.reynolds_number:.6g}" + ) + print( + f"Wing chord/span/thickness: {settings.wing_chord:.6g} / " + f"{settings.wing_span:.6g} / {settings.wing_thickness:.6g} m" + ) + print(f"Angle of attack: {settings.angle_of_attack_degrees:.6g} deg") + print(f"Completed {result.iterations} steady solver iterations.") + print( + f"Maximum speed: {final.max_speed:.6g} m/s; " + f"maximum divergence: {final.max_divergence:.6g} 1/s" + ) + print(f"Mid-span flow plot: {plots['midspan']}") + print(f"Tip-vorticity plot: {plots['tip_vorticity']}") + print(f"3D wake streamlines: {plots['streamlines']}") + + +if __name__ == "__main__": + main() diff --git a/Exp_solver_dev_tr/examples/run_finite_wing_transient_case.py b/Exp_solver_dev_tr/examples/run_finite_wing_transient_case.py new file mode 100644 index 0000000000000..c9c1fed0ea532 --- /dev/null +++ b/Exp_solver_dev_tr/examples/run_finite_wing_transient_case.py @@ -0,0 +1,131 @@ +"""Run the transient finite-wing case with a 0-to-5-degree AoA ramp. + +Quick start (from the project root):: + + python -m pip install -e ".[test]" + python examples/run_finite_wing_transient_case.py + python examples/run_finite_wing_transient_case.py --mode live + +The default case, ``cases/finite_wing_angle_ramp_transient.json``, linearly +increases angle of attack from 0 to 5 degrees over 5 physical seconds while +holding the freestream speed fixed. Its schedule has one-degree increments at +one-second intervals. Use ``--mode live`` to update the mid-span, +tip-vorticity, and 3D wake-streamline plots after every physical time step. +""" + +from __future__ import annotations + +import argparse +import json +from math import hypot +from pathlib import Path +from typing import Any + +from fvm3d import ( + FiniteWingSettings, + FiniteWingSolver, + FiniteWingTransientSettings, + LiveFiniteWingPlotter, + plot_finite_wing_result, +) + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CASE = PROJECT_ROOT / "cases" / "finite_wing_angle_ramp_transient.json" +DEFAULT_OUTPUT = PROJECT_ROOT / "results" / "finite_wing_angle_ramp_transient" + + +def _read_case( + path: Path, +) -> tuple[str, str, FiniteWingSettings, FiniteWingTransientSettings]: + """Load case metadata, flow settings, and transient controls from JSON.""" + with path.open("r", encoding="utf-8") as case_file: + document: Any = json.load(case_file) + if not isinstance(document, dict): + raise ValueError("the case document must be a JSON object") + case_id = document.get("case_id") + description = document.get("description") + settings_data = document.get("settings") + transient_data = document.get("transient") + if not isinstance(case_id, str) or not case_id.strip(): + raise ValueError("the case must define a non-empty string case_id") + if not isinstance(description, str): + raise ValueError("the case must define a string description") + if not isinstance(settings_data, dict): + raise ValueError("the case must define settings as a JSON object") + if not isinstance(transient_data, dict): + raise ValueError("the case must define transient controls as a JSON object") + return ( + case_id, + description, + FiniteWingSettings(**settings_data), + FiniteWingTransientSettings(**transient_data), + ) + + +def main() -> None: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--case", type=Path, default=DEFAULT_CASE, help="JSON case file") + parser.add_argument( + "--output", + type=Path, + default=DEFAULT_OUTPUT, + help="directory for 3D flow visualizations", + ) + parser.add_argument( + "--mode", + choices=("save", "live"), + default="save", + help="save final plots or update all plots after every physical time step", + ) + parser.add_argument( + "--show", + action="store_true", + help="display final plots in save mode (live mode keeps its windows open)", + ) + args = parser.parse_args() + if args.mode == "live" and args.show: + parser.error("--show cannot be combined with --mode live") + + case_id, description, settings, transient_settings = _read_case(args.case) + solver = FiniteWingSolver(settings) + if args.mode == "live": + live_plotter = LiveFiniteWingPlotter(settings, args.output) + result = solver.run_transient(transient_settings, observer=live_plotter) + plots = live_plotter.finish(result) + else: + result = solver.run_transient(transient_settings) + plots = plot_finite_wing_result(result, args.output, show=args.show) + + final = result.history[-1] + inlet_x, inlet_y, inlet_z = settings.inlet_velocity + final_time = result.physical_time + final_angle = result.angle_of_attack_degrees + if final_time is None or final_angle is None: + raise RuntimeError("transient solver returned a result without physical time") + print(f"Case: {case_id} | {description}") + print(f"Mesh: {settings.nx} x {settings.ny} x {settings.nz} cells") + print( + f"Freestream speed: {hypot(inlet_x, inlet_y):.6g} m/s; " + f"Re_chord={settings.reynolds_number:.6g}" + ) + print( + f"Initial inlet velocity: ({inlet_x:.6g}, {inlet_y:.6g}, " + f"{inlet_z:.6g}) m/s" + ) + print( + f"Completed {result.iterations} physical time steps at " + f"t={final_time:.6g} s; angle of attack={final_angle:.6g} deg" + ) + print( + f"Maximum speed: {final.max_speed:.6g} m/s; " + f"maximum divergence: {final.max_divergence:.6g} 1/s" + ) + print(f"Mid-span flow plot: {plots['midspan']}") + print(f"Tip-vorticity plot: {plots['tip_vorticity']}") + print(f"3D wake streamlines: {plots['streamlines']}") + + +if __name__ == "__main__": + main() diff --git a/Exp_solver_dev_tr/examples/run_fsi_case.py b/Exp_solver_dev_tr/examples/run_fsi_case.py new file mode 100644 index 0000000000000..1856103298816 --- /dev/null +++ b/Exp_solver_dev_tr/examples/run_fsi_case.py @@ -0,0 +1,147 @@ +"""Run the FSI user case and visualize flow fields and beam motion. + +Quick start (from the project root):: + + python -m pip install -e ".[test]" + python examples/run_fsi_case.py + +The default case is ``cases/turek_hron_fsi1.json``. It describes a 2.5 m by +0.41 m channel, a 0.05 m-radius fixed cylinder, and a 0.35 m cantilever beam. +Its uniform fluid mesh is 120 by 24 cells, so ``dx = 2.5 / 120`` m and +``dy = 0.41 / 24`` m. The mesh counts and solver/material values can be edited +in that JSON file. + +Use ``--case PATH`` to load another case, ``--nx N --ny N`` to override mesh +counts, or ``--steps N`` to set an outer-step limit. Use ``--end-time T`` to +stop at a physical simulation time instead. If both are supplied, the run +stops at whichever limit is reached first. Each physical time step performs +bounded fluid/structure inner iterations and advances only after their +coupling residual meets tolerance. The solver also reports elapsed physical +time from its stability-limited steps. + +The default ``--mode save`` writes final PNGs to ``results/fsi_turek_hron/``. +Use ``--mode live`` to update the same flow/pressure and beam-history plots +after every completed iteration; the live windows remain open until closed and +save to the same PNG filenames. Live mode requires an interactive Matplotlib +backend. ``--show`` opens the final saved plots in save mode; live mode opens +its windows automatically. +For example:: + + python examples/run_fsi_case.py --case cases/turek_hron_fsi1.json --end-time 0.25 --nx 160 --ny 32 --mode live + +This is a compact benchmark-oriented prototype; it is not a validated +reproduction of published Turek-Hron results. +""" + +from __future__ import annotations + +import argparse +import json +from dataclasses import replace +from pathlib import Path +from typing import Any + +from fsi import FSISettings, FSISolver, LiveFSIPlotter, plot_fsi_result + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CASE = PROJECT_ROOT / "cases" / "turek_hron_fsi1.json" +DEFAULT_OUTPUT = PROJECT_ROOT / "results" / "fsi_turek_hron" + + +def _read_case(path: Path) -> tuple[str, str, FSISettings]: + """Load case metadata and validated solver settings from a JSON file.""" + with path.open("r", encoding="utf-8") as case_file: + document: Any = json.load(case_file) + if not isinstance(document, dict): + raise ValueError("the case document must be a JSON object") + case_id = document.get("case_id") + description = document.get("description") + settings_data = document.get("settings") + if not isinstance(case_id, str) or not case_id.strip(): + raise ValueError("the case must define a non-empty string case_id") + if not isinstance(description, str): + raise ValueError("the case must define a string description") + if not isinstance(settings_data, dict): + raise ValueError("the case must define settings as a JSON object") + return case_id, description, FSISettings(**settings_data) + + +def main() -> None: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--case", type=Path, default=DEFAULT_CASE, help="JSON case file") + parser.add_argument( + "--output", + type=Path, + default=DEFAULT_OUTPUT, + help="directory for PNG visualizations", + ) + parser.add_argument("--steps", type=int, help="override the case's max_steps") + parser.add_argument( + "--end-time", + type=float, + help="override the case's physical end_time in seconds", + ) + parser.add_argument("--nx", type=int, help="override the number of x cells") + parser.add_argument("--ny", type=int, help="override the number of y cells") + parser.add_argument( + "--mode", + choices=("save", "live"), + default="save", + help="save final plots or update the visualization every iteration", + ) + parser.add_argument("--show", action="store_true", help="display plots after saving") + args = parser.parse_args() + if args.steps is not None and args.steps < 1: + parser.error("--steps must be positive") + if args.end_time is not None and args.end_time <= 0.0: + parser.error("--end-time must be positive") + if args.nx is not None and args.nx < 4: + parser.error("--nx must be at least 4") + if args.ny is not None and args.ny < 4: + parser.error("--ny must be at least 4") + case_id, description, settings = _read_case(args.case) + changes: dict[str, Any] = { + key: value + for key, value in ( + ("max_steps", args.steps), + ("nx", args.nx), + ("ny", args.ny), + ("end_time", args.end_time), + ) + if value is not None + } + if args.end_time is not None and args.steps is None: + changes["max_steps"] = None + if changes: + settings = replace(settings, **changes) + live_plotter = None + if args.mode == "live": + live_plotter = LiveFSIPlotter(settings, args.output) + result = FSISolver(settings).run(observer=live_plotter) + plot_paths = live_plotter.finish() + else: + result = FSISolver(settings).run() + plot_paths = plot_fsi_result(result, args.output, show=args.show) + final = result.history[-1] + print(f"Case: {case_id} | {description}") + print(f"Mesh: {settings.nx} x {settings.ny} cells") + print( + f"Cell size: dx={settings.width / settings.nx:.6g} m, " + f"dy={settings.height / settings.ny:.6g} m" + ) + print(f"Completed {result.steps} steps at t={result.final_time:.6g} s") + print( + f"Termination: {result.termination_reason}; " + f"all completed time steps converged: {result.converged}" + ) + print(f"Maximum speed: {final.max_speed:.6g} m/s") + print(f"Maximum divergence: {final.max_divergence:.6g} 1/s") + print(f"Beam tip displacement: {final.beam_tip_displacement:.6g} m") + print(f"Field visualization: {plot_paths['fields']}") + print(f"Beam history: {plot_paths['history']}") + + +if __name__ == "__main__": + main() diff --git a/Exp_solver_dev_tr/examples/run_heat_transfer_case.py b/Exp_solver_dev_tr/examples/run_heat_transfer_case.py new file mode 100644 index 0000000000000..513afc3e88cf8 --- /dev/null +++ b/Exp_solver_dev_tr/examples/run_heat_transfer_case.py @@ -0,0 +1,136 @@ +"""Run the steady rectangular-plate heat-transfer case. + +Quick start (from the project root):: + + python -m pip install -e ".[test]" + python examples/run_heat_transfer_case.py + +The default case, ``cases/heated_rectangular_plate.json``, solves steady +two-dimensional conduction in a 1 m by 1 m plate. Its top edge is held at +100 degrees C and its bottom edge at 0 degrees C. The left and right edges +are insulated by default and become convective when ``convection_enabled`` is +set to ``true`` in the case file. The uniform cell-centered mesh is 50 by 50; +edit the JSON file to change the plate, conductivity, mesh, or boundary data. +Set an edge temperature to ``null`` to make it insulated when convection is +disabled or convective when enabled. + +The runner writes ``heat_plate.png`` under ``results/heat_plate/``. It contains +the cell temperature field and conductive heat-flux vectors. Use ``--case`` +to select another JSON case, ``--nx`` / ``--ny`` to override the mesh, and +``--output`` to choose a different output directory. Add ``--show`` to open +the final saved plot, or use ``--mode live`` to watch the temperature field +and heat-flux vectors update during solver iterations. Live mode needs an +interactive Matplotlib backend. + +This is a steady-state, constant-conductivity conduction model with optional +surface convection. It does not model bulk fluid flow, internal heat +generation, or radiation. +""" + +from __future__ import annotations + +import argparse +import json +from dataclasses import replace +from pathlib import Path +from typing import Any + +from heat_transfer import ( + HeatSettings, + HeatSolver, + LiveHeatPlotter, + plot_heat_result, +) + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CASE = PROJECT_ROOT / "cases" / "heated_rectangular_plate.json" +DEFAULT_OUTPUT = PROJECT_ROOT / "results" / "heat_plate" + + +def _read_case(path: Path) -> tuple[str, str, HeatSettings]: + """Load case metadata and validated plate settings from JSON.""" + with path.open("r", encoding="utf-8") as case_file: + document: Any = json.load(case_file) + if not isinstance(document, dict): + raise ValueError("the case document must be a JSON object") + case_id = document.get("case_id") + description = document.get("description") + settings_data = document.get("settings") + if not isinstance(case_id, str) or not case_id.strip(): + raise ValueError("the case must define a non-empty string case_id") + if not isinstance(description, str): + raise ValueError("the case must define a string description") + if not isinstance(settings_data, dict): + raise ValueError("the case must define settings as a JSON object") + return case_id, description, HeatSettings(**settings_data) + + +def main() -> None: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("--case", type=Path, default=DEFAULT_CASE, help="JSON case file") + parser.add_argument( + "--output", + type=Path, + default=DEFAULT_OUTPUT, + help="directory for the temperature plot", + ) + parser.add_argument("--nx", type=int, help="override the number of x cells") + parser.add_argument("--ny", type=int, help="override the number of y cells") + parser.add_argument( + "--mode", + choices=("save", "live"), + default="save", + help="save the final plot or update the plot during every solver iteration", + ) + parser.add_argument("--show", action="store_true", help="display the saved plot") + args = parser.parse_args() + if args.nx is not None and args.nx < 2: + parser.error("--nx must be at least 2") + if args.ny is not None and args.ny < 2: + parser.error("--ny must be at least 2") + + case_id, description, settings = _read_case(args.case) + changes = { + name: value + for name, value in (("nx", args.nx), ("ny", args.ny)) + if value is not None + } + if changes: + settings = replace(settings, **changes) + if args.mode == "live": + live_plotter = LiveHeatPlotter(settings, args.output) + result = HeatSolver(settings).run(observer=live_plotter) + plot_path = live_plotter.finish(result) + else: + result = HeatSolver(settings).run() + plot_path = plot_heat_result(result, args.output, show=args.show) + print(f"Case: {case_id} | {description}") + print(f"Mesh: {settings.nx} x {settings.ny} cells") + print( + f"Cell size: dx={settings.width / settings.nx:.6g} m, " + f"dy={settings.height / settings.ny:.6g} m" + ) + print( + f"Temperature range: {result.temperature_c.min():.6g} to " + f"{result.temperature_c.max():.6g} deg C" + ) + print( + f"Solver iterations: {result.iterations}; converged: {result.converged}; " + f"relative residual: {result.relative_residual:.6g}" + ) + if settings.convection_enabled: + print( + "Surface convection: enabled; " + f"h={settings.convection_heat_transfer_coefficient_w_m2_k:.6g} " + "W/(m^2 K), " + f"ambient={settings.ambient_temperature_c:.6g} deg C" + ) + else: + print("Surface convection: disabled") + print(f"Temperature and heat-flux plot: {plot_path}") + + +if __name__ == "__main__": + main() diff --git a/Exp_solver_dev_tr/examples/run_user_case.py b/Exp_solver_dev_tr/examples/run_user_case.py new file mode 100644 index 0000000000000..3cc4af344f240 --- /dev/null +++ b/Exp_solver_dev_tr/examples/run_user_case.py @@ -0,0 +1,286 @@ +"""Run a versioned FVM case, export results, and create validation plots. + +Run from the repository root: + python examples/run_user_case.py + python examples/run_user_case.py --case path/to/setup-export.json --output results/my_case + python examples/run_user_case.py --mode live +""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import numpy as np + +from fvm import ( + CheckpointManager, + PythonFVMBackend, + compare_ghia_re100, + export_ghia_comparison, + load_case_file, + plot_cavity_fields, + plot_convergence_history, + plot_ghia_comparison, + plot_mesh_and_boundaries, +) + + +ROOT = Path(__file__).resolve().parents[1] + + +def _history_plot_values(history): + """Return the complete step and convergence series for live plotting.""" + return ( + [item.step for item in history], + [item.velocity_change for item in history], + [item.max_divergence_after for item in history], + ) + + +class LiveStepPlotter: + """Update domain fields and convergence metrics after every solver step.""" + + def __init__(self, mesh, velocity, pressure, history=()) -> None: + import matplotlib + + backend_name = matplotlib.get_backend().lower() + if backend_name in {"agg", "pdf", "svg", "ps", "template"}: + raise RuntimeError( + "live mode needs an interactive Matplotlib backend; use " + "--mode save to write static PNGs without windows" + ) + + import matplotlib.pyplot as plt + + self.pyplot = plt + self.mesh = mesh + plt.ion() + self.figure, axes = plt.subplots(1, 3, figsize=(14, 4), layout="constrained") + extent = (0.0, mesh.width, 0.0, mesh.height) + self.speed_image = axes[0].imshow( + np.zeros((mesh.ny, mesh.nx)), + origin="lower", + extent=extent, + interpolation="nearest", + cmap="viridis", + vmin=0.0, + vmax=1.0, + ) + self.figure.colorbar(self.speed_image, ax=axes[0], label="Speed (m/s)") + self.pressure_image = axes[1].imshow( + np.zeros((mesh.ny, mesh.nx)), + origin="lower", + extent=extent, + interpolation="nearest", + cmap="coolwarm", + ) + self.figure.colorbar(self.pressure_image, ax=axes[1], label="Pressure (Pa)") + self.speed_axis, self.pressure_axis, self.history_axis = axes + self.speed_axis.set_title("Velocity magnitude") + self.pressure_axis.set_title("Pressure") + for axis in (self.speed_axis, self.pressure_axis): + axis.set_xlabel("x (m)") + axis.set_ylabel("y (m)") + axis.set_aspect("equal") + + self.velocity_line, = self.history_axis.semilogy([], [], label="velocity change") + self.divergence_line, = self.history_axis.semilogy([], [], label="max divergence") + self.history_axis.set_xlabel("Step") + self.history_axis.set_ylabel("Change / residual") + self.history_axis.set_title("Live convergence") + self.history_axis.legend() + ( + self.steps, + self.velocity_changes, + self.divergences, + ) = _history_plot_values(history) + self.history_floor = np.finfo(np.float64).tiny + self._set_history() + state_label = ( + self._state_label(history[-1]) if history else "initial state" + ) + self._set_fields(velocity, pressure, state_label) + + def __call__(self, diagnostics, velocity, pressure) -> None: + """Refresh the live plots with an immutable per-step field snapshot.""" + self._set_fields(velocity, pressure, self._state_label(diagnostics)) + self.steps.append(diagnostics.step) + self.velocity_changes.append(diagnostics.velocity_change) + self.divergences.append(diagnostics.max_divergence_after) + self._set_history() + self.figure.canvas.draw_idle() + self.pyplot.pause(0.001) + + @staticmethod + def _state_label(diagnostics) -> str: + return ( + f"t={diagnostics.time:.4g} s" + if diagnostics.time is not None + else f"iteration {diagnostics.step}" + ) + + def _set_fields(self, velocity, pressure, state_label: str) -> None: + u = velocity.u.values + v = velocity.v.values + u_cell = 0.5 * (u[:, :-1] + u[:, 1:]) + v_cell = 0.5 * (v[:-1, :] + v[1:, :]) + speed = np.hypot(u_cell, v_cell) + self.speed_image.set_data(speed) + self.speed_image.set_clim(vmin=0.0, vmax=max(float(np.max(speed)), 1e-12)) + self.pressure_image.set_data(pressure.values) + self.speed_axis.set_title(f"Speed, {state_label}") + + def _set_history(self) -> None: + self.velocity_line.set_data( + self.steps, np.maximum(self.velocity_changes, self.history_floor) + ) + self.divergence_line.set_data( + self.steps, np.maximum(self.divergences, self.history_floor) + ) + if self.steps: + self.history_axis.set_xlim(1, max(self.steps[-1], 2)) + self.history_axis.relim() + self.history_axis.autoscale_view(scalex=False) + + def finish(self) -> None: + """Leave the final live view open until the user closes it.""" + self.pyplot.ioff() + self.pyplot.show(block=True) + + +def build_argument_parser() -> argparse.ArgumentParser: + """Define inputs used by solver users and setup-software integrations.""" + parser = argparse.ArgumentParser( + description="Run a schema-v1 case through the independent FVM backend." + ) + parser.add_argument( + "--case", + type=Path, + default=ROOT / "cases" / "lid_driven_cavity_re100_steady.json", + help="JSON problem definition (default: steady Re=100 cavity).", + ) + parser.add_argument( + "--output", + type=Path, + default=ROOT / "results" / "user_guide_lid_driven_cavity", + help="Directory for fields, reports, history, and plots.", + ) + parser.add_argument( + "--mode", + choices=("save", "live"), + default="save", + help=( + "save: write PNGs only (default); live: show geometry, update plots " + "each step, and also save all outputs" + ), + ) + parser.add_argument( + "--checkpoint-every", + type=int, + help="Save restart checkpoints every N completed steps; also save the final safe state.", + ) + parser.add_argument( + "--retain-checkpoints", + type=int, + default=5, + help="Number of recent checkpoint files to retain (default: 5).", + ) + parser.add_argument( + "--restart", + help="Resume from latest or a checkpoint filename in OUTPUT/checkpoints.", + ) + parser.add_argument( + "--live", + dest="mode", + action="store_const", + const="live", + default=argparse.SUPPRESS, + help=argparse.SUPPRESS, + ) + return parser + + +def main() -> int: + """Execute a case and return a nonzero exit code if it did not converge.""" + arguments = build_argument_parser().parse_args() + case_path = arguments.case if arguments.case.is_absolute() else Path.cwd() / arguments.case + output_path = ( + arguments.output + if arguments.output.is_absolute() + else Path.cwd() / arguments.output + ) + + backend = PythonFVMBackend() + case_definition = load_case_file(case_path) + prepared_case = backend.prepare(case_definition) + restart_state = ( + CheckpointManager(output_path / "checkpoints", arguments.retain_checkpoints).load( + arguments.restart, + case_definition.to_mapping(), + prepared_case.mesh, + ) + if arguments.restart is not None + else None + ) + plot_mesh_and_boundaries( + prepared_case.mesh, + prepared_case.boundary_conditions, + output_path / "geometry.png", + ) + if arguments.mode == "live": + import matplotlib.pyplot as plt + + # Show the setup first; the live field/convergence window follows. + plt.show(block=False) + plt.pause(0.1) + live_plotter = ( + LiveStepPlotter( + prepared_case.mesh, + restart_state.velocity if restart_state else prepared_case.initial_velocity, + restart_state.pressure if restart_state else prepared_case.initial_pressure, + restart_state.history if restart_state else (), + ) + if arguments.mode == "live" + else None + ) + backend_run = backend.run( + case_definition, + output_directory=output_path, + step_observer=live_plotter, + checkpoint_every=arguments.checkpoint_every, + restart=arguments.restart, + retain_checkpoints=arguments.retain_checkpoints, + ) + simulation = backend_run.simulation + comparison = compare_ghia_re100(simulation) + + # Backend exports fields, run settings, and history. Add validation-specific + # output and the corresponding visual summaries beside those artifacts. + export_ghia_comparison(comparison, output_path / "ghia_re100.json") + plot_cavity_fields(simulation, output_path / "cavity_fields.png") + plot_ghia_comparison(comparison, output_path / "ghia_profiles.png") + plot_convergence_history(simulation, output_path / "convergence_history.png") + + print(f"Case: {backend_run.case_id}") + print(f"Status: {backend_run.summary['status']}") + if simulation.settings.transient: + print( + f"Time steps: {simulation.steps}; physical time: " + f"{simulation.final_time:.6g} s" + ) + else: + print(f"Iterations: {simulation.steps}; pseudo-time is not physical time") + print(f"Reynolds number: {backend_run.summary['reynolds_number']:.6g}") + print(f"Ghia profile RMS: u={comparison.u_rms_error:.6g}, v={comparison.v_rms_error:.6g}") + print(f"Benchmark eligible: {comparison.benchmark_valid}") + print(f"Results: {output_path}") + if arguments.checkpoint_every is not None: + print(f"Checkpoints: {output_path / 'checkpoints'}") + if live_plotter is not None: + live_plotter.finish() + return 0 if simulation.converged else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fsi/__init__.py b/Exp_solver_dev_tr/src/fsi/__init__.py new file mode 100644 index 0000000000000..34b58437e07c8 --- /dev/null +++ b/Exp_solver_dev_tr/src/fsi/__init__.py @@ -0,0 +1,13 @@ +"""Compact two-dimensional fluid-structure interaction reference solver.""" + +from .solver import FSIResult, FSISettings, FSIStep, FSISolver +from .visualization import LiveFSIPlotter, plot_fsi_result + +__all__ = [ + "FSIResult", + "FSISettings", + "FSIStep", + "FSISolver", + "LiveFSIPlotter", + "plot_fsi_result", +] diff --git a/Exp_solver_dev_tr/src/fsi/solver.py b/Exp_solver_dev_tr/src/fsi/solver.py new file mode 100644 index 0000000000000..029131f25c6e6 --- /dev/null +++ b/Exp_solver_dev_tr/src/fsi/solver.py @@ -0,0 +1,714 @@ +"""Partitioned channel-flow and cantilever-beam FSI reference solver. + +The fluid uses a staggered Cartesian projection method with direct forcing for +the fixed cylinder and regularized drag coupling for the flexible beam. The +beam is a linear Euler-Bernoulli finite-element model integrated with Newmark +average acceleration. This intentionally compact implementation is for +learning and workflow development; it is not a validated Turek-Hron solver. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Integral, Real +from collections.abc import Callable + +import numpy as np +from numpy.typing import NDArray +from scipy.sparse import coo_matrix, csr_matrix +from scipy.sparse.linalg import spsolve + +FloatArray = NDArray[np.float64] +FSIStepObserver = Callable[ + ["FSIStep", FloatArray, FloatArray, FloatArray, FloatArray, FloatArray], None +] + + +@dataclass(frozen=True, slots=True) +class FSISettings: + """Geometry, material, and time controls for the Turek-Hron-style case. + + All values use SI units. The beam is attached to the downstream side of a + fixed circular cylinder, with its undeformed centerline parallel to the + channel and its free tip pointing downstream. + """ + + width: float = 2.5 + height: float = 0.41 + nx: int = 160 + ny: int = 32 + fluid_density: float = 1000.0 + dynamic_viscosity: float = 1.0 + inlet_mean_speed: float = 1.0 + cylinder_center_x: float = 0.2 + cylinder_center_y: float = 0.2 + cylinder_radius: float = 0.05 + beam_root_x: float = 0.25 + beam_root_y: float = 0.2 + beam_length: float = 0.35 + beam_thickness: float = 0.02 + beam_density: float = 10000.0 + youngs_modulus: float = 1.4e6 + beam_elements: int = 12 + time_step: float = 0.001 + max_steps: int | None = 2000 + end_time: float | None = None + minimum_time_step: float = 1e-12 + cfl_limit: float = 0.4 + coupling_tolerance: float = 1e-6 + max_inner_iterations_per_time_step: int = 200 + + def __post_init__(self) -> None: + for name in ( + "width", + "height", + "fluid_density", + "dynamic_viscosity", + "beam_length", + "beam_thickness", + "beam_density", + "youngs_modulus", + "time_step", + "minimum_time_step", + "cylinder_radius", + "coupling_tolerance", + ): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + for name in ( + "inlet_mean_speed", + "cylinder_center_x", + "cylinder_center_y", + "beam_root_x", + "beam_root_y", + ): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite number") + if not isfinite(value): + raise ValueError(f"{name} must be a finite number") + for name in ("nx", "ny", "beam_elements"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Integral): + raise TypeError(f"{name} must be an integer") + minimum = 4 if name in ("nx", "ny") else 2 + if value < minimum: + raise ValueError(f"{name} must be at least {minimum}") + if self.max_steps is not None: + if isinstance(self.max_steps, bool) or not isinstance(self.max_steps, Integral): + raise TypeError("max_steps must be a positive integer or None") + if self.max_steps < 1: + raise ValueError("max_steps must be a positive integer or None") + if self.end_time is not None and ( + isinstance(self.end_time, bool) + or not isinstance(self.end_time, Real) + or not isfinite(self.end_time) + or self.end_time <= 0.0 + ): + raise ValueError("end_time must be a finite positive number or None") + if self.max_steps is None and self.end_time is None: + raise ValueError("at least one of max_steps or end_time must be set") + if ( + isinstance(self.max_inner_iterations_per_time_step, bool) + or not isinstance(self.max_inner_iterations_per_time_step, Integral) + or self.max_inner_iterations_per_time_step < 1 + ): + raise ValueError("max_inner_iterations_per_time_step must be a positive integer") + if ( + isinstance(self.cfl_limit, bool) + or not isinstance(self.cfl_limit, Real) + or not isfinite(self.cfl_limit) + or not 0.0 < self.cfl_limit <= 1.0 + ): + raise ValueError("cfl_limit must be in (0, 1]") + if self.minimum_time_step > self.time_step: + raise ValueError("minimum_time_step must not exceed time_step") + if self.inlet_mean_speed <= 0.0: + raise ValueError("inlet_mean_speed must be positive") + if not 0.0 < self.cylinder_center_y - self.cylinder_radius: + raise ValueError("the cylinder must lie above the channel floor") + if self.cylinder_center_y + self.cylinder_radius >= self.height: + raise ValueError("the cylinder must lie below the channel ceiling") + if self.beam_root_x < 0.0 or self.beam_root_x + self.beam_length >= self.width: + raise ValueError("the beam must lie inside the channel") + if not 0.0 < self.beam_root_y < self.height: + raise ValueError("beam_root_y must lie inside the channel") + + +@dataclass(frozen=True, slots=True) +class FSIStep: + """Diagnostics recorded after one completed coupled time step.""" + + step: int + time: float + time_step: float + max_speed: float + max_divergence: float + beam_tip_displacement: float + beam_tip_velocity: float + inner_iterations: int + coupling_residual: float + converged: bool + + +@dataclass(frozen=True, slots=True) +class FSIResult: + """Final fields and diagnostics; converged means every completed step converged.""" + + u: FloatArray + v: FloatArray + pressure: FloatArray + beam_x: FloatArray + beam_y: FloatArray + beam_velocity: FloatArray + history: tuple[FSIStep, ...] + settings: FSISettings + converged: bool + termination_reason: str + + @property + def steps(self) -> int: + return len(self.history) + + @property + def final_time(self) -> float: + return self.history[-1].time if self.history else 0.0 + + +def _assemble_pressure_matrix(nx: int, ny: int, dx: float, dy: float) -> csr_matrix: + """Build -laplacian with Neumann sides/walls and zero correction at outlet.""" + rows: list[int] = [] + columns: list[int] = [] + values: list[float] = [] + for row in range(ny): + for column in range(nx): + index = row * nx + column + diagonal = 0.0 + for next_row, next_column, coefficient, is_outlet in ( + (row, column - 1, 1.0 / dx**2, False), + (row, column + 1, 1.0 / dx**2, column == nx - 1), + (row - 1, column, 1.0 / dy**2, False), + (row + 1, column, 1.0 / dy**2, False), + ): + if 0 <= next_row < ny and 0 <= next_column < nx: + neighbor = next_row * nx + next_column + rows.append(index) + columns.append(neighbor) + values.append(-coefficient) + diagonal += coefficient + elif is_outlet: + # The correction is prescribed at the east face, half a + # cell away from the last pressure center. + diagonal += 2.0 * coefficient + rows.append(index) + columns.append(index) + values.append(diagonal) + return coo_matrix((values, (rows, columns)), shape=(nx * ny, nx * ny)).tocsr() + + +def _beam_matrices( + elements: int, length: float, thickness: float, density: float, youngs_modulus: float +) -> tuple[FloatArray, FloatArray, FloatArray]: + """Assemble planar Euler-Bernoulli stiffness/mass and node positions.""" + node_count = elements + 1 + dof_count = 2 * node_count + element_length = length / elements + area = thickness + second_moment = thickness**3 / 12.0 + stiffness = np.zeros((dof_count, dof_count), dtype=np.float64) + mass = np.zeros_like(stiffness) + local_stiffness = youngs_modulus * second_moment / element_length**3 * np.array( + [ + [12.0, 6.0 * element_length, -12.0, 6.0 * element_length], + [6.0 * element_length, 4.0 * element_length**2, -6.0 * element_length, 2.0 * element_length**2], + [-12.0, -6.0 * element_length, 12.0, -6.0 * element_length], + [6.0 * element_length, 2.0 * element_length**2, -6.0 * element_length, 4.0 * element_length**2], + ], + dtype=np.float64, + ) + local_mass = density * area * element_length / 420.0 * np.array( + [ + [156.0, 22.0 * element_length, 54.0, -13.0 * element_length], + [22.0 * element_length, 4.0 * element_length**2, 13.0 * element_length, -3.0 * element_length**2], + [54.0, 13.0 * element_length, 156.0, -22.0 * element_length], + [-13.0 * element_length, -3.0 * element_length**2, -22.0 * element_length, 4.0 * element_length**2], + ], + dtype=np.float64, + ) + for element in range(elements): + dofs = np.arange(2 * element, 2 * element + 4) + stiffness[np.ix_(dofs, dofs)] += local_stiffness + mass[np.ix_(dofs, dofs)] += local_mass + return stiffness, mass, np.linspace(0.0, length, node_count, dtype=np.float64) + + +class FSISolver: + """Advance channel flow coupled to a cantilever behind a fixed cylinder. + + The fluid and structure are advanced with a loose partitioned update. + Transverse quadratic drag is integrated over the beam and distributed back + to the fluid with a normalized regularized kernel. The step size resolves + fluid advection and viscous diffusion. + """ + + def __init__(self, settings: FSISettings = FSISettings()) -> None: + if not isinstance(settings, FSISettings): + raise TypeError("settings must be an FSISettings instance") + self.settings = settings + self.dx = settings.width / settings.nx + self.dy = settings.height / settings.ny + self.x_cells = (np.arange(settings.nx) + 0.5) * self.dx + self.y_cells = (np.arange(settings.ny) + 0.5) * self.dy + self.x_faces = np.arange(settings.nx + 1) * self.dx + self.y_faces = np.arange(settings.ny + 1) * self.dy + self._pressure_matrix = _assemble_pressure_matrix( + settings.nx, settings.ny, self.dx, self.dy + ) + self._stiffness, self._mass, self._beam_s = _beam_matrices( + settings.beam_elements, + settings.beam_length, + settings.beam_thickness, + settings.beam_density, + settings.youngs_modulus, + ) + self._free_dofs = np.arange(2, self._stiffness.shape[0]) + + def _inlet_profile(self) -> FloatArray: + y = self.y_cells + return 6.0 * self.settings.inlet_mean_speed * y * (self.settings.height - y) / self.settings.height**2 + + def _initial_fields(self) -> tuple[FloatArray, FloatArray, FloatArray]: + settings = self.settings + u = np.zeros((settings.ny, settings.nx + 1), dtype=np.float64) + v = np.zeros((settings.ny + 1, settings.nx), dtype=np.float64) + pressure = np.zeros((settings.ny, settings.nx), dtype=np.float64) + u[:, 0] = self._inlet_profile() + return u, v, pressure + + def _beam_fluid_forces( + self, + v: FloatArray, + displacement: FloatArray, + beam_velocity: FloatArray, + ) -> tuple[FloatArray, FloatArray]: + """Spread transverse drag to the fluid and return equal beam loads.""" + settings = self.settings + cell_v = 0.5 * (v[:-1, :] + v[1:, :]) + force_density = np.zeros_like(cell_v) + nodal_load = np.zeros(len(self._beam_s), dtype=np.float64) + sigma = max(0.5 * settings.beam_thickness, 0.75 * min(self.dx, self.dy)) + area = self.dx * self.dy + ds = settings.beam_length / settings.beam_elements + node_y = settings.beam_root_y + displacement[0::2] + + for node, x in enumerate(settings.beam_root_x + self._beam_s): + y = node_y[node] + nodal_ds = ds * (0.5 if node in (0, len(self._beam_s) - 1) else 1.0) + weight = np.exp( + -0.5 + * ( + ((self.x_cells[None, :] - x) / sigma) ** 2 + + ((self.y_cells[:, None] - y) / sigma) ** 2 + ) + ) + weight_sum = float(np.sum(weight)) + if weight_sum <= np.finfo(np.float64).tiny: + raise RuntimeError("beam immersed-boundary kernel has zero support") + weight /= weight_sum + fluid_velocity = float(np.sum(weight * cell_v)) + relative_velocity = fluid_velocity - beam_velocity[node] + nodal_force = ( + 0.5 + * settings.fluid_density + * settings.beam_thickness + * abs(relative_velocity) + * relative_velocity + * nodal_ds + ) + nodal_load[node] = nodal_force + force_density -= nodal_force * weight / area + return force_density, nodal_load + + def _advance_beam( + self, + displacement: FloatArray, + velocity: FloatArray, + acceleration: FloatArray, + nodal_load: FloatArray, + dt: float, + ) -> tuple[FloatArray, FloatArray, FloatArray]: + """Take one Newmark-beta step with a clamped root and free tip.""" + gamma = 0.5 + beta = 0.25 + dofs = self._free_dofs + mass = self._mass[np.ix_(dofs, dofs)] + stiffness = self._stiffness[np.ix_(dofs, dofs)] + damping = 1e-4 * mass + 1e-5 * stiffness + effective = mass + gamma * dt * damping + beta * dt**2 * stiffness + predictor_displacement = ( + displacement[dofs] + + dt * velocity[dofs] + + dt**2 * (0.5 - beta) * acceleration[dofs] + ) + predictor_velocity = velocity[dofs] + dt * (1.0 - gamma) * acceleration[dofs] + force = np.zeros_like(displacement) + force[0::2] = nodal_load + rhs = ( + force[dofs] + - damping @ predictor_velocity + - stiffness @ predictor_displacement + ) + next_acceleration = np.zeros_like(acceleration) + next_acceleration[dofs] = np.linalg.solve(effective, rhs) + next_displacement = predictor_displacement + beta * dt**2 * next_acceleration[dofs] + next_velocity = predictor_velocity + gamma * dt * next_acceleration[dofs] + new_displacement = np.zeros_like(displacement) + new_velocity = np.zeros_like(velocity) + new_acceleration = np.zeros_like(acceleration) + new_displacement[dofs] = next_displacement + new_velocity[dofs] = next_velocity + new_acceleration[dofs] = next_acceleration[dofs] + return new_displacement, new_velocity, new_acceleration + + def _predict_velocity( + self, + u: FloatArray, + v: FloatArray, + pressure: FloatArray, + dt: float, + force_density: FloatArray, + *, + temporal_u: FloatArray, + temporal_v: FloatArray, + ) -> tuple[FloatArray, FloatArray]: + """Predict from fixed time-level storage and current nonlinear iterates.""" + settings = self.settings + density = settings.fluid_density + nu = settings.dynamic_viscosity / density + predicted_u = u.copy() + predicted_v = v.copy() + uc = u[:, 1:-1] + vc = v[1:-1, :] + temporal_uc = temporal_u[:, 1:-1] + temporal_vc = temporal_v[1:-1, :] + + u_x = np.where( + uc >= 0.0, + (uc - u[:, :-2]) / self.dx, + (u[:, 2:] - uc) / self.dx, + ) + v_at_u = 0.25 * ( + v[:-1, :-1] + v[:-1, 1:] + v[1:, :-1] + v[1:, 1:] + ) + u_extended_y = np.pad(uc, ((1, 1), (0, 0)), mode="edge") + u_extended_y[0, :] = -uc[0, :] + u_extended_y[-1, :] = -uc[-1, :] + u_y_positive = (u_extended_y[1:-1, :] - u_extended_y[:-2, :]) / self.dy + u_y_negative = (u_extended_y[2:, :] - u_extended_y[1:-1, :]) / self.dy + u_y = np.where(v_at_u >= 0.0, u_y_positive, u_y_negative) + u_lap_y = np.empty_like(uc) + u_lap_y[1:-1, :] = (uc[2:, :] - 2.0 * uc[1:-1, :] + uc[:-2, :]) / self.dy**2 + u_lap_y[0, :] = (uc[1, :] - 3.0 * uc[0, :]) / self.dy**2 + u_lap_y[-1, :] = (uc[-2, :] - 3.0 * uc[-1, :]) / self.dy**2 + u_lap_x = (u[:, 2:] - 2.0 * uc + u[:, :-2]) / self.dx**2 + u_pressure = (pressure[:, 1:] - pressure[:, :-1]) / self.dx + u_force = 0.5 * (force_density[:, :-1] + force_density[:, 1:]) + u_conv = uc * u_x + v_at_u * u_y + predicted_u[:, 1:-1] = temporal_uc + dt * ( + -u_conv + nu * (u_lap_x + u_lap_y) - u_pressure / density + u_force / density + ) + + v_y = np.where( + vc >= 0.0, + (vc - v[:-2, :]) / self.dy, + (v[2:, :] - vc) / self.dy, + ) + v_extended_x = np.pad(vc, ((0, 0), (1, 1)), mode="edge") + v_extended_x[:, 0] = -vc[:, 0] + v_extended_x[:, -1] = -vc[:, -1] + v_x_positive = (v_extended_x[:, 1:-1] - v_extended_x[:, :-2]) / self.dx + v_x_negative = (v_extended_x[:, 2:] - v_extended_x[:, 1:-1]) / self.dx + u_at_v = 0.25 * ( + u[:-1, :-1] + u[:-1, 1:] + u[1:, :-1] + u[1:, 1:] + ) + v_x = np.where(u_at_v >= 0.0, v_x_positive, v_x_negative) + v_lap_y = (v[2:, :] - 2.0 * vc + v[:-2, :]) / self.dy**2 + v_lap_x = np.empty_like(vc) + v_lap_x[:, 1:-1] = (vc[:, 2:] - 2.0 * vc[:, 1:-1] + vc[:, :-2]) / self.dx**2 + v_lap_x[:, 0] = (vc[:, 1] - 3.0 * vc[:, 0]) / self.dx**2 + v_lap_x[:, -1] = (vc[:, -2] - 3.0 * vc[:, -1]) / self.dx**2 + v_pressure = (pressure[1:, :] - pressure[:-1, :]) / self.dy + v_force = 0.5 * (force_density[:-1, :] + force_density[1:, :]) + v_conv = u_at_v * v_x + vc * v_y + predicted_v[1:-1, :] = temporal_vc + dt * ( + -v_conv + nu * (v_lap_x + v_lap_y) - v_pressure / density + v_force / density + ) + + predicted_u[:, 0] = self._inlet_profile() + predicted_u[:, -1] = predicted_u[:, -2] + predicted_v[0, :] = 0.0 + predicted_v[-1, :] = 0.0 + + # Direct forcing for the fixed cylinder on staggered velocity faces. + radius_squared = settings.cylinder_radius**2 + cylinder_u = ( + (self.x_faces[None, :] - settings.cylinder_center_x) ** 2 + + (self.y_cells[:, None] - settings.cylinder_center_y) ** 2 + ) <= radius_squared + cylinder_v = ( + (self.x_cells[None, :] - settings.cylinder_center_x) ** 2 + + (self.y_faces[:, None] - settings.cylinder_center_y) ** 2 + ) <= radius_squared + predicted_u[cylinder_u] = 0.0 + predicted_v[cylinder_v] = 0.0 + predicted_u[:, 0] = self._inlet_profile() + return predicted_u, predicted_v + + def _project( + self, u_star: FloatArray, v_star: FloatArray, pressure: FloatArray, dt: float + ) -> tuple[FloatArray, FloatArray, FloatArray]: + """Correct face velocities and pressure using a Dirichlet outlet.""" + settings = self.settings + divergence = ( + (u_star[:, 1:] - u_star[:, :-1]) / self.dx + + (v_star[1:, :] - v_star[:-1, :]) / self.dy + ) + rhs = (-settings.fluid_density / dt * divergence).ravel() + correction_values = np.asarray(spsolve(self._pressure_matrix, rhs)) + if not np.all(np.isfinite(correction_values)): + raise RuntimeError("pressure-correction solve produced non-finite values") + correction = correction_values.reshape((settings.ny, settings.nx)) + u = u_star.copy() + v = v_star.copy() + u[:, 1:-1] -= ( + dt + / settings.fluid_density + * (correction[:, 1:] - correction[:, :-1]) + / self.dx + ) + u[:, -1] -= ( + dt + / settings.fluid_density + * (0.0 - correction[:, -1]) + / (0.5 * self.dx) + ) + v[1:-1, :] -= ( + dt + / settings.fluid_density + * (correction[1:, :] - correction[:-1, :]) + / self.dy + ) + u[:, 0] = self._inlet_profile() + v[0, :] = 0.0 + v[-1, :] = 0.0 + pressure = pressure + correction + pressure -= np.mean(pressure) + return u, v, pressure + + @staticmethod + def _relative_change(new_values: FloatArray, old_values: FloatArray) -> float: + """Return a normalized infinity-norm change for one coupling variable.""" + scale = max(1.0, float(np.max(np.abs(new_values)))) + return float(np.max(np.abs(new_values - old_values)) / scale) + + def run(self, observer: FSIStepObserver | None = None) -> FSIResult: + """Run transient physical steps with bounded inner coupling iterations. + + ``max_steps`` and ``end_time`` are independent stopping limits. Each + physical step holds the previous-time fluid and beam states fixed while + iterating the coupled fluid/structure update to ``coupling_tolerance``. + """ + if observer is not None and not callable(observer): + raise TypeError("observer must be callable") + settings = self.settings + u, v, pressure = self._initial_fields() + dof_count = self._stiffness.shape[0] + displacement = np.zeros(dof_count, dtype=np.float64) + beam_velocity_dofs = np.zeros_like(displacement) + acceleration = np.zeros_like(displacement) + history: list[FSIStep] = [] + nu = settings.dynamic_viscosity / settings.fluid_density + diffusion_limit = 0.2 / (nu * (1.0 / self.dx**2 + 1.0 / self.dy**2)) + time = 0.0 + step = 0 + converged = True + termination_reason = "maximum_steps_reached" + while settings.max_steps is None or step < settings.max_steps: + time_tolerance = ( + 1e-14 * max(1.0, settings.end_time) + if settings.end_time is not None + else 0.0 + ) + if settings.end_time is not None and time >= settings.end_time - time_tolerance: + time = settings.end_time + converged = True + termination_reason = "final_time_reached" + break + + max_u = max(float(np.max(np.abs(u))), float(np.max(self._inlet_profile()))) + max_v = max( + float(np.max(np.abs(v))), + float(np.max(np.abs(beam_velocity_dofs[0::2]))), + ) + advective_rate = max_u / self.dx + max_v / self.dy + advective_limit = ( + settings.cfl_limit / advective_rate + if advective_rate > 0.0 + else settings.time_step + ) + dt = min(settings.time_step, diffusion_limit, advective_limit) + if settings.end_time is not None: + dt = min(dt, settings.end_time - time) + if dt < settings.minimum_time_step: + raise RuntimeError( + f"stable time step {dt:.6g} is below minimum_time_step " + f"{settings.minimum_time_step:.6g}" + ) + + old_u = u.copy() + old_v = v.copy() + old_pressure = pressure.copy() + old_displacement = displacement.copy() + old_beam_velocity = beam_velocity_dofs.copy() + old_acceleration = acceleration.copy() + iterate_u = old_u.copy() + iterate_v = old_v.copy() + iterate_pressure = old_pressure.copy() + iterate_displacement = old_displacement.copy() + iterate_beam_velocity = old_beam_velocity.copy() + step_converged = False + coupling_residual = float("inf") + + for inner_iteration in range( + 1, settings.max_inner_iterations_per_time_step + 1 + ): + cell_force, beam_load = self._beam_fluid_forces( + iterate_v, + iterate_displacement, + iterate_beam_velocity[0::2], + ) + candidate_displacement, candidate_beam_velocity, candidate_acceleration = ( + self._advance_beam( + old_displacement, + old_beam_velocity, + old_acceleration, + beam_load, + dt, + ) + ) + cell_force, _ = self._beam_fluid_forces( + iterate_v, + candidate_displacement, + candidate_beam_velocity[0::2], + ) + u_star, v_star = self._predict_velocity( + iterate_u, + iterate_v, + iterate_pressure, + dt, + cell_force, + temporal_u=old_u, + temporal_v=old_v, + ) + candidate_u, candidate_v, candidate_pressure = self._project( + u_star, v_star, iterate_pressure, dt + ) + coupling_residual = max( + self._relative_change(candidate_u, iterate_u), + self._relative_change(candidate_v, iterate_v), + self._relative_change(candidate_pressure, iterate_pressure), + self._relative_change(candidate_displacement, iterate_displacement), + self._relative_change(candidate_beam_velocity, iterate_beam_velocity), + ) + if coupling_residual <= settings.coupling_tolerance: + step_converged = True + u = candidate_u + v = candidate_v + pressure = candidate_pressure + displacement = candidate_displacement + beam_velocity_dofs = candidate_beam_velocity + acceleration = candidate_acceleration + break + + iterate_u = candidate_u + iterate_v = candidate_v + iterate_pressure = candidate_pressure + iterate_displacement = candidate_displacement + iterate_beam_velocity = candidate_beam_velocity + displacement = candidate_displacement + beam_velocity_dofs = candidate_beam_velocity + acceleration = candidate_acceleration + else: + u = candidate_u + v = candidate_v + pressure = candidate_pressure + + step += 1 + step_time = time + dt + if ( + settings.end_time is not None + and settings.end_time - step_time <= time_tolerance + ): + step_time = settings.end_time + dt = step_time - time + time = step_time + divergence = ( + (u[:, 1:] - u[:, :-1]) / self.dx + + (v[1:, :] - v[:-1, :]) / self.dy + ) + speed = np.sqrt( + (0.5 * (u[:, :-1] + u[:, 1:])) ** 2 + + (0.5 * (v[:-1, :] + v[1:, :])) ** 2 + ) + tip_displacement = float(displacement[-2]) + tip_velocity = float(beam_velocity_dofs[-2]) + diagnostic = FSIStep( + step=step, + time=time, + time_step=dt, + max_speed=float(np.max(speed)), + max_divergence=float(np.max(np.abs(divergence))), + beam_tip_displacement=tip_displacement, + beam_tip_velocity=tip_velocity, + inner_iterations=inner_iteration, + coupling_residual=coupling_residual, + converged=step_converged, + ) + history.append(diagnostic) + if observer is not None: + observer( + diagnostic, + u.copy(), + v.copy(), + pressure.copy(), + settings.beam_root_x + self._beam_s.copy(), + settings.beam_root_y + displacement[0::2].copy(), + ) + if not step_converged: + converged = False + termination_reason = "time_step_not_converged" + break + if settings.end_time is not None and time >= settings.end_time - time_tolerance: + time = settings.end_time + converged = True + termination_reason = "final_time_reached" + break + + beam_x = settings.beam_root_x + self._beam_s + beam_y = settings.beam_root_y + displacement[0::2] + return FSIResult( + u=u.copy(), + v=v.copy(), + pressure=pressure.copy(), + beam_x=beam_x, + beam_y=beam_y, + beam_velocity=beam_velocity_dofs[0::2].copy(), + history=tuple(history), + settings=settings, + converged=converged, + termination_reason=termination_reason, + ) diff --git a/Exp_solver_dev_tr/src/fsi/visualization.py b/Exp_solver_dev_tr/src/fsi/visualization.py new file mode 100644 index 0000000000000..3da03c3e85dd6 --- /dev/null +++ b/Exp_solver_dev_tr/src/fsi/visualization.py @@ -0,0 +1,246 @@ +"""Static and live plots for fluid fields and beam motion from an FSI run.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +from .solver import FSIResult, FSISettings, FSIStep, FloatArray + + +def _draw_fields( + settings: FSISettings, + u: FloatArray, + v: FloatArray, + pressure: FloatArray, + beam_x: FloatArray, + beam_y: FloatArray, + figure=None, +): + """Draw the shared speed/streamline and pressure/geometry figure.""" + import matplotlib.pyplot as plt + from matplotlib.patches import Circle + + if figure is None: + figure, axes = plt.subplots(1, 2, figsize=(13, 4.5), constrained_layout=True) + else: + figure.clear() + axes = figure.subplots(1, 2) + + x = (np.arange(settings.nx, dtype=np.float64) + 0.5) * settings.width / settings.nx + y = (np.arange(settings.ny, dtype=np.float64) + 0.5) * settings.height / settings.ny + x_grid, y_grid = np.meshgrid(x, y) + u_center = 0.5 * (u[:, :-1] + u[:, 1:]) + v_center = 0.5 * (v[:-1, :] + v[1:, :]) + speed = np.hypot(u_center, v_center) + maximum_deflection = float(np.max(np.abs(beam_y - settings.beam_root_y))) + target_display_deflection = 0.03 * settings.height + display_scale = ( + max(1.0, target_display_deflection / maximum_deflection) + if maximum_deflection > 0.0 + else 1.0 + ) + displayed_beam_y = settings.beam_root_y + ( + beam_y - settings.beam_root_y + ) * display_scale + + figure.suptitle(f"Beam deflection display scale: x{display_scale:.3g}") + speed_plot = axes[0].pcolormesh( + x_grid, y_grid, speed, shading="auto", cmap="viridis" + ) + axes[0].streamplot( + x, + y, + u_center, + v_center, + color="white", + density=1.1, + linewidth=0.6, + ) + axes[0].set_title("Fluid speed and streamlines") + figure.colorbar(speed_plot, ax=axes[0], label="Speed (m/s)") + + pressure_plot = axes[1].pcolormesh( + x_grid, y_grid, pressure, shading="auto", cmap="coolwarm" + ) + axes[1].set_title("Pressure") + figure.colorbar(pressure_plot, ax=axes[1], label="Pressure (Pa)") + + for axis in axes: + axis.add_patch( + Circle( + (settings.cylinder_center_x, settings.cylinder_center_y), + settings.cylinder_radius, + facecolor="0.35", + edgecolor="black", + zorder=5, + ) + ) + axis.plot( + beam_x, + np.full_like(beam_x, settings.beam_root_y), + color="white", + linestyle="--", + linewidth=1.0, + label="Undeformed beam", + zorder=5, + ) + axis.plot( + beam_x, + displayed_beam_y, + color="black", + linewidth=2.5, + label="Deformed beam (display-scaled)", + zorder=6, + ) + axis.set(xlim=(0.0, settings.width), ylim=(0.0, settings.height)) + axis.set_xlabel("x (m)") + axis.set_ylabel("y (m)") + axis.set_aspect("equal", adjustable="box") + axes[1].legend(loc="upper right", fontsize="small") + return figure + + +def _draw_history(history: tuple[FSIStep, ...], figure=None): + """Draw beam displacement and velocity against iteration number.""" + import matplotlib.pyplot as plt + + if figure is None: + figure, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True) + else: + figure.clear() + axes = figure.subplots(1, 2) + + iterations = np.asarray([item.step for item in history]) + tip_displacement = np.asarray( + [item.beam_tip_displacement for item in history] + ) + tip_velocity = np.asarray([item.beam_tip_velocity for item in history]) + axes[0].plot(iterations, tip_displacement, color="tab:blue") + axes[0].set( + title="Beam tip displacement", xlabel="Iteration", ylabel="y (m)" + ) + axes[1].plot(iterations, tip_velocity, color="tab:orange") + axes[1].set( + title="Beam tip velocity", xlabel="Iteration", ylabel="v (m/s)" + ) + return figure + + +def plot_fsi_result( + result: FSIResult, + output_directory: str | Path, + *, + show: bool = False, +) -> dict[str, Path]: + """Save speed/pressure and beam-history plots for a completed FSI run. + + The returned mapping contains ``fields`` and ``history`` PNG paths. + Figures are closed after saving; with ``show=True`` they are displayed + before being closed. The input result is not modified. + """ + if not isinstance(result, FSIResult): + raise TypeError("result must be an FSIResult") + if not isinstance(show, bool): + raise TypeError("show must be a bool") + if not result.history: + raise ValueError("result must contain at least one completed step") + + import matplotlib.pyplot as plt + + output_path = Path(output_directory) + output_path.mkdir(parents=True, exist_ok=True) + fields_figure = _draw_fields( + result.settings, + result.u, + result.v, + result.pressure, + result.beam_x, + result.beam_y, + ) + history_figure = _draw_history(result.history) + fields_path = output_path / "fsi_fields.png" + history_path = output_path / "fsi_history.png" + fields_figure.savefig(fields_path, dpi=160) + history_figure.savefig(history_path, dpi=160) + + if show: + plt.show() + plt.close(fields_figure) + plt.close(history_figure) + return {"fields": fields_path, "history": history_path} + + +class LiveFSIPlotter: + """Refresh the same two figures as :func:`plot_fsi_result` every step.""" + + def __init__( + self, settings: FSISettings, output_directory: str | Path + ) -> None: + import matplotlib.pyplot as plt + + if plt.get_backend().lower() in {"agg", "pdf", "ps", "svg", "cairo", "template"}: + raise RuntimeError( + "live visualization requires an interactive Matplotlib backend; " + "use --mode save for headless runs" + ) + self._plt = plt + self._settings = settings + self._output_directory = Path(output_directory) + self._output_directory.mkdir(parents=True, exist_ok=True) + self._history: list[FSIStep] = [] + + initial_u = np.zeros((settings.ny, settings.nx + 1), dtype=np.float64) + initial_v = np.zeros((settings.ny + 1, settings.nx), dtype=np.float64) + initial_pressure = np.zeros((settings.ny, settings.nx), dtype=np.float64) + beam_x = settings.beam_root_x + np.linspace( + 0.0, settings.beam_length, settings.beam_elements + 1 + ) + beam_y = np.full_like(beam_x, settings.beam_root_y) + self._fields_figure = _draw_fields( + settings, initial_u, initial_v, initial_pressure, beam_x, beam_y + ) + self._history_figure = _draw_history(()) + plt.ion() + plt.show(block=False) + + def __call__( + self, + diagnostics: FSIStep, + u: FloatArray, + v: FloatArray, + pressure: FloatArray, + beam_x: FloatArray, + beam_y: FloatArray, + ) -> None: + """Refresh both shared plot layouts with one completed solver step.""" + self._history.append(diagnostics) + self._fields_figure = _draw_fields( + self._settings, + u, + v, + pressure, + beam_x, + beam_y, + figure=self._fields_figure, + ) + self._history_figure = _draw_history( + tuple(self._history), figure=self._history_figure + ) + self._fields_figure.canvas.draw_idle() + self._history_figure.canvas.draw_idle() + self._plt.pause(0.001) + + def finish(self, *, show: bool = True) -> dict[str, Path]: + """Save the same final PNGs as save mode and optionally leave them open.""" + fields_path = self._output_directory / "fsi_fields.png" + history_path = self._output_directory / "fsi_history.png" + self._fields_figure.savefig(fields_path, dpi=160) + self._history_figure.savefig(history_path, dpi=160) + self._plt.ioff() + if show: + self._plt.show() + self._plt.close(self._fields_figure) + self._plt.close(self._history_figure) + return {"fields": fields_path, "history": history_path} diff --git a/Exp_solver_dev_tr/src/fvm/__init__.py b/Exp_solver_dev_tr/src/fvm/__init__.py new file mode 100644 index 0000000000000..037017a8a8fae --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/__init__.py @@ -0,0 +1,127 @@ +"""Building blocks for an independently testable finite-volume solver.""" + +from .boundary_conditions import ( + BoundaryConditions, + FixedValue, + MovingWall, + NoSlipWall, + ZeroGradient, +) +from .case_definition import ( + CaseDefinition, + CaseValidationError, + SolverSettings, + VelocityBoundarySpec, + load_case_file, + parse_case_definition, + validate_case_document, +) +from .checkpoint import CheckpointError, CheckpointManager +from .fields import ScalarField, VectorField +from .mesh import BOUNDARY_NAMES, CartesianMesh +from .integration import BackendRun, PreparedCase, PythonFVMBackend +from .momentum import MomentumAssembly, MomentumPrediction, MomentumPredictor +from .operators import ( + convection_operator, + convective_fluxes, + diffusion_operator, + diffusive_fluxes, + divergence, + face_gradient, + interpolate_to_faces, +) +from .pressure_correction import ( + PressureCorrectionAssembly, + PressureCorrectionResult, + PressureCorrectionSolver, +) +from .postprocessing import ( + CenterlineProfiles, + ComponentExtrema, + GhiaComparison, + GridStudyRow, + VelocityExtrema, + centerline_profiles, + compare_ghia_re100, + export_ghia_comparison, + export_simulation_result, + plot_cavity_fields, + plot_convergence_history, + plot_ghia_comparison, + plot_mesh_and_boundaries, + run_lid_driven_grid_study, + velocity_extrema, + write_grid_study_csv, +) +from .projection import ProjectionCorrector, ProjectionResult +from .simulation import ( + SimulationResult, + SimulationSettings, + SimulationState, + StateObserver, + StepObserver, + StepDiagnostics, + TransientSolver, +) + +__all__ = [ + "BOUNDARY_NAMES", + "BackendRun", + "BoundaryConditions", + "CaseDefinition", + "CaseValidationError", + "CheckpointError", + "CheckpointManager", + "CartesianMesh", + "CenterlineProfiles", + "ComponentExtrema", + "FixedValue", + "GhiaComparison", + "GridStudyRow", + "MovingWall", + "MomentumAssembly", + "MomentumPrediction", + "MomentumPredictor", + "PressureCorrectionAssembly", + "PressureCorrectionResult", + "PressureCorrectionSolver", + "ProjectionCorrector", + "ProjectionResult", + "PreparedCase", + "PythonFVMBackend", + "NoSlipWall", + "ScalarField", + "SimulationResult", + "SimulationSettings", + "SimulationState", + "SolverSettings", + "StepDiagnostics", + "StepObserver", + "StateObserver", + "TransientSolver", + "VectorField", + "VelocityExtrema", + "VelocityBoundarySpec", + "ZeroGradient", + "convection_operator", + "convective_fluxes", + "centerline_profiles", + "compare_ghia_re100", + "diffusion_operator", + "diffusive_fluxes", + "divergence", + "export_ghia_comparison", + "export_simulation_result", + "face_gradient", + "interpolate_to_faces", + "load_case_file", + "parse_case_definition", + "plot_cavity_fields", + "plot_convergence_history", + "plot_ghia_comparison", + "plot_mesh_and_boundaries", + "run_lid_driven_grid_study", + "velocity_extrema", + "validate_case_document", + "write_grid_study_csv", +] \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/boundary_conditions.py b/Exp_solver_dev_tr/src/fvm/boundary_conditions.py new file mode 100644 index 0000000000000..caed5d0c57441 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/boundary_conditions.py @@ -0,0 +1,113 @@ +"""Boundary-condition definitions and per-field boundary storage.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Real +from types import MappingProxyType +from typing import Mapping, TypeAlias + +from .mesh import BOUNDARY_NAMES + +Velocity: TypeAlias = tuple[float, float] +BoundaryValue: TypeAlias = float | Velocity + + +def _velocity_pair(value: tuple[float, float], name: str) -> Velocity: + """Normalize and validate a two-component velocity.""" + if not isinstance(value, (tuple, list)) or len(value) != 2: + raise ValueError(f"{name} must contain exactly two components") + if any( + isinstance(component, bool) + or not isinstance(component, Real) + or not isfinite(component) + for component in value + ): + raise ValueError(f"{name} components must be finite numbers") + return (float(value[0]), float(value[1])) + + +@dataclass(frozen=True, slots=True) +class FixedValue: + """A prescribed scalar value or two-component vector value.""" + + value: BoundaryValue + + def __post_init__(self) -> None: + if isinstance(self.value, bool): + raise TypeError("fixed value must be numeric") + if isinstance(self.value, Real): + if not isfinite(self.value): + raise ValueError("fixed value must be finite") + object.__setattr__(self, "value", float(self.value)) + else: + object.__setattr__(self, "value", _velocity_pair(self.value, "fixed value")) + + +@dataclass(frozen=True, slots=True) +class ZeroGradient: + """A homogeneous normal-gradient boundary condition.""" + + +@dataclass(frozen=True, slots=True) +class NoSlipWall: + """Stationary no-slip wall, represented by its prescribed velocity.""" + + velocity: Velocity = (0.0, 0.0) + + def __post_init__(self) -> None: + object.__setattr__(self, "velocity", _velocity_pair(self.velocity, "velocity")) + + +@dataclass(frozen=True, slots=True) +class MovingWall: + """Moving no-slip wall, represented by its prescribed velocity.""" + + velocity: Velocity + + def __post_init__(self) -> None: + object.__setattr__(self, "velocity", _velocity_pair(self.velocity, "velocity")) + + +BoundaryCondition: TypeAlias = FixedValue | ZeroGradient | NoSlipWall | MovingWall + + +class BoundaryConditions: + """Store conditions by `(field_name, side)` without applying them yet. + + A field can be a scalar such as ``pressure`` or a vector such as + ``velocity``. The numerical discretization will interpret each condition. + """ + + def __init__(self) -> None: + self._conditions: dict[tuple[str, str], BoundaryCondition] = {} + + def set( + self, field_name: str, boundary: str, condition: BoundaryCondition + ) -> None: + """Add or replace a condition for one field on one domain boundary.""" + if not isinstance(field_name, str) or not field_name.strip(): + raise ValueError("field_name must be a non-empty string") + if boundary not in BOUNDARY_NAMES: + raise ValueError(f"boundary must be one of {BOUNDARY_NAMES}") + if not isinstance(condition, (FixedValue, ZeroGradient, NoSlipWall, MovingWall)): + raise TypeError("unsupported boundary condition type") + self._conditions[(field_name, boundary)] = condition + + def get(self, field_name: str, boundary: str) -> BoundaryCondition: + """Return a stored condition or raise `KeyError` if it is not defined.""" + return self._conditions[(field_name, boundary)] + + def for_field(self, field_name: str) -> Mapping[str, BoundaryCondition]: + """Return a read-only mapping of the conditions defined for a field.""" + conditions = { + boundary: condition + for (stored_field, boundary), condition in self._conditions.items() + if stored_field == field_name + } + return MappingProxyType(conditions) + + def __len__(self) -> int: + """Return the number of stored field-boundary conditions.""" + return len(self._conditions) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/case_definition.py b/Exp_solver_dev_tr/src/fvm/case_definition.py new file mode 100644 index 0000000000000..64b4feec5a0ae --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/case_definition.py @@ -0,0 +1,429 @@ +"""Versioned, framework-neutral JSON case contract for solver integration.""" + +from __future__ import annotations + +import json +import math +from dataclasses import dataclass +from importlib.resources import files +from pathlib import Path +from typing import Mapping, TypeAlias + +from jsonschema import Draft202012Validator + +from .mesh import BOUNDARY_NAMES + +CaseDocument: TypeAlias = Mapping[str, object] +Velocity: TypeAlias = tuple[float, float] + + +class CaseValidationError(ValueError): + """One or more schema or solver-capability errors in a case definition.""" + + def __init__(self, errors: tuple[str, ...]) -> None: + self.errors = errors + super().__init__("Invalid case definition:\n- " + "\n- ".join(errors)) + + +@dataclass(frozen=True, slots=True) +class VelocityBoundarySpec: + """A supported no-slip or moving-wall velocity condition.""" + + boundary_type: str + velocity: Velocity + velocity_profile: tuple[tuple[float, Velocity], ...] = () + + def velocity_at(self, time: float) -> Velocity: + """Interpolate a tabulated moving-wall velocity, holding its endpoints.""" + if not self.velocity_profile: + return self.velocity + if time <= self.velocity_profile[0][0]: + return self.velocity_profile[0][1] + for (start_time, start_velocity), (end_time, end_velocity) in zip( + self.velocity_profile, self.velocity_profile[1:] + ): + if time <= end_time: + fraction = (time - start_time) / (end_time - start_time) + return tuple( + start + fraction * (end - start) + for start, end in zip(start_velocity, end_velocity) + ) + return self.velocity_profile[-1][1] + + def maximum_velocity_between(self, start: float, end: float) -> Velocity: + """Return component-wise absolute maxima over a piecewise-linear interval.""" + sample_times = [start, end] + sample_times.extend( + time for time, _ in self.velocity_profile if start < time < end + ) + samples = [self.velocity_at(time) for time in sample_times] + return tuple(max(abs(value[index]) for value in samples) for index in range(2)) + + +@dataclass(frozen=True, slots=True) +class SolverSettings: + """Transient solver controls accepted by the version 1.0 case contract.""" + + max_time_step: float + minimum_time_step: float + max_steps: int + cfl_limit: float + velocity_tolerance: float + continuity_tolerance: float + mass_tolerance: float + momentum_residual_tolerance: float + pressure_residual_tolerance: float + end_time: float | None = None + max_inner_iterations_per_time_step: int = 100 + + def to_solver_kwargs(self) -> dict[str, float | int | None]: + """Map contract field names to `TransientSolver` keyword names.""" + return { + "max_time_step": self.max_time_step, + "minimum_time_step": self.minimum_time_step, + "max_steps": self.max_steps, + "cfl_limit": self.cfl_limit, + "velocity_tolerance": self.velocity_tolerance, + "continuity_tolerance": self.continuity_tolerance, + "mass_tolerance": self.mass_tolerance, + "momentum_residual_tolerance": self.momentum_residual_tolerance, + "pressure_residual_tolerance": self.pressure_residual_tolerance, + "end_time": self.end_time, + "max_inner_iterations_per_time_step": self.max_inner_iterations_per_time_step, + } + + +@dataclass(frozen=True, slots=True) +class CaseDefinition: + """Validated, typed representation of a version 1.0 solver case.""" + + case_id: str + description: str + nx: int + ny: int + width: float + height: float + density: float + dynamic_viscosity: float + initial_u: float + initial_v: float + initial_pressure: float + velocity_boundaries: tuple[tuple[str, VelocityBoundarySpec], ...] + pressure_correction_boundary: str + solver: SolverSettings + transient: bool = True + schema_version: str = "1.0" + + def boundary_for(self, side: str) -> VelocityBoundarySpec: + """Return the velocity wall definition for one cardinal side.""" + for boundary, spec in self.velocity_boundaries: + if boundary == side: + return spec + raise KeyError(side) + + def to_mapping(self) -> dict[str, object]: + """Return a fresh JSON-compatible document in canonical field order.""" + boundaries: dict[str, object] = {} + for side, spec in self.velocity_boundaries: + if spec.boundary_type == "no_slip_wall": + boundaries[side] = {"type": spec.boundary_type} + elif spec.velocity_profile: + boundaries[side] = { + "type": spec.boundary_type, + "velocity_profile": [ + {"time_s": time, "velocity_m_s": list(velocity)} + for time, velocity in spec.velocity_profile + ], + } + else: + boundaries[side] = { + "type": spec.boundary_type, + "velocity_m_s": list(spec.velocity), + } + boundaries["pressure_correction"] = self.pressure_correction_boundary + solver = { + "max_time_step_s": self.solver.max_time_step, + "minimum_time_step_s": self.solver.minimum_time_step, + "max_steps": self.solver.max_steps, + "cfl_limit": self.solver.cfl_limit, + "velocity_tolerance_m_s": self.solver.velocity_tolerance, + "continuity_tolerance_s_inv": self.solver.continuity_tolerance, + "mass_tolerance_m2_s": self.solver.mass_tolerance, + "momentum_residual_tolerance": self.solver.momentum_residual_tolerance, + "pressure_residual_tolerance": self.solver.pressure_residual_tolerance, + "max_inner_iterations_per_time_step": ( + self.solver.max_inner_iterations_per_time_step + ), + } + if self.solver.end_time is not None: + solver["end_time_s"] = self.solver.end_time + return { + "schema_version": self.schema_version, + "case_id": self.case_id, + "description": self.description, + "units": "SI", + "physics": { + "model": "incompressible_laminar", + "transient": self.transient, + }, + "domain": { + "type": "rectangle", + "width_m": self.width, + "height_m": self.height, + }, + "mesh": { + "type": "uniform_cartesian", + "nx": self.nx, + "ny": self.ny, + }, + "material": { + "type": "newtonian_fluid", + "density_kg_m3": self.density, + "dynamic_viscosity_pa_s": self.dynamic_viscosity, + }, + "initial_conditions": { + "u_m_s": self.initial_u, + "v_m_s": self.initial_v, + "pressure_pa": self.initial_pressure, + }, + "boundary_conditions": boundaries, + "solver": solver, + } + + +def _case_schema() -> dict[str, object]: + """Read the packaged schema so installed users validate the same contract.""" + schema_path = files("fvm").joinpath("schemas", "case-v1.schema.json") + return json.loads(schema_path.read_text(encoding="utf-8")) + + +def _error_path(path: object) -> str: + """Format a JSON Schema instance path as a user-readable JSON pointer.""" + parts = [str(part) for part in path] + return "/" + "/".join(parts) if parts else "/" + + +def _format_schema_error(error: object) -> list[str]: + """Point required/unknown-property errors at the actual offending key.""" + path_parts = list(error.absolute_path) + base_path = _error_path(path_parts) + if error.validator == "required" and isinstance(error.instance, Mapping): + missing = sorted(set(error.validator_value) - set(error.instance)) + return [ + f"{_error_path(path_parts + [key])}: required property is missing" + for key in missing + ] + if error.validator == "additionalProperties" and isinstance(error.instance, Mapping): + declared = set(error.schema.get("properties", {})) + unknown = sorted(set(error.instance) - declared) + return [f"{_error_path(path_parts + [key])}: unknown property" for key in unknown] + return [f"{base_path}: {error.message}"] + + +def _non_finite_paths(value: object, path: str = "") -> list[str]: + """Catch NaN/Infinity values accepted by Python's permissive JSON decoder.""" + if isinstance(value, bool) or value is None: + return [] + if isinstance(value, float) and not math.isfinite(value): + return [path or "/"] + if isinstance(value, Mapping): + invalid: list[str] = [] + for key, child in value.items(): + invalid.extend(_non_finite_paths(child, f"{path}/{key}")) + return invalid + if isinstance(value, list): + invalid = [] + for index, child in enumerate(value): + invalid.extend(_non_finite_paths(child, f"{path}/{index}")) + return invalid + return [] + + +def validate_case_document(document: CaseDocument) -> None: + """Validate schema, finite values, and cross-field solver constraints. + + All schema failures are collected so setup-software callers can correct a + document in one pass. Errors include JSON-pointer-like paths and reject + unknown keys rather than silently ignoring likely misspellings. + """ + if not isinstance(document, Mapping): + raise CaseValidationError(("/: the case root must be a JSON object",)) + + validator = Draft202012Validator(_case_schema()) + schema_errors = sorted( + validator.iter_errors(document), + key=lambda error: (_error_path(error.absolute_path), error.message), + ) + errors = [message for error in schema_errors for message in _format_schema_error(error)] + errors.extend( + f"{path}: value must be finite" + for path in _non_finite_paths(document) + ) + + solver = document.get("solver") + if isinstance(solver, Mapping): + maximum = solver.get("max_time_step_s", 0.01) + minimum = solver.get("minimum_time_step_s", 1e-12) + if ( + isinstance(maximum, (int, float)) + and not isinstance(maximum, bool) + and isinstance(minimum, (int, float)) + and not isinstance(minimum, bool) + and minimum > maximum + ): + errors.append( + "/solver/minimum_time_step_s: must not exceed /solver/max_time_step_s" + ) + + boundary_conditions = document.get("boundary_conditions") + physics = document.get("physics") + transient = isinstance(physics, Mapping) and physics.get("transient") is True + if isinstance(boundary_conditions, Mapping): + for side in BOUNDARY_NAMES: + wall = boundary_conditions.get(side) + if isinstance(wall, Mapping) and wall.get("type") == "moving_wall": + velocities = [wall.get("velocity_m_s")] + profile = wall.get("velocity_profile") + if isinstance(profile, list): + profile_times: list[float] = [] + velocities.extend( + item.get("velocity_m_s") + for item in profile + if isinstance(item, Mapping) + ) + for point in profile: + if not isinstance(point, Mapping): + continue + point_time = point.get("time_s") + if ( + isinstance(point_time, (int, float)) + and not isinstance(point_time, bool) + ): + if profile_times and point_time <= profile_times[-1]: + errors.append( + f"/boundary_conditions/{side}/velocity_profile: " + "time_s values must be strictly increasing" + ) + profile_times.append(float(point_time)) + normal_component = 0 if side in ("west", "east") else 1 + if not transient and isinstance(profile, list): + errors.append( + f"/boundary_conditions/{side}/velocity_profile: " + "time-dependent walls require transient physics" + ) + for index, velocity in enumerate(velocities): + if ( + isinstance(velocity, list) + and len(velocity) == 2 + and velocity[normal_component] != 0.0 + ): + errors.append( + f"/boundary_conditions/{side}/velocity_profile/{index}/" + f"velocity_m_s/{normal_component}: wall-normal velocity " + "must be zero" + ) + + if isinstance(solver, Mapping): + end_time = solver.get("end_time_s") + if end_time is not None and not transient: + errors.append("/solver/end_time_s: requires transient physics") + + if errors: + raise CaseValidationError(tuple(errors)) + + +def parse_case_definition(document: CaseDocument) -> CaseDefinition: + """Validate a setup-software mapping and convert it to typed case data.""" + validate_case_document(document) + domain = document["domain"] + mesh = document["mesh"] + material = document["material"] + initial = document["initial_conditions"] + boundaries = document["boundary_conditions"] + solver = document["solver"] + assert isinstance(domain, Mapping) + assert isinstance(mesh, Mapping) + assert isinstance(material, Mapping) + assert isinstance(initial, Mapping) + assert isinstance(boundaries, Mapping) + assert isinstance(solver, Mapping) + + velocity_boundaries: list[tuple[str, VelocityBoundarySpec]] = [] + for side in BOUNDARY_NAMES: + wall = boundaries[side] + assert isinstance(wall, Mapping) + boundary_type = str(wall["type"]) + velocity = ( + tuple(float(component) for component in wall["velocity_m_s"]) + if boundary_type == "moving_wall" and "velocity_m_s" in wall + else (0.0, 0.0) + ) + profile = tuple( + ( + float(point["time_s"]), + tuple(float(component) for component in point["velocity_m_s"]), + ) + for point in wall.get("velocity_profile", []) + ) + if profile and velocity == (0.0, 0.0): + velocity = profile[0][1] + velocity_boundaries.append( + (side, VelocityBoundarySpec(boundary_type, velocity, profile)) + ) + + settings = SolverSettings( + max_time_step=float(solver.get("max_time_step_s", 0.01)), + minimum_time_step=float(solver.get("minimum_time_step_s", 1e-12)), + max_steps=int(solver["max_steps"]), + cfl_limit=float(solver.get("cfl_limit", 0.5)), + velocity_tolerance=float(solver.get("velocity_tolerance_m_s", 1e-6)), + continuity_tolerance=float(solver.get("continuity_tolerance_s_inv", 1e-8)), + mass_tolerance=float(solver.get("mass_tolerance_m2_s", 1e-10)), + momentum_residual_tolerance=float( + solver.get("momentum_residual_tolerance", 1e-10) + ), + pressure_residual_tolerance=float( + solver.get("pressure_residual_tolerance", 1e-10) + ), + end_time=( + float(solver["end_time_s"]) + if "end_time_s" in solver + else None + ), + max_inner_iterations_per_time_step=int( + solver.get("max_inner_iterations_per_time_step", 100) + ), + ) + return CaseDefinition( + schema_version=str(document["schema_version"]), + case_id=str(document["case_id"]), + description=str(document.get("description", "")), + nx=int(mesh["nx"]), + ny=int(mesh["ny"]), + width=float(domain["width_m"]), + height=float(domain["height_m"]), + density=float(material["density_kg_m3"]), + dynamic_viscosity=float(material["dynamic_viscosity_pa_s"]), + initial_u=float(initial["u_m_s"]), + initial_v=float(initial["v_m_s"]), + initial_pressure=float(initial["pressure_pa"]), + velocity_boundaries=tuple(velocity_boundaries), + pressure_correction_boundary=str(boundaries["pressure_correction"]), + solver=settings, + transient=bool(document["physics"]["transient"]), + ) + + +def load_case_file(path: str | Path) -> CaseDefinition: + """Read, validate, and convert a versioned JSON case file.""" + case_path = Path(path) + try: + with case_path.open("r", encoding="utf-8") as case_file: + document = json.load(case_file) + except json.JSONDecodeError as error: + raise CaseValidationError( + (f"/: invalid JSON at line {error.lineno}, column {error.colno}: {error.msg}",) + ) from error + except OSError as error: + raise CaseValidationError((f"/: cannot read case file {case_path}: {error}",)) from error + return parse_case_definition(document) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/checkpoint.py b/Exp_solver_dev_tr/src/fvm/checkpoint.py new file mode 100644 index 0000000000000..ec1f40b659866 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/checkpoint.py @@ -0,0 +1,368 @@ +"""Atomic persistence and validated restoration of solver checkpoints.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import tempfile +from dataclasses import asdict +from pathlib import Path +from typing import Mapping + +import numpy as np + +from .fields import ScalarField, VectorField +from .mesh import CartesianMesh +from .simulation import SimulationState, StepDiagnostics + +CHECKPOINT_FORMAT_VERSION = "1.0" +_CHECKPOINT_NAME = re.compile(r"^checkpoint_(\d+)(?:_(\d+))?\.npz$") + + +class CheckpointError(ValueError): + """A checkpoint is unreadable, invalid, or incompatible with a case.""" + + +class CheckpointManager: + """Read and write solver checkpoints in a dedicated directory. + + Numeric fields are stored in compressed NumPy archives. Metadata and the + complete run configuration are JSON-encoded inside the archive; `latest.json` + is the atomically updated pointer to the most recently committed checkpoint. + """ + + def __init__(self, directory: str | Path, retain_last: int = 5) -> None: + if isinstance(retain_last, bool) or not isinstance(retain_last, int): + raise TypeError("retain_last must be a positive integer") + if retain_last < 1: + raise ValueError("retain_last must be a positive integer") + self.directory = Path(directory) + self.retain_last = retain_last + + def save( + self, state: SimulationState, case_document: Mapping[str, object] + ) -> Path: + """Commit a complete state and then update the latest-checkpoint pointer.""" + self._validate_state(state) + normalized_case = json.loads(json.dumps(case_document, sort_keys=True)) + if not isinstance(normalized_case, dict): + raise TypeError("case_document must be a JSON-compatible object") + self.directory.mkdir(parents=True, exist_ok=True) + target = self._next_path(state.completed_steps) + metadata = { + "checkpoint_format_version": CHECKPOINT_FORMAT_VERSION, + "solver_version": "0.1.0", + "completed_steps": state.completed_steps, + "elapsed_time": state.elapsed_time, + "pseudo_time": state.pseudo_time, + "steady_time_step": state.steady_time_step, + "mesh": { + "nx": state.velocity.mesh.nx, + "ny": state.velocity.mesh.ny, + "width": state.velocity.mesh.width, + "height": state.velocity.mesh.height, + }, + "case": normalized_case, + "configuration_fingerprint": configuration_fingerprint(normalized_case), + "history": [asdict(item) for item in state.history], + } + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{target.name}.", suffix=".tmp", dir=self.directory + ) + temporary_path = Path(temporary_name) + try: + with os.fdopen(descriptor, "wb") as checkpoint_file: + np.savez_compressed( + checkpoint_file, + u=state.velocity.u.values, + v=state.velocity.v.values, + pressure=state.pressure.values, + metadata=np.asarray(json.dumps(metadata, sort_keys=True)), + ) + checkpoint_file.flush() + os.fsync(checkpoint_file.fileno()) + self._read_archive(temporary_path, state.velocity.mesh) + os.replace(temporary_path, target) + latest = { + "checkpoint_format_version": CHECKPOINT_FORMAT_VERSION, + "file": target.name, + "sha256": self._sha256(target), + "completed_steps": state.completed_steps, + } + self._write_json_atomically(self.directory / "latest.json", latest) + except Exception: + temporary_path.unlink(missing_ok=True) + raise + + self._apply_retention(target) + return target + + def load( + self, + source: str | Path, + case_document: Mapping[str, object], + mesh: CartesianMesh, + ) -> SimulationState: + """Load `latest` or a specific archive after compatibility checks.""" + path, expected_digest = self._resolve_source(source) + if expected_digest is not None: + try: + if self._sha256(path) != expected_digest: + raise CheckpointError( + "latest checkpoint SHA-256 does not match its manifest" + ) + except OSError as error: + raise CheckpointError(f"cannot read latest checkpoint file: {error}") from error + try: + with np.load(path, allow_pickle=False) as archive: + stored_mesh = self._read_metadata(archive) + if stored_mesh.get("checkpoint_format_version") != CHECKPOINT_FORMAT_VERSION: + raise CheckpointError("unsupported checkpoint format version") + metadata = stored_mesh + saved_case = metadata.get("case") + if not isinstance(saved_case, Mapping): + raise CheckpointError("checkpoint is missing its case configuration") + if metadata.get("configuration_fingerprint") != configuration_fingerprint( + saved_case + ): + raise CheckpointError("checkpoint case configuration fingerprint is invalid") + validate_case_compatibility(saved_case, case_document) + self._validate_mesh_metadata(metadata, mesh) + pressure_values = np.asarray(archive["pressure"], dtype=np.float64) + u_values = np.asarray(archive["u"], dtype=np.float64) + v_values = np.asarray(archive["v"], dtype=np.float64) + if pressure_values.shape != mesh.shape_for_location("cell_center"): + raise CheckpointError("checkpoint pressure array has an invalid shape") + if u_values.shape != mesh.shape_for_location("x_face"): + raise CheckpointError("checkpoint u array has an invalid shape") + if v_values.shape != mesh.shape_for_location("y_face"): + raise CheckpointError("checkpoint v array has an invalid shape") + if not all(np.all(np.isfinite(values)) for values in (pressure_values, u_values, v_values)): + raise CheckpointError("checkpoint fields must contain only finite values") + history_data = metadata.get("history") + if not isinstance(history_data, list): + raise CheckpointError("checkpoint history is missing or invalid") + history = tuple(StepDiagnostics(**item) for item in history_data) + completed_steps = metadata.get("completed_steps") + if ( + isinstance(completed_steps, bool) + or not isinstance(completed_steps, int) + or completed_steps != len(history) + ): + raise CheckpointError("checkpoint step count does not match its history") + velocity = VectorField(mesh, name="velocity") + velocity.set_values(u_values, v_values) + pressure = ScalarField(mesh, name="pressure") + pressure.set_values(pressure_values) + state = SimulationState( + velocity=velocity, + pressure=pressure, + completed_steps=completed_steps, + elapsed_time=float(metadata["elapsed_time"]), + pseudo_time=float(metadata["pseudo_time"]), + steady_time_step=( + None + if metadata.get("steady_time_step") is None + else float(metadata["steady_time_step"]) + ), + history=history, + ) + except CheckpointError: + raise + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as error: + raise CheckpointError(f"cannot load checkpoint {path}: {error}") from error + self._validate_state(state) + return state + + def _resolve_source(self, source: str | Path) -> tuple[Path, str | None]: + if str(source) == "latest": + manifest_path = self.directory / "latest.json" + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + filename = manifest["file"] + digest = manifest["sha256"] + if Path(filename).name != filename or not isinstance(digest, str): + raise ValueError("invalid latest manifest fields") + return self.directory / filename, digest + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as error: + raise CheckpointError(f"cannot read latest checkpoint manifest: {error}") from error + path = Path(source) + if not path.is_absolute(): + path = self.directory / path + if not path.is_file(): + raise CheckpointError(f"checkpoint file does not exist: {path}") + return path, None + + def _next_path(self, completed_steps: int) -> Path: + base = f"checkpoint_{completed_steps:08d}" + candidate = self.directory / f"{base}.npz" + suffix = 2 + while candidate.exists(): + candidate = self.directory / f"{base}_{suffix}.npz" + suffix += 1 + return candidate + + def _apply_retention(self, latest_path: Path) -> None: + checkpoints = [] + for path in self.directory.glob("checkpoint_*.npz"): + match = _CHECKPOINT_NAME.match(path.name) + if match: + checkpoints.append((int(match.group(1)), path.stat().st_mtime_ns, path)) + checkpoints.sort(reverse=True) + retained = {path for _, _, path in checkpoints[: self.retain_last]} + retained.add(latest_path) + for _, _, path in checkpoints: + if path not in retained: + try: + path.unlink() + except OSError: + pass + + @staticmethod + def _read_metadata(archive: np.lib.npyio.NpzFile) -> dict[str, object]: + try: + raw = archive["metadata"] + if raw.shape != (): + raise ValueError("metadata must be a scalar JSON value") + metadata = json.loads(str(raw.item())) + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as error: + raise CheckpointError(f"invalid checkpoint metadata: {error}") from error + if not isinstance(metadata, dict): + raise CheckpointError("checkpoint metadata root must be a JSON object") + return metadata + + @staticmethod + def _read_archive(path: Path, mesh: CartesianMesh) -> None: + try: + with np.load(path, allow_pickle=False) as archive: + metadata = CheckpointManager._read_metadata(archive) + if metadata.get("checkpoint_format_version") != CHECKPOINT_FORMAT_VERSION: + raise CheckpointError("unsupported checkpoint format version") + for name, location in ( + ("pressure", "cell_center"), + ("u", "x_face"), + ("v", "y_face"), + ): + values = np.asarray(archive[name]) + if values.shape != mesh.shape_for_location(location): + raise CheckpointError(f"checkpoint {name} array has an invalid shape") + if not np.all(np.isfinite(values)): + raise CheckpointError(f"checkpoint {name} array is not finite") + except CheckpointError: + raise + except (OSError, KeyError, TypeError, ValueError) as error: + raise CheckpointError(f"checkpoint validation failed: {error}") from error + + @staticmethod + def _validate_state(state: SimulationState) -> None: + if not isinstance(state, SimulationState): + raise TypeError("state must be a SimulationState") + if state.completed_steps < 0 or len(state.history) != state.completed_steps: + raise CheckpointError("state history must cover all completed steps") + if state.history and state.history[-1].step != state.completed_steps: + raise CheckpointError("state history step does not match completed_steps") + for value in (state.elapsed_time, state.pseudo_time): + if not np.isfinite(value) or value < 0.0: + raise CheckpointError("state times must be finite and non-negative") + if state.steady_time_step is not None and ( + not np.isfinite(state.steady_time_step) or state.steady_time_step <= 0.0 + ): + raise CheckpointError("steady_time_step must be finite and positive") + for values in ( + state.velocity.u.values, + state.velocity.v.values, + state.pressure.values, + ): + if not np.all(np.isfinite(values)): + raise CheckpointError("state fields must contain only finite values") + + @staticmethod + def _validate_mesh_metadata( + metadata: Mapping[str, object], mesh: CartesianMesh + ) -> None: + stored = metadata.get("mesh") + if not isinstance(stored, Mapping): + raise CheckpointError("checkpoint mesh metadata is missing") + expected = { + "nx": mesh.nx, + "ny": mesh.ny, + "width": mesh.width, + "height": mesh.height, + } + if any(stored.get(key) != value for key, value in expected.items()): + raise CheckpointError("checkpoint mesh does not match the case mesh") + + @staticmethod + def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as checkpoint_file: + for block in iter(lambda: checkpoint_file.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + @staticmethod + def _write_json_atomically(path: Path, document: Mapping[str, object]) -> None: + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", suffix=".tmp", dir=path.parent + ) + temporary_path = Path(temporary_name) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as output: + json.dump(document, output, indent=2, sort_keys=True) + output.write("\n") + output.flush() + os.fsync(output.fileno()) + os.replace(temporary_path, path) + except Exception: + temporary_path.unlink(missing_ok=True) + raise + + +def configuration_fingerprint(case_document: Mapping[str, object]) -> str: + """Hash numerical case inputs, excluding permitted continuation limits.""" + normalized = json.loads(json.dumps(case_document, sort_keys=True)) + solver = normalized.get("solver") + if isinstance(solver, dict): + solver.pop("max_steps", None) + solver.pop("end_time_s", None) + encoded = json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode() + return hashlib.sha256(encoded).hexdigest() + + +def validate_case_compatibility( + saved_case: Mapping[str, object], current_case: Mapping[str, object] +) -> None: + """Allow only monotonic run-limit extensions during a checkpoint restart.""" + saved_solver = saved_case.get("solver") + current_solver = current_case.get("solver") + if not isinstance(saved_solver, Mapping) or not isinstance(current_solver, Mapping): + raise CheckpointError("case configuration is missing solver settings") + if configuration_fingerprint(saved_case) != configuration_fingerprint(current_case): + raise CheckpointError( + "case configuration is incompatible with this checkpoint; mesh, physics, " + "boundaries, initial conditions, and numerical controls must match" + ) + saved_steps = saved_solver.get("max_steps") + current_steps = current_solver.get("max_steps") + if ( + isinstance(saved_steps, int) + and not isinstance(saved_steps, bool) + and isinstance(current_steps, int) + and not isinstance(current_steps, bool) + and current_steps < saved_steps + ): + raise CheckpointError("max_steps may be increased on restart, but not reduced") + saved_end_time = saved_solver.get("end_time_s") + current_end_time = current_solver.get("end_time_s") + if saved_end_time != current_end_time: + if ( + isinstance(saved_end_time, (int, float)) + and not isinstance(saved_end_time, bool) + and isinstance(current_end_time, (int, float)) + and not isinstance(current_end_time, bool) + and current_end_time >= saved_end_time + ): + return + raise CheckpointError("end_time_s may be increased on restart, but not removed or reduced") \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/externalization/__init__.py b/Exp_solver_dev_tr/src/fvm/externalization/__init__.py new file mode 100644 index 0000000000000..42bd1983cc25c --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/__init__.py @@ -0,0 +1,32 @@ +"""Transport-neutral step snapshots and pluggable result externalizers.""" + +from .model import StepSnapshot +from .store import SnapshotStore +from .grpc_transport import GrpcExternalizer, GrpcSnapshotServer +from .visualization import LiveSnapshotPlotter, plot_latest_snapshot, plot_snapshot +from .strategies import ( + AsyncFileExternalizer, + ExternalizationMetrics, + SharedFolderExternalizer, + SharedFolderPoller, + StepSnapshotObserver, + SynchronousFileExternalizer, + create_step_observer, +) + +__all__ = [ + "AsyncFileExternalizer", + "ExternalizationMetrics", + "GrpcExternalizer", + "GrpcSnapshotServer", + "LiveSnapshotPlotter", + "SharedFolderExternalizer", + "SharedFolderPoller", + "SnapshotStore", + "StepSnapshot", + "StepSnapshotObserver", + "SynchronousFileExternalizer", + "create_step_observer", + "plot_latest_snapshot", + "plot_snapshot", +] diff --git a/Exp_solver_dev_tr/src/fvm/externalization/grpc_transport.py b/Exp_solver_dev_tr/src/fvm/externalization/grpc_transport.py new file mode 100644 index 0000000000000..dd3ea3990d5f8 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/grpc_transport.py @@ -0,0 +1,263 @@ +"""Optional gRPC streaming transport for externalized solver snapshots.""" + +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +import json +from math import isfinite +from pathlib import Path +import queue +import threading +from time import perf_counter + +import grpc +from google.protobuf.wrappers_pb2 import BytesValue + +from .model import StepSnapshot +from .strategies import ExternalizationMetrics +from .store import SnapshotStore + +_SERVICE = "fvm.externalization.v1.SnapshotService" +_METHOD = f"/{_SERVICE}/Publish" + + +class GrpcSnapshotServer: + """Local or cloud-side gRPC endpoint that durably consumes snapshot streams.""" + + def __init__( + self, + directory: str | Path, + address: str = "127.0.0.1:0", + max_message_bytes: int = 64 * 1024 * 1024, + ) -> None: + if ( + isinstance(max_message_bytes, bool) + or not isinstance(max_message_bytes, int) + or max_message_bytes <= 0 + ): + raise ValueError("max_message_bytes must be a positive integer") + self.store = SnapshotStore(directory) + self.address = address + self._server = grpc.server( + ThreadPoolExecutor(max_workers=4), + options=(("grpc.max_receive_message_length", max_message_bytes),), + ) + handler = grpc.stream_unary_rpc_method_handler( + self._publish, + request_deserializer=BytesValue.FromString, + response_serializer=BytesValue.SerializeToString, + ) + self._server.add_generic_rpc_handlers( + (grpc.method_handlers_generic_handler(_SERVICE, {"Publish": handler}),) + ) + self._bound_port: int | None = None + self._run_locks: dict[str, threading.Lock] = {} + self._run_locks_guard = threading.Lock() + + @property + def target(self) -> str: + """Return the actual bound address after ``start``.""" + if self._bound_port is None: + raise RuntimeError("gRPC server has not been started") + host = self.address.rsplit(":", 1)[0] + return f"{host}:{self._bound_port}" + + def start(self, credentials: grpc.ServerCredentials | None = None) -> str: + if self._bound_port is not None: + return self.target + port = ( + self._server.add_secure_port(self.address, credentials) + if credentials is not None + else self._server.add_insecure_port(self.address) + ) + if port == 0: + raise OSError(f"could not bind gRPC server to {self.address}") + self._bound_port = port + self._server.start() + return self.target + + def stop(self, grace_seconds: float = 1.0) -> None: + if self._bound_port is not None: + self._server.stop(grace_seconds).wait() + self._bound_port = None + + def _publish(self, requests, context) -> BytesValue: + count = 0 + externalize_seconds = 0.0 + run_id: str | None = None + last_step = 0 + run_lock: threading.Lock | None = None + lock_acquired = False + try: + for request in requests: + snapshot = StepSnapshot.from_bytes(request.value) + if run_id is None: + run_id = snapshot.run_id + with self._run_locks_guard: + run_lock = self._run_locks.setdefault( + run_id, threading.Lock() + ) + lock_acquired = run_lock.acquire(blocking=False) + if not lock_acquired: + context.abort( + grpc.StatusCode.ABORTED, + f"another stream is publishing run_id {run_id}", + ) + last_step = self.store.latest_step_for(run_id) + elif snapshot.run_id != run_id: + context.abort( + grpc.StatusCode.INVALID_ARGUMENT, + "one gRPC stream may publish only one run_id", + ) + if snapshot.step <= last_step: + context.abort( + grpc.StatusCode.INVALID_ARGUMENT, + f"snapshot step {snapshot.step} is not after {last_step}", + ) + started = perf_counter() + self.store.write(snapshot) + externalize_seconds += perf_counter() - started + last_step = snapshot.step + count += 1 + return BytesValue( + value=json.dumps( + { + "snapshots": count, + "externalize_seconds": externalize_seconds, + }, + allow_nan=False, + ).encode("utf-8") + ) + finally: + if run_id is not None and run_lock is not None and lock_acquired: + with self._run_locks_guard: + run_lock.release() + if self._run_locks.get(run_id) is run_lock: + del self._run_locks[run_id] + + +class GrpcExternalizer: + """Strategy 4: stream snapshots over a bounded asynchronous gRPC channel.""" + + def __init__( + self, + target: str, + queue_size: int = 16, + timeout_seconds: float | None = None, + max_message_bytes: int = 64 * 1024 * 1024, + credentials: grpc.ChannelCredentials | None = None, + ) -> None: + if isinstance(queue_size, bool) or not isinstance(queue_size, int) or queue_size <= 0: + raise ValueError("queue_size must be a positive integer") + if timeout_seconds is not None and timeout_seconds <= 0.0: + raise ValueError("timeout_seconds must be positive") + if ( + isinstance(max_message_bytes, bool) + or not isinstance(max_message_bytes, int) + or max_message_bytes <= 0 + ): + raise ValueError("max_message_bytes must be a positive integer") + self.metrics = ExternalizationMetrics() + self._queue: queue.Queue[bytes | None] = queue.Queue(queue_size) + self._timeout_seconds = timeout_seconds + options = ( + ("grpc.max_send_message_length", max_message_bytes), + ("grpc.max_receive_message_length", max_message_bytes), + ) + self._channel = ( + grpc.secure_channel(target, credentials, options=options) + if credentials is not None + else grpc.insecure_channel(target, options=options) + ) + self._publish_call = self._channel.stream_unary( + _METHOD, + request_serializer=BytesValue.SerializeToString, + response_deserializer=BytesValue.FromString, + ) + self._error: Exception | None = None + self._closed = False + self._sent = 0 + self._worker = threading.Thread( + target=self._stream, name="fvm-grpc-externalizer", daemon=True + ) + self._worker.start() + + def publish(self, snapshot: StepSnapshot) -> None: + if self._closed: + raise RuntimeError("externalizer is closed") + started = perf_counter() + payload = snapshot.to_bytes() + while True: + self._raise_worker_error() + try: + self._queue.put(payload, timeout=0.1) + self._sent += 1 + break + except queue.Full: + continue + self.metrics.record_publish(len(payload), perf_counter() - started) + + def close(self) -> None: + if self._closed: + self._raise_worker_error() + return + self._closed = True + worker_error: RuntimeError | None = None + while self._worker.is_alive(): + try: + self._raise_worker_error() + except RuntimeError as error: + worker_error = error + break + try: + self._queue.put(None, timeout=0.1) + break + except queue.Full: + continue + self._worker.join(timeout=self._timeout_seconds) + if self._timeout_seconds is not None and self._worker.is_alive(): + self._channel.close() + raise TimeoutError("gRPC externalization did not finish before timeout") + self._channel.close() + if worker_error is not None: + raise worker_error + self._raise_worker_error() + + def _requests(self): + while True: + item = self._queue.get() + try: + if item is None: + return + yield BytesValue(value=item) + finally: + self._queue.task_done() + + def _stream(self) -> None: + try: + response = self._publish_call( + self._requests(), timeout=self._timeout_seconds + ) + acknowledgement = json.loads(response.value.decode("utf-8")) + acknowledged = acknowledgement["snapshots"] + externalize_seconds = acknowledgement["externalize_seconds"] + if ( + isinstance(acknowledged, bool) + or not isinstance(acknowledged, int) + or not isinstance(externalize_seconds, (int, float)) + or isinstance(externalize_seconds, bool) + or not isfinite(externalize_seconds) + or externalize_seconds < 0.0 + ): + raise ValueError("gRPC server returned invalid metrics") + if acknowledged != self._sent: + raise RuntimeError( + f"gRPC acknowledged {acknowledged} snapshots; sent {self._sent}" + ) + self.metrics.record_externalize_time(float(externalize_seconds)) + except Exception as error: + self._error = error + + def _raise_worker_error(self) -> None: + if self._error is not None: + raise RuntimeError(f"gRPC externalization failed: {self._error}") from self._error diff --git a/Exp_solver_dev_tr/src/fvm/externalization/model.py b/Exp_solver_dev_tr/src/fvm/externalization/model.py new file mode 100644 index 0000000000000..32d2eb958fd2b --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/model.py @@ -0,0 +1,196 @@ +"""Portable, validated snapshots that do not depend on solver classes.""" + +from __future__ import annotations + +from dataclasses import dataclass, fields, is_dataclass +from io import BytesIO +import json +from math import isfinite +from numbers import Integral, Real +import re +from types import MappingProxyType +from typing import Mapping + +import numpy as np +from numpy.typing import NDArray + + +FloatArray = NDArray[np.float64] +_RUN_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z") + + +def validate_run_id(run_id: str) -> str: + """Reject identifiers that are unsafe as filesystem path components.""" + if not isinstance(run_id, str) or _RUN_ID_PATTERN.fullmatch(run_id) is None: + raise ValueError( + "run_id must be 1-128 characters using letters, digits, dot, " + "underscore, or hyphen, and start with a letter or digit" + ) + return run_id + + +@dataclass(frozen=True, slots=True) +class StepSnapshot: + """Immutable numerical fields and diagnostics for one completed solver step.""" + + run_id: str + step: int + mesh: Mapping[str, float | int] + diagnostics: Mapping[str, int | float | None] + x_cell_centers: FloatArray + y_cell_centers: FloatArray + pressure: FloatArray + u_faces: FloatArray + v_faces: FloatArray + + def __post_init__(self) -> None: + validate_run_id(self.run_id) + if ( + isinstance(self.step, bool) + or not isinstance(self.step, Integral) + or self.step <= 0 + ): + raise ValueError("step must be a positive integer") + object.__setattr__(self, "step", int(self.step)) + required_mesh_keys = {"nx", "ny", "width", "height"} + if set(self.mesh) != required_mesh_keys: + raise ValueError("mesh must contain nx, ny, width, and height") + nx, ny = self.mesh["nx"], self.mesh["ny"] + width, height = self.mesh["width"], self.mesh["height"] + if ( + isinstance(nx, bool) + or not isinstance(nx, Integral) + or nx <= 0 + or isinstance(ny, bool) + or not isinstance(ny, Integral) + or ny <= 0 + ): + raise ValueError("mesh dimensions must be positive integers") + if ( + isinstance(width, bool) + or not isinstance(width, Real) + or isinstance(height, bool) + or not isinstance(height, Real) + ): + raise ValueError("mesh width and height must be finite positive numbers") + if not isfinite(float(width)) or float(width) <= 0.0: + raise ValueError("mesh width must be finite and positive") + if not isfinite(float(height)) or float(height) <= 0.0: + raise ValueError("mesh height must be finite and positive") + normalized_mesh = { + "nx": int(nx), + "ny": int(ny), + "width": float(width), + "height": float(height), + } + object.__setattr__(self, "mesh", MappingProxyType(normalized_mesh)) + normalized_diagnostics: dict[str, int | float | None] = {} + for name, value in self.diagnostics.items(): + if value is not None and ( + isinstance(value, bool) or not isinstance(value, Real) + ): + raise TypeError(f"diagnostic {name} must be a number or None") + if value is not None and not isfinite(float(value)): + raise ValueError(f"diagnostic {name} must be finite") + normalized_diagnostics[name] = ( + int(value) + if isinstance(value, Integral) + else (None if value is None else float(value)) + ) + object.__setattr__( + self, "diagnostics", MappingProxyType(normalized_diagnostics) + ) + shapes = { + "x_cell_centers": (nx,), + "y_cell_centers": (ny,), + "pressure": (ny, nx), + "u_faces": (ny, nx + 1), + "v_faces": (ny + 1, nx), + } + for name, shape in shapes.items(): + values = np.ascontiguousarray(getattr(self, name), dtype=np.float64) + if values.shape != shape: + raise ValueError(f"{name} must have shape {shape}") + if not np.all(np.isfinite(values)): + raise ValueError(f"{name} must contain only finite values") + values = np.frombuffer(values.tobytes(), dtype=np.float64).reshape(shape) + object.__setattr__(self, name, values) + + diagnostic_step = self.diagnostics.get("step", self.step) + if ( + isinstance(diagnostic_step, bool) + or not isinstance(diagnostic_step, Integral) + or diagnostic_step != self.step + ): + raise ValueError("diagnostics step must match snapshot step") + + @classmethod + def from_solver_step( + cls, run_id: str, diagnostics: object, velocity: object, pressure: object + ) -> StepSnapshot: + """Adapt solver observer objects at the one-way integration boundary.""" + if not is_dataclass(diagnostics): + raise TypeError("diagnostics must be a dataclass instance") + diagnostic_values = { + item.name: getattr(diagnostics, item.name) for item in fields(diagnostics) + } + mesh_object = getattr(velocity, "mesh", None) + if mesh_object is None: + raise TypeError("velocity snapshot must provide a mesh") + mesh = { + "nx": int(mesh_object.nx), + "ny": int(mesh_object.ny), + "width": float(mesh_object.width), + "height": float(mesh_object.height), + } + return cls( + run_id=run_id, + step=int(diagnostic_values["step"]), + mesh=mesh, + diagnostics=diagnostic_values, + x_cell_centers=mesh_object.x_cell_centers, + y_cell_centers=mesh_object.y_cell_centers, + pressure=pressure.values, + u_faces=velocity.u.values, + v_faces=velocity.v.values, + ) + + def to_bytes(self) -> bytes: + """Serialize one versioned snapshot without pickle or solver imports.""" + metadata = { + "format_version": 1, + "run_id": self.run_id, + "step": self.step, + "mesh": dict(self.mesh), + "diagnostics": dict(self.diagnostics), + } + buffer = BytesIO() + np.savez_compressed( + buffer, + metadata=np.asarray(json.dumps(metadata, allow_nan=False)), + x_cell_centers=self.x_cell_centers, + y_cell_centers=self.y_cell_centers, + pressure=self.pressure, + u_faces=self.u_faces, + v_faces=self.v_faces, + ) + return buffer.getvalue() + + @classmethod + def from_bytes(cls, payload: bytes) -> StepSnapshot: + """Decode a snapshot and validate its schema and array dimensions.""" + with np.load(BytesIO(payload), allow_pickle=False) as archive: + metadata = json.loads(str(archive["metadata"].item())) + if metadata.get("format_version") != 1: + raise ValueError("unsupported snapshot format version") + return cls( + run_id=metadata["run_id"], + step=metadata["step"], + mesh=metadata["mesh"], + diagnostics=metadata["diagnostics"], + x_cell_centers=archive["x_cell_centers"], + y_cell_centers=archive["y_cell_centers"], + pressure=archive["pressure"], + u_faces=archive["u_faces"], + v_faces=archive["v_faces"], + ) diff --git a/Exp_solver_dev_tr/src/fvm/externalization/snapshot_service.proto b/Exp_solver_dev_tr/src/fvm/externalization/snapshot_service.proto new file mode 100644 index 0000000000000..6067df8b0d7c2 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/snapshot_service.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package fvm.externalization.v1; + +import "google/protobuf/wrappers.proto"; + +service SnapshotService { + rpc Publish(stream google.protobuf.BytesValue) + returns (google.protobuf.BytesValue); +} diff --git a/Exp_solver_dev_tr/src/fvm/externalization/store.py b/Exp_solver_dev_tr/src/fvm/externalization/store.py new file mode 100644 index 0000000000000..a9eb5d5e9581d --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/store.py @@ -0,0 +1,216 @@ +"""Atomic, replayable local snapshot storage used by every transport strategy.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import tempfile +from collections.abc import Iterator +from numbers import Integral +from time import sleep + +from .model import StepSnapshot, validate_run_id + + +class SnapshotStore: + """Persist snapshots as atomically committed, independently readable files.""" + + def __init__(self, directory: str | Path, run_id: str | None = None) -> None: + self.directory = Path(directory) + self.run_id = None if run_id is None else validate_run_id(run_id) + + def write(self, snapshot: StepSnapshot) -> int: + """Atomically write a snapshot and return the committed byte count.""" + if not isinstance(snapshot, StepSnapshot): + raise TypeError("snapshot must be a StepSnapshot") + if self.run_id is not None and snapshot.run_id != self.run_id: + raise ValueError("snapshot run_id does not match this store") + run_directory = self.directory / snapshot.run_id + run_directory.mkdir(parents=True, exist_ok=True) + target = run_directory / f"step_{snapshot.step:08d}.npz" + manifest_path = run_directory / "latest.json" + previous_manifest = self._read_manifest(snapshot.run_id) + previous_latest = ( + previous_manifest["latest_step"] + if previous_manifest is not None + else snapshot.step + ) + if previous_manifest is not None and snapshot.step < previous_latest: + raise ValueError("snapshot steps must be written in increasing order") + payload = snapshot.to_bytes() + self._atomic_write(target, payload) + manifest = { + "format_version": 1, + "run_id": snapshot.run_id, + "first_step": min( + snapshot.step, + previous_manifest["first_step"] + if previous_manifest is not None + else snapshot.step, + ), + "latest_step": max(snapshot.step, previous_latest), + } + self._atomic_write( + manifest_path, + json.dumps(manifest, allow_nan=False).encode("utf-8"), + ) + return len(payload) + + @staticmethod + def _atomic_write(target: Path, payload: bytes) -> None: + file_descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{target.name}.", suffix=".tmp", dir=target.parent + ) + try: + with os.fdopen(file_descriptor, "wb") as temporary_file: + temporary_file.write(payload) + temporary_file.flush() + os.fsync(temporary_file.fileno()) + os.replace(temporary_name, target) + except OSError: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass + raise + + def read(self, step: int, run_id: str | None = None) -> StepSnapshot: + """Read one complete committed step.""" + if isinstance(step, bool) or not isinstance(step, Integral) or step <= 0: + raise ValueError("step must be a positive integer") + step = int(step) + selected_run = self.run_id if run_id is None else run_id + if selected_run is None: + matches = [ + candidate + for candidate_run in self.list_run_ids() + for candidate in ( + self.directory / candidate_run / f"step_{step:08d}.npz", + ) + if candidate.exists() + ] + if len(matches) > 1: + raise ValueError("run_id is required when multiple runs contain this step") + if not matches: + raise FileNotFoundError( + self.directory / f"*/step_{step:08d}.npz" + ) + path = matches[0] + else: + validate_run_id(selected_run) + path = self.directory / selected_run / f"step_{step:08d}.npz" + return StepSnapshot.from_bytes(path.read_bytes()) + + def iter_after( + self, step: int = 0, run_id: str | None = None + ) -> Iterator[StepSnapshot]: + """Yield committed snapshots in ascending step order.""" + if isinstance(step, bool) or not isinstance(step, Integral) or step < 0: + raise ValueError("step must be a non-negative integer") + step = int(step) + selected_run = self.run_id if run_id is None else run_id + if selected_run is not None: + validate_run_id(selected_run) + run_ids = (selected_run,) if selected_run is not None else self.list_run_ids() + for current_run in run_ids: + latest = self.latest_step_for(current_run) + first = self.first_step_for(current_run) + run_directory = self.directory / current_run + step_numbers = sorted( + int(path.stem[5:]) + for path in run_directory.glob("step_*.npz") + if path.stem[5:].isdecimal() + ) + for current_step in step_numbers: + if current_step < max(step + 1, first) or current_step > latest: + continue + yield self.read(current_step, current_run) + + def iter_after_by_run( + self, last_steps: dict[str, int] + ) -> Iterator[StepSnapshot]: + """Yield new snapshots using an independent cursor for every run.""" + for run_id in self.list_run_ids(): + yield from self.iter_after(last_steps.get(run_id, 0), run_id) + + @property + def latest_step(self) -> int: + """Return the largest committed step, or zero when the store is empty.""" + if self.run_id is not None: + return self.latest_step_for(self.run_id) + return max( + (self.latest_step_for(run_id) for run_id in self.list_run_ids()), + default=0, + ) + + def latest_step_for(self, run_id: str) -> int: + """Return the latest step for one run.""" + manifest = self._read_manifest(run_id) + return 0 if manifest is None else manifest["latest_step"] + + def first_step_for(self, run_id: str) -> int: + """Return the earliest committed step for one run.""" + manifest = self._read_manifest(run_id) + return 0 if manifest is None else manifest["first_step"] + + def _read_manifest(self, run_id: str) -> dict[str, int | str] | None: + validate_run_id(run_id) + manifest_path = self.directory / run_id / "latest.json" + if not manifest_path.exists(): + return None + for attempt in range(3): + try: + manifest_text = manifest_path.read_text(encoding="utf-8") + break + except PermissionError: + if attempt == 2: + raise + sleep(0.01) + manifest = json.loads(manifest_text) + if not isinstance(manifest, dict): + raise ValueError(f"invalid latest snapshot manifest: {manifest_path}") + first_step = manifest.get("first_step") + latest_step = manifest.get("latest_step") + version = manifest.get("format_version") + if ( + isinstance(version, bool) + or not isinstance(version, int) + or version != 1 + or manifest.get("run_id") != run_id + or isinstance(first_step, bool) + or not isinstance(first_step, int) + or first_step <= 0 + or isinstance(latest_step, bool) + or not isinstance(latest_step, int) + or latest_step < first_step + ): + raise ValueError(f"invalid latest snapshot manifest: {manifest_path}") + return manifest + + def list_run_ids(self) -> tuple[str, ...]: + """List run directories that contain at least one committed snapshot.""" + if not self.directory.exists(): + return () + return tuple( + sorted( + path.name + for path in self.directory.iterdir() + if path.is_dir() and (path / "latest.json").is_file() + ) + ) + + @property + def latest_snapshot(self) -> StepSnapshot: + """Read the most recently committed snapshot across this store.""" + run_ids = (self.run_id,) if self.run_id is not None else self.list_run_ids() + candidates = [ + self.directory / run_id / "latest.json" + for run_id in run_ids + if (self.directory / run_id / "latest.json").is_file() + ] + if not candidates: + raise FileNotFoundError(f"snapshot store is empty: {self.directory}") + latest_manifest = max(candidates, key=lambda path: path.stat().st_mtime_ns) + run_id = latest_manifest.parent.name + return self.read(self.latest_step_for(run_id), run_id=run_id) diff --git a/Exp_solver_dev_tr/src/fvm/externalization/strategies.py b/Exp_solver_dev_tr/src/fvm/externalization/strategies.py new file mode 100644 index 0000000000000..0e8a11f9d3bda --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/strategies.py @@ -0,0 +1,288 @@ +"""Local externalization strategies and the solver-observer adapter.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +import queue +import threading +from time import perf_counter +from numbers import Integral +from typing import Protocol + +from .model import StepSnapshot, validate_run_id +from .store import SnapshotStore + + +class Externalizer(Protocol): + """Minimal transport contract consumed by solver integrations.""" + + def publish(self, snapshot: StepSnapshot) -> None: ... + + def close(self) -> None: ... + + +class StepSnapshotObserver: + """Sample completed solver steps and allow an explicit final-step publish.""" + + def __init__( + self, + externalizer: Externalizer, + run_id: str, + snapshot_every: int = 10, + ) -> None: + if ( + isinstance(snapshot_every, bool) + or not isinstance(snapshot_every, Integral) + or snapshot_every <= 0 + ): + raise ValueError("snapshot_every must be a positive integer") + self.externalizer = externalizer + self.run_id = validate_run_id(run_id) + self.snapshot_every = int(snapshot_every) + self._last_published_step = 0 + + def __call__(self, diagnostics: object, velocity: object, pressure: object) -> None: + step = self._step_number(diagnostics) + if step % self.snapshot_every == 0: + self._publish(diagnostics, velocity, pressure) + + def publish_final_step( + self, diagnostics: object, velocity: object, pressure: object + ) -> bool: + """Publish the final state unless that step was already sampled.""" + step = self._step_number(diagnostics) + if step == self._last_published_step: + return False + if step < self._last_published_step: + raise ValueError("final snapshot step precedes the last published step") + self._publish(diagnostics, velocity, pressure) + return True + + @staticmethod + def _step_number(diagnostics: object) -> int: + step = getattr(diagnostics, "step", None) + if ( + isinstance(step, bool) + or not isinstance(step, Integral) + or step <= 0 + ): + raise ValueError("step diagnostics must contain a positive integer step") + return int(step) + + def _publish(self, diagnostics: object, velocity: object, pressure: object) -> None: + snapshot = StepSnapshot.from_solver_step( + self.run_id, diagnostics, velocity, pressure + ) + if snapshot.step <= self._last_published_step: + raise ValueError("snapshots must be published in increasing step order") + self.externalizer.publish(snapshot) + self._last_published_step = snapshot.step + + +@dataclass(slots=True) +class ExternalizationMetrics: + """Timing and volume counters for an externalization session.""" + + snapshots: int = 0 + bytes_written: int = 0 + publish_seconds: float = 0.0 + externalize_seconds: float = 0.0 + _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) + + def record( + self, + byte_count: int, + publish_seconds: float, + externalize_seconds: float, + ) -> None: + with self._lock: + self.snapshots += 1 + self.bytes_written += byte_count + self.publish_seconds += publish_seconds + self.externalize_seconds += externalize_seconds + + def record_publish(self, byte_count: int, elapsed: float) -> None: + with self._lock: + self.snapshots += 1 + self.bytes_written += byte_count + self.publish_seconds += elapsed + + def record_publish_time(self, elapsed: float) -> None: + with self._lock: + self.publish_seconds += elapsed + + def record_externalize(self, byte_count: int, elapsed: float) -> None: + with self._lock: + self.snapshots += 1 + self.bytes_written += byte_count + self.externalize_seconds += elapsed + + def record_externalize_time(self, elapsed: float) -> None: + with self._lock: + self.externalize_seconds += elapsed + + +class SynchronousFileExternalizer: + """Strategy 1: synchronously persist each solver step before continuing.""" + + def __init__(self, directory: str | Path) -> None: + self.store = SnapshotStore(directory) + self.metrics = ExternalizationMetrics() + self._closed = False + + def publish(self, snapshot: StepSnapshot) -> None: + self._ensure_open() + started = perf_counter() + byte_count = self.store.write(snapshot) + elapsed = perf_counter() - started + self.metrics.record(byte_count, elapsed, elapsed) + + def close(self) -> None: + self._closed = True + + def _ensure_open(self) -> None: + if self._closed: + raise RuntimeError("externalizer is closed") + + +class SharedFolderExternalizer: + """Strategy 2 producer: commit snapshots to a shared-folder spool.""" + + def __init__(self, shared_directory: str | Path) -> None: + self.store = SnapshotStore(shared_directory) + self.metrics = ExternalizationMetrics() + self._closed = False + + def publish(self, snapshot: StepSnapshot) -> None: + if self._closed: + raise RuntimeError("externalizer is closed") + started = perf_counter() + byte_count = self.store.write(snapshot) + self.metrics.record_publish(byte_count, perf_counter() - started) + + def close(self) -> None: + self._closed = True + + +class SharedFolderPoller: + """Independent consumer that periodically drains committed shared snapshots.""" + + def __init__( + self, shared_directory: str | Path, external_directory: str | Path + ) -> None: + self.source = SnapshotStore(shared_directory) + self.destination = SnapshotStore(external_directory) + self.last_steps = { + run_id: self.destination.latest_step_for(run_id) + for run_id in self.destination.list_run_ids() + } + self.snapshots = 0 + self.bytes_written = 0 + self.externalize_seconds = 0.0 + + def poll_once(self) -> int: + """Copy every newly committed snapshot; return the number copied.""" + copied = 0 + for snapshot in self.source.iter_after_by_run(self.last_steps): + started = perf_counter() + byte_count = self.destination.write(snapshot) + self.externalize_seconds += perf_counter() - started + self.bytes_written += byte_count + self.snapshots += 1 + self.last_steps[snapshot.run_id] = snapshot.step + copied += 1 + return copied + + def run( + self, + interval_seconds: float, + stop_event: threading.Event | None = None, + ) -> None: + """Poll until stopped; surface storage errors to the caller.""" + if interval_seconds <= 0.0: + raise ValueError("interval_seconds must be positive") + stop = stop_event or threading.Event() + while not stop.is_set(): + self.poll_once() + stop.wait(interval_seconds) + self.poll_once() + + +class AsyncFileExternalizer: + """Strategy 3: bounded in-process queue drained by a dedicated worker.""" + + def __init__(self, directory: str | Path, queue_size: int = 16) -> None: + if isinstance(queue_size, bool) or not isinstance(queue_size, int) or queue_size <= 0: + raise ValueError("queue_size must be a positive integer") + self.store = SnapshotStore(directory) + self.metrics = ExternalizationMetrics() + self._queue: queue.Queue[StepSnapshot | None] = queue.Queue(queue_size) + self._error: Exception | None = None + self._closed = False + self._worker = threading.Thread( + target=self._consume, name="fvm-externalizer", daemon=True + ) + self._worker.start() + + def publish(self, snapshot: StepSnapshot) -> None: + if self._closed: + raise RuntimeError("externalizer is closed") + started = perf_counter() + while True: + self._raise_worker_error() + try: + self._queue.put(snapshot, timeout=0.1) + break + except queue.Full: + continue + self.metrics.record_publish_time(perf_counter() - started) + + def close(self) -> None: + if self._closed: + self._raise_worker_error() + return + self._closed = True + self._enqueue_stop() + self._worker.join() + self._raise_worker_error() + + def _enqueue_stop(self) -> None: + while self._worker.is_alive(): + try: + self._queue.put(None, timeout=0.1) + return + except queue.Full: + continue + + def _consume(self) -> None: + while True: + item = self._queue.get() + try: + if item is None: + return + started = perf_counter() + try: + byte_count = self.store.write(item) + except Exception as error: + if self._error is None: + self._error = error + else: + self.metrics.record_externalize( + byte_count, perf_counter() - started + ) + finally: + self._queue.task_done() + + def _raise_worker_error(self) -> None: + if self._error is not None: + raise RuntimeError( + f"asynchronous externalization failed: {self._error}" + ) from self._error + + +def create_step_observer( + externalizer: Externalizer, run_id: str, snapshot_every: int = 10 +) -> StepSnapshotObserver: + """Sample solver callbacks every N steps; callers may force the final step.""" + return StepSnapshotObserver(externalizer, run_id, snapshot_every) diff --git a/Exp_solver_dev_tr/src/fvm/externalization/visualization.py b/Exp_solver_dev_tr/src/fvm/externalization/visualization.py new file mode 100644 index 0000000000000..d759596bd96c9 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/externalization/visualization.py @@ -0,0 +1,230 @@ +"""Visualization based only on the externalization snapshot contract.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np + +from .model import StepSnapshot +from .store import SnapshotStore + +if TYPE_CHECKING: + from matplotlib.axes import Axes + from matplotlib.figure import Figure + from matplotlib.image import AxesImage + from matplotlib.lines import Line2D + from matplotlib.quiver import Quiver + + +class LiveSnapshotPlotter: + """Update one interactive figure as externalized snapshots arrive.""" + + def __init__(self) -> None: + import matplotlib.pyplot as plt + + self.pyplot = plt + self.pyplot.ion() + self.figure, axes = plt.subplots( + 1, 4, figsize=(17, 4), layout="constrained" + ) + self.figure: Figure + self.speed_axis: Axes + self.pressure_axis: Axes + self.velocity_axis: Axes + self.history_axis: Axes + ( + self.speed_axis, + self.pressure_axis, + self.velocity_axis, + self.history_axis, + ) = axes + self.speed_image: AxesImage | None = None + self.pressure_image: AxesImage | None = None + self.velocity_quiver: Quiver | None = None + self.velocity_line: Line2D + self.divergence_line: Line2D + self.steps: list[int] = [] + self.velocity_changes: list[float] = [] + self.divergences: list[float] = [] + self._mesh: tuple[int, int, float, float] | None = None + self._history_floor = np.finfo(np.float64).tiny + + self.speed_axis.set_title("Velocity magnitude") + self.pressure_axis.set_title("Pressure") + self.velocity_axis.set_title("Cell-centered velocity") + self.history_axis.set_xlabel("Step") + self.history_axis.set_ylabel("Change / residual") + self.history_axis.set_title("Convergence history") + self.velocity_line, = self.history_axis.semilogy( + [], [], label="velocity change" + ) + self.divergence_line, = self.history_axis.semilogy( + [], [], label="max divergence" + ) + self.history_axis.legend() + self.pyplot.show(block=False) + + def update(self, snapshot: StepSnapshot) -> None: + """Append one persisted step to the existing live figure.""" + mesh = snapshot.mesh + mesh_key = ( + int(mesh["nx"]), + int(mesh["ny"]), + float(mesh["width"]), + float(mesh["height"]), + ) + if self._mesh is not None and mesh_key != self._mesh: + raise ValueError("mesh dimensions changed during one live run") + + u_cell = 0.5 * (snapshot.u_faces[:, :-1] + snapshot.u_faces[:, 1:]) + v_cell = 0.5 * (snapshot.v_faces[:-1, :] + snapshot.v_faces[1:, :]) + speed = np.hypot(u_cell, v_cell) + if self.speed_image is None: + extent = (0.0, mesh_key[2], 0.0, mesh_key[3]) + self.speed_image = self.speed_axis.imshow( + speed, + origin="lower", + extent=extent, + interpolation="nearest", + cmap="viridis", + vmin=0.0, + vmax=max(float(np.max(speed)), 1e-12), + ) + self.figure.colorbar( + self.speed_image, ax=self.speed_axis, label="Speed (m/s)" + ) + self.pressure_image = self.pressure_axis.imshow( + snapshot.pressure, + origin="lower", + extent=extent, + interpolation="nearest", + cmap="coolwarm", + ) + self.figure.colorbar( + self.pressure_image, ax=self.pressure_axis, label="Pressure (Pa)" + ) + grid_x, grid_y = np.meshgrid( + snapshot.x_cell_centers, snapshot.y_cell_centers + ) + self.velocity_quiver = self.velocity_axis.quiver( + grid_x, grid_y, u_cell, v_cell, speed, cmap="viridis" + ) + for axis in ( + self.speed_axis, + self.pressure_axis, + self.velocity_axis, + ): + axis.set_xlim(0.0, mesh_key[2]) + axis.set_ylim(0.0, mesh_key[3]) + axis.set_xlabel("x (m)") + axis.set_ylabel("y (m)") + axis.set_aspect("equal") + self._mesh = mesh_key + else: + self.speed_image.set_data(speed) + self.speed_image.set_clim( + vmin=0.0, vmax=max(float(np.max(speed)), 1e-12) + ) + self.pressure_image.set_data(snapshot.pressure) + self.velocity_quiver.set_UVC(u_cell, v_cell, speed) + + velocity_change = snapshot.diagnostics.get("velocity_change") + max_divergence = snapshot.diagnostics.get("max_divergence_after") + if velocity_change is None or max_divergence is None: + raise ValueError( + "live convergence plot requires velocity_change and " + "max_divergence_after diagnostics" + ) + self.steps.append(snapshot.step) + self.velocity_changes.append(float(velocity_change)) + self.divergences.append(float(max_divergence)) + self.velocity_line.set_data( + self.steps, + np.maximum(self.velocity_changes, self._history_floor), + ) + self.divergence_line.set_data( + self.steps, + np.maximum(self.divergences, self._history_floor), + ) + self.history_axis.set_xlim(1, max(snapshot.step, 2)) + self.history_axis.relim() + self.history_axis.autoscale_view(scalex=False) + + time_value = snapshot.diagnostics.get("time") + state = ( + f"t={time_value:.5g} s" + if time_value is not None + else f"iteration {snapshot.step}" + ) + self.figure.suptitle( + f"Run {snapshot.run_id}, step {snapshot.step} ({state})" + ) + self.figure.canvas.draw_idle() + self.pyplot.pause(0.001) + + def finish(self) -> None: + """Keep the final live view open until the user closes it.""" + self.pyplot.ioff() + self.pyplot.show(block=True) + + def wait_for_events(self, interval_seconds: float) -> None: + """Keep the plot responsive while waiting for another snapshot.""" + self.pyplot.pause(interval_seconds) + + def close(self) -> None: + """Close the interactive figure.""" + self.pyplot.close(self.figure) + + +def plot_snapshot( + snapshot: StepSnapshot, output_path: str | Path | None = None +) -> object: + """Render a persisted solver step without importing solver result classes.""" + import matplotlib.pyplot as plt + + mesh = snapshot.mesh + u_cell = 0.5 * (snapshot.u_faces[:, :-1] + snapshot.u_faces[:, 1:]) + v_cell = 0.5 * (snapshot.v_faces[:-1, :] + snapshot.v_faces[1:, :]) + speed = np.hypot(u_cell, v_cell) + x, y = snapshot.x_cell_centers, snapshot.y_cell_centers + figure, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained") + + speed_image = axes[0].pcolormesh(x, y, speed, shading="nearest", cmap="viridis") + figure.colorbar(speed_image, ax=axes[0], label="Speed (m/s)") + axes[0].set_title("Velocity magnitude") + + pressure_image = axes[1].pcolormesh( + x, y, snapshot.pressure, shading="nearest", cmap="coolwarm" + ) + figure.colorbar(pressure_image, ax=axes[1], label="Pressure (Pa)") + axes[1].set_title("Pressure") + + axes[2].quiver(x, y, u_cell, v_cell, speed, cmap="viridis") + axes[2].set_title("Cell-centered velocity") + for axis in axes: + axis.set_xlabel("x (m)") + axis.set_ylabel("y (m)") + axis.set_xlim(0.0, float(mesh["width"])) + axis.set_ylim(0.0, float(mesh["height"])) + axis.set_aspect("equal") + time_value = snapshot.diagnostics.get("time") + state = ( + f"t={time_value:.5g} s" + if time_value is not None + else f"iteration {snapshot.step}" + ) + figure.suptitle(f"Run {snapshot.run_id}, step {snapshot.step} ({state})") + if output_path is not None: + output = Path(output_path) + output.parent.mkdir(parents=True, exist_ok=True) + figure.savefig(output, dpi=160, bbox_inches="tight") + return figure + + +def plot_latest_snapshot( + store: SnapshotStore, output_path: str | Path | None = None +) -> object: + """Load the newest committed step from a store and render it.""" + return plot_snapshot(store.latest_snapshot, output_path) diff --git a/Exp_solver_dev_tr/src/fvm/fields.py b/Exp_solver_dev_tr/src/fvm/fields.py new file mode 100644 index 0000000000000..e0630540b772f --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/fields.py @@ -0,0 +1,84 @@ +"""Scalar and vector field storage on the staggered Cartesian mesh.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from math import isfinite +from numbers import Real + +import numpy as np +from numpy.typing import ArrayLike + +from .mesh import CartesianMesh, FloatArray + + +def _as_finite_array(values: ArrayLike, shape: tuple[int, int], name: str) -> FloatArray: + """Copy numeric values into a finite float array of the requested shape.""" + try: + array = np.asarray(values, dtype=np.float64) + except (TypeError, ValueError) as error: + raise TypeError(f"{name} values must be numeric") from error + if array.shape != shape: + raise ValueError(f"{name} values must have shape {shape}, got {array.shape}") + if not np.all(np.isfinite(array)): + raise ValueError(f"{name} values must all be finite") + return array.copy() + + +@dataclass(slots=True) +class ScalarField: + """A named scalar array located at cell centers or one face orientation.""" + + mesh: CartesianMesh + name: str + location: str = "cell_center" + initial_value: float = 0.0 + values: FloatArray = field(init=False, repr=False) + + def __post_init__(self) -> None: + if not isinstance(self.name, str) or not self.name.strip(): + raise ValueError("field name must be a non-empty string") + shape = self.mesh.shape_for_location(self.location) + if isinstance(self.initial_value, bool) or not isinstance(self.initial_value, Real): + raise TypeError("initial_value must be a finite number") + if not isfinite(self.initial_value): + raise ValueError("initial_value must be a finite number") + self.initial_value = float(self.initial_value) + self.values = np.full(shape, self.initial_value, dtype=np.float64) + + def set_values(self, values: ArrayLike) -> None: + """Replace field contents after checking shape, numeric type, and finiteness.""" + self.values = _as_finite_array(values, self.values.shape, self.name) + + +@dataclass(slots=True) +class VectorField: + """A 2D vector field with x/y components on their MAC face locations.""" + + mesh: CartesianMesh + name: str = "velocity" + initial_value: tuple[float, float] = (0.0, 0.0) + u: ScalarField = field(init=False) + v: ScalarField = field(init=False) + + def __post_init__(self) -> None: + if not isinstance(self.name, str) or not self.name.strip(): + raise ValueError("field name must be a non-empty string") + if len(self.initial_value) != 2: + raise ValueError("initial_value must contain x and y components") + components = tuple(self.initial_value) + if any( + isinstance(value, bool) or not isinstance(value, Real) or not isfinite(value) + for value in components + ): + raise ValueError("initial velocity components must be finite numbers") + self.initial_value = (float(components[0]), float(components[1])) + self.u = ScalarField(self.mesh, f"{self.name}.u", "x_face", self.initial_value[0]) + self.v = ScalarField(self.mesh, f"{self.name}.v", "y_face", self.initial_value[1]) + + def set_values(self, u_values: ArrayLike, v_values: ArrayLike) -> None: + """Replace both components, validating both before changing either one.""" + new_u = _as_finite_array(u_values, self.u.values.shape, self.u.name) + new_v = _as_finite_array(v_values, self.v.values.shape, self.v.name) + self.u.values = new_u + self.v.values = new_v \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/integration.py b/Exp_solver_dev_tr/src/fvm/integration.py new file mode 100644 index 0000000000000..fb0cc0b6c46ab --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/integration.py @@ -0,0 +1,307 @@ +"""Adapter between setup-software case documents and the Python FVM backend.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from numbers import Integral +from typing import Mapping + +import numpy as np + +from .boundary_conditions import BoundaryConditions, MovingWall, NoSlipWall +from .checkpoint import CheckpointManager +from .case_definition import CaseDefinition, CaseDocument, load_case_file, parse_case_definition +from .fields import ScalarField, VectorField +from .mesh import BOUNDARY_NAMES, CartesianMesh +from .postprocessing import velocity_extrema +from .simulation import SimulationResult, SimulationState, StepObserver, TransientSolver + + +@dataclass(frozen=True, slots=True) +class PreparedCase: + """Solver-owned objects translated from a framework-neutral definition.""" + + definition: CaseDefinition + mesh: CartesianMesh + initial_velocity: VectorField + initial_pressure: ScalarField + boundary_conditions: BoundaryConditions + solver: TransientSolver + + +@dataclass(frozen=True, slots=True) +class BackendRun: + """Simulation output returned to a caller, with a JSON-compatible summary.""" + + case_id: str + simulation: SimulationResult + summary: dict[str, object] + artifact_directory: Path | None + + +class PythonFVMBackend: + """Prepare and execute the capabilities described by a v1 case document. + + The setup framework only needs to emit the documented JSON contract (or a + mapping with the same keys). This adapter performs no framework imports; + unsupported models and boundary types are rejected by the case validator. + """ + + backend_id = "independent-fvm-python" + supported_schema_version = "1.0" + + def prepare(self, case: CaseDefinition | CaseDocument) -> PreparedCase: + """Translate validated case data to mesh, fields, BCs, and solver.""" + definition = case if isinstance(case, CaseDefinition) else parse_case_definition(case) + if definition.schema_version != self.supported_schema_version: + raise ValueError(f"unsupported schema version: {definition.schema_version}") + + mesh = CartesianMesh( + nx=definition.nx, + ny=definition.ny, + width=definition.width, + height=definition.height, + ) + velocity = VectorField( + mesh, + name="velocity", + initial_value=(definition.initial_u, definition.initial_v), + ) + pressure = ScalarField( + mesh, + name="pressure", + initial_value=definition.initial_pressure, + ) + boundaries = _case_boundary_conditions(definition, 0.0) + solver = TransientSolver( + density=definition.density, + viscosity=definition.dynamic_viscosity, + transient=definition.transient, + **definition.solver.to_solver_kwargs(), + ) + return PreparedCase(definition, mesh, velocity, pressure, boundaries, solver) + + def run( + self, + case: CaseDefinition | CaseDocument, + output_directory: str | Path | None = None, + *, + step_observer: StepObserver | None = None, + checkpoint_every: int | None = None, + restart: str | Path | None = None, + retain_checkpoints: int = 5, + ) -> BackendRun: + """Run a case and optionally checkpoint or resume from a run workspace.""" + prepared = self.prepare(case) + output_path = None if output_directory is None else Path(output_directory) + if checkpoint_every is not None and ( + isinstance(checkpoint_every, bool) + or not isinstance(checkpoint_every, Integral) + or checkpoint_every <= 0 + ): + raise ValueError("checkpoint_every must be a positive integer") + if (checkpoint_every is not None or restart is not None) and output_path is None: + raise ValueError("checkpointing and restart require output_directory") + if restart is not None and checkpoint_every is None: + raise ValueError("restart requires checkpoint_every to continue periodic saves") + + checkpoint_manager = ( + CheckpointManager(output_path / "checkpoints", retain_checkpoints) + if output_path is not None and checkpoint_every is not None + else None + ) + case_document = prepared.definition.to_mapping() + restart_state = ( + checkpoint_manager.load(restart, case_document, prepared.mesh) + if checkpoint_manager is not None and restart is not None + else None + ) + if output_path is not None: + output_path.mkdir(parents=True, exist_ok=True) + with (output_path / "case.json").open("w", encoding="utf-8") as case_file: + json.dump(case_document, case_file, indent=2) + + last_checkpoint_step = restart_state.completed_steps if restart_state else 0 + + def checkpoint_state(state: SimulationState) -> None: + nonlocal last_checkpoint_step + if ( + checkpoint_manager is not None + and checkpoint_every is not None + and state.completed_steps % checkpoint_every == 0 + ): + checkpoint_manager.save(state, case_document) + last_checkpoint_step = state.completed_steps + + simulation = prepared.solver.run( + prepared.initial_velocity, + prepared.initial_pressure, + prepared.boundary_conditions, + step_observer=step_observer, + state_observer=(checkpoint_state if checkpoint_manager is not None else None), + state_observer_interval=checkpoint_every or 1, + restart_state=restart_state, + boundary_conditions_at_time=( + lambda time: _case_boundary_conditions(prepared.definition, time) + ), + boundary_conditions_over_interval=( + lambda start, end: _case_boundary_conditions( + prepared.definition, end, interval=(start, end) + ) + ), + ) + if ( + checkpoint_manager is not None + and simulation.history + and simulation.termination_reason != "time_step_not_converged" + ): + final_step = simulation.history[-1].step + if final_step > last_checkpoint_step: + final_diagnostics = simulation.history[-1] + final_velocity = VectorField(simulation.velocity.mesh, name="velocity") + final_velocity.set_values( + simulation.velocity.u.values, simulation.velocity.v.values + ) + final_pressure = ScalarField( + simulation.pressure.mesh, name="pressure" + ) + final_pressure.set_values(simulation.pressure.values) + final_state = SimulationState( + velocity=final_velocity, + pressure=final_pressure, + completed_steps=final_step, + elapsed_time=final_diagnostics.time or 0.0, + pseudo_time=final_diagnostics.pseudo_time or 0.0, + steady_time_step=( + simulation.history[0].time_step + if not prepared.definition.transient + else None + ), + history=simulation.history, + ) + checkpoint_manager.save(final_state, case_document) + summary = self._result_summary(prepared.definition, simulation) + if restart_state is not None: + summary["restarted_from_step"] = restart_state.completed_steps + artifact_path: Path | None = None + if output_path is not None: + from .postprocessing import export_simulation_result + + artifact_path = export_simulation_result(simulation, output_path) + with (artifact_path / "summary.json").open("w", encoding="utf-8") as summary_file: + json.dump(summary, summary_file, indent=2) + return BackendRun( + case_id=prepared.definition.case_id, + simulation=simulation, + summary=summary, + artifact_directory=artifact_path, + ) + + def run_file( + self, + path: str | Path, + output_directory: str | Path | None = None, + *, + step_observer: StepObserver | None = None, + checkpoint_every: int | None = None, + restart: str | Path | None = None, + retain_checkpoints: int = 5, + ) -> BackendRun: + """Load a JSON case file, execute it, and optionally export artifacts.""" + return self.run( + load_case_file(path), + output_directory, + step_observer=step_observer, + checkpoint_every=checkpoint_every, + restart=restart, + retain_checkpoints=retain_checkpoints, + ) + + def _result_summary( + self, definition: CaseDefinition, simulation: SimulationResult + ) -> dict[str, object]: + """Create a unit-labeled, stable summary suitable for setup software.""" + extrema = velocity_extrema(simulation.velocity) + lid_speed = max( + float(np.hypot(*velocity)) + for side in BOUNDARY_NAMES + for velocity in ( + definition.boundary_for(side).velocity_profile + and tuple( + point_velocity + for _, point_velocity in definition.boundary_for(side).velocity_profile + ) + or (definition.boundary_for(side).velocity,) + ) + ) + reynolds_number = ( + definition.density * lid_speed * definition.width / definition.dynamic_viscosity + ) + summary: dict[str, object] = { + "result_format_version": "1.0", + "backend": self.backend_id, + "case_id": definition.case_id, + "schema_version": definition.schema_version, + "status": "converged" if simulation.converged else "not_converged", + "converged": simulation.converged, + "termination_reason": simulation.termination_reason, + "temporal_mode": "transient" if definition.transient else "steady", + "steps": simulation.steps, + "final_time_s": simulation.final_time, + "final_pseudo_time_s": simulation.final_pseudo_time, + "mesh": { + "nx": definition.nx, + "ny": definition.ny, + "width_m": definition.width, + "height_m": definition.height, + }, + "reynolds_number": reynolds_number, + "velocity_extrema": { + "u_min_m_s": extrema.u.minimum, + "u_min_location_m": list(extrema.u.minimum_location), + "u_max_m_s": extrema.u.maximum, + "u_max_location_m": list(extrema.u.maximum_location), + "v_min_m_s": extrema.v.minimum, + "v_min_location_m": list(extrema.v.minimum_location), + "v_max_m_s": extrema.v.maximum, + "v_max_location_m": list(extrema.v.maximum_location), + "speed_max_m_s": extrema.maximum_speed, + "speed_max_location_m": list(extrema.maximum_speed_location), + }, + } + if simulation.history: + last_step = simulation.history[-1] + summary["conservation"] = { + "max_divergence_s_inv": last_step.max_divergence_after, + "global_mass_imbalance_m2_s": last_step.global_mass_imbalance, + } + summary["residuals"] = { + "u_momentum": last_step.u_momentum_residual, + "v_momentum": last_step.v_momentum_residual, + "pressure": last_step.pressure_residual, + } + return summary + + +def _case_boundary_conditions( + definition: CaseDefinition, + time: float, + *, + interval: tuple[float, float] | None = None, +) -> BoundaryConditions: + """Materialize the case wall schedule at a time or its interval maximum.""" + boundaries = BoundaryConditions() + for side in BOUNDARY_NAMES: + wall = definition.boundary_for(side) + if wall.boundary_type != "moving_wall": + boundaries.set("velocity", side, NoSlipWall()) + else: + velocity = ( + wall.maximum_velocity_between(*interval) + if interval is not None + else wall.velocity_at(time) + ) + boundaries.set("velocity", side, MovingWall(velocity)) + return boundaries \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/mesh.py b/Exp_solver_dev_tr/src/fvm/mesh.py new file mode 100644 index 0000000000000..ee08c41d6f084 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/mesh.py @@ -0,0 +1,174 @@ +"""Uniform Cartesian mesh geometry for a two-dimensional MAC grid.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Integral, Real +from types import MappingProxyType +from typing import Mapping + +import numpy as np +from numpy.typing import NDArray + +FloatArray = NDArray[np.float64] +IndexArray = NDArray[np.intp] +BOUNDARY_NAMES = ("west", "east", "south", "north") + + +@dataclass(frozen=True, slots=True) +class CartesianMesh: + """Uniform rectangular mesh with cell-centered pressure and MAC faces. + + Coordinates are exposed as one-dimensional axes and as `(x, y)` arrays. + Array rows increase from south to north; columns increase from west to east. + In two dimensions, ``cell_area`` is the cell volume per unit depth. + """ + + nx: int + ny: int + width: float = 1.0 + height: float = 1.0 + + def __post_init__(self) -> None: + for name in ("nx", "ny"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Integral): + raise TypeError(f"{name} must be a positive integer") + if value <= 0: + raise ValueError(f"{name} must be a positive integer") + object.__setattr__(self, name, int(value)) + + for name in ("width", "height"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0: + raise ValueError(f"{name} must be a finite positive number") + object.__setattr__(self, name, float(value)) + + @property + def dx(self) -> float: + """Uniform cell width.""" + return self.width / self.nx + + @property + def dy(self) -> float: + """Uniform cell height.""" + return self.height / self.ny + + @property + def x_face_centers(self) -> FloatArray: + """X coordinates of vertical faces, including both side walls.""" + return np.linspace(0.0, self.width, self.nx + 1, dtype=np.float64) + + @property + def y_face_centers(self) -> FloatArray: + """Y coordinates of horizontal faces, including both side walls.""" + return np.linspace(0.0, self.height, self.ny + 1, dtype=np.float64) + + @property + def x_cell_centers(self) -> FloatArray: + """X coordinates of cell centers.""" + return (np.arange(self.nx, dtype=np.float64) + 0.5) * self.dx + + @property + def y_cell_centers(self) -> FloatArray: + """Y coordinates of cell centers.""" + return (np.arange(self.ny, dtype=np.float64) + 0.5) * self.dy + + @property + def cell_center_coordinates(self) -> tuple[FloatArray, FloatArray]: + """Return `(x, y)` coordinate arrays, each with shape `(ny, nx)`.""" + return np.meshgrid(self.x_cell_centers, self.y_cell_centers, indexing="xy") + + @property + def u_face_coordinates(self) -> tuple[FloatArray, FloatArray]: + """Return `(x, y)` coordinates for u locations, shape `(ny, nx + 1)`.""" + return np.meshgrid(self.x_face_centers, self.y_cell_centers, indexing="xy") + + @property + def v_face_coordinates(self) -> tuple[FloatArray, FloatArray]: + """Return `(x, y)` coordinates for v locations, shape `(ny + 1, nx)`.""" + return np.meshgrid(self.x_cell_centers, self.y_face_centers, indexing="xy") + + @property + def cell_area(self) -> float: + """Area of one cell (volume per unit depth).""" + return self.dx * self.dy + + @property + def u_face_area(self) -> float: + """Area per unit depth of a vertical face.""" + return self.dy + + @property + def v_face_area(self) -> float: + """Area per unit depth of a horizontal face.""" + return self.dx + + @property + def cell_areas(self) -> FloatArray: + """Cell areas as an array with shape `(ny, nx)`.""" + return np.full((self.ny, self.nx), self.cell_area, dtype=np.float64) + + @property + def u_face_areas(self) -> FloatArray: + """Vertical-face areas as an array with shape `(ny, nx + 1)`.""" + return np.full((self.ny, self.nx + 1), self.u_face_area, dtype=np.float64) + + @property + def v_face_areas(self) -> FloatArray: + """Horizontal-face areas as an array with shape `(ny + 1, nx)`.""" + return np.full((self.ny + 1, self.nx), self.v_face_area, dtype=np.float64) + + @property + def boundary_face_indices(self) -> Mapping[str, tuple[IndexArray, IndexArray]]: + """Return `(row_indices, column_indices)` for each boundary's normal faces. + + West/east indices address the u array; south/north indices address v. + Each call returns new index arrays so callers cannot mutate mesh state. + """ + rows = np.arange(self.ny, dtype=np.intp) + columns = np.arange(self.nx, dtype=np.intp) + return MappingProxyType( + { + "west": (rows.copy(), np.zeros(self.ny, dtype=np.intp)), + "east": (rows.copy(), np.full(self.ny, self.nx, dtype=np.intp)), + "south": (np.zeros(self.nx, dtype=np.intp), columns.copy()), + "north": (np.full(self.nx, self.ny, dtype=np.intp), columns.copy()), + } + ) + + @property + def boundary_face_counts(self) -> Mapping[str, int]: + """Number of geometric faces on each side of the mesh.""" + return MappingProxyType( + {"west": self.ny, "east": self.ny, "south": self.nx, "north": self.nx} + ) + + @property + def boundary_face_normals(self) -> Mapping[str, tuple[float, float]]: + """Outward unit normals for west, east, south, and north boundaries.""" + return MappingProxyType( + { + "west": (-1.0, 0.0), + "east": (1.0, 0.0), + "south": (0.0, -1.0), + "north": (0.0, 1.0), + } + ) + + def shape_for_location(self, location: str) -> tuple[int, int]: + """Return the array shape for a cell-center, x-face, or y-face field.""" + shapes = { + "cell_center": (self.ny, self.nx), + "x_face": (self.ny, self.nx + 1), + "y_face": (self.ny + 1, self.nx), + } + try: + return shapes[location] + except KeyError as error: + raise ValueError( + "location must be 'cell_center', 'x_face', or 'y_face'" + ) from error \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/momentum.py b/Exp_solver_dev_tr/src/fvm/momentum.py new file mode 100644 index 0000000000000..a73dcbb938521 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/momentum.py @@ -0,0 +1,475 @@ +"""Sparse staggered-grid momentum prediction for a transient projection step.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Real + +import numpy as np +from scipy.sparse import coo_matrix, csr_matrix +from scipy.sparse.linalg import spsolve + +from .boundary_conditions import ( + BoundaryConditions, + FixedValue, + MovingWall, + NoSlipWall, +) +from .fields import ScalarField, VectorField +from .mesh import BOUNDARY_NAMES, CartesianMesh, FloatArray +from .operators import face_gradient + +WallVelocities = dict[str, tuple[float, float]] + + +@dataclass(frozen=True, slots=True) +class MomentumAssembly: + """Two sparse component systems and terms used to construct their RHS. + + Boundary-aligned normal velocity faces are stored in ``fixed_u`` and + ``fixed_v``. The matrix unknowns are only the interior component values: + ``u`` has shape `(ny, nx - 1)` and ``v`` has shape `(ny - 1, nx)`. + Keeping the convection and pressure-gradient terms here makes each + assembled equation inspectable in tests and during debugging. + """ + + mesh: CartesianMesh + u_matrix: csr_matrix + u_rhs: FloatArray + v_matrix: csr_matrix + v_rhs: FloatArray + u_unknown_shape: tuple[int, int] + v_unknown_shape: tuple[int, int] + fixed_u: FloatArray + fixed_v: FloatArray + u_convection: FloatArray + v_convection: FloatArray + u_pressure_gradient: FloatArray + v_pressure_gradient: FloatArray + + +@dataclass(frozen=True, slots=True) +class MomentumPrediction: + """Predicted face velocities and normalized linear-system residuals.""" + + velocity: VectorField + u_relative_residual: float + v_relative_residual: float + + +def _validate_positive_parameter(name: str, value: float, allow_zero: bool = False) -> float: + """Validate and normalize a finite positive physical/solver parameter.""" + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite number") + if not isfinite(value) or value < 0.0 or (value == 0.0 and not allow_zero): + qualifier = "non-negative" if allow_zero else "positive" + raise ValueError(f"{name} must be finite and {qualifier}") + return float(value) + + +def _wall_velocities(boundary_conditions: BoundaryConditions) -> WallVelocities: + """Get a two-component prescribed velocity for every physical wall.""" + if not isinstance(boundary_conditions, BoundaryConditions): + raise TypeError("boundary_conditions must be BoundaryConditions") + + wall_values: WallVelocities = {} + for side in BOUNDARY_NAMES: + try: + condition = boundary_conditions.get("velocity", side) + except KeyError as error: + raise ValueError(f"missing velocity boundary condition for {side}") from error + + if isinstance(condition, (NoSlipWall, MovingWall)): + wall_values[side] = condition.velocity + elif isinstance(condition, FixedValue) and isinstance(condition.value, tuple): + wall_values[side] = condition.value + else: + raise ValueError( + f"velocity boundary {side} must prescribe both velocity components" + ) + return wall_values + + +def _staggered_upwind_convection( + u: FloatArray, + v: FloatArray, + walls: WallVelocities, + mesh: CartesianMesh, +) -> tuple[FloatArray, FloatArray]: + """Compute conservative upwind advection on u/v control volumes. + + Advecting velocities at the cross-component locations are linearly + interpolated. The transported component uses first-order upwind values; + tangential wall velocities supply its boundary-face values. + """ + u_adv_x = 0.5 * (u[:, :-1] + u[:, 1:]) + u_at_x_faces = np.where(u_adv_x >= 0.0, u[:, :-1], u[:, 1:]) + u_flux_x = u_adv_x * u_at_x_faces + + v_adv_at_u_y_faces = 0.5 * (v[:, :-1] + v[:, 1:]) + u_at_y_faces = np.empty((mesh.ny + 1, mesh.nx - 1), dtype=np.float64) + u_at_y_faces[1:-1, :] = np.where( + v_adv_at_u_y_faces[1:-1, :] >= 0.0, + u[:-1, 1:-1], + u[1:, 1:-1], + ) + u_at_y_faces[0, :] = np.where( + v_adv_at_u_y_faces[0, :] >= 0.0, walls["south"][0], u[0, 1:-1] + ) + u_at_y_faces[-1, :] = np.where( + v_adv_at_u_y_faces[-1, :] >= 0.0, u[-1, 1:-1], walls["north"][0] + ) + u_flux_y = v_adv_at_u_y_faces * u_at_y_faces + u_convection = ( + (u_flux_x[:, 1:] - u_flux_x[:, :-1]) * mesh.u_face_area + + (u_flux_y[1:, :] - u_flux_y[:-1, :]) * mesh.v_face_area + ) / mesh.cell_area + + v_adv_y = 0.5 * (v[:-1, :] + v[1:, :]) + v_at_y_faces = np.where(v_adv_y >= 0.0, v[:-1, :], v[1:, :]) + v_flux_y = v_adv_y * v_at_y_faces + + u_adv_at_v_x_faces = 0.5 * (u[:-1, :] + u[1:, :]) + v_at_x_faces = np.empty((mesh.ny - 1, mesh.nx + 1), dtype=np.float64) + v_at_x_faces[:, 1:-1] = np.where( + u_adv_at_v_x_faces[:, 1:-1] >= 0.0, + v[1:-1, :-1], + v[1:-1, 1:], + ) + v_at_x_faces[:, 0] = np.where( + u_adv_at_v_x_faces[:, 0] >= 0.0, walls["west"][1], v[1:-1, 0] + ) + v_at_x_faces[:, -1] = np.where( + u_adv_at_v_x_faces[:, -1] >= 0.0, v[1:-1, -1], walls["east"][1] + ) + v_flux_x = u_adv_at_v_x_faces * v_at_x_faces + v_convection = ( + (v_flux_x[:, 1:] - v_flux_x[:, :-1]) * mesh.u_face_area + + (v_flux_y[1:, :] - v_flux_y[:-1, :]) * mesh.v_face_area + ) / mesh.cell_area + return u_convection, v_convection + + +def _build_u_matrix( + mesh: CartesianMesh, + old_u: FloatArray, + fixed_u: FloatArray, + convection: FloatArray, + pressure_gradient: FloatArray, + walls: WallVelocities, + density: float, + viscosity: float, + time_step: float, +) -> tuple[csr_matrix, FloatArray, tuple[int, int]]: + """Assemble `rho/dt - mu*laplacian` for interior u control volumes.""" + unknown_shape = (mesh.ny, mesh.nx - 1) + unknown_count = unknown_shape[0] * unknown_shape[1] + storage = density / time_step + x_diffusion = viscosity / mesh.dx**2 + y_diffusion = viscosity / mesh.dy**2 + rows: list[int] = [] + columns: list[int] = [] + coefficients: list[float] = [] + rhs = np.empty(unknown_count, dtype=np.float64) + + for row_index in range(mesh.ny): + for face_index in range(1, mesh.nx): + row = row_index * (mesh.nx - 1) + face_index - 1 + diagonal = storage + rhs[row] = ( + storage * old_u[row_index, face_index] + - density * convection[row_index, face_index - 1] + - pressure_gradient[row_index, face_index - 1] + ) + + def connect(neighbor: int | None, weight: float, boundary_value: float = 0.0) -> None: + nonlocal diagonal + if weight == 0.0: + return + diagonal += weight + if neighbor is None: + rhs[row] += weight * boundary_value + else: + rows.append(row) + columns.append(neighbor) + coefficients.append(-weight) + + west = ( + row_index * (mesh.nx - 1) + face_index - 2 + if face_index > 1 + else None + ) + connect(west, x_diffusion, fixed_u[row_index, 0]) + east = ( + row_index * (mesh.nx - 1) + face_index + if face_index < mesh.nx - 1 + else None + ) + connect(east, x_diffusion, fixed_u[row_index, -1]) + + south = (row_index - 1) * (mesh.nx - 1) + face_index - 1 if row_index > 0 else None + connect( + south, + y_diffusion if row_index > 0 else 2.0 * y_diffusion, + walls["south"][0], + ) + north = ( + (row_index + 1) * (mesh.nx - 1) + face_index - 1 + if row_index < mesh.ny - 1 + else None + ) + connect( + north, + y_diffusion if row_index < mesh.ny - 1 else 2.0 * y_diffusion, + walls["north"][0], + ) + rows.append(row) + columns.append(row) + coefficients.append(diagonal) + + matrix = coo_matrix( + (coefficients, (rows, columns)), shape=(unknown_count, unknown_count) + ).tocsr() + return matrix, rhs, unknown_shape + + +def _build_v_matrix( + mesh: CartesianMesh, + old_v: FloatArray, + fixed_v: FloatArray, + convection: FloatArray, + pressure_gradient: FloatArray, + walls: WallVelocities, + density: float, + viscosity: float, + time_step: float, +) -> tuple[csr_matrix, FloatArray, tuple[int, int]]: + """Assemble `rho/dt - mu*laplacian` for interior v control volumes.""" + unknown_shape = (mesh.ny - 1, mesh.nx) + unknown_count = unknown_shape[0] * unknown_shape[1] + storage = density / time_step + x_diffusion = viscosity / mesh.dx**2 + y_diffusion = viscosity / mesh.dy**2 + rows: list[int] = [] + columns: list[int] = [] + coefficients: list[float] = [] + rhs = np.empty(unknown_count, dtype=np.float64) + + for face_index in range(1, mesh.ny): + for column_index in range(mesh.nx): + row = (face_index - 1) * mesh.nx + column_index + diagonal = storage + rhs[row] = ( + storage * old_v[face_index, column_index] + - density * convection[face_index - 1, column_index] + - pressure_gradient[face_index - 1, column_index] + ) + + def connect(neighbor: int | None, weight: float, boundary_value: float = 0.0) -> None: + nonlocal diagonal + if weight == 0.0: + return + diagonal += weight + if neighbor is None: + rhs[row] += weight * boundary_value + else: + rows.append(row) + columns.append(neighbor) + coefficients.append(-weight) + + west = row - 1 if column_index > 0 else None + connect(west, x_diffusion if column_index > 0 else 2.0 * x_diffusion, walls["west"][1]) + east = row + 1 if column_index < mesh.nx - 1 else None + connect(east, x_diffusion if column_index < mesh.nx - 1 else 2.0 * x_diffusion, walls["east"][1]) + + south = row - mesh.nx if face_index > 1 else None + connect(south, y_diffusion, fixed_v[0, column_index]) + north = row + mesh.nx if face_index < mesh.ny - 1 else None + connect(north, y_diffusion, fixed_v[-1, column_index]) + rows.append(row) + columns.append(row) + coefficients.append(diagonal) + + matrix = coo_matrix( + (coefficients, (rows, columns)), shape=(unknown_count, unknown_count) + ).tocsr() + return matrix, rhs, unknown_shape + + +class MomentumPredictor: + """Assemble and solve one explicit-convection/implicit-diffusion step. + + The predicted components satisfy, on their respective staggered control + volumes, + + `rho/dt * (u* - u_n) = -rho div(u_n u_n) - dp/dx + mu laplacian(u*)`, + + with the analogous equation for `v`. Convection is first-order upwind and + explicit. Diffusion is implicit; prescribed wall values contribute to the + matrix right-hand side. Pressure is the supplied cell-centered field (this + milestone does not compute pressure correction). + """ + + def __init__(self, density: float, viscosity: float, time_step: float) -> None: + """Create a predictor for one fluid and a fixed transient time step.""" + self.density = _validate_positive_parameter("density", density) + self.viscosity = _validate_positive_parameter("viscosity", viscosity, allow_zero=True) + self.time_step = _validate_positive_parameter("time_step", time_step) + + def assemble( + self, + velocity: VectorField, + pressure: ScalarField, + boundary_conditions: BoundaryConditions, + *, + temporal_velocity: VectorField | None = None, + ) -> MomentumAssembly: + """Build sparse component systems without modifying input fields. + + Velocity boundary conditions must prescribe both components on each + side. The boundary-aligned normal components are fixed directly; the + tangential components enter diffusion and convection at the adjacent + staggered control-volume faces. + """ + if not isinstance(velocity, VectorField): + raise TypeError("velocity must be a VectorField") + if not isinstance(pressure, ScalarField): + raise TypeError("pressure must be a ScalarField") + mesh = velocity.mesh + if pressure.mesh != mesh or pressure.location != "cell_center": + raise ValueError("pressure must be cell-centered on the velocity mesh") + if temporal_velocity is not None and temporal_velocity.mesh != mesh: + raise ValueError("temporal velocity must use the momentum mesh") + if mesh.nx < 2 or mesh.ny < 2: + raise ValueError("momentum prediction requires at least two cells per direction") + + walls = _wall_velocities(boundary_conditions) + old_u = np.asarray(velocity.u.values, dtype=np.float64).copy() + old_v = np.asarray(velocity.v.values, dtype=np.float64).copy() + storage_u = ( + old_u + if temporal_velocity is None + else np.asarray(temporal_velocity.u.values, dtype=np.float64) + ) + storage_v = ( + old_v + if temporal_velocity is None + else np.asarray(temporal_velocity.v.values, dtype=np.float64) + ) + if old_u.shape != mesh.shape_for_location("x_face"): + raise ValueError("u values have an invalid shape") + if old_v.shape != mesh.shape_for_location("y_face"): + raise ValueError("v values have an invalid shape") + if ( + not np.all(np.isfinite(old_u)) + or not np.all(np.isfinite(old_v)) + or not np.all(np.isfinite(storage_u)) + or not np.all(np.isfinite(storage_v)) + ): + raise ValueError("velocity values must all be finite") + if storage_u.shape != mesh.shape_for_location("x_face"): + raise ValueError("temporal u values have an invalid shape") + if storage_v.shape != mesh.shape_for_location("y_face"): + raise ValueError("temporal v values have an invalid shape") + fixed_u = old_u.copy() + fixed_v = old_v.copy() + + # On a MAC grid, u is stored on the west/east walls and v on the + # south/north walls. Tangential values are applied to adjacent CV faces. + fixed_u[:, 0] = walls["west"][0] + fixed_u[:, -1] = walls["east"][0] + fixed_v[0, :] = walls["south"][1] + fixed_v[-1, :] = walls["north"][1] + + pressure_gradient_x, pressure_gradient_y = face_gradient(pressure) + u_convection, v_convection = _staggered_upwind_convection( + fixed_u, fixed_v, walls, mesh + ) + u_matrix, u_rhs, u_shape = _build_u_matrix( + mesh, + storage_u, + fixed_u, + u_convection, + pressure_gradient_x[:, 1:-1], + walls, + self.density, + self.viscosity, + self.time_step, + ) + v_matrix, v_rhs, v_shape = _build_v_matrix( + mesh, + storage_v, + fixed_v, + v_convection, + pressure_gradient_y[1:-1, :], + walls, + self.density, + self.viscosity, + self.time_step, + ) + return MomentumAssembly( + mesh=mesh, + u_matrix=u_matrix, + u_rhs=u_rhs, + v_matrix=v_matrix, + v_rhs=v_rhs, + u_unknown_shape=u_shape, + v_unknown_shape=v_shape, + fixed_u=fixed_u, + fixed_v=fixed_v, + u_convection=u_convection, + v_convection=v_convection, + u_pressure_gradient=pressure_gradient_x[:, 1:-1].copy(), + v_pressure_gradient=pressure_gradient_y[1:-1, :].copy(), + ) + + def solve(self, assembly: MomentumAssembly) -> MomentumPrediction: + """Solve both sparse systems and restore fixed boundary-face values.""" + if not isinstance(assembly, MomentumAssembly): + raise TypeError("assembly must be a MomentumAssembly") + u_unknowns = np.asarray(spsolve(assembly.u_matrix, assembly.u_rhs), dtype=np.float64) + v_unknowns = np.asarray(spsolve(assembly.v_matrix, assembly.v_rhs), dtype=np.float64) + if not np.all(np.isfinite(u_unknowns)) or not np.all(np.isfinite(v_unknowns)): + raise RuntimeError("momentum linear solve produced non-finite values") + + predicted_u = assembly.fixed_u.copy() + predicted_v = assembly.fixed_v.copy() + predicted_u[:, 1:-1] = u_unknowns.reshape(assembly.u_unknown_shape) + predicted_v[1:-1, :] = v_unknowns.reshape(assembly.v_unknown_shape) + predicted_velocity = VectorField(assembly.mesh, name="predicted_velocity") + predicted_velocity.set_values(predicted_u, predicted_v) + + return MomentumPrediction( + velocity=predicted_velocity, + u_relative_residual=_relative_residual( + assembly.u_matrix, u_unknowns, assembly.u_rhs + ), + v_relative_residual=_relative_residual( + assembly.v_matrix, v_unknowns, assembly.v_rhs + ), + ) + + def predict( + self, + velocity: VectorField, + pressure: ScalarField, + boundary_conditions: BoundaryConditions, + *, + temporal_velocity: VectorField | None = None, + ) -> MomentumPrediction: + """Assemble and solve one momentum-prediction step in a single call.""" + return self.solve( + self.assemble( + velocity, + pressure, + boundary_conditions, + temporal_velocity=temporal_velocity, + ) + ) + + +def _relative_residual(matrix: csr_matrix, solution: FloatArray, rhs: FloatArray) -> float: + """Return a stable normalized L2 residual for a solved sparse system.""" + residual = matrix @ solution - rhs + return float(np.linalg.norm(residual) / max(float(np.linalg.norm(rhs)), 1.0)) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/operators.py b/Exp_solver_dev_tr/src/fvm/operators.py new file mode 100644 index 0000000000000..f8cf5abc5431f --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/operators.py @@ -0,0 +1,418 @@ +"""Finite-volume operators for cell scalars and MAC-staggered velocities.""" + +from __future__ import annotations + +from collections.abc import Mapping +from numbers import Real +from typing import Literal, TypeAlias + +import numpy as np +from numpy.typing import ArrayLike + +from .fields import ScalarField, VectorField +from .mesh import BOUNDARY_NAMES, CartesianMesh, FloatArray + +BoundaryValues: TypeAlias = Mapping[str, ArrayLike | float] +FaceArrays: TypeAlias = tuple[FloatArray, FloatArray] + + +def _cell_values(field: ScalarField) -> FloatArray: + """Check that an operator received a finite cell-centered scalar field.""" + if not isinstance(field, ScalarField): + raise TypeError("field must be a ScalarField") + if field.location != "cell_center": + raise ValueError("operator requires a cell-centered scalar field") + expected_shape = field.mesh.shape_for_location("cell_center") + values = np.asarray(field.values, dtype=np.float64) + if values.shape != expected_shape: + raise ValueError(f"field values must have shape {expected_shape}") + if not np.all(np.isfinite(values)): + raise ValueError("field values must all be finite") + return values + + +def _velocity_values(velocity: VectorField, mesh: CartesianMesh) -> FaceArrays: + """Check that velocity components belong to the same mesh and are finite.""" + if not isinstance(velocity, VectorField): + raise TypeError("velocity must be a VectorField") + if velocity.mesh != mesh: + raise ValueError("scalar and velocity fields must use the same mesh") + u_values = np.asarray(velocity.u.values, dtype=np.float64) + v_values = np.asarray(velocity.v.values, dtype=np.float64) + if u_values.shape != mesh.shape_for_location("x_face"): + raise ValueError("u values have an invalid shape") + if v_values.shape != mesh.shape_for_location("y_face"): + raise ValueError("v values have an invalid shape") + if not np.all(np.isfinite(u_values)) or not np.all(np.isfinite(v_values)): + raise ValueError("velocity values must all be finite") + return u_values, v_values + + +def _boundary_arrays( + mesh: CartesianMesh, boundary_values: BoundaryValues | None +) -> dict[str, FloatArray]: + """Expand scalar or side-array boundary values to one value per face.""" + if boundary_values is None: + return {} + if not isinstance(boundary_values, Mapping): + raise TypeError("boundary_values must be a mapping of side names to values") + unknown_sides = set(boundary_values) - set(BOUNDARY_NAMES) + if unknown_sides: + raise ValueError(f"unknown boundary names: {sorted(unknown_sides)}") + + boundary_lengths = { + "west": mesh.ny, + "east": mesh.ny, + "south": mesh.nx, + "north": mesh.nx, + } + normalized: dict[str, FloatArray] = {} + for side, boundary_value in boundary_values.items(): + try: + values = np.asarray(boundary_value, dtype=np.float64) + except (TypeError, ValueError) as error: + raise TypeError(f"{side} boundary values must be numeric") from error + if values.ndim == 0: + values = np.full(boundary_lengths[side], float(values), dtype=np.float64) + elif values.shape != (boundary_lengths[side],): + raise ValueError( + f"{side} boundary values must be scalar or have shape " + f"({boundary_lengths[side]},)" + ) + if not np.all(np.isfinite(values)): + raise ValueError(f"{side} boundary values must all be finite") + normalized[side] = values.copy() + return normalized + + +def _lower_boundary_gradient( + boundary_value: FloatArray, + first_cell: FloatArray, + spacing: float, + second_cell: FloatArray | None, + third_cell: FloatArray | None, +) -> FloatArray: + """Reconstruct the positive-axis gradient at a lower boundary face.""" + if second_cell is None: + return (first_cell - boundary_value) / (0.5 * spacing) + if third_cell is not None: + # A cubic through the face value and three cell centers keeps the + # boundary flux accurate enough for a second-order cell Laplacian. + return ( + (-46.0 / 15.0) * boundary_value + + (15.0 / 4.0) * first_cell + - (5.0 / 6.0) * second_cell + + (3.0 / 20.0) * third_cell + ) / spacing + return (-8.0 * boundary_value + 9.0 * first_cell - second_cell) / (3.0 * spacing) + + +def _upper_boundary_gradient( + boundary_value: FloatArray, + last_cell: FloatArray, + spacing: float, + second_cell: FloatArray | None, + third_cell: FloatArray | None, +) -> FloatArray: + """Reconstruct the positive-axis gradient at an upper boundary face.""" + if second_cell is None: + return (boundary_value - last_cell) / (0.5 * spacing) + if third_cell is not None: + return ( + (46.0 / 15.0) * boundary_value + - (15.0 / 4.0) * last_cell + + (5.0 / 6.0) * second_cell + - (3.0 / 20.0) * third_cell + ) / spacing + return (8.0 * boundary_value - 9.0 * last_cell + second_cell) / (3.0 * spacing) + + +def _lower_adjacent_face_gradient( + boundary_value: FloatArray, + first_cell: FloatArray, + second_cell: FloatArray, + third_cell: FloatArray, + spacing: float, +) -> FloatArray: + """Reconstruct the gradient one cell inward from a lower boundary.""" + return ( + (2.0 / 15.0) * boundary_value + - (5.0 / 4.0) * first_cell + + (7.0 / 6.0) * second_cell + - (1.0 / 20.0) * third_cell + ) / spacing + + +def _upper_adjacent_face_gradient( + boundary_value: FloatArray, + last_cell: FloatArray, + second_cell: FloatArray, + third_cell: FloatArray, + spacing: float, +) -> FloatArray: + """Reconstruct the gradient one cell inward from an upper boundary.""" + return ( + (-2.0 / 15.0) * boundary_value + + (5.0 / 4.0) * last_cell + - (7.0 / 6.0) * second_cell + + (1.0 / 20.0) * third_cell + ) / spacing + + +def interpolate_to_faces( + field: ScalarField, boundary_values: BoundaryValues | None = None +) -> FaceArrays: + """Interpolate a cell scalar to x/y faces using central averaging. + + Internal face values are arithmetic averages of adjacent cell values. + Boundary faces use the nearest cell value by default (zero-gradient + extrapolation); optional side values replace that default. + """ + cell_values = _cell_values(field) + mesh = field.mesh + boundaries = _boundary_arrays(mesh, boundary_values) + x_faces = np.empty(mesh.shape_for_location("x_face"), dtype=np.float64) + y_faces = np.empty(mesh.shape_for_location("y_face"), dtype=np.float64) + + x_faces[:, 1:-1] = 0.5 * (cell_values[:, :-1] + cell_values[:, 1:]) + x_faces[:, 0] = cell_values[:, 0] + x_faces[:, -1] = cell_values[:, -1] + y_faces[1:-1, :] = 0.5 * (cell_values[:-1, :] + cell_values[1:, :]) + y_faces[0, :] = cell_values[0, :] + y_faces[-1, :] = cell_values[-1, :] + + if "west" in boundaries: + x_faces[:, 0] = boundaries["west"] + if "east" in boundaries: + x_faces[:, -1] = boundaries["east"] + if "south" in boundaries: + y_faces[0, :] = boundaries["south"] + if "north" in boundaries: + y_faces[-1, :] = boundaries["north"] + return x_faces, y_faces + + +def face_gradient( + field: ScalarField, boundary_values: BoundaryValues | None = None +) -> FaceArrays: + """Compute `(dphi/dx, dphi/dy)` at vertical and horizontal faces. + + Internal gradients use a four-cell stencil where available, with + boundary-aware one-sided stencils near specified Dirichlet sides. Unless a + boundary value is supplied, the boundary-normal gradient is zero. With only + one or two cells along an axis, lower-order stencils are used as available. + """ + cell_values = _cell_values(field) + mesh = field.mesh + boundaries = _boundary_arrays(mesh, boundary_values) + gradient_x = np.zeros(mesh.shape_for_location("x_face"), dtype=np.float64) + gradient_y = np.zeros(mesh.shape_for_location("y_face"), dtype=np.float64) + + gradient_x[:, 1:-1] = (cell_values[:, 1:] - cell_values[:, :-1]) / mesh.dx + gradient_y[1:-1, :] = (cell_values[1:, :] - cell_values[:-1, :]) / mesh.dy + + if mesh.nx >= 4: + # A symmetric four-cell stencil gives face gradients with smaller + # errors; the following boundary reconstructions supply matching + # accuracy for the first and last interior faces. + gradient_x[:, 2:-2] = ( + 27.0 * (cell_values[:, 2:-1] - cell_values[:, 1:-2]) + - (cell_values[:, 3:] - cell_values[:, :-3]) + ) / (24.0 * mesh.dx) + if mesh.ny >= 4: + gradient_y[2:-2, :] = ( + 27.0 * (cell_values[2:-1, :] - cell_values[1:-2, :]) + - (cell_values[3:, :] - cell_values[:-3, :]) + ) / (24.0 * mesh.dy) + + if "west" in boundaries and mesh.nx >= 3: + gradient_x[:, 1] = _lower_adjacent_face_gradient( + boundaries["west"], + cell_values[:, 0], + cell_values[:, 1], + cell_values[:, 2], + mesh.dx, + ) + if "east" in boundaries and mesh.nx >= 3: + gradient_x[:, -2] = _upper_adjacent_face_gradient( + boundaries["east"], + cell_values[:, -1], + cell_values[:, -2], + cell_values[:, -3], + mesh.dx, + ) + if "south" in boundaries and mesh.ny >= 3: + gradient_y[1, :] = _lower_adjacent_face_gradient( + boundaries["south"], + cell_values[0, :], + cell_values[1, :], + cell_values[2, :], + mesh.dy, + ) + if "north" in boundaries and mesh.ny >= 3: + gradient_y[-2, :] = _upper_adjacent_face_gradient( + boundaries["north"], + cell_values[-1, :], + cell_values[-2, :], + cell_values[-3, :], + mesh.dy, + ) + + if "west" in boundaries: + second_cell = cell_values[:, 1] if mesh.nx > 1 else None + third_cell = cell_values[:, 2] if mesh.nx > 2 else None + gradient_x[:, 0] = _lower_boundary_gradient( + boundaries["west"], cell_values[:, 0], mesh.dx, second_cell, third_cell + ) + if "east" in boundaries: + second_cell = cell_values[:, -2] if mesh.nx > 1 else None + third_cell = cell_values[:, -3] if mesh.nx > 2 else None + gradient_x[:, -1] = _upper_boundary_gradient( + boundaries["east"], cell_values[:, -1], mesh.dx, second_cell, third_cell + ) + if "south" in boundaries: + second_cell = cell_values[1, :] if mesh.ny > 1 else None + third_cell = cell_values[2, :] if mesh.ny > 2 else None + gradient_y[0, :] = _lower_boundary_gradient( + boundaries["south"], cell_values[0, :], mesh.dy, second_cell, third_cell + ) + if "north" in boundaries: + second_cell = cell_values[-2, :] if mesh.ny > 1 else None + third_cell = cell_values[-3, :] if mesh.ny > 2 else None + gradient_y[-1, :] = _upper_boundary_gradient( + boundaries["north"], cell_values[-1, :], mesh.dy, second_cell, third_cell + ) + return gradient_x, gradient_y + + +def divergence(velocity: VectorField) -> FloatArray: + """Return the finite-volume divergence of face velocity in each cell. + + The face-normal velocity is multiplied by its face area, and the net + outward flux is divided by cell area. This is the discrete continuity + operator used by the later projection step. + """ + if not isinstance(velocity, VectorField): + raise TypeError("velocity must be a VectorField") + mesh = velocity.mesh + u_values, v_values = _velocity_values(velocity, mesh) + net_outward_flux = ( + (u_values[:, 1:] - u_values[:, :-1]) * mesh.u_face_area + + (v_values[1:, :] - v_values[:-1, :]) * mesh.v_face_area + ) + return net_outward_flux / mesh.cell_area + + +def _divergence_of_face_fluxes( + mesh: CartesianMesh, flux_x: FloatArray, flux_y: FloatArray +) -> FloatArray: + """Convert positive-coordinate face fluxes to cell-centered divergence.""" + net_outward_flux = ( + (flux_x[:, 1:] - flux_x[:, :-1]) * mesh.u_face_area + + (flux_y[1:, :] - flux_y[:-1, :]) * mesh.v_face_area + ) + return net_outward_flux / mesh.cell_area + + +def diffusive_fluxes( + field: ScalarField, + diffusivity: float = 1.0, + boundary_values: BoundaryValues | None = None, +) -> FaceArrays: + """Return face fluxes `diffusivity * grad(field)` on the MAC mesh. + + Diffusivity is constant over the domain. Missing boundary values imply + zero normal diffusive flux, which is the homogeneous Neumann condition. + """ + if isinstance(diffusivity, bool) or not isinstance(diffusivity, Real): + raise TypeError("diffusivity must be a finite non-negative number") + if not np.isfinite(diffusivity) or diffusivity < 0.0: + raise ValueError("diffusivity must be a finite non-negative number") + gradient_x, gradient_y = face_gradient(field, boundary_values) + return diffusivity * gradient_x, diffusivity * gradient_y + + +def diffusion_operator( + field: ScalarField, + diffusivity: float = 1.0, + boundary_values: BoundaryValues | None = None, +) -> FloatArray: + """Return the conservative cell-centered `div(diffusivity * grad(phi))`. + + ``boundary_values`` supplies Dirichlet values on any specified side; + unspecified sides have zero normal diffusive flux. + """ + flux_x, flux_y = diffusive_fluxes(field, diffusivity, boundary_values) + return _divergence_of_face_fluxes(field.mesh, flux_x, flux_y) + + +def convective_fluxes( + field: ScalarField, + velocity: VectorField, + scheme: Literal["central", "upwind"] = "upwind", + boundary_values: BoundaryValues | None = None, +) -> FaceArrays: + """Return conservative face fluxes `velocity * field`. + + ``central`` uses arithmetic interpolation on internal faces. ``upwind`` + selects the upstream cell value based on face-normal velocity. At an + inflow boundary, a supplied boundary value is used; otherwise the nearest + cell value is extrapolated. The latter is a convenience default, not a + replacement for a physically specified inflow condition. + """ + cell_values = _cell_values(field) + u_values, v_values = _velocity_values(velocity, field.mesh) + mesh = field.mesh + boundaries = _boundary_arrays(mesh, boundary_values) + + if scheme == "central": + face_values_x, face_values_y = interpolate_to_faces(field, boundaries) + elif scheme == "upwind": + face_values_x = np.empty(mesh.shape_for_location("x_face"), dtype=np.float64) + face_values_y = np.empty(mesh.shape_for_location("y_face"), dtype=np.float64) + + # Positive x/y velocity enters an internal face from its lower-index cell. + face_values_x[:, 1:-1] = np.where( + u_values[:, 1:-1] >= 0.0, cell_values[:, :-1], cell_values[:, 1:] + ) + face_values_y[1:-1, :] = np.where( + v_values[1:-1, :] >= 0.0, cell_values[:-1, :], cell_values[1:, :] + ) + + face_values_x[:, 0] = cell_values[:, 0] + face_values_x[:, -1] = cell_values[:, -1] + face_values_y[0, :] = cell_values[0, :] + face_values_y[-1, :] = cell_values[-1, :] + + # At west/south boundaries inward flow points in the positive axis direction. + if "west" in boundaries: + inflow = u_values[:, 0] > 0.0 + face_values_x[inflow, 0] = boundaries["west"][inflow] + if "east" in boundaries: + inflow = u_values[:, -1] < 0.0 + face_values_x[inflow, -1] = boundaries["east"][inflow] + if "south" in boundaries: + inflow = v_values[0, :] > 0.0 + face_values_y[0, inflow] = boundaries["south"][inflow] + if "north" in boundaries: + inflow = v_values[-1, :] < 0.0 + face_values_y[-1, inflow] = boundaries["north"][inflow] + else: + raise ValueError("scheme must be 'central' or 'upwind'") + + return u_values * face_values_x, v_values * face_values_y + + +def convection_operator( + field: ScalarField, + velocity: VectorField, + scheme: Literal["central", "upwind"] = "upwind", + boundary_values: BoundaryValues | None = None, +) -> FloatArray: + """Return conservative cell-centered `div(velocity * field)`. + + Face fluxes are multiplied by face areas and differenced before division + by cell area, so the sum over cells telescopes to the domain-boundary flux. + """ + flux_x, flux_y = convective_fluxes(field, velocity, scheme, boundary_values) + return _divergence_of_face_fluxes(field.mesh, flux_x, flux_y) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/postprocessing.py b/Exp_solver_dev_tr/src/fvm/postprocessing.py new file mode 100644 index 0000000000000..b13e2a5623ded --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/postprocessing.py @@ -0,0 +1,743 @@ +"""Post-processing, Ghia benchmark comparison, plots, and result export. + +The Re=100 reference profiles below are transcribed from Ghia, Ghia, and Shin, +Journal of Computational Physics 48 (1982), 387-411, +doi:10.1016/0021-9991(82)90058-4. Wall endpoints are retained in the source +tables but excluded from RMS comparisons because the lid velocity is +discontinuous at the two upper corners and boundary values are not interior +centerline samples. +""" + +from __future__ import annotations + +import csv +import json +from dataclasses import asdict, dataclass, fields +from math import isfinite +from numbers import Integral, Real +from pathlib import Path +from typing import Sequence + +import numpy as np + +from .boundary_conditions import BoundaryConditions, MovingWall, NoSlipWall +from .fields import ScalarField, VectorField +from .mesh import BOUNDARY_NAMES, CartesianMesh, FloatArray +from .simulation import SimulationResult, StepDiagnostics, TransientSolver + +# Coordinates are normalized and sorted from the lower wall to the upper/right wall. +GHIA_RE100_U_PROFILE = ( + (0.0000, 0.00000), + (0.0625, -0.04192), + (0.0703, -0.04775), + (0.1016, -0.06434), + (0.1719, -0.10150), + (0.2813, -0.15662), + (0.4531, -0.21090), + (0.5000, -0.20581), + (0.6172, -0.13641), + (0.7344, 0.00332), + (0.8516, 0.23151), + (0.9531, 0.68717), + (0.9609, 0.73722), + (0.9688, 0.78871), + (0.9766, 0.84123), + (1.0000, 1.00000), +) +GHIA_RE100_V_PROFILE = ( + (0.0000, 0.00000), + (0.0625, 0.09233), + (0.0703, 0.10091), + (0.0781, 0.10890), + (0.0938, 0.12317), + (0.1563, 0.16077), + (0.2266, 0.17507), + (0.2344, 0.17527), + (0.5000, 0.05454), + (0.8047, -0.24533), + (0.8594, -0.22445), + (0.9063, -0.16914), + (0.9453, -0.10313), + (0.9531, -0.08864), + (0.9609, -0.07391), + (0.9688, -0.05906), + (1.0000, 0.00000), +) + + +@dataclass(frozen=True, slots=True) +class CenterlineProfiles: + """Physical centerline coordinates and velocities interpolated from MAC data.""" + + u_y: FloatArray + u: FloatArray + v_x: FloatArray + v: FloatArray + + +@dataclass(frozen=True, slots=True) +class GhiaComparison: + """Interior-point Re=100 profile comparison in nondimensional coordinates.""" + + u_coordinate: FloatArray + u_reference: FloatArray + u_computed: FloatArray + v_coordinate: FloatArray + v_reference: FloatArray + v_computed: FloatArray + u_rms_error: float + v_rms_error: float + simulation_converged: bool + steady_solution: bool + + @property + def benchmark_valid(self) -> bool: + """Only a converged steady solution is eligible for benchmark acceptance.""" + return self.simulation_converged and self.steady_solution + + +@dataclass(frozen=True, slots=True) +class ComponentExtrema: + """Minimum and maximum of one velocity component and their coordinates.""" + + minimum: float + minimum_location: tuple[float, float] + maximum: float + maximum_location: tuple[float, float] + + +@dataclass(frozen=True, slots=True) +class VelocityExtrema: + """Component extrema plus maximum cell-centered speed.""" + + u: ComponentExtrema + v: ComponentExtrema + maximum_speed: float + maximum_speed_location: tuple[float, float] + + +@dataclass(frozen=True, slots=True) +class GridStudyRow: + """One grid's Re=100 run status and centerline errors.""" + + cells_per_side: int + converged: bool + steps: int + final_time: float + u_rms_error: float + v_rms_error: float + max_divergence: float + global_mass_imbalance: float + + @property + def benchmark_valid(self) -> bool: + """A grid result is benchmark-valid only if its run converged.""" + return self.converged + + +def _velocity_arrays(velocity: VectorField) -> tuple[FloatArray, FloatArray]: + """Validate face-array shapes and values before post-processing.""" + if not isinstance(velocity, VectorField): + raise TypeError("velocity must be a VectorField") + mesh = velocity.mesh + u = np.asarray(velocity.u.values, dtype=np.float64) + v = np.asarray(velocity.v.values, dtype=np.float64) + if u.shape != mesh.shape_for_location("x_face"): + raise ValueError("u values have an invalid shape") + if v.shape != mesh.shape_for_location("y_face"): + raise ValueError("v values have an invalid shape") + if not np.all(np.isfinite(u)) or not np.all(np.isfinite(v)): + raise ValueError("velocity values must all be finite") + return u, v + + +def centerline_profiles(velocity: VectorField) -> CenterlineProfiles: + """Interpolate staggered components onto the geometric cavity centerlines. + + ``u`` is interpolated in x from vertical faces to `x=width/2`; ``v`` is + interpolated in y from horizontal faces to `y=height/2`. The returned + profile coordinates remain physical distances, not normalized values. + """ + u_values, v_values = _velocity_arrays(velocity) + mesh = velocity.mesh + center_x = 0.5 * mesh.width + center_y = 0.5 * mesh.height + u_centerline = np.array( + [np.interp(center_x, mesh.x_face_centers, row) for row in u_values], + dtype=np.float64, + ) + v_centerline = np.array( + [np.interp(center_y, mesh.y_face_centers, v_values[:, column]) + for column in range(mesh.nx)], + dtype=np.float64, + ) + return CenterlineProfiles( + u_y=mesh.y_cell_centers.copy(), + u=u_centerline, + v_x=mesh.x_cell_centers.copy(), + v=v_centerline, + ) + + +def compare_ghia_re100( + simulation: SimulationResult, lid_speed: float = 1.0 +) -> GhiaComparison: + """Compare a simulation's centerlines with Ghia's Re=100 tabulated profiles. + + Wall endpoints are deliberately omitted. The RMS errors use interpolated, + dimensionless numerical velocities at the interior reference coordinates. + Results from a run capped before convergence are returned for inspection, + but ``benchmark_valid`` remains false. + """ + if not isinstance(simulation, SimulationResult): + raise TypeError("simulation must be a SimulationResult") + if isinstance(lid_speed, bool) or not isinstance(lid_speed, Real): + raise TypeError("lid_speed must be a finite positive number") + if not isfinite(lid_speed) or lid_speed <= 0.0: + raise ValueError("lid_speed must be a finite positive number") + mesh = simulation.velocity.mesh + if not np.isclose(mesh.width, mesh.height): + raise ValueError("Ghia cavity comparison requires a square domain") + viscosity = simulation.settings.viscosity + reynolds_number = ( + simulation.settings.density * lid_speed * mesh.width / viscosity + if viscosity > 0.0 + else 0.0 + ) + if not np.isclose(reynolds_number, 100.0, rtol=1e-8, atol=1e-10): + raise ValueError( + f"Ghia comparison requires Reynolds number 100, got {reynolds_number:.6g}" + ) + + profiles = centerline_profiles(simulation.velocity) + u_reference = np.asarray(GHIA_RE100_U_PROFILE, dtype=np.float64) + v_reference = np.asarray(GHIA_RE100_V_PROFILE, dtype=np.float64) + u_interior = (u_reference[:, 0] > 0.0) & (u_reference[:, 0] < 1.0) + v_interior = (v_reference[:, 0] > 0.0) & (v_reference[:, 0] < 1.0) + u_coordinates = u_reference[u_interior, 0] + v_coordinates = v_reference[v_interior, 0] + + # Wall values are used only to interpolate nearby interior reference points; + # the wall endpoints themselves are not included in the RMS comparisons. + u_grid = np.concatenate(([0.0], profiles.u_y / mesh.height, [1.0])) + u_values = np.concatenate(([0.0], profiles.u / lid_speed, [1.0])) + v_grid = np.concatenate(([0.0], profiles.v_x / mesh.width, [1.0])) + v_values = np.concatenate(([0.0], profiles.v / lid_speed, [0.0])) + if ( + u_coordinates[0] < u_grid[0] + or u_coordinates[-1] > u_grid[-1] + or v_coordinates[0] < v_grid[0] + or v_coordinates[-1] > v_grid[-1] + ): + raise ValueError("mesh is too coarse to interpolate all interior Ghia points") + + u_reference_values = u_reference[u_interior, 1] + v_reference_values = v_reference[v_interior, 1] + u_computed = np.interp(u_coordinates, u_grid, u_values) + v_computed = np.interp(v_coordinates, v_grid, v_values) + return GhiaComparison( + u_coordinate=u_coordinates, + u_reference=u_reference_values, + u_computed=u_computed, + v_coordinate=v_coordinates, + v_reference=v_reference_values, + v_computed=v_computed, + u_rms_error=float(np.sqrt(np.mean((u_computed - u_reference_values) ** 2))), + v_rms_error=float(np.sqrt(np.mean((v_computed - v_reference_values) ** 2))), + simulation_converged=simulation.converged, + steady_solution=( + not simulation.settings.transient or simulation.settings.end_time is None + ), + ) + + +def velocity_extrema(velocity: VectorField) -> VelocityExtrema: + """Find component extrema and maximum speed after averaging to cell centers.""" + u_values, v_values = _velocity_arrays(velocity) + mesh = velocity.mesh + u_x, u_y = mesh.u_face_coordinates + v_x, v_y = mesh.v_face_coordinates + + u_min_index = np.unravel_index(np.argmin(u_values), u_values.shape) + u_max_index = np.unravel_index(np.argmax(u_values), u_values.shape) + v_min_index = np.unravel_index(np.argmin(v_values), v_values.shape) + v_max_index = np.unravel_index(np.argmax(v_values), v_values.shape) + + u_center = 0.5 * (u_values[:, :-1] + u_values[:, 1:]) + v_center = 0.5 * (v_values[:-1, :] + v_values[1:, :]) + speed = np.hypot(u_center, v_center) + speed_index = np.unravel_index(np.argmax(speed), speed.shape) + cell_x, cell_y = mesh.cell_center_coordinates + + return VelocityExtrema( + u=ComponentExtrema( + minimum=float(u_values[u_min_index]), + minimum_location=(float(u_x[u_min_index]), float(u_y[u_min_index])), + maximum=float(u_values[u_max_index]), + maximum_location=(float(u_x[u_max_index]), float(u_y[u_max_index])), + ), + v=ComponentExtrema( + minimum=float(v_values[v_min_index]), + minimum_location=(float(v_x[v_min_index]), float(v_y[v_min_index])), + maximum=float(v_values[v_max_index]), + maximum_location=(float(v_x[v_max_index]), float(v_y[v_max_index])), + ), + maximum_speed=float(speed[speed_index]), + maximum_speed_location=( + float(cell_x[speed_index]), + float(cell_y[speed_index]), + ), + ) + + +def plot_mesh_and_boundaries( + mesh: CartesianMesh, + boundary_conditions: BoundaryConditions, + output_path: str | Path | None = None, +) -> object: + """Draw the rectangle, Cartesian grid, and prescribed wall directions.""" + import matplotlib.pyplot as plt + + if not isinstance(mesh, CartesianMesh): + raise TypeError("mesh must be a CartesianMesh") + if not isinstance(boundary_conditions, BoundaryConditions): + raise TypeError("boundary_conditions must be BoundaryConditions") + + figure, axis = plt.subplots(figsize=(6, 6), layout="constrained") + for x_coordinate in mesh.x_face_centers: + axis.axvline(x_coordinate, color="#cbd5e1", linewidth=0.7, zorder=0) + for y_coordinate in mesh.y_face_centers: + axis.axhline(y_coordinate, color="#cbd5e1", linewidth=0.7, zorder=0) + axis.plot( + [0.0, mesh.width, mesh.width, 0.0, 0.0], + [0.0, 0.0, mesh.height, mesh.height, 0.0], + color="#1f2937", + linewidth=2.0, + zorder=2, + ) + + for side in BOUNDARY_NAMES: + condition = boundary_conditions.get("velocity", side) + if isinstance(condition, MovingWall): + u_wall, v_wall = condition.velocity + magnitude = float(np.hypot(u_wall, v_wall)) + if magnitude > 0.0: + arrow_length = 0.22 * min(mesh.width, mesh.height) + dx = arrow_length * u_wall / magnitude + dy = arrow_length * v_wall / magnitude + if side in ("west", "east"): + inset = 0.025 * min(mesh.width, mesh.height) + start_x = inset if side == "west" else mesh.width - inset + start_y = 0.5 * (mesh.height - dy) + else: + start_x = 0.5 * (mesh.width - dx) + inset = 0.025 * min(mesh.width, mesh.height) + start_y = inset if side == "south" else mesh.height - inset + axis.quiver( + start_x, + start_y, + dx, + dy, + angles="xy", + scale_units="xy", + scale=1.0, + color="#d1495b", + width=0.009, + zorder=3, + label=f"{side} moving wall ({magnitude:g} m/s)", + ) + elif isinstance(condition, NoSlipWall): + inset = 0.035 * min(mesh.width, mesh.height) + label_locations = { + "west": (inset, 0.5 * mesh.height, 90.0), + "east": (mesh.width - inset, 0.5 * mesh.height, 90.0), + "south": (0.5 * mesh.width, inset, 0.0), + "north": (0.5 * mesh.width, mesh.height - inset, 0.0), + } + label_x, label_y, angle = label_locations[side] + axis.text( + label_x, + label_y, + "no-slip", + rotation=angle, + color="#475569", + fontsize=8, + ha="center", + va="center", + backgroundcolor="white", + zorder=4, + ) + else: + raise ValueError(f"unsupported velocity boundary condition on {side}") + + axis.set_xlim(0.0, mesh.width) + axis.set_ylim(0.0, mesh.height) + axis.set_aspect("equal") + axis.set_xlabel("x (m)") + axis.set_ylabel("y (m)") + axis.set_title(f"Domain and uniform Cartesian mesh ({mesh.nx} x {mesh.ny})") + handles, labels = axis.get_legend_handles_labels() + if handles: + axis.legend(handles, labels, loc="lower right") + return _finish_figure(figure, output_path) + + +def export_simulation_result( + simulation: SimulationResult, output_directory: str | Path +) -> Path: + """Write compressed fields, run metadata, and per-step history to a folder.""" + if not isinstance(simulation, SimulationResult): + raise TypeError("simulation must be a SimulationResult") + output = Path(output_directory) + output.mkdir(parents=True, exist_ok=True) + mesh = simulation.velocity.mesh + u_values, v_values = _velocity_arrays(simulation.velocity) + cell_u = 0.5 * (u_values[:, :-1] + u_values[:, 1:]) + cell_v = 0.5 * (v_values[:-1, :] + v_values[1:, :]) + + np.savez_compressed( + output / "fields.npz", + x_cell_centers=mesh.x_cell_centers, + y_cell_centers=mesh.y_cell_centers, + x_face_centers=mesh.x_face_centers, + y_face_centers=mesh.y_face_centers, + pressure=simulation.pressure.values, + u_faces=u_values, + v_faces=v_values, + u_cell_centers=cell_u, + v_cell_centers=cell_v, + ) + + metadata = { + "format_version": 1, + "mesh": { + "nx": mesh.nx, + "ny": mesh.ny, + "width": mesh.width, + "height": mesh.height, + }, + "settings": asdict(simulation.settings), + "converged": simulation.converged, + "termination_reason": simulation.termination_reason, + "steps": simulation.steps, + "final_time": simulation.final_time, + "final_pseudo_time": simulation.final_pseudo_time, + "temporal_mode": "transient" if simulation.settings.transient else "steady", + "velocity_extrema": asdict(velocity_extrema(simulation.velocity)), + } + with (output / "metadata.json").open("w", encoding="utf-8") as metadata_file: + json.dump(metadata, metadata_file, indent=2) + + history_fields = [field.name for field in fields(StepDiagnostics)] + with (output / "history.csv").open("w", newline="", encoding="utf-8") as history_file: + writer = csv.DictWriter(history_file, fieldnames=history_fields) + writer.writeheader() + writer.writerows(asdict(item) for item in simulation.history) + return output + + +def _finish_figure(figure: object, output_path: str | Path | None) -> object: + """Save a Matplotlib figure when requested and return it for customization.""" + if output_path is not None: + output = Path(output_path) + output.parent.mkdir(parents=True, exist_ok=True) + figure.savefig(output, dpi=160, bbox_inches="tight") + return figure + + +def plot_cavity_fields( + simulation: SimulationResult, output_path: str | Path | None = None +) -> object: + """Plot cell-centered speed, pressure, and streamlines for a cavity result.""" + import matplotlib.pyplot as plt + from matplotlib.colors import TwoSlopeNorm + + mesh = simulation.velocity.mesh + u_values, v_values = _velocity_arrays(simulation.velocity) + cell_u = 0.5 * (u_values[:, :-1] + u_values[:, 1:]) + cell_v = 0.5 * (v_values[:-1, :] + v_values[1:, :]) + speed = np.hypot(cell_u, cell_v) + vorticity = np.gradient(cell_v, mesh.dx, axis=1) - np.gradient( + cell_u, mesh.dy, axis=0 + ) + x, y = mesh.x_cell_centers, mesh.y_cell_centers + figure, axes = plt.subplots(2, 2, figsize=(11, 8), layout="constrained") + speed_axis, pressure_axis, streamline_axis, vorticity_axis = axes.flat + + speed_max = float(np.max(speed)) + if speed_max > 0.0: + speed_plot = speed_axis.contourf( + x, + y, + speed, + levels=np.linspace(0.0, speed_max, 33), + cmap="viridis", + ) + else: + speed_plot = speed_axis.pcolormesh( + x, y, speed, shading="nearest", cmap="viridis", vmin=0.0, vmax=1.0 + ) + figure.colorbar(speed_plot, ax=speed_axis, label="Speed (m/s)") + speed_axis.set_title("Velocity magnitude") + + pressure = simulation.pressure.values + pressure_limit = float(np.max(np.abs(pressure))) + pressure_limit = pressure_limit if pressure_limit > 0.0 else 1.0 + pressure_norm = TwoSlopeNorm( + vmin=-pressure_limit, vcenter=0.0, vmax=pressure_limit + ) + if float(np.ptp(pressure)) > 0.0: + pressure_plot = pressure_axis.contourf( + x, + y, + pressure, + levels=np.linspace(-pressure_limit, pressure_limit, 33), + cmap="coolwarm", + norm=pressure_norm, + ) + else: + pressure_plot = pressure_axis.pcolormesh( + x, + y, + pressure, + shading="nearest", + cmap="coolwarm", + norm=pressure_norm, + ) + figure.colorbar(pressure_plot, ax=pressure_axis, label="Pressure (Pa)") + pressure_axis.set_title("Pressure") + + if float(np.max(speed)) > 0.0: + streamline_axis.streamplot( + x, + y, + cell_u, + cell_v, + color=speed, + density=2.0, + linewidth=0.8, + arrowsize=0.8, + cmap="viridis", + ) + else: + streamline_axis.text(0.5, 0.5, "Zero velocity", ha="center", va="center") + streamline_axis.set_title("Streamlines") + + vorticity_limit = float(np.max(np.abs(vorticity))) + vorticity_limit = vorticity_limit if vorticity_limit > 0.0 else 1.0 + vorticity_norm = TwoSlopeNorm( + vmin=-vorticity_limit, vcenter=0.0, vmax=vorticity_limit + ) + if float(np.ptp(vorticity)) > 0.0: + vorticity_plot = vorticity_axis.contourf( + x, + y, + vorticity, + levels=np.linspace(-vorticity_limit, vorticity_limit, 33), + cmap="coolwarm", + norm=vorticity_norm, + ) + if float(np.min(vorticity)) < 0.0 < float(np.max(vorticity)): + vorticity_axis.contour( + x, y, vorticity, levels=[0.0], colors="#202020", linewidths=0.6 + ) + else: + vorticity_plot = vorticity_axis.pcolormesh( + x, + y, + vorticity, + shading="nearest", + cmap="coolwarm", + norm=vorticity_norm, + ) + figure.colorbar(vorticity_plot, ax=vorticity_axis, label="Vorticity (1/s)") + vorticity_axis.set_title("Vorticity") + + for axis in axes.flat: + axis.set_xlabel("x (m)") + axis.set_ylabel("y (m)") + axis.set_aspect("equal") + state = "converged" if simulation.converged else simulation.termination_reason + if simulation.settings.transient: + figure.suptitle(f"Cavity at t={simulation.final_time:.4g} s ({state})") + else: + figure.suptitle(f"Steady cavity after {simulation.steps} iterations ({state})") + return _finish_figure(figure, output_path) + + +def plot_ghia_comparison( + comparison: GhiaComparison, output_path: str | Path | None = None +) -> object: + """Plot both dimensionless centerline profiles against Ghia reference points.""" + import matplotlib.pyplot as plt + + figure, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained") + axes[0].plot(comparison.u_computed, comparison.u_coordinate, label="FVM") + axes[0].scatter(comparison.u_reference, comparison.u_coordinate, marker="x", label="Ghia Re=100") + axes[0].set_xlabel("u / lid speed") + axes[0].set_ylabel("y / height") + axes[0].set_title(f"Vertical centerline, RMS={comparison.u_rms_error:.3e}") + axes[0].legend() + + axes[1].plot(comparison.v_coordinate, comparison.v_computed, label="FVM") + axes[1].scatter(comparison.v_coordinate, comparison.v_reference, marker="x", label="Ghia Re=100") + axes[1].set_xlabel("x / width") + axes[1].set_ylabel("v / lid speed") + axes[1].set_title(f"Horizontal centerline, RMS={comparison.v_rms_error:.3e}") + axes[1].legend() + if not comparison.benchmark_valid: + figure.suptitle("Diagnostic comparison only: simulation has not converged") + return _finish_figure(figure, output_path) + + +def plot_convergence_history( + simulation: SimulationResult, output_path: str | Path | None = None +) -> object: + """Plot velocity change, continuity, and pressure residual versus time.""" + import matplotlib.pyplot as plt + + if not simulation.history: + raise ValueError("simulation has no time-step history to plot") + transient = simulation.settings.transient + x_values = np.array( + [item.time if transient else item.step for item in simulation.history], + dtype=np.float64, + ) + series = { + "max velocity change": [item.velocity_change for item in simulation.history], + "max post-projection divergence": [ + item.max_divergence_after for item in simulation.history + ], + "pressure residual": [item.pressure_residual for item in simulation.history], + } + figure, axis = plt.subplots(figsize=(7, 4), layout="constrained") + floor = np.finfo(np.float64).tiny + for label, values in series.items(): + axis.semilogy(x_values, np.maximum(values, floor), label=label) + axis.set_xlabel("Time (s)" if transient else "Iteration") + axis.set_ylabel("Residual / change") + axis.set_title("Transient convergence history" if transient else "Steady convergence history") + axis.legend() + axis.grid(True, which="both", alpha=0.25) + return _finish_figure(figure, output_path) + + +def run_lid_driven_grid_study( + grid_sizes: Sequence[int] = (16, 32, 64, 128), + *, + max_time_step: float = 1e-3, + max_steps: int = 1000, + cfl_limit: float = 0.5, + velocity_tolerance: float = 1e-6, +) -> tuple[GridStudyRow, ...]: + """Run Re=100 cavity cases on requested square grids and compare profiles. + + The default grid series is the planned 16/32/64/128 study. Each row keeps + the convergence flag: profile RMS errors from a run that reaches its step + cap are diagnostics, not accepted benchmark results. + """ + if not grid_sizes: + raise ValueError("grid_sizes must contain at least one resolution") + normalized_sizes: list[int] = [] + for size in grid_sizes: + if isinstance(size, bool) or not isinstance(size, Integral): + raise TypeError("grid sizes must be integers") + if size < 16: + raise ValueError("Ghia grid study resolutions must be at least 16 per side") + normalized_sizes.append(int(size)) + if normalized_sizes != sorted(set(normalized_sizes)): + raise ValueError("grid_sizes must be unique and strictly increasing") + + rows: list[GridStudyRow] = [] + for cells in normalized_sizes: + mesh = CartesianMesh(nx=cells, ny=cells) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + conditions = BoundaryConditions() + for side in BOUNDARY_NAMES: + if side == "north": + conditions.set("velocity", side, MovingWall((1.0, 0.0))) + else: + conditions.set("velocity", side, NoSlipWall()) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=max_time_step, + max_steps=max_steps, + cfl_limit=cfl_limit, + velocity_tolerance=velocity_tolerance, + ) + simulation = solver.run(velocity, pressure, conditions) + comparison = compare_ghia_re100(simulation) + last_step = simulation.history[-1] + rows.append( + GridStudyRow( + cells_per_side=cells, + converged=simulation.converged, + steps=simulation.steps, + final_time=simulation.final_time, + u_rms_error=comparison.u_rms_error, + v_rms_error=comparison.v_rms_error, + max_divergence=last_step.max_divergence_after, + global_mass_imbalance=last_step.global_mass_imbalance, + ) + ) + return tuple(rows) + + +def write_grid_study_csv(rows: Sequence[GridStudyRow], output_path: str | Path) -> Path: + """Write grid-study metrics to a CSV file.""" + if not rows: + raise ValueError("rows must contain at least one grid result") + output = Path(output_path) + output.parent.mkdir(parents=True, exist_ok=True) + field_names = [field.name for field in fields(GridStudyRow)] + with output.open("w", newline="", encoding="utf-8") as output_file: + writer = csv.DictWriter(output_file, fieldnames=field_names) + writer.writeheader() + writer.writerows(asdict(row) for row in rows) + return output + + +def export_ghia_comparison( + comparison: GhiaComparison, output_path: str | Path +) -> Path: + """Write profile samples, RMS errors, and convergence eligibility as JSON.""" + if not isinstance(comparison, GhiaComparison): + raise TypeError("comparison must be a GhiaComparison") + output = Path(output_path) + output.parent.mkdir(parents=True, exist_ok=True) + payload = { + "benchmark": "Ghia et al. lid-driven cavity Re=100", + "simulation_converged": comparison.simulation_converged, + "benchmark_valid": comparison.benchmark_valid, + "u_rms_error": comparison.u_rms_error, + "v_rms_error": comparison.v_rms_error, + "u_profile": [ + { + "coordinate": float(coordinate), + "reference": float(reference), + "computed": float(computed), + } + for coordinate, reference, computed in zip( + comparison.u_coordinate, + comparison.u_reference, + comparison.u_computed, + ) + ], + "v_profile": [ + { + "coordinate": float(coordinate), + "reference": float(reference), + "computed": float(computed), + } + for coordinate, reference, computed in zip( + comparison.v_coordinate, + comparison.v_reference, + comparison.v_computed, + ) + ], + } + with output.open("w", encoding="utf-8") as output_file: + json.dump(payload, output_file, indent=2) + return output \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/pressure_correction.py b/Exp_solver_dev_tr/src/fvm/pressure_correction.py new file mode 100644 index 0000000000000..1f189a4c84d51 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/pressure_correction.py @@ -0,0 +1,217 @@ +"""Sparse Neumann pressure-correction equation for the MAC projection method.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Integral, Real + +import numpy as np +from scipy.sparse import coo_matrix, csr_matrix, lil_matrix +from scipy.sparse.linalg import spsolve + +from .fields import ScalarField, VectorField +from .mesh import CartesianMesh, FloatArray +from .operators import divergence + + +@dataclass(frozen=True, slots=True) +class PressureCorrectionAssembly: + """Sparse positive-Neumann Poisson system with one pressure reference. + + The equation is `-laplacian(p') = -(rho/dt) * div(u*)`. The cell-centered + finite-volume matrix omits normal-gradient contributions at domain walls. + ``reference_cell`` is stored as `(row, column)` and has an identity row to + remove the constant-pressure nullspace. + """ + + mesh: CartesianMesh + matrix: csr_matrix + rhs: FloatArray + reference_cell: tuple[int, int] + net_boundary_flux: float + + +@dataclass(frozen=True, slots=True) +class PressureCorrectionResult: + """Cell-centered pressure correction and normalized sparse residual.""" + + correction: ScalarField + relative_residual: float + net_boundary_flux: float + + +def _positive_parameter(name: str, value: float) -> float: + """Validate a finite positive scalar used by the pressure equation.""" + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + return float(value) + + +def _reference_index( + reference_cell: tuple[int, int], mesh: CartesianMesh +) -> tuple[int, int, int]: + """Validate a `(row, column)` gauge location and return its flat index.""" + if ( + not isinstance(reference_cell, tuple) + or len(reference_cell) != 2 + or any(isinstance(index, bool) or not isinstance(index, Integral) for index in reference_cell) + ): + raise TypeError("reference_cell must be a (row, column) integer tuple") + row, column = (int(index) for index in reference_cell) + if not (0 <= row < mesh.ny and 0 <= column < mesh.nx): + raise ValueError("reference_cell lies outside the mesh") + return row, column, row * mesh.nx + column + + +def _net_boundary_flux(velocity: VectorField) -> tuple[float, float]: + """Return outward flux and an absolute-flux scale for compatibility checks.""" + mesh = velocity.mesh + u = np.asarray(velocity.u.values, dtype=np.float64) + v = np.asarray(velocity.v.values, dtype=np.float64) + if u.shape != mesh.shape_for_location("x_face"): + raise ValueError("u values have an invalid shape") + if v.shape != mesh.shape_for_location("y_face"): + raise ValueError("v values have an invalid shape") + if not np.all(np.isfinite(u)) or not np.all(np.isfinite(v)): + raise ValueError("velocity values must all be finite") + + east_flux = float(np.sum(u[:, -1]) * mesh.u_face_area) + west_flux = float(np.sum(u[:, 0]) * mesh.u_face_area) + north_flux = float(np.sum(v[-1, :]) * mesh.v_face_area) + south_flux = float(np.sum(v[0, :]) * mesh.v_face_area) + net_flux = east_flux - west_flux + north_flux - south_flux + flux_scale = abs(east_flux) + abs(west_flux) + abs(north_flux) + abs(south_flux) + return net_flux, flux_scale + + +def _assemble_neumann_matrix(mesh: CartesianMesh, reference_index: int) -> csr_matrix: + """Assemble `-laplacian` with zero normal flux on every outer face.""" + row_indices: list[int] = [] + column_indices: list[int] = [] + coefficients: list[float] = [] + inverse_dx_squared = 1.0 / mesh.dx**2 + inverse_dy_squared = 1.0 / mesh.dy**2 + + for row in range(mesh.ny): + for column in range(mesh.nx): + cell_index = row * mesh.nx + column + diagonal = 0.0 + neighbors = ( + (row, column - 1, inverse_dx_squared), + (row, column + 1, inverse_dx_squared), + (row - 1, column, inverse_dy_squared), + (row + 1, column, inverse_dy_squared), + ) + for neighbor_row, neighbor_column, coefficient in neighbors: + if 0 <= neighbor_row < mesh.ny and 0 <= neighbor_column < mesh.nx: + neighbor_index = neighbor_row * mesh.nx + neighbor_column + row_indices.append(cell_index) + column_indices.append(neighbor_index) + coefficients.append(-coefficient) + diagonal += coefficient + row_indices.append(cell_index) + column_indices.append(cell_index) + coefficients.append(diagonal) + + matrix = coo_matrix( + (coefficients, (row_indices, column_indices)), + shape=(mesh.nx * mesh.ny, mesh.nx * mesh.ny), + ).tolil() + + # A pure-Neumann Poisson matrix has an arbitrary additive constant. Replace + # one equation by p'(reference_cell) = 0 to choose a unique solution. + matrix[reference_index, :] = 0.0 + matrix[reference_index, reference_index] = 1.0 + return matrix.tocsr() + + +class PressureCorrectionSolver: + """Assemble and solve one homogeneous-Neumann pressure-correction system. + + The predicted velocity must have compatible net boundary flux. For a + closed cavity the momentum predictor enforces zero normal wall velocity, + so this condition is satisfied. A nonzero net flux cannot be removed by a + homogeneous-Neumann correction without changing the boundary conditions, + and is reported as an error instead of silently modifying the RHS. + """ + + def __init__( + self, + density: float, + time_step: float, + reference_cell: tuple[int, int] = (0, 0), + compatibility_tolerance: float = 1e-10, + ) -> None: + """Create a solver with a pressure gauge and flux tolerance. + + ``reference_cell`` uses zero-based `(row, column)` indexing. Net flux is + accepted when its magnitude is no greater than the tolerance times + `max(total absolute boundary flux, 1)`. + """ + self.density = _positive_parameter("density", density) + self.time_step = _positive_parameter("time_step", time_step) + self.compatibility_tolerance = _positive_parameter( + "compatibility_tolerance", compatibility_tolerance + ) + if ( + not isinstance(reference_cell, tuple) + or len(reference_cell) != 2 + or any( + isinstance(index, bool) or not isinstance(index, Integral) + for index in reference_cell + ) + ): + raise TypeError("reference_cell must be a (row, column) integer tuple") + self.reference_cell = tuple(int(index) for index in reference_cell) + + def assemble(self, predicted_velocity: VectorField) -> PressureCorrectionAssembly: + """Build the pressure equation from predicted face-velocity divergence.""" + if not isinstance(predicted_velocity, VectorField): + raise TypeError("predicted_velocity must be a VectorField") + mesh = predicted_velocity.mesh + row, column, reference_index = _reference_index(self.reference_cell, mesh) + net_flux, flux_scale = _net_boundary_flux(predicted_velocity) + if abs(net_flux) > self.compatibility_tolerance * max(flux_scale, 1.0): + raise ValueError( + "predicted velocity has incompatible net boundary flux " + f"({net_flux:.6g}); homogeneous-Neumann correction requires zero net flux" + ) + + velocity_divergence = divergence(predicted_velocity) + rhs = (-self.density / self.time_step * velocity_divergence).ravel().copy() + matrix = _assemble_neumann_matrix(mesh, reference_index) + rhs[reference_index] = 0.0 + return PressureCorrectionAssembly( + mesh=mesh, + matrix=matrix, + rhs=rhs, + reference_cell=(row, column), + net_boundary_flux=net_flux, + ) + + def solve(self, assembly: PressureCorrectionAssembly) -> PressureCorrectionResult: + """Solve the gauged sparse system and return a cell-centered correction.""" + if not isinstance(assembly, PressureCorrectionAssembly): + raise TypeError("assembly must be a PressureCorrectionAssembly") + solution = np.asarray(spsolve(assembly.matrix, assembly.rhs), dtype=np.float64) + if not np.all(np.isfinite(solution)): + raise RuntimeError("pressure-correction solve produced non-finite values") + + correction = ScalarField(assembly.mesh, name="pressure_correction") + correction.set_values(solution.reshape((assembly.mesh.ny, assembly.mesh.nx))) + residual = assembly.matrix @ solution - assembly.rhs + relative_residual = float( + np.linalg.norm(residual) / max(float(np.linalg.norm(assembly.rhs)), 1.0) + ) + return PressureCorrectionResult( + correction=correction, + relative_residual=relative_residual, + net_boundary_flux=assembly.net_boundary_flux, + ) + + def predict(self, predicted_velocity: VectorField) -> PressureCorrectionResult: + """Assemble and solve one pressure correction in a single call.""" + return self.solve(self.assemble(predicted_velocity)) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/projection.py b/Exp_solver_dev_tr/src/fvm/projection.py new file mode 100644 index 0000000000000..80fc0cb2dfbe4 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/projection.py @@ -0,0 +1,162 @@ +"""Velocity and pressure correction for one staggered-grid projection step.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Real + +import numpy as np + +from .fields import ScalarField, VectorField +from .mesh import FloatArray +from .operators import divergence +from .pressure_correction import PressureCorrectionResult + + +@dataclass(frozen=True, slots=True) +class ProjectionResult: + """Corrected fields and continuity diagnostics from one projection step.""" + + velocity: VectorField + pressure: ScalarField + pressure_correction: ScalarField + divergence_before: FloatArray + divergence_after: FloatArray + global_mass_imbalance: float + pressure_solve_residual: float + + @property + def max_divergence_before(self) -> float: + """Largest absolute cell divergence before velocity correction.""" + return float(np.max(np.abs(self.divergence_before))) + + @property + def max_divergence_after(self) -> float: + """Largest absolute cell divergence after velocity correction.""" + return float(np.max(np.abs(self.divergence_after))) + + +def _finite_cell_values(field: ScalarField, name: str) -> FloatArray: + """Validate a cell-centered scalar field before updating its values.""" + if not isinstance(field, ScalarField): + raise TypeError(f"{name} must be a ScalarField") + if field.location != "cell_center": + raise ValueError(f"{name} must be cell-centered") + values = np.asarray(field.values, dtype=np.float64) + if values.shape != field.mesh.shape_for_location("cell_center"): + raise ValueError(f"{name} values have an invalid shape") + if not np.all(np.isfinite(values)): + raise ValueError(f"{name} values must all be finite") + return values + + +class ProjectionCorrector: + """Correct a predicted MAC velocity and update pressure for one time step. + + The correction uses the same two-point face gradient as the M4 five-point + pressure matrix. Using a different gradient stencil here would make the + pressure solve and continuity correction inconsistent. + """ + + def __init__(self, density: float, time_step: float) -> None: + """Create a corrector using the density and time step of the predictor.""" + for name, value in (("density", density), ("time_step", time_step)): + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + self.density = float(density) + self.time_step = float(time_step) + + def correct_velocity( + self, predicted_velocity: VectorField, correction: ScalarField + ) -> VectorField: + """Return `u* - dt/rho grad(p')`, preserving normal wall velocities. + + Only internal faces are updated. The pressure matrix uses homogeneous + Neumann conditions, so correction gradients at outer normal faces are + zero and their predicted wall velocities remain unchanged. + """ + if not isinstance(predicted_velocity, VectorField): + raise TypeError("predicted_velocity must be a VectorField") + correction_values = _finite_cell_values(correction, "correction") + mesh = predicted_velocity.mesh + if correction.mesh != mesh: + raise ValueError("correction and velocity fields must use the same mesh") + + u_values = np.asarray(predicted_velocity.u.values, dtype=np.float64) + v_values = np.asarray(predicted_velocity.v.values, dtype=np.float64) + if u_values.shape != mesh.shape_for_location("x_face"): + raise ValueError("u values have an invalid shape") + if v_values.shape != mesh.shape_for_location("y_face"): + raise ValueError("v values have an invalid shape") + if not np.all(np.isfinite(u_values)) or not np.all(np.isfinite(v_values)): + raise ValueError("predicted velocity values must all be finite") + + corrected_u = u_values.copy() + corrected_v = v_values.copy() + corrected_u[:, 1:-1] -= ( + self.time_step + / self.density + * (correction_values[:, 1:] - correction_values[:, :-1]) + / mesh.dx + ) + corrected_v[1:-1, :] -= ( + self.time_step + / self.density + * (correction_values[1:, :] - correction_values[:-1, :]) + / mesh.dy + ) + + corrected_velocity = VectorField(mesh, name="corrected_velocity") + corrected_velocity.set_values(corrected_u, corrected_v) + return corrected_velocity + + def correct_pressure(self, pressure: ScalarField, correction: ScalarField) -> ScalarField: + """Return updated pressure `p + p'` without modifying either input.""" + pressure_values = _finite_cell_values(pressure, "pressure") + correction_values = _finite_cell_values(correction, "correction") + if pressure.mesh != correction.mesh: + raise ValueError("pressure and correction fields must use the same mesh") + updated_pressure = ScalarField(pressure.mesh, name="corrected_pressure") + updated_pressure.set_values(pressure_values + correction_values) + return updated_pressure + + def project( + self, + predicted_velocity: VectorField, + pressure: ScalarField, + pressure_correction: PressureCorrectionResult, + ) -> ProjectionResult: + """Correct velocity/pressure and report cell and global conservation. + + The input fields remain unchanged. ``global_mass_imbalance`` is the + domain integral of the corrected velocity divergence; for unit-depth + 2D meshes it equals the net boundary volume flux. + """ + if not isinstance(pressure_correction, PressureCorrectionResult): + raise TypeError("pressure_correction must be a PressureCorrectionResult") + if predicted_velocity.mesh != pressure.mesh: + raise ValueError("pressure and velocity fields must use the same mesh") + if pressure_correction.correction.mesh != predicted_velocity.mesh: + raise ValueError("pressure correction and velocity fields must use the same mesh") + + divergence_before = divergence(predicted_velocity) + corrected_velocity = self.correct_velocity( + predicted_velocity, pressure_correction.correction + ) + corrected_pressure = self.correct_pressure(pressure, pressure_correction.correction) + divergence_after = divergence(corrected_velocity) + global_mass_imbalance = float( + np.sum(divergence_after) * predicted_velocity.mesh.cell_area + ) + return ProjectionResult( + velocity=corrected_velocity, + pressure=corrected_pressure, + pressure_correction=pressure_correction.correction, + divergence_before=divergence_before, + divergence_after=divergence_after, + global_mass_imbalance=global_mass_imbalance, + pressure_solve_residual=pressure_correction.relative_residual, + ) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/schemas/case-v1.schema.json b/Exp_solver_dev_tr/src/fvm/schemas/case-v1.schema.json new file mode 100644 index 0000000000000..95cb452bab028 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/schemas/case-v1.schema.json @@ -0,0 +1,157 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://independent-fvm.local/schemas/case-v1.schema.json", + "title": "Independent FVM problem definition, version 1.0", + "description": "Framework-neutral SI input contract for the structured 2D incompressible solver.", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "case_id", + "units", + "physics", + "domain", + "mesh", + "material", + "initial_conditions", + "boundary_conditions", + "solver" + ], + "properties": { + "schema_version": {"const": "1.0"}, + "case_id": {"type": "string", "minLength": 1, "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]*$"}, + "description": {"type": "string"}, + "units": {"const": "SI"}, + "physics": { + "type": "object", + "additionalProperties": false, + "required": ["model", "transient"], + "properties": { + "model": {"const": "incompressible_laminar"}, + "transient": {"type": "boolean"} + } + }, + "domain": { + "type": "object", + "additionalProperties": false, + "required": ["type", "width_m", "height_m"], + "properties": { + "type": {"const": "rectangle"}, + "width_m": {"type": "number", "exclusiveMinimum": 0}, + "height_m": {"type": "number", "exclusiveMinimum": 0} + } + }, + "mesh": { + "type": "object", + "additionalProperties": false, + "required": ["type", "nx", "ny"], + "properties": { + "type": {"const": "uniform_cartesian"}, + "nx": {"type": "integer", "minimum": 2}, + "ny": {"type": "integer", "minimum": 2} + } + }, + "material": { + "type": "object", + "additionalProperties": false, + "required": ["type", "density_kg_m3", "dynamic_viscosity_pa_s"], + "properties": { + "type": {"const": "newtonian_fluid"}, + "density_kg_m3": {"type": "number", "exclusiveMinimum": 0}, + "dynamic_viscosity_pa_s": {"type": "number", "exclusiveMinimum": 0} + } + }, + "initial_conditions": { + "type": "object", + "additionalProperties": false, + "required": ["u_m_s", "v_m_s", "pressure_pa"], + "properties": { + "u_m_s": {"type": "number"}, + "v_m_s": {"type": "number"}, + "pressure_pa": {"type": "number"} + } + }, + "boundary_conditions": { + "type": "object", + "additionalProperties": false, + "required": ["west", "east", "south", "north", "pressure_correction"], + "properties": { + "west": {"$ref": "#/$defs/velocity_wall"}, + "east": {"$ref": "#/$defs/velocity_wall"}, + "south": {"$ref": "#/$defs/velocity_wall"}, + "north": {"$ref": "#/$defs/velocity_wall"}, + "pressure_correction": {"const": "homogeneous_neumann"} + } + }, + "solver": { + "type": "object", + "additionalProperties": false, + "required": ["max_steps"], + "properties": { + "max_time_step_s": {"type": "number", "exclusiveMinimum": 0}, + "minimum_time_step_s": {"type": "number", "exclusiveMinimum": 0}, + "max_steps": {"type": "integer", "minimum": 1}, + "cfl_limit": {"type": "number", "exclusiveMinimum": 0, "maximum": 1}, + "velocity_tolerance_m_s": {"type": "number", "exclusiveMinimum": 0}, + "continuity_tolerance_s_inv": {"type": "number", "exclusiveMinimum": 0}, + "mass_tolerance_m2_s": {"type": "number", "exclusiveMinimum": 0}, + "momentum_residual_tolerance": {"type": "number", "exclusiveMinimum": 0}, + "pressure_residual_tolerance": {"type": "number", "exclusiveMinimum": 0}, + "end_time_s": {"type": "number", "exclusiveMinimum": 0}, + "max_inner_iterations_per_time_step": {"type": "integer", "minimum": 1} + } + } + }, + "$defs": { + "velocity_wall": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": ["type"], + "properties": {"type": {"const": "no_slip_wall"}} + }, + { + "type": "object", + "additionalProperties": false, + "required": ["type", "velocity_m_s"], + "properties": { + "type": {"const": "moving_wall"}, + "velocity_m_s": { + "type": "array", + "items": {"type": "number"}, + "minItems": 2, + "maxItems": 2 + } + } + }, + { + "type": "object", + "additionalProperties": false, + "required": ["type", "velocity_profile"], + "properties": { + "type": {"const": "moving_wall"}, + "velocity_profile": { + "type": "array", + "minItems": 2, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["time_s", "velocity_m_s"], + "properties": { + "time_s": {"type": "number", "minimum": 0}, + "velocity_m_s": { + "type": "array", + "items": {"type": "number"}, + "minItems": 2, + "maxItems": 2 + } + } + } + } + } + } + ] + } + } +} \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm/simulation.py b/Exp_solver_dev_tr/src/fvm/simulation.py new file mode 100644 index 0000000000000..4653692d9ff8f --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm/simulation.py @@ -0,0 +1,674 @@ +"""Transient execution and convergence monitoring for the projection solver.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite +from numbers import Integral, Real +from collections.abc import Callable + +import numpy as np + +from .boundary_conditions import ( + BoundaryConditions, + FixedValue, + MovingWall, + NoSlipWall, +) +from .fields import ScalarField, VectorField +from .mesh import BOUNDARY_NAMES, FloatArray +from .momentum import MomentumPredictor +from .pressure_correction import PressureCorrectionSolver +from .projection import ProjectionCorrector + +StepObserver = Callable[["StepDiagnostics", VectorField, ScalarField], None] +StateObserver = Callable[["SimulationState"], None] +BoundaryConditionsAtTime = Callable[[float], BoundaryConditions] +BoundaryConditionsOverInterval = Callable[[float, float], BoundaryConditions] + + +@dataclass(frozen=True, slots=True) +class StepDiagnostics: + """Quantities recorded after each completed projection time step.""" + + step: int + time: float | None + pseudo_time: float | None + time_step: float + cfl_number: float + velocity_change: float + max_divergence_before: float + max_divergence_after: float + global_mass_imbalance: float + u_momentum_residual: float + v_momentum_residual: float + pressure_residual: float + inner_iterations: int = 1 + + +@dataclass(frozen=True, slots=True) +class SimulationState: + """Complete solver state at a completed step boundary.""" + + velocity: VectorField + pressure: ScalarField + completed_steps: int + elapsed_time: float + pseudo_time: float + steady_time_step: float | None + history: tuple[StepDiagnostics, ...] + + +@dataclass(frozen=True, slots=True) +class SimulationSettings: + """Immutable input settings retained for reproducible output export.""" + + density: float + viscosity: float + max_time_step: float + max_steps: int + cfl_limit: float + velocity_tolerance: float + continuity_tolerance: float + mass_tolerance: float + momentum_residual_tolerance: float + pressure_residual_tolerance: float + minimum_time_step: float + transient: bool + end_time: float | None + max_inner_iterations_per_time_step: int + + +@dataclass(frozen=True, slots=True) +class SimulationResult: + """Final fields, convergence state, and immutable step history.""" + + velocity: VectorField + pressure: ScalarField + history: tuple[StepDiagnostics, ...] + settings: SimulationSettings + converged: bool + termination_reason: str + + @property + def steps(self) -> int: + """Number of projection steps completed.""" + return len(self.history) + + @property + def final_time(self) -> float | None: + """Physical time reached by the final completed step.""" + return self.history[-1].time if self.history else 0.0 + + @property + def final_pseudo_time(self) -> float | None: + """Pseudo-time accumulated by a steady-state run.""" + return self.history[-1].pseudo_time if self.history else 0.0 + + +def _positive_number(name: str, value: float) -> float: + """Validate a finite positive scalar simulation setting.""" + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + return float(value) + + +def _wall_velocities(boundary_conditions: BoundaryConditions) -> dict[str, tuple[float, float]]: + """Read the vector velocity prescribed at every physical wall.""" + if not isinstance(boundary_conditions, BoundaryConditions): + raise TypeError("boundary_conditions must be BoundaryConditions") + wall_values: dict[str, tuple[float, float]] = {} + for side in BOUNDARY_NAMES: + try: + condition = boundary_conditions.get("velocity", side) + except KeyError as error: + raise ValueError(f"missing velocity boundary condition for {side}") from error + if isinstance(condition, (NoSlipWall, MovingWall)): + wall_values[side] = condition.velocity + elif isinstance(condition, FixedValue) and isinstance(condition.value, tuple): + wall_values[side] = condition.value + else: + raise ValueError( + f"velocity boundary {side} must prescribe both velocity components" + ) + return wall_values + + +def _advective_rate( + velocity: VectorField, wall_velocities: dict[str, tuple[float, float]] +) -> float: + """Estimate the global explicit-convection rate including moving walls.""" + mesh = velocity.mesh + u_values = np.asarray(velocity.u.values, dtype=np.float64) + v_values = np.asarray(velocity.v.values, dtype=np.float64) + if u_values.shape != mesh.shape_for_location("x_face"): + raise ValueError("u values have an invalid shape") + if v_values.shape != mesh.shape_for_location("y_face"): + raise ValueError("v values have an invalid shape") + if not np.all(np.isfinite(u_values)) or not np.all(np.isfinite(v_values)): + raise ValueError("velocity values must all be finite") + + max_u = float(np.max(np.abs(u_values))) + max_v = float(np.max(np.abs(v_values))) + max_u = max(max_u, *(abs(wall[0]) for wall in wall_velocities.values())) + max_v = max(max_v, *(abs(wall[1]) for wall in wall_velocities.values())) + return max_u / mesh.dx + max_v / mesh.dy + + +class TransientSolver: + """Run repeated momentum-predictor, pressure-solve, and projection steps. + + ``max_time_step`` is a cap. Each step is reduced as needed to satisfy + `dt * (max|u|/dx + max|v|/dy) <= cfl_limit`; moving-wall speeds are included + in those maxima. Diffusion is implicit in M3, so only explicit convection + contributes to this CFL restriction. + + Steady state is reported only when velocity change, continuity, global + mass balance, momentum residuals, and pressure residual all meet their + configured tolerances. Reaching ``max_steps`` instead returns a result + with ``converged=False`` and an explicit termination reason. + """ + + def __init__( + self, + density: float, + viscosity: float, + max_time_step: float, + max_steps: int = 1000, + cfl_limit: float = 0.5, + velocity_tolerance: float = 1e-6, + continuity_tolerance: float = 1e-8, + mass_tolerance: float = 1e-10, + momentum_residual_tolerance: float = 1e-10, + pressure_residual_tolerance: float = 1e-10, + minimum_time_step: float = 1e-12, + transient: bool = True, + end_time: float | None = None, + max_inner_iterations_per_time_step: int = 100, + ) -> None: + """Configure material properties, time-step limits, and stop criteria.""" + self.density = _positive_number("density", density) + if isinstance(viscosity, bool) or not isinstance(viscosity, Real): + raise TypeError("viscosity must be a finite non-negative number") + if not isfinite(viscosity) or viscosity < 0.0: + raise ValueError("viscosity must be a finite non-negative number") + self.viscosity = float(viscosity) + self.max_time_step = _positive_number("max_time_step", max_time_step) + self.minimum_time_step = _positive_number("minimum_time_step", minimum_time_step) + if self.minimum_time_step > self.max_time_step: + raise ValueError("minimum_time_step must not exceed max_time_step") + if isinstance(max_steps, bool) or not isinstance(max_steps, Integral): + raise TypeError("max_steps must be a positive integer") + if max_steps <= 0: + raise ValueError("max_steps must be a positive integer") + self.max_steps = int(max_steps) + self.cfl_limit = _positive_number("cfl_limit", cfl_limit) + if self.cfl_limit > 1.0: + raise ValueError("cfl_limit must not exceed 1 for explicit upwind convection") + self.velocity_tolerance = _positive_number("velocity_tolerance", velocity_tolerance) + self.continuity_tolerance = _positive_number( + "continuity_tolerance", continuity_tolerance + ) + self.mass_tolerance = _positive_number("mass_tolerance", mass_tolerance) + self.momentum_residual_tolerance = _positive_number( + "momentum_residual_tolerance", momentum_residual_tolerance + ) + self.pressure_residual_tolerance = _positive_number( + "pressure_residual_tolerance", pressure_residual_tolerance + ) + if not isinstance(transient, bool): + raise TypeError("transient must be a boolean") + self.transient = transient + self.end_time = ( + None if end_time is None else _positive_number("end_time", end_time) + ) + if self.end_time is not None and not self.transient: + raise ValueError("end_time is only valid for transient simulations") + if ( + isinstance(max_inner_iterations_per_time_step, bool) + or not isinstance(max_inner_iterations_per_time_step, Integral) + or max_inner_iterations_per_time_step <= 0 + ): + raise ValueError("max_inner_iterations_per_time_step must be a positive integer") + self.max_inner_iterations_per_time_step = int( + max_inner_iterations_per_time_step + ) + self.settings = SimulationSettings( + density=self.density, + viscosity=self.viscosity, + max_time_step=self.max_time_step, + max_steps=self.max_steps, + cfl_limit=self.cfl_limit, + velocity_tolerance=self.velocity_tolerance, + continuity_tolerance=self.continuity_tolerance, + mass_tolerance=self.mass_tolerance, + momentum_residual_tolerance=self.momentum_residual_tolerance, + pressure_residual_tolerance=self.pressure_residual_tolerance, + minimum_time_step=self.minimum_time_step, + transient=self.transient, + end_time=self.end_time, + max_inner_iterations_per_time_step=( + self.max_inner_iterations_per_time_step + ), + ) + + def estimate_time_step( + self, velocity: VectorField, boundary_conditions: BoundaryConditions + ) -> float: + """Return the maximum time step allowed by the current convective CFL.""" + if not isinstance(velocity, VectorField): + raise TypeError("velocity must be a VectorField") + walls = _wall_velocities(boundary_conditions) + rate = _advective_rate(velocity, walls) + if rate == 0.0: + return self.max_time_step + time_step = min(self.max_time_step, self.cfl_limit / rate) + if time_step < self.minimum_time_step: + raise RuntimeError( + f"stable time step {time_step:.6g} is below minimum_time_step " + f"{self.minimum_time_step:.6g}" + ) + return time_step + + def run( + self, + initial_velocity: VectorField, + initial_pressure: ScalarField, + boundary_conditions: BoundaryConditions, + *, + step_observer: StepObserver | None = None, + state_observer: StateObserver | None = None, + state_observer_interval: int = 1, + restart_state: SimulationState | None = None, + boundary_conditions_at_time: BoundaryConditionsAtTime | None = None, + boundary_conditions_over_interval: BoundaryConditionsOverInterval | None = None, + ) -> SimulationResult: + """Advance steady iterations or transient physical steps. + + Steady runs use a fixed pseudo-time step. Finite transient runs keep the + previous physical-time state fixed while iterating the nonlinear + predictor/projection system to tolerance at each physical time step. + Transient runs without ``end_time`` retain the legacy march-to-steady + behavior for existing case files. + + When ``step_observer`` is supplied, it is called after each completed + projection with that step's diagnostics and defensive copies of the + velocity and pressure fields. Observers can visualize or export state + without being able to mutate the running simulation. + """ + if not isinstance(initial_velocity, VectorField): + raise TypeError("initial_velocity must be a VectorField") + if not isinstance(initial_pressure, ScalarField): + raise TypeError("initial_pressure must be a ScalarField") + if initial_pressure.mesh != initial_velocity.mesh: + raise ValueError("initial pressure and velocity must use the same mesh") + if initial_pressure.location != "cell_center": + raise ValueError("initial pressure must be cell-centered") + if ( + isinstance(state_observer_interval, bool) + or not isinstance(state_observer_interval, Integral) + or state_observer_interval <= 0 + ): + raise ValueError("state_observer_interval must be a positive integer") + walls = _wall_velocities(boundary_conditions) + + if restart_state is None: + velocity = initial_velocity + pressure = initial_pressure + elapsed_time = 0.0 + pseudo_time = 0.0 + history: list[StepDiagnostics] = [] + completed_steps = 0 + restored_steady_time_step = None + else: + self._validate_restart_state(restart_state, initial_velocity) + velocity = self._copy_velocity(restart_state.velocity) + pressure = self._copy_pressure(restart_state.pressure) + elapsed_time = restart_state.elapsed_time + pseudo_time = restart_state.pseudo_time + history = list(restart_state.history) + completed_steps = restart_state.completed_steps + restored_steady_time_step = restart_state.steady_time_step + finite_transient = self.transient and self.end_time is not None + steady_time_step = restored_steady_time_step or self.max_time_step + if ( + finite_transient + and elapsed_time >= self.end_time - 1e-14 * max(1.0, self.end_time) + ): + return SimulationResult( + velocity=velocity, + pressure=pressure, + history=tuple(history), + settings=self.settings, + converged=True, + termination_reason="final_time_reached", + ) + if not self.transient: + if restored_steady_time_step is None: + initial_rate = _advective_rate(velocity, walls) + if initial_rate > 0.0: + steady_time_step = min( + self.max_time_step, + self.cfl_limit / (4.0 * initial_rate), + ) + if steady_time_step < self.minimum_time_step: + raise RuntimeError( + f"safe steady pseudo-time step {steady_time_step:.6g} is below " + f"minimum_time_step {self.minimum_time_step:.6g}" + ) + + for step in range(completed_steps + 1, self.max_steps + 1): + if finite_transient: + remaining_time = self.end_time - elapsed_time + if remaining_time <= 0.0: + break + time_step, interval_conditions = self._transient_step_size( + velocity, + elapsed_time, + remaining_time, + boundary_conditions, + boundary_conditions_at_time, + boundary_conditions_over_interval, + ) + step_time = elapsed_time + time_step + step_conditions = ( + boundary_conditions_at_time(step_time) + if boundary_conditions_at_time is not None + else boundary_conditions + ) + temporal_velocity = velocity + iterate_velocity = velocity + iterate_pressure = pressure + diagnostics: StepDiagnostics | None = None + for inner_iteration in range(1, self.max_inner_iterations_per_time_step + 1): + momentum, projection = self._project( + iterate_velocity, + iterate_pressure, + step_conditions, + time_step, + temporal_velocity=temporal_velocity, + ) + velocity_change = self._velocity_change( + projection.velocity, iterate_velocity + ) + advective_rate = _advective_rate( + iterate_velocity, + _wall_velocities(interval_conditions), + ) + diagnostics = StepDiagnostics( + step=step, + time=step_time, + pseudo_time=None, + time_step=time_step, + cfl_number=time_step * advective_rate, + velocity_change=velocity_change, + max_divergence_before=projection.max_divergence_before, + max_divergence_after=projection.max_divergence_after, + global_mass_imbalance=projection.global_mass_imbalance, + u_momentum_residual=momentum.u_relative_residual, + v_momentum_residual=momentum.v_relative_residual, + pressure_residual=projection.pressure_solve_residual, + inner_iterations=inner_iteration, + ) + iterate_velocity = projection.velocity + iterate_pressure = projection.pressure + if self._has_converged(diagnostics): + break + + assert diagnostics is not None + history.append(diagnostics) + velocity = iterate_velocity + pressure = iterate_pressure + elapsed_time = step_time + step_converged = self._has_converged(diagnostics) + else: + step_conditions = ( + boundary_conditions_at_time(elapsed_time) + if boundary_conditions_at_time is not None + else boundary_conditions + ) + advective_rate = _advective_rate( + velocity, _wall_velocities(step_conditions) + ) + if self.transient: + time_step = self.estimate_time_step(velocity, step_conditions) + step_conditions = ( + boundary_conditions_at_time(elapsed_time + time_step) + if boundary_conditions_at_time is not None + else boundary_conditions + ) + advective_rate = _advective_rate( + velocity, _wall_velocities(step_conditions) + ) + else: + time_step = steady_time_step + cfl_number = time_step * advective_rate + momentum, projection = self._project( + velocity, pressure, step_conditions, time_step + ) + velocity_change = self._velocity_change( + projection.velocity, velocity + ) + if self.transient: + elapsed_time += time_step + physical_time: float | None = elapsed_time + step_pseudo_time: float | None = None + else: + pseudo_time += time_step + physical_time = None + step_pseudo_time = pseudo_time + diagnostics = StepDiagnostics( + step=step, + time=physical_time, + pseudo_time=step_pseudo_time, + time_step=time_step, + cfl_number=cfl_number, + velocity_change=velocity_change, + max_divergence_before=projection.max_divergence_before, + max_divergence_after=projection.max_divergence_after, + global_mass_imbalance=projection.global_mass_imbalance, + u_momentum_residual=momentum.u_relative_residual, + v_momentum_residual=momentum.v_relative_residual, + pressure_residual=projection.pressure_solve_residual, + ) + history.append(diagnostics) + velocity = projection.velocity + pressure = projection.pressure + step_converged = self._has_converged(diagnostics) + + if step_observer is not None: + # Observers receive copies so visualization code cannot alter + # the state that will be advanced on the next time step. + velocity_snapshot = VectorField(velocity.mesh, name="observer_velocity") + velocity_snapshot.set_values(velocity.u.values, velocity.v.values) + pressure_snapshot = ScalarField( + pressure.mesh, name="observer_pressure" + ) + pressure_snapshot.set_values(pressure.values) + step_observer(diagnostics, velocity_snapshot, pressure_snapshot) + if ( + state_observer is not None + and step % state_observer_interval == 0 + and (not finite_transient or step_converged) + ): + state_observer( + SimulationState( + velocity=self._copy_velocity(velocity), + pressure=self._copy_pressure(pressure), + completed_steps=step, + elapsed_time=elapsed_time, + pseudo_time=pseudo_time, + steady_time_step=( + steady_time_step if not self.transient else None + ), + history=tuple(history), + ) + ) + if finite_transient: + if not step_converged: + return SimulationResult( + velocity=velocity, + pressure=pressure, + history=tuple(history), + settings=self.settings, + converged=False, + termination_reason="time_step_not_converged", + ) + if elapsed_time >= self.end_time - 1e-14 * max(1.0, self.end_time): + return SimulationResult( + velocity=velocity, + pressure=pressure, + history=tuple(history), + settings=self.settings, + converged=True, + termination_reason="final_time_reached", + ) + elif step_converged: + return SimulationResult( + velocity=velocity, + pressure=pressure, + history=tuple(history), + settings=self.settings, + converged=True, + termination_reason="converged", + ) + + return SimulationResult( + velocity=velocity, + pressure=pressure, + history=tuple(history), + settings=self.settings, + converged=False, + termination_reason="maximum_steps_reached", + ) + + @staticmethod + def _copy_velocity(velocity: VectorField) -> VectorField: + """Make an independent copy of staggered velocity fields.""" + copied = VectorField(velocity.mesh, name=velocity.name) + copied.set_values(velocity.u.values, velocity.v.values) + return copied + + @staticmethod + def _copy_pressure(pressure: ScalarField) -> ScalarField: + """Make an independent copy of a cell-centered pressure field.""" + copied = ScalarField(pressure.mesh, name=pressure.name) + copied.set_values(pressure.values) + return copied + + @staticmethod + def _validate_restart_state( + state: SimulationState, initial_velocity: VectorField + ) -> None: + """Reject inconsistent or incompatible restored solver state.""" + if not isinstance(state, SimulationState): + raise TypeError("restart_state must be a SimulationState") + if state.velocity.mesh != initial_velocity.mesh: + raise ValueError("restart state and initial velocity must use the same mesh") + if state.pressure.mesh != initial_velocity.mesh: + raise ValueError("restart state pressure must use the same mesh") + if state.pressure.location != "cell_center": + raise ValueError("restart state pressure must be cell-centered") + if ( + isinstance(state.completed_steps, bool) + or not isinstance(state.completed_steps, Integral) + or state.completed_steps < 0 + ): + raise ValueError("restart state completed_steps must be a non-negative integer") + for name, value in ( + ("elapsed_time", state.elapsed_time), + ("pseudo_time", state.pseudo_time), + ): + if not isfinite(value) or value < 0.0: + raise ValueError(f"restart state {name} must be finite and non-negative") + if state.steady_time_step is not None and ( + not isfinite(state.steady_time_step) or state.steady_time_step <= 0.0 + ): + raise ValueError("restart state steady_time_step must be finite and positive") + if len(state.history) != state.completed_steps: + raise ValueError("restart state history must cover all completed steps") + if state.history and state.history[-1].step != state.completed_steps: + raise ValueError("restart state history step does not match completed_steps") + + def _project( + self, + velocity: VectorField, + pressure: ScalarField, + boundary_conditions: BoundaryConditions, + time_step: float, + *, + temporal_velocity: VectorField | None = None, + ): + """Run one momentum, pressure-correction, and projection operation.""" + momentum = MomentumPredictor( + self.density, self.viscosity, time_step + ).predict( + velocity, + pressure, + boundary_conditions, + temporal_velocity=temporal_velocity, + ) + pressure_correction = PressureCorrectionSolver( + self.density, time_step + ).predict(momentum.velocity) + projection = ProjectionCorrector(self.density, time_step).project( + momentum.velocity, pressure, pressure_correction + ) + return momentum, projection + + @staticmethod + def _velocity_change(current: VectorField, previous: VectorField) -> float: + """Return the maximum staggered-face velocity difference.""" + return max( + float(np.max(np.abs(current.u.values - previous.u.values))), + float(np.max(np.abs(current.v.values - previous.v.values))), + ) + + def _transient_step_size( + self, + velocity: VectorField, + current_time: float, + remaining_time: float, + boundary_conditions: BoundaryConditions, + boundary_conditions_at_time: BoundaryConditionsAtTime | None, + boundary_conditions_over_interval: BoundaryConditionsOverInterval | None, + ) -> tuple[float, BoundaryConditions]: + """Choose a CFL-safe step using wall speeds over its full interval.""" + candidate = min(self.max_time_step, remaining_time) + interval_conditions = boundary_conditions + for _ in range(8): + end_time = current_time + candidate + interval_conditions = ( + boundary_conditions_over_interval(current_time, end_time) + if boundary_conditions_over_interval is not None + else ( + boundary_conditions_at_time(end_time) + if boundary_conditions_at_time is not None + else boundary_conditions + ) + ) + rate = _advective_rate(velocity, _wall_velocities(interval_conditions)) + allowed = self.max_time_step if rate == 0.0 else self.cfl_limit / rate + updated = min(candidate, allowed) + if abs(updated - candidate) <= 1e-14 * max(1.0, candidate): + break + candidate = updated + if candidate < self.minimum_time_step and remaining_time > self.minimum_time_step: + raise RuntimeError( + f"stable time step {candidate:.6g} is below minimum_time_step " + f"{self.minimum_time_step:.6g}" + ) + return candidate, interval_conditions + + def _has_converged(self, diagnostics: StepDiagnostics) -> bool: + """Require steady velocity, continuity, mass, and solver tolerances.""" + return ( + diagnostics.velocity_change <= self.velocity_tolerance + and diagnostics.max_divergence_after <= self.continuity_tolerance + and abs(diagnostics.global_mass_imbalance) <= self.mass_tolerance + and diagnostics.u_momentum_residual <= self.momentum_residual_tolerance + and diagnostics.v_momentum_residual <= self.momentum_residual_tolerance + and diagnostics.pressure_residual <= self.pressure_residual_tolerance + ) \ No newline at end of file diff --git a/Exp_solver_dev_tr/src/fvm3d/__init__.py b/Exp_solver_dev_tr/src/fvm3d/__init__.py new file mode 100644 index 0000000000000..95951c678fb6f --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm3d/__init__.py @@ -0,0 +1,22 @@ +"""Three-dimensional external-flow finite-volume reference solver.""" + +from .solver import ( + FiniteWingResult, + FiniteWingSettings, + FiniteWingSolver, + FiniteWingIteration, + FiniteWingTransientIteration, + FiniteWingTransientSettings, +) +from .visualization import LiveFiniteWingPlotter, plot_finite_wing_result + +__all__ = [ + "FiniteWingResult", + "FiniteWingSettings", + "FiniteWingSolver", + "FiniteWingIteration", + "FiniteWingTransientIteration", + "FiniteWingTransientSettings", + "LiveFiniteWingPlotter", + "plot_finite_wing_result", +] diff --git a/Exp_solver_dev_tr/src/fvm3d/solver.py b/Exp_solver_dev_tr/src/fvm3d/solver.py new file mode 100644 index 0000000000000..4244eadf3ebbd --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm3d/solver.py @@ -0,0 +1,1086 @@ +"""Steady 3D incompressible flow around a finite rectangular wing.""" + +from __future__ import annotations + +from dataclasses import dataclass +from math import cos, isfinite, pi, sin +from numbers import Integral, Real +from typing import Callable + +import numpy as np +from numpy.typing import NDArray +from scipy.sparse import coo_matrix, csr_matrix +from scipy.sparse.linalg import LinearOperator, cg + +FloatArray = NDArray[np.float64] +BoolArray = NDArray[np.bool_] +IndexArray = NDArray[np.int64] + + +@dataclass(frozen=True, slots=True) +class FiniteWingSettings: + """Fluid, grid, wing, and iteration controls; dimensional values are SI. + + The wing chord is aligned with x, its span with z, and its normal with y. + Positive angle of attack is represented in the wing-fixed frame by a + negative y component of the incoming flow. Exactly one of ``inlet_speed``, + ``inlet_velocity_x``, and ``inlet_velocity_y`` must be supplied. + + The solver uses pseudo-time steps internally to march toward a steady + solution. ``max_iterations`` controls the number of such iterations; no + physical-time horizon is modeled. + """ + + length_x: float = 6.0 + length_y: float = 3.0 + length_z: float = 3.0 + nx: int = 48 + ny: int = 25 + nz: int = 25 + density: float = 1.0 + dynamic_viscosity: float = 0.001 + wing_leading_edge_x: float = 1.5 + wing_chord: float = 1.0 + wing_span: float = 1.5 + wing_thickness: float = 0.12 + angle_of_attack_degrees: float = 5.0 + inlet_speed: float | None = 1.0 + inlet_velocity_x: float | None = None + inlet_velocity_y: float | None = None + pseudo_time_step_cap: float = 0.005 + minimum_pseudo_time_step: float = 1e-8 + max_iterations: int = 200 + cfl_limit: float = 0.25 + pressure_tolerance: float = 1e-8 + max_pressure_iterations: int = 1000 + + def __post_init__(self) -> None: + for name in ( + "length_x", + "length_y", + "length_z", + "density", + "dynamic_viscosity", + "wing_chord", + "wing_span", + "wing_thickness", + "pseudo_time_step_cap", + "minimum_pseudo_time_step", + "pressure_tolerance", + ): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + for name in ("nx", "ny", "nz"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Integral): + raise TypeError(f"{name} must be an integer") + if value < 4: + raise ValueError(f"{name} must be at least 4") + for name in ("wing_leading_edge_x", "angle_of_attack_degrees"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite number") + if not isfinite(value): + raise ValueError(f"{name} must be a finite number") + if not -5.0 <= self.angle_of_attack_degrees <= 20.0: + raise ValueError("angle_of_attack_degrees must be between -5 and 20") + for name in ("inlet_speed", "inlet_velocity_x", "inlet_velocity_y"): + value = getattr(self, name) + if value is not None and ( + isinstance(value, bool) + or not isinstance(value, Real) + or not isfinite(value) + ): + raise ValueError(f"{name} must be a finite number or None") + if sum( + value is not None + for value in (self.inlet_speed, self.inlet_velocity_x, self.inlet_velocity_y) + ) != 1: + raise ValueError( + "specify exactly one of inlet_speed, inlet_velocity_x, " + "or inlet_velocity_y" + ) + if self.inlet_speed is not None and self.inlet_speed <= 0.0: + raise ValueError("inlet_speed must be positive") + if self.inlet_velocity_x is not None and self.inlet_velocity_x <= 0.0: + raise ValueError("inlet_velocity_x must be positive") + alpha = self.angle_of_attack_degrees * pi / 180.0 + if self.inlet_velocity_y is not None: + if abs(sin(alpha)) <= 1e-12: + raise ValueError( + "inlet_velocity_y cannot determine speed at zero angle of attack" + ) + if -self.inlet_velocity_y / sin(alpha) <= 0.0: + raise ValueError( + "inlet_velocity_y sign must match the configured angle of attack" + ) + if ( + isinstance(self.max_iterations, bool) + or not isinstance(self.max_iterations, Integral) + or self.max_iterations < 1 + ): + raise ValueError("max_iterations must be a positive integer") + if self.minimum_pseudo_time_step > self.pseudo_time_step_cap: + raise ValueError( + "minimum_pseudo_time_step must not exceed pseudo_time_step_cap" + ) + if ( + isinstance(self.cfl_limit, bool) + or not isinstance(self.cfl_limit, Real) + or not isfinite(self.cfl_limit) + or not 0.0 < self.cfl_limit <= 1.0 + ): + raise ValueError("cfl_limit must be in (0, 1]") + if ( + isinstance(self.max_pressure_iterations, bool) + or not isinstance(self.max_pressure_iterations, Integral) + or self.max_pressure_iterations < 1 + ): + raise ValueError("max_pressure_iterations must be a positive integer") + if ( + self.wing_leading_edge_x < 0.0 + or self.wing_leading_edge_x + self.wing_chord >= self.length_x + ): + raise ValueError("the wing chord must lie inside the x domain") + if self.wing_span >= self.length_z or self.wing_thickness >= self.length_y: + raise ValueError("the wing must fit inside the y-z domain") + + @property + def inlet_velocity(self) -> tuple[float, float, float]: + """Return the resolved ``(u, v, w)`` freestream velocity.""" + alpha = self.angle_of_attack_degrees * pi / 180.0 + cosine = cos(alpha) + sine = sin(alpha) + if self.inlet_speed is not None: + speed = float(self.inlet_speed) + elif self.inlet_velocity_x is not None: + speed = float(self.inlet_velocity_x) / cosine + else: + assert self.inlet_velocity_y is not None + speed = -float(self.inlet_velocity_y) / sine + return speed * cosine, -speed * sine, 0.0 + + @property + def reynolds_number(self) -> float: + """Return the chord-based Reynolds number for the resolved freestream.""" + speed = float(np.hypot(*self.inlet_velocity[:2])) + return self.density * speed * self.wing_chord / self.dynamic_viscosity + + +@dataclass(frozen=True, slots=True) +class FiniteWingIteration: + """Steady pseudo-time diagnostics after one projected iteration.""" + + iteration: int + pseudo_time_step: float + max_speed: float + max_divergence: float + cfl_number: float + pressure_residual: float + + +@dataclass(frozen=True, slots=True) +class FiniteWingTransientSettings: + """Physical-time controls and angle-of-attack schedule for a transient run. + + Schedule entries are ``(time_seconds, angle_degrees)`` pairs. Values + between entries are linearly interpolated, and the final angle is held + after the last entry. + """ + + end_time: float + angle_of_attack_schedule: tuple[tuple[float, float], ...] + time_step_cap: float = 0.01 + minimum_time_step: float = 1e-8 + outlet_sponge_length: float = 2.0 + + def __post_init__(self) -> None: + for name in ( + "end_time", + "time_step_cap", + "minimum_time_step", + "outlet_sponge_length", + ): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + if self.minimum_time_step > self.time_step_cap: + raise ValueError("minimum_time_step must not exceed time_step_cap") + + schedule = self.angle_of_attack_schedule + if not isinstance(schedule, (list, tuple)) or len(schedule) < 2: + raise ValueError("angle_of_attack_schedule must contain at least two points") + normalized_schedule: list[tuple[float, float]] = [] + for index, point in enumerate(schedule): + if not isinstance(point, (list, tuple)) or len(point) != 2: + raise TypeError( + "each angle-of-attack schedule entry must be a time/angle pair" + ) + point_time, angle = point + for name, value in (("schedule time", point_time), ("angle", angle)): + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite number") + if not isfinite(value): + raise ValueError(f"{name} must be a finite number") + if point_time < 0.0: + raise ValueError("schedule times must be non-negative") + if not -5.0 <= angle <= 20.0: + raise ValueError("schedule angles must be between -5 and 20 degrees") + if index == 0 and point_time != 0.0: + raise ValueError("the angle-of-attack schedule must start at time 0") + if normalized_schedule and point_time <= normalized_schedule[-1][0]: + raise ValueError("schedule times must be strictly increasing") + normalized_schedule.append((float(point_time), float(angle))) + if normalized_schedule[-1][0] < self.end_time: + raise ValueError( + "the angle-of-attack schedule must cover the configured end_time" + ) + object.__setattr__(self, "angle_of_attack_schedule", tuple(normalized_schedule)) + + def angle_of_attack_at(self, time: float) -> float: + """Return the linearly interpolated angle at physical ``time``.""" + times = [point[0] for point in self.angle_of_attack_schedule] + angles = [point[1] for point in self.angle_of_attack_schedule] + return float(np.interp(time, times, angles)) + + +@dataclass(frozen=True, slots=True) +class FiniteWingTransientIteration: + """Physical-time diagnostics after one transient flow step.""" + + iteration: int + time: float + time_step: float + angle_of_attack_degrees: float + max_speed: float + max_divergence: float + cfl_number: float + pressure_residual: float + + +@dataclass(frozen=True, slots=True) +class FiniteWingResult: + """Cell-centered velocity/pressure fields and the finite-wing geometry.""" + + velocity_x: FloatArray + velocity_y: FloatArray + velocity_z: FloatArray + pressure: FloatArray + solid_mask: BoolArray + x_centers: FloatArray + y_centers: FloatArray + z_centers: FloatArray + history: tuple[FiniteWingIteration | FiniteWingTransientIteration, ...] + settings: FiniteWingSettings + physical_time: float | None = None + angle_of_attack_degrees: float | None = None + + @property + def iterations(self) -> int: + return len(self.history) + + +IterationObserver = Callable[ + [FiniteWingIteration | FiniteWingTransientIteration, FiniteWingResult], None +] + + +def _assemble_pressure_matrix( + solid: BoolArray, + dx: float, + dy: float, + dz: float, + *, + outlet_dirichlet: bool = True, +) -> tuple[csr_matrix, IndexArray]: + """Build the pressure-correction operator over fluid cells only.""" + ny, nx, nz = solid.shape + indices = np.full(solid.shape, -1, dtype=np.int64) + indices[~solid] = np.arange(np.count_nonzero(~solid), dtype=np.int64) + coefficients_by_axis = (1.0 / dy**2, 1.0 / dx**2, 1.0 / dz**2) + directions = ( + (-1, 0, 0, coefficients_by_axis[0], False), + (1, 0, 0, coefficients_by_axis[0], False), + (0, -1, 0, coefficients_by_axis[1], False), + (0, 1, 0, coefficients_by_axis[1], True), + (0, 0, -1, coefficients_by_axis[2], False), + (0, 0, 1, coefficients_by_axis[2], False), + ) + rows: list[int] = [] + columns: list[int] = [] + values: list[float] = [] + for row in range(ny): + for column in range(nx): + for depth in range(nz): + cell_index = int(indices[row, column, depth]) + if cell_index < 0: + continue + diagonal = 0.0 + for row_offset, column_offset, depth_offset, weight, outlet in directions: + next_row = row + row_offset + next_column = column + column_offset + next_depth = depth + depth_offset + if ( + 0 <= next_row < ny + and 0 <= next_column < nx + and 0 <= next_depth < nz + ): + neighbor_index = int(indices[next_row, next_column, next_depth]) + if neighbor_index >= 0: + diagonal += weight + rows.append(cell_index) + columns.append(neighbor_index) + values.append(-weight) + elif outlet and outlet_dirichlet: + diagonal += 2.0 * weight + rows.append(cell_index) + columns.append(cell_index) + values.append(diagonal) + matrix = coo_matrix( + (values, (rows, columns)), + shape=(int(np.count_nonzero(~solid)), int(np.count_nonzero(~solid))), + ).tocsr() + return matrix, indices + + +class FiniteWingSolver: + """Iterate low-Re incompressible flow toward a steady finite-wing solution. + + Velocities are stored on MAC faces and pressure at cell centers. Momentum + uses explicit upwind advection and diffusion with internal pseudo-time + stepping; pressure is projected with a sparse conjugate-gradient solve. + The wing is a grid-aligned rectangular solid, so this reference solver is + intended for qualitative visualization, not validated aerodynamic + coefficients. + """ + + def __init__(self, settings: FiniteWingSettings = FiniteWingSettings()) -> None: + if not isinstance(settings, FiniteWingSettings): + raise TypeError("settings must be a FiniteWingSettings instance") + self.settings = settings + self.dx = settings.length_x / settings.nx + self.dy = settings.length_y / settings.ny + self.dz = settings.length_z / settings.nz + self.x_centers = (np.arange(settings.nx, dtype=np.float64) + 0.5) * self.dx + self.y_centers = (np.arange(settings.ny, dtype=np.float64) + 0.5) * self.dy + self.z_centers = (np.arange(settings.nz, dtype=np.float64) + 0.5) * self.dz + self._solid = self._make_wing_mask() + self._u_blocked = np.zeros( + (settings.ny, settings.nx + 1, settings.nz), dtype=np.bool_ + ) + self._v_blocked = np.zeros( + (settings.ny + 1, settings.nx, settings.nz), dtype=np.bool_ + ) + self._w_blocked = np.zeros( + (settings.ny, settings.nx, settings.nz + 1), dtype=np.bool_ + ) + self._u_blocked[:, 1:-1, :] = self._solid[:, :-1, :] | self._solid[:, 1:, :] + self._v_blocked[1:-1, :, :] = self._solid[:-1, :, :] | self._solid[1:, :, :] + self._w_blocked[:, :, 1:-1] = self._solid[:, :, :-1] | self._solid[:, :, 1:] + self._pressure_matrix, self._pressure_indices = _assemble_pressure_matrix( + self._solid, self.dx, self.dy, self.dz + ) + self._pressure_diagonal = self._pressure_matrix.diagonal() + neumann_matrix, _ = _assemble_pressure_matrix( + self._solid, + self.dx, + self.dy, + self.dz, + outlet_dirichlet=False, + ) + reference_index = 0 + active_pressure_indices = np.ones( + neumann_matrix.shape[0], dtype=np.bool_ + ) + active_pressure_indices[reference_index] = False + self._neumann_active_pressure_indices = active_pressure_indices + self._neumann_pressure_matrix = neumann_matrix[ + active_pressure_indices + ][:, active_pressure_indices].tocsr() + self._neumann_pressure_diagonal = self._neumann_pressure_matrix.diagonal() + + def _make_wing_mask(self) -> BoolArray: + settings = self.settings + x_inside = ( + (self.x_centers >= settings.wing_leading_edge_x) + & (self.x_centers < settings.wing_leading_edge_x + settings.wing_chord) + ) + y_center = 0.5 * settings.length_y + z_center = 0.5 * settings.length_z + y_inside = np.abs(self.y_centers - y_center) <= 0.5 * max( + settings.wing_thickness, self.dy + ) + z_inside = np.abs(self.z_centers - z_center) <= 0.5 * settings.wing_span + solid = y_inside[:, None, None] & x_inside[None, :, None] & z_inside[None, None, :] + if not np.any(solid): + raise ValueError("the wing geometry does not cover any mesh cells") + if np.all(solid): + raise ValueError("the wing geometry cannot occupy the whole flow domain") + return solid + + def _apply_face_boundaries( + self, + u: FloatArray, + v: FloatArray, + w: FloatArray, + *, + inlet_velocity: tuple[float, float, float] | None = None, + set_farfield_tangential_values: bool = True, + ) -> None: + if inlet_velocity is None: + inlet_velocity = self.settings.inlet_velocity + inlet_x, inlet_y, _ = inlet_velocity + u[:, 0, :] = inlet_x + v[0, :, :] = inlet_y + v[-1, :, :] = inlet_y + w[:, :, 0] = 0.0 + w[:, :, -1] = 0.0 + if set_farfield_tangential_values: + u[:, -1, :] = u[:, -2, :] + v[:, 0, :] = inlet_y + v[:, -1, :] = v[:, -2, :] + w[:, 0, :] = 0.0 + w[:, -1, :] = w[:, -2, :] + u[0, :, :] = inlet_x + u[-1, :, :] = inlet_x + u[:, :, 0] = inlet_x + u[:, :, -1] = inlet_x + v[:, :, 0] = inlet_y + v[:, :, -1] = inlet_y + w[0, :, :] = 0.0 + w[-1, :, :] = 0.0 + u[self._u_blocked] = 0.0 + v[self._v_blocked] = 0.0 + w[self._w_blocked] = 0.0 + + def _initial_velocity( + self, inlet_velocity: tuple[float, float, float] | None = None + ) -> tuple[FloatArray, FloatArray, FloatArray]: + settings = self.settings + if inlet_velocity is None: + inlet_velocity = settings.inlet_velocity + inlet_x, inlet_y, inlet_z = inlet_velocity + u = np.full( + (settings.ny, settings.nx + 1, settings.nz), inlet_x, dtype=np.float64 + ) + v = np.full( + (settings.ny + 1, settings.nx, settings.nz), inlet_y, dtype=np.float64 + ) + w = np.full( + (settings.ny, settings.nx, settings.nz + 1), inlet_z, dtype=np.float64 + ) + self._apply_face_boundaries(u, v, w, inlet_velocity=inlet_velocity) + return u, v, w + + @staticmethod + def _cell_velocity( + u: FloatArray, v: FloatArray, w: FloatArray + ) -> tuple[FloatArray, FloatArray, FloatArray]: + return ( + 0.5 * (u[:, :-1, :] + u[:, 1:, :]), + 0.5 * (v[:-1, :, :] + v[1:, :, :]), + 0.5 * (w[:, :, :-1] + w[:, :, 1:]), + ) + + def _velocity_neighbor( + self, + field: FloatArray, + axis: int, + direction: int, + solid: BoolArray, + farfield_value: float, + advector: FloatArray, + ) -> FloatArray: + shifted_field = np.roll(field, shift=-direction, axis=axis) + shifted_solid = np.roll(solid, shift=-direction, axis=axis) + neighbor = np.where(shifted_solid, -field, shifted_field) + if axis == 1 and direction < 0: + boundary = 2.0 * farfield_value - field[:, 0, :] + neighbor[:, 0, :] = boundary + elif axis == 1 and direction > 0: + backflow = advector[:, -1, :] < 0.0 + neighbor[:, -1, :] = np.where( + backflow, + 2.0 * farfield_value - field[:, -1, :], + field[:, -1, :], + ) + else: + index = [slice(None)] * 3 + index[axis] = 0 if direction < 0 else -1 + neighbor[tuple(index)] = ( + 2.0 * farfield_value - field[tuple(index)] + ) + return neighbor + + def _pressure_gradient( + self, + pressure: FloatArray, + axis: int, + spacing: float, + *, + outlet_neumann: bool = False, + ) -> FloatArray: + previous = np.roll(pressure, shift=1, axis=axis) + following = np.roll(pressure, shift=-1, axis=axis) + previous_solid = np.roll(self._solid, shift=1, axis=axis) + following_solid = np.roll(self._solid, shift=-1, axis=axis) + previous = np.where(previous_solid, pressure, previous) + following = np.where(following_solid, pressure, following) + if axis == 1: + previous[:, 0, :] = pressure[:, 0, :] + following[:, -1, :] = ( + pressure[:, -1, :] + if outlet_neumann + else -pressure[:, -1, :] + ) + else: + index_low = [slice(None)] * 3 + index_high = [slice(None)] * 3 + index_low[axis] = 0 + index_high[axis] = -1 + previous[tuple(index_low)] = pressure[tuple(index_low)] + following[tuple(index_high)] = pressure[tuple(index_high)] + gradient = (following - previous) / (2.0 * spacing) + gradient[self._solid] = 0.0 + return gradient + + def _predict_velocity( + self, + u: FloatArray, + v: FloatArray, + w: FloatArray, + pressure: FloatArray, + dt: float, + inlet_velocity: tuple[float, float, float] | None = None, + *, + outlet_neumann: bool = False, + ) -> tuple[FloatArray, FloatArray, FloatArray]: + settings = self.settings + if inlet_velocity is None: + inlet_velocity = settings.inlet_velocity + inlet_x, inlet_y, inlet_z = inlet_velocity + cell_u, cell_v, cell_w = self._cell_velocity(u, v, w) + cell_u[self._solid] = 0.0 + cell_v[self._solid] = 0.0 + cell_w[self._solid] = 0.0 + component_fields = (cell_u, cell_v, cell_w) + inlet_components = (inlet_x, inlet_y, inlet_z) + axis_advectors = (cell_v, cell_u, cell_w) + spacings = (self.dy, self.dx, self.dz) + momentum_gradient_axes = (1, 0, 2) + momentum_component_spacings = (self.dx, self.dy, self.dz) + predicted_components: list[FloatArray] = [] + viscosity = settings.dynamic_viscosity / settings.density + + for component, field in enumerate(component_fields): + convection = np.zeros_like(field) + diffusion = np.zeros_like(field) + for axis, (spacing, advector) in enumerate( + zip(spacings, axis_advectors) + ): + negative = self._velocity_neighbor( + field, + axis, + -1, + self._solid, + inlet_components[component], + advector, + ) + positive = self._velocity_neighbor( + field, + axis, + 1, + self._solid, + inlet_components[component], + advector, + ) + derivative = np.where( + advector >= 0.0, + (field - negative) / spacing, + (positive - field) / spacing, + ) + convection += advector * derivative + diffusion += (negative - 2.0 * field + positive) / spacing**2 + pressure_gradient = self._pressure_gradient( + pressure, + momentum_gradient_axes[component], + momentum_component_spacings[component], + outlet_neumann=outlet_neumann, + ) + predicted = field + dt * ( + -convection + + viscosity * diffusion + - pressure_gradient / settings.density + ) + predicted[self._solid] = 0.0 + predicted_components.append(predicted) + + cell_u_star, cell_v_star, cell_w_star = predicted_components + u_star = np.empty_like(u) + v_star = np.empty_like(v) + w_star = np.empty_like(w) + u_star[:, 1:-1, :] = 0.5 * (cell_u_star[:, :-1, :] + cell_u_star[:, 1:, :]) + v_star[1:-1, :, :] = 0.5 * (cell_v_star[:-1, :, :] + cell_v_star[1:, :, :]) + w_star[:, :, 1:-1] = 0.5 * (cell_w_star[:, :, :-1] + cell_w_star[:, :, 1:]) + u_star[:, 0, :] = inlet_x + u_star[:, -1, :] = u_star[:, -2, :] + v_star[0, :, :] = inlet_y + v_star[-1, :, :] = inlet_y + w_star[:, :, 0] = inlet_z + w_star[:, :, -1] = inlet_z + self._apply_face_boundaries( + u_star, v_star, w_star, inlet_velocity=inlet_velocity + ) + return u_star, v_star, w_star + + def _solve_pressure_correction( + self, + divergence: FloatArray, + dt: float, + *, + outlet_neumann: bool = False, + ) -> tuple[FloatArray, float]: + rhs_full = ( + -self.settings.density / dt * divergence + ) + rhs = rhs_full[~self._solid] + if outlet_neumann: + rhs_sum = float(np.sum(rhs)) + rhs_scale = max(1.0, float(np.sum(np.abs(rhs)))) + if abs(rhs_sum) > 1e-8 * rhs_scale: + raise RuntimeError( + "pressure correction with a fixed-velocity outlet requires " + "compatible net boundary flux" + ) + matrix = self._neumann_pressure_matrix + diagonal = self._neumann_pressure_diagonal + active = self._neumann_active_pressure_indices + solved_values, info = cg( + matrix, + rhs[active], + M=LinearOperator( + matrix.shape, + matvec=lambda values: values / diagonal, + dtype=np.float64, + ), + rtol=self.settings.pressure_tolerance, + atol=0.0, + maxiter=self.settings.max_pressure_iterations, + ) + if info != 0: + raise RuntimeError( + "pressure-correction solver failed to converge " + f"(status {info})" + ) + correction_values = np.zeros_like(rhs) + correction_values[active] = solved_values + residual = self._neumann_pressure_matrix @ correction_values[active] - rhs[ + active + ] + else: + matrix = self._pressure_matrix + diagonal = self._pressure_diagonal + preconditioner = LinearOperator( + matrix.shape, + matvec=lambda values: values / diagonal, + dtype=np.float64, + ) + correction_values, info = cg( + matrix, + rhs, + M=preconditioner, + rtol=self.settings.pressure_tolerance, + atol=0.0, + maxiter=self.settings.max_pressure_iterations, + ) + if info != 0: + raise RuntimeError( + "pressure-correction solver failed to converge " + f"(status {info})" + ) + residual = matrix @ correction_values - rhs + residual_scale = max(1.0, float(np.max(np.abs(rhs)))) + relative_residual = float(np.max(np.abs(residual)) / residual_scale) + correction = np.zeros_like(divergence) + correction[~self._solid] = correction_values + return correction, relative_residual + + def _project( + self, + u_star: FloatArray, + v_star: FloatArray, + w_star: FloatArray, + pressure: FloatArray, + dt: float, + inlet_velocity: tuple[float, float, float] | None = None, + *, + outlet_neumann: bool = False, + ) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray, FloatArray, float]: + divergence_before = ( + (u_star[:, 1:, :] - u_star[:, :-1, :]) / self.dx + + (v_star[1:, :, :] - v_star[:-1, :, :]) / self.dy + + (w_star[:, :, 1:] - w_star[:, :, :-1]) / self.dz + ) + divergence_before[self._solid] = 0.0 + correction, pressure_residual = self._solve_pressure_correction( + divergence_before, dt, outlet_neumann=outlet_neumann + ) + corrected_u = u_star.copy() + corrected_v = v_star.copy() + corrected_w = w_star.copy() + corrected_u[:, 1:-1, :] -= ( + dt + / self.settings.density + * (correction[:, 1:, :] - correction[:, :-1, :]) + / self.dx + ) + if not outlet_neumann: + corrected_u[:, -1, :] -= ( + dt + / self.settings.density + * (0.0 - correction[:, -1, :]) + / (0.5 * self.dx) + ) + corrected_v[1:-1, :, :] -= ( + dt + / self.settings.density + * (correction[1:, :, :] - correction[:-1, :, :]) + / self.dy + ) + corrected_w[:, :, 1:-1] -= ( + dt + / self.settings.density + * (correction[:, :, 1:] - correction[:, :, :-1]) + / self.dz + ) + self._apply_face_boundaries( + corrected_u, + corrected_v, + corrected_w, + inlet_velocity=inlet_velocity, + set_farfield_tangential_values=False, + ) + divergence_after = ( + (corrected_u[:, 1:, :] - corrected_u[:, :-1, :]) / self.dx + + (corrected_v[1:, :, :] - corrected_v[:-1, :, :]) / self.dy + + (corrected_w[:, :, 1:] - corrected_w[:, :, :-1]) / self.dz + ) + divergence_after[self._solid] = 0.0 + updated_pressure = pressure + correction + updated_pressure[self._solid] = 0.0 + return ( + corrected_u, + corrected_v, + corrected_w, + updated_pressure, + divergence_after, + pressure_residual, + ) + + def _apply_outlet_sponge( + self, + u: FloatArray, + v: FloatArray, + w: FloatArray, + dt: float, + inlet_velocity: tuple[float, float, float], + sponge_length: float, + ) -> None: + """Damp outgoing disturbances smoothly before the transient outlet.""" + inlet_x, inlet_y, inlet_z = inlet_velocity + speed = float(np.hypot(inlet_x, inlet_y)) + sponge_start = self.settings.length_x - sponge_length + face_fraction = np.clip( + (np.arange(self.settings.nx + 1) * self.dx - sponge_start) + / sponge_length, + 0.0, + 1.0, + ) + cell_fraction = np.clip( + (self.x_centers - sponge_start) / sponge_length, + 0.0, + 1.0, + ) + damping_rate = 4.0 * speed / sponge_length + face_decay = np.exp(-damping_rate * dt * face_fraction**2) + cell_decay = np.exp(-damping_rate * dt * cell_fraction**2) + u[:] = inlet_x + (u - inlet_x) * face_decay[None, :, None] + v[:] = inlet_y + (v - inlet_y) * cell_decay[None, :, None] + w[:] = inlet_z + (w - inlet_z) * cell_decay[None, :, None] + + def _result( + self, + u: FloatArray, + v: FloatArray, + w: FloatArray, + pressure: FloatArray, + history: list[FiniteWingIteration | FiniteWingTransientIteration], + *, + physical_time: float | None = None, + angle_of_attack_degrees: float | None = None, + ) -> FiniteWingResult: + velocity_x, velocity_y, velocity_z = self._cell_velocity(u, v, w) + velocity_x[self._solid] = 0.0 + velocity_y[self._solid] = 0.0 + velocity_z[self._solid] = 0.0 + return FiniteWingResult( + velocity_x=velocity_x.copy(), + velocity_y=velocity_y.copy(), + velocity_z=velocity_z.copy(), + pressure=pressure.copy(), + solid_mask=self._solid.copy(), + x_centers=self.x_centers.copy(), + y_centers=self.y_centers.copy(), + z_centers=self.z_centers.copy(), + history=tuple(history), + settings=self.settings, + physical_time=physical_time, + angle_of_attack_degrees=angle_of_attack_degrees, + ) + + def run( + self, observer: IterationObserver | None = None + ) -> FiniteWingResult: + """Run the configured number of steady pseudo-time iterations. + + If provided, ``observer`` is called after each iteration with its + diagnostics and a copied snapshot of the current flow fields. + """ + if observer is not None and not callable(observer): + raise TypeError("observer must be callable or None") + settings = self.settings + u, v, w = self._initial_velocity() + pressure = np.zeros((settings.ny, settings.nx, settings.nz), dtype=np.float64) + history: list[FiniteWingIteration] = [] + viscosity = settings.dynamic_viscosity / settings.density + diffusion_limit = 0.2 / ( + viscosity + * (1.0 / self.dx**2 + 1.0 / self.dy**2 + 1.0 / self.dz**2) + ) + for iteration in range(1, settings.max_iterations + 1): + velocity_x, velocity_y, velocity_z = self._cell_velocity(u, v, w) + max_x = float(np.max(np.abs(velocity_x[~self._solid]))) + max_y = float(np.max(np.abs(velocity_y[~self._solid]))) + max_z = float(np.max(np.abs(velocity_z[~self._solid]))) + advective_rate = max_x / self.dx + max_y / self.dy + max_z / self.dz + advective_limit = ( + settings.cfl_limit / advective_rate + if advective_rate > 0.0 + else settings.pseudo_time_step_cap + ) + dt = min( + settings.pseudo_time_step_cap, diffusion_limit, advective_limit + ) + if dt < settings.minimum_pseudo_time_step: + raise RuntimeError( + f"stable pseudo-time step {dt:.6g} is below " + f"minimum_pseudo_time_step " + f"{settings.minimum_pseudo_time_step:.6g}" + ) + + u_star, v_star, w_star = self._predict_velocity(u, v, w, pressure, dt) + ( + u, + v, + w, + pressure, + divergence_after, + pressure_residual, + ) = self._project(u_star, v_star, w_star, pressure, dt) + velocity_x, velocity_y, velocity_z = self._cell_velocity(u, v, w) + speed = np.sqrt(velocity_x**2 + velocity_y**2 + velocity_z**2) + speed[self._solid] = 0.0 + divergence_after[self._solid] = 0.0 + diagnostics = FiniteWingIteration( + iteration=iteration, + pseudo_time_step=dt, + max_speed=float(np.max(speed)), + max_divergence=float(np.max(np.abs(divergence_after))), + cfl_number=dt * advective_rate, + pressure_residual=pressure_residual, + ) + history.append(diagnostics) + if observer is not None: + observer( + diagnostics, + self._result(u, v, w, pressure, history), + ) + + return self._result(u, v, w, pressure, history) + + def run_transient( + self, + transient_settings: FiniteWingTransientSettings, + observer: IterationObserver | None = None, + ) -> FiniteWingResult: + """Advance the flow to physical ``end_time`` with scheduled inlet AoA. + + The inlet speed remains fixed at the magnitude configured in + ``FiniteWingSettings``. Angle-of-attack values are interpolated from + the transient schedule at each physical time step. + """ + if not isinstance(transient_settings, FiniteWingTransientSettings): + raise TypeError( + "transient_settings must be a FiniteWingTransientSettings instance" + ) + if observer is not None and not callable(observer): + raise TypeError("observer must be callable or None") + settings = self.settings + schedule_start_angle = transient_settings.angle_of_attack_schedule[0][1] + if abs(settings.angle_of_attack_degrees - schedule_start_angle) > 1e-12: + raise ValueError( + "settings.angle_of_attack_degrees must match the initial " + "transient schedule angle" + ) + if transient_settings.outlet_sponge_length >= settings.length_x: + raise ValueError("outlet_sponge_length must be shorter than the x domain") + if ( + settings.length_x - transient_settings.outlet_sponge_length + <= settings.wing_leading_edge_x + settings.wing_chord + ): + raise ValueError("the outlet sponge must begin downstream of the wing") + + speed = float(np.hypot(*settings.inlet_velocity[:2])) + + def inlet_velocity_at(time: float) -> tuple[float, float, float]: + angle = transient_settings.angle_of_attack_at(time) * pi / 180.0 + return speed * cos(angle), -speed * sin(angle), 0.0 + + time = 0.0 + time_tolerance = 1e-12 * max(1.0, transient_settings.end_time) + current_angle = transient_settings.angle_of_attack_at(time) + inlet_velocity = inlet_velocity_at(time) + u, v, w = self._initial_velocity(inlet_velocity) + pressure = np.zeros((settings.ny, settings.nx, settings.nz), dtype=np.float64) + history: list[FiniteWingIteration | FiniteWingTransientIteration] = [] + viscosity = settings.dynamic_viscosity / settings.density + diffusion_limit = 0.2 / ( + viscosity + * (1.0 / self.dx**2 + 1.0 / self.dy**2 + 1.0 / self.dz**2) + ) + + while time < transient_settings.end_time - time_tolerance: + velocity_x, velocity_y, velocity_z = self._cell_velocity(u, v, w) + max_x = float(np.max(np.abs(velocity_x[~self._solid]))) + max_y = float(np.max(np.abs(velocity_y[~self._solid]))) + max_z = float(np.max(np.abs(velocity_z[~self._solid]))) + advective_rate = max_x / self.dx + max_y / self.dy + max_z / self.dz + advective_limit = ( + settings.cfl_limit / advective_rate + if advective_rate > 0.0 + else transient_settings.time_step_cap + ) + next_schedule_time = min( + ( + schedule_time + for schedule_time, _ in transient_settings.angle_of_attack_schedule + if schedule_time > time + time_tolerance + ), + default=transient_settings.end_time, + ) + dt = min( + transient_settings.time_step_cap, + diffusion_limit, + advective_limit, + transient_settings.end_time - time, + next_schedule_time - time, + ) + if dt < transient_settings.minimum_time_step: + raise RuntimeError( + f"stable time step {dt:.6g} is below minimum_time_step " + f"{transient_settings.minimum_time_step:.6g}" + ) + + next_time = time + dt + if transient_settings.end_time - next_time <= time_tolerance: + next_time = transient_settings.end_time + else: + for schedule_time, _ in transient_settings.angle_of_attack_schedule: + if abs(next_time - schedule_time) <= time_tolerance: + next_time = schedule_time + break + current_angle = transient_settings.angle_of_attack_at(next_time) + inlet_velocity = inlet_velocity_at(next_time) + u_star, v_star, w_star = self._predict_velocity( + u, + v, + w, + pressure, + dt, + inlet_velocity, + outlet_neumann=True, + ) + self._apply_outlet_sponge( + u_star, + v_star, + w_star, + dt, + inlet_velocity, + transient_settings.outlet_sponge_length, + ) + self._apply_face_boundaries( + u_star, v_star, w_star, inlet_velocity=inlet_velocity + ) + u_star[:, -1, :] = inlet_velocity[0] + ( + u, + v, + w, + pressure, + divergence_after, + pressure_residual, + ) = self._project( + u_star, + v_star, + w_star, + pressure, + dt, + inlet_velocity, + outlet_neumann=True, + ) + time = next_time + velocity_x, velocity_y, velocity_z = self._cell_velocity(u, v, w) + speed_field = np.sqrt( + velocity_x**2 + velocity_y**2 + velocity_z**2 + ) + speed_field[self._solid] = 0.0 + divergence_after[self._solid] = 0.0 + diagnostics = FiniteWingTransientIteration( + iteration=len(history) + 1, + time=time, + time_step=dt, + angle_of_attack_degrees=current_angle, + max_speed=float(np.max(speed_field)), + max_divergence=float(np.max(np.abs(divergence_after))), + cfl_number=dt * advective_rate, + pressure_residual=pressure_residual, + ) + history.append(diagnostics) + if observer is not None: + observer( + diagnostics, + self._result( + u, + v, + w, + pressure, + history, + physical_time=time, + angle_of_attack_degrees=current_angle, + ), + ) + + return self._result( + u, + v, + w, + pressure, + history, + physical_time=time, + angle_of_attack_degrees=current_angle, + ) diff --git a/Exp_solver_dev_tr/src/fvm3d/visualization.py b/Exp_solver_dev_tr/src/fvm3d/visualization.py new file mode 100644 index 0000000000000..d7078e819c3d5 --- /dev/null +++ b/Exp_solver_dev_tr/src/fvm3d/visualization.py @@ -0,0 +1,575 @@ +"""Static and live flow/vorticity plots for finite-wing runs.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +from .solver import FiniteWingIteration, FiniteWingResult, FiniteWingSettings + + +def _vorticity_x(result: FiniteWingResult) -> np.ndarray: + """Compute streamwise vorticity on the cell-centered grid.""" + spacing_y = result.settings.length_y / result.settings.ny + spacing_z = result.settings.length_z / result.settings.nz + d_w_dy = np.gradient(result.velocity_z, spacing_y, axis=0) + d_v_dz = np.gradient(result.velocity_y, spacing_z, axis=2) + streamwise_vorticity = d_w_dy - d_v_dz + streamwise_vorticity[result.solid_mask] = 0.0 + return streamwise_vorticity + + +def _integrate_wake_streamlines( + result: FiniteWingResult, +) -> list[np.ndarray]: + """Integrate 3D streamlines from just behind the wing through its wake.""" + from scipy.interpolate import RegularGridInterpolator + + settings = result.settings + trailing_edge = settings.wing_leading_edge_x + settings.wing_chord + x_start = trailing_edge + 0.1 * settings.wing_chord + x_end = float(result.x_centers[-1]) + if x_start >= x_end: + return [] + + center_y = 0.5 * settings.length_y + center_z = 0.5 * settings.length_z + seed_y = np.linspace( + max(float(result.y_centers[0]), center_y - 0.5 * settings.wing_chord), + min(float(result.y_centers[-1]), center_y + 0.5 * settings.wing_chord), + 7, + ) + seed_z = np.linspace( + max( + float(result.z_centers[0]), + center_z - 0.5 * settings.wing_span - 0.15 * settings.wing_chord, + ), + min( + float(result.z_centers[-1]), + center_z + 0.5 * settings.wing_span + 0.15 * settings.wing_chord, + ), + 9, + ) + points = np.array( + [(x_start, y, z) for y in seed_y for z in seed_z], + dtype=np.float64, + ) + if points.size == 0: + return [] + + interpolation_grid = ( + result.y_centers, + result.x_centers, + result.z_centers, + ) + interpolators = tuple( + RegularGridInterpolator( + interpolation_grid, + velocity, + bounds_error=False, + fill_value=np.nan, + ) + for velocity in (result.velocity_x, result.velocity_y, result.velocity_z) + ) + solid_interpolator = RegularGridInterpolator( + interpolation_grid, + result.solid_mask.astype(np.float64), + bounds_error=False, + fill_value=1.0, + ) + + def slopes( + x: float, y: np.ndarray, z: np.ndarray + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + samples = np.column_stack((y, np.full_like(y, x), z)) + u, v, w = (interpolator(samples) for interpolator in interpolators) + solid_fraction = solid_interpolator(samples) + valid = ( + np.isfinite(u) + & np.isfinite(v) + & np.isfinite(w) + & (u > 1e-10) + & (solid_fraction < 0.25) + ) + dy_dx = np.divide(v, u, out=np.zeros_like(v), where=valid) + dz_dx = np.divide(w, u, out=np.zeros_like(w), where=valid) + return dy_dx, dz_dx, valid + + paths = [[point.copy()] for point in points] + active = np.ones(len(points), dtype=bool) + step_x = 0.5 * settings.length_x / settings.nx + x = x_start + + while x < x_end and np.any(active): + step = min(step_x, x_end - x) + y = points[:, 1] + z = points[:, 2] + k1y, k1z, valid1 = slopes(x, y, z) + k2y, k2z, valid2 = slopes( + x + 0.5 * step, + y + 0.5 * step * k1y, + z + 0.5 * step * k1z, + ) + k3y, k3z, valid3 = slopes( + x + 0.5 * step, + y + 0.5 * step * k2y, + z + 0.5 * step * k2z, + ) + k4y, k4z, valid4 = slopes( + x + step, + y + step * k3y, + z + step * k3z, + ) + next_y = y + (step / 6.0) * (k1y + 2.0 * k2y + 2.0 * k3y + k4y) + next_z = z + (step / 6.0) * (k1z + 2.0 * k2z + 2.0 * k3z + k4z) + valid = ( + active + & valid1 + & valid2 + & valid3 + & valid4 + & (next_y >= result.y_centers[0]) + & (next_y <= result.y_centers[-1]) + & (next_z >= result.z_centers[0]) + & (next_z <= result.z_centers[-1]) + ) + next_x = x + step + for index in np.flatnonzero(valid): + points[index] = (next_x, next_y[index], next_z[index]) + paths[index].append(points[index].copy()) + active &= valid + x = next_x + + return [np.asarray(path) for path in paths if len(path) > 1] + + +def _draw_finite_wing_result( + result: FiniteWingResult, + *, + flow_figure=None, + vorticity_figure=None, + streamline_figure=None, +): + """Draw the shared mid-span, tip-vorticity, and 3D-wake views.""" + import matplotlib.pyplot as plt + from matplotlib.patches import Rectangle + + settings = result.settings + x_edges = np.linspace(0.0, settings.length_x, settings.nx + 1) + y_edges = np.linspace(0.0, settings.length_y, settings.ny + 1) + span_index = settings.nz // 2 + midspan_speed = np.sqrt( + result.velocity_x[:, :, span_index] ** 2 + + result.velocity_y[:, :, span_index] ** 2 + ) + vorticity_x = _vorticity_x(result) + trailing_edge = settings.wing_leading_edge_x + settings.wing_chord + requested_slices = ( + trailing_edge + 0.25 * settings.wing_chord, + trailing_edge + 0.75 * settings.wing_chord, + trailing_edge + 1.5 * settings.wing_chord, + ) + slice_indices = tuple( + min( + settings.nx - 1, + max(0, int(np.argmin(np.abs(result.x_centers - position)))), + ) + for position in requested_slices + ) + vorticity_maximum = max( + float(np.max(np.abs(vorticity_x[:, index, :]))) for index in slice_indices + ) + vorticity_limit = max(vorticity_maximum, 1e-12) + if flow_figure is None: + flow_figure = plt.figure(figsize=(10, 5), constrained_layout=True) + else: + flow_figure.clear() + flow_axis = flow_figure.subplots() + speed_plot = flow_axis.pcolormesh( + x_edges, + y_edges, + midspan_speed, + shading="flat", + cmap="viridis", + ) + flow_axis.streamplot( + result.x_centers, + result.y_centers, + result.velocity_x[:, :, span_index], + result.velocity_y[:, :, span_index], + color="white", + density=1.1, + linewidth=0.7, + ) + wing_y = 0.5 * settings.length_y + flow_axis.add_patch( + Rectangle( + (settings.wing_leading_edge_x, wing_y - 0.5 * settings.wing_thickness), + settings.wing_chord, + settings.wing_thickness, + facecolor="0.2", + edgecolor="white", + linewidth=0.8, + ) + ) + flow_figure.colorbar(speed_plot, ax=flow_axis, label="Speed (m/s)") + angle = ( + settings.angle_of_attack_degrees + if result.angle_of_attack_degrees is None + else result.angle_of_attack_degrees + ) + if result.physical_time is None: + flow_title = ( + f"Steady mid-span flow after iteration {result.iterations} " + f"(AoA={angle:g} deg)" + ) + vorticity_title = f"Steady wing-tip wake after iteration {result.iterations}" + else: + flow_title = ( + f"Transient mid-span flow at t={result.physical_time:.3g} s " + f"(AoA={angle:g} deg)" + ) + vorticity_title = f"Transient wing-tip wake at t={result.physical_time:.3g} s" + flow_axis.set( + title=flow_title, + xlabel="x (m)", + ylabel="y (m)", + xlim=(0.0, settings.length_x), + ylim=(0.0, settings.length_y), + ) + flow_axis.set_aspect("equal", adjustable="box") + + if streamline_figure is None: + streamline_figure = plt.figure(figsize=(11, 6), constrained_layout=True) + else: + streamline_figure.clear() + streamline_axis = streamline_figure.add_subplot(111, projection="3d") + streamlines = _integrate_wake_streamlines(result) + if streamlines: + from mpl_toolkits.mplot3d.art3d import Line3DCollection, Poly3DCollection + from matplotlib.colors import TwoSlopeNorm + from scipy.interpolate import RegularGridInterpolator + + flow_angle = np.deg2rad(angle) + cos_angle = np.cos(flow_angle) + sin_angle = np.sin(flow_angle) + + def to_freestream_coordinates(points: np.ndarray) -> np.ndarray: + relative_y = points[:, 1] - wing_y + relative_x = points[:, 0] - settings.wing_leading_edge_x + return np.column_stack( + ( + settings.wing_leading_edge_x + + relative_x * cos_angle + - relative_y * sin_angle, + wing_y + relative_x * sin_angle + relative_y * cos_angle, + points[:, 2], + ) + ) + + segments = np.concatenate( + [ + np.stack( + ( + to_freestream_coordinates(path[:-1]), + to_freestream_coordinates(path[1:]), + ), + axis=1, + ) + for path in streamlines + ], + axis=0, + ) + vorticity_interpolator = RegularGridInterpolator( + (result.y_centers, result.x_centers, result.z_centers), + vorticity_x, + bounds_error=False, + fill_value=0.0, + ) + segment_vorticity = np.concatenate( + [ + 0.5 + * ( + vorticity_interpolator( + np.column_stack( + (path[:-1, 1], path[:-1, 0], path[:-1, 2]) + ) + ) + + vorticity_interpolator( + np.column_stack( + (path[1:, 1], path[1:, 0], path[1:, 2]) + ) + ) + ) + for path in streamlines + ] + ) + vorticity_scale = max(float(np.max(np.abs(segment_vorticity))), 1e-12) + streamline_collection = Line3DCollection( + segments, + cmap="RdBu_r", + norm=TwoSlopeNorm( + vmin=-vorticity_scale, + vcenter=0.0, + vmax=vorticity_scale, + ), + linewidth=1.1, + alpha=0.9, + ) + streamline_collection.set_array(segment_vorticity) + streamline_axis.add_collection3d(streamline_collection) + streamline_figure.colorbar( + streamline_collection, + ax=streamline_axis, + label="Streamwise vorticity (1/s)", + shrink=0.72, + pad=0.08, + ) + + x0 = settings.wing_leading_edge_x + x1 = x0 + settings.wing_chord + y0 = wing_y - 0.5 * settings.wing_thickness + y1 = wing_y + 0.5 * settings.wing_thickness + z0 = 0.5 * (settings.length_z - settings.wing_span) + z1 = 0.5 * (settings.length_z + settings.wing_span) + wing_faces = [ + [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0)], + [(x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)], + [(x0, y0, z0), (x1, y0, z0), (x1, y0, z1), (x0, y0, z1)], + [(x0, y1, z0), (x1, y1, z0), (x1, y1, z1), (x0, y1, z1)], + [(x0, y0, z0), (x0, y1, z0), (x0, y1, z1), (x0, y0, z1)], + [(x1, y0, z0), (x1, y1, z0), (x1, y1, z1), (x1, y0, z1)], + ] + streamline_axis.add_collection3d( + Poly3DCollection( + [ + to_freestream_coordinates(np.asarray(face)) + for face in wing_faces + ], + facecolors="0.25", + edgecolors="black", + linewidths=0.5, + alpha=1.0, + ) + ) + + domain_corners = np.array( + [ + (x, y, z) + for x in (0.0, settings.length_x) + for y in (0.0, settings.length_y) + for z in (0.0, settings.length_z) + ] + ) + aligned_domain = to_freestream_coordinates(domain_corners) + streamline_axis.set_xlim( + float(np.min(aligned_domain[:, 0])), + float(np.max(aligned_domain[:, 0])), + ) + streamline_axis.set_ylim( + float(np.min(aligned_domain[:, 1])), + float(np.max(aligned_domain[:, 1])), + ) + streamline_axis.set_zlim(0.0, settings.length_z) + + streamline_axis.set( + xlabel="Freestream coordinate (m)", + ylabel="Cross-flow coordinate (m)", + zlabel="z (m)", + ) + x_limits = streamline_axis.get_xlim() + y_limits = streamline_axis.get_ylim() + streamline_axis.set_box_aspect( + (x_limits[1] - x_limits[0], y_limits[1] - y_limits[0], settings.length_z) + ) + streamline_axis.view_init(elev=25, azim=-55) + if result.physical_time is None: + streamline_title = ( + f"Freestream-aligned 3D wake streamlines after iteration " + f"{result.iterations} " + f"(AoA={angle:g} deg)" + ) + else: + streamline_title = ( + f"Transient freestream-aligned 3D wake streamlines " + f"at t={result.physical_time:.3g} s " + f"(AoA={angle:g} deg)" + ) + streamline_axis.set_title(streamline_title) + + if vorticity_figure is None: + vorticity_figure = plt.figure(figsize=(14, 4.5), constrained_layout=True) + else: + vorticity_figure.clear() + vorticity_axes = vorticity_figure.subplots(1, len(slice_indices)) + vorticity_plot = None + for axis, index in zip(vorticity_axes, slice_indices): + vorticity_slice = vorticity_x[:, index, :] + vorticity_plot = axis.pcolormesh( + result.z_centers, + result.y_centers, + vorticity_slice, + shading="gouraud", + cmap="RdBu_r", + vmin=-vorticity_limit, + vmax=vorticity_limit, + ) + induced_y = result.velocity_y[:, index, :] - settings.inlet_velocity[1] + induced_z = result.velocity_z[:, index, :] + if np.any(np.hypot(induced_y, induced_z) > 1e-12): + axis.streamplot( + result.z_centers, + result.y_centers, + induced_z, + induced_y, + color="black", + density=0.85, + linewidth=0.55, + arrowsize=0.75, + ) + axis.set( + title=f"x={result.x_centers[index]:.3g} m", + xlabel="Spanwise z (m)", + ylabel="Vertical y (m)", + xlim=(0.0, settings.length_z), + ylim=(0.0, settings.length_y), + ) + axis.set_aspect("equal", adjustable="box") + assert vorticity_plot is not None + vorticity_figure.colorbar( + vorticity_plot, + ax=list(vorticity_axes), + label="Streamwise vorticity (1/s)", + ) + vorticity_figure.suptitle( + f"{vorticity_title} " + "(black lines: induced cross-plane streamlines)" + ) + return flow_figure, vorticity_figure, streamline_figure + + +def _plot_paths(output_directory: str | Path) -> dict[str, Path]: + output_path = Path(output_directory) + output_path.mkdir(parents=True, exist_ok=True) + return { + "midspan": output_path / "finite_wing_midspan.png", + "tip_vorticity": output_path / "finite_wing_tip_vorticity.png", + "streamlines": output_path / "finite_wing_3d_streamlines.png", + } + + +def plot_finite_wing_result( + result: FiniteWingResult, + output_directory: str | Path, + *, + show: bool = False, +) -> dict[str, Path]: + """Save mid-span, downstream-vorticity, and 3D-wake plots.""" + if not isinstance(result, FiniteWingResult): + raise TypeError("result must be a FiniteWingResult") + if not isinstance(show, bool): + raise TypeError("show must be a bool") + if not result.history: + raise ValueError("result must contain at least one completed iteration") + + import matplotlib.pyplot as plt + + flow_figure, vorticity_figure, streamline_figure = _draw_finite_wing_result( + result + ) + paths = _plot_paths(output_directory) + flow_figure.savefig(paths["midspan"], dpi=160) + vorticity_figure.savefig(paths["tip_vorticity"], dpi=160) + streamline_figure.savefig(paths["streamlines"], dpi=160) + if show: + plt.show() + plt.close(flow_figure) + plt.close(vorticity_figure) + plt.close(streamline_figure) + return paths + + +class LiveFiniteWingPlotter: + """Update all finite-wing plots after every steady or transient step.""" + + def __init__( + self, settings: FiniteWingSettings, output_directory: str | Path + ) -> None: + import matplotlib.pyplot as plt + + if not isinstance(settings, FiniteWingSettings): + raise TypeError("settings must be a FiniteWingSettings instance") + if plt.get_backend().lower() in { + "agg", + "pdf", + "ps", + "svg", + "cairo", + "template", + }: + raise RuntimeError( + "live visualization requires an interactive Matplotlib backend; " + "use --mode save for headless runs" + ) + self._plt = plt + self._output_directory = Path(output_directory) + self._output_directory.mkdir(parents=True, exist_ok=True) + self._flow_figure = None + self._vorticity_figure = None + self._streamline_figure = None + + def __call__( + self, diagnostics: FiniteWingIteration, result: FiniteWingResult + ) -> None: + """Refresh both live plots with a copied iteration snapshot.""" + if diagnostics.iteration != result.iterations: + raise ValueError("diagnostics iteration must match the result history") + ( + self._flow_figure, + self._vorticity_figure, + self._streamline_figure, + ) = _draw_finite_wing_result( + result, + flow_figure=self._flow_figure, + vorticity_figure=self._vorticity_figure, + streamline_figure=self._streamline_figure, + ) + self._plt.show(block=False) + self._flow_figure.canvas.draw_idle() + self._vorticity_figure.canvas.draw_idle() + self._streamline_figure.canvas.draw_idle() + self._plt.pause(0.001) + + def finish( + self, result: FiniteWingResult, *, show: bool = True + ) -> dict[str, Path]: + """Save the final live views and optionally leave them open.""" + if not isinstance(result, FiniteWingResult): + raise TypeError("result must be a FiniteWingResult") + if not isinstance(show, bool): + raise TypeError("show must be a bool") + if not result.history: + raise ValueError("result must contain at least one completed iteration") + + ( + self._flow_figure, + self._vorticity_figure, + self._streamline_figure, + ) = _draw_finite_wing_result( + result, + flow_figure=self._flow_figure, + vorticity_figure=self._vorticity_figure, + streamline_figure=self._streamline_figure, + ) + paths = _plot_paths(self._output_directory) + self._flow_figure.savefig(paths["midspan"], dpi=160) + self._vorticity_figure.savefig(paths["tip_vorticity"], dpi=160) + self._streamline_figure.savefig(paths["streamlines"], dpi=160) + self._plt.ioff() + if show: + self._plt.show() + self._plt.close(self._flow_figure) + self._plt.close(self._vorticity_figure) + self._plt.close(self._streamline_figure) + return paths diff --git a/Exp_solver_dev_tr/src/heat_transfer/__init__.py b/Exp_solver_dev_tr/src/heat_transfer/__init__.py new file mode 100644 index 0000000000000..a2f9aef4b7f84 --- /dev/null +++ b/Exp_solver_dev_tr/src/heat_transfer/__init__.py @@ -0,0 +1,13 @@ +"""Basic steady two-dimensional heat conduction on a rectangular plate.""" + +from .solver import HeatIteration, HeatResult, HeatSettings, HeatSolver +from .visualization import LiveHeatPlotter, plot_heat_result + +__all__ = [ + "HeatIteration", + "HeatResult", + "HeatSettings", + "HeatSolver", + "LiveHeatPlotter", + "plot_heat_result", +] diff --git a/Exp_solver_dev_tr/src/heat_transfer/solver.py b/Exp_solver_dev_tr/src/heat_transfer/solver.py new file mode 100644 index 0000000000000..764df9f79a995 --- /dev/null +++ b/Exp_solver_dev_tr/src/heat_transfer/solver.py @@ -0,0 +1,356 @@ +"""Finite-volume solver for steady heat conduction in a rectangular plate.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from math import isfinite +from numbers import Integral, Real + +import numpy as np +from numpy.typing import NDArray +from scipy.sparse import coo_matrix, csr_matrix + +FloatArray = NDArray[np.float64] + + +@dataclass(frozen=True, slots=True) +class HeatSettings: + """Geometry, material, mesh, and boundary data for a 2D plate. + + All values use SI units except temperatures, which are in degrees Celsius. + A ``None`` boundary temperature is insulated when convection is disabled + and convective when enabled. At least one edge must define a heat exchange + condition. + """ + + width: float = 1.0 + height: float = 1.0 + nx: int = 50 + ny: int = 50 + thermal_conductivity: float = 10.0 + left_temperature_c: float | None = 0.0 + right_temperature_c: float | None = 0.0 + bottom_temperature_c: float | None = 0.0 + top_temperature_c: float | None = 100.0 + max_iterations: int = 10000 + residual_tolerance: float = 1e-8 + relaxation_factor: float = 1.7 + convection_enabled: bool = False + convection_heat_transfer_coefficient_w_m2_k: float | None = None + ambient_temperature_c: float | None = None + + def __post_init__(self) -> None: + for name in ("width", "height", "thermal_conductivity"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Real): + raise TypeError(f"{name} must be a finite positive number") + if not isfinite(value) or value <= 0.0: + raise ValueError(f"{name} must be a finite positive number") + for name in ("nx", "ny"): + value = getattr(self, name) + if isinstance(value, bool) or not isinstance(value, Integral): + raise TypeError(f"{name} must be an integer") + if value < 2: + raise ValueError(f"{name} must be at least 2") + if ( + isinstance(self.max_iterations, bool) + or not isinstance(self.max_iterations, Integral) + or self.max_iterations < 1 + ): + raise ValueError("max_iterations must be a positive integer") + if ( + isinstance(self.residual_tolerance, bool) + or not isinstance(self.residual_tolerance, Real) + or not isfinite(self.residual_tolerance) + or self.residual_tolerance <= 0.0 + ): + raise ValueError("residual_tolerance must be a finite positive number") + if ( + isinstance(self.relaxation_factor, bool) + or not isinstance(self.relaxation_factor, Real) + or not isfinite(self.relaxation_factor) + or not 0.0 < self.relaxation_factor < 2.0 + ): + raise ValueError("relaxation_factor must be in (0, 2)") + for name in ( + "left_temperature_c", + "right_temperature_c", + "bottom_temperature_c", + "top_temperature_c", + ): + value = getattr(self, name) + if value is not None and ( + isinstance(value, bool) + or not isinstance(value, Real) + or not isfinite(value) + ): + raise ValueError(f"{name} must be a finite number or None") + if not isinstance(self.convection_enabled, bool): + raise TypeError("convection_enabled must be a bool") + no_prescribed_temperatures = all( + getattr(self, name) is None + for name in ( + "left_temperature_c", + "right_temperature_c", + "bottom_temperature_c", + "top_temperature_c", + ) + ) + if self.convection_enabled: + coefficient = self.convection_heat_transfer_coefficient_w_m2_k + ambient_temperature = self.ambient_temperature_c + if ( + isinstance(coefficient, bool) + or not isinstance(coefficient, Real) + or not isfinite(coefficient) + or coefficient <= 0.0 + ): + raise ValueError( + "convection_heat_transfer_coefficient_w_m2_k must be a " + "finite positive number when convection is enabled" + ) + if ( + isinstance(ambient_temperature, bool) + or not isinstance(ambient_temperature, Real) + or not isfinite(ambient_temperature) + ): + raise ValueError( + "ambient_temperature_c must be finite when convection is enabled" + ) + if not no_prescribed_temperatures and all( + getattr(self, name) is not None + for name in ( + "left_temperature_c", + "right_temperature_c", + "bottom_temperature_c", + "top_temperature_c", + ) + ): + raise ValueError( + "convection_enabled requires at least one edge without a " + "prescribed temperature" + ) + elif no_prescribed_temperatures: + raise ValueError("at least one edge must have a prescribed temperature") + + +@dataclass(frozen=True, slots=True) +class HeatResult: + """Cell-centered temperature, heat flux, and iterative solve status.""" + + temperature_c: FloatArray + heat_flux_x: FloatArray + heat_flux_y: FloatArray + x_centers: FloatArray + y_centers: FloatArray + settings: HeatSettings + iterations: int + relative_residual: float + converged: bool + + +@dataclass(frozen=True, slots=True) +class HeatIteration: + """Convergence diagnostic for one steady-solver iteration.""" + + iteration: int + relative_residual: float + + +HeatIterationObserver = Callable[[HeatIteration, HeatResult], None] + + +class HeatSolver: + """Iteratively solve steady conduction with fixed and optional convective edges. + + The governing equation is ``div(k grad(T)) = 0`` for constant thermal + conductivity ``k``. Convection is a Robin boundary condition applied to + edges whose temperature is ``None``. The matrix is assembled with face + conductances and solved by successive over-relaxation. + """ + + def __init__(self, settings: HeatSettings = HeatSettings()) -> None: + if not isinstance(settings, HeatSettings): + raise TypeError("settings must be a HeatSettings instance") + self.settings = settings + + def _assemble_system(self) -> tuple[csr_matrix, FloatArray]: + settings = self.settings + nx = settings.nx + ny = settings.ny + dx = settings.width / nx + dy = settings.height / ny + conductivity = settings.thermal_conductivity + x_conductance = conductivity * dy / dx + y_conductance = conductivity * dx / dy + convection_coefficient = settings.convection_heat_transfer_coefficient_w_m2_k + ambient_temperature = settings.ambient_temperature_c + if settings.convection_enabled and ( + convection_coefficient is None or ambient_temperature is None + ): + raise RuntimeError("enabled convection is missing validated inputs") + matrix_rows: list[int] = [] + matrix_columns: list[int] = [] + matrix_values: list[float] = [] + rhs = np.zeros(nx * ny, dtype=np.float64) + + boundaries = ( + ("left_temperature_c", 0, -1, x_conductance, dy, 0.5 * dx), + ("right_temperature_c", 0, 1, x_conductance, dy, 0.5 * dx), + ("bottom_temperature_c", -1, 0, y_conductance, dx, 0.5 * dy), + ("top_temperature_c", 1, 0, y_conductance, dx, 0.5 * dy), + ) + for row in range(ny): + for column in range(nx): + cell = row * nx + column + diagonal = 0.0 + for ( + boundary_name, + row_offset, + column_offset, + conductance, + face_area, + half_cell_distance, + ) in boundaries: + neighbor_row = row + row_offset + neighbor_column = column + column_offset + has_neighbor = ( + 0 <= neighbor_row < ny and 0 <= neighbor_column < nx + ) + if has_neighbor: + diagonal += conductance + matrix_rows.append(cell) + matrix_columns.append(neighbor_row * nx + neighbor_column) + matrix_values.append(-conductance) + else: + boundary_temperature = getattr(settings, boundary_name) + if boundary_temperature is not None: + boundary_conductance = 2.0 * conductance + diagonal += boundary_conductance + rhs[cell] += boundary_conductance * boundary_temperature + elif settings.convection_enabled: + assert convection_coefficient is not None + assert ambient_temperature is not None + boundary_conductance = face_area / ( + half_cell_distance / conductivity + + 1.0 / convection_coefficient + ) + diagonal += boundary_conductance + rhs[cell] += boundary_conductance * ambient_temperature + matrix_rows.append(cell) + matrix_columns.append(cell) + matrix_values.append(diagonal) + + matrix = coo_matrix( + (matrix_values, (matrix_rows, matrix_columns)), + shape=(nx * ny, nx * ny), + ).tocsr() + return matrix, rhs + + def _make_result( + self, + temperature: FloatArray, + *, + iterations: int, + relative_residual: float, + converged: bool, + ) -> HeatResult: + settings = self.settings + nx = settings.nx + ny = settings.ny + dx = settings.width / settings.nx + dy = settings.height / settings.ny + temperature_gradient_y, temperature_gradient_x = np.gradient( + temperature, dy, dx + ) + x_centers = (np.arange(nx, dtype=np.float64) + 0.5) * dx + y_centers = (np.arange(ny, dtype=np.float64) + 0.5) * dy + return HeatResult( + temperature_c=temperature.copy(), + heat_flux_x=-settings.thermal_conductivity * temperature_gradient_x, + heat_flux_y=-settings.thermal_conductivity * temperature_gradient_y, + x_centers=x_centers, + y_centers=y_centers, + settings=settings, + iterations=iterations, + relative_residual=relative_residual, + converged=converged, + ) + + def run( + self, observer: HeatIterationObserver | None = None + ) -> HeatResult: + """Solve iteratively, notifying an optional observer after each sweep.""" + if observer is not None and not callable(observer): + raise TypeError("observer must be callable") + + settings = self.settings + matrix, rhs = self._assemble_system() + nx = settings.nx + ny = settings.ny + prescribed_temperatures = [ + value + for value in ( + settings.left_temperature_c, + settings.right_temperature_c, + settings.bottom_temperature_c, + settings.top_temperature_c, + ) + if value is not None + ] + initial_temperature = ( + float(np.mean(prescribed_temperatures)) + if prescribed_temperatures + else float(settings.ambient_temperature_c) + ) + temperature = np.full( + nx * ny, initial_temperature, dtype=np.float64 + ) + diagonal = matrix.diagonal() + indptr = matrix.indptr + indices = matrix.indices + coefficients = matrix.data + rhs_scale = max(1.0, float(np.max(np.abs(rhs)))) + relative_residual = float("inf") + converged = False + iteration = 0 + + for iteration in range(1, settings.max_iterations + 1): + for cell in range(nx * ny): + off_diagonal_sum = 0.0 + for position in range(indptr[cell], indptr[cell + 1]): + neighbor = indices[position] + if neighbor != cell: + off_diagonal_sum += coefficients[position] * temperature[neighbor] + gauss_seidel_value = (rhs[cell] - off_diagonal_sum) / diagonal[cell] + temperature[cell] += settings.relaxation_factor * ( + gauss_seidel_value - temperature[cell] + ) + + residual = matrix @ temperature - rhs + relative_residual = float(np.max(np.abs(residual)) / rhs_scale) + converged = relative_residual <= settings.residual_tolerance + if observer is not None: + temperature_field = temperature.reshape((ny, nx)).copy() + observer( + HeatIteration(iteration, relative_residual), + self._make_result( + temperature_field, + iterations=iteration, + relative_residual=relative_residual, + converged=converged, + ), + ) + if converged: + break + + temperature_field = temperature.reshape((ny, nx)) + if not np.all(np.isfinite(temperature_field)): + raise RuntimeError("heat-conduction solve produced non-finite temperatures") + return self._make_result( + temperature_field, + iterations=iteration, + relative_residual=relative_residual, + converged=converged, + ) diff --git a/Exp_solver_dev_tr/src/heat_transfer/visualization.py b/Exp_solver_dev_tr/src/heat_transfer/visualization.py new file mode 100644 index 0000000000000..6478e60f3b377 --- /dev/null +++ b/Exp_solver_dev_tr/src/heat_transfer/visualization.py @@ -0,0 +1,215 @@ +"""Static and live temperature/heat-flux plots for plate conduction runs.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +from .solver import HeatIteration, HeatResult, HeatSettings + + +def _temperature_limits(temperature: np.ndarray) -> tuple[float, float]: + minimum = float(np.min(temperature)) + maximum = float(np.max(temperature)) + if minimum == maximum: + padding = max(abs(minimum) * 1e-6, 1e-6) + return minimum - padding, maximum + padding + return minimum, maximum + + +def _draw_heat_plot( + result: HeatResult, + *, + title: str, + figure=None, +): + """Create the shared temperature/heat-flux plot used by save and live modes.""" + import matplotlib.pyplot as plt + + settings = result.settings + x_edges = np.linspace(0.0, settings.width, settings.nx + 1) + y_edges = np.linspace(0.0, settings.height, settings.ny + 1) + x_grid, y_grid = np.meshgrid(result.x_centers, result.y_centers) + stride = max(1, min(settings.nx, settings.ny) // 15) + limits = _temperature_limits(result.temperature_c) + + if figure is None: + figure, axis = plt.subplots(figsize=(8, 6), constrained_layout=True) + else: + figure.clear() + axis = figure.subplots() + temperature_plot = axis.pcolormesh( + x_edges, + y_edges, + result.temperature_c, + shading="flat", + cmap="inferno", + vmin=limits[0], + vmax=limits[1], + ) + figure.colorbar(temperature_plot, ax=axis, label="Temperature (°C)") + heat_flux_plot = axis.quiver( + x_grid[::stride, ::stride], + y_grid[::stride, ::stride], + result.heat_flux_x[::stride, ::stride], + result.heat_flux_y[::stride, ::stride], + color="cyan", + alpha=0.8, + label="Heat flux", + ) + axis.set( + title=title, + xlabel="x (m)", + ylabel="y (m)", + xlim=(0.0, settings.width), + ylim=(0.0, settings.height), + ) + axis.set_aspect("equal", adjustable="box") + axis.legend(loc="upper right") + return figure, temperature_plot, heat_flux_plot, axis + + +def _result_title(result: HeatResult) -> str: + status = "converged" if result.converged else "iteration limit reached" + model = ( + "conduction + surface convection" + if result.settings.convection_enabled + else "conduction only" + ) + return ( + f"Steady temperature and heat flux ({model}; " + f"{status} after {result.iterations} iterations)" + ) + + +def plot_heat_result( + result: HeatResult, + output_directory: str | Path, + *, + show: bool = False, +) -> Path: + """Save a plate-temperature plot with heat-flux vectors. + + Returns the path to ``heat_plate.png``. The result is not modified. + """ + if not isinstance(result, HeatResult): + raise TypeError("result must be a HeatResult") + if not isinstance(show, bool): + raise TypeError("show must be a bool") + + import matplotlib.pyplot as plt + + figure, _, _, _ = _draw_heat_plot(result, title=_result_title(result)) + output_path = Path(output_directory) + output_path.mkdir(parents=True, exist_ok=True) + plot_path = output_path / "heat_plate.png" + figure.savefig(plot_path, dpi=160) + if show: + plt.show() + plt.close(figure) + return plot_path + + +class LiveHeatPlotter: + """Refresh the shared temperature/heat-flux plot after every iteration.""" + + def __init__( + self, settings: HeatSettings, output_directory: str | Path + ) -> None: + import matplotlib.pyplot as plt + + if plt.get_backend().lower() in { + "agg", + "pdf", + "ps", + "svg", + "cairo", + "template", + }: + raise RuntimeError( + "live visualization requires an interactive Matplotlib backend; " + "use --mode save for headless runs" + ) + self._plt = plt + self._settings = settings + self._output_directory = Path(output_directory) + self._output_directory.mkdir(parents=True, exist_ok=True) + self._stride = max(1, min(settings.nx, settings.ny) // 15) + + initial_temperature = np.full( + (settings.ny, settings.nx), + np.mean( + [ + value + for value in ( + settings.left_temperature_c, + settings.right_temperature_c, + settings.bottom_temperature_c, + settings.top_temperature_c, + ) + if value is not None + ] + ), + dtype=np.float64, + ) + dx = settings.width / settings.nx + dy = settings.height / settings.ny + initial_result = HeatResult( + temperature_c=initial_temperature, + heat_flux_x=np.zeros_like(initial_temperature), + heat_flux_y=np.zeros_like(initial_temperature), + x_centers=(np.arange(settings.nx, dtype=np.float64) + 0.5) * dx, + y_centers=(np.arange(settings.ny, dtype=np.float64) + 0.5) * dy, + settings=settings, + iterations=0, + relative_residual=float("inf"), + converged=False, + ) + ( + self._figure, + self._temperature_plot, + self._heat_flux_plot, + self._axis, + ) = _draw_heat_plot(initial_result, title="Initial temperature guess") + plt.ion() + plt.show(block=False) + + def __call__(self, diagnostics: HeatIteration, result: HeatResult) -> None: + """Update live temperature and heat-flux artists for one iteration.""" + self._temperature_plot.set_array(result.temperature_c.ravel()) + self._temperature_plot.set_clim(*_temperature_limits(result.temperature_c)) + stride = self._stride + self._heat_flux_plot.set_UVC( + result.heat_flux_x[::stride, ::stride], + result.heat_flux_y[::stride, ::stride], + ) + self._axis.set_title( + f"{'Conduction + surface convection' if self._settings.convection_enabled else 'Conduction only'} | " + f"iteration {diagnostics.iteration} | " + f"relative residual {diagnostics.relative_residual:.3g}" + ) + self._figure.canvas.draw_idle() + self._plt.pause(0.001) + + def finish(self, result: HeatResult, *, show: bool = True) -> Path: + """Save the final live view and optionally leave it open.""" + if not isinstance(result, HeatResult): + raise TypeError("result must be a HeatResult") + if not isinstance(show, bool): + raise TypeError("show must be a bool") + self._temperature_plot.set_array(result.temperature_c.ravel()) + self._temperature_plot.set_clim(*_temperature_limits(result.temperature_c)) + stride = self._stride + self._heat_flux_plot.set_UVC( + result.heat_flux_x[::stride, ::stride], + result.heat_flux_y[::stride, ::stride], + ) + self._axis.set_title(_result_title(result)) + path = self._output_directory / "heat_plate.png" + self._figure.savefig(path, dpi=160) + self._plt.ioff() + if show: + self._plt.show() + self._plt.close(self._figure) + return path diff --git a/Exp_solver_dev_tr/tests/test_boundary_conditions.py b/Exp_solver_dev_tr/tests/test_boundary_conditions.py new file mode 100644 index 0000000000000..63a593336cda9 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_boundary_conditions.py @@ -0,0 +1,74 @@ +import pytest + +from fvm import ( + BoundaryConditions, + FixedValue, + MovingWall, + NoSlipWall, + ZeroGradient, +) + + +def test_cavity_conditions_can_be_stored_by_field_and_boundary() -> None: + conditions = BoundaryConditions() + conditions.set("velocity", "north", MovingWall((1.0, 0.0))) + conditions.set("velocity", "south", NoSlipWall()) + conditions.set("pressure", "north", ZeroGradient()) + conditions.set("pressure", "west", FixedValue(0.0)) + + assert conditions.get("velocity", "north") == MovingWall((1.0, 0.0)) + assert conditions.get("velocity", "south") == NoSlipWall() + assert conditions.get("pressure", "north") == ZeroGradient() + assert len(conditions) == 4 + assert set(conditions.for_field("pressure")) == {"north", "west"} + + +def test_complete_cavity_boundary_assignment() -> None: + conditions = BoundaryConditions() + conditions.set("velocity", "north", MovingWall((1.0, 0.0))) + for side in ("west", "east", "south"): + conditions.set("velocity", side, NoSlipWall()) + for side in ("west", "east", "south", "north"): + conditions.set("pressure", side, ZeroGradient()) + + assert set(conditions.for_field("velocity")) == {"west", "east", "south", "north"} + assert set(conditions.for_field("pressure")) == {"west", "east", "south", "north"} + assert conditions.get("velocity", "north") == MovingWall((1.0, 0.0)) + + +def test_boundary_conditions_can_replace_a_condition() -> None: + conditions = BoundaryConditions() + conditions.set("pressure", "east", ZeroGradient()) + conditions.set("pressure", "east", FixedValue(2.0)) + + assert len(conditions) == 1 + assert conditions.get("pressure", "east") == FixedValue(2.0) + + +def test_boundary_conditions_validate_names_and_types() -> None: + conditions = BoundaryConditions() + + with pytest.raises(ValueError, match="boundary"): + conditions.set("pressure", "middle", ZeroGradient()) + with pytest.raises(ValueError, match="field_name"): + conditions.set("", "north", ZeroGradient()) + with pytest.raises(TypeError, match="unsupported"): + conditions.set("pressure", "north", object()) # type: ignore[arg-type] + with pytest.raises(KeyError): + conditions.get("pressure", "north") + + +def test_velocity_conditions_require_two_finite_components() -> None: + with pytest.raises(ValueError, match="two components"): + MovingWall((1.0,)) # type: ignore[arg-type] + with pytest.raises(ValueError, match="finite"): + NoSlipWall((0.0, float("nan"))) + + +def test_field_conditions_are_read_only() -> None: + conditions = BoundaryConditions() + conditions.set("pressure", "north", ZeroGradient()) + + field_conditions = conditions.for_field("pressure") + with pytest.raises(TypeError): + field_conditions["south"] = ZeroGradient() # type: ignore[index] \ No newline at end of file diff --git a/Exp_solver_dev_tr/tests/test_checkpoint.py b/Exp_solver_dev_tr/tests/test_checkpoint.py new file mode 100644 index 0000000000000..7edcf58f3dc15 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_checkpoint.py @@ -0,0 +1,151 @@ +import json + +import numpy as np +import pytest + +from fvm import BoundaryConditions, CartesianMesh, MovingWall, NoSlipWall, ScalarField, TransientSolver, VectorField +from fvm.checkpoint import ( + CheckpointError, + CheckpointManager, + validate_case_compatibility, +) + + +def _case_document(max_steps: int = 4) -> dict[str, object]: + return { + "case_id": "checkpoint_test", + "mesh": {"nx": 5, "ny": 5, "width_m": 1.0, "height_m": 1.0}, + "material": {"density_kg_m3": 1.0, "dynamic_viscosity_pa_s": 0.01}, + "solver": {"max_steps": max_steps}, + } + + +def _saved_state(max_steps: int = 2): + mesh = CartesianMesh(nx=5, ny=5) + boundaries = BoundaryConditions() + for side in ("west", "east", "south"): + boundaries.set("velocity", side, NoSlipWall()) + boundaries.set("velocity", "north", MovingWall((1.0, 0.0))) + states = [] + TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=max_steps, + velocity_tolerance=1e-14, + ).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + boundaries, + state_observer=states.append, + ) + return mesh, states[-1] + + +def test_checkpoint_round_trips_state_and_loads_latest_or_specific(tmp_path) -> None: + mesh, state = _saved_state() + manager = CheckpointManager(tmp_path / "checkpoints") + checkpoint_path = manager.save(state, _case_document(max_steps=2)) + + latest = manager.load("latest", _case_document(max_steps=4), mesh) + specific = manager.load(checkpoint_path.name, _case_document(max_steps=2), mesh) + + for restored in (latest, specific): + assert restored.completed_steps == state.completed_steps == 2 + assert restored.elapsed_time == state.elapsed_time + assert restored.history == state.history + np.testing.assert_array_equal(restored.velocity.u.values, state.velocity.u.values) + np.testing.assert_array_equal(restored.velocity.v.values, state.velocity.v.values) + np.testing.assert_array_equal(restored.pressure.values, state.pressure.values) + manifest = json.loads((tmp_path / "checkpoints" / "latest.json").read_text()) + assert manifest["file"] == checkpoint_path.name + + +def test_checkpoint_rejects_numerically_incompatible_case(tmp_path) -> None: + mesh, state = _saved_state() + manager = CheckpointManager(tmp_path / "checkpoints") + manager.save(state, _case_document()) + changed_case = _case_document() + changed_case["material"] = { + "density_kg_m3": 1.0, + "dynamic_viscosity_pa_s": 0.02, + } + + with pytest.raises(CheckpointError, match="incompatible"): + manager.load("latest", changed_case, mesh) + + +def test_restart_compatibility_allows_only_increasing_run_limits() -> None: + saved_case = _case_document(max_steps=100) + saved_case["solver"]["end_time_s"] = 1.0 + extended_case = _case_document(max_steps=200) + extended_case["solver"]["end_time_s"] = 2.0 + + validate_case_compatibility(saved_case, extended_case) + + reduced_steps = _case_document(max_steps=99) + reduced_steps["solver"]["end_time_s"] = 1.0 + with pytest.raises(CheckpointError, match="max_steps may be increased"): + validate_case_compatibility(saved_case, reduced_steps) + reduced_time = _case_document(max_steps=100) + reduced_time["solver"]["end_time_s"] = 0.5 + with pytest.raises(CheckpointError, match="end_time_s may be increased"): + validate_case_compatibility(saved_case, reduced_time) + + +def test_checkpoint_latest_detects_modified_archive(tmp_path) -> None: + mesh, state = _saved_state() + manager = CheckpointManager(tmp_path / "checkpoints") + checkpoint_path = manager.save(state, _case_document()) + checkpoint_path.write_bytes(checkpoint_path.read_bytes() + b"corrupt") + + with pytest.raises(CheckpointError, match="SHA-256"): + manager.load("latest", _case_document(), mesh) + + +def test_checkpoint_retention_keeps_latest_and_newest_steps(tmp_path) -> None: + mesh = CartesianMesh(nx=5, ny=5) + boundaries = BoundaryConditions() + for side in ("west", "east", "south"): + boundaries.set("velocity", side, NoSlipWall()) + boundaries.set("velocity", "north", MovingWall((1.0, 0.0))) + states = [] + TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=4, + velocity_tolerance=1e-14, + ).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + boundaries, + state_observer=states.append, + ) + manager = CheckpointManager(tmp_path / "checkpoints", retain_last=2) + + for state in states: + manager.save(state, _case_document()) + + retained = list((tmp_path / "checkpoints").glob("checkpoint_*.npz")) + assert len(retained) == 2 + assert manager.load("latest", _case_document(), mesh).completed_steps == 4 + + +def test_failed_checkpoint_write_preserves_previous_latest(tmp_path, monkeypatch) -> None: + mesh, first_state = _saved_state(max_steps=1) + _, next_state = _saved_state(max_steps=2) + manager = CheckpointManager(tmp_path / "checkpoints") + manager.save(first_state, _case_document()) + latest_before = (tmp_path / "checkpoints" / "latest.json").read_text() + + def fail_write(*args, **kwargs): + raise OSError("simulated disk failure") + + monkeypatch.setattr("fvm.checkpoint.np.savez_compressed", fail_write) + with pytest.raises(OSError, match="simulated disk failure"): + manager.save(next_state, _case_document()) + + assert (tmp_path / "checkpoints" / "latest.json").read_text() == latest_before + restored = manager.load("latest", _case_document(), mesh) + assert restored.completed_steps == 1 \ No newline at end of file diff --git a/Exp_solver_dev_tr/tests/test_externalization.py b/Exp_solver_dev_tr/tests/test_externalization.py new file mode 100644 index 0000000000000..9c87624a3352a --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_externalization.py @@ -0,0 +1,289 @@ +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from types import SimpleNamespace + +import matplotlib +import numpy as np +import pytest + +matplotlib.use("Agg") + +from fvm.externalization import ( + AsyncFileExternalizer, + GrpcExternalizer, + GrpcSnapshotServer, + SharedFolderExternalizer, + SharedFolderPoller, + SnapshotStore, + StepSnapshot, + create_step_observer, + SynchronousFileExternalizer, + plot_latest_snapshot, +) + + +def _snapshot(step: int, run_id: str = "externalization-test") -> StepSnapshot: + return StepSnapshot( + run_id=run_id, + step=step, + mesh={"nx": 2, "ny": 2, "width": 1.0, "height": 1.0}, + diagnostics={ + "step": step, + "time": step * 0.1, + "pseudo_time": None, + "time_step": 0.1, + "cfl_number": 0.1, + "velocity_change": 0.01, + "max_divergence_before": 0.1, + "max_divergence_after": 0.0, + "global_mass_imbalance": 0.0, + "u_momentum_residual": 0.0, + "v_momentum_residual": 0.0, + "pressure_residual": 0.0, + "inner_iterations": 1, + }, + x_cell_centers=np.array([0.25, 0.75]), + y_cell_centers=np.array([0.25, 0.75]), + pressure=np.full((2, 2), step, dtype=float), + u_faces=np.full((2, 3), step, dtype=float), + v_faces=np.full((3, 2), -step, dtype=float), + ) + + +def test_snapshot_round_trip_is_validated_and_arrays_are_immutable() -> None: + snapshot = _snapshot(1) + + decoded = StepSnapshot.from_bytes(snapshot.to_bytes()) + + assert decoded.run_id == snapshot.run_id + assert decoded.step == 1 + np.testing.assert_array_equal(decoded.pressure, snapshot.pressure) + with pytest.raises(ValueError): + decoded.pressure[0, 0] = 4.0 + with pytest.raises(ValueError): + decoded.pressure.setflags(write=True) + with pytest.raises(ValueError, match="pressure must have shape"): + StepSnapshot( + run_id="invalid", + step=1, + mesh={"nx": 2, "ny": 2, "width": 1.0, "height": 1.0}, + diagnostics={"step": 1}, + x_cell_centers=np.array([0.25, 0.75]), + y_cell_centers=np.array([0.25, 0.75]), + pressure=np.zeros((1, 2)), + u_faces=np.zeros((2, 3)), + v_faces=np.zeros((3, 2)), + ) + + +@dataclass(frozen=True) +class _Step: + step: int + + +def _solver_fields(): + mesh = SimpleNamespace( + nx=2, + ny=2, + width=1.0, + height=1.0, + x_cell_centers=np.array([0.25, 0.75]), + y_cell_centers=np.array([0.25, 0.75]), + ) + velocity = SimpleNamespace( + mesh=mesh, + u=SimpleNamespace(values=np.zeros((2, 3))), + v=SimpleNamespace(values=np.zeros((3, 2))), + ) + pressure = SimpleNamespace(values=np.zeros((2, 2))) + return velocity, pressure + + +def test_step_observer_defaults_to_ten_steps_and_publishes_the_final_step() -> None: + class Collector: + def __init__(self) -> None: + self.steps: list[int] = [] + + def publish(self, snapshot: StepSnapshot) -> None: + self.steps.append(snapshot.step) + + collector = Collector() + observer = create_step_observer(collector, "sampled-run") + velocity, pressure = _solver_fields() + + for step in range(1, 21): + diagnostics = _Step(step) + observer(diagnostics, velocity, pressure) + assert observer.publish_final_step(_Step(20), velocity, pressure) is False + + assert collector.steps == [10, 20] + + +def test_step_observer_uses_configured_interval_and_final_step() -> None: + class Collector: + def __init__(self) -> None: + self.steps: list[int] = [] + + def publish(self, snapshot: StepSnapshot) -> None: + self.steps.append(snapshot.step) + + collector = Collector() + observer = create_step_observer( + collector, "custom-interval-run", snapshot_every=3 + ) + velocity, pressure = _solver_fields() + + for step in range(1, 6): + diagnostics = _Step(step) + observer(diagnostics, velocity, pressure) + observer.publish_final_step(_Step(5), velocity, pressure) + + assert collector.steps == [3, 5] + + +def test_synchronous_externalizer_writes_complete_readable_snapshots( + tmp_path: Path, +) -> None: + externalizer = SynchronousFileExternalizer(tmp_path / "sync") + externalizer.publish(_snapshot(1)) + externalizer.close() + store = SnapshotStore(tmp_path / "sync") + + assert store.latest_step == 1 + assert store.read(1).diagnostics["max_divergence_after"] == 0.0 + assert externalizer.metrics.snapshots == 1 + assert externalizer.metrics.bytes_written > 0 + + +def test_shared_folder_poller_copies_only_committed_new_steps( + tmp_path: Path, +) -> None: + shared = SharedFolderExternalizer(tmp_path / "shared") + poller = SharedFolderPoller(tmp_path / "shared", tmp_path / "externalized") + shared.publish(_snapshot(1)) + shared.publish(_snapshot(1, "other-run")) + shared.publish(_snapshot(2)) + + assert poller.poll_once() == 3 + assert poller.poll_once() == 0 + assert SnapshotStore(tmp_path / "externalized").latest_step == 2 + assert poller.snapshots == 3 + + +def test_async_externalizer_drains_bounded_queue_before_close(tmp_path: Path) -> None: + externalizer = AsyncFileExternalizer(tmp_path / "async", queue_size=1) + externalizer.publish(_snapshot(1)) + externalizer.publish(_snapshot(2)) + externalizer.close() + + assert SnapshotStore(tmp_path / "async").latest_step == 2 + assert externalizer.metrics.snapshots == 2 + assert externalizer.metrics.externalize_seconds >= 0.0 + + +def test_async_externalizer_surfaces_background_write_failure( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + externalizer = AsyncFileExternalizer(tmp_path / "failed", queue_size=1) + + def fail_write(snapshot: StepSnapshot) -> int: + raise OSError(f"disk unavailable for step {snapshot.step}") + + monkeypatch.setattr(externalizer.store, "write", fail_write) + externalizer.publish(_snapshot(1)) + + with pytest.raises(RuntimeError, match="asynchronous externalization failed"): + externalizer.close() + + +def test_grpc_externalizer_streams_snapshots_to_local_server(tmp_path: Path) -> None: + server = GrpcSnapshotServer(tmp_path / "grpc") + client = GrpcExternalizer(server.start(), queue_size=1) + try: + client.publish(_snapshot(1)) + client.publish(_snapshot(2)) + client.close() + finally: + server.stop() + + store = SnapshotStore(tmp_path / "grpc") + assert store.latest_step == 2 + assert store.read(1).run_id == "externalization-test" + assert client.metrics.snapshots == 2 + + +def test_grpc_server_accepts_independent_runs_in_separate_streams( + tmp_path: Path, +) -> None: + server = GrpcSnapshotServer(tmp_path / "grpc-multi-run") + target = server.start() + try: + for run_id in ("run-one", "run-two"): + client = GrpcExternalizer(target) + client.publish(_snapshot(1, run_id)) + client.close() + finally: + server.stop() + + store = SnapshotStore(tmp_path / "grpc-multi-run") + assert store.list_run_ids() == ("run-one", "run-two") + assert store.read(1, run_id="run-two").run_id == "run-two" + + +def test_snapshot_visualization_reads_externalized_data(tmp_path: Path) -> None: + store = SnapshotStore(tmp_path / "visualization") + store.write(_snapshot(1)) + + figure = plot_latest_snapshot(store, tmp_path / "snapshot.png") + + assert len(figure.axes) >= 3 + assert (tmp_path / "snapshot.png").stat().st_size > 1000 + + +def test_snapshot_store_writes_valid_metadata_without_pickle(tmp_path: Path) -> None: + store = SnapshotStore(tmp_path / "metadata") + store.write(_snapshot(1)) + + with np.load( + tmp_path / "metadata" / "externalization-test" / "step_00000001.npz", + allow_pickle=False, + ) as archive: + metadata = json.loads(str(archive["metadata"].item())) + + assert metadata["format_version"] == 1 + assert metadata["run_id"] == "externalization-test" + + +def test_snapshot_store_isolates_runs_and_requires_run_id_for_ambiguous_reads( + tmp_path: Path, +) -> None: + store = SnapshotStore(tmp_path / "multi-run") + store.write(_snapshot(1, "run-one")) + store.write(_snapshot(1, "run-two")) + + assert store.list_run_ids() == ("run-one", "run-two") + with pytest.raises(ValueError, match="run_id is required"): + store.read(1) + assert store.read(1, run_id="run-two").run_id == "run-two" + assert store.latest_snapshot.run_id in {"run-one", "run-two"} + + +def test_snapshot_store_supports_sparse_steps_and_rejects_out_of_order_writes( + tmp_path: Path, +) -> None: + store = SnapshotStore(tmp_path / "resumed") + store.write(_snapshot(20, "restarted-run")) + store.write(_snapshot(22, "restarted-run")) + + assert [item.step for item in store.iter_after_by_run({})] == [20, 22] + with pytest.raises(ValueError, match="in increasing order"): + store.write(_snapshot(21, "restarted-run")) + assert store.latest_step_for("restarted-run") == 22 + + +def test_snapshot_rejects_path_like_run_ids() -> None: + with pytest.raises(ValueError, match="run_id"): + _snapshot(1, "../outside") diff --git a/Exp_solver_dev_tr/tests/test_fields.py b/Exp_solver_dev_tr/tests/test_fields.py new file mode 100644 index 0000000000000..351228c443b60 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_fields.py @@ -0,0 +1,71 @@ +import numpy as np +import pytest + +from fvm import CartesianMesh, ScalarField, VectorField + + +def test_scalar_field_uses_requested_mesh_location() -> None: + mesh = CartesianMesh(nx=3, ny=2) + pressure = ScalarField(mesh, name="pressure", initial_value=4.5) + x_face_scalar = ScalarField(mesh, name="face_data", location="x_face") + y_face_scalar = ScalarField(mesh, name="face_data_y", location="y_face") + + assert pressure.values.shape == (2, 3) + assert x_face_scalar.values.shape == (2, 4) + assert y_face_scalar.values.shape == (3, 3) + np.testing.assert_array_equal(pressure.values, np.full((2, 3), 4.5)) + + +def test_scalar_field_replaces_values_with_a_copy() -> None: + field = ScalarField(CartesianMesh(nx=2, ny=2), name="pressure") + values = np.arange(4, dtype=np.float64).reshape(2, 2) + + field.set_values(values) + values[0, 0] = 100.0 + + assert field.values[0, 0] == 0.0 + np.testing.assert_array_equal(field.values, [[0.0, 1.0], [2.0, 3.0]]) + + +def test_scalar_field_rejects_wrong_shape_and_non_finite_values() -> None: + field = ScalarField(CartesianMesh(nx=2, ny=2), name="pressure") + + with pytest.raises(ValueError, match="shape"): + field.set_values(np.zeros((4,))) + with pytest.raises(ValueError, match="finite"): + field.set_values(np.full((2, 2), np.nan)) + + +def test_vector_field_has_mac_component_shapes_and_initial_values() -> None: + velocity = VectorField(CartesianMesh(nx=3, ny=2), initial_value=(1.0, -2.0)) + + assert velocity.u.values.shape == (2, 4) + assert velocity.v.values.shape == (3, 3) + np.testing.assert_array_equal(velocity.u.values, np.ones((2, 4))) + np.testing.assert_array_equal(velocity.v.values, np.full((3, 3), -2.0)) + + +def test_vector_field_updates_both_components_together() -> None: + velocity = VectorField(CartesianMesh(nx=2, ny=2)) + u_values = np.full((2, 3), 1.0) + v_values = np.full((3, 2), -1.0) + + velocity.set_values(u_values, v_values) + np.testing.assert_array_equal(velocity.u.values, u_values) + np.testing.assert_array_equal(velocity.v.values, v_values) + + previous_u = velocity.u.values.copy() + with pytest.raises(ValueError, match="shape"): + velocity.set_values(np.zeros((2, 3)), np.zeros((2, 2))) + np.testing.assert_array_equal(velocity.u.values, previous_u) + + +def test_re100_cavity_mesh_and_initial_velocity() -> None: + mesh = CartesianMesh(nx=64, ny=64, width=1.0, height=1.0) + velocity = VectorField(mesh) + + assert mesh.cell_area * mesh.nx * mesh.ny == pytest.approx(1.0) + assert velocity.u.values.shape == (64, 65) + assert velocity.v.values.shape == (65, 64) + assert np.count_nonzero(velocity.u.values) == 0 + assert np.count_nonzero(velocity.v.values) == 0 \ No newline at end of file diff --git a/Exp_solver_dev_tr/tests/test_fsi_solver.py b/Exp_solver_dev_tr/tests/test_fsi_solver.py new file mode 100644 index 0000000000000..f1427d0daaad3 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_fsi_solver.py @@ -0,0 +1,153 @@ +from unittest.mock import Mock + +import numpy as np +import pytest + +from fsi import FSISettings, FSISolver, LiveFSIPlotter, plot_fsi_result + + +def _small_settings(**overrides) -> FSISettings: + values = { + "nx": 40, + "ny": 12, + "beam_elements": 6, + "time_step": 0.0005, + "max_steps": 3, + } + values.update(overrides) + return FSISettings(**values) + + +def test_fsi_settings_reject_invalid_mesh_and_time_step() -> None: + with pytest.raises(ValueError, match="nx"): + FSISettings(nx=3) + with pytest.raises(ValueError, match="time_step"): + FSISettings(time_step=0.0) + + +def test_short_channel_beam_run_returns_finite_mac_fields_and_fixed_root() -> None: + result = FSISolver(_small_settings()).run() + + assert result.steps == 3 + assert result.final_time == pytest.approx(sum(item.time_step for item in result.history)) + assert result.converged + assert all(item.converged for item in result.history) + assert [item.time for item in result.history] == pytest.approx( + np.cumsum([item.time_step for item in result.history]) + ) + assert all( + item.coupling_residual <= result.settings.coupling_tolerance + for item in result.history + ) + assert result.u.shape == (12, 41) + assert result.v.shape == (13, 40) + assert result.pressure.shape == (12, 40) + assert result.beam_x.shape == (7,) + assert result.beam_y[0] == pytest.approx(result.settings.beam_root_y) + assert result.beam_y[-1] == pytest.approx( + result.settings.beam_root_y + result.history[-1].beam_tip_displacement + ) + assert np.all(np.isfinite(result.u)) + assert np.all(np.isfinite(result.v)) + assert np.all(np.isfinite(result.pressure)) + assert np.all(np.isfinite(result.beam_y)) + assert all(item.time_step <= result.settings.time_step for item in result.history) + assert all(item.max_divergence < 1e-8 for item in result.history) + + +def test_step_observer_gets_copied_fluid_fields() -> None: + observed_steps = [] + + def observe(diagnostics, u, v, pressure, beam_x, beam_y) -> None: + observed_steps.append(diagnostics.step) + u.fill(999.0) + v.fill(999.0) + pressure.fill(999.0) + beam_x.fill(999.0) + beam_y.fill(999.0) + + result = FSISolver(_small_settings(max_steps=2)).run(observer=observe) + + assert observed_steps == [1, 2] + assert np.max(result.u) < 999.0 + assert np.max(result.v) < 999.0 + assert not np.all(result.pressure == 999.0) + assert result.beam_y[0] != 999.0 + + +def test_end_time_clamps_last_step_and_reports_physical_time() -> None: + result = FSISolver( + _small_settings(max_steps=None, end_time=0.0007) + ).run() + + assert result.steps == 2 + assert result.final_time == pytest.approx(0.0007) + assert result.history[-1].time_step == pytest.approx(0.0002) + assert result.history[-1].time == pytest.approx(0.0007) + assert result.termination_reason == "final_time_reached" + assert result.converged + + +def test_run_stops_at_first_of_step_and_end_time_limits() -> None: + result = FSISolver( + _small_settings(max_steps=1, end_time=0.001) + ).run() + + assert result.steps == 1 + assert result.final_time < 0.001 + assert result.termination_reason == "maximum_steps_reached" + assert result.converged + + +def test_nonconverged_time_step_stops_with_explicit_status() -> None: + result = FSISolver( + _small_settings(max_steps=3, max_inner_iterations_per_time_step=1) + ).run() + + assert result.steps == 1 + assert not result.converged + assert result.termination_reason == "time_step_not_converged" + assert not result.history[0].converged + assert result.history[0].inner_iterations == 1 + + +def test_visualization_saves_field_and_beam_history_plots(tmp_path) -> None: + result = FSISolver(_small_settings(max_steps=2)).run() + + plots = plot_fsi_result(result, tmp_path) + + assert set(plots) == {"fields", "history"} + assert plots["fields"].name == "fsi_fields.png" + assert plots["history"].name == "fsi_history.png" + assert all(path.is_file() and path.stat().st_size > 0 for path in plots.values()) + + +def test_live_plotter_refreshes_each_iteration_and_saves_final_view( + tmp_path, monkeypatch +) -> None: + import matplotlib.pyplot as plt + + pauses = [] + monkeypatch.setattr(plt, "get_backend", lambda: "TkAgg") + monkeypatch.setattr(plt, "pause", lambda interval: pauses.append(interval)) + monkeypatch.setattr(plt, "show", Mock()) + settings = _small_settings(max_steps=2) + live_plotter = LiveFSIPlotter(settings, tmp_path) + + FSISolver(settings).run(observer=live_plotter) + plots = live_plotter.finish(show=False) + + assert pauses == [0.001, 0.001] + assert set(plots) == {"fields", "history"} + assert plots["fields"].name == "fsi_fields.png" + assert plots["history"].name == "fsi_history.png" + assert all(path.is_file() and path.stat().st_size > 0 for path in plots.values()) + + +def test_default_case_remains_finite_during_initial_transient() -> None: + result = FSISolver(FSISettings(max_steps=20)).run() + + assert all(np.isfinite(item.max_speed) for item in result.history) + assert all(np.isfinite(item.max_divergence) for item in result.history) + assert max(item.max_speed for item in result.history) < 5.0 + assert max(abs(item.beam_tip_displacement) for item in result.history) < 0.01 diff --git a/Exp_solver_dev_tr/tests/test_fvm3d.py b/Exp_solver_dev_tr/tests/test_fvm3d.py new file mode 100644 index 0000000000000..fe1121153a066 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_fvm3d.py @@ -0,0 +1,245 @@ +from dataclasses import replace + +import numpy as np +import pytest + +from fvm3d import ( + FiniteWingSettings, + FiniteWingSolver, + FiniteWingTransientSettings, + LiveFiniteWingPlotter, + plot_finite_wing_result, +) +from fvm3d.visualization import _integrate_wake_streamlines, _vorticity_x + + +def _ignore_matplotlib_call(*args: object, **kwargs: object) -> None: + _ = args, kwargs + + +def _small_settings(**overrides) -> FiniteWingSettings: + values = { + "length_x": 3.0, + "length_y": 2.0, + "length_z": 2.0, + "nx": 12, + "ny": 8, + "nz": 8, + "wing_leading_edge_x": 0.75, + "wing_chord": 0.75, + "wing_span": 1.0, + "wing_thickness": 0.5, + "pseudo_time_step_cap": 0.001, + "minimum_pseudo_time_step": 1e-10, + "max_iterations": 1, + "max_pressure_iterations": 500, + } + values.update(overrides) + return FiniteWingSettings(**values) + + +def test_inlet_speed_and_component_inputs_resolve_from_angle_of_attack() -> None: + by_speed = FiniteWingSettings(angle_of_attack_degrees=10.0, inlet_speed=2.0) + by_x = FiniteWingSettings( + angle_of_attack_degrees=10.0, + inlet_speed=None, + inlet_velocity_x=by_speed.inlet_velocity[0], + ) + by_y = FiniteWingSettings( + angle_of_attack_degrees=10.0, + inlet_speed=None, + inlet_velocity_y=by_speed.inlet_velocity[1], + ) + + assert by_speed.inlet_velocity == pytest.approx(by_x.inlet_velocity) + assert by_speed.inlet_velocity == pytest.approx(by_y.inlet_velocity) + assert by_speed.inlet_velocity[1] < 0.0 + assert by_speed.reynolds_number == pytest.approx(2000.0) + + +def test_settings_require_one_velocity_input_and_supported_angle() -> None: + with pytest.raises(ValueError, match="exactly one"): + FiniteWingSettings( + inlet_speed=1.0, + inlet_velocity_x=1.0, + ) + with pytest.raises(ValueError, match="between -5 and 20"): + FiniteWingSettings(angle_of_attack_degrees=21.0) + with pytest.raises(ValueError, match="cannot determine speed"): + FiniteWingSettings( + angle_of_attack_degrees=0.0, + inlet_speed=None, + inlet_velocity_y=0.2, + ) + + +def test_short_finite_wing_run_returns_finite_fields_and_projects_divergence() -> None: + result = FiniteWingSolver(_small_settings()).run() + + assert result.iterations == 1 + assert result.velocity_x.shape == (8, 12, 8) + assert result.velocity_y.shape == (8, 12, 8) + assert result.velocity_z.shape == (8, 12, 8) + assert result.pressure.shape == (8, 12, 8) + assert result.solid_mask.shape == (8, 12, 8) + assert np.any(result.solid_mask) + assert np.all(np.isfinite(result.velocity_x)) + assert np.all(np.isfinite(result.velocity_y)) + assert np.all(np.isfinite(result.velocity_z)) + assert np.all(np.isfinite(result.pressure)) + assert result.history[0].max_divergence < 1e-7 + + +def test_finite_wing_run_keeps_velocity_bounded_over_multiple_iterations() -> None: + result = FiniteWingSolver( + _small_settings(max_iterations=20, pseudo_time_step_cap=0.001) + ).run() + + assert result.iterations == 20 + assert max(step.max_speed for step in result.history) < 2.0 + assert max(step.max_divergence for step in result.history) < 1e-6 + + +def test_downstream_vorticity_resolves_counter_rotating_wingtip_cores() -> None: + settings = _small_settings(max_iterations=20) + result = FiniteWingSolver(settings).run() + trailing_edge = settings.wing_leading_edge_x + settings.wing_chord + slice_index = int( + np.argmin( + np.abs( + result.x_centers + - (trailing_edge + 0.25 * settings.wing_chord) + ) + ) + ) + + downstream_vorticity = _vorticity_x(result)[:, slice_index, :] + + assert np.min(downstream_vorticity) < 0.0 + assert np.max(downstream_vorticity) > 0.0 + + +def test_observer_receives_each_steady_iteration_snapshot() -> None: + observed = [] + settings = _small_settings(max_iterations=3) + + result = FiniteWingSolver(settings).run( + observer=lambda diagnostics, snapshot: observed.append( + (diagnostics, snapshot.iterations, snapshot.velocity_x.copy()) + ) + ) + + assert result.iterations == 3 + assert [entry[0].iteration for entry in observed] == [1, 2, 3] + assert [entry[1] for entry in observed] == [1, 2, 3] + assert observed[0][2].shape == result.velocity_x.shape + + +def test_transient_angle_ramp_reaches_configured_physical_end_time() -> None: + settings = _small_settings(angle_of_attack_degrees=0.0) + transient = FiniteWingTransientSettings( + end_time=0.02, + time_step_cap=0.005, + outlet_sponge_length=0.75, + angle_of_attack_schedule=((0.0, 0.0), (0.01, 1.0), (0.02, 2.0)), + ) + observed = [] + + result = FiniteWingSolver(settings).run_transient( + transient, + observer=lambda diagnostics, snapshot: observed.append( + (diagnostics, snapshot.physical_time, snapshot.angle_of_attack_degrees) + ), + ) + + assert result.iterations == 4 + assert result.physical_time == pytest.approx(0.02) + assert result.angle_of_attack_degrees == pytest.approx(2.0) + assert observed[0][0].time == pytest.approx(0.005) + assert observed[0][0].angle_of_attack_degrees == pytest.approx(0.5) + assert observed[-1][1] == pytest.approx(0.02) + assert observed[-1][2] == pytest.approx(2.0) + assert max(step.max_divergence for step in result.history) < 1e-7 + + +def test_transient_schedule_must_cover_end_time_and_match_initial_angle() -> None: + with pytest.raises(ValueError, match="must cover"): + FiniteWingTransientSettings( + end_time=2.0, + angle_of_attack_schedule=((0.0, 0.0), (1.0, 1.0)), + ) + + settings = _small_settings(angle_of_attack_degrees=1.0) + transient = FiniteWingTransientSettings( + end_time=1.0, + angle_of_attack_schedule=((0.0, 0.0), (1.0, 1.0)), + ) + with pytest.raises(ValueError, match="must match"): + FiniteWingSolver(settings).run_transient(transient) + + +def test_visualization_saves_all_three_flow_plots(tmp_path) -> None: + result = FiniteWingSolver(_small_settings()).run() + + plots = plot_finite_wing_result(result, tmp_path) + + assert set(plots) == {"midspan", "tip_vorticity", "streamlines"} + assert plots["midspan"].name == "finite_wing_midspan.png" + assert plots["tip_vorticity"].name == "finite_wing_tip_vorticity.png" + assert plots["streamlines"].name == "finite_wing_3d_streamlines.png" + assert all(path.is_file() and path.stat().st_size > 0 for path in plots.values()) + + +def test_3d_wake_streamlines_follow_uniform_flow_downstream() -> None: + result = FiniteWingSolver(_small_settings()).run() + uniform_flow = replace( + result, + velocity_x=np.ones_like(result.velocity_x), + velocity_y=np.zeros_like(result.velocity_y), + velocity_z=np.zeros_like(result.velocity_z), + solid_mask=np.zeros_like(result.solid_mask), + ) + + streamlines = _integrate_wake_streamlines(uniform_flow) + + assert streamlines + for path in streamlines: + assert path.shape[1] == 3 + assert np.all(np.diff(path[:, 0]) > 0.0) + assert path[-1, 0] == pytest.approx(result.x_centers[-1]) + assert np.allclose(path[:, 1], path[0, 1]) + assert np.allclose(path[:, 2], path[0, 2]) + + +def test_wake_streamlines_do_not_pass_through_the_wing() -> None: + result = FiniteWingSolver(_small_settings(max_iterations=10)).run() + + streamlines = _integrate_wake_streamlines(result) + + for path in streamlines: + x_indices = np.abs( + result.x_centers[None, :] - path[:, 0, None] + ).argmin(axis=1) + y_indices = np.abs( + result.y_centers[None, :] - path[:, 1, None] + ).argmin(axis=1) + z_indices = np.abs( + result.z_centers[None, :] - path[:, 2, None] + ).argmin(axis=1) + assert not np.any(result.solid_mask[y_indices, x_indices, z_indices]) + + +def test_live_plotter_updates_and_saves_all_shared_views(tmp_path, monkeypatch) -> None: + import matplotlib.pyplot as plt + + monkeypatch.setattr(plt, "get_backend", lambda: "TkAgg") + monkeypatch.setattr(plt, "show", _ignore_matplotlib_call) + monkeypatch.setattr(plt, "pause", _ignore_matplotlib_call) + settings = _small_settings(max_iterations=2) + plotter = LiveFiniteWingPlotter(settings, tmp_path) + + result = FiniteWingSolver(settings).run(observer=plotter) + plots = plotter.finish(result, show=False) + + assert set(plots) == {"midspan", "tip_vorticity", "streamlines"} + assert all(path.is_file() and path.stat().st_size > 0 for path in plots.values()) diff --git a/Exp_solver_dev_tr/tests/test_heat_transfer.py b/Exp_solver_dev_tr/tests/test_heat_transfer.py new file mode 100644 index 0000000000000..020af3979d5f7 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_heat_transfer.py @@ -0,0 +1,222 @@ +from unittest.mock import Mock + +import numpy as np +import pytest + +from heat_transfer import ( + HeatSettings, + HeatSolver, + LiveHeatPlotter, + plot_heat_result, +) + + +def test_equal_edge_temperatures_produce_uniform_plate_temperature() -> None: + result = HeatSolver( + HeatSettings( + nx=8, + ny=6, + left_temperature_c=25.0, + right_temperature_c=25.0, + bottom_temperature_c=25.0, + top_temperature_c=25.0, + ) + ).run() + + assert np.allclose(result.temperature_c, 25.0) + assert np.allclose(result.heat_flux_x, 0.0) + assert np.allclose(result.heat_flux_y, 0.0) + + +def test_opposing_fixed_temperatures_and_insulated_edges_give_linear_profile() -> None: + result = HeatSolver( + HeatSettings( + width=2.0, + height=1.0, + nx=20, + ny=8, + thermal_conductivity=5.0, + left_temperature_c=100.0, + right_temperature_c=0.0, + bottom_temperature_c=None, + top_temperature_c=None, + residual_tolerance=1e-12, + ) + ).run() + expected_temperature = 100.0 * (1.0 - result.x_centers / 2.0) + + assert np.allclose(result.temperature_c, expected_temperature[None, :]) + assert np.allclose(result.heat_flux_x, 250.0) + assert np.allclose(result.heat_flux_y, 0.0) + + +def test_hot_top_case_obeys_temperature_bounds_and_left_right_symmetry() -> None: + result = HeatSolver( + HeatSettings(nx=16, ny=12, top_temperature_c=100.0) + ).run() + + assert np.all(np.isfinite(result.temperature_c)) + assert result.temperature_c.min() >= 0.0 + assert result.temperature_c.max() <= 100.0 + assert np.allclose(result.temperature_c, result.temperature_c[:, ::-1]) + + +def test_convection_flag_off_ignores_convection_inputs() -> None: + insulated = HeatSolver( + HeatSettings( + nx=12, + ny=10, + left_temperature_c=None, + right_temperature_c=None, + bottom_temperature_c=0.0, + top_temperature_c=100.0, + ) + ).run() + disabled_with_inputs = HeatSolver( + HeatSettings( + nx=12, + ny=10, + left_temperature_c=None, + right_temperature_c=None, + bottom_temperature_c=0.0, + top_temperature_c=100.0, + convection_enabled=False, + convection_heat_transfer_coefficient_w_m2_k=250.0, + ambient_temperature_c=20.0, + ) + ).run() + + assert np.array_equal(insulated.temperature_c, disabled_with_inputs.temperature_c) + + +def test_enabled_surface_convection_changes_the_temperature_field() -> None: + conduction_only = HeatSolver( + HeatSettings( + nx=12, + ny=10, + left_temperature_c=None, + right_temperature_c=None, + bottom_temperature_c=0.0, + top_temperature_c=100.0, + ) + ).run() + with_convection = HeatSolver( + HeatSettings( + nx=12, + ny=10, + left_temperature_c=None, + right_temperature_c=None, + bottom_temperature_c=0.0, + top_temperature_c=100.0, + convection_enabled=True, + convection_heat_transfer_coefficient_w_m2_k=25.0, + ambient_temperature_c=20.0, + ) + ).run() + + assert with_convection.converged + assert np.max( + np.abs(with_convection.temperature_c - conduction_only.temperature_c) + ) > 1e-2 + assert with_convection.temperature_c.min() >= 0.0 + assert with_convection.temperature_c.max() <= 100.0 + + +def test_convection_with_ambient_only_boundaries_reaches_ambient_temperature() -> None: + result = HeatSolver( + HeatSettings( + nx=8, + ny=6, + left_temperature_c=None, + right_temperature_c=None, + bottom_temperature_c=None, + top_temperature_c=None, + convection_enabled=True, + convection_heat_transfer_coefficient_w_m2_k=15.0, + ambient_temperature_c=22.0, + ) + ).run() + + assert result.converged + assert np.allclose(result.temperature_c, 22.0) + + +def test_settings_reject_invalid_mesh_and_all_insulated_boundaries() -> None: + with pytest.raises(ValueError, match="nx"): + HeatSettings(nx=1) + with pytest.raises(ValueError, match="at least one edge"): + HeatSettings( + left_temperature_c=None, + right_temperature_c=None, + bottom_temperature_c=None, + top_temperature_c=None, + ) + with pytest.raises(ValueError, match="heat_transfer_coefficient"): + HeatSettings( + convection_enabled=True, + convection_heat_transfer_coefficient_w_m2_k=None, + ambient_temperature_c=20.0, + ) + with pytest.raises(ValueError, match="without a prescribed temperature"): + HeatSettings( + convection_enabled=True, + convection_heat_transfer_coefficient_w_m2_k=10.0, + ambient_temperature_c=20.0, + ) + + +def test_visualization_saves_temperature_and_heat_flux_plot(tmp_path) -> None: + result = HeatSolver(HeatSettings(nx=8, ny=8)).run() + + plot_path = plot_heat_result(result, tmp_path) + + assert plot_path.name == "heat_plate.png" + assert plot_path.is_file() + assert plot_path.stat().st_size > 0 + + +def test_iteration_observer_receives_copied_progressive_fields() -> None: + observed_iterations = [] + temperatures = [] + + def observe(diagnostics, result) -> None: + observed_iterations.append(diagnostics.iteration) + temperatures.append(result.temperature_c.copy()) + result.temperature_c.fill(-999.0) + + result = HeatSolver(HeatSettings(nx=10, ny=10)).run(observer=observe) + + assert observed_iterations == list(range(1, result.iterations + 1)) + assert result.converged + assert np.all(result.temperature_c >= 0.0) + assert not np.allclose(temperatures[0], temperatures[-1]) + + +def test_iteration_cap_is_reported_as_nonconvergence() -> None: + result = HeatSolver( + HeatSettings(nx=8, ny=8, max_iterations=1) + ).run() + + assert result.iterations == 1 + assert not result.converged + assert result.relative_residual > result.settings.residual_tolerance + + +def test_live_plotter_refreshes_each_iteration_and_saves_final_view( + tmp_path, monkeypatch +) -> None: + import matplotlib.pyplot as plt + + pauses = [] + monkeypatch.setattr(plt, "get_backend", lambda: "TkAgg") + monkeypatch.setattr(plt, "pause", lambda interval: pauses.append(interval)) + monkeypatch.setattr(plt, "show", Mock()) + settings = HeatSettings(nx=8, ny=8) + live_plotter = LiveHeatPlotter(settings, tmp_path) + + result = HeatSolver(settings).run(observer=live_plotter) + plot_path = live_plotter.finish(result, show=False) + + assert pauses == [0.001] * result.iterations + assert plot_path.name == "heat_plate.png" + assert plot_path.is_file() and plot_path.stat().st_size > 0 diff --git a/Exp_solver_dev_tr/tests/test_integration.py b/Exp_solver_dev_tr/tests/test_integration.py new file mode 100644 index 0000000000000..36d53cf4b87c4 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_integration.py @@ -0,0 +1,251 @@ +import copy +import json +from importlib.resources import files + +import numpy as np +import pytest +from jsonschema import Draft202012Validator + +from fvm import ( + CaseValidationError, + MovingWall, + NoSlipWall, + PythonFVMBackend, + load_case_file, + parse_case_definition, + validate_case_document, +) + +def _sample_document() -> dict[str, object]: + with open("cases/lid_driven_cavity_re100.json", encoding="utf-8") as case_file: + return json.load(case_file) + + +def test_packaged_schema_is_valid_and_sample_file_loads() -> None: + schema_path = files("fvm").joinpath("schemas", "case-v1.schema.json") + schema = json.loads(schema_path.read_text(encoding="utf-8")) + Draft202012Validator.check_schema(schema) + case = load_case_file("cases/lid_driven_cavity_re100.json") + + assert case.schema_version == "1.0" + assert case.case_id == "lid_driven_cavity_re100" + assert case.nx == case.ny == 16 + assert case.density == 1.0 + assert case.dynamic_viscosity == 0.01 + assert case.boundary_for("north").boundary_type == "moving_wall" + + +def test_shipped_cavity_cases_select_steady_and_accelerating_transient_modes() -> None: + steady = load_case_file("cases/lid_driven_cavity_re100_steady.json") + transient = load_case_file("cases/lid_driven_cavity_re100_transient.json") + + assert not steady.transient + assert steady.solver.max_time_step == pytest.approx(0.01) + assert steady.solver.cfl_limit == pytest.approx(0.5) + assert transient.transient + assert transient.solver.end_time == pytest.approx(6.0) + assert transient.boundary_for("north").velocity_at(0.5) == pytest.approx( + (0.5, 0.0) + ) + + +def test_steady_case_can_use_only_max_steps_for_solver_controls() -> None: + document = _sample_document() + document["physics"]["transient"] = False + document["solver"] = {"max_steps": 7} + + definition = parse_case_definition(document) + + assert definition.solver.max_steps == 7 + assert definition.solver.max_time_step == pytest.approx(0.01) + assert definition.solver.cfl_limit == pytest.approx(0.5) + assert definition.solver.velocity_tolerance == pytest.approx(1e-6) + + +def test_case_mapping_round_trips_and_maps_solver_objects() -> None: + definition = parse_case_definition(_sample_document()) + round_tripped = parse_case_definition(definition.to_mapping()) + prepared = PythonFVMBackend().prepare(definition) + + assert round_tripped == definition + assert prepared.mesh.nx == 16 + assert prepared.mesh.width == 1.0 + assert prepared.initial_velocity.u.values.shape == (16, 17) + assert prepared.initial_velocity.v.values.shape == (17, 16) + assert prepared.initial_pressure.values.shape == (16, 16) + assert prepared.boundary_conditions.get("velocity", "west") == NoSlipWall() + assert prepared.boundary_conditions.get("velocity", "north") == MovingWall((1.0, 0.0)) + assert prepared.solver.max_steps == 3 + assert prepared.solver.density == 1.0 + + +def test_time_dependent_wall_profile_interpolates_and_round_trips() -> None: + document = _sample_document() + document["boundary_conditions"]["north"] = { + "type": "moving_wall", + "velocity_profile": [ + {"time_s": 0.0, "velocity_m_s": [0.0, 0.0]}, + {"time_s": 1.0, "velocity_m_s": [1.0, 0.0]}, + ], + } + document["solver"]["end_time_s"] = 1.0 + definition = parse_case_definition(document) + wall = definition.boundary_for("north") + round_tripped = parse_case_definition(definition.to_mapping()) + + assert definition.transient + assert wall.velocity_at(0.5) == pytest.approx((0.5, 0.0)) + assert wall.maximum_velocity_between(0.25, 0.75) == pytest.approx((0.75, 0.0)) + assert round_tripped == definition + + +def test_case_schema_rejects_non_increasing_wall_profile_times() -> None: + document = _sample_document() + document["boundary_conditions"]["north"] = { + "type": "moving_wall", + "velocity_profile": [ + {"time_s": 0.5, "velocity_m_s": [0.5, 0.0]}, + {"time_s": 0.5, "velocity_m_s": [1.0, 0.0]}, + ], + } + + with pytest.raises(CaseValidationError, match="strictly increasing"): + validate_case_document(document) + + +def test_backend_runs_case_file_and_writes_stable_outputs(tmp_path) -> None: + backend = PythonFVMBackend() + + run = backend.run_file( + "cases/lid_driven_cavity_re100.json", + output_directory=tmp_path / "backend-run", + ) + + assert run.case_id == "lid_driven_cavity_re100" + assert not run.simulation.converged + assert run.summary["result_format_version"] == "1.0" + assert run.summary["reynolds_number"] == pytest.approx(100.0) + assert run.summary["status"] == "not_converged" + assert run.artifact_directory == tmp_path / "backend-run" + assert (run.artifact_directory / "case.json").exists() + assert (run.artifact_directory / "summary.json").exists() + assert (run.artifact_directory / "fields.npz").exists() + assert (run.artifact_directory / "history.csv").exists() + assert json.loads((run.artifact_directory / "summary.json").read_text())["case_id"] == run.case_id + + +def test_backend_forwards_step_observer_for_each_projection_step() -> None: + document = _sample_document() + document["solver"]["max_steps"] = 2 + document["solver"]["velocity_tolerance_m_s"] = 1e-14 + observed: list[tuple[int, tuple[int, int], tuple[int, int]]] = [] + + def observe(diagnostics, velocity, pressure) -> None: + observed.append( + (diagnostics.step, velocity.u.values.shape, pressure.values.shape) + ) + + run = PythonFVMBackend().run(document, step_observer=observe) + + assert len(observed) == run.simulation.steps + assert [entry[0] for entry in observed] == list(range(1, run.simulation.steps + 1)) + assert all(entry[1:] == ((16, 17), (16, 16)) for entry in observed) + + +def test_backend_checkpoints_and_resumes_from_latest(tmp_path) -> None: + document = _sample_document() + document["solver"]["max_steps"] = 3 + document["solver"]["velocity_tolerance_m_s"] = 1e-14 + output = tmp_path / "restartable-run" + backend = PythonFVMBackend() + + first = backend.run( + document, + output, + checkpoint_every=2, + ) + extended_document = copy.deepcopy(document) + extended_document["solver"]["max_steps"] = 4 + resumed = backend.run( + extended_document, + output, + checkpoint_every=2, + restart="latest", + ) + uninterrupted = backend.run(extended_document) + + assert first.simulation.steps == 3 + assert resumed.summary["restarted_from_step"] == 3 + assert [item.step for item in resumed.simulation.history] == [1, 2, 3, 4] + np.testing.assert_array_equal( + resumed.simulation.velocity.u.values, + uninterrupted.simulation.velocity.u.values, + ) + np.testing.assert_array_equal( + resumed.simulation.velocity.v.values, + uninterrupted.simulation.velocity.v.values, + ) + np.testing.assert_array_equal( + resumed.simulation.pressure.values, + uninterrupted.simulation.pressure.values, + ) + assert (output / "case.json").exists() + assert (output / "checkpoints" / "latest.json").exists() + assert (output / "checkpoints" / "checkpoint_00000002.npz").exists() + assert (output / "checkpoints" / "checkpoint_00000003.npz").exists() + assert (output / "checkpoints" / "checkpoint_00000004.npz").exists() + + +@pytest.mark.parametrize( + ("mutate", "expected_path"), + [ + (lambda case: case.pop("mesh"), "/mesh"), + (lambda case: case.update(schema_version="2.0"), "/schema_version"), + (lambda case: case.update(extra_setting=True), "/extra_setting"), + (lambda case: case["physics"].update(model="compressible"), "/physics/model"), + (lambda case: case["mesh"].update(type="unstructured"), "/mesh/type"), + (lambda case: case["boundary_conditions"].update(west={"type": "velocity_inlet"}), "/boundary_conditions/west"), + (lambda case: case["solver"].update(max_steps=0), "/solver/max_steps"), + ], +) +def test_schema_rejects_missing_unknown_or_unsupported_inputs(mutate, expected_path) -> None: + document = copy.deepcopy(_sample_document()) + mutate(document) + + with pytest.raises(CaseValidationError) as error: + validate_case_document(document) + + assert expected_path in str(error.value) + + +def test_semantic_validation_rejects_incompatible_wall_and_time_step_values() -> None: + non_tangent = copy.deepcopy(_sample_document()) + non_tangent["boundary_conditions"]["west"] = { + "type": "moving_wall", + "velocity_m_s": [0.1, 0.0], + } + with pytest.raises(CaseValidationError, match="wall-normal velocity"): + validate_case_document(non_tangent) + + invalid_time_step = copy.deepcopy(_sample_document()) + invalid_time_step["solver"]["minimum_time_step_s"] = 0.01 + with pytest.raises(CaseValidationError, match="must not exceed"): + validate_case_document(invalid_time_step) + + +def test_parser_rejects_non_finite_json_values() -> None: + document = _sample_document() + document["domain"]["width_m"] = float("nan") + + with pytest.raises(CaseValidationError, match="must be finite"): + parse_case_definition(document) + + +def test_loader_reports_invalid_json_and_missing_files(tmp_path) -> None: + invalid_json = tmp_path / "invalid.json" + invalid_json.write_text("{not json", encoding="utf-8") + + with pytest.raises(CaseValidationError, match="invalid JSON"): + load_case_file(invalid_json) + with pytest.raises(CaseValidationError, match="cannot read case file"): + load_case_file(tmp_path / "missing.json") \ No newline at end of file diff --git a/Exp_solver_dev_tr/tests/test_mesh.py b/Exp_solver_dev_tr/tests/test_mesh.py new file mode 100644 index 0000000000000..65e5295f4743d --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_mesh.py @@ -0,0 +1,64 @@ +import numpy as np +import pytest + +from fvm import BOUNDARY_NAMES, CartesianMesh + + +def test_mesh_dimensions_coordinates_and_areas() -> None: + mesh = CartesianMesh(nx=4, ny=2, width=2.0, height=1.0) + + assert mesh.dx == pytest.approx(0.5) + assert mesh.dy == pytest.approx(0.5) + np.testing.assert_allclose(mesh.x_cell_centers, [0.25, 0.75, 1.25, 1.75]) + np.testing.assert_allclose(mesh.y_cell_centers, [0.25, 0.75]) + np.testing.assert_allclose(mesh.x_face_centers, [0.0, 0.5, 1.0, 1.5, 2.0]) + np.testing.assert_allclose(mesh.y_face_centers, [0.0, 0.5, 1.0]) + + cell_x, cell_y = mesh.cell_center_coordinates + u_x, u_y = mesh.u_face_coordinates + v_x, v_y = mesh.v_face_coordinates + assert cell_x.shape == cell_y.shape == (2, 4) + assert u_x.shape == u_y.shape == (2, 5) + assert v_x.shape == v_y.shape == (3, 4) + assert mesh.cell_area * mesh.nx * mesh.ny == pytest.approx(2.0) + assert mesh.u_face_area == pytest.approx(0.5) + assert mesh.v_face_area == pytest.approx(0.5) + assert mesh.cell_areas.shape == (2, 4) + assert mesh.u_face_areas.shape == (2, 5) + assert mesh.v_face_areas.shape == (3, 4) + + +def test_boundary_face_indices_and_normals() -> None: + mesh = CartesianMesh(nx=3, ny=2) + faces = mesh.boundary_face_indices + + np.testing.assert_array_equal(faces["west"][0], [0, 1]) + np.testing.assert_array_equal(faces["west"][1], [0, 0]) + np.testing.assert_array_equal(faces["east"][1], [3, 3]) + np.testing.assert_array_equal(faces["south"][0], [0, 0, 0]) + np.testing.assert_array_equal(faces["north"][0], [2, 2, 2]) + assert dict(mesh.boundary_face_counts) == { + "west": 2, + "east": 2, + "south": 3, + "north": 3, + } + assert set(mesh.boundary_face_normals) == set(BOUNDARY_NAMES) + assert mesh.boundary_face_normals["north"] == (0.0, 1.0) + + +@pytest.mark.parametrize("nx, ny", [(0, 2), (2, 0), (-1, 2)]) +def test_mesh_rejects_non_positive_cell_counts(nx: int, ny: int) -> None: + with pytest.raises(ValueError): + CartesianMesh(nx=nx, ny=ny) + + +@pytest.mark.parametrize("width, height", [(0.0, 1.0), (1.0, -1.0), (float("inf"), 1.0)]) +def test_mesh_rejects_invalid_domain_size(width: float, height: float) -> None: + with pytest.raises(ValueError): + CartesianMesh(nx=2, ny=2, width=width, height=height) + + +def test_mesh_rejects_non_integer_cell_count() -> None: + with pytest.raises(TypeError): + CartesianMesh(nx=2.5, ny=2) # type: ignore[arg-type] \ No newline at end of file diff --git a/Exp_solver_dev_tr/tests/test_momentum.py b/Exp_solver_dev_tr/tests/test_momentum.py new file mode 100644 index 0000000000000..c541fc591d344 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_momentum.py @@ -0,0 +1,173 @@ +import numpy as np +import pytest + +from fvm import ( + BoundaryConditions, + CartesianMesh, + MomentumPredictor, + MovingWall, + NoSlipWall, + ScalarField, + VectorField, +) + + +def _wall_conditions(lid_speed: float = 0.0) -> BoundaryConditions: + conditions = BoundaryConditions() + for side in ("west", "east", "south", "north"): + if side == "north" and lid_speed != 0.0: + conditions.set("velocity", side, MovingWall((lid_speed, 0.0))) + else: + conditions.set("velocity", side, NoSlipWall()) + return conditions + + +def test_sparse_component_matrices_have_expected_stencil_coefficients() -> None: + mesh = CartesianMesh(nx=3, ny=2, width=3.0, height=2.0) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + predictor = MomentumPredictor(density=2.0, viscosity=1.0, time_step=0.5) + + assembly = predictor.assemble(velocity, pressure, _wall_conditions()) + + assert assembly.u_unknown_shape == (2, 2) + assert assembly.v_unknown_shape == (1, 3) + assert assembly.u_matrix.shape == (4, 4) + assert assembly.v_matrix.shape == (3, 3) + assert assembly.u_matrix[0, 0] == pytest.approx(9.0) + assert assembly.u_matrix[0, 1] == pytest.approx(-1.0) + assert assembly.u_matrix[0, 2] == pytest.approx(-1.0) + assert assembly.v_matrix[0, 0] == pytest.approx(9.0) + assert assembly.v_matrix[0, 1] == pytest.approx(-1.0) + assert np.all(assembly.u_rhs == 0.0) + assert np.all(assembly.v_rhs == 0.0) + + +def test_stationary_cavity_predictor_preserves_zero_flow() -> None: + mesh = CartesianMesh(nx=4, ny=3) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + predictor = MomentumPredictor(density=1.0, viscosity=0.01, time_step=0.1) + + prediction = predictor.predict(velocity, pressure, _wall_conditions()) + + assert np.count_nonzero(prediction.velocity.u.values) == 0 + assert np.count_nonzero(prediction.velocity.v.values) == 0 + assert prediction.u_relative_residual < 1e-14 + assert prediction.v_relative_residual < 1e-14 + + +def test_pressure_gradient_is_an_explicit_momentum_source() -> None: + mesh = CartesianMesh(nx=4, ny=3) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + x, _ = mesh.cell_center_coordinates + pressure.set_values(x) + density = 2.0 + time_step = 0.1 + predictor = MomentumPredictor(density, viscosity=0.0, time_step=time_step) + + assembly = predictor.assemble(velocity, pressure, _wall_conditions()) + prediction = predictor.solve(assembly) + + np.testing.assert_allclose(assembly.u_pressure_gradient, 1.0) + np.testing.assert_allclose(assembly.u_rhs, -1.0) + np.testing.assert_allclose( + prediction.velocity.u.values[:, 1:-1], -time_step / density + ) + assert np.count_nonzero(prediction.velocity.v.values) == 0 + + +def test_explicit_upwind_convection_is_included_in_each_rhs() -> None: + mesh = CartesianMesh(nx=4, ny=3) + velocity = VectorField(mesh) + u_values = np.zeros(mesh.shape_for_location("x_face")) + v_values = np.zeros(mesh.shape_for_location("y_face")) + u_values[:, 1:-1] = [ + [0.2, -0.1, 0.3], + [0.1, 0.4, -0.2], + [-0.3, 0.2, 0.1], + ] + v_values[1:-1, :] = [[0.2, -0.1, 0.3, 0.1], [-0.2, 0.3, 0.1, -0.1]] + velocity.set_values(u_values, v_values) + pressure = ScalarField(mesh, name="pressure") + density = 1.5 + time_step = 0.2 + predictor = MomentumPredictor(density, viscosity=0.0, time_step=time_step) + + assembly = predictor.assemble(velocity, pressure, _wall_conditions()) + + assert np.any(assembly.u_convection != 0.0) + assert np.any(assembly.v_convection != 0.0) + np.testing.assert_allclose( + assembly.u_rhs.reshape(assembly.u_unknown_shape), + density / time_step * u_values[:, 1:-1] + - density * assembly.u_convection, + ) + np.testing.assert_allclose( + assembly.v_rhs.reshape(assembly.v_unknown_shape), + density / time_step * v_values[1:-1, :] + - density * assembly.v_convection, + ) + + +def test_transient_storage_uses_fixed_time_level_during_nonlinear_iteration() -> None: + mesh = CartesianMesh(nx=4, ny=3) + iterate_velocity = VectorField(mesh) + iterate_velocity.u.values[:, 1:-1] = 0.25 + time_level_velocity = VectorField(mesh) + time_level_velocity.u.values[:, 1:-1] = 0.1 + pressure = ScalarField(mesh, name="pressure") + density = 1.5 + time_step = 0.2 + predictor = MomentumPredictor(density, viscosity=0.0, time_step=time_step) + + assembly = predictor.assemble( + iterate_velocity, + pressure, + _wall_conditions(), + temporal_velocity=time_level_velocity, + ) + + np.testing.assert_allclose( + assembly.u_rhs.reshape(assembly.u_unknown_shape) + + density * assembly.u_convection, + density / time_step * time_level_velocity.u.values[:, 1:-1], + ) + + +def test_moving_lid_enters_implicit_diffusion_without_mutating_inputs() -> None: + mesh = CartesianMesh(nx=4, ny=4) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + initial_u = velocity.u.values.copy() + initial_v = velocity.v.values.copy() + predictor = MomentumPredictor(density=1.0, viscosity=0.1, time_step=0.1) + + prediction = predictor.predict(velocity, pressure, _wall_conditions(lid_speed=1.0)) + + np.testing.assert_array_equal(velocity.u.values, initial_u) + np.testing.assert_array_equal(velocity.v.values, initial_v) + np.testing.assert_array_equal(prediction.velocity.u.values[:, [0, -1]], 0.0) + np.testing.assert_array_equal(prediction.velocity.v.values[[0, -1], :], 0.0) + assert np.all(prediction.velocity.u.values[:, 1:-1] > 0.0) + assert ( + np.mean(prediction.velocity.u.values[-1, 1:-1]) + > np.mean(prediction.velocity.u.values[0, 1:-1]) + ) + + +def test_predictor_rejects_missing_boundaries_and_invalid_properties() -> None: + mesh = CartesianMesh(nx=3, ny=3) + predictor = MomentumPredictor(density=1.0, viscosity=0.0, time_step=0.1) + + with pytest.raises(ValueError, match="missing velocity boundary"): + predictor.assemble( + VectorField(mesh), ScalarField(mesh, name="pressure"), BoundaryConditions() + ) + with pytest.raises(ValueError, match="density"): + MomentumPredictor(density=0.0, viscosity=0.01, time_step=0.1) + with pytest.raises(ValueError, match="viscosity"): + MomentumPredictor(density=1.0, viscosity=-0.01, time_step=0.1) + with pytest.raises(ValueError, match="time_step"): + MomentumPredictor(density=1.0, viscosity=0.01, time_step=0.0) diff --git a/Exp_solver_dev_tr/tests/test_operators.py b/Exp_solver_dev_tr/tests/test_operators.py new file mode 100644 index 0000000000000..e1df56ead348e --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_operators.py @@ -0,0 +1,183 @@ +import numpy as np +import pytest + +from fvm import ( + CartesianMesh, + ScalarField, + VectorField, + convection_operator, + convective_fluxes, + diffusion_operator, + diffusive_fluxes, + divergence, + face_gradient, + interpolate_to_faces, +) + + +def _linear_boundary_values(mesh: CartesianMesh) -> dict[str, np.ndarray]: + return { + "west": 3.0 * mesh.y_cell_centers, + "east": 2.0 * mesh.width + 3.0 * mesh.y_cell_centers, + "south": 2.0 * mesh.x_cell_centers, + "north": 2.0 * mesh.x_cell_centers + 3.0 * mesh.height, + } + + +def _quadratic_boundary_values(mesh: CartesianMesh) -> dict[str, np.ndarray]: + x = mesh.x_cell_centers + y = mesh.y_cell_centers + return { + "west": y**2, + "east": mesh.width**2 + y**2, + "south": x**2, + "north": x**2 + mesh.height**2, + } + + +def test_interpolation_is_exact_for_a_linear_field_with_face_values() -> None: + mesh = CartesianMesh(nx=5, ny=3, width=2.0, height=1.5) + x, y = mesh.cell_center_coordinates + field = ScalarField(mesh, name="linear") + field.set_values(2.0 * x + 3.0 * y) + + face_x, face_y = interpolate_to_faces(field, _linear_boundary_values(mesh)) + u_x, u_y = mesh.u_face_coordinates + v_x, v_y = mesh.v_face_coordinates + + np.testing.assert_allclose(face_x, 2.0 * u_x + 3.0 * u_y) + np.testing.assert_allclose(face_y, 2.0 * v_x + 3.0 * v_y) + + +def test_interpolation_defaults_to_nearest_cell_at_boundaries() -> None: + field = ScalarField(CartesianMesh(nx=2, ny=2), name="field") + field.set_values([[1.0, 3.0], [5.0, 7.0]]) + + face_x, face_y = interpolate_to_faces(field) + + np.testing.assert_allclose(face_x[:, 0], [1.0, 5.0]) + np.testing.assert_allclose(face_x[:, -1], [3.0, 7.0]) + np.testing.assert_allclose(face_x[:, 1], [2.0, 6.0]) + np.testing.assert_allclose(face_y[0, :], [1.0, 3.0]) + np.testing.assert_allclose(face_y[-1, :], [5.0, 7.0]) + + +def test_face_gradient_matches_linear_field_and_zero_gradient_defaults() -> None: + mesh = CartesianMesh(nx=4, ny=3, width=2.0, height=1.5) + x, y = mesh.cell_center_coordinates + field = ScalarField(mesh, name="linear") + field.set_values(2.0 * x + 3.0 * y) + + gradient_x, gradient_y = face_gradient(field, _linear_boundary_values(mesh)) + np.testing.assert_allclose(gradient_x, 2.0) + np.testing.assert_allclose(gradient_y, 3.0) + + neumann_x, neumann_y = face_gradient(field) + assert np.all(neumann_x[:, 0] == 0.0) + assert np.all(neumann_x[:, -1] == 0.0) + assert np.all(neumann_y[0, :] == 0.0) + assert np.all(neumann_y[-1, :] == 0.0) + + +def test_velocity_divergence_is_exact_for_linear_face_velocity() -> None: + mesh = CartesianMesh(nx=5, ny=3, width=2.0, height=1.5) + velocity = VectorField(mesh) + u_x, _ = mesh.u_face_coordinates + _, v_y = mesh.v_face_coordinates + velocity.set_values(u_x, v_y) + + np.testing.assert_allclose(divergence(velocity), 2.0) + + +def test_quadratic_diffusion_operator_returns_analytic_laplacian() -> None: + mesh = CartesianMesh(nx=7, ny=4, width=2.0, height=1.5) + x, y = mesh.cell_center_coordinates + field = ScalarField(mesh, name="quadratic") + field.set_values(x**2 + y**2) + + actual = diffusion_operator(field, boundary_values=_quadratic_boundary_values(mesh)) + + np.testing.assert_allclose(actual, 4.0, atol=1e-12) + + +def test_diffusive_fluxes_apply_diffusivity_and_zero_flux_boundaries() -> None: + mesh = CartesianMesh(nx=3, ny=2) + x, y = mesh.cell_center_coordinates + field = ScalarField(mesh, name="linear") + field.set_values(2.0 * x + 3.0 * y) + + flux_x, flux_y = diffusive_fluxes(field, diffusivity=0.5) + + np.testing.assert_allclose(flux_x[:, 1:-1], 1.0) + np.testing.assert_allclose(flux_y[1:-1, :], 1.5) + assert np.all(flux_x[:, (0, -1)] == 0.0) + assert np.all(flux_y[(0, -1), :] == 0.0) + + +def test_diffusion_operator_is_second_order_under_grid_refinement() -> None: + def rms_error(cells: int) -> float: + mesh = CartesianMesh(nx=cells, ny=cells) + x, y = mesh.cell_center_coordinates + field = ScalarField(mesh, name="manufactured") + exact = np.sin(np.pi * x) * np.sin(np.pi * y) + field.set_values(exact) + numerical = diffusion_operator( + field, + boundary_values={side: 0.0 for side in ("west", "east", "south", "north")}, + ) + analytical = -2.0 * np.pi**2 * exact + return float(np.sqrt(np.mean((numerical - analytical) ** 2))) + + coarse_error = rms_error(32) + fine_error = rms_error(64) + + assert coarse_error / fine_error > 3.5 + + +@pytest.mark.parametrize("scheme", ["central", "upwind"]) +def test_constant_scalar_convection_matches_scalar_times_divergence(scheme: str) -> None: + mesh = CartesianMesh(nx=4, ny=3, width=2.0, height=1.5) + scalar = ScalarField(mesh, name="constant", initial_value=2.0) + velocity = VectorField(mesh) + u_x, _ = mesh.u_face_coordinates + _, v_y = mesh.v_face_coordinates + velocity.set_values(u_x, v_y) + boundary_values = {side: 2.0 for side in ("west", "east", "south", "north")} + + actual = convection_operator(scalar, velocity, scheme, boundary_values) + + np.testing.assert_allclose(actual, 2.0 * divergence(velocity)) + + +def test_upwind_flux_uses_upstream_cell_and_inflow_boundary_value() -> None: + mesh = CartesianMesh(nx=2, ny=1) + scalar = ScalarField(mesh, name="scalar") + scalar.set_values([[1.0, 3.0]]) + velocity = VectorField(mesh) + velocity.set_values([[2.0, 2.0, 2.0]], [[0.0, 0.0], [0.0, 0.0]]) + + flux_x, _ = convective_fluxes( + scalar, + velocity, + scheme="upwind", + boundary_values={"west": 5.0}, + ) + + np.testing.assert_allclose(flux_x, [[10.0, 2.0, 6.0]]) + + +def test_operators_reject_invalid_meshes_boundaries_and_schemes() -> None: + mesh = CartesianMesh(nx=2, ny=2) + field = ScalarField(mesh, name="scalar") + velocity = VectorField(mesh) + + with pytest.raises(ValueError, match="same mesh"): + convection_operator(field, VectorField(CartesianMesh(nx=3, ny=2))) + with pytest.raises(ValueError, match="boundary values must be scalar or have shape"): + interpolate_to_faces(field, {"west": [1.0, 2.0, 3.0]}) + with pytest.raises(ValueError, match="unknown boundary"): + face_gradient(field, {"top": 0.0}) + with pytest.raises(ValueError, match="scheme"): + convective_fluxes(field, velocity, scheme="central-upwind") # type: ignore[arg-type] + with pytest.raises(ValueError, match="diffusivity"): + diffusion_operator(field, diffusivity=-1.0) diff --git a/Exp_solver_dev_tr/tests/test_postprocessing.py b/Exp_solver_dev_tr/tests/test_postprocessing.py new file mode 100644 index 0000000000000..bd8f889b0223c --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_postprocessing.py @@ -0,0 +1,192 @@ +import json + +import matplotlib +import numpy as np +import pytest + +matplotlib.use("Agg") + +from fvm import ( + BoundaryConditions, + CartesianMesh, + MovingWall, + NoSlipWall, + ScalarField, + TransientSolver, + VectorField, + centerline_profiles, + compare_ghia_re100, + export_ghia_comparison, + export_simulation_result, + plot_cavity_fields, + plot_convergence_history, + plot_ghia_comparison, + plot_mesh_and_boundaries, + run_lid_driven_grid_study, + velocity_extrema, + write_grid_study_csv, +) + + +def _conditions(lid_speed: float = 1.0) -> BoundaryConditions: + conditions = BoundaryConditions() + for side in ("west", "east", "south", "north"): + if side == "north": + conditions.set("velocity", side, MovingWall((lid_speed, 0.0))) + else: + conditions.set("velocity", side, NoSlipWall()) + return conditions + + +def _run_cavity(cells: int, max_steps: int = 2): + mesh = CartesianMesh(nx=cells, ny=cells) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=max_steps, + velocity_tolerance=1e-14, + ) + return solver.run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + _conditions(), + ) + + +def test_centerline_extraction_interpolates_mac_fields_to_exact_lines() -> None: + mesh = CartesianMesh(nx=6, ny=4, width=2.0, height=1.0) + velocity = VectorField(mesh) + u_values = np.broadcast_to(3.0 * mesh.y_cell_centers[:, None], (mesh.ny, mesh.nx + 1)) + v_values = np.broadcast_to(2.0 * mesh.x_cell_centers[None, :], (mesh.ny + 1, mesh.nx)) + velocity.set_values(u_values, v_values) + + profiles = centerline_profiles(velocity) + + np.testing.assert_allclose(profiles.u_y, mesh.y_cell_centers) + np.testing.assert_allclose(profiles.u, 3.0 * mesh.y_cell_centers) + np.testing.assert_allclose(profiles.v_x, mesh.x_cell_centers) + np.testing.assert_allclose(profiles.v, 2.0 * mesh.x_cell_centers) + + +def test_ghia_comparison_excludes_wall_endpoints_and_marks_uncapped_status() -> None: + simulation = _run_cavity(cells=16, max_steps=1) + + comparison = compare_ghia_re100(simulation) + + assert not comparison.benchmark_valid + assert len(comparison.u_coordinate) == 14 + assert len(comparison.v_coordinate) == 15 + assert np.all((comparison.u_coordinate > 0.0) & (comparison.u_coordinate < 1.0)) + assert np.all((comparison.v_coordinate > 0.0) & (comparison.v_coordinate < 1.0)) + assert np.isfinite(comparison.u_rms_error) + assert np.isfinite(comparison.v_rms_error) + + +def test_velocity_extrema_include_component_and_speed_locations() -> None: + mesh = CartesianMesh(nx=3, ny=2, width=2.0, height=1.0) + velocity = VectorField(mesh) + u_values = np.zeros(mesh.shape_for_location("x_face")) + v_values = np.zeros(mesh.shape_for_location("y_face")) + u_values[0, 0] = -2.0 + u_values[-1, -1] = 3.0 + v_values[0, 0] = -4.0 + v_values[-1, -1] = 5.0 + velocity.set_values(u_values, v_values) + + extrema = velocity_extrema(velocity) + + assert extrema.u.minimum == -2.0 + assert extrema.u.maximum == 3.0 + assert extrema.v.minimum == -4.0 + assert extrema.v.maximum == 5.0 + assert extrema.maximum_speed > 0.0 + assert len(extrema.maximum_speed_location) == 2 + + +def test_simulation_export_contains_fields_settings_and_history(tmp_path) -> None: + simulation = _run_cavity(cells=4, max_steps=1) + + output = export_simulation_result(simulation, tmp_path / "run") + + with np.load(output / "fields.npz") as fields: + assert fields["pressure"].shape == (4, 4) + assert fields["u_faces"].shape == (4, 5) + assert fields["v_faces"].shape == (5, 4) + metadata = json.loads((output / "metadata.json").read_text(encoding="utf-8")) + assert metadata["settings"]["density"] == 1.0 + assert metadata["steps"] == 1 + assert (output / "history.csv").read_text(encoding="utf-8").count("\n") == 2 + + +def test_matplotlib_plots_save_field_profile_and_history_figures(tmp_path) -> None: + simulation = _run_cavity(cells=16, max_steps=1) + comparison = compare_ghia_re100(simulation) + + field_figure = plot_cavity_fields(simulation, tmp_path / "fields.png") + profile_figure = plot_ghia_comparison(comparison, tmp_path / "profiles.png") + history_figure = plot_convergence_history(simulation, tmp_path / "history.png") + + assert len(field_figure.axes) >= 3 + assert len(profile_figure.axes) == 2 + assert len(history_figure.axes) == 1 + assert all((tmp_path / name).stat().st_size > 1000 for name in ( + "fields.png", "profiles.png", "history.png" + )) + + +def test_geometry_plot_shows_mesh_and_moving_wall(tmp_path) -> None: + mesh = CartesianMesh(nx=4, ny=4) + + figure = plot_mesh_and_boundaries( + mesh, + _conditions(), + tmp_path / "geometry.png", + ) + + assert len(figure.axes) == 1 + assert (tmp_path / "geometry.png").stat().st_size > 1000 + + +def test_grid_study_records_nonconvergence_and_writes_csv(tmp_path) -> None: + rows = run_lid_driven_grid_study( + grid_sizes=(16,), + max_steps=1, + velocity_tolerance=1e-14, + ) + + assert len(rows) == 1 + assert rows[0].cells_per_side == 16 + assert not rows[0].benchmark_valid + assert np.isfinite(rows[0].u_rms_error) + output = write_grid_study_csv(rows, tmp_path / "study.csv") + assert "cells_per_side" in output.read_text(encoding="utf-8") + + +def test_ghia_comparison_rejects_non_square_domain() -> None: + mesh = CartesianMesh(nx=16, ny=16, width=2.0, height=1.0) + solver = TransientSolver(1.0, 0.01, max_time_step=0.001, max_steps=1) + result = solver.run(VectorField(mesh), ScalarField(mesh, "pressure"), _conditions()) + + with pytest.raises(ValueError, match="square domain"): + compare_ghia_re100(result) + + +def test_ghia_comparison_rejects_a_non_re100_run() -> None: + mesh = CartesianMesh(nx=16, ny=16) + solver = TransientSolver(1.0, 0.02, max_time_step=0.001, max_steps=1) + result = solver.run(VectorField(mesh), ScalarField(mesh, "pressure"), _conditions()) + + with pytest.raises(ValueError, match="requires Reynolds number 100"): + compare_ghia_re100(result) + + +def test_ghia_report_exports_comparison_eligibility(tmp_path) -> None: + comparison = compare_ghia_re100(_run_cavity(cells=16, max_steps=1)) + + report_path = export_ghia_comparison(comparison, tmp_path / "ghia.json") + + report = json.loads(report_path.read_text(encoding="utf-8")) + assert report["benchmark"] == "Ghia et al. lid-driven cavity Re=100" + assert report["benchmark_valid"] is False + assert len(report["u_profile"]) == 14 \ No newline at end of file diff --git a/Exp_solver_dev_tr/tests/test_pressure_correction.py b/Exp_solver_dev_tr/tests/test_pressure_correction.py new file mode 100644 index 0000000000000..99e7d4f5c6a3a --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_pressure_correction.py @@ -0,0 +1,101 @@ +import numpy as np +import pytest + +from fvm import ( + CartesianMesh, + PressureCorrectionSolver, + VectorField, +) + + +def test_neumann_matrix_has_expected_coefficients_and_reference_row() -> None: + mesh = CartesianMesh(nx=3, ny=2, width=2.0, height=1.0) + velocity = VectorField(mesh) + solver = PressureCorrectionSolver(density=1.0, time_step=0.1) + + assembly = solver.assemble(velocity) + + assert assembly.matrix.shape == (6, 6) + assert assembly.matrix[0, 0] == pytest.approx(1.0) + assert np.count_nonzero(assembly.matrix.getrow(0).toarray()) == 1 + assert assembly.matrix[1, 1] == pytest.approx(8.5) + assert assembly.matrix[1, 0] == pytest.approx(-2.25) + assert assembly.matrix[1, 2] == pytest.approx(-2.25) + assert assembly.matrix[1, 4] == pytest.approx(-4.0) + assert np.all(assembly.rhs == 0.0) + + +def test_solver_recovers_known_discrete_pressure_correction() -> None: + mesh = CartesianMesh(nx=5, ny=4, width=2.0, height=1.5) + density = 1.7 + time_step = 0.025 + known = np.arange(mesh.nx * mesh.ny, dtype=np.float64).reshape(mesh.ny, mesh.nx) + velocity = VectorField(mesh) + u_values = np.zeros(mesh.shape_for_location("x_face")) + v_values = np.zeros(mesh.shape_for_location("y_face")) + u_values[:, 1:-1] = ( + time_step / density * np.diff(known, axis=1) / mesh.dx + ) + v_values[1:-1, :] = ( + time_step / density * np.diff(known, axis=0) / mesh.dy + ) + velocity.set_values(u_values, v_values) + solver = PressureCorrectionSolver( + density=density, + time_step=time_step, + reference_cell=(1, 2), + ) + + result = solver.predict(velocity) + + np.testing.assert_allclose( + result.correction.values, + known - known[1, 2], + atol=1e-12, + ) + assert result.correction.values[1, 2] == 0.0 + assert result.net_boundary_flux == pytest.approx(0.0) + assert result.relative_residual < 1e-12 + + +def test_solver_rejects_nonzero_net_boundary_flux() -> None: + mesh = CartesianMesh(nx=3, ny=2) + velocity = VectorField(mesh) + u_values = np.zeros(mesh.shape_for_location("x_face")) + u_values[:, -1] = 1.0 + velocity.set_values(u_values, np.zeros(mesh.shape_for_location("y_face"))) + solver = PressureCorrectionSolver(density=1.0, time_step=0.1) + + with pytest.raises(ValueError, match="incompatible net boundary flux"): + solver.assemble(velocity) + + +def test_solver_does_not_modify_predicted_velocity() -> None: + mesh = CartesianMesh(nx=3, ny=3) + velocity = VectorField(mesh) + u_values = np.zeros(mesh.shape_for_location("x_face")) + v_values = np.zeros(mesh.shape_for_location("y_face")) + u_values[1, 1] = 0.5 + u_values[1, 2] = 0.5 + v_values[1, 1] = 0.25 + v_values[2, 1] = 0.25 + velocity.set_values(u_values, v_values) + before_u = velocity.u.values.copy() + before_v = velocity.v.values.copy() + solver = PressureCorrectionSolver(density=1.0, time_step=0.1) + + solver.predict(velocity) + + np.testing.assert_array_equal(velocity.u.values, before_u) + np.testing.assert_array_equal(velocity.v.values, before_v) + + +@pytest.mark.parametrize("reference_cell", [(-1, 0), (0, 3)]) +def test_solver_rejects_reference_outside_mesh(reference_cell: tuple[int, int]) -> None: + velocity = VectorField(CartesianMesh(nx=3, ny=2)) + solver = PressureCorrectionSolver( + density=1.0, time_step=0.1, reference_cell=reference_cell + ) + + with pytest.raises(ValueError, match="outside the mesh"): + solver.assemble(velocity) diff --git a/Exp_solver_dev_tr/tests/test_projection.py b/Exp_solver_dev_tr/tests/test_projection.py new file mode 100644 index 0000000000000..ebdb005dc3162 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_projection.py @@ -0,0 +1,103 @@ +import numpy as np +import pytest + +from fvm import ( + BoundaryConditions, + CartesianMesh, + MomentumPredictor, + MovingWall, + NoSlipWall, + PressureCorrectionSolver, + ProjectionCorrector, + ScalarField, + VectorField, +) + + +def _cavity_conditions(lid_speed: float = 0.0) -> BoundaryConditions: + conditions = BoundaryConditions() + for side in ("west", "east", "south", "north"): + if side == "north" and lid_speed != 0.0: + conditions.set("velocity", side, MovingWall((lid_speed, 0.0))) + else: + conditions.set("velocity", side, NoSlipWall()) + return conditions + + +def test_projection_recovers_zero_divergence_from_discrete_gradient() -> None: + mesh = CartesianMesh(nx=5, ny=4, width=2.0, height=1.5) + density = 1.7 + time_step = 0.025 + known_correction = np.arange(mesh.nx * mesh.ny, dtype=np.float64).reshape( + mesh.ny, mesh.nx + ) + predicted = VectorField(mesh) + u_values = np.zeros(mesh.shape_for_location("x_face")) + v_values = np.zeros(mesh.shape_for_location("y_face")) + u_values[:, 1:-1] = ( + time_step / density * np.diff(known_correction, axis=1) / mesh.dx + ) + v_values[1:-1, :] = ( + time_step / density * np.diff(known_correction, axis=0) / mesh.dy + ) + predicted.set_values(u_values, v_values) + initial_pressure = ScalarField(mesh, name="pressure", initial_value=3.0) + old_u = predicted.u.values.copy() + old_v = predicted.v.values.copy() + old_pressure = initial_pressure.values.copy() + pressure_solver = PressureCorrectionSolver(density, time_step, reference_cell=(1, 2)) + pressure_correction = pressure_solver.predict(predicted) + corrector = ProjectionCorrector(density, time_step) + + result = corrector.project(predicted, initial_pressure, pressure_correction) + + np.testing.assert_allclose(result.velocity.u.values, 0.0, atol=1e-12) + np.testing.assert_allclose(result.velocity.v.values, 0.0, atol=1e-12) + np.testing.assert_allclose( + result.pressure.values, + old_pressure + known_correction - known_correction[1, 2], + atol=1e-12, + ) + assert result.max_divergence_before > 0.0 + assert result.max_divergence_after < 1e-12 + assert result.global_mass_imbalance == pytest.approx(0.0, abs=1e-12) + assert result.pressure_solve_residual < 1e-12 + np.testing.assert_array_equal(predicted.u.values, old_u) + np.testing.assert_array_equal(predicted.v.values, old_v) + np.testing.assert_array_equal(initial_pressure.values, old_pressure) + + +def test_lid_cavity_projection_reduces_continuity_and_preserves_wall_fluxes() -> None: + mesh = CartesianMesh(nx=12, ny=12) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + density = 1.0 + time_step = 0.001 + predictor = MomentumPredictor(density, viscosity=0.01, time_step=time_step) + predicted = predictor.predict(velocity, pressure, _cavity_conditions(lid_speed=1.0)) + predicted_u_walls = predicted.velocity.u.values[:, [0, -1]].copy() + predicted_v_walls = predicted.velocity.v.values[[0, -1], :].copy() + pressure_solver = PressureCorrectionSolver(density, time_step) + pressure_correction = pressure_solver.predict(predicted.velocity) + corrector = ProjectionCorrector(density, time_step) + + result = corrector.project(predicted.velocity, pressure, pressure_correction) + + assert result.max_divergence_before > 1e-3 + assert result.max_divergence_after < 1e-11 + assert abs(result.global_mass_imbalance) < 1e-12 + np.testing.assert_array_equal(result.velocity.u.values[:, [0, -1]], predicted_u_walls) + np.testing.assert_array_equal(result.velocity.v.values[[0, -1], :], predicted_v_walls) + np.testing.assert_allclose( + result.pressure.values, + pressure.values + pressure_correction.correction.values, + ) + + +def test_corrector_rejects_fields_on_different_meshes() -> None: + corrector = ProjectionCorrector(density=1.0, time_step=0.1) + velocity = VectorField(CartesianMesh(nx=3, ny=3)) + correction = ScalarField(CartesianMesh(nx=4, ny=3), name="correction") + + with pytest.raises(ValueError, match="same mesh"): + corrector.correct_velocity(velocity, correction) diff --git a/Exp_solver_dev_tr/tests/test_run_externalized_case.py b/Exp_solver_dev_tr/tests/test_run_externalized_case.py new file mode 100644 index 0000000000000..f2db809987d57 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_run_externalized_case.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import pytest + +from examples import run_externalized_case +from fvm.externalization import LiveSnapshotPlotter, SnapshotStore, StepSnapshot + + +def _snapshot(run_id: str, step: int) -> StepSnapshot: + return StepSnapshot( + run_id=run_id, + step=step, + mesh={"nx": 2, "ny": 2, "width": 1.0, "height": 1.0}, + diagnostics={ + "step": step, + "time": step * 0.1, + "velocity_change": 0.01 / step, + "max_divergence_after": 0.001 / step, + }, + x_cell_centers=np.array([0.25, 0.75]), + y_cell_centers=np.array([0.25, 0.75]), + pressure=np.full((2, 2), step, dtype=float), + u_faces=np.full((2, 3), step, dtype=float), + v_faces=np.full((3, 2), -step, dtype=float), + ) + + +def test_live_mode_displays_snapshots_from_externalized_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + run_id = "live-example-test" + snapshot_directory = tmp_path / "sync" / run_id / "snapshots" + snapshot = _snapshot(run_id, 1) + run_result = SimpleNamespace(simulation=SimpleNamespace(steps=1)) + plotters = [] + + class FakeLivePlotter: + def __init__(self) -> None: + self.updates: list[StepSnapshot] = [] + self.finished = False + self.closed = False + self.waits: list[float] = [] + plotters.append(self) + + def update(self, item: StepSnapshot) -> None: + self.updates.append(item) + + def finish(self) -> None: + self.finished = True + + def close(self) -> None: + self.closed = True + + def wait_for_events(self, interval_seconds: float) -> None: + self.waits.append(interval_seconds) + + def persist_snapshot(*args): + current_run_id = args[6] + store = SnapshotStore(snapshot_directory, run_id=current_run_id) + store.write(snapshot) + return run_result, snapshot_directory, current_run_id + + monkeypatch.setattr(run_externalized_case, "_run", persist_snapshot) + monkeypatch.setattr(run_externalized_case, "LiveSnapshotPlotter", FakeLivePlotter) + monkeypatch.setattr(matplotlib, "get_backend", lambda: "QtAgg") + + result, returned_directory, returned_run_id = run_externalized_case._run_live( + {}, + tmp_path, + "sync", + queue_size=8, + poll_interval=0.1, + snapshot_every=10, + run_id=run_id, + ) + + assert result is run_result + assert returned_directory == snapshot_directory + assert returned_run_id == run_id + assert len(plotters) == 1 + assert [item.step for item in plotters[0].updates] == [1] + np.testing.assert_array_equal(plotters[0].updates[0].pressure, snapshot.pressure) + assert plotters[0].finished + assert plotters[0].closed + + +def test_live_snapshot_plotter_updates_one_figure_for_multiple_steps( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(plt, "show", Mock()) + monkeypatch.setattr(plt, "pause", Mock()) + plotter = LiveSnapshotPlotter() + figure = plotter.figure + try: + plotter.update(_snapshot("live-plotter-test", 1)) + plotter.update(_snapshot("live-plotter-test", 2)) + + assert plotter.figure is figure + assert plotter.steps == [1, 2] + assert len(plotter.speed_axis.images) == 1 + assert len(plotter.pressure_axis.images) == 1 + finally: + plotter.close() diff --git a/Exp_solver_dev_tr/tests/test_simulation.py b/Exp_solver_dev_tr/tests/test_simulation.py new file mode 100644 index 0000000000000..6f24f9666ea84 --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_simulation.py @@ -0,0 +1,377 @@ +import numpy as np +import pytest + +from fvm import ( + BoundaryConditions, + CartesianMesh, + MovingWall, + NoSlipWall, + ScalarField, + TransientSolver, + VectorField, +) + + +def _conditions(lid_speed: float = 0.0) -> BoundaryConditions: + conditions = BoundaryConditions() + for side in ("west", "east", "south", "north"): + if side == "north" and lid_speed != 0.0: + conditions.set("velocity", side, MovingWall((lid_speed, 0.0))) + else: + conditions.set("velocity", side, NoSlipWall()) + return conditions + + +def test_stationary_cavity_converges_and_stays_at_rest() -> None: + mesh = CartesianMesh(nx=5, ny=4) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.1, + max_steps=5, + ) + + result = solver.run(velocity, pressure, _conditions()) + + assert result.converged + assert result.termination_reason == "converged" + assert result.steps == 1 + assert result.history[0].velocity_change == 0.0 + assert result.history[0].max_divergence_after == 0.0 + assert result.history[0].time_step == pytest.approx(0.1) + assert np.count_nonzero(result.velocity.u.values) == 0 + assert np.count_nonzero(result.velocity.v.values) == 0 + assert np.count_nonzero(velocity.u.values) == 0 + assert np.count_nonzero(pressure.values) == 0 + + +def test_time_step_estimate_includes_moving_wall_and_cfl_limit() -> None: + mesh = CartesianMesh(nx=10, ny=5, width=2.0, height=1.0) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=1.0, + cfl_limit=0.4, + ) + + time_step = solver.estimate_time_step(VectorField(mesh), _conditions(lid_speed=1.0)) + + assert time_step == pytest.approx(0.08) + + +def test_lid_cavity_runs_to_step_limit_with_cfl_and_continuity_monitored() -> None: + mesh = CartesianMesh(nx=8, ny=8) + velocity = VectorField(mesh) + pressure = ScalarField(mesh, name="pressure") + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.01, + max_steps=3, + cfl_limit=0.35, + velocity_tolerance=1e-14, + ) + + result = solver.run(velocity, pressure, _conditions(lid_speed=1.0)) + + assert not result.converged + assert result.termination_reason == "maximum_steps_reached" + assert result.steps == 3 + assert result.final_time == pytest.approx(sum(item.time_step for item in result.history)) + assert all(item.cfl_number <= 0.35 + 1e-14 for item in result.history) + assert all(item.max_divergence_after < 1e-10 for item in result.history) + assert all(abs(item.global_mass_imbalance) < 1e-12 for item in result.history) + assert all(item.pressure_residual < 1e-10 for item in result.history) + assert any(item.velocity_change > 0.0 for item in result.history) + + +def test_solver_reports_time_step_underflow_instead_of_using_unstable_step() -> None: + mesh = CartesianMesh(nx=10, ny=10) + velocity = VectorField(mesh) + velocity.u.values.fill(100.0) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=1.0, + cfl_limit=0.5, + minimum_time_step=0.1, + ) + + with pytest.raises(RuntimeError, match="below minimum_time_step"): + solver.estimate_time_step(velocity, _conditions()) + + +def test_solver_validates_iteration_and_cfl_configuration() -> None: + with pytest.raises(ValueError, match="max_steps"): + TransientSolver(1.0, 0.01, 0.1, max_steps=0) + with pytest.raises(ValueError, match="cfl_limit"): + TransientSolver(1.0, 0.01, 0.1, cfl_limit=1.1) + with pytest.raises(ValueError, match="minimum_time_step"): + TransientSolver(1.0, 0.01, 0.1, minimum_time_step=0.2) + + +def test_steady_mode_uses_fixed_pseudo_time_and_reports_iterations() -> None: + mesh = CartesianMesh(nx=5, ny=4) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.025, + max_steps=3, + transient=False, + ) + + result = solver.run( + VectorField(mesh), ScalarField(mesh, name="pressure"), _conditions() + ) + + assert result.converged + assert result.final_time is None + assert result.final_pseudo_time == pytest.approx(0.025) + assert result.history[0].time is None + assert result.history[0].pseudo_time == pytest.approx(0.025) + assert result.history[0].time_step == pytest.approx(0.025) + + +def test_steady_mode_caps_fixed_step_once_to_a_safe_cfl_value() -> None: + mesh = CartesianMesh(nx=8, ny=8) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.1, + max_steps=4, + cfl_limit=0.5, + velocity_tolerance=1e-14, + transient=False, + ) + + result = solver.run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + _conditions(lid_speed=1.0), + ) + + assert result.history[0].time_step < solver.max_time_step + assert len(result.history) == 4 + assert all( + item.time_step == pytest.approx(result.history[0].time_step) + for item in result.history + ) + assert all(item.cfl_number <= solver.cfl_limit for item in result.history) + + +def test_finite_transient_converges_each_time_step_before_advancing() -> None: + mesh = CartesianMesh(nx=4, ny=4) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=3, + cfl_limit=0.35, + velocity_tolerance=1e-6, + end_time=0.002, + max_inner_iterations_per_time_step=50, + ) + + result = solver.run( + VectorField(mesh), ScalarField(mesh, name="pressure"), _conditions(lid_speed=1.0) + ) + + assert result.converged + assert result.termination_reason == "final_time_reached" + assert result.final_time == pytest.approx(0.002) + assert [item.time for item in result.history] == pytest.approx([0.001, 0.002]) + assert all(item.inner_iterations > 1 for item in result.history) + assert all(item.cfl_number <= 0.35 + 1e-14 for item in result.history) + + +def test_finite_transient_stops_when_a_physical_step_cannot_converge() -> None: + mesh = CartesianMesh(nx=4, ny=4) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=3, + velocity_tolerance=1e-14, + end_time=0.002, + max_inner_iterations_per_time_step=1, + ) + + result = solver.run( + VectorField(mesh), ScalarField(mesh, name="pressure"), _conditions(lid_speed=1.0) + ) + + assert not result.converged + assert result.termination_reason == "time_step_not_converged" + assert result.steps == 1 + + +def test_step_observer_receives_each_step_without_mutating_solver_state() -> None: + mesh = CartesianMesh(nx=5, ny=5) + solver = TransientSolver( + density=1.0, + viscosity=0.01, + max_time_step=0.001, + max_steps=2, + velocity_tolerance=1e-14, + ) + observed_steps: list[int] = [] + + def observe(diagnostics, velocity_snapshot, pressure_snapshot) -> None: + observed_steps.append(diagnostics.step) + velocity_snapshot.u.values.fill(999.0) + pressure_snapshot.values.fill(999.0) + + result = solver.run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + _conditions(lid_speed=1.0), + step_observer=observe, + ) + + assert observed_steps == [1, 2] + assert np.max(result.velocity.u.values) < 999.0 + assert np.max(result.pressure.values) < 999.0 + + +def test_restart_state_matches_uninterrupted_transient_run() -> None: + mesh = CartesianMesh(nx=5, ny=5) + conditions = _conditions(lid_speed=1.0) + solver_options = { + "density": 1.0, + "viscosity": 0.01, + "max_time_step": 0.001, + "max_steps": 4, + "velocity_tolerance": 1e-14, + } + uninterrupted = TransientSolver(**solver_options).run( + VectorField(mesh), ScalarField(mesh, name="pressure"), conditions + ) + saved_states = [] + TransientSolver(**{**solver_options, "max_steps": 2}).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + state_observer=saved_states.append, + ) + + resumed = TransientSolver(**solver_options).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + restart_state=saved_states[-1], + ) + + assert [item.step for item in resumed.history] == [1, 2, 3, 4] + assert resumed.final_time == pytest.approx(uninterrupted.final_time) + np.testing.assert_array_equal(resumed.velocity.u.values, uninterrupted.velocity.u.values) + np.testing.assert_array_equal(resumed.velocity.v.values, uninterrupted.velocity.v.values) + np.testing.assert_array_equal(resumed.pressure.values, uninterrupted.pressure.values) + assert resumed.history == uninterrupted.history + + +def test_finite_transient_restart_preserves_elapsed_time() -> None: + mesh = CartesianMesh(nx=4, ny=4) + conditions = _conditions(lid_speed=1.0) + options = { + "density": 1.0, + "viscosity": 0.01, + "max_time_step": 0.001, + "max_steps": 4, + "end_time": 0.004, + "max_inner_iterations_per_time_step": 50, + } + uninterrupted = TransientSolver(**options).run( + VectorField(mesh), ScalarField(mesh, name="pressure"), conditions + ) + saved_states = [] + TransientSolver(**{**options, "max_steps": 2}).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + state_observer=saved_states.append, + ) + + resumed = TransientSolver(**options).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + restart_state=saved_states[-1], + ) + + assert saved_states[-1].elapsed_time == pytest.approx(0.002) + assert resumed.final_time == pytest.approx(0.004) + assert resumed.history == uninterrupted.history + np.testing.assert_array_equal(resumed.velocity.u.values, uninterrupted.velocity.u.values) + np.testing.assert_array_equal(resumed.velocity.v.values, uninterrupted.velocity.v.values) + np.testing.assert_array_equal(resumed.pressure.values, uninterrupted.pressure.values) + + +def test_restart_at_finite_transient_end_time_reports_completion() -> None: + mesh = CartesianMesh(nx=4, ny=4) + conditions = _conditions(lid_speed=1.0) + options = { + "density": 1.0, + "viscosity": 0.01, + "max_time_step": 0.001, + "max_steps": 4, + "end_time": 0.002, + "max_inner_iterations_per_time_step": 50, + } + saved_states = [] + original = TransientSolver(**options).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + state_observer=saved_states.append, + ) + + restarted = TransientSolver(**options).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + restart_state=saved_states[-1], + ) + + assert original.converged + assert restarted.converged + assert restarted.termination_reason == "final_time_reached" + assert restarted.history == original.history + + +def test_steady_restart_reuses_selected_pseudo_time_step() -> None: + mesh = CartesianMesh(nx=5, ny=5) + conditions = _conditions(lid_speed=1.0) + options = { + "density": 1.0, + "viscosity": 0.01, + "max_time_step": 0.1, + "max_steps": 4, + "velocity_tolerance": 1e-14, + "transient": False, + } + uninterrupted = TransientSolver(**options).run( + VectorField(mesh), ScalarField(mesh, name="pressure"), conditions + ) + saved_states = [] + TransientSolver(**{**options, "max_steps": 2}).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + state_observer=saved_states.append, + ) + + resumed = TransientSolver(**options).run( + VectorField(mesh), + ScalarField(mesh, name="pressure"), + conditions, + restart_state=saved_states[-1], + ) + + assert saved_states[-1].steady_time_step == pytest.approx( + uninterrupted.history[0].time_step + ) + assert resumed.history == uninterrupted.history + np.testing.assert_array_equal(resumed.velocity.u.values, uninterrupted.velocity.u.values) + np.testing.assert_array_equal(resumed.pressure.values, uninterrupted.pressure.values) diff --git a/Exp_solver_dev_tr/tests/test_user_workflow.py b/Exp_solver_dev_tr/tests/test_user_workflow.py new file mode 100644 index 0000000000000..3ed43e799f9cd --- /dev/null +++ b/Exp_solver_dev_tr/tests/test_user_workflow.py @@ -0,0 +1,102 @@ +import subprocess +import sys +from pathlib import Path +from runpy import run_path +from types import SimpleNamespace + +import pytest + + +@pytest.mark.parametrize( + ("arguments", "expected_mode"), + [([], "save"), (["--mode", "save"], "save"), (["--mode", "live"], "live"), (["--live"], "live")], +) +def test_user_command_selects_save_and_live_modes(arguments, expected_mode) -> None: + script_path = Path(__file__).parents[1] / "examples" / "run_user_case.py" + workflow = run_path(str(script_path)) + parser = workflow["build_argument_parser"]() + + assert parser.parse_args(arguments).mode == expected_mode + + +def test_user_command_defaults_to_the_steady_cavity_case() -> None: + script_path = Path(__file__).parents[1] / "examples" / "run_user_case.py" + workflow = run_path(str(script_path)) + arguments = workflow["build_argument_parser"]().parse_args([]) + + assert arguments.case.name == "lid_driven_cavity_re100_steady.json" + + +def test_user_command_parses_checkpoint_and_restart_options() -> None: + script_path = Path(__file__).parents[1] / "examples" / "run_user_case.py" + workflow = run_path(str(script_path)) + arguments = workflow["build_argument_parser"]().parse_args( + [ + "--checkpoint-every", + "100", + "--retain-checkpoints", + "3", + "--restart", + "latest", + ] + ) + + assert arguments.checkpoint_every == 100 + assert arguments.retain_checkpoints == 3 + assert arguments.restart == "latest" + + +def test_live_plot_history_starts_with_restored_checkpoint_history() -> None: + script_path = Path(__file__).parents[1] / "examples" / "run_user_case.py" + workflow = run_path(str(script_path)) + history = ( + SimpleNamespace(step=20, velocity_change=0.25, max_divergence_after=0.02), + SimpleNamespace(step=40, velocity_change=0.1, max_divergence_after=0.01), + ) + + steps, velocity_changes, divergences = workflow["_history_plot_values"](history) + + assert steps == [20, 40] + assert velocity_changes == [0.25, 0.1] + assert divergences == [0.02, 0.01] + + +def test_run_user_case_exports_expected_artifacts(tmp_path: Path) -> None: + repo_root = Path(__file__).parents[1] + script_path = repo_root / "examples" / "run_user_case.py" + case_path = repo_root / "cases" / "lid_driven_cavity_re100_workflow.json" + output_dir = tmp_path / "workflow_output" + + result = subprocess.run( + [ + sys.executable, + str(script_path), + "--case", + str(case_path), + "--output", + str(output_dir), + "--mode", + "save", + ], + capture_output=True, + text=True, + cwd=repo_root, + check=False, + ) + + assert result.returncode == 0, result.stdout + result.stderr + assert "Status: converged" in result.stdout + assert output_dir.exists() + for expected_file in ( + "case.json", + "summary.json", + "fields.npz", + "metadata.json", + "history.csv", + "ghia_re100.json", + "geometry.png", + "cavity_fields.png", + "ghia_profiles.png", + "convergence_history.png", + ): + assert (output_dir / expected_file).exists() \ No newline at end of file