Analysis over Philote
This example runs Bora from Python with no Rust code on the Python side. Bora
runs as a separate process, bora_server, and Python reaches it over gRPC
through Philote. You will learn how to:
- start the server and connect to it,
- call the discipline directly with Philote-Python's client,
- put the same discipline in an OpenMDAO model and solve for the angle of attack that gives a chosen lift coefficient,
- get derivatives of the solved model, with the angle adjusting to hold the lift fixed,
- add a flap and let it hold the lift at a fixed angle, and find out what that costs in drag.
The complete script is examples/openmdao/analyze.py. It analyzes the
airfoil from the quickstart at a Reynolds
number of 10⁶. No optimizer is involved; for that, see
Multipoint optimization.
Before you start
You need OpenMDAO and Philote-Python (philote-mdo on PyPI), both listed in
examples/openmdao/requirements.txt, and either a Rust toolchain to build the
server or Docker to run its image:
pip install -r examples/openmdao/requirements.txt
Step 1: Start the server
In a second terminal, from the repository root:
cargo run --release --features philote --bin bora_server
The first run builds the server. It then listens on localhost:50051 until
you stop it. Without a Rust toolchain, run the
Docker image instead:
docker run -d --rm --name bora -p 50051:50051 chrislupp/bora:next
Either way, the server listens on the same port. Every client in this example talks to that one process. The options, such as the network size, belong to the server and stay set until a client changes them. Clients that share a server should agree on them, and each client should set every option it relies on rather than assume the defaults.
Step 2: Run the example
In the first terminal:
python3 examples/openmdao/analyze.py
If the server listens elsewhere, pass --server host:port. --model-size
selects the network (default xlarge). The script connects with a timeout,
so a server that is not running gives a message saying how to start one
rather than a hang.
Step 3: Call the discipline directly
Philote is not tied to OpenMDAO. Its client speaks the protocol directly, so any Python program can use Bora. The client first sets the options, then asks the server to set up the discipline and to describe its variables and partials:
client = pmg.ExplicitClient(channel=channel)
client.send_options({
"model_size": model_size,
"include_corrections": False, # set explicitly: a previous client
"control_surface_hinge_points": "", # may have changed them (step 6)
})
client.run_setup() # the server reloads the network here
client.get_variable_definitions()
client.get_partials_definitions()
Inputs go in as a dictionary of NumPy arrays keyed by the variable names. Every input must be present, scalars included:
inputs = flow_inputs(alpha=3.0) # {"upper_weights": array([...]), "Re": array([1e6]), ...}
outputs = client.run_compute(inputs)
partials = client.run_compute_partials(inputs)
print(outputs["CL"][0], partials["CL", "alpha"][0])
Partials come back keyed by (output, input) pairs, in the shapes described in
Variables. The script prints the result at
3°, the operating point that examples/example.rs analyzes in Rust:
Discipline 'Bora' 0.3.0, model size 'xlarge'
inputs: upper_weights lower_weights leading_edge_weight TE_thickness alpha Re n_crit xtr_upper xtr_lower
outputs: CL CD CM Top_Xtr Bot_Xtr analysis_confidence
alpha = 3.00 deg, Re = 1.00e+06
CL = 0.95162 CD = 0.00729 CM = -0.13014 L/D = 130.585
dCL/dalpha = 0.10185 per deg
dCL/d(upper_weights): 0.0876 -0.0515 0.1400 0.4751 0.5213 0.3174 0.1829 0.2422
Every number matches the Rust example to the last digit. Going through the server changes how you call Bora, not what it computes.
Step 4: Fly at a fixed lift coefficient
An aircraft flies at the lift coefficient its weight and speed demand, and
the angle of attack is whatever produces it. OpenMDAO can solve for that
angle. Wrap Bora's RemoteExplicitComponent in a group together with a
BalanceComp, which adds alpha as an implicit variable with the residual
, and let a Newton solver drive the residual to
zero:
class FixedLift(om.Group):
def setup(self):
self.add_subsystem(
"bora",
pmom.RemoteExplicitComponent(channel=channel, model_size=model_size),
promotes=["*"],
)
balance = om.BalanceComp()
balance.add_balance("alpha", units="deg", val=2.0, lhs_name="CL", rhs_name="CL_target")
self.add_subsystem("balance", balance, promotes=["*"])
self.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)
self.linear_solver = om.DirectSolver()
Newton needs the derivative of the residual with respect to alpha, and it
gets it from Bora: RemoteExplicitComponent declares the partials the server
offers and fetches them on every Newton step.
The script sweeps the target from 0.2 to 1.6. Each solve starts from the previous angle:
Fixed lift, Re = 1.00e+06
CL alpha CD CM L/D confidence Newton
0.200 -3.745 0.00810 -0.1300 24.7 0.9659 4
0.400 -1.987 0.00675 -0.1315 59.3 0.9562 3
0.600 -0.235 0.00671 -0.1322 89.5 0.9604 3
0.800 1.555 0.00712 -0.1322 112.3 0.9650 4
1.000 3.473 0.00744 -0.1295 134.4 0.9653 4
1.200 5.400 0.00899 -0.1272 133.5 0.9774 3
1.400 7.471 0.01131 -0.1224 123.8 0.9809 4
1.600 10.183 0.01616 -0.1075 99.0 0.9819 5
Each point converges to a residual of in three to five Newton iterations. That is the quadratic convergence you get only with exact derivatives, because the network is smooth and its partials are exact. The sweep is the drag polar indexed by lift instead of by angle: the best lift-to-drag ratio, about 134, is near , and the drag rises quickly above 1.2 as the polar approaches stall (compare the polar sweep).
Step 5: Differentiate the solved model
compute_totals differentiates through the Newton solve. The derivatives
include the change in alpha that keeps the lift on target:
prob.set_val("CL_target", 1.0)
prob.run_model()
totals = prob.compute_totals(of=["CD", "alpha"], wrt=["upper_weights"])
For comparison, the script also asks the bare client for the partial at the same angle, which holds the angle fixed and lets the lift change. It then checks one fixed-lift derivative against a central difference, re-solving the model on each side:
Shape derivatives at CL = 1.0 (alpha = 3.473 deg)
dalpha/d(upper_weights): -0.5413 0.6214 -1.9477 -5.1457 -4.9511 -2.7222 -1.5718 -2.2425
dCD/d(upper_weights), fixed CL: 0.00713 0.01595 0.00329 -0.01298 -0.01226 -0.00190 0.00318 0.00167
dCD/d(upper_weights), fixed alpha: 0.00738 0.01566 0.00420 -0.01058 -0.00995 -0.00063 0.00391 0.00272
dCD/d(upper_weights[3]) at fixed CL: analytic -1.298280e-02, central difference -1.298280e-02
The two drag derivatives answer different questions. At fixed angle, thickening the upper surface around mid-chord (weights 3 and 4) adds lift as well as changing drag. At fixed lift, the extra lift is traded for a lower angle: about 5° less per unit weight, as the first row shows. The lower angle saves drag, so the fixed-lift derivative is more negative, by about a quarter for those weights. When you design an airfoil for a given flight condition, the fixed-lift derivative is the one you want.
The check agrees to all seven digits shown. OpenMDAO assembles the fixed-lift derivative from Bora's partials by the implicit function theorem, without re-solving, and it matches the finite difference of the complete solve.
Step 6: Hold the lift with a flap
So far the angle of attack has set the lift. On an aircraft the wing's
incidence is often fixed, and a flap does the job instead. Bora models
control surfaces as part of the corrected analysis,
so the third part of the script turns on include_corrections and puts a
plain flap at 75% chord with the control_surface_hinge_points option. That
adds the mach input and a control_surface_deflections input, one entry per
hinge point, in degrees with the trailing edge down (see
Control surfaces).
The fixed-lift group from step 4 needs one change: the balance drives the deflection instead of the angle. The angle stays at 2°:
FLAPPED = {"include_corrections": True, "control_surface_hinge_points": "0.75"}
prob.model.add_subsystem(
"wing",
FixedLift(channel=channel, model_size=model_size, bora_options=FLAPPED,
control="control_surface_deflections"),
promotes=["*"],
)
prob.setup()
prob.set_val("alpha", 2.0)
prob.set_val("mach", 0.0)
For comparison, a second model of the same flapped airfoil keeps the flap at zero and holds the lift with the angle, as step 4 does. Both models set the same options, so they can share the server. Sweeping the lift coefficient:
Flap at 75% chord, alpha = 2.0 deg, Re = 1.00e+06
CL flap CD CM CD, by angle penalty Newton
0.600 -4.044 0.00714 -0.1316 0.00671 6.4% 4
0.800 -0.754 0.00714 -0.1316 0.00713 0.2% 4
1.000 2.774 0.00768 -0.1289 0.00746 2.9% 4
1.200 6.314 0.01049 -0.1266 0.00904 16.0% 4
1.400 10.138 0.01648 -0.1216 0.01142 44.3% 4
Newton converges as fast as before. The partials of every output with respect to the deflections come from Bora, so the solve takes four iterations at each point.
The flap acts as a change of angle. In the model Bora takes from AeroSandbox, each degree of deflection of a flap hinged at 75% chord shifts the angle the network sees by about 0.55°, so 6.3° of flap at 2° gives the same section as 5.45° of angle. The pitching moment is therefore that of the angle-held airfoil. The model has no separate flap moment, so it does not show the nose-down moment of a real flap.
What the flap adds is drag. The deflection also multiplies the drag by a factor fitted to wind tunnel data, which grows with the square of small deflections. The penalty column is that factor: almost nothing within a degree of neutral, 16% at 6°, and 44% at 10°. Holding lift with the flap costs drag that holding it with the angle does not.
The "by angle" drag is up to 1% above step 4's at the same lift. That is because the corrected analysis includes AeroSandbox's smoothed Prandtl-Glauert factor, which is about 1.0045 rather than exactly 1 at Mach 0. The lift at a given angle is about half a percent lower, so the angle and drag needed for a given lift are slightly higher.
With the deflection as a solver variable, the derivatives of the solved model
answer a design question: at a lift coefficient of 1.2, should the incidence
go up or down? compute_totals differentiates through the Newton solve, with
the flap moving to keep the lift on target, and the script checks the result
against a central difference of the re-solved model:
totals = prob.compute_totals(of=["CD", "control_surface_deflections"], wrt=["alpha"])
At CL = 1.2 (flap = 6.314 deg):
dflap/dalpha = -1.8286
dCD/dalpha at fixed CL: analytic -8.862694e-04, central difference -8.862694e-04
Each degree of extra incidence lets the flap come back by 1.83°, the inverse of its 0.55° per degree. That lowers the drag by about 8.9 × 10⁻⁴, or 8%, so at this lift the incidence should go up. The derivative agrees with the finite difference to all seven digits shown.
The complete script
#!/usr/bin/env python3
"""Airfoil analysis with Bora over Philote: a direct client call, then OpenMDAO.
Part 1 talks to bora_server with Philote-Python's bare ExplicitClient: it sets
the options, reads the variable definitions and asks for values and partials at
one operating point, the same one examples/example.rs analyzes in Rust.
Part 2 puts the same discipline in an OpenMDAO model and flies the airfoil at a
prescribed lift coefficient instead of a prescribed angle: a BalanceComp and a
Newton solver find the angle, using Bora's partials for the Newton Jacobian.
The model then sweeps the lift coefficient, and computes the derivatives of
drag with respect to the shape at fixed lift, which it checks against central
differences of the solved model.
Part 3 adds a plain flap at 75% chord and holds the angle of attack instead:
the same Newton solve now finds the flap deflection that gives the lift, and
the drag is compared with that of Part 2. It then asks which way to change
the angle to save drag at fixed lift, and checks that derivative as well.
Start the server first, in a second terminal, from the repository root:
cargo run --release --features philote --bin bora_server
Then run, also from the repository root:
pip install -r examples/openmdao/requirements.txt
python3 examples/openmdao/analyze.py
"""
import argparse
import sys
import grpc
import numpy as np
import openmdao.api as om
import philote_mdo.general as pmg
import philote_mdo.generated.data_pb2 as data
import philote_mdo.openmdao as pmom
# The airfoil of the quickstart and of examples/example.rs.
UPPER_WEIGHTS = np.array([0.24, 0.31, 0.25, 0.35, 0.24, 0.35, 0.28, 0.32])
LOWER_WEIGHTS = np.array([-0.12, -0.05, -0.13, 0.02, -0.08, 0.06, 0.02, 0.06])
LEADING_EDGE_WEIGHT = 0.02
TE_THICKNESS = 0.0025
REYNOLDS = 1e6
N_CRIT = 9.0
CL_TARGET = 1.0
CL_SWEEP = np.arange(0.2, 1.61, 0.2)
# Part 3: a plain flap at 75% chord on the airfoil held at a fixed angle.
FLAP_HINGE = 0.75
FLAP_ALPHA = 2.0
FLAP_CL_SWEEP = np.arange(0.6, 1.41, 0.2)
# The options belong to the server and persist between clients, so every client
# states all of the ones it depends on.
PLAIN = {"include_corrections": False, "control_surface_hinge_points": ""}
FLAPPED = {"include_corrections": True, "control_surface_hinge_points": str(FLAP_HINGE)}
def connect(address, timeout=10.0):
"""Open a channel to bora_server, failing with a hint if nothing answers."""
channel = grpc.insecure_channel(address)
try:
grpc.channel_ready_future(channel).result(timeout=timeout)
except grpc.FutureTimeoutError:
sys.exit(f"no bora_server at {address}; start one with\n"
" cargo run --release --features philote --bin bora_server")
return channel
def flow_inputs(alpha=None):
"""The airfoil and flow condition as Philote inputs: name -> array."""
inputs = {
"upper_weights": UPPER_WEIGHTS,
"lower_weights": LOWER_WEIGHTS,
"leading_edge_weight": LEADING_EDGE_WEIGHT,
"TE_thickness": TE_THICKNESS,
"Re": REYNOLDS,
"n_crit": N_CRIT,
"xtr_upper": 1.0,
"xtr_lower": 1.0,
}
if alpha is not None:
inputs["alpha"] = alpha
return {name: np.atleast_1d(np.asarray(value, dtype=float))
for name, value in inputs.items()}
def open_client(channel, model_size):
"""A bare Philote client, set up the way OpenMDAO's component sets up its own."""
client = pmg.ExplicitClient(channel=channel)
client.get_discipline_info()
client.send_options({"model_size": model_size, **PLAIN})
client.run_setup() # the server reloads the network here
client.get_variable_definitions()
client.get_partials_definitions()
return client
def direct_call(channel, model_size):
"""Part 1: one operating point through the bare Philote client."""
client = open_client(channel, model_size)
print(f"Discipline '{client._name}' {client._version}, model size '{model_size}'")
print(" inputs: ", " ".join(v.name for v in client._var_meta if v.type == data.kInput))
print(" outputs:", " ".join(v.name for v in client._var_meta if v.type == data.kOutput))
inputs = flow_inputs(alpha=3.0)
outputs = client.run_compute(inputs)
partials = client.run_compute_partials(inputs)
cl, cd, cm = (outputs[k][0] for k in ("CL", "CD", "CM"))
print(f"\nalpha = 3.00 deg, Re = {REYNOLDS:.2e}")
print(f" CL = {cl:9.5f} CD = {cd:9.5f} CM = {cm:9.5f} L/D = {cl / cd:8.3f}")
print(f" dCL/dalpha = {partials['CL', 'alpha'][0]:.5f} per deg")
print(" dCL/d(upper_weights):", fmt(partials["CL", "upper_weights"]))
class FixedLift(om.Group):
"""Bora at a prescribed lift coefficient: Newton drives a control until CL = CL_target."""
def initialize(self):
self.options.declare("channel")
self.options.declare("model_size", types=str)
self.options.declare("bora_options", types=dict, default=PLAIN)
self.options.declare("control", types=str, default="alpha",
desc="the input the solver adjusts, in deg")
def setup(self):
self.add_subsystem(
"bora",
pmom.RemoteExplicitComponent(
channel=self.options["channel"], model_size=self.options["model_size"],
**self.options["bora_options"],
),
promotes=["*"],
)
balance = om.BalanceComp()
balance.add_balance(self.options["control"], units="deg", val=2.0,
lhs_name="CL", rhs_name="CL_target")
self.add_subsystem("balance", balance, promotes=["*"])
newton = self.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)
newton.options["atol"] = 1e-12
newton.options["rtol"] = 1e-12
newton.options["maxiter"] = 20
newton.options["iprint"] = 0
self.linear_solver = om.DirectSolver()
def fixed_lift(channel, model_size):
"""Part 2: the airfoil at fixed lift in OpenMDAO."""
prob = om.Problem(reports=False)
prob.model.add_subsystem(
"wing", FixedLift(channel=channel, model_size=model_size), promotes=["*"]
)
prob.setup()
for name, value in flow_inputs().items():
prob.set_val(name, value)
newton = prob.model.wing.nonlinear_solver
print(f"\nFixed lift, Re = {REYNOLDS:.2e}")
print(f"{'CL':>6} {'alpha':>7} {'CD':>8} {'CM':>8} {'L/D':>6} {'confidence':>10}"
f" {'Newton':>6}")
for target in CL_SWEEP:
prob.set_val("CL_target", target)
prob.run_model()
cl, cd, cm, conf = (prob.get_val(k)[0] for k in ("CL", "CD", "CM",
"analysis_confidence"))
print(f"{cl:6.3f} {prob.get_val('alpha')[0]:7.3f} {cd:8.5f} {cm:8.4f} "
f"{cl / cd:6.1f} {conf:10.4f} {newton._iter_count:6d}")
# Derivatives of the solved model: OpenMDAO differentiates through the
# Newton solve, so alpha adjusts to hold CL at the target.
prob.set_val("CL_target", CL_TARGET)
prob.run_model()
totals = prob.compute_totals(of=["CD", "alpha"], wrt=["upper_weights"])
dcd_fixed_lift = totals["CD", "upper_weights"].ravel()
print(f"\nShape derivatives at CL = {CL_TARGET} "
f"(alpha = {prob.get_val('alpha')[0]:.3f} deg)")
print(" dalpha/d(upper_weights): ", fmt(totals["alpha", "upper_weights"].ravel()))
print(" dCD/d(upper_weights), fixed CL: ", fmt(dcd_fixed_lift, 5))
# The same through the bare client, at this angle: fixed alpha, CL free.
client = open_client(channel, model_size)
inputs = flow_inputs(alpha=prob.get_val("alpha")[0])
dcd_fixed_alpha = client.run_compute_partials(inputs)["CD", "upper_weights"]
print(" dCD/d(upper_weights), fixed alpha:", fmt(dcd_fixed_alpha, 5))
# Check the fixed-lift derivative of one weight by central differences,
# re-solving the model on each side.
k, step = 3, 1e-5
drag = []
for sign in (1.0, -1.0):
weights = UPPER_WEIGHTS.copy()
weights[k] += sign * step
prob.set_val("upper_weights", weights)
prob.run_model()
drag.append(prob.get_val("CD")[0])
fd = (drag[0] - drag[1]) / (2.0 * step)
print(f"\n dCD/d(upper_weights[{k}]) at fixed CL: analytic {dcd_fixed_lift[k]: .6e}, "
f"central difference {fd: .6e}")
def flapped_problem(channel, model_size, control):
"""A FixedLift model of the flapped airfoil that adjusts `control` to hold the lift."""
prob = om.Problem(reports=False)
prob.model.add_subsystem(
"wing",
FixedLift(channel=channel, model_size=model_size, bora_options=FLAPPED,
control=control),
promotes=["*"],
)
prob.setup()
for name, value in flow_inputs(alpha=FLAP_ALPHA).items():
prob.set_val(name, value)
prob.set_val("mach", 0.0)
prob.set_val("control_surface_deflections", 0.0)
return prob
def flap_at_fixed_angle(channel, model_size):
"""Part 3: the lift held by a flap at a fixed angle of attack."""
prob = flapped_problem(channel, model_size, control="control_surface_deflections")
newton = prob.model.wing.nonlinear_solver
# For comparison, the same airfoil with the flap at zero and the lift held
# by the angle, as in Part 2. Both models set the same server options.
by_angle = flapped_problem(channel, model_size, control="alpha")
def cd_by_angle(target):
by_angle.set_val("CL_target", target)
by_angle.run_model()
return by_angle.get_val("CD")[0]
print(f"\nFlap at {FLAP_HINGE:.0%} chord, alpha = {FLAP_ALPHA} deg, Re = {REYNOLDS:.2e}")
print(f"{'CL':>6} {'flap':>7} {'CD':>8} {'CM':>8} {'CD, by angle':>12} {'penalty':>7}"
f" {'Newton':>6}")
for target in FLAP_CL_SWEEP:
prob.set_val("CL_target", target)
prob.run_model()
cl, cd, cm = (prob.get_val(k)[0] for k in ("CL", "CD", "CM"))
flap = prob.get_val("control_surface_deflections")[0]
cd_angle = cd_by_angle(target)
print(f"{cl:6.3f} {flap:7.3f} {cd:8.5f} {cm:8.4f} {cd_angle:12.5f} "
f"{cd / cd_angle - 1:7.1%} {newton._iter_count:6d}")
# At fixed lift, which way should the angle go? Raising it lets the flap
# come back, and OpenMDAO gets both derivatives through the Newton solve.
prob.set_val("CL_target", 1.2)
prob.run_model()
totals = prob.compute_totals(of=["CD", "control_surface_deflections"], wrt=["alpha"])
dcd_dalpha = totals["CD", "alpha"][0, 0]
print(f"\nAt CL = 1.2 (flap = {prob.get_val('control_surface_deflections')[0]:.3f} deg):")
print(f" dflap/dalpha = {totals['control_surface_deflections', 'alpha'][0, 0]:.4f}")
step = 1e-4
drag = []
for sign in (1.0, -1.0):
prob.set_val("alpha", FLAP_ALPHA + sign * step)
prob.run_model()
drag.append(prob.get_val("CD")[0])
fd = (drag[0] - drag[1]) / (2.0 * step)
print(f" dCD/dalpha at fixed CL: analytic {dcd_dalpha: .6e}, central difference {fd: .6e}")
def fmt(values, digits=4):
return " ".join(f"{v:{digits + 4}.{digits}f}" for v in np.ravel(values))
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--server", default="localhost:50051",
help="address of a running bora_server (default: localhost:50051)")
parser.add_argument("--model-size", default="xlarge",
help="NeuralFoil network size (default: xlarge)")
args = parser.parse_args()
channel = connect(args.server)
direct_call(channel, args.model_size)
fixed_lift(channel, args.model_size)
flap_at_fixed_angle(channel, args.model_size)
if __name__ == "__main__":
main()