-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPMsolver.cpp
2383 lines (2213 loc) · 100 KB
/
PMsolver.cpp
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
#ifdef _WIN32
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QSettings>
#include <QStandardPaths>
#endif
//#include <sys/param.h>
#include <iostream>
#include <sys/types.h>
#include <sstream>
#include <fstream>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include <thread>
#include <condition_variable>
#include <mutex>
#include <ctime>
#include <chrono>
#include <ratio>
#include <list>
#include <vector>
#include <string_view>
#ifdef FSI_OPENMP
#include <omp.h>
#endif
#include <armadillo> // linear algebra library
#include "pugixml.hpp"
#ifdef FSI_MPI
#include <mpi.h>
#endif
const double pi = 3.14159265358979323846;
const double th = 30.0 * pi / 180.0;
static const arma::uword x = 0, y = 1, z = 2;
#include <PMsolver.h> // TODO must be consistent and perhaps shared with GUI
#include <fsi_thread.h>
#include "fsi_output.hpp"
//#pragma GCC diagnostic ignored "-Wunused-variable"
//#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wpadded" // ignore struct padding warnings
// standardize and simplify matrix object handling
#define ZERO(arg) (arg).zeros()
#define ENDROW(var) (var)((var).n_rows - 1 // note: unusual looks - missing close paren
#define ENDCOL(var) (var).n_cols - 1
#define ENDN3D(var) (var).n_slices - 1
#define NROWS(matrix) (matrix).n_rows
#define NCOLS(matrix) (matrix).n_cols
#define N3D(matrix) (matrix).n_slices
#define MATDIM(m) (m).n_rows, (m).n_cols // assign same dimensions
#define MATDIMCAT(m,n) (m).n_rows + (n).n_rows, (m).n_cols // assign dimensions for concatenation
#define COMP(i, j) slice(j).unsafe_col(i) // x,y,z components of an arma cube
#define BSIZE (3 * (2 * m + 2) * (n + 1)) // number of elements in BXYZ
#define WSIZE (3 * nts * (n + 1)) // number of elements WXYZ
#define CSIZE (3 * 2 * m * n) // number of elements CXYZ
#define BDIM 3, 2 * m + 2, n + 1
#define WDIM 3, nts, n + 1
#define CDIM 3, 2 * m, n
#define MATRIX_OUT(x) matrix_out(doc, #x, x) // same XML name as variable name
#define MATRIX_OUTATT(x) matrix_out(doc, #x, x, t) // picks up time t
// settings following convention envvars prefaced with FSI_NAME_, default prefaced with default_
#define SETV(n) set_fsi_parm(FSI_NAME_##n, default_##n, key_val_map, doc, argc, argv)
#define SET(n) const auto n = SETV(n)
#define SETS(n) set_fsi_parm(n, FSI_NAME_##n, default_##n, key_val_map, doc, argc, argv)
#define ATTR(varname) doc.child("settings").append_attribute(varname)
#define ATTRVAL(patt, att, val) \
patt = doc.child("settings").attribute(att); \
if (patt == nullptr) doc.child("settings").append_attribute(att) = val; \
else patt.set_value(val)
#define SLEEP(secs) this_thread::sleep_for(seconds(secs))
using namespace std;
using namespace arma;
using namespace chrono;
string read_file(string_view path);
void read_NASTRAN(const string meshfile, cube &XYZ, unsigned int &nnodes, unsigned int &nelems,
int &m, int &n);
void mexINFLUENCE(const double *x, const double *y, const double *z,
const double *xp, const double *yp, const double *zp,
double *AB, const double Miu,
const int nx, const int ny, const int t,
const int slice1 = -1, const int slice2 = -1);
typedef map<string,string> key_val_map_t;
bool parse_ini(istream &, key_val_map_t &);
int parse_ini(const char *, key_val_map_t &);
bool has_opt(char** begin, char** end, const string& option);
int set_fsi_parm(const char *varname,
const int default_val,
key_val_map_t &key_val_map,
pugi::xml_node &doc,
int argc, char **argv);
double set_fsi_parm(const char *varname,
const double default_val,
key_val_map_t &key_val_map,
pugi::xml_node &doc,
int argc, char **argv);
void set_fsi_parm(string &outstring,
const char *varname,
const char *default_val,
key_val_map_t &key_val_map,
pugi::xml_node &doc,
int argc, char **argv);
#ifdef Q_OS_WIN32
extern string Xsettings_file;
#endif
extern vector<double **> tandem_output;
vector<double **> tandem_output;
extern int min_workinc, max_workinc;
#define MIN_WORKINC 99999999
int min_workinc = MIN_WORKINC, max_workinc = 0;
extern condition_variable cv_parent;
static string settings;
// threading
static mutex mtx; // used in parent thread to await launching of children
extern mutex parent_mtx;
mutex parent_mtx;
static condition_variable cv_child; // set by parent thread to awaken children
condition_variable cv_parent; // set by last child thread to awaken parent
#ifndef FSI_OPENMP
static atomic<mex_thread *>pmex = nullptr;
static int pmex_id = 0; // identifier for synchronization
#endif
static bool program_ending = false;
extern int world_rank;
int world_rank = -1; // default signifies no MPI
#ifdef FSI_STATS
timecheck mex_time; // manages stop watch
#ifdef FSI_OPENMP
map<const int, mex_stat_map_t *> thread_stat_map;
#else
map<const thread::id, mex_stat_map_t *> thread_stat_map;
#endif
// mapping: threads[id] -> pmex -> mex_stat
// so each thread has stats per mex routine
#endif
inline void rotate(cube &out, const mat &ROT, const cube &in) {
assert(out.size() == in.size());
vec::fixed<3> tout, tin;
cube::const_iterator itin = in.begin();
const cube::const_iterator itend = in.end();
cube::iterator itout = out.begin();
for (; itin != itend;) {
tin(x) = *itin++;
tin(y) = *itin++;
tin(z) = *itin++;
tout = ROT * tin;
*itout++ = tout(x);
*itout++ = tout(y);
*itout++ = tout(z);
}
}
inline void dot_entire(mat &out, const cube &in, const cube &in1) {
assert(in.size() == in1.size());
cube::const_iterator itin = in.begin(),
it1in = in1.begin();
const cube::const_iterator itend = in.end();
cube::iterator itout = out.begin();
for (; itin != itend;) {
*itout = *itin++ * *it1in++; // X
*itout += *itin++ * *it1in++; // Y
*itout++ += *itin++ * *it1in++; // Z
}
}
inline void dot_entire_xyz(cube &out, const cube &ix, const cube &iy, const cube &iz, const cube &in1) {
assert(ix.size() == in1.size());
assert(iy.size() == in1.size());
assert(iz.size() == in1.size());
cube::const_iterator ixin = ix.begin(),
iyin = iy.begin(),
izin = iz.begin(),
it1in = in1.begin();
const cube::const_iterator itend = ix.end();
cube::iterator itout = out.begin();
for (; ixin != itend;) {
*itout = *ixin++ * *it1in++; // X
*itout += *ixin++ * *it1in++; // Y
*itout++ += *ixin++ * *it1in; // Z
it1in -= 2;
*itout = *iyin++ * *it1in++; // X
*itout += *iyin++ * *it1in++; // Y
*itout++ += *iyin++ * *it1in; // Z
it1in -= 2;
*itout = *izin++ * *it1in++; // X
*itout += *izin++ * *it1in++; // Y
*itout++ += *izin++ * *it1in++; // Z
assert(itout <= out.end());
}
}
/*!
* vect computes vectors: normal, chord-wise tangent, span-wise tangent
*
* returns area
*
* MATLAB: function [n, tx, ty, s]=VECT(x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4)
*/
double vect(const double x1, const double y1, const double z1,
const double x2, const double y2, const double z2,
const double x3, const double y3, const double z3,
const double x4, const double y4, double const z4,
double *n, // normal vector
double *tx, // chord-wise tangential vector
double *ty // span-wise tangential vector
) {
// calculating chordwise tangent
//double d4 = sqrt(pow(x1-x4, 2) + pow(y1-y4, 2)+pow(z1-z4, 2));
const double A1 = ((x4 + x3) - (x1 + x2)) / 2,
A2 = ((y4 + y3) - (y1 + y2)) / 2,
A3 = ((z4 + z3) - (z1 + z2)) / 2,
AA = sqrt(A1 * A1 + A2 * A2 + A3 * A3);
tx[x] = A1 / AA;
tx[y] = A2 / AA;
tx[z] = A3 / AA;
// next vector in this plan
const double b1 = x2 - x1,
b2 = y2 - y1,
b3 = z2 - z1,
bb = sqrt(b1 * b1 + b2 * b2 + b3 * b3);
// d4 = sqrt(pow(x1-x4, 2) + pow(y1-y4, 2) + pow(z1-z4, 2));
const double b[] = {b1 / bb, b2 / bb, b3 / bb};
// normal vector
const double v1 = tx[y] * b[z] - tx[z] * b[y],
v2 = b[x] * tx[z] - tx[x] * b[z],
v3 = tx[x] * b[y] - tx[y] * b[x],
vv = sqrt(v1 * v1 + v2 * v2 + v3 * v3);
n[x] = v1 / vv;
n[y] = v2 / vv;
n[z] = v3 / vv;
// tangential vector in spanwise direction
ty[x] = n[y] * tx[z] - n[z] * tx[y];
ty[y] = tx[x] * n[z] - tx[z] * n[x];
ty[z] = n[x] * tx[y] - n[y] * tx[x];
// % tt=sqrt(ty(1)^2+ty(2)^2+ty(3)^2);
// % ty(1)= ty(1)/tt;
// % ty(2) = ty(2)/tt;
// % ty(3) = ty(3)/tt;
// calculation of area
const double e1 = x3 - x1,
e2 = y3 - y1,
e3 = z3 - z1,
f1 = x2 - x1,
f2 = y2 - y1,
f3 = z2 - z1;
// normal area
const double s11 = f2 * b3 - f3 * b2,
s12 = b1 * f3 - f1 * b3,
s13 = f1 * b2 - f2 * b1,
s21 = b2 * e3 - b3 * e2,
s22 = e1 * b3 - b1 * e3,
s23 = b1 * e2 - b2 * e1;
return 0.5 * (sqrt(s11 * s11 + s12 * s12 + s13 * s13) +
sqrt(s21 * s21 + s22 * s22 + s23 * s23));
}
/*!
* lspace(vec, start, end)
* variation of MATLAB linspace
*/
void lspace(vec &p, const double x1, const double x2) {
double newval = x1;
const size_t n = NROWS(p);
const double step = (x2 - x1) / (n - 1);
for (size_t i = 0; i < n; i++) {
p[i] = newval;
newval += step;
}
}
void flipdim(mat &dst, const mat &src, const int dim,
const size_t torow = 0) {
const size_t nrows = (torow == 0 ? NROWS(src) : torow);
const size_t ncols = NCOLS(src);
assert(dim == 1 || dim == 2);
assert(torow == 0 || NROWS(dst) >= nrows);
assert(torow != 0 || NROWS(dst) >= NROWS(src));
assert(NCOLS(dst) == NCOLS(src));
if (dim == 1) { // flip rows
for (size_t row = 0; row < nrows; row++) {
for (size_t col = 0; col < ncols; col++) {
dst(nrows - row - 1, col) = src(row, col);
}
}
}
if (dim == 2) { // flip columns
for (size_t row = 0; row < nrows; row++) {
for (size_t col = 0; col < ncols; col++) {
dst(row, ncols - col - 1) = src(row, col);
}
}
}
}
#define MACROVAR(param) #param
#define NANerr(var) if (var.has_nan()) NANerror(t, MACROVAR(var))
void NANerror(const int t, const string &var) {
std::cerr << "ERROR:Solver computational error: calculated a NaN (not a number) for variable " << var << " at time " << t << " ." << std::endl;
exit(1);
}
/*!
* \brief mex_thread::mex_parent - Awakens and synchronizes POSIX child threads
* for MPI and POSIX thread types
*
* Called by main thread for each task once at each time step. Exists only in base class.
*
* The mex_thread object must be re-initialized by its `mex_thread_init()` each time step.
* mex_thread_init() always calls this after its init is complete at time step for MPI and POSIX
*/
#ifndef FSI_OPENMP
void mex_thread::mex_parent() {
unique_lock<mutex> parent_lck(parent_mtx);
TSTART(mex_time, steady_clock::now()); // start mex timing
// new task
pmex_id++; // don't mistake this run for previous run
pmex = this; // new task now available
unique_lock<mutex> lck(mtx);
try {
cv_child.notify_all();
}
catch (exception& e) {
std::cerr << "exception caught when cv_child.notify_all() in mex_parent() "
"Exception: " << e.what() << '\n';
}
lck.unlock(); // allow remaining children to continue
// wait for last worker to finish
if (has_unfinished_workers()) {
try {
cv_parent.wait(parent_lck);
}
catch (system_error& e) {
std::cerr << "system_error exception caught when launching cv_parent.wait() "
"Exception: " << e.what() << '\n';
}
}
pmex = nullptr; // task finished - no active task
TSTOP(mex_time, steady_clock::now()); // stop mex timing and add elapsed
}
/*!
* \brief mex_thread - main POSIX thread routine for all mex child threads
*
* Assumes that pmex will contain the address of the mex object to run
* and that the pmex object will already be initialized for the specifics of the run.
*
* This is the main entry point called by each POSIX child thread at startup. It
* - waits for work to do and
* - calls the mex_thread_run() method from the subclass
*
* Not used with the OpenMP thread model
*/
void mex_thread_main(int partner_rank) {
int thread_pmex_id = -1; // prevent dups, won't block 1st time if task ready
for (;;) {
#ifdef FSI_STATS
const steady_clock::time_point start = steady_clock::now();
#endif
unique_lock<mutex> lck(mtx);
// don't wait if next task is already available
// and don't mistake this task for task already completed
if (pmex == nullptr || pmex_id == thread_pmex_id) {
try {
cv_child.wait(lck); // generic child thread waits for work to do
}
catch (exception& e) {
std::cerr << "exception caught when cv_child.wait() in mex_thread_main() "
"Exception: " << e.what() << '\n';
}
}
// when told to proceed by main thread, all data must already by loaded for mex run
lck.unlock(); // allows other threads to continue
if (program_ending) return;
thread_pmex_id = pmex_id;
assert(pmex != nullptr);
#ifdef FSI_STATS
mex_thread *local_pmex = pmex;
#endif
(*pmex).mex_thread_run(partner_rank);
// note: when the last thread is finishing, pmex will be cleared
#ifdef FSI_STATS
// statistics
mex_stat *pmex_stat = (*thread_stat_map[this_thread::get_id()])[local_pmex];
pmex_stat->call_count++;
pmex_stat->elapsed += duration_cast<mex_thread_time_units_t>(steady_clock::now() - start);
#endif
} // forever
}
#endif
// INFLUENCE - only sig
// SOURCEVEL - mat sig1(2 * m, n);
// wingwakeinf - mat MUEA1(2 * m, n); mat MUEW1doubled(nts, n);
// WAKEINFLUENCE - mat MUEW1(nts, n);
#ifdef FSI_MPI
/*!
* \brief compute_main - main MPI compute logic on remote machine
* - posts MPI read, decodes response, determining calculation type and invoking compute() method
* of corresponding type
* - compute method calculates and sends data to corresponding POSIX thread on host system.
* - in lock step with mex_thread_run() on host system, MPI rank == POSIX thread index-1
* \param m
* \param n
* \param nts
* \param nthreads
* \param workinc
* \param workfactor
*/
void compute_main(const int m, const int n, const int nts,
const int nthreads, const int workinc, const double workfactor) {
//std::cerr << "compute_main: m=" << m << " n=" << n << " nts=" << nts << " nthreads=" << nthreads << " workinc=" << workinc << " workfactor=" << workfactor << std::endl;
influence_thread *pinfluence = nullptr;
sourcevel_thread *psourcevel = nullptr;
wingwakeinf_thread *pwingwakeinf = nullptr;
wakeinfluence_thread *pwakeinfluence = nullptr;
double *BXYZ = nullptr, *CXYZ = nullptr, *WXYZ = nullptr, *precv = nullptr;
// cube *pXYZ = cube(WXYZ, WDIM, false, false);
int t = -1;
const int n_elem_all_grids = BSIZE + CSIZE + WSIZE, // total size of all grids that are broadcast
max_recv_size = 2 * m * n + nts * n; // wingwakeinf coefficient arrays will always the biggest
BXYZ = new double[n_elem_all_grids];
CXYZ = &BXYZ[BSIZE];
WXYZ = &CXYZ[CSIZE];
precv = new double[max_recv_size];
for (;;) {
MPI_Status recv_status;
int rstat = MPI_Probe(0, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_status);
if (rstat != MPI_SUCCESS) std::cerr << "MPI_Probe receive stat:" << rstat << std::endl;
assert (rstat == MPI_SUCCESS);
//mat MUEA1(2 * m, n);
//mat MUEW1doubled(nts, n);
//mat sig = mat (precv, 2 * m, n, false, true);
//mat sig2 = mat (precv + sig.n_elem, nts, n, false, true);
// WAKEINFLUENCE - mat MUEW1(nts, n);
//mat sig3 = mat (precv, nts, n, false, true);
const unsigned int mex_type = recv_status.MPI_TAG & MEX_MASK,
ord = recv_status.MPI_TAG & ~MEX_MASK;
if (ord == do_finalize) {
rstat = MPI_Recv(precv, 0, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
assert(rstat == MPI_SUCCESS);
return; // and finalize and exit
}
//std::cerr << "compute_main:received rank:" << rank << " mex type:" << mex_type << " ord:" << ord << std::endl;
if (mex_type != influence_mask) {
//std::cerr << "compute_main:calling MPI_Recv rank:" << world_rank << " precv=" << precv << " max_recv_size=" << max_recv_size << " *precv=" << *precv <<std::endl;
rstat = MPI_Recv(precv, max_recv_size, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
assert(rstat == MPI_SUCCESS);
}
int count;
switch (mex_type) {
case influence_mask:
MPI_Get_count(&recv_status, MPI_DOUBLE, &count);
assert(count == 0 || count == n_elem_all_grids);
if (count > 0) {
t++;
//std::cerr << "compute_main t=" << t << " :calling INFLUENCE MPI_Recv for grids, rank:" << world_rank << " ord=" << ord << std::endl;
rstat = MPI_Recv(BXYZ, n_elem_all_grids, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
assert(rstat == MPI_SUCCESS);
if (ord == time_pulse) break; // only time pulse and receive grid point updates - no reply
} else {
//std::cerr << "compute_main:calling INFLUENCE MPI_Recv rank:" << world_rank <<std::endl;
rstat = MPI_Recv(precv, max_recv_size, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
assert(rstat == MPI_SUCCESS);
}
if (t >= nts) {
//std::cerr << "compute_main: t reaches nts, so returning" << std::endl;
return;
}
if (pinfluence == nullptr) {
//std::cerr << "compute_main: allocating INFLUENCE object compute for t=" << t << " rank=" << world_rank << std::endl;
pinfluence = new influence_thread("INFLUENCE", nthreads, 2 * m, n, CXYZ, BXYZ, workinc, 0 /* unused */);
// maybe mex_compute_init
}
//std::cerr << "compute_main: calling INFLUENCE compute for t=" << t << " rank=" << world_rank<<
// " tag:" << ord << std::endl;
pinfluence->compute(ord, 1.0); // just pass 1 coefficient
//std::cerr << "compute_main: returned from INFLUENCE compute for t=" << t << " rank=" << world_rank<< std::endl;
break;
case sourcevel_mask:
if (psourcevel == nullptr) {
psourcevel = new sourcevel_thread("SOURCEVEL", nthreads, nts, 2 * m, n,
WXYZ, BXYZ, workinc, workfactor);
}
// TODO - are all these coefficients always different? If not, we can save some transmission buffering
//std::cerr << "compute_main: calling SOURCEVEL compute for t=" << t << " rank=" << world_rank <<
// " tag:" << recv_status.MPI_TAG << std::endl;
psourcevel->compute(ord, precv, t);
break;
case wingwakeinf_mask:
if (pwingwakeinf == nullptr) {
pwingwakeinf = new wingwakeinf_thread ("wingwakeinf", nthreads, nts, 2 * m, n,
WXYZ, BXYZ, workinc, workfactor);
}
//outd("MUEA1check", sig, t);
//outd("MUEW1doubledcheck", sig2, t);
//std::cerr << "compute_main: calling wingwakeinf compute for t=" << t << " rank=" << world_rank << std::endl;
pwingwakeinf->compute(ord, precv, t);
break;
case wakeinfluence_mask:
if (pwakeinfluence == nullptr) {
pwakeinfluence = new wakeinfluence_thread ("WAKEINFLUENCE", nthreads, nts, 2 * m, n,
CXYZ,
//&WXYZ(0, 1, 0),
// #define WDIM 3, nts, n + 1
//&WXYZ[3 * nts], // TODO check: must skip 1st column
&WXYZ[3], // TODO check: must skip 1st column
workinc); // skip 1st row chord-wise
}
// TODO check offsets
//wakeinfluence_thread oWAKEINFLUENCE("WAKEINFLUENCE", nthreads, nts, 2 * m, n,
// CXYZ(0).memptr(),
// &WXYZ(0)(0, 1, 0), workinc); // skip 1st row chord-wise
// and
// oWAKEINFLUENCE.mex_thread_init(t, &MUEW1(1, 0), C1.memptr());
// mat MUEW1(nts, n); nts is low order, so (1,0) is offset by nts from start of sig
//outd("MUEW1check", sig3, t);
//std::cerr << "compute_main: calling WAKEINFLUENCE compute for t=" << t << std::endl;
//pwakeinfluence->compute(recv_status.MPI_TAG & ~MEX_MASK, &precv[nts], t);
pwakeinfluence->compute(ord, precv, t);
break;
default:
std::cerr << "Error in received data - cannot determine work type from " << recv_status.MPI_TAG << std::endl;
exit(1);
}
} // forever
}
#endif
int main(int argc, char **argv) {
const steady_clock::time_point start_time = steady_clock::now();
time_t ctime_start_time;
time(&ctime_start_time);
int world_size = 0;
#ifdef FSI_MPI
{
int provided;
int mpi_init_status = MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided);
if (mpi_init_status != MPI_SUCCESS) {
std::cerr << "ERROR: MPI_Init_thread fails with status=" << mpi_init_status << std::endl;
assert(mpi_init_status == MPI_SUCCESS);
exit(1);
}
assert(provided == MPI_THREAD_MULTIPLE);
if (mpi_init_status == MPI_SUCCESS) {
// Get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// Get the rank of the process
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
std::cerr << "started for rank " << world_rank << " PID:" << getpid() << std::endl;
if (MPI_TAG_UB != 0 && MPI_TAG_UB < wakeinfluence_mask) {
// Get the name of the processor
char processor_name[MPI_MAX_PROCESSOR_NAME + 1];
bzero(processor_name, sizeof(processor_name));
int name_len;
MPI_Get_processor_name(processor_name, &name_len);
std::cerr << "PLATFORM ERROR: for processor " << processor_name <<
", maximum tag size (" << MPI_TAG_UB <<
") for this platform is not compatible with this program (" <<
argv[0] <<
"). Report this to developers along with system architecture and word size." <<
std::endl;
}
}
}
#endif
pugi::xml_document doctop;
// validators appear to insist on an element acting as an envelope, however useless
pugi::xml_node doc = doctop.append_child("data");
assert(doc != nullptr);
doc.append_child("settings");
key_val_map_t key_val_map;
const bool daemon_mode = (argc > 0 && has_opt(argv, argv + argc, "-d"));
if (daemon_mode) { // take settings from standard inpout
std::cerr << "Running in daemon mode." << std::endl;
if (!parse_ini(cin, key_val_map)) {
std::cerr << "parse ini error from cin" << std::endl;
return 1;
}
} else {
//TODO this logic is broken - user should still use settings file if command line
// arguments - the existing code should give precedence to command line args
// parse_ini should be called regardless of whether command line args exist
if (argc < 2) { // no command line arguments
// find user settings
#ifdef Q_OS_WIN32
// TODO is this just a hack to get through init without a settings file in win32?
string string_default_settings(QDir::homePath().toStdString() + "/fsisettings.ini");
#else
string string_default_settings = getenv("HOME");
string_default_settings += SETTINGS_FILE_PATH SETTINGS_FILE_NAME;
#endif
const char *default_settings = string_default_settings.c_str();
// take settings path from command line or environment
//cerr << "default settings:" << default_settings << std::endl;
SETS(settings);
#ifndef Q_OS_WIN32
cerr << "Discovered settings:" << settings << std::endl;
//TODO still makes no sense for WIN32 platform
if (default_settings == settings) // no settings path found anywhere
// for win32, settings are done through windows registry, so inhibit warning here
cerr << "Standard settings file " << settings << " will be used." << std::endl;
else
cerr << "Settings file " << settings << " selected." << std::endl;
#endif
// populate our key/value map according to the settings file
{
int ret = parse_ini(settings.c_str(), key_val_map);
if (ret == -1) {
if (settings == default_settings) {
std::cerr << "No settings file found at " << settings << ": factory default settings will be used." << std::endl;
} else {
std::cerr << "No settings file found at " << settings << ": solver will terminate." << std::endl;
return 1;
}
} else if (ret == 0) {
std::cerr << "Parsing or open error in settings file: " << settings << std::endl;
return 1;
}
}
#ifdef Q_OS_WIN32
Xsettings_file = settings; // set globally for win32
#endif
std::cerr << FSI_NAME_settings " is " << settings << std::endl;
}
}
string datafilepath;
#ifdef _WIN32
//string string_default_datafilepath = QDir::homePath().toStdString();
QString qstring_default_datafilepath;
QStandardPaths::locate(QStandardPaths::AppDataLocation,
qstring_default_datafilepath,
QStandardPaths::LocateDirectory);
std::cerr << "home loc: " << QDir::homePath().toStdString() << std::endl;
{
auto locs = QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation);
qstring_default_datafilepath = locs[0];
//qstring_default_datafilepath = QDir::homePath() + "/AppData/Roaming/itcas/";
}
string string_default_datafilepath = qstring_default_datafilepath.toStdString();
string_default_datafilepath += "/itcas/";
#else
string string_default_datafilepath = getenv("HOME");
string_default_datafilepath += SETTINGS_FILE_PATH;
#endif
string_default_datafilepath += DATA_FILE_NAME;
const char *default_datafilepath = string_default_datafilepath.c_str();
SETS(datafilepath); // location of output file
string NASTRANpath;
const char *default_NASTRANpath = "";
SETS(NASTRANpath); // location of output file
//const double alfa = 0.0; // Angle of Attack (historical)
//const double AOA = alfa * pi / 180.0; // Angle of Attack radians (historical)
// input angular mesh adjustments and convert to radians (conversion automated)
SET(pitch); // pitch angle
SET(AOA); // Angle of Attack
SET(roll); // roll angle of the wing
SET(sweep); // Sweep angle of the wing
std::cerr << "AOA=" << AOA << " roll=" << roll << " sweep=" << sweep << std::endl;
const mat::fixed<3, 3> RotX1 = {{1, 0, 0},
{0, cos(roll), -sin(roll)},
{0, sin(roll), cos(roll)}},
RotY1 = {{cos(pitch), 0, -sin(pitch)},
{0, 1, 0},
{sin(pitch), 0, cos(pitch)}},
RotZ1 = {{cos(sweep), -sin(sweep), 0},
{sin(sweep), cos(sweep), 0},
{0, 0, 1}};
// Display each command-line argument.
if (world_rank <= 0) {
std::cerr << FSI_NAME_datafilepath " is " << datafilepath << std::endl;
std::cerr << "Command-line arguments (" << argc << "): ";
for (int count = 0; count < argc; count++)
std::cerr << argv[count] << " ";
//std::cerr << " argv[" << count << "] " << argv[count];
std::cerr << std::endl;
#ifndef _WIN32
extern void write_test(const string); // try to create path and test file and exit if failure
write_test(datafilepath);
#endif
}
int m_mesh = SETV(m), n_mesh = SETV(n); // first assign m,n accordding to regular input
cube XYZ(3, 2 * m_mesh + 2, n_mesh + 1); // boundary points
string mesh_str;
unsigned int nnodes = 0, nelems = 0;
if (NASTRANpath.length() > 0) { // read m, n, boundary points from NASTRAN file
read_NASTRAN(NASTRANpath, XYZ, nnodes, nelems, m_mesh, n_mesh);
mesh_str = read_file(NASTRANpath);
pugi::xml_attribute patt;
ATTRVAL(patt, "m", m_mesh); // if attribute already assigned, update, else append
ATTRVAL(patt, "n", n_mesh);
doc.child("settings").attribute("n").set_value(n_mesh);
}
const int m = m_mesh, // chord-wise panels
n = n_mesh; // span-wise panels
const uword mx2 = m * 2;
// defining global constants and wing geometry
SET(taper);
//%AR=5; // Aspect ratio of the wing
SET(c); // Root chord length in m
SET(rho); // Air density kg/m^3
SET(twist); // wing linear twist
SET(span); // Wing span
SET(T); // wing thickness(t),
SET(p); // maximum thickness from cord(p)
SET(M); // mean camber(m)
SET(nts); // Number of time steps
//const double Pinf = 101325.0; // Free stream pressure in pasacal
SET(Q); // freestream velocity
//const double Mach = Q / 343.0; // freestream mach number
SET(dxw); // wake shedding distance
//const double xf = 0.4 * c; // Distance from leading edge to pitching axis in m.
const double default_ydist = span * 0.2; // Distance of wing root from flapping axis. in m.
SET(ydist); // Distance of wing root from flapping axis. in m.
SET(Omega_rpm); // rotation speed in rpm
const double default_omegax = Omega_rpm / 60.0 * 2.0 * pi; // rotation speed in rad/s
SET(omegax); // rotation speed in rad/s
SET(tspc); // Number of time steps per cycle
const double default_ts = 60.0 / Omega_rpm / tspc; // Time step
SET(ts); // Time step
//const int ti = 0:ts:(nts-1)*ts;// time vector
SET(workinc);
SET(workfactor);
SET(nblades); // Number of blades
std::cerr << std::endl << "m=" << m << " n=" << n << " nts=" << nts << std::endl;
std::cerr << "nastran path=" << NASTRANpath << std::endl;
// TODO: putting the nastran read after the following statement results in errors in the read
// number of CPU threads to consume
#ifdef FSI_MPI
if (world_size <= 1) {
std::cerr << "ERROR: world size < 2 or solver was not run under MPI" << std::endl;
assert(world_size > 1);
exit(1);
}
const int nthreads = world_size - 1;
if (world_rank > 0) {
compute_main(m, n, nts, nthreads, workinc, workfactor);
MPI_Finalize();
return (0);
}
ATTR("nthreads") = to_string(nthreads).c_str(); // #threads came from MPI, so file setting manually
#else
#ifdef _WIN32
// returns 0 when not able to detect number of concurrent threads in hardware
const int default_nthreads = (thread::hardware_concurrency() == 0 ? 3 : thread::hardware_concurrency() - 1);
#else
//const int default_nthreads = 13;
const int default_nthreads = (thread::hardware_concurrency() > 1 ? thread::hardware_concurrency() - 1 : 1);
#endif
SET(nthreads);
world_size = nthreads + 1;
#endif
std::cerr << std::endl << "m=" << m << " n=" << n << " nts=" << nts << " nthreads=" << nthreads << " workinc=" << workinc << " workfactor=" << workfactor << std::endl;
ATTR("program") = argv[0];
#ifdef FSI_OPENMP
#ifdef FSI_STATS
for (int ithread = 0; ithread < nthreads; ithread++) {
thread_stat_map[ithread] = new mex_stat_map_t; // stats indexed first by thread
}
#endif
std::cerr << nthreads << " OpenMP threads will be requested.\n";
#else
// spawn POSIX threads for MPI and POSIX-only thread model
list<thread> all_threads;
for (int i = 0; i < nthreads; ++i) {
all_threads.push_back(thread(mex_thread_main, i + 1)); // rank of MPI tandem partner
}
for (auto &it: all_threads) {
#ifdef FSI_STATS
thread_stat_map[it.get_id()] = new mex_stat_map_t; // stats indexed first by thread
//cout << "thread_stat_map " << it.get_id() << " =" << thread_stat_map[it.get_id()] << std::endl;
#else
it.detach(); // no need to get thread ID later, so detach now
#endif
}
#ifdef FSI_MPI
std::cerr << nthreads << " POSIX threads started to pair with MPI threads.\n";
#else
std::cerr << nthreads << " POSIX threads started.\n";
#endif
#endif
std::cerr.precision(8);
size_t i, j;
vec ti(nts);
lspace(ti, 0, ts * (nts - 1));
//QString checked_val = qsettings.value(checked_var).toString();
if (NASTRANpath.length() > 0) { // read boundary points from NASTRAN file
//read_NASTRAN(NASTRANpath, XYZ);
// adding the wake panel grid
//angp = atan2(Zpanelgridu(m+1,1:n+1) - Zpanelgridu(m,1:n+1),Xpanelgridu(m+1,1:n+1) -Xpanelgridu(m,1:n+1));
//angp(j) = atan2(Zpanelgridu(m, j) - Zpanelgridu(m - 1, j),
// Xpanelgridu(m, j) - Xpanelgridu(m - 1, j));
//cube XYZ(3, 2 * m + 2, n + 1); // boundary points
vec angp(n + 1);
for (j = 0; j < n + 1; j++) {
//#define DEBUG_WAKE
#ifdef DEBUG_WAKE
std::cerr << "BP: " << XYZ(z, 2 * m, j) << " " << XYZ(z, 2 * m - 1, j) << " " <<
XYZ(x, 2 * m, j) << " " << XYZ(x, 2 * m - 1, j) << std::endl;
std::cerr << "diff: " << XYZ(z, 2 * m, j) - XYZ(z, 2 * m - 1, j) << " " <<
XYZ(x, 2 * m, j) - XYZ(x, 2 * m - 1, j) << std::endl;
#endif
angp(j) = atan2(XYZ(z, 2 * m, j) - XYZ(z, 2 * m - 1, j),
XYZ(x, 2 * m, j) - XYZ(x, 2 * m - 1, j));
}
XYZ.row(y) += ydist;
#ifdef DEBUG_WAKE
angp.raw_print(std::cerr, "angp=");
angp.raw_print(std::cerr, "ypline=");
#endif
//Xpanelgridu(m+2,1:n+1) =Xpanelgridu(m+1,1:n+1)+dxw*cos(angp(:,1:n+1));
//Ypanelgridu(m+2,1:n+1) =ypline(1:n+1);
//Zpanelgridu(m+2,1:n+1) =Zpanelgridu(m+1,1:n+1)+dxw*sin(angp(:,1:n+1));
vec ypline = linspace<vec>(-pi / 2, pi / 2, n + 1);
for (i = 0; i < NROWS(ypline); i++) {
ypline(i) = ydist + (sin(ypline(i)) + 1.0) / 2.0 * span; // Nonlinear span-wise spacing symmetry (- 0 +)
}
#ifdef DEBUG_WAKE
std::cerr << "ydist=" << ydist << " span=" << span << std::endl;
#endif
for (j = 0; j < n + 1; j++) {
//Xpanelgridu(m + 1, j) = Xpanelgridu(m, j) + dxw * cos(angp(j));
//Ypanelgridu(m + 1, j) = ypline(j);
//Zpanelgridu(m + 1, j) = Zpanelgridu(m, j) + dxw * sin(angp(j));
#ifdef DEBUG_WAKE
std::cerr << "wake XYZ(" << 2 * m + 1 << "," << j << ")=" << dxw * cos(angp(j)) <<
" " << ypline(j) << " " << dxw * sin(angp(j)) << std::endl;
#endif
XYZ(x, 2 * m + 1, j) = XYZ(x, 2 * m, j) + dxw * cos(angp(j));
XYZ(y, 2 * m + 1, j) = ypline(j);
XYZ(z, 2 * m + 1, j) = XYZ(z, 2 * m, j) + dxw * sin(angp(j));
}
// factor in rotations for AOA, sweep, roll
for (uword iy = 0; iy < XYZ.n_slices; iy++) {
for (uword ix = 0; ix < XYZ.n_cols; ix++) {
XYZ.COMP(ix, iy) = RotX1 * RotY1 * RotZ1 * XYZ.COMP(ix, iy); // apply rotations
}
}
} else { // generate boundary points
vec Xu(m + 1), Zu(m + 1), Xl(m + 1), Zl(m + 1);
{ // clean up namespace a little
vec x(m + 1), r(m + 1), beta(m + 1), zc(m + 1),
zt(NROWS(x));
lspace(beta, 0, pi);
for (i = 0; i < m + 1; i++) {
x(i) = c / 2.0 * (1.0 - cos(beta(i))); // cosine distribution of chord-wise panels
}
for (j = 0; j < NROWS(zc); j++) {
if ((x(j) / c >= 0) && (x(j) / c < p)) {
zc(j) = (M / (p * p)) * ((2 * p * x(j)) - (pow(x(j), 2) / c));
} else if ((x(j) / c >= p) && (x(j) / c <= 1)) {
zc(j) = (M * (c - x(j)) / pow((1 - p), 2)) * (1 - 2 * p + (x(j) / c));
}
}
for (j = 0; j < NROWS(x); j++) {
r(j) = (j == NROWS(x) - 1 ? 0 : atan2((zc(j + 1) - zc(j)), (x(j + 1) - x(j))));
}
for (i = 0; i < NROWS(zt); i++) {
zt(i) = (T / 0.2) * c *
(0.2969 * pow(x(i) / c, 0.5) -
0.126 * x(i) / c - 0.3516 * pow(x(i) / c, 2) +
0.2843 * pow(x(i) / c, 3) - 0.1036 * pow(x(i) / c, 4));
}
for (i = 0; i < NROWS(x); i++) {
Xu(i) = x (i) - zt(i) * sin(r(i));
Zu(i) = zc(i) + zt(i) * cos(r(i));
Xl(i) = x (i) + zt(i) * sin(r(i));
Zl(i) = zc(i) - zt(i) * cos(r(i));
}
}
mat Xpanelgridu(m + 2, n + 1), Ypanelgridu(m + 2, n + 1), Zpanelgridu(m + 2, n + 1),
Xpanelgridl(m + 1, n + 1), Ypanelgridl(m + 1, n + 1), Zpanelgridl(m + 1, n + 1),
Xpanelgridl1(m + 1, n + 1), Zpanelgridl1(m + 1, n + 1),
Xpanelgridu1(m + 1, n + 1), Zpanelgridu1(m + 1, n + 1);
ZERO(Xpanelgridu); ZERO(Ypanelgridu); ZERO(Zpanelgridu);
ZERO(Xpanelgridl); ZERO(Ypanelgridl); ZERO(Zpanelgridl);
mat Span_dez(m + 1, n + 1);
vec ypline = linspace<vec>(-pi / 2, pi / 2, n + 1);
for (i = 0; i < NROWS(ypline); i++) {
ypline(i) = ydist + (sin(ypline(i)) + 1.0) / 2.0 * span; // Nonlinear span-wise spacing symmetry (- 0 +)
}
for (j = 0; j < n + 1; j++) {
for (i = 0; i < m + 1; i++) {
Span_dez(i, j) = ypline(j) - ydist;
// grid for upper surface of the wing
Ypanelgridu(i, j) = ypline(j);
Xpanelgridu(i, j) = Xu(i);
Zpanelgridu(i, j) = Zu(i);
// grid for lower surface of the wing
Ypanelgridl(i, j) = ypline(j);
Xpanelgridl(i, j) = Xl(i);
Zpanelgridl(i, j) = Zl(i);
}
}
// defining the wing twist, wing taper and wing sweep
mat L_Twistl(m + 1, n + 1), L_Twistu(m + 1, n + 1);
for (j = 0; j < n + 1; j++) {
for (i = 0; i < m + 1; i++) {
// Apply linear twist (L_Twist)
L_Twistl(i, j) = twist * (1.0 - Span_dez(i, j) / span);
Zpanelgridl1(i, j) =
Zpanelgridl(i, j) * cos(L_Twistl(i, j)) -
Xpanelgridl(i, j) * sin(L_Twistl(i, j));
Xpanelgridl1(i, j) =
Xpanelgridl(i, j) * cos(L_Twistl(i, j)) +
Zpanelgridl(i, j) * sin(L_Twistl(i, j));
Xpanelgridl(i, j) = Xpanelgridl1(i, j);
Zpanelgridl(i, j) = Zpanelgridl1(i, j);
L_Twistu(i, j) = twist * (1 - Span_dez(i, j) / span);
Zpanelgridu1(i, j) =
Zpanelgridu(i, j) * cos(L_Twistu(i, j)) -
Xpanelgridu(i, j) * sin(L_Twistu(i, j));
Xpanelgridu1(i, j) =
Xpanelgridu(i, j) * cos(L_Twistu(i, j)) +
Zpanelgridu(i, j) * sin(L_Twistu(i, j));
Xpanelgridu(i, j) = Xpanelgridu1(i, j);
Zpanelgridu(i, j) = Zpanelgridu1(i, j);
// Apply linear taper (backward taper)
// Apply linear taper (forward taper)
Zpanelgridl(i, j) *= 1.0 + (taper - 1.0) / span * (Span_dez(i, j));
Xpanelgridl(i, j) *= 1.0 + (taper - 1.0) / span * (Span_dez(i, j));
Zpanelgridu(i, j) *= 1.0 + (taper - 1.0) / span * (Span_dez(i, j));
Xpanelgridu(i, j) *= 1.0 + (taper - 1.0) / span * (Span_dez(i, j));
Xpanelgridl(i, j) += Span_dez(i, j) * tan(atan2((1 - taper) * c, span));
Xpanelgridu(i, j) += Span_dez(i, j) * tan(atan2((1 - taper) * c, span));
// Apply wing sweep
Xpanelgridl(i, j) += Span_dez(i, j) * tan(sweep);
Xpanelgridu(i, j) += Span_dez(i, j) * tan(sweep);
}
}