Repository navigation
Expand file tree
/
Copy pathstreamvorti.cpp
More file actions
1983 lines (1736 loc) · 86.3 KB
/
Copy pathstreamvorti.cpp
File metadata and controls
1983 lines (1736 loc) · 86.3 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
/*
* StreamVorti - Software for solving PDEs using explicit methods.
* Copyright (C) 2017 Konstantinos A. Mountris
* Copyright (C) 2020-2026 Benjamin F. Zwick
* Copyright (C) 2025 Weizheng Li
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* George C. BOURANTAS
* Konstantinos A. MOUNTRIS
* Benjamin F. ZWICK
* Weizheng(Will) LI
*/
// Demo usage: (save everything)
// ./StreamVorti -dim 2 -sx 1 -sy 1 -nx 40 -ny 40 -nn 25 -Re 1000 -sm -sn -sd -sdd -ss -pv -cr
//
// SDL usage (requires ECL):
// ./StreamVorti -f demo/cavity.lisp -pv
// Related header
#include <StreamVorti/streamvorti.hpp>
// SDL/Lisp support (conditional)
#ifdef STREAMVORTI_WITH_ECL
#include <StreamVorti/lisp/ecl_runtime.hpp>
#include <StreamVorti/lisp/lisp_loader.hpp>
#endif
// C++ standard library headers (alphabetically sorted)
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
// Other libraries' headers
#include "mfem.hpp"
// Conditional includes
#ifdef _OPENMP
#include <omp.h>
#endif
// ============================================================================
// FUNCTION IMPLEMENTATIONS
// ============================================================================
// All struct definitions and function declarations have been moved to
// include/StreamVorti/stream_vorti.hpp for proper header/implementation split.
// ============================================================================
// MAIN FUNCTION
// ============================================================================
/**
* @brief Main driver for 2D lid-driven cavity flow solver
*
* Solves incompressible Navier-Stokes equations using stream function-vorticity
* formulation with Meshless Point Collocation (MPC) and DC PSE operators.
*
* Algorithm (from Bourantas et al. 2019):
* 1. Compute DC PSE derivative operators (pre-processing)
* 2. Time-stepping loop:
* a) Update vorticity: explicit Euler for transport equation
* b) Solve streamfunction: ∇²ψ = -ω (Poisson equation)
* c) Apply boundary conditions for lid-driven cavity
* d) Check steady-state convergence
* e) Output solutions (DAT files, ParaView)
*
* @param argc Number of command-line arguments
* @param argv Command-line argument values
* @return EXIT_SUCCESS on success, EXIT_FAILURE on error
*/
int main(int argc, char *argv[])
{
// Options
const char *mesh_file = "";
const char *sdl_file = ""; // SDL file for Lisp-based configuration
const char *lisp_path = ""; // Path to SDL Lisp source files
int order = 1;
const char *method = "dcpse"; // Spatial discretization method: "dcpse" or "fdm"
// Output filename prefix and extension
std::string fname = "mfem_square10x10";
std::string fext = ".dat";
// Mesh generation
int dim = 2;
int nx = 20;
int ny = 20;
int nz = 0;
double sx = 1.0;
double sy = 1.0;
double sz = 1.0;
// Output requests
bool save_mesh = false;
bool save_neighbors = false;
bool save_d = false; // all 1st derivatives (gradient)
bool save_dd = false; // all 2nd derivatives (Hessian)
bool save_solutions = false;
bool paraview_output = false;
std::string paraview_filename = fname;
std::string paraview_prefix_path = "ParaView";
// Simulation parameters
SimulationParams params;
// Performance Metrics parameters
PerformanceMetrics perf_metrics;
// Parse command-line options
mfem::OptionsParser args(argc, argv);
#ifdef STREAMVORTI_WITH_ECL
args.AddOption(&sdl_file, "-f", "--sdl-file",
"SDL (Simulation Definition Language) file to load.");
args.AddOption(&lisp_path, "-lp", "--lisp-path",
"Path to SDL Lisp source files.");
#endif
// Simulation options
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree).");
args.AddOption(&dim, "-dim", "--dimension",
"Dimension of mesh (applies to generated mesh only).");
args.AddOption(&nx, "-nx", "--num-x-divisions",
"Number of x divisions.");
args.AddOption(&ny, "-ny", "--num-y-divisions",
"Number of y divisions.");
args.AddOption(&nz, "-nz", "--num-z-divisions",
"Number of z divisions.");
args.AddOption(&sx, "-sx", "--size-x",
"Mesh size in x direction.");
args.AddOption(&sy, "-sy", "--size-y",
"Mesh size in y direction.");
args.AddOption(&sz, "-sz", "--size-z",
"Mesh size in z direction.");
args.AddOption(&method, "-method", "--spatial-method",
"Spatial discretization method: dcpse or fdm (default: dcpse).");
args.AddOption(¶ms.num_neighbors, "-nn", "--num-neighbors",
"Number of neighbors for DCPSE (default: 25).");
args.AddOption(¶ms.reynolds_number, "-Re", "--reynolds-number",
"Reynolds number of simulating fluid (default: 1000).");
args.AddOption(¶ms.dt, "-dt", "--timestep",
"Time step size (default: 1e-4).");
args.AddOption(¶ms.final_time, "-ft", "--final-time",
"Final simulation time (default: 60000).");
// Output options
args.AddOption(&save_mesh,
"-sm", "--save-mesh", "-no-sm", "--no-save-mesh",
"Save mesh to file.");
args.AddOption(&save_neighbors,
"-sn", "--save-neighbors", "-no-sn", "--no-save-neighbors",
"Save neighbors to file.");
args.AddOption(&save_d,
"-sd", "--save-1st-derivative", "-no-sd", "--no-save-1st-derivative",
"Save 1st derivatives to file.");
args.AddOption(&save_dd,
"-sdd", "--save-2nd-derivative", "-no-sdd", "--no-save-2nd-derivative",
"Save 2nd derivatives to file.");
args.AddOption(&save_solutions,
"-ss", "--save-solutions", "-no-ss", "--no-save-solutions",
"Save simuation solutions to file.");
args.AddOption(¶view_output, "-pv", "--paraview", "-no-pv", "--no-paraview",
"Enable or disable ParaView output.");
args.AddOption(¶ms.paraview_output_frequency, "-pvf", "--paraview-freq",
"Frequency of ParaView output (in timesteps).");
// Timesteping options
args.AddOption(¶ms.gershgorin_frequency, "-gf", "--gershgorin-freq",
"Frequency of Gershgorin timestep checks (default: 1000).");
args.AddOption(¶ms.enable_adaptive_timestep,
"-adaptive", "--adaptive-timestep", "-no-adaptive", "--no-adaptive-timestep",
"Enable or disable adaptive timestepping based on Gershgorin criterion.");
args.AddOption(¶ms.gershgorin_safety_factor, "-gsf", "--gershgorin-safety",
"Safety factor for Gershgorin timestep (default: 5.0).");
// Solver options
args.AddOption(¶ms.solver_type, "-solver", "--linear-solver",
"Linear solver: umfpack, cg, gmres, minres, bicgstab, hypre (if available)");
args.AddOption(¶ms.symmetrize_laplacian, "-sym", "--symmetrize",
"-no-sym", "--no-symmetrize",
"Symmetrize DCPSE Laplacian: L=(L+L^T)/2 (required for CG/PCG solvers).");
args.AddOption(¶ms.solver_print_level, "-spl", "--solver-print-level",
"Solver print level (0=quiet, 1=summary, 2=verbose).");
args.AddOption(¶ms.solver_max_iter, "-smi", "--solver-max-iter",
"Maximum iterations for iterative solvers.");
args.AddOption(¶ms.solver_rel_tol, "-srt", "--solver-rel-tol",
"Relative tolerance for iterative solvers.");
// Residual monitoring options
args.AddOption(¶ms.check_residuals,
"-cr", "--check-residuals", "-no-cr", "--no-check-residuals",
"Enable or disable residual monitoring and logging.");
args.AddOption(¶ms.residual_check_freq, "-rcf", "--residual-check-freq",
"Frequency of residual checks (default: 100).");
args.Parse();
if (!args.Good()) {
args.PrintUsage(std::cout);
return 1;
}
args.PrintOptions(std::cout);
// Mesh pointer - will be set by SDL mode or traditional mode
mfem::Mesh* mesh = nullptr;
#ifdef STREAMVORTI_WITH_ECL
bool sdl_mode = false;
// Store SDL boundary conditions for runtime evaluation
std::vector<StreamVorti::Lisp::BoundaryCondition> sdl_boundaries;
std::vector<StreamVorti::Lisp::LineProbe> sdl_probes;
bool use_sdl_bcs = false;
#endif
#ifdef STREAMVORTI_WITH_ECL
// ===== SDL Mode =====
// If an SDL file is specified, use the Lisp-based configuration
if (sdl_file[0] != '\0')
{
sdl_mode = true;
std::cout << "\n" << std::string(70, '=') << std::endl;
std::cout << "SDL MODE - Loading simulation from: " << sdl_file << std::endl;
std::cout << std::string(70, '=') << "\n" << std::endl;
try {
// Initialize ECL runtime
std::string lpath = lisp_path[0] != '\0' ? lisp_path : "lisp";
StreamVorti::Lisp::Runtime::init(lpath);
// Load simulation from SDL file
auto config = StreamVorti::Lisp::Loader::load(sdl_file);
std::cout << "Loaded simulation: " << config.name << std::endl;
std::cout << " Dimension: " << config.dimension << std::endl;
std::cout << " Mesh vertices: " << config.mesh->GetNV() << std::endl;
std::cout << " Mesh elements: " << config.mesh->GetNE() << std::endl;
std::cout << " Boundaries defined: " << config.boundaries.size() << std::endl;
// Store SDL boundary conditions for runtime evaluation
if (!config.boundaries.empty()) {
sdl_boundaries = std::move(config.boundaries);
use_sdl_bcs = true;
std::cout << " Using SDL boundary conditions (" << sdl_boundaries.size() << " regions):\n";
for (const auto& bc : sdl_boundaries) {
std::cout << " - " << bc.name << " (attr=" << bc.attribute
<< ", type=" << bc.type;
if (bc.u_function) std::cout << ", u-func";
if (bc.v_function) std::cout << ", v-func";
if (bc.function && !bc.u_function) std::cout << ", scalar-func";
std::cout << ")\n";
}
} else {
std::cout << " No SDL boundary conditions defined, using hardcoded lid-driven cavity BCs.\n";
}
// Store SDL line probes for post-processing
if (!config.probes.empty()) {
sdl_probes = std::move(config.probes);
std::cout << " Line probes (" << sdl_probes.size() << "):\n";
for (const auto& p : sdl_probes) {
std::cout << " - " << p.name << " (" << p.axis << " = " << p.position << ")\n";
}
}
// Map spatial method from SDL
if (!config.dcpse.method.empty()) {
method = config.dcpse.method == "fdm" ? "fdm" : "dcpse";
}
// Map SDL config to SimulationParams
params.num_neighbors = config.dcpse.num_neighbors;
params.reynolds_number = static_cast<int>(config.physics.reynolds);
params.dt = config.solver.dt;
params.final_time = config.solver.end_time;
params.output_prefix = config.name;
// Map solver tolerance and iterations
params.solver_rel_tol = config.solver.tolerance;
params.solver_max_iter = config.solver.max_iterations;
// Map output settings
if (config.output.format == "vtk") {
paraview_output = true;
}
if (!config.output.directory.empty()) {
paraview_prefix_path = config.output.directory;
}
// Map output interval to paraview frequency (convert time to steps)
if (config.output.interval > 0 && params.dt > 0) {
params.paraview_output_frequency = static_cast<int>(config.output.interval / params.dt);
}
std::cout << "\nMapped SDL parameters:" << std::endl;
std::cout << " Reynolds number: " << params.reynolds_number << std::endl;
std::cout << " Timestep: " << params.dt << std::endl;
std::cout << " Final time: " << params.final_time << std::endl;
std::cout << " Spatial method: " << method << std::endl;
std::cout << " DCPSE neighbors: " << params.num_neighbors << std::endl;
std::cout << " Solver tolerance: " << params.solver_rel_tol << std::endl;
std::cout << " ParaView output frequency: " << params.paraview_output_frequency << std::endl;
// Get mesh dimensions from SDL config (for grid_size reporting)
// Note: GetNV() = (nx+1)*(ny+1) for a structured mesh, so sqrt gives nx+1
int nv = config.mesh->GetNV();
nx = ny = static_cast<int>(std::sqrt(static_cast<double>(nv))) - 1;
dim = config.dimension;
// Transfer ownership of mesh
mesh = config.mesh.release();
std::cout << "\nContinuing with SDL-configured simulation...\n" << std::endl;
} catch (const StreamVorti::Lisp::EclException& e) {
std::cerr << "ECL Error: " << e.what() << std::endl;
StreamVorti::Lisp::Runtime::shutdown();
return EXIT_FAILURE;
} catch (const std::exception& e) {
std::cerr << "Error loading SDL file: " << e.what() << std::endl;
StreamVorti::Lisp::Runtime::shutdown();
return EXIT_FAILURE;
}
}
#endif // STREAMVORTI_WITH_ECL
// Create or load mesh (traditional mode - only if not in SDL mode)
if (mesh == nullptr) {
mesh = CreateOrLoadMesh(mesh_file, dim, nx, ny, nz, sx, sy, sz, save_mesh);
}
perf_metrics.grid_size = nx;
// dat files for Matlab
std::string dat_dir = "output_dat";
std::filesystem::create_directories(dat_dir);
std::cout << "Created DAT output directory: " << dat_dir << std::endl;
// Save mesh if requested
if (save_mesh) {
// Save mesh as MFEM format
std::ofstream mesh_ofs(fname+".mesh");
mesh_ofs.precision(8);
mesh->Print(mesh_ofs);
}
// Set up finite element space
dim = mesh->Dimension();
mfem::H1_FECollection fec(order, dim);
mfem::FiniteElementSpace fes(mesh, &fec, 1);
std::cout << "main: Number of finite element unknowns: " << fes.GetTrueVSize() << std::endl;
mfem::GridFunction gf(&fes); // as 'x' in ex1.cpp
// ================== Timing PHASE 1: DERIVATIVE COMPUTATION ==================
mfem::StopWatch deriv_timer;
deriv_timer.Start();
// Validate and determine spatial method
std::string spatial_method(method);
if (spatial_method != "dcpse" && spatial_method != "fdm") {
MFEM_ABORT("Unknown spatial method: '" << spatial_method
<< "'. Supported methods: dcpse, fdm.");
}
std::cout << "Phase 1 - Spatial method: " << spatial_method << std::endl;
StreamVorti::DerivativeOperator* deriv_op = nullptr;
if (spatial_method == "fdm") {
StreamVorti::FiniteDiff* fd = nullptr;
if (dim == 2) {
fd = new StreamVorti::FiniteDiff2d(gf);
} else if (dim == 3) {
fd = new StreamVorti::FiniteDiff3d(gf);
} else {
MFEM_ABORT("Unsupported dimension for FDM: " << dim);
}
fd->Update();
deriv_op = fd;
} else {
deriv_op = InitialiseDCPSE(gf, dim, params.num_neighbors);
}
deriv_timer.Stop();
perf_metrics.derivative_time = deriv_timer.RealTime();
std::cout << "Phase 1 - Derivatives computation: " << perf_metrics.derivative_time << " s" << std::endl;
// Save derivative matrices if requested
if (save_d || save_dd) {
if (auto* dcpse = dynamic_cast<StreamVorti::Dcpse*>(deriv_op)) {
SaveDerivativeMatrices(dcpse, params, dim, save_d, save_dd, dat_dir);
}
}
// Save neighbors if requested (DCPSE only — FD has no neighbor concept)
if (save_neighbors) {
if (auto* dcpse = dynamic_cast<StreamVorti::Dcpse*>(deriv_op)) {
std::cout << "main: Save neighbor indices to file... " << std::endl;
dcpse->SaveNeighsToFile(dcpse->NeighborIndices(), dat_dir + "/" + params.output_prefix + ".neighbors" + params.output_extension);
std::cout << "done." << std::endl;
}
}
// ================================================================
// PART 1: INITIALIZATION
// ================================================================
const int num_nodes = mesh->GetNV();
if (dim != 2) {
MFEM_ABORT("Setup: Only 2D simulations are currently supported.");
}
// Get derivative matrices via the common interface
const mfem::SparseMatrix& dx_matrix = deriv_op->Dx();
const mfem::SparseMatrix& dy_matrix = deriv_op->Dy();
const mfem::SparseMatrix& dxx_matrix = deriv_op->Dxx();
const mfem::SparseMatrix& dyy_matrix = deriv_op->Dyy();
std::cout << "Setup: Retrieved derivative matrices successfully." << std::endl;
// Print ASCII sparsity patterns of derivative matrices
PrintSparsityPattern(dx_matrix, "Dx (d/dx) - Full View");
PrintSparsityPattern(dx_matrix, "Dx (d/dx) - Top-Left 10x10",
72, 24, 10, 10);
PrintSparsityPattern(dxx_matrix, "Dxx (d²/dx²) - Full View");
PrintSparsityPattern(dxx_matrix, "Dxx (d²/dx²) - Top-Left 10x10",
72, 24, 10, 10);
// Identify boundary and interior nodes
std::vector<int> bottom_nodes, right_nodes, top_nodes, left_nodes, interior_nodes;
IdentifyBoundaryNodes(mesh, bottom_nodes, right_nodes, top_nodes, left_nodes, interior_nodes);
// Also identify boundary nodes by MFEM boundary attributes (for SDL BC integration)
std::map<int, std::vector<int>> boundary_nodes_by_attr;
std::vector<int> interior_nodes_by_attr;
IdentifyBoundaryNodesByAttribute(mesh, boundary_nodes_by_attr, interior_nodes_by_attr);
#ifdef STREAMVORTI_WITH_ECL
// For SDL mode, use attribute-based interior nodes (correct for any geometry).
// The hardcoded IdentifyBoundaryNodes only works for unit-square cavity.
if (use_sdl_bcs) {
interior_nodes = interior_nodes_by_attr;
}
#endif
// ================================================================
// COMPUTE PER-NODE OUTWARD NORMALS FROM MESH GEOMETRY
// ================================================================
// Uses MFEM's GetBdrFaceTransformations() + CalcOrtho() to compute
// proper outward unit normals at each boundary node. Normals are
// averaged at nodes shared by multiple boundary elements.
// Used for Neumann BCs (∂ψ/∂n = nx·∂ψ/∂x + ny·∂ψ/∂y = 0) and
// velocity BCs (ψ integration along boundary tangent).
std::map<int, mfem::Vector> node_normals; // node_id → (nx, ny)
{
int sdim = mesh->SpaceDimension();
for (int be = 0; be < mesh->GetNBE(); ++be) {
auto *FTr = mesh->GetBdrFaceTransformations(be);
if (!FTr) continue;
// Evaluate normal at the midpoint of the boundary element
const mfem::IntegrationRule &ir =
mfem::IntRules.Get(FTr->GetGeometryType(), 1);
const mfem::IntegrationPoint &ip = ir.IntPoint(0);
FTr->SetAllIntPoints(&ip);
// CalcOrtho gives outward normal (scaled by element weight)
mfem::Vector nor(sdim);
mfem::CalcOrtho(FTr->Jacobian(), nor);
double len = nor.Norml2();
if (len > 1e-15) nor /= len; // unit normal
// Accumulate at each vertex of the boundary element
mfem::Array<int> verts;
mesh->GetBdrElementVertices(be, verts);
for (int j = 0; j < verts.Size(); ++j) {
if (node_normals.find(verts[j]) == node_normals.end()) {
node_normals[verts[j]].SetSize(sdim);
node_normals[verts[j]] = 0.0;
}
node_normals[verts[j]] += nor;
}
}
// Normalize averaged normals
for (auto& [node, n] : node_normals) {
double len = n.Norml2();
if (len > 1e-15) n /= len;
}
}
// Combine all boundary nodes for streamfunction boundary conditions.
// For SDL mode, use attribute-based nodes (includes all boundaries).
// For CLI mode, use hardcoded cavity boundary nodes.
std::vector<int> all_boundary_nodes;
#ifdef STREAMVORTI_WITH_ECL
if (use_sdl_bcs) {
std::set<int> bnd_set;
for (const auto& [attr, nodes] : boundary_nodes_by_attr) {
bnd_set.insert(nodes.begin(), nodes.end());
}
all_boundary_nodes.assign(bnd_set.begin(), bnd_set.end());
} else
#endif
{
all_boundary_nodes.insert(all_boundary_nodes.end(), bottom_nodes.begin(), bottom_nodes.end());
all_boundary_nodes.insert(all_boundary_nodes.end(), right_nodes.begin(), right_nodes.end());
all_boundary_nodes.insert(all_boundary_nodes.end(), top_nodes.begin(), top_nodes.end());
all_boundary_nodes.insert(all_boundary_nodes.end(), left_nodes.begin(), left_nodes.end());
}
// ================================================================
// STREAM FUNCTION BOUNDARY CONDITIONS
// ================================================================
// The Poisson equation for the stream function is: -∇²ψ = ω
// (negated for positive definiteness with CG/direct solvers).
//
// Boundary conditions on ψ depend on BC type:
// no-slip/slip: Dirichlet ψ = constant (determined by flow rate)
// velocity: Dirichlet ψ = ∫u dy (integrated from velocity profile)
// pressure/outflow: Neumann ∂ψ/∂n = 0 (natural outflow)
//
// For Dirichlet nodes, the matrix row is replaced with identity: ψ_i = ψ_bc_i
// For Neumann nodes, the matrix row is replaced with the normal derivative
// operator: (∂ψ/∂n)_i = 0
//
// Reference: von Karman cylinder code (ns_solver.cpp)
// Prescribed stream function values at boundary nodes.
// Initialized to 0 (backward-compatible with cavity where ψ=0 everywhere).
mfem::Vector psi_bc(num_nodes);
psi_bc = 0.0;
// Lists of Dirichlet and Neumann boundary nodes for the ψ equation.
// Neumann nodes also store their normal axis ('x' or 'y') to select
// the correct derivative operator.
std::vector<int> dirichlet_psi_nodes;
std::vector<std::pair<int, char>> neumann_psi_info; // (node_idx, axis)
#ifdef STREAMVORTI_WITH_ECL
if (use_sdl_bcs) {
// ============================================================
// A1. Classify boundary nodes by ψ condition type
// ============================================================
// First pass: compute ψ at velocity (inlet) boundaries by integrating
// the prescribed velocity profile along the boundary.
//
// For a velocity BC on a vertical boundary (= x val):
// u = ∂ψ/∂y → ψ(y) = ∫₀ʸ u(x₀, η) dη
//
// For a velocity BC on a horizontal boundary (= y val):
// v = -∂ψ/∂x → ψ(x) = ψ_ref - ∫₀ˣ v(ξ, y₀) dξ
//
// No-slip/slip walls: ψ = constant, determined from boundary
// connectivity (second pass below).
// Number of Simpson's rule sub-intervals for ψ integration
constexpr int nsub = 20;
for (const auto& bc : sdl_boundaries) {
auto it = boundary_nodes_by_attr.find(bc.attribute);
if (it == boundary_nodes_by_attr.end()) continue;
const auto& nodes = it->second;
if (bc.type == "velocity") {
// Compute ψ at each node by numerically integrating the
// velocity function from 0 to the node's coordinate:
// Vertical boundary (= x val): ψ(y) = ∫₀ʸ u(x₀, η) dη
// Horizontal boundary (= y val): ψ(x) = -∫₀ˣ v(ξ, y₀) dξ
//
// Each node is independent — no sorting or inter-node
// dependencies. Uses composite Simpson's rule (nsub intervals).
for (int vi : nodes) {
const double* vtx = mesh->GetVertex(vi);
double psi_val = 0.0;
if (bc.predicate_axis == 'x' && bc.u_function) {
double x0 = bc.predicate_value;
double y = vtx[1];
double h = y / nsub;
for (int k = 0; k < nsub; ++k) {
double a = k * h;
double b = (k + 1) * h;
double m = 0.5 * (a + b);
psi_val += (h / 6.0) * (
bc.u_function->evaluateAt(x0, a, 0.0) +
4.0 * bc.u_function->evaluateAt(x0, m, 0.0) +
bc.u_function->evaluateAt(x0, b, 0.0));
}
} else if (bc.predicate_axis == 'y' && bc.v_function) {
double y0 = bc.predicate_value;
double x = vtx[0];
double h = x / nsub;
for (int k = 0; k < nsub; ++k) {
double a = k * h;
double b = (k + 1) * h;
double m = 0.5 * (a + b);
psi_val -= (h / 6.0) * (
bc.v_function->evaluateAt(a, y0, 0.0) +
4.0 * bc.v_function->evaluateAt(m, y0, 0.0) +
bc.v_function->evaluateAt(b, y0, 0.0));
}
}
psi_bc[vi] = psi_val;
}
// All velocity boundary nodes are Dirichlet
for (int vi : nodes) {
dirichlet_psi_nodes.push_back(vi);
}
} else if (bc.type == "pressure" || bc.type == "outflow") {
// Neumann ∂ψ/∂n = 0: natural outflow condition.
// The normal direction is determined from predicate_axis:
// (= x val) → outward normal is ±x̂ → ∂ψ/∂x = 0
// (= y val) → outward normal is ±ŷ → ∂ψ/∂y = 0
char axis = bc.predicate_axis;
if (axis == '\0') {
MFEM_ABORT("Pressure/outflow BC '" << bc.name
<< "' requires a simple predicate (= x val) or (= y val) "
<< "to determine the normal direction for Neumann ∂ψ/∂n = 0");
}
for (int vi : nodes) {
neumann_psi_info.push_back({vi, axis});
}
} else {
// no-slip, slip: Dirichlet ψ = constant.
// The constant is determined below from shared corner nodes.
for (int vi : nodes) {
dirichlet_psi_nodes.push_back(vi);
}
}
}
// ============================================================
// A2. Compute wall ψ constants from boundary connectivity
// ============================================================
// ψ = constant on any impermeable wall (from u·n = 0).
// The constant is determined by mass conservation: it equals ψ
// at the corner where the wall meets a velocity boundary.
//
// Algorithm: use MFEM boundary element connectivity to discover
// which walls are adjacent to which velocity boundaries, then
// compute ψ at the shared corner vertex.
//
// Step 1: Build vertex → set of boundary attributes map
std::map<int, std::set<int>> vertex_attrs;
for (int be = 0; be < mesh->GetNBE(); ++be) {
int attr = mesh->GetBdrAttribute(be);
mfem::Array<int> verts;
mesh->GetBdrElementVertices(be, verts);
for (int j = 0; j < verts.Size(); ++j) {
vertex_attrs[verts[j]].insert(attr);
}
}
// Step 2: Build attribute → BC map
std::map<int, const StreamVorti::Lisp::BoundaryCondition*> attr_to_bc;
for (const auto& bc : sdl_boundaries) {
attr_to_bc[bc.attribute] = &bc;
}
// Step 3: For each wall BC, find adjacent velocity BC via corner
// vertices and compute the wall ψ constant
for (const auto& wall_bc : sdl_boundaries) {
if (wall_bc.type != "no-slip" && wall_bc.type != "slip") continue;
auto wall_nodes_it = boundary_nodes_by_attr.find(wall_bc.attribute);
if (wall_nodes_it == boundary_nodes_by_attr.end()) continue;
// Search for corner vertices where this wall meets a velocity BC
double wall_psi = 0.0;
bool found = false;
for (const auto& [vi, attrs] : vertex_attrs) {
if (attrs.find(wall_bc.attribute) == attrs.end()) continue;
if (attrs.size() < 2) continue; // not a corner
// Check if any other attribute at this corner is a velocity BC
for (int other_attr : attrs) {
if (other_attr == wall_bc.attribute) continue;
auto bc_it = attr_to_bc.find(other_attr);
if (bc_it == attr_to_bc.end()) continue;
const auto* vel_bc = bc_it->second;
if (vel_bc->type != "velocity") continue;
// Found a velocity BC adjacent to this wall.
// Compute ψ at the corner vertex coordinate using
// the same Simpson's rule as velocity boundary nodes.
const double* corner = mesh->GetVertex(vi);
double psi_val = 0.0;
if (vel_bc->predicate_axis == 'x' && vel_bc->u_function) {
double x0 = vel_bc->predicate_value;
double y = corner[1];
double h = y / nsub;
for (int k = 0; k < nsub; ++k) {
double a = k * h, b = (k + 1) * h, m = 0.5 * (a + b);
psi_val += (h / 6.0) * (
vel_bc->u_function->evaluateAt(x0, a, 0.0) +
4.0 * vel_bc->u_function->evaluateAt(x0, m, 0.0) +
vel_bc->u_function->evaluateAt(x0, b, 0.0));
}
} else if (vel_bc->predicate_axis == 'y' && vel_bc->v_function) {
double y0 = vel_bc->predicate_value;
double x = corner[0];
double h = x / nsub;
for (int k = 0; k < nsub; ++k) {
double a = k * h, b = (k + 1) * h, m = 0.5 * (a + b);
psi_val -= (h / 6.0) * (
vel_bc->v_function->evaluateAt(a, y0, 0.0) +
4.0 * vel_bc->v_function->evaluateAt(m, y0, 0.0) +
vel_bc->v_function->evaluateAt(b, y0, 0.0));
}
}
wall_psi = psi_val;
found = true;
break;
}
if (found) break;
}
// Apply wall constant to all nodes on this wall
if (found) {
for (int vi : wall_nodes_it->second) {
psi_bc[vi] = wall_psi;
}
}
}
std::cout << "Setup: Classified boundary nodes for ψ equation:" << std::endl;
std::cout << " Dirichlet: " << dirichlet_psi_nodes.size() << " nodes" << std::endl;
std::cout << " Neumann: " << neumann_psi_info.size() << " nodes" << std::endl;
} else
#endif
{
// CLI mode: all boundary nodes are Dirichlet with ψ = 0 (cavity)
dirichlet_psi_nodes = all_boundary_nodes;
}
// Pre-classify boundary nodes by BC type for the vorticity step.
// This determines how wall vorticity is computed:
// no-slip: ω = ∂²ψ/∂n² (Dirichlet ψ, derive ω from ψ field)
// slip: ω = 0 (Dirichlet ψ, free tangential stress)
// velocity/outflow: ω = ∂v/∂x - ∂u/∂y (from velocity field)
std::map<int, std::string> boundary_node_bc_type;
#ifdef STREAMVORTI_WITH_ECL
if (use_sdl_bcs) {
for (const auto& bc : sdl_boundaries) {
auto it = boundary_nodes_by_attr.find(bc.attribute);
if (it == boundary_nodes_by_attr.end()) continue;
for (int ni : it->second) {
boundary_node_bc_type[ni] = bc.type;
}
}
} else
#endif
{
// CLI mode: top nodes are velocity (lid), rest are no-slip walls
std::set<int> top_set(top_nodes.begin(), top_nodes.end());
for (int vi : all_boundary_nodes) {
boundary_node_bc_type[vi] =
(top_set.count(vi) ? "velocity" : "no-slip");
}
}
// ================================================================
// LAPLACIAN MATRIX ASSEMBLY
// ================================================================
// Assemble -∇²ψ = ω system with mixed Dirichlet/Neumann BCs.
// Use mfem::Add to merge sparsity patterns correctly — SparseMatrix::Add
// only updates existing entries and silently drops new columns from B.
// CG/PCG solvers require SPD matrices — abort if selected without symmetrization
if ((params.solver_type == "cg") && !params.symmetrize_laplacian) {
MFEM_ABORT("Solver '" << params.solver_type
<< "' requires a symmetric matrix. "
<< "Use -sym to symmetrize the DCPSE Laplacian, "
<< "or use a non-symmetric solver (gmres, umfpack).");
}
mfem::SparseMatrix* laplacian_matrix;
if (params.symmetrize_laplacian) {
// Symmetrize DCPSE Laplacian: L = (L + L^T) / 2
// DCPSE operators approximate the symmetric continuous Laplacian
// but have non-symmetric stencils. Symmetrizing enables CG solvers.
mfem::SparseMatrix* L_raw = mfem::Add(-1.0, dxx_matrix, -1.0, dyy_matrix);
mfem::SparseMatrix* L_t = mfem::Transpose(*L_raw);
laplacian_matrix = mfem::Add(0.5, *L_raw, 0.5, *L_t);
delete L_raw;
delete L_t;
std::cout << "Setup: Symmetrized DCPSE Laplacian: L = (L + L^T) / 2" << std::endl;
} else {
laplacian_matrix = mfem::Add(-1.0, dxx_matrix, -1.0, dyy_matrix);
}
// STEP 1: Replace Neumann rows with normal derivative operator (∂ψ/∂n = 0)
// For outlet at x=const: row ← dx_matrix row (enforces ∂ψ/∂x = 0)
// For outlet at y=const: row ← dy_matrix row (enforces ∂ψ/∂y = 0)
for (const auto& [idx, axis] : neumann_psi_info) {
laplacian_matrix->EliminateRow(idx);
const mfem::SparseMatrix& deriv = (axis == 'x') ? dx_matrix : dy_matrix;
mfem::Array<int> cols;
mfem::Vector vals;
deriv.GetRow(idx, cols, vals);
for (int j = 0; j < cols.Size(); ++j) {
if (std::abs(vals(j)) > 0.0) {
laplacian_matrix->Set(idx, cols[j], vals(j));
}
}
}
// STEP 2: Dirichlet elimination — zero row AND column, set diagonal to 1.
// Matches the parallel code's EliminateRowsCols + EliminateBC.
//
// Cannot use EliminateRowCol(rc, Ae) here because it assumes symmetric
// sparsity (MFEM docs: "assumes element (i,rc) is assembled iff (rc,i)
// is assembled"), which DCPSE matrices don't satisfy.
//
// Instead: EliminateCols zeros all Dirichlet columns in a single O(nnz)
// pass and saves the eliminated entries in Ae. Then EliminateRow zeros
// Dirichlet rows (no saving needed — rhs is set to psi_bc directly).
// Each timestep, the RHS correction rhs -= Ae * psi_bc accounts for
// the eliminated column coupling.
mfem::Array<int> col_marker(num_nodes);
col_marker = 0;
for (int idx : dirichlet_psi_nodes) col_marker[idx] = 1;
mfem::SparseMatrix* Ae = new mfem::SparseMatrix(num_nodes);
laplacian_matrix->EliminateCols(col_marker, *Ae);
for (int idx : dirichlet_psi_nodes) {
laplacian_matrix->EliminateRow(idx);
laplacian_matrix->Set(idx, idx, 1.0);
}
laplacian_matrix->Finalize();
Ae->Finalize();
std::cout << "Setup: Created Laplacian matrix with boundary conditions." << std::endl;
// ================== Timing PHASE 2: FACTORIZATION ==================
mfem::StopWatch factor_timer;
factor_timer.Start();
// Create and setup linear solver (factorization happens here for direct solvers)
SolverPackage* solver_package = CreateLinearSolver(params.solver_type, *laplacian_matrix, params);
if (!solver_package || !solver_package->solver) {
MFEM_ABORT("Failed to create linear solver");
}
mfem::Solver* linear_solver = solver_package->solver;
factor_timer.Stop();
perf_metrics.factorization_time = factor_timer.RealTime();
std::cout << "Phase 2 - Factorization: " << perf_metrics.factorization_time << " s" << std::endl;
// Initialize solution vectors
mfem::Vector vorticity(num_nodes);
mfem::Vector streamfunction(num_nodes);
mfem::Vector vorticity_old(num_nodes); // for residual monitor
mfem::Vector rhs(num_nodes);
vorticity = 0.0;
streamfunction = 0.0;
// Derivative vectors (allocated once, reused throughout)
// Streamfunction derivatives (for interior vorticity update)
mfem::Vector dpsi_dy(num_nodes); // ∂ψ/∂y
mfem::Vector dpsi_dx(num_nodes); // ∂ψ/∂x
// CRITICAL FIX: Separate velocity vectors (for boundary conditions)
mfem::Vector u_velocity(num_nodes); // u = ∂ψ/∂y (with BCs applied)
mfem::Vector v_velocity(num_nodes); // v = -∂ψ/∂x (with BCs applied)
// Velocity derivatives (for boundary vorticity calculation)
mfem::Vector du_dy(num_nodes); // ∂u/∂y
mfem::Vector dv_dx(num_nodes); // ∂v/∂x
// Vorticity derivatives
mfem::Vector domega_dx(num_nodes);
mfem::Vector domega_dy(num_nodes);
mfem::Vector d2omega_dx2(num_nodes);
mfem::Vector d2omega_dy2(num_nodes);
// Residual monitoring vectors
mfem::Vector convection_term(num_nodes);
mfem::Vector diffusion_term(num_nodes);
// ====================================================================
// PARAVIEW OUTPUT SETUP
// ====================================================================
// Create finite element spaces
mfem::FiniteElementSpace scalar_fes(const_cast<mfem::Mesh*>(mesh), &fec, 1);
mfem::FiniteElementSpace vector_fes(const_cast<mfem::Mesh*>(mesh), &fec, mesh->SpaceDimension());
// Create grid functions
mfem::GridFunction vorticity_gf(&scalar_fes);
mfem::GridFunction streamfunction_gf(&scalar_fes);
mfem::GridFunction velocity_gf(&vector_fes);
// Boundary diagnostic fields (static, written at t=0 for visualization)
mfem::GridFunction boundary_normal_gf(&vector_fes);
mfem::GridFunction bc_type_gf(&scalar_fes);
mfem::GridFunction mesh_bdr_attr_gf(&scalar_fes);
boundary_normal_gf = 0.0;
bc_type_gf = 0.0;
mesh_bdr_attr_gf = 0.0;
for (const auto& [node, normal] : node_normals) {
boundary_normal_gf(vector_fes.DofToVDof(node, 0)) = normal(0);
boundary_normal_gf(vector_fes.DofToVDof(node, 1)) = normal(1);
}
for (const auto& [node, bc_type] : boundary_node_bc_type) {
// Encode: 0=interior, 1=no-slip, 2=slip, 3=velocity, 4=outflow/pressure
double val = 0.0;
if (bc_type == "no-slip") val = 1.0;
else if (bc_type == "slip") val = 2.0;
else if (bc_type == "velocity") val = 3.0;
else if (bc_type == "outflow" || bc_type == "pressure") val = 4.0;
bc_type_gf[node] = val;
}
// Mesh boundary attribute per node (from boundary_nodes_by_attr).
// Nodes shared by multiple boundary elements get the highest attribute.
for (const auto& [attr, nodes] : boundary_nodes_by_attr) {
for (int node : nodes) {
mesh_bdr_attr_gf[node] = static_cast<double>(attr);
}
}
// Log boundary diagnostics
{
int n_noslip = 0, n_slip = 0, n_velocity = 0, n_outflow = 0;
for (const auto& [node, bc_type] : boundary_node_bc_type) {
if (bc_type == "no-slip") n_noslip++;
else if (bc_type == "slip") n_slip++;
else if (bc_type == "velocity") n_velocity++;
else n_outflow++;
}
std::cout << "Setup: Boundary node classification:" << std::endl;
std::cout << " no-slip: " << n_noslip << ", slip: " << n_slip
<< ", velocity: " << n_velocity << ", outflow/pressure: " << n_outflow
<< std::endl;
std::cout << " Boundary normals computed for " << node_normals.size()
<< " nodes" << std::endl;
}
// Create ParaView data collection
mfem::ParaViewDataCollection paraview_dc(paraview_filename, mesh);
if (paraview_output) {
// paraview_dc.SetPrecision(8);
paraview_dc.SetPrefixPath(paraview_prefix_path);
paraview_dc.SetLevelsOfDetail(order);
// paraview_dc.SetDataFormat(mfem::VTKFormat::ASCII);
paraview_dc.SetDataFormat(mfem::VTKFormat::BINARY);
// paraview_dc.SetHighOrderOutput(true);
// Register fields
paraview_dc.RegisterField("Vorticity", &vorticity_gf);
paraview_dc.RegisterField("StreamFunction", &streamfunction_gf);
paraview_dc.RegisterField("Velocity", &velocity_gf);
paraview_dc.RegisterField("BoundaryNormal", &boundary_normal_gf);
paraview_dc.RegisterField("BCType", &bc_type_gf);
paraview_dc.RegisterField("MeshBdrAttribute", &mesh_bdr_attr_gf);
// Set time and cycle, then save
paraview_dc.SetCycle(0);
paraview_dc.SetTime(0.0);
paraview_dc.Save();
std::cout << "Created ParaView output directory: " << paraview_prefix_path << std::endl;
}
// Helper: update GridFunctions from solution vectors.
// Used by both ParaView output and SaveSolutionToFile.
auto UpdateGridFunctions = [&]() {
for (int i = 0; i < num_nodes; ++i) {
vorticity_gf[i] = vorticity[i];
streamfunction_gf[i] = streamfunction[i];
velocity_gf(vector_fes.DofToVDof(i, 0)) = u_velocity[i];
velocity_gf(vector_fes.DofToVDof(i, 1)) = v_velocity[i];
}
};
// ====================================================================
// TIME-STEPPING PARAMETERS
// ====================================================================
double current_dt = params.dt; //fixed dt
int num_timesteps = static_cast<int>(params.final_time / params.dt);
// Initialize steady state monitoring
mfem::Vector steady_prev_vorticity(num_nodes);