File size: 10,498 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 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 | from pathlib import Path
from shutil import which
from contextlib import redirect_stderr, redirect_stdout
import glob
import io
import math
import os
import re
import subprocess
import tempfile
FLUENT_EXEC_FILE = r"C:\Program Files\ANSYS Inc\v261\fluent\ntbin\win64\fluent.exe"
DESKTOP = Path(r"C:\Users\user\Desktop")
CASE_FILE = DESKTOP / "pipe_laminar.cas"
DATA_FILE = DESKTOP / "pipe_laminar.dat"
REQUIRED_FILES = (CASE_FILE, DATA_FILE)
FLOAT_RE = r"[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?"
def is_nonempty_file(path: Path) -> bool:
return path.is_file() and path.stat().st_size > 0
def find_fluent_executable() -> str:
explicit = Path(FLUENT_EXEC_FILE)
if explicit.is_file():
return str(explicit)
cmd = which("fluent")
if cmd:
return cmd
candidates = []
for key, value in os.environ.items():
if key.startswith("AWP_ROOT"):
candidates.append(Path(value) / "fluent" / "ntbin" / "win64" / "fluent.exe")
for pattern in (
r"C:\Program Files\ANSYS Inc\ANSYS Student\v*\fluent\ntbin\win64\fluent.exe",
r"C:\Program Files\ANSYS Inc\v*\fluent\ntbin\win64\fluent.exe",
):
candidates.extend(Path(p) for p in glob.glob(pattern))
for candidate in candidates:
if candidate.is_file():
return str(candidate)
raise FileNotFoundError("Fluent executable not found")
def decode_case(path: Path) -> str:
return path.read_bytes().decode("latin-1", errors="ignore")
def extract_zone(text: str, zone_type: str, zone_name: str) -> str:
start = re.search(
rf"\(39\s+\([^\n]*\b{re.escape(zone_type)}\s+{re.escape(zone_name)}\s+1\)\(",
text,
flags=re.I,
)
if not start:
return ""
following = text[start.start() :]
end = following.find("\n(39 ", 5)
return following if end < 0 else following[:end]
def case_configuration_is_valid(case_file: Path) -> bool:
text = decode_case(case_file)
low = text.lower()
required_tokens = (
'(0 "fluent26.1.',
"(2 3)",
"(rp-3d? . #t)",
"(rp-double? . #t)",
"(rp-seg? . #t)",
"(rp-unsteady? . #f)",
"(rp-lam? . #t)",
"(rp-turb? . #f)",
"(rp-visc? . #t)",
"(flow/scheme 20)",
"(pressure/scheme 12)",
"(mom/scheme 1)",
"(density (constant . 998.2)",
"(viscosity (constant . 0.001003)",
"(material . water-liquid)",
"(cfd-post-mesh-info ((0 0 (fluid) (wall wall fluid) (outlet pressure-outlet fluid) (inlet velocity-inlet fluid)))",
)
if not all(token in low for token in required_tokens):
return False
inlet = extract_zone(text, "velocity-inlet", "inlet").lower()
outlet = extract_zone(text, "pressure-outlet", "outlet").lower()
wall = extract_zone(text, "wall", "wall").lower()
if not inlet or not outlet or not wall:
return False
if "(vmag (constant . 0.1)" not in inlet:
return False
if "(flow-direction-component ((constant . 1)" not in inlet:
return False
if "(p (constant . 0)" not in outlet:
return False
if "(moving? . #f)" not in wall:
return False
return True
def extract_predictions(root: Path) -> dict:
journal = """/file/read-case-data pipe_laminar.cas
/mesh/check
/report/surface-integrals/area-weighted-avg outlet () x-velocity no
/exit yes
"""
with tempfile.NamedTemporaryFile(
mode="w", encoding="ascii", suffix=".jou", dir=root, delete=False
) as stream:
stream.write(journal)
journal_path = Path(stream.name)
try:
proc = subprocess.run(
[find_fluent_executable(), "3ddp", "-g", "-i", journal_path.name],
cwd=root,
capture_output=True,
text=True,
timeout=300,
)
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
if (
proc.returncode != 0
or "Error:" in output
or 'Reading "pipe_laminar.cas"' not in output
or 'Reading "pipe_laminar.dat"' not in output
):
raise RuntimeError("Fluent did not load the case and data cleanly")
extents = {}
for axis in "xyz":
match = re.search(
rf"{axis}-coordinate:\s*min \(m\) =\s*({FLOAT_RE}),\s*max \(m\) =\s*({FLOAT_RE})",
output,
flags=re.I,
)
if not match:
raise RuntimeError(f"{axis} extent not found")
extents[axis] = (float(match.group(1)), float(match.group(2)))
cells = re.search(r"(\d+)\s+hexahedral cells", output, flags=re.I)
volume = re.search(rf"minimum volume \(m3\):\s*({FLOAT_RE})", output, flags=re.I)
values = re.findall(rf"^\s*outlet\s+({FLOAT_RE})\s*$", output, flags=re.I | re.M)
if not cells or not volume or not values:
raise RuntimeError("hex-cell count, mesh volume, or outlet velocity not found")
return {
"extents": extents,
"hexahedral_cells": int(cells.group(1)),
"minimum_cell_volume_m3": float(volume.group(1)),
"outlet_mean_x_velocity_m_s": float(values[-1]),
}
finally:
try:
journal_path.unlink()
except OSError:
pass
def solution_and_near_wall_layers_are_valid(root: Path, outlet_mean: float) -> bool:
import ansys.fluent.core as pyfluent
from ansys.fluent.core.services.field_data import SurfaceDataType
solver = pyfluent.launch_fluent(
mode="solver",
precision="double",
processor_count=1,
dimension=3,
ui_mode="no_gui",
start_watchdog=False,
)
try:
solver.settings.file.read_case_data(file_name=str(root / CASE_FILE.stem))
plane_name = "__eval_c15_mid_plane"
solver.settings.results.surfaces.plane_surface[plane_name] = {
"method": "yz-plane",
"x": 0.05,
}
data = solver.fields.field_data.get_surface_data(
data_types=[SurfaceDataType.Vertices, SurfaceDataType.FacesConnectivity],
surfaces=[plane_name],
)[plane_name]
vertices = data[SurfaceDataType.Vertices]
faces = data[SurfaceDataType.FacesConnectivity]
if len(vertices) < 25 or len(faces) < 16:
return False
radii = [math.hypot(float(row[1]), float(row[2])) for row in vertices]
if max(radii) > 0.00202 or abs(max(radii) - 0.002) > 2e-5:
return False
adjacency = [set() for _ in vertices]
for face in faces:
indices = [int(value) for value in face]
for index, first in enumerate(indices):
second = indices[(index + 1) % len(indices)]
adjacency[first].add(second)
adjacency[second].add(first)
wall_vertices = [index for index, radius in enumerate(radii) if radius >= 0.00198]
if len(wall_vertices) < 16:
return False
chains = 0
for start in wall_vertices:
current = start
for _ in range(3):
candidates = [
neighbor
for neighbor in adjacency[current]
if 1e-7 < radii[current] - radii[neighbor] < 5e-4
]
if not candidates:
break
current = min(candidates, key=lambda neighbor: radii[current] - radii[neighbor])
else:
chains += 1
if chains < 0.8 * len(wall_vertices):
return False
velocity = solver.fields.field_data.get_scalar_field_data(
field_name="x-velocity",
surfaces=[plane_name],
)[plane_name]
wall_velocity = [abs(float(velocity[index])) for index in wall_vertices]
core_velocity = [
float(value)
for value, radius in zip(velocity, radii)
if radius <= 0.0005
]
if not core_velocity or max(float(value) for value in velocity) < 1.25 * outlet_mean:
return False
if sum(core_velocity) / len(core_velocity) < 1.15 * outlet_mean:
return False
if max(wall_velocity) > 0.05 * outlet_mean:
return False
pressure = solver.fields.field_data.get_scalar_field_data(
field_name="pressure",
surfaces=["inlet", "outlet"],
)
inlet_pressure = sum(float(value) for value in pressure["inlet"]) / len(pressure["inlet"])
outlet_pressure = sum(float(value) for value in pressure["outlet"]) / len(pressure["outlet"])
return 1.0 < inlet_pressure - outlet_pressure < 1000.0
finally:
solver.exit()
def predictions_are_valid(predictions: dict) -> bool:
extents = predictions["extents"]
targets = {
"x": (0.0, 0.100, 2e-5),
"y": (-0.002, 0.002, 2e-5),
"z": (-0.002, 0.002, 2e-5),
}
for axis, (expected_min, expected_max, tolerance) in targets.items():
actual_min, actual_max = extents[axis]
if abs(actual_min - expected_min) > tolerance:
return False
if abs(actual_max - expected_max) > tolerance:
return False
if predictions["minimum_cell_volume_m3"] <= 0:
return False
if predictions["hexahedral_cells"] < 1000:
return False
return 0.095 <= predictions["outlet_mean_x_velocity_m_s"] <= 0.105
def kill_ansys_related() -> None:
for image in ("fluent.exe", "cortex.exe"):
try:
subprocess.run(
["taskkill", "/F", "/IM", image],
capture_output=True,
creationflags=0x08000000,
)
except Exception:
pass
def evaluate() -> bool:
kill_ansys_related()
if any(not is_nonempty_file(path) for path in REQUIRED_FILES):
return False
try:
if not case_configuration_is_valid(CASE_FILE):
return False
predictions = extract_predictions(DESKTOP)
return predictions_are_valid(predictions) and solution_and_near_wall_layers_are_valid(
DESKTOP,
predictions["outlet_mean_x_velocity_m_s"],
)
except Exception:
return False
def main() -> None:
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
result = evaluate()
print("True" if result else "False")
if __name__ == "__main__":
main()
|