"""Planar stage and rotor-alone cases: the MoC stator and the Goldman vortex rotor as 2D cascades in Fluent.
On an axial machine the rotating-frame forces on a cylinder (centrifugal and Coriolis) are radial,
so the blade-to-blade plane with the rotor zone translating at U is the stage at that radius, and
the rotor alone is a stationary cascade fed with its relative inflow. Radial equilibrium and
spanwise stream-tube changes are left out. Fluent's 2D flows are per metre of depth.
``python -m turbo_moc.fluent.stage.planar <workflow.yaml> [stage|rotor|stage-extract|rotor-extract]`` designs the rows
(``planar_design``), assembles the planar mesh, writes the Fluent case and, when the workflow asks
for it, solves it and extracts the fields; the ``-extract`` modes only re-extract a solved case.
"""
import json
import sys
from pathlib import Path
import numpy as np
import yaml
from . import case, planar_design, planar_mesh
from .setup import solve
STATOR, ROTOR = case.STATOR, case.ROTOR
VELOCITIES = ("x-velocity", "y-velocity")
FIELDS = ("absolute-pressure", "density", "x-velocity", "y-velocity", "relative-x-velocity", "relative-y-velocity")
[docs]
def swirl_direction(stator):
"""+1 when the stator exit flow runs towards +x in the planar frame (the flow runs towards -y)."""
points = stator["xy"][np.unique(stator["boundaries"]["periodic_left"])]
points = points[np.argsort(points[:, 1])][: max(3, len(points) // 10)]
return -float(np.sign(np.polyfit(points[:, 1], points[:, 0], 1)[0]))
[docs]
def inflow_direction(rotor):
"""+1 when the rotor's inlet extension runs towards +x as the flow runs towards -y."""
points = rotor["xy"][np.unique(rotor["boundaries"]["periodic_left"])]
points = points[np.argsort(points[:, 1])][-max(3, len(points) // 10):]
return -float(np.sign(np.polyfit(points[:, 1], points[:, 0], 1)[0]))
[docs]
def build_mesh(output_dir, design, rotor_only=False):
sections, passages = design["sections"], design["rotor"]["passages"]
if "stator_1" not in sections:
rotor = sections["rotor_1"]
return {"mesh_file": planar_mesh.write_cgns(output_dir / "mesh" / "rotor_2d.cgns", {"rotor_1": rotor}),
"swirl_direction": inflow_direction(rotor), "rotor_passages": 1,
"stator_pitch_m": float(rotor["pitch"][0]) / 1e3, "rotor_pitch_m": float(rotor["pitch"][0]) / 1e3,
"cells": {"rotor_1": len(rotor["cells"])}}
stator, rotor = planar_mesh.assemble(sections["stator_1"], sections["rotor_1"], passages,
match=not design.get("mixing", False))
zones = {"rotor_1": sections["rotor_1"]} if rotor_only else {"stator_1": stator, "rotor_1": rotor}
name = "rotor_2d.cgns" if rotor_only else "stage_2d.cgns"
return {"mesh_file": planar_mesh.write_cgns(output_dir / "mesh" / name, zones),
"swirl_direction": swirl_direction(stator), "rotor_passages": 1 if rotor_only else passages,
"stator_pitch_m": float(stator["pitch"][0]) / 1e3,
"rotor_pitch_m": float(sections["rotor_1"]["pitch"][0]) / 1e3,
"rotor_sector_m": float(rotor["pitch"][0]) / 1e3,
"cells": {row: len(section["cells"]) for row, section in zones.items()}}
[docs]
def import_mesh(settings, mesh_file, rows):
settings.file.import_.read(file_type="cgns-mesh", file_name=str(mesh_file))
settings.mesh.check()
types = case.boundary_types(settings.setup.boundary_conditions)
return {f"{row}_{name}": case.zone(types, row.split("_fluid")[0], name)
for row in rows for name in planar_mesh.BOUNDARIES}
[docs]
def flow_model(settings, options):
"""Inviscid when the workflow says ``viscous: false``; the turbulence residuals then drop out."""
if options.get("viscous", True):
return options
settings.setup.models.viscous.model = "inviscid"
return dict(options, residual_equations={key: value for key, value in options["residual_equations"].items()
if key not in ("k", "omega")})
[docs]
def translational_periodicity(settings, zones, rows, pitch_m):
"""Each row's sides paired one sector apart along +x (2D needs the explicit translation vector).
``pitch_m`` is one sector for all rows, or a ``{row: sector}`` mapping when the rows differ (mixing plane).
"""
for row in rows:
sector = pitch_m[row] if isinstance(pitch_m, dict) else pitch_m
settings.mesh.modify_zones.make_periodic(zone_name=zones[f"{row}_periodic_left"],
shadow_zone_name=zones[f"{row}_periodic_right"],
rotate_periodic=False, create=True, auto_translation=False,
direction=[sector, 0.0])
periodic = settings.setup.boundary_conditions.periodic
for name in periodic.get_object_names():
periodic[name].periodic.rotationally_periodic = "Translational"
[docs]
def turbulence(boundary, options, backflow=False):
boundary.turbulence.turbulence_specification = "Intensity and Viscosity Ratio"
prefix = "backflow_" if backflow else ""
setattr(boundary.turbulence, f"{prefix}turbulent_intensity", options["turbulence_intensity"])
setattr(boundary.turbulence, f"{prefix}turbulent_viscosity_ratio", options["turbulence_viscosity_ratio"])
[docs]
def outlet_boundary(settings, zones, pressure, options):
outlet = settings.setup.boundary_conditions.pressure_outlet[zones[f"{ROTOR}_outlet"]]
outlet.momentum.gauge_pressure.value = pressure
if options.get("viscous", True):
turbulence(outlet, options, backflow=True)
[docs]
def mass_flow_inflow(inflow, mesh):
"""The design relative inflow of one rotor passage, per metre of depth, and its planar direction."""
beta = np.radians(inflow["beta"])
return {"p": inflow["p"], "W": inflow["W"],
"direction": [mesh["swirl_direction"] * np.sin(beta), -np.cos(beta)],
"mass_flow": inflow["rho"] * inflow["W"] * np.cos(beta) * mesh["rotor_pitch_m"]}
[docs]
def total_pressure_expression(closure, total, static, degree=8):
"""Inlet total pressure that is isentropic on the barotropic model at any inlet state.
Fluent subtracts rho W^2 / 2 from the total pressure of a pressure-defined density; giving it
p + rho(p) [H(P0_rel) - H(p)] makes that equal to the barotropic head drop, so W^2 / 2 = H(P0_rel) - H(p)
whether the inflow is supersonic or subsonic. H(p) is fitted from 0.3 times the design static pressure
to just below P0_rel.
"""
pressure = np.linspace(0.3 * static, 0.98 * total, 400)
coefficients = np.polyfit(pressure / total - 1, float(closure.head(total)) - closure.head(pressure), degree)
ratio = f"(AbsolutePressure / {total:.10e} [Pa] - 1)"
horner = f"{coefficients[0]:.12e}"
for value in coefficients[1:]:
horner = f"({horner}) * {ratio} {'+' if value >= 0 else '-'} {abs(value):.12e}"
return f"AbsolutePressure + barotropic_density * ({horner}) * 1 [m^2/s^2]"
[docs]
def inlet_direction(inflow, beta):
swirl = np.sign(inflow["direction"][0]) or 1.0
return [swirl * np.sin(np.radians(beta)), -np.cos(np.radians(beta))]
[docs]
def solve_rotor(solver, configured, options):
"""Start from a uniform inflow, then the staged strategy.
A stage ``beta`` [deg] turns the inlet flow direction, so a passage started with a supersonic axial inflow
can be carried to the subsonic-axial unique incidence. A stage ``outlet_pressure`` [Pa] resets the back
pressure, so a passage started against a low back pressure can be raised to the design one.
"""
from ..common import set_order
settings = solver.settings
inflow = configured["inflow"]
kind, name = configured["inlet"]
inlet = getattr(settings.setup.boundary_conditions, kind)[name]
first = next((stage["beta"] for stage in options["solution_strategy"] if "beta" in stage), None)
direction = inflow["direction"] if first is None else inlet_direction(inflow, first)
initialization = settings.solution.initialization
initialization.initialization_type = "standard"
initialization.defaults["pressure"] = inflow["p"]
for component, value in zip(VELOCITIES, direction):
initialization.defaults[component] = value * inflow["W"]
initialization.standard_initialize()
for stage in options["solution_strategy"]:
if "beta" in stage:
for component, value in zip(inlet.momentum.flow_direction, inlet_direction(inflow, stage["beta"])):
component.value = value
print(f" inlet angle {stage['beta']:.2f} deg", flush=True)
if "outlet_pressure" in stage:
outlet = settings.setup.boundary_conditions.pressure_outlet[configured["boundaries"][f"{ROTOR}_outlet"]]
outlet.momentum.gauge_pressure.value = stage["outlet_pressure"]
print(f" outlet pressure {stage['outlet_pressure']:.0f} Pa", flush=True)
set_order(settings, first_order=stage["order"] == "first")
settings.solution.run_calculation.pseudo_time_settings.time_step_method.time_step_size_scale_factor = (
stage["time_scale_factor"])
print(f" {stage['iterations']} iterations, {stage['order']} order", flush=True)
settings.solution.run_calculation.iterate(iter_count=stage["iterations"])
[docs]
def summary(design, mesh, cycle):
rotor = design["rotor"]
return {"stator_exit": design["stator_exit"], "relative_inflow": design["relative_inflow"],
"rotor": {"chord_mm": rotor["chord"], "passages": rotor["passages"], "pitch_chord": rotor["pitch_chord"],
"beta_inlet": rotor["blade"]["beta_inlet"], "beta_outlet": rotor["blade"]["beta_outlet"],
**{key: rotor["blade"][key] for key in ("M_inlet", "M_outlet", "M_lower", "M_upper",
"nu_inlet_deg", "nu_outlet_deg", "nu_lower_deg",
"nu_upper_deg", "num_points")},
"surfaces": {side: {"x": rotor["blade"][side]["x"], "y": rotor["blade"][side]["y"]}
for side in ("pressure", "suction")},
"blade_x_range": [float(min(rotor["blade"]["blade"]["x"])), float(max(rotor["blade"]["blade"]["x"]))]},
"stator": {"pitch_mm": float(design["stator"]["design"].blade["pitch"])} if "design" in design["stator"] else None,
"cycle": {key: value for key, value in cycle.items() if key not in ("relative_inflow", "barotropy_dir")},
"mesh": {key: str(value) if isinstance(value, Path) else value for key, value in mesh.items()}}
[docs]
def main(config_file, mode="stage"):
if mode.endswith("-extract"):
return extract_case(config_file, "rotor_2d" if mode.startswith("rotor") else "stage_2d")
config_file = Path(config_file).resolve()
workflow = yaml.safe_load(config_file.read_text(encoding="utf-8"))
source = yaml.safe_load((config_file.parent / workflow["project_file"]).read_text(encoding="utf-8"))
output_dir = (config_file.parent / workflow["output_dir"]).resolve()
output_dir.mkdir(parents=True, exist_ok=True)
rotor_only = mode == "rotor"
name = "rotor_2d" if rotor_only else "stage_2d"
print("1/5 Goldman vortex rotor (and MoC stator) and their planar passages", flush=True)
prescribed = rotor_only and "relative_inflow" in workflow
design = (planar_design.design_rotor_only if prescribed else planar_design.design_stage)(source, workflow)
mesh = build_mesh(output_dir, design, rotor_only)
cycle = {"blade_speed": float(workflow.get("blade_speed", 0.0)),
"outlet_pressure": float(design.get("outlet_pressure") or workflow["outlet_pressure"]),
"relative_inflow": design["relative_inflow"], "inlet": workflow.get("inlet", "mass_flow"), "interface": workflow.get("interface", "frozen_rotor"),
"barotropy_dir": output_dir / "barotropy"}
inflow = design["relative_inflow"]
print(f" rotor inflow M_rel {inflow['M']:.3f} at {inflow['beta']:.2f} deg (axial Mach {inflow['axial_mach']:.3f}); "
f"rotor chord {design['rotor']['chord']:.2f} mm, {design['rotor']['passages']} passages per stator pitch; "
f"cells {mesh['cells']}", flush=True)
start = design["rotor"]["starting"]
print(f" starting check: throat/inlet {start['throat_ratio']:.3f}, Kantrowitz {start['kantrowitz_ratio']:.3f}, "
f"margin {start['margin']:.3f}", flush=True)
from ..barotropic_model import generate_barotropic_model
from ..common import load_dependencies
barotropy, pyfluent = load_dependencies(False)
print("2/5 Barotropic model along the stator inlet isentrope", flush=True)
parameters = dict(design["stator"]["config"]["method_of_characteristics"])
baro = dict(workflow["barotropic"])
if "backend" in baro:
parameters["backend"] = baro["backend"]
if baro.get("pressure_ratio") == "auto":
baro["pressure_ratio"] = float(design["stator"]["nozzle"]["meta"]["P0"]) / (cycle["outlet_pressure"] / 100)
print(f" fit from P0 down to p_out / 100: pressure ratio {baro['pressure_ratio']:.0f}", flush=True)
expressions, state = generate_barotropic_model(barotropy, {"nozzle": parameters}, design["stator"]["nozzle"],
baro, output_dir / "barotropy")
options = workflow["fluent"]
print(f"3/5 Launch Fluent 2D ({options['ui_mode']})", flush=True)
fluent_dir = output_dir / "fluent"
fluent_dir.mkdir(exist_ok=True)
solver = pyfluent.launch_fluent(product_version=options["product_version"], mode="solver", dimension=2,
precision="double", processor_count=options["processor_count"],
ui_mode=options["ui_mode"], start_timeout=options["start_timeout"],
cwd=str(fluent_dir), cleanup_on_exit=False)
print(f"4/5 Configure the planar {'rotor' if rotor_only else 'stage'}", flush=True)
configured = (configure_rotor if rotor_only else configure_stage)(solver, mesh, state, expressions, cycle, options)
case_file = fluent_dir / f"{name}.cas.h5"
solver.settings.file.batch_options.confirm_overwrite = False
solver.settings.file.write_case(file_name=str(case_file))
(fluent_dir / f"{name}_summary.json").write_text(json.dumps(
{**configured, **summary(design, mesh, cycle), "inlet_state": state, "case_file": str(case_file)},
indent=2, default=float), encoding="utf-8")
print(f"5/5 Case saved: {case_file}", flush=True)
if options.get("solve", False):
try:
if rotor_only:
solve_rotor(solver, configured, options)
else:
solve(solver, options, VELOCITIES)
solver.settings.file.write_case_data(file_name=str(case_file))
extract(solver, configured, fluent_dir / f"{name}_fields.npz")
print(f" Solved, saved and extracted: {case_file}", flush=True)
finally:
if options["ui_mode"] == "no_gui":
close_fluent(solver, fluent_dir)
elif options["ui_mode"] == "no_gui":
close_fluent(solver, fluent_dir)
return case_file
[docs]
def close_fluent(solver, fluent_dir):
"""Exit Fluent, then run its own cleanup scripts so no MPI process keeps the licence or the files."""
import subprocess
try:
solver.exit()
except Exception:
pass
for script in fluent_dir.glob("cleanup-fluent-*.bat"):
subprocess.run(["cmd", "/c", str(script)], cwd=str(fluent_dir), capture_output=True)
script.unlink(missing_ok=True)
if __name__ == "__main__":
main(*sys.argv[1:])