# Solve a 2D short cantilever topology optimization problem¶

from __future__ import annotations

import matplotlib.pyplot as plt
from gemseo.api import configure_logger
from gemseo.api import create_scenario
from gemseo.problems.topo_opt.topopt_initialize import (
initialize_design_space_and_discipline_to,
)
from matplotlib import colors

configure_logger()


## Setup the topology optimization problem¶

Define the target volume fraction:

volume_fraction = 0.3


Define the problem type:

problem_name = "Short_Cantilever"


Define the number of elements in the x- and y- directions:

n_x = 50
n_y = 25


Define the full material Young’s modulus and Poisson’s ratio:

e0 = 1
nu = 0.3


Define the penalty of the SIMP approach:

penalty = 3


Define the minimum member size in the solution:

min_memeber_size = 1.5


Instantiate the DesignSpace and the disciplines:

design_space, disciplines = initialize_design_space_and_discipline_to(
problem=problem_name,
n_x=n_x,
n_y=n_y,
e0=e0,
nu=nu,
penalty=penalty,
min_member_size=min_memeber_size,
vf0=volume_fraction,
)


## Solve the topology optimization problem¶

Generate a MDOScenario:

scenario = create_scenario(
disciplines,
formulation="DisciplinaryOpt",
objective_name="compliance",
design_space=design_space,
)


Add the volume fraction constraint to the scenario:

scenario.add_constraint("volume fraction", "ineq", value=volume_fraction)


Generate the XDSM:

scenario.xdsmize()


Execute the scenario:

scenario.execute(input_data={"max_iter": 200, "algo": "NLOPT_MMA"})


## Results¶

Post-process the optimization history:

scenario.post_process(
"BasicHistory",
variable_names=["compliance"],
save=True,
show=False,
file_name=problem_name + "_history.png",
)


Plot the solution:

plt.ion()  # Ensure that redrawing is possible
fig, ax = plt.subplots()
im = ax.imshow(
-scenario.optimization_result.x_opt.reshape((n_x, n_y)).T,
cmap="gray",
interpolation="none",
norm=colors.Normalize(vmin=-1, vmax=0),
)
fig.show()
im.set_array(-scenario.optimization_result.x_opt.reshape((n_x, n_y)).T)
fig.canvas.draw()
plt.savefig(problem_name + "_solution.png")


Total running time of the script: ( 0 minutes 0.000 seconds)

Gallery generated by Sphinx-Gallery