diff --git a/CMakeLists.txt b/CMakeLists.txt index b2b4b1fb..82521785 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1752,9 +1752,8 @@ if(Python3_Interpreter_FOUND) TIMEOUT 600 ENVIRONMENT "${_cabledyn_python_test_environment}") - # Discrete buoyancy modules on a lazy wave in a cross current (the attachment polish falls - # back from diverging Newton steps on the frictional seabed): the static solve converges and - # its end tensions match the equivalent smeared section. + # Discrete buoyancy modules on a lazy wave in a cross current on a frictional seabed: the static + # solve converges without a fallback and its end tensions match the equivalent smeared section. add_test(NAME attachment_cross_current COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_attachment_cross_current.py --exe $ @@ -1961,8 +1960,23 @@ if(Python3_Interpreter_FOUND) LABELS "python;integration;static;dynamic;capi" TIMEOUT 600 ENVIRONMENT "${_cabledyn_python_test_environment}") + # Discrete buoyancy modules in oblique and cross currents (speed, heading, module count and + # mesh refinement swept): the attachment polish converges without its fallbacks on a frictional + # seabed, and a mid-water lazy wave's end forces balance its weight, buoyancy and drag (C API). + # PROCESSORS reserves the four driver processes the test runs at once. + add_test(NAME attachment_polish_current + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_attachment_polish_current.py + --exe $ + --library ${_node_channels_library} + --source ${CMAKE_CURRENT_SOURCE_DIR} + --output ${CMAKE_BINARY_DIR}/attachment_polish_current) + set_tests_properties(attachment_polish_current PROPERTIES + LABELS "python;hermite;static;robustness;attachments;capi" + PROCESSORS 4 + TIMEOUT 900 + ENVIRONMENT "${_cabledyn_python_test_environment}") else() - message(STATUS "node_channels_refined_line: skipped (numpy not importable in ${Python3_EXECUTABLE})") + message(STATUS "node_channels_refined_line, attachment_polish_current: skipped (numpy not importable in ${Python3_EXECUTABLE})") endif() # The arbiter imports numpy + scipy at load time; only register the test when they are diff --git a/doc/driver_format.md b/doc/driver_format.md index 84d808ed..eb2d0104 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -1041,8 +1041,9 @@ Behaviour: with the same drag law at rest, so a run in a current starts in equilibrium. An attachment above the free surface carries its weight only, in the static initial condition too. Attachments have no seabed contact of their own; the node's contact acts on the line. -- The static equilibrium is solved first with each attachment's net weight spread over the two - elements at its node, then carried to the discrete loads by continuation. The current drag +- The static equilibrium is solved first with each attachment's net weight, and in a current + across the vertical plane of the line its drag areas, spread over the two elements at its node, + then carried to the discrete loads by continuation. The current drag depends on the node's position and line direction, and the weight on the side of the surface an attachment is on, so the final solve is repeated until the node positions change by less than 1e-9 m and no attachment changes side. On a line restrained in torsion the torsion stage diff --git a/doc/theory.rst b/doc/theory.rst index 6db8e69f..533b726a 100644 --- a/doc/theory.rst +++ b/doc/theory.rst @@ -2970,8 +2970,12 @@ the nodal tangent :math:`\mathbf{m}_j/\lvert\mathbf{m}_j\rvert` (the line's Mori :math:`C_dA = C_{d,n} d` and :math:`C_dA_x = \pi C_{d,t} d`). The drag enters the velocity tangent and, through :math:`\mathbf{m}_j`, the position tangent exactly. Above the free surface an attachment carries its weight :math:`-m g\,\mathbf{e}_z` alone. The statics start from the -equilibrium with the net weight smeared over the node's two elements and continue to the lumped -load in warm-started Newton solves; in a deck current the drag at rest is added, each solve takes +equilibrium with the net weight smeared over the node's two elements, in a deck current across +the vertical plane of the chord with the drag areas smeared over them too (per-metre drag +coefficients :math:`C_dA/(d\,L)` and :math:`C_dA_x/(\pi d\,L)` added to an element of length +:math:`L` for each share), and continue to the lumped loads in warm-started Newton solves, the +smeared weight and drag moving to the node together; in a deck current the drag at rest is +lumped at the node, each solve takes every attachment's load on the side of the still-water level its node is on, and the final solve is repeated with the loads of its own solution until the nodes stop moving and no attachment changes side (an attachment that its weight in air takes below the surface and its @@ -2989,12 +2993,16 @@ At most 64 load steps may fail in all. A discrete state reached this way passes tensile, physical-branch and stability checks of the smeared state before it is accepted, the kink limit :math:`L_0\kappa \le 0.7` applied away from the attachment nodes: a lumped load turns the line by a slope jump :math:`\theta` at its node, which the :math:`C^1` elements -beside the node carry as :math:`L_0\kappa \approx 2\theta` at any mesh size. The smeared state carries no -attachment drag, and on a frictional seabed, whose regularised friction force turns from its -sticking stiffness to its sliding capacity over a short slip, the Newton update for a -cross-flow drag can overshoot and diverge from the first step (a lazy wave with 25 modules in a -0.3 m/s cross current on 2 m elements, even in steps of 1/64), which the pseudo-transient -regularisation avoids. +beside the node carry as :math:`L_0\kappa \approx 2\theta` at any mesh size. On a frictional +seabed, whose regularised friction force turns from its sticking stiffness to its sliding +capacity over a short slip, a smeared state without the attachment drag left the polish to apply +the whole module drag, and its damped Newton updates diverged from the first step as the +grounded run slid metres sideways (a lazy wave with 25 modules in a 0.3 m/s cross current on 2 m +elements); with the drag smeared, each load step moves the line by millimetres and converges in +a few iterations. A current along the plane does not move the line out of it, and the polish +carries the attachment drag from the smeared state without it, as the smeared start of a coarse +deck mesh could otherwise stop at the grounded-run compression check (a lazy wave restrained in +torsion in 0.5 m/s along its plane). As the pitch :math:`p` of identical modules shrinks, the discrete equilibrium converges to the smeared section at :math:`O(p^2)`. diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index bb3317d5..691923e2 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -1874,6 +1874,8 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, LOGICAL :: bathymetry_flat, require_3d_static, sym_broken, planar_unstable, saddle_kept ! whether the line would be solved in 3D without its torsion (a twisted line always is) LOGICAL :: require_3d_untwisted + ! the deck current has a component across the vertical plane of the chord + LOGICAL :: cross_current ! A planar equilibrium in a current that is a saddle out of its plane (see route_pass). REAL(wp), ALLOCATABLE :: l0_saddle(:), ea_saddle(:), ei_saddle(:), w_saddle(:), q_saddle(:), curv_saddle(:) INTEGER, ALLOCATABLE :: fixed_saddle(:) @@ -1916,6 +1918,10 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, ! smeared equivalent first), and the attachment nodes on the final mesh. LOGICAL :: has_att REAL(wp), ALLOCATABLE :: w_bare_deck(:), l0_deck_att(:), w_bare(:) + ! In a current across the line's plane, the line's own drag coefficients (cur_obj, deck mesh), + ! to which the attachments' drag smeared into cur_obj (smear_attachment_drag) returns in the + ! polish; unallocated when no attachment drag is smeared. + REAL(wp), ALLOCATABLE :: att_cdn_bare(:), att_cdt_bare(:) INTEGER, ALLOCATABLE :: att_node(:) ! STIFFENERS: the cable's own bending stiffness per element (internal order), without the ! sleeve, for the cable's share of the bend moment (allocated only on a stiffened line) @@ -2116,6 +2122,7 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, ! A current with a component across the vertical plane of the chord pushes the line out ! of that plane, which the dynamics (endpoints held, every other DOF free) follow: the ! static equilibrium is then solved in 3D as well. + cross_current = .FALSE. IF (opts%has_current) THEN IF (opts%has_current_grid) THEN ! a current grid (Currents 2 and 5): the static start takes its t = 0 sample, every point @@ -2129,7 +2136,7 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, IF (ABS(-frame_cs(2)*opts%current_grid%velocity(1, ix, iy, iz, 1) + & frame_cs(1)*opts%current_grid%velocity(2, ix, iy, iz, 1)) > & 64.0_wp*EPSILON(CD_ONE)*MAX(CD_ONE, NORM2(opts%current_grid%velocity(:, ix, iy, iz, 1)))) & - require_3d_static = .TRUE. + cross_current = .TRUE. END DO END DO END DO @@ -2138,13 +2145,14 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, DO i = 1, SIZE(opts%current_profile_z) IF (ABS(-frame_cs(2)*opts%current_profile_velocity(1, i) + frame_cs(1)*opts%current_profile_velocity(2, i)) & > 64.0_wp*EPSILON(CD_ONE)*MAX(CD_ONE, NORM2(opts%current_profile_velocity(:, i)))) & - require_3d_static = .TRUE. + cross_current = .TRUE. END DO ELSE IF (ABS(-frame_cs(2)*opts%current_velocity(1) + frame_cs(1)*opts%current_velocity(2)) > & 64.0_wp*EPSILON(CD_ONE)*MAX(CD_ONE, NORM2(opts%current_velocity))) THEN - require_3d_static = .TRUE. + cross_current = .TRUE. END IF END IF + IF (cross_current) require_3d_static = .TRUE. ! A lay azimuth across the vertical plane of the chord puts the as-laid friction ! reference, and the friction it holds, out of that plane: solved in 3D as well. This is ! decided here, before the held (planar) DOFs below are chosen. @@ -2440,6 +2448,24 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, IF (ALLOCATED(cur_obj%profile_velocity)) DEALLOCATE (cur_obj%profile_velocity) IF (ALLOCATED(cur_obj%grid)) DEALLOCATE (cur_obj%grid) END IF + ! In a current across the vertical plane of the chord the smeared start carries the + ! attachments' drag as well as their weight, spread over the same elements + ! (smear_attachment_drag), and the polish moves it to the nodes with the weight. Without + ! it the polish applied the whole attachment drag to the smeared state, which that drag + ! pushes out of its plane: on a frictional seabed its damped Newton solves diverged as + ! the grounded run slid metres sideways (25 modules on a lazy wave in 0.3 m/s across its + ! plane). A current along the plane does not move the line out of it, and the polish + ! carries the attachment drag as before: carried by the smeared start instead, it stopped + ! the current stepping on a coarse deck mesh at the grounded-run compression check (a lazy + ! wave restrained in torsion in 0.5 m/s along its plane, whose discrete state the polish + ! reaches). + IF (has_att .AND. cur_obj%drag .AND. cross_current) THEN + IF (ANY(ln%att(4, :) > CD_ZERO .OR. ln%att(6, :) > CD_ZERO)) THEN + att_cdn_bare = cur_obj%cdn + att_cdt_bare = cur_obj%cdt + CALL smear_attachment_drag(cur_obj%cdn, cur_obj%cdt, cur_obj%diam, l0, att_node, ln%att) + END IF + END IF IF (as_laid) THEN CALL as_laid_reference(es, em) IF (es /= CD_DECKDRV_OK) THEN @@ -3276,7 +3302,12 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, CALL attachment_static_polish(l0, ea, ei, w_bare, w, diam, att_node, ln%att, q_static, fixed_dofs, & contact_enabled, contact_z, frame_cs, endconn_k, endconn_d0_local, & endconn_mode, opts, static_tol, ErrStat, ErrMsg, bathymetry, cur_obj, & - fell_back=att_fell_back) + fell_back=att_fell_back, cdn_bare=att_cdn_bare, cdt_bare=att_cdt_bare) + ! the discrete equilibrium carries the line's own drag (the attachments' at their nodes) + IF (ALLOCATED(att_cdn_bare)) THEN + cur_obj%cdn = att_cdn_bare + cur_obj%cdt = att_cdt_bare + END IF IF (ErrStat /= CD_DECKDRV_OK) RETURN ! A discrete state the damped Newton solves did not reach alone (pseudo-transient ! continuation, line search or smaller load steps) passes the acceptance checks the @@ -5471,15 +5502,51 @@ SUBROUTINE smear_attachments(w, l0, node, att, rho_w, g) END DO END SUBROUTINE smear_attachments + SUBROUTINE smear_attachment_drag(cdn, cdt, diam, l0, node, att) + !! Spread each attachment's drag areas over the elements next to its node, as + !! smear_attachments spreads its net weight: the normal drag area CdA and the axial drag area + !! CdAx become per-metre drag coefficients of those elements (Cd_n d per metre and + !! pi Cd_t d per metre, the line's own Morison law), so that the smeared line carries the + !! attachments' current drag as well as their weight. + REAL(wp), INTENT(INOUT) :: cdn(:), cdt(:) + REAL(wp), INTENT(IN) :: diam(:), l0(:), att(:, :) + INTEGER, INTENT(IN) :: node(:) + INTEGER :: k, j, ne + ne = SIZE(l0) + DO k = 1, SIZE(node) + j = node(k) + IF (j == 1) THEN + CALL add_share(1, CD_ONE) + ELSE IF (j == ne + 1) THEN + CALL add_share(ne, CD_ONE) + ELSE + CALL add_share(j - 1, 0.5_wp) + CALL add_share(j, 0.5_wp) + END IF + END DO + CONTAINS + SUBROUTINE add_share(e, share) + INTEGER, INTENT(IN) :: e + REAL(wp), INTENT(IN) :: share + cdn(e) = cdn(e) + share*att(4, k)/(diam(e)*l0(e)) + cdt(e) = cdt(e) + share*att(6, k)/(4.0_wp*QUARTER_PI*diam(e)*l0(e)) + END SUBROUTINE add_share + END SUBROUTINE smear_attachment_drag + SUBROUTINE attachment_static_polish(l0, ea, ei, w_bare, w_smear, diam, node, att, q, fixed_dofs, & contact_enabled, contact_z, frame_cs, endconn_k, endconn_d0, endconn_mode, & - opts, tol, ErrStat, ErrMsg, bathymetry, cur_obj, fell_back) + opts, tol, ErrStat, ErrMsg, bathymetry, cur_obj, fell_back, cdn_bare, & + cdt_bare) !! Homotopy from the smeared-attachment equilibrium q to the discrete one: in warm-started !! Newton solves the element weights move from w_smear to w_bare while the lumped nodal !! forces -(m - rho V) g e_z (-m g e_z for an attachment above the still-water level, !! attachment_static_weight) and, in a deck current, the attachment current drag grow from !! zero to full, with the contact, dry-buoyancy, end-connection and line current terms of - !! the builder's static problem. The drag depends on the node's position (profile current, + !! the builder's static problem. With cdn_bare and cdt_bare (the line's own drag + !! coefficients of cur_obj, whose cdn and cdt carry the attachments' drag smeared, + !! smear_attachment_drag) the element drag coefficients move from those of cur_obj to them + !! with the weights, so the smeared drag passes to the nodes as the smeared weight does. + !! The drag depends on the node's position (profile current, !! current grid) and line tangent, and the weight on the side of the surface the node is on, !! so each solve takes them at its incoming state and the full-load solve is repeated with !! those of the last solution until the solution stops moving and no attachment changes @@ -5495,12 +5562,12 @@ SUBROUTINE attachment_static_polish(l0, ea, ei, w_bare, w_smear, diam, node, att !! and still advances at the smaller size. At most MAX_FAILED_STEPS load steps may fail in !! all, a backstop that a steady homotopy does not reach (16 failures at worst, at !! MIN_STEP); with at most 1/MIN_STEP converged steps this bounds the polish. - !! The smeared state carries no attachment drag, and on a frictional seabed, whose - !! regularised friction force turns from its sticking stiffness to its sliding capacity - !! over a short slip, the Newton update for a cross-flow drag can overshoot far from the - !! equilibrium and diverge (even in load steps of 1/64), which the pseudo-transient - !! regularisation avoids. Once a damped Newton solve has failed, the - !! later ones get NEWTON_RETRY_ITER iterations before the fallbacks take over. A polish + !! On a frictional seabed, whose regularised friction force turns from its sticking + !! stiffness to its sliding capacity over a short slip, the Newton update for a cross-flow + !! drag can overshoot far from the equilibrium and diverge, which the pseudo-transient + !! regularisation avoids (from a smeared state without the attachment drag, which the polish + !! then applied whole, even load steps of 1/64 diverged). Once a damped Newton solve has + !! failed, the later ones get NEWTON_RETRY_ITER iterations before the fallbacks take over. A polish !! whose damped Newton solves all converge takes exactly the solves it took before. !! fell_back (optional out) reports that a damped Newton solve failed, so that the state !! was reached with the fallbacks (and the caller re-runs its acceptance checks on it). @@ -5517,6 +5584,7 @@ SUBROUTINE attachment_static_polish(l0, ea, ei, w_bare, w_smear, diam, node, att TYPE(CD_BathymetryType), INTENT(IN), OPTIONAL :: bathymetry TYPE(CD_HermiteStaticCurrentType), INTENT(IN), OPTIONAL :: cur_obj LOGICAL, INTENT(OUT), OPTIONAL :: fell_back + REAL(wp), INTENT(IN), OPTIONAL :: cdn_bare(:), cdt_bare(:) INTEGER, PARAMETER :: NSTEP = 8, MAX_FIXED_POINT = 60 ! Smallest load-fraction step: 1/NSTEP halved seven times. Newton budget once a damped ! Newton solve of this polish has failed (a converging one takes well under it). Budget @@ -5538,9 +5606,23 @@ SUBROUTINE attachment_static_polish(l0, ea, ei, w_bare, w_smear, diam, node, att ! The damped Newton failure of the first failed solve, and of the last one. CHARACTER(1024) :: first_msg, last_msg CHARACTER(48) :: step_buf, lam_buf + ! the current of the solves (cur_obj with the element drag coefficients of the load + ! fraction; unallocated without cur_obj) and cur_obj's smeared coefficients + TYPE(CD_HermiteStaticCurrentType), ALLOCATABLE :: cur_l + REAL(wp), ALLOCATABLE :: cdn_smear(:), cdt_smear(:) + LOGICAL :: blend_drag ErrStat = CD_DECKDRV_OK; ErrMsg = '' IF (PRESENT(fell_back)) fell_back = .FALSE. + blend_drag = .FALSE. + IF (PRESENT(cur_obj)) THEN + ALLOCATE (cur_l, SOURCE=cur_obj) + blend_drag = PRESENT(cdn_bare) .AND. PRESENT(cdt_bare) + IF (blend_drag) THEN + cdn_smear = cur_obj%cdn + cdt_smear = cur_obj%cdt + END IF + END IF first_msg = '' last_msg = '' newton_failed = .FALSE. @@ -5568,6 +5650,10 @@ SUBROUTINE attachment_static_polish(l0, ea, ei, w_bare, w_smear, diam, node, att DO WHILE (lam_done < CD_ONE) lam = MIN(CD_ONE, lam_done + dlam) wl = w_bare + (CD_ONE - lam)*(w_smear - w_bare) + IF (blend_drag) THEN + cur_l%cdn = cdn_bare + (CD_ONE - lam)*(cdn_smear - cdn_bare) + cur_l%cdt = cdt_bare + (CD_ONE - lam)*(cdt_smear - cdt_bare) + END IF CALL solve_with(lam, converged) IF (ErrStat /= CD_DECKDRV_OK) RETURN IF (converged) THEN @@ -5692,7 +5778,7 @@ SUBROUTINE solve_with(scale, ok, dq_max) bending_quadrature_order=opts%bending_quadrature_order, & endconn_stiffness=endconn_k, endconn_direction=endconn_d0, & endconn_mode=endconn_mode, waterline_z=CD_ZERO, dry_buoyancy=dry, & - water_weight=opts%rhoW*opts%g, current=cur_obj, & + water_weight=opts%rhoW*opts%g, current=cur_l, & backtracking=mode == MERIT, merit_line_search=mode == MERIT, & pseudo_transient=mode == PSEUDO_TRANSIENT) ELSE @@ -5703,7 +5789,7 @@ SUBROUTINE solve_with(scale, ok, dq_max) bending_quadrature_order=opts%bending_quadrature_order, & endconn_stiffness=endconn_k, endconn_direction=endconn_d0, & endconn_mode=endconn_mode, waterline_z=CD_ZERO, dry_buoyancy=dry, & - water_weight=opts%rhoW*opts%g, current=cur_obj, & + water_weight=opts%rhoW*opts%g, current=cur_l, & backtracking=mode == MERIT, merit_line_search=mode == MERIT, & pseudo_transient=mode == PSEUDO_TRANSIENT) END IF diff --git a/tests/test_attachment_cross_current.py b/tests/test_attachment_cross_current.py index 29305eee..5f6346b0 100644 --- a/tests/test_attachment_cross_current.py +++ b/tests/test_attachment_cross_current.py @@ -6,14 +6,16 @@ The lazy-wave power cable of ``tests/data/lazy_wave_touchdown_planar_{refined,coarse}_att.dat`` (25 discrete buoyancy modules at a 4 m pitch, rigid end connections, seabed friction 0.35) is put in a uniform current across its vertical plane. The static solve reaches the discrete -equilibrium from the smeared one by a homotopy in the module loads and drag; on the refined -mesh in 0.3 m/s its damped Newton steps diverge on the frictional seabed, and the polish must -fall back to its regularised solves rather than fail (its note naming that path is required). +equilibrium from the smeared one by a homotopy in the module loads and drag. Every deck must solve (exit 0), and its line-end tensions must agree with the deck that replaces the modules by the equivalent smeared section (the same submerged weight, displaced volume and normal drag per metre over the stretch the modules cover): FairTen within 1 % and -AnchTen within 2 % of the smeared values. +AnchTen within 2 % of the smeared values. The static solve reaches the discrete state without a +fallback: in a current across the line's plane the smeared start carries the modules' drag as well +as their weight, so the polish only moves both to the nodes (with the drag left out of the smeared +start, the refined deck in 0.3 m/s reached it only through the pseudo-transient and line-search +repetitions). usage: test_attachment_cross_current.py --exe --data --output """ @@ -32,10 +34,8 @@ BARE_D, BARE_M, BARE_CDN, BARE_CDT = 0.16, 36.70, 1.2, 0.1 FAIR_TOL, ANCH_TOL = 0.01, 0.02 CASES = [("refined", 0.3), ("refined", 0.6), ("coarse", 0.3), ("coarse", 0.6)] -# The case whose polish takes the fallback path; its note says so (and that the state passed -# the acceptance checks of the smeared state). -FALLBACK_CASE = "refined_0.3" -FALLBACK_NOTE = "was reached after a failed Newton solve" +# Notes of a static solve that reached its state through a fallback. +FALLBACK_NOTES = ("reached after a failed Newton solve", "stalled", "looser tolerance") def with_current(text: str, speed: float) -> str: @@ -95,8 +95,9 @@ def main() -> int: rc, row, log = run(exe, d / "deck.dat") if rc != 0 or "FairTen4" not in row: failures.append("%s %s: exit %d\n%s" % (name, kind, rc, log[-2000:])) - if kind == "discrete" and name == FALLBACK_CASE and FALLBACK_NOTE not in log: - failures.append("%s: the polish did not report its fallback path" % name) + notes = [n for n in FALLBACK_NOTES if n in log] + if notes: + failures.append("%s %s: the static solve needed a fallback (%s)" % (name, kind, ", ".join(notes))) results[kind] = row if all("FairTen4" in r for r in results.values()): disc, smr = results["discrete"], results["smeared"] diff --git a/tests/test_attachment_polish_current.py b/tests/test_attachment_polish_current.py new file mode 100644 index 00000000..62fb5126 --- /dev/null +++ b/tests/test_attachment_polish_current.py @@ -0,0 +1,289 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Discrete buoyancy modules in an oblique or cross current: the attachment polish converges cleanly. + +The static solve of a line with ATTACHMENTS first finds the equilibrium with the modules smeared +over the elements beside their nodes, then carries it to the lumped loads by a homotopy (the +attachment polish). The smeared start carried the modules' weight but not their current drag, so +the polish applied the whole module drag to it: on the frictional seabed of +``tests/data/lazy_wave_touchdown_planar_coarse_att.dat`` (friction 0.35) in a current across the +line's plane, its damped Newton solves diverged as the grounded run slid metres sideways, and the +discrete state was reached only through the pseudo-transient and line-search fallbacks (25 +modules, 2 m elements, 0.3 m/s at 90 deg: the first load step of 1/8 failed). In a current +across the line's plane the smeared start now carries the module drag too, and the polish moves it +to the nodes with the weight (a current along the plane keeps the former path: the in-plane +control below). + +Gates: + +1. Robustness, on the frictional lazy wave with its 96 m buoyant stretch rebuilt from 10, 25 or 40 + modules (the same total mass, volume and drag area), on the deck's 4 m / 10 m grading with the + buoyant section at 1, 2 or 4 times its node density, or on 2 m elements throughout with that + section refined again, in a uniform current of 0.1 to 0.5 m/s at 45 or 90 deg to the line's + plane (and two controls: still water and an in-plane current): every deck solves (exit 0) + without a fallback note ("reached after a failed Newton solve", "stalled", "looser + tolerance"), and the line's mean out-of-plane offset has the sign of the current's cross + component. +2. Physics, on the lazy wave of ``examples/lazy_wave_buoyancy_modules.dat`` hung in mid-water (the + seabed lowered to 300 m, so no contact force enters the balance) with 25 or 40 modules in 0.3 or + 0.5 m/s at 45 or 90 deg: the end forces the line puts on its two points (C API, double + precision) balance its weight and buoyancy, the modules' net weight and the current drag of + cable (three-point Gauss on the Hermite centreline rebuilt from the node positions and + tangents) and modules (at their nodes) to 1e-6 of the largest load, and the line deflects + toward the current's cross component. The C API's declination and azimuth are a central + difference of the node positions, which is not the tangent at a module node (the curvature + jumps there), so a module's tangent is the mean of the one-sided fourth-order differences. +3. Torsion, on ``tests/data/lazy_wave_torsion_attachments.dat`` (the frictional lazy wave restrained + in torsion with one turn of pretwist) in 0.3 m/s at 45 deg: the deck solves without a fallback + note and its torsion stage reports the twist solved (it stopped before in the smeared stage). + +usage: test_attachment_polish_current.py --exe --library --source + --output +""" + +from __future__ import annotations + +import argparse +import math +import os +import re +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import numpy as np + +FALLBACK_NOTES = ("reached after a failed Newton solve", "stalled", "looser tolerance") +BALANCE_TOL = 1.0e-6 + +# (mesh, speed m/s, heading deg from the line's plane, modules, buoyant-section refinement). +# mesh "deck": the deck's 4 m / 10 m grading; "fine": 2 m elements throughout. Every case but the +# two controls reached its discrete state only through the polish's fallbacks before. +ROBUST_CASES = [ + ("fine", 0.3, 90, 25, 1), + ("fine", 0.3, 90, 25, 4), + ("fine", 0.3, 90, 40, 2), + ("fine", 0.3, 45, 40, 4), + ("fine", 0.1, 90, 10, 4), + ("fine", 0.1, 45, 25, 1), + ("fine", 0.2, 45, 10, 2), + ("fine", 0.2, 90, 40, 4), + ("fine", 0.5, 45, 40, 2), + ("fine", 0.5, 45, 25, 1), + ("deck", 0.2, 90, 25, 4), + ("deck", 0.5, 45, 10, 2), + ("deck", 0.5, 45, 40, 4), + ("deck", 0.5, 45, 25, 1), + ("fine", 0.0, 0, 25, 2), + ("fine", 0.3, 0, 25, 2), +] +# (speed, heading, modules, refinement) on the mid-water lazy wave +BALANCE_CASES = [(0.3, 90, 25, 2), (0.5, 90, 40, 4), (0.3, 45, 25, 4), (0.5, 90, 25, 4)] +# (speed, heading) on the lazy wave restrained in torsion +TORSION_CASES = [(0.3, 45)] + +RHO, G = 1025.0, 9.80665 +# examples/lazy_wave_buoyancy_modules.dat: the bare cable and its ten modules over 70.614-115.614 m +GOMEX_D, GOMEX_M, GOMEX_EA, GOMEX_CDN, GOMEX_CDT = 0.16, 36.70, 4.69e8, 1.2, 0.1 +GOMEX_MOD = (114.15, 0.2297, 0.78, 0.2042) + + +def current_row(speed: float, heading: float) -> str: + th = math.radians(heading) + ux, uy = round(speed * math.cos(th), 12) + 0.0, round(speed * math.sin(th), 12) + 0.0 + return "uniform %.12g %.12g 0.0 current" % (ux, uy) + + +def touchdown_deck(source: Path, mesh: str, speed: float, heading: float, n_mod: int, refine: int) -> str: + """The frictional lazy wave with n_mod modules over 80-176 m (25 at 4 m in the deck).""" + text = (source / "tests" / "data" / "lazy_wave_touchdown_planar_coarse_att.dat").read_text() + pitch = 96.0 / (n_mod - 1) + per_pitch = max(1, round(pitch / 4.0)) + g = 2 if mesh == "fine" else 1 + rows = "4 bare 80.0 %d\n4 bare 96.0 %d\n4 bare 424.0 %d\n" % ( + 20 * g, (n_mod - 1) * per_pitch * refine * g, 170 if mesh == "fine" else 42) + text = re.sub(r"(-+ SECTIONS -+\n.*\n.*\n)(?:4 .*\n)+", lambda m: m.group(1) + rows, text) + s = 25.0 / n_mod + att = "4 80.0:%.10g:176.0 %.6g %.6g %.6g 1.0 0.0\n" % (pitch, 91.32 * s, 0.18378 * s, 1.392 * s) + text = re.sub(r"(-+ ATTACHMENTS -+\n.*\n.*\n)(?:4 .*\n)+", lambda m: m.group(1) + att, text) + if speed: + text = re.sub(r"^(0\.0 TMax)$", lambda m: m.group(1) + "\n" + current_row(speed, heading), text, + count=1, flags=re.M) + return text + + +def torsion_deck(source: Path, speed: float, heading: float) -> str: + """tests/data/lazy_wave_torsion_attachments.dat, static only, in a uniform current.""" + text = (source / "tests" / "data" / "lazy_wave_torsion_attachments.dat").read_text() + text, n = re.subn(r"^\S+(\s+TMax)$", lambda m: "0.0" + m.group(1) + "\n" + current_row(speed, heading), text, + count=1, flags=re.M) + if n != 1: + raise RuntimeError("the torsion deck has no TMax row") + return text + + +def gomex_sections(n_mod: int, refine: int) -> list[tuple[float, int]]: + return [(70.614, 71), (45.0, (n_mod - 1) * max(1, round(45.0 / (n_mod - 1))) * refine), (54.601, 55)] + + +def midwater_deck(source: Path, speed: float, heading: float, n_mod: int, refine: int) -> str: + """examples/lazy_wave_buoyancy_modules.dat with n_mod modules (the same totals), seabed at 300 m.""" + text = (source / "examples" / "lazy_wave_buoyancy_modules.dat").read_text() + rows = "".join("1 bare %.3f %d\n" % sec for sec in gomex_sections(n_mod, refine)) + text = re.sub(r"(-+ SECTIONS -+\n.*\n.*\n)(?:1 .*\n)+", lambda m: m.group(1) + rows, text) + s = 10.0 / n_mod + m, v, cda, cdax = (x * s for x in GOMEX_MOD) + att = "1 70.614:%.10g:115.614 %.6g %.6g %.6g 1.0 %.6g\n" % (45.0 / (n_mod - 1), m, v, cda, cdax) + text = re.sub(r"(-+ ATTACHMENTS -+\n.*\n.*\n)(?:1 .*\n)+", lambda m_: m_.group(1) + att, text) + text = re.sub(r"^uniform 0\.5 0\.0 0\.0 .*$", current_row(speed, heading), text, count=1, flags=re.M) + text = re.sub(r"^80\.0(\s+WtrDpth)", r"300.0\1", text, count=1, flags=re.M) + text = re.sub(r'^"TDP1[sx]"\n', "", text, flags=re.M) + return text + + +def run(exe: str, d: Path, text: str) -> tuple[int, str]: + d.mkdir(parents=True, exist_ok=True) + (d / "deck.dat").write_text(text, newline="\n") + p = subprocess.run([exe, "deck.dat", "o"], cwd=d, capture_output=True, text=True, timeout=1200) + return p.returncode, p.stdout + p.stderr + + +def static_y(d: Path) -> np.ndarray: + lines = (d / "o.static.out").read_text().splitlines()[3:] + return np.array([float(ln.split()[4]) for ln in lines if ln.strip()]) + + +def morison(u: np.ndarray, t: np.ndarray, d: float, cdn: float, cdt: float) -> np.ndarray: + t = t / np.linalg.norm(t) + ut = np.dot(u, t) * t + un = u - ut + return 0.5 * RHO * d * (cdn * np.linalg.norm(un) * un + math.pi * cdt * np.linalg.norm(ut) * ut) + + +def balance(deck: Path, speed: float, heading: float, n_mod: int, refine: int) -> tuple[float, float]: + """(|end forces - loads| / largest load, mean y offset) of the static state through the C API.""" + from cabledyn import CableDyn + + with CableDyn(deck) as model: + line = model.line(1) + x = np.array(line.node_positions()) + ten = np.array(line.node_tensions()) + dec, azi = np.radians(line.declination()), np.radians(line.azimuth()) + ends = np.array([model.channel("Point1F" + c) + model.channel("Point2F" + c) for c in "xyz"]) + largest = max(abs(model.channel("FairTen1")), abs(model.channel("AnchTen1"))) + l0 = np.concatenate([np.full(n, length / n) for length, n in gomex_sections(n_mod, refine)]) + if len(x) != len(l0) + 1: + raise RuntimeError("the static solve refined the mesh (%d nodes)" % len(x)) + tan = np.stack([np.sin(dec) * np.cos(azi), np.sin(dec) * np.sin(azi), np.cos(dec)], 1) + m = tan * (1.0 + ten / GOMEX_EA)[:, None] # dr/ds, the stretch from the tension + th = math.radians(heading) + u = np.array([round(speed * math.cos(th), 12), round(speed * math.sin(th), 12), 0.0]) + w_bare = (GOMEX_M - RHO * math.pi / 4.0 * GOMEX_D**2) * G + load = np.array([0.0, 0.0, -w_bare * l0.sum()]) + gx = [0.5 - 0.5 * math.sqrt(0.6), 0.5, 0.5 + 0.5 * math.sqrt(0.6)] + gw = [5.0 / 18.0, 8.0 / 18.0, 5.0 / 18.0] + for e, le in enumerate(l0): + for xi, wgt in zip(gx, gw): + dh = [(-6 * xi + 6 * xi**2) / le, 1 - 4 * xi + 3 * xi**2, (6 * xi - 6 * xi**2) / le, -2 * xi + 3 * xi**2] + rp = dh[0] * x[e] + dh[1] * m[e] + dh[2] * x[e + 1] + dh[3] * m[e + 1] + load += wgt * le * np.linalg.norm(rp) * morison(u, rp, GOMEX_D, GOMEX_CDN, GOMEX_CDT) + s = 10.0 / n_mod + mass, vol, cda, cdax = (v * s for v in GOMEX_MOD) + cum = np.concatenate([[0.0], np.cumsum(l0)]) + for k in range(n_mod): + j = int(np.argmin(np.abs(cum - (70.614 + k * 45.0 / (n_mod - 1))))) + load[2] -= (mass - RHO * vol) * G + tl = 25 * x[j] - 48 * x[j - 1] + 36 * x[j - 2] - 16 * x[j - 3] + 3 * x[j - 4] + tr = -25 * x[j] + 48 * x[j + 1] - 36 * x[j + 2] + 16 * x[j + 3] - 3 * x[j + 4] + t = tl / np.linalg.norm(tl) + tr / np.linalg.norm(tr) + t /= np.linalg.norm(t) + ut = np.dot(u, t) * t + un = u - ut + load += 0.5 * RHO * (cda * np.linalg.norm(un) * un + cdax * np.linalg.norm(ut) * ut) + largest = max(largest, abs(load[2])) + return float(np.abs(ends - load).max() / largest), float(x[:, 1].mean()) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--exe", required=True) + ap.add_argument("--library", required=True) + ap.add_argument("--source", required=True) + ap.add_argument("--output", required=True) + ap.add_argument("--jobs", type=int, default=4) + a = ap.parse_args() + exe = str(Path(a.exe).resolve()) + source = Path(a.source) + out = Path(a.output) + failures: list[str] = [] + + def robust(case): + mesh, speed, heading, n_mod, refine = case + name = "%s_U%.1f_h%d_N%d_r%d" % case + rc, log = run(exe, out / name, touchdown_deck(source, mesh, speed, heading, n_mod, refine)) + return name, case, rc, log + + def solve_balance(case): + speed, heading, n_mod, refine = case + name = "midwater_U%.1f_h%d_N%d_r%d" % case + rc, log = run(exe, out / name, midwater_deck(source, speed, heading, n_mod, refine)) + return name, case, rc, log + + def torsion(case): + speed, heading = case + name = "torsion_U%.1f_h%d" % case + rc, log = run(exe, out / name, torsion_deck(source, speed, heading)) + return name, rc, log + + with ThreadPoolExecutor(a.jobs) as pool: + torsion_runs = pool.map(torsion, TORSION_CASES) + robust_runs = list(pool.map(robust, ROBUST_CASES)) + balance_runs = list(pool.map(solve_balance, BALANCE_CASES)) + torsion_runs = list(torsion_runs) + + for name, (mesh, speed, heading, n_mod, refine), rc, log in robust_runs: + notes = [n for n in FALLBACK_NOTES if n in log] + y = static_y(out / name).mean() if rc == 0 else float("nan") + uy = speed * math.sin(math.radians(heading)) + print("%-26s exit %d fallback notes %s mean y %+.4f m" % (name, rc, notes or "none", y)) + if rc != 0: + failures.append("%s: exit %d\n%s" % (name, rc, log[-1500:])) + elif notes: + failures.append("%s: the static solve needed a fallback (%s)" % (name, ", ".join(notes))) + elif (uy > 0.0 and not y > 0.0) or (uy == 0.0 and abs(y) > 1.0e-9): + failures.append("%s: mean out-of-plane offset %.3e m against a cross current %.3f m/s" % (name, y, uy)) + + for name, rc, log in torsion_runs: + notes = [n for n in FALLBACK_NOTES if n in log] + solved = "torsion solved" in log + print("%-26s exit %d fallback notes %s torsion solved %s" % (name, rc, notes or "none", solved)) + if rc != 0 or notes or not solved: + failures.append("%s: exit %d, fallback notes %s, torsion solved %s\n%s" % (name, rc, notes, solved, + log[-1500:])) + + os.environ["CABLEDYN_LIBRARY"] = str(Path(a.library).resolve()) + sys.path.insert(0, str(source / "python")) + for name, (speed, heading, n_mod, refine), rc, log in balance_runs: + notes = [n for n in FALLBACK_NOTES if n in log] + if rc != 0 or notes: + failures.append("%s: exit %d, fallback notes %s\n%s" % (name, rc, notes, log[-1500:])) + continue + err, y = balance(out / name / "deck.dat", speed, heading, n_mod, refine) + print("%-26s force balance %.2e of the largest load mean y %+.4f m" % (name, err, y)) + if not err <= BALANCE_TOL: + failures.append("%s: the end forces miss the line's loads by %.2e of the largest load" % (name, err)) + if not y > 0.0: + failures.append("%s: mean out-of-plane offset %.3e m against the current" % (name, y)) + + for f in failures: + print("FAIL: " + f) + if failures: + return 1 + print("PASS: the attachment polish converges cleanly in oblique and cross currents, in force balance") + return 0 + + +if __name__ == "__main__": + sys.exit(main())