Tutorial: topology optimisation using pyfe3d#
Author: Saullo G. P. Castro
Cite this tutorial as:
Saullo G. P. Castro. General-purpose finite element solver based on Python and Cython. Zenodo. DOI: https://doi.org/10.5281/zenodo.6573489.
The material distribution of a square membrane is optimised to minimise its compliance under a point load, for a prescribed fraction of the material, with a density-based approach and the gradient-based SLSQP algorithm of scipy.
The stiffness of the material follows the power law of the density introduced by Bendsøe (1989, Section 3, Eq. 7) for this approach.
References#
Bendsøe, M. P., Optimal shape design as a material distribution problem, Structural Optimization, 1(4), 193-202, 1989. https://doi.org/10.1007/BF01650949
Importing Python modules#
[1]:
%matplotlib inline
import numpy as np
from numpy import isclose
import matplotlib.pyplot as plt
from scipy.sparse.linalg import cg
from scipy.sparse import coo_matrix
from scipy.optimize import minimize
from pyfe3d.shellprop_utils import isotropic_plate
from pyfe3d import Quad4R, Quad4RData, Quad4RProbe, INT, DOUBLE, DOF
Creating mesh#
A \(3 \times 3\) m steel plate, 3 mm thick, meshed with \(39 \times 39\) nodes, i.e. \(38 \times 38\) Quad4R elements. Each element has one design variable, its density \(\rho_i\).
[2]:
data = Quad4RData()
probe = Quad4RProbe()
nx = 39
ny = 39
N = DOF*nx*ny
a = 3.0
b = 3.0
c = 3
E0 = 203.e9 # Pa
nu = 0.33
h = 0.003 # m
xtmp = np.linspace(0, a, nx)
ytmp = np.linspace(0, b, ny)
xmesh, ymesh = np.meshgrid(xtmp, ytmp)
ncoords = np.vstack((xmesh.T.flatten(), ymesh.T.flatten(), np.zeros_like(ymesh.T.flatten()))).T
x = ncoords[:, 0]
y = ncoords[:, 1]
z = ncoords[:, 2]
ncoords_flatten = ncoords.flatten()
nids = 1 + np.arange(ncoords.shape[0])
nid_pos = dict(zip(nids, np.arange(len(nids))))
nids_mesh = nids.reshape(nx, ny)
n1s = nids_mesh[:-1, :-1].flatten()
n2s = nids_mesh[1:, :-1].flatten()
n3s = nids_mesh[1:, 1:].flatten()
n4s = nids_mesh[:-1, 1:].flatten()
num_elements = len(n1s)
print('# number of elements', num_elements)
nodes = list(zip(n1s, n2s, n3s, n4s))
# number of elements 1444
Calculate the stiffness matrix for a vector of design variables “rho”#
The Young modulus of every element follows the power law \(E_i = \rho_i^c E_0\) of Bendsøe (1989), where \(E_0\) is the Young modulus of the solid material and the exponent \(c = 3\) penalises intermediate densities, which then give little stiffness for their volume and are driven towards 0 or 1.
[3]:
def calc_K(rho):
E = rho**c*E0
KC0r = np.zeros(data.KC0_SPARSE_SIZE*num_elements, dtype=INT)
KC0c = np.zeros(data.KC0_SPARSE_SIZE*num_elements, dtype=INT)
KC0v = np.zeros(data.KC0_SPARSE_SIZE*num_elements, dtype=DOUBLE)
quads = []
init_k_KC0 = 0
i = 0
for n1, n2, n3, n4 in zip(n1s, n2s, n3s, n4s):
prop = isotropic_plate(thickness=h, E=E[i], nu=nu)
i += 1
pos1 = nid_pos[n1]
pos2 = nid_pos[n2]
pos3 = nid_pos[n3]
pos4 = nid_pos[n4]
r1 = ncoords[pos1]
r2 = ncoords[pos2]
r3 = ncoords[pos3]
quad = Quad4R(probe)
quad.n1 = n1
quad.n2 = n2
quad.n3 = n3
quad.n4 = n4
quad.c1 = DOF*nid_pos[n1]
quad.c2 = DOF*nid_pos[n2]
quad.c3 = DOF*nid_pos[n3]
quad.c4 = DOF*nid_pos[n4]
quad.init_k_KC0 = init_k_KC0
quad.update_rotation_matrix(ncoords_flatten)
quad.update_probe_xe(ncoords_flatten)
quad.update_KC0(KC0r, KC0c, KC0v, prop)
quads.append(quad)
init_k_KC0 += data.KC0_SPARSE_SIZE
KC0 = coo_matrix((KC0v, (KC0r, KC0c)), shape=(N, N)).tocsc()
return KC0
Sensitivity of the stiffness matrix with respect to the vector “rho”#
Each \(\rho_i\) affects only the stiffness matrix of element \(i\), which is linear in \(E_i\), so
where \(\mathbf{K}_i(E)\) is the stiffness matrix of element \(i\) alone, assembled with the modulus \(E\). The function below returns it.
[4]:
def K_rho(rho, i):
E_rho = c*rho[i]**(c-1)*E0
prop = isotropic_plate(thickness=h, E=E_rho, nu=nu)
KC0r = np.zeros(1*data.KC0_SPARSE_SIZE, dtype=INT)
KC0c = np.zeros(1*data.KC0_SPARSE_SIZE, dtype=INT)
KC0v = np.zeros(1*data.KC0_SPARSE_SIZE, dtype=DOUBLE)
n1, n2, n3, n4 = nodes[i]
pos1 = nid_pos[n1]
pos2 = nid_pos[n2]
pos3 = nid_pos[n3]
pos4 = nid_pos[n4]
r1 = ncoords[pos1]
r2 = ncoords[pos2]
r3 = ncoords[pos3]
quad = Quad4R(probe)
quad.n1 = n1
quad.n2 = n2
quad.n3 = n3
quad.n4 = n4
quad.c1 = DOF*nid_pos[n1]
quad.c2 = DOF*nid_pos[n2]
quad.c3 = DOF*nid_pos[n3]
quad.c4 = DOF*nid_pos[n4]
quad.init_k_KC0 = 0
quad.update_rotation_matrix(ncoords_flatten)
quad.update_probe_xe(ncoords_flatten)
quad.update_KC0(KC0r, KC0c, KC0v, prop)
KC0 = coo_matrix((KC0v, (KC0r, KC0c)), shape=(N, N)).tocsc()
return KC0
Applying boundary conditions and forces#
The in-plane displacements \(u\), \(v\) are zero at the two corners at \(x = 0\), \((0, 0)\) and \((0, b)\). The out-of-plane displacement \(w\) and the rotations about \(x\) and \(y\) are restrained at all nodes, making it a two-dimensional membrane problem. A point force of \(-1000\) N along \(y\) acts at the corner \((a, 0)\).
[5]:
bk = np.zeros(N, dtype=bool)
check = isclose(x, 0) & (isclose(y, 0.) | isclose(y, b))
bk[0::DOF] = check
bk[1::DOF] = check
# making it a 2D membrane problem
bk[2::DOF] = True
bk[3::DOF] = True
bk[4::DOF] = True
bu = ~bk
# point load along v at the corner (a, 0)
fext = np.zeros(N)
ftotal = -1000.
print('ftotal', ftotal)
check = isclose(x, a) & isclose(y, 0)
fext[1::DOF][check] = ftotal
ftotal -1000.0
Performing topology optimization#
The compliance \(C = \mathbf{u}^T \mathbf{K} \mathbf{u}\), with \(\mathbf{K}\mathbf{u} = \mathbf{f}\), is minimised subject to the volume fraction \(\sum_i \rho_i / n \le 0.4\) and the bounds \(10^{-6} \le \rho_i \le 1\). The lower bound keeps the stiffness matrix non-singular. The static problem is solved with the conjugate gradient method on the diagonally scaled system.
Since the load does not depend on \(\rho\), the adjoint method gives the gradient without further solutions:
The function jac uses the displacements of the last call to objective, which SLSQP evaluates at the same design before it asks for the gradient. The start design is the full plate, \(\rho_i = 1\); every call to objective prints the compliance.
[6]:
uu = None
K = None
def jac(rho):
"""Adjoint gradient of the compliance with respect to each density in 'rho'
"""
u = np.zeros(N)
u[bu] = uu
C_rho = np.zeros(num_elements)
for i in range(num_elements):
C_rho[i] = - u.T @ K_rho(rho, i) @ u
return C_rho
def rel_volume(rho):
target_rel_volume = 0.4
constr = target_rel_volume - np.sum(rho)/num_elements
return constr
def objective(rho):
global uu, K
K = calc_K(rho)
Kuu = K[bu, :][:, bu]
PREC = np.max(1/Kuu.diagonal())
uu, info = cg(PREC*Kuu, PREC*fext[bu], atol=1e-3)
compl = uu.T @ Kuu @ uu
print('compliance', compl)
return compl
constraints = [
{'type': 'ineq', 'fun': rel_volume},
]
bounds = [[1.e-6, 1.] for _ in range(num_elements)]
rho = np.ones(num_elements)
topopt = minimize(objective, rho, jac=jac, method='SLSQP',
constraints=constraints, bounds=bounds)
compliance 0.03383225280019338
compliance 0.550820821357927
compliance 0.3505638968840433
compliance 0.32130668356894426
compliance 0.26043922507979655
compliance 0.24492970799217506
compliance 0.22077159839167812
compliance 0.21053402048656888
compliance 0.2005847361657363
compliance 0.190243279482539
compliance 0.18564211169581507
compliance 0.1759417540491384
compliance 0.16932400397920516
compliance 0.16611815578105593
compliance 0.1602069081328862
compliance 0.1569087053646178
compliance 0.15427709952108196
compliance 0.15071399729949073
compliance 0.1475615563059305
compliance 0.1436210582685398
compliance 0.14157510160636189
compliance 0.13909168522341503
compliance 0.1375895812086768
compliance 0.13478601481845126
compliance 0.13171535702181636
compliance 0.1283898252350652
compliance 0.12299877561075966
compliance 0.11929994172458125
compliance 0.11449273941551141
compliance 0.11253231031255001
compliance 0.11066073959207486
compliance 0.10839585437600242
compliance 0.10584273583502743
compliance 0.10430562327219259
compliance 0.10241433114552381
compliance 0.10028003206137576
compliance 0.09773891279412787
compliance 0.09621219524140309
compliance 0.09494219901025658
compliance 0.09409845663554511
compliance 0.09309008576484118
compliance 0.09188210389192476
compliance 0.09079752552801554
compliance 0.08971187916416162
compliance 0.08835008435134978
compliance 0.08737344654746068
compliance 0.08645136743295276
compliance 0.08530625478065598
compliance 0.08399289145440925
compliance 0.08311936821696782
compliance 0.08213885250612622
compliance 0.08124382843278259
compliance 0.08025786658198115
compliance 0.0791029404688389
compliance 0.07826053774476772
compliance 0.07754239595524093
compliance 0.07684355900523665
compliance 0.07612069707094249
compliance 0.07535938951723294
compliance 0.0745944603360613
compliance 0.07382068519686805
compliance 0.0731952905773516
compliance 0.07256151599079526
compliance 0.07201715050930957
compliance 0.07170820603115231
compliance 0.07125266544904096
compliance 0.07048997497734207
compliance 0.07001731166092276
compliance 0.06933125802833277
compliance 0.06889194325412135
compliance 0.06839176025767872
compliance 0.06805937605863369
compliance 0.06765407151490356
compliance 0.06713268257450525
compliance 0.06669831743830795
compliance 0.06633402577086589
compliance 0.06591248918540361
compliance 0.06543346822192575
compliance 0.06505742558436792
compliance 0.06471381521566844
compliance 0.06436682647729236
compliance 0.0641455774271735
compliance 0.0638570475360049
compliance 0.06361912478420297
compliance 0.06342017671661616
compliance 0.06325292459082774
compliance 0.06307699550532839
compliance 0.06284894995787678
compliance 0.06261030226390961
compliance 0.06239622237870474
compliance 0.06209076333506107
compliance 0.061848230329852434
compliance 0.06164587706106595
compliance 0.061461056099937926
compliance 0.06126755552194031
compliance 0.06100873823764771
compliance 0.06083538354338194
compliance 0.060657581573009406
compliance 0.0604235297845178
compliance 0.06021782837385118
compliance 0.05999268887479371
Checking the result of the topology optimization#
The final compliance and volume fraction are printed, and the density of each element is plotted at its centroid.
[7]:
print('success:', topopt.success, '-', topopt.message)
print('iterations:', topopt.nit)
print('final compliance:', topopt.fun)
print('volume fraction:', np.sum(topopt.x)/num_elements)
print('fraction of elements with rho > 0.9:', np.mean(topopt.x > 0.9))
print('fraction of elements with rho < 0.1:', np.mean(topopt.x < 0.1))
xcg = np.zeros((num_elements, 3))
i = 0
for n1, n2, n3, n4 in zip(n1s, n2s, n3s, n4s):
pos1 = nid_pos[n1]
pos2 = nid_pos[n2]
pos3 = nid_pos[n3]
pos4 = nid_pos[n4]
r1 = ncoords[pos1]
r2 = ncoords[pos2]
r3 = ncoords[pos3]
r4 = ncoords[pos4]
xcg[i] = (r1 + r2 + r3 + r4)/4
i += 1
plt.figure(figsize=(5.5, 4.5))
plt.scatter(xcg[:, 0], xcg[:, 1], c=topopt.x, vmin=0, vmax=1, marker='s')
plt.colorbar(label=r'$\rho$')
plt.gca().set_aspect('equal')
plt.xlabel('$x$ [m]')
plt.ylabel('$y$ [m]')
plt.show()
success: False - Iteration limit reached
iterations: 100
final compliance: 0.05999268887479371
volume fraction: 0.3999999999999999
fraction of elements with rho > 0.9: 0.1731301939058172
fraction of elements with rho < 0.1: 0.389196675900277