Tutorial: Ply tailoring using SLSQP for a simply-supported plate under normal load#

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.

Requirements#

This tutorial needs numpy, scipy, matplotlib, pymoo and pyfe3d, e.g. python -m pip install numpy scipy matplotlib pymoo pyfe3d.

Importing modules#

The thicknesses of the \(0^\circ\), \(\pm 45^\circ\) and \(90^\circ\) plies of every element of a composite plate are optimised with the gradient-based SLSQP algorithm of scipy to minimise the volume of the plate, under a limit on its maximum deflection.

[1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from pymoo.core.problem import ElementwiseProblem
from scipy.optimize import minimize as scipy_minimize
from scipy.optimize import Bounds
from scipy.sparse.linalg import spsolve
from scipy.sparse import coo_matrix
from pyfe3d.shellprop import ShellProp
from pyfe3d import Quad4, Quad4Data, Quad4Probe, INT, DOUBLE, DOF

Ply stiffness#

Each ply is orthotropic with the in-plane reduced stiffnesses

\[Q_{11} = \frac{E_1}{1 - \nu_{12}\nu_{21}}, \quad Q_{22} = \frac{E_2}{1 - \nu_{12}\nu_{21}}, \quad Q_{12} = \frac{\nu_{12} E_2}{1 - \nu_{12}\nu_{21}}, \quad Q_{66} = G_{12}, \quad \nu_{21} = \nu_{12}\frac{E_2}{E_1}\]

and the transverse shear stiffnesses \(G_{13}\), \(G_{23}\). A ply at the angle \(\theta\) has the transformed stiffnesses \(\bar{Q}_{ij}(\theta)\), with \(c = \cos\theta\), \(s = \sin\theta\):

\[\bar{Q}_{11} = Q_{11}c^4 + 2(Q_{12} + 2Q_{66})s^2c^2 + Q_{22}s^4, \quad \bar{Q}_{22} = Q_{11}s^4 + 2(Q_{12} + 2Q_{66})s^2c^2 + Q_{22}c^4\]
\[\bar{Q}_{12} = (Q_{11} + Q_{22} - 4Q_{66})s^2c^2 + Q_{12}(s^4 + c^4), \quad \bar{Q}_{66} = (Q_{11} + Q_{22} - 2Q_{12} - 2Q_{66})s^2c^2 + Q_{66}(s^4 + c^4)\]
\[\bar{Q}_{44} = G_{23}c^2 + G_{13}s^2, \quad \bar{Q}_{55} = G_{13}c^2 + G_{23}s^2, \quad \bar{Q}_{45} = (G_{13} - G_{23})cs\]

The function below returns them in a \(6 \times 6\) matrix with the Voigt ordering used by the code (\(\bar{Q}_{11}, \bar{Q}_{12}, \bar{Q}_{22}\) in the first block, the transverse shear terms at indices 3 and 4, \(\bar{Q}_{66}\) at index 5); the transverse normal row and column are zero.

[2]:
def get_Q_matrix(E1, E2, nu12, G12, G13, G23, theta_deg):
    """
    Calculate the transformed reduced stiffness matrix Q_bar for a given angle.
    """
    nu21 = nu12 * E2 / E1
    denom = 1 - nu12 * nu21
    Q11 = E1 / denom
    Q22 = E2 / denom
    Q12 = nu12 * E2 / denom
    Q66 = G12

    c = np.cos(np.radians(theta_deg))
    s = np.sin(np.radians(theta_deg))

    c2 = c**2; s2 = s**2; c4 = c**4; s4 = s**4

    Q_bar_11 = Q11*c4 + 2*(Q12 + 2*Q66)*s2*c2 + Q22*s4
    Q_bar_22 = Q11*s4 + 2*(Q12 + 2*Q66)*s2*c2 + Q22*c4
    Q_bar_12 = (Q11 + Q22 - 4*Q66)*s2*c2 + Q12*(s4 + c4)
    Q_bar_66 = (Q11 + Q22 - 2*Q12 - 2*Q66)*s2*c2 + Q66*(s4 + c4)

    Q_bar_44 = G23 * c2 + G13 * s2
    Q_bar_55 = G13 * c2 + G23 * s2
    Q_bar_45 = (G13 - G23) * c * s

    Q_bar = np.array([
        [Q_bar_11, Q_bar_12, 0, 0, 0, 0],
        [Q_bar_12, Q_bar_22, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, Q_bar_44, Q_bar_45, 0],
        [0, 0, 0, Q_bar_45, Q_bar_55, 0],
        [0, 0, 0, 0, 0, Q_bar_66]
    ])
    return Q_bar

Smeared laminate and plate model#

A rectangular plate \(a \times b\), simply supported on its four edges, carries a point load \(P\) normal to its mid-plane at the centre. The design variables are three continuous thicknesses per element: \(h_0\) of the \(0^\circ\) plies, \(h_{45}\) of each of the \(+45^\circ\) and \(-45^\circ\) plies, and \(h_{90}\) of the \(90^\circ\) plies. The laminate of each element is smeared: the stacking sequence is not modelled, and the stiffnesses are

\[h = h_0 + 2h_{45} + h_{90}, \qquad \mathbf{A} = h_0\bar{\mathbf{Q}}(0^\circ) + h_{45}\left[\bar{\mathbf{Q}}(45^\circ) + \bar{\mathbf{Q}}(-45^\circ)\right] + h_{90}\bar{\mathbf{Q}}(90^\circ), \qquad \mathbf{D} = \frac{h^2}{12}\mathbf{A}, \qquad \mathbf{B} = \mathbf{0}\]

that is, \(\mathbf{D}\) is the bending stiffness of a homogeneous plate with the averaged stiffness \(\mathbf{A}/h\). The transverse shear stiffnesses \(A_{44}, A_{45}, A_{55}\) take the shear correction factor \(5/6\). These values are written directly into a ShellProp of each Quad4 element.

By symmetry only the quarter \(0 \le x \le a/2\), \(0 \le y \le b/2\) is modelled:

  • \(w = 0\) at the simply supported edges \(x = 0\) and \(y = 0\);

  • the rotation about \(y\) is zero along the symmetry line \(x = a/2\), and the rotation about \(x\) is zero along \(y = b/2\);

  • the in-plane displacements \(u\), \(v\) are restrained everywhere: with \(\mathbf{B} = \mathbf{0}\) the bending problem is uncoupled from the membrane one, and this also satisfies \(u = 0\) at \(x = a/2\) and \(v = 0\) at \(y = b/2\);

  • the centre node lies on both symmetry lines, so it carries \(P/4\).

The method _evaluate updates the element stiffness matrices for a design var, solves the static problem and returns the objective F, the volume of the full plate (four times that of the quarter), and the constraint G on the maximum deflection (next section). The class follows the pymoo ElementwiseProblem interface.

[3]:
class SmearedPlateOptimization(ElementwiseProblem):
    def __init__(self, nx, ny, a, b, load_val, max_deflection, h_min, h_max, mat_data):
        self.nx = nx
        self.ny = ny
        self.n_elems = (self.nx - 1)*(self.ny - 1)
        self.a = a
        self.b = b
        self.load_val = load_val
        self.max_deflection = max_deflection
        self.rho = mat_data['rho']

        # ply stiffness matrices for 0, 90, +45 and -45 degrees
        E1, E2 = mat_data['E1'], mat_data['E2']
        nu12, G12 = mat_data['nu12'], mat_data['G12']
        G13, G23 = mat_data['G13'], mat_data['G23']

        num_orientations = 3

        self.Q0 = get_Q_matrix(E1, E2, nu12, G12, G13, G23, 0)
        self.Q90 = get_Q_matrix(E1, E2, nu12, G12, G13, G23, 90)
        self.Q45p = get_Q_matrix(E1, E2, nu12, G12, G13, G23, 45)
        self.Q45m = get_Q_matrix(E1, E2, nu12, G12, G13, G23, -45)
        self.Q45_sum = self.Q45p + self.Q45m

        self.eid_prop = {}

        n_var = num_orientations*self.n_elems

        self._init_fe_model()

        super().__init__(n_var=n_var, n_obj=1,
                         n_ieq_constr=1,
                         xl=h_min,
                         xu=h_max)

    def _init_fe_model(self):
        data = Quad4Data()
        probe = Quad4Probe()

        # quarter plate, 0 <= x <= a/2, 0 <= y <= b/2
        xtmp = np.linspace(0, self.a/2, self.nx)
        ytmp = np.linspace(0, self.b/2, self.ny)
        xmesh, ymesh = np.meshgrid(xtmp, ytmp)
        ncoords = np.vstack((xmesh.T.flatten(), ymesh.T.flatten(), np.zeros_like(ymesh.T.flatten()))).T
        self.ncoords = ncoords
        ncoords_flatten = ncoords.flatten()
        self.ncoords_flatten = ncoords_flatten

        nids = 1 + np.arange(ncoords.shape[0])
        nid_pos = dict(zip(nids, np.arange(len(nids))))
        nids_mesh = nids.reshape(self.nx, self.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)

        self.KC0r = np.zeros(data.KC0_SPARSE_SIZE*num_elements, dtype=INT)
        self.KC0c = np.zeros(data.KC0_SPARSE_SIZE*num_elements, dtype=INT)
        self.KC0v = np.zeros(data.KC0_SPARSE_SIZE*num_elements, dtype=DOUBLE)
        self.N = DOF*self.nx*self.ny

        self.quads = []
        init_k_KC0 = 0
        eid = -1
        for n1, n2, n3, n4 in zip(n1s, n2s, n3s, n4s):
            # placeholder property, overwritten in _evaluate
            prop = ShellProp()
            eid += 1
            self.eid_prop[eid] = prop

            quad = Quad4(probe)
            quad.eid = eid
            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(self.KC0r, self.KC0c, self.KC0v, prop)
            self.quads.append(quad)
            init_k_KC0 += data.KC0_SPARSE_SIZE

    def _evaluate(self, var, out, *args, **kwargs):
        total_volume = 0.0

        # zeroing the values of the sparse stiffness matrix before updating them
        self.KC0v *= 0

        for i, quad in enumerate(self.quads):
            prop = self.eid_prop[quad.eid]
            h0 = var[3*i]
            h45 = var[3*i + 1]
            h90 = var[3*i + 2]

            h_total = h0 + 2*h45 + h90

            # smeared stiffness
            A = (h0 * self.Q0) + (h90 * self.Q90) + (h45 * self.Q45_sum)
            D = (h_total**2 / 12.0) * A

            # membrane stiffness
            prop.A11 = A[0, 0]
            prop.A12 = A[0, 1]
            prop.A22 = A[1, 1]
            prop.A66 = A[5, 5]

            # transverse shear stiffness, with the shear correction factor 5/6
            prop.A44 = 5/6.*A[3, 3]
            prop.A45 = 5/6.*A[3, 4]
            prop.A55 = 5/6.*A[4, 4]

            # bending stiffness
            prop.D11 = D[0, 0]
            prop.D12 = D[0, 1]
            prop.D22 = D[1, 1]
            prop.D66 = D[5, 5]

            prop.h = h_total

            quad.update_probe_xe(self.ncoords_flatten)
            quad.update_KC0(self.KC0r, self.KC0c, self.KC0v, prop, update_KC0v_only=1)

            total_volume += quad.area * h_total

        KC0 = coo_matrix((self.KC0v, (self.KC0r, self.KC0c)), shape=(self.N, self.N)).tocsc()

        bk = np.zeros(self.N, dtype=bool)

        x = self.ncoords[:, 0]
        y = self.ncoords[:, 1]

        # in-plane displacements u and v restrained everywhere
        bk[0::DOF] = True
        bk[1::DOF] = True

        # simply supported edges x = 0 and y = 0
        at_edges = np.isclose(x, 0.) | np.isclose(y, 0.)
        bk[2::DOF][at_edges] = True

        # symmetry about x = a/2: rotation about y restrained
        at_sym_along_x = np.isclose(x, self.a/2)
        bk[4::DOF][at_sym_along_x] = True

        # symmetry about y = b/2: rotation about x restrained
        at_sym_along_y = np.isclose(y, self.b/2)
        bk[3::DOF][at_sym_along_y] = True

        bu = ~bk

        # point load at the centre node, one quarter of the load of the full plate
        fext = np.zeros(self.N)
        fmid = self.load_val/4
        check = np.isclose(x, self.a/2) & np.isclose(y, self.b/2)
        fext[2::DOF][check] = fmid

        KC0uu = KC0[bu, :][:, bu]

        # solving the static system
        uu = spsolve(KC0uu, fext[bu])

        u = np.zeros(self.N)
        u[bu] = uu

        # deflections in the z direction and their maximum absolute value
        self.result_w = u[2::DOF]
        w_max = np.max(np.abs(self.result_w))

        # volume of the full plate, four times that of the quarter
        out["F"] = 4*total_volume
        out["G"] = w_max/self.max_deflection - 1

Objective and constraint#

The optimisation problem reads

\[\min_{\mathbf{h}} V(\mathbf{h}) \quad \text{subject to} \quad g(\mathbf{h}) = \frac{w_{\max}(\mathbf{h})}{w_{\text{allow}}} - 1 \le 0, \qquad h_{\min} \le h_j \le h_{\max}\]

with \(V\) the volume of the plate and \(w_{\max}\) its maximum absolute deflection. scipy takes separate functions for the objective and the constraints, and its inequality constraints are written as \(c(\mathbf{h}) \ge 0\); the constraint function therefore returns \(-g\).

[4]:
def objective_function(x, problem):
    out = {}
    problem._evaluate(x, out)
    return out["F"]

def constraint_function(x, problem):
    out = {}
    problem._evaluate(x, out)
    return -out["G"]

Problem data#

A \(2 \times 1\) m plate under a central load \(P = 80\) N, with the allowed deflection \(w_{\text{allow}} = 1\) mm. The quarter model has \(13 \times 7\) nodes, i.e. \(12 \times 6\) elements and three thickness variables per element, each between \(h_{\min} = 0.125\) mm and \(h_{\max} = 2.5\) mm.

[5]:
# carbon/epoxy ply properties
mat_data = {
    'E1': 140e9,
    'E2': 10e9,
    'nu12': 0.3,
    'G12': 5e9,
    'G13': 5e9,
    'G23': 5e9,
    'rho': 1600.0
}

h_min = 0.125e-3
h_max = 2.5e-3

problem = SmearedPlateOptimization(
    nx=13, ny=7,
    a=2.0, b=1.0,
    load_val=80.0,
    max_deflection=0.001,
    h_min=h_min,
    h_max=h_max,
    mat_data=mat_data
)
print('number of elements of the quarter model:', problem.n_elems)
print('number of design variables:', problem.n_var)
number of elements of the quarter model: 72
number of design variables: 216

Optimisation with SLSQP#

SLSQP (sequential least-squares quadratic programming) solves a sequence of quadratic sub-problems built from the gradients of the objective and of the constraints. Here the gradients are approximated by forward finite differences (jac="2-point"), so each gradient costs one finite element analysis per design variable. The start design has all thicknesses at \((h_{\min} + h_{\max})/2\). The callback prints the volume and the constraint value \(g\) at each iteration.

[6]:
x0 = np.ones(problem.n_var) * (h_min + h_max) / 2.0
bounds = Bounds([h_min]*problem.n_var, [h_max]*problem.n_var)

# inequality constraint, fun(x) >= 0
cons = {'type': 'ineq', 'fun': lambda x: constraint_function(x, problem)}

iteration = 0
def print_callback(xk):
    global iteration
    iteration += 1
    out = {}
    problem._evaluate(xk, out)
    print(f"iteration {iteration}: volume = {out['F']:.4e} m^3, g = {out['G']:.4e}")

res = scipy_minimize(
    lambda x: objective_function(x, problem),
    x0,
    method='SLSQP',
    bounds=bounds,
    constraints=cons,
    callback=print_callback,
    options={'ftol': 1e-6, 'disp': True, 'maxiter': 200},
    jac="2-point"
)
iteration 1: volume = 3.6853e-03 m^3, g = 2.9718e+02
iteration 2: volume = 4.0813e-03 m^3, g = 1.1630e+02
iteration 3: volume = 4.3750e-03 m^3, g = 2.0174e+01
iteration 4: volume = 4.5795e-03 m^3, g = 1.4750e+01
iteration 5: volume = 4.7635e-03 m^3, g = 3.7677e-01
iteration 6: volume = 5.0156e-03 m^3, g = 1.1788e-01
iteration 7: volume = 4.4294e-03 m^3, g = 7.4450e-01
iteration 8: volume = 3.6435e-03 m^3, g = 4.5772e+00
iteration 9: volume = 3.9806e-03 m^3, g = 7.5188e-01
iteration 10: volume = 4.2793e-03 m^3, g = 8.1847e-02
iteration 11: volume = 4.1880e-03 m^3, g = 4.8259e-02
iteration 12: volume = 3.9463e-03 m^3, g = 3.0609e-01
iteration 13: volume = 4.1486e-03 m^3, g = 7.4797e-02
iteration 14: volume = 4.2004e-03 m^3, g = 6.2020e-03
iteration 15: volume = 4.1794e-03 m^3, g = -3.1282e-03
iteration 16: volume = 4.1626e-03 m^3, g = 6.3331e-04
iteration 17: volume = 4.1403e-03 m^3, g = 1.1737e-03
iteration 18: volume = 4.1304e-03 m^3, g = 1.1788e-06
iteration 19: volume = 4.1154e-03 m^3, g = -1.2426e-04
iteration 20: volume = 4.1112e-03 m^3, g = 2.3036e-04
iteration 21: volume = 4.1108e-03 m^3, g = 9.3608e-05
iteration 22: volume = 4.1101e-03 m^3, g = 1.2587e-04
iteration 23: volume = 4.1102e-03 m^3, g = 2.1415e-05
iteration 24: volume = 4.1102e-03 m^3, g = 1.6867e-05
iteration 25: volume = 4.1102e-03 m^3, g = 3.5762e-08
Optimization terminated successfully    (Exit mode 0)
            Current function value: 0.004110246352650484
            Iterations: 25
            Function evaluations: 5437
            Gradient evaluations: 25

Results#

The optimised design is analysed once more to print its volume and maximum deflection, and the mean thickness of each ply orientation over the elements.

[7]:
out_final = {}
problem._evaluate(res.x, out_final)
w_max = np.max(np.abs(problem.result_w))
h0_vals, h45_vals, h90_vals = res.x[0::3], res.x[1::3], res.x[2::3]
V0 = objective_function(x0, problem)

print(f"success: {res.success}, message: {res.message}")
print(f"iterations: {res.nit}, function evaluations: {res.nfev}")
print(f"volume of the start design: {V0:.4e} m^3")
print(f"volume of the optimised plate: {out_final['F']:.4e} m^3")
print(f"maximum deflection: {w_max*1e3:.4f} mm (allowed {problem.max_deflection*1e3:.1f} mm)")
print(f"constraint value g: {out_final['G']:.4e}")
print(f"mean thicknesses [mm]: h0 = {h0_vals.mean()*1e3:.4f}, h45 = {h45_vals.mean()*1e3:.4f}, "
      f"h90 = {h90_vals.mean()*1e3:.4f}")
success: True, message: Optimization terminated successfully
iterations: 25, function evaluations: 5437
volume of the start design: 1.0500e-02 m^3
volume of the optimised plate: 4.1102e-03 m^3
maximum deflection: 1.0000 mm (allowed 1.0 mm)
constraint value g: 3.5762e-08
mean thicknesses [mm]: h0 = 0.4667, h45 = 0.5173, h90 = 0.5538

Optimised design#

The figure shows, on the modelled quarter of the plate (\(x\) from the simply supported edge to the centre line at \(a/2\)), the deflection \(w\) of the optimised design and the thicknesses \(h_0\), \(h_{45}\) and \(h_{90}\) of each element.

[8]:
def plot_design(problem, h0_vals, h45_vals, h90_vals):
    nx, ny = problem.nx, problem.ny
    xg = problem.ncoords[:, 0].reshape(nx, ny)
    yg = problem.ncoords[:, 1].reshape(nx, ny)
    w = problem.result_w.reshape(nx, ny)

    fig, axes = plt.subplots(2, 2, figsize=(10, 6), constrained_layout=True)

    ax = axes[0, 0]
    cs = ax.contourf(xg, yg, w*1e3, levels=20, cmap='viridis')
    fig.colorbar(cs, ax=ax, label='$w$ [mm]')
    ax.set_title('Deflection')

    for ax, vals, name in zip([axes[0, 1], axes[1, 0], axes[1, 1]],
                              [h0_vals, h45_vals, h90_vals],
                              ['$h_0$', '$h_{45}$', '$h_{90}$']):
        # element i has the indices (ix, iy) with i = ix*(ny - 1) + iy
        vals_grid = np.asarray(vals).reshape(nx - 1, ny - 1)
        pc = ax.pcolormesh(xg, yg, vals_grid*1e3, cmap='viridis', edgecolors='k',
                           linewidth=0.3, vmin=0, vmax=np.max(vals_grid*1e3))
        fig.colorbar(pc, ax=ax, label=name + ' [mm]')
        ax.set_title('Thickness ' + name)

    for ax in axes.flatten():
        ax.set_aspect('equal')
        ax.set_xlabel('$x$ [m]')
        ax.set_ylabel('$y$ [m]')
    plt.show()


plot_design(problem, h0_vals, h45_vals, h90_vals)
../_images/notebooks_tut-opt-lightweight-smeared-deflection-SLSQP_17_0.png