Python Connection via Feature DefinitionNewThis content is new.
This tutorial demonstrates how to connect CAESES with Python directly from a Feature Definition.
Although CAESES provides a dedicated Connection interface for communicating with external applications, executing Python scripts directly from a Feature Definition is often a simpler and more lightweight solution. This approach is well suited for custom calculations, data processing, and automation tasks.
In this tutorial, you will learn how to:
- Create a Python script from a Feature Definition
- Execute the Python script from within CAESES
- Write calculation results to external files
- Read the generated result files
- Assign the imported values to parameters in CAESES
- Plot the optimization results with Python
How the Connection Works
The idea is simple: the Feature Definition does all the communication with Python through files in the project directory.
- CAESES writes the input data (here: the sampled track geometry) to a CSV file.
- CAESES writes the Python script itself, with the current parameter values already inserted.
- CAESES starts Python as a process and runs the script.
- Python writes its results to a text file.
- CAESES reads the text file and assigns the values to parameters.
Because the script is regenerated on every update, the Python calculation always uses the current state of the parametric model. This is what makes the approach usable inside an optimization.
What You Need
| Item | Provided? |
|---|---|
Python with numpy, pandas and matplotlib | No – install as described below |
| Parametric 2D track model | Build it yourself (see 2D Roller Coaster) or use the final project file |
| Calculation Feature Definition | Yes |
| Plotting Feature Definition | Yes |
Example optimization results run.csv and run_best.csv | Yes |
Final project python-connection.cdb | Yes |
You don't need to write the Feature Definitions yourself. The following sections explain what the provided ones do, so you can adapt the approach to your own calculations.
Steps at a Glance
- Install Python and the required packages.
- Build the parametric 2D track.
- Load the Calculation Feature Definition and connect its inputs.
- Run it once with Create Animation enabled to check the connection.
- Set up and run the NSGA-II optimization.
- Load the Plotting Feature Definition and plot the results.
Python Requirements
To follow this tutorial, you must have Python installed on your computer. If Python is not already installed, you can download the latest version from the official Python website:
https://www.python.org/downloads/Required Python Packages
This tutorial uses the following Python packages:
- numpy – Numerical arrays and mathematical functions.
- pandas – Reads, processes, and exports tabular data.
- matplotlib – Generates plots for visualizing the calculation results.
Install the required packages by running the following commands in a terminal or PowerShell window:
pip install numpy
pip install pandas
pip install matplotlib
The Feature Definitions start Python with the command python. Check in a terminal that python --version works. On some systems Python is started with py (Windows launcher) or python3 (Linux) instead. In that case, change the command in the line process py("python") of both Feature Definitions, or enter the full path to the Python executable, for example C:/Python313/python.exe.
2D Roller Coaster
For this tutorial, a 2D roller coaster is used to demonstrate the connection between Python and CAESES.
The model consists of a cart moving along a two-dimensional track. The cart starts from the top of a hill with zero initial velocity, travels down the hill, and then passes through a vertical loop.
Parametric Inputs
Three design variables are used to define the main dimensions of the 2D roller-coaster track:
| Design Variable | Description |
|---|---|
hillHeight | Height of the initial hill |
loopHeightRatio | Ratio of the loop height to the hill height |
loopWidthRatio | Ratio of the loop width to the loop height |
The remaining track dimensions are derived from these design variables:
loopHeight = hillHeight * loopHeightRatio
loopWidth = loopHeight * loopWidthRatio
hillLength = 1.5 * hillHeight
lineLength = loopHeight / 2
Track Geometry
The 2D track is constructed from the following curves:
hillCurve– A smooth spline curve defining the initial hill. The curve is constructed with horizontal tangency at its start and end and zero curvature at the end.loopCurve– An elliptical curve defining the vertical loop based onloopHeightandloopWidth.line1– A straight section connectinghillCurvetoloopCurve.line2– A straight section connecting the end ofloopCurveto the final point of the track.track– A polycurve that combines all the individual curve segments into the complete roller-coaster track.
The following figure illustrates the main parameters used to define the 2D track:

To build the track:
-
Create the parameters
hillHeight,loopHeightRatioandloopWidthRatio, and the derived parametersloopHeight,loopWidth,hillLengthandlineLengthwith the expressions shown above. -
Create the points
hillStart,hillEnd,loopStartandtrackEndfrom these parameters. The values in the last column are for the example design withhillHeight = 7,loopHeightRatio = 0.6andloopWidthRatio = 1, which givesloopHeight = loopWidth = 4.2,hillLength = 10.5andlineLength = 2.1:Point x y Example (x, y) hillStart0hillHeight(0, 7) hillEndhillLength0(10.5, 0) loopStarthillLength + lineLength0(12.6, 0) trackEndhillLength + 2 * lineLength0(14.7, 0) The loop starts and ends at
loopStart. Its center lies at[loopStart:x, loopHeight / 2, 0], in the example [12.6, 2.1,0]. -
Create
hillCurveas an FSpline fromhillStarttohillEnd, with horizontal start and end tangents and zero curvature at the end. -
Create
loopCurveas an FEllipse withloopHeightandloopWidth. -
Create
line1andline2as FLine objects. -
Combine all segments into
track, an FPolyCurve.
If you are new to modeling curves in CAESES, the First Modeling Steps tutorial explains how to create parameters, points and curves.
Define the points first. They position and connect the individual track curves, so the curves follow automatically when a design variable changes.
Calculation Feature Definition
The Calculation Feature Definition provides the connection between CAESES and Python for evaluating the roller-coaster track. It follows the workflow described in How the Connection Works.
Inputs of the Feature Definition
The Feature Definition receives the following inputs from CAESES:
- The complete
trackcurve - The loop height
- The loop width
- The number of points sampled along the track and passed to Python
- An option to enable or disable the creation of the 2D roller-coaster animation
These inputs are used to prepare the data required by the generated Python script and to evaluate the motion of the cart along the track.
The following figure shows the inputs of the Calculation Feature Definition:

Creating the Track Input File
Before the Python calculation is executed, the Feature Definition generates a track.csv file from the input track curve.
The curve is sampled at the specified number of points, and the following information is written for each point:
| Column | Description |
|---|---|
id | Sequential point identifier |
x | X-coordinate of the sampled point |
y | Y-coordinate of the sampled point |
s | Arc length along the track from the start to the current point |
c | Curvature of the track at the current point |
All of these values are calculated directly in CAESES from the input curve and passed to Python through the generated track.csv file.
The file is created with the following code:
// **********************************************************************************************************
// 1. Create input file (track.csv) for the Python script (calculation.py)
// **********************************************************************************************************
ffile csvFile(getProjectDir() + "/track.csv")
if (!csvFile.openWrite())
echo("Failed to open file \"" + csvFile.getAbsolutePath() + "\" for writing")
break()
endif
double j()
// use file.write() or file.writeLine() to write to the file.
csvFile.writeLine("id, x, y, s, c")
loop (n)
j = $$i / (n - 1)
csvFile.writeLine(($$i + 1).toString() + ", " + crv.getPos(j):X.toString() + ", " + crv.getPos(j):Y.toString() + ", " + crv.getLengthFromTo(0,j).toString() + ", " + crv.getCurv(j).toString())
endloop
//close file when done with it
csvFile.close()
The resulting track.csv file provides Python with the discretized geometry and local curvature information required for the roller-coaster calculations.
Creating the Python Script
The next step performed by the Feature Definition is to create the calculation.py script.
Rather than maintaining a separate Python script manually, the Feature Definition writes the required Python code directly from CAESES. The generated script reads the previously created track.csv file, performs the roller-coaster calculations, writes the results to results.txt, and optionally generates an animation of the cart moving along the track as roller_coaster.gif.
This keeps the Python calculation directly connected to the parametric CAESES model and allows the script to be regenerated automatically whenever the track geometry or input parameters change.
It is easiest to read the generated script first. This is the calculation.py that CAESES writes for one design:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Read CAESES data
df = pd.read_csv("track.csv")
df.columns = df.columns.str.strip()
x, y, s, c = [df[k].to_numpy() for k in ("x", "y", "s", "c")]
# Calculate Speed, Ride Time and G-Force
g = 9.80665
v = np.sqrt(np.maximum(2 * g * (y[0] - y), 0))
vreq = np.sqrt(np.maximum(g * (2.1)**2 / (2.1), 0))
vtop = np.sqrt(np.maximum(2 * g * (y[0] - 4.2), 0))
ds = np.diff(s)
v_avg = (v[:-1] + v[1:]) / 2
dt = ds / v_avg
ride_time = np.sum(dt)
g_force = v**2 * np.abs(c) / g
# Write Results to File
with open("results.txt", "w") as file:
file.write(f"Track_length: {s[-1]:.6f} m\n")
file.write(f"Ride_time: {ride_time:.6f} s\n")
file.write(f"Mean_speed: {s[-1] / ride_time:.6f} m/s\n")
file.write(f"Maximum_speed: {np.max(v):.6f} m/s\n")
file.write(f"Req_speed: {vreq:.6f} m/s\n")
file.write(f"Top_speed: {vtop:.6f} m/s\n")
file.write(f"Maximum_Normal_G-Force: {np.max(g_force):.6f} g")
# Create Animation
if 0:
fps = 30
time = np.r_[0, np.cumsum(dt)]
t = np.arange(0, time[-1], 1/fps)
xa, ya, sa, va, ga = [np.interp(t, time, a) for a in (x, y, s, v, g_force)]
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(x, y)
cart, = ax.plot([], [], "o")
text = ax.text(0.98, 0.95, "", transform=ax.transAxes, ha="right", va="top")
ax.set(xlabel="x [m]", ylabel="y [m]", title="Roller Coaster")
ax.axis("equal")
ax.grid()
def update(i):
cart.set_data([xa[i]], [ya[i]])
text.set_text(f"Time: {t[i]:.2f} s\nDistance: {sa[i]:.2f} m\nSpeed: {va[i]:.2f} m/s\nNormal G-force: {ga[i]:.2f} g")
return cart, text
ani = FuncAnimation(fig, update, len(t), interval=1000/fps)
ani.save("roller_coaster.gif", writer="pillow", fps=fps)
plt.show()
The generated Python script performs the following tasks:
- Reads the sampled track geometry from
track.csv. - Calculates the cart speed along the track using the change in potential energy.
- Calculates the ride time from the local track length and average speed.
- Calculates the normal g-force from the cart speed and local track curvature.
- Writes the main calculated quantities to
results.txt. - Optionally generates
roller_coaster.gifto visualize the cart motion along the track.
The Feature Definition creates this script line by line with pythonFile.writeLine(). Each Python line becomes a string, so quotes inside the Python code are escaped as \" and line breaks as \\n.
Look for the places where the string is interrupted with " + ... + ", for example:
pythonFile.writeLine("vtop = np.sqrt(np.maximum(2 * g * (y[0] - " + loopHeight + "), 0))")
pythonFile.writeLine("if " + flag + ":")
Here CAESES inserts the current values of loopHeight and of the Create Animation option directly into the Python code. In the generated script above they appear as 4.2 and 0. This is the key trick of the approach: the script always contains the values of the current design, without passing them separately.
Show the Feature Definition code that writes calculation.py
// **********************************************************************************************************
// 2. Create the Python script (calculation.py) to calculate the parameters for the 2D roller coaster
// **********************************************************************************************************
ffile pythonFile(getProjectDir() + "/calculation.py")
if (!pythonFile.openWrite())
echo("Failed to open file \"" + pythonFile.getAbsolutePath() + "\" for writing")
break()
endif
// use file.write() or file.writeLine() to write to the file.
pythonFile.writeLine("import numpy as np")
pythonFile.writeLine("import pandas as pd")
pythonFile.writeLine("import matplotlib.pyplot as plt")
pythonFile.writeLine("from matplotlib.animation import FuncAnimation")
pythonFile.writeLine("")
pythonFile.writeLine("# Read CAESES data")
pythonFile.writeLine("df = pd.read_csv(\"track.csv\")")
pythonFile.writeLine("df.columns = df.columns.str.strip()")
pythonFile.writeLine("x, y, s, c = [df[k].to_numpy() for k in (\"x\", \"y\", \"s\", \"c\")]")
pythonFile.writeLine("")
pythonFile.writeLine("# Calculate Speed, Ride Time and G-Force")
pythonFile.writeLine("g = 9.80665")
pythonFile.writeLine("v = np.sqrt(np.maximum(2 * g * (y[0] - y), 0))")
pythonFile.writeLine("vreq = np.sqrt(np.maximum(g * (" + loopWidth / 2 + ")**2 / (" + loopHeight / 2 + "), 0))")
pythonFile.writeLine("vtop = np.sqrt(np.maximum(2 * g * (y[0] - " + loopHeight + "), 0))")
pythonFile.writeLine("ds = np.diff(s)")
pythonFile.writeLine("v_avg = (v[:-1] + v[1:]) / 2")
pythonFile.writeLine("dt = ds / v_avg")
pythonFile.writeLine("ride_time = np.sum(dt)")
pythonFile.writeLine("g_force = v**2 * np.abs(c) / g")
pythonFile.writeLine("")
pythonFile.writeLine("# Write Results to File")
pythonFile.writeLine("with open(\"results.txt\", \"w\") as file:")
pythonFile.writeLine(" file.write(f\"Track_length: {s[-1]:.6f} m\\n\")")
pythonFile.writeLine(" file.write(f\"Ride_time: {ride_time:.6f} s\\n\")")
pythonFile.writeLine(" file.write(f\"Mean_speed: {s[-1] / ride_time:.6f} m/s\\n\")")
pythonFile.writeLine(" file.write(f\"Maximum_speed: {np.max(v):.6f} m/s\\n\")")
pythonFile.writeLine(" file.write(f\"Req_speed: {vreq:.6f} m/s\\n\")")
pythonFile.writeLine(" file.write(f\"Top_speed: {vtop:.6f} m/s\\n\")")
pythonFile.writeLine(" file.write(f\"Maximum_Normal_G-Force: {np.max(g_force):.6f} g\")")
pythonFile.writeLine("")
pythonFile.writeLine("# Create Animation")
pythonFile.writeLine("if " + flag + ":")
pythonFile.writeLine(" fps = 30")
pythonFile.writeLine(" time = np.r_[0, np.cumsum(dt)]")
pythonFile.writeLine(" t = np.arange(0, time[-1], 1/fps)")
pythonFile.writeLine("")
pythonFile.writeLine(" xa, ya, sa, va, ga = [np.interp(t, time, a) for a in (x, y, s, v, g_force)]")
pythonFile.writeLine("")
pythonFile.writeLine(" fig, ax = plt.subplots(figsize=(8, 5))")
pythonFile.writeLine(" ax.plot(x, y)")
pythonFile.writeLine(" cart, = ax.plot([], [], \"o\")")
pythonFile.writeLine(" text = ax.text(0.98, 0.95, \"\", transform=ax.transAxes, ha=\"right\", va=\"top\")")
pythonFile.writeLine("")
pythonFile.writeLine(" ax.set(xlabel=\"x [m]\", ylabel=\"y [m]\", title=\"Roller Coaster\")")
pythonFile.writeLine(" ax.axis(\"equal\")")
pythonFile.writeLine(" ax.grid()")
pythonFile.writeLine("")
pythonFile.writeLine(" def update(i):")
pythonFile.writeLine(" cart.set_data([xa[i]], [ya[i]])")
pythonFile.writeLine(" text.set_text(f\"Time: {t[i]:.2f} s\\nDistance: {sa[i]:.2f} m\\nSpeed: {va[i]:.2f} m/s\\nNormal G-force: {ga[i]:.2f} g\")")
pythonFile.writeLine(" return cart, text")
pythonFile.writeLine("")
pythonFile.writeLine(" ani = FuncAnimation(fig, update, len(t), interval=1000/fps)")
pythonFile.writeLine(" ani.save(\"roller_coaster.gif\", writer=\"pillow\", fps=fps)")
pythonFile.writeLine(" plt.show()")
pythonFile.close()
Running the Python Script
Once calculation.py has been created, it can be executed directly from within the Feature Definition as a Python process.
The project directory is used as the working directory so that the Python script can access the generated track.csv file and write the resulting results.txt and roller_coaster.gif files to the same location.
// **********************************************************************************************************
// 3. Execute the Python script to calculate the parameters and animate the 2D roller coaster
// **********************************************************************************************************
string scriptPath(pythonFile.getAbsoluteFilePath())
process py("python") // cmd call: python calculation.py
py.setWorkingDir(getProjectDir())
py.setArguments([scriptPath])
py.run()
The python process executes the generated calculation.py script using the current CAESES project directory as its working directory.
py.run() starts Python from the Feature Definition. py.setArguments() takes a list of command-line arguments. Here the list contains only the path of the Python script, but you can pass more arguments, as the Plotting Feature Definition shows later.
Reading the Results
Finally, the values stored in results.txt are read automatically by the Feature Definition and assigned to the corresponding CAESES parameters.
These parameters can then be exposed as attributes of the Feature Definition and used for further evaluation, visualization, or optimization within CAESES.
For one design, the generated results.txt looks like this:
Track_length: 30.579425 m
Ride_time: 5.660301 s
Mean_speed: 5.402438 m/s
Maximum_speed: 11.717214 m/s
Req_speed: 4.538057 m/s
Top_speed: 7.410617 m/s
Maximum_Normal_G-Force: 6.724076 g
The Feature Definition splits the file into lines, takes the second word of each line as the value and assigns it to a parameter:
// **********************************************************************************************************
// 4. Read the calculated parameters from results.txt
// **********************************************************************************************************
ffile resultsFile(getProjectDir() + "/results.txt")
if (!resultsFile.openRead())
echo("Failed to open file \"" + resultsFile.getAbsolutePath() + "\" for reading.")
break()
endif
string readFile(resultsFile.readAll())
string line()
stringParameter import(readFile)
objectlist fileLines(import.splitByString("\r\n"))
unsigned m(fileLines.getCount())
unsigned i()
while (i < m)
line = fileLines.at(i).castto(FString)
objectlist lineSplit(line.split())
double value(lineSplit.at(1).castTo(FString).toDouble())
if (i == 0)
parameter trackLength(value)
elseif (i == 1)
parameter rideTime(value)
elseif (i == 2)
parameter meanSpeed(value)
elseif (i == 3)
parameter maxSpeed(value)
elseif (i == 4)
parameter reqSpeed(value)
elseif (i == 5)
parameter topSpeed(value)
else
parameter maxGForce(value)
endif
echo(line)
i += 1
endwhile
//close file when done with it
resultsFile.close()
The values are assigned by line number, not by their label: the first line becomes trackLength, the second rideTime, and so on. If you change the order of the file.write() lines in the Python script, change the order of the if/elseif branches as well. Otherwise the values end up in the wrong parameters without any error message.
Outputs of the Feature Definition
The Feature Definition returns the following parameters:
| Parameter | Line in results.txt | Description |
|---|---|---|
trackLength | Track_length | Total length of the roller-coaster track |
rideTime | Ride_time | Total time required for the cart to travel along the track |
meanSpeed | Mean_speed | Mean speed of the cart over the complete track |
maxSpeed | Maximum_speed | Maximum speed reached by the cart |
reqSpeed | Req_speed | Required speed for passing through the loop |
topSpeed | Top_speed | Speed of the cart at the top of the loop |
maxGForce | Maximum_Normal_G-Force | Maximum normal acceleration experienced along the track |
In the provided project, these outputs are referenced by parameters in the 03_results group. For example, maxNormalGForce holds the value of maxGForce. These result parameters are used as objectives and constraints in the optimization.
Using the Calculation Feature Definition
- Load the provided Calculation Feature Definition into the Features tab of the Model workspace.
- Create a feature from it and assign the inputs described above: the
trackcurve,loopHeight,loopWidthand the number of points. - Enable Create Animation and update the feature once. Check that the parameters show values and that
results.txtandroller_coaster.gifappear in the project directory. - Disable Create Animation again before the optimization.
Animation File
The Calculation Feature Definition can also generate an animation file, roller_coaster.gif, in the same directory as the CAESES project.
The animation shows the generated 2D roller-coaster track and the motion of the cart along it. As the cart moves along the track, the current time, distance traveled, speed, and normal g-force are displayed.
The animation is generated only when the Create Animation option in the Feature Definition is enabled.
Optimization Problem
Now that the connection between CAESES and Python has been established, the roller-coaster calculation can be integrated into an optimization workflow.
The objective of this tutorial is to estimate the Pareto front of the roller-coaster design by considering two competing objectives:
-
Minimize the maximum normal g-force (
maxNormalGForce) to improve passenger comfort by limiting the maximum normal acceleration experienced during the ride. -
Maximize the mean speed (
meanSpeed) to achieve a faster and more exciting ride.
These objectives are competing because increasing the speed of the cart can also increase the normal g-forces experienced along the track. Therefore, the optimization aims to identify Pareto-optimal designs representing different trade-offs between passenger comfort and ride excitement.
Design Variables
The optimization uses three design variables:
| Design Variable | Description | Minimum | Maximum |
|---|---|---|---|
hillHeight | Height of the initial hill in meters | 4 | 10 |
loopHeightRatio | Ratio of the loop height to the hill height | 0.4 | 0.8 |
loopWidthRatio | Ratio of the loop width to the loop height | 0.7 | 1.3 |
The loop is defined as an ellipse. When loopWidthRatio is equal to 1, the loop width and height are equal, resulting in a circular loop.
Objectives
The optimization considers the following two objectives:
| Objective | Description | Goal |
|---|---|---|
maxNormalGForce | Maximum normal g-force experienced along the track | Minimize |
meanSpeed | Mean speed of the cart over the complete track | Maximize |
Constraints
To ensure that the resulting designs remain within the desired operating range, the following constraints are applied:
| Constraint | Requirement | Description |
|---|---|---|
GForceCon | maxNormalGForce ≤ 5 g | Limits the maximum normal g-force to 5 g |
SpeedCon | topSpeed ≥ reqSpeed | Ensures that the cart has sufficient speed at the top of the loop to satisfy the required loop speed |
NSGA-II Optimization
The NSGA-II (Non-dominated Sorting Genetic Algorithm II) is used to estimate the Pareto front. NSGA-II is a multi-objective evolutionary algorithm designed to identify a diverse set of non-dominated solutions when multiple competing objectives are considered.
In the Optimize workspace, create a new NSGA-II design engine and connect the previously defined design variables, objectives, and constraints to it.
For this study, the NSGA-II algorithm is configured with the following settings:
| Setting | Value |
|---|---|
| Population Size | 50 |
| Number of Generations | 50 |
| Total Function Evaluations | 2,500 |
| Mutation Probability | 0.1 |
| Crossover Probability | 0.9 |

Enter 49 as Population Size. The designs are numbered starting from 0, so this gives 50 designs per generation.
NSGA-II requires the population size of each generation to be at least 4 and divisible by 4. If necessary, CAESES adjusts the population size internally to satisfy this requirement.
During the optimization, CAESES generates candidate designs by modifying the three design variables. For each design, the Calculation Feature Definition evaluates the roller-coaster performance and returns the calculated quantities to the Design Engine.
NSGA-II then uses these results to progressively estimate the Pareto front between the two competing objectives:
- Minimize the maximum normal g-force
- Maximize the mean speed
The resulting Pareto front represents the best trade-offs between achieving a higher mean speed and reducing the maximum normal g-force experienced during the ride.
Keep the Create Animation option in the Calculation Feature Definition disabled during the optimization. Generating an animation for every evaluated design is unnecessary and would significantly increase the computational time.
Optimization Results
When the NSGA-II Design Engine is executed, CAESES creates a new run directory within the project directory. Once the optimization is completed, two CSV files containing the optimization results are generated:
-
run.csv– Contains the results of all evaluated designs in the order in which they were evaluated. -
run_best.csv– Contains the best designs identified during the optimization. For a multi-objective optimization, this file contains the designs that form the Pareto front.
You can download both files to try the plotting step without running the optimization yourself.
Plotting Optimization Results
In addition to using Python for the Calculation Feature Definition, this tutorial also demonstrates how Python can be connected to CAESES to visualize the results of the NSGA-II optimization.
Python provides powerful libraries such as pandas and matplotlib for processing tabular data and generating customized plots.
Plotting Feature Definition
The Plotting Feature Definition connects CAESES with Python for post-processing the optimization results. It reads either run.csv, containing all evaluated designs, or run_best.csv, containing the Pareto-optimal designs.
The generated plots show the relationship between the two objectives, maximum normal g-force and mean speed, while the points are colored according to the values of the individual design variables. This makes it easier to visualize the influence of each design variable on the optimization results and the trade-off between ride speed and passenger comfort.
The resulting plots can be saved in different formats supported by matplotlib, such as PNG or SVG.
The following figure shows the inputs of the Plotting Feature Definition:
- Load the provided Plotting Feature Definition into the Features tab of the Model workspace.
- Create a feature from it.
- Select the results file as Input File (
run.csvorrun_best.csv). - Enter the file name of the plot as Output Plot, for example
allevaluations.png.
Creating the Plotting Script
As with the Calculation Feature Definition, the first step is to generate a Python script. In this case, the script is named visualization.py.
The script reads the selected optimization results file, processes the tabular data using pandas, and generates the plots using matplotlib. This is the generated script:
import sys
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv(sys.argv[1], sep=";")
df.columns = df.columns.str.strip()
df.rename(columns={
"|00_parameters|hillHeight": "Hill Height (m)",
"|00_parameters|loopHeight": "Loop Height (m)",
"|00_parameters|loopWidth": "Loop Width (m)",
"|03_results|meanSpeed": "Mean Speed (m/s)",
"|03_results|maxNormalGForce": "Max. Normal G-Force (g)",
}, inplace=True)
x, y = "Mean Speed (m/s)", "Max. Normal G-Force (g)"
fig, ax = plt.subplots(3, 1, figsize=(7, 12), sharex=True, sharey=True)
for a, (v, cmap, vmin, vmax) in zip(ax, [
("Hill Height (m)", "viridis", 4, 10),
("Loop Height (m)", "plasma", 3, 8),
("Loop Width (m)", "cividis", 3, 10),
]):
s = a.scatter(df[x], df[y], c=df[v], cmap=cmap, vmin=vmin, vmax=vmax)
a.set_ylabel(y)
a.grid()
fig.colorbar(s, ax=a, label=v)
ax[-1].set_xlabel(x)
ax[-1].set_xlim(4, 7)
ax[-1].set_ylim(4, 5)
fig.tight_layout()
fig.savefig(sys.argv[2], dpi=300)
plt.show()
The script creates three scatter plots. In each subplot, the horizontal axis represents the mean speed, while the vertical axis represents the maximum normal g-force. The point colors represent the corresponding geometric parameter: hill height, loop height, or loop width.
The column names such as |03_results|meanSpeed are the parameter names used in the CAESES project, as they appear in the header of run.csv. If your parameters are named or grouped differently, adapt the rename block.
Show the Feature Definition code that writes visualization.py
// **********************************************************************************************************
// 1. Create the Python script (visualization.py) for generating the Pareto front plots
// **********************************************************************************************************
ffile pythonFile(getProjectDir() + "/visualization.py")
if (!pythonFile.openWrite())
echo("Failed to open file \"" + pythonFile.getAbsolutePath() + "\" for writing")
break()
endif
// use file.write() or file.writeLine() to write to the file.
pythonFile.writeLine("import sys")
pythonFile.writeLine("import pandas as pd")
pythonFile.writeLine("import matplotlib.pyplot as plt")
pythonFile.writeLine("import numpy as np")
pythonFile.writeLine("")
pythonFile.writeLine("df = pd.read_csv(sys.argv[1], sep=\";\")")
pythonFile.writeLine("df.columns = df.columns.str.strip()")
pythonFile.writeLine("df.rename(columns={")
pythonFile.writeLine(" \"|00_parameters|hillHeight\": \"Hill Height (m)\",")
pythonFile.writeLine(" \"|00_parameters|loopHeight\": \"Loop Height (m)\",")
pythonFile.writeLine(" \"|00_parameters|loopWidth\": \"Loop Width (m)\",")
pythonFile.writeLine(" \"|03_results|meanSpeed\": \"Mean Speed (m/s)\",")
pythonFile.writeLine(" \"|03_results|maxNormalGForce\": \"Max. Normal G-Force (g)\",")
pythonFile.writeLine("}, inplace=True)")
pythonFile.writeLine("")
pythonFile.writeLine("x, y = \"Mean Speed (m/s)\", \"Max. Normal G-Force (g)\"")
pythonFile.writeLine("fig, ax = plt.subplots(3, 1, figsize=(7, 12), sharex=True, sharey=True)")
pythonFile.writeLine("")
pythonFile.writeLine("for a, (v, cmap, vmin, vmax) in zip(ax, [")
pythonFile.writeLine(" (\"Hill Height (m)\", \"viridis\", 4, 10),")
pythonFile.writeLine(" (\"Loop Height (m)\", \"plasma\", 3, 8),")
pythonFile.writeLine(" (\"Loop Width (m)\", \"cividis\", 3, 10),")
pythonFile.writeLine("]):")
pythonFile.writeLine("")
pythonFile.writeLine(" s = a.scatter(df[x], df[y], c=df[v], cmap=cmap, vmin=vmin, vmax=vmax)")
pythonFile.writeLine(" a.set_ylabel(y)")
pythonFile.writeLine(" a.grid()")
pythonFile.writeLine(" fig.colorbar(s, ax=a, label=v)")
pythonFile.writeLine("")
pythonFile.writeLine("ax[-1].set_xlabel(x)")
pythonFile.writeLine("ax[-1].set_xlim(4, 7)")
pythonFile.writeLine("ax[-1].set_ylim(4, 5)")
pythonFile.writeLine("fig.tight_layout()")
pythonFile.writeLine("fig.savefig(sys.argv[2], dpi=300)")
pythonFile.writeLine("plt.show()")
pythonFile.close()
Running the Plotting Script
Compared with calculation.py, the visualization.py script requires two additional command-line arguments: the input CSV file containing the optimization results and the output file name for the generated plot.
These arguments are passed from CAESES when the Python script is executed:
- Input file – The
run.csvorrun_best.csvfile containing the optimization results. - Output file – The file name and format used to save the generated plot, for example,
allevaluations.pngfor all evaluated designs orparetofront.pngfor the Pareto-optimal designs.
// **********************************************************************************************************
// 2. Execute the Python script to visualize the optimization results
// **********************************************************************************************************
string scriptPath(pythonFile.getAbsoluteFilePath())
process py("python") // cmd call: python visualization.py <input file> <output plot>
py.setWorkingDir(getProjectDir())
py.setArguments([scriptPath, file.getFileName(), plotName])
py.run()
The arguments passed to visualization.py are accessed within the Python script using sys.argv.
sys.argv[1]retrieves the input CSV file containing the optimization results.sys.argv[2]retrieves the output file name for the generated plot.
The script path is passed as the first element of py.setArguments(), while the input and output files become sys.argv[1] and sys.argv[2] within the Python script.
Optimization Plots
The plots generated from the optimization results are shown below. Each figure contains three subplots, one for each geometric parameter:
- Hill Height (m)
- Loop Height (m)
- Loop Width (m)
In all subplots, the horizontal axis represents the Mean Speed (m/s), while the vertical axis represents the Max. Normal G-Force (g). The color scale represents the value of the corresponding geometric parameter, making it easier to identify how the track geometry influences the trade-off between the two optimization objectives.
All Evaluations
The following figure shows all designs evaluated during the NSGA-II optimization and is generated from run.csv.

Troubleshooting
Nothing happens, or the parameters stay empty
CAESES could not start Python. Check that python --version works in a terminal. If Python is started with py or python3 on your system, or is not on the PATH, change process py("python") in the Feature Definition to that command or to the full path of the Python executable.
"ModuleNotFoundError: No module named 'pandas'"
The required packages are missing for the Python installation that CAESES uses. Run the pip install commands from Required Python Packages with the same Python, for example python -m pip install pandas.
"Failed to open file ... results.txt for reading"
The Python script stopped before it wrote its results. Open the CAESES console to see the error message, or run python calculation.py manually in the project directory to see the Python error.
To test your Python setup outside CAESES, download the example files track.csv and calculation.py for one design, put them in one folder and run python calculation.py there. If this creates a results.txt, Python and the packages are set up correctly.
All values end up in the first parameter, or values are wrong
The results are split into lines with "\r\n", which matches the Windows line endings that Python writes on Windows. On Linux, Python writes "\n" line endings, so change the separator in splitByString() to "\n". Also check that the order of the lines in results.txt matches the order of the if/elseif branches.
CAESES Project File
If you want to take a look at the finalized parametric model you can find the resulting CAESES project file python-connection.cdb here: