DAFoam shape optimisation tutorial: minimum drag with no loss of downforce on the Ahmed body

Published by Ruggero Poletto on

TL;DR

  • We wrote a DAFoam v5.0.0 script that minimises the drag coefficient CD of the Ahmed body (25° slant) while lift may not increase, and while the rear shape respects “regulation” rules: height limit, maximum width, ground clearance, packaging volume and minimum internal height.
  • 35 FFD design variables, adjoint gradients, IPOPT, 30 iterations: steady RANS CD drops from 0.294 to 0.119 (−59.6 %) and CL goes from +0.325 to −0.232: the body ends up making downforce instead of lift.
  • CD was within 1 % of its final value after 13 iterations; the rest of the run gives small refinements.
  • On cloudHPC the whole optimisation ran in 4 h 07 min on 96 vCPU hypercore (701,765 cells, peak RAM 316 GB).
  • The 59.6 % comes from a steady Spalart–Allmaras RANS model on a deformed mesh. Take it as the model’s answer, not a wind-tunnel number: re-mesh the final shape and check it with a scale-resolving simulation before building anything.

DAFoam adjoint optimisation of the Ahmed body: surface pressure coefficient through 30 iterations

Why this tutorial

A group of Formula Student students asked us a simple question: “How do we write the DAFoam script that gives us the lowest-drag body that still respects the rules?” The rules are geometric (maximum height, maximum width, ground clearance, parts that cannot move, room for the driver and the chassis) and aerodynamic (minimising drag alone would flatten the car and lose downforce).

DAFoam is a good fit because the whole optimisation (objective, design variables, geometric constraints, optimiser) lives in one Python file, runScript.py. Every rule becomes a few lines of code. We introduced the adjoint method and DAFoam on cloudHPC in DAFoam: Let the Adjoint Design Your Shape and Industrial Aerodynamic Optimization: Mastering DAFoam and Discrete Adjoints in the Cloud; this post is the hands-on follow-up and walks through that file block by block on the Ahmed body, the standard simplified car shape with public experimental data (Ahmed et al., 1984), so anyone can reproduce it before moving to their own car.

What this post covers:

  • how each “regulation” maps to a DAFoam / pyGeo feature;
  • the complete, working runScript.py (download at the end);
  • the results: shape change, drag and lift history, flow fields;
  • how to run it on cloudHPC, with run time and the settings that matter.

Results at a glance

Quantity Baseline Optimised (iteration 30) Change
Drag coefficient CD 0.294 0.119 −59.6 %
Lift coefficient CL (positive = lift) +0.325 −0.232 lift → downforce
Pressure part of CD 0.233 0.061 −74 %
Rest of CD (mostly skin friction) ≈ 0.06 ≈ 0.06 unchanged
Mean base pressure coefficient −0.16 +0.07 base suction removed
Rear packaging volume (constraint ≥ 1.0) 1.000 1.000 active
Minimum internal height (constraint ≥ 0.8) 1.000 0.996 not active

CD and CL use the half-model frontal area (0.0560 m²) and U∞ = 40 m/s. The baseline values come from the step-1 run (unchanged geometry); pressure split and base pressure are computed on iteration 0, whose shape differs from the baseline by about 1 mm (see “How IPOPT starts”).

The case: Ahmed body, 25° slant

Set-up of the DAFoam optimisation: Ahmed body, FFD box, domain and boundary conditions

Item Setting
Geometry Ahmed body, L 1.044 m, W 0.389 m, H 0.288 m, ground clearance 0.050 m, front radius 0.100 m, 25° slant over the last 0.222 m; stilts not modelled. Generated with CadQuery (genAhmedBody.py)
Model Half model, symmetry plane y = 0
Domain x −2.08…6.32 m, y 0…1.04 m, z 0…1.2 m
Flow U∞ = 40 m/s (as in the experiment), incompressible, steady
Solver DAFoam v5.0.0 DASimpleFoam on OpenFOAM v2506, Spalart–Allmaras, Spalding wall function (mean y+ ≈ 60)
Boundaries inlet fixed U and ν̃ = 4.5·10⁻⁵ m²/s; outlet p = 0; ground, top and side slip; body wall
Mesh snappyHexMesh, 701,765 cells, body cells 5 mm (level 4), 3 prism layers, 2 refinement boxes
Body patches bodyFront (fixed) and bodyRear (x > 0.70 m, the design surface)

The ground is a slip wall to keep the tutorial simple: the experiment had a fixed floor with its own boundary layer, and a Formula Student car runs on a road that moves relative to the car. For your own car, use a moving-ground velocity condition. The baseline CD of 0.294 is 3 % above the value of about 0.285 usually quoted for the 25° Ahmed body (Ahmed et al., 1984). That agreement is partly lucky: steady RANS models are known to struggle with the 25° slant, where the flow on the slant is on the edge between attached and separated.

How the regulations become code

Rule DAFoam / pyGeo feature In this tutorial
Parts that cannot change Keep them out of the FFD box, or freeze FFD points bodyFront is outside the box; FFD columns i = 0, 1 are frozen to blend smoothly
Maximum height Upper bound on vertical FFD moves roof may drop 0.10 m, may rise only up to z = 0.338 m
Maximum width Bound on spanwise moves sides may move inwards up to 0.08 m, never outwards
Ground clearance Lower bound on the underbody points floor may rise up to 0.08 m (diffuser), never drop
Packaging (chassis, driver) addVolumeConstraint, addThicknessConstraints1D rear volume ≥ baseline; internal height ≥ 80 % at 6 stations
Left/right symmetry Half model + paired FFD moves each design variable moves the two mirrored points together
Keep downforce Constraint on a force function CL ≤ CL_baseline

FFD (free-form deformation) moves the surface as a smooth function of the control points, and each surface point moves by a weighted average of the control-point moves. So bounding every control point also bounds every surface point: the envelope rules become simple design-variable bounds.

The script, block by block

The full runScript.py is in the download. Here are the parts you will change for your own car.

1. Flow conditions and reference values

U0 = 40.0                       # m/s
nuTilda0 = 4.5e-5               # m2/s, freestream Spalart-Allmaras variable
A0 = 0.389 * 0.288 / 2.0        # m2, frontal area of the HALF model
qA = 0.5 * U0**2 * A0           # incompressible solver: forces per unit density

The incompressible solver returns kinematic pressure (p/ρ), so the force is per unit density and the coefficient is just force / (½ U² A). For a half model use half the frontal area.

2. Objective and constraint functions

"function": {
    "CD": {"type": "force", "source": "patchToFace",
           "patches": ["bodyFront", "bodyRear"],
           "directionMode": "fixedDirection", "direction": [1.0, 0.0, 0.0],
           "scale": 1.0 / qA},
    "CL": {"type": "force", "source": "patchToFace",
           "patches": ["bodyFront", "bodyRear"],
           "directionMode": "fixedDirection", "direction": [0.0, 0.0, 1.0],  # + = lift
           "scale": 1.0 / qA},
},

Every quantity the optimiser may use goes in function. Integrate the forces over all body patches, not only the one that is deformed. On a real car add the wings, floor and wheels to patches.

3. Design surface and mesh deformation

"designSurfaces": ["bodyRear"],   # all its points must be inside the FFD box

meshOptions = {
    "gridFile": os.getcwd(), "fileType": "OpenFOAM",
    "symmetryPlanes": [
        [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],   # symmetry plane y = 0
        [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]],   # ground z = 0
        [[0.0, 0.0, 1.2], [0.0, 0.0, 1.0]],   # top z = 1.2
        [[0.0, 1.04, 0.0], [0.0, 1.0, 0.0]],  # side y = 1.04
    ],
}

Two rules that save hours:

  • Every point of a design surface must be inside the FFD box. That is why the body is split into two STL regions in genAhmedBody.py, and only bodyRear (x > 0.70 m) is a design surface.
  • IDWarp moves the volume mesh with the surface. Declaring the flat domain boundaries as symmetryPlanes keeps their points sliding in the plane, so the ground stays at z = 0 and the far-field walls stay where they are.

4. FFD box and design variables

The FFD box (FFD/genFFD.py) has 7 × 2 × 4 control points: 7 along the flow (x 0.70–1.07 m), 2 across the full width (the mirror pair), 4 in height. Each design variable moves a mirrored pair of points together, so the body stays symmetric by construction:

roof  = [{pts[i,0,k]: ez, pts[i,1,k]: ez} for i in free_i for k in (nK-2, nK-1)]
floor = [{pts[i,0,0]: ez, pts[i,1,0]: ez} for i in free_i]
side  = [{pts[i,1,k]: ey, pts[i,0,k]: -ey} for i in free_i for k in range(nK)]

self.add_design_var("roof",  lower=-0.10, upper=np.array(roof_up), scaler=10.0)
self.add_design_var("floor", lower=0.0,   upper=0.08,              scaler=10.0)
self.add_design_var("side",  lower=-0.08, upper=0.0,               scaler=10.0)

That gives 10 roof, 5 floor and 20 side variables: 35 in total. roof_up is the room between the baseline top surface and the height limit at each FFD column, so the roof can fill the slant but never rise above the roof line.

5. Geometric constraints (packaging)

# volume of the rear part >= baseline (grid at mid height, projected up and down)
self.geometry.nom_addVolumeConstraint("volcon", leList, teList, nSpan=8, nChord=16)
# vertical internal height at 6 stations >= 80 % of baseline
self.geometry.nom_addThicknessConstraints1D("heightcon", ptList, nCon=6, axis=[0, 0, 1])

self.add_constraint("geometry.volcon",   lower=1.0)
self.add_constraint("geometry.heightcon", lower=0.8)

The volume constraint stops the optimiser from simply shrinking the rear. The thickness constraint guarantees a minimum internal height where the chassis or the driver must fit. For a real car the next step is addTriangulatedSurfaceConstraint, which keeps the body outside a “keep-in” STL of the chassis and driver.

6. Objective and aerodynamic constraint

self.add_objective("scenario1.aero_post.CD", scaler=1.0)
self.add_constraint("scenario1.aero_post.CL", upper=CL_BASELINE, scaler=1.0)

Lift is positive upwards, so “no loss of downforce” means CL may not increase.

7. Two-step workflow

CL_BASELINE = None      # step 1: baseline flow + one adjoint check, prints CD and CL
CL_BASELINE = 0.32545   # step 2: paste the printed CL and launch again

Step 1 is cheap (37 min on 32 vCPU in our case) and catches mesh, boundary-condition and adjoint problems before the long run.

8. Optimiser

prob.driver.options["optimizer"] = "IPOPT"
prob.driver.opt_settings = {"tol": 1.0e-5, "constr_viol_tol": 1.0e-5, "max_iter": 30,
                            "mu_strategy": "adaptive", "limited_memory_max_history": 10,
                            "nlp_scaling_method": "none", "alpha_for_y": "full", "recalc_y": "yes"}

9. Adjoint and mesh-quality settings for snappyHexMesh grids

"adjEqnOption": {"gmresRelTol": 1.0e-6, "pcFillLevel": 2, "jacMatReOrdering": "rcm",
                 "gmresMaxIters": 2000, "gmresRestart": 2000},
"checkMeshThreshold": {"maxAspectRatio": 2000.0, "maxNonOrth": 75.0, "maxSkewness": 8.0},

snappyHexMesh grids are less regular than the block-structured meshes in most DAFoam tutorials. A fill level 2 ILU preconditioner and a high GMRES iteration limit keep the adjoint solves converging when the mesh is strongly deformed (see the run-time section). The relaxed mesh-quality thresholds match a snappy mesh; the worst values during the run stayed at non-orthogonality 63° and skewness 2.6.

Results

Drag and lift history

Optimisation history of CD and CL over 30 IPOPT iterations

IPOPT iteration CD CL
0 0.290 +0.314
3 0.156 −0.095
5 0.139 −0.180
10 0.125 −0.222
13 0.120 −0.237
20 0.119 −0.229
30 0.119 −0.232

Most of the gain comes in the first 3 iterations. After iteration 13 CD changes by less than 1 %. IPOPT stopped at the 30-iteration limit, not at its convergence tolerance (dual infeasibility 4.5·10⁻⁴ against 10⁻⁵): more iterations would bring little, but strictly speaking this is not a fully converged optimum.

The lift constraint ended inactive: the drag-optimal shape already makes downforce (CL −0.232 against a limit of +0.325). On this body, removing drag and adding downforce point the same way. On a Formula Student car with wings and a floor that will not always be true, so keep the constraint in the script.

How the shape changed

Side profile and plan view: start vs optimised shape

Surface pressure coefficient, start vs optimised

Change at the rear end (x = 1.044 m) Baseline Optimised
Top of the base z = 0.234 m z = 0.269 m (+35 mm, slant partly filled)
Bottom of the base z = 0.050 m z = 0.070 m (+20 mm, diffuser)
Half-width of the base 0.195 m 0.150 m (−45 mm per side, boat tail)
Base area (half model) 0.0356 m² 0.0264 m² (−26 %)

The optimiser found the classic recipe: boat-tail the sides, add an underbody diffuser, and replace the sharp 25° slant with a rounded, shallower one that ends higher. The volume constraint is active: the rear keeps exactly its baseline volume, so the taper is paid for by filling the slant.

The bounds tell you which rules limit the design: 7 of the 10 roof variables sit on the height limit, 4 of the 20 side variables on the maximum taper (−80 mm) and 11 on the maximum-width bound (no outward move), 3 of the 5 floor variables on the ground-clearance bound, and the packaging volume constraint is active. On a real car this is the useful output for the students: those are the rules that cost drag.

Flow on the symmetry plane

Velocity magnitude on the symmetry plane, start vs optimised

On the baseline the flow follows the 25° slant, and the low pressure on the slant and around the rear is where the lift comes from: the pressure on the rear part alone gives CL ≈ +0.40, partly offset by the front. On the optimised body the flow leaves a rounded, shallower slant and a smaller base; the tapered sides and the diffuser make the wake close more gently, and the mean base pressure rises from Cp −0.16 to +0.07. The pressure part of drag falls by 74 %; the friction part does not change. The rear changes alter the pressure on the whole body: in pressure terms the fixed front part goes from CL −0.09 to −0.21 and the rear part from +0.40 to −0.02, so most of the final downforce acts on the part that did not move.

What we learned

  • One script, seven rules: every geometric rule in this tutorial is a bound or a pyGeo constraint, written in fewer than 30 lines.
  • Split the body: the fixed part and the design part must be separate patches, and the design patch must sit entirely inside the FFD box.
  • Look at the active bounds after the run. They show which rule costs drag.
  • The drag reduction is large because the 25° Ahmed body is a high-drag shape with a lot of room for boat tailing. Do not expect 60 % on a car that is already shaped for low drag.

How much to trust the 59.6 %

This is a steady RANS (Spalart–Allmaras) result on a mesh deformed by the optimiser, and that matters:

  • RANS models are known to mispredict the 25° Ahmed flow; the baseline match (+3 % on CD) does not mean the optimised wake is predicted with the same accuracy. Detailed wake measurements for the baseline exist (Lienhart and Becker, 2003) and are the natural next check.
  • The final shape was evaluated on the deformed mesh (non-orthogonality 63°, skewness 2.5), not on a fresh mesh of the new geometry.
  • The ground is a slip wall and the stilts are missing.

Before using such a shape on a car, export it, re-mesh it with snappyHexMesh, run a mesh-independence check, and confirm the gain with a scale-resolving model (DES/LES) or a wind-tunnel test. The adjoint optimisation tells you which way to go and which rules limit you; it does not replace the validation.

How IPOPT starts

Iteration 0 is not exactly the baseline. IPOPT is an interior-point method: it moves the starting design slightly inside the bounds (about 1 mm here) before the first evaluation. That small move changed CD from 0.294 to 0.290 and CL from 0.325 to 0.314, which shows how sensitive the 25° slant flow is. The table above uses the step-1 baseline; the figures show iteration 0.

Run time and cost on cloudHPC

Run Instance Billed time Cost
Step 1: baseline + one adjoint (check, ILU fill level 1) 32 vCPU hypercore, spot 37 min €2.18
Step 2: optimisation, 30 IPOPT iterations 96 vCPU hypercore, regular 4 h 07 min €87.12
Total €89.30
Step 2 breakdown (96 MPI processes) Value
Solver wall time 14,003 s (3.9 h)
Flow solutions (primal) 41, each 3,000 SIMPLE iterations, median 54 s
Adjoint solves 62 (CD and CL for each of 31 gradients), median 82 s and 208 GMRES iterations
Slow adjoint solves 4 solves (2 iterations) needed about 1,900 GMRES iterations, 19 min each
Jacobian colouring (once) 391 s
Peak RAM (whole machine) 316 GB of 363 GB (≈ 450 kB per cell)

Memory, not CPU, decides the machine: with the adjoint and a fill-level-2 preconditioner the run peaked at about 450 kB per cell. A 1.5 M-cell car would need around 680 GB, more than this machine has: plan a larger instance (more vCPU and subdomains) or a coarser mesh for the optimisation loop.

The optimisation ran on a regular instance on purpose: an IPOPT run keeps its state in memory and cannot be resumed after a preemption, and it was expected to last more than 3 hours. The short step-1 check is fine on spot.

How to run it on cloudHPC

  1. Upload the case folder (0.orig/, constant/, system/, FFD/, preProcessing.sh, runScript.py). It must already contain the body STL (constant/triSurface/body.stl, written by genAhmedBody.py, which needs CadQuery) and the FFD file (FFD/rearFFD.xyz, written by FFD/genFFD.py). Both are included in the download.
  2. Choose DAFoam-v5.0.0, hypercore (or highcore). cloudHPC runs preProcessing.sh, then runScript.py with one MPI process per physical core.
  3. DAFoam does not change numberOfSubdomains for you. Our preProcessing.sh sets it to $(nproc) so the same folder works on any machine size.
  4. Step 1 with CL_BASELINE = None (32 vCPU, spot), read BASELINE CD … CL … in the log, paste the CL, then launch step 2 (96 vCPU, regular instance for runs over 3 h).
  5. Keep either runScript.py or an Allrun in the folder: if both exist, cloudHPC runs both.
  6. Results: the deformed mesh and fields of every iteration are in the processor*/0.000N folders (N = gradient evaluation), the final flow in processor*/3000. Read them with ParaView or PyVista as a decomposed case.

FAQ

Can DAFoam handle geometric constraints such as Formula Student rules?
Yes. Envelope limits (height, width, ground clearance) become bounds on the FFD design variables; packaging needs become volume, thickness or triangulated-surface constraints in pyGeo; frozen parts stay outside the FFD box.

Why not minimise drag alone?
On a racing car, minimising drag alone can remove downforce. Adding CL ≤ CL_baseline costs one line. On the Ahmed body the constraint ended inactive, but on a car with wings it usually is not.

How many design variables can I use?
The adjoint cost does not grow with the number of design variables: one adjoint solve per function (here CD and CL) gives the gradient with respect to all of them. We used 35; hundreds are fine.

How long does a DAFoam optimisation take?
Here, 30 iterations on a 0.7 M-cell half model took 3.9 h of solver time on 96 cores. Each iteration is one flow solution plus one adjoint per function. CD was within 1 % of its final value after 13 iterations.

Is a steady RANS optimum reliable for a car?
It gives the right direction and shows which rules are limiting. The magnitude needs checking on a fresh mesh and with a scale-resolving model or a wind tunnel, especially for bluff rear ends like the 25° Ahmed body.

Download

Download the case files (ZIP)

The ZIP contains the full case (runScript.py, preProcessing.sh, genAhmedBody.py, FFD/genFFD.py, 0.orig, constant, system) and the post-processing scripts used for every number and figure in this post.

References

  1. Ahmed, S. R., Ramm, G., Faltin, G. (1984). Some Salient Features of the Time-Averaged Ground Vehicle Wake. SAE Technical Paper 840300. https://doi.org/10.4271/840300
  2. Lienhart, H., Becker, S. (2003). Flow and Turbulence Structure in the Wake of a Simplified Car Model. SAE Technical Paper 2003-01-0656. https://doi.org/10.4271/2003-01-0656
  3. He, P., Mader, C. A., Martins, J. R. R. A., Maki, K. J. (2020). DAFoam: An Open-Source Adjoint Framework for Multidisciplinary Design Optimization with OpenFOAM. AIAA Journal 58(3), 1304–1319. https://doi.org/10.2514/1.J058853
  4. DAFoam documentation and tutorials. https://dafoam.github.io
  5. Kenway, G. K. W., Kennedy, G. J., Martins, J. R. R. A. (2010). A CAD-Free Approach to High-Fidelity Aerostructural Optimization. AIAA 2010-9231. https://doi.org/10.2514/6.2010-9231 (FFD parametrisation used by pyGeo)
  6. Wächter, A., Biegler, L. T. (2006). On the implementation of an interior-point filter line-search algorithm for large-scale nonlinear programming. Mathematical Programming 106, 25–57. https://doi.org/10.1007/s10107-004-0559-y (IPOPT)
  7. Gray, J. S., Hwang, J. T., Martins, J. R. R. A., Moore, K. T., Naylor, B. A. (2019). OpenMDAO: An open-source framework for multidisciplinary design, analysis, and optimization. Structural and Multidisciplinary Optimization 59, 1075–1104. https://doi.org/10.1007/s00158-019-02211-z
  8. Spalart, P. R., Allmaras, S. R. (1992). A One-Equation Turbulence Model for Aerodynamic Flows. AIAA Paper 92-0439. https://doi.org/10.2514/6.1992-439
  9. Formula Student Germany, rules. https://www.formulastudent.de/fsg/rules/

CloudHPC is a HPC provider to run engineering simulations on the cloud. CloudHPC provides from 1 to 224 vCPUs for each process in several configuration of HPC infrastructure - both multi-thread and multi-core. Current software ranges includes several CAE, CFD, FEA, FEM software among which OpenFOAM, FDS, Blender and several others.

New users benefit of a FREE trial of 300 vCPU/Hours to be used on the platform in order to test the platform, all each features and verify if it is suitable for their needs