External Optimization using Python
In addition to the optimization algorithms included in CAESES, it is possible to connect CAESES to an External Optimizer β useful if you want to use an algorithm that is not available in CAESES, or if you already have an existing optimization workflow you would like to integrate. This tutorial demonstrates this by connecting CAESES to a Python-based external optimizer using NSGA-III (pymoo).
The finalized CAESES project can be downloaded at the end of the tutorial.
Want to jump straight to the external optimization setup and follow along with your own example geometry? Then click below:
Jump to Setup of External OptimizationOverview of the Optimization Problemβ
In this tutorial, a multi-objective optimization problem involving the design of a pressure vessel is solved. A pressure vessel is a closed container designed to hold gases or liquids at a pressure significantly different from the ambient pressure.
The optimization problem considered in this tutorial has the following objectives:
- Minimize the total manufacturing cost.
- Minimize the welding effort.
- Maximize the structural strength.
The optimization is subject to the following constraints:
- The shell and head thicknesses must satisfy the minimum design requirements.
- The vessel must provide at least the required internal volume.
Since this is a three-objective optimization problem, the NSGA-III algorithm is a suitable choice, which is specifically designed for many-objective optimization problems.
Python with Pymooβ
To implement NSGA-III, this tutorial uses the Python optimization framework pymoo, which provides a comprehensive collection of state-of-the-art optimization algorithms.
For this example case, Python was chosen, since it is one of the most widely used programming languages, has an extensive scientific computing ecosystem, and can be easily extended or customized. With the assistance of modern Large Language Models (LLMs), developing custom optimization workflows in Python has become even more accessible.
The pressure vessel optimization problem presented in this tutorial is based on the equations described in the following reference: Cost minimization of pressure vessel design problem using PSO, SA, PS, GODLIKE, CUCKOO, FF, FP, ALO, GSA and MVO
Python Requirementsβ
To follow this tutorial, Python must be installed on your computer. If Python is not already installed, download the latest version from the official Python website: https://www.python.org/downloads/
This tutorial also requires the pymoo optimization framework and the NumPy numerical computing library. Both packages can be installed from the Python Package Index (PyPI) using:
pip install pymoo numpy
The Python script imports all required libraries for running the NSGA-III optimization and communicating with CAESES:
# --- NSGA-III + CAESES ---
import os, json, time, numpy as np
from pymoo.core.problem import ElementwiseProblem
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.optimize import minimize
from pymoo.util.ref_dirs import get_reference_directions
Here, os, json, and time are part of the Python standard library, while numpy and pymoo are external packages required by the optimization script.
Parameters of the Pressure Vesselβ
A parametric model of the pressure vessel is developed for the optimization problem. The model consists of a cylindrical shell and two hemispherical heads, as illustrated in the figure below.

The design variables considered in this model are:
- Shell length (L)
- Inner radius (R)
- Shell thickness (Ts)
- Head thickness (Th)
- Material type used for manufacturing the pressure vessel and its corresponding welding filler (type)
The design variables R and L are continuous variables. In contrast, the shell thickness (Ts) and head thickness (Th) are discrete variables and can only take values that are integer multiples of 0.0625 in.
The material type is also treated as a discrete design variable. Each material corresponds to a predefined set of mechanical and economic properties, as listed below.
Inputsβ
The objective of this case study is to design a compressed-air storage tank with an operating pressure of 1000 psi and a minimum required internal volume of 750 ftΒ³.
Main Dimensionsβ
The main dimensions of the pressure vessel are defined by the following design variables:
| Design Variable | Default Value | Lower Bound | Upper Bound |
|---|---|---|---|
L | 160 in | 140 in | 200 in |
Radius | 50 in | 25 in | 75 in |
Material Typeβ
The material type is a discrete design variable that determines the construction material and its associated welding filler, density, allowable stress, and material costs.
Define the material type with a default value of 1, ranging from a lower bound of 0 to an upper bound of 2.
The available material types and their properties are listed below.
| Type | Construction Material | Welding Filler | Density (lb/inΒ³) | Allowable Stress (psi) | Construction Cost ($/lb) | Welding Cost ($/lb) |
|---|---|---|---|---|---|---|
| 0 | Carbon Steel | ER70S-6 / E7018 | 0.2840 | 20,000 | 0.70 | 2.50 |
| 1 | Stainless Steel 304 | ER308L | 0.2890 | 25,000 | 2.30 | 8.00 |
| 2 | Aluminum 6061 | ER4043 | 0.0975 | 14,000 | 3.00 | 12.00 |
The material type can only take the discrete values 0, 1, or 2, with each value corresponding to one of the predefined material configurations listed above.
Thicknessβ
The shell and head thicknesses are discrete design variables with increments of 0.0625 in.
The allowable thickness ranges are:
The minimum required head thickness is calculated as:
The minimum required shell thickness is calculated as:
where is the internal pressure, is the inner radius, and is the allowable stress of the selected material.
The required shell and head thicknesses are calculated using the thin-walled pressure vessel equations, ensuring that the membrane stresses do not exceed the allowable stress of the selected material.
Geometry of the Vesselβ
Once the model parameters have been defined, they are used to generate the geometry of the pressure vessel.
Geometry Curvesβ
The geometry is constructed from a set of parametric curves organized into the following sub-scopes:
innerβ contains the curves defining the inner geometry of the pressure vessel.outerβ contains the curves defining the outer geometry of the pressure vessel.
Scope Structure and Curvesβ
The scope structure under 01_geometry|curves and the resulting curves should appear as shown in the figure below.

Surfacesβ
Once the curves have been created, they are used to generate the surfaces of the pressure vessel.
Within the surfaces sub-scope, create the following two sub-scopes:
innerβ contains the surfaces representing the inner geometry of the pressure vessel.outerβ contains the surfaces representing the outer geometry of the pressure vessel.
The inner surface of the pressure vessel is created using a Revolution Surface. The inner contour curve is revolved about the X-axis, which is specified as the Principal Axis.
The resulting inner surface is shown below.

BRepβ
Once all outer surfaces have been created, combine them into a BRep named vessel. The resulting solid model of the pressure vessel is shown below.

Evaluationsβ
Once the parametric model of the pressure vessel has been completed, the objective functions and constraints of the optimization problem can be defined and evaluated.
Cost of the Pressure Vesselβ
In this tutorial, the total manufacturing cost is divided into two components:
- Construction cost
- Welding cost
Construction Costβ
The construction cost is determined by the amount of material required to manufacture the pressure vessel.
The material volume of the two hemispherical heads is calculated as:
The material volume of the cylindrical shell is calculated as:
The total construction cost of the pressure vessel is calculated as:
where:
- is the inner radius of the pressure vessel.
- is the length of the cylindrical shell.
- is the head thickness.
- is the shell thickness.
- is the density of the selected material.
- is the construction cost per unit mass.
Welding Costβ
The welding cost is determined by the amount of weld material required to manufacture the pressure vessel. In this problem, the cylindrical shell is fabricated from rolled plates using a 60Β° V-groove butt joint. Additional welds are required to join the two hemispherical heads to the cylindrical shell.
The weld material volume required to join the two hemispherical heads to the cylindrical shell is calculated as:
The weld material volume required for the longitudinal seam of the cylindrical shell is calculated as:
The total welding cost of the pressure vessel is calculated as:
where is the welding cost per unit mass.
Objective Functionsβ
The optimization problem includes three objective functions:
- Minimize the total manufacturing cost.
- Minimize the total volume of weld material.
- Maximize the structural strength.
The total manufacturing cost is calculated as the sum of the construction and welding costs:
The total volume of weld material is calculated as:
The safety factor of the pressure vessel is defined as:
where and are the minimum required shell and head thicknesses, respectively.
A higher value of indicates that the selected shell and head thicknesses exceed their minimum required values by a larger margin. Therefore, maximizing increases the structural strength of the pressure vessel.
Constraints of the Optimization Problemβ
The optimization problem includes four constraints related to the internal volume and the required plate thicknesses.
The internal volume of the pressure vessel must be greater than or equal to the minimum required volume:
The shell thickness must be greater than or equal to the head thickness:
The selected head thickness must be greater than or equal to the minimum required head thickness:
The selected shell thickness must be greater than or equal to the minimum required shell thickness:
A design is considered feasible only when all four constraints are satisfied.
The figure below shows how to create a constraint in CAESES and illustrates the four constraints required for this optimization problem.

For the external optimization workflow, all constraints are formulated relative to zero. Whether a constraint is satisfied depends on the comparison operator.
In this tutorial, all constraints use the greater than or equal to (>=) operator. Therefore, a constraint value greater than or equal to zero indicates that the constraint is satisfied, while a negative value indicates a constraint violation.
This zero-based formulation is required by the external optimizer used in this tutorial. Other optimization algorithms available in CAESES can also handle constraint expressions with values on the right-hand side of the comparison operator.
External Optimizationβ
The External Optimization engine provides an interface that allows an external optimization program to control the design generation process in CAESES. This makes it possible to couple virtually any optimization algorithm with CAESES.
Communication between CAESES and the external optimizer is based on the JSON protocol and can be performed using either:
- JSON files (file-based communication).
- A WebSocket connection through the API endpoint
/experimental/jsonengine.
When the External Optimization engine is started in CAESES, the specified external executable is launched as a separate process. The executable uses the current Design Engine run directory as its working directory.
When using the WebSocket API, an authentication token must be configured.
To do this, open Settings β External API in CAESES and enter a token in the Token field.

Creating the External Optimization Design Engineβ
The figure below shows how to create an External Optimization Design Engine in CAESES.
The design variables, objective functions, and constraints are configured in the same way as for any other Design Engine in CAESES. The main difference is that, instead of selecting one of the built-in optimization algorithms, an external executable is specified.

In this tutorial, the external optimizer is implemented in Python. Therefore, the Executable field is set to the Python interpreter (python.exe on Windows or python on Linux/macOS), while the Arguments field specifies the path to the optimization script, NSGA_III.py.
The Python script used in this tutorial can be downloaded here:
Download Python ScriptThis Python script handles the JSON-based communication between CAESES and the external optimizer. In this tutorial, the external optimizer is implemented in Python, but the same communication interface can be used with any programming language that supports reading and writing JSON files or communicating through the API.
Communication Workflowβ
The communication between CAESES and the external optimizer consists of five main stages:
- Design Engine Setup
- Design Request
- Design Evaluation
- Results
- Finishing the Optimization
Design Engine Setupβ
After the Design Engine starts, CAESES provides the optimization setup to the external optimizer, automatically. The setup is available either as:
setup.jsonin the Design Engine run directory, or- the
/setupAPI endpoint.
An example setup.json file is shown below:
{
"designVariables": [
{
"lower_bound": 0.0,
"upper_bound": 2.0
},
{
"lower_bound": 20.0,
"upper_bound": 99.0
},
{
"lower_bound": 20.0,
"upper_bound": 99.0
},
{
"lower_bound": 25.0,
"upper_bound": 75.0
},
{
"lower_bound": 160.0,
"upper_bound": 240.0
}
],
"nInequalityConstraints": 3,
"nObjectives": 3
}
Design Requestβ
The external optimizer generates one or more candidate designs and sends them to CAESES using the RunRequest schema.
Depending on the communication method, the request is sent through:
in.json, or- the
/requestAPI endpoint.
An example in.json file is shown below:
{
"designs": [
{
"dv": [
1.0,
27.0,
71.0,
62.011600294079706,
221.48909109187045
]
}
]
}
For file-based communication, create an additional file named in.ready after writing in.json. This file notifies CAESES that the request is complete and ready for processing.
Design Evaluationβ
CAESES creates the requested designs and evaluates all objective functions and constraints defined in the project.
Resultsβ
After all requested designs have been evaluated, CAESES returns the results using the RunResult schema.
The results are available through:
out.json, or- the
/resultAPI endpoint.
An example out.json file is shown below:
{
"designs": [
{
"constraints": [
1.9570359882368118,
0.4472679941184059,
5813047.260927142
],
"dbid": 57001,
"ieq": [],
"name": "externalOpti_02_des0001",
"objectives": [
1085084.8526991631,
16802.35688276421,
-1.7889797952947086
]
}
]
}
For file-based communication, CAESES creates an out.ready file after out.json has been written. Before submitting the next request, this file must be removed by the external optimizer.
When using the API, if the results are not yet available, the /result endpoint returns an HTTP 500 status code.
Finishing the Optimizationβ
When the optimization is complete, notify CAESES by either:
- creating a file named
finishedin the Design Engine run directory, or - calling the
/finishedAPI endpoint.
If the Design Engine run is aborted from within CAESES, an abort file is created in the run directory. When using the API, the corresponding endpoints return an HTTP 404 status code.
Python Implementation Detailsβ
The script implements the JSON-based communication protocol described above and configures the NSGA-III algorithm from pymoo. The downloaded script already contains this logic β expand the section below only if you want a full walkthrough of how it works.
Full Python implementation walkthrough
The setup provided by CAESES is loaded and parsed into the design variable bounds and problem dimensions:
# ========= Load setup =========
with open("setup.json") as f:
setup = json.load(f)
specs = setup["designVariables"]
n_var = len(specs)
n_obj = int(setup.get("nObjectives", 1))
n_constr = int(setup.get("nConstraints", setup.get("nIenqualityConstraints", 0)))
xl = np.array([d["lower_bound"] for d in specs], float)
xu = np.array([d["upper_bound"] for d in specs], float)
Population Size
In NSGA-III, the population size is based on the number of reference directions generated using the Das-Dennis method.
The number of reference directions is calculated as:
where:
- is the number of partitions (
n_partitions). - is the number of objectives.
- is the number of reference directions, which is used as the population size in this tutorial.
In the Python script, the reference directions and the NSGA-III algorithm are configured as follows:
# ========= Run NSGA-III =========
problem = CAESESProblem()
ref_dirs = get_reference_directions(
"das-dennis",
n_dim=n_obj,
n_partitions=4
)
algorithm = NSGA3(
pop_size=len(ref_dirs),
ref_dirs=ref_dirs
)
res = minimize(
problem,
algorithm,
seed=1,
termination=("n_gen", 10),
save_history=True,
verbose=True
)
The population size is explicitly set to the number of generated reference directions (pop_size=len(ref_dirs)).
For this optimization problem, there are three objectives () and n_partitions = 4. Therefore:
Thus, the population contains 15 designs per generation.
With n_gen = 10, the total number of design evaluations is:
Therefore, 150 designs are evaluated during the optimization.
CAESES Problem Definition in Python
The following class defines the optimization problem used by pymoo and manages the communication between the external optimizer and CAESES for each design evaluation.
The class inherits from ElementwiseProblem, which allows pymoo to evaluate one candidate design at a time. For each evaluation, the design variables are sent to CAESES, the corresponding design is generated and evaluated, and the resulting objective and constraint values are returned to the optimizer.
# ========= Problem =========
class CAESESProblem(ElementwiseProblem):
def __init__(self):
super().__init__(
n_var=n_var,
n_obj=n_obj,
n_constr=n_constr,
xl=xl,
xu=xu
)
self._feval = -1
Problem Definition
The constructor initializes the optimization problem using:
super().__init__(
n_var=n_var,
n_obj=n_obj,
n_constr=n_constr,
xl=xl,
xu=xu
)
The parameters define the main characteristics of the optimization problem:
n_varβ number of design variables.n_objβ number of objective functions.n_constrβ number of constraints.xlβ lower bounds of the design variables.xuβ upper bounds of the design variables.
An evaluation counter is also initialized:
self._feval = -1
This counter is used to assign a sequential ID to each design evaluation.
Preparing the Design Variables
For each candidate design generated by NSGA-III, pymoo automatically calls the _evaluate() function:
def _evaluate(self, x, out, *args, **kwargs):
Here, x contains the current design variables, while out is used to return the calculated objective and constraint values to pymoo.
The design vector is first converted to a NumPy array:
x_eval = np.array(x, dtype=float)
The first three design variables are discrete and must therefore take integer values:
x_eval[:3] = np.round(x_eval[:3])
In this tutorial, these variables represent the material type and the discrete indices used to define the head and shell thicknesses.
Sending the Design Variables to CAESES
The design vector is written to in.json:
with open("in.json", "w") as f:
json.dump(
{"designs": [{"dv": x_eval.tolist()}]},
f,
indent=2
)
This creates a design request in the JSON format expected by CAESES. The file has the following general structure:
{
"designs": [
{
"dv": [...]
}
]
}
After in.json has been written, the script creates the in.ready file:
with open("in.ready", "w") as f:
f.write("1")
The presence of in.ready signals to CAESES that the design request has been completely written and is ready to be processed.
Waiting for CAESES
After sending the design variables, the external optimizer waits for CAESES to complete the design evaluation:
while not os.path.exists("out.ready"):
time.sleep(0.05)
CAESES creates out.ready when the requested design has been evaluated and the results are available.
The script checks for the presence of this file every 0.05 seconds before continuing.
Reading the Evaluation Results
Once out.ready is available, the results are read from out.json:
with open("out.json") as f:
resj = json.load(f)
design = resj["designs"][0]
The objective function values are then extracted:
F = np.array(design["objectives"], float)
and passed to pymoo:
out["F"] = F[:n_obj]
The array out["F"] contains the objective function values that NSGA-III uses to evaluate and compare the candidate designs.
Handling the Constraints
If the optimization problem contains constraints, their values are extracted from the CAESES results:
if n_constr > 0:
G = -np.array(design["constraints"], float)
out["G"] = G
else:
out["G"] = np.zeros(0)
In this tutorial, the constraints in CAESES are formulated using the >= comparison operator. Therefore, a constraint is satisfied when:
pymoo, however, expects inequality constraints to be formulated as:
Therefore, the constraint values returned by CAESES are multiplied by β1 before being passed to pymoo:
This converts the constraint convention used in CAESES to the convention expected by pymoo.
Tracking the Evaluations
After each design has been evaluated, the evaluation counter is increased:
self._feval += 1
The corresponding evaluation ID is then stored with the pymoo individual:
out["eval_id"] = self._feval
The design variables and objective values are also printed to the Python console:
print(
f"Evaluation {self._feval}: "
f"X = {x_eval.tolist()}, "
f"F = {out['F'].tolist()}"
)
This makes it possible to follow the progress of the optimization while the script is running.
Cleaning Up the Communication Files
After the results have been read, the communication files associated with the current evaluation are removed:
for fp in ("out.json", "out.ready", "in.json", "in.ready"):
if os.path.exists(fp):
os.remove(fp)
This prepares the working directory for the next design evaluation.
Evaluation Cycle
The complete evaluation cycle can be summarized as follows:
- pymoo generates a candidate design.
- The Python script writes the design variables to
in.json. - The script creates
in.readyto signal that the design request is ready. - CAESES generates and evaluates the candidate design.
- CAESES writes the objective and constraint values to
out.json. - CAESES creates
out.readyto signal that the results are available. - The Python script reads the results and returns them to pymoo.
- The communication files are removed.
- The process is repeated for the next candidate design.
Optimization Resultsβ
The Python script provided with this tutorial also generates a file named results.txt, which contains the final Pareto-optimal solutions identified by the NSGA-III algorithm.
The following part of the script prepares and saves the optimization results:
# ========= Save results =========
# Make a copy so res.X is not modified
X_out = np.array(res.X, copy=True)
# Convert the first three design variables to integers
X_out[:, :3] = np.round(X_out[:, :3]).astype(int)
# Flip the sign of the last objective
F_out = np.array(res.F, copy=True)
F_out[:, -1] *= -1
with open("results.txt", "w") as f:
f.write("Optimization Finished\n")
f.write("=====================\n\n")
f.write("Final Pareto Front\n")
f.write("------------------\n\n")
f.write("Design IDs:\n")
f.write(str(res.opt.get("eval_id")))
f.write("\n\nDesign Variables (X):\n")
f.write(str(X_out))
f.write("\n\nObjective Values (F):\n")
f.write(str(F_out))
The result file includes:
- The IDs of the Pareto-optimal designs.
- The corresponding design variables:
typeβ material type.intThβ discrete head thickness index.intTsβ discrete shell thickness index.Radiusβ inner radius of the pressure vessel.Lβ shell length.
- The objective function values:
totalCostβ total manufacturing cost.Vweldβ total weld material volume.SFβ safety factor.
An example of the generated output is shown below:
Optimization Finished
=====================
Final Pareto Front
------------------
Design IDs:
[ 85. 115. 93. 135. 137. 138. 142. 143.]
Design Variables (X):
[[ 1. 63. 67. 35.37170169 225.35678648]
[ 1. 29. 92. 27.48875345 226.49140318]
[ 0. 30. 69. 32.17002568 220.01030562]
[ 0. 26. 90. 32.17834783 169.02097808]
[ 2. 30. 38. 32.18292614 220.03598683]
[ 1. 59. 41. 32.30811080 169.75121078]
[ 1. 55. 42. 32.30029889 223.32344018]
[ 0. 59. 56. 32.52837308 221.78511588]]
Objective Values (F):
[[6.35310849e+05 1.09589944e+04 2.95963991e+00]
[5.72087528e+05 1.84290371e+04 5.22941138e+00]
[1.55656038e+05 1.09618191e+04 2.68106718e+00]
[1.54751307e+05 1.63992683e+04 3.49613972e+00]
[1.53162513e+05 3.32553435e+03 1.03315652e+00]
[3.18253336e+05 3.41752466e+03 1.98286122e+00]
[3.81989263e+05 4.10121922e+03 2.03171495e+00]
[1.48902948e+05 7.28925546e+03 2.15196745e+00]]
The type design variable represents the selected material. In this tutorial, the values 0, 1, and 2 correspond to the three available material types. The Pareto front contains optimal designs for all three materials, showing that each material can produce competitive solutions depending on the trade-off between the objective functions.
The figure below presents a correlation and regression analysis based on the 150 designs evaluated during the optimization.
Green points represent feasible designs, while red points indicate constraint violations.
The color scale of each correlation plot indicates the strength and direction of the relationship between a design variable and an objective function. Reddish or bluish colors indicate a stronger positive or negative influence, while a greenish color indicates a neutral or negligible influence.

CAESES Project Fileβ
If you want to take a look at the finalized setup you can find the resulting CAESES project file external-optimization.cdb here: