HongchengGao's picture
Align task taxonomy and IDs with the updated paper; main evaluation 306
3de3b50 verified
Raw History Blame Contribute Delete
8.97 kB
#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import math
import re
from pathlib import Path
ROOT = Path("/home/user/Desktop")
GAIN_LABELS = ("PC_GS_KP", "PC_GS_KI")
GAIN_COUNT = 30
EXPECTED = (
0.229181,
0.225569,
1.297634,
1.745830,
303.606000,
336.553857,
)
REL_TOL = 2.0e-3
ABS_TOL = 2.0e-5
BASE_DISCON_SHA256 = "455a2b0248301016fce55b908198c0992479de2490be73f69fde3ad83c37a26e"
LIBDISCON_SHA256 = "45111ec68ce797c9c6f6d0352642f1ebeff2315cff187a846ae1660c780dbfcf"
PERFORMANCE_SHA256 = "a8d9c2d88bd1d9073287256b042d7752d2202a01e611c08e283b9109504caf5b"
def read(path: Path) -> str:
return path.read_text(encoding="utf-8", errors="ignore")
def digest(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def close(
actual: float,
expected: float,
rel_tol: float = REL_TOL,
abs_tol: float = ABS_TOL,
) -> 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{re.escape(name)}\s+-",
text,
re.MULTILINE,
)
if not match:
raise ValueError(f"missing parameter {name}")
return match.group(1).strip('"').rstrip(",")
def values_for_label(text: str, label: str) -> list[float]:
matches: list[list[float]] = []
for line in text.splitlines():
values, marker, comment = line.partition("!")
if marker and re.search(rf"\b{re.escape(label)}\b", comment):
matches.append([float(token) for token in values.split()])
if len(matches) != 1:
raise ValueError(f"expected one {label} field")
return matches[0]
def non_gain_signature(text: str) -> str:
lines: list[str] = []
for line in text.splitlines():
values, marker, comment = line.partition("!")
if marker and any(re.search(rf"\b{label}\b", comment) for label in GAIN_LABELS):
lines.append(f"<pitch-gain-values>!{comment}")
else:
lines.append(line)
return "\n".join(lines)
def controller_ok(path: Path, factor: float, baseline: str) -> bool:
text = read(path)
if non_gain_signature(text) != non_gain_signature(baseline):
return False
if parameter(text, "PC_GS_n") != str(GAIN_COUNT):
return False
if values_for_label(text, "PC_GS_angles") != values_for_label(
baseline, "PC_GS_angles"
):
return False
for label in GAIN_LABELS:
original = values_for_label(baseline, label)
actual = values_for_label(text, label)
if len(original) != GAIN_COUNT or len(actual) != GAIN_COUNT:
return False
if any(
not close(value, factor * source, rel_tol=2.0e-8, abs_tol=2.0e-12)
for value, source in zip(actual, original)
):
return False
return True
def population_std(values: list[float]) -> float:
if not values:
raise ValueError("empty sample window")
mean = sum(values) / len(values)
return math.sqrt(sum((value - mean) ** 2 for value in values) / len(values))
def output_metrics(path: Path) -> tuple[float, float, float]:
lines = read(path).splitlines()
if "at commit v5.0.0" not in "\n".join(lines[:6]):
raise ValueError("output was not generated by OpenFAST 5.0.0")
header_index = next(
index for index, line in enumerate(lines) if line.split()[:1] == ["Time"]
)
headers = lines[header_index].split()
units = lines[header_index + 1].split()
indices = {name: headers.index(name) for name in (
"Time",
"Wind1VelX",
"RotSpeed",
"BldPitch1",
"GenPwr",
)}
expected_units = {
"Time": "(s)",
"Wind1VelX": "(m/s)",
"RotSpeed": "(rpm)",
"BldPitch1": "(deg)",
"GenPwr": "(kW)",
}
if any(units[indices[name]] != unit for name, unit in expected_units.items()):
raise ValueError("unexpected native OpenFAST units")
rows: list[list[float]] = []
for line in lines[header_index + 2 :]:
fields = line.split()
if len(fields) != len(headers):
continue
try:
rows.append([float(value) for value in fields])
except ValueError:
continue
if len(rows) != 601:
raise ValueError("incorrect native output sample count")
for index, row in enumerate(rows):
if not close(
row[indices["Time"]],
index / 10.0,
rel_tol=0.0,
abs_tol=2.0e-8,
):
raise ValueError("output timestamps are not 0.1-second samples")
wind = [row[indices["Wind1VelX"]] for row in rows]
if population_std(wind) < 0.5:
raise ValueError("native output does not contain turbulent wind")
window = [row for row in rows if row[indices["Time"]] >= 10.0]
if len(window) != 501:
raise ValueError("incorrect 10-to-60-second sample count")
return tuple(
population_std([row[indices[channel]] for row in window])
for channel in ("RotSpeed", "BldPitch1", "GenPwr")
)
def parse_summary(path: Path) -> tuple[float, ...]:
rows = [line.strip() for line in read(path).splitlines() if line.strip()]
if len(rows) != 1:
raise ValueError("summary must contain exactly one row")
values = tuple(float(field.strip()) for field in rows[0].split(","))
if len(values) != 6 or not all(math.isfinite(value) for value in values):
raise ValueError("summary must contain six finite values")
return values
def check() -> bool:
required = (
"DISCON.IN",
"Cp_Ct_Cq.NREL5MW.txt",
"libdiscon.so",
"postprocess.py",
"elasto_rosco.dat",
"aero_rosco.dat",
"rosco_soft.IN",
"rosco_stiff.IN",
"servo_soft.dat",
"servo_stiff.dat",
"rosco_soft.fst",
"rosco_stiff.fst",
"rosco_soft.out",
"rosco_stiff.out",
"rosco_soft.log",
"rosco_stiff.log",
"summary.txt",
)
if any(
not (ROOT / name).is_file() or (ROOT / name).stat().st_size == 0
for name in required
):
return False
if (
digest(ROOT / "DISCON.IN") != BASE_DISCON_SHA256
or digest(ROOT / "libdiscon.so") != LIBDISCON_SHA256
or digest(ROOT / "Cp_Ct_Cq.NREL5MW.txt") != PERFORMANCE_SHA256
):
return False
baseline = read(ROOT / "DISCON.IN")
if not controller_ok(ROOT / "rosco_soft.IN", 0.5, baseline):
return False
if not controller_ok(ROOT / "rosco_stiff.IN", 1.5, baseline):
return False
elasto = read(ROOT / "elasto_rosco.dat")
aero = read(ROOT / "aero_rosco.dat")
if '"../5MW_Baseline/' in elasto or '"../5MW_Baseline/' in aero:
return False
for case in ("soft", "stiff"):
servo = read(ROOT / f"servo_{case}.dat")
if (
parameter(servo, "PCMode") != "5"
or parameter(servo, "VSContrl") != "5"
or parameter(servo, "DLL_FileName") != "libdiscon.so"
or parameter(servo, "DLL_InFile") != f"rosco_{case}.IN"
):
return False
main = read(ROOT / f"rosco_{case}.fst")
expected_main = {
"TMax": "60.0",
"DT_Out": "0.1",
"OutFileFmt": "1",
"EDFile": "elasto_rosco.dat",
"InflowFile": (
"5MW_Baseline/"
"NRELOffshrBsline5MW_InflowWind_12mps.dat"
),
"AeroFile": "aero_rosco.dat",
"ServoFile": f"servo_{case}.dat",
}
if any(
parameter(main, name) != value
for name, value in expected_main.items()
):
return False
log = read(ROOT / f"rosco_{case}.log")
if (
"OpenFAST-v5.0.0" not in log
or "OpenFAST terminated normally." not in log
or "Simulated Time: 60 seconds" not in log
or "FATAL ERROR" in log
):
return False
soft = output_metrics(ROOT / "rosco_soft.out")
stiff = output_metrics(ROOT / "rosco_stiff.out")
calculated = (soft[0], stiff[0], soft[1], stiff[1], soft[2], stiff[2])
reported = parse_summary(ROOT / "summary.txt")
return (
all(close(actual, expected) for actual, expected in zip(calculated, EXPECTED))
and all(
close(actual, expected)
for actual, expected in zip(reported, EXPECTED)
)
and all(
close(actual, expected, rel_tol=5.0e-7, abs_tol=5.0e-6)
for actual, expected in zip(reported, calculated)
)
)
def main() -> int:
try:
result = check()
except Exception:
result = False
print("True" if result else "False")
return 0
if __name__ == "__main__":
raise SystemExit(main())