-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfenton_gui.cpp
More file actions
2538 lines (2137 loc) · 100 KB
/
fenton_gui.cpp
File metadata and controls
2538 lines (2137 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ==============================================================================
* ENGINEERING TECHNICAL REFERENCE & THEORETICAL FORMULATION
* ==============================================================================
* PROGRAM: Nonlinear Wave Hydrodynamics Solver (Fenton's Stream Function)
* METHOD: Fourier Approximation Method for Steady Water Waves (N=50)
* REFERENCE: Fenton, J.D. (1999). "Numerical methods for nonlinear waves."
* In P.L.-F. Liu (Ed.), Advances in Coastal and Ocean Engineering
* (Vol. 5, pp. 241–324). World Scientific: Singapore.
* ==============================================================================
*
* 1. INTRODUCTION & SCOPE
* -----------------------------------------------------------------------------
* This software calculates the hydrodynamics of steady, periodic surface gravity
* waves using high-order Stream Function theory. Unlike Linear (Airy) Theory,
* which assumes infinitesimal amplitudes, this method retains full nonlinearity
* in the boundary conditions.
*
* Implementation Specifics (C++ Port):
* - Solver: Dense nonlinear least-squares solver aligned with SciPy
* scipy.optimize.least_squares behavior:
* • TRF-style trust-region steps for robust continuation seeding.
* • MINPACK-style Levenberg–Marquardt for final rapid convergence.
* - Stability: Uses a Homotopy (continuation) method, stepping wave height
* incrementally from near-linear to target height to guarantee convergence.
* (Implemented as 4 steps: linspace(0.01, H_target, 4), matching Python.)
* - Regime: Applicable to stable waves in shallow, intermediate, and deep
* water regimes up to the Miche breaking limit.
*
* 2. GOVERNING FIELD EQUATIONS
* -----------------------------------------------------------------------------
* The fluid is modeled as inviscid, incompressible, and irrotational.
* The flow is solved in a frame of reference moving with the wave celerity (c),
* rendering the flow steady.
*
* A. Field Equation (Laplace):
* ∇²ψ = ∂²ψ/∂x² + ∂²ψ/∂z² = 0
* Where ψ(x,z) is the stream function. Velocities are defined as:
* u = ∂ψ/∂z (Horizontal)
* w = -∂ψ/∂x (Vertical)
*
* B. Bottom Boundary Condition (BBC) at z=0:
* The seabed is impermeable (a streamline).
* ψ(x, 0) = -Q
* Where Q is the volume flux per unit width in the moving frame.
*
* 3. FREE SURFACE BOUNDARY CONDITIONS
* -----------------------------------------------------------------------------
* The solution is constrained by two nonlinear conditions at the unknown
* free surface elevation z = η(x):
*
* A. Kinematic Boundary Condition (KBC):
* The free surface is a streamline (constant ψ).
* ψ(x, η) = 0
*
* B. Dynamic Boundary Condition (DBC - Bernoulli):
* Pressure is constant (atmospheric) along the surface.
* 1/2 * [ (∂ψ/∂x)² + (∂ψ/∂z)² ] + gη = R
* Where R is the Bernoulli constant (Total Energy Head).
*
* 4. NUMERICAL SOLUTION (FOURIER ANSATZ)
* -----------------------------------------------------------------------------
* The stream function is approximated by a truncated Fourier series of order N
* (N=50) that analytically satisfies the Field Equation and Bottom BC:
*
* ψ(x,z) = -(ū + c) z + Σ_{j=1..N} B_j * [sinh(jkz)/cosh(jkd)] * cos(jkx)
*
* Deep Water Numerical Stability:
* To prevent floating-point overflow when kd >> 1, the code replaces the
* hyperbolic ratio with asymptotic exponentials when arguments > 25.0:
*
* sinh(jkz)/cosh(jkd) ≈ exp(jk(z-d))
*
* Optimization Vector (State Space):
* The solver minimizes residuals for the vector
*
* X = [k, η_0...η_N, B_1...B_N, Q, R]
*
* IMPORTANT (Overdetermined Residual System):
* The residual vector dimension is NOT equal to the number of unknowns.
* For N=50:
* - Unknowns: n = 1 + (N+1) + N + 2 = 2N + 4 = 104
* - Residuals: m = 3 + (N+1) + (N+1) = 2(N+1) + 3 = 105
* The implementation MUST allocate m=105 and never assume m==n, otherwise
* out-of-bounds writes will occur and results will become optimizer/flags dependent.
*
* 5. DERIVED PHYSICAL PARAMETERS & OUTPUT DEFINITIONS
* -----------------------------------------------------------------------------
* Upon convergence, the software calculates the following engineering parameters
* derived from the solved Fourier coefficients (B_j).
*
* A. FUNDAMENTAL WAVE GEOMETRY & PHASE
* ------------------------------------
* 1. Wavelength (L):
* Horizontal distance between crests. Solved via dispersion relation.
* L = c·T = 2π / k
*
* 2. Celerity (c):
* Phase velocity. c = L / T.
*
* B. KINEMATICS (VELOCITIES & ACCELERATIONS)
* ------------------------------------------
* 1. Horizontal Velocity (u):
* u(x,z) = c - ū + Σ_{j=1..N} jkB_j * [cosh(jkz)/cosh(jkd)] * cos(jkx)
*
* 2. Vertical Velocity (w):
* w(x,z) = Σ_{j=1..N} jkB_j * [sinh(jkz)/cosh(jkd)] * sin(jkx)
*
* 3. Max Acceleration (a_x):
* Total derivative (Convective acceleration).
* a_x = Du/Dt = u * ∂u/∂x + w * ∂u/∂z
*
* NOTE (Python-parity detail):
* The vertical perturbation term uses +sin(j·phase) (not -sin). A sign error
* here distorts the convective term w·∂u/∂z and breaks Max Accel parity.
*
* 4. Velocity Asymmetry:
* Asymmetry = |u_crest| / |u_trough|
*
* C. DYNAMICS (INTEGRAL PROPERTIES)
* ---------------------------------
* Computed using exact integral invariants (Fenton Eqs 14-16).
*
* 1. Impulse (I):
* Total wave momentum (kg·m/s).
* I = ρ(c d - Q)
*
* 2. Energy Density (E):
* Mean Energy (J/m²).
* PE = 1/2 ρ g mean(η²)
* KE = 1/2 (cI - Qρ U_c)
* E = PE + KE
*
* 3. Power / Energy Flux (P):
* Rate of energy transfer (W/m).
* P = c(3KE - 2PE) + 1/2 mean(u_b²)(I + ρ c d) + 1/2 ρ Q U_c²
*
* Note on mean(u_b²) (Mean Square Bed Velocity):
* To avoid deep-water integration errors, this is computed algebraically:
* mean(u_b²) = 2(R - g d) - c²
*
* 4. Radiation Stress (Sxx):
* Excess momentum flux (N/m).
* Sxx = 4KE - 3PE + ρ mean(u_b²) d + 2ρ I U_c
*
* 5. Mean Stokes Drift (U_drift):
* U_drift = I / (ρ d)
*
* D. STABILITY & REGIME CLASSIFICATION
* ------------------------------------
* 1. Ursell Number (U_r):
* U_r = H L² / d³ (Values > 26 indicate significant nonlinearity).
*
* 2. Miche Limit (H_max):
* Theoretical max height before breaking.
* H_max = 0.142 L tanh(kd)
*
* 3. Saturation (Breaking Index):
* Saturation = H / H_max
* - If > 1.0: Wave is BREAKING.
* - If < 1.0: Wave is STABLE.
*
* 4. Regime:
* - Shallow: d/L < 0.05
* - Intermediate: 0.05 < d/L < 0.5
* - Deep: d/L > 0.5
*
* ==============================================================================
* 6. SOFTWARE USAGE & COMPILATION GUIDE (C++)
* ==============================================================================
*
* A. PREREQUISITES
* ----------------
* - Windows (Win32 API GUI build). MinGW-w64 (g++) or MSVC with C++17 support.
* - Basic familiarity with the command line (Terminal/CMD).
*
* B. BUILDING FROM SOURCE
* ------------------------------------
* 1. Ensure a C++17-capable toolchain is installed and on PATH (g++ recommended).
*
* 2. Compile (release-like build, GUI subsystem):
* > g++ fenton_gui.cpp -o fenton_gui.exe -O3 -std=gnu++17 -march=native ^
* -lgdi32 -luser32 -lkernel32 -lcomctl32 -static -mwindows -pthread
*
* Build note (Python-parity / "no current" stability):
* This solver is path-sensitive: small floating-point differences can change trust-region
* acceptance and LM step damping, pushing the "no current" case to a different local minimum.
* On this system, Python-parity (including the "no current" scenario) is achieved ONLY when
* compiling with -march=native (enables CPU-specific instruction selection such as FMA and
* vectorization patterns). Removing -march=native has been observed to produce incorrect
* "no current" results even when all equations and tolerances are unchanged.
* For bitwise-stable results, keep the same CPU family, compiler version, and flags.
*
* 3. Run:
* > fenton_gui.exe
*
* C. STANDALONE EXECUTABLE (.EXE)
* ------------------------------
* The build command above produces a standalone fenton_gui.exe (no Python required).
* The program writes results to the GUI output panel and also produces an "output.txt"
* file (UTF-8) to disk.
*
* ==============================================================================
* BIBLIOGRAPHY
* ==============================================================================
*
* 1. Fenton, J.D. (1999). "Numerical methods for nonlinear waves."
* In P.L.-F. Liu (Ed.), Advances in Coastal and Ocean Engineering (Vol. 5,
* pp. 241–324). World Scientific: Singapore.
* [Primary Source: Comprehensive review of fully-nonlinear methods including
* Fourier approximation, Boundary Integral Equation (BIE) methods, and
* Local Polynomial Approximation].
* URL: https://johndfenton.com/Papers/Fenton99Liu-Numerical-methods-for-nonlinear-waves.pdf
*
* 2. Fenton, J.D. (1988). "The numerical solution of steady water wave problems."
* Computers & Geosciences, 14(3), 357–368.
* [The core algorithm for high-accuracy Stream Function Theory].
* URL: https://doi.org/10.1016/0098-3004(88)90066-0
*
* 3. Fenton, J.D. (1985). "A fifth-order Stokes theory for steady waves."
* Journal of Waterway, Port, Coastal, and Ocean Engineering, 111(2), 216–234.
* [Standard analytical theory for deep/intermediate water pile design].
* URL: https://doi.org/10.1061/(ASCE)0733-950X(1985)111:2(216)
*
* 4. Fenton, J.D. (1978). "Wave forces on vertical bodies of revolution."
* Journal of Fluid Mechanics, 85(2), 241–255.
* [Foundational diffraction theory for large diameter piles].
* URL: https://johndfenton.com/Papers/Fenton78-Waves-on-bodies-of-revolution.pdf
*
* 5. Fenton, J.D. (1990). "Nonlinear wave theories." In B. Le Méhauté &
* D.M. Hanes (Eds.), The Sea: Ocean Engineering Science (Vol. 9, Part A).
* John Wiley & Sons.
* [Comprehensive guide for selecting wave theories: Stokes vs Cnoidal vs Stream].
* URL: https://www.johndfenton.com/Papers/Fenton90b-Nonlinear-wave-theories.pdf
* ==============================================================================
*/
#define _USE_MATH_DEFINES
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX 1
#endif
#include <windows.h>
#include <commctrl.h>
// --- nanosleep64 stub (MSYS2/MinGW GCC 15 + -static workaround) -----------------
#if defined(_WIN32) && defined(__MINGW32__)
#include <time.h> // struct _timespec64
#include <errno.h>
#include <limits.h> // LLONG_MAX
extern "C" __attribute__((used))
int __cdecl nanosleep64(const struct _timespec64* request, struct _timespec64* remain)
{
if (!request) { errno = EINVAL; return -1; }
const long long sec = (long long)request->tv_sec;
const long nsec = (long)request->tv_nsec;
if (sec < 0 || nsec < 0 || nsec >= 1000000000L) { errno = EINVAL; return -1; }
// Convert to 100ns units for WaitableTimer (ceil so we don't undersleep)
const long long max_sec = LLONG_MAX / 10000000LL;
const long long sec_c = (sec > max_sec) ? max_sec : sec;
long long total_100ns = sec_c * 10000000LL + ((long long)nsec + 99LL) / 100LL;
if (total_100ns <= 0) total_100ns = 1;
HANDLE t = CreateWaitableTimerW(NULL, TRUE, NULL);
if (!t) {
// Fallback: Sleep (ms resolution)
unsigned long long total_ms =
(unsigned long long)sec_c * 1000ULL +
(unsigned long long)((nsec + 999999L) / 1000000L);
DWORD ms = (total_ms > 0xFFFFFFFEULL) ? 0xFFFFFFFEUL : (DWORD)total_ms;
Sleep(ms);
} else {
LARGE_INTEGER due;
due.QuadPart = -total_100ns; // relative
if (SetWaitableTimer(t, &due, 0, NULL, NULL, FALSE))
WaitForSingleObject(t, INFINITE);
CloseHandle(t);
}
if (remain) {
remain->tv_sec = 0;
remain->tv_nsec = 0;
}
return 0;
}
#endif // defined(_WIN32) && defined(__MINGW32__)
// -------------------------------------------------------------------------------
// Continue with the rest of C/C++ includes
#include <algorithm>
#include <atomic>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <future>
#include <iomanip>
#include <limits>
#include <memory>
#include <mutex>
#include <queue>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <fstream>
// ==============================================================================
// THREAD POOL (Persistent, low overhead)
// ==============================================================================
class ThreadPool {
public:
explicit ThreadPool(size_t threads = 0) : m_stop(false) {
if (threads == 0) threads = std::thread::hardware_concurrency();
if (threads == 0) threads = 2;
m_workers.reserve(threads);
for (size_t i = 0; i < threads; ++i) {
m_workers.emplace_back([this]() {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [this]() { return m_stop || !m_tasks.empty(); });
if (m_stop && m_tasks.empty()) return;
task = std::move(m_tasks.front());
m_tasks.pop();
}
task();
}
});
}
}
template <class F, class... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
using return_type = typename std::result_of<F(Args...)>::type;
auto task = std::make_shared<std::packaged_task<return_type()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_stop) throw std::runtime_error("enqueue on stopped ThreadPool");
m_tasks.emplace([task]() { (*task)(); });
}
m_cv.notify_one();
return res;
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(m_mutex);
m_stop = true;
}
m_cv.notify_all();
for (std::thread& w : m_workers) {
if (w.joinable()) w.join();
}
}
private:
std::vector<std::thread> m_workers;
std::queue<std::function<void()>> m_tasks;
std::mutex m_mutex;
std::condition_variable m_cv;
bool m_stop;
};
// Lazy global pool (used for Jacobian construction)
static std::unique_ptr<ThreadPool> g_pool;
// ==============================================================================
// PHYSICAL CONSTANTS (must match fenton_gui.py)
// ==============================================================================
namespace Phys {
using Real = double;
constexpr Real PI = 3.141592653589793238462643383279502884;
constexpr Real RHO = 1025.0;
constexpr Real G_STD = 9.80665;
}
using Phys::Real;
// ==============================================================================
// SMALL LINEAR ALGEBRA (dense, for n ~ 100)
// ==============================================================================
namespace LinAlg {
static inline bool is_finite(Real x) {
return std::isfinite(x);
}
static inline Real dot(const std::vector<Real>& a, const std::vector<Real>& b) {
Real s = 0.0;
const size_t n = a.size();
for (size_t i = 0; i < n; ++i) s += a[i] * b[i];
return s;
}
static inline Real norm2_sq(const std::vector<Real>& a) {
return dot(a, a);
}
static inline Real norm2(const std::vector<Real>& a) {
return std::sqrt(norm2_sq(a));
}
static inline Real norm_inf(const std::vector<Real>& a) {
Real m = 0.0;
for (Real v : a) m = std::max(m, std::abs(v));
return m;
}
// Solve A x = b with Gaussian elimination + partial pivoting.
// A is overwritten (row operations). b is overwritten. Returns false if singular.
static bool solve_linear_system(int n, std::vector<Real>& A, std::vector<Real>& b, std::vector<Real>& x) {
x = b;
for (int k = 0; k < n - 1; ++k) {
Real max_v = 0.0;
int max_i = k;
for (int i = k; i < n; ++i) {
const Real v = std::abs(A[i * n + k]);
if (v > max_v) { max_v = v; max_i = i; }
}
if (max_v < 1e-30) return false;
if (max_i != k) {
for (int j = k; j < n; ++j) std::swap(A[k * n + j], A[max_i * n + j]);
std::swap(x[k], x[max_i]);
}
const Real pivot = A[k * n + k];
const Real inv_pivot = 1.0 / pivot;
for (int i = k + 1; i < n; ++i) {
const Real m = A[i * n + k] * inv_pivot;
A[i * n + k] = 0.0;
for (int j = k + 1; j < n; ++j) A[i * n + j] -= m * A[k * n + j];
x[i] -= m * x[k];
}
}
if (std::abs(A[(n - 1) * n + (n - 1)]) < 1e-30) return false;
for (int i = n - 1; i >= 0; --i) {
Real sum = 0.0;
for (int j = i + 1; j < n; ++j) sum += A[i * n + j] * x[j];
x[i] = (x[i] - sum) / A[i * n + i];
}
return true;
}
// Solve min ||A x - b||_2 for a tall (rows >= cols) matrix A using Householder QR.
// A_in is row-major of size rows*cols. b_in length rows.
// Returns false if the problem is rank-deficient / numerically singular.
static bool qr_solve_least_squares(int rows, int cols,
const std::vector<Real>& A_in,
const std::vector<Real>& b_in,
std::vector<Real>& x_out)
{
if (rows < cols) return false;
if ((int)A_in.size() != rows * cols) return false;
if ((int)b_in.size() != rows) return false;
std::vector<Real> A = A_in; // working copy (row-major)
std::vector<Real> b = b_in; // will become Q^T b
std::vector<Real> v; // Householder vector (reused)
v.reserve((size_t)rows);
for (int k = 0; k < cols; ++k) {
// Compute 2-norm of column k from row k..rows-1
Real sigma = 0.0;
for (int i = k; i < rows; ++i) {
const Real a = A[(size_t)i * (size_t)cols + (size_t)k];
sigma += a * a;
}
if (sigma <= 0.0) continue;
const Real x0 = A[(size_t)k * (size_t)cols + (size_t)k];
const Real normx = std::sqrt(sigma);
// alpha = -sign(x0) * ||x||
const Real alpha = -std::copysign(normx, x0);
// v = x; v0 = x0 - alpha
v.assign((size_t)(rows - k), 0.0);
v[0] = x0 - alpha;
for (int i = k + 1; i < rows; ++i) {
v[(size_t)(i - k)] = A[(size_t)i * (size_t)cols + (size_t)k];
}
// tau = 2 / (v^T v)
Real vTv = 0.0;
for (Real vi : v) vTv += vi * vi;
if (vTv <= 0.0) continue;
const Real tau = 2.0 / vTv;
// Apply to A columns k..cols-1
for (int j = k; j < cols; ++j) {
Real dot_v = 0.0;
for (int i = 0; i < rows - k; ++i) {
dot_v += v[(size_t)i] * A[(size_t)(k + i) * (size_t)cols + (size_t)j];
}
const Real s = tau * dot_v;
for (int i = 0; i < rows - k; ++i) {
A[(size_t)(k + i) * (size_t)cols + (size_t)j] -= s * v[(size_t)i];
}
}
// Apply to b
Real dot_b = 0.0;
for (int i = 0; i < rows - k; ++i) {
dot_b += v[(size_t)i] * b[(size_t)(k + i)];
}
const Real sb = tau * dot_b;
for (int i = 0; i < rows - k; ++i) {
b[(size_t)(k + i)] -= sb * v[(size_t)i];
}
// Explicitly set below-diagonal entries to zero (numerical hygiene)
A[(size_t)k * (size_t)cols + (size_t)k] = alpha;
for (int i = k + 1; i < rows; ++i) {
A[(size_t)i * (size_t)cols + (size_t)k] = 0.0;
}
}
// Back-substitution on R (upper triangle in A)
x_out.assign((size_t)cols, 0.0);
for (int i = cols - 1; i >= 0; --i) {
const Real rii = A[(size_t)i * (size_t)cols + (size_t)i];
if (std::abs(rii) < 1e-30) return false;
Real sum = 0.0;
for (int j = i + 1; j < cols; ++j) {
sum += A[(size_t)i * (size_t)cols + (size_t)j] * x_out[(size_t)j];
}
x_out[(size_t)i] = (b[(size_t)i] - sum) / rii;
}
return true;
}
// Convenience: compute y = J * x for row-major J (m x n).
static inline void mat_vec_mul(int rows, int cols,
const std::vector<Real>& J,
const std::vector<Real>& x,
std::vector<Real>& y)
{
y.assign((size_t)rows, 0.0);
for (int i = 0; i < rows; ++i) {
Real s = 0.0;
const size_t off = (size_t)i * (size_t)cols;
for (int j = 0; j < cols; ++j) s += J[off + (size_t)j] * x[(size_t)j];
y[(size_t)i] = s;
}
}
// ------------------------------------------------------------------------------
// Symmetric eigen-decomposition (Jacobi rotations)
// ------------------------------------------------------------------------------
// Implemented dependency-free to support SciPy-parity TRF(tr_solver='exact')
// steps. For our dense n~100 systems, Jacobi is sufficiently robust.
//
// Input:
// A_in : symmetric matrix (n x n) in row-major.
// Output:
// w : eigenvalues (n)
// V : eigenvectors (n x n) in row-major, columns are eigenvectors.
//
// Notes:
// - Cyclic Jacobi with thresholding.
// - Eigenvalues are NOT sorted.
// ------------------------------------------------------------------------------
static bool jacobi_eigen_sym(const std::vector<Real>& A_in, int n,
std::vector<Real>& w,
std::vector<Real>& V,
int max_sweeps = 60)
{
if ((int)A_in.size() != n * n) return false;
std::vector<Real> A = A_in;
w.assign((size_t)n, 0.0);
V.assign((size_t)n * (size_t)n, 0.0);
for (int i = 0; i < n; ++i) V[(size_t)i * (size_t)n + (size_t)i] = 1.0;
auto a = [&](int r, int c) -> Real& { return A[(size_t)r * (size_t)n + (size_t)c]; };
auto v = [&](int r, int c) -> Real& { return V[(size_t)r * (size_t)n + (size_t)c]; };
const Real eps = std::numeric_limits<Real>::epsilon();
for (int sweep = 0; sweep < max_sweeps; ++sweep) {
Real off = 0.0;
for (int p = 0; p < n; ++p) {
for (int q = p + 1; q < n; ++q) off += std::abs(a(p, q));
}
if (off <= eps) break;
for (int p = 0; p < n; ++p) {
for (int q = p + 1; q < n; ++q) {
const Real apq = a(p, q);
if (std::abs(apq) <= eps) continue;
const Real app = a(p, p);
const Real aqq = a(q, q);
const Real tau = (aqq - app) / (2.0 * apq);
const Real t = std::copysign((Real)1.0, tau) /
(std::abs(tau) + std::sqrt((Real)1.0 + tau * tau));
const Real c = 1.0 / std::sqrt(1.0 + t * t);
const Real s = t * c;
a(p, q) = 0.0;
a(q, p) = 0.0;
a(p, p) = app - t * apq;
a(q, q) = aqq + t * apq;
for (int k = 0; k < n; ++k) {
if (k == p || k == q) continue;
const Real aik = a(p, k);
const Real aqk = a(q, k);
a(p, k) = c * aik - s * aqk;
a(k, p) = a(p, k);
a(q, k) = s * aik + c * aqk;
a(k, q) = a(q, k);
}
for (int k = 0; k < n; ++k) {
const Real vip = v(k, p);
const Real viq = v(k, q);
v(k, p) = c * vip - s * viq;
v(k, q) = s * vip + c * viq;
}
}
}
}
for (int i = 0; i < n; ++i) w[(size_t)i] = A[(size_t)i * (size_t)n + (size_t)i];
return true;
}
static void jt_j(int m, int n, const std::vector<Real>& J, std::vector<Real>& A) {
A.assign((size_t)n * (size_t)n, 0.0);
for (int i = 0; i < m; ++i) {
const size_t row = (size_t)i * (size_t)n;
for (int a = 0; a < n; ++a) {
const Real Jia = J[row + (size_t)a];
if (Jia == 0.0) continue;
for (int b = a; b < n; ++b) {
A[(size_t)a * (size_t)n + (size_t)b] += Jia * J[row + (size_t)b];
}
}
}
for (int a = 0; a < n; ++a) {
for (int b = a + 1; b < n; ++b) {
A[(size_t)b * (size_t)n + (size_t)a] = A[(size_t)a * (size_t)n + (size_t)b];
}
}
}
static bool svd_via_jtj(int m, int n,
const std::vector<Real>& J,
std::vector<Real>& s,
std::vector<Real>& V)
{
std::vector<Real> A;
jt_j(m, n, J, A);
std::vector<Real> w;
if (!jacobi_eigen_sym(A, n, w, V, 60)) return false;
for (Real& ev : w) {
if (ev < 0.0 && ev > (Real)-1e-14) ev = 0.0;
}
std::vector<int> idx((size_t)n);
for (int i = 0; i < n; ++i) idx[(size_t)i] = i;
std::sort(idx.begin(), idx.end(), [&](int a, int b) { return w[(size_t)a] > w[(size_t)b]; });
std::vector<Real> V_sorted((size_t)n * (size_t)n, 0.0);
s.assign((size_t)n, 0.0);
for (int col = 0; col < n; ++col) {
const int src = idx[(size_t)col];
const Real ev = std::max((Real)0.0, w[(size_t)src]);
s[(size_t)col] = std::sqrt(ev);
for (int r = 0; r < n; ++r) {
V_sorted[(size_t)r * (size_t)n + (size_t)col] = V[(size_t)r * (size_t)n + (size_t)src];
}
}
V.swap(V_sorted);
return true;
}
// --------------------------------------------------------------------------------------
// One-sided Jacobi SVD for tall/skinny dense matrices (m >= n).
//
// Why this exists:
// SciPy's TRF('exact') path performs an SVD of J_h directly (LAPACK), which is
// numerically more stable than forming J^T J (squares the condition number).
// The earlier C++ parity implementation used eigen(J^T J) for convenience.
// That is usually fine, but if you want to be extreme about accuracy
// (especially near-breaking regimes, strong nonlinearity, or ill-conditioned
// Jacobians), one-sided Jacobi SVD is a better match to SciPy's intent.
//
// Algorithm:
// We orthogonalize the columns of A = J in-place by applying Jacobi rotations
// to column pairs (p, q) until off-diagonal correlations are negligible.
// Accumulated rotations are stored in V (right singular vectors). At the end,
// the singular values are the column norms of the orthogonalized matrix.
//
// Notes:
// - We do NOT explicitly construct U.
// - TRF only needs (s, V) and uf = U^T f. We compute uf via
// uf = diag(1/s) * V^T * (J^T f)
// which remains valid for this decomposition.
// - Output singular values are sorted descending, with V columns permuted.
// --------------------------------------------------------------------------------------
static bool svd_jacobi_onesided(int m, int n,
const std::vector<Real>& J,
std::vector<Real>& s,
std::vector<Real>& V)
{
if (m < n || m <= 0 || n <= 0) return false;
// Working copy of J (A in the algorithm).
std::vector<Real> A = J; // row-major (m x n)
// V starts as identity.
V.assign((size_t)n * (size_t)n, 0.0);
for (int i = 0; i < n; ++i) V[(size_t)i * (size_t)n + (size_t)i] = 1.0;
auto col_dot = [&](int p, int q) -> Real {
Real sum = 0.0;
// Deterministic accumulation order; use compensated summation to reduce
// round-off when m is large or columns are nearly parallel.
Real c = 0.0;
for (int i = 0; i < m; ++i) {
const Real prod = A[(size_t)i * (size_t)n + (size_t)p] * A[(size_t)i * (size_t)n + (size_t)q];
const Real y = prod - c;
const Real t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
};
auto col_norm2 = [&](int p) -> Real {
Real sum = 0.0;
Real c = 0.0;
for (int i = 0; i < m; ++i) {
const Real v = A[(size_t)i * (size_t)n + (size_t)p];
const Real prod = v * v;
const Real y = prod - c;
const Real t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
};
// Tolerance consistent with Jacobi sweeps.
const Real eps = std::sqrt(std::numeric_limits<Real>::epsilon());
// Sweeps: for n~104, 20-30 sweeps is more than enough for near-orthogonality.
const int max_sweeps = 30;
for (int sweep = 0; sweep < max_sweeps; ++sweep) {
Real max_corr = 0.0;
for (int p = 0; p < n; ++p) {
const Real app = col_norm2(p);
if (app <= 0.0) continue;
for (int q = p + 1; q < n; ++q) {
const Real aqq = col_norm2(q);
if (aqq <= 0.0) continue;
const Real apq = col_dot(p, q);
const Real denom = std::sqrt(app * aqq);
if (denom <= 0.0) continue;
const Real corr = std::abs(apq) / denom;
if (corr > max_corr) max_corr = corr;
// If columns are nearly orthogonal, skip.
if (corr < 10.0 * eps) continue;
// Compute Jacobi rotation for columns p, q.
const Real tau = (aqq - app) / (2.0 * apq);
const Real t = std::copysign((Real)1.0, tau) /
(std::abs(tau) + std::sqrt((Real)1.0 + tau * tau));
const Real c_rot = 1.0 / std::sqrt(1.0 + t * t);
const Real s_rot = t * c_rot;
// Rotate columns of A.
for (int i = 0; i < m; ++i) {
const size_t off = (size_t)i * (size_t)n;
const Real aip = A[off + (size_t)p];
const Real aiq = A[off + (size_t)q];
A[off + (size_t)p] = c_rot * aip - s_rot * aiq;
A[off + (size_t)q] = s_rot * aip + c_rot * aiq;
}
// Accumulate rotation into V.
for (int i = 0; i < n; ++i) {
const size_t off = (size_t)i * (size_t)n;
const Real vip = V[off + (size_t)p];
const Real viq = V[off + (size_t)q];
V[off + (size_t)p] = c_rot * vip - s_rot * viq;
V[off + (size_t)q] = s_rot * vip + c_rot * viq;
}
}
}
// Stop early if correlations are negligible.
if (max_corr < 10.0 * eps) break;
}
// Singular values are norms of orthogonalized columns.
s.assign((size_t)n, 0.0);
for (int j = 0; j < n; ++j) {
const Real n2 = col_norm2(j);
s[(size_t)j] = std::sqrt(std::max((Real)0.0, n2));
}
// Sort descending singular values (like LAPACK/SciPy).
std::vector<int> idx((size_t)n);
for (int i = 0; i < n; ++i) idx[(size_t)i] = i;
std::sort(idx.begin(), idx.end(), [&](int a, int b) { return s[(size_t)a] > s[(size_t)b]; });
std::vector<Real> V_sorted((size_t)n * (size_t)n, 0.0);
std::vector<Real> s_sorted((size_t)n, 0.0);
for (int col = 0; col < n; ++col) {
const int src = idx[(size_t)col];
s_sorted[(size_t)col] = s[(size_t)src];
for (int r = 0; r < n; ++r) {
V_sorted[(size_t)r * (size_t)n + (size_t)col] = V[(size_t)r * (size_t)n + (size_t)src];
}
}
V.swap(V_sorted);
s.swap(s_sorted);
return true;
}
} // namespace LinAlg
// ==============================================================================
// FENTON STREAM FUNCTION SOLVER (Matches Python formulation)
// ==============================================================================
class FentonStreamFunction {
public:
// ----------------------------- inputs -----------------------------------
Real H_target; // [m]
Real T_target; // [s]
Real d; // [m]
Real Uc; // [m/s] (Eulerian / lab-frame)
Real g; // [m/s^2]
int N; // Fourier order (N=50)
// ------------------------- solver controls ------------------------------
int nstep; // continuation steps in wave height
int number; // max Newton iterations per step
Real crit; // intermediate-step convergence factor
Real criter_final; // final-step convergence factor
// Current criterion (1=Eulerian, 2=Stokes). GUI uses Eulerian current.
int Current_criterion;
// Derived nondimensional inputs (C++ Read_data equivalents)
Real MaxH; // H/d
Real T_nd; // T * sqrt(g/d)
Real Height; // (H/d) / (T_nd^2) = H/(g T^2)
Real Current; // Uc / sqrt(g d)
// ----------------------------- outputs ----------------------------------
Real k; // [rad/m]
Real L; // [m]
Real c; // [m/s]
std::vector<Real> eta_nodes; // size (N+1), absolute z from bed [m]
std::vector<Real> Bj; // size (N), B_1..B_N (depth scaling)
Real eta_crest; // [m] relative to SWL
Real eta_trough; // [m] relative to SWL
Real steepness;
Real rel_depth;
Real ursell;
std::string regime;
Real breaking_limit_miche;
Real breaking_index;
bool is_breaking;
// Integral properties (dimensional)
Real EulerianCurrent;
Real StokesCurrent;
Real MeanFluidSpeed;
Real WaveVolumeFlux_q;
Real VolumeFluxQ;
Real BernoulliR;
Real Bernoulli_r;
Real KineticEnergy;
Real PotentialEnergy;
Real EnergyDensity;
Real MomentumFlux;
Real MomentumFluxDepth;
Real Sxx;
Real Sxx_depth;
Real Impulse;
Real I_depth;
Real Power;
Real F_depth;
Real Cg;
// Additional invariants (depth-scaled; used in Solution-Flat reporting)
Real E_depth;
Real KE_depth;
Real PE_depth;
// Mean Stokes / mass-transport current (dimensional)
Real MassTransport;
// Bed orbital statistics / kinematics
Real MeanSquareBedVelocity; // ub^2 [m^2/s^2]
Real u_bed;
Real u_surf;
Real acc_max;
Real w_max;
Real asymmetry;
// Convenience (not printed in the report header but computed like Python)
Real tau_bed;
Real ExcursionBed;
bool converged;
std::string last_error;
// -------------------------- construction --------------------------------
explicit FentonStreamFunction(Real H, Real T, Real depth, Real current = 0.0)
: H_target(H), T_target(T), d(depth), Uc(current),
g(Phys::G_STD), N(50),
nstep(4), number(40), crit(1e-8), criter_final(1e-10),
Current_criterion(1),
MaxH(0.0), T_nd(0.0), Height(0.0), Current(0.0),
k(0.0), L(0.0), c(0.0),
eta_nodes((size_t)50 + 1, depth),
Bj((size_t)50, 0.0),
eta_crest(0.0), eta_trough(0.0),
steepness(0.0), rel_depth(0.0), ursell(0.0), regime(""),
breaking_limit_miche(0.0), breaking_index(0.0), is_breaking(false),
EulerianCurrent(0.0), StokesCurrent(0.0), MeanFluidSpeed(0.0),
WaveVolumeFlux_q(0.0), VolumeFluxQ(0.0),
BernoulliR(0.0), Bernoulli_r(0.0),
KineticEnergy(0.0), PotentialEnergy(0.0), EnergyDensity(0.0),
MomentumFlux(0.0), MomentumFluxDepth(0.0),
Sxx(0.0), Sxx_depth(0.0),
Impulse(0.0), I_depth(0.0),
Power(0.0), F_depth(0.0),
Cg(0.0),
MeanSquareBedVelocity(0.0),
u_bed(0.0), u_surf(0.0), acc_max(0.0), w_max(0.0), asymmetry(0.0),
tau_bed(0.0), ExcursionBed(0.0),
converged(false), last_error("")
{