From 54daaa50a474e177f293c2ef308ae9fbbc08c244 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 03:05:32 +0900 Subject: [PATCH 01/19] build(windows): link the core-linked C tests through IFX in the static release With CABLEDYN_STATIC_WINDOWS_RELEASE the core archive holds /Qipo objects, which only an IFX link reads. test_c_api_raw_small_dt and test_memory_growth link cabledyn_core from a C main, so CMake linked them with link.exe, which reported every CableDyn_* symbol unresolved (LNK2019, LNK1120) and stopped a full build of the test suite with the release flags (Intel ifx 2025.3.2). They now take LINKER_LANGUAGE Fortran in that configuration, as test_lapack_guard_pages does everywhere. Other builds are unchanged. Pre-existing on dev (6195432); not specific to a feature branch. Signed-off-by: Jae Hoon Seo --- CMakeLists.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 84066a67..770c9279 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1419,6 +1419,12 @@ if(NOT WIN32) endif() # Growth bounds [MiB]: observed 0.0 MiB over 20000 C-API steps and 0.11 MiB over 1000 # aggregate steps; 2 MiB leaves room for allocator page granularity. +if(CABLEDYN_STATIC_WINDOWS_RELEASE) + # The static IFX core archive holds /Qipo objects, which only an IFX link reads (link.exe, + # the C linker, reports every CableDyn_* symbol unresolved): the C tests that link the core + # directly link through IFX there. + set_target_properties(test_c_api_raw_small_dt test_memory_growth PROPERTIES LINKER_LANGUAGE Fortran) +endif() add_test(NAME memory_growth COMMAND test_memory_growth 2 ${CMAKE_CURRENT_SOURCE_DIR}/examples/spread_3line_chain.dat 20000) set_tests_properties(memory_growth PROPERTIES LABELS "c;capi;dynamic;memory" SKIP_RETURN_CODE 77) From 4c1aadc54feb18715a95a65ed4022f81ec49cc59 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 04:23:47 +0900 Subject: [PATCH 02/19] fix(deck): a number beyond the range of the kind is not finite on every compiler real_token_defect read a token spelled as a decimal number and judged the value; a READ error made it give up, leaving the token to its row reader. The GNU run-time reads a magnitude beyond HUGE (1e309) as Inf, which is then named "not a finite number"; the Intel run-time stops the READ with a conversion error, so an Intel build named the same deck "malformed POINTS row" or "wave row value ... is not a number". A token of numeric shape that does not read is now REAL_NONFINITE, the GNU verdict. test_deck_reader_io failed 2 checks under Intel ifx 2025.3.2 (with /fp:precise); gfortran is unchanged. Pre-existing on dev (6195432). Signed-off-by: Jae Hoon Seo --- src/CableDyn_DeckDriver.f90 | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index d914afda..731aea62 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -39840,7 +39840,9 @@ END FUNCTION real_defect_text INTEGER FUNCTION real_token_defect(tok) RESULT(k) !! real_value_defect of a token that reads whole as a real number; REAL_OK for a token - !! that is not a number at all (a name), which its own reader then judges. + !! that is not a number at all (a name), which its own reader then judges. A token spelled + !! as a number that the READ refuses is a magnitude beyond the range of the kind: gfortran + !! reads one beyond HUGE as Inf, the Intel run-time stops the READ with a conversion error. CHARACTER(*), INTENT(IN) :: tok REAL(wp) :: x INTEGER :: ios @@ -39848,7 +39850,10 @@ INTEGER FUNCTION real_token_defect(tok) RESULT(k) IF (LEN_TRIM(tok) == 0) RETURN IF (.NOT. numeric_token_shape(tok)) RETURN READ (tok, *, IOSTAT=ios) x - IF (ios /= 0) RETURN + IF (ios /= 0) THEN + k = REAL_NONFINITE + RETURN + END IF k = real_value_defect(x) END FUNCTION real_token_defect From d6c93333fc274669eaaec41a4a50a60df2a647b7 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 04:49:52 +0900 Subject: [PATCH 03/19] fix(io): find a missing input file by INQUIRE before the OPEN CD_Open_Input learnt that a deck or table was missing from a failing OPEN(STATUS='OLD'). For a name longer than the Windows path limit, CD_Native_Path hands the run-time an extended-length (\\?\) spelling, and the Intel Fortran run-time of ifx 2025.3.2 ends the process with STATUS_STACK_BUFFER_OVERRUN (0xC0000409) when such an OPEN of about 600 characters or more fails: it overruns a buffer while it formats the error. A twenty-line program reproduces it (OPEN of "\\?\D:\missing_<580 d>.dat" stops the process; 560 returns IOSTAT 43; INQUIRE of the same names returns). The Windows wheel's DLL and the release driver crashed on a missing deck of 1100 characters (python/tests/test_native_model.py:: test_long_failure_message_is_kept_whole took the whole python_package test down). An INQUIRE now finds the missing file first; the message is unchanged ("... (file not found)") and gfortran behaves as before. A compiler run-time bug; pre-existing on dev (6195432). Other OPENs of extended-length names that fail (outputs in a folder that does not exist) take the same run-time path and are not covered here. Signed-off-by: Jae Hoon Seo --- src/CableDyn_PathIO.f90 | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/CableDyn_PathIO.f90 b/src/CableDyn_PathIO.f90 index 9b16ceb1..5958270d 100644 --- a/src/CableDyn_PathIO.f90 +++ b/src/CableDyn_PathIO.f90 @@ -160,7 +160,8 @@ SUBROUTINE CD_Open_Input(unit, path, ios, reason) CHARACTER(*), INTENT(IN) :: path CHARACTER(*), INTENT(OUT) :: reason CHARACTER(:), ALLOCATABLE :: native - INTEGER :: stat + INTEGER :: stat, iq + LOGICAL :: exists unit = -1 CALL CD_Native_Path(path, native, stat, reason) @@ -168,6 +169,16 @@ SUBROUTINE CD_Open_Input(unit, path, ios, reason) ios = 1 RETURN END IF + ! A missing file is found by INQUIRE, not by a failing OPEN: the Intel Fortran run-time + ! (ifx 2025.3) ends the process with a stack buffer overrun when an OPEN of an + ! extended-length (\\?\) name of about 600 characters or more fails, as it formats the + ! error; INQUIRE of the same name returns. + exists = .TRUE. + INQUIRE (FILE=native, EXIST=exists, IOSTAT=iq) + IF (iq == 0 .AND. .NOT. exists) THEN + ios = 1 + RETURN + END IF OPEN (NEWUNIT=unit, FILE=native, STATUS='OLD', ACTION='READ', IOSTAT=ios) END SUBROUTINE CD_Open_Input From 8c266d5ff9d96a598a437ef0ea977ac121bcf1ff Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 06:02:08 +0900 Subject: [PATCH 04/19] build: automatic local variables with every compiler and OpenMP setting Separate C API handles (and Python objects) may run concurrently on several threads. The Windows wheel and the release binaries are built with Intel ifx without OpenMP, and there ifx keeps the fixed-size local arrays and CHARACTER locals of every procedure in static storage (its default /Qauto-scalar makes only numeric and LOGICAL scalars automatic): every thread shares them. An initialisation that ran while other handles stepped then failed with "tangent assembly failed" or "band scatter" errors (c_api_threads, test_concurrent_initialisation_and_stepping_from_ threads). A twenty-line reproducer (16 threads filling and checking a local array, a 3x3 local and a CHARACTER local) shows corrupted arrays and internal I/O under the default flags and none under /Qauto. /Qauto (-auto off Windows) for ifx and -frecursive for gfortran make every local automatic. gfortran moves a local array above -fmax-stack-var-size to static storage without -frecursive, but -fopenmp already implies it, so the default gfortran build is unchanged. The source has no other implicit static storage: no local is initialised in its declaration, no DATA or COMMON, and the module variables are the explicitly SAVEd registries, test hooks and diagnostics tallies. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 9 +++++++++ CMakeLists.txt | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aceb1c69..ec7ca73f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -460,6 +460,15 @@ All notable changes to CableDyn are recorded in this file. The format follows share: a free spar rod with a 55 m pinned cable (EI 2e4 N m^2) started 5.7e-2 m off its equilibrium, drifted 7e-2 m in 3 s and moved a leg tension by 2.3 %. Such a line now takes the static passes too (4 here); the rod holds its pose to the output's 8 digits. +- Separate handles used on several threads at once failed in the Windows wheel and the release + binaries (Intel ifx without OpenMP): ifx kept the fixed-size local arrays and `CHARACTER` locals + of every procedure in static storage, which all threads share, so an initialisation that ran + while other handles stepped stopped with "tangent assembly failed" or "band scatter" errors + (gfortran builds were not affected: `-fopenmp` makes every local automatic). Every build now + makes local variables automatic, `/Qauto` (`-auto`) with ifx and `-frecursive` with gfortran, + which `-fopenmp` already implied, so the default gfortran build is unchanged. The release + benchmark decks run as fast or faster (0.3 to 21 %); ifx results change at round-off (with + `/fp:precise` every example is bit-identical). - In OpenFAST, Free Rigid6 bodies and Free, Pinned and CoupledPinned rods started their first step from zero acceleration: the module restores its state mirror after the output call at `t = 0`, which marked the objects' accelerations as committed before the start accelerations diff --git a/CMakeLists.txt b/CMakeLists.txt index 770c9279..28b18ea1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -140,6 +140,24 @@ if(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU") $<$:-Wall> $<$:-Wextra>) endif() +# Local variables are automatic in every procedure, whatever the OpenMP setting: separate +# models (C API handles, Python objects, FAST.Farm turbines) may step concurrently on +# several threads, and a local in static storage is shared by every thread that runs its +# procedure. Without OpenMP, IFX keeps fixed-size local arrays and CHARACTER locals in +# static storage (its default, /Qauto-scalar, makes only the numeric and LOGICAL scalars +# automatic), and gfortran moves a local array larger than -fmax-stack-var-size (64 KiB) +# there; /Qauto (-auto) and -frecursive put them on the stack (-fopenmp already implies +# -frecursive, so the default GNU build is unchanged). A value that must persist between +# calls is SAVEd explicitly. +if(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU") + add_compile_options($<$:-frecursive>) +elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "IntelLLVM") + if(WIN32) + add_compile_options($<$:/Qauto>) + else() + add_compile_options($<$:-auto>) + endif() +endif() # GNU builds on Windows (MinGW-w64): every executable gets a 64 MiB stack reserve instead of # the 2 MiB MinGW default. With OpenMP, gfortran places fixed-size local arrays on the stack # (-fopenmp implies -frecursive), and the stack depth of the OpenBLAS kernels varies with the From 9021de647cf5788bc991f9c36309633e2fc084de Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 14:10:32 +0900 Subject: [PATCH 05/19] fix(dynamics): no closures over a model in the line step callbacks With automatic locals, concurrent steps of separate handles still ended the ifx builds with access violations and privileged-instruction faults. A debug build symbolised through DbgHelp showed every faulting thread in CD_Cable_Gen_Alpha_Step's residual evaluation calling the load or added-mass callback, with the faulting instruction outside every loaded module, on one page shared by all threads: the callbacks were internal procedures of the EI = 0 line model (model_force, model_load_band, model_added_mass_band, closing over the model), and ifx calls an internal procedure passed as an argument through a trampoline kept in memory every thread shares. A 40-line reproducer (an internal function passed through an optional dummy to a procedure pointer in another module) gives wrong results or crashes with two threads under the default flags, /Qauto and /recursive alike, and runs clean with one. The integrator now also takes the loads as an object: CD_Cable_Step_Loads (CableDyn_Dynamic) with deferred force, banded-load and banded added-mass bindings and flags for the roles it fills, passed as `loads` to CD_Cable_Gen_Alpha_Step and CD_Cable_Initial_Acceleration in place of the corresponding procedure arguments (which stay, for callers without their own state). The line model passes a model_step_loads pointing at itself (and at the blended inertia lengths after a length change under the force blend), so its initialisation, step and acceleration recompute keep the same calls in the same order. No internal procedure is passed as an argument or pointed to anywhere in src/ or app/ any more. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 8 ++ src/CableDyn_Dynamic.f90 | 159 ++++++++++++++++++++++++++++----- src/CableDyn_Model.f90 | 187 ++++++++++++++++++--------------------- 3 files changed, 231 insertions(+), 123 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec7ca73f..6b58ad75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -460,6 +460,14 @@ All notable changes to CableDyn are recorded in this file. The format follows share: a free spar rod with a 55 m pinned cable (EI 2e4 N m^2) started 5.7e-2 m off its equilibrium, drifted 7e-2 m in 3 s and moved a leg tension by 2.3 %. Such a line now takes the static passes too (4 here); the rod holds its pose to the output's 8 digits. +- Concurrent steps of separate handles crashed the ifx builds with access violations: an `EI = 0` + line model passed its load and added-mass callbacks to the integrator as internal procedures, + and ifx calls such a closure through a trampoline kept in memory every thread shares, so two + threads stepping distinct models called each other's half-written trampolines (a 40-line + reproducer crashes with two threads under every ifx option). The model now hands its loads to + the integrator as an object (`CD_Cable_Step_Loads`); results are unchanged. Seven decks + stepped together on 28 threads (`c_api_threads_mixed`) failed every run before and pass 50 of + 50. - Separate handles used on several threads at once failed in the Windows wheel and the release binaries (Intel ifx without OpenMP): ifx kept the fixed-size local arrays and `CHARACTER` locals of every procedure in static storage, which all threads share, so an initialisation that ran diff --git a/src/CableDyn_Dynamic.f90 b/src/CableDyn_Dynamic.f90 index 20c2ca98..7fe89be4 100644 --- a/src/CableDyn_Dynamic.f90 +++ b/src/CableDyn_Dynamic.f90 @@ -53,6 +53,7 @@ MODULE CableDyn_Dynamic PUBLIC :: CD_Cable_Dynamic_Force_Proc PUBLIC :: CD_Cable_Added_Mass_Proc PUBLIC :: CD_Cable_Added_Mass_Banded_Proc + PUBLIC :: CD_Cable_Step_Loads TYPE :: GenAlphaConfig !! Generalized-alpha policy. The Chung-Hulbert parameters (alpha_m, alpha_f, beta, gamma) are derived from @@ -303,6 +304,60 @@ SUBROUTINE CD_Cable_Added_Mass_Banded_Proc(q, accel, free, kl, ku, M_add_a, M_ad END SUBROUTINE CD_Cable_Added_Mass_Banded_Proc END INTERFACE + !> The banded dynamic loads of a step as an object (the `loads` argument of + !> CD_Cable_Gen_Alpha_Step and CD_Cable_Initial_Acceleration), for a caller whose loads are + !> computed from its own data, such as a line model: an extension carries that data as + !> components. Such a caller does not pass internal procedures as the callbacks: an internal + !> procedure passed as an argument is a closure over its host's frame, which Intel ifx + !> (2025.3, Windows) calls through a trampoline kept in memory every thread shares, so two + !> threads stepping distinct models through closures corrupt each other's calls. + !> has_force: the object gives the force and the banded load (load_force_proc and + !> load_band_proc); has_added_mass: the banded added mass (added_mass_band_proc). + TYPE, ABSTRACT :: CD_Cable_Step_Loads + LOGICAL :: has_force = .FALSE. + LOGICAL :: has_added_mass = .FALSE. + CONTAINS + PROCEDURE(step_loads_force), DEFERRED :: force + PROCEDURE(step_loads_load_banded), DEFERRED :: load_banded + PROCEDURE(step_loads_added_mass_banded), DEFERRED :: added_mass_banded + END TYPE CD_Cable_Step_Loads + + ABSTRACT INTERFACE + SUBROUTINE step_loads_force(self, q, v, force, ErrStat, ErrMsg) + !! CD_Cable_Dynamic_Force_Proc of the object. + IMPORT :: wp, CD_Cable_Step_Loads + CLASS(CD_Cable_Step_Loads), INTENT(INOUT) :: self + REAL(wp), INTENT(IN) :: q(:), v(:) + REAL(wp), INTENT(OUT) :: force(:) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + END SUBROUTINE step_loads_force + + SUBROUTINE step_loads_load_banded(self, q, v, free, kl, ku, force, jac_q_band, jac_v_band, ErrStat, ErrMsg) + !! CD_Cable_Dynamic_Load_Banded_Proc of the object. + IMPORT :: wp, CD_Cable_Step_Loads + CLASS(CD_Cable_Step_Loads), INTENT(INOUT) :: self + REAL(wp), INTENT(IN) :: q(:), v(:) + INTEGER, INTENT(IN) :: free(:), kl, ku + REAL(wp), INTENT(OUT) :: force(:), jac_q_band(:, :), jac_v_band(:, :) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + END SUBROUTINE step_loads_load_banded + + SUBROUTINE step_loads_added_mass_banded(self, q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, & + ErrStat, ErrMsg, need_tangent) + !! CD_Cable_Added_Mass_Banded_Proc of the object. + IMPORT :: wp, CD_Cable_Step_Loads + CLASS(CD_Cable_Step_Loads), INTENT(INOUT) :: self + REAL(wp), INTENT(IN) :: q(:), accel(:) + INTEGER, INTENT(IN) :: free(:), kl, ku + REAL(wp), INTENT(OUT) :: M_add_a(:), M_add_band(:, :), dMa_a_dq_band(:, :) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + LOGICAL, INTENT(IN), OPTIONAL :: need_tangent + END SUBROUTINE step_loads_added_mass_banded + END INTERFACE + CONTAINS SUBROUTINE CD_Clear_GenAlpha_Workspace(work) @@ -409,11 +464,13 @@ END SUBROUTINE CD_Clear_GenAlpha_Workspace SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension_only, & f_ext, fixed_dofs, a0, ErrStat, ErrMsg, & load_proc, added_mass_proc, load_force_proc, structural_mass, workspace, & - added_mass_band_proc) + added_mass_band_proc, loads) !! Consistent-mass initial acceleration: solve M a = f_ext - f_int(q) on the free !! DOFs (fixed DOFs get a = 0), without load callbacks. Gives the caller a !! consistent a_n to seed CD_Cable_Gen_Alpha_Step; ``v`` is accepted for !! signature parity with the loaded case but does not enter the structural solve. + !! loads (CD_Cable_Step_Loads) stands for load_force_proc (has_force) and + !! added_mass_band_proc (has_added_mass), which are then not passed. REAL(wp), INTENT(IN) :: q(:), v(:) INTEGER, INTENT(IN) :: elem_conn(:, :) REAL(wp), INTENT(IN) :: l0(:), ea(:), rho_a(:) @@ -429,6 +486,7 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension PROCEDURE(CD_Cable_Added_Mass_Banded_Proc), OPTIONAL :: added_mass_band_proc REAL(wp), INTENT(IN), OPTIONAL :: structural_mass(:, :) TYPE(CD_CableGenAlphaWorkspace), INTENT(INOUT), TARGET, OPTIONAL :: workspace + CLASS(CD_Cable_Step_Loads), INTENT(INOUT), OPTIONAL :: loads INTEGER :: n_dof, n_elem, n_free, kl, ku, ldab INTEGER, POINTER :: free(:) @@ -439,10 +497,25 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension INTEGER :: es CHARACTER(1024) :: em LOGICAL :: use_element_mass_band + ! the force and the banded added mass: from a callback, or from loads (loads_force, loads_mass) + LOGICAL :: has_force, has_mass_band, loads_force, loads_mass a0 = CD_ZERO ErrStat = CD_DYN_OK ErrMsg = '' + loads_force = .FALSE. + loads_mass = .FALSE. + IF (PRESENT(loads)) THEN + loads_force = loads%has_force + loads_mass = loads%has_added_mass + END IF + IF ((loads_force .AND. (PRESENT(load_proc) .OR. PRESENT(load_force_proc))) .OR. & + (loads_mass .AND. (PRESENT(added_mass_proc) .OR. PRESENT(added_mass_band_proc)))) THEN + CALL fail(ErrStat, ErrMsg, 'pass a load either as a callback or in loads, not both') + RETURN + END IF + has_force = PRESENT(load_force_proc) .OR. loads_force + has_mass_band = PRESENT(added_mass_band_proc) .OR. loads_mass n_dof = SIZE(q) CALL check_state_shapes(n_dof, [SIZE(v), SIZE(a0), SIZE(f_ext)], ErrStat, ErrMsg) IF (ErrStat /= 0) RETURN @@ -463,14 +536,14 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension work%dof_marker, ErrStat, ErrMsg) IF (ErrStat /= 0) RETURN free => work%free(1:n_free) - IF (PRESENT(added_mass_proc) .AND. PRESENT(added_mass_band_proc)) THEN + IF (PRESENT(added_mass_proc) .AND. has_mass_band) THEN CALL fail(ErrStat, ErrMsg, 'pass either added_mass_proc or added_mass_band_proc, not both') RETURN END IF ! Banded added mass requires the banded path; a dense load_proc is incompatible ! (mirrors CD_Cable_Gen_Alpha_Step). Keep validation consistent across both entry ! points so a banded callback is never mixed with a dense one. - IF (PRESENT(added_mass_band_proc) .AND. PRESENT(load_proc)) THEN + IF (has_mass_band .AND. PRESENT(load_proc)) THEN CALL fail(ErrStat, ErrMsg, 'added_mass_band_proc cannot be mixed with a dense load_proc; use one path') RETURN END IF @@ -506,7 +579,7 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension M_add => work%M_add_eval(1:n_dof, 1:n_dof) dMa_a_dq => work%dMa_a_dq_eval(1:n_dof, 1:n_dof) END IF - IF (PRESENT(added_mass_band_proc)) THEN + IF (has_mass_band) THEN M_add_a => work%M_add_a_eval(1:n_dof) M_add_band => work%M_add_band(1:ldab, 1:n_free) dMa_band => work%dMa_a_dq_band(1:ldab, 1:n_free) @@ -538,8 +611,12 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension CALL fail(ErrStat, ErrMsg, 'internal-force assembly failed: '//TRIM(em)) RETURN END IF - IF (PRESENT(load_force_proc)) THEN - CALL load_force_proc(q, v, load, es, em) + IF (has_force) THEN + IF (loads_force) THEN + CALL loads%force(q, v, load, es, em) + ELSE + CALL load_force_proc(q, v, load, es, em) + END IF IF (es /= 0) THEN CALL fail_callback(ErrStat, ErrMsg, 'dynamic force load failed: '//TRIM(em), es) RETURN @@ -574,10 +651,15 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension RETURN END IF M = M + M_add - ELSE IF (PRESENT(added_mass_band_proc)) THEN + ELSE IF (has_mass_band) THEN zero_accel = CD_ZERO - CALL added_mass_band_proc(q, zero_accel, free, kl, ku, M_add_a, M_add_band, dMa_band, es, em, & - need_tangent=.TRUE.) + IF (loads_mass) THEN + CALL loads%added_mass_banded(q, zero_accel, free, kl, ku, M_add_a, M_add_band, dMa_band, es, em, & + need_tangent=.TRUE.) + ELSE + CALL added_mass_band_proc(q, zero_accel, free, kl, ku, M_add_a, M_add_band, dMa_band, es, em, & + need_tangent=.TRUE.) + END IF IF (es /= 0) THEN CALL fail_callback(ErrStat, ErrMsg, 'banded added mass failed: '//TRIM(em), es) RETURN @@ -612,7 +694,7 @@ SUBROUTINE CD_Cable_Initial_Acceleration(q, v, elem_conn, l0, ea, rho_a, tension CALL fail(ErrStat, ErrMsg, 'mass band packing failed: '//TRIM(em)) RETURN END IF - IF (PRESENT(added_mass_band_proc)) M_band = M_band + M_add_band + IF (has_mass_band) M_band = M_band + M_add_band CALL CD_Solve_Banded(M_band, kl, ku, rhs, es, em) END IF IF (es /= 0 .OR. .NOT. CD_All_Finite(rhs)) THEN @@ -630,9 +712,11 @@ SUBROUTINE CD_Cable_Gen_Alpha_Step(q, v, a, elem_conn, l0, ea, rho_a, tension_on load_band_proc, prescribed_q, prescribed_v, prescribed_a, structural_mass, & workspace, added_mass_band_proc, start_load, start_tension, & probe_q, probe_R, probe_K, start_stiffness, axial_damping, & - axial_l0_rate, start_l0, mass_l0, start_l0_rate) + axial_l0_rate, start_l0, mass_l0, start_l0_rate, loads) !! One generalized-alpha step: the constant load f_ext plus the optional load, !! banded-load, force-only and added-mass callbacks (hydrodynamics, damping, contact). + !! loads (CD_Cable_Step_Loads) stands for load_force_proc and load_band_proc (has_force) + !! and for added_mass_band_proc (has_added_mass), which are then not passed. !! On a singular effective tangent returns CD_DYN_SINGULAR; on a line-search !! stall returns converged=.FALSE., stalled=.TRUE. !! @@ -723,6 +807,7 @@ SUBROUTINE CD_Cable_Gen_Alpha_Step(q, v, a, elem_conn, l0, ea, rho_a, tension_on !! with, for T_d,n; axial_l0_rate stays the rate at t_{n+1}, for T_d,n+1. Absent: !! axial_l0_rate. REAL(wp), INTENT(IN), OPTIONAL :: start_l0(:), mass_l0(:), start_l0_rate(:) + CLASS(CD_Cable_Step_Loads), INTENT(INOUT), OPTIONAL :: loads INTEGER :: n_dof, n_elem, n_free, bt, kl, ku, ldab INTEGER, POINTER :: free(:), fixed(:), ipiv(:) @@ -757,6 +842,8 @@ SUBROUTINE CD_Cable_Gen_Alpha_Step(q, v, a, elem_conn, l0, ea, rho_a, tension_on REAL(wp) :: diag_scale_cached, op_norm, op_norm_cached LOGICAL :: accepted, has_load_proc, has_load_band_proc, has_added_mass_proc, has_added_mass_band_proc LOGICAL :: has_load_force_proc + ! the force and banded load (loads_force) and the banded added mass (loads_mass) from loads + LOGICAL :: loads_force, loads_mass LOGICAL :: has_prescribed, direct_banded, have_eff, tangent_fresh, use_element_mass_band ! clock at the start of a profiled kernel (CABLEDYN_PROFILE; zero when not profiling) INTEGER(int64) :: prof_k0 @@ -778,17 +865,28 @@ SUBROUTINE CD_Cable_Gen_Alpha_Step(q, v, a, elem_conn, l0, ea, rho_a, tension_on ! call that fails early cannot leave an older step's data to a later armed re-solve. IF (PRESENT(workspace)) workspace%start_valid = workspace%start_valid .AND. workspace%guess_armed n_dof = SIZE(q) + loads_force = .FALSE. + loads_mass = .FALSE. + IF (PRESENT(loads)) THEN + loads_force = loads%has_force + loads_mass = loads%has_added_mass + END IF + IF ((loads_force .AND. (PRESENT(load_proc) .OR. PRESENT(load_band_proc) .OR. PRESENT(load_force_proc))) .OR. & + (loads_mass .AND. (PRESENT(added_mass_proc) .OR. PRESENT(added_mass_band_proc)))) THEN + CALL fail(ErrStat, ErrMsg, 'pass a load either as a callback or in loads, not both') + RETURN + END IF has_load_proc = PRESENT(load_proc) - has_load_band_proc = PRESENT(load_band_proc) + has_load_band_proc = PRESENT(load_band_proc) .OR. loads_force has_added_mass_proc = PRESENT(added_mass_proc) - has_added_mass_band_proc = PRESENT(added_mass_band_proc) - has_load_force_proc = PRESENT(load_force_proc) + has_added_mass_band_proc = PRESENT(added_mass_band_proc) .OR. loads_mass + has_load_force_proc = PRESENT(load_force_proc) .OR. loads_force NULLIFY (load_proc_cb, added_mass_proc_cb, load_force_proc_cb, load_band_proc_cb, added_mass_band_proc_cb) IF (has_load_proc) load_proc_cb => load_proc - IF (has_load_band_proc) load_band_proc_cb => load_band_proc + IF (PRESENT(load_band_proc)) load_band_proc_cb => load_band_proc IF (has_added_mass_proc) added_mass_proc_cb => added_mass_proc - IF (has_added_mass_band_proc) added_mass_band_proc_cb => added_mass_band_proc - IF (has_load_force_proc) load_force_proc_cb => load_force_proc + IF (PRESENT(added_mass_band_proc)) added_mass_band_proc_cb => added_mass_band_proc + IF (PRESENT(load_force_proc)) load_force_proc_cb => load_force_proc IF (has_load_proc .AND. has_load_band_proc) THEN CALL fail(ErrStat, ErrMsg, 'pass either load_proc or load_band_proc, not both') RETURN @@ -1721,7 +1819,11 @@ SUBROUTINE start_forces(es_s, em_s) load_n(i) = start_load(i) END DO ELSE IF (has_load_force_proc) THEN - CALL load_force_proc_cb(q_n, v_n, load_n, es_s, em_s) + IF (loads_force) THEN + CALL loads%force(q_n, v_n, load_n, es_s, em_s) + ELSE + CALL load_force_proc_cb(q_n, v_n, load_n, es_s, em_s) + END IF IF (es_s /= 0) THEN em_s = 'step-start dynamic force load failed: '//TRIM(em_s) RETURN @@ -2002,7 +2104,11 @@ SUBROUTINE eval_dynamic_core(q_eval, Rout, es_e, em_e, effout, effbandout) END IF IF (has_load_band_proc) THEN ! the callback defines every INTENT(OUT) band entry itself - CALL load_band_proc_cb(qf, vf, free, kl, ku, load_eval, jq_band, jv_band, es_e, em_e) + IF (loads_force) THEN + CALL loads%load_banded(qf, vf, free, kl, ku, load_eval, jq_band, jv_band, es_e, em_e) + ELSE + CALL load_band_proc_cb(qf, vf, free, kl, ku, load_eval, jq_band, jv_band, es_e, em_e) + END IF IF (es_e /= 0) THEN em_e = 'dynamic banded load failed: '//TRIM(em_e) Rout = CD_ZERO @@ -2059,7 +2165,11 @@ SUBROUTINE eval_dynamic_core(q_eval, Rout, es_e, em_e, effout, effbandout) RETURN END IF ELSE IF (has_load_force_proc .AND. .NOT. tangent_requested) THEN - CALL load_force_proc_cb(qf, vf, load_eval, es_e, em_e) + IF (loads_force) THEN + CALL loads%force(qf, vf, load_eval, es_e, em_e) + ELSE + CALL load_force_proc_cb(qf, vf, load_eval, es_e, em_e) + END IF IF (es_e /= 0) THEN em_e = 'dynamic force load failed: '//TRIM(em_e) Rout = CD_ZERO @@ -2109,8 +2219,13 @@ SUBROUTINE eval_dynamic_core(q_eval, Rout, es_e, em_e, effout, effbandout) END IF M_eff_eval = M_eff_eval + M_add_eval ELSE IF (has_added_mass_band_proc) THEN - CALL added_mass_band_proc_cb(q_alpha, a_alpha, free, kl, ku, M_add_a_eval, M_add_band, & - dMa_a_dq_band, es_e, em_e, PRESENT(effbandout)) + IF (loads_mass) THEN + CALL loads%added_mass_banded(q_alpha, a_alpha, free, kl, ku, M_add_a_eval, M_add_band, & + dMa_a_dq_band, es_e, em_e, PRESENT(effbandout)) + ELSE + CALL added_mass_band_proc_cb(q_alpha, a_alpha, free, kl, ku, M_add_a_eval, M_add_band, & + dMa_a_dq_band, es_e, em_e, PRESENT(effbandout)) + END IF IF (es_e /= 0) THEN em_e = 'banded added mass failed: '//TRIM(em_e) Rout = CD_ZERO diff --git a/src/CableDyn_Model.f90 b/src/CableDyn_Model.f90 index d81f086c..39d4f3f7 100644 --- a/src/CableDyn_Model.f90 +++ b/src/CableDyn_Model.f90 @@ -59,7 +59,8 @@ MODULE CableDyn_Model USE CableDyn_VIV, ONLY: CD_VIV_Node_Lift, CD_VIV_Crossflow_Motion, CD_VIV_Phase_Rate, CD_VIV_Mean_Square, & CD_VIV_Wrap_Phase, CD_VIV_NM, CD_VIV_TWO_PI USE CableDyn_Dynamic, ONLY: GenAlphaConfig, CD_CableGenAlphaWorkspace, CD_Clear_GenAlpha_Workspace, & - CD_Cable_Initial_Acceleration, CD_Cable_Gen_Alpha_Step, CD_DYN_OK, CD_DYN_ALLOCFAIL, & + CD_Cable_Initial_Acceleration, CD_Cable_Gen_Alpha_Step, CD_Cable_Step_Loads, & + CD_DYN_OK, CD_DYN_ALLOCFAIL, & CD_EI0_SUBSTEPS_AUTO, CD_EI0_SUBSTEPS_OFF USE CableDyn_Mesh, ONLY: CD_Partition_Free_Dofs, CD_Validate_Connectivity USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: int64 @@ -454,6 +455,20 @@ MODULE CableDyn_Model LOGICAL :: sub_test_repeat = .FALSE., sub_test_more = .FALSE. END TYPE CD_ModelType + !> The load contributors and added mass of a model as the dynamic loads of its steps + !> (CD_Cable_Step_Loads): the integrator calls them on the model this object points to, with + !> the added mass on the lengths l0_mass when associated (the blended lengths of the inertia + !> after a length change under the force blend). The model passes this object, never + !> internal procedures, so that distinct models step concurrently (see CD_Cable_Step_Loads). + TYPE, EXTENDS(CD_Cable_Step_Loads) :: model_step_loads + TYPE(CD_ModelType), POINTER :: model => NULL() + REAL(wp), POINTER :: l0_mass(:) => NULL() + CONTAINS + PROCEDURE :: force => model_step_force + PROCEDURE :: load_banded => model_step_load_banded + PROCEDURE :: added_mass_banded => model_step_added_mass_banded + END TYPE model_step_loads + CONTAINS SUBROUTINE CD_Init_Model(model, q0, v0, elem_conn, l0, ea, rho_a, tension_only, & @@ -475,7 +490,7 @@ SUBROUTINE CD_Init_Model(model, q0, v0, elem_conn, l0, ea, rho_a, tension_only, !! initial acceleration is computed consistently from the current structure, !! load, and fixed DOFs; callers do not provide a0. Existing model storage is !! released before the new model is populated. - TYPE(CD_ModelType), INTENT(INOUT) :: model + TYPE(CD_ModelType), INTENT(INOUT), TARGET :: model REAL(wp), INTENT(IN) :: q0(:), v0(:) INTEGER, INTENT(IN) :: elem_conn(:, :) REAL(wp), INTENT(IN) :: l0(:), ea(:), rho_a(:) @@ -531,6 +546,7 @@ SUBROUTINE CD_Init_Model(model, q0, v0, elem_conn, l0, ea, rho_a, tension_only, INTEGER :: n_dof, n_elem, n_nodes, es, istat, e INTEGER, ALLOCATABLE :: free(:) TYPE(CD_ModelType) :: old_model + TYPE(model_step_loads) :: step_loads CHARACTER(1024) :: em LOGICAL :: use_seabed, use_seabed_damping, use_seabed_friction LOGICAL :: use_damping, use_drag, use_fk, use_buoyancy, use_added_mass, has_load @@ -1395,22 +1411,24 @@ SUBROUTINE CD_Init_Model(model, q0, v0, elem_conn, l0, ea, rho_a, tension_only, has_load = model%has_seabed .OR. model%has_seabed_damping .OR. model%has_seabed_friction .OR. & model%has_damping .OR. model%has_viscoelastic .OR. model%has_syrope .OR. model%has_morison_drag .OR. & model%has_froude_krylov .OR. model%has_buoyancy_recovery + step_loads%model => model + step_loads%has_force = has_load + step_loads%has_added_mass = model%has_added_mass IF (has_load .AND. model%has_added_mass) THEN CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & model%fixed_dofs, model%a, es, em, & - load_force_proc=model_force, workspace=model%dynamic_workspace, & - added_mass_band_proc=model_added_mass_band) + workspace=model%dynamic_workspace, loads=step_loads) ELSE IF (has_load) THEN CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & model%fixed_dofs, model%a, es, em, & - load_force_proc=model_force, workspace=model%dynamic_workspace) + workspace=model%dynamic_workspace, loads=step_loads) ELSE IF (model%has_added_mass) THEN CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & model%fixed_dofs, model%a, es, em, & - workspace=model%dynamic_workspace, added_mass_band_proc=model_added_mass_band) + workspace=model%dynamic_workspace, loads=step_loads) ELSE CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & @@ -1426,30 +1444,6 @@ SUBROUTINE CD_Init_Model(model, q0, v0, elem_conn, l0, ea, rho_a, tension_only, model%initialized = .TRUE. ! the line's initial tension, the floor of the tension scale of the sub-stepping (sub_count) model%sub_t_init = initial_tension(model) - - CONTAINS - - SUBROUTINE model_force(q, v, force, ErrStat, ErrMsg) - REAL(wp), INTENT(IN) :: q(:), v(:) - REAL(wp), INTENT(OUT) :: force(:) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - CALL model_contributor_force(model, q, v, force, ErrStat, ErrMsg) - ErrStat = as_dyn_callback_status(ErrStat) - END SUBROUTINE model_force - - SUBROUTINE model_added_mass_band(q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, ErrStat, ErrMsg, & - need_tangent) - REAL(wp), INTENT(IN) :: q(:), accel(:) - INTEGER, INTENT(IN) :: free(:), kl, ku - REAL(wp), INTENT(OUT) :: M_add_a(:), M_add_band(:, :), dMa_a_dq_band(:, :) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - LOGICAL, INTENT(IN), OPTIONAL :: need_tangent - CALL model_added_mass_banded(model, q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, & - ErrStat, ErrMsg, need_tangent=need_tangent) - ErrStat = as_dyn_callback_status(ErrStat) - END SUBROUTINE model_added_mass_band END SUBROUTINE CD_Init_Model SUBROUTINE CD_Init_Line_Model(model, anchor, fairlead, line_types, sections, gravity, rho_water, & @@ -2643,7 +2637,7 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM prescribed_q, prescribed_v, prescribed_a) !! One generalized-alpha step of the model over dt, as given (CD_Step_Model without its !! resolved sub-stepping). - TYPE(CD_ModelType), INTENT(INOUT) :: model + TYPE(CD_ModelType), INTENT(INOUT), TARGET :: model REAL(wp), INTENT(IN) :: dt LOGICAL, INTENT(OUT) :: converged, stalled INTEGER, INTENT(OUT) :: n_iter, ErrStat @@ -2654,9 +2648,11 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM CHARACTER(1024) :: em LOGICAL :: has_load, blend, force_lengths REAL(wp) :: af - REAL(wp), ALLOCATABLE :: l0_new(:), l0_dot_new(:), l0_start(:), l0_mass(:), f_ext_new(:), f_ext_c(:) + REAL(wp), ALLOCATABLE :: l0_new(:), l0_dot_new(:), l0_start(:), f_ext_new(:), f_ext_c(:) + REAL(wp), ALLOCATABLE, TARGET :: l0_mass(:) REAL(wp), ALLOCATABLE :: l0_dot_start(:) TYPE(model_lengths_aside) :: aside + TYPE(model_step_loads) :: step_loads converged = .FALSE. stalled = .FALSE. @@ -2773,13 +2769,16 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM model%l0_dot(e) = (CD_ONE - af)*l0_dot_new(e) + af*model%l0_dot_c(e) END DO END IF + step_loads%model => model + step_loads%has_force = has_load + step_loads%has_added_mass = model%has_added_mass + IF (ALLOCATED(l0_mass)) step_loads%l0_mass => l0_mass IF (PRESENT(prescribed_q) .AND. has_load .AND. model%has_added_mass) THEN CALL CD_Cable_Gen_Alpha_Step(model%q, model%v, model%a, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, model%fixed_dofs, & dt, model%cfg, model%q_step, model%v_step, model%a_step, converged, stalled, & n_iter, & - es, em, load_force_proc=model_force, load_band_proc=model_load_band, & - added_mass_band_proc=model_added_mass_band, prescribed_q=prescribed_q, & + es, em, loads=step_loads, prescribed_q=prescribed_q, & prescribed_v=prescribed_v, prescribed_a=prescribed_a, & workspace=model%dynamic_workspace, start_load=model%load_start_work, & start_tension=model%tension_start_work, & @@ -2791,7 +2790,7 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM model%rho_a, model%tension_only, model%f_ext, model%fixed_dofs, & dt, model%cfg, model%q_step, model%v_step, model%a_step, converged, stalled, & n_iter, & - es, em, load_force_proc=model_force, load_band_proc=model_load_band, & + es, em, loads=step_loads, & prescribed_q=prescribed_q, prescribed_v=prescribed_v, & prescribed_a=prescribed_a, workspace=model%dynamic_workspace, & start_load=model%load_start_work, start_tension=model%tension_start_work, & @@ -2803,7 +2802,7 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM model%rho_a, model%tension_only, model%f_ext, model%fixed_dofs, & dt, model%cfg, model%q_step, model%v_step, model%a_step, converged, stalled, & n_iter, & - es, em, added_mass_band_proc=model_added_mass_band, prescribed_q=prescribed_q, & + es, em, loads=step_loads, prescribed_q=prescribed_q, & prescribed_v=prescribed_v, prescribed_a=prescribed_a, & workspace=model%dynamic_workspace, & start_l0=l0_start, mass_l0=l0_mass) @@ -2820,8 +2819,7 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM model%rho_a, model%tension_only, model%f_ext, model%fixed_dofs, & dt, model%cfg, model%q_step, model%v_step, model%a_step, converged, stalled, & n_iter, es, em, & - load_force_proc=model_force, load_band_proc=model_load_band, & - added_mass_band_proc=model_added_mass_band, workspace=model%dynamic_workspace, & + loads=step_loads, workspace=model%dynamic_workspace, & start_load=model%load_start_work, start_tension=model%tension_start_work, & start_stiffness=model%stiffness_start_work, & axial_damping=model%ba_dyn, axial_l0_rate=model%l0_dot, & @@ -2831,7 +2829,7 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM model%rho_a, model%tension_only, model%f_ext, model%fixed_dofs, & dt, model%cfg, model%q_step, model%v_step, model%a_step, converged, stalled, & n_iter, es, em, & - load_force_proc=model_force, load_band_proc=model_load_band, & + loads=step_loads, & workspace=model%dynamic_workspace, start_load=model%load_start_work, & start_tension=model%tension_start_work, & start_stiffness=model%stiffness_start_work, & @@ -2842,7 +2840,7 @@ SUBROUTINE step_model_plain(model, dt, converged, stalled, n_iter, ErrStat, ErrM model%rho_a, model%tension_only, model%f_ext, model%fixed_dofs, & dt, model%cfg, model%q_step, model%v_step, model%a_step, converged, stalled, & n_iter, es, em, & - added_mass_band_proc=model_added_mass_band, workspace=model%dynamic_workspace, & + loads=step_loads, workspace=model%dynamic_workspace, & start_l0=l0_start, mass_l0=l0_mass) ELSE CALL CD_Cable_Gen_Alpha_Step(model%q, model%v, model%a, model%elem_conn, model%l0, model%ea_dyn, & @@ -3079,40 +3077,6 @@ SUBROUTINE step_start_load(es_s, em_s) END IF model%load_start_valid = .TRUE. END SUBROUTINE step_start_load - - SUBROUTINE model_force(q, v, force, ErrStat, ErrMsg) - REAL(wp), INTENT(IN) :: q(:), v(:) - REAL(wp), INTENT(OUT) :: force(:) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - CALL model_contributor_force(model, q, v, force, ErrStat, ErrMsg) - ErrStat = as_dyn_callback_status(ErrStat) - END SUBROUTINE model_force - - SUBROUTINE model_load_band(q, v, free, kl, ku, force, jac_q_band, jac_v_band, ErrStat, ErrMsg) - REAL(wp), INTENT(IN) :: q(:), v(:) - INTEGER, INTENT(IN) :: free(:), kl, ku - REAL(wp), INTENT(OUT) :: force(:), jac_q_band(:, :), jac_v_band(:, :) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - CALL model_contributor_load_banded(model, q, v, free, kl, ku, force, jac_q_band, jac_v_band, & - ErrStat, ErrMsg) - END SUBROUTINE model_load_band - - SUBROUTINE model_added_mass_band(q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, ErrStat, ErrMsg, & - need_tangent) - !! The added mass at q_alpha; after a length change under the force blend with the - !! blended lengths of the inertia (l0_mass, unallocated and so absent otherwise). - REAL(wp), INTENT(IN) :: q(:), accel(:) - INTEGER, INTENT(IN) :: free(:), kl, ku - REAL(wp), INTENT(OUT) :: M_add_a(:), M_add_band(:, :), dMa_a_dq_band(:, :) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - LOGICAL, INTENT(IN), OPTIONAL :: need_tangent - CALL model_added_mass_banded(model, q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, & - ErrStat, ErrMsg, need_tangent=need_tangent, l0_elem=l0_mass) - ErrStat = as_dyn_callback_status(ErrStat) - END SUBROUTINE model_added_mass_band END SUBROUTINE step_model_plain SUBROUTINE CD_Step_Model_Recovering(model, dt, converged, stalled, n_iter, ErrStat, ErrMsg, & @@ -6099,7 +6063,7 @@ END SUBROUTINE CD_Recompute_Model_Acceleration SUBROUTINE recompute_model_acceleration_now(model, ErrStat, ErrMsg) !! CD_Recompute_Model_Acceleration with the lengths and rates in place. - TYPE(CD_ModelType), INTENT(INOUT) :: model + TYPE(CD_ModelType), INTENT(INOUT), TARGET :: model INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg @@ -6111,6 +6075,7 @@ SUBROUTINE recompute_model_acceleration_now(model, ErrStat, ErrMsg) ! Entry acceleration: every failure below restores it whole, so a failed ! recompute leaves the committed state untouched. REAL(wp) :: a_entry(model%n_dof) + TYPE(model_step_loads) :: step_loads ErrStat = CD_MODEL_OK ErrMsg = '' @@ -6131,22 +6096,24 @@ SUBROUTINE recompute_model_acceleration_now(model, ErrStat, ErrMsg) END IF a_entry = model%a model%a_prescribed_work(1:nc) = model%a(model%fixed_dofs) + step_loads%model => model + step_loads%has_force = has_load + step_loads%has_added_mass = model%has_added_mass IF (has_load .AND. model%has_added_mass) THEN CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & model%fixed_dofs, model%a, es, em, & - load_force_proc=model_force, workspace=model%dynamic_workspace, & - added_mass_band_proc=model_added_mass_band) + workspace=model%dynamic_workspace, loads=step_loads) ELSE IF (has_load) THEN CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & model%fixed_dofs, model%a, es, em, & - load_force_proc=model_force, workspace=model%dynamic_workspace) + workspace=model%dynamic_workspace, loads=step_loads) ELSE IF (model%has_added_mass) THEN CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & model%fixed_dofs, model%a, es, em, & - workspace=model%dynamic_workspace, added_mass_band_proc=model_added_mass_band) + workspace=model%dynamic_workspace, loads=step_loads) ELSE CALL CD_Cable_Initial_Acceleration(model%q, model%v, model%elem_conn, model%l0, model%ea_dyn, & model%rho_a, model%tension_only, model%f_ext, & @@ -6348,28 +6315,6 @@ SUBROUTINE ensure_support_acceleration_workspace(model, n_free, ErrStat, ErrMsg) END IF END IF END SUBROUTINE ensure_support_acceleration_workspace - - SUBROUTINE model_force(q, v, force, ErrStat, ErrMsg) - REAL(wp), INTENT(IN) :: q(:), v(:) - REAL(wp), INTENT(OUT) :: force(:) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - CALL model_contributor_force(model, q, v, force, ErrStat, ErrMsg) - ErrStat = as_dyn_callback_status(ErrStat) - END SUBROUTINE model_force - - SUBROUTINE model_added_mass_band(q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, ErrStat, ErrMsg, & - need_tangent) - REAL(wp), INTENT(IN) :: q(:), accel(:) - INTEGER, INTENT(IN) :: free(:), kl, ku - REAL(wp), INTENT(OUT) :: M_add_a(:), M_add_band(:, :), dMa_a_dq_band(:, :) - INTEGER, INTENT(OUT) :: ErrStat - CHARACTER(*), INTENT(OUT) :: ErrMsg - LOGICAL, INTENT(IN), OPTIONAL :: need_tangent - CALL model_added_mass_banded(model, q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, & - ErrStat, ErrMsg, need_tangent=need_tangent) - ErrStat = as_dyn_callback_status(ErrStat) - END SUBROUTINE model_added_mass_band END SUBROUTINE recompute_model_acceleration_now SUBROUTINE CD_Audit_Model_Step(model, time, dt, new_spike) @@ -9365,6 +9310,46 @@ SUBROUTINE alloc_fail(ErrStat, ErrMsg, msg) ErrMsg = 'CableDyn_Model: '//msg END SUBROUTINE alloc_fail + SUBROUTINE model_step_force(self, q, v, force, ErrStat, ErrMsg) + !! The force of the model's load contributors at (q, v) (model_step_loads). + CLASS(model_step_loads), INTENT(INOUT) :: self + REAL(wp), INTENT(IN) :: q(:), v(:) + REAL(wp), INTENT(OUT) :: force(:) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + CALL model_contributor_force(self%model, q, v, force, ErrStat, ErrMsg) + ErrStat = as_dyn_callback_status(ErrStat) + END SUBROUTINE model_step_force + + SUBROUTINE model_step_load_banded(self, q, v, free, kl, ku, force, jac_q_band, jac_v_band, ErrStat, ErrMsg) + !! The force and banded Jacobians of the model's load contributors at (q, v) + !! (model_step_loads). + CLASS(model_step_loads), INTENT(INOUT) :: self + REAL(wp), INTENT(IN) :: q(:), v(:) + INTEGER, INTENT(IN) :: free(:), kl, ku + REAL(wp), INTENT(OUT) :: force(:), jac_q_band(:, :), jac_v_band(:, :) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + CALL model_contributor_load_banded(self%model, q, v, free, kl, ku, force, jac_q_band, jac_v_band, & + ErrStat, ErrMsg) + END SUBROUTINE model_step_load_banded + + SUBROUTINE model_step_added_mass_banded(self, q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, & + ErrStat, ErrMsg, need_tangent) + !! The model's banded added mass at q (model_step_loads), on the lengths l0_mass when + !! associated (a disassociated pointer is an absent l0_elem). + CLASS(model_step_loads), INTENT(INOUT) :: self + REAL(wp), INTENT(IN) :: q(:), accel(:) + INTEGER, INTENT(IN) :: free(:), kl, ku + REAL(wp), INTENT(OUT) :: M_add_a(:), M_add_band(:, :), dMa_a_dq_band(:, :) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + LOGICAL, INTENT(IN), OPTIONAL :: need_tangent + CALL model_added_mass_banded(self%model, q, accel, free, kl, ku, M_add_a, M_add_band, dMa_a_dq_band, & + ErrStat, ErrMsg, need_tangent=need_tangent, l0_elem=self%l0_mass) + ErrStat = as_dyn_callback_status(ErrStat) + END SUBROUTINE model_step_added_mass_banded + PURE INTEGER FUNCTION as_dyn_callback_status(model_es) RESULT(dyn_es) !! Translate a model load-callback status into the integrator's namespace so an allocation !! failure inside model_contributor_load/_force is forwarded as CD_DYN_ALLOCFAIL (and preserved From 46c2f830a33a65018e5f9cf3e9c910360a96b5f5 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 06:23:07 +0900 Subject: [PATCH 06/19] test(threads): concurrent steps on every handle route and a source audit c_api_threads steps one EI = 0 chain deck. Two gates cover the rest of what separate handles may run at once: - c_api_threads_mixed (test_c_api_threads --mixed): seven decks stepped together, four threads each, 40 steps, every final coupled load against the deck's serial reference: the EI = 0 chain and finite-EI cable of the coupled aggregate, viscoelastic and Syrope segments, the UMaine mixed deck, Free points, the Lozon power cable and a Free rod (new tests/data/c_api_free_rod.dat, stepped at its dtM). - thread_safe_sources (tests/test_thread_safe_sources.py), compiler independent so that a gfortran CI run catches what only an ifx build shows: no internal procedure as a procedure value, no local initialised in its declaration and no DATA/COMMON, every variable in static storage on a reviewed list with its reason (50: the handle and instance registries, test hooks, opt-in profiles, diagnostics tallies), and the automatic-locals flags in CMakeLists.txt. A scratch source with a closure and an implicit SAVE checks the checks. Measured with the static release flags (ifx 2025.3.2), 7 decks x 4 threads: the build before the two fixes fails the mixed gate 5 of 5 runs (access violations, heap corruption), automatic locals alone 5 of 5, the closure fix alone 5 of 5; with both it passes 50 of 50 (and c_api_threads 50 of 50, against 20 of 20 failures before, 10 of 10 with either fix alone). The source audit fails on the code before the fixes (the closures in CableDyn_Model and CableDyn_DeckDriver, the missing flags) and passes now. Signed-off-by: Jae Hoon Seo --- CMakeLists.txt | 23 +++ tests/data/c_api_free_rod.dat | 41 +++++ tests/test_c_api_threads.c | 94 +++++++++- tests/test_thread_safe_sources.py | 287 ++++++++++++++++++++++++++++++ 4 files changed, 440 insertions(+), 5 deletions(-) create mode 100644 tests/data/c_api_free_rod.dat create mode 100644 tests/test_thread_safe_sources.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 28b18ea1..6126bda1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1376,6 +1376,21 @@ add_test(NAME c_api_threads_stress $,1,0>) set_tests_properties(c_api_threads_stress PROPERTIES LABELS "c;unit;capi;threading" TIMEOUT 600 ENVIRONMENT "CABLEDYN_THREAD_TEST_LOOPS=5;CABLEDYN_THREAD_TEST_TIMEOUT=540") +# Concurrent steps on every per-handle route at once, 4 threads per deck, each trajectory against +# its deck's serial reference: EI = 0 chain and finite-EI cable on the coupled aggregate, +# viscoelastic and Syrope segments, a mixed EI = 0/finite-EI deck, Free points, a finite-EI +# power cable and a Free rod. Static locals or closure trampolines shared by the threads fail it. +add_test(NAME c_api_threads_mixed + COMMAND test_c_api_threads --mixed 40 + ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/host_coupling_chain_cable.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/ve_polyester_catenary_mooring.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/syrope_polyester_mooring.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/iea15mw_umaine_mixed_cabledyn.dat + ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/foam_esflowc_box_points.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/lozon_gomaine200_power_cable.dat + ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/c_api_free_rod.dat) +set_tests_properties(c_api_threads_mixed PROPERTIES LABELS "c;unit;capi;threading" TIMEOUT 600 + ENVIRONMENT "CABLEDYN_THREAD_TEST_TIMEOUT=540") if(WIN32) # Host threads that ran OpenMP teams, then an immediate process exit: MinGW-w64 # libgomp could hang in its exit handler when a pool thread was still ending. @@ -1575,6 +1590,14 @@ if(Python3_Interpreter_FOUND) LABELS "python;unit;stack" ENVIRONMENT "${_cabledyn_python_test_environment}") + # Storage that concurrent models could share: closures, implicit SAVE, unreviewed static + # variables, and the automatic-locals flags (tests/test_thread_safe_sources.py). + add_test(NAME thread_safe_sources + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_thread_safe_sources.py) + set_tests_properties(thread_safe_sources PROPERTIES + LABELS "python;unit;threading" + ENVIRONMENT "${_cabledyn_python_test_environment}") + add_test(NAME documentation_sources COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_documentation.py) set_tests_properties(documentation_sources PROPERTIES diff --git a/tests/data/c_api_free_rod.dat b/tests/data/c_api_free_rod.dat new file mode 100644 index 00000000..f5d8e5e3 --- /dev/null +++ b/tests/data/c_api_free_rod.dat @@ -0,0 +1,41 @@ +--------------------- CableDyn Input File ------------------------------------ +C API concurrency test deck: a Free rod hung between a Fixed anchor line and a line to a +Coupled point, so a handle steps the rod through the coupled aggregate (fixed step dtM) +(test_c_api_threads --mixed). +--------------------------- LINE TYPES ---------------------------------------- +Name Diam Mass EA BA EI Cdn Cdt Can Cat +(-) (m) (kg/m) (N) (-) (Nm2) (-) (-) (-) (-) +line 0.10 80.0 1.0e5 0.0 0.0 1.0 0.0 1.0 0.0 +--------------------------- ROD TYPES ----------------------------------------- +Name Diam Mass Cd Ca CdEnd CaEnd +(-) (m) (kg/m) (-) (-) (-) (-) +rodmat 0.20 50.0 1.0 1.0 0.0 0.0 +--------------------------- RODS ---------------------------------------------- +ID RodType Type XA YA ZA XB YB ZB NumSegs Outputs +(-) (-) (-) (m) (m) (m) (m) (m) (m) (-) (-) +1 rodmat Free 0.0 0.0 -4.0 0.0 0.0 -2.0 2 - +--------------------------- POINTS -------------------------------------------- +ID Type X Y Z Mass Vol CdA Ca +(-) (-) (m) (m) (m) (kg) (m3) (m2) (-) +1 Fixed 2.0 0.0 -5.0 0.0 0.0 0.0 0.0 +2 Rod1A 0.0 0.0 -4.0 0.0 0.0 0.0 0.0 +3 Rod1B 0.0 0.0 -2.0 0.0 0.0 0.0 0.0 +4 Coupled 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 +--------------------------- LINES --------------------------------------------- +ID NodeA NodeB Outputs +(-) (-) (-) (-) +1 2 1 - +2 3 4 - +--------------------------- SECTIONS ------------------------------------------ +LineID LineType Length NumSegs +(-) (-) (m) (-) +1 line 3.5 3 +2 line 1.2 2 +--------------------------- OPTIONS ------------------------------------------- +9.80665 g +1025.0 rhoW +10.0 WtrDpth +1.0e5 kBot +0.05 dtM +1.0 TMax +--------------------------- END ----------------------------------------------- diff --git a/tests/test_c_api_threads.c b/tests/test_c_api_threads.c index 414e8a98..ecd3f935 100644 --- a/tests/test_c_api_threads.c +++ b/tests/test_c_api_threads.c @@ -21,6 +21,13 @@ * 5. 24 threads step distinct handles concurrently while other threads keep * failing to open a missing deck; every trajectory matches a serial reference. * + * test_c_api_threads --mixed [ ...] instead steps every deck on + * several threads at once, all decks concurrently (each handle its own model: EI = 0 + * lines, finite-EI cables, Syrope and viscoelastic segments, points, bodies and rods take + * their own code paths), n_steps steps each, and checks every trajectory against the + * deck's serial reference. A procedure whose locals or callbacks live in storage that + * every thread shares (static locals, closure trampolines) fails it. + * * CABLEDYN_THREAD_TEST_LOOPS= repeats checks 2-5 n times in one process (stress * mode). A watchdog thread ends the process with a failure naming the phase in * progress when the run exceeds CABLEDYN_THREAD_TEST_TIMEOUT seconds (default 300), @@ -252,8 +259,8 @@ static double private_mb(void) #endif } -/* Initialises `path`, takes N_STEP held steps, and records the final coupled loads. */ -static int step_deck(const char *path, double *loads, int *ndof_out, char *msg, size_t msg_len) +/* Initialises `path`, takes n_step steps, and records the final coupled loads. */ +static int step_deck(const char *path, int n_step, double *loads, int *ndof_out, char *msg, size_t msg_len) { void *h = NULL; int err = -1, ndof, k, n_iter = 0; @@ -273,7 +280,7 @@ static int step_deck(const char *path, double *loads, int *ndof_out, char *msg, return 1; } CableDyn_GetCoupledMotion(h, q, v, a, ndof, &err); - for (k = 0; k < N_STEP && err == CD_C_OK; ++k) { + for (k = 0; k < n_step && err == CD_C_OK; ++k) { /* A slow surge of every coupled x DOF keeps the lines working. */ int i; for (i = 0; i < ndof; i += 3) q[i] += 0.002; @@ -326,6 +333,7 @@ static void init_worker(void *raw) struct step_job { const char *path; const char *missing_path; + int n_step; int ndof; int failed; double loads[MAX_DOF]; @@ -335,7 +343,7 @@ struct step_job { static void step_worker(void *raw) { struct step_job *job = (struct step_job *)raw; - job->failed = step_deck(job->path, job->loads, &job->ndof, job->msg, sizeof job->msg); + job->failed = step_deck(job->path, job->n_step, job->loads, &job->ndof, job->msg, sizeof job->msg); } static void missing_worker(void *raw) @@ -478,7 +486,7 @@ static int check_concurrent_steps(const char *deck) char msg[512] = {0}; int i, j, ndof = 0, failed = 0; - if (step_deck(deck, reference, &ndof, msg, sizeof msg) != 0) { + if (step_deck(deck, N_STEP, reference, &ndof, msg, sizeof msg) != 0) { fprintf(stderr, "FAIL serial reference run: %s\n", msg); return 1; } @@ -486,6 +494,7 @@ static int check_concurrent_steps(const char *deck) for (i = 0; i < N_STEPPERS + N_MISSING; ++i) { jobs[i].path = deck; jobs[i].missing_path = "missing_deck_for_thread_test.dat"; + jobs[i].n_step = N_STEP; tasks[i].fn = i < N_STEPPERS ? step_worker : missing_worker; tasks[i].arg = &jobs[i]; } @@ -523,6 +532,67 @@ static int check_concurrent_steps(const char *deck) return 0; } +/* Steps every deck on MAX_THREADS / n_decks threads at once, all decks concurrently, and + * checks every final coupled load against the deck's serial reference. */ +static int check_mixed_steps(int n_decks, char **decks, int n_step) +{ + enum { MAX_DECKS = 8 }; + static struct step_job jobs[MAX_THREADS]; + static double reference[MAX_DECKS][MAX_DOF]; + struct task tasks[MAX_THREADS]; + int ndof[MAX_DECKS]; + char msg[512] = {0}; + int d, i, j, per_deck, n, failed = 0; + + if (n_decks < 1 || n_decks > MAX_DECKS) { + fprintf(stderr, "FAIL --mixed takes 1 to %d decks\n", MAX_DECKS); + return 1; + } + for (d = 0; d < n_decks; ++d) { + if (step_deck(decks[d], n_step, reference[d], &ndof[d], msg, sizeof msg) != 0) { + fprintf(stderr, "FAIL serial reference run of %s: %s\n", decks[d], msg); + return 1; + } + } + per_deck = MAX_THREADS / n_decks; + if (per_deck > 6) per_deck = 6; + n = per_deck * n_decks; + memset(jobs, 0, sizeof jobs); + for (i = 0; i < n; ++i) { + jobs[i].path = decks[i % n_decks]; + jobs[i].n_step = n_step; + tasks[i].fn = step_worker; + tasks[i].arg = &jobs[i]; + } + if (run_tasks(n, tasks) != 0) { + fprintf(stderr, "FAIL could not start the mixed stepping threads\n"); + return 1; + } + for (i = 0; i < n; ++i) { + d = i % n_decks; + if (jobs[i].failed || jobs[i].ndof != ndof[d]) { + fprintf(stderr, " thread %d (%s) failed: %s\n", i, decks[d], jobs[i].msg); + ++failed; + continue; + } + for (j = 0; j < ndof[d]; ++j) { + if (fabs(jobs[i].loads[j] - reference[d][j]) > 1.0e-9 * (1.0 + fabs(reference[d][j]))) { + fprintf(stderr, " thread %d (%s): load %d = %.17g, reference %.17g\n", i, decks[d], j, + jobs[i].loads[j], reference[d][j]); + ++failed; + break; + } + } + } + printf("mixed concurrent steps: %d decks x %d threads x %d steps: failed=%d\n", n_decks, per_deck, n_step, + failed); + if (failed != 0) { + fprintf(stderr, "FAIL concurrent Step of mixed decks on distinct handles\n"); + return 1; + } + return 0; +} + #if defined(_WIN32) /* ------------------------------------------------------- exit stress (Win32) -- */ @@ -666,6 +736,20 @@ int main(int argc, char **argv) return exit_stress(argv[2], atoi(argv[3])); } #endif + /* test_c_api_threads --mixed [ ...]: concurrent steps of mixed decks. */ + if (argc >= 4 && strcmp(argv[1], "--mixed") == 0) { + setvbuf(stdout, NULL, _IONBF, 0); + if (watchdog_start() != 0) return 1; + loops = env_seconds("CABLEDYN_THREAD_TEST_LOOPS", 1); + if (loops < 1) loops = 1; + for (loop = 0; loop < loops; ++loop) { + if (loops > 1) printf("loop %ld of %ld\n", loop + 1, loops); + current_phase = "concurrent Step (mixed decks)"; + if (check_mixed_steps(argc - 3, argv + 3, atoi(argv[2])) != 0) return 1; + } + printf("PASS c_api_threads --mixed\n"); + return 0; + } if (argc != 4) { fprintf(stderr, "usage: test_c_api_threads \n"); return 2; diff --git a/tests/test_thread_safe_sources.py b/tests/test_thread_safe_sources.py new file mode 100644 index 00000000..bc69b0b1 --- /dev/null +++ b/tests/test_thread_safe_sources.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Source audit of the storage that concurrent models could share. + +Separate models (C API handles, Python objects) may step on several threads at once, so +the Fortran sources of the library and the driver (src/, app/) must keep every model's data +in the model. Compiler-independent checks, so that a gfortran build catches what only an +ifx build would show at run time (test_c_api_threads): + +* no internal procedure is a procedure value (an actual argument, a keyword argument or a + pointer target): ifx calls such a closure through a trampoline kept in memory that every + thread shares; +* no local variable is initialised in its declaration (an implicit SAVE: one copy for every + thread), and no DATA or COMMON; +* every variable in static storage (SAVE, module variables) is one of the reviewed + process-wide entries below, with the reason it is not per-model state; +* the build makes every other local automatic (CMakeLists.txt: /Qauto, -auto, -frecursive). +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SOURCES = sorted( + list((ROOT / "src").rglob("*.f90")) + list((ROOT / "app").rglob("*.f90")), +) + +# (file, variable): why the process-wide storage is not model state. +REVIEWED_STATIC = { + ("CableDyn_CAPI.f90", "g_handle_registry"): "live-handle registry, under the registry lock", + ("CableDyn_CAPI.f90", "g_handle_count"): "live-handle registry, under the registry lock", + ("CableDyn_OF.f90", "Inst"): "OpenFAST instance registry, resized at initialisation only", + ("CableDyn_OF.f90", "g_serial"): "OpenFAST instance generation counter, at initialisation only", + ("CableDyn_DeckDriver.f90", "body_static_pass_limit"): "test hook of the standalone body statics", + ("CableDyn_DeckDriver.f90", "probe_armed"): "test hook of the standalone multibody march", + ("CableDyn_DeckDriver.f90", "probe_v0"): "test hook of the standalone multibody march", + ("CableDyn_DeckDriver.f90", "probe_w0"): "test hook of the standalone multibody march", + ("CableDyn_DeckDriver.f90", "probe_rec"): "test hook of the standalone multibody march", + ("CableDyn_DeckDriver.f90", "warned"): "warn-once flag of a message, under an OpenMP critical", + ("CableDyn_Profile.f90", "*"): "opt-in run profile (CABLEDYN_PROFILE), written only when armed", + ("CableDyn_HermiteCableDynamic.f90", "prof_*"): "opt-in step profile, written only when armed", + ("CableDyn_HermiteCableDynamic.f90", "n_substep_recoveries"): "process-wide diagnostics tally", + ("CableDyn_System.f90", "n_fallback_entries"): "process-wide diagnostics tally", + ("CableDyn_CosseratAssemble.f90", "CD_COSASM_*"): "process-wide diagnostics tallies", + ("CableDyn_CosseratDynamic.f90", "CD_COSDYN_*"): "process-wide diagnostics tallies", + ("cabledyn.f90", "printed"): "the driver program prints its profile once", +} + +DECL = re.compile( + r"^(integer|real|logical|character|complex|double\s+precision|type\s*\(|class\s*\(|procedure\s*\()", + re.I, +) +UNIT = re.compile( + r"^(?:(?:pure|elemental|impure|recursive|non_recursive|module)\s+)*" + r"(?:(?:integer|real|logical|character|complex|double\s+precision|type\s*\([^)]*\))" + r"(?:\s*\([^)]*\))?\s+)?(?:(?:pure|elemental|impure|recursive)\s+)*" + r"(subroutine|function)\s+(\w+)", + re.I, +) + + +def statements(path: Path): + """(line number, statement) with comments, continuations and semicolons resolved.""" + buf, start = "", None + for no, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + if raw.lstrip().startswith("#"): + continue + out, quote = [], None + for ch in raw: + if quote: + out.append(ch) + if ch == quote: + quote = None + elif ch in "'\"": + quote = ch + out.append(ch) + elif ch == "!": + break + else: + out.append(ch) + text = "".join(out).strip() + if not text: + continue + if buf and text.startswith("&"): + text = text[1:] + if start is None: + start = no + if text.endswith("&"): + buf += text[:-1] + " " + continue + line, buf, line_no, start = buf + text, "", start, None + for stmt in split_top(line, ";"): + if stmt.strip(): + yield line_no, stmt.strip() + + +def split_top(text: str, sep: str) -> list[str]: + parts, depth, cur, quote = [], 0, [], None + for ch in text: + if quote: + cur.append(ch) + if ch == quote: + quote = None + continue + if ch in "'\"": + quote = ch + elif ch in "([": + depth += 1 + elif ch in ")]": + depth -= 1 + elif ch == sep and depth == 0: + parts.append("".join(cur)) + cur = [] + continue + cur.append(ch) + parts.append("".join(cur)) + return parts + + +def without_strings(text: str) -> str: + return re.sub(r"'[^']*'|\"[^\"]*\"", "''", text) + + +class Scope: + def __init__(self, kind: str, name: str): + self.kind, self.name = kind, name + self.contains = False + self.internal: list[str] = [] + self.declared: set[str] = set() + self.body: list[tuple[int, str, Scope]] = [] + + +def scan(path: Path): + """Yield (kind, line, scope name, detail) findings of one file.""" + stack: list[Scope] = [] + in_type = in_interface = 0 + hosts: list[Scope] = [] + for no, stmt in statements(path): + low = stmt.lower() + if in_interface: + if re.match(r"^end\s*interface\b", low): + in_interface -= 1 + continue + if re.match(r"^(abstract\s+)?interface\b", low): + in_interface += 1 + continue + if in_type: + if re.match(r"^end\s*type\b", low): + in_type -= 1 + continue + if re.match(r"^type\b(?!\s*\()(?!\s+is\b)", low): + in_type += 1 + continue + if re.match(r"^(module|submodule\s*\([^)]*\))\s+\w+\s*$", low) and not re.match( + r"^module\s+(procedure|subroutine|function)\b", low + ): + stack.append(Scope("module", low.split()[-1])) + continue + if re.match(r"^program\s+\w+", low): + stack.append(Scope("program", low.split()[1])) + continue + m = UNIT.match(stmt) + if m and not low.startswith("end"): + if stack and stack[-1].kind in ("unit", "program") and stack[-1].contains: + stack[-1].internal.append(m.group(2).lower()) + stack.append(Scope("unit", m.group(2))) + continue + if re.match(r"^end\s*(subroutine|function|module|program|submodule)\b|^end$", low): + if stack: + done = stack.pop() + if done.kind in ("unit", "program") and done.internal: + hosts.append(done) + continue + if low == "contains": + if stack: + stack[-1].contains = True + continue + unit = next((s for s in reversed(stack) if s.kind in ("unit", "program")), None) + for scope in stack: + if scope.kind in ("unit", "program"): + scope.body.append((no, stmt, unit)) + where = unit.name if unit else (stack[-1].name if stack else "?") + if re.match(r"^(data\s+\w|common\b)", low): + yield "DATA/COMMON", no, where, stmt + continue + if re.match(r"^save\b(?!\s*=)", low): + yield "SAVE statement", no, where, stmt + continue + if not DECL.match(stmt) or "::" not in stmt: + continue + attrs, names = stmt.split("::", 1) + attrs_low = attrs.lower() + variables = [re.match(r"\s*(\w+)", n).group(1) for n in split_top(names, ",")] + if unit is not None: + unit.declared.update(v.lower() for v in variables) + if "parameter" in attrs_low: + continue + if unit is not None and unit.kind == "program": + continue # a main program's variables: one program, one thread + if unit is None or re.search(r"\bsave\b", attrs_low): + for name in variables: + yield "STATIC", no, where, name + continue + if "intent" in attrs_low or re.search(r"\bvalue\b", attrs_low): + continue + for item in split_top(names, ","): + body = item.replace("==", "") + if "=" in body: # an initialiser, "=> NULL()" included, implies SAVE + yield "INITIALISED LOCAL", no, where, stmt + break + for host in hosts: + names = set(host.internal) + for no, stmt, inside in host.body: + code = without_strings(stmt).lower() + # in its own body the name is the result; a local declaration hides it + for name in names - {inside.name.lower()} - inside.declared: + for m in re.finditer(r"(?|\w\s*=)$", before) and not re.match(r"^\s*$", before): + yield "CLOSURE", no, host.name, f"{name}: {stmt[:120]}" + + +def reviewed(file: str, name: str) -> bool: + for (f, pattern), _ in REVIEWED_STATIC.items(): + if f != file: + continue + if pattern == "*" or name == pattern: + return True + if pattern.endswith("*") and name.lower().startswith(pattern[:-1].lower()): + return True + return False + + +class ThreadSafeSources(unittest.TestCase): + def setUp(self): + self.findings = [(p.name, *f) for p in SOURCES for f in scan(p)] + self.assertGreater(len(SOURCES), 40) + + def test_no_closures(self): + bad = [f for f in self.findings if f[1] == "CLOSURE"] + self.assertEqual(bad, [], "internal procedures passed as procedure values") + + def test_no_implicit_static_storage(self): + bad = [ + f + for f in self.findings + if f[1] in ("INITIALISED LOCAL", "DATA/COMMON", "SAVE statement") + ] + self.assertEqual(bad, [], "locals in static storage") + + def test_static_storage_is_reviewed(self): + bad = [f for f in self.findings if f[1] == "STATIC" and not reviewed(f[0], f[4])] + self.assertEqual(bad, [], "static storage not in REVIEWED_STATIC") + n = sum(1 for f in self.findings if f[1] == "STATIC") + print(f"{n} reviewed variables in static storage in {len(SOURCES)} files") + + def test_build_makes_locals_automatic(self): + cmake = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + for flag in ("-frecursive>", "/Qauto>", "-auto>"): + self.assertTrue(flag in cmake, f"CMakeLists.txt does not pass {flag[:-1]}") + + def test_audit_sees_a_closure_and_an_initialised_local(self): + # the checks themselves: a closure and an implicit SAVE in a scratch source + probe = Path(__file__).with_name("thread_safe_probe.f90.tmp") + probe.write_text( + "MODULE m\nCONTAINS\n SUBROUTINE host(x)\n REAL :: x\n INTEGER :: calls = 0\n" + " CALL apply(f, x)\n CALL apply(g=f)\n CONTAINS\n REAL FUNCTION f(y)\n" + " REAL :: y\n f = y + x\n END FUNCTION f\n END SUBROUTINE host\nEND MODULE m\n", + encoding="utf-8", + ) + try: + kinds = [f[0] for f in scan(probe)] + finally: + probe.unlink() + self.assertEqual(kinds.count("CLOSURE"), 2, kinds) + self.assertEqual(kinds.count("INITIALISED LOCAL"), 1, kinds) + + +if __name__ == "__main__": + unittest.main() From c9ba2810045d8b8d26616d511fd3ba58596caa40 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 06:28:33 +0900 Subject: [PATCH 07/19] fix(io): no OPEN that would fail, so a long name cannot end the ifx run-time The Intel Fortran run-time of ifx 2025.3.2 ends the process with STATUS_STACK_BUFFER_OVERRUN (0xC0000409) when an OPEN of a name of about 600 characters or more fails, while it formats the error. CD_Native_Path spells a path beyond the Windows limit in the extended-length (\\?\) form, so any failing OPEN of a long user-supplied name hit it: the input deck was covered by an INQUIRE (46f802d), the outputs were not. The release driver given an output root in a folder that does not exist, three 200-character folders deep, crashed with 0xC0000409 before this change. CableDyn_PathIO now answers in one place whether a runtime spelling opens, CD_Path_Openable: src/cabledyn_path.c opens it with the system (CreateFileA on the narrow name the run-time is given, OPEN_EXISTING for reading, OPEN_ALWAYS for writing, which leaves an existing file as it is; open() and fstat() elsewhere; a folder does not open) and closes it. CD_Open_Read and CD_Open_Write (STATUS 'REPLACE' or a given status) ask it before their OPEN and report 1 without an OPEN when it says no, and CD_Open_Input (UTF-8 names) goes through CD_Open_Read in place of the INQUIRE. Every OPEN of a user-supplied name uses them: the 25 output files of the deck driver, the range graphs, the aggregate's static profile, the keyword driver, the driver program (its write check, the file-identity check, the mixed route's output and the nModes scan) and, around their own OPENs, the OpenFAST adapter's native output and its temporary-file removal. The messages are unchanged. Gates: deck_reader_io opens names of 680 characters in a folder that does not exist for writing, for reading and as an input, a folder for reading, and runs a deck with such an output root; each returns a status or the "cannot open output file" message, and a short name still writes and reads back (a write probe leaves the file as it is). driver_cli_paths runs the driver with that output root: exit 1 and "cannot write output files" (0xC0000409 before, under ifx). Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 6 +++ app/cabledyn.f90 | 10 ++-- src/CableDyn_DeckDriver.f90 | 46 +++++++++--------- src/CableDyn_Driver.f90 | 9 ++-- src/CableDyn_OpenFAST_Aggregate.f90 | 3 +- src/CableDyn_PathIO.f90 | 74 +++++++++++++++++++++++------ src/CableDyn_RangeOutput.f90 | 3 +- src/cabledyn_path.c | 52 +++++++++++++++++++- src/openfast/CableDyn_OF.f90 | 12 ++++- tests/check_driver_paths.cmake | 16 +++++++ tests/test_deck_reader_io.f90 | 58 +++++++++++++++++++++- 11 files changed, 236 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b58ad75..505f03eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -460,6 +460,12 @@ All notable changes to CableDyn are recorded in this file. The format follows share: a free spar rod with a 55 m pinned cable (EI 2e4 N m^2) started 5.7e-2 m off its equilibrium, drifted 7e-2 m in 3 s and moved a leg tension by 2.3 %. Such a line now takes the static passes too (4 here); the rod holds its pose to the output's 8 digits. +- A failing `OPEN` of a file name of about 600 characters or more (the extended-length spelling of + a path beyond the Windows limit) ended an ifx-built program or the wheel's DLL with + `STATUS_STACK_BUFFER_OVERRUN` inside the Intel Fortran run-time, for example an output root in + a folder that does not exist. Every `OPEN` of a user-supplied name now first asks the system + whether the file opens (`CD_Path_Openable`) and reports the failure without attempting the + `OPEN`; the messages are unchanged. - Concurrent steps of separate handles crashed the ifx builds with access violations: an `EI = 0` line model passed its load and added-mass callbacks to the integrator as internal procedures, and ifx calls such a closure through a trampoline kept in memory every thread shares, so two diff --git a/app/cabledyn.f90 b/app/cabledyn.f90 index 9accf8a1..3f83766b 100644 --- a/app/cabledyn.f90 +++ b/app/cabledyn.f90 @@ -24,7 +24,7 @@ PROGRAM cabledyn CD_Classify_Dynamic_Completion, CD_DECKDRV_OK, & CD_DECKDRV_BADINPUT, CD_DECKDRV_SOLVEFAIL, CD_DECK_PATHLEN USE CableDyn_PathIO, ONLY: CD_Get_Argument, CD_Native_Path, CD_Lock_Path, CD_PATH_OK, & - CD_LOCK_ACQUIRED, CD_LOCK_HELD + CD_LOCK_ACQUIRED, CD_LOCK_HELD, CD_Open_Read, CD_Open_Write USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, & CD_AGG_NMovingPoints, CD_AGG_GetMovingPointMesh, & CD_AGG_Step_Moving, CD_AGG_CalcOutput, CD_AGG_End, & @@ -271,7 +271,7 @@ SUBROUTINE check_output_root(deck, deck_spelling, root, root_spelling) ! A probe file beside the outputs proves the directory exists and is writable. probe = root_spelling//'.write_check.tmp' INQUIRE (FILE=probe, EXIST=exists) - OPEN (NEWUNIT=unit, FILE=probe, STATUS='UNKNOWN', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, probe, ios, status='UNKNOWN') IF (ios /= 0) THEN WRITE (error_unit, '(A)') PROG//': cannot write output files at "'//root// & '" (check that the directory exists and is writable)' @@ -423,7 +423,7 @@ LOGICAL FUNCTION same_file(a, b) RESULT(same) IF (.NOT. (exists_a .AND. exists_b)) RETURN same = normalized_path(a) == normalized_path(b) IF (same) RETURN - OPEN (NEWUNIT=unit, FILE=a, STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL CD_Open_Read(unit, a, ios) IF (ios /= 0) RETURN opened = .FALSE. INQUIRE (FILE=b, OPENED=opened) @@ -600,7 +600,7 @@ SUBROUTINE run_mixed_held_deck(deck, root, dt, has_dt, run_time, has_run_time, h acceleration = CD_ZERO END IF dynamic_path = TRIM(root)//'.out' - OPEN (NEWUNIT=unit, FILE=TRIM(dynamic_path), STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, TRIM(dynamic_path), ios) IF (ios /= 0) THEN run_stat = CD_DECKDRV_BADINPUT run_msg = 'CableDyn_driver: cannot open mixed dynamic output: '//TRIM(dynamic_path) @@ -726,7 +726,7 @@ LOGICAL FUNCTION deck_requests_modes(deck) RESULT(requested) REAL(wp) :: x requested = .FALSE. in_options = .FALSE. - OPEN (NEWUNIT=u, FILE=deck, STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL CD_Open_Read(u, deck, ios) IF (ios /= 0) RETURN DO READ (u, '(A)', IOSTAT=ios) line diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 731aea62..b1731ce3 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -157,7 +157,7 @@ MODULE CableDyn_DeckDriver USE CableDyn_RigidKinematics, ONLY: CD_Rigid_Advance_Newmark, CD_RIGID_OK, CD_RIGID_NEWMARK_GAMMA, & CD_RIGID_NEWMARK_BETA USE CableDyn_SO3, ONLY: CD_Log_SO3, CD_Exp_SO3 - USE CableDyn_PathIO, ONLY: CD_Open_Input, CD_Native_Path, CD_Strip_BOM + USE CableDyn_PathIO, ONLY: CD_Open_Input, CD_Open_Write, CD_Native_Path, CD_Strip_BOM USE CableDyn_Profile, ONLY: CD_Profile_Enter, CD_Profile_Step, CD_PROF_INPUT, CD_PROF_INIT, CD_PROF_FLUID, & CD_PROF_SOLVE, CD_PROF_CHECK, CD_PROF_OUTPUT, CD_PROF_PROGRESS, CD_PROF_FINAL USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_IS_FINITE @@ -18550,7 +18550,7 @@ SUBROUTINE write_out(out_root, channels, lines, points, ne, q_all, q_off, ten_al END DO END IF path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); RETURN END IF @@ -18609,7 +18609,7 @@ SUBROUTINE write_static_config_out(out_root, lines, ne, q_all, q_off, ten_all, t ErrMsg = '' tab = char_tab() path = TRIM(out_root)//'.static.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open static-configuration output file: '//TRIM(path)); RETURN END IF @@ -18697,7 +18697,7 @@ SUBROUTINE write_static_line_position_file(out_root, line_id, nelem, q_line, Err ErrStat = CD_DECKDRV_OK ErrMsg = '' path = TRIM(out_root)//'.Line'//TRIM(int_to_str(line_id))//'.p.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open line position output file: '//TRIM(path)); RETURN END IF @@ -18724,7 +18724,7 @@ SUBROUTINE write_static_line_tension_file(out_root, line_id, nelem, tension_line ErrStat = CD_DECKDRV_OK ErrMsg = '' path = TRIM(out_root)//'.Line'//TRIM(int_to_str(line_id))//'.t.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open line tension output file: '//TRIM(path)); RETURN END IF @@ -18774,7 +18774,7 @@ SUBROUTINE open_dynamic_line_outputs(out_root, lines, models, pos_units, ten_uni ne = nnode - 1 IF (line_output_has_flag(lines(i)%outputs, 'p')) THEN path = TRIM(out_root)//'.Line'//TRIM(int_to_str(lines(i)%id))//'.p.out' - OPEN (NEWUNIT=pos_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(pos_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open dynamic line position output file: '//TRIM(path)); RETURN @@ -18790,7 +18790,7 @@ SUBROUTINE open_dynamic_line_outputs(out_root, lines, models, pos_units, ten_uni END IF IF (line_output_has_flag(lines(i)%outputs, 't')) THEN path = TRIM(out_root)//'.Line'//TRIM(int_to_str(lines(i)%id))//'.t.out' - OPEN (NEWUNIT=ten_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(ten_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open dynamic line tension output file: '//TRIM(path)); RETURN @@ -18851,7 +18851,7 @@ SUBROUTINE open_dynamic_system_line_outputs(out_root, lines, system, pos_units, ne = nnode - 1 IF (line_output_has_flag(lines(i)%outputs, 'p')) THEN path = TRIM(out_root)//'.Line'//TRIM(int_to_str(lines(i)%id))//'.p.out' - OPEN (NEWUNIT=pos_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(pos_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open system dynamic line position output file: '//TRIM(path)); RETURN @@ -18867,7 +18867,7 @@ SUBROUTINE open_dynamic_system_line_outputs(out_root, lines, system, pos_units, END IF IF (line_output_has_flag(lines(i)%outputs, 't')) THEN path = TRIM(out_root)//'.Line'//TRIM(int_to_str(lines(i)%id))//'.t.out' - OPEN (NEWUNIT=ten_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(ten_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open system dynamic line tension output file: '//TRIM(path)); RETURN @@ -19137,7 +19137,7 @@ SUBROUTINE open_line_lift_file(out_root, line_id, nnode, unit, ErrStat, ErrMsg, ErrStat = CD_DECKDRV_OK ErrMsg = '' path = TRIM(out_root)//'.Line'//TRIM(int_to_str(line_id))//'.V.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN unit = 0 CALL fail(ErrStat, ErrMsg, 'cannot open dynamic line VIV lift output file: '//TRIM(path)); RETURN @@ -19178,7 +19178,7 @@ SUBROUTINE open_dynamic_rod_outputs(out_root, rods, pos_units, ErrStat, ErrMsg) IF (.NOT. rod_outputs_requested(rods(i)%outputs)) CYCLE IF (rod_output_has_flag(rods(i)%outputs, 'p')) THEN path = TRIM(out_root)//'.Rod'//TRIM(int_to_str(rods(i)%id))//'.p.out' - OPEN (NEWUNIT=pos_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(pos_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_rod_outputs(pos_units) CALL fail(ErrStat, ErrMsg, 'cannot open dynamic rod position output file: '//TRIM(path)); RETURN @@ -19307,7 +19307,7 @@ SUBROUTINE write_dynamic_out(out_root, channels, lines, points, opts, models, co lift_units=lift_units) IF (ErrStat /= CD_DECKDRV_OK) RETURN path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); RETURN @@ -19463,7 +19463,7 @@ SUBROUTINE write_system_dynamic_out(out_root, channels, lines, points, opts, sys lift_units=lift_units) IF (ErrStat /= CD_DECKDRV_OK) RETURN path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); RETURN @@ -19852,7 +19852,7 @@ SUBROUTINE write_rigid6_dynamic_out(out_root, channels, bodies, lines, points, o bathymetry=bathymetry) IF (ErrStat /= CD_DECKDRV_OK) RETURN path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); RETURN END IF @@ -20028,7 +20028,7 @@ SUBROUTINE write_rod_dynamic_out(out_root, channels, rod_types, rods, lines, poi bathymetry=bathymetry) IF (ErrStat /= CD_DECKDRV_OK) RETURN path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)) RETURN @@ -21173,7 +21173,7 @@ SUBROUTINE write_objects_dynamic_out(out_root, channels, bodies, rod_types, rods rst(k)%a, rst(k)%alpha, ErrStat, ErrMsg, rod=rst(k), bathymetry=bathymetry) IF (ErrStat /= CD_DECKDRV_OK) RETURN END DO - OPEN (NEWUNIT=unit, FILE=TRIM(out_root)//'.out', STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, TRIM(out_root)//'.out', ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(out_root)//'.out'); RETURN END IF @@ -21891,7 +21891,7 @@ SUBROUTINE write_multibody_dynamic_out(deck_path, out_root, channels, types, bod ! ---- output ---- nstep = NINT(opts%tmax/opts%dtM) path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); GOTO 900 END IF @@ -30977,7 +30977,7 @@ SUBROUTINE write_hermite_dynamic_out(out_root, channels, lines, points, opts, ca CALL range_setup_planned(ranges, lines, channels, opts, ErrStat, ErrMsg, cables=cables, bathymetry=bathymetry) IF (ErrStat /= CD_DECKDRV_OK) RETURN path = TRIM(out_root)//'.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); RETURN END IF @@ -31312,7 +31312,7 @@ SUBROUTINE write_hermite_static_profile(out_root, lines, cables, ErrStat, ErrMsg CALL fail(ErrStat, ErrMsg, 'Hermite static-profile cable count does not match line count'); RETURN END IF path = TRIM(out_root)//'.static.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open Hermite static profile: '//TRIM(path)); RETURN END IF @@ -31406,7 +31406,7 @@ SUBROUTINE write_hermite_static_element_profile(out_root, lines, cables, ErrStat CALL fail(ErrStat, ErrMsg, 'Hermite static-element cable count does not match line count'); RETURN END IF path = TRIM(out_root)//'.elements.out' - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open Hermite static-element profile: '//TRIM(path)); RETURN END IF @@ -31715,7 +31715,7 @@ SUBROUTINE open_dynamic_hermite_line_outputs(out_root, lines, cables, pos_units, IF (.NOT. line_outputs_requested(lines(i)%outputs)) CYCLE IF (line_output_has_flag(lines(i)%outputs, 'p')) THEN path = TRIM(out_root)//'.Line'//TRIM(int_to_str(lines(i)%id))//'.p.out' - OPEN (NEWUNIT=pos_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(pos_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open Hermite line position output: '//TRIM(path)); RETURN @@ -31740,7 +31740,7 @@ SUBROUTINE open_dynamic_hermite_line_outputs(out_root, lines, cables, pos_units, END IF IF (line_output_has_flag(lines(i)%outputs, 't')) THEN path = TRIM(out_root)//'.Line'//TRIM(int_to_str(lines(i)%id))//'.t.out' - OPEN (NEWUNIT=ten_units(i), FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(ten_units(i), path, ios) IF (ios /= 0) THEN CALL close_dynamic_line_outputs(pos_units, ten_units, lift_units) CALL fail(ErrStat, ErrMsg, 'cannot open Hermite line tension output: '//TRIM(path)); RETURN @@ -32174,7 +32174,7 @@ SUBROUTINE write_modes_file(out_root, lines, res, ErrStat, ErrMsg) ErrStat = CD_DECKDRV_OK ErrMsg = '' tb = char_tab() - OPEN (NEWUNIT=unit, FILE=TRIM(out_root)//'.modes.out', STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, TRIM(out_root)//'.modes.out', ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open modal output file: '//TRIM(out_root)//'.modes.out'); RETURN END IF diff --git a/src/CableDyn_Driver.f90 b/src/CableDyn_Driver.f90 index a68c39a8..e7f6eb9d 100644 --- a/src/CableDyn_Driver.f90 +++ b/src/CableDyn_Driver.f90 @@ -34,6 +34,7 @@ MODULE CableDyn_Driver !! CableDyn_Static path; tensions are recovered with !! CD_Compute_Cable_Tension on the converged state. USE CableDyn_Precision, ONLY: wp, CD_ZERO, CD_ONE, CD_All_Finite, CD_Is_Finite + USE CableDyn_PathIO, ONLY: CD_Open_Read, CD_Open_Write USE CableDyn_Loads, ONLY: CD_Submerged_Weight, CD_Assemble_Distributed_Load USE CableDyn_Assemble, ONLY: CD_Compute_Cable_Tension USE CableDyn_Static, ONLY: CableSolverConfig, CD_Static_Cable_Solve, & @@ -333,7 +334,7 @@ SUBROUTINE parse_input(path, gravity, rho_water, tension_only, has_seabed, z_flo ! error return and silences -Wmaybe-uninitialized. ALLOCATE (nodes(3, 0), conn(2, 0), l0(0), ea(0), mass_pl(0), diam(0), fixed_dofs(0)) - OPEN (NEWUNIT=unit, FILE=path, STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL CD_Open_Read(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open input file: '//TRIM(path)) RETURN @@ -515,7 +516,7 @@ SUBROUTINE parse_line_deck(path, gravity, rho_water, tension_only, has_seabed, z ALLOCATE (line_types(0), sections(0)) ALLOCATE (factors(4)); factors = [0.25_wp, 0.5_wp, 0.75_wp, CD_ONE] - OPEN (NEWUNIT=unit, FILE=path, STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL CD_Open_Read(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open input file: '//TRIM(path)); RETURN END IF @@ -688,7 +689,7 @@ SUBROUTINE CD_Deck_Is_Line_Object(input_path, is_line, ErrStat, ErrMsg) is_line = .FALSE. ErrStat = 0 ErrMsg = '' - OPEN (NEWUNIT=unit, FILE=input_path, STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL CD_Open_Read(unit, input_path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open input file: '//TRIM(input_path)); RETURN END IF @@ -747,7 +748,7 @@ SUBROUTINE write_csv(path, q, conn, tension, converged, stalled, at_floor, n_ite ErrMsg = '' n_nodes = SIZE(q)/3 n_elem = SIZE(conn, 2) - OPEN (NEWUNIT=unit, FILE=path, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, path, ios) IF (ios /= 0) THEN CALL fail(ErrStat, ErrMsg, 'cannot open output file: '//TRIM(path)); RETURN END IF diff --git a/src/CableDyn_OpenFAST_Aggregate.f90 b/src/CableDyn_OpenFAST_Aggregate.f90 index 62d59dcb..5f68343a 100644 --- a/src/CableDyn_OpenFAST_Aggregate.f90 +++ b/src/CableDyn_OpenFAST_Aggregate.f90 @@ -42,6 +42,7 @@ MODULE CableDyn_OpenFAST_Aggregate !! dt that differs from it (a mismatched size would silently desync the cables, whose !! generalised-alpha step carries the Init dt, from the mooring columns). USE CableDyn_Precision, ONLY: wp, CD_ZERO, CD_ONE, CD_All_Finite + USE CableDyn_PathIO, ONLY: CD_Open_Write USE CableDyn_FatalReport, ONLY: CD_Fatal_Thread_Init USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: int64 USE CableDyn_Linalg, ONLY: CD_Blas_Runtime_Check, CD_LINALG_OK @@ -2675,7 +2676,7 @@ SUBROUTINE CD_AGG_WriteStaticProfile(self, path, ErrStat, ErrMsg) ErrMsg = 'CableDyn_OpenFAST_Aggregate: line map unavailable for the static profile' RETURN END IF - OPEN (NEWUNIT=unit, FILE=TRIM(path), STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, TRIM(path), ios) IF (ios /= 0) THEN ErrStat = CD_AGG_BADINPUT ErrMsg = 'CableDyn_OpenFAST_Aggregate: cannot open static profile: '//TRIM(path) diff --git a/src/CableDyn_PathIO.f90 b/src/CableDyn_PathIO.f90 index 5958270d..500cee6d 100644 --- a/src/CableDyn_PathIO.f90 +++ b/src/CableDyn_PathIO.f90 @@ -13,7 +13,8 @@ MODULE CableDyn_PathIO IMPLICIT NONE PRIVATE - PUBLIC :: CD_Get_Argument, CD_Native_Path, CD_Open_Input, CD_Path_Is_Device, CD_Lock_Path + PUBLIC :: CD_Get_Argument, CD_Native_Path, CD_Open_Input, CD_Open_Read, CD_Open_Write, CD_Path_Openable + PUBLIC :: CD_Path_Is_Device, CD_Lock_Path PUBLIC :: CD_Strip_BOM !> CD_Native_Path status: converted, a reserved device name, a name the ANSI code @@ -61,6 +62,12 @@ FUNCTION c_path_lock(in, in_len) RESULT(n) BIND(C, name='cabledyn_path_lock') INTEGER(C_INT), VALUE :: in_len INTEGER(C_INT) :: n END FUNCTION c_path_lock + FUNCTION c_path_probe(in, in_len, for_output) RESULT(n) BIND(C, name='cabledyn_path_probe') + IMPORT :: C_INT, C_CHAR + CHARACTER(KIND=C_CHAR), INTENT(IN) :: in(*) + INTEGER(C_INT), VALUE :: in_len, for_output + INTEGER(C_INT) :: n + END FUNCTION c_path_probe END INTERFACE CONTAINS @@ -160,8 +167,7 @@ SUBROUTINE CD_Open_Input(unit, path, ios, reason) CHARACTER(*), INTENT(IN) :: path CHARACTER(*), INTENT(OUT) :: reason CHARACTER(:), ALLOCATABLE :: native - INTEGER :: stat, iq - LOGICAL :: exists + INTEGER :: stat unit = -1 CALL CD_Native_Path(path, native, stat, reason) @@ -169,19 +175,59 @@ SUBROUTINE CD_Open_Input(unit, path, ios, reason) ios = 1 RETURN END IF - ! A missing file is found by INQUIRE, not by a failing OPEN: the Intel Fortran run-time - ! (ifx 2025.3) ends the process with a stack buffer overrun when an OPEN of an - ! extended-length (\\?\) name of about 600 characters or more fails, as it formats the - ! error; INQUIRE of the same name returns. - exists = .TRUE. - INQUIRE (FILE=native, EXIST=exists, IOSTAT=iq) - IF (iq == 0 .AND. .NOT. exists) THEN - ios = 1 - RETURN - END IF - OPEN (NEWUNIT=unit, FILE=native, STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL CD_Open_Read(unit, native, ios) END SUBROUTINE CD_Open_Input + SUBROUTINE CD_Open_Read(unit, name, ios) + !! OPEN the existing file name (a runtime spelling, such as one CD_Native_Path gave) for + !! sequential formatted reading. ios /= 0 on failure: the OPEN's IOSTAT, or 1 when + !! CD_Path_Openable refused the name and no OPEN was attempted. + INTEGER, INTENT(OUT) :: unit, ios + CHARACTER(*), INTENT(IN) :: name + + unit = -1 + ios = 1 + IF (.NOT. CD_Path_Openable(name, .FALSE.)) RETURN + OPEN (NEWUNIT=unit, FILE=name, STATUS='OLD', ACTION='READ', IOSTAT=ios) + END SUBROUTINE CD_Open_Read + + SUBROUTINE CD_Open_Write(unit, name, ios, status) + !! OPEN name (a runtime spelling: one CD_Native_Path gave, or an output root's spelling + !! with a suffix) for sequential formatted writing, STATUS 'REPLACE' or, given, status. + !! ios /= 0 on failure: the OPEN's IOSTAT, or 1 when CD_Path_Openable refused the name + !! and no OPEN was attempted. + INTEGER, INTENT(OUT) :: unit, ios + CHARACTER(*), INTENT(IN) :: name + CHARACTER(*), INTENT(IN), OPTIONAL :: status + + unit = -1 + ios = 1 + IF (.NOT. CD_Path_Openable(name, .TRUE.)) RETURN + IF (PRESENT(status)) THEN + OPEN (NEWUNIT=unit, FILE=name, STATUS=status, ACTION='WRITE', IOSTAT=ios) + ELSE + OPEN (NEWUNIT=unit, FILE=name, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + END IF + END SUBROUTINE CD_Open_Write + + LOGICAL FUNCTION CD_Path_Openable(name, for_output) RESULT(openable) + !! Whether the system opens name (a runtime spelling, trailing blanks ignored) for + !! reading an existing file or, with for_output, for writing (a missing file is then + !! created empty, an existing one left as it is). Every OPEN of a user-supplied name asks + !! here first and is not attempted when the answer is no: the Intel Fortran run-time + !! (ifx 2025.3, Windows) ends the process with a stack buffer overrun (0xC0000409) while + !! it formats the error of a failing OPEN of a name of about 600 characters or more (the + !! extended-length \\?\ spelling CD_Native_Path gives a long path), where an INQUIRE or + !! this probe returns. + CHARACTER(*), INTENT(IN) :: name + LOGICAL, INTENT(IN) :: for_output + INTEGER(C_INT) :: mode + + mode = 0_C_INT + IF (for_output) mode = 1_C_INT + openable = c_path_probe(name, INT(LEN_TRIM(name), C_INT), mode) == 0_C_INT + END FUNCTION CD_Path_Openable + PURE LOGICAL FUNCTION CD_Path_Is_Device(path) RESULT(is_device) !! True on Windows when any component of path is a reserved device name. CHARACTER(*), INTENT(IN) :: path diff --git a/src/CableDyn_RangeOutput.f90 b/src/CableDyn_RangeOutput.f90 index de2b6b96..7680cfa5 100644 --- a/src/CableDyn_RangeOutput.f90 +++ b/src/CableDyn_RangeOutput.f90 @@ -27,6 +27,7 @@ MODULE CableDyn_RangeOutput !! length the deformed chord length from the grounded end to the TDP (0 while no node !! beyond the grounded end node is grounded). USE CableDyn_Precision, ONLY: wp, CD_ZERO, CD_ONE + USE CableDyn_PathIO, ONLY: CD_Open_Write USE CableDyn_Bathymetry, ONLY: CD_BathymetryType, CD_Bathymetry_Floor, CD_Bathymetry_Is_Initialized, & CD_BATHY_OK USE CableDyn_SeabedContact, ONLY: CD_SEABED_CONTACT_BLEND @@ -522,7 +523,7 @@ SUBROUTINE CD_Range_Write_Files(set, out_root, ErrStat, ErrMsg) END IF WRITE (id_text, '(I0)') set%lines(il)%line_id path = TRIM(out_root)//'.Line'//TRIM(id_text)//'.range.out' - OPEN (NEWUNIT=unit, FILE=TRIM(path), STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL CD_Open_Write(unit, TRIM(path), ios) IF (ios /= 0) THEN ErrStat = CD_RANGE_BADINPUT ErrMsg = 'CableDyn_RangeOutput: cannot open range-graph output file: '//TRIM(path) diff --git a/src/cabledyn_path.c b/src/cabledyn_path.c index c3c605bf..3ba1983a 100644 --- a/src/cabledyn_path.c +++ b/src/cabledyn_path.c @@ -24,7 +24,11 @@ * the console or discards output; * cabledyn_path_lock * an exclusive lock file for an output root, released by the operating - * system when the process ends, however it ends. + * system when the process ends, however it ends; + * cabledyn_path_probe + * whether the system opens a runtime spelling for reading or for writing, asked + * before the Fortran OPEN so that an OPEN that would fail is never attempted + * (see CD_Path_Openable in src/CableDyn_PathIO.f90). * * On other systems names are UTF-8 byte strings that the runtime opens unchanged, * so the conversion is the identity and the lock uses an advisory flock(). @@ -52,6 +56,18 @@ int cabledyn_path_arg(int index, char *buf, int buflen); int cabledyn_path_native(const char *in, int in_len, int for_output, int reserve, char *out, int outlen); int cabledyn_path_is_device(const char *in, int in_len); int cabledyn_path_lock(const char *in, int in_len); +int cabledyn_path_probe(const char *in, int in_len, int for_output); + +/* The name s[0..n) as a NUL-terminated copy (malloc), or NULL. */ +static char *terminated(const char *s, int n) { + char *t; + if (s == NULL || n <= 0) return NULL; + t = (char *)malloc((size_t)n + 1); + if (t == NULL) return NULL; + memcpy(t, s, (size_t)n); + t[n] = '\0'; + return t; +} /* Copies n bytes and a terminating NUL when they fit; returns n or CD_PATH_ERR_BUFFER. */ static int copy_out(const char *src, int n, char *out, int outlen) { @@ -402,6 +418,24 @@ int cabledyn_path_lock(const char *in, int in_len) { return CD_LOCK_FAILED; } +/* 0 when the system opens the runtime spelling in[0..in_len) (the narrow name the Fortran + * OPEN is given) for reading an existing file, or for writing (for_output; a missing file + * is created, an existing one left as it is), else 1. The ANSI entry point reads the name + * as the runtime's own calls do. A directory is refused: without backup semantics it does + * not open. The handle is closed at once. */ +int cabledyn_path_probe(const char *in, int in_len, int for_output) { + char *name = terminated(in, in_len); + HANDLE h; + if (name == NULL) return 1; + h = CreateFileA(name, for_output ? GENERIC_WRITE : GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, + for_output ? OPEN_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + free(name); + if (h == INVALID_HANDLE_VALUE) return 1; + CloseHandle(h); + return 0; +} + #else /* !_WIN32 */ #include @@ -425,6 +459,22 @@ int cabledyn_path_native(const char *in, int in_len, int for_output, int reserve return copy_out(in, in_len, out, outlen); } +/* 0 when the system opens in[0..in_len) for reading an existing regular file (not a + * directory), or for writing (for_output; a missing file is created, an existing one left + * as it is), else 1. */ +int cabledyn_path_probe(const char *in, int in_len, int for_output) { + char *name = terminated(in, in_len); + struct stat st; + int fd, ok; + if (name == NULL) return 1; + fd = open(name, for_output ? (O_WRONLY | O_CREAT) : O_RDONLY, 0666); + free(name); + if (fd < 0) return 1; + ok = fstat(fd, &st) == 0 && !S_ISDIR(st.st_mode); + close(fd); + return ok ? 0 : 1; +} + static char *lock_name = NULL; static int lock_fd = -1; diff --git a/src/openfast/CableDyn_OF.f90 b/src/openfast/CableDyn_OF.f90 index 64cc4138..c4a56e8f 100644 --- a/src/openfast/CableDyn_OF.f90 +++ b/src/openfast/CableDyn_OF.f90 @@ -77,6 +77,7 @@ MODULE CableDyn USE CableDyn_Types USE NWTC_Library USE CableDyn_Precision, ONLY: wp + USE CableDyn_PathIO, ONLY: CD_Path_Openable USE CableDyn_Conventions, ONLY: CD_NATIVE_CHANNEL_FMT USE CableDyn_Hydro, ONLY: CD_Current_Profile_Velocity, CD_SeaState_Steady_Current, CD_HYDRO_OK USE CableDyn_DeckDriver, ONLY: CD_Deck_Query_dtM, CD_DECKDRV_OK, CD_Is_Line_Node_Channel, & @@ -359,8 +360,14 @@ SUBROUTINE open_native_outputs( id, root, t_start, ErrStat, ErrMsg, write_profil ! BACKSPACE and replace the abandoned row. OpenFOutFile opens write-only and ! therefore makes that standard record-positioning operation fail on gfortran. iomsg = '' - OPEN (un, FILE=TRIM(root)//'.out', STATUS='REPLACE', FORM='FORMATTED', & - ACTION='READWRITE', POSITION='REWIND', IOSTAT=ios, IOMSG=iomsg) + ! CD_Path_Openable: a failing OPEN of a long name ends the ifx run-time (CableDyn_PathIO) + IF (CD_Path_Openable(TRIM(root)//'.out', .TRUE.)) THEN + OPEN (un, FILE=TRIM(root)//'.out', STATUS='REPLACE', FORM='FORMATTED', & + ACTION='READWRITE', POSITION='REWIND', IOSTAT=ios, IOMSG=iomsg) + ELSE + ios = 1 + iomsg = 'The file cannot be created or written.' + END IF IF (ios /= 0) THEN CALL SetErrStat( ErrID_Fatal, 'Cannot open native output file "'//TRIM(root)// & '.out" for transactional read/write access. '//TRIM(iomsg), & @@ -5089,6 +5096,7 @@ END SUBROUTINE write_deck_copy SUBROUTINE delete_file( path ) CHARACTER(*), INTENT(IN) :: path INTEGER(IntKi) :: un, ios + IF (.NOT. CD_Path_Openable(TRIM(path), .FALSE.)) RETURN ! no OPEN that fails (CableDyn_PathIO) CALL GetNewUnit( un ) OPEN (un, FILE=TRIM(path), STATUS='OLD', IOSTAT=ios) IF (ios == 0) CLOSE (un, STATUS='DELETE', IOSTAT=ios) diff --git a/tests/check_driver_paths.cmake b/tests/check_driver_paths.cmake index 50aac37b..67b53205 100644 --- a/tests/check_driver_paths.cmake +++ b/tests/check_driver_paths.cmake @@ -5,6 +5,8 @@ # by a best-fit look-alike (café -> cafe); # * no output file may be the deck or a file the deck reads, however it is spelled; # * reserved Windows device names are refused instead of blocking on the console; +# * an output root beyond the path limit in a folder that does not exist is refused with +# the reason (exit 1), not a run-time crash; # * a second run on an output root that a live run holds is refused, and the lock # disappears with the run. if(DEFINED DELAYED_RUN) @@ -136,6 +138,20 @@ file(WRITE "${WORK}/auxclash_deck.dat" "${clash_text}") run_driver("auxclash_deck.dat" "auxclash") expect_refusal("output over the bathymetry file" "would overwrite the input file") +# --- an output root beyond the path limit in a folder that does not exist ---------------- +# Its runtime spelling (extended-length on Windows) is about 700 characters: a failing OPEN +# of such a name ended an ifx-built driver inside the Intel run-time (0xC0000409); it must +# be refused with the reason instead. +string(REPEAT "a" 200 seg_a) +string(REPEAT "b" 200 seg_b) +string(REPEAT "c" 200 seg_c) +file(WRITE "${WORK}/long_root_deck.dat" "${static_text}") +run_driver("long_root_deck.dat" "${WORK}/no_such_folder/${seg_a}/${seg_b}/${seg_c}/run") +if(NOT run_rc EQUAL 1 OR NOT run_err MATCHES "cannot write output files") + message(FATAL_ERROR "long output root in a missing folder: expected exit 1 and 'cannot write output files', " + "got rc=${run_rc}\n${run_err}") +endif() + # --- reserved Windows device names ----------------------------------------------------- if(WIN32) run_driver("CON" "dev_run") diff --git a/tests/test_deck_reader_io.f90 b/tests/test_deck_reader_io.f90 index c676fc3f..a58f50a5 100644 --- a/tests/test_deck_reader_io.f90 +++ b/tests/test_deck_reader_io.f90 @@ -7,10 +7,15 @@ PROGRAM test_deck_reader_io !! whitespace-only rows, ASCII whitespace separators), rejected characters (NUL and !! non-ASCII whitespace outside comments), whole-record section headers, row-level !! diagnostics that name the deck line, per-row OPTIONS validation (a shadowed invalid - !! row still fails), bathymetry grids in any row order, and reserved device names. + !! row still fails), bathymetry grids in any row order, reserved device names, and files + !! that do not open: a failing OPEN of a name of 600 characters or more ends an ifx-built + !! program inside the Intel run-time (0xC0000409), so the opens of names beyond the Windows + !! path limit in a folder that does not exist, and of a folder, must return a status (and + !! the deck run with such an output root a message) instead; this program then ends. USE CableDyn_Precision, ONLY: wp USE CableDyn_DeckDriver, ONLY: CD_Run_Deck_Driver, CD_Deck_Query_dtM, CD_DECKDRV_OK, CD_DECKDRV_BADINPUT - USE CableDyn_PathIO, ONLY: CD_Path_Is_Device, CD_Native_Path, CD_PATH_OK, CD_PATH_ERR_DEVICE + USE CableDyn_PathIO, ONLY: CD_Path_Is_Device, CD_Native_Path, CD_PATH_OK, CD_PATH_ERR_DEVICE, & + CD_Open_Read, CD_Open_Write, CD_Open_Input, CD_Path_Openable IMPLICIT NONE CHARACTER(*), PARAMETER :: ANCHOR = '1 Fixed 400.0 0.0 -50.0', SECTION = '1 chain 410.0 41' @@ -26,6 +31,7 @@ PROGRAM test_deck_reader_io CALL check_bathymetry_row_order() CALL check_waterkin_diagnostics() CALL check_device_names() + CALL check_files_that_do_not_open() CALL check_nonfinite_and_subnormal_values() CALL check_admissible_magnitudes() CALL check_strict_line_attachments() @@ -284,6 +290,54 @@ SUBROUTINE check_device_names() 'reserved Windows device') END SUBROUTINE check_device_names + SUBROUTINE check_files_that_do_not_open() + !! Opens that fail return a status without attempting the OPEN (CD_Path_Openable): a + !! folder, and names of about 680 characters (three 200-character folders that do not + !! exist, spelt for the runtime as CD_Native_Path spells them, extended-length on Windows) + !! for writing, for reading and as a deck run's output root. A short name still writes + !! and reads back, and a probe for writing leaves an existing file as it is. + CHARACTER(:), ALLOCATABLE :: native, long_name + CHARACTER(512) :: why + CHARACTER(64) :: line + INTEGER :: stat, unit, ios, es + CHARACTER(1024) :: em + LOGICAL :: conv + + long_name = 'reader_missing_folder/'//REPEAT('a', 200)//'/'//REPEAT('b', 200)//'/'//REPEAT('c', 200)//'/run' + CALL CD_Native_Path(long_name, native, stat, why, for_output=.TRUE.) + CALL require(stat == CD_PATH_OK .AND. LEN(native) >= LEN(long_name), & + 'a long output name has a runtime spelling: '//TRIM(why)) + IF (stat /= CD_PATH_OK) RETURN + WRITE (*, '(A,I0,A)') ' files that do not open: a runtime spelling of ', LEN(native), ' characters' + CALL require(.NOT. CD_Path_Openable(native//'.out', .TRUE.), 'a name in a missing folder does not open') + CALL CD_Open_Write(unit, native//'.out', ios) + CALL require(ios /= 0, 'writing a long name in a missing folder fails with a status') + CALL CD_Open_Read(unit, native//'.out', ios) + CALL require(ios /= 0, 'reading a long missing name fails with a status') + CALL CD_Open_Input(unit, long_name//'.dat', ios, why) + CALL require(ios /= 0, 'a long missing input fails with a status') + CALL CD_Open_Read(unit, '.', ios) + CALL require(ios /= 0, 'a folder does not open for reading') + CALL write_bytes('reader_long_root.dat', chain_deck(ANCHOR, '', 'FairTen1')) + CALL CD_Run_Deck_Driver('reader_long_root.dat', native, conv, es, em) + CALL require(es /= CD_DECKDRV_OK .AND. INDEX(em, 'cannot open output file') > 0, & + 'a deck run with a long output root in a missing folder reports it: '//TRIM(em(1:200))) + ! a short name still opens, and a write probe leaves the file as it is + CALL CD_Open_Write(unit, 'reader_open_probe.txt', ios) + CALL require(ios == 0, 'a short name opens for writing') + IF (ios /= 0) RETURN + WRITE (unit, '(A)') 'kept' + CLOSE (unit) + CALL require(CD_Path_Openable('reader_open_probe.txt', .TRUE.), 'an existing file opens for writing') + CALL CD_Open_Read(unit, 'reader_open_probe.txt', ios) + CALL require(ios == 0, 'a short name opens for reading') + IF (ios /= 0) RETURN + line = '' + READ (unit, '(A)', IOSTAT=ios) line + CLOSE (unit, STATUS='DELETE') + CALL require(ios == 0 .AND. line == 'kept', 'a write probe leaves the file as it is') + END SUBROUTINE check_files_that_do_not_open + SUBROUTINE check_nonfinite_and_subnormal_values() !! Every number of an OPTIONS row and of a numeric table column must be finite and !! normal: "x < lo .OR. x > hi" is false for NaN, so a NaN must never reach a range From c1b8548ca1771fe28b719c922c35a97c2a4a3032 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 04:23:48 +0900 Subject: [PATCH 08/19] build(windows): /fp:precise for the static Intel release The static release compiled CableDyn with the Intel default /fp:fast (only the reference LAPACK took /fp:precise). That model lets the compiler reassociate sums, divide by multiplying with a reciprocal and flush subnormals to zero, each differently at every inlined (/Qipo) call site, so one expression rounds differently on two code paths. Under Intel ifx 2025.3.2 the full test suite of the release configuration then failed gates that hold two routes to the same bits: hermite_cable_control (A), syrope (impl:commit-bit-identical), model (committed-side twin), openfast_aggregate (zero CONTROL command against an uncontrolled cable, restore), control_torsion (R, S), two_moving_ends (Z, a held Coupled End B against a Fixed one); profile summed 0.030 + 0.005 s to below 0.035 s; clamped_cable_ends' elastica secant stalled on equal residuals and wrote NaN into its deck; deck_reader_io read subnormal deck values as zero. With /fp:precise every one of them passes. The first five and the last two fail on dev (6195432) as well; control_torsion belongs to feat/torsion-routes-a, two_moving_ends to feat/two-moving-ends. Signed-off-by: Jae Hoon Seo --- CMakeLists.txt | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6126bda1..fba97db2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,7 +45,15 @@ if(CABLEDYN_STATIC_WINDOWS_RELEASE) # then holds IPO objects, so it links only through an IPO-capable IFX link (the # driver below, or the OpenFAST Release|x64 project, which enables whole-program # optimisation). - string(APPEND CMAKE_Fortran_FLAGS " /libs:static /heap-arrays:1024 /Qipo") + # + # /fp:precise: IFX defaults to /fp:fast, which lets it reassociate sums, replace a division by + # a multiplication with the reciprocal, and flush subnormals to zero, differently at every + # inlined call site. The same expression then rounds differently on two code paths, so the + # gates that hold two routes to the same bits (a zero control command and an uncontrolled + # cable, a held Coupled End B and a Fixed one, a committed and a re-derived torque) fail, a + # subnormal deck value reads as zero, and a secant iteration can stall on equal residuals. + # The reference LAPACK is built with /fp:precise as well. + string(APPEND CMAKE_Fortran_FLAGS " /libs:static /heap-arrays:1024 /Qipo /fp:precise") # CMake does not pass the compile flags to an IFX executable link on Windows. The shared # library (the Windows wheel's cabledyn.dll) links the same IPO objects, so it needs the # flag as well: without it IFX hands the intermediate objects to link.exe (LNK1107). From 585617a475dc0e14f3c07292aaeb505dd717c985 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 07:25:05 +0900 Subject: [PATCH 09/19] build(openfast): automatic local variables in the Visual Studio project The OpenFAST Visual Studio project compiles the CableDyn adapter (CableDyn_Types.f90, CableDyn_OF.f90) itself. Its OpenMP configurations get automatic locals from /Qopenmp, the others did not: there ifx keeps fixed-size local arrays and CHARACTER locals in static storage, which every thread shares. Every configuration (Debug, Release, OpenMP, Double, Matlab) now sets LocalVariableStorage="localStorageAutomatic" (/Qauto, the setting's name in the Intel project system), as the CMake build of the core does with every compiler, so all builds are uniform. thread_safe_sources checks every compiler tool of the template. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 3 ++- integration/openfast/README.md | 4 ++++ integration/openfast/vs-build/CableDyn.vfproj.in | 16 ++++++++-------- tests/test_thread_safe_sources.py | 11 ++++++++++- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 505f03eb..28f7c480 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -480,7 +480,8 @@ All notable changes to CableDyn are recorded in this file. The format follows while other handles stepped stopped with "tangent assembly failed" or "band scatter" errors (gfortran builds were not affected: `-fopenmp` makes every local automatic). Every build now makes local variables automatic, `/Qauto` (`-auto`) with ifx and `-frecursive` with gfortran, - which `-fopenmp` already implied, so the default gfortran build is unchanged. The release + which `-fopenmp` already implied, so the default gfortran build is unchanged, and so does every + configuration of the OpenFAST Visual Studio project (`LocalVariableStorage`). The release benchmark decks run as fast or faster (0.3 to 21 %); ifx results change at round-off (with `/fp:precise` every example is bit-identical). - In OpenFAST, Free Rigid6 bodies and Free, Pinned and CoupledPinned rods started their first diff --git a/integration/openfast/README.md b/integration/openfast/README.md index 17373be4..19b72aba 100644 --- a/integration/openfast/README.md +++ b/integration/openfast/README.md @@ -48,6 +48,10 @@ For the static Windows release, pass a clean, unpatched checkout to [Installation](../../doc/installation.rst)). Its Visual Studio project compiles the CableDyn adapter with `/heap-arrays:1024`, as the static CMake build compiles the CableDyn core, so arrays whose size is known only at run time are placed on the heap rather than on the `openfast.exe` stack. +Every configuration also makes local variables automatic (`/Qauto`, as the CMake build of the +core does with every compiler): without OpenMP, ifx keeps fixed-size local arrays and `CHARACTER` +locals in static storage, which every thread shares, and the turbines of a FAST.Farm run, like +separate C API handles, may step on several threads at once. ## License of modified files diff --git a/integration/openfast/vs-build/CableDyn.vfproj.in b/integration/openfast/vs-build/CableDyn.vfproj.in index 2b3b99c0..3be6d8e2 100644 --- a/integration/openfast/vs-build/CableDyn.vfproj.in +++ b/integration/openfast/vs-build/CableDyn.vfproj.in @@ -5,35 +5,35 @@ - + - + - + - + - + - + - + - + diff --git a/tests/test_thread_safe_sources.py b/tests/test_thread_safe_sources.py index bc69b0b1..892342a7 100644 --- a/tests/test_thread_safe_sources.py +++ b/tests/test_thread_safe_sources.py @@ -15,7 +15,8 @@ thread), and no DATA or COMMON; * every variable in static storage (SAVE, module variables) is one of the reviewed process-wide entries below, with the reason it is not per-model state; -* the build makes every other local automatic (CMakeLists.txt: /Qauto, -auto, -frecursive). +* the build makes every other local automatic (CMakeLists.txt: /Qauto, -auto, -frecursive; + the OpenFAST Visual Studio project: LocalVariableStorage in every configuration). """ from __future__ import annotations @@ -265,6 +266,14 @@ def test_build_makes_locals_automatic(self): cmake = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") for flag in ("-frecursive>", "/Qauto>", "-auto>"): self.assertTrue(flag in cmake, f"CMakeLists.txt does not pass {flag[:-1]}") + # the OpenFAST Visual Studio project compiles the adapter: every configuration too + vfproj = (ROOT / "integration/openfast/vs-build/CableDyn.vfproj.in").read_text( + encoding="utf-8" + ) + tools = re.findall(r"]*>", vfproj) + self.assertGreater(len(tools), 0) + for tool in tools: + self.assertIn('LocalVariableStorage="localStorageAutomatic"', tool) def test_audit_sees_a_closure_and_an_initialised_local(self): # the checks themselves: a closure and an implicit SAVE in a scratch source From aa9250d547234f93fef03e518ba4e3e8e27f8937 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 07:58:34 +0900 Subject: [PATCH 10/19] fix(diagnostics): per-system and per-workspace counts, no process-wide tallies Four diagnostics tallies were module variables written from the step of every model, so concurrent handles mixed their counts, and without OpenMP (the ifx release) their !$OMP ATOMIC was inactive and increments could be lost: - n_fallback_entries (CableDyn_System), the subdivision-retry tripwire of CD_Step_System: now a component of CD_SystemType, outside the snapshot, so a restored step keeps its count. CD_System_Fallback_Count/Reset take the system; the aggregate gets CD_AGG_Fallback_Count/Reset. - CD_COSASM_* (CableDyn_CosseratAssemble), the tangent and internal-force assembly counts and times: now components of CD_CosseratAssemblyWorkspace, kept by the workspace-backed kernels; the dense kernel without a workspace no longer counts or reads the clock (nothing read it). - CD_COSDYN_* (CableDyn_CosseratDynamic), the modified-Newton stale-tangent counts and histograms: now components of CD_CosseratGenAlphaWorkspace; CD_Reset_Cosserat_Dyn_Counts and CD_Reset_Cosserat_Asm_Counts take the workspace. - n_substep_recoveries (CableDyn_HermiteCableDynamic): each model already counts its recovered intervals (recovery_event_count, CD_HermiteCable_Dyn_Get_Recovery_Diagnostics). The process-wide total is read only by the run profiles of the driver and the OpenFAST module, so it becomes a figure of the opt-in step profile (prof_n_recover, counted while the profile is armed, like the other profile counts; a profiled run steps its cables serially). Process-wide by design and documented as such: the opt-in run profile (CableDyn_Profile, armed by CABLEDYN_PROFILE in the driver and the OpenFAST module), the Hermite step profile (prof_*), the C API handle registry (locked), the OpenFAST instance registry, and the driver's test hooks and warn-once flag; thread_safe_sources lists each with its reason. Tests read the per-object counts (the Hermite recovery gates read the model's diagnostics and check the armed profile's count and its reset); example outputs are bit-identical. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 6 +++ src/CableDyn_CosseratAssemble.f90 | 50 +++++++----------- src/CableDyn_CosseratDynamic.f90 | 67 ++++++++++++------------- src/CableDyn_HermiteCableDynamic.f90 | 30 ++++++----- src/CableDyn_OpenFAST_Aggregate.f90 | 16 ++++++ src/CableDyn_System.f90 | 35 ++++++------- tests/test_core_release_regressions.f90 | 12 ++--- tests/test_cosserat_assemble.f90 | 13 ++--- tests/test_cosserat_dynamic.f90 | 14 +++--- tests/test_hermite_cable_dynamic.f90 | 31 ++++++++---- tests/test_l3_lazywave_dynamic.f90 | 8 +-- tests/test_of_mooring_counters.f90 | 12 ++--- tests/test_openfast_touchdown.f90 | 8 +-- tests/test_thread_safe_sources.py | 50 +++++++++--------- 14 files changed, 190 insertions(+), 162 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 28f7c480..2d3c47e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -460,6 +460,12 @@ All notable changes to CableDyn are recorded in this file. The format follows share: a free spar rod with a 55 m pinned cable (EI 2e4 N m^2) started 5.7e-2 m off its equilibrium, drifted 7e-2 m in 3 s and moved a leg tension by 2.3 %. Such a line now takes the static passes too (4 here); the rod holds its pose to the output's 8 digits. +- Diagnostic counts that concurrent models shared: the adaptive-substep fallbacks of an `EI = 0` + system and the assembly and modified-Newton counts of the finite-EI Cosserat solver were + process-wide (and lost increments without OpenMP); they are now kept per system and per solver + workspace. The count of finite-EI intervals recovered by substeps is reported only by the opt-in + run profile (`CABLEDYN_PROFILE`), whose figures stay process-wide by design; each model keeps its + own. No result changes. - A failing `OPEN` of a file name of about 600 characters or more (the extended-length spelling of a path beyond the Windows limit) ended an ifx-built program or the wheel's DLL with `STATUS_STACK_BUFFER_OVERRUN` inside the Intel Fortran run-time, for example an output root in diff --git a/src/CableDyn_CosseratAssemble.f90 b/src/CableDyn_CosseratAssemble.f90 index 3c25f44b..3d4ff454 100644 --- a/src/CableDyn_CosseratAssemble.f90 +++ b/src/CableDyn_CosseratAssemble.f90 @@ -30,26 +30,8 @@ MODULE CableDyn_CosseratAssemble PUBLIC :: CD_Assemble_Cosserat_Internal_Force_Workspace PUBLIC :: CD_Cosserat_Free_Bandwidth, CD_Cosserat_Free_Bandwidth_Workspace PUBLIC :: CD_CosseratAssemblyWorkspace, CD_Clear_CosseratAssembly_Workspace - PUBLIC :: CD_COSASM_N_TANGENT, CD_COSASM_N_FORCE, CD_COSASM_T_TANGENT, CD_COSASM_T_FORCE PUBLIC :: CD_Reset_Cosserat_Asm_Counts - !! Diagnostic assembly counters for performance measurement: how many - !! global tangent vs internal-force assemblies have run since the last reset. - !! Incremented once per assembly call (in the serial part, not the OpenMP element - !! loop), they let a benchmark / solver attribute wall time to Newton tangent - !! builds vs residual (line-search) evaluations. Not part of any numerical result; - !! ignore in production. - !! - !! CONTRACT: these are PROCESS-GLOBAL, single-run, single-threaded instrumentation - !! -- not per-model and not synchronized. They are only meaningful for one model - !! stepped on one thread (a benchmark resets then reads them); - !! concurrent multi-model or multi-threaded stepping would interleave the counts. - !! They are diagnostics only, so a corrupted count never affects a physics result. - INTEGER, SAVE :: CD_COSASM_N_TANGENT = 0 - INTEGER, SAVE :: CD_COSASM_N_FORCE = 0 - REAL(wp), SAVE :: CD_COSASM_T_TANGENT = 0.0_wp - REAL(wp), SAVE :: CD_COSASM_T_FORCE = 0.0_wp - TYPE :: CD_CosseratAssemblyWorkspace !! Reusable scratch for finite-EI global assembly kernels. INTEGER, ALLOCATABLE :: global_to_free(:) @@ -57,6 +39,13 @@ MODULE CableDyn_CosseratAssemble REAL(wp), ALLOCATABLE :: Ke(:, :, :) INTEGER, ALLOCATABLE :: elem_es(:) CHARACTER(120), ALLOCATABLE :: elem_em(:) + ! Diagnostics of the assemblies run on this workspace since CD_Reset_Cosserat_Asm_Counts: + ! the global tangent and internal-force assemblies and their wall time, so a benchmark can + ! attribute time to Newton tangents and residual-only evaluations. They belong to the + ! workspace (one per model), so concurrent models never mix their counts, and no result + ! depends on them. + INTEGER :: n_tangent = 0, n_force = 0 + REAL(wp) :: t_tangent = 0.0_wp, t_force = 0.0_wp END TYPE CD_CosseratAssemblyWorkspace CONTAINS @@ -71,12 +60,13 @@ SUBROUTINE CD_Clear_CosseratAssembly_Workspace(work) IF (ALLOCATED(work%elem_em)) DEALLOCATE (work%elem_em) END SUBROUTINE CD_Clear_CosseratAssembly_Workspace - SUBROUTINE CD_Reset_Cosserat_Asm_Counts() - !! Zero the diagnostic assembly counters (call before a timed solve). - CD_COSASM_N_TANGENT = 0 - CD_COSASM_N_FORCE = 0 - CD_COSASM_T_TANGENT = 0.0_wp - CD_COSASM_T_FORCE = 0.0_wp + SUBROUTINE CD_Reset_Cosserat_Asm_Counts(work) + !! Zero the diagnostic assembly counters of a workspace (call before a timed solve). + TYPE(CD_CosseratAssemblyWorkspace), INTENT(INOUT) :: work + work%n_tangent = 0 + work%n_force = 0 + work%t_tangent = 0.0_wp + work%t_force = 0.0_wp END SUBROUTINE CD_Reset_Cosserat_Asm_Counts SUBROUTINE CD_Assemble_Cosserat_Tangent_Force(nodes_ref, elem_conn, ea, gas, ei, gj, q, & @@ -90,15 +80,12 @@ SUBROUTINE CD_Assemble_Cosserat_Tangent_Force(nodes_ref, elem_conn, ea, gas, ei, INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg INTEGER :: n_nodes, n_elem, e, a, b, ndof, gmap(12), i, j, es - INTEGER(INT64) :: c0, rate REAL(wp) :: Lam0(3, 3), L0, qe(12), Kte(12, 12), finte(12) REAL(wp), ALLOCATABLE :: fe(:, :), Ke(:, :, :) INTEGER, ALLOCATABLE :: elem_es(:) CHARACTER(120), ALLOCATABLE :: elem_em(:) CHARACTER(120) :: em - CD_COSASM_N_TANGENT = CD_COSASM_N_TANGENT + 1 - CALL SYSTEM_CLOCK(c0, rate) Kt = 0.0_wp fint = 0.0_wp CALL check_inputs(nodes_ref, elem_conn, ea, gas, ei, gj, q, n_nodes, n_elem, ndof, ErrStat, ErrMsg) @@ -158,7 +145,6 @@ SUBROUTINE CD_Assemble_Cosserat_Tangent_Force(nodes_ref, elem_conn, ea, gas, ei, END DO END DO END DO - CALL add_elapsed(CD_COSASM_T_TANGENT, c0, rate) END SUBROUTINE CD_Assemble_Cosserat_Tangent_Force SUBROUTINE CD_Cosserat_Free_Bandwidth(elem_conn, n_nodes, free, kl, ku, ErrStat, ErrMsg) @@ -273,7 +259,7 @@ SUBROUTINE CD_Assemble_Cosserat_Tangent_Force_Banded_Free_Workspace(nodes_ref, e REAL(wp) :: Lam0(3, 3), L0, qe(12), Kte(12, 12), finte(12) CHARACTER(120) :: em - CD_COSASM_N_TANGENT = CD_COSASM_N_TANGENT + 1 + work%n_tangent = work%n_tangent + 1 CALL SYSTEM_CLOCK(c0, rate) Kb = 0.0_wp fint = 0.0_wp @@ -382,7 +368,7 @@ SUBROUTINE CD_Assemble_Cosserat_Tangent_Force_Banded_Free_Workspace(nodes_ref, e END DO END DO END DO - CALL add_elapsed(CD_COSASM_T_TANGENT, c0, rate) + CALL add_elapsed(work%t_tangent, c0, rate) END SUBROUTINE CD_Assemble_Cosserat_Tangent_Force_Banded_Free_Workspace SUBROUTINE CD_Assemble_Cosserat_Internal_Force(nodes_ref, elem_conn, ea, gas, ei, gj, q, & @@ -417,7 +403,7 @@ SUBROUTINE CD_Assemble_Cosserat_Internal_Force_Workspace(nodes_ref, elem_conn, e REAL(wp) :: Lam0(3, 3), L0, qe(12), finte(12) CHARACTER(120) :: em - CD_COSASM_N_FORCE = CD_COSASM_N_FORCE + 1 + work%n_force = work%n_force + 1 CALL SYSTEM_CLOCK(c0, rate) fint = 0.0_wp CALL check_inputs(nodes_ref, elem_conn, ea, gas, ei, gj, q, n_nodes, n_elem, ndof, ErrStat, ErrMsg) @@ -472,7 +458,7 @@ SUBROUTINE CD_Assemble_Cosserat_Internal_Force_Workspace(nodes_ref, elem_conn, e fint(gmap(i)) = fint(gmap(i)) + work%fe(i, e) END DO END DO - CALL add_elapsed(CD_COSASM_T_FORCE, c0, rate) + CALL add_elapsed(work%t_force, c0, rate) END SUBROUTINE CD_Assemble_Cosserat_Internal_Force_Workspace SUBROUTINE ensure_assembly_workspace(work, ndof, n_elem, need_tangent, ErrStat, ErrMsg) diff --git a/src/CableDyn_CosseratDynamic.f90 b/src/CableDyn_CosseratDynamic.f90 index 2c315ad0..9fcf6a63 100644 --- a/src/CableDyn_CosseratDynamic.f90 +++ b/src/CableDyn_CosseratDynamic.f90 @@ -40,24 +40,11 @@ MODULE CableDyn_CosseratDynamic PUBLIC :: CD_Cosserat_Mechanical_Energy PUBLIC :: CD_Spatial_Inertia, CD_Spatial_Inertia_Dir, CD_Gyro_Torque, CD_Gyro_Torque_DOmega PUBLIC :: CD_Reset_Cosserat_Dyn_Counts - PUBLIC :: CD_COSDYN_HIST_MAX, CD_COSDYN_N_STALE_ACCEPT, CD_COSDYN_N_STALE_REJECT - PUBLIC :: CD_COSDYN_N_DEFERRED_REFRESH - PUBLIC :: CD_COSDYN_STALE_ACCEPT_HIST, CD_COSDYN_STALE_REJECT_HIST - PUBLIC :: CD_COSDYN_DEFERRED_REFRESH_HIST - - ! Modified-Newton stale-tangent diagnostics. CONTRACT: like the assembly counters in - ! CableDyn_CosseratAssemble, these are PROCESS-GLOBAL, single-run, single-threaded - ! instrumentation -- not per-model and not synchronized. They are only meaningful for - ! one model stepped on one thread (reset via CD_Reset_Cosserat_Dyn_Counts, then read); - ! concurrent multi-model or multi-threaded stepping would interleave them. Diagnostics - ! only -- a corrupted count never affects a physics result. + PUBLIC :: CD_COSDYN_HIST_MAX + + ! Histogram bins of the modified-Newton diagnostics of CD_CosseratGenAlphaWorkspace: the + ! Newton iteration of a stale-tangent outcome, the last bin collecting the later ones. INTEGER, PARAMETER :: CD_COSDYN_HIST_MAX = 16 - INTEGER, SAVE :: CD_COSDYN_N_STALE_ACCEPT = 0 - INTEGER, SAVE :: CD_COSDYN_N_STALE_REJECT = 0 - INTEGER, SAVE :: CD_COSDYN_N_DEFERRED_REFRESH = 0 - INTEGER, SAVE :: CD_COSDYN_STALE_ACCEPT_HIST(0:CD_COSDYN_HIST_MAX) = 0 - INTEGER, SAVE :: CD_COSDYN_STALE_REJECT_HIST(0:CD_COSDYN_HIST_MAX) = 0 - INTEGER, SAVE :: CD_COSDYN_DEFERRED_REFRESH_HIST(0:CD_COSDYN_HIST_MAX) = 0 ABSTRACT INTERFACE SUBROUTINE CD_Cosserat_Dynamic_Force_Proc(q, v, force, ErrStat, ErrMsg) @@ -123,6 +110,15 @@ END SUBROUTINE CD_Cosserat_Dynamic_Load_Banded_Proc REAL(wp), ALLOCATABLE :: load_jv_band(:, :) REAL(wp), ALLOCATABLE :: eff_band(:, :) TYPE(CD_CosseratAssemblyWorkspace) :: assembly + ! Modified-Newton stale-tangent diagnostics of the steps run on this workspace (one per + ! model, so concurrent models never mix their counts) since CD_Reset_Cosserat_Dyn_Counts: + ! stale-tangent steps accepted and rejected, refreshes before the first solve (no path + ! takes one), and histograms over the Newton iteration of each outcome. No result + ! depends on them. + INTEGER :: n_stale_accept = 0, n_stale_reject = 0, n_deferred_refresh = 0 + INTEGER :: stale_accept_hist(0:CD_COSDYN_HIST_MAX) = 0 + INTEGER :: stale_reject_hist(0:CD_COSDYN_HIST_MAX) = 0 + INTEGER :: deferred_refresh_hist(0:CD_COSDYN_HIST_MAX) = 0 END TYPE CD_CosseratGenAlphaWorkspace CONTAINS @@ -167,15 +163,16 @@ SUBROUTINE CD_Clear_CosseratGenAlpha_Workspace(work) work%ldab_capacity = 0 END SUBROUTINE CD_Clear_CosseratGenAlpha_Workspace - SUBROUTINE CD_Reset_Cosserat_Dyn_Counts() - !! Zero modified-Newton diagnostic counters. These are benchmark-only + SUBROUTINE CD_Reset_Cosserat_Dyn_Counts(work) + !! Zero the modified-Newton diagnostic counters of a workspace. These are benchmark-only !! diagnostics and do not affect the numerical path. - CD_COSDYN_N_STALE_ACCEPT = 0 - CD_COSDYN_N_STALE_REJECT = 0 - CD_COSDYN_N_DEFERRED_REFRESH = 0 - CD_COSDYN_STALE_ACCEPT_HIST = 0 - CD_COSDYN_STALE_REJECT_HIST = 0 - CD_COSDYN_DEFERRED_REFRESH_HIST = 0 + TYPE(CD_CosseratGenAlphaWorkspace), INTENT(INOUT) :: work + work%n_stale_accept = 0 + work%n_stale_reject = 0 + work%n_deferred_refresh = 0 + work%stale_accept_hist = 0 + work%stale_reject_hist = 0 + work%deferred_refresh_hist = 0 END SUBROUTINE CD_Reset_Cosserat_Dyn_Counts SUBROUTINE CD_Cosserat_Mechanical_Energy(nodes_ref, elem_conn, ea, gas, ei, gj, rho_a, & @@ -1216,7 +1213,7 @@ SUBROUTINE CD_Cosserat_Gen_Alpha_Step(nodes_ref, elem_conn, ea, gas, ei, gj, rho CALL CD_Solve_Factored_Banded(eff_band, kl, ku, ipiv, dq, es, em) IF (es /= 0 .OR. .NOT. CD_All_Finite(dq)) THEN IF (cfg%modified_newton .AND. .NOT. tangent_fresh) THEN - CALL record_stale_reject(n_iter) + CALL record_stale_reject(work, n_iter) have_eff = .FALSE. CYCLE END IF @@ -1246,13 +1243,13 @@ SUBROUTINE CD_Cosserat_Gen_Alpha_Step(nodes_ref, elem_conn, ea, gas, ei, gj, rho n_iter = n_iter + 1 IF (.NOT. accepted) THEN IF (cfg%modified_newton .AND. .NOT. tangent_fresh) THEN - CALL record_stale_reject(n_iter - 1) + CALL record_stale_reject(work, n_iter - 1) have_eff = .FALSE. CYCLE END IF stalled = .TRUE.; EXIT END IF - IF (cfg%modified_newton .AND. .NOT. tangent_fresh) CALL record_stale_accept(n_iter - 1) + IF (cfg%modified_newton .AND. .NOT. tangent_fresh) CALL record_stale_accept(work, n_iter - 1) qk = q_trial IF (cfg%modified_newton) THEN R = R_trial @@ -1689,20 +1686,22 @@ SUBROUTINE ensure_real_matrix(x, nrow, ncol, ErrStat, ErrMsg) END IF END SUBROUTINE ensure_real_matrix - SUBROUTINE record_stale_accept(iter) + SUBROUTINE record_stale_accept(work, iter) + TYPE(CD_CosseratGenAlphaWorkspace), INTENT(INOUT) :: work INTEGER, INTENT(IN) :: iter INTEGER :: idx idx = MIN(MAX(iter, 0), CD_COSDYN_HIST_MAX) - CD_COSDYN_N_STALE_ACCEPT = CD_COSDYN_N_STALE_ACCEPT + 1 - CD_COSDYN_STALE_ACCEPT_HIST(idx) = CD_COSDYN_STALE_ACCEPT_HIST(idx) + 1 + work%n_stale_accept = work%n_stale_accept + 1 + work%stale_accept_hist(idx) = work%stale_accept_hist(idx) + 1 END SUBROUTINE record_stale_accept - SUBROUTINE record_stale_reject(iter) + SUBROUTINE record_stale_reject(work, iter) + TYPE(CD_CosseratGenAlphaWorkspace), INTENT(INOUT) :: work INTEGER, INTENT(IN) :: iter INTEGER :: idx idx = MIN(MAX(iter, 0), CD_COSDYN_HIST_MAX) - CD_COSDYN_N_STALE_REJECT = CD_COSDYN_N_STALE_REJECT + 1 - CD_COSDYN_STALE_REJECT_HIST(idx) = CD_COSDYN_STALE_REJECT_HIST(idx) + 1 + work%n_stale_reject = work%n_stale_reject + 1 + work%stale_reject_hist(idx) = work%stale_reject_hist(idx) + 1 END SUBROUTINE record_stale_reject PURE REAL(wp) FUNCTION infnorm(x) diff --git a/src/CableDyn_HermiteCableDynamic.f90 b/src/CableDyn_HermiteCableDynamic.f90 index ba175eee..10e0bf21 100644 --- a/src/CableDyn_HermiteCableDynamic.f90 +++ b/src/CableDyn_HermiteCableDynamic.f90 @@ -223,10 +223,11 @@ MODULE CableDyn_HermiteCableDynamic 'end_conn', 'wave_fk', 'held_fk', 'torsion'] REAL(wp), SAVE :: prof_t_asm(HC_ASM_NSEC) = 0.0_wp - ! Number of coupling intervals completed by internal generalised-alpha substeps after the nominal - ! interval was too large for the prescribed boundary motion or environmental load. This counter is - ! independent of prof_enabled so temporal-refinement studies can report the actual line advances. - INTEGER, SAVE :: n_substep_recoveries = 0 + ! Coupling intervals completed by internal generalised-alpha substeps (the nominal interval was + ! too large for the prescribed boundary motion or environmental load), summed over every model + ! while the profile is armed, for the profile reports of the driver and the OpenFAST module. + ! Each model counts its own in recovery_event_count (CD_HermiteCable_Dyn_Get_Recovery_Diagnostics). + INTEGER, SAVE :: prof_n_recover = 0 TYPE :: CD_HermiteCableDynType !! Persistent finite-EI Hermite dynamic model: geometry, gen-alpha constants, and state. @@ -623,7 +624,7 @@ SUBROUTINE CD_HermiteCable_Dyn_Reset_Profile() !! the SYSTEM_CLOCK overhead in the step/residual hot path. prof_enabled = .TRUE. prof_n_step = 0; prof_n_resid = 0; prof_n_solve = 0; prof_n_am = 0; prof_n_alloc = 0 - prof_n_tan = 0; prof_n_factor = 0; prof_n_correct = 0 + prof_n_tan = 0; prof_n_factor = 0; prof_n_correct = 0; prof_n_recover = 0 prof_t_step = 0.0_wp; prof_t_resid = 0.0_wp; prof_t_eff = 0.0_wp prof_t_tan = 0.0_wp; prof_t_factor = 0.0_wp prof_t_solve = 0.0_wp; prof_t_am = 0.0_wp @@ -5486,8 +5487,10 @@ SUBROUTINE CD_HermiteCable_Dyn_Step_Recovering(model, dt, max_iter, tol, ErrStat END IF END DO IF (es == CD_HCDYN_OK) THEN - !$OMP ATOMIC UPDATE - n_substep_recoveries = n_substep_recoveries + 1 + IF (prof_enabled) THEN + !$OMP ATOMIC UPDATE + prof_n_recover = prof_n_recover + 1 + END IF model%recovery_event_count = model%recovery_event_count + 1 model%recovery_max_substeps_used = MAX(model%recovery_max_substeps_used, nsub) ErrStat = CD_HCDYN_OK; ErrMsg = '' @@ -5734,15 +5737,18 @@ LOGICAL FUNCTION temporal_increment_ok(model) RESULT(ok) END FUNCTION temporal_increment_ok PURE FUNCTION CD_HermiteCable_Dyn_Recovery_Count() RESULT(n) - !! Coupling intervals that completed only via internal substepping since the last - !! CD_HermiteCable_Dyn_Recovery_Reset (the finite-EI analogue of CD_System_Fallback_Count). + !! Coupling intervals of every model that completed only via internal substepping while the + !! step profile was armed (CD_HermiteCable_Dyn_Reset_Profile), since the last + !! CD_HermiteCable_Dyn_Recovery_Reset: a process-wide figure of the opt-in profile, like + !! the other profile counts (a profiled run steps its cables serially). One model's own + !! count is CD_HermiteCable_Dyn_Get_Recovery_Diagnostics. INTEGER :: n - n = n_substep_recoveries + n = prof_n_recover END FUNCTION CD_HermiteCable_Dyn_Recovery_Count SUBROUTINE CD_HermiteCable_Dyn_Recovery_Reset() - !! Zero the substep-recovery tripwire (start of a measured window). - n_substep_recoveries = 0 + !! Zero the profile's substep-recovery count (start of a measured window). + prof_n_recover = 0 END SUBROUTINE CD_HermiteCable_Dyn_Recovery_Reset SUBROUTINE CD_HermiteCable_Dyn_Energy(model, kinetic, strain, ErrStat, ErrMsg, connection) diff --git a/src/CableDyn_OpenFAST_Aggregate.f90 b/src/CableDyn_OpenFAST_Aggregate.f90 index 5f68343a..8d5007e7 100644 --- a/src/CableDyn_OpenFAST_Aggregate.f90 +++ b/src/CableDyn_OpenFAST_Aggregate.f90 @@ -93,6 +93,7 @@ MODULE CableDyn_OpenFAST_Aggregate CD_Deck_Current_End USE CableDyn_RangeOutput, ONLY: CD_RangeSet, CD_Range_End USE CableDyn_System, ONLY: CD_Get_System_Substep_Counts, CD_System_NLines, CD_System_Line_NDOF, & + CD_System_Fallback_Count, CD_System_Fallback_Reset, & CD_Get_System_Line_State, & CD_Update_System_Line_SegmentLength, CD_Save_System_Line_Control, & CD_Restore_System_Line_Control, & @@ -109,6 +110,7 @@ MODULE CableDyn_OpenFAST_Aggregate PUBLIC :: CD_AGG_HasRigid6 PUBLIC :: CD_AGG_HasRod PUBLIC :: CD_AGG_HasPoint3 + PUBLIC :: CD_AGG_Fallback_Count, CD_AGG_Fallback_Reset PUBLIC :: CD_AGG_Rigid6_MirrorSize, CD_AGG_Get_Rigid6_States, CD_AGG_Set_Rigid6_States PUBLIC :: CD_AGG_Rod_MirrorSize, CD_AGG_Get_Rod_States, CD_AGG_Set_Rod_States PUBLIC :: CD_AGG_Refresh_PointMesh @@ -625,6 +627,20 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi CALL CD_AGG_End(candidate, es, em) END SUBROUTINE CD_AGG_Init_From_Deck + PURE INTEGER FUNCTION CD_AGG_Fallback_Count(self) RESULT(n) + !! Subdivision-retry entries of the EI = 0 system step since its initialisation or the + !! last CD_AGG_Fallback_Reset (CD_System_Fallback_Count); 0 without an EI = 0 system. + TYPE(CD_AGG_ModuleType), INTENT(IN) :: self + n = 0 + IF (self%has_sys) n = CD_System_Fallback_Count(self%sys%fast%system) + END FUNCTION CD_AGG_Fallback_Count + + SUBROUTINE CD_AGG_Fallback_Reset(self) + !! Zero the subdivision-retry tripwire of the EI = 0 system (start of a measured window). + TYPE(CD_AGG_ModuleType), INTENT(INOUT) :: self + IF (self%has_sys) CALL CD_System_Fallback_Reset(self%sys%fast%system) + END SUBROUTINE CD_AGG_Fallback_Reset + INTEGER FUNCTION CD_AGG_NMovingPoints(self, ErrStat, ErrMsg) RESULT(n) !! Total host-prescribed (moving) points: the EI=0 system's moving points followed by !! one fairlead per cable. diff --git a/src/CableDyn_System.f90 b/src/CableDyn_System.f90 index 87760f8a..6ca7fc81 100644 --- a/src/CableDyn_System.f90 +++ b/src/CableDyn_System.f90 @@ -123,14 +123,6 @@ MODULE CableDyn_System INTEGER, PARAMETER, PUBLIC :: CD_LINE_END_A = 1 INTEGER, PARAMETER, PUBLIC :: CD_LINE_END_B = 2 - ! Adaptive-substep fallback tripwire: how many times CD_Step_System entered the - ! subdivision retry since the last reset. A plain integer increment on the RARE - ! stall path only (the converged path never touches it), so it is always on -- - ! diagnostics can read it to assert a healthy run never needed the fallback, and a - ! coupled log can report it at shutdown. - ! Module-level (not per-system): a diagnostics tally, not model state. - INTEGER, SAVE :: n_fallback_entries = 0 - TYPE :: CD_SystemPointType !! Named system point. Fixed/coupled points are externally prescribed. !! Free/connect points are integrated by the system dynamic-point step. @@ -245,6 +237,13 @@ MODULE CableDyn_System ! mean squares per node, 3 per node: sized like snap_q, line by line). REAL(wp), ALLOCATABLE :: snap_viv(:) LOGICAL :: snap_valid = .FALSE. + ! Adaptive-substep fallback tripwire: how many times CD_Step_System entered the + ! subdivision retry of this system since its initialisation or the last + ! CD_System_Fallback_Reset. An increment on the RARE stall path only (the converged path + ! never touches it), so it is always on: diagnostics can assert that a healthy run never + ! needed the fallback. Per system, so concurrent systems never mix their counts; not part + ! of the snapshot (a restored step keeps its count) and of no result. + INTEGER :: n_fallback_entries = 0 END TYPE CD_SystemType CONTAINS @@ -1534,8 +1533,8 @@ RECURSIVE SUBROUTINE CD_Step_System(system, dt, q_coupled, v_coupled, a_coupled, ! and on ANY failure to complete the full interval converged it restores that snapshot ! -- so a mid-interval state can never leak. IF (.NOT. converged .AND. depth < MAX_SUBDIV) THEN - !$OMP ATOMIC UPDATE - n_fallback_entries = n_fallback_entries + 1 + ! the system's own count, outside the lines' parallel region: one thread steps a system + system%n_fallback_entries = system%n_fallback_entries + 1 ! Capture the coupled motion at the START of the interval only on the rare subdivision ! path. The common converged path must not heap-allocate just to prepare an unused retry. ALLOCATE (q0(SIZE(q_coupled)), v0(SIZE(q_coupled)), a0(SIZE(q_coupled))) @@ -3639,16 +3638,18 @@ SUBROUTINE CD_Get_System_Substep_Counts(system, calls, events, max_used, capped, END DO END SUBROUTINE CD_Get_System_Substep_Counts - PURE FUNCTION CD_System_Fallback_Count() RESULT(n) - !! Subdivision-retry entries since the last CD_System_Fallback_Reset (see the - !! module-level tripwire note). + PURE FUNCTION CD_System_Fallback_Count(system) RESULT(n) + !! Subdivision-retry entries of system since its initialisation or the last + !! CD_System_Fallback_Reset (see CD_SystemType%n_fallback_entries). + TYPE(CD_SystemType), INTENT(IN) :: system INTEGER :: n - n = n_fallback_entries + n = system%n_fallback_entries END FUNCTION CD_System_Fallback_Count - SUBROUTINE CD_System_Fallback_Reset() - !! Zero the subdivision-retry tripwire (start of a measured window). - n_fallback_entries = 0 + SUBROUTINE CD_System_Fallback_Reset(system) + !! Zero the subdivision-retry tripwire of system (start of a measured window). + TYPE(CD_SystemType), INTENT(INOUT) :: system + system%n_fallback_entries = 0 END SUBROUTINE CD_System_Fallback_Reset END MODULE CableDyn_System diff --git a/tests/test_core_release_regressions.f90 b/tests/test_core_release_regressions.f90 index 9193d831..c8c62411 100644 --- a/tests/test_core_release_regressions.f90 +++ b/tests/test_core_release_regressions.f90 @@ -178,12 +178,12 @@ SUBROUTINE case_fallback_restores_constitutive_state() END DO ac = 0.0_wp - CALL CD_System_Fallback_Reset() + CALL CD_System_Fallback_Reset(system) CALL CD_Step_System(system, DT, qc, vc, ac, conv, stalled, n_iter, es, em) CALL require(es == CD_SYSTEM_OK, 'fallback:system-step '//TRIM(em)) CALL require(.NOT. conv, 'fallback:step-stalls-at-every-depth') - CALL require(CD_System_Fallback_Count() > 0, 'fallback:subdivision-entered') - CALL CD_System_Fallback_Reset() + CALL require(CD_System_Fallback_Count(system) > 0, 'fallback:subdivision-entered') + CALL CD_System_Fallback_Reset(system) DO i = 1, 2 CALL CD_Get_Model_State(ref(i), pq, pv, pa, es, em) @@ -264,12 +264,12 @@ SUBROUTINE case_fallback_restores_committed_lengths() vc(4) = 0.2_wp ac = 0.0_wp - CALL CD_System_Fallback_Reset() + CALL CD_System_Fallback_Reset(system) CALL CD_Step_System(system, DT, qc, vc, ac, conv, stalled, n_iter, es, em) CALL require(es == CD_SYSTEM_OK, 'fallback-lengths:system-step '//TRIM(em)) CALL require(.NOT. conv, 'fallback-lengths:step-stalls-at-every-depth') - CALL require(CD_System_Fallback_Count() > 0, 'fallback-lengths:subdivision-entered') - CALL CD_System_Fallback_Reset() + CALL require(CD_System_Fallback_Count(system) > 0, 'fallback-lengths:subdivision-entered') + CALL CD_System_Fallback_Reset(system) CALL CD_Get_Model_State(ref, pq, pv, pa, es, em) DO j = 1, 6 diff --git a/tests/test_cosserat_assemble.f90 b/tests/test_cosserat_assemble.f90 index 397b8976..8f05584d 100644 --- a/tests/test_cosserat_assemble.f90 +++ b/tests/test_cosserat_assemble.f90 @@ -15,8 +15,8 @@ PROGRAM test_cosserat_assemble CD_Assemble_Cosserat_Tangent_Force_Banded_Free, & CD_Assemble_Cosserat_Internal_Force, & CD_Cosserat_Free_Bandwidth, & - CD_COSASM_N_FORCE, CD_COSASM_N_TANGENT, & - CD_Reset_Cosserat_Asm_Counts + CD_Assemble_Cosserat_Internal_Force_Workspace, & + CD_CosseratAssemblyWorkspace, CD_Reset_Cosserat_Asm_Counts IMPLICIT NONE REAL(wp), PARAMETER :: EA = 1.0e3_wp, GAS = 5.0e2_wp, EI = 2.0e2_wp, GJ = 1.5e2_wp @@ -30,6 +30,7 @@ PROGRAM test_cosserat_assemble REAL(wp) :: fplus(NDOF), fminus(NDOF), ffd(NDOF), fref(NDOF), kd(NDOF), frob, ksum, h REAL(wp), ALLOCATABLE :: Kb(:, :), Kfree(:, :), Kfrom_band(:, :) CHARACTER(120) :: em + TYPE(CD_CosseratAssemblyWorkspace) :: asm_work nfail = 0 nodes_ref(:, 1) = [0.0_wp, 0.0_wp, 0.0_wp] @@ -131,10 +132,10 @@ PROGRAM test_cosserat_assemble ! Force-only assembly must remain a true residual-only path: it should not ! increment the tangent assembly counter or route through the Hessian path. - CALL CD_Reset_Cosserat_Asm_Counts() - CALL CD_Assemble_Cosserat_Internal_Force(nodes_ref, conn, ea_a, gas_a, ei_a, gj_a, q, .TRUE., & - fint2, es, em) - CALL require(es == 0 .AND. CD_COSASM_N_FORCE == 1 .AND. CD_COSASM_N_TANGENT == 0, & + CALL CD_Reset_Cosserat_Asm_Counts(asm_work) + CALL CD_Assemble_Cosserat_Internal_Force_Workspace(nodes_ref, conn, ea_a, gas_a, ei_a, gj_a, q, .TRUE., & + asm_work, fint2, es, em) + CALL require(es == 0 .AND. asm_work%n_force == 1 .AND. asm_work%n_tangent == 0, & 'force-only-does-not-touch-tangent-counter') ! === fail-closed connectivity / property validation (mirrors the reference mesh diff --git a/tests/test_cosserat_dynamic.f90 b/tests/test_cosserat_dynamic.f90 index a61ded70..062c30db 100644 --- a/tests/test_cosserat_dynamic.f90 +++ b/tests/test_cosserat_dynamic.f90 @@ -16,8 +16,7 @@ PROGRAM test_cosserat_dynamic CD_Cosserat_Mechanical_Energy, CD_Assemble_Cosserat_Mass, & CD_Assemble_Cosserat_Mass_Banded_Free, CD_Cosserat_Mass_MatVec, & CD_CosseratGenAlphaWorkspace, CD_Clear_CosseratGenAlpha_Workspace, & - CD_Reset_Cosserat_Dyn_Counts, CD_COSDYN_N_STALE_ACCEPT, & - CD_COSDYN_N_STALE_REJECT, CD_COSDYN_N_DEFERRED_REFRESH + CD_Reset_Cosserat_Dyn_Counts USE CableDyn_CosseratAssemble, ONLY: CD_Assemble_Cosserat_Internal_Force, CD_Cosserat_Free_Bandwidth USE CableDyn_Cosserat, ONLY: CD_Reference_Frame, CD_Cosserat_Element_Energy USE CableDyn_Dynamic, ONLY: GenAlphaConfig, CD_DYN_OK @@ -363,6 +362,7 @@ SUBROUTINE check_modified_newton_reuses_tangent() INTEGER :: es_l, nit_full, nit_mod LOGICAL :: cvg_full, stl_full, cvg_mod, stl_mod CHARACTER(120) :: em_l + TYPE(CD_CosseratGenAlphaWorkspace) :: mod_work amp = 2.0e-3_wp q0 = q @@ -391,14 +391,16 @@ SUBROUTINE check_modified_newton_reuses_tangent() q_full, v_full, a_full, cvg_full, stl_full, nit_full, es_l, em_l) CALL require(es_l == CD_DYN_OK .AND. cvg_full .AND. .NOT. stl_full, 'cosserat-mod-newton:full-converged') - CALL CD_Reset_Cosserat_Dyn_Counts() + CALL CD_Reset_Cosserat_Dyn_Counts(mod_work) CALL CD_Cosserat_Gen_Alpha_Step(nodes_ref, conn, ea_a, gas_a, ei_a, gj_a, ra, it, in_, .TRUE., & q0, v0, a_init, f_load, [INTEGER ::], 0.02_wp, cfg_mod, & - q_mod, v_mod, a_mod, cvg_mod, stl_mod, nit_mod, es_l, em_l) + q_mod, v_mod, a_mod, cvg_mod, stl_mod, nit_mod, es_l, em_l, & + workspace=mod_work) CALL require(es_l == CD_DYN_OK .AND. cvg_mod .AND. .NOT. stl_mod, 'cosserat-mod-newton:modified-converged') - CALL require(CD_COSDYN_N_STALE_ACCEPT + CD_COSDYN_N_STALE_REJECT > 0, & + CALL require(mod_work%n_stale_accept + mod_work%n_stale_reject > 0, & 'cosserat-mod-newton:stale-tangent-attempted') - CALL require(CD_COSDYN_N_DEFERRED_REFRESH == 0, 'cosserat-mod-newton:no-pre-solve-refresh') + CALL require(mod_work%n_deferred_refresh == 0, 'cosserat-mod-newton:no-pre-solve-refresh') + CALL CD_Clear_CosseratGenAlpha_Workspace(mod_work) dqmax = nan_max_abs(q_mod - q_full) dvmax = nan_max_abs(v_mod - v_full) damax = nan_max_abs(a_mod - a_full) diff --git a/tests/test_hermite_cable_dynamic.f90 b/tests/test_hermite_cable_dynamic.f90 index 6d59e505..f23800d9 100644 --- a/tests/test_hermite_cable_dynamic.f90 +++ b/tests/test_hermite_cable_dynamic.f90 @@ -562,7 +562,7 @@ SUBROUTINE check_tensile_safety() TYPE(CD_HermiteCableDynType) :: m REAL(wp), ALLOCATABLE :: l0(:), EAv(:), EIv(:), rhoAv(:), wv(:), seed(:), q_before(:) INTEGER, ALLOCATABLE :: fx(:) - INTEGER :: es, event_count, worst_element + INTEGER :: es, event_count, worst_element, n_before REAL(wp) :: worst_force, worst_threshold, worst_xi, worst_time CHARACTER(300) :: em @@ -580,12 +580,12 @@ SUBROUTINE check_tensile_safety() CALL require(INDEX(em, 'axial compression') > 0, 'tensile-safety diagnostic identifies axial compression') CALL require(nan_max_abs(m%q - q_before) <= TINY(1.0_wp), & 'rejected tensile-safety step does not commit its candidate state') - CALL CD_HermiteCable_Dyn_Recovery_Reset() + n_before = recovered_intervals(m) CALL CD_HermiteCable_Dyn_Step_Recovering(m, 0.01_wp, 20, 1.0e-9_wp, es, em) CALL require(es == CD_HCDYN_NOCONVERGE, 'recovering step preserves tensile-safety rejection') CALL require(INDEX(em, 'tensile qualification failed') > 0 .AND. INDEX(em, 'diverged') == 0, & 'recovering step reports spatial qualification rather than temporal divergence') - CALL require(CD_HermiteCable_Dyn_Recovery_Count() == 0, & + CALL require(recovered_intervals(m) == n_before, & 'tensile-safety rejection does not attempt temporal subdivision') CALL require(nan_max_abs(m%q - q_before) <= TINY(1.0_wp), & 'recovering tensile-safety rejection preserves the committed state') @@ -838,7 +838,6 @@ SUBROUTINE check_recovering_step() CALL require(es == CD_HCDYN_OK, 'recovering identity init m1: '//TRIM(em)) CALL CD_HermiteCable_Dyn_Init(m2, l0, EAv, EIv, rhoAv, wv, seed, fx, 0.0_wp, 0.0_wp, 0.9_wp, es, em) CALL require(es == CD_HCDYN_OK, 'recovering identity init m2: '//TRIM(em)) - CALL CD_HermiteCable_Dyn_Recovery_Reset() pd(1) = 3 DO s = 1, 5 pq(1) = 0.002_wp*REAL(s, wp); pv(1) = 0.002_wp/DTC; pa(1) = 0.0_wp @@ -852,7 +851,7 @@ SUBROUTINE check_recovering_step() CALL require(nan_max_abs(m1%q - m2%q) <= 0.0_wp, 'recovering wrapper q bit-identical on a converging step') CALL require(nan_max_abs(m1%v - m2%v) <= 0.0_wp, 'recovering wrapper v bit-identical on a converging step') CALL require(nan_max_abs(m1%a - m2%a) <= 0.0_wp, 'recovering wrapper a bit-identical on a converging step') - CALL require(CD_HermiteCable_Dyn_Recovery_Count() == 0, 'no recovery on converging steps (count stays 0)') + CALL require(recovered_intervals(m2) == 0, 'no recovery on converging steps (count stays 0)') CALL CD_HermiteCable_Dyn_End(m1) CALL CD_HermiteCable_Dyn_End(m2) @@ -871,16 +870,20 @@ SUBROUTINE check_recovering_step() pres_dofs=pd, pres_q=pq, pres_v=pv, pres_a=pa) CALL require(es == CD_HCDYN_NOCONVERGE, 'recovery probe: plain full step diverges on the hard interval') ! Wrapper on the same interval + same budget: substeps and completes, landing at t+dt on target. + ! the armed step profile counts the recovered interval too (process-wide, with its reset) + CALL CD_HermiteCable_Dyn_Reset_Profile() CALL CD_HermiteCable_Dyn_Recovery_Reset() - n0 = CD_HermiteCable_Dyn_Recovery_Count() + n0 = recovered_intervals(mr) CALL CD_HermiteCable_Dyn_Step_Recovering(mr, DTV, MAXIT_HARD, 1.0e-6_wp, es, em, & pres_dofs=pd, pres_q=pq, pres_v=pv, pres_a=pa) CALL require(es == CD_HCDYN_OK, 'recovery: wrapper completes the violent interval via substepping: '//TRIM(em)) - CALL require(CD_HermiteCable_Dyn_Recovery_Count() == n0 + 1, 'recovery: the substep tripwire incremented') + CALL require(recovered_intervals(mr) == n0 + 1, 'recovery: the substep tripwire incremented') + CALL require(CD_HermiteCable_Dyn_Recovery_Count() == 1, 'recovery: the armed profile counts the interval') CALL require(ABS(mr%q(3) - ZJUMP) < 1.0e-10_wp, 'recovery: prescribed boundary landed exactly on target') CALL require(ABS(mr%t - DTV) < 1.0e-9_wp, 'recovery: cable landed at t+dt (fixed-dt aggregate contract)') CALL CD_HermiteCable_Dyn_Recovery_Reset() CALL require(CD_HermiteCable_Dyn_Recovery_Count() == 0, 'recovery tripwire zero after reset') + CALL CD_HermiteCable_Dyn_Disable_Profile() ! --- (3) a converged full step can still be temporally under-resolved --- CALL CD_HermiteCable_Dyn_Init(mq, l0, EAv, EIv, rhoAv, wv, seed, fx, 0.0_wp, 0.0_wp, 0.9_wp, es, em) @@ -890,11 +893,10 @@ SUBROUTINE check_recovering_step() CALL CD_HermiteCable_Dyn_Step(mq, DTV, 40, 1.0e-6_wp, es, em, & pres_dofs=pd, pres_q=pq, pres_v=pv, pres_a=pa) CALL require(es == CD_HCDYN_OK, 'quality-gate probe: full step is Newton-converged') - CALL CD_HermiteCable_Dyn_Recovery_Reset() CALL CD_HermiteCable_Dyn_Step_Recovering(mrq, DTV, 40, 1.0e-6_wp, es, em, & pres_dofs=pd, pres_q=pq, pres_v=pv, pres_a=pa) CALL require(es == CD_HCDYN_OK, 'quality-gate recovery: under-resolved step subdivides: '//TRIM(em)) - CALL require(CD_HermiteCable_Dyn_Recovery_Count() == 1, & + CALL require(recovered_intervals(mrq) == 1, & 'quality-gate recovery: converged but under-resolved interval counted') CALL require(ABS(mrq%q(3) - ZJUMP) < 1.0e-10_wp, 'quality-gate recovery lands on prescribed target') CALL CD_HermiteCable_Dyn_End(mq) @@ -912,12 +914,11 @@ SUBROUTINE check_recovering_step() ! temporal gate's limit, while each quarter step is resolved (the gate measures ! deformation, so a smaller, nearly rigid rotation of the beam is accepted whole). pq = [-2.0_wp]; pv = [0.3_wp]; pa = [0.1_wp] - CALL CD_HermiteCable_Dyn_Recovery_Reset() CALL CD_HermiteCable_Dyn_Step_Recovering(mk, DTV, 40, 1.0e-6_wp, es, em, & pres_dofs=pd, pres_q=pq, pres_v=pv, pres_a=pa, & max_substeps=4) CALL require(es == CD_HCDYN_OK, 'quintic recovery completes on four substeps: '//TRIM(em)) - CALL require(CD_HermiteCable_Dyn_Recovery_Count() == 1, 'quintic comparison exercised recovery') + CALL require(recovered_intervals(mk) == 1, 'quintic comparison exercised recovery') CALL CD_HermiteCable_Dyn_Get_Recovery_Diagnostics(mk, recovery_events, recovery_max_used, es, em) CALL require(es == CD_HCDYN_OK .AND. recovery_events == 1 .AND. recovery_max_used == 4, & 'recovery diagnostics report the committed interval and winning rung') @@ -1026,6 +1027,14 @@ SUBROUTINE test_quintic_state(q0, v0, a0, q1, v1, a1, duration, u, q, v, a) (3.0_wp*u - 12.0_wp*u2 + 10.0_wp*u3)*a1 END SUBROUTINE test_quintic_state + INTEGER FUNCTION recovered_intervals(model) RESULT(n) + !! The intervals the model completed by internal substeps (its recovery diagnostics). + TYPE(CD_HermiteCableDynType), INTENT(IN) :: model + INTEGER :: max_used, es + CHARACTER(256) :: em + CALL CD_HermiteCable_Dyn_Get_Recovery_Diagnostics(model, n, max_used, es, em) + END FUNCTION recovered_intervals + SUBROUTINE require(cond, label) LOGICAL, INTENT(IN) :: cond CHARACTER(*), INTENT(IN) :: label diff --git a/tests/test_l3_lazywave_dynamic.f90 b/tests/test_l3_lazywave_dynamic.f90 index 703c4fd6..b74083b2 100644 --- a/tests/test_l3_lazywave_dynamic.f90 +++ b/tests/test_l3_lazywave_dynamic.f90 @@ -55,7 +55,7 @@ PROGRAM test_l3_lazywave_dynamic CD_HermiteCable_Dyn_Set_ForceBlend, & CD_HermiteCable_Dyn_Set_Drag, CD_HermiteCable_Dyn_Set_AddedMass, & CD_HermiteCable_Dyn_Step, CD_HermiteCable_Dyn_Step_Recovering, & - CD_HermiteCable_Dyn_Recovery_Count, CD_HermiteCable_Dyn_Recovery_Reset, & + CD_HermiteCable_Dyn_Get_Recovery_Diagnostics, & CD_HermiteCable_Dyn_Curvature_Exact, & CD_HermiteCable_Dyn_End, CD_HCDYN_OK IMPLICIT NONE @@ -752,7 +752,7 @@ SUBROUTINE refined_dynamic_response(l0, q0, eav, eiv, w, rhoa, diam, cdn, cdt, c TYPE(CD_HermiteCableDynType) :: dyn REAL(wp) :: t, z0, zt, vt, at, pq(1), pv(1), pa(1), k, arc, mnorm, tension, axial_now REAL(wp) :: cycle_tsum(3), nodal_curvature(SIZE(l0) + 1) - INTEGER :: pdof(1), step, nscore, cycle_count(3), cycle_index + INTEGER :: pdof(1), step, nscore, cycle_count(3), cycle_index, recovery_max_used CALL CD_HermiteCable_Dyn_Init(dyn, l0, eav, eiv, rhoa, w, q0, fixed, -2000.0_wp, 0.0_wp, 0.5_wp, es, em) IF (es /= CD_HCDYN_OK) RETURN @@ -763,7 +763,6 @@ SUBROUTINE refined_dynamic_response(l0, q0, eav, eiv, w, rhoa, diam, cdn, cdt, c CALL CD_HermiteCable_Dyn_Set_ForceBlend(dyn, force_blend, es, em) IF (es /= CD_HCDYN_OK) THEN; CALL CD_HermiteCable_Dyn_End(dyn); RETURN; END IF z0 = q0(3); pdof = [3] - CALL CD_HermiteCable_Dyn_Recovery_Reset() peak = 0.0_wp; peak_arc = 0.0_wp; tmean = 0.0_wp; minimum_axial = HUGE(1.0_wp) tmin = HUGE(1.0_wp); tmax = -HUGE(1.0_wp); nscore = 0 curvature_profile = 0.0_wp; cycle_peak = 0.0_wp; cycle_tsum = 0.0_wp @@ -802,7 +801,8 @@ SUBROUTINE refined_dynamic_response(l0, q0, eav, eiv, w, rhoa, diam, cdn, cdt, c DO cycle_index = 1, 3 cycle_tmean(cycle_index) = cycle_tsum(cycle_index)/REAL(MAX(1, cycle_count(cycle_index)), wp) END DO - recoveries = CD_HermiteCable_Dyn_Recovery_Count() + ! the model's own count of intervals recovered by substeps + CALL CD_HermiteCable_Dyn_Get_Recovery_Diagnostics(dyn, recoveries, recovery_max_used, es, em) CALL CD_HermiteCable_Dyn_End(dyn) END SUBROUTINE refined_dynamic_response diff --git a/tests/test_of_mooring_counters.f90 b/tests/test_of_mooring_counters.f90 index cb8a1846..47135ac0 100644 --- a/tests/test_of_mooring_counters.f90 +++ b/tests/test_of_mooring_counters.f90 @@ -22,10 +22,10 @@ PROGRAM test_of_mooring_counters !! subdivides) and its reset semantics hold; !! * loads out are finite every step. USE CableDyn_Precision, ONLY: wp - USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, CD_AGG_NMovingPoints, & + USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_Fallback_Count, CD_AGG_Fallback_Reset, & + CD_AGG_ModuleType, CD_AGG_Init_From_Deck, CD_AGG_NMovingPoints, & CD_AGG_GetMovingPointMesh, CD_AGG_Step_Moving, CD_AGG_CalcOutput, & CD_AGG_End, CD_AGG_OK - USE CableDyn_System, ONLY: CD_System_Fallback_Count, CD_System_Fallback_Reset USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_IS_FINITE IMPLICIT NONE @@ -62,8 +62,8 @@ PROGRAM test_of_mooring_counters CALL require(es == CD_AGG_OK, 'initial mesh read') ! reset semantics: the tripwire starts a measured window at zero - CALL CD_System_Fallback_Reset() - CALL require(CD_System_Fallback_Count() == 0, 'fallback tripwire zero after reset') + CALL CD_AGG_Fallback_Reset(agg) + CALL require(CD_AGG_Fallback_Count(agg) == 0, 'fallback tripwire zero after reset') nstep = NINT(DURATION/DTM) w = 2.0_wp*pi/PERIOD @@ -109,11 +109,11 @@ PROGRAM test_of_mooring_counters WRITE (*, '(A,F6.2,A,I0)') 'counters: newton/step mean = ', iter_sum/REAL(nstep, wp), & ' max = ', iter_max - WRITE (*, '(A,I0)') 'counters: substep fallbacks = ', CD_System_Fallback_Count() + WRITE (*, '(A,I0)') 'counters: substep fallbacks = ', CD_AGG_Fallback_Count(agg) CALL require(iter_sum/REAL(nstep, wp) <= MEAN_ITER_GATE, 'mean Newton/step within the band') CALL require(iter_max <= MAX_ITER_GATE, 'max Newton/step within the band') - CALL require(CD_System_Fallback_Count() == 0, 'no substep fallback over the healthy window') + CALL require(CD_AGG_Fallback_Count(agg) == 0, 'no substep fallback over the healthy window') CALL CD_AGG_End(agg, es, em) CALL require(es == CD_AGG_OK, 'aggregate End') diff --git a/tests/test_openfast_touchdown.f90 b/tests/test_openfast_touchdown.f90 index d432050b..b4d53f53 100644 --- a/tests/test_openfast_touchdown.f90 +++ b/tests/test_openfast_touchdown.f90 @@ -7,11 +7,11 @@ PROGRAM test_openfast_touchdown !! a multi-node grounded run (not merely a seabed endpoint), and drives all platform attachments !! through a finite surge/heave trajectory in a uniform current. USE CableDyn_Precision, ONLY: wp - USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, & + USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_Fallback_Count, CD_AGG_Fallback_Reset, & + CD_AGG_ModuleType, CD_AGG_Init_From_Deck, & CD_AGG_NMovingPoints, CD_AGG_NFluidNodes, & CD_AGG_GetMovingPointMesh, CD_AGG_SetFluidFields, & CD_AGG_Step_Moving, CD_AGG_CalcOutput, CD_AGG_End, CD_AGG_OK - USE CableDyn_System, ONLY: CD_System_Fallback_Count, CD_System_Fallback_Reset USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_IS_FINITE IMPLICIT NONE @@ -67,7 +67,7 @@ PROGRAM test_openfast_touchdown nstep = NINT(DURATION/DT) iter_max = 0 stalled_count = 0 - CALL CD_System_Fallback_Reset() + CALL CD_AGG_Fallback_Reset(agg) DO s = 1, nstep t = REAL(s, wp)*DT phase = omega*t @@ -109,7 +109,7 @@ PROGRAM test_openfast_touchdown EXIT END IF END DO - CALL require(CD_System_Fallback_Count() == 0, 'no EI=0 adaptive-substep fallback at 40 Hz') + CALL require(CD_AGG_Fallback_Count(agg) == 0, 'no EI=0 adaptive-substep fallback at 40 Hz') CALL require(stalled_count == 0, 'no aggregate nonlinear-stall recovery at 40 Hz') CALL require(iter_max <= 40, 'bounded nonlinear iterations over the touchdown trajectory') WRITE (*, '(A,I0,A,I0)') 'touchdown gate: grounded nodes=', grounded_nodes, ', max Newton iterations=', iter_max diff --git a/tests/test_thread_safe_sources.py b/tests/test_thread_safe_sources.py index 892342a7..442bcd28 100644 --- a/tests/test_thread_safe_sources.py +++ b/tests/test_thread_safe_sources.py @@ -23,6 +23,7 @@ import re import unittest +from collections.abc import Iterator from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -44,10 +45,6 @@ ("CableDyn_DeckDriver.f90", "warned"): "warn-once flag of a message, under an OpenMP critical", ("CableDyn_Profile.f90", "*"): "opt-in run profile (CABLEDYN_PROFILE), written only when armed", ("CableDyn_HermiteCableDynamic.f90", "prof_*"): "opt-in step profile, written only when armed", - ("CableDyn_HermiteCableDynamic.f90", "n_substep_recoveries"): "process-wide diagnostics tally", - ("CableDyn_System.f90", "n_fallback_entries"): "process-wide diagnostics tally", - ("CableDyn_CosseratAssemble.f90", "CD_COSASM_*"): "process-wide diagnostics tallies", - ("CableDyn_CosseratDynamic.f90", "CD_COSDYN_*"): "process-wide diagnostics tallies", ("cabledyn.f90", "printed"): "the driver program prints its profile once", } @@ -64,13 +61,14 @@ ) -def statements(path: Path): +def statements(path: Path) -> Iterator[tuple[int, str]]: """(line number, statement) with comments, continuations and semicolons resolved.""" - buf, start = "", None + buf, start = "", 0 for no, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): if raw.lstrip().startswith("#"): continue - out, quote = [], None + out: list[str] = [] + quote: str | None = None for ch in raw: if quote: out.append(ch) @@ -88,19 +86,22 @@ def statements(path: Path): continue if buf and text.startswith("&"): text = text[1:] - if start is None: + if not buf: start = no if text.endswith("&"): buf += text[:-1] + " " continue - line, buf, line_no, start = buf + text, "", start, None + line, buf, line_no = buf + text, "", start for stmt in split_top(line, ";"): if stmt.strip(): yield line_no, stmt.strip() def split_top(text: str, sep: str) -> list[str]: - parts, depth, cur, quote = [], 0, [], None + parts: list[str] = [] + cur: list[str] = [] + depth = 0 + quote: str | None = None for ch in text: if quote: cur.append(ch) @@ -127,7 +128,7 @@ def without_strings(text: str) -> str: class Scope: - def __init__(self, kind: str, name: str): + def __init__(self, kind: str, name: str) -> None: self.kind, self.name = kind, name self.contains = False self.internal: list[str] = [] @@ -135,7 +136,7 @@ def __init__(self, kind: str, name: str): self.body: list[tuple[int, str, Scope]] = [] -def scan(path: Path): +def scan(path: Path) -> Iterator[tuple[str, int, str, str]]: """Yield (kind, line, scope name, detail) findings of one file.""" stack: list[Scope] = [] in_type = in_interface = 0 @@ -181,9 +182,10 @@ def scan(path: Path): stack[-1].contains = True continue unit = next((s for s in reversed(stack) if s.kind in ("unit", "program")), None) - for scope in stack: - if scope.kind in ("unit", "program"): - scope.body.append((no, stmt, unit)) + if unit is not None: + for scope in stack: + if scope.kind in ("unit", "program"): + scope.body.append((no, stmt, unit)) where = unit.name if unit else (stack[-1].name if stack else "?") if re.match(r"^(data\s+\w|common\b)", low): yield "DATA/COMMON", no, where, stmt @@ -195,7 +197,7 @@ def scan(path: Path): continue attrs, names = stmt.split("::", 1) attrs_low = attrs.lower() - variables = [re.match(r"\s*(\w+)", n).group(1) for n in split_top(names, ",")] + variables = [m.group(1) for n in split_top(names, ",") if (m := re.match(r"\s*(\w+)", n))] if unit is not None: unit.declared.update(v.lower() for v in variables) if "parameter" in attrs_low: @@ -214,11 +216,11 @@ def scan(path: Path): yield "INITIALISED LOCAL", no, where, stmt break for host in hosts: - names = set(host.internal) + internal_names = set(host.internal) for no, stmt, inside in host.body: code = without_strings(stmt).lower() # in its own body the name is the result; a local declaration hides it - for name in names - {inside.name.lower()} - inside.declared: + for name in internal_names - {inside.name.lower()} - inside.declared: for m in re.finditer(r"(? bool: class ThreadSafeSources(unittest.TestCase): - def setUp(self): + def setUp(self) -> None: self.findings = [(p.name, *f) for p in SOURCES for f in scan(p)] self.assertGreater(len(SOURCES), 40) - def test_no_closures(self): + def test_no_closures(self) -> None: bad = [f for f in self.findings if f[1] == "CLOSURE"] self.assertEqual(bad, [], "internal procedures passed as procedure values") - def test_no_implicit_static_storage(self): + def test_no_implicit_static_storage(self) -> None: bad = [ f for f in self.findings @@ -256,13 +258,13 @@ def test_no_implicit_static_storage(self): ] self.assertEqual(bad, [], "locals in static storage") - def test_static_storage_is_reviewed(self): + def test_static_storage_is_reviewed(self) -> None: bad = [f for f in self.findings if f[1] == "STATIC" and not reviewed(f[0], f[4])] self.assertEqual(bad, [], "static storage not in REVIEWED_STATIC") n = sum(1 for f in self.findings if f[1] == "STATIC") print(f"{n} reviewed variables in static storage in {len(SOURCES)} files") - def test_build_makes_locals_automatic(self): + def test_build_makes_locals_automatic(self) -> None: cmake = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") for flag in ("-frecursive>", "/Qauto>", "-auto>"): self.assertTrue(flag in cmake, f"CMakeLists.txt does not pass {flag[:-1]}") @@ -275,7 +277,7 @@ def test_build_makes_locals_automatic(self): for tool in tools: self.assertIn('LocalVariableStorage="localStorageAutomatic"', tool) - def test_audit_sees_a_closure_and_an_initialised_local(self): + def test_audit_sees_a_closure_and_an_initialised_local(self) -> None: # the checks themselves: a closure and an implicit SAVE in a scratch source probe = Path(__file__).with_name("thread_safe_probe.f90.tmp") probe.write_text( From e14d982d345023d308055ba9d2831148afa46782 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 08:02:19 +0900 Subject: [PATCH 11/19] test(driver): a profile total of 0.000 s is 0.0 % of itself driver_profile_failure failed on the ifx release build when the failing run (three steps of a short deck) took less than half a millisecond: the profile then prints "total 0.000 s 0.0 %", since the driver gives no share of a zero total, and the check required 100.0 %. The total row now reads either a positive share of 100.0 % or exactly 0.000 s and 0.0 %; any other share still fails (checked against "0.012 s 0.0 %"). The same row of check_driver_profile.cmake takes the same form. The checks of the phase rows are unchanged, so a failed run still charges nothing to the finalisation it never reached. Signed-off-by: Jae Hoon Seo --- tests/check_driver_profile.cmake | 4 +++- tests/check_driver_profile_failure.cmake | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/check_driver_profile.cmake b/tests/check_driver_profile.cmake index 56aee54d..7352002f 100644 --- a/tests/check_driver_profile.cmake +++ b/tests/check_driver_profile.cmake @@ -49,7 +49,9 @@ foreach(row "\n outputs +[0-9]+\\.[0-9]+ s" "\n progress and bookkeeping +[0-9]+\\.[0-9]+ s" "\n finalisation +[0-9]+\\.[0-9]+ s" - "\n total +[0-9]+\\.[0-9]+ s +100\\.0 %" + # the total is 100 % of itself, or 0.000 s and 0.0 % when the whole run took less than half a + # millisecond (a fast build on the short deck): the driver gives no share of a zero total + "\n total +([0-9]+\\.[0-9]+ s +100\\.0|0\\.000 s +0\\.0) %" "\n March: [1-9][0-9]* committed step\\(s\\), [0-9]+\\.[0-9]+ ms per step\\.") if(NOT profiled MATCHES "${row}") message(FATAL_ERROR "the profiled stdout lacks \"${row}\":\n${profiled}") diff --git a/tests/check_driver_profile_failure.cmake b/tests/check_driver_profile_failure.cmake index ff924c4c..b0d5bde4 100644 --- a/tests/check_driver_profile_failure.cmake +++ b/tests/check_driver_profile_failure.cmake @@ -20,7 +20,9 @@ foreach(row "Run-time profile \\(CABLEDYN_PROFILE\\), wall-clock time:" "\n dynamic march +[0-9]+\\.[0-9]+ s" "\n finalisation +0\\.000 s +0\\.0 %" - "\n total +[0-9]+\\.[0-9]+ s +100\\.0 %") + # the total is 100 % of itself, or 0.000 s and 0.0 % when the whole run took less than half a + # millisecond (a fast build on the short deck): the driver gives no share of a zero total + "\n total +([0-9]+\\.[0-9]+ s +100\\.0|0\\.000 s +0\\.0) %") if(NOT out MATCHES "${row}") message(FATAL_ERROR "the stdout of the failed run lacks \"${row}\":\n${out}") endif() From 8ee30fc21cd6d5506806e81fa482f402cbc07d8c Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 17:33:33 +0900 Subject: [PATCH 12/19] build(intel): /fp:precise for every ifx build and the OpenFAST projects The static Windows release compiled with /fp:precise, but every other ifx build kept the Intel default /fp:fast: a plain ifx CMake build (with or without OpenMP), the core the OpenFAST CMake route builds as an external project, its adapter target, and the OpenFAST Visual Studio project. Under /fp:fast the gates that hold two routes to the same bits fail and subnormal deck values read as zero, as they did in the release before /fp:precise. CMakeLists.txt now passes /fp:precise (-fp-model precise off Windows) to every Fortran compile of an IntelLLVM build, in every configuration; the static release takes it from there instead of its own flag list. The OpenFAST CMake patch gives the adapter target the same model, and every configuration of the Visual Studio project sets FloatingPointModel="precise". GNU builds are unchanged. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 10 +++++++ CMakeLists.txt | 27 +++++++++++++------ integration/openfast/README.md | 5 +++- .../patches/0006-cabledyn-cmake.patch | 13 +++++++-- .../openfast/vs-build/CableDyn.vfproj.in | 16 +++++------ 5 files changed, 52 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d3c47e7..ef10f50f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -294,6 +294,16 @@ All notable changes to CableDyn are recorded in this file. The format follows ### Changed +- Every Intel ifx build compiles CableDyn with the value-safe floating-point model, + `/fp:precise` (`-fp-model precise` off Windows): the static Windows release and wheel, every + other CMake build and configuration with ifx (with or without OpenMP, including the core that + the OpenFAST CMake route builds, and its adapter), and every configuration of the OpenFAST + Visual Studio project. The ifx default, `/fp:fast`, reassociates sums, divides by + multiplying with the reciprocal and flushes subnormals to zero, differently at every inlined + call site, so the gates that hold two routes to the same bits failed (a zero control command + against an uncontrolled cable, a held Coupled End B against a Fixed one, a committed against a + re-derived torque), subnormal deck values read as zero and the clamped-cable elastica secant + stalled. Results of ifx builds change at round-off; gfortran builds are unchanged. - The macOS wheel needs macOS 15 or newer on Apple silicon (0.3.0: macOS 14). It is built on the macOS 15 runner, as GitHub retires the macOS 14 runner image on 2 November 2026, and its Homebrew gfortran and OpenBLAS support no older macOS. On macOS 14, build from source. diff --git a/CMakeLists.txt b/CMakeLists.txt index fba97db2..d6256229 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,14 +46,9 @@ if(CABLEDYN_STATIC_WINDOWS_RELEASE) # driver below, or the OpenFAST Release|x64 project, which enables whole-program # optimisation). # - # /fp:precise: IFX defaults to /fp:fast, which lets it reassociate sums, replace a division by - # a multiplication with the reciprocal, and flush subnormals to zero, differently at every - # inlined call site. The same expression then rounds differently on two code paths, so the - # gates that hold two routes to the same bits (a zero control command and an uncontrolled - # cable, a held Coupled End B and a Fixed one, a committed and a re-derived torque) fail, a - # subnormal deck value reads as zero, and a secant iteration can stall on equal residuals. - # The reference LAPACK is built with /fp:precise as well. - string(APPEND CMAKE_Fortran_FLAGS " /libs:static /heap-arrays:1024 /Qipo /fp:precise") + # The floating-point model is /fp:precise, as in every IFX build (below); the reference + # LAPACK is built with /fp:precise as well. + string(APPEND CMAKE_Fortran_FLAGS " /libs:static /heap-arrays:1024 /Qipo") # CMake does not pass the compile flags to an IFX executable link on Windows. The shared # library (the Windows wheel's cabledyn.dll) links the same IPO objects, so it needs the # flag as well: without it IFX hands the intermediate objects to link.exe (LNK1107). @@ -166,6 +161,22 @@ elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "IntelLLVM") add_compile_options($<$:-auto>) endif() endif() +# The value-safe floating-point model in every IFX build and configuration: /fp:precise +# (-fp-model precise off Windows), for the core, the driver, the tests, the wheel and the +# OpenFAST build of the core alike. IFX defaults to /fp:fast, which lets it reassociate sums, +# replace a division by a multiplication with the reciprocal and flush subnormals to zero, +# differently at every inlined call site. The same expression then rounds differently on two +# code paths, so the gates that hold two routes to the same bits (a zero control command and +# an uncontrolled cable, a held Coupled End B and a Fixed one, a committed and a re-derived +# torque) fail, a subnormal deck value reads as zero, and a secant iteration can stall on +# equal residuals. GNU builds keep their default, value-safe model (no -ffast-math). +if(CMAKE_Fortran_COMPILER_ID STREQUAL "IntelLLVM") + if(WIN32) + add_compile_options($<$:/fp:precise>) + else() + add_compile_options("$<$:SHELL:-fp-model precise>") + endif() +endif() # GNU builds on Windows (MinGW-w64): every executable gets a 64 MiB stack reserve instead of # the 2 MiB MinGW default. With OpenMP, gfortran places fixed-size local arrays on the stack # (-fopenmp implies -frecursive), and the stack depth of the OpenBLAS kernels varies with the diff --git a/integration/openfast/README.md b/integration/openfast/README.md index 19b72aba..94fe0f3d 100644 --- a/integration/openfast/README.md +++ b/integration/openfast/README.md @@ -51,7 +51,10 @@ whose size is known only at run time are placed on the heap rather than on the ` Every configuration also makes local variables automatic (`/Qauto`, as the CMake build of the core does with every compiler): without OpenMP, ifx keeps fixed-size local arrays and `CHARACTER` locals in static storage, which every thread shares, and the turbines of a FAST.Farm run, like -separate C API handles, may step on several threads at once. +separate C API handles, may step on several threads at once. Every configuration, and the +adapter target of the CMake route, compiles with the value-safe floating-point model +(`/fp:precise`, `-fp-model precise` off Windows), as every Intel build of the core does: the +ifx default, `/fp:fast`, may reassociate sums and flush subnormals to zero. ## License of modified files diff --git a/integration/openfast/patches/0006-cabledyn-cmake.patch b/integration/openfast/patches/0006-cabledyn-cmake.patch index affd82eb..27e0b64f 100644 --- a/integration/openfast/patches/0006-cabledyn-cmake.patch +++ b/integration/openfast/patches/0006-cabledyn-cmake.patch @@ -1,9 +1,9 @@ diff --git a/modules/cabledyn/CMakeLists.txt b/modules/cabledyn/CMakeLists.txt new file mode 100644 -index 000000000..40f9728a6 +index 000000000..be1a9133b --- /dev/null +++ b/modules/cabledyn/CMakeLists.txt -@@ -0,0 +1,185 @@ +@@ -0,0 +1,194 @@ +# +# Copyright (C) 2026 Jae Hoon Seo, SMI Lab, Inha University +# @@ -148,6 +148,15 @@ index 000000000..40f9728a6 + ${CABLEDYN_ROOT}/src/openfast/CableDyn_Types.f90 +) +target_link_libraries(cabledynlib cabledyn_core seastlib nwtclibs) ++if (CMAKE_Fortran_COMPILER_ID STREQUAL "IntelLLVM") ++ # The value-safe floating-point model for the adapter, as the core's own build sets for ++ # every IFX build (see CableDyn's CMakeLists.txt): IFX defaults to /fp:fast. ++ if (WIN32) ++ target_compile_options(cabledynlib PRIVATE /fp:precise) ++ else() ++ target_compile_options(cabledynlib PRIVATE "SHELL:-fp-model precise") ++ endif() ++endif() +if (TARGET cabledyn_core_ep) + # the imported core cannot carry dependencies itself; the consumer orders the build + add_dependencies(cabledynlib cabledyn_core_ep) diff --git a/integration/openfast/vs-build/CableDyn.vfproj.in b/integration/openfast/vs-build/CableDyn.vfproj.in index 3be6d8e2..7f959e26 100644 --- a/integration/openfast/vs-build/CableDyn.vfproj.in +++ b/integration/openfast/vs-build/CableDyn.vfproj.in @@ -5,35 +5,35 @@ - + - + - + - + - + - + - + - + From 6d68a5f844c17658d1aafc022d994141a67f2202 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 20:47:29 +0900 Subject: [PATCH 13/19] build(intel): heap arrays above 1 MiB in every ifx build Only the static Windows release compiled with /heap-arrays:1024 (and the OpenFAST Visual Studio project with HeapArrays="1024"). A non-static ifx CMake build (/O2 /Qauto -Qiopenmp, the configuration of a plain ifx build and of the core in the OpenFAST CMake route) kept run-time-sized arrays and array temporaries on the stack: test_hermite_node_reaction on the 2835-node mixed IEA-15 MW deck and the fine-mesh deck FINE_A01557 of cable_statics_matrix stopped with forrtl severe (170), stack overflow, in the 1 MiB stack of an MSVC-linked program, and passed with a 64 MiB reserve. CMakeLists.txt now passes /heap-arrays:1024 (-heap-arrays 1024 off Windows) to every Fortran compile of an IntelLLVM build, next to the floating-point model; the static release takes it from there instead of its own flag list (same flags, the objects unchanged: every example deck bit-identical). With it both tests pass in the non-static build. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 6 ++++++ CMakeLists.txt | 26 ++++++++++++++++---------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef10f50f..661a9a3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -401,6 +401,12 @@ All notable changes to CableDyn are recorded in this file. The format follows is now laid from End A, the line seen from its other end, and its nodes put back in order. The deck starts at the same equilibrium as before on Windows (1e-7 m, 6e-4 N), and moving the fixed rod by 1 ulp either way or 1e-12 m up leaves the rod's start unchanged (0 m). +- A non-static ifx build (a plain CMake build with ifx, or the core of the OpenFAST CMake route) + kept run-time-sized arrays and array temporaries on the stack, as only the static Windows + release compiled with `/heap-arrays`: the 2835-node mixed IEA-15 MW deck and a fine-mesh deck of + the statics matrix overflowed the 1 MiB stack of an MSVC-linked program. Every ifx build now + compiles with `/heap-arrays:1024` (`-heap-arrays 1024` off Windows), as the static release and + the OpenFAST Visual Studio project did; the static release is unchanged. - A rod numbered as a body no longer joins the body's attachment points. A `RodA/B` end point keeps its rod's id where a `Body` point keeps its body's, and the body's point list took every point with its id: a rod end POINT row listed before the body's points became the body's diff --git a/CMakeLists.txt b/CMakeLists.txt index d6256229..08f07e5e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -31,13 +31,8 @@ if(CABLEDYN_STATIC_WINDOWS_RELEASE) # The release executables target x86-64-v3 (CABLEDYN_TARGET_AVX2 below). set(CABLEDYN_TARGET_AVX2 ON CACHE BOOL "" FORCE) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded" CACHE STRING "" FORCE) - # Large finite-EI meshes create compiler-generated array temporaries in deeply - # nested residual/assembly calls. Keep those temporaries off the process stack; - # the released executable also receives a generous reserve below. The size - # threshold keeps run-time-sized arrays and temporaries on the heap but leaves - # compile-time-sized locals up to 1 MiB on the stack: with a bare /heap-arrays, - # IFX 2025.3 heap-allocates the host frame of every procedure with internal - # procedures and never frees it, leaking memory on each call. + # Run-time-sized arrays and array temporaries go to the heap (/heap-arrays:1024), as in + # every IFX build (below); the released executable also receives a generous reserve below. # # /Qipo: the element, hydrodynamic, and assembly kernels live in separate modules # and are called per element and per Newton iteration; without interprocedural @@ -48,7 +43,7 @@ if(CABLEDYN_STATIC_WINDOWS_RELEASE) # # The floating-point model is /fp:precise, as in every IFX build (below); the reference # LAPACK is built with /fp:precise as well. - string(APPEND CMAKE_Fortran_FLAGS " /libs:static /heap-arrays:1024 /Qipo") + string(APPEND CMAKE_Fortran_FLAGS " /libs:static /Qipo") # CMake does not pass the compile flags to an IFX executable link on Windows. The shared # library (the Windows wheel's cabledyn.dll) links the same IPO objects, so it needs the # flag as well: without it IFX hands the intermediate objects to link.exe (LNK1107). @@ -170,11 +165,22 @@ endif() # an uncontrolled cable, a held Coupled End B and a Fixed one, a committed and a re-derived # torque) fail, a subnormal deck value reads as zero, and a secant iteration can stall on # equal residuals. GNU builds keep their default, value-safe model (no -ffast-math). +# +# Run-time-sized arrays and the compiler's array temporaries on the heap, in every IFX build: +# /heap-arrays:1024 (-heap-arrays 1024 off Windows). The library runs on threads whose stack the +# host sets (1 MiB for python.exe and an MSVC-linked program: the stack_c_api and c_api_threads +# gates), and large finite-EI meshes create array temporaries in deeply nested residual and +# assembly calls; without the option a non-static IFX build overflows those stacks. The size +# threshold leaves compile-time-sized locals up to 1 MiB on the stack: with a bare /heap-arrays, +# IFX 2025.3 heap-allocates the host frame of every procedure with internal procedures and +# never frees it, leaking memory on each call. if(CMAKE_Fortran_COMPILER_ID STREQUAL "IntelLLVM") if(WIN32) - add_compile_options($<$:/fp:precise>) + add_compile_options($<$:/fp:precise> + $<$:/heap-arrays:1024>) else() - add_compile_options("$<$:SHELL:-fp-model precise>") + add_compile_options("$<$:SHELL:-fp-model precise>" + "$<$:SHELL:-heap-arrays 1024>") endif() endif() # GNU builds on Windows (MinGW-w64): every executable gets a 64 MiB stack reserve instead of From 4465cfb98ef6982e3500e1473ee244a4eeb68e79 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 18:57:24 +0900 Subject: [PATCH 14/19] fix(release): openfast.exe names its OpenFAST base and CableDyn version, not v5.0.0-dirty OpenFAST stamps its version with `git describe --dirty` (the VersionInfo pre-build step vs-build/CreateGitVersion.bat, and git_describe in modules/version/CMakeLists.txt). The integration patches modify the pinned v5.0.0 checkout, so the released openfast.exe called itself OpenFAST-v5.0.0-dirty. Both build routes now stamp '-CableDyn-', e.g. OpenFAST-v5.0.0-CableDyn-0.3.0. The OpenFAST part is `git describe --tags --abbrev=8` of the checked-out commit (no --dirty), i.e. the unpatched base, so a later base bump stays correct; the CableDyn part is the project version of CMakeLists.txt. A base not described by a release tag (vX.Y.Z or vX.Y.Z-N-g) stops the build. - integrate_openfast_vs_solution.ps1 replaces CreateGitVersion.bat with a script that writes the fixed header, and writes the header itself; a rerun writes the same bytes. - New patch 0021 sets the same string in OpenFAST's CMake build. - build_static_windows.ps1 fails unless `openfast.exe -v` prints exactly OpenFAST- and no "dirty"; openfast_build_gate.ps1 checks the run log of the CMake route the same way. - The release workflow checks out OpenFAST with its history and tags (fetch-depth: 0), which `git describe --tags` needs. - check_release_metadata.py checks that the installation, release and integration docs state the identity for the current version; NOTICE lists the modified version CMakeLists.txt. Signed-off-by: Jae Hoon Seo --- .github/workflows/release-windows-static.yml | 2 + CHANGELOG.md | 5 +++ DEVELOPMENT.md | 4 +- NOTICE | 6 +-- RELEASE.md | 4 +- doc/installation.rst | 3 +- integration/openfast/README.md | 15 ++++++- .../integrate_openfast_vs_solution.ps1 | 42 ++++++++++++++++++- integration/openfast/openfast_build_gate.ps1 | 11 ++++- .../openfast/patches/0021-version-cmake.patch | 42 +++++++++++++++++++ release/build_static_windows.ps1 | 20 +++++++++ release/check_release_metadata.py | 5 +++ tests/test_documentation.py | 14 +++++++ 13 files changed, 163 insertions(+), 10 deletions(-) create mode 100644 integration/openfast/patches/0021-version-cmake.patch diff --git a/.github/workflows/release-windows-static.yml b/.github/workflows/release-windows-static.yml index 33ed671b..eea6de91 100644 --- a/.github/workflows/release-windows-static.yml +++ b/.github/workflows/release-windows-static.yml @@ -32,6 +32,8 @@ jobs: repository: OpenFAST/openfast ref: 2895884d2be01862173c88d70f86b358d2f1a50a path: openfast + # the history and tags: openfast.exe names its base by `git describe --tags` + fetch-depth: 0 persist-credentials: false - name: Check out the pinned OpenFAST regression model diff --git a/CHANGELOG.md b/CHANGELOG.md index 661a9a3e..4502e8ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -582,6 +582,11 @@ All notable changes to CableDyn are recorded in this file. The format follows side, or by the sign of a round-off component: in OpenFAST about half the rows of a cable in the x-z plane read 359.9x. A line whose chord heads within 45° of +X now reports its azimuths in (−180, 180], every other line in [0, 360) as before. +- The CableDyn-enabled `openfast.exe` named itself `OpenFAST-v5.0.0-dirty`: OpenFAST stamps its + version with `git describe --dirty`, and the integration patches modify the checkout. Built + through the Visual Studio solution or through CMake it now reads + `OpenFAST-v5.0.0-CableDyn-`, the describe of the unpatched OpenFAST base and + the CableDyn version, and the release build fails unless `openfast.exe -v` prints exactly that. ## [0.3.0] - 2026-10-23 diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 2f7bfa8b..704a8b10 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -242,8 +242,8 @@ and a MinGW `FAST.Farm.exe` (`-DBUILD_FASTFARM=ON`) with the default stack stops stack overflow while ElastoDyn initialises. `openfast_build_gate.ps1` builds `openfast.exe`, runs a `CompMooring = 5` case, -checks that the CableDyn banner appears in the log, and checks that the output is -finite. +checks that the CableDyn banner appears in the log, that the executable names itself +`OpenFAST--CableDyn-`, and that the output is finite. An `openfast.exe` built this way through CMake does not embed the UTF-8 active-code-page manifest (`app/utf8_code_page.manifest`), so on Windows it may not diff --git a/NOTICE b/NOTICE index 1bcae455..b56bb457 100644 --- a/NOTICE +++ b/NOTICE @@ -22,9 +22,9 @@ OpenFAST (Apache License, Version 2.0) https://github.com/OpenFAST/openfast * integration/openfast/patches/ contains patches that MODIFY OpenFAST source - files (the root and openfast-library CMakeLists.txt; FAST_AeroMap.f90, - FAST_Funcs.f90, FAST_Mapping.f90, FAST_ModGlue.f90, FAST_Registry.txt, - FAST_Solver.f90, FAST_Subs.f90, and FAST_Types.f90 in + files (the root, openfast-library, and version CMakeLists.txt; + FAST_AeroMap.f90, FAST_Funcs.f90, FAST_Mapping.f90, FAST_ModGlue.f90, + FAST_Registry.txt, FAST_Solver.f90, FAST_Subs.f90, and FAST_Types.f90 in modules/openfast-library/src; FAST_Farm_IO.f90, FAST_Farm_Registry.txt, FAST_Farm_Subs.f90, and FAST_Farm_Types.f90 in glue-codes/fast-farm/src). The modified files remain under the Apache License, Version 2.0, and diff --git a/RELEASE.md b/RELEASE.md index ded58fe6..19dd0d58 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -102,7 +102,9 @@ solution, which still supplies the single-precision routines they do not build. The build fails if either executable imports a non-system DLL or lacks the UTF-8 active-code-page manifest (`release/check_static_windows_binary.ps1`), or if the standalone and `CompMooring = 5` smoke cases fail with a system-only `PATH` or from -a folder named in mixed scripts. +a folder named in mixed scripts. It also fails unless `openfast.exe -v` names the +executable `OpenFAST-v5.0.0-CableDyn-0.3.0`: the OpenFAST base and the CableDyn version, +never a `-dirty` describe of the patched tree. The release workflow (`.github/workflows/release-windows-static.yml`) produces exactly these assets: diff --git a/doc/installation.rst b/doc/installation.rst index bad8fb6c..c264d5a9 100644 --- a/doc/installation.rst +++ b/doc/installation.rst @@ -34,7 +34,8 @@ What is on the release page * - ``openfast.exe`` - OpenFAST v5.0.0 (maintained by NLR, the National Laboratory of the Rockies, formerly NREL) with CableDyn built in as ``CompMooring = 5``; stock MoorDyn - (``CompMooring = 3``) is still available in the same binary (:doc:`openfast`) + (``CompMooring = 3``) is still available in the same binary (:doc:`openfast`). It names + itself ``OpenFAST-v5.0.0-CableDyn-0.3.0`` (``openfast.exe -v`` and the start of every run). * - ``cabledyn-0.3.0-py3-none-any.whl`` - the pure-Python package: deck editing, case generation, driver automation, result readers, fatigue and spectral post-processing (:doc:`python`) diff --git a/integration/openfast/README.md b/integration/openfast/README.md index 94fe0f3d..74cb9fb4 100644 --- a/integration/openfast/README.md +++ b/integration/openfast/README.md @@ -16,7 +16,7 @@ this repository. | --- | --- | | `patches/*.patch` | Patch series, one file per patch; `0006` and `0016`–`0020` add new CableDyn-owned files, the others modify upstream files | | `prepare_openfast_source.ps1` | Checks the upstream revision and a clean worktree, then applies the series | -| `integrate_openfast_vs_solution.ps1` | Adds CableDyn to the Intel Fortran Visual Studio solution of the Windows release | +| `integrate_openfast_vs_solution.ps1` | Adds CableDyn to the Intel Fortran Visual Studio solution of the Windows release and sets its version string | | `vs-build/CableDyn.vfproj.in` | Visual Studio project template used by that script | | `openfast_build_gate.ps1` | Builds a configured OpenFAST tree and runs a coupled `CompMooring = 5` smoke case | @@ -56,6 +56,19 @@ adapter target of the CMake route, compiles with the value-safe floating-point m (`/fp:precise`, `-fp-model precise` off Windows), as every Intel build of the core does: the ifx default, `/fp:fast`, may reassociate sums and flush subnormals to zero. +## Version string + +OpenFAST names its version with `git describe --dirty`, which would read `v5.0.0-dirty` on +the patched tree. A CableDyn-enabled executable names itself +`OpenFAST--CableDyn-` instead, here +`OpenFAST-v5.0.0-CableDyn-0.3.0` (printed by `openfast.exe -v` and at the start of every run). +The OpenFAST part is `git describe --tags --abbrev=8` of the checked-out commit, the +unpatched base; the CableDyn part is the project version in the CableDyn `CMakeLists.txt`. +Patch `0021` sets it in the CMake build, and `integrate_openfast_vs_solution.ps1` in the +Visual Studio solution, whose `vs-build/CreateGitVersion.bat` it replaces. Both stop unless +the base is described by a release tag (`vX.Y.Z` or `vX.Y.Z-N-g`), so the checkout +needs its tags: a `git clone` has them, a single-commit shallow fetch does not. + ## License of modified files The patches modify OpenFAST source files licensed under the Apache License, Version 2.0. The diff --git a/integration/openfast/integrate_openfast_vs_solution.ps1 b/integration/openfast/integrate_openfast_vs_solution.ps1 index af8c8acc..a440abf8 100644 --- a/integration/openfast/integrate_openfast_vs_solution.ps1 +++ b/integration/openfast/integrate_openfast_vs_solution.ps1 @@ -41,6 +41,29 @@ $LinkLibraries = @($LinkLibraries | ForEach-Object { (Resolve-Path -LiteralPath $_).Path }) +# Version stamp. The pre-build step of the VersionInfo project, vs-build\CreateGitVersion.bat, +# writes vs-build\gitVersionInfo.h from `git describe --dirty`, so a patched tree would call +# itself '-dirty'. Name the build after its OpenFAST base and the CableDyn version instead, +# '-CableDyn-'. `git describe` without --dirty describes the +# checked-out commit, the unpatched base, whether or not the patch series is applied; the +# CableDyn version is the project version of the CableDyn CMakeLists.txt. The pre-build script +# is replaced as a whole and the header written from the same string (at the end of this +# script), so a rerun leaves both unchanged. +$describeOut = & git -C $OpenFASTRoot describe --tags --abbrev=8 +if ($LASTEXITCODE -ne 0 -or $null -eq $describeOut) { + throw "git describe found no tag for the OpenFAST checkout $OpenFASTRoot (fetch its tags)" +} +$baseDescribe = "$describeOut".Trim() +if ($baseDescribe -notmatch '^v\d+\.\d+\.\d+(-\d+-g[0-9a-f]{8,})?$') { + throw "the OpenFAST base describes as '$baseDescribe', not as a release tag vX.Y.Z or vX.Y.Z-N-gHASH" +} +$cableDynCMake = Get-Content -LiteralPath (Join-Path $CableDynRoot 'CMakeLists.txt') -Raw +if ($cableDynCMake -notmatch 'project\(CableDynCore VERSION (\d+\.\d+\.\d+)') { + throw 'CableDyn project version not found in CMakeLists.txt' +} +$versionStamp = "$baseDescribe-CableDyn-$($Matches[1])" +$versionDefine = "#define GIT_VERSION_INFO '$versionStamp'" + function Escape-Xml([string]$Value) { return [Security.SecurityElement]::Escape($Value) } @@ -175,4 +198,21 @@ $settings.Encoding = New-Object Text.UTF8Encoding($false) $writer = [Xml.XmlWriter]::Create($openfastProject, $settings) try { $vf.Save($writer) } finally { $writer.Dispose() } -Write-Host 'PASS: CableDyn added to OpenFAST Visual Studio Release solution' +# The pre-build step runs in vs-build\modules; the VersionInfo project includes the header +# through GIT_INCLUDE_FILE='..\gitVersionInfo.h'. +$versionScript = @( + '@ECHO off' + 'REM Written by CableDyn integration/openfast/integrate_openfast_vs_solution.ps1: the OpenFAST' + 'REM base and the CableDyn version this executable is built from.' + ">..\gitVersionInfo.h ECHO $versionDefine" + 'EXIT /B 0' +) -join "`r`n" +[IO.File]::WriteAllText((Join-Path $OpenFASTRoot 'vs-build\CreateGitVersion.bat'), "$versionScript`r`n", + [Text.Encoding]::ASCII) +$versionHeader = Join-Path $OpenFASTRoot 'vs-build\gitVersionInfo.h' +if (-not (Test-Path -LiteralPath $versionHeader) -or + (Get-Content -LiteralPath $versionHeader -Raw) -ne "$versionDefine`r`n") { + [IO.File]::WriteAllText($versionHeader, "$versionDefine`r`n", [Text.Encoding]::ASCII) +} + +Write-Host "PASS: CableDyn added to OpenFAST Visual Studio Release solution (version $versionStamp)" diff --git a/integration/openfast/openfast_build_gate.ps1 b/integration/openfast/openfast_build_gate.ps1 index a11d7a99..c04946ba 100644 --- a/integration/openfast/openfast_build_gate.ps1 +++ b/integration/openfast/openfast_build_gate.ps1 @@ -15,7 +15,8 @@ # to openfast.exe with no errors; # 2. IDENTITY -- a coupled smoke run actually initializes the CableDyn module (the # DispNVD identity banner appears in the OpenFAST log output; a build that -# silently fell back to another mooring module fails here); +# silently fell back to another mooring module fails here), and the +# executable names itself OpenFAST--CableDyn-; # 3. RUN -- the smoke case completes (exit 0) and its .out carries finite data to the # final row (no NaN/Infinity). # @@ -192,6 +193,14 @@ Step ("run smoke (TMax = {0} s)" -f $TMax) { if ($logText -notmatch 'Running CableDyn \(') { $script:failures += 'IDENTITY: the CableDyn module banner never appeared -- CompMooring=5 did not initialize' } + # the executable names its OpenFAST base and the CableDyn version (patch 0021), never a + # '-dirty' describe of the patched tree + $cdCMake = Get-Content -LiteralPath (Join-Path $PSScriptRoot '..\..\CMakeLists.txt') -Raw + $cdVersion = [regex]::Match($cdCMake, 'project\(CableDynCore VERSION (\d+\.\d+\.\d+)').Groups[1].Value + $idPattern = '(?m)^\s*OpenFAST-v\d+\.\d+\.\d+(-\d+-g[0-9a-f]+)?-CableDyn-' + [regex]::Escape($cdVersion) + '\s*$' + if ($logText -notmatch $idPattern -or $logText -match 'OpenFAST-\S*dirty') { + $script:failures += "IDENTITY: the OpenFAST banner does not read OpenFAST--CableDyn-$cdVersion" + } } if (-not (Test-Path $outFile)) { diff --git a/integration/openfast/patches/0021-version-cmake.patch b/integration/openfast/patches/0021-version-cmake.patch new file mode 100644 index 00000000..9c4afd82 --- /dev/null +++ b/integration/openfast/patches/0021-version-cmake.patch @@ -0,0 +1,42 @@ +diff --git a/modules/version/CMakeLists.txt b/modules/version/CMakeLists.txt +index 1c714c368..8a91bea44 100644 +--- a/modules/version/CMakeLists.txt ++++ b/modules/version/CMakeLists.txt +@@ -22,10 +22,34 @@ if( DEFINED GIT_DESCRIBE ) + "Version information has been set as a CMake flag. This should only used when the git-version cannot be set automatically." + ) + else() +- include(GetGitRevisionDescription) +- git_describe(GIT_DESCRIBE) ++ # CableDyn integration: the CableDyn patch series leaves the worktree modified, so the ++ # upstream `git describe --dirty` would call every CableDyn build '-dirty'. Describe ++ # the checked-out commit instead (no --dirty), which is the unpatched OpenFAST base. ++ find_package(Git QUIET) ++ if( GIT_FOUND ) ++ execute_process(COMMAND "${GIT_EXECUTABLE}" describe --tags --abbrev=8 ++ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" ++ RESULT_VARIABLE _cabledyn_describe_result ++ OUTPUT_VARIABLE GIT_DESCRIBE ++ ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) ++ endif() ++ if( NOT GIT_FOUND OR NOT _cabledyn_describe_result EQUAL 0 OR ++ NOT GIT_DESCRIBE MATCHES "^v[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9]+-g[0-9a-f]+)?$" ) ++ message( FATAL_ERROR ++ "The OpenFAST checkout is not described by a release tag (git describe --tags: '${GIT_DESCRIBE}'). " ++ "Fetch its tags (git fetch --tags), or set -DGIT_DESCRIBE=." ++ ) ++ endif() + endif() +-add_definitions(-DGIT_VERSION_INFO="${GIT_DESCRIBE}") ++# CableDyn integration: the executables name the CableDyn version they carry, the project ++# version of CABLEDYN_ROOT/CMakeLists.txt: '-CableDyn-'. ++file(STRINGS "${CABLEDYN_ROOT}/CMakeLists.txt" _cabledyn_project REGEX "^project\\(CableDynCore VERSION ") ++string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" _cabledyn_version "${_cabledyn_project}") ++if( NOT _cabledyn_version ) ++ message( FATAL_ERROR "No CableDyn project version in ${CABLEDYN_ROOT}/CMakeLists.txt" ) ++endif() ++set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CABLEDYN_ROOT}/CMakeLists.txt") ++add_definitions(-DGIT_VERSION_INFO="${GIT_DESCRIBE}-CableDyn-${_cabledyn_version}") + + add_library(versioninfolib STATIC + src/VersionInfo.f90 diff --git a/release/build_static_windows.ps1 b/release/build_static_windows.ps1 index 8a72f4a6..a9fa02d1 100644 --- a/release/build_static_windows.ps1 +++ b/release/build_static_windows.ps1 @@ -190,6 +190,18 @@ Invoke-StaticToolchain "cmake --build `"$cdBuild`" --target cabledyn_core cabled -OpenFASTRoot $OpenFASTRoot -CableDynRoot $CableDynRoot -CableDynBuildDir $cdBuild ` -LinkLibraries $lapackLibraries +# The identity openfast.exe must report, derived here independently of the integration script: +# the describe of the pinned OpenFAST commit (never '-dirty') and the CableDyn project version. +$ofDescribe = "$(& git -C $OpenFASTRoot describe --tags --abbrev=8)".Trim() +if ($LASTEXITCODE -ne 0 -or $ofDescribe -notmatch '^v\d+\.\d+\.\d+') { + throw "the OpenFAST checkout $OpenFASTRoot is not described by a release tag ('$ofDescribe')" +} +if ((Get-Content -LiteralPath (Join-Path $CableDynRoot 'CMakeLists.txt') -Raw) -notmatch + 'project\(CableDynCore VERSION (\d+\.\d+\.\d+)') { + throw 'CableDyn project version not found in CMakeLists.txt' +} +$expectedOpenFASTVersion = "$ofDescribe-CableDyn-$($Matches[1])" + $devenv = Join-Path $vsRoot 'Common7\IDE\devenv.com' if (-not (Test-Path -LiteralPath $devenv)) { throw "Visual Studio command-line builder not found: $devenv" } $openFastBuild = "`"$devenv`" `"$OpenFASTRoot\vs-build\OpenFAST.sln`" /Build `"Release|x64`" " + @@ -228,6 +240,14 @@ try { if ($versionRun.Text -notmatch 'Build\s+x86-64-v3') { throw "CableDyn_driver.exe is not the x86-64-v3 build with the processor check`n$($versionRun.Text)" } + # Identity gate: openfast.exe names its OpenFAST base and the CableDyn version. + $ofVersionRun = Invoke-NativeCapture $openfast @('-v') + Write-Host $ofVersionRun.Text + if ($ofVersionRun.ExitCode -ne 0 -or $ofVersionRun.Text -match 'dirty' -or + $ofVersionRun.Text -notmatch "(?m)^\s*OpenFAST-$([regex]::Escape($expectedOpenFASTVersion))\s*$") { + throw "openfast.exe -v does not report OpenFAST-$expectedOpenFASTVersion`n$($ofVersionRun.Text)" + } + Write-Host "PASS openfast.exe identity: OpenFAST-$expectedOpenFASTVersion" # On a processor without x86-64-v3 both executables stop at start with the message # (simulated here): exit 3 before any CableDyn or OpenFAST code prints. $env:CABLEDYN_CPU_GUARD_SIMULATE = 'SIMULATED-FEATURE' diff --git a/release/check_release_metadata.py b/release/check_release_metadata.py index 21c3bbbd..e3e44e8d 100644 --- a/release/check_release_metadata.py +++ b/release/check_release_metadata.py @@ -171,6 +171,11 @@ def main() -> int: "OpenFAST example banner": f"Running CableDyn (v{version}," in read( "examples/openfast/README.md" ), + # The name openfast.exe reports (release/build_static_windows.ps1 checks the binary). + "OpenFAST executable identity": all( + re.search(rf"OpenFAST-v\d+\.\d+\.\d+-CableDyn-{re.escape(version)}\b", read(name)) + for name in ("doc/installation.rst", "RELEASE.md", "integration/openfast/README.md") + ), "Python licence metadata": 'license-files = ["LICENSE"]' in read( "python/pyproject.toml" ), diff --git a/tests/test_documentation.py b/tests/test_documentation.py index e87011c2..ca217be3 100644 --- a/tests/test_documentation.py +++ b/tests/test_documentation.py @@ -144,6 +144,20 @@ def test_windows_release_is_publicly_reproducible(self) -> None: build_script.index("integrate_openfast_vs_solution.ps1"), "the host glue patch must be applied before adding the Visual Studio project", ) + # openfast.exe names its OpenFAST base and the CableDyn version, never '-dirty': + # both build routes stamp it, the release build checks it, and the release + # checkout carries the tags `git describe` needs. + integrate_script = ( + ROOT / "integration" / "openfast" / "integrate_openfast_vs_solution.ps1" + ).read_text(encoding="utf-8") + self.assertIn("CreateGitVersion.bat", integrate_script) + self.assertIn("describe --tags --abbrev=8", integrate_script) + version_patch = ( + ROOT / "integration" / "openfast" / "patches" / "0021-version-cmake.patch" + ).read_text(encoding="utf-8") + self.assertIn('-CableDyn-${_cabledyn_version}', version_patch) + self.assertIn("@('-v')", build_script) + self.assertIn("fetch-depth: 0", workflow) self.assertIn("devenv.com", build_script) self.assertIn("Release|x64", build_script) self.assertNotIn('cmake --build `"$ofBuild`"', build_script) From 8faa89a0335fa993dd4046f14989edf87fe1ff14 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 14:08:16 +0900 Subject: [PATCH 15/19] perf(waves): block sine, cosine and exponential in the wave kinematics Under /fp:precise ifx does not use its vector maths library, so every phase cosine, sine and depth exponential of a wave component became one scalar library call per element; the MinGW-w64 library of gfortran is slow there as well. CableDyn_WaveMath evaluates them in blocks of plain IEEE arithmetic that vectorise under any floating-point model: one Cody-Waite reduction per sine-cosine pair (pi/2 in three parts), Taylor polynomials through r^17/r^18 and r^13, and 2^n from its bits; phases beyond 2^20 pi/2 and exponents outside the normal range take the intrinsic. Explicit-shape arguments keep the blocks vectorised when inlined. CD_Component_Wave_Kinematics and CD_Sea_Kinematics call them and keep the sines with the cosines of the elevation pass. test_wave_math checks the kernels against quadruple precision: within 2.3 ulp (sine, cosine) over |theta| <= 4e4 and 1.1 ulp (exponential) over -708..709, quadrant boundaries, signed zero, tiny phases, the subnormal tail and the intrinsic fallback. One thread, best of five, ifx /fp:precise: chain_two_train_sea -33 %, chain_torsethaugen_spread -31 %, als_volturnus_line_break_* -14 %, lazy_wave_vessel_rao and lazy_wave_bend_stiffener -9 %; gfortran: -21 %, -20 %, -9 %, +0.1 and +1.2 %. Decks without waves are unchanged. Example A/B (both compilers): 49 of 53 decks identical; the two lazy-wave vessel decks differ by one unit in the last printed digit (7e-8 of a tension's scale); the VolturnUS line-break decks diverge after t = 860 s to 0.15-0.21 of the anchor-2 tension's scale, the same size as the gfortran-ifx difference of the unchanged code. Signed-off-by: Jae Hoon Seo --- ARCHITECTURE.md | 1 + CHANGELOG.md | 17 +++++ CMakeLists.txt | 10 ++- doc/api_reference.md | 3 + src/CableDyn_Hydro.f90 | 50 +++++++------ src/CableDyn_WaveMath.f90 | 136 +++++++++++++++++++++++++++++++++ src/CableDyn_WaveSpectra.f90 | 30 +++++--- tests/test_wave_math.f90 | 141 +++++++++++++++++++++++++++++++++++ 8 files changed, 355 insertions(+), 33 deletions(-) create mode 100644 src/CableDyn_WaveMath.f90 create mode 100644 tests/test_wave_math.f90 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 4493aa34..032fe55e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -446,6 +446,7 @@ src/ CableDyn_Hydro.f90 Morison loads, Airy and JONSWAP waves, currents CableDyn_WaveSpectra.f90 spectra, spreading, and multi-train seas CableDyn_StreamWave.f90 stream-function regular nonlinear waves + CableDyn_WaveMath.f90 block sine/cosine and exponential of the wave kinematics CableDyn_Vessel.f90 vessel kinematics, 6-DOF motion, displacement RAOs CableDyn_SeabedContact.f90 C1 normal contact and stick-slip friction laws CableDyn_Bathymetry.f90 gridded bathymetry diff --git a/CHANGELOG.md b/CHANGELOG.md index 4502e8ae..010a7de2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -346,6 +346,23 @@ All notable changes to CableDyn are recorded in this file. The format follows 0.1 s drops from 18,000 components to 1,800. On the 300 s lazy-wave case both records then run in 72 s, and every output channel's standard deviation moves by at most 0.002 %. A record with no component at or below the cut-off is refused by name. +- Waves run faster under every compiler: the wave kinematics evaluate their phase sines and + cosines and depth exponentials in blocks of plain arithmetic that vectorise under any + floating-point model (`CableDyn_WaveMath`: one argument reduction for each sine-cosine pair, + polynomials, the power of two from its bits) in place of one library call per component, + which ifx makes under `/fp:precise`. At one thread, best of five, an irregular sea runs 31 to + 33 % faster with ifx (`chain_two_train_sea` 1.83 s to 1.22 s, `chain_torsethaugen_spread` + 1.64 s to 1.13 s) and 20 to 21 % faster with gfortran (4.09 s to 3.22 s, 3.56 s to 2.86 s); + the VolturnUS line-break decks 14 % (ifx, 31.0 s to 26.8 s) and 9 % (gfortran); + `lazy_wave_vessel_rao` and `lazy_wave_bend_stiffener` 9 % with ifx and within 1 % of before + with gfortran; decks without waves run as before. This recovers about two thirds of what + `/fp:precise` cost the Windows release (`chain_two_train_sea` +83 % over `/fp:fast` before, + +24 % now). The sines and cosines are within 2.3 ulp and the exponentials within 1.1 ulp of + quadruple precision, so wave decks change at round-off: 49 of the 53 example decks give + identical files, two lazy-wave decks differ by one unit in the last printed digit (7e-8 of a + tension's scale), and in the two VolturnUS line-break decks the drifting platform amplifies + round-off after t = 860 s to 0.15 to 0.21 of the anchor-2 tension's scale, as much as the + gfortran and ifx builds of the unchanged code differ by. - Coupled OpenFAST runs start from the equilibrium in SeaState's steady current (`CurrMod 1`), as standalone decks start in their `current` option, instead of from the still-water shape. The current is evaluated at SeaState's vertical grid levels for the static solves only; the diff --git a/CMakeLists.txt b/CMakeLists.txt index 08f07e5e..7d98d69c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -445,6 +445,7 @@ add_library(cabledyn_obj OBJECT src/CableDyn_Assemble.f90 src/CableDyn_Loads.f90 src/CableDyn_Bathymetry.f90 + src/CableDyn_WaveMath.f90 src/CableDyn_Hydro.f90 src/CableDyn_WaveSpectra.f90 src/CableDyn_StreamWave.f90 @@ -819,6 +820,12 @@ target_link_libraries(test_hydro PRIVATE cabledyn_core) add_test(NAME hydro COMMAND test_hydro) set_tests_properties(hydro PROPERTIES LABELS "fortran;unit;hydro") +# The block sine, cosine and exponential of the wave kinematics against quadruple precision. +add_executable(test_wave_math tests/test_wave_math.f90) +target_link_libraries(test_wave_math PRIVATE cabledyn_core) +add_test(NAME wave_math COMMAND test_wave_math) +set_tests_properties(wave_math PROPERTIES LABELS "fortran;unit;hydro") + add_executable(test_cable_static tests/test_cable_static.f90) target_link_libraries(test_cable_static PRIVATE cabledyn_core) add_test(NAME cable_static COMMAND test_cable_static) @@ -3041,7 +3048,8 @@ if(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU") test_endconn_spring test_torsion_coupling test_torsion_one_end - test_two_moving_ends) + test_two_moving_ends + test_wave_math) target_compile_options(${_cabledyn_exact_real_test} PRIVATE -Wno-compare-reals) endforeach() target_compile_options(test_openfast_aggregate PRIVATE diff --git a/doc/api_reference.md b/doc/api_reference.md index 29c0e844..1ab5b910 100644 --- a/doc/api_reference.md +++ b/doc/api_reference.md @@ -113,6 +113,9 @@ no deck route runs on it (a finite-EI line with two moving ends runs on the cubi spreading and multi-train seas of the standalone deck * - `CableDyn_StreamWave` - regular nonlinear waves by the stream-function (Fourier) method +* - `CableDyn_WaveMath` + - the phase sines and cosines and depth exponentials of the wave kinematics, in vectorised + blocks * - `CableDyn_Bathymetry` - the seabed elevation field * - `CableDyn_SeabedContact` diff --git a/src/CableDyn_Hydro.f90 b/src/CableDyn_Hydro.f90 index 7cc03891..a8965123 100644 --- a/src/CableDyn_Hydro.f90 +++ b/src/CableDyn_Hydro.f90 @@ -14,6 +14,7 @@ MODULE CableDyn_Hydro !! * Dean & Dalrymple (1991), linear Airy wave theory. !! * Wheeler (1970), vertical stretching through the splash zone. USE CableDyn_Precision, ONLY: wp, CD_ZERO, CD_ONE, CD_All_Finite, CD_Is_Finite + USE CableDyn_WaveMath, ONLY: CD_Wave_SinCos, CD_Wave_Exp USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 IMPLICIT NONE PRIVATE @@ -2257,11 +2258,11 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc !! remains full validation for public/direct calls. `amplitude_scale` multiplies every !! amplitude (a start-up ramp) without the caller forming a scaled copy of the table; the !! result equals passing amplitude_scale*amplitude. - !! Each component's phase cosine and sine and its depth-profile ratios are evaluated in - !! element-wise loops (vectorisable, one trigonometric pair per component) into fixed-size - !! local buffers, and the sums then run in component order. Components beyond the buffer - !! length are evaluated one at a time with the same expressions, so the result does not - !! depend on the buffer. exp_m2kd is the caller's table of EXP(-2 k_comp(i) depth) for this + !! Each component's phase sine and cosine (one argument reduction for both) and its depth + !! exponential come from the block kernels of CableDyn_WaveMath into fixed-size local + !! buffers, and the sums then run in component order. Components beyond the buffer length + !! are evaluated block by block with the same expressions, so the result does not depend on + !! the buffer. exp_m2kd is the caller's table of EXP(-2 k_comp(i) depth) for this !! depth (constant for a fixed table): it replaces the per-call exponential with the same !! value, so the result is bit-identical. !! tail_sums(:, i) holds the sums over components j >= i of a_j omega_j, a_j omega_j^2 and @@ -2285,13 +2286,14 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc REAL(wp), INTENT(IN), OPTIONAL :: exp_m2kd(:), tail_sums(:, :) INTEGER :: i, n, nb, n_small, i0, j, nk REAL(wp) :: amp - REAL(wp) :: cb, sb, x_along, theta, z_eval + REAL(wp) :: cb, sb, x_along, z_eval ! the elevation keeps the cosines of the first NBUF components; the velocity sums run in ! blocks of NBLK (NBUF a multiple of NBLK, so a block lies wholly inside or past the buffer) INTEGER, PARAMETER :: NBUF = 1024, NBLK = 32 REAL(wp), PARAMETER :: HALF_ULP = 0.5_wp*EPSILON(CD_ONE) REAL(wp) :: scl, e_neg, denom - REAL(wp) :: cth(NBUF), bc(NBLK), bs(NBLK), ch(NBLK), sh(NBLK), mag(3), rest(3) + REAL(wp) :: cth(NBUF), sth(NBUF), thb(NBUF), th(NBLK), bc(NBLK), bs(NBLK), ch(NBLK), sh(NBLK) + REAL(wp) :: mag(3), rest(3) LOGICAL :: trust_inputs, at_bed, use_tail, small(NBLK) eta = CD_ZERO @@ -2358,16 +2360,24 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc sb = SIN(direction_deg*DEG2RAD) x_along = x*cb + y*sb nb = MIN(n, NBUF) - ! the elevation sums every component (Wheeler stretching needs the total eta) + ! the elevation sums every component (Wheeler stretching needs the total eta); the phase + ! sines of the first NBUF components are kept for the velocity sums DO i = 1, nb - cth(i) = COS(k_comp(i)*x_along - omega_comp(i)*t + phase(i)) + thb(i) = k_comp(i)*x_along - omega_comp(i)*t + phase(i) END DO + CALL CD_Wave_SinCos(nb, thb, sth, cth) DO i = 1, nb eta = eta + (scl*amplitude(i))*cth(i) END DO - DO i = nb + 1, n - theta = k_comp(i)*x_along - omega_comp(i)*t + phase(i) - eta = eta + (scl*amplitude(i))*COS(theta) + DO i0 = nb + 1, n, NBLK + nk = MIN(n - i0 + 1, NBLK) + DO j = 1, nk + th(j) = k_comp(i0 + j - 1)*x_along - omega_comp(i0 + j - 1)*t + phase(i0 + j - 1) + END DO + CALL CD_Wave_SinCos(nk, th, bs, bc) + DO j = 1, nk + eta = eta + (scl*amplitude(i0 + j - 1))*bc(j) + END DO END DO IF (stretch) THEN @@ -2393,24 +2403,22 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc nk = MIN(n - i0 + 1, NBLK) IF (i0 <= nb) THEN bc(1:nk) = cth(i0:i0 + nk - 1) + bs(1:nk) = sth(i0:i0 + nk - 1) ELSE DO j = 1, nk - bc(j) = COS(k_comp(i0 + j - 1)*x_along - omega_comp(i0 + j - 1)*t + phase(i0 + j - 1)) + th(j) = k_comp(i0 + j - 1)*x_along - omega_comp(i0 + j - 1)*t + phase(i0 + j - 1) END DO + CALL CD_Wave_SinCos(nk, th, bs, bc) END IF - ! the sine in its own loop: a compiler fuses COS and SIN of one argument into a sincos - ! call, which in the MinGW runtime costs several times a cos plus a sin DO j = 1, nk - bs(j) = SIN(k_comp(i0 + j - 1)*x_along - omega_comp(i0 + j - 1)*t + phase(i0 + j - 1)) + th(j) = k_comp(i0 + j - 1)*z_eval END DO + CALL CD_Wave_Exp(nk, th, ch) IF (PRESENT(exp_m2kd)) THEN - DO j = 1, nk - ch(j) = EXP(k_comp(i0 + j - 1)*z_eval) - sh(j) = exp_m2kd(i0 + j - 1) - END DO + sh(1:nk) = exp_m2kd(i0:i0 + nk - 1) ELSE + ! the intrinsic, as the caller's table exp_m2kd is built, so both give the same bits DO j = 1, nk - ch(j) = EXP(k_comp(i0 + j - 1)*z_eval) sh(j) = EXP(-2.0_wp*(k_comp(i0 + j - 1)*depth)) END DO END IF diff --git a/src/CableDyn_WaveMath.f90 b/src/CableDyn_WaveMath.f90 new file mode 100644 index 00000000..9e3a4a68 --- /dev/null +++ b/src/CableDyn_WaveMath.f90 @@ -0,0 +1,136 @@ +! File: src/CableDyn_WaveMath.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +MODULE CableDyn_WaveMath + !! The sines, cosines and exponentials of the wave kinematics, evaluated in blocks. + !! + !! An irregular sea sums, at every point and time, one phase cosine and sine and one depth + !! exponential per component: thousands of transcendental evaluations per node and step. The + !! intrinsic functions become one scalar library call per element where the compiler may not + !! use its vector library (Intel ifx under /fp:precise, as every ifx build compiles), and the + !! MinGW-w64 library of gfortran reduces large arguments in x87 precision (errors of 10^4 to + !! 10^5 ulp at |x| ~ 10^4). Here each block is plain IEEE arithmetic that compilers vectorise + !! under any value-safe floating-point model (a value-unsafe one may fold the rounding to an + !! integer below; the build compiles this file value-safe with every compiler): + !! + !! * sine and cosine together, from ONE argument reduction (they are always needed in pairs): + !! theta = n pi/2 + r with n the integer nearest 2 theta/pi and + !! r = ((theta - n P1) - n P2) - n P3, the Cody-Waite reduction with pi/2 split in three + !! parts whose products with |n| < 2^20 are exact (P1 and P2 carry 33 bits); sin r and cos r + !! by their Taylor series through r^17 and r^18 (|r| <= pi/4, truncation below 2e-19); the + !! quadrant n mod 4 selects and signs them; + !! * exp(x) = 2^n exp(r) with n the integer nearest x/ln 2, r = (x - n L1) - n L2 (ln 2 in two + !! parts, |r| <= ln(2)/2), exp r by its Taylor series through r^13 (truncation below 1e-17) + !! and 2^n from its IEEE bits. + !! + !! Against quadruple precision (test_wave_math) the results are within 2.3 ulp over + !! |theta| <= 4e4 (sine, cosine) and 1.1 ulp over -708 <= x <= 709 (exponential); a phase + !! formed as k x - omega t + phi already carries a rounding error of |theta| ulp(1), far above + !! that. Elements beyond the reduction (|theta| > 2^20 pi/2) or the normal range (x < -708, + !! x > 709) take the intrinsic. The arrays are explicit-shape: inlined into a caller's loops, + !! the blocks then still vectorise. + USE CableDyn_Precision, ONLY: wp + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 + IMPLICIT NONE + PRIVATE + + PUBLIC :: CD_Wave_SinCos, CD_Wave_Exp + + REAL(wp), PARAMETER :: TWO_OVER_PI = 0.63661977236758134308_wp + ! pi/2 = P1 + P2 + P3 (+ 8.5e-32): P1 and P2 carry 33 significant bits (fdlibm's pio2_1, pio2_2) + REAL(wp), PARAMETER :: P1 = 1.57079632673412561417e+00_wp + REAL(wp), PARAMETER :: P2 = 6.07710050630396597660e-11_wp + REAL(wp), PARAMETER :: P3 = 2.02226624871116645580e-21_wp + REAL(wp), PARAMETER :: THETA_MAX = 1.6470993291652855e+06_wp ! 2^20 pi/2 + REAL(wp), PARAMETER :: INV_LN2 = 1.44269504088896338700e+00_wp + ! ln 2 = L1 + L2: L1 carries 32 significant bits (fdlibm's ln2_hi), so n L1 is exact for |n| < 2^21 + REAL(wp), PARAMETER :: L1 = 6.93147180369123816490e-01_wp + REAL(wp), PARAMETER :: L2 = 1.90821492927058770002e-10_wp + REAL(wp), PARAMETER :: X_LOW = -708.0_wp, X_HIGH = 709.0_wp + ! (y + ROUNDER) - ROUNDER is y rounded to the nearest integer for |y| < 2^51, in plain IEEE + ! arithmetic (ANINT can become a library call that blocks the vector loop) + REAL(wp), PARAMETER :: ROUNDER = 6755399441055744.0_wp ! 1.5 * 2^52 + ! Taylor coefficients 1/m! + REAL(wp), PARAMETER :: F2 = 0.5_wp, F3 = 1.0_wp/6.0_wp, F4 = 1.0_wp/24.0_wp, F5 = 1.0_wp/120.0_wp, & + F6 = 1.0_wp/720.0_wp, F7 = 1.0_wp/5040.0_wp, F8 = 1.0_wp/40320.0_wp, & + F9 = 1.0_wp/362880.0_wp, F10 = 1.0_wp/3628800.0_wp, F11 = 1.0_wp/39916800.0_wp, & + F12 = 1.0_wp/479001600.0_wp, F13 = 1.0_wp/6227020800.0_wp, & + F14 = 1.0_wp/87178291200.0_wp, F15 = 1.0_wp/1307674368000.0_wp, & + F16 = 1.0_wp/20922789888000.0_wp, F17 = 1.0_wp/355687428096000.0_wp, & + F18 = 1.0_wp/6402373705728000.0_wp + +CONTAINS + + PURE SUBROUTINE CD_Wave_SinCos(n, theta, s, c) + !! s = sin(theta), c = cos(theta) for the n elements (explicit-shape arrays, so that the + !! loop vectorises wherever the call is inlined). + INTEGER, INTENT(IN) :: n + REAL(wp), INTENT(IN) :: theta(n) + REAL(wp), INTENT(OUT) :: s(n), c(n) + INTEGER :: i, q + REAL(wp) :: th, fn, r, r2, ps, pc, ss, cc + LOGICAL :: far + + DO i = 1, n + th = MAX(-THETA_MAX, MIN(THETA_MAX, theta(i))) + fn = (th*TWO_OVER_PI + ROUNDER) - ROUNDER + r = ((th - fn*P1) - fn*P2) - fn*P3 + r2 = r*r + ! Horner's scheme, its innermost terms first + ps = F13 + r2*(-F15 + r2*F17) + ps = r + (r*r2)*(-F3 + r2*(F5 + r2*(-F7 + r2*(F9 + r2*(-F11 + r2*ps))))) + pc = F12 + r2*(-F14 + r2*(F16 - r2*F18)) + pc = (1.0_wp - F2*r2) + (r2*r2)*(F4 + r2*(-F6 + r2*(F8 + r2*(-F10 + r2*pc)))) + ps = MERGE(ps, r, ABS(r) > 0.0_wp) ! sin(-0) = -0 (ifx's SIGN would drop the sign) + ! quadrant q = n mod 4: (sin, cos) = (ps, pc), (pc, -ps), (-ps, -pc), (-pc, ps) + q = IAND(INT(fn), 3) + ss = MERGE(pc, ps, BTEST(q, 0)) + cc = MERGE(ps, pc, BTEST(q, 0)) + s(i) = MERGE(-ss, ss, BTEST(q, 1)) + c(i) = MERGE(-cc, cc, BTEST(q + 1, 1)) + END DO + far = .FALSE. + DO i = 1, n + far = far .OR. ABS(theta(i)) > THETA_MAX + END DO + IF (.NOT. far) RETURN + DO i = 1, n + IF (ABS(theta(i)) > THETA_MAX) THEN + s(i) = SIN(theta(i)) + c(i) = COS(theta(i)) + END IF + END DO + END SUBROUTINE CD_Wave_SinCos + + PURE SUBROUTINE CD_Wave_Exp(n, x, e) + !! e = exp(x) for the n elements (explicit-shape arrays, as CD_Wave_SinCos). + INTEGER, INTENT(IN) :: n + REAL(wp), INTENT(IN) :: x(n) + REAL(wp), INTENT(OUT) :: e(n) + INTEGER :: i + INTEGER(INT64) :: m + REAL(wp) :: xc, fn, r, p + LOGICAL :: outside + + DO i = 1, n + xc = MAX(X_LOW, MIN(X_HIGH, x(i))) + fn = (xc*INV_LN2 + ROUNDER) - ROUNDER + r = (xc - fn*L1) - fn*L2 + p = F9 + r*(F10 + r*(F11 + r*(F12 + r*F13))) + p = 1.0_wp + r*(1.0_wp + r*(F2 + r*(F3 + r*(F4 + r*(F5 + r*(F6 + r*(F7 + r*(F8 + r*p)))))))) + ! times 2^m from its IEEE bits, m in [-1022, 1023] for the clamped argument (SCALE can + ! become a library call per element) + m = INT(fn, INT64) + 1023_INT64 + e(i) = p*TRANSFER(ISHFT(m, 52), p) + END DO + outside = .FALSE. + DO i = 1, n + outside = outside .OR. (x(i) < X_LOW .OR. x(i) > X_HIGH) + END DO + IF (.NOT. outside) RETURN + DO i = 1, n + IF (x(i) < X_LOW .OR. x(i) > X_HIGH) e(i) = EXP(x(i)) + END DO + END SUBROUTINE CD_Wave_Exp + +END MODULE CableDyn_WaveMath diff --git a/src/CableDyn_WaveSpectra.f90 b/src/CableDyn_WaveSpectra.f90 index 2b617f1e..09487849 100644 --- a/src/CableDyn_WaveSpectra.f90 +++ b/src/CableDyn_WaveSpectra.f90 @@ -30,6 +30,7 @@ MODULE CableDyn_WaveSpectra !! |theta - theta_p| <= pi/2, K(s) = Gamma(s+1)/(sqrt(pi) Gamma(s+1/2)). USE CableDyn_Precision, ONLY: wp, CD_ZERO, CD_ONE, CD_Is_Finite USE CableDyn_Hydro, ONLY: CD_Solve_Dispersion_Wavenumber, CD_HYDRO_OK + USE CableDyn_WaveMath, ONLY: CD_Wave_SinCos, CD_Wave_Exp USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 IMPLICIT NONE PRIVATE @@ -621,6 +622,8 @@ SUBROUTINE CD_Sea_Kinematics(sea, x, y, z, t, depth, scale, eta, velocity, accel !! Linear multi-directional sea kinematics at (x, y, z, t) with Wheeler stretching. !! scale multiplies every amplitude (the start-up ramp). pdyn: the linear dynamic !! pressure per unit density at the stretched depth [m^2/s^2]; zero above the surface. + !! The phase sines and cosines (one argument reduction for both) and the depth exponentials + !! come from the block kernels of CableDyn_WaveMath. TYPE(CD_SeaType), INTENT(IN) :: sea REAL(wp), INTENT(IN) :: x, y, z, t, depth, scale REAL(wp), INTENT(OUT) :: eta, velocity(3), acceleration(3) @@ -628,11 +631,11 @@ SUBROUTINE CD_Sea_Kinematics(sea, x, y, z, t, depth, scale, eta, velocity, accel CHARACTER(*), INTENT(OUT) :: ErrMsg REAL(wp), INTENT(OUT), OPTIONAL :: pdyn INTEGER, PARAMETER :: NB = 256 - ! The phase cosines of the elevation pass, kept for the kinematics pass (whose chunk loop - ! would compute the same values again), for the first NKEEP components; the rest are - ! recomputed there. A multiple of NB, so each chunk is either kept whole or recomputed. + ! The phase cosines and sines of the elevation pass, kept for the kinematics pass (whose + ! chunk loop would compute the same values again), for the first NKEEP components; the rest + ! are recomputed there. A multiple of NB, so each chunk is either kept whole or recomputed. INTEGER, PARAMETER :: NKEEP = 16*NB - REAL(wp) :: cth(NB), sth(NB), ch(NB), sh(NB), ckeep(NKEEP) + REAL(wp) :: th(NB), cth(NB), sth(NB), ch(NB), sh(NB), ckeep(NKEEP), skeep(NKEEP) INTEGER :: i0, i1, i, m, n_small REAL(wp) :: z_eval, a, e1, e2, den, uh @@ -648,13 +651,18 @@ SUBROUTINE CD_Sea_Kinematics(sea, x, y, z, t, depth, scale, eta, velocity, accel END IF DO i0 = 1, sea%n_comp, NB i1 = MIN(sea%n_comp, i0 + NB - 1) + m = i1 - i0 + 1 DO i = i0, i1 - cth(i - i0 + 1) = COS(sea%k(i)*(x*sea%cosb(i) + y*sea%sinb(i)) - sea%omega(i)*t + sea%phase(i)) + th(i - i0 + 1) = sea%k(i)*(x*sea%cosb(i) + y*sea%sinb(i)) - sea%omega(i)*t + sea%phase(i) END DO + CALL CD_Wave_SinCos(m, th, sth, cth) DO i = i0, i1 eta = eta + (scale*sea%amplitude(i))*cth(i - i0 + 1) END DO - IF (i1 <= NKEEP) ckeep(i0:i1) = cth(1:i1 - i0 + 1) + IF (i1 <= NKEEP) THEN + ckeep(i0:i1) = cth(1:m) + skeep(i0:i1) = sth(1:m) + END IF END DO IF (z > eta) RETURN IF (.NOT. (depth + eta > EPSILON(depth)*depth)) THEN @@ -668,21 +676,21 @@ SUBROUTINE CD_Sea_Kinematics(sea, x, y, z, t, depth, scale, eta, velocity, accel m = i1 - i0 + 1 IF (i1 <= NKEEP) THEN cth(1:m) = ckeep(i0:i1) + sth(1:m) = skeep(i0:i1) ELSE DO i = i0, i1 - cth(i - i0 + 1) = COS(sea%k(i)*(x*sea%cosb(i) + y*sea%sinb(i)) - sea%omega(i)*t + sea%phase(i)) + th(i - i0 + 1) = sea%k(i)*(x*sea%cosb(i) + y*sea%sinb(i)) - sea%omega(i)*t + sea%phase(i) END DO + CALL CD_Wave_SinCos(m, th, sth, cth) END IF - DO i = i0, i1 - sth(i - i0 + 1) = SIN(sea%k(i)*(x*sea%cosb(i) + y*sea%sinb(i)) - sea%omega(i)*t + sea%phase(i)) - END DO ! cosh(k(z+h))/sinh(kh) and sinh(k(z+h))/sinh(kh) without overflow, from e1 = EXP(k z) ! and e2 = EXP(-k (z + 2h)) = e2kd/e1 at the synthesis depth: one exponential per ! component. A component whose e1 or e2kd underflows, or a call at another depth than the ! synthesis, takes the second exponential instead. DO i = i0, i1 - ch(i - i0 + 1) = EXP(sea%k(i)*z_eval) + th(i - i0 + 1) = sea%k(i)*z_eval END DO + CALL CD_Wave_Exp(m, th, ch) n_small = 0 IF (ABS(depth - sea%depth) <= CD_ZERO) THEN n_small = COUNT(ch(1:m) <= TINY(CD_ONE) .OR. sea%e2kd(i0:i1) <= TINY(CD_ONE)) diff --git a/tests/test_wave_math.f90 b/tests/test_wave_math.f90 new file mode 100644 index 00000000..5ce4beb4 --- /dev/null +++ b/tests/test_wave_math.f90 @@ -0,0 +1,141 @@ +! File: tests/test_wave_math.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +PROGRAM test_wave_math + !! Gate for the block kernels of CableDyn_WaveMath against an independent oracle, the + !! quadruple-precision intrinsics (a double argument is exact in quadruple precision): + !! 1. sine and cosine of 400,000 phases over |theta| <= 4e4 (the phases of a 3-hour sea) + !! within 3 ulp of the correctly rounded values, and the identities sin^2 + cos^2 = 1 + !! to 4 ulp and sin(-theta) = -sin(theta), cos(-theta) = cos(theta) bit for bit; + !! 2. the quadrant boundaries (theta = n pi/2 rounded, n up to 2^19) and tiny phases + !! (sin theta = theta, cos theta = 1 below 2^-27, signed zero kept); + !! 3. exp over -745 <= x <= 709 within 2 ulp (in the normal range), the subnormal tail and + !! underflow to zero as the intrinsic gives them, exp(0) = 1; + !! 4. phases beyond the reduction's range (|theta| > 2^20 pi/2) take the intrinsic (to 1e-6: + !! a clamped reduction would be off by O(1)). + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 + USE CableDyn_Precision, ONLY: wp + USE CableDyn_WaveMath, ONLY: CD_Wave_SinCos, CD_Wave_Exp + IMPLICIT NONE + INTEGER, PARAMETER :: qp = SELECTED_REAL_KIND(30) + INTEGER, PARAMETER :: N = 400000 + INTEGER :: nfail, i + REAL(wp), ALLOCATABLE :: th(:), s(:), c(:), x(:), e(:), s2(:), c2(:) + REAL(wp) :: ulp_s, ulp_c, ulp_e, ulp_id, pi_wp + REAL(qp) :: pi_q + + nfail = 0 + ALLOCATE (th(N), s(N), c(N), x(N), e(N), s2(N), c2(N)) + ! 1. phases over |theta| <= 4e4, with irrational spacing + DO i = 1, N + th(i) = -4.0e4_wp + 8.0e4_wp*REAL(i, wp)/REAL(N, wp) + 1.0e-7_wp*REAL(i, wp)*SQRT(2.0_wp) + END DO + CALL CD_Wave_SinCos(N, th, s, c) + ulp_s = 0.0_wp + ulp_c = 0.0_wp + ulp_id = 0.0_wp + DO i = 1, N + ulp_s = MAX(ulp_s, ulp_error(s(i), SIN(REAL(th(i), qp)))) + ulp_c = MAX(ulp_c, ulp_error(c(i), COS(REAL(th(i), qp)))) + ulp_id = MAX(ulp_id, REAL(ABS(REAL(s(i), qp)**2 + REAL(c(i), qp)**2 - 1.0_qp), wp)/EPSILON(1.0_wp)) + END DO + WRITE (*, '(A,F6.3,A,F6.3,A,F6.3,A)') ' sin, cos over |theta| <= 4e4: max error ', ulp_s, ' and ', ulp_c, & + ' ulp; sin^2 + cos^2 - 1 within ', ulp_id, ' ulp' + CALL require(ulp_s <= 3.0_wp .AND. ulp_c <= 3.0_wp, 'sine and cosine within 3 ulp') + CALL require(ulp_id <= 4.0_wp, 'sin^2 + cos^2 = 1 within 4 ulp') + CALL CD_Wave_SinCos(N, -th, s2, c2) + CALL require(ALL(s2 == -s) .AND. ALL(c2 == c), 'sine odd and cosine even bit for bit') + + ! 2. quadrant boundaries and tiny phases + pi_wp = 4.0_wp*ATAN(1.0_wp) + pi_q = 4.0_qp*ATAN(1.0_qp) + DO i = 1, 2000 + th(i) = REAL(REAL(MOD(i*262, 524288) - 262144, qp)*pi_q/2.0_qp, wp) + END DO + CALL CD_Wave_SinCos(2000, th, s, c) + ulp_s = 0.0_wp + DO i = 1, 2000 + ulp_s = MAX(ulp_s, abs_error(s(i), SIN(REAL(th(i), qp)), REAL(th(i), qp)), & + abs_error(c(i), COS(REAL(th(i), qp)), REAL(th(i), qp))) + END DO + WRITE (*, '(A,ES9.2)') ' at the quadrant boundaries (|n| <= 2^18): max |error| / ulp(theta) ', ulp_s + CALL require(ulp_s <= 1.0_wp, 'quadrant boundaries: error below ulp(theta)') + th(1:4) = [0.0_wp, -0.0_wp, 1.0e-10_wp, -2.0_wp**(-30)] + CALL CD_Wave_SinCos(4, th, s, c) + ! the sign bits themselves: ifx's SIGN treats -0 as +0 by default (/assume:nominus0) + CALL require(s(1) == 0.0_wp .AND. s(2) == 0.0_wp .AND. .NOT. BTEST(TRANSFER(s(1), 0_INT64), 63) .AND. & + BTEST(TRANSFER(s(2), 0_INT64), 63), 'sin(+-0) = +-0') + CALL require(ALL(c(1:4) == 1.0_wp) .AND. s(3) == th(3) .AND. s(4) == th(4), 'tiny phases: sin = theta, cos = 1') + + ! 3. exponential + DO i = 1, N + x(i) = -745.0_wp + 1454.0_wp*REAL(i, wp)/REAL(N, wp) + 1.0e-9_wp*REAL(i, wp) + END DO + x(N) = 0.0_wp + CALL CD_Wave_Exp(N, x, e) + ulp_e = 0.0_wp + DO i = 1, N + IF (x(i) >= -708.0_wp .AND. x(i) <= 709.0_wp) THEN + ulp_e = MAX(ulp_e, ulp_error(e(i), EXP(REAL(x(i), qp)))) + ELSE + CALL require(e(i) == EXP(x(i)), 'exp outside the normal range is the intrinsic') + END IF + END DO + WRITE (*, '(A,F6.3,A)') ' exp over -708 <= x <= 709: max error ', ulp_e, ' ulp' + CALL require(ulp_e <= 2.0_wp, 'exp within 2 ulp') + CALL require(e(N) == 1.0_wp, 'exp(0) = 1') + x(1:3) = [-745.2_wp, -800.0_wp, -720.0_wp] + CALL CD_Wave_Exp(3, x, e) + CALL require(e(1) == EXP(x(1)) .AND. e(2) == 0.0_wp .AND. e(3) == EXP(x(3)) .AND. e(3) > 0.0_wp, & + 'subnormal tail and underflow as the intrinsic') + + ! 4. beyond the reduction's range + th(1:3) = [2.0e6_wp, -3.5e7_wp, 1.0e9_wp] + CALL CD_Wave_SinCos(3, th, s, c) + ulp_s = 0.0_wp + DO i = 1, 3 + ulp_s = MAX(ulp_s, REAL(ABS(REAL(s(i), qp) - SIN(REAL(th(i), qp))), wp), & + REAL(ABS(REAL(c(i), qp) - COS(REAL(th(i), qp))), wp)) + END DO + WRITE (*, '(A,ES9.2)') ' beyond 2^20 pi/2 (the intrinsic): max |error| ', ulp_s + CALL require(ulp_s <= 1.0e-6_wp, 'phases beyond 2^20 pi/2 are not reduced as near ones') + + IF (nfail > 0) THEN + WRITE (*, '(A,I0,A)') 'test_wave_math: ', nfail, ' check(s) FAILED' + ERROR STOP 1 + END IF + WRITE (*, '(A)') 'test_wave_math: all checks passed' + +CONTAINS + + REAL(wp) FUNCTION ulp_error(value, exact) RESULT(ulps) + !! |value - exact| in units of the last place of the correctly rounded exact value. + REAL(wp), INTENT(IN) :: value + REAL(qp), INTENT(IN) :: exact + REAL(wp) :: rounded + rounded = REAL(exact, wp) + IF (rounded == 0.0_wp) THEN + ulps = REAL(ABS(REAL(value, qp) - exact), wp)/TINY(1.0_wp) + ELSE + ulps = REAL(ABS(REAL(value, qp) - exact)/REAL(SPACING(rounded), qp), wp) + END IF + END FUNCTION ulp_error + + REAL(wp) FUNCTION abs_error(value, exact, arg) RESULT(rel) + !! |value - exact| over ulp(arg): near a zero of sine or cosine the phase's own rounding + !! (half an ulp of theta) bounds what any evaluation can resolve. + REAL(wp), INTENT(IN) :: value + REAL(qp), INTENT(IN) :: exact, arg + rel = REAL(ABS(REAL(value, qp) - exact)/REAL(SPACING(MAX(1.0_wp, REAL(ABS(arg), wp))), qp), wp) + END FUNCTION abs_error + + SUBROUTINE require(cond, label) + LOGICAL, INTENT(IN) :: cond + CHARACTER(*), INTENT(IN) :: label + IF (.NOT. cond) THEN + nfail = nfail + 1 + WRITE (*, '(A)') 'FAIL: '//label + END IF + END SUBROUTINE require + +END PROGRAM test_wave_math From 0e2002b083fcc28ec1b247d9bdc329f1fddac460 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 16:49:47 +0900 Subject: [PATCH 16/19] fix(waves): NaN through the block sine, cosine and exponential CD_Wave_SinCos and CD_Wave_Exp clamp each argument to the range of their reduction before evaluating it, and the elements outside that range were picked for the intrinsic by |theta| > 2^20 pi/2 and x < -708 .OR. x > 709. A NaN fails both comparisons, and the clamp itself may turn it into a finite bound (Fortran leaves MIN and MAX of a NaN unspecified; gfortran returns the other argument), so under gfortran sin(NaN) and cos(NaN) came back as 6.4e-11 and 1.0 and exp(NaN) as exp(-708) = 3.3e-308. The intrinsics they replace gave NaN, and CD_Sea_Kinematics does not check its point and time, so a NaN position turned into a finite elevation and velocity. The fallback now takes every element that is not inside the range (.NOT. (ABS(theta) <= THETA_MAX), .NOT. (x >= X_LOW .AND. x <= X_HIGH)), so a NaN takes the intrinsic and comes back NaN. Finite arguments take the same path as before: the results are bit-identical. test_wave_math gate 5: NaN and -Inf phases inside a block of finite ones, and a NaN exponent, give NaN, the finite elements of the block unchanged; on the previous kernels it fails (6.42e-11, 1.0, 3.31e-308). Signed-off-by: Jae Hoon Seo --- src/CableDyn_WaveMath.f90 | 16 ++++++++++------ tests/test_wave_math.f90 | 19 ++++++++++++++++++- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/CableDyn_WaveMath.f90 b/src/CableDyn_WaveMath.f90 index 9e3a4a68..8c8c9a8b 100644 --- a/src/CableDyn_WaveMath.f90 +++ b/src/CableDyn_WaveMath.f90 @@ -27,8 +27,10 @@ MODULE CableDyn_WaveMath !! |theta| <= 4e4 (sine, cosine) and 1.1 ulp over -708 <= x <= 709 (exponential); a phase !! formed as k x - omega t + phi already carries a rounding error of |theta| ulp(1), far above !! that. Elements beyond the reduction (|theta| > 2^20 pi/2) or the normal range (x < -708, - !! x > 709) take the intrinsic. The arrays are explicit-shape: inlined into a caller's loops, - !! the blocks then still vectorise. + !! x > 709), and NaN, take the intrinsic, so a NaN argument gives NaN as the intrinsic does (the + !! clamp to the range may turn it into a finite bound: Fortran leaves MIN and MAX of a NaN + !! unspecified, and gfortran returns the other argument). The arrays are explicit-shape: + !! inlined into a caller's loops, the blocks then still vectorise. USE CableDyn_Precision, ONLY: wp USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 IMPLICIT NONE @@ -89,13 +91,14 @@ PURE SUBROUTINE CD_Wave_SinCos(n, theta, s, c) s(i) = MERGE(-ss, ss, BTEST(q, 1)) c(i) = MERGE(-cc, cc, BTEST(q + 1, 1)) END DO + ! beyond the reduction, or NaN (every comparison with a NaN is false) far = .FALSE. DO i = 1, n - far = far .OR. ABS(theta(i)) > THETA_MAX + far = far .OR. .NOT. (ABS(theta(i)) <= THETA_MAX) END DO IF (.NOT. far) RETURN DO i = 1, n - IF (ABS(theta(i)) > THETA_MAX) THEN + IF (.NOT. (ABS(theta(i)) <= THETA_MAX)) THEN s(i) = SIN(theta(i)) c(i) = COS(theta(i)) END IF @@ -123,13 +126,14 @@ PURE SUBROUTINE CD_Wave_Exp(n, x, e) m = INT(fn, INT64) + 1023_INT64 e(i) = p*TRANSFER(ISHFT(m, 52), p) END DO + ! outside the normal range, or NaN outside = .FALSE. DO i = 1, n - outside = outside .OR. (x(i) < X_LOW .OR. x(i) > X_HIGH) + outside = outside .OR. .NOT. (x(i) >= X_LOW .AND. x(i) <= X_HIGH) END DO IF (.NOT. outside) RETURN DO i = 1, n - IF (x(i) < X_LOW .OR. x(i) > X_HIGH) e(i) = EXP(x(i)) + IF (.NOT. (x(i) >= X_LOW .AND. x(i) <= X_HIGH)) e(i) = EXP(x(i)) END DO END SUBROUTINE CD_Wave_Exp diff --git a/tests/test_wave_math.f90 b/tests/test_wave_math.f90 index 5ce4beb4..22eb8060 100644 --- a/tests/test_wave_math.f90 +++ b/tests/test_wave_math.f90 @@ -12,8 +12,12 @@ PROGRAM test_wave_math !! 3. exp over -745 <= x <= 709 within 2 ulp (in the normal range), the subnormal tail and !! underflow to zero as the intrinsic gives them, exp(0) = 1; !! 4. phases beyond the reduction's range (|theta| > 2^20 pi/2) take the intrinsic (to 1e-6: - !! a clamped reduction would be off by O(1)). + !! a clamped reduction would be off by O(1)); + !! 5. a NaN argument gives NaN (sine, cosine and exponential) and an infinite phase NaN, as + !! the intrinsics: the clamp to the reduction's range must not turn a NaN into a finite + !! value (gfortran's MIN and MAX return the non-NaN argument). USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 + USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_VALUE, IEEE_QUIET_NAN, IEEE_POSITIVE_INF, IEEE_IS_NAN USE CableDyn_Precision, ONLY: wp USE CableDyn_WaveMath, ONLY: CD_Wave_SinCos, CD_Wave_Exp IMPLICIT NONE @@ -100,6 +104,19 @@ PROGRAM test_wave_math WRITE (*, '(A,ES9.2)') ' beyond 2^20 pi/2 (the intrinsic): max |error| ', ulp_s CALL require(ulp_s <= 1.0e-6_wp, 'phases beyond 2^20 pi/2 are not reduced as near ones') + ! 5. NaN and infinite arguments, alone and within a block of finite ones + th(1:5) = [0.5_wp, IEEE_VALUE(1.0_wp, IEEE_QUIET_NAN), 1.0e3_wp, -IEEE_VALUE(1.0_wp, IEEE_POSITIVE_INF), 2.0_wp] + CALL CD_Wave_SinCos(5, th, s, c) + WRITE (*, '(A,4ES11.3)') ' sin, cos of NaN and of -Inf: ', s(2), c(2), s(4), c(4) + CALL require(IEEE_IS_NAN(s(2)) .AND. IEEE_IS_NAN(c(2)) .AND. IEEE_IS_NAN(s(4)) .AND. IEEE_IS_NAN(c(4)), & + 'sine and cosine of NaN and of an infinite phase are NaN') + CALL require(ABS(REAL(s(3), qp) - SIN(REAL(th(3), qp))) <= REAL(4.0_wp*SPACING(1.0_wp), qp), & + 'finite phases of the same block unaffected') + x(1:3) = [-1.0_wp, IEEE_VALUE(1.0_wp, IEEE_QUIET_NAN), 2.0_wp] + CALL CD_Wave_Exp(3, x, e) + WRITE (*, '(A,ES11.3)') ' exp of NaN: ', e(2) + CALL require(IEEE_IS_NAN(e(2)) .AND. .NOT. IEEE_IS_NAN(e(1)) .AND. .NOT. IEEE_IS_NAN(e(3)), 'exp of NaN is NaN') + IF (nfail > 0) THEN WRITE (*, '(A,I0,A)') 'test_wave_math: ', nfail, ' check(s) FAILED' ERROR STOP 1 From 1fc5af93388fa87f8aec7d40b1c0a9e2a1ae208c Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 16:53:17 +0900 Subject: [PATCH 17/19] build(waves): IEEE semantics for the block kernels under GNU fast-math CD_Wave_SinCos and CD_Wave_Exp round to an integer as (y + 1.5*2^52) - 1.5*2^52 and reduce the phase by pi/2 in exact parts. A value-unsafe floating-point model folds the rounding to y, and the kernels then return garbage: under the IFX default /fp:fast (a non-static IFX CMake build, /O2 /Qauto -Qiopenmp, before every IFX build took /fp:precise) test_wave_math failed its first check, the error overflowing the printed field; a sweep of 10^6 phases per decade gave sine and cosine errors of O(1) (4.5e15 ulp of 1) and exp wrong by O(1) as well (exp(709) = 4.49e307 for 8.22e307). gfortran -Ofast does the same. Every IFX build now compiles with /fp:precise (-fp-model precise), so only a GNU build given -ffast-math or -Ofast in its flags is left: src/CableDyn_WaveMath.f90 takes -fno-fast-math under gfortran, after the build's own flags. The GNU objects are byte-identical to those before (-O2 and -O3). Signed-off-by: Jae Hoon Seo --- CMakeLists.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d98d69c..de683382 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -477,6 +477,15 @@ set_target_properties(cabledyn_obj PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(cabledyn_obj PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED ON C_EXTENSIONS OFF) target_include_directories(cabledyn_obj PUBLIC "${CMAKE_Fortran_MODULE_DIRECTORY}") target_link_libraries(cabledyn_obj PUBLIC ${CABLEDYN_LAPACK}) +# The block sine, cosine and exponential of the wave kinematics (src/CableDyn_WaveMath.f90) +# round to an integer as (y + 1.5*2^52) - 1.5*2^52 and reduce the phase by pi/2 in exact parts. +# A value-unsafe floating-point model may reassociate both and fold the rounding to y, so that +# every sine, cosine and exponential is wrong by O(1). Every IFX build compiles with +# /fp:precise (-fp-model precise) already (above); a GNU build given -ffast-math (or -Ofast) +# in its flags still compiles this file with IEEE semantics. +if(CMAKE_Fortran_COMPILER_ID STREQUAL "GNU") + set_source_files_properties(src/CableDyn_WaveMath.f90 PROPERTIES COMPILE_OPTIONS "-fno-fast-math") +endif() if(CABLEDYN_HAVE_OPENBLAS_SET_NUM_THREADS) target_compile_definitions(cabledyn_obj PRIVATE CABLEDYN_HAVE_OPENBLAS_SET_NUM_THREADS=1) endif() From e1271e87f391b13ce3352f32f177a1dac0f4062b Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 31 Oct 2026 17:07:25 +0900 Subject: [PATCH 18/19] test(waves): the block kernels over their whole range and at their zeros test_wave_math sampled the sine and cosine only over |theta| <= 4e4 and the quadrant boundaries only against ulp(theta), so a reduction that failed above 4e4 passed: with its range cut to 1e5 (the intrinsic taking over, 5.7e6 ulp under MinGW) every check still held. Its ulp of the exponential came from SPACING, which returns TINY wherever the spacing is subnormal, so below exp(-672) the errors were divided by up to 2^52 too much. A 3 MB array temporary for -theta overflowed the 1 MB stack of a build without heap arrays. - 400,000 phases over 4e4 < |theta| < 2^20 pi/2: within 3 ulp (measured 2.16 and 2.20); - the double nearest n pi/2 for every 1 <= n < 2^20, where sine or cosine falls to 6.2e-19: the error within 3 ulp of the value plus |n| 8.5e-32, the part of pi/2 below P1 + P2 + P3 (measured 0.997 of that bound; the relative error reaches 2.8e6 ulp of those tiny values, an absolute 9e-26 at most); - the ulp from the exponent of the correctly rounded value, 2^(e-53), down to 2^-1074; - -theta in an allocated array. With the range cut to 1e5 the new checks fail (beyond 1e6 ulp, the bound exceeded); the previous test passed it. The module header and the CHANGELOG entry stated 2.3 ulp over |theta| <= 4e4; sweeps of 10^6 phases per decade give up to 2.36 ulp (at theta = -1.108e4), and next to the zeros the bound above. They now state 2.4 ulp over |theta| <= 2^20 pi/2 and 9e-26 next to a zero. The kernels are unchanged. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 32 +++++++++---------- src/CableDyn_WaveMath.f90 | 12 ++++--- tests/test_wave_math.f90 | 67 +++++++++++++++++++++++++++++++++------ 3 files changed, 82 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 010a7de2..b74d797a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -346,23 +346,23 @@ All notable changes to CableDyn are recorded in this file. The format follows 0.1 s drops from 18,000 components to 1,800. On the 300 s lazy-wave case both records then run in 72 s, and every output channel's standard deviation moves by at most 0.002 %. A record with no component at or below the cut-off is refused by name. -- Waves run faster under every compiler: the wave kinematics evaluate their phase sines and - cosines and depth exponentials in blocks of plain arithmetic that vectorise under any +- Waves run faster under every compiler: the wave kinematics evaluate their phase sines and cosines + and depth exponentials in blocks of plain arithmetic that vectorise under any value-safe floating-point model (`CableDyn_WaveMath`: one argument reduction for each sine-cosine pair, - polynomials, the power of two from its bits) in place of one library call per component, - which ifx makes under `/fp:precise`. At one thread, best of five, an irregular sea runs 31 to - 33 % faster with ifx (`chain_two_train_sea` 1.83 s to 1.22 s, `chain_torsethaugen_spread` - 1.64 s to 1.13 s) and 20 to 21 % faster with gfortran (4.09 s to 3.22 s, 3.56 s to 2.86 s); - the VolturnUS line-break decks 14 % (ifx, 31.0 s to 26.8 s) and 9 % (gfortran); - `lazy_wave_vessel_rao` and `lazy_wave_bend_stiffener` 9 % with ifx and within 1 % of before - with gfortran; decks without waves run as before. This recovers about two thirds of what - `/fp:precise` cost the Windows release (`chain_two_train_sea` +83 % over `/fp:fast` before, - +24 % now). The sines and cosines are within 2.3 ulp and the exponentials within 1.1 ulp of - quadruple precision, so wave decks change at round-off: 49 of the 53 example decks give - identical files, two lazy-wave decks differ by one unit in the last printed digit (7e-8 of a - tension's scale), and in the two VolturnUS line-break decks the drifting platform amplifies - round-off after t = 860 s to 0.15 to 0.21 of the anchor-2 tension's scale, as much as the - gfortran and ifx builds of the unchanged code differ by. + polynomials, the power of two from its bits) in place of one library call per component, which ifx + makes under `/fp:precise`. At one thread, best of five, an irregular sea runs 31 to 33 % faster + with ifx (`chain_two_train_sea` 1.83 s to 1.22 s, `chain_torsethaugen_spread` 1.64 s to 1.13 s) + and 20 to 21 % faster with gfortran (4.09 s to 3.22 s, 3.56 s to 2.86 s); the VolturnUS line-break + decks 14 % (ifx, 31.0 s to 26.8 s) and 9 % (gfortran); `lazy_wave_vessel_rao` and + `lazy_wave_bend_stiffener` 9 % with ifx and within 1 % of before with gfortran; decks without + waves run as before. This recovers about two thirds of what `/fp:precise` cost the Windows release + (`chain_two_train_sea` +83 % over `/fp:fast` before, +24 % now). The sines and cosines are within + 2.4 ulp (within 9e-26 next to their zeros) and the exponentials within 1.1 ulp of quadruple + precision, so wave decks change at round-off: 49 of the 53 example decks give identical files, two + lazy-wave decks differ by one unit in the last printed digit (7e-8 of a tension's scale), and in + the two VolturnUS line-break decks the drifting platform amplifies round-off after t = 860 s to + 0.15 to 0.21 of the anchor-2 tension's scale, as much as the gfortran and ifx builds of the + unchanged code differ by. - Coupled OpenFAST runs start from the equilibrium in SeaState's steady current (`CurrMod 1`), as standalone decks start in their `current` option, instead of from the still-water shape. The current is evaluated at SeaState's vertical grid levels for the static solves only; the diff --git a/src/CableDyn_WaveMath.f90 b/src/CableDyn_WaveMath.f90 index 8c8c9a8b..c77b7df1 100644 --- a/src/CableDyn_WaveMath.f90 +++ b/src/CableDyn_WaveMath.f90 @@ -23,10 +23,14 @@ MODULE CableDyn_WaveMath !! parts, |r| <= ln(2)/2), exp r by its Taylor series through r^13 (truncation below 1e-17) !! and 2^n from its IEEE bits. !! - !! Against quadruple precision (test_wave_math) the results are within 2.3 ulp over - !! |theta| <= 4e4 (sine, cosine) and 1.1 ulp over -708 <= x <= 709 (exponential); a phase - !! formed as k x - omega t + phi already carries a rounding error of |theta| ulp(1), far above - !! that. Elements beyond the reduction (|theta| > 2^20 pi/2) or the normal range (x < -708, + !! Against quadruple precision (test_wave_math, and sweeps of 10^6 phases per decade) the + !! results are within 2.4 ulp over |theta| <= 2^20 pi/2 (sine, cosine) and 1.1 ulp over + !! -708 <= x <= 709 (exponential). Next to a zero of the sine or cosine, the double nearest + !! n pi/2, the value is as small as theta's distance from the multiple (down to 6.2e-19) and the + !! part of pi/2 below P1 + P2 + P3, 8.5e-32, adds |n| 8.5e-32 (at most 9e-26) to the error: + !! up to 2.8e6 ulp of that tiny value, 4e-10 ulp of 1. A phase formed as k x - omega t + phi + !! already carries a rounding error of |theta| ulp(1), far above both. + !! Elements beyond the reduction (|theta| > 2^20 pi/2) or the normal range (x < -708, !! x > 709), and NaN, take the intrinsic, so a NaN argument gives NaN as the intrinsic does (the !! clamp to the range may turn it into a finite bound: Fortran leaves MIN and MAX of a NaN !! unspecified, and gfortran returns the other argument). The arrays are explicit-shape: diff --git a/tests/test_wave_math.f90 b/tests/test_wave_math.f90 index 22eb8060..0e27307d 100644 --- a/tests/test_wave_math.f90 +++ b/tests/test_wave_math.f90 @@ -5,12 +5,18 @@ PROGRAM test_wave_math !! Gate for the block kernels of CableDyn_WaveMath against an independent oracle, the !! quadruple-precision intrinsics (a double argument is exact in quadruple precision): !! 1. sine and cosine of 400,000 phases over |theta| <= 4e4 (the phases of a 3-hour sea) - !! within 3 ulp of the correctly rounded values, and the identities sin^2 + cos^2 = 1 - !! to 4 ulp and sin(-theta) = -sin(theta), cos(-theta) = cos(theta) bit for bit; + !! and of 400,000 over 4e4 < |theta| < 2^20 pi/2 (long records, short waves) within 3 ulp + !! of the correctly rounded values, and the identities sin^2 + cos^2 = 1 to 4 ulp and + !! sin(-theta) = -sin(theta), cos(-theta) = cos(theta) bit for bit; !! 2. the quadrant boundaries (theta = n pi/2 rounded, n up to 2^19) and tiny phases - !! (sin theta = theta, cos theta = 1 below 2^-27, signed zero kept); - !! 3. exp over -745 <= x <= 709 within 2 ulp (in the normal range), the subnormal tail and - !! underflow to zero as the intrinsic gives them, exp(0) = 1; + !! (sin theta = theta, cos theta = 1 below 2^-27, signed zero kept); at the double + !! nearest n pi/2 for every 1 <= n < 2^20, where sine or cosine falls to the distance from + !! the multiple (down to 6.2e-19), the error within the reduction's bound: 3 ulp of the + !! value plus |n| 8.5e-32, the part of pi/2 below P1 + P2 + P3 (with P3 dropped the + !! error would be |n| 2e-21, with P3 rounded to 53 bits n P3 inexact); + !! 3. exp over -745 <= x <= 709 within 2 ulp (in the normal range; the ulp from the + !! exponent, since SPACING returns TINY below 2^-969), the subnormal tail and underflow + !! to zero as the intrinsic gives them, exp(0) = 1; !! 4. phases beyond the reduction's range (|theta| > 2^20 pi/2) take the intrinsic (to 1e-6: !! a clamped reduction would be off by O(1)); !! 5. a NaN argument gives NaN (sine, cosine and exponential) and an infinite phase NaN, as @@ -24,9 +30,10 @@ PROGRAM test_wave_math INTEGER, PARAMETER :: qp = SELECTED_REAL_KIND(30) INTEGER, PARAMETER :: N = 400000 INTEGER :: nfail, i - REAL(wp), ALLOCATABLE :: th(:), s(:), c(:), x(:), e(:), s2(:), c2(:) + REAL(wp), ALLOCATABLE :: th(:), s(:), c(:), x(:), e(:), s2(:), c2(:), tb(:), sb(:), cb(:) REAL(wp) :: ulp_s, ulp_c, ulp_e, ulp_id, pi_wp - REAL(qp) :: pi_q + REAL(qp) :: pi_q, sq, cq + REAL(wp), PARAMETER :: THETA_MAX = 1.6470993291652855e6_wp ! 2^20 pi/2 nfail = 0 ALLOCATE (th(N), s(N), c(N), x(N), e(N), s2(N), c2(N)) @@ -47,8 +54,24 @@ PROGRAM test_wave_math ' ulp; sin^2 + cos^2 - 1 within ', ulp_id, ' ulp' CALL require(ulp_s <= 3.0_wp .AND. ulp_c <= 3.0_wp, 'sine and cosine within 3 ulp') CALL require(ulp_id <= 4.0_wp, 'sin^2 + cos^2 = 1 within 4 ulp') - CALL CD_Wave_SinCos(N, -th, s2, c2) + x = -th ! (not -th as the actual argument: a 3 MB temporary on the stack) + CALL CD_Wave_SinCos(N, x, s2, c2) CALL require(ALL(s2 == -s) .AND. ALL(c2 == c), 'sine odd and cosine even bit for bit') + ! 1b. 4e4 < |theta| < 2^20 pi/2, geometric spacing, alternating sign + DO i = 1, N + th(i) = 4.0e4_wp*(0.99999_wp*THETA_MAX/4.0e4_wp)**(REAL(i, wp)/REAL(N, wp)) + IF (MOD(i, 2) == 0) th(i) = -th(i) + END DO + CALL CD_Wave_SinCos(N, th, s, c) + ulp_s = 0.0_wp + ulp_c = 0.0_wp + DO i = 1, N + ulp_s = MAX(ulp_s, ulp_error(s(i), SIN(REAL(th(i), qp)))) + ulp_c = MAX(ulp_c, ulp_error(c(i), COS(REAL(th(i), qp)))) + END DO + WRITE (*, '(A,F6.3,A,F6.3,A)') ' sin, cos over 4e4 < |theta| < 2^20 pi/2: max error ', ulp_s, ' and ', ulp_c, & + ' ulp' + CALL require(ulp_s <= 3.0_wp .AND. ulp_c <= 3.0_wp, 'sine and cosine within 3 ulp up to 2^20 pi/2') ! 2. quadrant boundaries and tiny phases pi_wp = 4.0_wp*ATAN(1.0_wp) @@ -64,6 +87,25 @@ PROGRAM test_wave_math END DO WRITE (*, '(A,ES9.2)') ' at the quadrant boundaries (|n| <= 2^18): max |error| / ulp(theta) ', ulp_s CALL require(ulp_s <= 1.0_wp, 'quadrant boundaries: error below ulp(theta)') + ! the double nearest n pi/2: the smallest sines and cosines the reduction meets + ALLOCATE (tb(2**20 - 1), sb(2**20 - 1), cb(2**20 - 1)) + DO i = 1, 2**20 - 1 + tb(i) = REAL(REAL(i, qp)*pi_q/2.0_qp, wp) + END DO + CALL CD_Wave_SinCos(2**20 - 1, tb, sb, cb) + ulp_s = 0.0_wp + ulp_c = 0.0_wp + DO i = 1, 2**20 - 1 + sq = SIN(REAL(tb(i), qp)) + cq = COS(REAL(tb(i), qp)) + ulp_s = MAX(ulp_s, ulp_error(sb(i), sq), ulp_error(cb(i), cq)) + ulp_c = MAX(ulp_c, REAL(ABS(REAL(sb(i), qp) - sq)/(3.0_qp*ulp_q(REAL(sq, wp)) + REAL(i, qp)*8.5e-32_qp), wp), & + REAL(ABS(REAL(cb(i), qp) - cq)/(3.0_qp*ulp_q(REAL(cq, wp)) + REAL(i, qp)*8.5e-32_qp), wp)) + END DO + WRITE (*, '(A,ES9.2,A,F6.3,A,ES9.2,A)') ' at the doubles nearest n pi/2 (1 <= n < 2^20): max error ', ulp_s, & + ' ulp, ', ulp_c, ' of 3 ulp + |n| 8.5e-32 (|sin| or |cos| down to ', MINVAL(MIN(ABS(sb), ABS(cb))), ')' + CALL require(ulp_c <= 1.0_wp, 'nearest n pi/2: within 3 ulp + |n| 8.5e-32') + DEALLOCATE (tb, sb, cb) th(1:4) = [0.0_wp, -0.0_wp, 1.0e-10_wp, -2.0_wp**(-30)] CALL CD_Wave_SinCos(4, th, s, c) ! the sign bits themselves: ifx's SIGN treats -0 as +0 by default (/assume:nominus0) @@ -134,10 +176,17 @@ REAL(wp) FUNCTION ulp_error(value, exact) RESULT(ulps) IF (rounded == 0.0_wp) THEN ulps = REAL(ABS(REAL(value, qp) - exact), wp)/TINY(1.0_wp) ELSE - ulps = REAL(ABS(REAL(value, qp) - exact)/REAL(SPACING(rounded), qp), wp) + ulps = REAL(ABS(REAL(value, qp) - exact)/ulp_q(rounded), wp) END IF END FUNCTION ulp_error + REAL(qp) FUNCTION ulp_q(r) RESULT(u) + !! The spacing of the doubles at r, 2^(e - 53), down to the subnormal spacing 2^-1074 (SPACING + !! returns TINY wherever that spacing is subnormal, below 2^-969). + REAL(wp), INTENT(IN) :: r + u = SCALE(1.0_qp, MAX(EXPONENT(r), MINEXPONENT(r)) - DIGITS(r)) + END FUNCTION ulp_q + REAL(wp) FUNCTION abs_error(value, exact, arg) RESULT(rel) !! |value - exact| over ulp(arg): near a zero of sine or cosine the phase's own rounding !! (half an ulp of theta) bounds what any evaluation can resolve. From bc20c718201bc4e817a12345b04099a1fd8987d7 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Tue, 3 Nov 2026 06:57:34 +0900 Subject: [PATCH 19/19] fix(capi): pause the OpenMP pool on Close only under GNU OpenMP CableDyn_Close called omp_pause_resource_all(omp_pause_soft) on every close (since 0.1.0) to join the calling thread's OpenMP pool, so that a MinGW-w64 libgomp process does not hang at exit on pool threads still ending. The Intel and LLVM runtimes (libiomp5, libomp) pause the runtime of the whole process instead: closing one handle paused the OpenMP of every other handle and of the host, and the first parallel region of another thread then deadlocked resuming it, spinning on a lock no live thread held. Found as eight test_c_api_threads processes of a non-static ifx build with OpenMP that had spun for two days, then reproduced: the threading gate hung in its concurrent-Step phase every time (also with a single stepping thread, without the earlier phases, with Intel's own runtime swapped in, with affinity and topology detection off); the stepping thread waited inside CD_Step_System's parallel-region entry after the main thread had closed its reference handle. The pause is now taken only when this unit was built by GCC (COMPILER_VERSION). The non-static ifx OpenMP build passes the gate 20 of 20 with OMP_NUM_THREADS 1 and 4 (it hung 20 of 20); gfortran passes c_api_threads, _omp32, _stress, _mixed, _exit (the exit-hang gate the pause exists for), thread_safe_sources and python_package. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 8 ++++++++ src/CableDyn_CAPI.f90 | 24 +++++++++++++++--------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b74d797a..a102a6f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -418,6 +418,14 @@ All notable changes to CableDyn are recorded in this file. The format follows is now laid from End A, the line seen from its other end, and its nodes put back in order. The deck starts at the same equilibrium as before on Windows (1e-7 m, 6e-4 N), and moving the fixed rod by 1 ulp either way or 1e-12 m up leaves the rod's start unchanged (0 m). +- `CableDyn_Close` no longer pauses the OpenMP runtime of the whole process under the Intel and + LLVM OpenMP runtimes (ifx and other non-GNU builds with OpenMP). Every close called + `omp_pause_resource_all` (since 0.1.0) to join the calling thread's pool, a fix for GNU + OpenMP's process exit on MinGW-w64; libiomp5 and libomp pause the runtime of every thread + instead, so closing one handle paused the OpenMP of every other handle and of the host, and the + next parallel region on another thread deadlocked resuming it. An ifx build with OpenMP that + stepped a handle on a second thread after a close hung every time (the threading gate, 20 of + 20 runs); it now passes 20 of 20 with 1 and with 4 OpenMP threads. GNU builds keep the pool join. - A non-static ifx build (a plain CMake build with ifx, or the core of the OpenFAST CMake route) kept run-time-sized arrays and array temporaries on the stack, as only the static Windows release compiled with `/heap-arrays`: the 2835-node mixed IEA-15 MW deck and a fine-mesh deck of diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 13e7451b..87e46e43 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -11,7 +11,7 @@ MODULE CableDyn_CAPI !! the point-system object graph used by OpenFAST-facing integrations. USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_BOOL, C_CHAR, C_DOUBLE, C_INT, C_NULL_CHAR, C_NULL_PTR, C_PTR, & C_ASSOCIATED, C_LOC, C_F_POINTER - USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64, COMPILER_VERSION USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_IS_FINITE USE CableDyn_DeckDriver, ONLY: CD_Init_Deck_System, CD_DECKDRV_OK, CD_DECKDRV_BADINPUT, CD_DECKDRV_SOLVEFAIL, & CD_Deck_Query_dtM, CD_DECK_NAMELEN, CD_Eval_Aggregate_Channel, & @@ -1366,13 +1366,17 @@ SUBROUTINE CableDyn_Close(handle, err_stat) BIND(C, NAME='CableDyn_Close') !! it is never dereferenced or deallocated. Only a validated live handle is !! de-registered, finalized, deallocated, and nulled. !! - !! Closing a live handle also releases the OpenMP thread pool of the calling - !! thread (outside a parallel region only; the next parallel region starts a new - !! one). A pool left to the runtime is torn down when its host thread exits, and - !! its threads then end detached: a process that exits while one of them is - !! still ending can hang in the OpenMP runtime's exit handler (MinGW-w64 libgomp - !! with winpthreads). Joining the pool here means a host thread that closes its - !! handles before it ends leaves no such thread behind. + !! With GNU OpenMP (libgomp), closing a live handle also releases the OpenMP thread + !! pool of the calling thread (outside a parallel region only; the next parallel + !! region starts a new one). A pool left to the runtime is torn down when its host + !! thread exits, and its threads then end detached: a process that exits while one + !! of them is still ending can hang in the OpenMP runtime's exit handler (MinGW-w64 + !! libgomp with winpthreads). Joining the pool here means a host thread that closes + !! its handles before it ends leaves no such thread behind. The Intel and LLVM + !! runtime (libiomp5/libomp) pauses the whole process instead: one handle's Close + !! then paused the OpenMP of every other handle and of the host, and the first + !! parallel region of another thread deadlocked resuming it. Those runtimes are not + !! paused here. !$ USE OMP_LIB, ONLY: omp_pause_resource_all, omp_pause_soft TYPE(C_PTR), INTENT(INOUT) :: handle INTEGER(C_INT), INTENT(OUT) :: err_stat @@ -1380,6 +1384,8 @@ SUBROUTINE CableDyn_Close(handle, err_stat) BIND(C, NAME='CableDyn_Close') INTEGER :: es CHARACTER(CD_C_MSG_LEN) :: em !$ INTEGER :: omp_stat + ! libgomp only (see above): COMPILER_VERSION names the compiler that built this unit + LOGICAL, PARAMETER :: OMP_POOL_JOIN_ON_CLOSE = INDEX(COMPILER_VERSION(), 'GCC') > 0 err_stat = CD_C_OK IF (.NOT. C_ASSOCIATED(handle)) RETURN @@ -1401,7 +1407,7 @@ SUBROUTINE CableDyn_Close(handle, err_stat) BIND(C, NAME='CableDyn_Close') DEALLOCATE (h) handle = C_NULL_PTR ! Nonzero inside an active parallel region, where the pool is left alone. -!$ omp_stat = omp_pause_resource_all(omp_pause_soft) +!$ IF (OMP_POOL_JOIN_ON_CLOSE) omp_stat = omp_pause_resource_all(omp_pause_soft) END SUBROUTINE CableDyn_Close FUNCTION CableDyn_IsInitialized(handle) RESULT(is_initialized) BIND(C, NAME='CableDyn_IsInitialized')