cfdbender 0.4.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cfdbender/__init__.py +7 -0
- cfdbender/_pyfs.py +92 -0
- cfdbender/core/__init__.py +13 -0
- cfdbender/core/adapter.py +148 -0
- cfdbender/core/executables.py +157 -0
- cfdbender/core/flight.py +346 -0
- cfdbender/core/matrix.py +354 -0
- cfdbender/core/naming.py +172 -0
- cfdbender/core/plan.py +463 -0
- cfdbender/core/registry.py +735 -0
- cfdbender/core/results.py +117 -0
- cfdbender/core/run.py +150 -0
- cfdbender/core/settings.py +92 -0
- cfdbender/core/workspace.py +93 -0
- cfdbender/geometry/__init__.py +1 -0
- cfdbender/geometry/blade_slicing.py +355 -0
- cfdbender/hpc/__init__.py +21 -0
- cfdbender/hpc/_plan.py +266 -0
- cfdbender/hpc/_profiles.py +305 -0
- cfdbender/hpc/_render.py +271 -0
- cfdbender/hpc/_submit.py +96 -0
- cfdbender/hpc/_walltime.py +301 -0
- cfdbender/matrix/__init__.py +1 -0
- cfdbender/matrix/cli.py +228 -0
- cfdbender/matrix/collection.py +251 -0
- cfdbender/matrix/exports.py +122 -0
- cfdbender/matrix/rerun.py +126 -0
- cfdbender/matrix/selection.py +62 -0
- cfdbender/matrix/submission.py +272 -0
- cfdbender/solvers/__init__.py +47 -0
- cfdbender/solvers/_host/__init__.py +1 -0
- cfdbender/solvers/_host/_config.py +10 -0
- cfdbender/solvers/_host/_execute.py +52 -0
- cfdbender/solvers/_host/_mesh.py +62 -0
- cfdbender/solvers/_host/_ram.py +69 -0
- cfdbender/solvers/_host/_single.py +63 -0
- cfdbender/solvers/flightstream/__init__.py +114 -0
- cfdbender/solvers/flightstream/reader.py +191 -0
- cfdbender/solvers/mock/__init__.py +273 -0
- cfdbender/solvers/openfoam/__init__.py +201 -0
- cfdbender/solvers/openfoam/_config.py +410 -0
- cfdbender/solvers/openfoam/_execute.py +162 -0
- cfdbender/solvers/openfoam/_history.py +158 -0
- cfdbender/solvers/pyfr/__init__.py +118 -0
- cfdbender/solvers/pyfr/_config.py +196 -0
- cfdbender/solvers/pyfr/_execute.py +127 -0
- cfdbender/solvers/pyfr/_history.py +88 -0
- cfdbender/solvers/qprop/__init__.py +303 -0
- cfdbender/solvers/qprop/_config.py +259 -0
- cfdbender/solvers/qprop/_execute.py +269 -0
- cfdbender/solvers/qprop/_output.py +64 -0
- cfdbender/solvers/qprop/_polar.py +98 -0
- cfdbender/solvers/qprop/_prop.py +81 -0
- cfdbender/solvers/qprop/_sections.py +193 -0
- cfdbender/solvers/su2/__init__.py +210 -0
- cfdbender/solvers/su2/_config.py +290 -0
- cfdbender/solvers/su2/_execute.py +196 -0
- cfdbender/solvers/su2/_history.py +117 -0
- cfdbender/solvers/su2/_pysu2_worker.py +25 -0
- cfdbender/solvers/su2/_ram.py +13 -0
- cfdbender/solvers/su2/_reference.py +79 -0
- cfdbender/solvers/su2/_single.py +3 -0
- cfdbender/solvers/su2/routes.py +61 -0
- cfdbender/solvers/xfoil/__init__.py +171 -0
- cfdbender/solvers/xfoil/_config.py +144 -0
- cfdbender/solvers/xfoil/_execute.py +227 -0
- cfdbender/solvers/xfoil/_polar.py +88 -0
- cfdbender/testing/__init__.py +301 -0
- cfdbender/workspace/__init__.py +1 -0
- cfdbender/workspace/cli.py +99 -0
- cfdbender/workspace/planning.py +38 -0
- cfdbender-0.4.2.dist-info/METADATA +57 -0
- cfdbender-0.4.2.dist-info/RECORD +77 -0
- cfdbender-0.4.2.dist-info/WHEEL +5 -0
- cfdbender-0.4.2.dist-info/entry_points.txt +3 -0
- cfdbender-0.4.2.dist-info/licenses/LICENSE +21 -0
- cfdbender-0.4.2.dist-info/top_level.txt +1 -0
cfdbender/core/flight.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""Resolve a matrix FLIGHT_CONDITION into one flow state, without any solver.
|
|
2
|
+
|
|
3
|
+
The cell grammar and the state resolution follow the pyflightstream matrix:
|
|
4
|
+
comma-separated KEY:value pairs whose keys carry their units in their names.
|
|
5
|
+
Five keys constrain the air (MACH, TASmps, REmi in millions, ALTFT in feet,
|
|
6
|
+
dISA in kelvin as an offset), five pin it (RHOkgm3, MUPas, ASMPS, TK, PPA), and
|
|
7
|
+
seven state the attitude (ALPHA, BETA, ADVANCE_RATIO, RPM, roll_rate,
|
|
8
|
+
pitch_rate, yaw_rate). Keys match case-insensitively.
|
|
9
|
+
|
|
10
|
+
The atmosphere is ISO 2533 from -2000 m to 20000 m with a Sutherland viscosity.
|
|
11
|
+
Exactly one of MACH or TASmps fixes the velocity. ALTFT and dISA fix the
|
|
12
|
+
temperature (sea level and zero when absent); a TK pin replaces it, and the
|
|
13
|
+
speed of sound and viscosity follow it unless ASMPS or MUPas pin them. REmi
|
|
14
|
+
solves the density from Re = rho V L / mu with L the reference length of the
|
|
15
|
+
row's REF file; otherwise the density is the ideal-gas density of the
|
|
16
|
+
altitude's pressure (or a PPA pin) at the state's temperature, and the Reynolds
|
|
17
|
+
number is an outcome. Whenever the density is solved or pinned, the pressure
|
|
18
|
+
is p = rho R T unless PPA pins it.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import math
|
|
24
|
+
from collections.abc import Mapping
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
|
|
27
|
+
AIR_KEYS = ("MACH", "TASmps", "REmi", "ALTFT", "dISA")
|
|
28
|
+
PIN_KEYS = ("RHOkgm3", "MUPas", "ASMPS", "TK", "PPA")
|
|
29
|
+
ATTITUDE_KEYS = ("ALPHA", "BETA", "ADVANCE_RATIO", "RPM", "roll_rate", "pitch_rate", "yaw_rate")
|
|
30
|
+
STATE_KEYS = (*AIR_KEYS, *PIN_KEYS)
|
|
31
|
+
CANONICAL_KEYS = {key.upper(): key for key in (*STATE_KEYS, *ATTITUDE_KEYS)}
|
|
32
|
+
|
|
33
|
+
GAMMA = 1.4
|
|
34
|
+
GAS_CONSTANT = 287.05287
|
|
35
|
+
SEA_LEVEL_TEMPERATURE = 288.15
|
|
36
|
+
SEA_LEVEL_PRESSURE = 101325.0
|
|
37
|
+
GRAVITY = 9.80665
|
|
38
|
+
LAPSE_RATE = 0.0065
|
|
39
|
+
TROPOPAUSE_ALTITUDE = 11000.0
|
|
40
|
+
TROPOPAUSE_TEMPERATURE = 216.65
|
|
41
|
+
FLOOR_ALTITUDE = -2000.0
|
|
42
|
+
CEILING_ALTITUDE = 20000.0
|
|
43
|
+
METRES_PER_FOOT = 0.3048
|
|
44
|
+
SUTHERLAND_VISCOSITY = 1.716e-5
|
|
45
|
+
SUTHERLAND_TEMPERATURE = 273.15
|
|
46
|
+
SUTHERLAND_CONSTANT = 110.4
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class FlightConditionError(ValueError):
|
|
50
|
+
"""A flight condition is under-determined, contradictory or outside the atmosphere."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class FlowState:
|
|
55
|
+
"""One resolved free stream in SI units, with where its density came from.
|
|
56
|
+
|
|
57
|
+
``reynolds`` is None only when no reference length was available and the
|
|
58
|
+
row stated no REmi. ``density_source`` is ``solved-from-reynolds``,
|
|
59
|
+
``pinned`` or ``atmosphere``. ``stated`` holds the state keys as written.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
mach: float
|
|
63
|
+
velocity: float
|
|
64
|
+
temperature: float
|
|
65
|
+
pressure: float
|
|
66
|
+
density: float
|
|
67
|
+
viscosity: float
|
|
68
|
+
sonic_velocity: float
|
|
69
|
+
reynolds: float | None
|
|
70
|
+
reynolds_length: float | None
|
|
71
|
+
density_source: str
|
|
72
|
+
stated: Mapping[str, float]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def canonical_key(name: str) -> str:
|
|
76
|
+
"""Return the pyflightstream spelling of a known key, else the key in upper case."""
|
|
77
|
+
return CANONICAL_KEYS.get(name.strip().upper(), name.strip().upper())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def sutherland_viscosity(temperature: float) -> float:
|
|
81
|
+
"""Dynamic viscosity in Pa s at a temperature in K."""
|
|
82
|
+
ratio = temperature / SUTHERLAND_TEMPERATURE
|
|
83
|
+
return float(
|
|
84
|
+
SUTHERLAND_VISCOSITY
|
|
85
|
+
* math.pow(ratio, 1.5)
|
|
86
|
+
* (SUTHERLAND_TEMPERATURE + SUTHERLAND_CONSTANT)
|
|
87
|
+
/ (temperature + SUTHERLAND_CONSTANT)
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def speed_of_sound(temperature: float) -> float:
|
|
92
|
+
"""Speed of sound in m/s of the ideal gas at a temperature in K."""
|
|
93
|
+
return math.sqrt(GAMMA * GAS_CONSTANT * temperature)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def standard_atmosphere(altitude_m: float) -> tuple[float, float]:
|
|
97
|
+
"""Return the ISO 2533 (temperature K, pressure Pa) at a geopotential altitude."""
|
|
98
|
+
exponent = GRAVITY / (LAPSE_RATE * GAS_CONSTANT)
|
|
99
|
+
if altitude_m <= TROPOPAUSE_ALTITUDE:
|
|
100
|
+
temperature = SEA_LEVEL_TEMPERATURE - LAPSE_RATE * altitude_m
|
|
101
|
+
return temperature, SEA_LEVEL_PRESSURE * (temperature / SEA_LEVEL_TEMPERATURE) ** exponent
|
|
102
|
+
base = SEA_LEVEL_PRESSURE * (TROPOPAUSE_TEMPERATURE / SEA_LEVEL_TEMPERATURE) ** exponent
|
|
103
|
+
height = altitude_m - TROPOPAUSE_ALTITUDE
|
|
104
|
+
pressure = base * math.exp(-GRAVITY * height / (GAS_CONSTANT * TROPOPAUSE_TEMPERATURE))
|
|
105
|
+
return TROPOPAUSE_TEMPERATURE, pressure
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def states_flow(condition: Mapping[str, float]) -> bool:
|
|
109
|
+
"""Whether a point states more of the air than a bare MACH number.
|
|
110
|
+
|
|
111
|
+
A row stating only MACH (with attitude keys) keeps the flow state of its
|
|
112
|
+
setup, which is how matrices written before the full cell keep working.
|
|
113
|
+
"""
|
|
114
|
+
return any(key in condition for key in STATE_KEYS if key != "MACH")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def row_flow(
|
|
118
|
+
condition: Mapping[str, float],
|
|
119
|
+
*,
|
|
120
|
+
reference_length: float | None,
|
|
121
|
+
label: str,
|
|
122
|
+
native_mach: bool = True,
|
|
123
|
+
) -> tuple[dict[str, float], FlowState | None]:
|
|
124
|
+
"""Split a point's condition into its non-state keys and its resolved flow.
|
|
125
|
+
|
|
126
|
+
Parameters
|
|
127
|
+
----------
|
|
128
|
+
condition : mapping of str to float
|
|
129
|
+
One point's condition with canonical keys.
|
|
130
|
+
reference_length : float or None
|
|
131
|
+
The REF file's length, required when REmi is stated.
|
|
132
|
+
label : str
|
|
133
|
+
Names the row in every refusal.
|
|
134
|
+
native_mach : bool, optional
|
|
135
|
+
True for a solver that reads a bare MACH itself: a row stating only
|
|
136
|
+
MACH and angles is then returned unchanged with no flow state.
|
|
137
|
+
|
|
138
|
+
Returns
|
|
139
|
+
-------
|
|
140
|
+
tuple
|
|
141
|
+
The condition without the state keys, and the flow state or None when
|
|
142
|
+
the row states no flow to resolve.
|
|
143
|
+
"""
|
|
144
|
+
stated = any(key in condition for key in STATE_KEYS)
|
|
145
|
+
if not (states_flow(condition) or (stated and not native_mach)):
|
|
146
|
+
return dict(condition), None
|
|
147
|
+
kept = {key: value for key, value in condition.items() if key not in STATE_KEYS}
|
|
148
|
+
return kept, resolve_flow(condition, reference_length=reference_length, label=label)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def mach_reynolds(
|
|
152
|
+
condition: Mapping[str, float],
|
|
153
|
+
reference: Mapping[str, object] | None,
|
|
154
|
+
*,
|
|
155
|
+
native_mach: bool,
|
|
156
|
+
) -> tuple[dict[str, float], dict[str, float]]:
|
|
157
|
+
"""Return the non-state condition keys and the resolved Mach and Reynolds numbers.
|
|
158
|
+
|
|
159
|
+
For a two-dimensional solver whose case is made dimensionless by one
|
|
160
|
+
reference length: REmi gives the Reynolds number directly, and other air
|
|
161
|
+
keys give it over the REF file's ``length``. A BETA of zero is dropped and
|
|
162
|
+
any other BETA refused. The second mapping is empty when the row states no
|
|
163
|
+
flow to resolve. Since REmi is the Reynolds number itself, no density is
|
|
164
|
+
solved from it, so ``MACH:0, REmi:3`` (an incompressible polar) is accepted.
|
|
165
|
+
"""
|
|
166
|
+
if condition.get("BETA", 0.0) != 0.0:
|
|
167
|
+
raise ValueError("a two-dimensional case flies at BETA 0; remove BETA from the row")
|
|
168
|
+
condition = {key: value for key, value in condition.items() if key != "BETA"}
|
|
169
|
+
if "REmi" in condition:
|
|
170
|
+
label = "FLIGHT_CONDITION"
|
|
171
|
+
if condition["REmi"] <= 0:
|
|
172
|
+
raise FlightConditionError(f"{label}: REmi must be positive")
|
|
173
|
+
if "RHOkgm3" in condition:
|
|
174
|
+
raise FlightConditionError(
|
|
175
|
+
f"{label}: FLIGHT_CONDITION states RHOkgm3 and REmi; each fixes the density, "
|
|
176
|
+
"state one"
|
|
177
|
+
)
|
|
178
|
+
if sum(key in condition for key in ("MACH", "TASmps")) != 1:
|
|
179
|
+
# The velocity refusal of the resolver, worded once.
|
|
180
|
+
resolve_flow(condition, reference_length=1.0, label=label)
|
|
181
|
+
rest = {key: value for key, value in condition.items() if key != "REmi"}
|
|
182
|
+
kept, state = row_flow(rest, reference_length=None, label=label, native_mach=native_mach)
|
|
183
|
+
flow = {"reynolds": condition["REmi"] * 1e6}
|
|
184
|
+
if state is not None:
|
|
185
|
+
flow["mach"] = state.mach
|
|
186
|
+
elif "MACH" in kept:
|
|
187
|
+
flow["mach"] = kept.pop("MACH")
|
|
188
|
+
return kept, flow
|
|
189
|
+
raw = (reference or {}).get("length")
|
|
190
|
+
length = float(raw) if isinstance(raw, (int, float)) and not isinstance(raw, bool) else None
|
|
191
|
+
kept, state = row_flow(
|
|
192
|
+
condition, reference_length=length, label="FLIGHT_CONDITION", native_mach=native_mach
|
|
193
|
+
)
|
|
194
|
+
if state is None:
|
|
195
|
+
return kept, {}
|
|
196
|
+
if state.reynolds is None:
|
|
197
|
+
raise ValueError(
|
|
198
|
+
"FLIGHT_CONDITION gives a Reynolds number only with REmi or with a length "
|
|
199
|
+
"in the REF file"
|
|
200
|
+
)
|
|
201
|
+
return kept, {"mach": state.mach, "reynolds": state.reynolds}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def agree(
|
|
205
|
+
table: Mapping[str, object], updates: Mapping[str, object], source: str
|
|
206
|
+
) -> dict[str, object]:
|
|
207
|
+
"""Add matrix-derived values to an input table, refusing a disagreeing value.
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
table : Mapping
|
|
212
|
+
Setup (or condition) values as the files state them.
|
|
213
|
+
updates : Mapping
|
|
214
|
+
Values the matrix row determines.
|
|
215
|
+
source : str
|
|
216
|
+
The matrix column the updates come from, named in a refusal.
|
|
217
|
+
|
|
218
|
+
Returns
|
|
219
|
+
-------
|
|
220
|
+
dict
|
|
221
|
+
The table with the updates; a value equal to the stated one is accepted.
|
|
222
|
+
"""
|
|
223
|
+
result = dict(table)
|
|
224
|
+
for key, value in updates.items():
|
|
225
|
+
if key in result:
|
|
226
|
+
stated = result[key]
|
|
227
|
+
same = (
|
|
228
|
+
math.isclose(float(stated), float(value), rel_tol=1e-9)
|
|
229
|
+
if isinstance(stated, (int, float))
|
|
230
|
+
and isinstance(value, (int, float))
|
|
231
|
+
and not isinstance(stated, bool)
|
|
232
|
+
else stated == value
|
|
233
|
+
)
|
|
234
|
+
if not same:
|
|
235
|
+
raise ValueError(
|
|
236
|
+
f"conflict: {key} is {stated!r} in the inputs and {value!r} from the "
|
|
237
|
+
f"matrix {source}; state it in one place"
|
|
238
|
+
)
|
|
239
|
+
result[key] = value
|
|
240
|
+
return result
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def resolve_flow(
|
|
244
|
+
condition: Mapping[str, float], *, reference_length: float | None, label: str
|
|
245
|
+
) -> FlowState:
|
|
246
|
+
"""Resolve the state keys of one point's condition into a flow state.
|
|
247
|
+
|
|
248
|
+
Parameters
|
|
249
|
+
----------
|
|
250
|
+
condition : mapping of str to float
|
|
251
|
+
One point's condition with canonical keys; attitude and other keys are ignored.
|
|
252
|
+
reference_length : float or None
|
|
253
|
+
The REF file's length in metres, required when REmi is stated.
|
|
254
|
+
label : str
|
|
255
|
+
Names the row in every refusal.
|
|
256
|
+
|
|
257
|
+
Returns
|
|
258
|
+
-------
|
|
259
|
+
FlowState
|
|
260
|
+
Velocity, temperature, pressure, density, viscosity and Reynolds number.
|
|
261
|
+
|
|
262
|
+
Raises
|
|
263
|
+
------
|
|
264
|
+
FlightConditionError
|
|
265
|
+
No velocity or two, a non-positive pin or Reynolds number, REmi with
|
|
266
|
+
RHOkgm3 or without a reference length, or ALTFT outside the atmosphere.
|
|
267
|
+
"""
|
|
268
|
+
state = {key: float(condition[key]) for key in STATE_KEYS if key in condition}
|
|
269
|
+
velocity_keys = [key for key in ("MACH", "TASmps") if key in state]
|
|
270
|
+
if len(velocity_keys) != 1:
|
|
271
|
+
raise FlightConditionError(
|
|
272
|
+
f"{label}: FLIGHT_CONDITION states "
|
|
273
|
+
f"{' and '.join(velocity_keys) if velocity_keys else 'no velocity'}; "
|
|
274
|
+
"state exactly one of MACH or TASmps"
|
|
275
|
+
)
|
|
276
|
+
speed_key = velocity_keys[0]
|
|
277
|
+
if state[speed_key] < 0:
|
|
278
|
+
raise FlightConditionError(f"{label}: {speed_key} is a speed and cannot be negative")
|
|
279
|
+
if "RHOkgm3" in state and "REmi" in state:
|
|
280
|
+
raise FlightConditionError(
|
|
281
|
+
f"{label}: FLIGHT_CONDITION states RHOkgm3 and REmi; each fixes the density, state one"
|
|
282
|
+
)
|
|
283
|
+
for key in (*PIN_KEYS, "REmi"):
|
|
284
|
+
if key in state and state[key] <= 0:
|
|
285
|
+
raise FlightConditionError(f"{label}: {key} must be positive")
|
|
286
|
+
if reference_length is not None and not (
|
|
287
|
+
math.isfinite(reference_length) and reference_length > 0
|
|
288
|
+
):
|
|
289
|
+
raise FlightConditionError(f"{label}: the REF length must be a positive length")
|
|
290
|
+
altitude_ft = state.get("ALTFT", 0.0)
|
|
291
|
+
altitude_m = altitude_ft * METRES_PER_FOOT
|
|
292
|
+
if not FLOOR_ALTITUDE <= altitude_m <= CEILING_ALTITUDE:
|
|
293
|
+
floor_ft = math.ceil(FLOOR_ALTITUDE / METRES_PER_FOOT)
|
|
294
|
+
ceiling_ft = math.floor(CEILING_ALTITUDE / METRES_PER_FOOT)
|
|
295
|
+
raise FlightConditionError(
|
|
296
|
+
f"{label}: ALTFT:{altitude_ft:g} is outside the modelled atmosphere, "
|
|
297
|
+
f"{floor_ft} ft to {ceiling_ft} ft"
|
|
298
|
+
)
|
|
299
|
+
standard_temperature, standard_pressure = standard_atmosphere(altitude_m)
|
|
300
|
+
temperature = state.get("TK", standard_temperature + state.get("dISA", 0.0))
|
|
301
|
+
if temperature <= 0:
|
|
302
|
+
raise FlightConditionError(f"{label}: dISA drives the temperature to absolute zero")
|
|
303
|
+
sonic = state.get("ASMPS", speed_of_sound(temperature))
|
|
304
|
+
viscosity = state.get("MUPas", sutherland_viscosity(temperature))
|
|
305
|
+
velocity = state["MACH"] * sonic if speed_key == "MACH" else state["TASmps"]
|
|
306
|
+
reynolds: float | None
|
|
307
|
+
if "REmi" in state:
|
|
308
|
+
if reference_length is None:
|
|
309
|
+
raise FlightConditionError(
|
|
310
|
+
f"{label}: REmi needs the reference length of the row's REF file "
|
|
311
|
+
"(its length key); a Reynolds number is measured against it"
|
|
312
|
+
)
|
|
313
|
+
if velocity <= 0:
|
|
314
|
+
raise FlightConditionError(
|
|
315
|
+
f"{label}: REmi solves the density only at a positive speed; "
|
|
316
|
+
"state the density with ALTFT, dISA or RHOkgm3 instead"
|
|
317
|
+
)
|
|
318
|
+
reynolds = state["REmi"] * 1e6
|
|
319
|
+
density = reynolds * viscosity / (velocity * reference_length)
|
|
320
|
+
source = "solved-from-reynolds"
|
|
321
|
+
pressure = state.get("PPA", density * GAS_CONSTANT * temperature)
|
|
322
|
+
else:
|
|
323
|
+
if "RHOkgm3" in state:
|
|
324
|
+
density = state["RHOkgm3"]
|
|
325
|
+
source = "pinned"
|
|
326
|
+
pressure = state.get("PPA", density * GAS_CONSTANT * temperature)
|
|
327
|
+
else:
|
|
328
|
+
pressure = state.get("PPA", standard_pressure)
|
|
329
|
+
density = pressure / (GAS_CONSTANT * temperature)
|
|
330
|
+
source = "atmosphere"
|
|
331
|
+
reynolds = (
|
|
332
|
+
None if reference_length is None else density * velocity * reference_length / viscosity
|
|
333
|
+
)
|
|
334
|
+
return FlowState(
|
|
335
|
+
mach=velocity / sonic,
|
|
336
|
+
velocity=velocity,
|
|
337
|
+
temperature=temperature,
|
|
338
|
+
pressure=pressure,
|
|
339
|
+
density=density,
|
|
340
|
+
viscosity=viscosity,
|
|
341
|
+
sonic_velocity=sonic,
|
|
342
|
+
reynolds=reynolds,
|
|
343
|
+
reynolds_length=reference_length,
|
|
344
|
+
density_source=source,
|
|
345
|
+
stated=state,
|
|
346
|
+
)
|
cfdbender/core/matrix.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Read named pipe-delimited matrices without any solver dependency.
|
|
2
|
+
|
|
3
|
+
Required columns are POL, RUN, SET, REF and PPROC. The optional columns are
|
|
4
|
+
those of a pyflightstream matrix, with the same names and meanings: HIDDEN,
|
|
5
|
+
AIRCRAFT, CONFIGURATION, DESCRIPTION, FLIGHT_CONDITION, SWEEP_VALUES, GEOMETRY,
|
|
6
|
+
SYMMETRY, SYMMETRY_LOADS, NCPUS, WALLTIME, SOLVER_BUILD (FS_BUILD is accepted as
|
|
7
|
+
its pyflightstream name), WORKFLOW and VAR_NAMES_VALUES. A cell holding ``-``
|
|
8
|
+
states nothing. FLIGHT_CONDITION holds comma-separated KEY:number pairs and at
|
|
9
|
+
most one KEY:sweep; its values come from SWEEP_VALUES. Known keys match
|
|
10
|
+
case-insensitively and keep their pyflightstream spelling (MACH, REmi, TK,
|
|
11
|
+
ALPHA, ...); other keys are kept in upper case. VAR_NAMES_VALUES holds
|
|
12
|
+
``/``-separated ``KEY: value`` pairs that override keys of the row's setup
|
|
13
|
+
file; a value is read as a TOML value when it is one, otherwise as text.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import difflib
|
|
19
|
+
import math
|
|
20
|
+
import re
|
|
21
|
+
import tomllib
|
|
22
|
+
from collections.abc import Mapping
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from types import MappingProxyType
|
|
26
|
+
|
|
27
|
+
from cfdbender.core.flight import canonical_key
|
|
28
|
+
from cfdbender.core.settings import WorkspaceError
|
|
29
|
+
|
|
30
|
+
REQUIRED_COLUMNS = ("POL", "RUN", "SET", "REF", "PPROC")
|
|
31
|
+
OPTIONAL_COLUMNS = (
|
|
32
|
+
"HIDDEN",
|
|
33
|
+
"AIRCRAFT",
|
|
34
|
+
"CONFIGURATION",
|
|
35
|
+
"DESCRIPTION",
|
|
36
|
+
"FLIGHT_CONDITION",
|
|
37
|
+
"SWEEP_VALUES",
|
|
38
|
+
"GEOMETRY",
|
|
39
|
+
"SYMMETRY",
|
|
40
|
+
"SYMMETRY_LOADS",
|
|
41
|
+
"NCPUS",
|
|
42
|
+
"WALLTIME",
|
|
43
|
+
"SOLVER_BUILD",
|
|
44
|
+
"FS_BUILD",
|
|
45
|
+
"WORKFLOW",
|
|
46
|
+
"VAR_NAMES_VALUES",
|
|
47
|
+
)
|
|
48
|
+
COLUMNS = (*REQUIRED_COLUMNS, *OPTIONAL_COLUMNS)
|
|
49
|
+
UNSTATED = ("", "-", "NA")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class MatrixError(WorkspaceError):
|
|
53
|
+
"""A matrix or one of its rows cannot be planned safely."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _no_variables() -> Mapping[str, object]:
|
|
57
|
+
return MappingProxyType({})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class MatrixRow:
|
|
62
|
+
"""One data row, numbered before filtering RUN, with exact text identifiers.
|
|
63
|
+
|
|
64
|
+
``hidden`` is the HIDDEN cell (whether a solver with a window shows it);
|
|
65
|
+
it never removes a row, which RUN alone decides. ``variables`` holds the
|
|
66
|
+
VAR_NAMES_VALUES overrides of setup keys. Text columns stating ``-`` are
|
|
67
|
+
empty strings, and other unstated columns are None.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
row_number: int
|
|
71
|
+
pol: str
|
|
72
|
+
run: int
|
|
73
|
+
setup_id: str
|
|
74
|
+
reference_id: str
|
|
75
|
+
post_id: str
|
|
76
|
+
condition: Mapping[str, float]
|
|
77
|
+
sweep_key: str | None
|
|
78
|
+
sweep_values: tuple[float, ...]
|
|
79
|
+
walltime: str | None
|
|
80
|
+
description: str
|
|
81
|
+
workflow: str
|
|
82
|
+
hidden: bool = False
|
|
83
|
+
aircraft: str = ""
|
|
84
|
+
configuration: str = ""
|
|
85
|
+
geometry: str | None = None
|
|
86
|
+
ncpus: int | None = None
|
|
87
|
+
solver_build: str | None = None
|
|
88
|
+
variables: Mapping[str, object] = field(default_factory=_no_variables)
|
|
89
|
+
condition_order: tuple[str, ...] = ()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _number(text: str, label: str) -> float:
|
|
93
|
+
try:
|
|
94
|
+
value = float(text)
|
|
95
|
+
except ValueError as error:
|
|
96
|
+
raise MatrixError(f"{label}: {text!r} must be a finite number") from error
|
|
97
|
+
if not math.isfinite(value):
|
|
98
|
+
raise MatrixError(f"{label}: {text!r} must be a finite number")
|
|
99
|
+
return 0.0 if value == 0 else value
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _artifact_id(text: str, prefix: str, label: str) -> str:
|
|
103
|
+
code = text.removesuffix(".toml").removeprefix(prefix)
|
|
104
|
+
if not code or not code.isascii() or not code.isdecimal():
|
|
105
|
+
raise MatrixError(f"{label}: {text!r} must name {prefix}<digits>.toml")
|
|
106
|
+
return prefix + code
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _condition(
|
|
110
|
+
cells: Mapping[str, str], label: str
|
|
111
|
+
) -> tuple[dict[str, float], str | None, tuple[str, ...]]:
|
|
112
|
+
held: dict[str, float] = {}
|
|
113
|
+
swept: str | None = None
|
|
114
|
+
text = cells.get("FLIGHT_CONDITION", "")
|
|
115
|
+
if text in UNSTATED:
|
|
116
|
+
return held, swept, ()
|
|
117
|
+
seen: set[str] = set()
|
|
118
|
+
for pair in text.split(","):
|
|
119
|
+
name, colon, raw = pair.partition(":")
|
|
120
|
+
key, raw = canonical_key(name), raw.strip()
|
|
121
|
+
if not colon or re.fullmatch("[A-Za-z][A-Za-z0-9_]*", key) is None:
|
|
122
|
+
raise MatrixError(f"{label}: FLIGHT_CONDITION needs KEY:number pairs")
|
|
123
|
+
if key in seen:
|
|
124
|
+
raise MatrixError(f"{label}: FLIGHT_CONDITION repeats {key}")
|
|
125
|
+
seen.add(key)
|
|
126
|
+
if raw.casefold() == "sweep":
|
|
127
|
+
if swept is not None:
|
|
128
|
+
raise MatrixError(f"{label}: only one FLIGHT_CONDITION key may sweep")
|
|
129
|
+
swept = key
|
|
130
|
+
else:
|
|
131
|
+
held[key] = _number(raw, f"{label} FLIGHT_CONDITION {key}")
|
|
132
|
+
order = tuple(canonical_key(pair.partition(":")[0]) for pair in text.split(","))
|
|
133
|
+
return held, swept, order
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _value(text: str) -> object:
|
|
137
|
+
try:
|
|
138
|
+
value = tomllib.loads(f"value = {text}")["value"]
|
|
139
|
+
except tomllib.TOMLDecodeError:
|
|
140
|
+
return text
|
|
141
|
+
if not isinstance(value, (str, int, float, bool, list, dict)):
|
|
142
|
+
return text
|
|
143
|
+
return value
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _split_outside(text: str, separator: str) -> list[str]:
|
|
147
|
+
parts: list[str] = []
|
|
148
|
+
depth = start = 0
|
|
149
|
+
for index, char in enumerate(text):
|
|
150
|
+
if char in "[{":
|
|
151
|
+
depth += 1
|
|
152
|
+
elif char in "]}":
|
|
153
|
+
depth -= 1
|
|
154
|
+
elif char == separator and depth == 0:
|
|
155
|
+
parts.append(text[start:index])
|
|
156
|
+
start = index + 1
|
|
157
|
+
parts.append(text[start:])
|
|
158
|
+
return parts
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _variables(text: str, label: str) -> Mapping[str, object]:
|
|
162
|
+
found: dict[str, object] = {}
|
|
163
|
+
if text in UNSTATED:
|
|
164
|
+
return MappingProxyType(found)
|
|
165
|
+
for pair in _split_outside(text, "/"):
|
|
166
|
+
name, colon, raw = pair.partition(":")
|
|
167
|
+
key, raw = name.strip(), raw.strip()
|
|
168
|
+
if not colon:
|
|
169
|
+
raise MatrixError(
|
|
170
|
+
f"{label}: VAR_NAMES_VALUES entry {pair.strip()!r} is not a KEY: value pair; "
|
|
171
|
+
"the cell holds '/'-separated KEY: value entries"
|
|
172
|
+
)
|
|
173
|
+
if re.fullmatch("[A-Za-z_][A-Za-z0-9_]*([.][A-Za-z_][A-Za-z0-9_]*)*", key) is None:
|
|
174
|
+
raise MatrixError(f"{label}: VAR_NAMES_VALUES key {key!r} is not a setup key name")
|
|
175
|
+
if key.upper() in COLUMNS:
|
|
176
|
+
raise MatrixError(
|
|
177
|
+
f"{label}: VAR_NAMES_VALUES states {key}, which is a matrix column; "
|
|
178
|
+
f"state it in the {key.upper()} column only"
|
|
179
|
+
)
|
|
180
|
+
if key in found:
|
|
181
|
+
raise MatrixError(
|
|
182
|
+
f"{label}: VAR_NAMES_VALUES states {key} twice; keep the value the row means"
|
|
183
|
+
)
|
|
184
|
+
if not raw:
|
|
185
|
+
raise MatrixError(f"{label}: VAR_NAMES_VALUES key {key} has no value")
|
|
186
|
+
found[key] = _value(raw)
|
|
187
|
+
return MappingProxyType(found)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _row(cells: Mapping[str, str], number: int, path: Path) -> MatrixRow:
|
|
191
|
+
pol = cells["POL"]
|
|
192
|
+
label = f"{path.name} data row {number}, POL {pol!r}"
|
|
193
|
+
if re.fullmatch("[A-Za-z0-9][A-Za-z0-9_-]*", pol) is None:
|
|
194
|
+
raise MatrixError(f"{label}: POL must be a non-empty filename-safe identifier")
|
|
195
|
+
if cells["RUN"] not in ("0", "1"):
|
|
196
|
+
raise MatrixError(f"{label}: RUN must be 0 or 1")
|
|
197
|
+
held, swept, order = _condition(cells, label)
|
|
198
|
+
values_text = cells.get("SWEEP_VALUES", "")
|
|
199
|
+
values: tuple[float, ...] = ()
|
|
200
|
+
if swept is None and values_text not in UNSTATED:
|
|
201
|
+
raise MatrixError(f"{label}: SWEEP_VALUES needs one FLIGHT_CONDITION key set to sweep")
|
|
202
|
+
if swept is not None:
|
|
203
|
+
if values_text in UNSTATED:
|
|
204
|
+
raise MatrixError(f"{label}: SWEEP_VALUES must name the values of {swept}")
|
|
205
|
+
values = tuple(_number(v.strip(), f"{label} SWEEP_VALUES") for v in values_text.split(","))
|
|
206
|
+
if len(set(values)) != len(values):
|
|
207
|
+
raise MatrixError(f"{label}: repeated SWEEP_VALUES would write the same point")
|
|
208
|
+
walltime = cells.get("WALLTIME", "")
|
|
209
|
+
if walltime in UNSTATED:
|
|
210
|
+
walltime_value = None
|
|
211
|
+
else:
|
|
212
|
+
match = re.fullmatch("([0-9]+(?:[.][0-9]+)?)(s|m|h|d)", walltime)
|
|
213
|
+
if match is None or _number(match[1], f"{label} WALLTIME") <= 0:
|
|
214
|
+
raise MatrixError(f"{label}: WALLTIME needs a positive number and s, m, h or d")
|
|
215
|
+
walltime_value = walltime
|
|
216
|
+
hidden = cells.get("HIDDEN", "")
|
|
217
|
+
if hidden not in (*UNSTATED, "0", "1"):
|
|
218
|
+
raise MatrixError(f"{label}: HIDDEN must be 0, 1 or -")
|
|
219
|
+
for column in ("SYMMETRY", "SYMMETRY_LOADS"):
|
|
220
|
+
if cells.get(column, "") not in UNSTATED:
|
|
221
|
+
raise MatrixError(
|
|
222
|
+
f"{label}: {column} {cells[column]!r} is not read by cfdbender solvers, which "
|
|
223
|
+
"take symmetry from the mesh and the setup; write - in the cell"
|
|
224
|
+
)
|
|
225
|
+
ncpus_text = cells.get("NCPUS", "")
|
|
226
|
+
ncpus: int | None = None
|
|
227
|
+
if ncpus_text not in UNSTATED:
|
|
228
|
+
if not ncpus_text.isascii() or not ncpus_text.isdecimal() or int(ncpus_text) < 1:
|
|
229
|
+
raise MatrixError(f"{label}: NCPUS must be a positive whole number or -")
|
|
230
|
+
ncpus = int(ncpus_text)
|
|
231
|
+
build = cells.get("SOLVER_BUILD", cells.get("FS_BUILD", ""))
|
|
232
|
+
if build not in UNSTATED and re.fullmatch("[A-Za-z0-9][A-Za-z0-9._+-]*", build) is None:
|
|
233
|
+
raise MatrixError(f"{label}: SOLVER_BUILD {build!r} must be a version such as 8.3.0")
|
|
234
|
+
geometry = cells.get("GEOMETRY", "")
|
|
235
|
+
if geometry not in UNSTATED and (
|
|
236
|
+
chr(92) in geometry or any(ord(c) < 32 or c in '<>"|?*' for c in geometry)
|
|
237
|
+
):
|
|
238
|
+
raise MatrixError(f"{label}: GEOMETRY {geometry!r} must name a file with / separators")
|
|
239
|
+
workflow = cells.get("WORKFLOW", "")
|
|
240
|
+
|
|
241
|
+
def text(column: str) -> str:
|
|
242
|
+
value = cells.get(column, "")
|
|
243
|
+
return "" if value in UNSTATED else value
|
|
244
|
+
|
|
245
|
+
return MatrixRow(
|
|
246
|
+
row_number=number,
|
|
247
|
+
pol=pol,
|
|
248
|
+
run=int(cells["RUN"]),
|
|
249
|
+
setup_id=_artifact_id(cells["SET"], "s", f"{label} SET"),
|
|
250
|
+
reference_id=_artifact_id(cells["REF"], "r", f"{label} REF"),
|
|
251
|
+
post_id=_artifact_id(cells["PPROC"], "p", f"{label} PPROC"),
|
|
252
|
+
condition=MappingProxyType(held),
|
|
253
|
+
sweep_key=swept,
|
|
254
|
+
sweep_values=values,
|
|
255
|
+
walltime=walltime_value,
|
|
256
|
+
description=text("DESCRIPTION"),
|
|
257
|
+
workflow="steady" if workflow in UNSTATED else workflow,
|
|
258
|
+
hidden=hidden == "1",
|
|
259
|
+
aircraft=text("AIRCRAFT"),
|
|
260
|
+
configuration=text("CONFIGURATION"),
|
|
261
|
+
geometry=None if geometry in UNSTATED else geometry,
|
|
262
|
+
ncpus=ncpus,
|
|
263
|
+
solver_build=None if build in UNSTATED else build,
|
|
264
|
+
variables=_variables(cells.get("VAR_NAMES_VALUES", ""), label),
|
|
265
|
+
condition_order=order,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def parse_matrix(data: bytes, source: Path, *, active_only: bool = True) -> tuple[MatrixRow, ...]:
|
|
270
|
+
"""Parse exact input bytes, retaining data row numbers before the RUN filter.
|
|
271
|
+
|
|
272
|
+
Parameters
|
|
273
|
+
----------
|
|
274
|
+
data : bytes
|
|
275
|
+
UTF-8 text with an optional BOM, hash comments and dashed separator rules.
|
|
276
|
+
source : Path
|
|
277
|
+
Source name for refusal messages.
|
|
278
|
+
active_only : bool, optional
|
|
279
|
+
Return only RUN = 1 rows; all rows are checked regardless.
|
|
280
|
+
|
|
281
|
+
Returns
|
|
282
|
+
-------
|
|
283
|
+
tuple of MatrixRow
|
|
284
|
+
Rows in source order, with ids kept as text, including leading zeros.
|
|
285
|
+
"""
|
|
286
|
+
try:
|
|
287
|
+
lines = data.decode("utf-8-sig").splitlines()
|
|
288
|
+
except UnicodeError as error:
|
|
289
|
+
raise MatrixError(f"{source}: cannot read UTF-8: {error}") from error
|
|
290
|
+
content = [
|
|
291
|
+
line.strip()
|
|
292
|
+
for line in lines
|
|
293
|
+
if line.strip() and not line.lstrip().startswith("#") and set(line.strip()) - set("-:+| \t")
|
|
294
|
+
]
|
|
295
|
+
if not content:
|
|
296
|
+
raise MatrixError(f"{source}: missing matrix header: {', '.join(REQUIRED_COLUMNS)}")
|
|
297
|
+
header = [c.strip() for c in content[0].split("|")]
|
|
298
|
+
if any(not c for c in header) or len(set(header)) != len(header):
|
|
299
|
+
raise MatrixError(f"{source}: blank or duplicate matrix headers")
|
|
300
|
+
missing = set(REQUIRED_COLUMNS) - set(header)
|
|
301
|
+
unknown = set(header) - set(COLUMNS)
|
|
302
|
+
if missing or unknown:
|
|
303
|
+
hints = [
|
|
304
|
+
f"{name} (closest known column: {close[0]})" if close else name
|
|
305
|
+
for name in sorted(unknown)
|
|
306
|
+
for close in [difflib.get_close_matches(name, COLUMNS, n=1)]
|
|
307
|
+
]
|
|
308
|
+
raise MatrixError(
|
|
309
|
+
f"{source}: missing columns: {', '.join(sorted(missing)) or '(none)'}; "
|
|
310
|
+
f"unsupported columns: {', '.join(hints) or '(none)'}"
|
|
311
|
+
)
|
|
312
|
+
if {"SOLVER_BUILD", "FS_BUILD"} <= set(header):
|
|
313
|
+
raise MatrixError(f"{source}: SOLVER_BUILD and FS_BUILD name one column; keep one")
|
|
314
|
+
result: list[MatrixRow] = []
|
|
315
|
+
seen: set[str] = set()
|
|
316
|
+
for number, line in enumerate(content[1:], 1):
|
|
317
|
+
fields = [c.strip() for c in line.split("|")]
|
|
318
|
+
if len(fields) != len(header):
|
|
319
|
+
raise MatrixError(f"{source}: data row {number} needs {len(header)} columns")
|
|
320
|
+
row = _row(dict(zip(header, fields, strict=True)), number, source)
|
|
321
|
+
if row.pol.casefold() in seen:
|
|
322
|
+
raise MatrixError(f"{source}: data row {number} repeats POL {row.pol!r}")
|
|
323
|
+
seen.add(row.pol.casefold())
|
|
324
|
+
if row.run == 1 or not active_only:
|
|
325
|
+
result.append(row)
|
|
326
|
+
return tuple(result)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def read_matrix(path: str | Path, *, active_only: bool = True) -> tuple[MatrixRow, ...]:
|
|
330
|
+
"""Read a pipe-delimited .fs matrix without interpreting solver settings.
|
|
331
|
+
|
|
332
|
+
Parameters
|
|
333
|
+
----------
|
|
334
|
+
path : str or Path
|
|
335
|
+
Matrix location. Workspace discovery belongs to the planning layer.
|
|
336
|
+
active_only : bool, optional
|
|
337
|
+
Return only RUN = 1 rows.
|
|
338
|
+
|
|
339
|
+
Returns
|
|
340
|
+
-------
|
|
341
|
+
tuple of MatrixRow
|
|
342
|
+
Validated rows. No solver is loaded and no file is written.
|
|
343
|
+
|
|
344
|
+
Raises
|
|
345
|
+
------
|
|
346
|
+
MatrixError
|
|
347
|
+
Named read, schema, identity or cell refusal.
|
|
348
|
+
"""
|
|
349
|
+
source = Path(path)
|
|
350
|
+
try:
|
|
351
|
+
data = source.read_bytes()
|
|
352
|
+
except OSError as error:
|
|
353
|
+
raise MatrixError(f"{source}: cannot read: {error}") from error
|
|
354
|
+
return parse_matrix(data, source, active_only=active_only)
|