Manufacturing Cost Optimizer

Project Overview & Use Case

In the corporate world, finding the “optimal” way to do something can save millions of dollars. This is called Mathematical Optimization.

The Use Case: Imagine you are a packaging engineer for Coca-Cola. You need to design a brand-new cylindrical soda can that holds exactly 330ml of liquid. However, aluminum is expensive. Your goal is to find the exact radius and height of the can that uses the absolute minimum amount of aluminum (surface area) while strictly obeying the rule that it must hold exactly 330ml of liquid.

The Output: Doing this by hand requires advanced multi-variable calculus. This script uses SciPy’s optimize.minimize module to instantly calculate the mathematically perfect dimensions for the manufacturing plant.

System Workflow (How It Works)

The Objective Function: We define a Python function representing the total surface area of a cylinder. This is what we are asking SciPy to make as small as possible.

The Constraint: We define a second Python function representing the volume. We tell SciPy that no matter what dimensions it tries, the resulting volume minus 330 must equal zero.

The Bounds: We tell SciPy that the radius and height cannot be negative numbers (you cannot manufacture a can with a negative radius).

The Engine: We pass our functions, rules, and an initial “guess” into SciPy’s minimize engine. It uses an advanced calculus algorithm to test microscopic adjustments until it finds the absolute perfect bottom of the cost curve.

Source Code

cost_optimizer.py

import numpy as np
from scipy.optimize import minimize

def calculate_surface_area(dimensions):
  """
  The Objective Function: Calculates the surface area of a cylinder.
  We want SciPy to MINIMIZE this value.
  Formula: 2 * π * r^2 (Top and Bottom) + 2 * π * r * h (The sides)
  """
  radius = dimensions[0]
  height = dimensions[1]
  
  top_and_bottom_area = 2 * np.pi * (radius ** 2)
  side_area = 2 * np.pi * radius * height
  
  total_area = top_and_bottom_area + side_area
  return total_area

def volume_constraint(dimensions):
  """
  The Constraint: The can MUST hold exactly 330 cubic centimeters (ml).
  SciPy optimization requires constraints to equal 0. 
  So, we calculate Volume - 330. When Volume is 330, the result is 0.
  Formula for Volume: π * r^2 * h
  """
  radius = dimensions[0]
  height = dimensions[1]
  
  volume = np.pi * (radius ** 2) * height
  
  # Return how far off we are from the target of 330
  return volume - 330.0

def run_optimization():
  print("⚙️ Initiating SciPy Manufacturing Optimization...")
  print("Target: 330ml Capacity. Goal: Minimize Aluminum Usage.
")

  # 1. Provide an initial guess for the algorithm to start calculating from.
  # Let's guess a radius of 5cm and a height of 10cm.
  initial_guess = [5.0, 10.0]

  # 2. Define the bounds (Radius and Height must be greater than 0.1 cm)
  # None means there is no maximum limit.
  boundaries = ((0.1, None), (0.1, None))

  # 3. Define the constraints dictionary expected by SciPy
  # 'type': 'eq' means the constraint function must equal exactly 0.
  strict_rules = {'type': 'eq', 'fun': volume_constraint}

  # 4. Run the SciPy Minimize Engine
  print("🧮 Running SLSQP Calculus Algorithm...")
  result = minimize(
      fun=calculate_surface_area, # The function to make as small as possible
      x0=initial_guess,           # Where to start guessing
      method='SLSQP',             # The specific mathematical algorithm to use
      bounds=boundaries,          # The physical size limits
      constraints=strict_rules    # The strict volume rules
  )

  # 5. Extract and format the results
  if result.success:
      optimal_radius = result.x[0]
      optimal_height = result.x[1]
      minimum_aluminum = result.fun
      
      print("
✅ OPTIMIZATION SUCCESSFUL!")
      print("-" * 40)
      print("🏆 THE MATHEMATICALLY PERFECT CAN DIMENSIONS:")
      print(f"🔹 Radius: {optimal_radius:.2f} cm")
      print(f"🔹 Height: {optimal_height:.2f} cm")
      print("-" * 40)
      print(f"📉 Minimum Aluminum Required: {minimum_aluminum:.2f} square cm")
      
      # Verify the volume
      final_volume = np.pi * (optimal_radius ** 2) * optimal_height
      print(f"💧 Final Verified Capacity:   {final_volume:.2f} ml")
      
      # Fun fact of geometry
      print("
💡 Engineering Fun Fact: Notice that the optimal Height is exactly double the optimal Radius (Height = Diameter)!")
  else:
      print("❌ Optimization failed:", result.message)

if __name__ == "__main__":
  run_optimization()
  

Code Explanation (SciPy Concepts)

The Objective Function (fun): In optimization, you always have a target you want to maximize (like profit) or minimize (like cost, time, or materials). Here, our function calculates surface area. SciPy will repeatedly call this function, passing in different numbers, trying to make the output as low as possible.

The Constraint Function (constraints): Without rules, SciPy would just say the optimal radius and height are 0.0, resulting in 0 aluminum used. The constraint forces SciPy to only consider dimensions where the volume is 330. SciPy’s engine requires this to be framed as an equation that equals zero (which is why we return Volume - 330).

minimize(): This is the powerhouse function of scipy.optimize. It takes the problem, the rules, and a starting point, and handles all the complex differential equations in the background.

method=‘SLSQP’: This stands for Sequential Least SQuares Programming. It is one of the few algorithms capable of handling both bounds (limits on variables) and constraints (strict equations that must be met) at the same time.

result.x and result.fun: When the calculation finishes, SciPy returns a specific object. result.x contains the list of winning variables (the perfect radius and height), and result.fun contains the final output of the objective function (the lowest possible surface area).

Execution Guide

Install Requirements: Open your terminal or command prompt. pip install scipy numpy

Save the file: Create a new Python file named cost_optimizer.py and paste the provided code.

Run the script: Navigate to the folder in your terminal and execute: python cost_optimizer.py

Review Output: In a fraction of a second, SciPy will perform the calculus required to find the exact engineering dimensions needed to save the company millions on packaging!