-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathLinearWaveBody.cc
2465 lines (2090 loc) · 82.9 KB
/
LinearWaveBody.cc
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 Rhys Mainwaring
//
// 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 <https://www.gnu.org/licenses/>.
#include "LinearWaveBody.hh"
#include <gz/common/Profiler.hh>
#include <gz/common/SystemPaths.hh>
#include <gz/msgs/wrench.pb.h>
#include <gz/math/Matrix6.hh>
#include <gz/plugin/Register.hh>
#include <gz/transport.hh>
#include <gz/sim/components/AngularVelocity.hh>
#include <gz/sim/components/Collision.hh>
#include <gz/sim/components/Inertial.hh>
#include <gz/sim/components/LinearVelocity.hh>
#include <gz/sim/components/Link.hh>
#include <gz/sim/components/Model.hh>
#include <gz/sim/components/Name.hh>
#include <gz/sim/components/ParentEntity.hh>
#include <gz/sim/components/Pose.hh>
#include <gz/sim/components/World.hh>
#include <gz/sim/Link.hh>
#include <gz/sim/Model.hh>
#include <gz/sim/Util.hh>
#include <sdf/Element.hh>
#include <Eigen/Dense>
#include <highfive/H5File.hpp>
#include <chrono>
#include <list>
#include <mutex>
#include <vector>
#include <string>
#include <mlinterp>
using namespace gz;
using namespace sim;
using namespace systems;
namespace Eigen
{
using Vector6d = Matrix<double, 6, 1>;
using Matrix6d = Matrix<double, 6, 6>;
}
namespace
{
/// \brief use stream buffers to populate a vector from a whitespace
/// delimited string of numbers.
/// https://stackoverflow.com/questions/4423361/constructing-a-vector-with-istream-iterators
/// https://stackoverflow.com/questions/2275135/splitting-a-string-by-whitespace-in-c
std::vector<double> whitespaceDelimitedStringToDoubleVector(
const std::string &_input)
{
// tokenise
std::istringstream buffer(_input);
std::vector<std::string> tokens(
(std::istream_iterator<std::string>(buffer)),
std::istream_iterator<std::string>());
std::vector<double> ret(tokens.size());
for (size_t i=0; i<tokens.size(); ++i)
ret[i] = std::stod(tokens[i]);
return ret;
}
template<typename T>
T SdfGet(
const std::shared_ptr<const sdf::Element> &_sdf,
const std::string &_key)
{
return _sdf->Get<T>(_key);
}
/// \brief template specialisation for std::vector<double>.
///
/// Parse data a whitespace delimited string (commas will be ignored in XML).
template<>
std::vector<double> SdfGet<std::vector<double>>(
const std::shared_ptr<const sdf::Element> &_sdf,
const std::string &_key)
{
auto str = _sdf->Get<std::string>(_key);
std::vector<double> ret = whitespaceDelimitedStringToDoubleVector(str);
return ret;
}
/// \brief template specialisation for Eigen::Matrix6d.
///
/// Parse data a whitespace delimited string (commas will be ignored in XML).
/// Eigen assumes a vector contains successive columns, so transpose.
template<>
Eigen::Matrix6d SdfGet<Eigen::Matrix6d>(
const std::shared_ptr<const sdf::Element> &_sdf,
const std::string &_key)
{
auto str = _sdf->Get<std::string>(_key);
std::vector<double> v = whitespaceDelimitedStringToDoubleVector(str);
Eigen::Matrix6d ret(v.data());
return ret.transpose();
}
/// \brief template specialisation for Eigen::Vector6d.
///
/// Parse data a whitespace delimited string (commas will be ignored in XML).
template<>
Eigen::Vector6d SdfGet<Eigen::Vector6d>(
const std::shared_ptr<const sdf::Element> &_sdf,
const std::string &_key)
{
auto str = _sdf->Get<std::string>(_key);
std::vector<double> v = whitespaceDelimitedStringToDoubleVector(str);
Eigen::Vector6d ret(v.data());
return ret;
}
}
class gz::sim::systems::LinearWaveBodyPrivate
{
/// \todo List of items to investigate or fix
///
/// 1. Linear displacements should be calculated for the origin of the
/// floating body waterplane. Done.
///
/// 2. Improve pose notation to emphasise frame
/// (e.g. Peter Corke's notation).
/// Use Kane/monogram (Drake) notation. Done
///
/// 3. Set waterplane pose in parameters. Done.
///
/// 4. Remove hardcoding of 1 heading for excitation data.
///
/// 5. Add support for finding file in model:// or package:// dirs. Done.
///
/// 6. Refactor code to read HDF5 files. Removing duplicated code. Done.
///
/// 7. Improve handing of overrides. This should happen once in config
/// not in the update loop. Done.
///
/// 8. Review and document assunmptions about what quantities are treated
/// as constants in the linear potential wave-body model.
///
/// Hydrostatics
/// - cg and cb are supplied in the body frame at equilibrium position
/// are not updated as the body pose alters, or if the body is given
/// an initial pose.
/// - the body waterplane origin is located on the free surface.
/// - the displacements used in the hydrostatics restoring force are
/// calculated in the world frame. The reference is the initial
/// position of origin of the body waterplane.
///
/// 9. Simplify data structures for debugging, publishing forces etc.
/// map[forceName] -> { enable, debug, publish, topic, ... }
/// and perhaps a bitmasks for switching features on/off
///
/// 10. Interpolate hdf5 date for constant coefficient case. Done.
///
/// 11. Optimise interpolation to eliminate unnecessary copies.
///
/// 12. Use math::eigen3::convert for converting Matrix and Vector types.
///
/// 13. Review use of Eigen.
///
/// \brief WEC-Sim BEMIO hydro data structure (read from HDF5 file)
///
/// For details see:
/// http://wec-sim.github.io/WEC-Sim/master/user/advanced_features.html#bemio-hydro-data-structure
///
/// This is the raw data loaded from file. It is not accessed directly in
/// the simulation updates.
///
/// The hydro coefficients are assumed to be non-dimensional.
///
struct HydroData
{
/// \brief Hydro data hdf5 file.
public: std::string hdf5File;
/// \brief Infinite frequency radiation added mass [Ndof, Ndof]
Eigen::Matrix6d Ainf = Eigen::Matrix6d::Zero();
/// \brief Radiation added mass [Ndof, Ndof, Nf]
std::vector<Eigen::Matrix6d> A;
/// \brief Radiation wave damping [Ndof, Ndof, Nf]
std::vector<Eigen::Matrix6d> B;
/// \brief Radiation IRF [Ndof, Ndof, len(ra_t)]
std::vector<Eigen::Matrix6d> ra_K;
/// \brief Radiation IRF time steps
std::vector<double> ra_t;
/// \brief Radiation IRF temporal angular frequency steps
std::vector<double> ra_w;
/// \todo remove hardcoding of 1 heading for excitation data
/// \brief Excitation force [Ndof, Nh, Nf]
std::vector<Eigen::Matrix<double, 6, 1>> ex_re;
std::vector<Eigen::Matrix<double, 6, 1>> ex_im;
std::vector<Eigen::Matrix<double, 6, 1>> ex_ma;
std::vector<Eigen::Matrix<double, 6, 1>> ex_ph;
/// \brief Froude-Krylov component of excitation force [Ndof, Nh, Nf]
std::vector<Eigen::Matrix<double, 6, 1>> fk_re;
std::vector<Eigen::Matrix<double, 6, 1>> fk_im;
std::vector<Eigen::Matrix<double, 6, 1>> fk_ma;
std::vector<Eigen::Matrix<double, 6, 1>> fk_ph;
/// \brief Scattering component of excitation force [Ndof, Nh, Nf]
std::vector<Eigen::Matrix<double, 6, 1>> sc_re;
std::vector<Eigen::Matrix<double, 6, 1>> sc_im;
std::vector<Eigen::Matrix<double, 6, 1>> sc_ma;
std::vector<Eigen::Matrix<double, 6, 1>> sc_ph;
/// \brief Excitation IRF [Ndof, Nh, len(ex_t)]
std::vector<Eigen::Matrix<double, 6, 1>> ex_K;
/// \brief Excitation IRF time steps
std::vector<double> ex_t;
/// \brief Excitation IRF temporal angular frequency steps
std::vector<double> ex_w;
/// \brief Hydrostatic linear restoring stiffness [6, 6]
Eigen::Matrix6d K_hs = Eigen::Matrix6d::Zero();
// Properties
/// \brief Number of bodies
double Nb{1};
/// \brief Number of wave frequencies
double Nf{0};
/// \brief Number of wave headings
double Nh{1};
/// \brief Center of buoyancy [3]
Eigen::Vector3d cb = Eigen::Vector3d::Zero();
/// \brief Center of gravity [3]
Eigen::Vector3d cg = Eigen::Vector3d::Zero();
/// \brief Displaced volume
double Vo{0.0};
// SimulationParameters
/// \brief Wave periods [1, Nf]
Eigen::VectorXd T;
/// \brief Gravitational acceleration
double g{9.81};
/// \brief Fluid density
double rho{1025.0};
/// \brief Are quantities non-dimensional?
///
/// \note: not set correctly in HDF5 by bemio.
double scaled{1};
/// \brief Wave temporal angular frequencies [1, Nf]
Eigen::VectorXd w;
/// \brief Wave directions in degrees [1, Nh]
Eigen::VectorXd theta;
};
/// \brief Dimensioned hydrodynamics force coefficients (constant).
///
/// The force coefficients used in the simulation update.
///
struct HydroForceCoeffs
{
/// \brief Hydrostatic linear restoring stiffness [6, 6]
Eigen::Matrix6d K_hs = Eigen::Matrix6d::Zero();
/// \brief Radiation added mass [Ndof, Ndof]
Eigen::Matrix6d A = Eigen::Matrix6d::Zero();
/// \brief Radiation damping [Ndof, Ndof]
Eigen::Matrix6d B = Eigen::Matrix6d::Zero();
/// \brief Combined excitation force [Ndof, Nh=1]
Eigen::Vector6d ex_re = Eigen::Vector6d::Zero();
Eigen::Vector6d ex_im = Eigen::Vector6d::Zero();
/// \brief Froude-Krylov excitation force [Ndof, Nh=1]
Eigen::Vector6d fk_re = Eigen::Vector6d::Zero();
Eigen::Vector6d fk_im = Eigen::Vector6d::Zero();
/// \brief Scattering excitation force [Ndof, Nh=1]
Eigen::Vector6d sc_re = Eigen::Vector6d::Zero();
Eigen::Vector6d sc_im = Eigen::Vector6d::Zero();
};
/// \brief Waves parameters (regular waves)
///
/// Override priority (lowest number => highest priority)
/// 1. SDF <waves>
/// 4. Default
///
/// \todo integrate with the waves plugin - details should be retrieved
/// from the waves entity.
///
struct Waves
{
/// \brief Wave period (s)
double period{6.0};
/// \brief Wave height (m). Height = 2 * amplitude.
double height{4.0};
/// \brief Wave direction (rad). Zero is aligned with world x-axis.
double direction{0.0};
/// \brief Wave phase (rad).
double phase{0.0};
};
/// \brief Simulation parameters.
///
/// Override priority (lowest number => highest priority)
/// 1. SDF <waves>
/// 2. SDF <simulation_parameters>
/// 3. SDF <hdf5_file>
/// 4. Default
///
struct SimulationParameters
{
double g{9.81};
double rho{1025.0};
double T{6.0};
double w{2.0 * GZ_PI / T};
};
/// \brief Simulation parameters.
///
/// Override priority (lowest number => highest priority)
/// 1. SDF <geometry>
/// 2. SDF <hdf5_file>
/// 3. Default
///
struct Geometry
{
/// \brief Position vector of the waterplane origin in body frame.
public: gz::math::Vector3d p_BoBwp_B = gz::math::Vector3d::Zero;
/// \brief Position vector of the center of buoyancy in body frame.
public: gz::math::Vector3d p_BoBcb_B = gz::math::Vector3d::Zero;
/// \brief Displaced volume.
double Vo{0.0};
};
/// \brief Destructor
public: ~LinearWaveBodyPrivate();
/// \brief Initialize the system.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void Init(EntityComponentManager &_ecm);
/// \brief Read a WECSim HDF5 BEM data file.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void ReadWECSim(EntityComponentManager &_ecm);
/// \brief Update the physics and markers.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void Update(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update link state.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateLinkState(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the gravity forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateGravityForces(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the hydrostatic forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateHydrostaticForces(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the radiation forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateRadiationForces(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the radiation damping forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateRadiationDampingForces(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the radiation added mass forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateRadiationAddedMassForces(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the radiation forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void RadiationForcesImpulseResponseFunction(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Update the excitation forces.
/// \param[in] _info Simulation update info.
/// \param[in] _ecm Mutable reference to the EntityComponentManager.
public: void UpdateExcitationForces(
const UpdateInfo &_info, EntityComponentManager &_ecm);
/// \brief Model interface
public: sim::Model model{kNullEntity};
/// \brief Link entity
public: sim::Entity linkEntity{kNullEntity};
/// \brief Static pose of the link waterplane in the link frame
public: gz::math::Pose3d X_BBwp = gz::math::Pose3d::Zero;
/// \brief Initial pose of the body waterplane in the world frame
public: gz::math::Pose3d X0_WBwp = gz::math::Pose3d::Zero;
/// \brief Link world linear velocity at previous time-step
public: gz::math::Vector3d v_WB_W_prev = gz::math::Vector3d::Zero;
/// \brief Link world angular velocity at previous time-step
public: gz::math::Vector3d w_WB_W_prev = gz::math::Vector3d::Zero;
/// \brief Link state to update each time-step.
struct LinkState
{
gz::math::Pose3d X_WB;
gz::math::Pose3d X_WBcm;
gz::math::Pose3d X_WBwp;
gz::math::Pose3d X_BBcm;
gz::math::Pose3d X_BcmBwp;
gz::math::Vector3d p_BoBcm_B;
gz::math::Vector3d p_BoBcm_W;
gz::math::Vector3d p_BcmBcb_B;
gz::math::Vector3d p_BcmBcb_W;
gz::math::Vector3d p_BcmBwp_Bcm;
gz::math::Vector3d p_BcmBwp_W;
};
/// \brief Common link state required by force calculations.
public: LinkState linkState;
/// \brief Initialization flag
public: bool initialized{false};
/// \brief Copy of the sdf configuration used for this plugin
public: sdf::ElementPtr sdf;
/// \brief Set during Load to true if the configuration for the system is
/// valid and the post-update can run
public: bool validConfig{false};
/// \brief Name of the world
public: std::string worldName;
/// \brief Hydro data populated from hdf5 file.
public: HydroData hydroData;
/// \brief Waves parameters.
public: Waves waves;
/// \brief Simulation parameters.
public: SimulationParameters simParams;
/// \brief Geometry parameters.
public: Geometry geometry;
/// \brief Hydrostatic force constant coefficients used in sim update.
public: HydroForceCoeffs hydroForceCoeffs;
/// \brief Flags to enable forces.
struct ForceFlags
{
bool gravityOn{true};
bool buoyancyOn{true};
bool hydrostaticRestoringOn{true};
bool radiationDampingOn{true};
bool radiationAddedMassOn{true};
bool excitationOn{true};
bool excitationFroudeKrylovOn{true};
bool excitationScatteringOn{true};
};
public: ForceFlags forceFlags;
/// \brief Flags to enable additional debug info.
struct DebugFlags
{
bool gravityOn{false};
bool buoyancyOn{false};
bool radiationDampingOn{false};
bool radiationAddedMassOn{false};
bool excitationOn{false};
};
public: DebugFlags debugFlags;
// Flags to note if SDF has overridden hdf5 data
public: bool waveOverrideOn{false};
public: bool simParamOverrideOn{false};
public: bool geometryOverrideOn{false};
public: bool hydrostaticOverrideOn{false};
public: bool radiationOverrideOn{false};
public: bool excitationOverrideOn{false};
/// \brief Mutex to protect wave marker updates.
public: std::recursive_mutex mutex;
/// \brief Previous update time (s).
public: double prevTime;
/// \brief Publishers
struct Publishers
{
double updateRate = 20;
// Enable / disable force publishers
bool gravityOn{false};
bool buoyancyOn{false};
bool hydrostaticRestoringOn{false};
bool radiationDampingOn{false};
bool radiationAddedMassOn{false};
bool excitationOn{false};
bool excitationFroudeKrylovOn{false};
bool excitationScatteringOn{false};
// Topic strings
std::string gravityTopic
{"/force/gravity"};
std::string buoyancyTopic
{"/force/buoyancy"};
std::string restoringTopic
{"/force/restoring"};
std::string radiationDampingTopic
{"/force/radiation_damping"};
std::string radiationAddedMassTopic
{"/force/radiation_added_mass"};
std::string excitationTopic
{"/force/excitation"};
std::string excitationFroudeKrylovTopic
{"/force/excitation_froude_krylov"};
std::string excitationScatteringTopic
{"/force/excitation_scattering"};
// Publishers
transport::Node::Publisher gravityPub;
transport::Node::Publisher buoyancyPub;
transport::Node::Publisher restoringPub;
transport::Node::Publisher radiationDampingPubl;
transport::Node::Publisher radiationAddedMassPubl;
transport::Node::Publisher excitationPub;
transport::Node::Publisher excitationFroudeKrylovPubl;
transport::Node::Publisher excitationScatteringPub;
};
/// \brief Publishers
public: Publishers publishers;
/// \brief Transport node for wave marker messages
public: transport::Node node;
};
/////////////////////////////////////////////////
LinearWaveBody::LinearWaveBody() : System(),
dataPtr(std::make_unique<LinearWaveBodyPrivate>())
{
}
/////////////////////////////////////////////////
LinearWaveBody::~LinearWaveBody()
{
}
namespace
{
/// \todo Optimise to reduce / eliminate copies.
/// The inefficiency is because we read data
/// in Eigen Vectors and Matrices and represent
/// the coefficients as a vector of matrices rathen
/// a matrix of time series suitable for interpolation.
/// \brief Interpolation helpers
///
/// \param _Xd data vector
/// \param _Xi interpolation point
/// \param _Yd data vector of matrix
/// \param _Yi interpolation matrix
template <typename Matrix>
void Interp(
const Eigen::VectorXd &_Xd,
double _Xi,
const std::vector<Matrix> &_Yd,
Matrix *_Yi)
{
// check there is data to interpolate
if (_Xd.size() == 0)
return;
// get dimensions
size_t nf = _Xd.size();
size_t n1 = _Yd[0].rows();
size_t n2 = _Yd[0].cols();
// convert to std::vector
std::vector<double> Xdd;
for (size_t k=0; k<nf; ++k)
{
Xdd.push_back(_Xd[k]);
}
// reshape to (n1 * n2) x 1 x Nf vectors for interpolation
std::vector<std::vector<double>> Ydd(n1*n2);
for (size_t i=0; i<n1; ++i)
{
for (size_t j=0; j<n2; ++j)
{
size_t idx = j*n1 + i;
for (size_t k=0; k<nf; ++k)
{
auto& m = _Yd[k];
double val = m(i, j);
Ydd[idx].push_back(val);
}
}
}
// interpolate
size_t ni = 1;
double yi[] = { 0.0 };
double xi[] = { _Xi };
for (size_t i=0; i<n1; ++i)
{
for (size_t j=0; j<n2; ++j)
{
size_t idx = j*n1 + i;
size_t nd[] = { nf };
double* xd = Xdd.data();
double* yd = Ydd[idx].data();
mlinterp::interp(nd, ni, yd, yi, xd, xi);
(*_Yi)(i, j) = yi[0];
}
}
};
}
/////////////////////////////////////////////////
/// \brief Configure the model
///
/// The plugin reads in data from an hdf5 file. Defaults are used if a file
/// file is not provided. A number of parameters may be overridden if options
/// are set in the plugin XML. This is the load order.
///
/// 1. Read the <hdf5_file> into the struct HydroData.
/// - override defaults for g and rho in struct SimulationParameters
/// - override defaults for cg and Vo in struc Geometry
///
/// 2. Read the <waves> element
/// - override defaults in struct Waves
/// - override defaults for T and w in struct SimulationParameters
///
/// 3. Read the <simulation_parameters> element
/// - override defaults in struct SimulationParameters
///
/// 4. Read the <geometry> element
///
/// 5. Look up the hydro coefficients from the hdf5 data
/// - \todo locate the index of w
/// - rescale the coefficients to dimensioned quantities
///
/// 6. Read the <hydro_coeff> elements
/// - override hydrostatic, radiation and excitation coefficients
/// if elements are present.
///
void LinearWaveBody::Configure(const Entity &_entity,
const std::shared_ptr<const sdf::Element> &_sdf,
EntityComponentManager &_ecm,
EventManager &_eventMgr)
{
GZ_PROFILE("LinearWaveBody::Configure");
gzmsg << "LinearWaveBody: configuring\n";
// Clone sdf for non-const access.
this->dataPtr->sdf = _sdf->Clone();
// Get the name of the world
if (this->dataPtr->worldName.empty())
{
_ecm.Each<components::World, components::Name>(
[&](const Entity &,
const components::World *,
const components::Name *_name) -> bool
{
// Assume there's only one world
this->dataPtr->worldName = _name->Data();
return false;
});
}
// Capture the model entity
this->dataPtr->model = Model(_entity);
if (!this->dataPtr->model.Valid(_ecm))
{
gzerr << "The LinearWaveBody system should be attached to a model entity. "
<< "Failed to initialize." << "\n";
return;
}
// Set the link entity
std::string linkName("base_link");
this->dataPtr->linkEntity = this->dataPtr->model.LinkByName(_ecm, linkName);
if (!_ecm.HasEntity(this->dataPtr->linkEntity))
{
gzerr << "Link name" << linkName << "does not exist";
return;
}
/// \note Must enable world velocity and acceleration checks to register
/// components for pose, velocity and acceleration.
/// Link::AddWorldForce fails silently if not enabled.
gz::sim::Link baseLink(this->dataPtr->linkEntity);
baseLink.EnableVelocityChecks(_ecm, true);
baseLink.EnableAccelerationChecks(_ecm, true);
// Parameters
/// \todo set waterplane pose in parameters
this->dataPtr->X_BBwp.Pos() = gz::math::Vector3d(0, 0, 0);
/// \todo add support for finding file in model:// or package:// dirs.
//////////
// 1a. read WEC-Sim hdf5 BEM file
if (_sdf->HasElement("hdf5_file"))
{
std::string fileUri = _sdf->Get<std::string>("hdf5_file");
// Find the file path
common::SystemPaths systemPaths;
this->dataPtr->hydroData.hdf5File = systemPaths.FindFileURI(fileUri);
this->dataPtr->ReadWECSim(_ecm);
}
else
{
gzwarn << "Missing element <hdf5_file> for HDF5 file. "
<< "Check this is intentional - using overrides and defaults.\n";
}
/// 1b. apply overrides
if (_sdf->HasElement("hdf5_file"))
{
// simulation parameters
this->dataPtr->simParams.g = this->dataPtr->hydroData.g;
this->dataPtr->simParams.rho = this->dataPtr->hydroData.rho;
// geometry
this->dataPtr->geometry.Vo = this->dataPtr->hydroData.Vo;
/// \todo override cg, cb, waterplane origin
}
//////////
// 2a. read the <waves> element
if (_sdf->HasElement("waves"))
{
this->dataPtr->waveOverrideOn = true;
auto sdfWaves = _sdf->GetElementImpl("waves");
// regular waves
if (sdfWaves->HasElement("regular"))
{
auto sdfRegWaves = sdfWaves->GetElementImpl("regular");
if (sdfRegWaves->HasElement("period"))
this->dataPtr->waves.period =
sdfRegWaves->Get<double>("period");
if (sdfRegWaves->HasElement("height"))
this->dataPtr->waves.height =
sdfRegWaves->Get<double>("height");
if (sdfRegWaves->HasElement("direction"))
this->dataPtr->waves.direction =
sdfRegWaves->Get<double>("direction");
if (sdfRegWaves->HasElement("phase"))
this->dataPtr->waves.phase =
sdfRegWaves->Get<double>("phase");
}
}
// 2a. apply overrides
if (this->dataPtr->waveOverrideOn)
{
// simulation parameters
this->dataPtr->simParams.T = this->dataPtr->waves.period;
this->dataPtr->simParams.w = 2.0 * GZ_PI / this->dataPtr->simParams.T;
}
//////////
// 3a. read the <simulation_parameters> element
if (_sdf->HasElement("simulation_parameters"))
{
this->dataPtr->simParamOverrideOn = true;
auto sdfSimParams = _sdf->GetElementImpl("simulation_parameters");
if (sdfSimParams->HasElement("gravity"))
this->dataPtr->simParams.g = sdfSimParams->Get<double>("gravity");
if (sdfSimParams->HasElement("fluid_density"))
this->dataPtr->simParams.rho = sdfSimParams->Get<double>("fluid_density");
}
//////////
// 4a. read the <geometry> element.
if (_sdf->HasElement("geometry"))
{
this->dataPtr->geometryOverrideOn = true;
auto sdfGeom = _sdf->GetElementImpl("geometry");
if (sdfGeom->HasElement("center_of_waterplane"))
this->dataPtr->geometry.p_BoBwp_B =
sdfGeom->Get<gz::math::Vector3d>("center_of_waterplane");
if (sdfGeom->HasElement("center_of_buoyancy"))
this->dataPtr->geometry.p_BoBcb_B =
sdfGeom->Get<gz::math::Vector3d>("center_of_buoyancy");
if (sdfGeom->HasElement("displaced_volume"))
this->dataPtr->geometry.Vo =
sdfGeom->Get<double>("displaced_volume");
}
//////////
// 5a. interpolate hydro coeffs from hdf5 data.
if (_sdf->HasElement("hdf5_file"))
{
/// \note we allow g and rho to override hdf5 values
double g = this->dataPtr->simParams.g;
double rho = this->dataPtr->simParams.rho;
// hydrostatics
this->dataPtr->hydroForceCoeffs.K_hs =
this->dataPtr->hydroData.K_hs * rho * g;
// interpolate and scale.
double w = this->dataPtr->simParams.w;
// radiation added mass [Ndof, Ndof, Nf]
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.A, // Yd
&this->dataPtr->hydroForceCoeffs.A // Yi
);
this->dataPtr->hydroForceCoeffs.A *= rho;
// radiation damping [Ndof, Ndof, Nf]
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.B, // Yd
&this->dataPtr->hydroForceCoeffs.B // Yi
);
this->dataPtr->hydroForceCoeffs.B *= rho * w;
// excitation combined [Ndof, Nh, Nf]
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.ex_re, // Yd
&this->dataPtr->hydroForceCoeffs.ex_re // Yi
);
this->dataPtr->hydroForceCoeffs.ex_re *= rho * g;
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.ex_im, // Yd
&this->dataPtr->hydroForceCoeffs.ex_im // Yi
);
this->dataPtr->hydroForceCoeffs.ex_im *= rho * g;
// excitation Froude-Krylov [Ndof, Nh, Nf]
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.fk_re, // Yd
&this->dataPtr->hydroForceCoeffs.fk_re // Yi
);
this->dataPtr->hydroForceCoeffs.fk_re *= rho * g;
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.fk_im, // Yd
&this->dataPtr->hydroForceCoeffs.fk_im // Yi
);
this->dataPtr->hydroForceCoeffs.fk_im *= rho * g;
// excitation scattering [Ndof, Nh, Nf]
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.sc_re, // Yd
&this->dataPtr->hydroForceCoeffs.sc_re // Yi
);
this->dataPtr->hydroForceCoeffs.sc_re *= rho * g;
Interp(
this->dataPtr->hydroData.w, w, // Xd, Xi
this->dataPtr->hydroData.sc_im, // Yd
&this->dataPtr->hydroForceCoeffs.sc_im // Yi
);
this->dataPtr->hydroForceCoeffs.sc_im *= rho * g;
}
//////////
// 6. read the <hydro_coeffs> elements.
sdf::ElementPtr sdfHydrostatic;
sdf::ElementPtr sdfRadiation;
sdf::ElementPtr sdfExcitation;
if (_sdf->HasElement("hydro_coeffs"))
{
auto sdfHydro = _sdf->GetElementImpl("hydro_coeffs");
/// \todo use the scaled parameter - current assumption is all
/// hydro coeff overrides are dimensioned.
if (sdfHydro->HasElement("scaled"))
double scaled = sdfHydro->Get<double>("scaled");
if (sdfHydro->HasElement("hydrostatic"))
sdfHydrostatic = sdfHydro->GetElementImpl("hydrostatic");
if (sdfHydro->HasElement("radiation"))
sdfRadiation = sdfHydro->GetElementImpl("radiation");
if (sdfHydro->HasElement("excitation"))
sdfExcitation = sdfHydro->GetElementImpl("excitation");
}
// 6a. hydrostatic coefficients
if (sdfHydrostatic)
{
this->dataPtr->hydrostaticOverrideOn = true;
if (sdfHydrostatic->HasElement("linear_restoring"))
{
this->dataPtr->hydroForceCoeffs.K_hs =
SdfGet<Eigen::Matrix6d>(sdfHydrostatic, "linear_restoring");
}
}
// 6b. hydrodynamic radiation coefficients
if (sdfRadiation)
{
this->dataPtr->radiationOverrideOn = true;
if (sdfRadiation->HasElement("added_mass"))
this->dataPtr->hydroForceCoeffs.A =
SdfGet<Eigen::Matrix6d>(sdfRadiation, "added_mass");