File size: 5,211 Bytes
5154c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import math
import re
from pathlib import Path


ROOT = Path("/home/user/Desktop")
RPMS = (6, 9, 12, 15)
AIR_DENSITY = 1.225
ROTOR_RADIUS_M = 63.0
WIND_SPEED_MPS = 8.0
EXPECTED_CP = (0.347895, 0.447509, 0.397957, 0.296552)
ABS_TOL = 2e-5
REL_TOL = 5e-4


def read(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="ignore")


def close(actual: float, expected: float) -> bool:
    return math.isfinite(actual) and abs(actual - expected) <= max(
        ABS_TOL, REL_TOL * max(1.0, abs(expected))
    )


def parameter(text: str, name: str) -> str:
    match = re.search(rf"^\s*(\S+).*?\s{name}\s+-", text, re.MULTILINE)
    if not match:
        raise ValueError(f"missing parameter {name}")
    return match.group(1).strip('"').rstrip(",")


def read_channel_mean(path: Path, channel: str, window_s: float) -> tuple[float, float]:
    lines = read(path).splitlines()
    if "at commit v5.0.0" not in "\n".join(lines[:5]):
        raise ValueError("output was not generated by OpenFAST 5.0.0")
    header_index = next(
        index for index, line in enumerate(lines) if line.split() and line.split()[0] == "Time"
    )
    headers = lines[header_index].split()
    units = lines[header_index + 1].split()
    channel_index = headers.index(channel)
    if len(units) != len(headers) or units[channel_index] != "(W)":
        raise ValueError(f"{channel} must be reported in watts")
    rows: list[tuple[float, float]] = []
    for line in lines[header_index + 2 :]:
        values = line.split()
        if len(values) != len(headers):
            continue
        try:
            rows.append((float(values[0]), float(values[channel_index])))
        except ValueError:
            continue
    if not rows or not close(rows[-1][0], 30.0):
        raise ValueError("incomplete 30-second output")
    start = rows[-1][0] - window_s
    selected = [value for time, value in rows if time >= start]
    if len(selected) < 90:
        raise ValueError("insufficient samples in final averaging window")
    return sum(selected) / len(selected), rows[-1][0]


def parse_summary(path: Path) -> list[tuple[float, float, float]]:
    rows: list[tuple[float, float, float]] = []
    for line in read(path).splitlines():
        if not line.strip():
            continue
        values = [float(value.strip()) for value in line.split(",")]
        if len(values) != 3:
            raise ValueError("summary rows must contain rpm, tsr, cp")
        rows.append((values[0], values[1], values[2]))
    if len(rows) != len(RPMS):
        raise ValueError("summary must contain four rows")
    return rows


def valid_inputs(rpm: int) -> bool:
    fst = read(ROOT / f"case_rpm{rpm}.fst")
    ed = read(ROOT / f"elasto_rpm{rpm}.dat")
    expected = {
        "TMax": "30",
        "DT_Out": "0.1",
        "OutFileFmt": "1",
        "CompInflow": "1",
        "CompAero": "2",
        "CompServo": "0",
        "EDFile": f"elasto_rpm{rpm}.dat",
        "InflowFile": "5MW_Baseline/NRELOffshrBsline5MW_InflowWind_Steady8mps.dat",
        "AeroFile": "aerodyn_tsr.dat",
    }
    if any(parameter(fst, key) != value for key, value in expected.items()):
        return False
    return (
        parameter(ed, "GenDOF").lower() == "false"
        and close(float(parameter(ed, "RotSpeed")), float(rpm))
    )


def check() -> bool:
    required = ["run_sweep.py", "postprocess.py", "aerodyn_tsr.dat", "summary.txt"]
    for rpm in RPMS:
        required.extend(
            (
                f"elasto_rpm{rpm}.dat",
                f"case_rpm{rpm}.fst",
                f"case_rpm{rpm}.out",
                f"case_rpm{rpm}.log",
            )
        )
    if any(not (ROOT / name).is_file() or (ROOT / name).stat().st_size == 0 for name in required):
        return False

    aero = read(ROOT / "aerodyn_tsr.dat")
    if '"RtAeroPwr"' not in aero or '"../5MW_Baseline/' in aero:
        return False
    if any(not valid_inputs(rpm) for rpm in RPMS):
        return False

    available_power_w = (
        0.5 * AIR_DENSITY * math.pi * ROTOR_RADIUS_M**2 * WIND_SPEED_MPS**3
    )
    calculated: list[tuple[float, float, float]] = []
    for rpm in RPMS:
        if "OpenFAST terminated normally." not in read(ROOT / f"case_rpm{rpm}.log"):
            return False
        aero_power_w, _ = read_channel_mean(ROOT / f"case_rpm{rpm}.out", "RtAeroPwr", 10.0)
        tsr = (rpm * 2.0 * math.pi / 60.0) * ROTOR_RADIUS_M / WIND_SPEED_MPS
        calculated.append((float(rpm), tsr, aero_power_w / available_power_w))

    reported = parse_summary(ROOT / "summary.txt")
    for index, rpm in enumerate(RPMS):
        expected = (float(rpm), calculated[index][1], EXPECTED_CP[index])
        if any(not close(value, target) for value, target in zip(calculated[index], expected)):
            return False
        if any(not close(value, target) for value, target in zip(reported[index], expected)):
            return False
    return True


def main() -> int:
    try:
        result = check()
    except Exception:
        result = False
    print("True" if result else "False")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())