Data Analysis for Engineers/Module 3

Module 3 · Section 8 of 11

Lesson 3.7 - Optimization

Target: ~10 min read - 20 min hands-on

Overview

scipy.optimize.minimize finds the input value(s) that minimize a function you define - perfect for "least material," "lowest cost," or "minimum loss" problems. We'll minimize the sheet-metal area of an open-top cylindrical tank for a required volume.

Why This Matters (Engineering Context)

"Smallest / cheapest design that still meets the requirement" is a constrained minimization whatever the field - a tank, a heat sink, a conductor size, an order quantity. Knowing minimize turns it into a few lines.

Code-Along

from scipy.optimize import minimize
import numpy as np

# [Chemical/Mechanical] minimize the sheet area of an OPEN-TOP cylindrical tank
# for a fixed volume V = pi r^2 h, choosing the radius r (h then follows from V).
V_req = 2.0     # m^3


# The objective: minimize() always passes the variables as an ARRAY, so the
# single radius arrives as r[0]. Return the quantity we want to make smallest.
def surface_area(r):
    r = r[0]
    h = V_req / (np.pi * r ** 2)                  # height implied by the fixed volume
    return np.pi * r ** 2 + 2 * np.pi * r * h     # base area + wall area (no lid)


# x0 = starting guess; bounds keep the search in physically sensible radii
result = minimize(surface_area, x0=[0.5], bounds=[(0.1, 3.0)])
r_opt = result.x[0]                               # result.x holds the optimal variables
h_opt = V_req / (np.pi * r_opt ** 2)

print(f"Optimal radius: {r_opt:.4f} m")
print(f"Height at optimum: {h_opt:.4f} m   (h / r = {h_opt / r_opt:.2f})")
print(f"Minimum sheet area: {result.fun:.4f} m^2")   # result.fun = objective at the optimum
print(f"Converged: {result.success}")

Run it: for an open-top cylinder the optimal proportion is h / r = 1 (height equals radius) - a classic analytic result the optimizer should reproduce to a couple of decimals.

Practice Exercises

  1. Change V_req to 5.0 m^3 and re-optimize - do the optimal r and h still satisfy h / r = 1?
  2. Add a constraint that the height must not exceed 1.5 m (a headroom limit) and re-solve.
  3. Minimize the area for a closed tank instead (add a top: 2 * pi * r**2). What is the optimal h / r now?
# Try the practice exercises here

Knowledge Check

  1. What does scipy.optimize.minimize require you to define besides the objective function?
  2. What does it mean for a constraint to be "active" or "binding" at the optimum?
  3. Why are bounds useful in addition to constraints?
Answer key
  1. An objective function, and optionally constraints and/or bounds on the variables
  2. The optimal solution sits exactly at the edge of what the constraint allows
  3. Bounds keep the optimizer out of physically meaningless values during the search

30 / 63 sections · Course home · Join the coaching cohort