Repository navigation
Expand file tree
/
Copy pathbuilder.py
More file actions
3303 lines (2908 loc) · 113 KB
/
Copy pathbuilder.py
File metadata and controls
3303 lines (2908 loc) · 113 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
# SPDX-License-Identifier: Apache-2.0
"""Typed object model for building and editing CableDyn decks in Python.
:class:`DeckModel` holds a deck as linked Python objects (line types, rod
types, bodies, rods, points, lines with their sections, the optional
per-line and per-point tables, options, and output channels). Objects refer
to each other by reference, not by id, so renaming a point or a line type
keeps every row that uses it consistent, and removing an object that is still
in use fails unless the removal is asked to cascade.
The model does not parse or validate deck text itself. :meth:`DeckModel.load`
reads through :class:`cabledyn.DeckFile`, and :meth:`DeckModel.to_text`
renders canonical deck text that is validated by :class:`cabledyn.DeckFile`
with the same native rules. Comments, column alignment, and records the
native reader ignores are not kept; use :class:`cabledyn.DeckFile` to edit a
deck while preserving its source text.
The row classes here (``Line``, ``Point``, ``Body``, ``Rod``, ...) describe
deck input. The live solver views of a running model share some of these
names but are different classes, in :mod:`cabledyn.objects` (re-exported by
:mod:`cabledyn.model`); import each family from its own module.
"""
from __future__ import annotations
import contextlib
import copy
import numbers
import operator
import os
import re
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Generic, TypeVar, Union
from cabledyn.deck import _check_free_text
from cabledyn.deck_file import (
_LINE_OPTION_PATTERN,
_PINNED_END_CONNECTIONS,
_RIGID_END_CONNECTIONS,
_ROD_ATTACHMENT_ALIASES,
_WAVETRAIN_KEYWORDS,
DeckFile,
DeckRecord,
_body_point_id,
_copy_companions,
_end_connection_end,
_is_csys_token,
_is_scalar_option_keyword,
_is_turbine_point_type,
_native_int,
_option_key,
_plan_companion_copies,
_render,
_render_quoted_text,
_rod_end_token,
_rod_point,
_split_records,
_strip_inline_comment,
_table_float,
_turbine_id,
)
__all__ = [
"Attachment",
"Body",
"Control",
"DeckModel",
"DeckReferenceError",
"EndConnection",
"EquivalentBuoyancy",
"ExternalLoad",
"Failure",
"Line",
"LineType",
"MoorDynBody",
"ObjectCollection",
"Option",
"OptionSet",
"OutputList",
"Point",
"Rod",
"RodEnd",
"RodType",
"Section",
"Stiffener",
"SyropeEA",
"SyropeIC",
"Turbine",
]
_END_CONNECTION_KEYWORDS = _PINNED_END_CONNECTIONS | _RIGID_END_CONNECTIONS
# TorsStiffness keywords of the optional END CONNECTIONS torsion columns
_TORSION_KEYWORDS = frozenset({"free", "zero"}) | _RIGID_END_CONNECTIONS
Vec3 = tuple[float, float, float]
"""A three-component vector ``(x, y, z)``."""
_BANNER = "--------------------- CableDyn Input File ------------------------------------"
_FOOTER = "--------------------- need this line -----------------------------------------"
_MOTION_KEYWORDS = ("motionFile", "vesselMotion", "vesselRAO")
_POSITIONAL_KEYS = frozenset({"waves", "current"})
_CHANNEL_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
(
"line",
re.compile(
r"(fairten|anchten|anchfz|anchfh|fairangle|anchangle|fairdecl|anchdecl|fairincl|anchincl"
r"|fairdefl|anchdefl)"
r"([0-9]+)()",
re.IGNORECASE,
),
),
("line", re.compile(r"(tdp)([0-9]+)(s|x|y|z|lay|exc|grd)", re.IGNORECASE)),
(
"line",
re.compile(r"(ten|curvx|curvy|curv|bendmom|stfmom|torq)([0-9]+)(n[0-9]+)", re.IGNORECASE),
),
("line", re.compile(r"(twist)([0-9]+)(n[0-9]+|)", re.IGNORECASE)),
("line", re.compile(r"(l)([0-9]+)(n[0-9]+(?:[pva][xyz]|dec|azi))", re.IGNORECASE)),
("point", re.compile(r"(point|con)([0-9]+)(p[xyz])", re.IGNORECASE)),
("point", re.compile(r"(point)([0-9]+)(f[xyzh])", re.IGNORECASE)),
("body", re.compile(r"(body)([0-9]+)((?:p|r|v|rv|a|ra|f|m)[xyz])", re.IGNORECASE)),
(
"rod",
re.compile(
r"(rod)([0-9]+)(n[0-9]+p[xyz]|(?:p|v|rv|a|ra|f|m)[xyz]|r[xy]|tena|tenb|sub)",
re.IGNORECASE,
),
),
)
class DeckReferenceError(ValueError):
"""An object is used by other deck objects, or belongs to another model.
Raised by :meth:`DeckModel.remove` when the object is still referenced
and ``cascade`` is false, and when a row names an object that is not part
of the model.
Attributes
----------
referrers : tuple[object, ...]
The objects (and output channel names) that still use the object.
"""
def __init__(self, message: str, referrers: Sequence[object] = ()) -> None:
super().__init__(message)
self.referrers = tuple(referrers)
# --------------------------------------------------------------------------- objects
@dataclass(frozen=True)
class SyropeEA:
"""Syrope working-curve axial stiffness, the ``SYROPE:<file>|alpha|beta`` EA form.
Attributes
----------
settings : str
Syrope settings file, relative to the deck or absolute.
alpha : float
Fast-spring stiffness intercept, in N.
beta : float
Fast-spring stiffness slope on tension (dimensionless).
"""
settings: str
alpha: float
beta: float
@dataclass(eq=False)
class LineType:
"""One ``LINE TYPES`` row, in CableDyn column order.
Attributes
----------
name : str
Unique type name (case-insensitive).
diam : float
Hydrodynamic, volume-equivalent diameter, in m.
mass : float
Dry mass per unstretched metre, in kg/m.
ea : float | tuple[float, ...] | SyropeEA
Axial stiffness in N; ``(Es, Ed)`` or ``(Es, alphaMBL, vbeta)`` for a
viscoelastic type, or a :class:`SyropeEA`.
ba : float | tuple[float, ...]
Axial damping in N s (negative: damping ratio), or ``(Bs, Bd)``.
ei : float | tuple[float, ...]
Bending stiffness, in N m^2; ``(EI, Bb)`` adds the bending damping
``Bb`` in N m^2 s (written ``EI|Bb``), and ``(EI, -zeta, f)`` gives it
as the damping ratio ``zeta`` of a bending mode of frequency ``f`` in Hz
(written ``EI|-zeta|f``; ``Bb = zeta EI / (pi f)``).
cdn, cdt, can, cat : float
Normal and tangential drag and added-mass coefficients.
gas, gj, irt, irn : float | None
Optional finite-EI columns (shear and torsional stiffness, rotary
inertias). All four set writes the 14-column row; all ``None`` writes
the 10-column row. ``gj`` may be ``(GJ, K)``, with ``K`` the
torque-tension coupling in N m (written ``GJ|K``), or ``(GJ, K, Bt)``,
with ``Bt`` the torsional damping in N m^2 s, negative for a damping
ratio (written ``GJ|K|Bt``).
cl, df, cf : float | None
Optional cross-flow VIV columns of a type (MoorDyn's lift
coefficient and the half-range and centre of the synchronisation band
in non-dimensional frequency). ``cl`` set writes the 13-column row, with
MoorDyn's ``df = 0.08`` and ``cf = 0.18`` where they are ``None``.
clx, il_alpha : float | None
Optional in-line VIV of a type, a ``VIV`` section row
``Name ClX [alpha]``: the in-line shedding coefficient (it needs ``cl``,
the in-line phase running at twice the cross-flow one) and the frequency
band of that phase, ``0 <= il_alpha < 1``; ``None`` leaves alpha out of
the row (the solver takes 0.15).
"""
name: str
diam: float
mass: float
ea: float | tuple[float, ...] | SyropeEA
ba: float | tuple[float, ...] = 0.0
ei: float | tuple[float, ...] = 0.0
cdn: float = 0.0
cdt: float = 0.0
can: float = 0.0
cat: float = 0.0
gas: float | None = None
gj: float | tuple[float, ...] | None = None
irt: float | None = None
irn: float | None = None
cl: float | None = None
df: float | None = None
cf: float | None = None
clx: float | None = None
il_alpha: float | None = None
@dataclass(eq=False)
class RodType:
"""One ``ROD TYPES`` row.
Attributes
----------
name : str
Unique type name (case-insensitive).
diam : float
Cylinder diameter, in m.
mass : float
Dry mass per unit length, in kg/m.
cd, ca : float
Transverse drag and added-mass coefficients.
cd_end, ca_end : float
End drag and end added-mass coefficients.
cd_ax, ca_ax : float | None
Optional axial side drag and added-mass coefficients (both or neither).
"""
name: str
diam: float
mass: float
cd: float = 0.0
ca: float = 0.0
cd_end: float = 0.0
ca_end: float = 0.0
cd_ax: float | None = None
ca_ax: float | None = None
@dataclass(eq=False)
class Body:
"""One CableDyn ``BODIES`` row (15 columns, or 18 with the inertias).
Attributes
----------
id : int
Unique body id, at least 1.
type : str
``Point3``, ``Rigid6``, ``Coupled``, or ``Vessel``.
x, y, z : float
Reference position, in m.
roll, pitch, yaw : float
Reference orientation, in degrees.
mass : float
Body mass, in kg.
volume : float
Displaced volume, in m^3.
c33, c44, c55 : float
Heave (N/m) and roll/pitch (N m/rad) hydrostatic restoring.
cda : float
Drag area, in m^2.
ca : float
Added-mass coefficient.
inertia : tuple[float, float, float] | None
``(Ixx, Iyy, Izz)`` in kg m^2; required for ``Rigid6``.
"""
id: int
type: str
x: float
y: float
z: float
roll: float = 0.0
pitch: float = 0.0
yaw: float = 0.0
mass: float = 0.0
volume: float = 0.0
c33: float = 0.0
c44: float = 0.0
c55: float = 0.0
cda: float = 0.0
ca: float = 0.0
inertia: Vec3 | None = None
@dataclass(eq=False)
class MoorDynBody:
"""One 14-column MoorDyn v2 ``BODIES`` row (a Rigid6 body with a centre of gravity).
Attributes
----------
id : int
Unique body id, at least 1.
type : str
``Free``, ``Coupled``, or ``Vessel``.
x, y, z : float
Reference position, in m.
roll, pitch, yaw : float
Reference orientation, in degrees.
mass : float
Body mass, in kg.
cg : float | tuple[float, ...]
Centre of gravity in the body frame: ``z`` or ``(x, y, z)``, in m.
inertia : float | tuple[float, ...]
Inertia about the CG: one value or ``(Ixx, Iyy, Izz)``, in kg m^2.
volume : float
Displaced volume, in m^3.
cda : float | tuple[float, ...]
Drag area: one value, ``(CdA, CdA_rot)``, or 3 or 6 entries, in m^2.
ca : float | tuple[float, ...]
Added-mass coefficient: one value or 3 entries.
"""
id: int
type: str
x: float
y: float
z: float
roll: float = 0.0
pitch: float = 0.0
yaw: float = 0.0
mass: float = 0.0
cg: float | tuple[float, ...] = 0.0
inertia: float | tuple[float, ...] = 0.0
volume: float = 0.0
cda: float | tuple[float, ...] = 0.0
ca: float | tuple[float, ...] = 0.0
AnyBody = Union[Body, MoorDynBody] # noqa: UP007 (a runtime alias must work on Python 3.10)
@dataclass(eq=False)
class Rod:
"""One ``RODS`` row.
Attributes
----------
id : int
Unique rod id, at least 1.
rod_type : RodType
The rod's type.
type : str
Attachment kind: ``Free``, ``Fixed``, ``Pinned``, ``Coupled``,
``Vessel`` (or a MoorDyn alias), or ``Body``/``BodyPinned``/``BodyPin``
together with :attr:`body`.
end_a, end_b : tuple[float, float, float]
End A and End B coordinates, in m (body frame for a body rod).
num_segs : int
Hydrodynamic segments; ``0`` declares a zero-length rod.
outputs : str
``-`` or ``p``.
body : Body | MoorDynBody | None
The body a ``Body``/``BodyPinned`` rod is attached to.
"""
id: int
rod_type: RodType
type: str
end_a: Vec3
end_b: Vec3
num_segs: int
outputs: str = "-"
body: AnyBody | None = None
@property
def type_token(self) -> str:
"""The attachment as written in the deck, for example ``Body1Pinned``."""
if self.body is not None and self.type.lower().startswith("body"):
return f"{self.type[:4]}{self.body.id}{self.type[4:]}"
return self.type
@dataclass(frozen=True)
class RodEnd:
"""End ``A`` or ``B`` of a rod, used as a line end (``R<N>A``) or a point type.
Attributes
----------
rod : Rod
The rod.
end : str
``"A"`` or ``"B"``.
"""
rod: Rod
end: str
@property
def token(self) -> str:
"""The deck token of this end as a line attachment, for example ``R2A``."""
return f"R{self.rod.id}{self.end.upper()}"
@dataclass(eq=False)
class Turbine:
"""One ``TURBINES`` row of a standalone FAST.Farm deck.
Attributes
----------
id : int
Turbine number ``J``, 1 to 10000.
x, y, z : float
Farm-global reference position, in m.
ptfm : tuple[float, ...] | None
Optional ``(surge, sway, heave, roll, pitch, yaw)`` initial platform
displacement, in m and degrees.
"""
id: int
x: float
y: float
z: float
ptfm: tuple[float, ...] | None = None
@dataclass(eq=False)
class Point:
"""One ``POINTS`` row.
Attributes
----------
id : int
Unique point id, at least 1.
type : str
``Fixed``, ``Coupled``, ``Vessel``, ``Free``, ``Connect``, or
``Body``/``Rod``/``Turbine``/``T`` together with :attr:`body`,
:attr:`rod_end`, or :attr:`turbine`.
x, y, z : float
Position (or body-frame offset for a body point), in m.
mass : float
Point mass, in kg.
volume : float
Displaced volume, in m^3.
cda : float
Drag area, in m^2.
ca : float
Added-mass coefficient.
body : Body | MoorDynBody | None
The body of a ``Body<N>`` point.
rod_end : RodEnd | None
The rod end of a ``Rod<N>A``/``Rod<N>B`` point.
turbine : int | None
The turbine number of a ``Turbine<J>``/``T<J>`` point.
"""
id: int
type: str
x: float
y: float
z: float
mass: float = 0.0
volume: float = 0.0
cda: float = 0.0
ca: float = 0.0
body: AnyBody | None = None
rod_end: RodEnd | None = None
turbine: int | None = None
@property
def type_token(self) -> str:
"""The point type as written in the deck, for example ``Body1`` or ``Rod2A``."""
kind = self.type.lower()
if kind == "body" and self.body is not None:
return f"{self.type}{self.body.id}"
if kind == "rod" and self.rod_end is not None:
return f"{self.type}{self.rod_end.rod.id}{self.rod_end.end.upper()}"
if kind in {"turbine", "t"} and self.turbine is not None:
return f"{self.type}{self.turbine}"
return self.type
LineEnd = Union[Point, RodEnd] # noqa: UP007 (a runtime alias must work on Python 3.10)
@dataclass(eq=False)
class Section:
"""One section of a line (a ``SECTIONS`` row).
Attributes
----------
line_type : LineType
The section's line type.
length : float
Unstretched length, in m.
num_segs : int
Number of elements.
"""
line_type: LineType
length: float
num_segs: int
@dataclass(eq=False)
class Line:
"""One ``LINES`` row with its ordered sections (End A to End B).
Attributes
----------
id : int
Unique line id, at least 1.
end_a, end_b : Point | RodEnd
End A (fairlead side) and End B (anchor side) attachments.
sections : list[Section]
Ordered sections from End A.
outputs : str
Per-line output flags: ``-`` or a combination of ``p``, ``t``, ``r``.
stock_row : bool
Write a single-section line as a stock MoorDyn 7-column row
(``ID LineType AttachA AttachB UnstrLen NumSegs Outputs``) instead of
a 4-column row plus one ``SECTIONS`` row.
"""
id: int
end_a: LineEnd
end_b: LineEnd
sections: list[Section] = field(default_factory=list)
outputs: str = "-"
stock_row: bool = False
@property
def length(self) -> float:
"""Total unstretched length, the sum of the section lengths, in m."""
return float(sum(float(section.length) for section in self.sections))
@property
def num_segs(self) -> int:
"""Total number of elements over all sections."""
return sum(int(section.num_segs) for section in self.sections)
@dataclass(eq=False)
class EndConnection:
"""One ``END CONNECTIONS`` row: the bending boundary at a finite-EI line end.
Attributes
----------
line : Line
The line.
end : str
``"A"`` or ``"B"``.
stiffness : float | str
Rotational stiffness in N m/rad, ``Pinned``, or ``Rigid``.
direction : tuple[float, float, float]
Non-zero reference direction (End A to End B convention).
torsion_stiffness : float | str | None
Optional torsional restraint: ``Free``, ``Rigid`` or a stiffness in N m/rad; ``None``
writes the six-column row (no torsion columns).
normal : tuple[float, float, float] | None
Zero-twist reference normal in the frame of ``direction`` (with ``torsion_stiffness``).
pretwist : float | None
Optional roll of the end frame about ``direction``, in degrees.
"""
line: Line
end: str
stiffness: float | str
direction: Vec3
torsion_stiffness: float | str | None = None
normal: Vec3 | None = None
pretwist: float | None = None
@dataclass(eq=False)
class EquivalentBuoyancy:
"""One ``EQUIVALENT BUOYANCY`` row: a line type given by its submerged weight.
Attributes
----------
line_type : LineType
The line type rewritten by the row.
diam : float
Equivalent diameter, in m.
submerged_weight : float
Net submerged weight, in N/m (negative for uplift).
"""
line_type: LineType
diam: float
submerged_weight: float
@dataclass(eq=False)
class Attachment:
"""One ``ATTACHMENTS`` row: discrete modules or clumps on a finite-EI line.
Attributes
----------
line : Line
The finite-EI line.
arc_length : float | tuple[float, float, float]
Arc length from End A in m, or a series ``(first, pitch, last)``.
mass : float
Dry mass, in kg.
volume : float
Displaced volume, in m^3.
cda : float
Normal drag area, in m^2.
ca : float
Added-mass coefficient.
cdax : float | None
Optional axial drag area, in m^2.
"""
line: Line
arc_length: float | tuple[float, float, float]
mass: float = 0.0
volume: float = 0.0
cda: float = 0.0
ca: float = 0.0
cdax: float | None = None
@dataclass(eq=False)
class Stiffener:
"""One ``STIFFENERS`` row: a conical segment of a bend stiffener on a finite-EI line.
The rows of one line end follow each other outward from the stiffener root, each starting
where the previous one ends; a cylindrical root, a cone and a tip are three rows.
Attributes
----------
line : Line
The finite-EI line.
end : str
The end the stiffener sleeves, ``A`` or ``B``.
length : float
Length of the segment, in m.
root_od : float
Outer diameter at the segment's root side, in m.
tip_od : float
Outer diameter at the segment's tip side, in m.
inner_d : float
Inner diameter, in m.
modulus : float
Young's modulus of the stiffener material, in Pa.
density : float
Density of the stiffener material, in kg/m^3.
"""
line: Line
end: str
length: float
root_od: float
tip_od: float
inner_d: float
modulus: float
density: float
@dataclass(eq=False)
class SyropeIC:
"""One ``SYROPE IC`` row: the prior load history of Syrope lines.
Attributes
----------
lines : list[Line]
The lines with a Syrope section (alone or in a composite line).
tmax0 : float
Running maximum tension, in N.
tmean0 : float
Mean tension, in N.
"""
lines: list[Line]
tmax0: float
tmean0: float
@dataclass(eq=False)
class Failure:
"""One ``FAILURE`` row. Its ``FailID`` is its position in :attr:`DeckModel.failures`.
Attributes
----------
point : Point
The point the lines detach from.
lines : list[Line]
The lines that detach; each must attach to :attr:`point`.
fail_time : float
Trigger time in s; ``0`` disables the time trigger.
fail_tension : float
Trigger tension in N; ``0`` disables the tension trigger.
"""
point: Point
lines: list[Line]
fail_time: float = 0.0
fail_tension: float = 0.0
@dataclass(eq=False)
class Control:
"""One ``CONTROL`` row: lines driven by an OpenFAST cable-control channel.
Attributes
----------
channel : int
Positive control channel.
lines : list[Line]
The controlled lines.
"""
channel: int
lines: list[Line]
@dataclass(eq=False)
class ExternalLoad:
"""One ``EXTERNAL LOADS`` row on a Rigid6 body.
Attributes
----------
id : int
Row id; the rows are numbered 1, 2, 3, ... in deck order.
body : Body | MoorDynBody
The loaded Rigid6 body.
csys : str
``G`` (global axes) or ``L`` (body axes).
force : float | tuple[float, ...]
``0`` or ``(f1, f2, f3)``, in N.
blin : float | tuple[float, ...]
Linear damping, one value or three, in N s/m.
bquad : float | tuple[float, ...]
Quadratic damping, one value or three, in N s^2/m^2.
"""
id: int
body: AnyBody
csys: str = "G"
force: float | tuple[float, ...] = 0.0
blin: float | tuple[float, ...] = 0.0
bquad: float | tuple[float, ...] = 0.0
@dataclass(eq=False)
class Option:
"""One ``OPTIONS`` row.
Attributes
----------
keyword : str
Option keyword as written (case-insensitive; native aliases allowed).
values : tuple[str, ...]
Value tokens: one for a scalar option; several for ``dynamic_solver``
and the positional ``waves``/``current``/``wavetrain`` forms.
description : str | None
Text written after a `` - `` separator.
"""
keyword: str
values: tuple[str, ...]
description: str | None = None
@property
def value(self) -> str:
"""The first value token."""
return self.values[0]
# --------------------------------------------------------------------------- rendering
def _num(value: object, what: str) -> str:
"""Render a number as the shortest token that parses back to the same float."""
if isinstance(value, bool) or not isinstance(value, numbers.Real):
raise TypeError(f"{what} must be a number, got {value!r}")
return repr(float(value))
def _int(value: Any, what: str) -> str:
if isinstance(value, bool):
raise TypeError(f"{what} must be an integer, got {value!r}")
try:
return str(operator.index(value))
except TypeError as exc:
raise TypeError(f"{what} must be an integer, got {value!r}") from exc
def _text(value: object, what: str, *, quote: bool = True) -> str:
"""Render one text token (quoted where the native reader needs it).
In a text column (``quote``) a name with interior spaces, such as
``"my chain"``, is written quoted: the native reader keeps a quoted value
whole.
"""
if not isinstance(value, str):
raise TypeError(f"{what} must be a string, got {value!r}")
try:
return _render(value, text=quote)
except ValueError as exc:
if quote and " " in value and value == value.strip(" "):
with contextlib.suppress(ValueError):
return f'"{_render_quoted_text(value)}"'
raise ValueError(f"{what}: {exc}") from exc
def _multi(value: object, what: str) -> str:
"""Render a number or a sequence of numbers as a ``a|b|c`` token."""
if isinstance(value, (tuple, list)):
if not value:
raise ValueError(f"{what} must not be empty")
return "|".join(_num(item, what) for item in value)
return _num(value, what)
def _vec(value: object, size: int, what: str) -> list[str]:
if not isinstance(value, (tuple, list)) or len(value) != size:
raise ValueError(f"{what} must be a sequence of {size} numbers")
return [_num(item, what) for item in value]
def _end_letter(end: object) -> str:
if not isinstance(end, str):
raise TypeError(f"end must be a string, got {end!r}")
try:
return _end_connection_end(end).upper()
except ValueError as exc:
raise ValueError(f"end must be A or B, got {end!r}") from exc
def _table(header: str, units: str, rows: list[list[str]]) -> list[str]:
"""Return a section's header, units, and aligned data rows."""
table = [header.split(), units.split(), *rows]
widths: dict[int, int] = {}
for row in table:
for column, token in enumerate(row):
widths[column] = max(widths.get(column, 0), len(token))
out: list[str] = []
for row in table:
cells = [token.ljust(widths[column]) for column, token in enumerate(row)]
out.append(" ".join(cells).rstrip())
return out
# --------------------------------------------------------------------------- parsing
def _f(token: str) -> float:
return _table_float(token)
def _fmulti(token: str) -> float | tuple[float, ...]:
parts = token.split("|")
if len(parts) == 1:
return _f(parts[0])
return tuple(_f(part) for part in parts)
def _f3(tokens: Sequence[str]) -> Vec3:
return (_f(tokens[0]), _f(tokens[1]), _f(tokens[2]))
def _ids(text: str) -> list[int]:
return [_native_int(value) for value in text.split(",")]
def _key(value: int | str) -> int | str:
if isinstance(value, bool):
raise TypeError(f"object keys must be an integer id or a name, got {value!r}")
if isinstance(value, str):
return value.lower()
return operator.index(value)
_T = TypeVar("_T")
class ObjectCollection(Generic[_T]):
"""A live, read-only view of one kind of model object, looked up by id or name.
Iteration yields the objects in deck order. ``collection[key]`` returns
the object with that integer id (points, lines, bodies, rods, turbines)
or case-insensitive name (line and rod types). Add, rename, and remove
objects through :class:`DeckModel`.
"""
def __init__(self, items: list[_T], key: Callable[[_T], int | str], label: str) -> None:
self._items = items
self._keyfn = key
self._label = label
def __iter__(self) -> Iterator[_T]:
return iter(tuple(self._items))
def __len__(self) -> int:
return len(self._items)
def __contains__(self, item: object) -> bool:
if isinstance(item, (int, str)) and not isinstance(item, bool):
return self.get(item) is not None
return any(existing is item for existing in self._items)
def __getitem__(self, key: int | str) -> _T:
found = self.get(key)
if found is None:
raise KeyError(f"{self._label} {key!r} does not exist")
return found
def get(self, key: int | str) -> _T | None:
"""Return the object with ``key``, or ``None``.
Parameters
----------
key : int | str
Integer id, or case-insensitive name.
Returns
-------
object | None
The first matching object in deck order.
"""
wanted = _key(key)
for item in self._items:
stored = self._keyfn(item)
if isinstance(stored, str):
stored = stored.lower()
if not isinstance(stored, bool) and stored == wanted:
return item
return None
def keys(self) -> list[int | str]:
"""Return the ids or names in deck order."""
return [self._keyfn(item) for item in self._items]
def next_id(self) -> int:
"""Return one more than the largest integer id (1 for an empty collection)."""
ids = [key for key in self.keys() if isinstance(key, int)]
return max(ids, default=0) + 1
def __repr__(self) -> str:
return f"<{self._label} collection: {self.keys()!r}>"
class OptionSet:
"""The ``OPTIONS`` rows of a model, in deck order.
A keyword may appear more than once (the last row wins natively, and
``wavetrain`` rows add up). Lookups match native aliases
case-insensitively, so ``dt`` finds a ``dtM`` row.
"""
def __init__(self) -> None:
self._rows: list[Option] = []
def __iter__(self) -> Iterator[Option]:
return iter(tuple(self._rows))
def __len__(self) -> int:
return len(self._rows)
def __contains__(self, keyword: object) -> bool:
return isinstance(keyword, str) and self.get(keyword) is not None
def __repr__(self) -> str:
return f"<OPTIONS: {[row.keyword for row in self._rows]!r}>"
@staticmethod
def _identity(keyword: str) -> str:
return _option_key(keyword)
def get(self, keyword: str) -> Option | None:
"""Return the effective (last) row for ``keyword`` or an alias, or ``None``.
Parameters
----------
keyword : str
Option keyword or native alias (case-insensitive).