Skip to main content
Version: 0.2.0

Multipoint optimization

In this tutorial you set up an airfoil optimization in OpenMDAO, with Bora doing the aerodynamics and IPOPT doing the optimizing. You will learn how to:

  • run Bora as a server and connect it to OpenMDAO through Philote,
  • analyze several operating points with one server,
  • add geometric constraints of your own next to Bora's outputs,
  • hand the whole problem to IPOPT with exact gradients.

The example designs an airfoil for a human-powered aircraft. It is the case the NeuralFoil paper uses to demonstrate optimization (Sharpe and Hansman, 2025), originally from Drela's study of airfoil optimization (Drela, 1998). The complete script is examples/openmdao/optimize_daedalus.py. The steps below walk through it.

Before you start​

You need:

  • OpenMDAO and Philote-Python (philote-mdo on PyPI), listed in examples/openmdao/requirements.txt
  • pyOptSparse built with IPOPT. The conda-forge package includes it: conda install -c conda-forge pyoptsparse
  • A Rust toolchain. The script starts bora_server through cargo run --features philote, so the first run also builds the server

Install the Python packages and run the example from the repository root:

pip install -r examples/openmdao/requirements.txt
python3 examples/openmdao/optimize_daedalus.py

The whole run takes a few seconds once the server is built. If you already have a server running, pass --server host:port. --model-size selects the network (default large).

Step 1: Know what you are solving​

The airfoil has to fly well across the aircraft's whole speed range, so the objective is drag averaged over six lift coefficients, with more weight on the higher ones. More lift means flying slower, so each point has its own Reynolds number: ReCL\mathrm{Re}\sqrt{C_L} is held at the value for Re=500 000\mathrm{Re} = 500\,000 and CL=1.25C_L = 1.25.

RoleQuantity
Minimize16∑iwi CD,i\frac{1}{6}\sum_i w_i\, C_{D,i} at CL=0.8,1.0,1.2,1.4,1.5,1.6C_L = 0.8, 1.0, 1.2, 1.4, 1.5, 1.6 with w=5,6,7,8,9,10w = 5, 6, 7, 8, 9, 10
Subject toCL,iC_{L,i} equal to its target at each point
CM,i≥−0.133C_{M,i} \ge -0.133 and analysis confidence ≥0.90\ge 0.90 at each point
angle of attack increasing with CLC_L
t/c≥0.128t/c \ge 0.128 at x/c=0.33x/c = 0.33 (main spar), t/c≥0.014t/c \ge 0.014 at x/c=0.90x/c = 0.90 (rear spar)
trailing-edge angle ≥6.03°\ge 6.03°, positive thickness everywhere
wiggliness at most twice that of the starting airfoil
Design variables16 surface weights, the leading-edge weight, one angle of attack per point (23)
Fixedzero trailing-edge thickness, Ncrit=9N_\mathrm{crit} = 9, free transition
StartNACA 0012

Two of the constraints are there to keep the optimizer honest rather than to describe the aircraft. The confidence limit keeps it inside the region where the network is trustworthy (see Analysis confidence). The wiggliness, the sum of squared second differences of each side's weights, stops it from exploiting bumpy shapes. The NeuralFoil paper recommends both, along with positive thickness (Sharpe and Hansman, 2025).

The formulation, the bounds and the normalization of the objective follow AeroSandbox's NeuralFoil optimization tutorial (AeroSandbox), so you can compare your result with the one it reports.

Step 2: Start Bora and connect to it​

bora_server serves Bora's Philote discipline over gRPC. The script starts it on a free port and opens a channel to it:

examples/openmdao/optimize_daedalus.py (abridged)
address = f"localhost:{free_port()}"
server = subprocess.Popen(
["cargo", "run", "--release", "--quiet", "--features", "philote",
"--bin", "bora_server", "--", address],
cwd=REPO_ROOT,
)
atexit.register(server.terminate)

channel = grpc.insecure_channel(address)
wait_for(channel, server)

wait_for blocks until the server accepts connections, which on the first run includes building it.

Step 3: Add one component per operating point​

Each operating point is a Philote-Python RemoteExplicitComponent. All six share the channel, so one server answers them all, and each receives Bora's analytic partials. The shape inputs are promoted so every point sees the same airfoil.

Bora's discipline takes a scalar angle of attack, while the design vector holds all six angles. Use src_indices to give each point its own entry:

examples/openmdao/optimize_daedalus.py (abridged)
for i in range(N_POINTS):
name = f"point{i}"
model.add_subsystem(
name,
pmom.RemoteExplicitComponent(channel=channel, model_size=model_size),
promotes_inputs=shape_inputs,
)
model.connect("alpha", f"{name}.alpha", src_indices=[i])

The flow conditions are not design variables. Set them once after prob.setup():

for i, reynolds in enumerate(REYNOLDS):
prob.set_val(f"point{i}.Re", reynolds)
prob.set_val(f"point{i}.n_crit", 9.0)
prob.set_val(f"point{i}.xtr_upper", 1.0)
prob.set_val(f"point{i}.xtr_lower", 1.0)

Step 4: Compute the geometry locally​

The spar, trailing-edge and wiggliness constraints depend only on the shape, so there is no reason to send them through the network. The KulfanGeometry component in examples/openmdao/kulfan.py computes them in Python, from the same Kulfan formula Bora uses in generate_kulfan_coordinates, and supplies its own analytic partials.

A useful detail: thickness is linear in the weights, because the leading-edge mode is the same on both surfaces and cancels. Its Jacobian is therefore constant, and you can tell OpenMDAO so with linear=True. IPOPT then treats the spar and positive-thickness constraints as linear and never has to re-evaluate their derivatives:

examples/openmdao/optimize_daedalus.py (abridged)
model.add_constraint(
"geometry.thickness", lower=SPAR_THICKNESS_MIN, indices=[0, 1],
alias="spar_thickness", linear=True,
)

Step 5: Add the objective, design variables and constraints​

The objective is an ExecComp that averages the weighted drag of the six points. Scale it with ref: its value is around 0.08, and IPOPT works best when the objective is near one.

examples/openmdao/optimize_daedalus.py (abridged)
model.add_objective("objective.drag", ref=0.01)

for i, cl in enumerate(CL_TARGETS):
model.add_constraint(f"point{i}.CL", equals=cl)
model.add_constraint(f"point{i}.CM", lower=CM_MIN)
model.add_constraint(f"point{i}.analysis_confidence", lower=CONFIDENCE_MIN)

Note that the lift is a constraint, not an input. The optimizer adjusts each point's angle of attack until the lift matches its target.

Step 6: Configure IPOPT​

pyOptSparse runs IPOPT with a limited-memory quasi-Newton Hessian:

examples/openmdao/optimize_daedalus.py (abridged)
driver = prob.driver = om.pyOptSparseDriver(optimizer="IPOPT")
driver.opt_settings["mu_strategy"] = "monotone"
driver.opt_settings["limited_memory_max_history"] = 50

If you port settings from the AeroSandbox tutorial, be aware that it gives IPOPT an exact Hessian, and two of its choices do not carry over to a quasi-Newton one:

  • Leave out start_with_resto. With it, IPOPT never leaves the restoration phase from the NACA 0012 and stops at an infeasible point.
  • Raise limited_memory_max_history. The default keeps 6 updates. With 50, and the objective scaled as in Step 5, the run takes 98 iterations instead of 556. Either change alone still needs over 400.

Step 7: Run it​

The script prints the starting point, IPOPT's summary and the optimum. Here is a run, without IPOPT's iteration log and option table:

Starting point (NACA 0012):
CL target Re alpha CL CD CM L/D confidence
0.80 6.25e+05 7.295 0.8481 0.01306 -0.0074 64.9 0.9795
1.00 5.59e+05 9.119 0.9849 0.01630 0.0045 60.4 0.9839
1.20 5.1e+05 10.943 1.0840 0.02098 0.0220 51.7 0.9836
1.40 4.72e+05 12.766 1.1426 0.02831 0.0407 40.4 0.9761
1.50 4.56e+05 13.678 1.1633 0.03379 0.0468 34.4 0.9702
1.60 4.42e+05 14.590 1.1763 0.04153 0.0491 28.3 0.9646

objective mean(w * CD) = 0.209324
t/c at x/c = 0.33: 0.1188 at x/c = 0.90: 0.0267
trailing-edge angle = 15.849 deg
wiggliness = 0.04648 (limit 0.09297)

Number of Iterations....: 98
Total seconds in IPOPT = 3.091
EXIT: Optimal Solution Found.

Optimized:
CL target Re alpha CL CD CM L/D confidence
0.80 6.25e+05 1.216 0.8000 0.00769 -0.1244 104.1 0.9663
1.00 5.59e+05 3.047 1.0000 0.00841 -0.1265 118.9 0.9731
1.20 5.1e+05 4.815 1.2000 0.00947 -0.1296 126.8 0.9740
1.40 4.72e+05 6.585 1.4000 0.01072 -0.1326 130.5 0.9755
1.50 4.56e+05 7.516 1.5000 0.01142 -0.1330 131.3 0.9756
1.60 4.42e+05 8.700 1.6000 0.01263 -0.1289 126.7 0.9743

objective mean(w * CD) = 0.078334
t/c at x/c = 0.33: 0.1280 at x/c = 0.90: 0.0140
trailing-edge angle = 6.030 deg
wiggliness = 0.09297 (limit 0.09297)

Kulfan parameters:
upper_weights = [0.177813 0.236825 0.350829 0.337303 0.380060 0.357433 0.187523 0.216231]
lower_weights = [-0.102093 -0.038836 -0.017524 -0.002367 0.020386 0.018594 0.067472 0.108128]
leading_edge_weight = 0.349865

Wrote optimized_daedalus.dat

The optimized airfoil is written to optimized_daedalus.dat in Selig format, ready for XFoil or any other tool.

Results​

Start with the constraints. In the output above, the spar thicknesses, the trailing-edge angle and the wiggliness sit exactly at their limits, and the moment at CL=1.5C_L = 1.5 is at −0.133-0.133. Active constraints like these tell you what is shaping the design: here the structure and manufacturing limits matter as much as the drag. If you want a different airfoil, these are the numbers to change.

The shape itself has gone from the symmetric NACA 0012 to a strongly cambered section with a nearly flat lower surface:

main spar, t/c ≥ 0.128rear spar, t/c ≥ 0.014start, NACA 0012optimized00.51.0x/c
The starting NACA 0012 and the optimized section. The dimension lines at the two spar stations have the required thicknesses; at the optimum both meet the surfaces exactly, so both constraints are active. One small square is 0.02 of the chord.

Next, look at performance away from the six design points. Flying both sections along the same schedule, with the Reynolds number following the lift, shows the camber at work. The NACA 0012 stalls near CL=1.2C_L = 1.2, so it cannot reach four of the six targets at any angle. The optimized section carries lift to about 1.64 with low drag throughout, and pays for it with a nose-down moment that the CMC_M limit holds in check:

00.010.020.030.040.050.51.01.5Section drag coefficientSection lift coefficientNACA 0012optimized−0.20−0.15−0.10−0.0500.050.51.01.5Section moment coefficientSection lift coefficientlimit −0.133NACA 0012optimized
Both sections flown along the schedule of the problem, each angle of attack evaluated at the Reynolds number its own lift implies. The circles are the six design points of the optimum; they lie on its curves. Each curve stops at maximum lift and where the analysis confidence falls below 0.9. The vertical line is the moment limit. One small square is 0.05 in lift, 0.001 in drag and 0.005 in moment.

Finally, confirm that IPOPT actually converged rather than just stopping. Optimality and feasibility should both fall to near zero together. Here they stay high for most of the run, jumping up whenever the optimizer takes a long step (at iterations 10, 55 and 73), then drop fast once the active constraints settle near iteration 85. At the end, optimality is about 2×10−92 \times 10^{-9} and the constraint violation is at rounding error:

110−510−10Optimality020406080100110−510−1010−15IPOPT iterationFeasibility
Optimality (IPOPT's dual infeasibility) and feasibility (its largest constraint violation) at each of the 98 IPOPT iterations, read from IPOPT's output file. One small square is two iterations across and one decade up.

The complete scripts​

The example is two files. optimize_daedalus.py builds and runs the problem:

examples/openmdao/optimize_daedalus.py
#!/usr/bin/env python3
"""Multipoint airfoil optimization with OpenMDAO, IPOPT and Bora over Philote.

Reproduces the human-powered-aircraft case from AeroSandbox's NeuralFoil
optimization tutorial, which follows Drela's "Pros and Cons of Airfoil
Optimization" (1998), with Bora as the aerodynamic analysis:

minimize mean_i(w_i * CD_i) over six lift coefficients CL_i
w.r.t. 16 Kulfan weights, the leading-edge weight, one alpha per point
subject to CL_i = target_i, CM_i >= -0.133, confidence_i >= 0.90,
alpha increasing with CL,
t/c >= 0.128 at x/c = 0.33, t/c >= 0.014 at x/c = 0.90,
trailing-edge angle >= 6.03 deg, t/c > 0 everywhere,
wiggliness <= 2x that of the starting NACA 0012

Each operating point is a `RemoteExplicitComponent` (Philote-Python) talking to
one `bora_server` over gRPC; Bora supplies the analytic partials. The geometric
constraints are evaluated locally in `kulfan.py`.

The script starts `bora_server` itself (building it on first use through cargo)
unless `--server` names one that is already running.

Usage, from the repository root:
pip install -r examples/openmdao/requirements.txt # plus pyOptSparse with IPOPT
python3 examples/openmdao/optimize_daedalus.py
"""

import argparse
import atexit
import json
import os
import re
import socket
import subprocess
import sys
from pathlib import Path

import grpc
import numpy as np
import openmdao.api as om
import philote_mdo.openmdao as pmom

from kulfan import NUM_WEIGHTS, KulfanGeometry, selig_coordinates, wiggliness

REPO_ROOT = Path(__file__).resolve().parents[2]

# Operating points: lift coefficients, their weights in the objective, and a
# Reynolds number that keeps Re * sqrt(CL) fixed (constant wing loading).
CL_TARGETS = np.array([0.8, 1.0, 1.2, 1.4, 1.5, 1.6])
CL_WEIGHTS = np.array([5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
REYNOLDS = 500e3 * (CL_TARGETS / 1.25) ** -0.5
N_POINTS = len(CL_TARGETS)

OBJECTIVE_REF = 0.01
CM_MIN = -0.133
CONFIDENCE_MIN = 0.90
TE_ANGLE_MIN = 6.03 # deg
SPAR_STATIONS = [0.33, 0.90]
SPAR_THICKNESS_MIN = [0.128, 0.014]
# Positive thickness is checked at interior stations; it is identically zero at
# the leading edge, and at the trailing edge with zero trailing-edge thickness.
POSITIVE_STATIONS = list(np.linspace(0.0, 1.0, 101)[1:-1])

# Starting airfoil: NACA 0012 (Kulfan weights fitted to its coordinates).
NACA0012_UPPER = np.array(
[0.172884, 0.151563, 0.173763, 0.127681, 0.164818, 0.126376, 0.145898, 0.1392]
)
NACA0012_LOWER = -NACA0012_UPPER
WIGGLINESS_MAX = 2.0 * wiggliness(NACA0012_UPPER, NACA0012_LOWER)


def free_port():
with socket.socket() as s:
s.bind(("localhost", 0))
return s.getsockname()[1]


def start_server():
"""Start bora_server on a free local port; returns its address."""
address = f"localhost:{free_port()}"
command = ["cargo", "run", "--release", "--quiet", "--features", "philote",
"--bin", "bora_server", "--", address]
print(f"Starting bora_server on {address} (first run builds it)...", flush=True)
server = subprocess.Popen(command, cwd=REPO_ROOT)
atexit.register(server.terminate)
return address, server


def wait_for(channel, server, timeout=600.0):
"""Block until the channel is ready, failing early if the server exits."""
future = grpc.channel_ready_future(channel)
waited = 0.0
while True:
try:
future.result(timeout=1.0)
return
except grpc.FutureTimeoutError:
waited += 1.0
if server is not None and server.poll() is not None:
sys.exit("bora_server exited before accepting connections")
if waited >= timeout:
sys.exit("timed out waiting for bora_server")


class AlphaSchedule(om.ExplicitComponent):
"""Differences of consecutive alphas, constrained positive."""

def setup(self):
self.add_input("alpha", shape=N_POINTS, units="deg")
self.add_output("alpha_steps", shape=N_POINTS - 1, units="deg")
rows = np.repeat(np.arange(N_POINTS - 1), 2)
cols = np.column_stack([np.arange(N_POINTS - 1), np.arange(1, N_POINTS)]).ravel()
vals = np.tile([-1.0, 1.0], N_POINTS - 1)
self.declare_partials("alpha_steps", "alpha", rows=rows, cols=cols, val=vals)

def compute(self, inputs, outputs):
outputs["alpha_steps"] = np.diff(inputs["alpha"])


def build_problem(channel, model_size):
prob = om.Problem(reports=False)
model = prob.model

design = model.add_subsystem("design", om.IndepVarComp(), promotes=["*"])
design.add_output("upper_weights", NACA0012_UPPER)
design.add_output("lower_weights", NACA0012_LOWER)
design.add_output("leading_edge_weight", 0.0)
design.add_output("TE_thickness", 0.0)
design.add_output("alpha", np.degrees(CL_TARGETS / (2.0 * np.pi)), units="deg")

shape_inputs = ["upper_weights", "lower_weights", "leading_edge_weight", "TE_thickness"]
for i in range(N_POINTS):
name = f"point{i}"
model.add_subsystem(
name,
pmom.RemoteExplicitComponent(channel=channel, model_size=model_size),
promotes_inputs=shape_inputs,
)
model.connect("alpha", f"{name}.alpha", src_indices=[i])

model.add_subsystem(
"geometry",
KulfanGeometry(stations=SPAR_STATIONS + POSITIVE_STATIONS),
promotes_inputs=["upper_weights", "lower_weights", "TE_thickness"],
)
model.add_subsystem("schedule", AlphaSchedule(), promotes_inputs=["alpha"])

# Objective: the weighted drag, averaged over the points (AeroSandbox's
# normalization, mean(w * CD), so the optimum compares directly).
terms = " + ".join(f"{w:g} * CD{i}" for i, w in enumerate(CL_WEIGHTS))
model.add_subsystem("objective", om.ExecComp(f"drag = ({terms}) / {N_POINTS}"))
for i in range(N_POINTS):
model.connect(f"point{i}.CD", f"objective.CD{i}")

# Design variables and bounds. The first weight of each side is kept away
# from zero (a round leading edge), as in the reference case.
upper_lower = np.full(NUM_WEIGHTS, -0.25)
upper_lower[0] = 0.05
lower_upper = np.full(NUM_WEIGHTS, 0.25)
lower_upper[0] = -0.05
model.add_design_var("upper_weights", lower=upper_lower, upper=0.5)
model.add_design_var("lower_weights", lower=-0.5, upper=lower_upper)
model.add_design_var("leading_edge_weight", lower=-1.0, upper=1.0)
model.add_design_var("alpha", lower=-5.0, upper=18.0, units="deg")

# ref scales the objective (about 0.08) towards one for IPOPT.
model.add_objective("objective.drag", ref=OBJECTIVE_REF)

for i, cl in enumerate(CL_TARGETS):
model.add_constraint(f"point{i}.CL", equals=cl)
model.add_constraint(f"point{i}.CM", lower=CM_MIN)
model.add_constraint(f"point{i}.analysis_confidence", lower=CONFIDENCE_MIN)
model.add_constraint("schedule.alpha_steps", lower=0.0, linear=True)

n_spar = len(SPAR_STATIONS)
model.add_constraint(
"geometry.thickness", lower=SPAR_THICKNESS_MIN, indices=list(range(n_spar)),
alias="spar_thickness", linear=True,
)
model.add_constraint(
"geometry.thickness", lower=0.0,
indices=list(range(n_spar, n_spar + len(POSITIVE_STATIONS))),
alias="positive_thickness", linear=True,
)
model.add_constraint("geometry.te_angle", lower=TE_ANGLE_MIN, units="deg")
model.add_constraint("geometry.wiggliness", upper=WIGGLINESS_MAX)

# pyOptSparse runs IPOPT with a limited-memory (L-BFGS) Hessian, where the
# reference used an exact one; a longer memory than the default 6 pairs
# roughly halves the iteration count. The reference's start_with_resto is
# left off: from the NACA 0012 the restoration phase stalls without an
# exact Hessian.
driver = prob.driver = om.pyOptSparseDriver(optimizer="IPOPT", print_results=False)
driver.opt_settings["mu_strategy"] = "monotone"
driver.opt_settings["limited_memory_max_history"] = 50
driver.opt_settings["print_level"] = 5

prob.setup()
for i, reynolds in enumerate(REYNOLDS):
prob.set_val(f"point{i}.Re", reynolds)
prob.set_val(f"point{i}.n_crit", 9.0)
prob.set_val(f"point{i}.xtr_upper", 1.0)
prob.set_val(f"point{i}.xtr_lower", 1.0)
return prob


def report(prob, title):
print(f"\n{title}")
print(f"{'CL target':>9} {'Re':>9} {'alpha':>7} {'CL':>7} {'CD':>8} "
f"{'CM':>8} {'L/D':>6} {'confidence':>10}")
alpha = prob.get_val("alpha")
for i, target in enumerate(CL_TARGETS):
cl, cd, cm = (prob.get_val(f"point{i}.{k}")[0] for k in ("CL", "CD", "CM"))
conf = prob.get_val(f"point{i}.analysis_confidence")[0]
print(f"{target:9.2f} {REYNOLDS[i]:9.3g} {alpha[i]:7.3f} {cl:7.4f} {cd:8.5f} "
f"{cm:8.4f} {cl / cd:6.1f} {conf:10.4f}")
thickness = prob.get_val("geometry.thickness")
print(f"\nobjective mean(w * CD) = {prob.get_val('objective.drag')[0]:.6f}")
print(f"t/c at x/c = 0.33: {thickness[0]:.4f} at x/c = 0.90: {thickness[1]:.4f}")
print(f"trailing-edge angle = {prob.get_val('geometry.te_angle')[0]:.3f} deg")
print(f"wiggliness = {prob.get_val('geometry.wiggliness')[0]:.5f} "
f"(limit {WIGGLINESS_MAX:.5f})")

np.set_printoptions(precision=6, floatmode="fixed", suppress=True, linewidth=100)
print("\nKulfan parameters:")
print(f" upper_weights = {prob.get_val('upper_weights')}")
print(f" lower_weights = {prob.get_val('lower_weights')}")
print(f" leading_edge_weight = {prob.get_val('leading_edge_weight')[0]:.6f}")


def state(prob):
"""The design and its operating points, for --json."""
alpha = prob.get_val("alpha")
points = []
for i, target in enumerate(CL_TARGETS):
values = {k: float(prob.get_val(f"point{i}.{k}")[0])
for k in ("CL", "CD", "CM", "analysis_confidence")}
points.append({"cl_target": float(target), "re": float(REYNOLDS[i]),
"alpha": float(alpha[i]), "cl": values["CL"], "cd": values["CD"],
"cm": values["CM"], "confidence": values["analysis_confidence"]})
return {
"kulfan": {
"upper": prob.get_val("upper_weights").tolist(),
"lower": prob.get_val("lower_weights").tolist(),
"leading_edge": float(prob.get_val("leading_edge_weight")[0]),
"te_thickness": float(prob.get_val("TE_thickness")[0]),
},
"objective": float(prob.get_val("objective.drag")[0]),
"spar_thickness": prob.get_val("geometry.thickness")[:len(SPAR_STATIONS)].tolist(),
"te_angle": float(prob.get_val("geometry.te_angle")[0]),
"points": points,
}


def schedule_polar(channel, model_size, kulfan):
"""Sweep alpha along the flight schedule, Re = 500k (CL / 1.25)^-0.5.

The Reynolds number depends on the lift it produces, so each angle is
solved by fixed-point iteration on Re, starting from the previous angle.
"""
prob = om.Problem(reports=False)
prob.model.add_subsystem(
"nf", pmom.RemoteExplicitComponent(channel=channel, model_size=model_size),
promotes=["*"])
prob.setup()
prob.set_val("upper_weights", kulfan["upper"])
prob.set_val("lower_weights", kulfan["lower"])
prob.set_val("leading_edge_weight", kulfan["leading_edge"])
prob.set_val("TE_thickness", kulfan["te_thickness"])
prob.set_val("n_crit", 9.0)
prob.set_val("xtr_upper", 1.0)
prob.set_val("xtr_lower", 1.0)

rows, reynolds = [], 500e3
for alpha in np.arange(-4.0, 18.0 + 1e-9, 0.25):
prob.set_val("alpha", alpha)
cl = None
for _ in range(20):
prob.set_val("Re", reynolds)
prob.run_model()
cl = float(prob.get_val("CL")[0])
if cl <= 0.2:
break
updated = 500e3 * (cl / 1.25) ** -0.5
if abs(updated - reynolds) < 1.0:
break
reynolds = updated
if cl <= 0.2:
reynolds = 500e3
continue
rows.append({"alpha": float(alpha), "re": float(reynolds), "cl": cl,
"cd": float(prob.get_val("CD")[0]), "cm": float(prob.get_val("CM")[0]),
"confidence": float(prob.get_val("analysis_confidence")[0])})
return rows


def ipopt_history(prob, objective_ref):
"""Objective, feasibility (inf_pr) and optimality (inf_du) per iteration, from IPOPT's
output file."""
path = Path(prob.get_outputs_dir()) / "IPOPT.out"
pattern = re.compile(r"^\s*(\d+)(r?)\s+(\S+)\s+(\S+)\s+(\S+)\s")
history = []
for line in path.read_text().splitlines():
match = pattern.match(line)
if match:
history.append({"iter": int(match[1]), "restoration": bool(match[2]),
"objective": float(match[3]) * objective_ref,
"feasibility": float(match[4]),
"optimality": float(match[5])})
return history


def write_json(path, channel, model_size, start, optimized, history):
data = {
"model": model_size,
"cl_targets": CL_TARGETS.tolist(),
"cl_weights": CL_WEIGHTS.tolist(),
"constraints": {
"cm_min": CM_MIN, "confidence_min": CONFIDENCE_MIN, "te_angle_min": TE_ANGLE_MIN,
"spar_stations": SPAR_STATIONS, "spar_thickness_min": SPAR_THICKNESS_MIN,
},
"start": start,
"optimized": optimized,
"history": history,
}
for key in ("start", "optimized"):
data[key]["schedule"] = schedule_polar(channel, model_size, data[key]["kulfan"])
Path(path).write_text(json.dumps(data, indent=1) + "\n")
print(f"Wrote {path}")


def write_dat(prob, path):
xy = selig_coordinates(
prob.get_val("upper_weights"), prob.get_val("lower_weights"),
prob.get_val("leading_edge_weight")[0], prob.get_val("TE_thickness")[0],
)
np.savetxt(path, xy, fmt="%.6f", header="Bora OpenMDAO optimized", comments="")
print(f"\nWrote {path}")


def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--server", help="address of a running bora_server "
"(default: start one on a free port)")
parser.add_argument("--model-size", default="large",
help="NeuralFoil network size (default: large, as in the reference)")
parser.add_argument("--output", default="optimized_daedalus.dat",
help="Selig-format file for the optimized airfoil")
parser.add_argument("--json", metavar="PATH",
help="also write the figure data of the docs page to PATH "
"(docs/src/data/optimization.json)")
args = parser.parse_args()

server = None
address = args.server
if address is None:
address, server = start_server()
channel = grpc.insecure_channel(address)
wait_for(channel, server)

# OpenMDAO writes its output directory (with IPOPT.out) under target/.
os.environ.setdefault("OPENMDAO_WORKDIR", str(REPO_ROOT / "target"))
(REPO_ROOT / "target").mkdir(exist_ok=True)
prob = build_problem(channel, args.model_size)
prob.run_model()
report(prob, "Starting point (NACA 0012):")
start = state(prob)

result = prob.run_driver()
report(prob, "Optimized:" if result.success else "IPOPT did not converge; last iterate:")
write_dat(prob, args.output)
if args.json:
history = ipopt_history(prob, OBJECTIVE_REF)
write_json(args.json, channel, args.model_size, start, state(prob), history)


if __name__ == "__main__":
main()

kulfan.py holds the Kulfan geometry and the KulfanGeometry component used in Step 4:

examples/openmdao/kulfan.py
"""Kulfan (CST) geometry for the OpenMDAO example.

The parameterization matches Bora's `generate_kulfan_coordinates` and
AeroSandbox's `KulfanAirfoil`: class function x^0.5 (1 - x), an order-7
Bernstein shape function per surface, a linear trailing-edge thickness term and
the leading-edge modification mode.
"""

from math import comb

import numpy as np
import openmdao.api as om

NUM_WEIGHTS = 8
DEG = 180.0 / np.pi


def bernstein_basis(x):
"""Order-7 Bernstein basis at stations x, shape (len(x), 8)."""
x = np.atleast_1d(np.asarray(x, dtype=float))
n = NUM_WEIGHTS - 1
return np.stack(
[comb(n, k) * x**k * (1.0 - x) ** (n - k) for k in range(NUM_WEIGHTS)], axis=-1
)


def class_function(x):
return np.sqrt(x) * (1.0 - x)


def leading_edge_mode(x):
return x * np.maximum(1.0 - x, 0.0) ** (NUM_WEIGHTS + 0.5)


def surface(x, weights, leading_edge_weight, te_thickness, te_sign):
"""y/c of one surface at stations x (te_sign is +1 upper, -1 lower)."""
x = np.atleast_1d(np.asarray(x, dtype=float))
return (
class_function(x) * (bernstein_basis(x) @ weights)
+ te_sign * x * te_thickness / 2.0
+ leading_edge_weight * leading_edge_mode(x)
)


def selig_coordinates(upper_weights, lower_weights, leading_edge_weight, te_thickness, n=101):
"""Selig-format coordinates (upper TE -> LE -> lower TE) with cosine spacing."""
x = 0.5 * (1.0 - np.cos(np.linspace(0.0, np.pi, n)))
yu = surface(x, upper_weights, leading_edge_weight, te_thickness, 1.0)
yl = surface(x, lower_weights, leading_edge_weight, te_thickness, -1.0)
upper = np.column_stack([x[::-1], yu[::-1]])
lower = np.column_stack([x[1:], yl[1:]])
return np.vstack([upper, lower])


def wiggliness(upper_weights, lower_weights):
"""Sum of squared second differences of both weight vectors."""
return np.sum(np.diff(upper_weights, 2) ** 2) + np.sum(np.diff(lower_weights, 2) ** 2)


class KulfanGeometry(om.ExplicitComponent):
"""Geometric quantities the optimization constrains.

Outputs
-------
thickness : t/c at the `stations` option. Upper minus lower surface, so the
leading-edge mode cancels and t/c is linear in the weights.
te_angle : trailing-edge wedge angle in degrees, defined as in AeroSandbox's
`KulfanAirfoil.TE_angle()`. At x = 1 the class function has slope -1 and
only the last Bernstein mode is nonzero, so each surface's slope there
is set by its last weight.
wiggliness : sum of squared second differences of the weights, a discrete
measure of the shape's curvature variation.
"""

def initialize(self):
self.options.declare("stations", types=(list, tuple, np.ndarray))

def setup(self):
x = np.asarray(self.options["stations"], dtype=float)
self._x = x
# t(x) = C(x) B(x) . (w_u - w_l) + x * TE_thickness
self._rows = class_function(x)[:, None] * bernstein_basis(x)

self.add_input("upper_weights", shape=NUM_WEIGHTS)
self.add_input("lower_weights", shape=NUM_WEIGHTS)
self.add_input("TE_thickness", val=0.0)
self.add_output("thickness", shape=len(x))
self.add_output("te_angle", val=0.0, units="deg")
self.add_output("wiggliness", val=0.0)

last = [NUM_WEIGHTS - 1]
self.declare_partials("thickness", "upper_weights", val=self._rows)
self.declare_partials("thickness", "lower_weights", val=-self._rows)
self.declare_partials("thickness", "TE_thickness", val=x)
self.declare_partials("te_angle", "upper_weights", rows=[0], cols=last)
self.declare_partials("te_angle", "lower_weights", rows=[0], cols=last)
self.declare_partials("te_angle", "TE_thickness")
self.declare_partials("wiggliness", ["upper_weights", "lower_weights"])

def compute(self, inputs, outputs):
wu, wl, te = inputs["upper_weights"], inputs["lower_weights"], inputs["TE_thickness"]
outputs["thickness"] = self._rows @ (wu - wl) + self._x * te
outputs["te_angle"] = DEG * (np.arctan(wu[-1]) - np.arctan(wl[-1]) + np.arctan(te))
outputs["wiggliness"] = wiggliness(wu, wl)

def compute_partials(self, inputs, partials):
wu, wl, te = inputs["upper_weights"], inputs["lower_weights"], inputs["TE_thickness"]
partials["te_angle", "upper_weights"] = DEG * (1.0 / (1.0 + wu[-1] ** 2))
partials["te_angle", "lower_weights"] = -DEG * (1.0 / (1.0 + wl[-1] ** 2))
partials["te_angle", "TE_thickness"] = DEG * (1.0 / (1.0 + te**2))
# d/dw sum((D w)^2) = 2 D^T D w, with D the second-difference operator.
d = np.diff(np.eye(NUM_WEIGHTS), 2, axis=0)
partials["wiggliness", "upper_weights"] = 2.0 * d.T @ (d @ wu)
partials["wiggliness", "lower_weights"] = 2.0 * d.T @ (d @ wl)