Repository navigation
Expand file tree
/
Copy pathdeck_file.py
More file actions
5340 lines (5035 loc) · 247 KB
/
Copy pathdeck_file.py
File metadata and controls
5340 lines (5035 loc) · 247 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
"""Loss-aware reading, validation, editing, and case generation for decks.
The reader mirrors the native Fortran deck reader: records end at ``\\r\\n``,
``\\n``, or ``\\r``; a leading UTF-8 byte-order mark is not deck text; ``#``,
``!``, and a whitespace-led ``--`` start comments; rows are split on ASCII
whitespace (space, tab, CR, LF, FF, VT), and a NUL or non-ASCII whitespace
character outside a comment is rejected; table rows are read with Fortran
list-directed semantics, so text columns may be quoted while numeric columns
must be plain unquoted Fortran numbers.
"""
from __future__ import annotations
import contextlib
import copy
import hashlib
import itertools
import json
import math
import os
import re
import sys
import tempfile
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from pathlib import Path, PureWindowsPath
from types import MappingProxyType
from cabledyn._paths import windows_device_component
from cabledyn.errors import DeckFormatError
_SECTION_ALIASES = {
"LINE TYPES": "LINE TYPES",
"LINETYPES": "LINE TYPES",
"LINE DICTIONARY": "LINE TYPES",
"BODIES": "BODIES",
"BODY": "BODIES",
"POINTS": "POINTS",
"CONNECTION PROPERTIES": "POINTS",
"POINT PROPERTIES": "POINTS",
"CONNECTS": "POINTS",
"LINES": "LINES",
"LINE PROPERTIES": "LINES",
"SECTIONS": "SECTIONS",
"OPTIONS": "OPTIONS",
"SOLVER OPTIONS": "OPTIONS",
"OUTPUTS": "OUTPUTS",
"OUTPUT": "OUTPUTS",
"ROD TYPES": "ROD TYPES",
"RODTYPES": "ROD TYPES",
"ROD DICTIONARY": "ROD TYPES",
"RODS": "RODS",
"ROD LIST": "RODS",
"ROD PROPERTIES": "RODS",
"EQUIVALENT BUOYANCY": "EQUIVALENT BUOYANCY",
"EQUIVALENT SECTIONS": "EQUIVALENT BUOYANCY",
"BUOYANCY SECTIONS": "EQUIVALENT BUOYANCY",
"FAILURE": "FAILURE",
"FAILURES": "FAILURE",
"CONTROL": "CONTROL",
"CONTROLS": "CONTROL",
"SYROPE IC": "SYROPE IC",
"END CONNECTIONS": "END CONNECTIONS",
"END CONNECTION": "END CONNECTIONS",
"TURBINES": "TURBINES",
"TURBINE": "TURBINES",
"EXTERNAL LOADS": "EXTERNAL LOADS",
"EXTERNAL LOAD": "EXTERNAL LOADS",
"ATTACHMENTS": "ATTACHMENTS",
"LINE ATTACHMENTS": "ATTACHMENTS",
"CLUMPS": "ATTACHMENTS",
"STIFFENERS": "STIFFENERS",
"STIFFENER": "STIFFENERS",
"BEND STIFFENERS": "STIFFENERS",
"BEND STIFFENER": "STIFFENERS",
}
# Table sections whose rows the native reader takes through a Fortran
# list-directed READ. Their descriptive and units rows are recognized by the
# native rule "the row has no token that reads as a real number".
_LIST_DIRECTED_SECTIONS = frozenset(
{
"LINE TYPES",
"BODIES",
"ROD TYPES",
"RODS",
"POINTS",
"LINES",
"SECTIONS",
"EQUIVALENT BUOYANCY",
"END CONNECTIONS",
"TURBINES",
"EXTERNAL LOADS",
}
)
# Table sections the native reader splits on whitespace and parses column by
# column (their comma-separated line lists are valid there).
_WHITESPACE_TABLE_SECTIONS = frozenset(
{"FAILURE", "CONTROL", "SYROPE IC", "ATTACHMENTS", "STIFFENERS"}
)
_TABLE_SECTIONS = _LIST_DIRECTED_SECTIONS | _WHITESPACE_TABLE_SECTIONS
_NATIVE_RECORD_LENGTH = 512
_INT32_MAX = 2**31 - 1
# Largest dtM/TMax step count the native driver indexes (default INTEGER - 1).
_NATIVE_MAX_STEPS = 2**31 - 2
# The native token separators: space, tab, CR, LF, FF, VT (ASCII whitespace).
_WHITESPACE = " \t\r\n\f\v"
# ROD TYPES header names that mark columns 6-7 as the retired CableDyn axial
# coefficients (rejected) or as MoorDyn's end coefficients.
_LEGACY_ROD_AXIAL_NAMES = frozenset(
{"cdax", "caax", "cd_ax", "ca_ax", "cdt", "cat", "cd_t", "ca_t"}
)
_ROD_END_NAMES = frozenset({"cdend", "caend", "cd_end", "ca_end"})
_TOKEN = re.compile(r"[^ \t\r\n\f\v]+")
_ASCII_UPPER = str.maketrans("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
_UTF8_BOM = ""
# Native numeric_token_shape: [sign] digits [. digits] (or [sign] . digits) with an optional
# exponent e/E/d/D [sign] digits. A list-directed READ would also take "1+2" as 1e2 and
# "10-5" as 1e-4; neither is a number to the native reader.
_FORTRAN_REAL = re.compile(r"([+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+))(?:[EeDd]([+-]?[0-9]+))?")
_NUMBER_CHARACTERS = frozenset("0123456789.+-eEdD")
# A table column is read by a list-directed READ, which also takes a q/Q exponent (a
# token outside the characters above, so list_safe_row leaves it to that READ).
_TABLE_REAL = re.compile(r"([+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+))(?:[EeDdQq]([+-]?[0-9]+))?")
_FORTRAN_SPECIAL_REAL = re.compile(r"[+-]?(?:inf|infinity|nan)", re.IGNORECASE)
_FORTRAN_INTEGER = re.compile(r"[+-]?[0-9]+")
_LIST_REPEAT = re.compile(r"[0-9]+\*")
_LIST_SEPARATORS = frozenset("/,;")
_FIELDS = {
"line_type": ("name", "diam", "mass", "ea", "ba", "ei", "cdn", "cdt", "can", "cat"),
"point": ("id", "type", "x", "y", "z", "mass", "vol", "cda", "ca"),
"line": ("id", "nodea", "nodeb", "outputs"),
"section": ("lineid", "linetype", "length", "numsegs"),
"end_connection": (
"lineid",
"end",
"stiffness",
"ezx",
"ezy",
"ezz",
"torsstiffness",
"nxx",
"nxy",
"nxz",
"pretwist",
),
}
_PATH_OPTIONS = {
"bathymetryfile",
"bathymetry_file",
"seafloorfile",
"seafloor_file",
"motionfile",
"vesselmotion",
"vesselrao",
"wavekin",
"waterkin",
}
_PATH_OPTION_GROUP = {
"bathymetryfile": "bathymetry",
"bathymetry_file": "bathymetry",
"seafloorfile": "bathymetry",
"seafloor_file": "bathymetry",
"motionfile": "motion",
"vesselmotion": "vesselmotion",
"vesselrao": "vesselrao",
"wavekin": "waterkin",
"waterkin": "waterkin",
}
_OPTION_ALIASES = {
"g": "gravity",
"gravity": "gravity",
"rhow": "water_density",
"wtrdnsty": "water_density",
"water_density": "water_density",
"wtrdpth": "water_depth",
"water_depth": "water_depth",
"bathymetryfile": "bathymetry",
"bathymetry_file": "bathymetry",
"seafloorfile": "bathymetry",
"seafloor_file": "bathymetry",
"kbot": "kbot",
"kb": "kbot",
"cbot": "cbot",
"cb": "cbot",
"dtm": "dtm",
"dt": "dtm",
"rhoinf": "rhoinf",
"rho_inf": "rhoinf",
"modified_newton": "modified_newton",
"modifiednewton": "modified_newton",
"adaptive_mesh": "adaptive_mesh",
"adaptivemesh": "adaptive_mesh",
"cable_load_feedback": "cable_load_feedback",
"cableloadfeedback": "cable_load_feedback",
"tensile_safety": "tensile_safety",
"tensilesafety": "tensile_safety",
"tensile_strain_tolerance": "tensile_strain_tolerance",
"tensilestraintolerance": "tensile_strain_tolerance",
"recovery_max_substeps": "recovery_max_substeps",
"recoverymaxsubsteps": "recovery_max_substeps",
"axial_quadrature_order": "axial_quadrature_order",
"axialquadratureorder": "axial_quadrature_order",
"axial_quadrature": "axial_quadrature_order",
"bending_quadrature_order": "bending_quadrature_order",
"bendingquadratureorder": "bending_quadrature_order",
"bending_quadrature": "bending_quadrature_order",
"frictionmu": "friction",
"mu": "friction",
"frictioncoefficient": "friction",
"frictionmuaxial": "friction_axial",
"frictionmu_axial": "friction_axial",
"mu_axial": "friction_axial",
"muaxial": "friction_axial",
"frictionmulateral": "friction_lateral",
"frictionmu_lateral": "friction_lateral",
"mu_lateral": "friction_lateral",
"mulateral": "friction_lateral",
"frictionmunormal": "friction_lateral",
"frictionmu_normal": "friction_lateral",
"wave": "waves",
"waves": "waves",
"wavekin": "waterkin",
"waterkin": "waterkin",
"ramptime": "ramp_time",
"ramp_time": "ramp_time",
"tramp": "ramp_time",
"maxstrain": "max_strain",
"max_strain": "max_strain",
"vivrmswindow": "viv_rms_window",
"viv_rms_window": "viv_rms_window",
"rangestart": "range_start",
"range_start": "range_start",
"waveseed": "wave_seed",
"wave_seed": "wave_seed",
"wavespreading": "wave_spreading",
"wave_spreading": "wave_spreading",
"wavedirections": "wave_directions",
"wave_directions": "wave_directions",
"wavecomponents": "wave_components",
"wave_components": "wave_components",
"streamorder": "stream_order",
"stream_order": "stream_order",
"nmodes": "n_modes",
"n_modes": "n_modes",
"modes": "n_modes",
"alpha_force_blend": "alpha_force_blend",
"alphaforceblend": "alpha_force_blend",
"ei0_substeps": "ei0_substeps",
"ei0substeps": "ei0_substeps",
"ei0_substep_angle": "ei0_substep_angle",
"ei0substepangle": "ei0_substep_angle",
"ei0_substep_max": "ei0_substep_max",
"ei0substepmax": "ei0_substep_max",
"cable_statics": "cable_statics",
"cablestatics": "cable_statics",
"staticsfriction": "statics_friction",
"statics_friction": "statics_friction",
"staticsseabedfrictionpolicy": "statics_friction",
"seabedfrictionpolicy": "statics_friction",
"layazimuth": "lay_azimuth",
"lay_azimuth": "lay_azimuth",
"aslaidtension": "as_laid_tension",
"as_laid_tension": "as_laid_tension",
"outputrecovery": "output_recovery",
"output_recovery": "output_recovery",
}
# Per-line static friction rows (native apply_option): ``layAzimuth<ID>`` and ``asLaidTension<ID>``
# with the LINE id appended; the id is a plain decimal suffix, and leading zeros name the same line.
_LINE_OPTION_PATTERN = re.compile(r"(layazimuth|aslaidtension)([0-9]+)\Z")
_LINE_OPTION_FAMILIES = {"layazimuth": "lay_azimuth", "aslaidtension": "as_laid_tension"}
_STATICS_FRICTION_POLICIES = frozenset({"aslaid", "as_laid", "as-laid", "none"})
_SCALAR_OPTION_KEYWORDS = frozenset(_OPTION_ALIASES) | {
"icmode",
"bodyic",
"bodyscheme",
"bodysubstep",
"dtwave",
"wvhicoff",
"bodywetting",
"bodyhydro",
"rodhydro",
"tmax",
"motionfile",
"vesselmotion",
"vesselrao",
"vesselref",
"current",
"tscheme",
"dtic",
"tmaxic",
"cdscaleic",
"threshic",
"writelog",
"dtout",
"currents",
"inertialf",
"inertialf_rampt",
}
# Native CD_DECK_NAMELEN: the longest OUTPUTS channel name the reader stores.
_NATIVE_NAME_LENGTH = 64
_STOCK_LINE_FIELDS = ("lineid", "linetype", "nodea", "nodeb", "length", "numsegs", "outputs")
_NATIVE_MAX_SEGMENTS = 1_000_000
# Native admissible magnitudes (CableDyn_DeckDriver section/line-type validation).
_NATIVE_MAX_SECTION_LENGTH = 1.0e6
_NATIVE_MIN_SEGMENT_LENGTH = 1.0e-6
_NATIVE_MAX_EA = 1.0e15
_NATIVE_MAX_ABS_MASS = 1.0e6
_NATIVE_MAX_DIAMETER = 1.0e3
# Native admissible input magnitudes (driver_format.md "Admissible input ranges").
_NATIVE_MAX_COORDINATE = 1.0e6
_NATIVE_MAX_COEFFICIENT = 1.0e15
_NATIVE_MAX_SMALL_COEFFICIENT = 1.0e3
# Relative band around the displaced water mass within which a line type is neutrally buoyant
# (the native NEUTRAL_BUOYANCY_REL_TOL).
_NATIVE_NEUTRAL_BUOYANCY_REL_TOL = 1.0e-6
_NATIVE_MIN_EA = 1.0e-3
_NATIVE_MIN_DIAMETER = 1.0e-6
_NATIVE_MAX_GRAVITY = 1.0e3
_NATIVE_MAX_WATER_DENSITY = 1.0e5
_NATIVE_MAX_FLUID_SPEED = 1.0e3
_NATIVE_MAX_WAVE_HEIGHT = 1.0e3
_NATIVE_WAVE_PERIOD_RANGE = (0.1, 1.0e5)
_DISABLED_MOTION_FILE_VALUES = frozenset({"0", "none"})
# Alternative prescribed-motion sources (native apply_option): only one may be active.
_MOTION_SOURCE_KEYWORDS = ("motionfile", "vesselmotion", "vesselrao")
# Native STATIC_CHECK_HINT: appended to the errors that ask a standalone deck without TMax for
# the march (those naming one of the cues).
_STATIC_CHECK_HINT = "; to check a dynamic deck's static start only, give TMax = 0"
_STATIC_CHECK_CUES = ("dtM and TMax", "requires dtM", "require dtM", "dynamic deck (TMax)")
_END_CONNECTION_ENDS = {
"a": "a",
"enda": "a",
"end_a": "a",
"b": "b",
"endb": "b",
"end_b": "b",
}
_PINNED_END_CONNECTIONS = frozenset({"pinned", "free", "zero"})
# Host-driven (platform-borne) BODIES types, MoorDyn aliases included (native append_body)
_HOST_BODY_TYPES = frozenset({"coupled", "vessel", "cpld", "ves"})
# native apply_option: MoorDyn-F's inertialF other than 1
_INERTIAL_F_MESSAGE = (
"CableDyn returns the inertia of coupled bodies and rods with their coupled loads, as "
"MoorDyn-F's inertialF 1; inertialF 0 (MoorDyn-F's default: no inertia) and 2 (the inertia "
"ramped in) are not supported: use 1 or remove the row"
)
# Bodies pinned to a host node (MoorDyn CoupledPinned/VesselPinned): coupled hosts only
_PINNED_BODY_TYPES = frozenset({"coupledpinned", "cpldpin", "vesselpinned", "vespin"})
_PINNED_BODY_HOST_MESSAGE = (
"CoupledPinned/VesselPinned BODY requires a coupled host (OpenFAST CompMooring = 5); in a "
"standalone deck use a Free body, or a Coupled body with a motionFile"
)
_RIGID6_DYNAMIC_MESSAGE = "Rigid6 BODY requires a dynamic deck with dtM and TMax"
_PINNED_BODY_VALUE_MESSAGE = (
"CoupledPinned/VesselPinned BODY requires Ixx/Iyy/Izz > 0 and non-negative Mass/Vol/CdA/Ca"
)
# MoorDyn RODS attachment aliases (native append_rod)
_ROD_ATTACHMENT_ALIASES = {
"anchor": "fixed",
"fix": "fixed",
"pin": "pinned",
"point": "free",
"con": "free",
"ves": "vessel",
"cpld": "coupled",
"cpldpin": "coupledpinned",
"vesselpinned": "coupledpinned",
"vespin": "coupledpinned",
}
_RIGID_END_CONNECTIONS = frozenset({"rigid", "infinity", "inf"})
# TorsStiffness keywords of an end free to twist (a numeric 0 is free too)
_FREE_TORSION_KEYWORDS = frozenset({"free", "zero"})
# native CD_HTORS_MAX_TWIST: the largest imposed static twist, 1000 turns
_MAX_STATIC_TWIST_DEG = 360000.0
# Native TORS_NX_PARALLEL_TOL: smallest |Nx x Ez| of unit vectors (about 0.06 degrees off Ez).
_TORSION_NORMAL_PARALLEL_TOL = 1.0e-3
_WATERKIN_FILENAME_LETTERS = frozenset("abcdfghijklmnopqrstuvwxyzABCDFGHIJKLMNOPQRSTUVWXYZ")
# MoorDyn-C kinematics files the native reader opens by fixed name in the deck folder
# (read_moordyn_c_kinematics): WaveKin 3, WaveKin 7 and Currents 1, 2 and 5.
_MOORDYN_C_WAVE_FILES = {3: "wave_elevation.txt", 7: "wave_frequencies.txt"}
_MOORDYN_C_CURRENT_FILES = {
1: "current_profile.txt",
2: "current_profile_dynamic.txt",
5: "current_profile_4d.txt",
}
def _moordyn_c_wave_kin(value: str | None) -> int:
"""Return the MoorDyn-C numeric WaveKin mode (3 or 7) a WaterKin value selects, else 0."""
if value is None:
return 0
value = _strip_quotes(value)
if value.lower() in {"none", "seastate"} or any(
character in _WATERKIN_FILENAME_LETTERS for character in value
):
return 0
mode = round(_native_float(value)) # a validated WaterKin row reads as a finite number
return mode if mode in _MOORDYN_C_WAVE_FILES else 0
def _moordyn_c_currents(value: str | None) -> int:
"""Return the MoorDyn-C ``Currents`` mode (0, 1, 2 or 5) of a validated row value."""
if value is None:
return 0
mode = round(_native_float(value))
return mode if mode in _MOORDYN_C_CURRENT_FILES else 0
def _comment_position(text: str) -> int | None:
"""Return where the native ``scan_comment`` rules start a comment, if anywhere."""
positions = [position for marker in ("#", "!") if (position := text.find(marker)) >= 0]
if "---" not in text:
search_from = 0
while (position := text.find("--", search_from)) >= 0:
if position == 0 or text[position - 1] in _WHITESPACE:
positions.append(position)
break
search_from = position + 2
return min(positions) if positions else None
def _strip_inline_comment(text: str) -> str:
"""Return ``text`` without its native inline comment and trailing blanks."""
position = _comment_position(text)
return (text if position is None else text[:position]).rstrip(_WHITESPACE)
def _character_error(visible: str) -> str | None:
"""Mirror the native ``record_charset_status`` check of non-comment text.
A NUL character, or a non-ASCII whitespace character such as a no-break
space, is not a token separator; the native reader rejects both rather
than let them hide inside a token.
"""
if "\x00" in visible:
return "contains a NUL character outside a comment; save the file as plain text"
for character in visible:
if not character.isascii() and character.isspace():
return (
f"contains the non-ASCII whitespace character U+{ord(character):04X} outside "
"a comment; separate values with ASCII spaces or tabs"
)
return None
def _ascii_upper(text: str) -> str:
"""Upper-case ASCII letters only, as the native section-name matcher does."""
return text.translate(_ASCII_UPPER)
def _split_records(text: str) -> tuple[list[str], list[str]]:
"""Split text into records and their terminators exactly like the native reader.
Only ``\\r\\n``, ``\\n``, and ``\\r`` end a record; other Unicode line
separators (form feed, U+2028, ...) are ordinary record content.
"""
lines: list[str] = []
endings: list[str] = []
start = 0
for match in re.finditer(r"\r\n|\n|\r", text):
lines.append(text[start : match.start()])
endings.append(match.group())
start = match.end()
if start < len(text):
lines.append(text[start:])
endings.append("")
return lines, endings
def _row_tokens(text: str) -> list[str]:
"""Split a native row on the native token separators (ASCII whitespace)."""
return re.findall(_TOKEN, text)
def _token_spans(text: str) -> list[tuple[int, int]]:
return [match.span() for match in re.finditer(_TOKEN, text)]
def _quoted_token_spans(text: str) -> list[tuple[int, int]]:
"""Mirror the native ``token_bounds`` tokenizer used for table rows.
Tokens are separated by ASCII whitespace, except that a token opening with
a quote runs to the matching close quote (keeping any whitespace inside it)
and then on to the next separator. An unterminated quote runs to the end
of the row.
"""
spans: list[tuple[int, int]] = []
position, length = 0, len(text)
while True:
while position < length and text[position] in _WHITESPACE:
position += 1
if position >= length:
return spans
start = position
if text[position] in "\"'":
close = text.find(text[position], position + 1)
position = length if close < 0 else close + 1
while position < length and text[position] not in _WHITESPACE:
position += 1
spans.append((start, position))
def _quoted_row_tokens(text: str) -> list[str]:
"""Split a table row into the tokens the native list-directed reader sees."""
return [text[start:stop] for start, stop in _quoted_token_spans(text)]
def _dequote(raw: str, where: str) -> tuple[str, bool]:
"""Return the list-directed value of one raw token and whether it was quoted."""
if raw[0] not in "\"'":
return raw, False
quote = raw[0]
if len(raw) < 3 or raw[-1] != quote or quote in raw[1:-1]:
raise DeckFormatError(
f"{where}: invalid quoting in token {raw}; a quoted value must be "
"non-empty text inside one pair of matching quotes"
)
return raw[1:-1], True
def _strip_quotes(value: str) -> str:
"""Mirror the native ``strip_quotes`` used for path-valued options."""
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
return value[1:-1]
return value
def _has_list_separator(raw: str) -> bool:
"""True when list-directed input would not take an unquoted token whole."""
return (
any(character in _LIST_SEPARATORS for character in raw)
or _LIST_REPEAT.match(raw) is not None
)
def _render(value: object, *, text: bool = False) -> str:
"""Render one value as a token the native reader takes back unchanged.
``text`` marks a list-directed character column: a value that holds a
list-directed separator (``/``, ``,``, ``;``) or starts with a repeat count
(``3*``) is quoted there. Values that no native reader can take back as a
single token raise ``ValueError``.
"""
if value is None:
raise ValueError("deck values must not be None")
if isinstance(value, bool):
return "True" if value else "False"
if isinstance(value, float):
# the shortest text that reads back as the same double (0.1, not
# 0.10000000000000001); a whole number keeps its integer spelling (510)
shortest = repr(value)
return shortest[:-2] if shortest.endswith(".0") else shortest
if not isinstance(value, (int, str)):
raise ValueError(
f"deck values must be a number, Boolean, or string, not {type(value).__name__}"
)
rendered = str(value)
if not rendered:
raise ValueError("native deck tokens must not be empty")
if any(character.isspace() for character in rendered):
raise ValueError(f"native deck tokens cannot contain whitespace: {rendered!r}")
if '"' in rendered or "'" in rendered:
raise ValueError(f"native deck tokens cannot contain quotes: {rendered!r}")
if "#" in rendered or "!" in rendered or rendered.startswith("--") or "---" in rendered:
raise ValueError(f"native deck tokens cannot contain comment/header markers: {rendered!r}")
if text and _has_list_separator(rendered):
rendered = f'"{rendered}"'
return rendered
def _is_csys_token(token: str) -> bool:
"""An EXTERNAL LOADS CSys entry: G, L, or MoorDyn-F's ``-`` (refused for a body)."""
return len(token) == 1 and token in "GgLl-"
def _render_quoted_text(value: str) -> str:
"""Check text written inside double quotes, where spaces are allowed.
The native reader keeps a quoted token whole, spaces included; a quote,
a comment marker, or a line or tab character cannot be written there.
"""
if not value:
raise ValueError("native deck tokens must not be empty")
if any(character in "\"'\t\r\n\f\v" for character in value):
raise ValueError(f"a quoted deck value cannot contain quotes or line breaks: {value!r}")
if _comment_position(value) is not None or "---" in value:
raise ValueError(f"native deck tokens cannot contain comment/header markers: {value!r}")
return value
def _reads_as_real(raw: str) -> bool:
"""Mirror the native ``numeric_token_shape``: the token is spelled as one number.
This is the native header-row test: a row with no such token is a column
name or units row.
"""
return (
_FORTRAN_REAL.fullmatch(raw) is not None or _FORTRAN_SPECIAL_REAL.fullmatch(raw) is not None
)
def _has_numeric_token(tokens: list[str]) -> bool:
return any(_reads_as_real(token) for token in tokens)
def _native_float(token: str) -> float:
"""Parse one plain Fortran real token.
Accepts an optional sign, a mantissa with optional decimal point, and an
optional exponent written with ``E``/``D``/``Q`` (either case) or as a bare
signed exponent (``3.0+6``), plus ``Inf``/``Infinity``/``NaN``. Anything
else, including ``_`` digit separators, raises ``ValueError``.
"""
value = _fortran_real_value(token)
if value is None:
raise ValueError(f"{token!r} is not a Fortran real number")
if _is_subnormal(value):
raise ValueError(f"{token!r} is subnormal; write 0 or a normal number")
return value
def _table_float(token: str) -> float:
"""Parse a number in a table column (list-directed READ: a q/Q exponent is allowed)."""
match = _TABLE_REAL.fullmatch(token)
if match is None:
return _native_float(token)
mantissa, exponent = match.groups()
value = float(mantissa if exponent is None else f"{mantissa}e{exponent}")
if _is_subnormal(value):
raise ValueError(f"{token!r} is subnormal; write 0 or a normal number")
return value
def _keyword_column_real(token: str) -> float | None:
"""Mirror the native ``parse_real_token`` on a keyword column (END CONNECTIONS stiffnesses).
The value of a plain real (``E``/``D`` exponent, no ``Q``; quotes removed as the
list-directed READ of a character column does), or ``None`` when the token is not a
number or is NaN, infinite or subnormal.
"""
value = _fortran_real_value(_strip_quotes(token))
if value is None or not math.isfinite(value) or _is_subnormal(value):
return None
return value
def _fortran_real_value(token: str) -> float | None:
"""Return what a native list-directed ``READ (token, *) real`` gives, or ``None``."""
match = _FORTRAN_REAL.fullmatch(token)
if match is not None:
mantissa, exponent = match.groups()
return float(mantissa if exponent is None else f"{mantissa}e{exponent}")
if _FORTRAN_SPECIAL_REAL.fullmatch(token) is not None:
return float(token)
return None
def _is_subnormal(value: float) -> bool:
return math.isfinite(value) and value != 0.0 and abs(value) < sys.float_info.min
def _real_token_defect(token: str) -> str | None:
"""Mirror the native ``real_token_defect``: why a numeric token is inadmissible.
A token that reads whole as a real number must be finite (not NaN, Inf, or a
decimal beyond the double range) and not subnormal. Tokens that are not numbers
at all (names, paths) return ``None``; their own readers judge them.
"""
token = token.strip(_WHITESPACE)
if not token or any(character in " \"'/,;*\t" for character in token):
return None
value = _fortran_real_value(token)
if value is None:
return None
if not math.isfinite(value):
return (
f"value {token!r} is not a finite number (NaN, Inf and magnitudes beyond "
"1.8e308 are not accepted)"
)
if _is_subnormal(value):
return (
f"value {token!r} is subnormal (a nonzero magnitude below 2.2e-308); "
"write 0 or a normal number"
)
return None
def _check_section_magnitude(length: float, segments: int, where: str) -> None:
"""Mirror the native section magnitude gate (length and segment length)."""
if length > _NATIVE_MAX_SECTION_LENGTH or length / segments < _NATIVE_MIN_SEGMENT_LENGTH:
raise DeckFormatError(
f"{where}: section Length must be at most 1e6 m with segments of at least 1e-6 m"
)
def _native_int(token: str) -> int:
"""Parse one Fortran default-INTEGER token (sign and digits, 32-bit range)."""
if _FORTRAN_INTEGER.fullmatch(token) is None:
raise ValueError(f"{token!r} is not a Fortran integer")
value = int(token)
if not -_INT32_MAX - 1 <= value <= _INT32_MAX:
raise ValueError(f"{token!r} does not fit a 32-bit Fortran integer")
return value
def _native_id_suffix(text: str) -> int:
"""Mirror the native ``int_suffix``: all digits, positive, 32-bit; else 0."""
if not text or not text.isascii() or not text.isdigit():
return 0
value = int(text)
return value if value <= _INT32_MAX else 0
def _native_positive_int(text: str, first: int, last: int) -> int:
"""Mirror the native ``parse_positive_int`` on 1-based inclusive ``text[first:last]``."""
if first > last or first < 1 or last > len(text):
return 0
return _native_id_suffix(text[first - 1 : last])
def _parse_line_node_channel(lowered: str) -> tuple[int, int, int, int]:
"""Mirror the native ``parse_line_node_channel``: (line, node, kind, component)."""
last = len(lowered)
if lowered.startswith("twist") and last > 5 and "n" not in lowered[5:]:
# Twist<L>: the line's total twist (node 1)
line_id = _native_positive_int(lowered, 6, last)
return (line_id, 1, 11, 0) if line_id > 0 else (line_id, 0, 0, 0)
for keyword, code in (
("torq", 9),
("twist", 10),
("ten", 3),
("curvx", 13),
("curvy", 14),
("curv", 5),
("bendmom", 6),
("stfmom", 12),
):
if lowered.startswith(keyword):
prefix = len(keyword)
separator = lowered.find("n", prefix)
if last <= prefix or separator < 0:
return 0, 0, 0, 0
line_id = _native_positive_int(lowered, prefix + 1, separator)
node_id = _native_positive_int(lowered, separator + 2, last)
return line_id, node_id, code if line_id > 0 and node_id > 0 else 0, 0
# Otherwise an ``L<L>N<J>...`` channel (the caller dispatches only ``l``-led names).
npos = lowered.find("n", 1) + 1 # 1-based index of the first 'n' after the 'l'
if npos == 0:
return 0, 0, 0, 0
if last >= npos + 4 and lowered[last - 3 :] in {"dec", "azi"}:
line_id = _native_positive_int(lowered, 2, npos - 1)
node_id = _native_positive_int(lowered, npos + 1, last - 3)
if line_id <= 0 or node_id <= 0:
return line_id, node_id, 0, 0
return line_id, node_id, 7 if lowered.endswith("dec") else 8, 0
if not (last >= npos + 3 and lowered[last - 2] in "pva"):
return 0, 0, 0, 0
line_id = _native_positive_int(lowered, 2, npos - 1)
node_id = _native_positive_int(lowered, npos + 1, last - 2)
if line_id <= 0 or node_id <= 0:
return line_id, node_id, 0, 0
component = "xyz".find(lowered[-1]) + 1
kind = {"p": 1, "v": 2, "a": 4}[lowered[last - 2]] if component else 0
return line_id, node_id, kind, component
def _channel_identity_key(channel: str) -> str:
"""Mirror the native ``channel_identity_key`` used to reject duplicate OUTPUTS.
Names compare case-insensitively and numeric ids by value; alias spellings
of one quantity collapse (``Con<P>p?`` = ``Point<P>p?``, ``FairAngle`` =
``FairDecl``, ``AnchAngle`` = ``AnchDecl``).
"""
lowered = channel.lower()
if lowered.startswith(("fairten", "anchten")):
line_id = _native_id_suffix(lowered[7:])
return f"{lowered[:7]}:{line_id}" if line_id > 0 else lowered
if lowered.startswith(("anchfz", "anchfh")):
line_id = _native_id_suffix(lowered[6:])
return f"{lowered[:6]}:{line_id}" if line_id > 0 else lowered
if lowered.startswith(
("fairangle", "anchangle", "fairdecl", "anchdecl", "fairincl", "anchincl")
):
width = 9 if lowered.startswith(("fairangle", "anchangle")) else 8
line_id = _native_id_suffix(lowered[width:])
if line_id <= 0:
return lowered
if lowered.startswith(("fairincl", "anchincl")):
return f"{lowered[:8]}:{line_id}"
return f"{lowered[:4]}decl:{line_id}"
if lowered.startswith(("fairdefl", "anchdefl")):
line_id = _native_id_suffix(lowered[8:])
return f"{lowered[:8]}:{line_id}" if line_id > 0 else lowered
if lowered.startswith("point") or (
lowered.startswith("con") and lowered[3:4].isascii() and lowered[3:4].isdigit()
):
start = 5 if lowered.startswith("point") else 3
separator = lowered.rfind("p")
point_id = _native_id_suffix(lowered[start:separator]) if separator > start else 0
component = (
"xyz".find(lowered[separator + 1]) + 1
if point_id > 0 and separator + 2 == len(lowered)
else 0
)
return f"point:{point_id}:{component}" if point_id > 0 and component > 0 else lowered
touchdown = re.fullmatch(r"tdp([0-9]{1,9})(s|x|y|z|lay|exc|grd)", lowered)
if touchdown is not None and int(touchdown.group(1)) > 0:
component = ("s", "x", "y", "z", "lay", "exc", "grd").index(touchdown.group(2)) + 1
return f"tdp:{int(touchdown.group(1))}:{component}"
if lowered.startswith(("ten", "curv", "bendmom", "stfmom", "l", "torq", "twist")):
line_id, node_id, kind, component = _parse_line_node_channel(lowered)
if line_id > 0 and node_id > 0 and kind > 0:
return f"node:{line_id}:{node_id}:{kind}:{component}"
return lowered
def _row_key(token: str) -> str:
"""Return a table row's integer id as the validator keys it (``str(int)``)."""
try:
return str(_native_int(token))
except ValueError:
return token.lower()
def _channel_id(digits: str) -> str:
"""Return a channel's digit-string id by value (native ``int_suffix``; 0 = no id)."""
return str(_native_id_suffix(digits))
def _end_b_holds_connection(point_type: str) -> bool:
"""Native finalize_checks: an End B that holds a connection or a torsion frame -- a Fixed point,
or a Coupled/Vessel (Turbine<J>) point that drives it as a second moving end."""
return point_type in {"fixed", "coupled", "vessel"} or _is_turbine_point_type(point_type)
def _end_b_holds_frame(point_type: str) -> bool:
"""Native end_b_holds_frame: an End B that can hold an END CONNECTION or a torsion frame -- as
_end_b_holds_connection, or a body point or a rod end (a line between two objects on the
multibody march, which checks the object)."""
return (
_end_b_holds_connection(point_type)
or point_type.startswith("body")
or _rod_point(point_type) is not None
)
def _is_turbine_point_type(point_type: str) -> bool:
"""Mirror the native FAST.Farm ``Turbine<J>``/``T<J>`` vocabulary detection."""
return point_type.startswith("turbine") or (
len(point_type) >= 2
and point_type[0] == "t"
and point_type[1:].isascii()
and point_type[1:].isdigit()
)
def _turbine_id(point_type: str) -> int:
return _native_id_suffix(point_type[7:] if point_type.startswith("turbine") else point_type[1:])
def _rod_point(point_type: str) -> tuple[int, str] | None:
"""Mirror the native ``parse_rod_point_type`` (``Rod<N>A``/``Rod<N>B``)."""
match = re.fullmatch(r"rod([0-9]+)([ab])", point_type)
if match is None:
return None
rod_id = _native_id_suffix(match.group(1))
return (rod_id, match.group(2)) if rod_id >= 1 else None
def _rod_end_token(token: str) -> str | None:
"""Mirror the native ``parse_line_attachment`` rod ends (``R<N>A``, ``Rod<N>B``, ...)."""
match = re.fullmatch(r"(?:rod|r)([0-9]+)([ab])", token.lower())
if match is None or _native_id_suffix(match.group(1)) < 1:
return None
return f"rod{_native_id_suffix(match.group(1))}{match.group(2)}"
def _body_point_id(point_type: str) -> int:
return _native_id_suffix(point_type[4:]) if point_type.startswith("body") else 0
def _selector_int(text: object, what: str) -> int:
"""Parse an integer selector argument; bad input is an API ``ValueError``."""
if isinstance(text, bool):
raise ValueError(f"{what} must be an integer, got {text!r}")
if isinstance(text, int):
return text
if isinstance(text, str):
try:
return _native_int(text.strip())
except ValueError:
pass
raise ValueError(f"{what} must be an integer, got {text!r}")
def _line_option(keyword: str) -> tuple[str, int] | None:
"""Return (family, line id) of a per-line static friction row, else ``None``.
``layAzimuth<ID>`` and ``asLaidTension<ID>`` (case-insensitive) set the lay azimuth and the
as-laid tension of the LINE ``ID`` alone, over the global ``layAzimuth`` / ``asLaidTension``
row; the family is ``lay_azimuth`` or ``as_laid_tension``.
"""
match = _LINE_OPTION_PATTERN.match(keyword.lower())
if match is None:
return None
return _LINE_OPTION_FAMILIES[match.group(1)], int(match.group(2))
def _is_scalar_option_keyword(keyword: str) -> bool:
"""Whether ``keyword`` (any case) is a two-token scalar OPTIONS keyword (per-line rows too)."""
return keyword.lower() in _SCALAR_OPTION_KEYWORDS or _line_option(keyword) is not None
def _option_key(keyword: str) -> str:
"""Return the native identity of an option keyword (aliases collapse to one key)."""
lowered = keyword.lower()
if lowered in _WAVETRAIN_KEYWORDS:
# native CD_Sea_Parse_Train takes both spellings of the one keyword
return "wavetrain"
line_option = _line_option(lowered)
if line_option is not None:
# layAzimuth7 and layAzimuth07 set the same line natively: the last row wins
return f"{line_option[0]}:{line_option[1]}"
return _OPTION_ALIASES.get(lowered, lowered)
def _end_connection_end(token: str) -> str:
"""Return canonical ``a``/``b`` for the native end-name aliases."""
try:
return _END_CONNECTION_ENDS[token.lower()]
except KeyError as exc:
raise ValueError("END CONNECTIONS End must be A or B") from exc
def _text_columns(section: str, width: int) -> frozenset[int]:
"""Zero-based columns the native list-directed READ takes as character data."""
if section == "LINE TYPES":
return frozenset({0, 3, 4})
if section == "LINES":
# LineType and Outputs; the attachments are point ids or rod ends, never quoted
return frozenset({1, 6}) if width == 7 else frozenset({3})
if section == "RODS":
return frozenset({1, 2, 10})
if section == "END CONNECTIONS":
# End, Stiffness and the optional TorsStiffness keyword
return frozenset({1, 2, 6}) if width >= 10 else frozenset({1, 2})
if section in {"POINTS", "SECTIONS", "BODIES"}:
return frozenset({1})
if section in {"ROD TYPES", "EQUIVALENT BUOYANCY"}:
return frozenset({0})
return frozenset()
# Spectral wave rows (native CD_Sea_Parse_Train): the value count of the single-train
# ``waves`` form; a ``wavetrain`` row adds a trailing spreading exponent except for airy.
_SPECTRUM_VALUES = {
"pm": 3,
"issc": 3,
"bretschneider": 3,
"piersonmoskowitz": 3,
"pierson-moskowitz": 3,
"torsethaugen": 3,
"ochihubble": 7,
"ochi-hubble": 7,
"ochi_hubble": 7,
}
_WAVETRAIN_VALUES = {
**{mode: count + 1 for mode, count in _SPECTRUM_VALUES.items()},
"jonswap": 5,
"airy": 3,
}
_WAVETRAIN_KEYWORDS = frozenset({"wavetrain", "wave_train"})
# First tokens of the positional OPTIONS rows (native apply_option).
_POSITIONAL_ROW_STARTS = frozenset(
{"airy", "jonswap", "stream", "dean", "uniform", "profile", "dynamic_solver"}
)
# Native JONSWAP gamma bound: the spectrum normalisation 1 - 0.287 ln(gamma) must stay positive.
_JONSWAP_GAMMA_LIMIT = math.exp(1.0 / 0.287)
def _is_positional_option(tokens: list[str]) -> bool:
"""Recognize only the positional forms accepted by ``apply_option``."""
first = tokens[0].lower()
last = tokens[-1].lower()
return (
(len(tokens) == 2 and first == "none" and last in {"wave", "waves", "current"})
or (len(tokens) == 5 and first == "uniform" and last == "current")
or (len(tokens) == 10 and first == "profile" and last == "current")
or (len(tokens) == 5 and first in {"airy", "stream", "dean"} and last in {"wave", "waves"})
or (len(tokens) == 6 and first == "jonswap" and last in {"wave", "waves"})
or (
last in {"wave", "waves"}
and first in _SPECTRUM_VALUES
and len(tokens) == _SPECTRUM_VALUES[first] + 2
)
or (
last in _WAVETRAIN_KEYWORDS
and first in _WAVETRAIN_VALUES