-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathMoorDyn2.cpp
More file actions
3412 lines (3099 loc) · 101 KB
/
Copy pathMoorDyn2.cpp
File metadata and controls
3412 lines (3099 loc) · 101 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
/*
* Copyright (c) 2022, Matt Hall
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// This is version 2.a5, 2021-03-16
#include "MoorDyn2.h"
#include "Misc.hpp"
#include "MoorDyn2.hpp"
#include "Rod.hpp"
#include "leanvtk/leanvtk.hpp"
#include <atomic>
#include <iomanip>
#include <filesystem>
#ifdef LINUX
#include <cmath>
#include <ctype.h>
// contributed by Yi-Hsiang Yu at NREL
#define isnan(x) std::isnan(x)
#endif
using namespace std;
// Formating constants for rod files outputs (iomanip)
constexpr int WIDTH = 20; // Width for output
constexpr int PRECISION = 7; // Precision for output
/**
* @brief A helper function for getting the size of a vector as an unsigned int
*
* @tparam T
* @param a Vector to get size of
* @return unsigned int Size of vector (truncated to lower sizeof(unsigned int)
* bytes)
*/
template<typename T>
unsigned int
ui_size(const std::vector<T>& a)
{
return static_cast<unsigned int>(a.size());
}
namespace moordyn {
/// The list of units for the output
const char* UnitList[] = {
"s", // 0: Time
"m", "m", "m", // 1: PosX 2: PosY 3: PosZ
"deg", "deg", "deg", // 4: RX 5: RY 6: RZ
"m/s", "m/s", "m/s", // 7: VelX 8: VelY 9: VelZ
"deg/s", "deg/s", "deg/s", // 10: RVelX 11: RVelY 12: RVelZ
"m/s^2", "m/s^2", "m/s^2", // 13: AccX 14: AccY 15: AccZ
"deg/s^2", "deg/s^2", "deg/s^2", // 16: RAccX 17: RAccY 18: RAccZ
"N", // 19: Ten
"N", "N", "N", // 20: FX 21: FY 22: FZ
"N*m", "N*m", "N*m", // 23: MX 24: MY 25: MZ
"(frac)" // 26: Sub
};
std::atomic<size_t> __systems_counter(0);
moordyn::MoorDyn::MoorDyn(const char* infilename, int log_level)
: io::IO(NULL)
, _filepath("Mooring/lines.txt")
, _basename("lines")
, _basepath("Mooring/")
, ICDfac(5.0)
, ICdt(1.0)
, ICTmax(120.0)
, ICthresh(0.001)
, WaveKinTemp(waves::WAVES_NONE)
, dtM0((std::numeric_limits<real>::max)())
, cfl(0.5)
, dtOut(0.0)
, _t_integrator(NULL)
, ICgenDynamic(false)
, ICfile("")
, env(std::make_shared<EnvCond>())
, GroundBody(NULL)
, waves(nullptr)
, seafloor(nullptr)
, npW(0)
{
++__systems_counter;
SetLogger(new Log(log_level));
if (infilename && (strlen(infilename) > 0)) {
_filepath = infilename;
const std::size_t lastSlash = _filepath.find_last_of("/\\");
const std::size_t lastDot = _filepath.find_last_of('.');
_basename = _filepath.substr(lastSlash + 1, lastDot - lastSlash - 1);
_basepath = _filepath.substr(0, lastSlash + 1);
}
LOGMSG << "\n Running MoorDyn (v" << MOORDYN_MAJOR_VERSION << "."
<< MOORDYN_MINOR_VERSION << "." << MOORDYN_PATCH_VERSION << ")"
<< endl
<< " MoorDyn v2 has significant ongoing input file changes "
"from v1."
<< endl
<< " Copyright: (C) 2024 National Renewable Energy Laboratory, "
"(C) 2014-2019 Matt Hall"
<< endl
<< " This program is released under the BSD 3-Clause license."
<< endl;
LOGMSG << "The filename is " << _filepath << endl;
LOGDBG << "The basename is " << _basename << endl;
LOGDBG << "The basepath is " << _basepath << endl;
env->g = 9.80665;
env->WtrDpth = 0.;
env->rho_w = 1025.;
env->kb = 3.0e6;
env->cb = 3.0e5;
env->waterKinOptions = waves::WaterKinOptions();
env->WriteUnits = 1; // by default, write units line
env->writeLog = 0; // by default, don't write out a log file
env->FrictionCoefficient = 0.0;
env->FricDamp = 200.0;
env->StatDynFricScale = 1.0;
waves = std::make_shared<moordyn::Waves>(_log);
const moordyn::error_id err = ReadInFile();
if (err != MOORDYN_SUCCESS) {
delete GetLogger();
}
MOORDYN_THROW(err, "Exception while reading the input file");
LOGDBG << "MoorDyn is expecting " << NCoupledDOF()
<< " coupled degrees of freedom" << endl;
}
moordyn::MoorDyn::~MoorDyn()
{
if (outfileMain.is_open())
outfileMain.close();
for (auto outfile : outfiles) // int l=0; l<nLines; l++)
if (outfile && outfile->is_open())
outfile->close();
delete _t_integrator;
delete GroundBody;
for (auto obj : LinePropList)
delete obj;
for (auto obj : RodPropList)
delete obj;
for (auto obj : FailList)
delete obj;
for (auto obj : BodyList)
delete obj;
for (auto obj : RodList)
delete obj;
for (auto obj : PointList)
delete obj;
for (auto obj : LineList)
delete obj;
delete GetLogger();
if (--__systems_counter == 0) {
reset_instance_ids();
}
}
moordyn::error_id
moordyn::MoorDyn::icLegacy()
{
moordyn::error_id err = MOORDYN_SUCCESS;
string err_msg;
// dtIC set to fraction of input so convergence is over dtIC (as described
// in docs)
const unsigned int convergence_iters = 9; // 10 iterations, indexed 0-9
ICdt = ICdt / (convergence_iters + 1);
try {
_t_integrator->Init();
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
if (ICfile != "") {
try {
_t_integrator->LoadState(_basepath + ICfile);
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
}
LOGMSG << "Finalizing ICs using dynamic solve (" << ICDfac
<< "X normal drag)" << endl;
for (auto obj : LineList)
obj->scaleDrag(ICDfac);
for (auto obj : PointList)
obj->scaleDrag(ICDfac);
for (auto obj : RodList)
obj->scaleDrag(ICDfac);
for (auto obj : BodyList)
obj->scaleDrag(ICDfac);
// vector to store tensions for analyzing convergence
vector<real> FairTens(LineList.size(), 0.0);
vector<real> FairTensLast_col(convergence_iters, 0.0);
for (unsigned int i = 0; i < convergence_iters; i++)
FairTensLast_col[i] = 1.0 * i;
vector<vector<real>> FairTensLast(LineList.size(), FairTensLast_col);
unsigned int iic = 1; // To match MDF indexing
real t = 0;
bool converged = true;
real max_error = 0.0;
unsigned int max_error_line = 0;
real best_score = (std::numeric_limits<real>::max)();
real best_score_t = 0.0;
unsigned int best_score_line = 0;
ICdt = ICdt / (convergence_iters + 1);
while ((ICTmax - t) > (std::numeric_limits<real>::min)()) {
// Integrate one ICD timestep (ICdt)
real t_target = ICdt;
real dt;
_t_integrator->Next();
while ((dt = t_target) > 0.0) {
if (dtM0 < dt)
dt = dtM0;
try {
_t_integrator->Step(dt);
t = _t_integrator->GetTime();
t_target -= dt;
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS) {
LOGERR << "Dynam Relax t = " << t << " s: " << err_msg << endl;
return err;
}
}
// Roll previous fairlead tensions for comparison
for (unsigned int lf = 0; lf < LineList.size(); lf++) {
for (int pt = convergence_iters - 1; pt > 0; pt--)
FairTensLast[lf][pt] = FairTensLast[lf][pt - 1];
FairTensLast[lf][0] = FairTens[lf];
}
// go through points to get fairlead forces
for (unsigned int lf = 0; lf < LineList.size(); lf++)
FairTens[lf] =
LineList[lf]->getNodeTen(LineList[lf]->getN()).norm();
// check for convergence (compare current tension at each fairlead with
// previous convergence_iters-1 values)
if (iic > convergence_iters) {
// check for any non-convergence, and continue to the next time step
// if any occurs
converged = true;
max_error = 0.0;
for (unsigned int lf = 0; lf < LineList.size(); lf++) {
for (unsigned int pt = 0; pt < convergence_iters; pt++) {
const real error =
abs(FairTens[lf] / FairTensLast[lf][pt] - 1.0);
if (error > max_error) {
max_error = error;
max_error_line = LineList[lf]->number;
}
}
}
if (max_error < best_score) {
best_score = max_error;
best_score_t = t;
best_score_line = max_error_line;
}
if (max_error > ICthresh) {
converged = false;
LOGDBG << "Dynamic relaxation t = " << t << "s (time step "
<< iic << "), error = " << 100.0 * max_error
<< "% on line " << max_error_line << " \r";
}
if (converged)
break;
}
iic++;
}
if (converged) {
LOGMSG << "Fairlead tensions converged" << endl;
} else {
LOGWRN << "Fairlead tensions did not converge" << endl;
}
LOGMSG << "Remaining error after " << t << " s = " << 100.0 * max_error
<< "% on line " << max_error_line << endl;
if (!converged) {
LOGMSG << "Best score at " << best_score_t
<< " s = " << 100.0 * best_score << "% on line "
<< best_score_line << endl;
}
// We are setting the timer again later, but better doing it here as well,
// so no regressions might happens on the subinstances setTime() callings
_t_integrator->SetTime(0.0);
// restore drag coefficients to normal values and restart time counter of
// each object
for (auto obj : LineList) {
obj->scaleDrag(1.0 / ICDfac);
obj->setTime(0.0);
}
for (auto obj : PointList)
obj->scaleDrag(1.0 / ICDfac);
for (auto obj : RodList) {
obj->scaleDrag(1.0 / ICDfac);
obj->setTime(0.0);
}
for (auto obj : BodyList)
obj->scaleDrag(1.0 / ICDfac);
return MOORDYN_SUCCESS;
}
moordyn::error_id
moordyn::MoorDyn::icStationary()
{
moordyn::error_id err = MOORDYN_SUCCESS;
string err_msg;
real t = 0;
real error_prev = (std::numeric_limits<real>::max)();
real error = (std::numeric_limits<real>::max)();
real error0 = error;
real best_score = (std::numeric_limits<real>::max)();
real best_score_t = 0.0;
LOGMSG << "Finalizing ICs using static solve" << endl;
time::StationaryScheme t_integrator(_log, waves);
t_integrator.SetGround(GroundBody);
for (auto obj :
BodyList) // TODO: make these lists only iterate over the free lines.
// Check other places where this is called
t_integrator.AddBody(obj);
for (auto obj : RodList)
t_integrator.AddRod(obj);
for (auto obj : PointList)
t_integrator.AddPoint(obj);
for (auto obj : LineList)
t_integrator.AddLine(obj);
t_integrator.SetCFL((std::min)(cfl, 1.0));
try {
t_integrator.Init();
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
if (ICfile != "") {
try {
t_integrator.LoadState(_basepath + ICfile);
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
}
auto n_states = t_integrator.NStates();
while ((ICTmax - t) > (std::numeric_limits<real>::min)()) {
// Integrate one ICD timestep (ICdt)
real t_target = ICdt;
real dt;
t_integrator.Next();
while ((dt = t_target) > 0.0) {
if (dtM0 < dt)
dt = dtM0;
try {
t_integrator.Step(dt);
error = t_integrator.Error();
if (!t)
error0 = error;
t = t_integrator.GetTime();
t_target -= dt;
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS) {
LOGERR << "t = " << t << " s" << endl;
return err;
}
}
if (error < best_score) {
best_score = error;
best_score_t = t;
}
const real error_rel = error / error0;
const real error_deriv = std::abs(error_prev - error) / error_prev;
if (!error || (error_rel < ICthresh) || (error_deriv < ICthresh))
break;
error_prev = error;
LOGDBG << "Stationary solution t = " << t << "s, "
<< "error avg = " << error / n_states << " m/s2, "
<< "error change = " << 100.0 * error_deriv << "% \r";
}
_t_integrator->SetState(t_integrator.GetState());
LOGMSG << "Remaining error after " << t << " s = " << error / n_states
<< " m/s2" << endl;
LOGMSG << "Best score at " << best_score_t
<< " s = " << best_score / n_states << " m/s2" << endl;
return MOORDYN_SUCCESS;
}
moordyn::error_id
moordyn::MoorDyn::Init(const double* x, const double* xd, bool skip_ic)
{
moordyn::error_id err = MOORDYN_SUCCESS;
string err_msg;
if (NCoupledDOF() && !x) {
LOGERR << "ERROR: "
<< "MoorDyn::Init received a Null position vector, "
<< "but " << NCoupledDOF() << "components are required" << endl;
}
// <<<<<<<<< need to add bodys
// ------------------ do static bodies and lines ---------------------------
LOGMSG << "Creating mooring system..." << endl;
// call ground body to update all the fixed things...
GroundBody->initializeUnfreeBody();
// initialize fixed bodies and attached objects
for (auto l : FixedBodyIs) {
BodyList[l]->initializeUnfreeBody(BodyList[l]->body_r6, vec6::Zero());
}
// initialize coupled objects based on passed kinematics
int ix = 0;
for (auto l : CpldBodyIs) {
LOGMSG << "Initializing coupled Body " << l + 1 << " at " << x[ix]
<< ", " << x[ix + 1] << ", " << x[ix + 2] << "..." << endl;
// BUG: These conversions will not be needed in the future
vec6 r, rd;
if (BodyList[l]->type == Body::COUPLED) {
moordyn::array2vec6(x + ix, r);
moordyn::array2vec6(xd + ix, rd);
ix += 6;
} else {
// for pinned body 3 entries will be taken
vec3 r3, rd3, rdd3;
moordyn::array2vec(x + ix, r3);
r(Eigen::seqN(0, 3)) = r3;
moordyn::array2vec(xd + ix, rd3);
rd(Eigen::seqN(0, 3)) = rd3;
ix += 3;
}
BodyList[l]->initializeUnfreeBody(r, rd, vec6::Zero());
}
for (auto l : CpldRodIs) {
LOGMSG << "Initializing coupled Rod " << l + 1 << " at " << x[ix]
<< ", " << x[ix + 1] << ", " << x[ix + 2] << "..." << endl;
vec6 r, rd, rdd;
if (RodList[l]->type == Rod::COUPLED) {
// for cantilevered rods 6 entries will be taken
moordyn::array2vec6(x + ix, r);
moordyn::array2vec6(xd + ix, rd);
ix += 6;
} else {
// for pinned rods 3 entries will be taken
vec3 r3, rd3, rdd3;
moordyn::array2vec(x + ix, r3);
r(Eigen::seqN(0, 3)) = r3;
moordyn::array2vec(xd + ix, rd3);
rd(Eigen::seqN(0, 3)) = rd3;
ix += 3;
}
RodList[l]->initiateStep(r, rd, vec6::Zero());
RodList[l]->updateFairlead(0.0);
// call this just to set up the output file header
RodList[l]->initialize();
}
for (auto l : CpldPointIs) {
LOGMSG << "Initializing coupled Point " << l + 1 << " at " << x[ix]
<< ", " << x[ix + 1] << ", " << x[ix + 2] << endl;
vec r, rd;
moordyn::array2vec(x + ix, r);
moordyn::array2vec(xd + ix, rd);
PointList[l]->initiateStep(r, rd);
try {
PointList[l]->updateFairlead(0.0);
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS) {
LOGERR << "Error initializing coupled point" << l << ": " << err_msg
<< endl;
return err;
}
// call this just to set WaterKin (may also set up output file in
// future)
PointList[l]->initialize();
ix += 3;
}
if (dtM0 < (0.9 * (std::numeric_limits<real>::max)()))
cfl = (std::numeric_limits<real>::max)(); // Is 90% of max sufficient
// tolerance for this check?
// Compute the timestep
for (auto obj : LineList)
dtM0 = (std::min)(dtM0, obj->cfl2dt(cfl));
for (auto obj : PointList)
dtM0 = (std::min)(dtM0, obj->cfl2dt(cfl));
for (auto obj : RodList)
dtM0 = (std::min)(dtM0, obj->cfl2dt(cfl));
for (auto obj : BodyList)
dtM0 = (std::min)(dtM0, obj->cfl2dt(cfl));
// And get the resulting CFL
cfl = 0.0;
for (auto obj : LineList)
cfl = (std::max)(cfl, obj->dt2cfl(dtM0));
for (auto obj : PointList)
cfl = (std::max)(cfl, obj->dt2cfl(dtM0));
for (auto obj : RodList)
cfl = (std::max)(cfl, obj->dt2cfl(dtM0));
for (auto obj : BodyList)
cfl = (std::max)(cfl, obj->dt2cfl(dtM0));
LOGMSG << "dtM = " << dtM0 << " s (CFL = " << cfl << ")" << endl;
// Initialize the system state
_t_integrator->SetCFL(cfl);
// ------------------ do IC gen --------------------
if (!skip_ic) {
for (unsigned int l = 0; l < LineList.size(); l++) {
LineList[l]->IC_gen = true; // turn on IC_gen flag
}
moordyn::error_id err;
if (ICgenDynamic)
err = icLegacy();
else
err = icStationary();
if (err != MOORDYN_SUCCESS)
return err;
for (unsigned int l = 0; l < LineList.size(); l++) {
LineList[l]->IC_gen = false; // turn off IC_gen flag
}
} else {
try {
_t_integrator->Init();
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
if (ICfile != "") {
try {
_t_integrator->LoadState(_basepath + ICfile);
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
}
}
_t_integrator->SetTime(0.0);
// store passed WaveKin value to enable waves in simulation if applicable
// (they're not enabled during IC gen)
env->waterKinOptions.waveMode = WaveKinTemp;
try {
// TODO - figure out how i want to do this better
// because this is horrible. the solution is probably to move EnvCond
// to its own .hpp and .cpp file so that it can contain the Seafloor and
// can itself be queries about the seafloor in general
real tmp = env->WtrDpth;
if (seafloor) {
env->WtrDpth = -seafloor->getAverageDepth();
}
LOGMSG << "Water kinematics for runtime:" << endl;
waves->setup(env, seafloor, _t_integrator, _basepath.c_str());
env->WtrDpth = tmp;
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
// @mth: new approach to be implemented
// ------------------------- calculate wave time series if needed
// -------------------
// if (env->WaveKin == 2)
// {
// for (int l=0; l<LineList.size(); l++)
// LineList[l]->makeWaveKinematics( 0.0 );
// }
// -------------------------- start main output file
// --------------------------------
stringstream oname;
oname << _basepath << _basename << ".out";
outfileMain.open(oname.str());
if (!outfileMain.is_open()) {
LOGERR << "ERROR: Unable to write to main output file " << oname.str()
<< endl;
return MOORDYN_INVALID_OUTPUT_FILE;
}
// --- channel titles ---
outfileMain << setw(10) << right
<< "Time";
for (auto channel : outChans)
outfileMain << setw(WIDTH) << right << channel.Name;
outfileMain << endl;
if (env->WriteUnits > 0) {
// --- units ---
outfileMain << setw(10) << right
<< "(s)";
for (auto channel : outChans)
outfileMain << setw(WIDTH) << right
<< channel.Units;
outfileMain << "\n";
}
// write t=0 output
return WriteOutputs(0.0, 0.0);
}
moordyn::error_id DECLDIR
moordyn::MoorDyn::Step(const double* x,
const double* xd,
double* f,
double& t,
double& dt)
{
// should check if wave kinematics have been set up if expected!
if (!disableOutput) {
const auto default_precision{ std::cout.precision() };
std::cout << std::fixed << setprecision(1);
LOGDBG << "t = " << t << "s \r";
std::cout << std::defaultfloat << setprecision(default_precision);
if (!disableOutTime)
cout << "\rt = " << t << " " << flush;
}
if (dt <= 0) {
// Nothing to do, just recover the forces if there are coupled DOFs
if (NCoupledDOF())
return GetForces(f);
else
return MOORDYN_SUCCESS;
}
if (NCoupledDOF() && (!x || !xd || !f)) {
LOGERR << "Null Pointer received in " << __FUNC_NAME__ << " ("
<< XSTR(__FILE__) << ":" << __LINE__ << ")" << endl;
}
unsigned int ix = 0;
// ---------------- set positions and velocities -----------------------
// ... of any coupled bodies, rods, and points at this instant, to be
// used later for extrapolating motions
for (auto l : CpldBodyIs) {
// BUG: These conversions will not be needed in the future
vec6 r, rd, rdd;
const vec6 rd_b = BodyList[l]->getUnfreeVel();
if (BodyList[l]->type == Body::COUPLED) {
moordyn::array2vec6(x + ix, r);
moordyn::array2vec6(xd + ix, rd);
// determine acceleration
rdd = (rd - rd_b) / dt;
ix += 6;
} else {
// for pinned body 3 entries will be taken
vec3 r3, rd3, rdd3;
moordyn::array2vec(x + ix, r3);
r(Eigen::seqN(0, 3)) = r3;
moordyn::array2vec(xd + ix, rd3);
rd(Eigen::seqN(0, 3)) = rd3;
// determine acceleration
rdd(Eigen::seqN(0, 3)) = (rd3 - rd_b.head<3>()) / dt;
ix += 3;
}
// acceleration required for inertial terms
BodyList[l]->initiateStep(r, rd, rdd);
}
for (auto l : CpldRodIs) {
vec6 r, rd, rdd;
const vec6 rd_r = RodList[l]->getUnfreeVel();
if (RodList[l]->type == Rod::COUPLED) {
// for cantilevered rods 6 entries will be taken
moordyn::array2vec6(x + ix, r);
moordyn::array2vec6(xd + ix, rd);
// determine acceleration
rdd = (rd - rd_r) / dt;
ix += 6;
} else {
// for pinned rods 3 entries will be taken
vec3 r3, rd3, rdd3;
moordyn::array2vec(x + ix, r3);
r(Eigen::seqN(0, 3)) = r3;
moordyn::array2vec(xd + ix, rd3);
rd(Eigen::seqN(0, 3)) = rd3;
// determine acceleration
rdd(Eigen::seqN(0, 3)) = (rd3 - rd_r.head<3>()) / dt;
ix += 3;
}
// acceleration required for inertial terms
RodList[l]->initiateStep(r, rd, rdd);
}
for (auto l : CpldPointIs) {
vec r, rd;
moordyn::array2vec(x + ix, r);
moordyn::array2vec(xd + ix, rd);
PointList[l]->initiateStep(r, rd);
ix += 3;
}
// -------------------- do time stepping -----------------------
real t_target = dt;
real dt_step;
_t_integrator->Next();
while ((dt_step = t_target) > 0.0) {
if (dtM0 < dt_step)
dt_step = dtM0;
moordyn::error_id err = MOORDYN_SUCCESS;
string err_msg;
try {
_t_integrator->Step(dt_step);
t = _t_integrator->GetTime();
t_target -= dt_step;
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS) {
LOGERR << "t = " << t << " s: " << err_msg << endl;
return err;
}
}
// --------------- check for line failures (detachments!) ----------------
// step 1: check for time-triggered failures
for (unsigned int l = 0; l < FailList.size(); l++) {
auto failure = FailList[l];
if (failure->status || (failure->time < t))
continue;
LOGMSG << "Failure number " << l + 1 << " triggered at time " << t
<< " s" << endl;
moordyn::error_id err = MOORDYN_SUCCESS;
string err_msg;
try {
detachLines(failure);
}
MOORDYN_CATCHER(err, err_msg);
if (err != MOORDYN_SUCCESS)
return err;
}
// step 2: check for tension-triggered failures (this will require
// specifying max tension things)
// ------------------------ write outputs --------------------------
const moordyn::error_id err = WriteOutputs(t, dt);
if (err != MOORDYN_SUCCESS)
return err;
// recover the forces if there are coupled DOFs
if (NCoupledDOF())
return GetForces(f);
else
return MOORDYN_SUCCESS;
}
void
MoorDyn::BreakLine(moordyn::Point* point, moordyn::Line* line)
{
// Detach the line from the point
moordyn::EndPoints end_point;
auto pt_attachments = point->getLines();
for (auto attachment : pt_attachments) {
if (attachment.line == line) {
end_point = attachment.end_point;
}
}
point->removeLine(line);
// Create the new point
moordyn::Point *pt = new Point(point, PointList.size());
PointList.push_back(pt);
waves->addPoint(pt);
_t_integrator->AddPoint(pt);
// Set the state of the point
auto state = _t_integrator->r(0);
pt->initialize(state->get(pt));
for (unsigned int i = 1; i < _t_integrator->GetNState(); i++) {
_t_integrator->r(i)->get(pt) = state->get(pt);
}
for (unsigned int i = 0; i < _t_integrator->GetNDeriv(); i++) {
_t_integrator->rd(i)->get(pt).row(0)(Eigen::seqN(0, 3)) =
state->get(pt).row(0)(Eigen::seqN(3, 3));
// NOTE: Although when cloning free points we can actually get the
// acceleration, I (Jose Luis Cercos-Pita) do not think is worthy, so
// I am simply setting no acceleration
_t_integrator->rd(i)->get(pt).row(0)(Eigen::seqN(3, 3)) = vec::Zero();
}
// Attach the line to the point
pt->addLine(line, end_point);
}
std::vector<uint64_t>
MoorDyn::Serialize(void)
{
std::vector<uint64_t> data, subdata;
data.push_back(io::IO::Serialize((uint64_t)npW));
// Ask to save the data off all the subinstances
subdata = _t_integrator->Serialize();
data.insert(data.end(), subdata.begin(), subdata.end());
for (auto body : BodyList) {
subdata = body->Serialize();
data.insert(data.end(), subdata.begin(), subdata.end());
}
for (auto rod : RodList) {
subdata = rod->Serialize();
data.insert(data.end(), subdata.begin(), subdata.end());
}
for (auto point : PointList) {
subdata = point->Serialize();
data.insert(data.end(), subdata.begin(), subdata.end());
}
for (auto line : LineList) {
subdata = line->Serialize();
data.insert(data.end(), subdata.begin(), subdata.end());
}
return data;
}
uint64_t*
MoorDyn::Deserialize(const uint64_t* data)
{
uint64_t* ptr = (uint64_t*)data;
uint64_t n;
ptr = io::IO::Deserialize(ptr, n);
npW = n;
// Load the children data also
ptr = _t_integrator->Deserialize(ptr);
for (auto body : BodyList) {
ptr = body->Deserialize(ptr);
}
for (auto rod : RodList) {
ptr = rod->Deserialize(ptr);
}
for (auto point : PointList) {
ptr = point->Deserialize(ptr);
}
for (auto line : LineList) {
ptr = line->Deserialize(ptr);
}
return ptr;
}
void
MoorDyn::saveVTK(const char* filename) const
{
// First, check that the filename has an extension, or append it otherwise
filesystem::path filepath(filename);
std::string extension = filepath.extension().u8string();
if (extension.empty()) {
LOGWRN << "Extension will be added to the output file: '"
<< filename << ".vtm'" << endl;
filepath = filesystem::path(std::string(filename) + ".vtm").u8string();
}
// Now create a folder for the subentities
std::string prefix = filepath.parent_path().u8string();
std::string stem = filepath.stem().u8string();
if (prefix.empty())
prefix = stem;
else
prefix = prefix + "/" + stem;
try {
filesystem::create_directory(prefix);
} catch (std::filesystem::filesystem_error& e) {
// We are ok, let's the writters complain just in case
}
// Time to write the subentities
prefix = prefix + "/" + stem + "_";
std::vector<leanvtk::VTKWriter*> vtks;
for (auto body : BodyList) {
body->saveVTK((prefix + std::to_string(vtks.size()) + ".vtp").c_str());
vtks.push_back((leanvtk::VTKWriter*)body->getVTK());
}
for (auto point : PointList) {
point->saveVTK((prefix + std::to_string(vtks.size()) + ".vtp").c_str());
vtks.push_back((leanvtk::VTKWriter*)point->getVTK());
}
for (auto rod : RodList) {
rod->saveVTK((prefix + std::to_string(vtks.size()) + ".vtp").c_str());
vtks.push_back((leanvtk::VTKWriter*)rod->getVTK());
}
for (auto line : LineList) {
line->saveVTK((prefix + std::to_string(vtks.size()) + ".vtp").c_str());
vtks.push_back((leanvtk::VTKWriter*)line->getVTK());
}
if (!write_vtm(filepath.u8string(), vtks)) {
throw moordyn::output_file_error((
std::string("Failure saving the system VTM file '") +
filepath.u8string() +
"'").c_str());
}
}
moordyn::error_id
moordyn::MoorDyn::ReadInFile()
{
int i = 0;
vector<string> in_txt;
if (readFileIntoBuffers(in_txt) != MOORDYN_SUCCESS) {
return MOORDYN_INVALID_INPUT_FILE;
}
// We are really interested in looking for the writeLog option, to start
// logging as soon as possible
if ((i = findStartOfSection(in_txt, { "OPTIONS" })) != -1) {
LOGDBG << " Reading options:" << endl;
// Parse options until the next header or the end of the file
while ((in_txt[i].find("---") == string::npos) &&
(i < (int)in_txt.size())) {
vector<string> entries = moordyn::str::split(in_txt[i], ' ');
if (entries.size() < 2) {
i++;
continue;
}
const string value = entries[0];
const string name = entries[1];
if (name == "writeLog") {
env->writeLog = atoi(value.c_str());
const moordyn::error_id err = SetupLog();
if (err != MOORDYN_SUCCESS)
return err;
break;
}
i++;
}
}
// Now we can read all the options
if ((i = findStartOfSection(in_txt, { "OPTIONS" })) != -1) {
LOGDBG << " Reading options:" << endl;
// Parse options until the next header or the end of the file
while ((in_txt[i].find("---") == string::npos) &&
(i < (int)in_txt.size())) {
vector<string> entries = moordyn::str::split(in_txt[i], ' ');
if (entries.size() < 2) {
i++;