133 comprehensive supply chain skills covering decision framing, planning, forecasting, optimization, logistics, manufacturing, procurement, and domain-specific solutions

GitHub stars
99

Install

/plugin install supply-chain-skills@awesome-supply-chain

Run it inside Claude Code after adding the marketplace with /plugin marketplace add kishorkukreja/awesome-supply-chain.

Contents

Discovered from source

Skills 133

1D Cutting Stock Problem

You are an expert in one-dimensional cutting stock problems and linear cutting optimization. Your goal is to help minimize material waste and costs when cutting standard-length stock materials (pipes, rods, beams, paper rolls, etc.) into smaller pieces to meet customer demand.

Initial Assessment

Before solving 1D cutting stock problems, understand:

  1. Problem Characteristics

    • What material is being cut? (steel rods, pipes, lumber, paper, fabric)
    • Standard stock lengths available? (e.g., 6m, 12m, custom lengths)
    • Are multiple stock lengths available or single length?
    • Cost per stock piece or per unit length?
  2. Demand Requirements

    • How many different item lengths needed?
    • Quantity of each length? (10s, 100s, 1000s)
    • Complete list of (length, quantity) pairs?
    • Any tolerance on lengths (+/- allowance)?
  3. Cutting Constraints

    • Minimum usable piece length?
    • Maximum number of cuts per stock?
    • Kerf width (saw blade thickness/material lost per cut)?
    • Any setup costs for different cutting patterns?
  4. Optimization Objective

    • Minimize number of stock pieces used?
    • Minimize total material cost?
    • Minimize trim waste percentage?
    • Maximize utilization?
  5. Solution Requirements

    • Need exact optimal solution or fast approximation?
    • Real-time cutting (online) or batch planning (offline)?
    • Can patterns be complex or need simplicity?

1D Cutting Stock Framework

Problem Classification

1. Classical Cutting Stock Problem (CSP)

  • Single stock length
  • Multiple item lengths with demands
  • Minimize number of stocks used
  • Minimize waste

2. Multiple Stock Lengths Problem

  • Different stock lengths available
  • Each has different cost
  • Minimize total cost (not just quantity)

3. Residual Length Problem

  • Previously cut stocks with residual lengths available
  • Use residuals before cutting new stocks
  • Minimize total material consumption

4. Cutting Stock with Setup Costs

  • Each distinct cutting pattern has setup cost
  • Minimize stocks used + pattern complexity
  • Trade-off between waste and setups

5. Two-Stage Cutting

  • First cut stocks into intermediate pieces
  • Then cut intermediates into final items
  • Common in integrated production

Mathematical Formulation

Classical Cutting Stock Problem

Given:

  • L = standard stock length
  • n = number of item types
  • l_i = length of item type i (i = 1, ..., n)
  • d_i = demand for item type i

Pattern Definition: A cutting pattern j is a vector a_j = (a_1j, a_2j, ..., a_nj) where:

  • a_ij = number of items of type i cut from pattern j
  • Σ(l_i × a_ij) ≤ L (pattern feasibility)

Decision Variables:

  • x_j = number of times pattern j is used

Objective: Minimize Σ x_j (minimize total stocks used)

Constraints: Σ(a_ij × x_j) ≥ d_i for all i = 1, ..., n (meet demand) x_j ≥ 0, integer

Key Challenge:

  • Number of possible patterns is exponential
  • Cannot enumerate all patterns explicitly
  • Requires column generation technique

Algorithms and Solution Methods

Method 1: First Fit Decreasing (FFD) - Simple Heuristic

def first_fit_decreasing(items, stock_length):
    """
    First Fit Decreasing Heuristic for 1D Cutting Stock

    Fast greedy algorithm - good for quick solutions

    Parameters:
    - items: list of (length, quantity, item_id) tuples
    - stock_length: length of standard stock

    Returns: cutting plan with patterns

    Performance: Typically 10-30% above optimal
    Complexity: O(n log n + nk) where k = number of stocks used
    """

    # Expand items by quantity and sort by decreasing length
    pieces = []
    for length, quantity, item_id in items:
        for _ in range(quantity):
            pieces.append((length, item_id))

    pieces.sort(reverse=True, key=lambda x: x[0])

    # Initialize bins (stocks)
    stocks = []

    for piece_length, item_id in pieces:
        # Try to fit in existing stock
        placed = False

        for stock in stocks:
            if stock['remaining'] >= piece_length:
                stock['items'].append({
                    'length': piece_length,
                    'id': item_id
                })
                stock['remaining'] -= piece_length
                placed = True
                break

        # Need new stock
        if not placed:
            new_stock = {
                'items': [{
                    'length': piece_length,
                    'id': item_id
                }],
                'remaining': stock_length - piece_length
            }
            stocks.append(new_stock)

    # Calculate statistics
    total_used = sum(stock_length - s['remaining'] for s in stocks)
    total_available = len(stocks) * stock_length
    utilization = (total_used / total_available * 100) if total_available > 0 else 0

    return {
        'num_stocks': len(stocks),
        'stocks': stocks,
        'utilization': utilization,
        'waste': total_available - total_used
    }


# Example usage
items = [
    (2300, 5, 'A'),  # 5 pieces of 2300mm
    (1500, 8, 'B'),  # 8 pieces of 1500mm
    (1200, 12, 'C'), # 12 pieces of 1200mm
    (800, 6, 'D')    # 6 pieces of 800mm
]
stock_length = 6000

result = first_fit_decreasing(items, stock_length)
print(f"Stocks needed: {result['num_stocks']}")
print(f"Utilization: {result['utilization']:.2f}%")
print(f"Waste: {result['waste']}mm")

Method 2: Best Fit Decreasing (BFD) - Improved Heuristic

def best_fit_decreasing(items, stock_length):
    """
    Best Fit Decreasing Heuristic

    Better than FFD - finds tightest fit to minimize waste

    Parameters:
    - items: list of (length, quantity, item_id) tuples
    - stock_length: length of standard stock

    Returns: cutting plan

    Performance: Typically 5-20% above optimal
    """

    # Expand and sort pieces
    pieces = []
    for length, quantity, item_id in items:
        for _ in range(quantity):
            pieces.append((length, item_id))

    pieces.sort(reverse=True, key=lambda x: x[0])

    stocks = []

    for piece_length, item_id in pieces:
        # Find best fitting stock (minimum remaining space after placement)
        best_stock_idx = None
        min_remaining = float('inf')

        for idx, stock in enumerate(stocks):
            if stock['remaining'] >= piece_length:
                remaining_after = stock['remaining'] - piece_length
                if remaining_after < min_remaining:
                    min_remaining = remaining_after
                    best_stock_idx = idx

        if best_stock_idx is not None:
            # Place in best fitting stock
            stocks[best_stock_idx]['items'].append({
                'length': piece_length,
                'id': item_id
            })
            stocks[best_stock_idx]['remaining'] -= piece_length
        else:
            # Create new stock
            new_stock = {
                'items': [{
                    'length': piece_length,
                    'id': item_id
                }],
                'remaining': stock_length - piece_length
            }
            stocks.append(new_stock)

    # Calculate statistics
    total_used = sum(stock_length - s['remaining'] for s in stocks)
    total_available = len(stocks) * stock_length

    return {
        'num_stocks': len(stocks),
        'stocks': stocks,
        'utilization': (total_used / total_available * 100) if total_available > 0 else 0,
        'waste': total_available - total_used
    }

Method 3: Column Generation - Optimal Solution

from pulp import *
import numpy as np

class ColumnGenerationCuttingStock:
    """
    Column Generation for 1D Cutting Stock Problem

    Finds optimal or near-optimal solution using:
    1. Master Problem (LP): Select best patterns
    2. Pricing Problem (Knapsack): Generate new profitable patterns

    This is the state-of-the-art exact method for cutting stock
    """

    def __init__(self, stock_length, items, kerf=0):
        """
        Initialize cutting stock problem

        Parameters:
        - stock_length: length of standard stock
        - items: list of (length, demand, item_id) tuples
        - kerf: material lost per cut (saw blade width)
        """
        self.stock_length = stock_length
        self.items = items
        self.kerf = kerf
        self.n_items = len(items)

        # Extract lengths and demands
        self.lengths = [item[0] for item in items]
        self.demands = [item[1] for item in items]
        self.item_ids = [item[2] for item in items]

        # Storage for patterns
        self.patterns = []
        self.pattern_count = 0

    def generate_initial_patterns(self):
        """
        Generate initial patterns (one item type per pattern)
        Each pattern cuts maximum number of one item type
        """
        initial_patterns = []

        for i in range(self.n_items):
            pattern = [0] * self.n_items
            # Maximum number of item i that fits in one stock
            max_fit = int(self.stock_length / (self.lengths[i] + self.kerf))
            pattern[i] = max_fit
            initial_patterns.append(pattern)

        self.patterns = initial_patterns
        return initial_patterns

    def solve_master_problem(self):
        """
        Solve Master Problem (Restricted)

        Linear Programming Relaxation:
        Minimize Σ x_j
        Subject to: Σ(a_ij × x_j) ≥ d_i for all i
                    x_j ≥ 0

        Returns: solution and dual values
        """

        prob = LpProblem("Cutting_Stock_Master", LpMinimize)

        # Decision variables: x_j = number of times pattern j is used
        num_patterns = len(self.patterns)
        x = [LpVariable(f"x_{j}", lowBound=0, cat='Continuous')
             for j in range(num_patterns)]

        # Objective: minimize total stocks used
        prob += lpSum(x), "Total_Stocks"

        # Constraints: meet demand for each item type
        constraints = []
        for i in range(self.n_items):
            constraint = lpSum(self.patterns[j][i] * x[j]
                             for j in range(num_patterns)) >= self.demands[i]
            prob += constraint, f"Demand_{i}"
            constraints.append(constraint)

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract solution
        solution = {
            'objective': value(prob.objective),
            'pattern_usage': [x[j].varValue for j in range(num_patterns)],
            'status': LpStatus[prob.status]
        }

        # Extract dual values (shadow prices)
        dual_values = []
        for i in range(self.n_items):
            constraint_name = f"Demand_{i}"
            for name, constraint in prob.constraints.items():
                if constraint_name in name:
                    dual_values.append(constraint.pi)
                    break

        solution['dual_values'] = dual_values

        return solution

    def solve_pricing_problem(self, dual_values):
        """
        Solve Pricing Problem (Knapsack)

        Find new pattern with negative reduced cost:
        max Σ(π_i × a_i)
        subject to: Σ(l_i × a_i) ≤ L
                    a_i ≥ 0, integer

        This is a 0/1 knapsack variant (unbounded knapsack)

        Parameters:
        - dual_values: dual values from master problem (π_i)

        Returns: new pattern if found, None otherwise
        """

        # Solve unbounded knapsack
        # dp[w] = maximum value achievable with weight w
        capacity = self.stock_length
        dp = [0] * (capacity + 1)
        item_used = [[-1, 0] for _ in range(capacity + 1)]  # [item_idx, count]

        for w in range(1, capacity + 1):
            for i in range(self.n_items):
                item_length = self.lengths[i] + self.kerf
                if item_length <= w:
                    value = dp[w - item_length] + dual_values[i]
                    if value > dp[w]:
                        dp[w] = value
                        item_used[w] = [i, 1]

        # Check if new pattern is profitable (reduced cost < 0)
        # Reduced cost = 1 - max_value
        max_value = dp[capacity]
        reduced_cost = 1 - max_value

        if reduced_cost >= -1e-6:  # No profitable pattern found
            return None

        # Backtrack to find pattern
        new_pattern = [0] * self.n_items
        w = capacity

        while w > 0 and item_used[w][0] != -1:
            item_idx = item_used[w][0]
            # Count how many of this item in the pattern
            temp_w = w
            count = 0
            while temp_w > 0 and item_used[temp_w][0] == item_idx:
                count += 1
                item_length = self.lengths[item_idx] + self.kerf
                temp_w -= item_length

            new_pattern[item_idx] += count
            w = temp_w

        # Alternative: use proper unbounded knapsack backtracking
        new_pattern = self._knapsack_backtrack(dual_values)

        return new_pattern

    def _knapsack_backtrack(self, values):
        """
        Solve unbounded knapsack properly and backtrack
        """
        capacity = self.stock_length
        dp = [0] * (capacity + 1)
        used_item = [-1] * (capacity + 1)

        for w in range(1, capacity + 1):
            for i in range(self.n_items):
                item_length = self.lengths[i] + self.kerf
                if item_length <= w:
                    new_value = dp[w - item_length] + values[i]
                    if new_value > dp[w]:
                        dp[w] = new_value
                        used_item[w] = i

        # Backtrack
        pattern = [0] * self.n_items
        w = capacity

        while w > 0 and used_item[w] != -1:
            i = used_item[w]
            pattern[i] += 1
            w -= (self.lengths[i] + self.kerf)

        return pattern

    def solve(self, max_iterations=100, tolerance=1e-6):
        """
        Solve cutting stock problem using column generation

        Algorithm:
        1. Start with initial patterns
        2. Solve master problem (LP)
        3. Get dual values
        4. Solve pricing problem to generate new pattern
        5. If profitable pattern found, add to master and repeat
        6. Otherwise, solve master as IP for integer solution

        Returns: optimal cutting plan
        """

        # Generate initial patterns
        self.generate_initial_patterns()

        print("Starting Column Generation...")
        print(f"Items: {self.n_items}")
        print(f"Total demand: {sum(self.demands)}")
        print(f"Stock length: {self.stock_length}")
        print()

        iteration = 0

        while iteration < max_iterations:
            iteration += 1

            # Solve master problem
            master_solution = self.solve_master_problem()

            if master_solution['status'] != 'Optimal':
                print(f"Warning: Master problem not optimal: {master_solution['status']}")
                break

            dual_values = master_solution['dual_values']

            print(f"Iteration {iteration}: LP Objective = {master_solution['objective']:.2f}")

            # Solve pricing problem
            new_pattern = self.solve_pricing_problem(dual_values)

            if new_pattern is None:
                print("No more profitable patterns. LP optimal.")
                break

            # Add new pattern
            self.patterns.append(new_pattern)
            print(f"  Added pattern: {new_pattern}")

        # Solve master problem as Integer Program for final solution
        print("\nSolving integer program for final solution...")
        integer_solution = self.solve_master_ip()

        return integer_solution

    def solve_master_ip(self):
        """
        Solve Master Problem as Integer Program

        Get integer solution from LP relaxation
        """

        prob = LpProblem("Cutting_Stock_IP", LpMinimize)

        num_patterns = len(self.patterns)
        x = [LpVariable(f"x_{j}", lowBound=0, cat='Integer')
             for j in range(num_patterns)]

        # Objective
        prob += lpSum(x), "Total_Stocks"

        # Constraints
        for i in range(self.n_items):
            prob += (lpSum(self.patterns[j][i] * x[j] for j in range(num_patterns))
                    >= self.demands[i]), f"Demand_{i}"

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract solution
        pattern_usage = [x[j].varValue for j in range(num_patterns)]

        # Build cutting plan
        stocks = []
        for j, usage in enumerate(pattern_usage):
            if usage and usage > 0.5:
                for _ in range(int(usage)):
                    stock = {
                        'pattern_id': j,
                        'pattern': self.patterns[j],
                        'items': []
                    }

                    # Add items according to pattern
                    for i in range(self.n_items):
                        if self.patterns[j][i] > 0:
                            for _ in range(self.patterns[j][i]):
                                stock['items'].append({
                                    'length': self.lengths[i],
                                    'id': self.item_ids[i]
                                })

                    # Calculate utilization
                    total_length = sum(item['length'] for item in stock['items'])
                    stock['used_length'] = total_length
                    stock['waste'] = self.stock_length - total_length

                    stocks.append(stock)

        total_used = sum(s['used_length'] for s in stocks)
        total_available = len(stocks) * self.stock_length

        solution = {
            'num_stocks': int(value(prob.objective)),
            'stocks': stocks,
            'patterns': self.patterns,
            'pattern_usage': pattern_usage,
            'utilization': (total_used / total_available * 100) if total_available > 0 else 0,
            'total_waste': total_available - total_used,
            'status': LpStatus[prob.status]
        }

        print(f"\nOptimal solution found!")
        print(f"Stocks needed: {solution['num_stocks']}")
        print(f"Utilization: {solution['utilization']:.2f}%")
        print(f"Total waste: {solution['total_waste']}")

        return solution


# Example usage
def example_column_generation():
    """Example: Cutting steel rods"""

    # Items: (length, quantity, id)
    items = [
        (2300, 5, 'A'),   # 5 pieces of 2300mm
        (1500, 8, 'B'),   # 8 pieces of 1500mm
        (1200, 12, 'C'),  # 12 pieces of 1200mm
        (800, 6, 'D'),    # 6 pieces of 800mm
        (600, 10, 'E')    # 10 pieces of 600mm
    ]

    stock_length = 6000  # 6 meter standard stock
    kerf = 5  # 5mm saw blade width

    solver = ColumnGenerationCuttingStock(stock_length, items, kerf)
    solution = solver.solve()

    # Print detailed results
    print("\n" + "="*70)
    print("CUTTING PLAN")
    print("="*70)

    for idx, stock in enumerate(solution['stocks']):
        print(f"\nStock {idx+1}:")
        print(f"  Pattern: {stock['pattern']}")
        print(f"  Items: {[f\"{item['id']}({item['length']})\" for item in stock['items']]}")
        print(f"  Used: {stock['used_length']}mm")
        print(f"  Waste: {stock['waste']}mm ({stock['waste']/stock_length*100:.1f}%)")

    return solution

Method 4: Dynamic Programming - Small Problems

def cutting_stock_dp_small(items, stock_length, max_stocks=None):
    """
    Dynamic Programming approach for small cutting stock problems

    Only practical for small problems due to exponential state space

    Parameters:
    - items: list of (length, quantity, item_id)
    - stock_length: standard stock length
    - max_stocks: maximum number of stocks to consider

    Returns: optimal solution

    Limitation: Only works for small problems (total items < 30)
    """

    # Expand items
    pieces = []
    for length, quantity, item_id in items:
        for _ in range(quantity):
            pieces.append((length, item_id))

    n = len(pieces)

    if n > 30:
        raise ValueError("Problem too large for DP approach. Use column generation.")

    if max_stocks is None:
        max_stocks = n  # Worst case

    # State: (items_packed_bitmask, number_of_stocks)
    # Value: True if achievable, False otherwise

    from functools import lru_cache

    @lru_cache(maxsize=None)
    def can_pack(remaining_mask, num_stocks):
        """Check if remaining items can be packed in num_stocks"""

        if remaining_mask == 0:
            return True

        if num_stocks == 0:
            return False

        # Try all possible patterns for next stock
        # Enumerate all subsets of remaining items that fit in one stock
        for pattern_mask in range(1, remaining_mask + 1):
            if (pattern_mask & remaining_mask) != pattern_mask:
                continue

            # Check if pattern fits in one stock
            total_length = 0
            for i in range(n):
                if pattern_mask & (1 << i):
                    total_length += pieces[i][0]

            if total_length <= stock_length:
                # Try this pattern
                new_remaining = remaining_mask & ~pattern_mask
                if can_pack(new_remaining, num_stocks - 1):
                    return True

        return False

    # Find minimum number of stocks needed
    initial_mask = (1 << n) - 1  # All items need to be packed

    for num_stocks in range(1, max_stocks + 1):
        if can_pack(initial_mask, num_stocks):
            return {
                'min_stocks': num_stocks,
                'method': 'DP (exact)',
                'note': 'Optimal solution'
            }

    return None

Complete 1D Cutting Stock Solver

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

class OneDCuttingStockSolver:
    """
    Comprehensive 1D Cutting Stock Solver

    Supports multiple solution methods:
    - Fast heuristics (FFD, BFD)
    - Optimal column generation
    - Visualization
    """

    def __init__(self, stock_length, kerf=0):
        """
        Initialize solver

        Parameters:
        - stock_length: length of standard stock material
        - kerf: material lost per cut (saw blade width)
        """
        self.stock_length = stock_length
        self.kerf = kerf
        self.items = []
        self.solution = None

    def add_item(self, length, quantity, item_id=None):
        """Add item to cutting list"""
        if item_id is None:
            item_id = f"Item_{len(self.items)}"

        self.items.append((length, quantity, item_id))

    def add_items(self, items_list):
        """
        Add multiple items

        items_list: list of (length, quantity) or (length, quantity, id)
        """
        for item in items_list:
            if len(item) == 2:
                self.add_item(item[0], item[1])
            else:
                self.add_item(item[0], item[1], item[2])

    def solve(self, method='column_generation', **kwargs):
        """
        Solve cutting stock problem

        Methods:
        - 'ffd': First Fit Decreasing (fast)
        - 'bfd': Best Fit Decreasing (better)
        - 'column_generation': Optimal or near-optimal

        Returns: solution dictionary
        """

        if method == 'ffd':
            self.solution = first_fit_decreasing(self.items, self.stock_length)
            self.solution['method'] = 'First Fit Decreasing'

        elif method == 'bfd':
            self.solution = best_fit_decreasing(self.items, self.stock_length)
            self.solution['method'] = 'Best Fit Decreasing'

        elif method == 'column_generation':
            cg_solver = ColumnGenerationCuttingStock(
                self.stock_length, self.items, self.kerf
            )
            self.solution = cg_solver.solve(**kwargs)
            self.solution['method'] = 'Column Generation (Optimal)'

        else:
            raise ValueError(f"Unknown method: {method}")

        return self.solution

    def visualize(self, max_stocks=10, save_path=None):
        """
        Visualize cutting patterns

        Parameters:
        - max_stocks: maximum number of stocks to display
        - save_path: path to save figure
        """

        if self.solution is None:
            raise ValueError("No solution to visualize. Run solve() first.")

        stocks_to_show = min(max_stocks, len(self.solution['stocks']))

        fig, axes = plt.subplots(stocks_to_show, 1,
                                figsize=(12, stocks_to_show * 0.8))

        if stocks_to_show == 1:
            axes = [axes]

        colors = plt.cm.tab20(np.linspace(0, 1, 20))

        for idx in range(stocks_to_show):
            ax = axes[idx]
            stock = self.solution['stocks'][idx]

            # Draw stock boundary
            ax.add_patch(patches.Rectangle(
                (0, 0), self.stock_length, 1,
                fill=False, edgecolor='black', linewidth=2
            ))

            # Draw pieces
            current_pos = 0
            for item_idx, item in enumerate(stock['items']):
                color = colors[hash(item['id']) % 20]

                # Draw piece
                ax.add_patch(patches.Rectangle(
                    (current_pos, 0), item['length'], 1,
                    facecolor=color, edgecolor='black',
                    linewidth=1, alpha=0.7
                ))

                # Add label
                center_x = current_pos + item['length'] / 2
                ax.text(center_x, 0.5, f"{item['id']}\n{item['length']}",
                       ha='center', va='center',
                       fontsize=8, fontweight='bold')

                current_pos += item['length']

            # Draw waste area
            if current_pos < self.stock_length:
                waste = self.stock_length - current_pos
                ax.add_patch(patches.Rectangle(
                    (current_pos, 0), waste, 1,
                    facecolor='gray', edgecolor='black',
                    linewidth=1, alpha=0.3, hatch='//'
                ))
                ax.text(current_pos + waste/2, 0.5, f"Waste\n{waste}",
                       ha='center', va='center',
                       fontsize=7, style='italic')

            ax.set_xlim(0, self.stock_length)
            ax.set_ylim(0, 1)
            ax.set_aspect('auto')
            ax.set_title(f'Stock {idx+1} (Used: {current_pos}, Waste: {self.stock_length-current_pos})',
                        fontsize=10)
            ax.set_xlabel('Length')
            ax.set_yticks([])
            ax.grid(True, alpha=0.3, axis='x')

        plt.suptitle(
            f'1D Cutting Stock Solution - {self.solution["method"]}\n'
            f'Stocks Used: {self.solution["num_stocks"]} | '
            f'Utilization: {self.solution["utilization"]:.1f}%',
            fontsize=14, fontweight='bold'
        )

        plt.tight_layout()

        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')

        plt.show()

    def print_solution(self):
        """Print detailed solution summary"""

        if self.solution is None:
            print("No solution available.")
            return

        print("=" * 80)
        print("1D CUTTING STOCK SOLUTION")
        print("=" * 80)
        print(f"Method: {self.solution['method']}")
        print(f"Stock length: {self.stock_length}")
        print(f"Stocks used: {self.solution['num_stocks']}")
        print(f"Utilization: {self.solution['utilization']:.2f}%")
        print(f"Total waste: {self.solution.get('total_waste', self.solution.get('waste', 0))}")
        print()

        print("CUTTING PATTERNS:")
        print("-" * 80)

        for idx, stock in enumerate(self.solution['stocks'][:20]):  # Show first 20
            items_str = ", ".join([f"{item['id']}({item['length']})"
                                  for item in stock['items']])
            waste = self.stock_length - sum(item['length'] for item in stock['items'])
            print(f"Stock {idx+1:3d}: {items_str:50s} | Waste: {waste}")

        if len(self.solution['stocks']) > 20:
            print(f"... and {len(self.solution['stocks']) - 20} more stocks")

        print()

        # Item summary
        print("ITEM SUMMARY:")
        print("-" * 80)
        for length, quantity, item_id in self.items:
            print(f"{item_id}: {quantity} pieces × {length} = {quantity * length} total length")

    def export_cutting_list(self, filename):
        """Export cutting list to CSV"""

        if self.solution is None:
            raise ValueError("No solution to export. Run solve() first.")

        import csv

        with open(filename, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(['Stock #', 'Item ID', 'Length', 'Position', 'Stock Waste'])

            for stock_idx, stock in enumerate(self.solution['stocks']):
                position = 0
                waste = self.stock_length - sum(item['length'] for item in stock['items'])

                for item in stock['items']:
                    writer.writerow([
                        stock_idx + 1,
                        item['id'],
                        item['length'],
                        position,
                        waste if position == 0 else ''
                    ])
                    position += item['length']

        print(f"Cutting list exported to {filename}")


# Example usage
if __name__ == "__main__":

    print("Example 1: Steel Rod Cutting")
    print("=" * 80)

    # Create solver
    solver = OneDCuttingStockSolver(stock_length=6000, kerf=5)

    # Add items to cut
    solver.add_items([
        (2300, 5, 'A'),   # 5 pieces of 2300mm
        (1500, 8, 'B'),   # 8 pieces of 1500mm
        (1200, 12, 'C'),  # 12 pieces of 1200mm
        (800, 6, 'D'),    # 6 pieces of 800mm
        (600, 10, 'E')    # 10 pieces of 600mm
    ])

    # Solve using column generation (optimal)
    print("\nSolving with Column Generation (optimal)...")
    solution = solver.solve(method='column_generation')
    solver.print_solution()

    # Visualize
    solver.visualize(max_stocks=5)

    # Export cutting list
    solver.export_cutting_list('cutting_list.csv')

    print("\n" + "=" * 80)
    print("Example 2: Compare Methods")
    print("=" * 80)

    # Compare different methods
    methods = ['ffd', 'bfd', 'column_generation']
    results = {}

    for method in methods:
        solver2 = OneDCuttingStockSolver(stock_length=6000)
        solver2.add_items([
            (2300, 5, 'A'),
            (1500, 8, 'B'),
            (1200, 12, 'C'),
            (800, 6, 'D')
        ])

        solution = solver2.solve(method=method)
        results[method] = {
            'stocks': solution['num_stocks'],
            'utilization': solution['utilization']
        }

    print("\nMethod Comparison:")
    print("-" * 60)
    print(f"{'Method':<25} {'Stocks':<10} {'Utilization':<15}")
    print("-" * 60)
    for method, result in results.items():
        print(f"{method:<25} {result['stocks']:<10} {result['utilization']:<15.2f}%")

Tools & Libraries

Python Libraries

PuLP - Linear Programming

pip install pulp

Google OR-Tools - Comprehensive optimization

from ortools.linear_solver import pywraplp

# OR-Tools has built-in cutting stock examples

SciPy - Optimization toolkit

from scipy.optimize import linprog

pycutstock - Cutting stock specialized library

pip install pycutstock

Commercial Software

  • CutList Plus - Professional cutting optimizer
  • OptiCut - 1D/2D cutting optimization
  • Cutting Optimization Pro - Multi-material cutting
  • MaxCut - Industrial cutting stock software

Online Tools

  • Cut List Optimizer - Free web-based
  • Cut List Calculator - Simple cutting planner

Common Challenges & Solutions

Challenge: Large Number of Items

Problem:

  • Hundreds or thousands of items
  • Column generation too slow
  • Many patterns to consider

Solutions:

  • Use FFD/BFD for initial quick solution
  • Apply column generation with time limit
  • Group similar lengths together
  • Use parallel pattern generation
  • Implement pattern pool management

Challenge: Multiple Stock Lengths

Problem:

  • Different stock lengths available
  • Each has different cost
  • Must choose which stock to use

Solutions:

def multi_length_cutting_stock(items, stock_specs):
    """
    Solve cutting stock with multiple stock lengths

    Parameters:
    - items: list of (length, quantity, id)
    - stock_specs: list of (length, cost, availability)

    Returns: solution minimizing total cost
    """

    from pulp import *

    # For each stock type, generate patterns
    all_patterns = []
    pattern_costs = []
    pattern_stock_type = []

    for stock_idx, (stock_length, stock_cost, availability) in enumerate(stock_specs):
        # Generate patterns for this stock length
        # (simplified - use proper pattern generation)
        patterns = generate_patterns_for_stock(items, stock_length)

        for pattern in patterns:
            all_patterns.append(pattern)
            pattern_costs.append(stock_cost)
            pattern_stock_type.append(stock_idx)

    # Solve with cost objective
    prob = LpProblem("Multi_Stock_Cutting", LpMinimize)

    n_patterns = len(all_patterns)
    x = [LpVariable(f"x_{j}", lowBound=0, cat='Integer')
         for j in range(n_patterns)]

    # Objective: minimize total cost
    prob += lpSum(pattern_costs[j] * x[j] for j in range(n_patterns))

    # Demand constraints
    n_items = len(items)
    for i in range(n_items):
        prob += lpSum(all_patterns[j][i] * x[j]
                     for j in range(n_patterns)) >= items[i][1]

    # Availability constraints
    for stock_idx in range(len(stock_specs)):
        if stock_specs[stock_idx][2] is not None:  # If availability limited
            prob += lpSum(x[j] for j in range(n_patterns)
                         if pattern_stock_type[j] == stock_idx) <= stock_specs[stock_idx][2]

    prob.solve(PULP_CBC_CMD(msg=0))

    return {
        'total_cost': value(prob.objective),
        'pattern_usage': [x[j].varValue for j in range(n_patterns)]
    }

def generate_patterns_for_stock(items, stock_length):
    """Generate feasible patterns for a given stock length"""
    # Simplified pattern generation
    patterns = []
    # Implementation similar to column generation pricing problem
    return patterns

Challenge: Residual/Leftover Management

Problem:

  • Previously cut stocks with leftovers
  • Want to use residuals before cutting new stock
  • Inventory of various length leftovers

Solutions:

def cutting_with_residuals(items, stock_length, residuals):
    """
    Cutting stock considering existing residual pieces

    Parameters:
    - items: list of (length, quantity, id)
    - stock_length: new stock length
    - residuals: list of (length, quantity) of leftover pieces

    Strategy:
    1. First try to satisfy demand from residuals
    2. Then cut new stock for remaining demand
    """

    # Step 1: Allocate residuals using FFD
    remaining_items = []

    for item_length, item_qty, item_id in items:
        qty_needed = item_qty

        # Try to use residuals
        for res_idx, (res_length, res_qty) in enumerate(residuals):
            if res_length >= item_length and res_qty > 0:
                use_qty = min(qty_needed, res_qty)
                residuals[res_idx] = (res_length, res_qty - use_qty)
                qty_needed -= use_qty

                if qty_needed == 0:
                    break

        if qty_needed > 0:
            remaining_items.append((item_length, qty_needed, item_id))

    # Step 2: Cut new stock for remaining items
    if remaining_items:
        solution = first_fit_decreasing(remaining_items, stock_length)
    else:
        solution = {'num_stocks': 0, 'stocks': []}

    return {
        'new_stocks_needed': solution['num_stocks'],
        'residuals_used': sum(r[1] for r in residuals if r[1] > 0),
        'solution': solution
    }

Challenge: Setup Costs and Pattern Complexity

Problem:

  • Different cutting patterns require different setup
  • Trade-off between waste and number of patterns
  • Prefer simpler patterns

Solutions:

  • Modify objective: minimize (stocks + α × num_patterns)
  • Add pattern complexity penalty
  • Limit number of distinct patterns
  • Use pattern repetition bonus

Output Format

Cutting Stock Solution Report

Problem Summary:

  • Material: Steel rods
  • Stock length: 6000mm
  • Saw kerf: 5mm
  • Total items: 41 pieces (5 different lengths)
  • Total length needed: 51,400mm

Solution:

  • Method: Column Generation (Optimal)
  • Stocks used: 12
  • Total material: 72,000mm
  • Material utilized: 51,400mm (71.4%)
  • Total waste: 20,600mm (28.6%)
  • Average waste per stock: 1,717mm

Cutting Patterns:

PatternUsageItemsWasteEfficiency
132×2300, 1×1200195mm96.8%
243×1500, 1×800200mm96.7%
324×1200, 1×600595mm90.1%
436×8001,200mm80.0%

Detailed Cutting List:

Stock 1: A(2300) A(2300) C(1200) | Waste: 195mm
Stock 2: A(2300) A(2300) C(1200) | Waste: 195mm
Stock 3: A(2300) A(2300) C(1200) | Waste: 195mm
Stock 4: B(1500) B(1500) B(1500) D(800) | Waste: 200mm
...

Material Cost Analysis:

  • Cost per stock: $45.00
  • Total material cost: $540.00
  • Waste cost: $154.50 (28.6%)
  • Cost per item: $13.17

Questions to Ask

If you need more context:

  1. What material are you cutting? (steel, wood, pipe, paper, fabric)
  2. What is the standard stock length(s)?
  3. What items do you need? (list of lengths and quantities)
  4. Is there a saw blade kerf/cutting width to account for?
  5. Do you have any leftover pieces to use first?
  6. Is there a minimum usable piece length?
  7. What's more important: minimizing stocks or minimizing waste percentage?
  8. Do you need the optimal solution or is a fast good solution okay?
  9. Are there multiple stock lengths available with different costs?
  10. Will this be a one-time cut or recurring production?

Related Skills

  • 2d-cutting-stock: For two-dimensional sheet cutting
  • guillotine-cutting: For guillotine cutting constraints
  • nesting-optimization: For irregular shape nesting
  • trim-loss-minimization: For general trim loss optimization
  • knapsack-problems: For value-based cutting optimization
  • column-generation: For advanced pattern generation techniques
  • optimization-modeling: For general optimization problem formulation

2D Bin Packing

You are an expert in 2D bin packing and rectangular packing optimization. Your goal is to help pack rectangular items into 2D bins or sheets while minimizing waste, number of bins used, or maximizing space utilization.

Initial Assessment

Before solving 2D bin packing problems, understand:

  1. Problem Type

    • Pack into fixed-size bins (minimize bins used)?
    • Pack into variable-size bins (minimize total area)?
    • Single large bin (maximize utilization)?
    • Cutting from sheets (minimize waste)?
  2. Item Characteristics

    • How many items to pack? (10s, 100s, 1000s)
    • Item dimensions: width x height
    • Can items be rotated? (90-degree rotation allowed?)
    • Are items all different or some identical?
    • Any item priorities or grouping requirements?
  3. Bin/Sheet Specifications

    • Bin dimensions: width x height
    • Fixed or variable bin sizes?
    • Unlimited bins or limited quantity?
    • Any margin/spacing requirements between items?
  4. Cutting Constraints

    • Guillotine cuts only? (straight cuts across entire sheet)
    • Free-form packing allowed?
    • Maximum number of cutting stages?
    • Trim loss acceptable?
  5. Optimization Objective

    • Minimize number of bins used?
    • Minimize total area/material cost?
    • Maximize utilization percentage?
    • Minimize cutting complexity?

2D Bin Packing Framework

Problem Classification

1. 2D Bin Packing Problem (2D-BPP)

  • Pack rectangles into minimum number of identical bins
  • All items must be packed
  • Items cannot overlap
  • Items typically axis-aligned

2. 2D Strip Packing Problem

  • Fixed width, minimize height
  • Single strip (bin with infinite height)
  • Minimize total height used

3. 2D Cutting Stock Problem

  • Cut items from larger sheets
  • Minimize material waste
  • Often with guillotine constraints

4. Rectangle Packing Problem

  • Pack into single large rectangle
  • Maximize number of items packed
  • Or maximize space utilization

5. Two-Dimensional Knapsack

  • Items have values
  • Maximize total value in fixed bin
  • Items may not all fit

Mathematical Formulation

Basic 2D Bin Packing Model

Decision Variables:

  • x_i, y_i = coordinates of item i's bottom-left corner
  • b_i = bin number assigned to item i
  • w_j = 1 if bin j is used, 0 otherwise
  • r_i = 1 if item i is rotated, 0 otherwise

Objective: Minimize ∑ w_j (minimize bins used)

Constraints:

  1. Non-overlap: items in same bin don't overlap
  2. Containment: items fit within bin boundaries
  3. Assignment: each item assigned to exactly one bin
  4. Rotation (optional): items can be rotated 90°

Complexity:

  • NP-hard problem
  • No polynomial-time optimal algorithm (unless P=NP)
  • Requires heuristic or metaheuristic approaches

Algorithms and Solution Methods

Exact Methods

Branch and Bound

  • Guarantees optimal solution
  • Only practical for small problems (<20-30 items)
  • Exponential time complexity

Integer Programming Formulation

from pulp import *

def solve_2d_bin_packing_ip(items, bin_width, bin_height, max_bins=None):
    """
    2D Bin Packing using Integer Programming

    Parameters:
    - items: list of (width, height) tuples
    - bin_width: width of each bin
    - bin_height: height of each bin
    - max_bins: maximum number of bins to consider

    Returns optimal packing solution

    Note: Only practical for small problems (<20 items)
    """

    n = len(items)
    if max_bins is None:
        max_bins = n  # Worst case: one item per bin

    bins = range(max_bins)
    item_ids = range(n)

    # Create problem
    prob = LpProblem("2D_Bin_Packing", LpMinimize)

    # Decision variables
    # x[i,b] = x coordinate of item i in bin b
    x = LpVariable.dicts("x",
                        [(i, b) for i in item_ids for b in bins],
                        lowBound=0, upBound=bin_width, cat='Continuous')

    # y[i,b] = y coordinate of item i in bin b
    y = LpVariable.dicts("y",
                        [(i, b) for i in item_ids for b in bins],
                        lowBound=0, upBound=bin_height, cat='Continuous')

    # a[i,b] = 1 if item i assigned to bin b
    a = LpVariable.dicts("assign",
                        [(i, b) for i in item_ids for b in bins],
                        cat='Binary')

    # w[b] = 1 if bin b is used
    w = LpVariable.dicts("use_bin", bins, cat='Binary')

    # Objective: minimize number of bins
    prob += lpSum([w[b] for b in bins]), "Total_Bins"

    # Constraints

    # 1. Each item assigned to exactly one bin
    for i in item_ids:
        prob += lpSum([a[i,b] for b in bins]) == 1, f"Assign_{i}"

    # 2. Item fits within bin boundaries
    for i in item_ids:
        for b in bins:
            prob += x[i,b] + items[i][0] <= bin_width + (1 - a[i,b]) * bin_width, \
                    f"Fit_Width_{i}_{b}"
            prob += y[i,b] + items[i][1] <= bin_height + (1 - a[i,b]) * bin_height, \
                    f"Fit_Height_{i}_{b}"

    # 3. Bin is used if any item assigned to it
    for b in bins:
        for i in item_ids:
            prob += a[i,b] <= w[b], f"Bin_Used_{i}_{b}"

    # 4. Non-overlapping constraints (simplified - full version more complex)
    # This is a simplified model; full non-overlap requires additional binary variables

    # Solve
    status = prob.solve(PULP_CBC_CMD(msg=1, timeLimit=300))

    if LpStatus[status] != 'Optimal':
        return None

    # Extract solution
    solution = {
        'num_bins': int(value(prob.objective)),
        'bins': []
    }

    for b in bins:
        if w[b].varValue > 0.5:
            bin_items = []
            for i in item_ids:
                if a[i,b].varValue > 0.5:
                    bin_items.append({
                        'item_id': i,
                        'x': x[i,b].varValue,
                        'y': y[i,b].varValue,
                        'width': items[i][0],
                        'height': items[i][1]
                    })
            solution['bins'].append(bin_items)

    return solution

Heuristic Methods

First Fit Decreasing Height (FFDH)

  • Sort items by decreasing height
  • Pack items left-to-right on shelves
  • Start new shelf when item doesn't fit
def first_fit_decreasing_height(items, bin_width, bin_height):
    """
    First Fit Decreasing Height (FFDH) Algorithm

    Classic shelf-based packing heuristic
    - Sorts items by decreasing height
    - Packs items left-to-right on shelves
    - Opens new shelf/bin when needed

    Parameters:
    - items: list of (width, height, item_id) tuples
    - bin_width: bin width
    - bin_height: bin height

    Returns packing solution
    """

    # Sort by decreasing height, then decreasing width
    sorted_items = sorted(items, key=lambda x: (x[1], x[0]), reverse=True)

    bins = []

    for item_width, item_height, item_id in sorted_items:
        placed = False

        # Try to place in existing bins
        for bin_idx, bin_data in enumerate(bins):
            shelves = bin_data['shelves']

            # Try each shelf
            for shelf in shelves:
                if (shelf['remaining_width'] >= item_width and
                    shelf['height'] >= item_height):
                    # Place on this shelf
                    x = bin_width - shelf['remaining_width']
                    y = shelf['y']

                    bin_data['items'].append({
                        'id': item_id,
                        'x': x,
                        'y': y,
                        'width': item_width,
                        'height': item_height
                    })

                    shelf['remaining_width'] -= item_width
                    placed = True
                    break

            if placed:
                break

            # Try to create new shelf in this bin
            if not placed:
                current_height = sum(s['height'] for s in shelves)
                if current_height + item_height <= bin_height:
                    # Create new shelf
                    new_shelf = {
                        'y': current_height,
                        'height': item_height,
                        'remaining_width': bin_width - item_width
                    }
                    shelves.append(new_shelf)

                    bin_data['items'].append({
                        'id': item_id,
                        'x': 0,
                        'y': current_height,
                        'width': item_width,
                        'height': item_height
                    })
                    placed = True
                    break

        # Need new bin
        if not placed:
            new_bin = {
                'items': [{
                    'id': item_id,
                    'x': 0,
                    'y': 0,
                    'width': item_width,
                    'height': item_height
                }],
                'shelves': [{
                    'y': 0,
                    'height': item_height,
                    'remaining_width': bin_width - item_width
                }]
            }
            bins.append(new_bin)

    return {
        'num_bins': len(bins),
        'bins': bins,
        'utilization': calculate_utilization(bins, bin_width, bin_height)
    }

def calculate_utilization(bins, bin_width, bin_height):
    """Calculate space utilization percentage"""
    total_item_area = 0
    for bin_data in bins:
        for item in bin_data['items']:
            total_item_area += item['width'] * item['height']

    total_bin_area = len(bins) * bin_width * bin_height
    return (total_item_area / total_bin_area * 100) if total_bin_area > 0 else 0

Next Fit Decreasing Height (NFDH)

  • Similar to FFDH but only considers current bin
  • Simpler but less efficient

Best Fit Decreasing Height (BFDH)

  • Tries to find best shelf for each item
  • Better utilization than FFDH
def best_fit_decreasing_height(items, bin_width, bin_height):
    """
    Best Fit Decreasing Height Algorithm

    Finds the shelf with minimum remaining space that fits the item
    """

    sorted_items = sorted(items, key=lambda x: (x[1], x[0]), reverse=True)
    bins = []

    for item_width, item_height, item_id in sorted_items:
        best_bin = None
        best_shelf = None
        min_waste = float('inf')

        # Find best fitting shelf
        for bin_idx, bin_data in enumerate(bins):
            for shelf_idx, shelf in enumerate(bin_data['shelves']):
                if (shelf['remaining_width'] >= item_width and
                    shelf['height'] >= item_height):
                    waste = shelf['remaining_width'] - item_width
                    if waste < min_waste:
                        min_waste = waste
                        best_bin = bin_idx
                        best_shelf = shelf_idx

        if best_bin is not None:
            # Place on best shelf
            shelf = bins[best_bin]['shelves'][best_shelf]
            x = bin_width - shelf['remaining_width']
            y = shelf['y']

            bins[best_bin]['items'].append({
                'id': item_id,
                'x': x,
                'y': y,
                'width': item_width,
                'height': item_height
            })

            shelf['remaining_width'] -= item_width
        else:
            # Try to create new shelf or new bin
            placed = False
            for bin_idx, bin_data in enumerate(bins):
                shelves = bin_data['shelves']
                current_height = sum(s['height'] for s in shelves)

                if current_height + item_height <= bin_height:
                    new_shelf = {
                        'y': current_height,
                        'height': item_height,
                        'remaining_width': bin_width - item_width
                    }
                    shelves.append(new_shelf)

                    bin_data['items'].append({
                        'id': item_id,
                        'x': 0,
                        'y': current_height,
                        'width': item_width,
                        'height': item_height
                    })
                    placed = True
                    break

            if not placed:
                # Create new bin
                new_bin = {
                    'items': [{
                        'id': item_id,
                        'x': 0,
                        'y': 0,
                        'width': item_width,
                        'height': item_height
                    }],
                    'shelves': [{
                        'y': 0,
                        'height': item_height,
                        'remaining_width': bin_width - item_width
                    }]
                }
                bins.append(new_bin)

    return {
        'num_bins': len(bins),
        'bins': bins,
        'utilization': calculate_utilization(bins, bin_width, bin_height)
    }

Guillotine Algorithm

  • Recursive subdivision using guillotine cuts
  • Each cut goes completely across rectangle
  • Common in manufacturing/cutting applications
class Rectangle:
    """Rectangle representation for guillotine algorithm"""
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.item_id = None

    def area(self):
        return self.width * self.height

    def fits(self, item_width, item_height):
        return self.width >= item_width and self.height >= item_height

def guillotine_algorithm(items, bin_width, bin_height, split_rule='shorter_leftover'):
    """
    Guillotine Algorithm with Free Rectangles

    Maintains list of free rectangles
    Places items and splits rectangles with guillotine cuts

    Parameters:
    - items: list of (width, height, id) tuples
    - bin_width, bin_height: bin dimensions
    - split_rule: 'shorter_leftover' or 'longer_leftover'

    Returns packing solution
    """

    # Sort items by area (largest first)
    sorted_items = sorted(items, key=lambda x: x[0] * x[1], reverse=True)

    bins = []

    for item_width, item_height, item_id in sorted_items:
        placed = False

        # Try rotation
        rotations = [(item_width, item_height, False)]
        rotations.append((item_height, item_width, True))  # 90-degree rotation

        for try_width, try_height, rotated in rotations:
            if placed:
                break

            # Try existing bins
            for bin_data in bins:
                free_rects = bin_data['free_rectangles']

                # Find best free rectangle
                best_rect_idx = None
                best_rect_score = float('inf')

                for idx, rect in enumerate(free_rects):
                    if rect.fits(try_width, try_height):
                        # Score: prefer smaller remaining area
                        score = rect.area() - (try_width * try_height)
                        if score < best_rect_score:
                            best_rect_score = score
                            best_rect_idx = idx

                if best_rect_idx is not None:
                    rect = free_rects.pop(best_rect_idx)

                    # Place item
                    bin_data['items'].append({
                        'id': item_id,
                        'x': rect.x,
                        'y': rect.y,
                        'width': try_width,
                        'height': try_height,
                        'rotated': rotated
                    })

                    # Split rectangle with guillotine cut
                    new_rects = split_rectangle(rect, try_width, try_height, split_rule)
                    free_rects.extend(new_rects)

                    placed = True
                    break

            if placed:
                break

        # Create new bin if not placed
        if not placed:
            new_bin = {
                'items': [{
                    'id': item_id,
                    'x': 0,
                    'y': 0,
                    'width': item_width,
                    'height': item_height,
                    'rotated': False
                }],
                'free_rectangles': []
            }

            # Add remaining free rectangles from split
            initial_rect = Rectangle(0, 0, bin_width, bin_height)
            new_rects = split_rectangle(initial_rect, item_width, item_height, split_rule)
            new_bin['free_rectangles'] = new_rects

            bins.append(new_bin)

    return {
        'num_bins': len(bins),
        'bins': bins,
        'utilization': calculate_utilization(bins, bin_width, bin_height)
    }

def split_rectangle(rect, used_width, used_height, split_rule):
    """
    Split rectangle after placing item

    Creates two new free rectangles using guillotine cut
    """

    new_rects = []

    remaining_width = rect.width - used_width
    remaining_height = rect.height - used_height

    if split_rule == 'shorter_leftover':
        # Horizontal cut if remaining width is shorter
        if remaining_width <= remaining_height:
            # Horizontal cut
            if remaining_width > 0:
                new_rects.append(Rectangle(
                    rect.x + used_width, rect.y,
                    remaining_width, rect.height
                ))
            if remaining_height > 0:
                new_rects.append(Rectangle(
                    rect.x, rect.y + used_height,
                    used_width, remaining_height
                ))
        else:
            # Vertical cut
            if remaining_height > 0:
                new_rects.append(Rectangle(
                    rect.x, rect.y + used_height,
                    rect.width, remaining_height
                ))
            if remaining_width > 0:
                new_rects.append(Rectangle(
                    rect.x + used_width, rect.y,
                    remaining_width, used_height
                ))

    return new_rects

Maximal Rectangles Algorithm

  • Maintains list of all maximal free rectangles
  • More complex but better utilization
  • No guillotine constraint
def maximal_rectangles_algorithm(items, bin_width, bin_height):
    """
    Maximal Rectangles Algorithm

    More sophisticated than guillotine - maintains all maximal free rectangles
    No guillotine constraint, allowing better packing

    This allows more flexible packing patterns
    """

    sorted_items = sorted(items, key=lambda x: x[0] * x[1], reverse=True)
    bins = []

    for item_width, item_height, item_id in sorted_items:
        placed = False

        # Try both orientations
        for try_width, try_height, rotated in [(item_width, item_height, False),
                                                 (item_height, item_width, True)]:
            if placed:
                break

            # Try existing bins
            for bin_data in bins:
                free_rects = bin_data['free_rectangles']

                # Find best free rectangle using Best Area Fit
                best_idx = None
                best_score = float('inf')
                best_x, best_y = 0, 0

                for idx, rect in enumerate(free_rects):
                    if rect.width >= try_width and rect.height >= try_height:
                        # Score: prefer tightest fit
                        leftover_x = rect.width - try_width
                        leftover_y = rect.height - try_height
                        score = min(leftover_x, leftover_y)

                        if score < best_score:
                            best_score = score
                            best_idx = idx
                            best_x = rect.x
                            best_y = rect.y

                if best_idx is not None:
                    # Place item
                    bin_data['items'].append({
                        'id': item_id,
                        'x': best_x,
                        'y': best_y,
                        'width': try_width,
                        'height': try_height,
                        'rotated': rotated
                    })

                    # Update free rectangles
                    placed_rect = Rectangle(best_x, best_y, try_width, try_height)
                    update_maximal_rectangles(free_rects, placed_rect)

                    placed = True
                    break

            if placed:
                break

        if not placed:
            # Create new bin
            initial_rect = Rectangle(0, 0, bin_width, bin_height)

            new_bin = {
                'items': [{
                    'id': item_id,
                    'x': 0,
                    'y': 0,
                    'width': item_width,
                    'height': item_height,
                    'rotated': False
                }],
                'free_rectangles': [initial_rect]
            }

            placed_rect = Rectangle(0, 0, item_width, item_height)
            update_maximal_rectangles(new_bin['free_rectangles'], placed_rect)

            bins.append(new_bin)

    return {
        'num_bins': len(bins),
        'bins': bins,
        'utilization': calculate_utilization(bins, bin_width, bin_height)
    }

def update_maximal_rectangles(free_rects, placed_rect):
    """
    Update list of maximal free rectangles after placing an item

    Split intersecting rectangles and remove non-maximal ones
    """

    new_rects = []

    for rect in free_rects[:]:
        if rectangles_intersect(rect, placed_rect):
            # Split this rectangle
            splits = split_intersecting_rectangle(rect, placed_rect)
            new_rects.extend(splits)
        else:
            new_rects.append(rect)

    # Remove non-maximal rectangles
    free_rects.clear()
    for rect in new_rects:
        is_maximal = True
        for other in new_rects:
            if rect != other and contains(other, rect):
                is_maximal = False
                break
        if is_maximal:
            free_rects.append(rect)

def rectangles_intersect(rect1, rect2):
    """Check if two rectangles intersect"""
    return not (rect1.x + rect1.width <= rect2.x or
                rect2.x + rect2.width <= rect1.x or
                rect1.y + rect1.height <= rect2.y or
                rect2.y + rect2.height <= rect1.y)

def contains(outer, inner):
    """Check if outer rectangle contains inner rectangle"""
    return (outer.x <= inner.x and
            outer.y <= inner.y and
            outer.x + outer.width >= inner.x + inner.width and
            outer.y + outer.height >= inner.y + inner.height)

def split_intersecting_rectangle(rect, placed):
    """Split rectangle by removing placed rectangle area"""
    splits = []

    # Create up to 4 new rectangles around the placed item

    # Left piece
    if placed.x > rect.x:
        splits.append(Rectangle(
            rect.x, rect.y,
            placed.x - rect.x, rect.height
        ))

    # Right piece
    if placed.x + placed.width < rect.x + rect.width:
        splits.append(Rectangle(
            placed.x + placed.width, rect.y,
            rect.x + rect.width - (placed.x + placed.width), rect.height
        ))

    # Bottom piece
    if placed.y > rect.y:
        splits.append(Rectangle(
            rect.x, rect.y,
            rect.width, placed.y - rect.y
        ))

    # Top piece
    if placed.y + placed.height < rect.y + rect.height:
        splits.append(Rectangle(
            rect.x, placed.y + placed.height,
            rect.width, rect.y + rect.height - (placed.y + placed.height)
        ))

    return splits

Metaheuristic Methods

Genetic Algorithm for 2D Packing

import random
import numpy as np

class GeneticAlgorithm2DBinPacking:
    """
    Genetic Algorithm for 2D Bin Packing

    Chromosome: permutation of items (packing order)
    Fitness: number of bins used (lower is better)
    """

    def __init__(self, items, bin_width, bin_height,
                 population_size=100, generations=200,
                 mutation_rate=0.1, crossover_rate=0.8):
        self.items = items
        self.bin_width = bin_width
        self.bin_height = bin_height
        self.population_size = population_size
        self.generations = generations
        self.mutation_rate = mutation_rate
        self.crossover_rate = crossover_rate

        self.n_items = len(items)
        self.best_solution = None
        self.best_fitness = float('inf')

    def create_chromosome(self):
        """Create random chromosome (item permutation)"""
        return list(np.random.permutation(self.n_items))

    def decode_chromosome(self, chromosome):
        """
        Decode chromosome to packing solution
        Uses FFDH to pack items in the order specified by chromosome
        """
        ordered_items = [self.items[i] for i in chromosome]
        result = first_fit_decreasing_height(
            ordered_items, self.bin_width, self.bin_height
        )
        return result

    def fitness(self, chromosome):
        """
        Fitness function: number of bins used
        Lower is better
        """
        solution = self.decode_chromosome(chromosome)
        return solution['num_bins']

    def crossover(self, parent1, parent2):
        """
        Order Crossover (OX) for permutations
        """
        if random.random() > self.crossover_rate:
            return parent1.copy(), parent2.copy()

        size = len(parent1)

        # Select crossover points
        cx_point1 = random.randint(0, size - 2)
        cx_point2 = random.randint(cx_point1 + 1, size - 1)

        # Create offspring
        child1 = [-1] * size
        child2 = [-1] * size

        # Copy segments
        child1[cx_point1:cx_point2] = parent1[cx_point1:cx_point2]
        child2[cx_point1:cx_point2] = parent2[cx_point1:cx_point2]

        # Fill remaining positions
        self._fill_offspring(child1, parent2, cx_point2)
        self._fill_offspring(child2, parent1, cx_point2)

        return child1, child2

    def _fill_offspring(self, child, parent, start_pos):
        """Fill remaining positions in offspring"""
        child_set = set([x for x in child if x != -1])
        pos = start_pos

        for item in parent[start_pos:] + parent[:start_pos]:
            if item not in child_set:
                while child[pos % len(child)] != -1:
                    pos += 1
                child[pos % len(child)] = item
                child_set.add(item)

    def mutate(self, chromosome):
        """
        Swap mutation: swap two random positions
        """
        if random.random() < self.mutation_rate:
            pos1, pos2 = random.sample(range(len(chromosome)), 2)
            chromosome[pos1], chromosome[pos2] = chromosome[pos2], chromosome[pos1]
        return chromosome

    def tournament_selection(self, population, fitnesses, tournament_size=3):
        """Tournament selection"""
        tournament_indices = random.sample(range(len(population)), tournament_size)
        tournament_fitnesses = [fitnesses[i] for i in tournament_indices]
        winner_idx = tournament_indices[tournament_fitnesses.index(min(tournament_fitnesses))]
        return population[winner_idx]

    def solve(self):
        """
        Run genetic algorithm
        """
        # Initialize population
        population = [self.create_chromosome() for _ in range(self.population_size)]

        for generation in range(self.generations):
            # Evaluate fitness
            fitnesses = [self.fitness(chrom) for chrom in population]

            # Track best solution
            min_fitness_idx = fitnesses.index(min(fitnesses))
            if fitnesses[min_fitness_idx] < self.best_fitness:
                self.best_fitness = fitnesses[min_fitness_idx]
                self.best_solution = self.decode_chromosome(population[min_fitness_idx])
                print(f"Generation {generation}: Best = {self.best_fitness} bins")

            # Create new population
            new_population = []

            # Elitism: keep best solution
            new_population.append(population[min_fitness_idx])

            # Generate offspring
            while len(new_population) < self.population_size:
                # Selection
                parent1 = self.tournament_selection(population, fitnesses)
                parent2 = self.tournament_selection(population, fitnesses)

                # Crossover
                child1, child2 = self.crossover(parent1, parent2)

                # Mutation
                child1 = self.mutate(child1)
                child2 = self.mutate(child2)

                new_population.extend([child1, child2])

            population = new_population[:self.population_size]

        return self.best_solution

# Usage example
def example_genetic_algorithm():
    """Example usage of genetic algorithm"""

    # Generate random items
    np.random.seed(42)
    n_items = 30
    items = [(random.randint(10, 50), random.randint(10, 50), i)
             for i in range(n_items)]

    bin_width = 100
    bin_height = 100

    # Run genetic algorithm
    ga = GeneticAlgorithm2DBinPacking(
        items, bin_width, bin_height,
        population_size=50,
        generations=100
    )

    solution = ga.solve()

    print(f"\nFinal Solution:")
    print(f"Number of bins: {solution['num_bins']}")
    print(f"Utilization: {solution['utilization']:.2f}%")

    return solution

Simulated Annealing

import math
import random

def simulated_annealing_2d_packing(items, bin_width, bin_height,
                                    initial_temp=1000, cooling_rate=0.995,
                                    iterations=10000):
    """
    Simulated Annealing for 2D Bin Packing

    Neighborhood: swap two items in packing order
    """

    # Initial solution: random order + FFDH
    current_order = list(range(len(items)))
    random.shuffle(current_order)

    current_items = [items[i] for i in current_order]
    current_solution = first_fit_decreasing_height(
        current_items, bin_width, bin_height
    )
    current_cost = current_solution['num_bins']

    best_order = current_order.copy()
    best_solution = current_solution
    best_cost = current_cost

    temperature = initial_temp

    for iteration in range(iterations):
        # Generate neighbor: swap two items
        neighbor_order = current_order.copy()
        i, j = random.sample(range(len(items)), 2)
        neighbor_order[i], neighbor_order[j] = neighbor_order[j], neighbor_order[i]

        # Evaluate neighbor
        neighbor_items = [items[idx] for idx in neighbor_order]
        neighbor_solution = first_fit_decreasing_height(
            neighbor_items, bin_width, bin_height
        )
        neighbor_cost = neighbor_solution['num_bins']

        # Acceptance criterion
        delta = neighbor_cost - current_cost

        if delta < 0 or random.random() < math.exp(-delta / temperature):
            current_order = neighbor_order
            current_solution = neighbor_solution
            current_cost = neighbor_cost

            if current_cost < best_cost:
                best_order = current_order.copy()
                best_solution = current_solution
                best_cost = current_cost
                print(f"Iteration {iteration}: New best = {best_cost} bins")

        # Cool down
        temperature *= cooling_rate

    return best_solution

Complete 2D Bin Packing Solver

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

class TwoDimensionalBinPacker:
    """
    Comprehensive 2D Bin Packing Solver

    Supports multiple algorithms and visualization
    """

    def __init__(self, bin_width, bin_height):
        self.bin_width = bin_width
        self.bin_height = bin_height
        self.items = []
        self.solution = None

    def add_item(self, width, height, item_id=None):
        """Add item to pack"""
        if item_id is None:
            item_id = len(self.items)
        self.items.append((width, height, item_id))

    def add_items(self, items_list):
        """Add multiple items: list of (width, height) tuples"""
        for width, height in items_list:
            self.add_item(width, height)

    def solve(self, algorithm='ffdh', **kwargs):
        """
        Solve using specified algorithm

        Algorithms:
        - 'ffdh': First Fit Decreasing Height
        - 'bfdh': Best Fit Decreasing Height
        - 'guillotine': Guillotine algorithm
        - 'maxrects': Maximal Rectangles
        - 'genetic': Genetic Algorithm
        - 'simulated_annealing': Simulated Annealing
        """

        if algorithm == 'ffdh':
            self.solution = first_fit_decreasing_height(
                self.items, self.bin_width, self.bin_height
            )

        elif algorithm == 'bfdh':
            self.solution = best_fit_decreasing_height(
                self.items, self.bin_width, self.bin_height
            )

        elif algorithm == 'guillotine':
            self.solution = guillotine_algorithm(
                self.items, self.bin_width, self.bin_height
            )

        elif algorithm == 'maxrects':
            self.solution = maximal_rectangles_algorithm(
                self.items, self.bin_width, self.bin_height
            )

        elif algorithm == 'genetic':
            ga = GeneticAlgorithm2DBinPacking(
                self.items, self.bin_width, self.bin_height,
                **kwargs
            )
            self.solution = ga.solve()

        elif algorithm == 'simulated_annealing':
            self.solution = simulated_annealing_2d_packing(
                self.items, self.bin_width, self.bin_height,
                **kwargs
            )

        else:
            raise ValueError(f"Unknown algorithm: {algorithm}")

        return self.solution

    def visualize(self, bin_indices=None, save_path=None):
        """
        Visualize packing solution

        Parameters:
        - bin_indices: list of bin indices to visualize (None = all)
        - save_path: path to save figure
        """

        if self.solution is None:
            raise ValueError("No solution to visualize. Run solve() first.")

        bins = self.solution['bins']

        if bin_indices is None:
            bin_indices = range(len(bins))

        n_bins = len(bin_indices)
        cols = min(3, n_bins)
        rows = (n_bins + cols - 1) // cols

        fig, axes = plt.subplots(rows, cols, figsize=(5*cols, 5*rows))
        if n_bins == 1:
            axes = [axes]
        else:
            axes = axes.flatten() if n_bins > 1 else [axes]

        colors = plt.cm.tab20(np.linspace(0, 1, 20))

        for idx, bin_idx in enumerate(bin_indices):
            ax = axes[idx]
            bin_data = bins[bin_idx]

            # Draw bin boundary
            ax.add_patch(patches.Rectangle(
                (0, 0), self.bin_width, self.bin_height,
                fill=False, edgecolor='black', linewidth=2
            ))

            # Draw items
            for item_idx, item in enumerate(bin_data['items']):
                color = colors[item['id'] % 20]

                rect = patches.Rectangle(
                    (item['x'], item['y']),
                    item['width'], item['height'],
                    facecolor=color, edgecolor='black',
                    linewidth=1, alpha=0.7
                )
                ax.add_patch(rect)

                # Add item ID label
                cx = item['x'] + item['width'] / 2
                cy = item['y'] + item['height'] / 2
                ax.text(cx, cy, str(item['id']),
                       ha='center', va='center',
                       fontsize=8, fontweight='bold')

            ax.set_xlim(0, self.bin_width)
            ax.set_ylim(0, self.bin_height)
            ax.set_aspect('equal')
            ax.set_title(f'Bin {bin_idx + 1}')
            ax.set_xlabel('Width')
            ax.set_ylabel('Height')
            ax.grid(True, alpha=0.3)

        # Hide empty subplots
        for idx in range(len(bin_indices), len(axes)):
            axes[idx].axis('off')

        plt.suptitle(
            f'2D Bin Packing Solution\n'
            f'Bins Used: {self.solution["num_bins"]} | '
            f'Utilization: {self.solution["utilization"]:.1f}%',
            fontsize=14, fontweight='bold'
        )

        plt.tight_layout()

        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')

        plt.show()

    def get_statistics(self):
        """Get detailed statistics about the solution"""

        if self.solution is None:
            return None

        total_item_area = sum(w * h for w, h, _ in self.items)
        total_bin_area = self.solution['num_bins'] * self.bin_width * self.bin_height

        stats = {
            'num_items': len(self.items),
            'num_bins': self.solution['num_bins'],
            'bin_size': (self.bin_width, self.bin_height),
            'total_item_area': total_item_area,
            'total_bin_area': total_bin_area,
            'utilization': self.solution['utilization'],
            'waste_percentage': 100 - self.solution['utilization'],
            'bins': []
        }

        for bin_idx, bin_data in enumerate(self.solution['bins']):
            bin_item_area = sum(
                item['width'] * item['height']
                for item in bin_data['items']
            )
            bin_area = self.bin_width * self.bin_height

            stats['bins'].append({
                'bin_id': bin_idx,
                'num_items': len(bin_data['items']),
                'used_area': bin_item_area,
                'total_area': bin_area,
                'utilization': (bin_item_area / bin_area * 100)
            })

        return stats

    def print_solution(self):
        """Print solution summary"""

        if self.solution is None:
            print("No solution available.")
            return

        stats = self.get_statistics()

        print("=" * 60)
        print("2D BIN PACKING SOLUTION")
        print("=" * 60)
        print(f"Items to pack: {stats['num_items']}")
        print(f"Bin dimensions: {stats['bin_size'][0]} x {stats['bin_size'][1]}")
        print(f"Bins used: {stats['num_bins']}")
        print(f"Overall utilization: {stats['utilization']:.2f}%")
        print(f"Waste percentage: {stats['waste_percentage']:.2f}%")
        print()

        print("Bin Details:")
        print("-" * 60)
        for bin_stat in stats['bins']:
            print(f"Bin {bin_stat['bin_id'] + 1}: "
                  f"{bin_stat['num_items']} items, "
                  f"{bin_stat['utilization']:.1f}% utilization")


# Example usage
if __name__ == "__main__":
    # Create packer
    packer = TwoDimensionalBinPacker(bin_width=100, bin_height=100)

    # Add items
    np.random.seed(42)
    items = [
        (30, 40), (25, 35), (50, 20), (40, 30),
        (20, 25), (35, 45), (15, 30), (25, 20),
        (40, 40), (30, 30), (20, 40), (35, 25),
        (45, 35), (25, 25), (30, 35), (20, 30)
    ]
    packer.add_items(items)

    # Solve using different algorithms
    print("Testing FFDH algorithm:")
    solution_ffdh = packer.solve(algorithm='ffdh')
    packer.print_solution()

    print("\nTesting Guillotine algorithm:")
    solution_guillotine = packer.solve(algorithm='guillotine')
    packer.print_solution()

    # Visualize
    packer.visualize()

Tools & Libraries

Python Libraries

rectpack

from rectpack import newPacker

def pack_with_rectpack(items, bin_width, bin_height):
    """Use rectpack library for 2D packing"""
    packer = newPacker()

    # Add bins
    for i in range(len(items)):  # Add enough bins
        packer.add_bin(bin_width, bin_height)

    # Add items
    for i, (w, h, item_id) in enumerate(items):
        packer.add_rect(w, h, rid=item_id)

    # Pack
    packer.pack()

    # Extract results
    bins_used = len([b for b in packer if b])

    return {
        'num_bins': bins_used,
        'packer': packer
    }

binpack - Simple 1D/2D bin packing

py2dbp - 2D bin packing algorithms

OR-Tools - Google's optimization library

Commercial Software

  • CutLogic 2D: Professional cutting optimization
  • Cutting Optimization Pro: Cutting and nesting
  • OptiCut: Sheet optimization software
  • MaxCut: Cutting stock optimization

Common Challenges & Solutions

Challenge: Items Don't Fit Efficiently

Problem:

  • Low utilization (<70%)
  • Too many bins used
  • Odd-shaped gaps

Solutions:

  • Allow 90-degree rotation
  • Try different sorting strategies
  • Use metaheuristic algorithms (GA, SA)
  • Combine small items strategically
  • Consider pre-grouping similar sizes

Challenge: Guillotine Constraint Too Restrictive

Problem:

  • Guillotine cuts waste space
  • Need more flexible packing

Solutions:

  • Use maximal rectangles algorithm
  • Allow limited non-guillotine patterns
  • Multi-stage cutting approach
  • Optimize stage sequence

Challenge: Real-Time Packing Needed

Problem:

  • Items arrive dynamically
  • Need fast solution
  • Can't repack already placed items

Solutions:

  • Use fast online algorithms (FFDH, NFDH)
  • Reserve space for expected items
  • Periodic re-optimization windows
  • Hybrid online/offline approach

Challenge: Many Small Items

Problem:

  • Thousands of tiny items
  • Combinatorial explosion
  • Slow computation

Solutions:

  • Pre-cluster similar items
  • Use hierarchical approach
  • Limit search time with time-based stopping
  • Parallel processing

Output Format

2D Bin Packing Report

Executive Summary:

  • Items packed: 150
  • Bins used: 12 sheets (100cm x 100cm each)
  • Utilization: 87.3%
  • Waste: 12.7%
  • Algorithm: Guillotine with GA optimization

Packing Details:

BinItemsUsed AreaUtilizationWaste
1158,750 cm²87.5%12.5%
2139,100 cm²91.0%9.0%
3148,450 cm²84.5%15.5%

Cutting Pattern Example (Bin 1):

+------------------+
|  A   |  B  | C  |
|------+-----+----|
|  D   | E  F|  G |
|------+-----+----|
|  H   |  I  |  J |
+------------------+

Item List:

Item IDWidthHeightBinPosition (x,y)Rotated
A00140301(0, 0)No
A00225301(40, 0)No
A00320301(65, 0)Yes

Cost Analysis:

  • Material cost per sheet: $50
  • Total material cost: $600
  • Waste cost: $76 (12.7%)
  • Potential savings with perfect packing: $76

Questions to Ask

If you need more context:

  1. What are the bin/sheet dimensions?
  2. How many items need to be packed? What are their sizes?
  3. Can items be rotated 90 degrees?
  4. Are there guillotine cutting constraints?
  5. What's the optimization goal? (minimize bins, minimize waste, maximize value)
  6. Are there any spacing requirements between items?
  7. Do items have priorities or must-pack requirements?
  8. Is this a one-time problem or recurring production?

Related Skills

  • 1d-cutting-stock: For one-dimensional cutting problems
  • 3d-bin-packing: For three-dimensional packing
  • pallet-loading: For pallet loading optimization
  • container-loading-optimization: For container packing
  • strip-packing: For strip packing problems
  • guillotine-cutting: For guillotine cutting constraints
  • nesting-optimization: For irregular shape nesting
  • knapsack-problems: For value-based packing

2D Cutting Stock Problem

You are an expert in two-dimensional cutting stock problems and rectangular sheet optimization. Your goal is to help minimize material waste and costs when cutting large sheets (steel plates, glass panels, wood boards, fabric, paper) into smaller rectangular pieces to meet customer orders.

Initial Assessment

Before solving 2D cutting stock problems, understand:

  1. Material Characteristics

    • What material? (steel plate, glass, wood, fabric, paper)
    • Standard sheet dimensions? (e.g., 2440×1220mm, 3000×1500mm)
    • Single sheet size or multiple available?
    • Sheet cost per piece or per square meter?
    • Material grain direction matters?
  2. Item Requirements

    • How many different rectangular items needed?
    • Dimensions of each item (width × height)?
    • Quantity of each item?
    • Total list of (width, height, quantity) tuples?
    • Can items be rotated 90 degrees?
  3. Cutting Constraints

    • Guillotine cuts only? (straight cuts across entire sheet)
    • Free-form cutting allowed?
    • Maximum number of cutting stages? (2-stage, 3-stage)
    • Saw blade kerf (material lost per cut)?
    • Minimum trim size?
  4. Optimization Objective

    • Minimize number of sheets used?
    • Minimize total material cost?
    • Minimize trim waste percentage?
    • Minimize cutting complexity?
    • Balance waste vs. setup time?
  5. Production Constraints

    • Any item grouping requirements?
    • Maximum items per sheet?
    • Cutting machine limitations?
    • Time constraints for solution?

2D Cutting Stock Framework

Problem Classification

1. Unconstrained 2D Cutting Stock

  • Free-form cutting allowed
  • Any cutting pattern acceptable
  • Minimize sheets used or waste
  • Most flexible but complex

2. Guillotine 2D Cutting Stock

  • All cuts must be guillotine (edge-to-edge)
  • Simpler cutting process
  • May increase waste vs. free-form
  • Common in manufacturing

3. Two-Stage Guillotine Cutting

  • Stage 1: Cut sheet into strips
  • Stage 2: Cut strips into items
  • Practical for many cutting machines
  • Restricted pattern space

4. Three-Stage Guillotine Cutting

  • Stage 1: Cut sheet into sections
  • Stage 2: Cut sections into strips
  • Stage 3: Cut strips into items
  • More flexible than two-stage

5. Non-Guillotine with Limited Cuts

  • Allow some non-guillotine cuts
  • Minimize number of non-guillotine cuts
  • Balance flexibility vs. complexity

Mathematical Formulation

Classical 2D Cutting Stock Problem

Given:

  • W, H = sheet width and height
  • n = number of item types
  • w_i, h_i = width and height of item type i
  • d_i = demand for item type i

Pattern Definition: A cutting pattern p is a layout of items on one sheet where:

  • Items don't overlap
  • Items fit within sheet boundaries
  • a_ip = number of items of type i in pattern p
  • Can be represented by coordinates: (x, y, w, h, rotation) for each item

Decision Variables:

  • x_p = number of times pattern p is used

Objective: Minimize Σ x_p (minimize sheets used)

Or: Minimize Σ (cost_p × x_p) (minimize material cost)

Constraints: Σ (a_ip × x_p) ≥ d_i for all i = 1, ..., n (meet demand) x_p ≥ 0, integer

Complexity:

  • Strongly NP-hard
  • Pattern generation is itself NP-hard (2D knapsack)
  • Requires sophisticated algorithms

Algorithms and Solution Methods

Method 1: Two-Stage Guillotine Cutting - Practical Heuristic

import numpy as np
from typing import List, Tuple, Dict

class TwoStageGuillotineCutting:
    """
    Two-Stage Guillotine Cutting for 2D Cutting Stock

    Stage 1: Cut sheet horizontally into strips
    Stage 2: Cut strips vertically into items

    This is a practical approximation that works well for many applications
    """

    def __init__(self, sheet_width, sheet_height, kerf=0):
        """
        Initialize solver

        Parameters:
        - sheet_width: width of standard sheet
        - sheet_height: height of standard sheet
        - kerf: material lost per cut
        """
        self.sheet_width = sheet_width
        self.sheet_height = sheet_height
        self.kerf = kerf
        self.items = []

    def add_item(self, width, height, quantity, item_id=None):
        """Add item to cut list"""
        if item_id is None:
            item_id = f"Item_{len(self.items)}"

        self.items.append({
            'id': item_id,
            'width': width,
            'height': height,
            'quantity': quantity,
            'area': width * height
        })

    def generate_strip_patterns(self):
        """
        Generate feasible strip patterns

        A strip pattern: one height, multiple items of possibly different widths

        Returns: list of strip patterns
        """
        strip_patterns = []

        # For each unique height, generate strip patterns
        unique_heights = list(set(item['height'] for item in self.items))

        for strip_height in unique_heights:
            if strip_height > self.sheet_height:
                continue

            # Items that fit this height
            eligible_items = [item for item in self.items
                            if item['height'] <= strip_height]

            # Use 1D cutting stock to pack items into strip width
            patterns = self._generate_1d_patterns_for_strip(
                eligible_items, strip_height, self.sheet_width
            )

            for pattern in patterns:
                strip_patterns.append({
                    'height': strip_height,
                    'items': pattern,
                    'waste_width': self._calculate_strip_waste(pattern)
                })

        return strip_patterns

    def _generate_1d_patterns_for_strip(self, eligible_items, strip_height, strip_width):
        """
        Generate 1D patterns for items that fit in a strip

        This is essentially 1D cutting stock in the width dimension
        """
        patterns = []

        # Simple greedy pattern generation
        # In practice, use proper 1D column generation here

        # Pattern 1: Single item type per strip (simple patterns)
        for item in eligible_items:
            if item['height'] == strip_height:
                num_fit = int(strip_width / (item['width'] + self.kerf))
                if num_fit > 0:
                    pattern = {item['id']: num_fit}
                    patterns.append(pattern)

        # Pattern 2: Multiple item types (mixed patterns)
        # Simplified: try pairs of items
        for i, item1 in enumerate(eligible_items):
            if item1['height'] > strip_height:
                continue

            for item2 in eligible_items[i:]:
                if item2['height'] > strip_height:
                    continue

                # Try different combinations
                for n1 in range(int(strip_width / (item1['width'] + self.kerf)) + 1):
                    remaining = strip_width - n1 * (item1['width'] + self.kerf)
                    n2 = int(remaining / (item2['width'] + self.kerf))

                    if n1 + n2 > 0:
                        pattern = {}
                        if n1 > 0:
                            pattern[item1['id']] = n1
                        if n2 > 0:
                            pattern[item2['id']] = n2
                        patterns.append(pattern)

        return patterns

    def _calculate_strip_waste(self, pattern):
        """Calculate waste width in a strip pattern"""
        total_width = 0
        for item in self.items:
            if item['id'] in pattern:
                total_width += item['width'] * pattern[item['id']]
        return self.sheet_width - total_width

    def solve_column_generation(self):
        """
        Solve 2-stage guillotine cutting using column generation

        This is simplified - full implementation would use proper pricing problem
        """

        from pulp import *

        # Generate initial strip patterns
        strip_patterns = self.generate_strip_patterns()

        # Master problem: select strips to pack into sheets
        prob = LpProblem("Two_Stage_Cutting", LpMinimize)

        # Variables: how many of each strip pattern to use
        n_patterns = len(strip_patterns)
        x = [LpVariable(f"strip_{i}", lowBound=0, cat='Integer')
             for i in range(n_patterns)]

        # Approximate number of sheets as sum of strip heights / sheet height
        # This is a simplification; exact formulation requires bin packing constraint
        prob += lpSum(x[i] * strip_patterns[i]['height'] / self.sheet_height
                     for i in range(n_patterns)), "Sheets"

        # Demand constraints
        for item in self.items:
            item_id = item['id']
            prob += lpSum(x[i] * strip_patterns[i]['items'].get(item_id, 0)
                         for i in range(n_patterns)) >= item['quantity'], f"Demand_{item_id}"

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract solution
        strip_usage = [x[i].varValue for i in range(n_patterns)]

        # Pack strips into sheets
        sheets = self._pack_strips_into_sheets(strip_patterns, strip_usage)

        return {
            'num_sheets': len(sheets),
            'sheets': sheets,
            'strip_patterns': strip_patterns,
            'strip_usage': strip_usage
        }

    def _pack_strips_into_sheets(self, strip_patterns, strip_usage):
        """
        Pack strips into sheets using First Fit Decreasing Height
        """

        # Create list of strips to pack
        strips_to_pack = []
        for i, usage in enumerate(strip_usage):
            if usage and usage > 0.5:
                for _ in range(int(usage)):
                    strips_to_pack.append(strip_patterns[i])

        # Sort by decreasing height
        strips_to_pack.sort(key=lambda s: s['height'], reverse=True)

        # Pack into sheets
        sheets = []

        for strip in strips_to_pack:
            # Try to fit in existing sheet
            placed = False

            for sheet in sheets:
                if sheet['remaining_height'] >= strip['height']:
                    sheet['strips'].append(strip)
                    sheet['remaining_height'] -= strip['height']
                    placed = True
                    break

            if not placed:
                # Create new sheet
                sheets.append({
                    'strips': [strip],
                    'remaining_height': self.sheet_height - strip['height']
                })

        # Calculate utilization
        for sheet in sheets:
            used_area = sum(
                (self.sheet_width - s['waste_width']) * s['height']
                for s in sheet['strips']
            )
            sheet['utilization'] = used_area / (self.sheet_width * self.sheet_height) * 100

        return sheets

    def solve_simple(self):
        """
        Simple two-stage solution without column generation

        Faster but less optimal
        """

        # Sort items by area (largest first)
        sorted_items = sorted(self.items, key=lambda x: x['area'], reverse=True)

        sheets = []
        remaining_items = {item['id']: item['quantity'] for item in self.items}

        while any(qty > 0 for qty in remaining_items.values()):
            # Create new sheet
            sheet = self._fill_sheet_greedy(remaining_items)
            sheets.append(sheet)

        total_used_area = sum(
            sum(item['width'] * item['height'] * item.get('count', 1)
                for item in sheet['items'])
            for sheet in sheets
        )
        total_sheet_area = len(sheets) * self.sheet_width * self.sheet_height

        return {
            'num_sheets': len(sheets),
            'sheets': sheets,
            'utilization': (total_used_area / total_sheet_area * 100) if total_sheet_area > 0 else 0
        }

    def _fill_sheet_greedy(self, remaining_items):
        """Fill one sheet greedily using two-stage approach"""

        sheet = {
            'strips': [],
            'items': [],
            'remaining_height': self.sheet_height
        }

        # Sort items by height (tallest first)
        items_by_height = sorted(
            [(item, remaining_items[item['id']]) for item in self.items
             if remaining_items[item['id']] > 0],
            key=lambda x: x[0]['height'],
            reverse=True
        )

        for item, qty_needed in items_by_height:
            if sheet['remaining_height'] < item['height']:
                continue

            # Create strip for this item
            strip_height = item['height']
            strip_width = self.sheet_width
            num_items_in_strip = int(strip_width / (item['width'] + self.kerf))

            if num_items_in_strip > 0:
                num_items_to_cut = min(num_items_in_strip, qty_needed)

                sheet['strips'].append({
                    'height': strip_height,
                    'items': [{
                        'id': item['id'],
                        'width': item['width'],
                        'height': item['height'],
                        'count': num_items_to_cut
                    }]
                })

                sheet['items'].extend([item] * num_items_to_cut)
                remaining_items[item['id']] -= num_items_to_cut
                sheet['remaining_height'] -= strip_height

        return sheet


# Example usage
def example_two_stage_cutting():
    """Example: Cutting steel plates"""

    solver = TwoStageGuillotineCutting(
        sheet_width=2440,  # mm
        sheet_height=1220,  # mm
        kerf=3  # mm saw kerf
    )

    # Add items to cut
    solver.add_item(800, 600, 10, 'A')
    solver.add_item(1000, 500, 8, 'B')
    solver.add_item(600, 400, 15, 'C')
    solver.add_item(1200, 800, 5, 'D')

    # Solve
    print("Solving two-stage guillotine cutting...")
    solution = solver.solve_simple()

    print(f"\nSheets needed: {solution['num_sheets']}")
    print(f"Utilization: {solution['utilization']:.2f}%")

    for i, sheet in enumerate(solution['sheets']):
        print(f"\nSheet {i+1}:")
        for strip in sheet['strips']:
            print(f"  Strip (h={strip['height']}): {strip['items']}")

    return solution

Method 2: Column Generation for 2D Cutting Stock

from pulp import *
import itertools

class ColumnGeneration2DCuttingStock:
    """
    Column Generation for 2D Cutting Stock Problem

    Uses:
    - Master Problem: Select best cutting patterns
    - Pricing Problem: Generate new patterns (2D knapsack)

    Note: Pricing problem for 2D is NP-hard itself
    We use heuristics for pattern generation
    """

    def __init__(self, sheet_width, sheet_height, items, kerf=0):
        """
        Initialize solver

        Parameters:
        - sheet_width: sheet width
        - sheet_height: sheet height
        - items: list of {'id', 'width', 'height', 'quantity'}
        - kerf: cutting kerf
        """
        self.sheet_width = sheet_width
        self.sheet_height = sheet_height
        self.items = items
        self.kerf = kerf
        self.n_items = len(items)

        self.patterns = []

    def generate_initial_patterns(self):
        """
        Generate initial patterns

        Simple approach: one item type per pattern, maximum quantity that fits
        """
        initial_patterns = []

        for item in self.items:
            # Calculate max items that fit
            max_cols = int(self.sheet_width / (item['width'] + self.kerf))
            max_rows = int(self.sheet_height / (item['height'] + self.kerf))
            max_items = max_cols * max_rows

            if max_items > 0:
                pattern = {
                    'items': {item['id']: max_items},
                    'layout': self._create_simple_layout(item, max_cols, max_rows)
                }
                initial_patterns.append(pattern)

            # Also try rotated
            if item['width'] != item['height']:
                max_cols_rot = int(self.sheet_width / (item['height'] + self.kerf))
                max_rows_rot = int(self.sheet_height / (item['width'] + self.kerf))
                max_items_rot = max_cols_rot * max_rows_rot

                if max_items_rot > max_items:
                    pattern = {
                        'items': {item['id']: max_items_rot},
                        'layout': self._create_simple_layout_rotated(item, max_cols_rot, max_rows_rot)
                    }
                    initial_patterns.append(pattern)

        self.patterns = initial_patterns
        return initial_patterns

    def _create_simple_layout(self, item, cols, rows):
        """Create simple grid layout"""
        layout = []
        for row in range(rows):
            for col in range(cols):
                layout.append({
                    'id': item['id'],
                    'x': col * (item['width'] + self.kerf),
                    'y': row * (item['height'] + self.kerf),
                    'width': item['width'],
                    'height': item['height'],
                    'rotated': False
                })
        return layout

    def _create_simple_layout_rotated(self, item, cols, rows):
        """Create simple grid layout with rotation"""
        layout = []
        for row in range(rows):
            for col in range(cols):
                layout.append({
                    'id': item['id'],
                    'x': col * (item['height'] + self.kerf),
                    'y': row * (item['width'] + self.kerf),
                    'width': item['height'],  # Swapped
                    'height': item['width'],  # Swapped
                    'rotated': True
                })
        return layout

    def solve_master_problem(self):
        """
        Solve Master Problem (LP Relaxation)

        min Σ x_p
        s.t. Σ a_ip * x_p >= d_i  ∀i
             x_p >= 0
        """

        prob = LpProblem("2D_Cutting_Master", LpMinimize)

        n_patterns = len(self.patterns)
        x = [LpVariable(f"x_{p}", lowBound=0, cat='Continuous')
             for p in range(n_patterns)]

        # Objective: minimize sheets
        prob += lpSum(x), "Total_Sheets"

        # Demand constraints
        for item in self.items:
            item_id = item['id']
            prob += lpSum(
                self.patterns[p]['items'].get(item_id, 0) * x[p]
                for p in range(n_patterns)
            ) >= item['quantity'], f"Demand_{item_id}"

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract dual values
        dual_values = {}
        for item in self.items:
            constraint_name = f"Demand_{item['id']}"
            for name, constraint in prob.constraints.items():
                if constraint_name in name:
                    dual_values[item['id']] = constraint.pi
                    break

        return {
            'objective': value(prob.objective),
            'pattern_usage': [x[p].varValue for p in range(n_patterns)],
            'dual_values': dual_values,
            'status': LpStatus[prob.status]
        }

    def solve_pricing_problem(self, dual_values):
        """
        Solve Pricing Problem: Find pattern with negative reduced cost

        This is a 2D knapsack problem - NP-hard
        We use heuristic pattern generation

        max Σ π_i * a_i
        s.t. items fit in sheet without overlap
        """

        # Use greedy heuristic to generate pattern
        # Try several heuristics and pick best

        best_pattern = None
        best_value = 0

        # Heuristic 1: Greedy by value density
        pattern1 = self._generate_pattern_greedy_value(dual_values)
        value1 = self._calculate_pattern_value(pattern1, dual_values)

        if value1 > best_value:
            best_value = value1
            best_pattern = pattern1

        # Heuristic 2: First Fit Decreasing
        pattern2 = self._generate_pattern_ffd(dual_values)
        value2 = self._calculate_pattern_value(pattern2, dual_values)

        if value2 > best_value:
            best_value = value2
            best_pattern = pattern2

        # Check reduced cost
        reduced_cost = 1 - best_value

        if reduced_cost >= -1e-6:
            return None  # No profitable pattern

        return best_pattern

    def _generate_pattern_greedy_value(self, dual_values):
        """Generate pattern greedily by value density"""

        # Calculate value per area for each item
        items_with_value = []
        for item in self.items:
            value_density = dual_values.get(item['id'], 0) / (item['width'] * item['height'])
            items_with_value.append((value_density, item))

        items_with_value.sort(reverse=True)

        # Greedy placement
        placed_items = []
        occupied = np.zeros((self.sheet_height, self.sheet_width), dtype=bool)

        for _, item in items_with_value:
            # Try to place as many as possible
            for rotation in [False, True]:
                w = item['width'] if not rotation else item['height']
                h = item['height'] if not rotation else item['width']

                # Find positions where item fits
                for y in range(0, self.sheet_height - h + 1, max(1, h // 10)):
                    for x in range(0, self.sheet_width - w + 1, max(1, w // 10)):
                        if not occupied[y:y+h, x:x+w].any():
                            # Place item
                            placed_items.append({
                                'id': item['id'],
                                'x': x,
                                'y': y,
                                'width': w,
                                'height': h,
                                'rotated': rotation
                            })
                            occupied[y:y+h, x:x+w] = True

        # Convert to pattern format
        pattern = {'items': {}, 'layout': placed_items}
        for placed in placed_items:
            item_id = placed['id']
            pattern['items'][item_id] = pattern['items'].get(item_id, 0) + 1

        return pattern

    def _generate_pattern_ffd(self, dual_values):
        """Generate pattern using First Fit Decreasing"""

        # Sort items by value (dual value)
        items_sorted = sorted(
            self.items,
            key=lambda x: dual_values.get(x['id'], 0),
            reverse=True
        )

        # Use shelf-based packing
        shelves = []
        placed_items = []

        for item in items_sorted:
            # Try both orientations
            for rotation in [False, True]:
                w = item['width'] if not rotation else item['height']
                h = item['height'] if not rotation else item['width']

                # Try to fit on existing shelf
                placed = False
                for shelf in shelves:
                    if shelf['remaining_width'] >= w and shelf['height'] >= h:
                        # Place on shelf
                        x = self.sheet_width - shelf['remaining_width']
                        y = shelf['y']

                        placed_items.append({
                            'id': item['id'],
                            'x': x,
                            'y': y,
                            'width': w,
                            'height': h,
                            'rotated': rotation
                        })

                        shelf['remaining_width'] -= w
                        placed = True
                        break

                if placed:
                    break

                # Try new shelf
                current_height = sum(s['height'] for s in shelves)
                if not placed and current_height + h <= self.sheet_height:
                    shelves.append({
                        'y': current_height,
                        'height': h,
                        'remaining_width': self.sheet_width - w
                    })

                    placed_items.append({
                        'id': item['id'],
                        'x': 0,
                        'y': current_height,
                        'width': w,
                        'height': h,
                        'rotated': rotation
                    })
                    break

        # Convert to pattern
        pattern = {'items': {}, 'layout': placed_items}
        for placed in placed_items:
            item_id = placed['id']
            pattern['items'][item_id] = pattern['items'].get(item_id, 0) + 1

        return pattern

    def _calculate_pattern_value(self, pattern, dual_values):
        """Calculate total value of pattern"""
        total_value = 0
        for item_id, count in pattern['items'].items():
            total_value += dual_values.get(item_id, 0) * count
        return total_value

    def solve(self, max_iterations=50):
        """
        Solve 2D cutting stock using column generation

        Returns: solution with patterns and usage
        """

        print("Starting 2D Column Generation...")

        # Generate initial patterns
        self.generate_initial_patterns()
        print(f"Initial patterns: {len(self.patterns)}")

        for iteration in range(max_iterations):
            # Solve master problem
            master_sol = self.solve_master_problem()

            print(f"Iteration {iteration+1}: LP Obj = {master_sol['objective']:.2f}")

            # Solve pricing problem
            new_pattern = self.solve_pricing_problem(master_sol['dual_values'])

            if new_pattern is None:
                print("No profitable pattern found. Optimal.")
                break

            # Add pattern
            self.patterns.append(new_pattern)
            print(f"  Added pattern with {sum(new_pattern['items'].values())} items")

        # Solve as IP
        print("\nSolving integer program...")
        final_solution = self.solve_master_ip()

        return final_solution

    def solve_master_ip(self):
        """Solve master problem as integer program"""

        prob = LpProblem("2D_Cutting_IP", LpMinimize)

        n_patterns = len(self.patterns)
        x = [LpVariable(f"x_{p}", lowBound=0, cat='Integer')
             for p in range(n_patterns)]

        prob += lpSum(x), "Total_Sheets"

        for item in self.items:
            item_id = item['id']
            prob += lpSum(
                self.patterns[p]['items'].get(item_id, 0) * x[p]
                for p in range(n_patterns)
            ) >= item['quantity'], f"Demand_{item_id}"

        prob.solve(PULP_CBC_CMD(msg=0))

        # Build solution
        pattern_usage = [x[p].varValue for p in range(n_patterns)]

        sheets = []
        for p, usage in enumerate(pattern_usage):
            if usage and usage > 0.5:
                for _ in range(int(usage)):
                    sheets.append({
                        'pattern_id': p,
                        'pattern': self.patterns[p],
                        'layout': self.patterns[p]['layout']
                    })

        # Calculate utilization
        sheet_area = self.sheet_width * self.sheet_height
        total_used = 0
        for sheet in sheets:
            for placed in sheet['layout']:
                total_used += placed['width'] * placed['height']

        utilization = (total_used / (len(sheets) * sheet_area) * 100) if sheets else 0

        return {
            'num_sheets': len(sheets),
            'sheets': sheets,
            'utilization': utilization,
            'total_waste': len(sheets) * sheet_area - total_used
        }


# Example usage
def example_2d_column_generation():
    """Example: 2D cutting stock with column generation"""

    items = [
        {'id': 'A', 'width': 800, 'height': 600, 'quantity': 10},
        {'id': 'B', 'width': 1000, 'height': 500, 'quantity': 8},
        {'id': 'C', 'width': 600, 'height': 400, 'quantity': 15},
        {'id': 'D', 'width': 1200, 'height': 800, 'quantity': 5}
    ]

    solver = ColumnGeneration2DCuttingStock(
        sheet_width=2440,
        sheet_height=1220,
        items=items,
        kerf=3
    )

    solution = solver.solve()

    print(f"\n{'='*70}")
    print(f"SOLUTION")
    print(f"{'='*70}")
    print(f"Sheets needed: {solution['num_sheets']}")
    print(f"Utilization: {solution['utilization']:.2f}%")
    print(f"Total waste: {solution['total_waste']}")

    return solution

Method 3: Guillotine Cutting with Pattern Generation

class GuillotineCuttingPattern:
    """
    Generate guillotine cutting patterns

    All cuts must be straight edge-to-edge
    """

    def __init__(self, sheet_width, sheet_height):
        self.sheet_width = sheet_width
        self.sheet_height = sheet_height

    def generate_guillotine_patterns(self, items, max_patterns=100):
        """
        Generate feasible guillotine cutting patterns

        Uses recursive subdivision
        """

        patterns = []

        # Try different first-cut positions and orientations
        for first_cut_horizontal in [True, False]:
            if first_cut_horizontal:
                # Horizontal first cut
                for cut_pos in range(100, self.sheet_height, 100):
                    pattern = self._recursive_guillotine(
                        0, 0, self.sheet_width, self.sheet_height,
                        items, cut_pos, True
                    )
                    if pattern:
                        patterns.append(pattern)

            else:
                # Vertical first cut
                for cut_pos in range(100, self.sheet_width, 100):
                    pattern = self._recursive_guillotine(
                        0, 0, self.sheet_width, self.sheet_height,
                        items, cut_pos, False
                    )
                    if pattern:
                        patterns.append(pattern)

            if len(patterns) >= max_patterns:
                break

        return patterns

    def _recursive_guillotine(self, x, y, width, height, items, cut_pos, horizontal):
        """
        Recursively generate guillotine pattern

        Parameters:
        - x, y: position of current rectangle
        - width, height: size of current rectangle
        - items: items to pack
        - cut_pos: position of guillotine cut
        - horizontal: True if horizontal cut, False if vertical
        """

        # Base case: try to fit single item type
        pattern = {'items': {}, 'layout': []}

        for item in items:
            # Try both orientations
            for rotated in [False, True]:
                w = item['width'] if not rotated else item['height']
                h = item['height'] if not rotated else item['width']

                # How many fit?
                cols = int(width / w)
                rows = int(height / h)
                count = cols * rows

                if count > 0:
                    # Create pattern with this item
                    for row in range(rows):
                        for col in range(cols):
                            pattern['layout'].append({
                                'id': item['id'],
                                'x': x + col * w,
                                'y': y + row * h,
                                'width': w,
                                'height': h,
                                'rotated': rotated
                            })
                    pattern['items'][item['id']] = count
                    return pattern

        return None

Complete 2D Cutting Stock Solver

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

class TwoDCuttingStockSolver:
    """
    Comprehensive 2D Cutting Stock Solver

    Supports:
    - Two-stage guillotine cutting
    - Column generation
    - Visualization
    - Export to cutting lists
    """

    def __init__(self, sheet_width, sheet_height, kerf=0):
        """
        Initialize solver

        Parameters:
        - sheet_width: standard sheet width
        - sheet_height: standard sheet height
        - kerf: saw blade kerf (material lost per cut)
        """
        self.sheet_width = sheet_width
        self.sheet_height = sheet_height
        self.kerf = kerf
        self.items = []
        self.solution = None

    def add_item(self, width, height, quantity, item_id=None):
        """Add rectangular item to cut list"""
        if item_id is None:
            item_id = f"Item_{len(self.items)}"

        self.items.append({
            'id': item_id,
            'width': width,
            'height': height,
            'quantity': quantity
        })

    def solve(self, method='two_stage'):
        """
        Solve 2D cutting stock problem

        Methods:
        - 'two_stage': Two-stage guillotine (fast, practical)
        - 'column_generation': Column generation (better, slower)

        Returns: solution
        """

        if method == 'two_stage':
            solver = TwoStageGuillotineCutting(
                self.sheet_width, self.sheet_height, self.kerf
            )
            for item in self.items:
                solver.add_item(item['width'], item['height'],
                              item['quantity'], item['id'])
            self.solution = solver.solve_simple()
            self.solution['method'] = 'Two-Stage Guillotine'

        elif method == 'column_generation':
            solver = ColumnGeneration2DCuttingStock(
                self.sheet_width, self.sheet_height, self.items, self.kerf
            )
            self.solution = solver.solve()
            self.solution['method'] = 'Column Generation'

        return self.solution

    def visualize(self, sheet_index=0, save_path=None):
        """
        Visualize cutting pattern for a specific sheet

        Parameters:
        - sheet_index: index of sheet to visualize
        - save_path: path to save figure
        """

        if self.solution is None:
            raise ValueError("No solution. Run solve() first.")

        if sheet_index >= len(self.solution['sheets']):
            raise ValueError(f"Sheet index {sheet_index} out of range")

        sheet = self.solution['sheets'][sheet_index]

        fig, ax = plt.subplots(figsize=(12, 8))

        # Draw sheet boundary
        ax.add_patch(patches.Rectangle(
            (0, 0), self.sheet_width, self.sheet_height,
            fill=False, edgecolor='black', linewidth=3
        ))

        # Get layout
        if 'layout' in sheet:
            layout = sheet['layout']
        else:
            # Reconstruct from strips
            layout = []
            y_pos = 0
            for strip in sheet.get('strips', []):
                for item in strip.get('items', []):
                    for i in range(item.get('count', 1)):
                        layout.append({
                            'id': item['id'],
                            'x': i * item['width'],
                            'y': y_pos,
                            'width': item['width'],
                            'height': item['height']
                        })
                y_pos += strip['height']

        # Draw items
        colors = plt.cm.tab20(np.linspace(0, 1, 20))

        for item in layout:
            color = colors[hash(item['id']) % 20]

            rect = patches.Rectangle(
                (item['x'], item['y']),
                item['width'], item['height'],
                facecolor=color, edgecolor='black',
                linewidth=1, alpha=0.7
            )
            ax.add_patch(rect)

            # Label
            cx = item['x'] + item['width'] / 2
            cy = item['y'] + item['height'] / 2
            ax.text(cx, cy, f"{item['id']}\n{item['width']}×{item['height']}",
                   ha='center', va='center',
                   fontsize=9, fontweight='bold',
                   bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))

        ax.set_xlim(0, self.sheet_width)
        ax.set_ylim(0, self.sheet_height)
        ax.set_aspect('equal')
        ax.set_xlabel('Width (mm)', fontsize=12)
        ax.set_ylabel('Height (mm)', fontsize=12)
        ax.set_title(
            f'2D Cutting Pattern - Sheet {sheet_index + 1}\n'
            f'Sheet: {self.sheet_width}×{self.sheet_height}mm',
            fontsize=14, fontweight='bold'
        )
        ax.grid(True, alpha=0.3)

        plt.tight_layout()

        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')

        plt.show()

    def print_solution(self):
        """Print solution summary"""

        if not self.solution:
            print("No solution available.")
            return

        print("=" * 80)
        print("2D CUTTING STOCK SOLUTION")
        print("=" * 80)
        print(f"Method: {self.solution.get('method', 'Unknown')}")
        print(f"Sheet size: {self.sheet_width} × {self.sheet_height}")
        print(f"Sheets used: {self.solution['num_sheets']}")
        print(f"Utilization: {self.solution.get('utilization', 0):.2f}%")
        print()

        print("Items to cut:")
        for item in self.items:
            print(f"  {item['id']}: {item['quantity']} pcs @ {item['width']}×{item['height']}")


# Example usage
if __name__ == "__main__":

    print("Example: Steel Plate Cutting")
    print("=" * 80)

    solver = TwoDCuttingStockSolver(
        sheet_width=2440,
        sheet_height=1220,
        kerf=3
    )

    solver.add_item(800, 600, 10, 'A')
    solver.add_item(1000, 500, 8, 'B')
    solver.add_item(600, 400, 15, 'C')
    solver.add_item(1200, 800, 5, 'D')

    # Solve
    solution = solver.solve(method='two_stage')
    solver.print_solution()

    # Visualize first sheet
    solver.visualize(sheet_index=0)

Tools & Libraries

Python Libraries

  • PuLP: Linear programming for column generation
  • OR-Tools: Google's optimization toolkit
  • py2d-pack: 2D packing algorithms
  • rectpack: Rectangle packing library

Commercial Software

  • CutLogic 2D: Professional 2D cutting optimizer
  • Cutting Optimization Pro: Glass and metal cutting
  • OptiCut: Sheet cutting optimization
  • MaxCut: Industrial cutting stock

Common Challenges & Solutions

Challenge: Guillotine Constraint Too Restrictive

Solution: Use three-stage cutting or limited non-guillotine cuts

Challenge: Many Small Items

Solution: Pre-clustering and hierarchical optimization

Challenge: Mixed Materials

Solution: Multi-objective optimization balancing cost and waste


Output Format

Solution Summary:

  • Sheets used: 8
  • Utilization: 87.3%
  • Method: Two-Stage Guillotine

Pattern Details: See cutting diagrams


Questions to Ask

  1. What material? (steel, glass, wood, fabric)
  2. Standard sheet size?
  3. Items list with dimensions and quantities?
  4. Guillotine cuts only?
  5. Can items rotate?
  6. Saw kerf width?
  7. Optimization goal?

Related Skills

  • 1d-cutting-stock: For 1D cutting problems
  • guillotine-cutting: For guillotine-specific algorithms
  • nesting-optimization: For irregular shapes
  • trim-loss-minimization: For general trim loss
  • 2d-bin-packing: For bin packing variants

3D Bin Packing

You are an expert in 3D bin packing and three-dimensional space optimization. Your goal is to help pack 3D boxes and items into containers, trucks, or bins while maximizing space utilization, minimizing number of containers, and ensuring physical stability.

Load Planning Rules

These rules matter most on real shipments: many order lines, upright cartons, and groups (POs, customers, stops) that must ship together. A wrong container count costs a full container of freight, so the claims you make about feasibility have to be as reliable as the plan itself.

Read grouping constraints literally

"Every PO ships whole in one container" decides which container each PO goes in. It says nothing about stacks, layers, or lanes. Cartons from different POs in the same container can share a stack, sit on each other, and fill each other's headroom. Commercial load planners do exactly this. Do not add a stricter rule (one PO per stack, one SKU per column, no mixing) unless the user asks for it. If a rule like that seems operationally necessary, ask, or show the plan both ways.

Separate proofs from search results

Only these facts prove that a load needs more containers, or that a group cannot ship whole:

  • Volume bound: total cargo volume / container volume, rounded up.
  • Payload bound: total weight / payload, rounded up.
  • Group too big: a group's volume or weight exceeds one container.
  • Dimension: a carton fits in no allowed orientation.

Everything else is a search result: a heuristic that did not find a fit, or a bound computed under a packing model you chose (homogeneous columns, whole layers, single-PO stacks). Report those as "my packer did not find an N-container plan", never as "N containers is impossible". A bound under your own model is not a lower bound for the real problem. Real plans beat it by mixing cartons within stacks and using headroom.

When the lower bound and your best plan differ, report both, plus the gap. If a group is truly too big (one of the bounds above), say so with the number. Offer a split or bigger equipment, and still plan everything else.

Use the headroom

Upright cartons stack in whole tiers, which leaves a gap under the roof. Five tiers of 49 cm cartons leave about 25 cm in a 269.5 cm high-cube. Flat cartons from other groups (rods, shelves, 10 cm boxes) fit there. Before concluding that a large group needs a container to itself, check whether small flat groups can ride on top of it.

Orientation

"This side up" cartons may only rotate about the vertical axis (2 orientations). The sample code's allow_rotation=True tries all 6 and will tip them. Use per-item allowed orientations.

Report slack and tolerance on tight plans

Master-data carton sizes are often a few millimetres off. For any container above about 85% fill, or any group above about 75% of a container, report the spare length, width, and height. Re-check the fit with every carton grown 1-3 mm per side. Recommend the tightest valid plan with its risk stated, and give a looser fallback separately. Do not swap the fallback in as the main answer without saying the tighter plan exists.

Verify every plan before reporting it

Check the actual carton positions before giving a container count:

  • Every carton placed exactly once.
  • Inside the container walls.
  • No overlaps.
  • Upright cartons kept upright.
  • Each stacked carton supported over most of its base (70-80% or more).
  • Weight within payload.

Say which checks ran. A plan that has not been checked is a draft.

Use the bundled planner for real shipments

For a real carton list (order lines with dimensions, counts and weights), run the bundled planner before writing your own packer:

python3 scripts/load_plan.py shipment.csv --out plan/

It uses only the Python standard library. The input CSV needs these columns: po, sku, length_cm, width_cm, height_cm, line_weight_kg, cartons, this_side_up. Rename the user's columns to match. Use --group-col if the grouping key is something other than a PO (a customer, a stop). Container defaults are a 40' HC: 1203.5 × 235.2 × 269.5 cm and 28,620 kg. Pass --length --width --height --payload for other equipment or the carrier's exact box.

What it does:

  • Computes the lower bound and flags any group that cannot ship whole, with the reason.
  • Assigns groups to containers.
  • Packs each container from single-SKU columns in lanes, with flat cartons riding in the headroom.
  • Re-checks every container with cartons 1, 2 and 3 mm larger.
  • Verifies every carton's position.

Read plan/report.md and plan/summary.json, and build your answer from them:

  • the container count against the lower bound, and whether it is proven optimal;
  • each container's groups and fill;
  • the tolerance results;
  • any oversize group.

Oversize groups are left unassigned by default. When there is one, also run the planner with --split-oversize into a second folder (--out plan-split/). Then report both plans: the count without the oversize group, and the total count with it split. That way the user decides with the real number in front of them, not an estimate. Recommend neither until they approve the split. If the planner uses more containers than the lower bound, say "best found, not proven optimal", and you may try to improve on it. If your own search finds a better plan, verify it to the same standard before you report it.

Top up booked containers (Advisor)

On full-container freight the booked space is already paid for. After a plan is settled, or when the user asks what else fits, run the Advisor. It keeps the container count and each PO's container fixed, and recommends extra cartons of lines already in each container:

python3 scripts/load_plan.py shipment.csv --out advice/ --advise [--allocation allocation.csv]
    [--objective volume|cartons|value] [--limits limits.csv]
  • Without --allocation it plans first, then advises on that plan. Pass --allocation (columns po,container) to advise on a plan the user already has, for example one from another load planner.
  • --objective volume is the default and fills the most cubic metres. cartons maximises the number of extra cartons. value needs value_per_carton in the limits file.
  • limits.csv (columns po,sku, plus optional max_extra, multiple and value_per_carton) caps each line, respects case packs, and sets the value used by --objective value. Ask the user for limits when they matter: open-to-buy, forecast, supplier stock, case packs. Uncapped advice will happily fill a box with one bulky SKU.
  • Report the recommendations from advice/advice.csv as suggestions for the buyer or supplier, never as an order. For each line give the PO, the SKU, the extra cartons and the extra m³. Give the base and advised fill per container, the extra weight, and the tolerance of the fuller load, since topped-up containers are tighter.

About the code below

The code further down teaches the classic algorithms. It does not handle grouping constraints or per-item orientation. The extreme-point and layer sketches can leave boxes floating. Do not take their container count as evidence that a load needs more containers.

Initial Assessment

Before solving 3D bin packing problems, understand:

  1. Problem Objectives

    • Minimize number of containers/bins used?
    • Maximize utilization of fixed containers?
    • Minimize shipping costs?
    • Ensure load stability?
  2. Item Specifications

    • How many items to pack? (10s, 100s, 1000s)
    • Item dimensions: length x width x height
    • Item weights (important for stability)?
    • Fragility or stackability constraints?
    • Can items be rotated? (all 6 orientations or restricted?)
  3. Container Specifications

    • Container dimensions: L x W x H
    • Weight capacity limit?
    • Multiple container types available?
    • Unlimited containers or fixed quantity?
  4. Physical Constraints

    • Weight distribution requirements?
    • Center of gravity constraints?
    • Stacking limits (max items on top)?
    • Fragile items (can't be at bottom)?
    • Load sequence requirements (LIFO/FIFO)?
  5. Special Requirements

    • Multi-drop deliveries (order matters)?
    • Groups that must stay together (PO, customer, stop)? Together in one container, or also in separate stacks? (Default: same container only.)
    • How exact are the carton dimensions? Any dunnage or clearance to reserve?
    • Axle weight limits?
    • Door access considerations?

3D Bin Packing Framework

Problem Classification

1. 3D Bin Packing Problem (3D-BPP)

  • Pack boxes into minimum number of identical bins
  • All items must be packed
  • No overlapping
  • Items axis-aligned or with rotation

2. Single Container Loading Problem

  • Maximize utilization of one container
  • May not fit all items
  • Focus on space efficiency

3. Pallet/Container Loading Problem

  • Pack onto pallets first, then into containers
  • Two-level optimization
  • Consider pallet arrangements

4. Multi-Container Heterogeneous Packing

  • Different container sizes available
  • Optimize container selection + packing
  • Minimize total cost or volume

5. Weight-Constrained 3D Packing

  • Both volume and weight limits
  • Weight distribution matters
  • Center of gravity constraints

Mathematical Formulation

Basic 3D Bin Packing Model

Decision Variables:

  • x_i, y_i, z_i = coordinates of item i's corner
  • b_i = bin/container number for item i
  • o_i = orientation of item i (0-5 for 6 possible rotations)
  • used_j = 1 if bin j is used, 0 otherwise

Objective: Minimize ∑ used_j (minimize bins)

Constraints:

  1. Non-overlap: No two items in same bin overlap
  2. Containment: All items fit within bin boundaries
  3. Support: Items have adequate support from below
  4. Weight: Total weight ≤ capacity
  5. Stability: Center of gravity within bounds

Complexity:

  • NP-hard (even harder than 2D)
  • 3D version significantly more complex
  • Requires sophisticated heuristics

Algorithms and Solution Methods

Exact Methods

Integer Programming Formulation

from pulp import *
import numpy as np

def solve_3d_bin_packing_ip(items, bin_dims, max_bins=None):
    """
    3D Bin Packing using Integer Programming

    WARNING: Only practical for very small problems (<10 items)

    Parameters:
    - items: list of (length, width, height, weight, id) tuples
    - bin_dims: (length, width, height, weight_capacity)
    - max_bins: maximum bins to consider

    Returns optimal solution (if found within time limit)
    """

    n = len(items)
    if max_bins is None:
        max_bins = n

    L, W, H, max_weight = bin_dims
    bins = range(max_bins)
    item_ids = range(n)

    prob = LpProblem("3D_Bin_Packing", LpMinimize)

    # Decision variables
    # Position of item i in bin b
    x = LpVariable.dicts("x", [(i,b) for i in item_ids for b in bins],
                        lowBound=0, upBound=L, cat='Continuous')
    y = LpVariable.dicts("y", [(i,b) for i in item_ids for b in bins],
                        lowBound=0, upBound=W, cat='Continuous')
    z = LpVariable.dicts("z", [(i,b) for i in item_ids for b in bins],
                        lowBound=0, upBound=H, cat='Continuous')

    # Assignment: item i in bin b
    a = LpVariable.dicts("assign", [(i,b) for i in item_ids for b in bins],
                        cat='Binary')

    # Bin used
    used = LpVariable.dicts("used", bins, cat='Binary')

    # Objective
    prob += lpSum([used[b] for b in bins]), "Total_Bins"

    # Constraints

    # 1. Each item in exactly one bin
    for i in item_ids:
        prob += lpSum([a[i,b] for b in bins]) == 1, f"Assign_{i}"

    # 2. Items fit in bin boundaries
    for i in item_ids:
        for b in bins:
            l, w, h, weight, _ = items[i]
            M = max(L, W, H)  # Big M

            prob += x[i,b] + l <= L + M * (1 - a[i,b]), f"FitL_{i}_{b}"
            prob += y[i,b] + w <= W + M * (1 - a[i,b]), f"FitW_{i}_{b}"
            prob += z[i,b] + h <= H + M * (1 - a[i,b]), f"FitH_{i}_{b}"

    # 3. Weight capacity
    for b in bins:
        prob += lpSum([items[i][3] * a[i,b] for i in item_ids]) <= \
                max_weight, f"Weight_{b}"

    # 4. Bin used if items assigned
    for b in bins:
        for i in item_ids:
            prob += a[i,b] <= used[b], f"BinUsed_{i}_{b}"

    # Note: Non-overlap constraints are complex and omitted in this simplified version

    # Solve with time limit
    prob.solve(PULP_CBC_CMD(msg=1, timeLimit=300))

    if LpStatus[prob.status] != 'Optimal':
        return None

    # Extract solution
    solution = {'num_bins': int(value(prob.objective)), 'bins': []}

    for b in bins:
        if used[b].varValue > 0.5:
            bin_items = []
            for i in item_ids:
                if a[i,b].varValue > 0.5:
                    bin_items.append({
                        'item_id': i,
                        'position': (x[i,b].varValue, y[i,b].varValue, z[i,b].varValue),
                        'dimensions': items[i][:3],
                        'weight': items[i][3]
                    })
            solution['bins'].append(bin_items)

    return solution

Heuristic Methods

Bottom-Left-Back (BLB) Algorithm

  • Greedy placement strategy
  • Place items at lowest, leftmost, back-most position
  • Fast but may not be optimal
class Box:
    """3D Box representation"""
    def __init__(self, length, width, height, weight=0, item_id=None):
        self.length = length
        self.width = width
        self.height = height
        self.weight = weight
        self.item_id = item_id

    def volume(self):
        return self.length * self.width * self.height

    def can_support(self, other_box):
        """Check if this box can support another box on top"""
        # Simple check: base area
        return (self.length >= other_box.length and
                self.width >= other_box.width)

class Space:
    """Available 3D space in container"""
    def __init__(self, x, y, z, length, width, height):
        self.x = x
        self.y = y
        self.z = z
        self.length = length
        self.width = width
        self.height = height

    def volume(self):
        return self.length * self.width * self.height

    def fits(self, box, orientation):
        """Check if box fits in this space with given orientation"""
        l, w, h = self.get_oriented_dimensions(box, orientation)
        return l <= self.length and w <= self.width and h <= self.height

    @staticmethod
    def get_oriented_dimensions(box, orientation):
        """Get box dimensions for given orientation (0-5)"""
        dims = [box.length, box.width, box.height]

        # 6 possible orientations (assuming rectangular boxes)
        orientations = [
            (0, 1, 2),  # Original: L, W, H
            (0, 2, 1),  # Rotated: L, H, W
            (1, 0, 2),  # Rotated: W, L, H
            (1, 2, 0),  # Rotated: W, H, L
            (2, 0, 1),  # Rotated: H, L, W
            (2, 1, 0),  # Rotated: H, W, L
        ]

        perm = orientations[orientation]
        return dims[perm[0]], dims[perm[1]], dims[perm[2]]

def bottom_left_back_packing(items, container_dims, allow_rotation=True):
    """
    Bottom-Left-Back (BLB) Algorithm for 3D Bin Packing

    Greedy algorithm that places each item at the lowest,
    leftmost, back-most available position

    Parameters:
    - items: list of Box objects
    - container_dims: (length, width, height, max_weight)
    - allow_rotation: whether to try different orientations

    Returns packing solution
    """

    L, W, H, max_weight = container_dims

    # Sort items by volume (largest first)
    sorted_items = sorted(items, key=lambda b: b.volume(), reverse=True)

    containers = []

    for box in sorted_items:
        placed = False

        # Try existing containers
        for container in containers:
            spaces = container['spaces']
            current_weight = container['total_weight']

            # Try each available space
            for space_idx, space in enumerate(spaces):

                # Try different orientations
                orientations = range(6) if allow_rotation else [0]

                for orientation in orientations:
                    l, w, h = Space.get_oriented_dimensions(box, orientation)

                    if (space.fits(box, orientation) and
                        current_weight + box.weight <= max_weight):

                        # Place box
                        container['items'].append({
                            'box': box,
                            'position': (space.x, space.y, space.z),
                            'dimensions': (l, w, h),
                            'orientation': orientation
                        })

                        container['total_weight'] += box.weight

                        # Remove used space and add new spaces
                        spaces.pop(space_idx)
                        new_spaces = create_residual_spaces(space, l, w, h)
                        spaces.extend(new_spaces)

                        # Sort spaces by position (bottom-left-back first)
                        spaces.sort(key=lambda s: (s.z, s.y, s.x))

                        placed = True
                        break

                if placed:
                    break

            if placed:
                break

        # Create new container if not placed
        if not placed:
            l, w, h = box.length, box.width, box.height

            new_container = {
                'items': [{
                    'box': box,
                    'position': (0, 0, 0),
                    'dimensions': (l, w, h),
                    'orientation': 0
                }],
                'spaces': [],
                'total_weight': box.weight,
                'dimensions': (L, W, H)
            }

            # Create initial residual spaces
            initial_space = Space(0, 0, 0, L, W, H)
            new_spaces = create_residual_spaces(initial_space, l, w, h)
            new_container['spaces'] = new_spaces

            containers.append(new_container)

    return {
        'num_containers': len(containers),
        'containers': containers,
        'utilization': calculate_3d_utilization(containers, L, W, H)
    }

def create_residual_spaces(space, used_l, used_w, used_h):
    """
    Create residual spaces after placing a box

    Returns up to 3 new spaces
    """
    spaces = []

    # Space to the right
    if space.length > used_l:
        spaces.append(Space(
            space.x + used_l, space.y, space.z,
            space.length - used_l, space.width, space.height
        ))

    # Space in front
    if space.width > used_w:
        spaces.append(Space(
            space.x, space.y + used_w, space.z,
            used_l, space.width - used_w, space.height
        ))

    # Space above
    if space.height > used_h:
        spaces.append(Space(
            space.x, space.y, space.z + used_h,
            used_l, used_w, space.height - used_h
        ))

    return spaces

def calculate_3d_utilization(containers, L, W, H):
    """Calculate volume utilization percentage"""
    total_item_volume = 0
    for container in containers:
        for item in container['items']:
            l, w, h = item['dimensions']
            total_item_volume += l * w * h

    total_container_volume = len(containers) * L * W * H
    return (total_item_volume / total_container_volume * 100) if total_container_volume > 0 else 0

Layer Building Algorithm

  • Build horizontal layers
  • Pack items within each layer (2D problem)
  • Stack layers vertically
  • Good for real-world packing
def layer_building_algorithm(items, container_dims):
    """
    Layer Building Algorithm for 3D Packing

    Builds horizontal layers and packs items within each layer
    More practical for real-world loading

    Parameters:
    - items: list of Box objects
    - container_dims: (length, width, height, max_weight)

    Returns layered packing solution
    """

    L, W, H, max_weight = container_dims

    # Sort items by height (tallest first for each layer)
    sorted_items = sorted(items, key=lambda b: b.height, reverse=True)

    containers = []

    remaining_items = sorted_items.copy()

    while remaining_items:
        # Start new container
        container = {
            'layers': [],
            'items': [],
            'total_weight': 0,
            'current_height': 0
        }

        while remaining_items and container['current_height'] < H:
            # Select items for new layer
            layer_height = remaining_items[0].height

            # Find items that fit in this layer height
            layer_items = [
                item for item in remaining_items
                if item.height == layer_height
            ]

            if not layer_items:
                # Try next height
                remaining_items.pop(0)
                continue

            # Check if layer fits
            if container['current_height'] + layer_height > H:
                break

            # Pack items in 2D for this layer
            layer_packing = pack_layer_2d(
                layer_items, L, W,
                max_weight - container['total_weight']
            )

            if not layer_packing['items']:
                break

            # Add layer to container
            layer_z = container['current_height']

            for item_data in layer_packing['items']:
                container['items'].append({
                    'box': item_data['box'],
                    'position': (
                        item_data['x'],
                        item_data['y'],
                        layer_z
                    ),
                    'dimensions': (
                        item_data['box'].length,
                        item_data['box'].width,
                        item_data['box'].height
                    ),
                    'layer': len(container['layers'])
                })

                container['total_weight'] += item_data['box'].weight
                remaining_items.remove(item_data['box'])

            container['layers'].append({
                'z': layer_z,
                'height': layer_height,
                'items': layer_packing['items']
            })

            container['current_height'] += layer_height

        if container['items']:
            containers.append(container)

        # If no items packed, need new strategy
        if remaining_items and not container['items']:
            # Force pack at least one item
            item = remaining_items.pop(0)
            new_container = {
                'items': [{
                    'box': item,
                    'position': (0, 0, 0),
                    'dimensions': (item.length, item.width, item.height),
                    'layer': 0
                }],
                'layers': [{'z': 0, 'height': item.height, 'items': [item]}],
                'total_weight': item.weight,
                'current_height': item.height
            }
            containers.append(new_container)

    return {
        'num_containers': len(containers),
        'containers': containers,
        'utilization': calculate_3d_utilization(containers, L, W, H)
    }

def pack_layer_2d(items, layer_length, layer_width, remaining_weight):
    """
    Pack items in 2D for a single layer

    Uses simple FFDH algorithm adapted for 2D
    """

    # Sort by area
    sorted_items = sorted(items, key=lambda b: b.length * b.width, reverse=True)

    packed_items = []
    strips = []  # Horizontal strips in the layer
    total_weight = 0

    for box in sorted_items:
        if total_weight + box.weight > remaining_weight:
            continue

        placed = False

        # Try existing strips
        for strip in strips:
            if (strip['remaining_length'] >= box.length and
                strip['width'] >= box.width):

                # Place in strip
                x = layer_length - strip['remaining_length']
                y = strip['y']

                packed_items.append({
                    'box': box,
                    'x': x,
                    'y': y
                })

                strip['remaining_length'] -= box.length
                total_weight += box.weight
                placed = True
                break

        if not placed:
            # Create new strip
            current_width = sum(s['width'] for s in strips)

            if current_width + box.width <= layer_width:
                new_strip = {
                    'y': current_width,
                    'width': box.width,
                    'remaining_length': layer_length - box.length
                }
                strips.append(new_strip)

                packed_items.append({
                    'box': box,
                    'x': 0,
                    'y': current_width
                })

                total_weight += box.weight

    return {'items': packed_items}

Extreme Point Algorithm

  • Maintains set of extreme points (potential placement positions)
  • Places boxes at extreme points
  • More sophisticated than BLB
class ExtremePoint:
    """3D Extreme Point for placement"""
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __lt__(self, other):
        # Sort by z (height), then y (width), then x (length)
        return (self.z, self.y, self.x) < (other.z, other.y, other.x)

def extreme_point_algorithm(items, container_dims, allow_rotation=True):
    """
    Extreme Point Algorithm for 3D Packing

    Uses extreme points as potential placement positions
    Generally better quality than simple BLB

    Parameters:
    - items: list of Box objects
    - container_dims: (L, W, H, max_weight)
    - allow_rotation: allow 6 orientations
    """

    L, W, H, max_weight = container_dims

    # Sort by volume
    sorted_items = sorted(items, key=lambda b: b.volume(), reverse=True)

    containers = []

    for box in sorted_items:
        placed = False

        # Try existing containers
        for container in containers:
            extreme_points = container['extreme_points']
            current_weight = container['total_weight']

            # Sort extreme points (lowest, leftmost, back-most first)
            extreme_points.sort()

            for ep in extreme_points[:]:  # Copy list as we'll modify it
                orientations = range(6) if allow_rotation else [0]

                for orientation in orientations:
                    l, w, h = Space.get_oriented_dimensions(box, orientation)

                    # Check if box fits at this extreme point
                    if (ep.x + l <= L and ep.y + w <= W and ep.z + h <= H and
                        current_weight + box.weight <= max_weight):

                        # Check for overlap with existing items
                        overlaps = False
                        for existing in container['items']:
                            if boxes_overlap_3d(
                                ep.x, ep.y, ep.z, l, w, h,
                                existing['position'][0], existing['position'][1], existing['position'][2],
                                existing['dimensions'][0], existing['dimensions'][1], existing['dimensions'][2]
                            ):
                                overlaps = True
                                break

                        if not overlaps:
                            # Place box
                            container['items'].append({
                                'box': box,
                                'position': (ep.x, ep.y, ep.z),
                                'dimensions': (l, w, h),
                                'orientation': orientation
                            })

                            container['total_weight'] += box.weight

                            # Remove this extreme point
                            extreme_points.remove(ep)

                            # Generate new extreme points
                            new_eps = [
                                ExtremePoint(ep.x + l, ep.y, ep.z),      # Right
                                ExtremePoint(ep.x, ep.y + w, ep.z),      # Front
                                ExtremePoint(ep.x, ep.y, ep.z + h)       # Top
                            ]

                            # Add only feasible extreme points
                            for new_ep in new_eps:
                                if (new_ep.x < L and new_ep.y < W and new_ep.z < H):
                                    # Check if not dominated by existing EP
                                    if not is_dominated(new_ep, extreme_points):
                                        extreme_points.append(new_ep)

                            placed = True
                            break

                if placed:
                    break

            if placed:
                break

        # Create new container
        if not placed:
            l, w, h = box.length, box.width, box.height

            new_container = {
                'items': [{
                    'box': box,
                    'position': (0, 0, 0),
                    'dimensions': (l, w, h),
                    'orientation': 0
                }],
                'extreme_points': [
                    ExtremePoint(l, 0, 0),
                    ExtremePoint(0, w, 0),
                    ExtremePoint(0, 0, h)
                ],
                'total_weight': box.weight
            }

            containers.append(new_container)

    return {
        'num_containers': len(containers),
        'containers': containers,
        'utilization': calculate_3d_utilization(containers, L, W, H)
    }

def boxes_overlap_3d(x1, y1, z1, l1, w1, h1, x2, y2, z2, l2, w2, h2):
    """Check if two 3D boxes overlap"""
    return not (x1 + l1 <= x2 or x2 + l2 <= x1 or
                y1 + w1 <= y2 or y2 + w2 <= y1 or
                z1 + h1 <= z2 or z2 + h2 <= z1)

def is_dominated(point, existing_points):
    """Check if point is dominated by any existing point"""
    for ep in existing_points:
        if ep.x <= point.x and ep.y <= point.y and ep.z <= point.z:
            if ep.x < point.x or ep.y < point.y or ep.z < point.z:
                return True
    return False

Metaheuristic Methods

Genetic Algorithm for 3D Packing

import random
import numpy as np

class GeneticAlgorithm3DPacking:
    """
    Genetic Algorithm for 3D Bin Packing

    Chromosome encodes:
    - Item sequence (order to pack)
    - Orientation for each item
    """

    def __init__(self, items, container_dims,
                 population_size=50, generations=100,
                 mutation_rate=0.15, crossover_rate=0.8):
        self.items = items
        self.container_dims = container_dims
        self.population_size = population_size
        self.generations = generations
        self.mutation_rate = mutation_rate
        self.crossover_rate = crossover_rate

        self.n_items = len(items)
        self.best_solution = None
        self.best_fitness = float('inf')

    def create_chromosome(self):
        """
        Create random chromosome

        Chromosome = (sequence, orientations)
        """
        sequence = list(np.random.permutation(self.n_items))
        orientations = [random.randint(0, 5) for _ in range(self.n_items)]
        return {'sequence': sequence, 'orientations': orientations}

    def decode_chromosome(self, chromosome):
        """Decode chromosome to packing solution using BLB"""
        ordered_items = [self.items[i] for i in chromosome['sequence']]

        # Apply orientations (simplified - just use orientation 0 for now)
        result = bottom_left_back_packing(
            ordered_items, self.container_dims, allow_rotation=True
        )
        return result

    def fitness(self, chromosome):
        """
        Fitness = number of containers (minimize)
        Secondary: maximize utilization
        """
        solution = self.decode_chromosome(chromosome)
        # Minimize bins, maximize utilization
        return solution['num_containers'] - solution['utilization'] / 1000

    def crossover(self, parent1, parent2):
        """Order crossover for sequence + uniform for orientations"""
        if random.random() > self.crossover_rate:
            return parent1.copy(), parent2.copy()

        # Crossover sequence (OX)
        size = len(parent1['sequence'])
        cx_point1 = random.randint(0, size - 2)
        cx_point2 = random.randint(cx_point1 + 1, size - 1)

        child1_seq = [-1] * size
        child2_seq = [-1] * size

        child1_seq[cx_point1:cx_point2] = parent1['sequence'][cx_point1:cx_point2]
        child2_seq[cx_point1:cx_point2] = parent2['sequence'][cx_point1:cx_point2]

        self._fill_sequence(child1_seq, parent2['sequence'], cx_point2)
        self._fill_sequence(child2_seq, parent1['sequence'], cx_point2)

        # Crossover orientations (uniform)
        child1_orient = []
        child2_orient = []
        for i in range(size):
            if random.random() < 0.5:
                child1_orient.append(parent1['orientations'][i])
                child2_orient.append(parent2['orientations'][i])
            else:
                child1_orient.append(parent2['orientations'][i])
                child2_orient.append(parent1['orientations'][i])

        return (
            {'sequence': child1_seq, 'orientations': child1_orient},
            {'sequence': child2_seq, 'orientations': child2_orient}
        )

    def _fill_sequence(self, child, parent, start_pos):
        """Fill offspring sequence"""
        child_set = set([x for x in child if x != -1])
        pos = start_pos

        for item in parent[start_pos:] + parent[:start_pos]:
            if item not in child_set:
                while child[pos % len(child)] != -1:
                    pos += 1
                child[pos % len(child)] = item
                child_set.add(item)

    def mutate(self, chromosome):
        """
        Mutation: swap two items in sequence
        and randomly change some orientations
        """
        # Swap mutation on sequence
        if random.random() < self.mutation_rate:
            pos1, pos2 = random.sample(range(self.n_items), 2)
            seq = chromosome['sequence']
            seq[pos1], seq[pos2] = seq[pos2], seq[pos1]

        # Random change on orientations
        for i in range(self.n_items):
            if random.random() < self.mutation_rate / 2:
                chromosome['orientations'][i] = random.randint(0, 5)

        return chromosome

    def tournament_selection(self, population, fitnesses, tournament_size=3):
        """Tournament selection"""
        tournament_idx = random.sample(range(len(population)), tournament_size)
        tournament_fit = [fitnesses[i] for i in tournament_idx]
        winner_idx = tournament_idx[tournament_fit.index(min(tournament_fit))]
        return population[winner_idx]

    def solve(self):
        """Run genetic algorithm"""
        # Initialize population
        population = [self.create_chromosome() for _ in range(self.population_size)]

        for generation in range(self.generations):
            # Evaluate fitness
            fitnesses = [self.fitness(chrom) for chrom in population]

            # Track best
            min_fit_idx = fitnesses.index(min(fitnesses))
            if fitnesses[min_fit_idx] < self.best_fitness:
                self.best_fitness = fitnesses[min_fit_idx]
                self.best_solution = self.decode_chromosome(population[min_fit_idx])
                print(f"Gen {generation}: Best = {self.best_solution['num_containers']} containers")

            # New population
            new_population = [population[min_fit_idx]]  # Elitism

            while len(new_population) < self.population_size:
                parent1 = self.tournament_selection(population, fitnesses)
                parent2 = self.tournament_selection(population, fitnesses)

                child1, child2 = self.crossover(parent1, parent2)

                child1 = self.mutate(child1)
                child2 = self.mutate(child2)

                new_population.extend([child1, child2])

            population = new_population[:self.population_size]

        return self.best_solution

Complete 3D Bin Packing Solver

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np

class ThreeDimensionalBinPacker:
    """
    Comprehensive 3D Bin Packing Solver

    Supports multiple algorithms, visualization, and physical constraints
    """

    def __init__(self, container_length, container_width, container_height,
                 weight_capacity=None):
        self.container_dims = (
            container_length, container_width, container_height,
            weight_capacity if weight_capacity else float('inf')
        )
        self.items = []
        self.solution = None

    def add_item(self, length, width, height, weight=0, item_id=None,
                 stackable=True, fragile=False):
        """Add item to pack"""
        if item_id is None:
            item_id = f"Item_{len(self.items)}"

        box = Box(length, width, height, weight, item_id)
        box.stackable = stackable
        box.fragile = fragile
        self.items.append(box)

    def add_items_from_list(self, items_data):
        """
        Add multiple items

        items_data: list of dicts with keys: length, width, height, weight
        """
        for item in items_data:
            self.add_item(
                item.get('length'),
                item.get('width'),
                item.get('height'),
                item.get('weight', 0),
                item.get('id'),
                item.get('stackable', True),
                item.get('fragile', False)
            )

    def solve(self, algorithm='blb', **kwargs):
        """
        Solve 3D packing problem

        Algorithms:
        - 'blb': Bottom-Left-Back
        - 'layer': Layer Building
        - 'extreme_point': Extreme Point
        - 'genetic': Genetic Algorithm
        """

        if algorithm == 'blb':
            self.solution = bottom_left_back_packing(
                self.items, self.container_dims,
                kwargs.get('allow_rotation', True)
            )

        elif algorithm == 'layer':
            self.solution = layer_building_algorithm(
                self.items, self.container_dims
            )

        elif algorithm == 'extreme_point':
            self.solution = extreme_point_algorithm(
                self.items, self.container_dims,
                kwargs.get('allow_rotation', True)
            )

        elif algorithm == 'genetic':
            ga = GeneticAlgorithm3DPacking(
                self.items, self.container_dims,
                population_size=kwargs.get('population_size', 50),
                generations=kwargs.get('generations', 100)
            )
            self.solution = ga.solve()

        else:
            raise ValueError(f"Unknown algorithm: {algorithm}")

        return self.solution

    def visualize(self, container_index=0, save_path=None):
        """
        3D visualization of packing solution

        Parameters:
        - container_index: which container to visualize
        - save_path: path to save figure
        """

        if self.solution is None:
            raise ValueError("No solution to visualize")

        if container_index >= len(self.solution['containers']):
            raise ValueError(f"Container index {container_index} out of range")

        container = self.solution['containers'][container_index]
        L, W, H = self.container_dims[:3]

        fig = plt.figure(figsize=(12, 10))
        ax = fig.add_subplot(111, projection='3d')

        # Draw container boundaries
        self._draw_container_box(ax, L, W, H)

        # Draw items
        colors = plt.cm.tab20(np.linspace(0, 1, 20))

        for idx, item in enumerate(container['items']):
            pos = item['position']
            dims = item['dimensions']
            color = colors[idx % 20]

            self._draw_box(ax, pos, dims, color, alpha=0.7)

            # Add label
            center = (
                pos[0] + dims[0]/2,
                pos[1] + dims[1]/2,
                pos[2] + dims[2]/2
            )
            ax.text(center[0], center[1], center[2],
                   str(item['box'].item_id),
                   fontsize=8, ha='center')

        ax.set_xlabel('Length')
        ax.set_ylabel('Width')
        ax.set_zlabel('Height')
        ax.set_title(f'Container {container_index + 1}\n'
                    f'{len(container["items"])} items | '
                    f'Weight: {container["total_weight"]:.1f}')

        # Set equal aspect ratio
        max_dim = max(L, W, H)
        ax.set_xlim(0, max_dim)
        ax.set_ylim(0, max_dim)
        ax.set_zlim(0, max_dim)

        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')

        plt.show()

    def _draw_container_box(self, ax, L, W, H):
        """Draw container boundary wireframe"""
        # Define the 8 vertices of the container
        vertices = [
            [0, 0, 0], [L, 0, 0], [L, W, 0], [0, W, 0],  # Bottom
            [0, 0, H], [L, 0, H], [L, W, H], [0, W, H]   # Top
        ]

        # Define the 12 edges
        edges = [
            [0, 1], [1, 2], [2, 3], [3, 0],  # Bottom
            [4, 5], [5, 6], [6, 7], [7, 4],  # Top
            [0, 4], [1, 5], [2, 6], [3, 7]   # Vertical
        ]

        for edge in edges:
            points = [vertices[edge[0]], vertices[edge[1]]]
            ax.plot3D(*zip(*points), 'k-', linewidth=2)

    def _draw_box(self, ax, position, dimensions, color, alpha=0.7):
        """Draw a 3D box"""
        x, y, z = position
        l, w, h = dimensions

        # Define 8 vertices of the box
        vertices = np.array([
            [x, y, z], [x+l, y, z], [x+l, y+w, z], [x, y+w, z],
            [x, y, z+h], [x+l, y, z+h], [x+l, y+w, z+h], [x, y+w, z+h]
        ])

        # Define 6 faces
        faces = [
            [vertices[0], vertices[1], vertices[5], vertices[4]],  # Front
            [vertices[2], vertices[3], vertices[7], vertices[6]],  # Back
            [vertices[0], vertices[3], vertices[7], vertices[4]],  # Left
            [vertices[1], vertices[2], vertices[6], vertices[5]],  # Right
            [vertices[0], vertices[1], vertices[2], vertices[3]],  # Bottom
            [vertices[4], vertices[5], vertices[6], vertices[7]]   # Top
        ]

        face_collection = Poly3DCollection(faces,
                                          facecolors=color,
                                          linewidths=1,
                                          edgecolors='black',
                                          alpha=alpha)
        ax.add_collection3d(face_collection)

    def get_statistics(self):
        """Get detailed statistics"""
        if self.solution is None:
            return None

        L, W, H, max_weight = self.container_dims

        total_item_volume = sum(b.volume() for b in self.items)
        total_container_volume = self.solution['num_containers'] * L * W * H

        stats = {
            'num_items': len(self.items),
            'num_containers': self.solution['num_containers'],
            'container_dims': (L, W, H),
            'weight_capacity': max_weight,
            'total_item_volume': total_item_volume,
            'total_container_volume': total_container_volume,
            'utilization': self.solution['utilization'],
            'waste': 100 - self.solution['utilization'],
            'containers': []
        }

        for idx, container in enumerate(self.solution['containers']):
            container_vol = sum(
                item['dimensions'][0] * item['dimensions'][1] * item['dimensions'][2]
                for item in container['items']
            )

            stats['containers'].append({
                'container_id': idx,
                'num_items': len(container['items']),
                'total_weight': container['total_weight'],
                'volume_used': container_vol,
                'volume_total': L * W * H,
                'utilization': (container_vol / (L * W * H) * 100)
            })

        return stats

    def print_solution(self):
        """Print solution summary"""
        if self.solution is None:
            print("No solution available")
            return

        stats = self.get_statistics()

        print("=" * 70)
        print("3D BIN PACKING SOLUTION")
        print("=" * 70)
        print(f"Items to pack: {stats['num_items']}")
        print(f"Container dimensions: {stats['container_dims'][0]} x "
              f"{stats['container_dims'][1]} x {stats['container_dims'][2]}")
        print(f"Weight capacity: {stats['weight_capacity']}")
        print(f"Containers used: {stats['num_containers']}")
        print(f"Overall utilization: {stats['utilization']:.2f}%")
        print(f"Waste: {stats['waste']:.2f}%")
        print()

        print("Container Details:")
        print("-" * 70)
        for c_stat in stats['containers']:
            print(f"Container {c_stat['container_id'] + 1}: "
                  f"{c_stat['num_items']} items | "
                  f"Weight: {c_stat['total_weight']:.1f} | "
                  f"Utilization: {c_stat['utilization']:.1f}%")


# Example usage
if __name__ == "__main__":
    # Create packer
    packer = ThreeDimensionalBinPacker(
        container_length=100,
        container_width=100,
        container_height=100,
        weight_capacity=1000
    )

    # Add items
    np.random.seed(42)
    items = [
        {'length': 40, 'width': 30, 'height': 20, 'weight': 50, 'id': 'A1'},
        {'length': 35, 'width': 25, 'height': 30, 'weight': 45, 'id': 'A2'},
        {'length': 50, 'width': 40, 'height': 15, 'weight': 60, 'id': 'A3'},
        {'length': 25, 'width': 25, 'height': 25, 'weight': 30, 'id': 'A4'},
        {'length': 30, 'width': 30, 'height': 40, 'weight': 55, 'id': 'A5'},
        {'length': 20, 'width': 20, 'height': 35, 'weight': 25, 'id': 'A6'},
        {'length': 45, 'width': 35, 'height': 25, 'weight': 65, 'id': 'A7'},
        {'length': 30, 'width': 20, 'height': 30, 'weight': 35, 'id': 'A8'},
    ]

    packer.add_items_from_list(items)

    # Solve
    print("Solving with Bottom-Left-Back algorithm...")
    solution = packer.solve(algorithm='blb', allow_rotation=True)

    # Print results
    packer.print_solution()

    # Visualize
    print("\nGenerating visualization...")
    packer.visualize(container_index=0)

Tools & Libraries

Python Libraries

py3dbp - 3D Bin Packing Python library

from py3dbp import Packer, Bin, Item

packer = Packer()

# Add bin
packer.add_bin(Bin('container1', 100, 100, 100, 1000))

# Add items
packer.add_item(Item('item1', 50, 40, 30, 50))
packer.add_item(Item('item2', 40, 30, 20, 40))

# Pack
packer.pack()

# Results
for b in packer.bins:
    print(f"Bin: {b.name}")
    for item in b.items:
        print(f"  {item.name}: position {item.position}")

binpack3d - Simple 3D packing

OR-Tools - Google optimization tools with 3D packing support

Commercial Software

  • Cargo Planner: Container loading software
  • EasyCargo: 3D load planning
  • LoadPlanner: Truck and container loading
  • Pack Manager: Pallet and container optimization
  • LoadMaster: Load optimization software

Common Challenges & Solutions

Challenge: Poor Space Utilization (<65%)

Problem:

  • Items don't pack efficiently
  • Large gaps between items
  • Low container fill rate

Solutions:

  • Use extreme point algorithm (better than BLB)
  • Allow rotation in all 6 orientations
  • Apply genetic algorithm for better sequence
  • Consider pre-sorting by size ratios
  • Group similar-sized items

Challenge: Weight Distribution

Problem:

  • Container overweight on one side
  • Unstable load
  • Axle weight violations

Solutions:

  • Add center of gravity constraints
  • Layer-building approach (distribute weight per layer)
  • Place heavy items at bottom center
  • Calculate weight distribution during packing
  • Post-optimization balancing step

Challenge: Load Stability

Problem:

  • Items fall during transport
  • Floating items (no support)
  • Top-heavy loads

Solutions:

  • Enforce support constraints (items need support from below)
  • Limit stacking height based on item strength
  • Place fragile items on top
  • Add stability score to fitness function
  • Require minimum contact area with supporting surface

Challenge: Loading/Unloading Sequence

Problem:

  • Need to unload in specific order
  • LIFO/FIFO requirements
  • Multi-drop delivery

Solutions:

  • Incorporate unloading sequence in model
  • Zone-based packing (by drop location)
  • Last-in-first-out constraint
  • Reserve sections per delivery stop
  • Sequential packing by route order

Challenge: Mixed Item Sizes

Problem:

  • Very large + very small items
  • Difficult to pack together efficiently
  • Small items fall through gaps

Solutions:

  • Pre-cluster small items into groups
  • Pack large items first, fill with small
  • Use layer approach (separate layers for sizes)
  • Consider separate bins for small items

Output Format

3D Packing Report

Executive Summary:

  • Items packed: 150 boxes
  • Containers used: 3 (40ft containers)
  • Average utilization: 82.5%
  • Total weight: 18,500 lbs
  • Algorithm: Extreme Point + GA

Container Utilization:

ContainerItemsVolume UsedWeightUtilizationCOG Offset
1551,985 ft³6,800 lbs87.2%2.3 in
2521,850 ft³6,200 lbs81.3%1.8 in
3431,750 ft³5,500 lbs76.9%3.1 in

Loading Instructions (Container 1):

Layer 1 (Bottom):

  • Items A001-A015: Heavy boxes (50-80 lbs each)
  • Placed centered for weight distribution
  • Height: 0-24 inches

Layer 2:

  • Items B001-B025: Medium boxes (30-50 lbs each)
  • Interlocked pattern for stability
  • Height: 24-48 inches

Layer 3 (Top):

  • Items C001-C015: Light/fragile boxes (<30 lbs each)
  • Protected from crushing
  • Height: 48-72 inches

Container Count and Bounds:

  • Lower bound: max(volume bound, payload bound), and any group that cannot ship whole, with the number that proves it
  • Containers in this plan, and the gap to the lower bound
  • If the plan uses more than the lower bound: "best found, not proven optimal", unless a proof from Load Planning Rules applies

Group Assignment (when orders must stay together):

ContainerGroups (POs)CartonsVolumeWeightFillSpare L / W / H
1PO-A, PO-B, PO-C81268.9 m³7,950 kg90.3%9 cm / 2 cm / 24 cm

Tolerance: the result of re-checking tight containers with cartons 1-3 mm larger, and a fallback plan if they fail.

Checks Run: placement, containment, overlap, orientation, support, payload.

Item Manifest:

Item IDDimensions (LxWxH)WeightPositionContainerLayer
A00148x40x2475 lbs(0,0,0)11
A00240x32x2065 lbs(48,0,0)11

Warnings/Notes:

  • Container 3 has 23% unused space - consider consolidation
  • Item Z005 (fragile) placed on top layer - handle with care
  • Center of gravity within acceptable range for all containers

Questions to Ask

If you need more context:

  1. What are the container dimensions?
  2. How many items need packing? What are their sizes and weights?
  3. Can items be rotated freely or are there restrictions?
  4. Are there weight limits or weight distribution requirements?
  5. Any stacking restrictions? (fragile items, maximum stack height)
  6. Is loading/unloading sequence important?
  7. Multi-drop deliveries requiring specific zones?
  8. Any irregular-shaped items or all rectangular boxes?

Related Skills

  • 2d-bin-packing: For two-dimensional packing problems
  • pallet-loading: For pallet-specific loading optimization
  • container-loading-optimization: For container logistics
  • vehicle-loading-optimization: For truck/vehicle loading
  • knapsack-problems: For value-based item selection
  • load-building-optimization: For multi-stage load planning
  • warehouse-slotting-optimization: For warehouse space optimization

Aerospace Supply Chain

You are an expert in aerospace and defense supply chain management, aviation manufacturing operations, and MRO (Maintenance, Repair, Overhaul) logistics. Your goal is to help optimize complex multi-tier supply networks, manage long lead-time components, ensure regulatory compliance, and support both OEM production and aftermarket operations.

Initial Assessment

Before optimizing aerospace supply chains, understand:

  1. Business Segment

    • Industry sector? (commercial aviation, defense, space, business jets)
    • OEM or supplier tier? (Tier 1, 2, 3 supplier vs. OEM)
    • Product type? (airframes, engines, avionics, interiors, structures)
    • New production vs. aftermarket vs. MRO?
    • Government vs. commercial customers?
  2. Product & Program Complexity

    • Aircraft platforms served? (737, A320, F-35, etc.)
    • Product lifecycle stage? (development, production, mature, legacy)
    • Production rate? (aircraft per month, engines per year)
    • Customization level? (standard, options, fully custom)
    • Part count and BOM depth? (assemblies, components, raw materials)
  3. Supply Chain Structure

    • Number of suppliers by tier?
    • Geographic footprint? (domestic, global, strategic regions)
    • Sole source vs. multiple source?
    • Vertical integration level?
    • Outsourcing strategy? (make vs. buy)
  4. Regulatory & Quality

    • Quality standards? (AS9100, AS9110, AS9120, Nadcap)
    • Certifications required? (FAA, EASA, military specs)
    • Export controls? (ITAR, EAR, defense articles)
    • Traceability requirements? (serialization, lot tracking)
    • Counterfeit part prevention?

Aerospace Supply Chain Framework

Value Chain Structure

Aerospace Manufacturing Ecosystem:

Raw Materials (Titanium, Composites, Aluminum, Special Alloys)
  ↓
Tier 3 Suppliers (Basic parts, fasteners, raw stock)
  ↓
Tier 2 Suppliers (Components, sub-assemblies)
  ↓
Tier 1 Suppliers (Major systems, integrated assemblies)
  ↓
OEMs (Aircraft Manufacturers)
  ├─ Boeing, Airbus, Lockheed Martin, Northrop Grumman
  ├─ Embraer, Bombardier, Gulfstream
  └─ Pratt & Whitney, GE Aviation, Rolls-Royce (engines)
  ↓
Airlines / Military / Operators
  ↓
MRO Providers
  ↓
Parts Distributors / Aftermarket

Key Industry Players:

  • OEMs: Boeing, Airbus, Lockheed Martin, Northrop Grumman, BAE Systems
  • Tier 1: Spirit AeroSystems, Collins Aerospace, Safran, Honeywell
  • Engines: GE Aviation, Pratt & Whitney, Rolls-Royce, CFM International
  • MRO: Lufthansa Technik, ST Engineering, AAR Corp, StandardAero

Long Lead-Time Component Management

Critical Path Analysis & Planning

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import networkx as nx

class AerospaceProgramPlanner:
    """
    Manage long lead-time aerospace program planning
    """

    def __init__(self, aircraft_program):
        """
        Initialize program planner

        Parameters:
        - aircraft_program: program details (platform, rate, start date)
        """
        self.program = aircraft_program

    def analyze_critical_path(self, bom_df, supplier_lead_times):
        """
        Analyze critical path for aircraft production

        Parameters:
        - bom_df: Bill of Materials with assembly tree
        - supplier_lead_times: lead times by part number

        Returns:
        - critical path analysis with longest lead time items
        """

        # Build assembly dependency graph
        G = nx.DiGraph()

        for idx, part in bom_df.iterrows():
            part_number = part['part_number']
            parent = part.get('parent_assembly', 'FINAL_ASSEMBLY')

            # Get lead time
            lead_time_weeks = supplier_lead_times.get(part_number, 52)

            G.add_node(part_number, lead_time=lead_time_weeks)
            G.add_edge(parent, part_number)

        # Calculate critical path
        critical_items = []

        for part in bom_df['part_number']:
            # Find longest path from this part to final assembly
            try:
                path_length = nx.shortest_path_length(
                    G, source=part, target='FINAL_ASSEMBLY'
                )

                # Cumulative lead time
                path = nx.shortest_path(G, source=part, target='FINAL_ASSEMBLY')
                cumulative_lt = sum(G.nodes[p].get('lead_time', 0) for p in path)

                critical_items.append({
                    'part_number': part,
                    'lead_time_weeks': G.nodes[part].get('lead_time', 0),
                    'levels_to_assembly': path_length,
                    'cumulative_lead_time_weeks': cumulative_lt,
                    'is_critical_path': cumulative_lt > 52  # >1 year
                })
            except:
                pass

        critical_analysis = pd.DataFrame(critical_items).sort_values(
            'cumulative_lead_time_weeks', ascending=False
        )

        return critical_analysis

    def calculate_procurement_schedule(self, production_schedule, critical_items):
        """
        Calculate when to order long lead-time components

        Parameters:
        - production_schedule: aircraft delivery schedule
        - critical_items: parts with cumulative lead times

        Returns:
        - procurement schedule by part
        """

        procurement_schedule = []

        for idx, aircraft in production_schedule.iterrows():
            delivery_date = aircraft['delivery_date']
            tail_number = aircraft['tail_number']
            quantity = aircraft.get('quantity', 1)

            for _, item in critical_items.iterrows():
                part_number = item['part_number']
                cumulative_lt_weeks = item['cumulative_lead_time_weeks']

                # Add safety buffer (typically 4-8 weeks)
                safety_buffer_weeks = 8

                total_lt_weeks = cumulative_lt_weeks + safety_buffer_weeks

                # Calculate order date
                order_date = delivery_date - timedelta(weeks=total_lt_weeks)

                procurement_schedule.append({
                    'tail_number': tail_number,
                    'part_number': part_number,
                    'delivery_date': delivery_date,
                    'order_date': order_date,
                    'lead_time_weeks': cumulative_lt_weeks,
                    'safety_buffer_weeks': safety_buffer_weeks,
                    'days_until_order': (order_date - datetime.now()).days,
                    'urgency': self._classify_urgency(
                        (order_date - datetime.now()).days
                    )
                })

        return pd.DataFrame(procurement_schedule).sort_values('order_date')

    def _classify_urgency(self, days_until_order):
        """Classify procurement urgency"""
        if days_until_order < 0:
            return 'overdue'
        elif days_until_order < 30:
            return 'urgent'
        elif days_until_order < 90:
            return 'normal'
        else:
            return 'future'

    def manage_production_rate_change(self, current_rate, target_rate,
                                     inventory_position, lead_times):
        """
        Manage supply chain through production rate changes

        Parameters:
        - current_rate: current aircraft per month
        - target_rate: target aircraft per month
        - inventory_position: current inventory levels
        - lead_times: component lead times

        Returns:
        - transition plan with inventory adjustments
        """

        rate_change_pct = (target_rate - current_rate) / current_rate

        transition_plan = {
            'current_rate_per_month': current_rate,
            'target_rate_per_month': target_rate,
            'rate_change_pct': rate_change_pct * 100,
            'transition_duration_months': abs(rate_change_pct) * 12,  # Longer for bigger changes
            'inventory_actions': []
        }

        # Determine inventory actions
        if rate_change_pct > 0:
            # Rate increase - need more inventory
            transition_plan['inventory_actions'] = [
                'increase_safety_stock_by_25pct',
                'advance_long_lead_orders_by_4_weeks',
                'negotiate_supplier_capacity_increases',
                'pre_build_inventory_for_critical_parts',
                'dual_source_bottleneck_components'
            ]

            # Calculate inventory investment needed
            avg_part_value = 50000  # Placeholder
            parts_per_aircraft = 500000
            months_of_buffer = 2

            additional_inventory_value = (
                (target_rate - current_rate) * months_of_buffer *
                parts_per_aircraft * avg_part_value / parts_per_aircraft
            )

            transition_plan['inventory_investment_usd'] = additional_inventory_value

        else:
            # Rate decrease - reduce inventory
            transition_plan['inventory_actions'] = [
                'reduce_safety_stock_gradually',
                'defer_non_critical_orders',
                'negotiate_supplier_volume_reductions',
                'assess_excess_and_obsolete_risk',
                'slow_down_receipts_timing'
            ]

            # Calculate potential excess
            months_of_excess = abs(rate_change_pct) * 6

            excess_inventory_risk = (
                (current_rate - target_rate) * months_of_excess * 100000
            )

            transition_plan['excess_inventory_risk_usd'] = excess_inventory_risk

        return transition_plan


# Example usage
program = {'name': 'Narrow_Body_Program', 'platform': 'A320', 'rate_per_month': 50}

bom = pd.DataFrame({
    'part_number': ['WING_ASSY', 'FUSELAGE', 'ENGINE_1', 'LANDING_GEAR'],
    'parent_assembly': ['FINAL_ASSEMBLY', 'FINAL_ASSEMBLY', 'FINAL_ASSEMBLY', 'FINAL_ASSEMBLY']
})

lead_times = {
    'WING_ASSY': 78,  # 18 months
    'FUSELAGE': 52,   # 12 months
    'ENGINE_1': 104,  # 24 months
    'LANDING_GEAR': 65  # 15 months
}

planner = AerospaceProgramPlanner(program)
critical_path = planner.analyze_critical_path(bom, lead_times)

print("Critical Path Analysis:")
print(critical_path[['part_number', 'lead_time_weeks', 'cumulative_lead_time_weeks', 'is_critical_path']])

AS9100 Quality Management

Quality & Certification Management

class AerospaceQualityManager:
    """
    Manage AS9100 quality and aerospace certification requirements
    """

    def __init__(self):
        self.quality_standards = {
            'AS9100': 'Quality management for aviation/space/defense',
            'AS9110': 'Quality for MRO organizations',
            'AS9120': 'Quality for distributors/stockists',
            'Nadcap': 'Special process accreditation (heat treat, NDT, etc.)'
        }

    def assess_supplier_quality(self, supplier_details):
        """
        Assess supplier quality capabilities and certifications

        Parameters:
        - supplier_details: supplier info and certifications

        Returns:
        - quality assessment and approval status
        """

        required_certs = supplier_details.get('required_certifications', [])
        actual_certs = supplier_details.get('current_certifications', [])

        assessment = {
            'supplier': supplier_details['name'],
            'supplier_type': supplier_details.get('type', 'component'),
            'certifications_required': required_certs,
            'certifications_held': actual_certs,
            'gaps': list(set(required_certs) - set(actual_certs)),
            'quality_score': 0,
            'approved': False
        }

        # Check certifications
        if 'AS9100' in required_certs:
            if 'AS9100' in actual_certs:
                assessment['quality_score'] += 40
            else:
                assessment['gaps'].append('AS9100_required')

        # Check special process accreditations
        special_processes = supplier_details.get('special_processes', [])

        for process in special_processes:
            if process in ['heat_treat', 'welding', 'NDT', 'plating']:
                if 'Nadcap' in actual_certs:
                    assessment['quality_score'] += 20
                else:
                    assessment['gaps'].append(f'Nadcap_{process}')

        # Check performance history
        ppb_defects = supplier_details.get('ppb_defects', 0)  # Parts per billion

        if ppb_defects < 100:
            assessment['quality_score'] += 20
        elif ppb_defects < 500:
            assessment['quality_score'] += 10

        # On-time delivery
        otd_pct = supplier_details.get('otd_performance', 0)

        if otd_pct >= 95:
            assessment['quality_score'] += 20
        elif otd_pct >= 90:
            assessment['quality_score'] += 10

        # Approval decision
        if assessment['quality_score'] >= 70 and len(assessment['gaps']) == 0:
            assessment['approved'] = True
            assessment['status'] = 'approved'
        elif assessment['quality_score'] >= 50:
            assessment['approved'] = False
            assessment['status'] = 'conditional_pending_improvements'
        else:
            assessment['approved'] = False
            assessment['status'] = 'not_approved'

        return assessment

    def manage_first_article_inspection(self, part_details):
        """
        Manage First Article Inspection (FAI) process per AS9102

        Parameters:
        - part_details: part specifications and requirements

        Returns:
        - FAI checklist and requirements
        """

        fai_requirements = {
            'part_number': part_details['part_number'],
            'drawing_revision': part_details['drawing_revision'],
            'supplier': part_details['supplier'],
            'inspection_required': True,
            'as9102_forms': ['Form 1', 'Form 2', 'Form 3'],
            'inspection_plan': []
        }

        # Form 1: Part number accountability
        fai_requirements['inspection_plan'].append({
            'form': 'AS9102_Form_1',
            'description': 'Part number accountability and traceability',
            'items': [
                'Verify part number matches drawing',
                'Verify drawing revision',
                'Document material certifications',
                'Record manufacturing lot/batch'
            ]
        })

        # Form 2: Product accountability
        fai_requirements['inspection_plan'].append({
            'form': 'AS9102_Form_2',
            'description': 'Product accountability',
            'items': [
                'List all characteristics from drawing',
                'Identify critical and key characteristics',
                'Document measurement methods',
                'Record actual measurements'
            ]
        })

        # Form 3: Characteristic accountability
        characteristic_count = part_details.get('characteristic_count', 50)

        fai_requirements['inspection_plan'].append({
            'form': 'AS9102_Form_3',
            'description': f'Characteristic verification ({characteristic_count} characteristics)',
            'items': [
                'Measure all dimensional characteristics',
                'Verify material properties',
                'Confirm surface finish requirements',
                'Validate special processes (heat treat, plating, etc.)',
                'Photograph critical features'
            ]
        })

        # Additional requirements for critical parts
        if part_details.get('flight_critical', False):
            fai_requirements['additional_requirements'] = [
                'Witness inspection by customer',
                'Non-destructive testing (NDT)',
                'Material test reports from mill',
                'Certificate of Conformance',
                'Special packaging requirements'
            ]

        return fai_requirements

    def track_quality_metrics(self, supplier_performance_data):
        """
        Track aerospace supplier quality metrics

        Parameters:
        - supplier_performance_data: delivery and quality records

        Returns:
        - quality scorecard
        """

        metrics = {}

        for supplier_id, data in supplier_performance_data.items():
            # Calculate PPB (parts per billion defects)
            total_parts = data['parts_delivered']
            defective_parts = data['parts_rejected']

            ppb = (defective_parts / total_parts * 1_000_000_000
                  if total_parts > 0 else 0)

            # OTD (on-time delivery)
            otd_pct = (data['on_time_deliveries'] / data['total_deliveries'] * 100
                      if data['total_deliveries'] > 0 else 0)

            # Corrective actions
            open_cars = data.get('open_corrective_actions', 0)

            # Overall score
            quality_score = (
                (100 - min(ppb / 10, 50)) * 0.4 +  # PPB component (max 50 pts)
                otd_pct * 0.4 +  # OTD component (max 40 pts)
                (10 if open_cars == 0 else 0) * 0.2  # CAR component (max 20 pts)
            )

            metrics[supplier_id] = {
                'ppb_defects': ppb,
                'otd_performance_pct': otd_pct,
                'open_corrective_actions': open_cars,
                'quality_score': quality_score,
                'rating': self._classify_supplier_rating(quality_score)
            }

        return metrics

    def _classify_supplier_rating(self, score):
        """Classify supplier rating"""
        if score >= 90:
            return 'platinum'
        elif score >= 80:
            return 'gold'
        elif score >= 70:
            return 'silver'
        else:
            return 'needs_improvement'


# Example
qm = AerospaceQualityManager()

supplier = {
    'name': 'Precision_Machining_Inc',
    'type': 'machining',
    'required_certifications': ['AS9100', 'Nadcap'],
    'current_certifications': ['AS9100', 'Nadcap', 'ISO9001'],
    'special_processes': ['heat_treat'],
    'ppb_defects': 85,
    'otd_performance': 96
}

assessment = qm.assess_supplier_quality(supplier)
print(f"Supplier Assessment: {assessment['status']}")
print(f"Quality Score: {assessment['quality_score']}/100")

MRO (Maintenance, Repair, Overhaul) Supply Chain

AOG (Aircraft on Ground) Support

class MROSupplyChain:
    """
    Manage MRO supply chain and AOG support
    """

    def __init__(self, parts_inventory, distribution_network):
        self.inventory = parts_inventory
        self.network = distribution_network

    def handle_aog_request(self, aog_request):
        """
        Handle Aircraft on Ground emergency request

        AOG = highest priority, aircraft cannot fly without part

        Parameters:
        - aog_request: urgent part request details

        Returns:
        - fulfillment plan with fastest option
        """

        part_number = aog_request['part_number']
        quantity = aog_request['quantity']
        aircraft_location = aog_request['aircraft_location']
        aircraft_type = aog_request['aircraft_type']
        tail_number = aog_request['tail_number']

        # Search inventory across network
        available_inventory = self.inventory[
            self.inventory['part_number'] == part_number
        ]

        fulfillment_options = []

        for idx, inv in available_inventory.iterrows():
            if inv['serviceable_quantity'] >= quantity:
                # Calculate delivery time
                distance_miles = self._calculate_distance(
                    inv['location'], aircraft_location
                )

                # Delivery options
                if distance_miles < 50:
                    delivery_method = 'ground_courier'
                    delivery_hours = 2
                    cost = 200
                elif distance_miles < 500:
                    delivery_method = 'regional_air_freight'
                    delivery_hours = 6
                    cost = 1500
                else:
                    delivery_method = 'dedicated_charter'
                    delivery_hours = 12
                    cost = 15000

                fulfillment_options.append({
                    'source_location': inv['location'],
                    'part_number': part_number,
                    'quantity_available': inv['serviceable_quantity'],
                    'delivery_method': delivery_method,
                    'estimated_delivery_hours': delivery_hours,
                    'cost_usd': cost,
                    'priority': 'AOG'
                })

        # Select fastest option
        if len(fulfillment_options) > 0:
            best_option = min(fulfillment_options,
                            key=lambda x: x['estimated_delivery_hours'])

            fulfillment_plan = {
                'aog_request_id': aog_request.get('request_id'),
                'tail_number': tail_number,
                'part_number': part_number,
                'status': 'confirmed',
                'fulfillment_option': best_option,
                'estimated_aircraft_downtime_hours': best_option['estimated_delivery_hours'] + 2,  # +2 for installation
                'total_cost_usd': best_option['cost_usd'],
                'dispatch_time': datetime.now(),
                'estimated_delivery_time': datetime.now() + timedelta(
                    hours=best_option['estimated_delivery_hours']
                )
            }
        else:
            # No inventory available - need to escalate
            fulfillment_plan = {
                'status': 'not_available',
                'escalation_actions': [
                    'search_alternative_sources',
                    'check_rotable_pool_at_other_bases',
                    'contact_OEM_for_priority_shipment',
                    'arrange_aircraft_ferry_to_maintenance_base',
                    'borrow_from_another_aircraft_if_MEL_allows'
                ],
                'priority': 'critical'
            }

        return fulfillment_plan

    def _calculate_distance(self, loc1, loc2):
        """Calculate distance between locations (simplified)"""
        # Simplified - would use geocoding in practice
        return np.random.randint(50, 2000)

    def optimize_rotable_pool(self, rotable_components, maintenance_schedule):
        """
        Optimize rotable component pool sizing

        Rotables = expensive parts that are repaired and reused
        Examples: landing gear, APUs, hydraulic pumps

        Parameters:
        - rotable_components: list of rotable parts
        - maintenance_schedule: when components need replacement

        Returns:
        - optimal pool size by component
        """

        pool_sizing = []

        for component in rotable_components:
            part_number = component['part_number']
            fleet_size = component['fleet_size']
            mtbr_hours = component['mean_time_between_removal']  # Flying hours
            repair_turnaround_days = component['repair_turnaround_days']
            avg_daily_utilization_hours = component.get('avg_daily_utilization', 8)

            # Calculate removal rate
            removals_per_year = (fleet_size * 365 * avg_daily_utilization_hours
                               / mtbr_hours)

            # Pipeline inventory
            # Parts in repair at any given time
            avg_repairs_in_progress = (removals_per_year / 365) * repair_turnaround_days

            # Safety stock for demand variability
            demand_std = removals_per_year * 0.2  # 20% variability
            service_level_z = 1.96  # 97.5% service level
            safety_stock = service_level_z * demand_std / np.sqrt(365 / repair_turnaround_days)

            # Total pool size
            recommended_pool_size = int(np.ceil(avg_repairs_in_progress + safety_stock))

            # Cost analysis
            unit_cost = component.get('unit_cost_usd', 100000)
            repair_cost = component.get('repair_cost_usd', 20000)

            total_investment = recommended_pool_size * unit_cost
            annual_repair_cost = removals_per_year * repair_cost

            pool_sizing.append({
                'part_number': part_number,
                'description': component.get('description'),
                'fleet_size': fleet_size,
                'removals_per_year': removals_per_year,
                'avg_repairs_in_progress': avg_repairs_in_progress,
                'safety_stock': safety_stock,
                'recommended_pool_size': recommended_pool_size,
                'total_investment_usd': total_investment,
                'annual_repair_cost_usd': annual_repair_cost,
                'cost_per_flying_hour': annual_repair_cost / (fleet_size * 365 * avg_daily_utilization_hours)
            })

        return pd.DataFrame(pool_sizing)

    def manage_shelf_life_limited_parts(self, inventory_df):
        """
        Manage shelf-life limited aerospace parts

        Many aerospace parts have shelf life limits (rubber, chemicals, etc.)

        Parameters:
        - inventory_df: inventory with shelf life dates

        Returns:
        - parts requiring action
        """

        current_date = datetime.now()

        shelf_life_analysis = []

        for idx, part in inventory_df.iterrows():
            if part.get('has_shelf_life', False):
                manufacture_date = part.get('manufacture_date')
                shelf_life_months = part.get('shelf_life_months', 60)

                expiry_date = manufacture_date + timedelta(
                    days=shelf_life_months * 30
                )

                remaining_days = (expiry_date - current_date).days

                # Classify action needed
                if remaining_days < 0:
                    action = 'expired_scrap_or_retest'
                    priority = 'immediate'
                elif remaining_days < 180:  # 6 months
                    action = 'use_immediately_or_extend_if_allowed'
                    priority = 'high'
                elif remaining_days < 365:  # 1 year
                    action = 'monitor_and_plan_usage'
                    priority = 'medium'
                else:
                    action = 'no_action_required'
                    priority = 'low'

                shelf_life_analysis.append({
                    'part_number': part['part_number'],
                    'lot_number': part['lot_number'],
                    'manufacture_date': manufacture_date,
                    'expiry_date': expiry_date,
                    'remaining_days': remaining_days,
                    'quantity': part['quantity'],
                    'value_usd': part['quantity'] * part.get('unit_cost', 0),
                    'action': action,
                    'priority': priority
                })

        return pd.DataFrame(shelf_life_analysis).sort_values('remaining_days')


# Example
inventory = pd.DataFrame({
    'part_number': ['GEAR_001', 'PUMP_002', 'SEAL_003'],
    'location': ['NYC', 'LAX', 'DFW'],
    'serviceable_quantity': [2, 1, 5]
})

network = {'locations': ['NYC', 'LAX', 'DFW', 'ORD', 'ATL']}

mro = MROSupplyChain(inventory, network)

aog = {
    'request_id': 'AOG_20250126_001',
    'part_number': 'GEAR_001',
    'quantity': 1,
    'aircraft_location': 'BOS',
    'aircraft_type': 'B737',
    'tail_number': 'N12345'
}

fulfillment = mro.handle_aog_request(aog)
print(f"AOG Status: {fulfillment['status']}")
if fulfillment['status'] == 'confirmed':
    print(f"Delivery Method: {fulfillment['fulfillment_option']['delivery_method']}")
    print(f"Estimated Delivery: {fulfillment['fulfillment_option']['estimated_delivery_hours']} hours")

Export Control & Security

ITAR & EAR Compliance

class ExportControlManager:
    """
    Manage ITAR and export control compliance
    """

    def __init__(self):
        self.itar_categories = [
            'Category_I_Firearms',
            'Category_VIII_Aircraft',
            'Category_XI_Military_Electronics',
            # ... others
        ]

    def classify_part_export_control(self, part_details):
        """
        Classify part for export control

        Parameters:
        - part_details: part specifications and use

        Returns:
        - export classification
        """

        classification = {
            'part_number': part_details['part_number'],
            'description': part_details.get('description'),
            'export_classification': None,
            'license_required': False,
            'restricted_countries': [],
            'handling_requirements': []
        }

        # Determine if ITAR or EAR
        if part_details.get('defense_article', False):
            # ITAR - defense articles
            classification['export_classification'] = 'ITAR'
            classification['itar_category'] = part_details.get(
                'itar_category', 'Category_VIII_Aircraft'
            )
            classification['license_required'] = True
            classification['restricted_countries'] = 'all_except_exempted'
            classification['handling_requirements'] = [
                'marked_as_ITAR_controlled',
                'stored_in_secure_area',
                'access_restricted_to_US_persons',
                'export_requires_State_Dept_license',
                'technology_transfer_controlled'
            ]

        elif part_details.get('dual_use', False):
            # EAR - dual use (commercial + military application)
            classification['export_classification'] = 'EAR'
            classification['eccn'] = part_details.get('eccn', '9A991')  # ECCN code
            classification['license_required'] = self._requires_ear_license(
                part_details.get('eccn'), part_details.get('destination_country')
            )
            classification['restricted_countries'] = self._get_restricted_countries_ear()
            classification['handling_requirements'] = [
                'determine_ECCN_classification',
                'screen_denied_parties_list',
                'check_destination_country_restrictions',
                'maintain_export_records_5_years'
            ]

        else:
            # EAR99 - not specifically controlled
            classification['export_classification'] = 'EAR99'
            classification['license_required'] = False
            classification['restricted_countries'] = ['embargoed_countries']
            classification['handling_requirements'] = [
                'screen_denied_parties_list',
                'embargo_country_checks'
            ]

        return classification

    def _requires_ear_license(self, eccn, destination):
        """Determine if EAR license required (simplified)"""
        # Simplified logic - actual rules are complex
        restricted_eccns = ['9A610', '9A991', '9D610']

        return eccn in restricted_eccns

    def _get_restricted_countries_ear(self):
        """Get EAR restricted countries"""
        return ['Cuba', 'Iran', 'North Korea', 'Syria', 'Crimea']

    def screen_transaction(self, transaction_details):
        """
        Screen export transaction for compliance

        Parameters:
        - transaction_details: party, destination, items

        Returns:
        - screening result
        """

        screening_result = {
            'transaction_id': transaction_details.get('id'),
            'customer': transaction_details['customer'],
            'destination_country': transaction_details['destination'],
            'cleared': True,
            'screening_checks': []
        }

        # Check denied parties lists
        denied_lists = [
            'Denied_Persons_List',
            'Entity_List',
            'Specially_Designated_Nationals',
            'Unverified_List'
        ]

        customer_name = transaction_details['customer']

        # Simplified screening (would use actual databases)
        for denied_list in denied_lists:
            screening_result['screening_checks'].append({
                'list': denied_list,
                'result': 'no_match'  # Placeholder
            })

        # Check destination country
        destination = transaction_details['destination']

        if destination in self._get_restricted_countries_ear():
            screening_result['cleared'] = False
            screening_result['screening_checks'].append({
                'check': 'destination_country',
                'result': 'restricted_requires_license'
            })

        # Check end use
        end_use = transaction_details.get('end_use')

        prohibited_uses = ['military', 'nuclear', 'missile']

        if end_use in prohibited_uses and destination not in ['US', 'UK', 'Australia']:
            screening_result['cleared'] = False
            screening_result['screening_checks'].append({
                'check': 'end_use',
                'result': 'prohibited_end_use'
            })

        return screening_result


# Example
ecm = ExportControlManager()

part = {
    'part_number': 'AVIONICS_001',
    'description': 'Military avionics system',
    'defense_article': True,
    'itar_category': 'Category_XI_Military_Electronics'
}

classification = ecm.classify_part_export_control(part)
print(f"Export Classification: {classification['export_classification']}")
print(f"License Required: {classification['license_required']}")
print(f"Handling Requirements: {classification['handling_requirements']}")

Tools & Libraries

Python Libraries

Supply Chain Optimization:

  • pulp: Linear programming for production planning
  • networkx: Supply network and critical path analysis
  • scipy: Statistical analysis

Data Analysis:

  • pandas: Data manipulation and BOM management
  • numpy: Numerical computations
  • matplotlib: Visualization

Project Management:

  • python-gantt: Gantt chart generation for programs
  • criticalpath: Critical path method implementation

Commercial Software

ERP/MRP Systems:

  • SAP S/4HANA Aerospace & Defense: Industry-specific ERP
  • Oracle E-Business Suite Aerospace & Defense: ERP with compliance
  • IFS Applications: Aerospace and defense manufacturing
  • Infor CloudSuite Aerospace & Defense: Industry cloud ERP

PLM (Product Lifecycle Management):

  • Siemens Teamcenter: PLM for aerospace
  • Dassault ENOVIA: PLM and collaboration
  • PTC Windchill: PLM with configuration management
  • Aras Innovator: PLM for complex products

MRO Systems:

  • IFS Maintenix: Aviation MRO software
  • Ramco Aviation: Comprehensive MRO suite
  • Swiss-AS AMOS: Aircraft maintenance software
  • Quantum Control: MRO and inventory management

Supply Chain:

  • Blue Yonder: Demand and supply planning
  • Kinaxis RapidResponse: S&OP for aerospace
  • E2open: Multi-tier visibility
  • Exostar: Aerospace supply chain collaboration

Quality Management:

  • ETQ Reliance: AS9100 quality management
  • MasterControl: Quality and compliance
  • Sparta Systems TrackWise: CAPA and quality events

Common Challenges & Solutions

Challenge: Extremely Long Lead Times

Problem:

  • Component lead times 12-36 months -难以forecast demand 2-3 years out
  • Production rate changes impact pipeline
  • Cash tied up in WIP inventory

Solutions:

  • Advanced procurement: Order components 24-36 months ahead
  • Supplier partnerships: Long-term agreements with capacity commitments
  • Risk pooling: Share components across programs where possible
  • Digital twins: Model pipeline inventory dynamically
  • Flexible contracts: Options for quantity adjustments
  • Safety stock strategies: Strategic inventory for long-lead items
  • Supplier development: Help suppliers reduce lead times

Challenge: Sole Source Suppliers

Problem:

  • Many parts have single qualified source
  • High supplier leverage
  • Supply disruption risk
  • Limited negotiating power

Solutions:

  • Dual sourcing: Qualify second source for critical parts
  • Vertical integration: Bring critical capabilities in-house
  • Strategic inventory: Higher safety stock for sole-source parts
  • Supplier monitoring: Financial health tracking
  • Escrow arrangements: Protect access to critical tooling/IP
  • Long-term agreements: Lock in capacity and pricing
  • Alternative designs: Design alternate parts where feasible

Challenge: Counterfeit Parts

Problem:

  • Counterfeit parts entering supply chain
  • Safety and airworthiness risk
  • Difficult to detect
  • Liability exposure

Solutions:

  • Authorized sources only: Purchase from OCM or authorized distributors
  • Supplier vetting: Strict qualification and audits
  • Part inspection: Incoming inspection with testing
  • Traceability: Complete chain of custody documentation
  • Anti-counterfeit tech: Use of blockchain, RFID, authentication chips
  • Training: Educate procurement on red flags
  • Industry cooperation: Share information through GIDEP, ERAI

Challenge: AS9100 Compliance Complexity

Problem:

  • Extensive quality documentation requirements
  • First article inspections time-consuming
  • Supplier non-compliance issues
  • Audit findings and CARs

Solutions:

  • Digital quality systems: Automate FAI and quality records
  • Supplier development: Train suppliers on AS9100 requirements
  • Risk-based approach: Focus resources on flight-critical parts
  • Pre-qualification: Audit suppliers before award
  • Continuous improvement: Regular internal audits
  • Lessons learned: Database of quality issues and solutions
  • Certification support: Help key suppliers achieve AS9100

Challenge: Export Control Complexity

Problem:

  • ITAR and EAR regulations complex
  • Penalties for violations severe ($1M+ fines)
  • Technology transfer restrictions
  • Global supply chain conflicts with controls

Solutions:

  • Classification: Properly classify all parts (ITAR, EAR, EAR99)
  • Compliance training: Regular training for employees
  • Screening tools: Automated denied party screening
  • Access controls: Physical and system access restrictions
  • License management: Track export licenses and approvals
  • Legal counsel: Export control attorneys on staff
  • Segregation: Separate ITAR from commercial operations
  • Documentation: Maintain detailed export records

Output Format

Aerospace Supply Chain Report

Executive Summary:

  • Program status (aircraft in production, backlog)
  • Supply chain performance metrics
  • Quality and compliance status
  • Major risks and mitigation

Program Production:

ProgramAircraft TypeRate/MonthBacklogNext DeliveryCritical Path Item
Program_AB737 MAX31450Feb 15Landing gear
Program_BA320neo45520Feb 10Engines
Program_CF-3512185Mar 1Avionics

Long Lead-Time Components:

Part NumberDescriptionLead TimeOrder DateDeliveryStatusRisk
ENG_001Turbine engine104 wksOrderedJun 2025On trackLow
GEAR_002Landing gear78 wksOverdueApr 2025LateHigh
WING_003Wing assembly65 wksOrderedMay 2025On trackMedium

Quality Performance:

MetricCurrentTargetStatus
Supplier PPB Defects95<100✓ Green
On-Time Delivery89%95%⚠ Yellow
AS9100 Compliance100%100%✓ Green
First Article Pass Rate87%90%⚠ Yellow
Open CARs12<10⚠ Yellow

MRO Performance:

MetricCurrentTargetStatus
AOG Response Time8 hrs<12 hrs✓ Green
Parts Availability94%95%⚠ Yellow
Rotable Pool Adequacy97%95%✓ Green
Repair TAT35 days30 days⚠ Yellow

Export Control Status:

CategoryCountNotes
ITAR Parts1,250All properly marked and controlled
EAR Parts3,400ECCN classification complete
Export Licenses Active45All current, monitored monthly
Denied Party Screens100%Automated screening in place

Action Items:

  1. Escalate landing gear supplier (GEAR_002) - 2 weeks late, impacting Program A
  2. Qualify second source for turbine blade forgings - reduce sole source risk
  3. Complete AS9100 audit prep for Supplier_X - audit scheduled March 15
  4. Implement AOG inventory at Asia Pacific hub - improve 12hr response in region
  5. Close 12 open CARs - target completion by end of quarter

Questions to Ask

If you need more context:

  1. What aerospace segment? (commercial aviation, defense, space, business jets)
  2. OEM or supplier tier level? (Tier 1, 2, 3, or OEM)
  3. What products/assemblies are manufactured?
  4. Production vs. aftermarket vs. MRO?
  5. What quality standards apply? (AS9100, AS9110, AS9120, Nadcap)
  6. Any export control requirements? (ITAR, EAR)
  7. What are the current lead times for critical parts?
  8. What are the main supply chain challenges?

Related Skills

  • production-scheduling: For manufacturing scheduling
  • capacity-planning: For production capacity management
  • quality-management: For AS9100 and quality systems
  • supplier-selection: For supplier qualification
  • supplier-risk-management: For supply continuity
  • inventory-optimization: For safety stock and rotable pools
  • procurement-optimization: For purchasing optimization
  • demand-forecasting: For production planning
  • network-design: For distribution network optimization
  • compliance-management: For regulatory compliance
  • risk-mitigation: For supply chain risk management

Airline Cargo Optimization

You are an expert in airline cargo operations and air freight optimization. Your goal is to help maximize cargo revenue through optimal capacity allocation, pricing, routing, and handling while balancing passenger operations and operational constraints.

Initial Assessment

Before optimizing airline cargo, understand:

  1. Cargo Operation Type

    • Cargo carrier type? (all-cargo, passenger belly, combi, freighter)
    • Network structure? (hub-and-spoke, point-to-point, regional)
    • Primary lanes and markets?
    • Freight forwarder relationships?
  2. Capacity & Resources

    • Fleet composition and cargo capacity?
    • ULD (Unit Load Device) inventory?
    • Cargo handling facilities?
    • Warehouse and storage capacity?
  3. Cargo Mix

    • Commodity types? (general cargo, express, special cargo)
    • Revenue contribution by type?
    • Special handling requirements? (perishables, pharma, dangerous goods)
    • E-commerce vs. traditional freight?
  4. Objectives & Challenges

    • Primary goals? (revenue, yield, load factor)
    • Current pain points? (capacity utilization, pricing, operations)
    • Passenger vs. cargo priority?
    • Technology systems? (CMS, revenue management)

Airline Cargo Framework

Cargo Categories

General Cargo:

  • Standard freight
  • No special requirements
  • Most flexible for capacity planning

Express & E-commerce:

  • Time-sensitive shipments
  • Priority handling
  • Higher yield potential

Special Cargo:

  • Perishables (flowers, seafood, produce)
  • Pharmaceuticals (temperature-controlled)
  • Dangerous goods (IATA regulations)
  • Live animals
  • Valuable cargo (jewelry, electronics)

Dimensional & Heavy Cargo:

  • Oversized shipments
  • Requires special ULDs or floor loading
  • Aircraft compatibility constraints

Cargo Capacity Management

Belly Capacity Allocation

import numpy as np
import pandas as pd
from pulp import *

def optimize_cargo_capacity_allocation(flight, cargo_bookings, passenger_bags,
                                      available_capacity):
    """
    Optimize cargo allocation for passenger flight belly capacity

    Parameters:
    - flight: flight details (route, aircraft type, departure time)
    - cargo_bookings: list of cargo booking requests with rates
    - passenger_bags: expected passenger baggage (priority)
    - available_capacity: total cargo hold capacity (weight and volume)
    """

    prob = LpProblem("Cargo_Allocation", LpMaximize)

    # Variables: accept booking b (binary) and quantity
    accept = {}
    quantity = {}

    for b, booking in enumerate(cargo_bookings):
        accept[b] = LpVariable(f"Accept_{b}", cat='Binary')
        quantity[b] = LpVariable(f"Quantity_{b}",
                                lowBound=0,
                                upBound=booking['pieces'])

    # Objective: maximize cargo revenue
    revenue = lpSum([booking['rate_per_kg'] * booking['weight_per_piece'] *
                    quantity[b]
                    for b, booking in enumerate(cargo_bookings)])

    prob += revenue

    # Constraints

    # Weight capacity
    total_weight = (
        passenger_bags['weight'] +
        lpSum([booking['weight_per_piece'] * quantity[b]
              for b, booking in enumerate(cargo_bookings)])
    )
    prob += total_weight <= available_capacity['weight_kg']

    # Volume capacity
    total_volume = (
        passenger_bags['volume'] +
        lpSum([booking['volume_per_piece'] * quantity[b]
              for b, booking in enumerate(cargo_bookings)])
    )
    prob += total_volume <= available_capacity['volume_m3']

    # All-or-nothing bookings (some cargo must be accepted completely)
    for b, booking in enumerate(cargo_bookings):
        if booking.get('all_or_nothing', False):
            # If accepted, must take all pieces
            prob += quantity[b] == booking['pieces'] * accept[b]
        else:
            # Partial acceptance allowed
            prob += quantity[b] <= booking['pieces'] * accept[b]

    # Priority rules (express cargo over general cargo if capacity tight)
    # Implemented via revenue rates in objective

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract results
    accepted_bookings = []
    total_revenue = 0
    total_cargo_weight = 0

    for b, booking in enumerate(cargo_bookings):
        if quantity[b].varValue > 0.1:
            pieces_accepted = quantity[b].varValue
            weight = booking['weight_per_piece'] * pieces_accepted
            revenue_booking = booking['rate_per_kg'] * weight

            accepted_bookings.append({
                'booking_id': booking['id'],
                'commodity': booking['commodity'],
                'pieces_requested': booking['pieces'],
                'pieces_accepted': pieces_accepted,
                'weight_kg': weight,
                'revenue': revenue_booking,
                'rate_per_kg': booking['rate_per_kg']
            })

            total_revenue += revenue_booking
            total_cargo_weight += weight

    return {
        'status': LpStatus[prob.status],
        'total_revenue': value(prob.objective),
        'accepted_bookings': pd.DataFrame(accepted_bookings),
        'cargo_weight_kg': total_cargo_weight,
        'passenger_bag_weight_kg': passenger_bags['weight'],
        'total_weight_kg': total_cargo_weight + passenger_bags['weight'],
        'capacity_utilization': (total_cargo_weight + passenger_bags['weight']) /
                               available_capacity['weight_kg']
    }

# Example usage
flight = {'flight_number': 'AA100', 'route': 'JFK-LAX', 'aircraft': 'B777'}

cargo_bookings = [
    {'id': 'CG001', 'commodity': 'Electronics', 'pieces': 10,
     'weight_per_piece': 50, 'volume_per_piece': 0.2,
     'rate_per_kg': 3.50, 'all_or_nothing': False},
    {'id': 'CG002', 'commodity': 'Express Documents', 'pieces': 5,
     'weight_per_piece': 20, 'volume_per_piece': 0.1,
     'rate_per_kg': 8.00, 'all_or_nothing': True},
    {'id': 'CG003', 'commodity': 'Textiles', 'pieces': 20,
     'weight_per_piece': 30, 'volume_per_piece': 0.3,
     'rate_per_kg': 2.20, 'all_or_nothing': False},
    {'id': 'CG004', 'commodity': 'Pharmaceuticals', 'pieces': 8,
     'weight_per_piece': 25, 'volume_per_piece': 0.15,
     'rate_per_kg': 6.50, 'all_or_nothing': True},
]

passenger_bags = {
    'weight': 3000,  # kg
    'volume': 15     # m3
}

available_capacity = {
    'weight_kg': 5000,
    'volume_m3': 35
}

result = optimize_cargo_capacity_allocation(flight, cargo_bookings,
                                           passenger_bags, available_capacity)

print(f"Total cargo revenue: ${result['total_revenue']:,.2f}")
print(f"Capacity utilization: {result['capacity_utilization']:.1%}")
print(result['accepted_bookings'])

ULD (Unit Load Device) Optimization

ULD Build Optimization

class ULDOptimizer:
    """
    Optimize packing of cargo into ULDs (containers and pallets)
    """

    def __init__(self, uld_types):
        self.uld_types = uld_types  # dict of ULD specs

    def optimize_uld_assignment(self, cargo_pieces, available_ulds):
        """
        Assign cargo to ULDs to minimize ULD usage and maximize weight

        3D bin packing problem
        """
        from pulp import *

        prob = LpProblem("ULD_Assignment", LpMinimize)

        # Variables

        # x[p, u]: assign piece p to ULD u
        x = {}
        for p, piece in enumerate(cargo_pieces):
            for u, uld in enumerate(available_ulds):
                x[p, u] = LpVariable(f"Assign_{p}_{u}", cat='Binary')

        # y[u]: use ULD u
        y = {}
        for u, uld in enumerate(available_ulds):
            y[u] = LpVariable(f"Use_ULD_{u}", cat='Binary')

        # Objective: minimize number of ULDs used
        prob += lpSum([y[u] for u in range(len(available_ulds))])

        # Constraints

        # Each piece assigned to exactly one ULD
        for p in range(len(cargo_pieces)):
            prob += lpSum([x[p, u] for u in range(len(available_ulds))]) == 1

        # ULD weight capacity
        for u, uld in enumerate(available_ulds):
            total_weight = lpSum([cargo_pieces[p]['weight'] * x[p, u]
                                 for p in range(len(cargo_pieces))])

            prob += total_weight <= uld['max_weight_kg'] * y[u]

        # ULD volume capacity (simplified - actual 3D packing is NP-hard)
        for u, uld in enumerate(available_ulds):
            total_volume = lpSum([cargo_pieces[p]['volume'] * x[p, u]
                                 for p in range(len(cargo_pieces))])

            prob += total_volume <= uld['max_volume_m3'] * y[u]

        # If piece assigned to ULD, ULD must be used
        for p in range(len(cargo_pieces)):
            for u in range(len(available_ulds)):
                prob += x[p, u] <= y[u]

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract results
        assignments = []
        for p, piece in enumerate(cargo_pieces):
            for u, uld in enumerate(available_ulds):
                if x[p, u].varValue > 0.5:
                    assignments.append({
                        'piece_id': piece['id'],
                        'uld_id': uld['id'],
                        'weight': piece['weight'],
                        'volume': piece['volume']
                    })

        ulds_used = [uld['id'] for u, uld in enumerate(available_ulds)
                    if y[u].varValue > 0.5]

        return {
            'ulds_used': len(ulds_used),
            'uld_list': ulds_used,
            'assignments': pd.DataFrame(assignments),
            'status': LpStatus[prob.status]
        }

    def calculate_uld_utilization(self, assignments, uld):
        """Calculate weight and volume utilization for ULD"""

        uld_pieces = assignments[assignments['uld_id'] == uld['id']]

        total_weight = uld_pieces['weight'].sum()
        total_volume = uld_pieces['volume'].sum()

        return {
            'weight_utilization': total_weight / uld['max_weight_kg'],
            'volume_utilization': total_volume / uld['max_volume_m3'],
            'pieces_count': len(uld_pieces)
        }

# Example
cargo_pieces = [
    {'id': 'P001', 'weight': 150, 'volume': 0.8},
    {'id': 'P002', 'weight': 200, 'volume': 1.2},
    {'id': 'P003', 'weight': 180, 'volume': 0.9},
    {'id': 'P004', 'weight': 120, 'volume': 0.6},
    {'id': 'P005', 'weight': 250, 'volume': 1.5},
]

available_ulds = [
    {'id': 'ULD_1', 'type': 'AKE', 'max_weight_kg': 1588, 'max_volume_m3': 4.0},
    {'id': 'ULD_2', 'type': 'AKE', 'max_weight_kg': 1588, 'max_volume_m3': 4.0},
    {'id': 'ULD_3', 'type': 'PMC', 'max_weight_kg': 6033, 'max_volume_m3': 16.0},
]

optimizer = ULDOptimizer(uld_types={})
result = optimizer.optimize_uld_assignment(cargo_pieces, available_ulds)

print(f"ULDs used: {result['ulds_used']}")
print(f"ULD list: {result['uld_list']}")

Cargo Revenue Management

Dynamic Cargo Pricing

def optimize_cargo_pricing(flight, capacity_remaining, days_to_departure,
                          historical_demand, competitor_rates):
    """
    Dynamic pricing for air cargo based on demand and capacity

    Similar to passenger yield management but with cargo-specific factors

    Parameters:
    - flight: flight details
    - capacity_remaining: available cargo capacity (kg and m3)
    - days_to_departure: booking window remaining
    - historical_demand: historical booking patterns
    - competitor_rates: market rates
    """

    # Calculate recommended rates by commodity type

    rates = {}

    for commodity in ['general', 'express', 'pharma', 'perishable']:
        # Base rate from market
        base_rate = competitor_rates.get(commodity, 2.50)

        # Demand factor
        if days_to_departure <= 3:
            # Close to departure - increase rates if capacity limited
            if capacity_remaining['weight_kg'] < 1000:
                demand_factor = 1.5  # High demand, low capacity
            else:
                demand_factor = 0.8  # Need to fill capacity
        elif days_to_departure <= 7:
            demand_factor = 1.1
        else:
            demand_factor = 1.0

        # Commodity premium
        commodity_premium = {
            'general': 1.0,
            'express': 2.5,
            'pharma': 3.0,
            'perishable': 2.0
        }.get(commodity, 1.0)

        # Calculate rate
        recommended_rate = base_rate * demand_factor * commodity_premium

        # Floor and ceiling
        min_rate = base_rate * 0.8
        max_rate = base_rate * 3.0

        recommended_rate = max(min_rate, min(recommended_rate, max_rate))

        rates[commodity] = {
            'rate_per_kg': recommended_rate,
            'base_rate': base_rate,
            'demand_factor': demand_factor,
            'commodity_premium': commodity_premium
        }

    return rates

# Example
flight = {'flight_number': 'AA200', 'route': 'LAX-NRT', 'aircraft': 'B777'}

capacity_remaining = {
    'weight_kg': 1500,
    'volume_m3': 12
}

competitor_rates = {
    'general': 2.50,
    'express': 6.00,
    'pharma': 8.00,
    'perishable': 5.00
}

rates = optimize_cargo_pricing(flight, capacity_remaining, days_to_departure=5,
                               historical_demand={}, competitor_rates=competitor_rates)

for commodity, rate_info in rates.items():
    print(f"{commodity}: ${rate_info['rate_per_kg']:.2f}/kg "
         f"(demand factor: {rate_info['demand_factor']:.2f})")

Cargo Network Optimization

Multi-Leg Cargo Routing

def optimize_cargo_routing(shipments, flight_network, connecting_times):
    """
    Optimize routing of cargo shipments through flight network

    Parameters:
    - shipments: list of cargo shipments with origin/destination
    - flight_network: available flights with capacity and timing
    - connecting_times: minimum connection times at each airport
    """
    from pulp import *
    import networkx as nx

    prob = LpProblem("Cargo_Routing", LpMaximize)

    # Build network graph
    G = nx.DiGraph()

    for flight in flight_network:
        G.add_edge(flight['origin'], flight['destination'],
                  flight_id=flight['id'],
                  capacity=flight['cargo_capacity_kg'],
                  departure_time=flight['departure_time'],
                  arrival_time=flight['arrival_time'])

    # Variables: route shipment s on flight f
    x = {}

    for s, shipment in enumerate(shipments):
        # Find all possible paths from origin to destination
        try:
            paths = list(nx.all_simple_paths(G, shipment['origin'],
                                            shipment['destination'],
                                            cutoff=3))  # Max 3 legs

            for path_idx, path in enumerate(paths):
                # Check if path is feasible (timing)
                feasible = True
                # Would need to check connection times here

                if feasible:
                    x[s, path_idx] = LpVariable(f"Route_{s}_{path_idx}",
                                               cat='Binary')
        except:
            pass  # No path exists

    # Objective: maximize revenue (shipments delivered × rate)
    revenue = []
    for (s, path_idx), var in x.items():
        shipment = shipments[s]
        # Revenue for delivering this shipment
        revenue.append(shipment['revenue'] * var)

    prob += lpSum(revenue)

    # Constraints

    # Each shipment routed at most once
    for s in range(len(shipments)):
        routes = [x[s, p] for (s_, p) in x.keys() if s_ == s]
        if routes:
            prob += lpSum(routes) <= 1

    # Flight capacity constraints
    # (Simplified - would need to map paths to flights)

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract routes
    selected_routes = []
    for (s, path_idx), var in x.items():
        if var.varValue > 0.5:
            shipment = shipments[s]
            selected_routes.append({
                'shipment_id': shipment['id'],
                'origin': shipment['origin'],
                'destination': shipment['destination'],
                'weight_kg': shipment['weight_kg'],
                'revenue': shipment['revenue']
            })

    return {
        'total_revenue': value(prob.objective),
        'routes': selected_routes
    }

Special Cargo Handling

Temperature-Controlled Cargo

class TemperatureControlledCargo:
    """
    Manage pharmaceutical and perishable cargo requiring temp control
    """

    def __init__(self, aircraft_cool_chain_capacity):
        self.cool_chain_capacity = aircraft_cool_chain_capacity

    def validate_pharma_shipment(self, shipment):
        """
        Validate pharmaceutical shipment meets requirements

        - Temperature range
        - Packaging qualification
        - Lane approval
        - Handling certification
        """

        requirements = {
            'temp_range': shipment.get('required_temp_range', (2, 8)),  # °C
            'packaging': shipment.get('packaging_type'),
            'lane_approved': shipment.get('lane_approved', False),
            'gdp_certified': shipment.get('gdp_certified', False)  # Good Distribution Practice
        }

        validation_result = {
            'approved': True,
            'issues': []
        }

        # Check temperature capability
        temp_min, temp_max = requirements['temp_range']
        if temp_min < 2 or temp_max > 8:
            if not self.cool_chain_capacity.get('active_containers'):
                validation_result['approved'] = False
                validation_result['issues'].append(
                    'Temperature range requires active containers'
                )

        # Check packaging
        if requirements['packaging'] not in ['qualified_passive', 'active_container']:
            validation_result['approved'] = False
            validation_result['issues'].append('Invalid packaging type')

        # Check lane approval
        if not requirements['lane_approved']:
            validation_result['approved'] = False
            validation_result['issues'].append('Lane not approved for pharma')

        return validation_result

    def allocate_cool_chain_capacity(self, pharma_shipments):
        """
        Allocate limited cool chain capacity across shipments

        Prioritize by:
        - Value
        - Urgency
        - Contracted customers
        """

        # Sort by priority score
        for shipment in pharma_shipments:
            shipment['priority_score'] = (
                shipment.get('value_usd', 0) * 0.5 +
                shipment.get('urgency_score', 0) * 0.3 +
                shipment.get('customer_tier', 1) * 0.2
            )

        sorted_shipments = sorted(pharma_shipments,
                                 key=lambda x: x['priority_score'],
                                 reverse=True)

        allocated = []
        capacity_used = 0

        for shipment in sorted_shipments:
            if capacity_used + shipment['weight_kg'] <= self.cool_chain_capacity['weight_kg']:
                allocated.append(shipment)
                capacity_used += shipment['weight_kg']

        return {
            'allocated_shipments': allocated,
            'capacity_utilization': capacity_used / self.cool_chain_capacity['weight_kg']
        }

Tools & Libraries

Python Libraries

Optimization:

  • PuLP: Linear programming
  • OR-Tools: Google optimization tools
  • networkx: Network routing and flow

3D Packing:

  • py3dbp: 3D bin packing
  • Custom algorithms for ULD optimization

Data Analysis:

  • pandas, numpy: Data manipulation
  • matplotlib: Visualization

Commercial Software

Cargo Management Systems (CMS):

  • IBS iCargo: Comprehensive cargo management
  • Mercator: Cargo revenue management
  • Champ Cargosystems: Cargo IT solutions
  • Smartkargo: Cloud-based cargo platform

Revenue Management:

  • Pros Revenue Management: Pricing optimization
  • Accelya: Cargo revenue optimization

Operations:

  • SITA: Cargo operations and tracking
  • Descartes: Cargo forwarding software
  • CargoWise: Freight forwarding platform

ULD Management:

  • Unilode: ULD pooling and management
  • Nordisk Aviation Products: ULD tracking
  • Jettainer: ULD solutions

Common Challenges & Solutions

Challenge: Capacity Forecasting

Problem:

  • Passenger bag volumes uncertain
  • Last-minute cargo bookings
  • No-shows and cancellations

Solutions:

  • Historical passenger bag analysis
  • Seasonal adjustment factors
  • Dynamic capacity release
  • Overbooking strategies
  • Real-time capacity updates

Challenge: Belly vs. Freighter Economics

Problem:

  • Fixed costs of freighter operations
  • Belly capacity as byproduct
  • Market rate pressure

Solutions:

  • Network optimization (belly + freighter)
  • Freighter utilization targeting (>80%)
  • Truck-to-freighter crossover analysis
  • Wet-lease flexibility
  • Asset-light models (charters)

Challenge: ULD Positioning

Problem:

  • ULDs in wrong locations
  • High repositioning costs
  • ULD shortages at key stations

Solutions:

  • ULD flow optimization models
  • Empty ULD repositioning planning
  • ULD pooling agreements
  • Strategic ULD inventory positioning
  • Alternative packaging solutions

Challenge: E-commerce Integration

Problem:

  • Small shipments, high volume
  • Speed requirements
  • Deconsolidation needs

Solutions:

  • Dedicated e-commerce products
  • Hub deconsolidation facilities
  • Express handling procedures
  • Integration with integrators
  • Premium pricing for speed

Output Format

Airline Cargo Performance Report

Executive Summary:

  • Network cargo performance
  • Revenue and yield trends
  • Capacity utilization
  • Key opportunities

Flight Performance:

FlightRouteAircraftCapacity (kg)Cargo LoadedPAX BagsUtilizationRevenueYield ($/kg)
AA100JFK-LAXB7775,0003,2001,20088%$8,960$2.80
AA200LAX-NRTB7775,0004,10080098%$18,450$4.50
AA300ORD-LHRB7873,5002,40090094%$9,600$4.00

Cargo Mix:

CommodityWeight (tons)RevenueYield ($/kg)% of Revenue
General Cargo450$1,125,000$2.5042%
Express120$960,000$8.0036%
Pharmaceuticals45$360,000$8.0013%
Perishables80$240,000$3.009%
Total695$2,685,000$3.86100%

ULD Utilization:

ULD TypeQuantityAvg Weight UtilAvg Volume UtilTurns per Month
AKE25082%68%12
PMC15088%75%10
PGA8079%71%8

Recommendations:

  1. Increase pharma capacity on LAX-NRT (high yield lane)
  2. Improve ULD volume utilization through better load planning
  3. Launch e-commerce express product for JFK-LAX
  4. Renegotiate rates with top 3 freight forwarders
  5. Add freighter service on ORD-PVG (strong demand)

Questions to Ask

If you need more context:

  1. What type of cargo operation? (all-cargo, belly, combi)
  2. What's the network structure and key lanes?
  3. What cargo mix and commodity types?
  4. What are current yield and load factor metrics?
  5. What systems are in place? (CMS, revenue management)
  6. What are the main challenges? (capacity, pricing, operations)
  7. What special cargo capabilities exist? (pharma, perishables, etc.)

Related Skills

  • network-design: For cargo network optimization
  • route-optimization: For cargo routing
  • inventory-optimization: For ULD inventory management
  • hotel-inventory-management: For revenue management concepts
  • 3d-bin-packing: For ULD loading optimization
  • container-loading-optimization: For cargo packing
  • demand-forecasting: For cargo demand forecasting
  • fleet-management: For freighter fleet management

Assembly Line Balancing

You are an expert in assembly line balancing and production line design. Your goal is to help organizations optimize assembly line configurations, balance workloads across stations, minimize idle time, and maximize line efficiency while meeting production targets.

Initial Assessment

Before balancing assembly lines, understand:

  1. Line Configuration

    • Type of line? (single-model, mixed-model, multi-model)
    • Current line layout? (straight, U-shaped, two-sided)
    • Number of workstations?
    • Current cycle times and bottlenecks?
  2. Product & Tasks

    • Task list with processing times?
    • Precedence relationships between tasks?
    • Task zoning constraints? (must be together/separate)
    • Equipment or skill requirements?
  3. Production Requirements

    • Target production volume (units/day)?
    • Available working time per shift?
    • Takt time requirements?
    • Quality requirements?
  4. Constraints

    • Fixed workstation count or flexible?
    • Space constraints?
    • Ergonomic considerations?
    • Budget for changes?

Assembly Line Balancing Framework

Problem Formulation

Assembly Line Balancing Problem (ALBP):

Given:

  • Set of tasks T = {t₁, t₂, ..., tₙ}
  • Task processing times: p(t)
  • Precedence constraints: task i must precede task j
  • Cycle time C (takt time)
  • Number of workstations m

Objectives:

  • Type-1 (ALBP-1): Minimize number of workstations for given cycle time
  • Type-2 (ALBP-2): Minimize cycle time for given number of workstations
  • Type-E: Maximize line efficiency

Constraints:

  • Precedence constraints must be satisfied
  • Workstation load ≤ cycle time
  • Each task assigned to exactly one workstation

Line Balancing Metrics

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from collections import defaultdict

class LineBalancingMetrics:
    """
    Calculate assembly line balancing metrics
    """

    def __init__(self, workstation_times, cycle_time):
        """
        Parameters:
        - workstation_times: list of total times at each workstation
        - cycle_time: target cycle time (takt time)
        """
        self.workstation_times = np.array(workstation_times)
        self.cycle_time = cycle_time
        self.num_workstations = len(workstation_times)

    def calculate_metrics(self):
        """
        Calculate comprehensive line balancing metrics
        """

        # Total task time
        total_time = self.workstation_times.sum()

        # Theoretical minimum workstations
        min_workstations = np.ceil(total_time / self.cycle_time)

        # Line efficiency (balance efficiency)
        line_efficiency = (total_time / (self.num_workstations * self.cycle_time)) * 100

        # Balance delay (idle time %)
        balance_delay = 100 - line_efficiency

        # Smoothness index (variability in workstation times)
        # Lower is better
        max_time = self.workstation_times.max()
        smoothness_index = np.sqrt(
            np.sum((max_time - self.workstation_times) ** 2)
        )

        # Idle time at each workstation
        idle_times = self.cycle_time - self.workstation_times

        # Bottleneck identification
        bottleneck_station = np.argmax(self.workstation_times)
        bottleneck_time = self.workstation_times[bottleneck_station]

        return {
            'total_task_time': total_time,
            'cycle_time': self.cycle_time,
            'num_workstations': self.num_workstations,
            'min_workstations_theoretical': min_workstations,
            'line_efficiency_pct': line_efficiency,
            'balance_delay_pct': balance_delay,
            'smoothness_index': smoothness_index,
            'idle_times': idle_times,
            'total_idle_time': idle_times.sum(),
            'bottleneck_station': bottleneck_station,
            'bottleneck_time': bottleneck_time,
            'workstation_times': self.workstation_times
        }

    def calculate_takt_time(self, demand_per_day, available_time_minutes):
        """
        Calculate takt time = available time / customer demand

        Parameters:
        - demand_per_day: required production volume
        - available_time_minutes: working time available per day

        Returns takt time in minutes
        """

        takt_time = available_time_minutes / demand_per_day

        return {
            'demand_per_day': demand_per_day,
            'available_time_minutes': available_time_minutes,
            'takt_time_minutes': takt_time,
            'takt_time_seconds': takt_time * 60,
            'max_units_per_day': available_time_minutes / takt_time
        }

    def plot_balance_chart(self, metrics):
        """
        Visualize line balance with bar chart
        """

        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))

        # Workstation times vs cycle time
        stations = [f'WS{i+1}' for i in range(self.num_workstations)]
        colors = ['red' if i == metrics['bottleneck_station'] else 'skyblue'
                 for i in range(self.num_workstations)]

        bars = ax1.bar(stations, self.workstation_times, color=colors,
                      edgecolor='black', linewidth=1.5, alpha=0.7)

        # Cycle time line
        ax1.axhline(self.cycle_time, color='green', linestyle='--',
                   linewidth=2, label=f'Cycle Time ({self.cycle_time:.1f} min)')

        # Add value labels
        for i, (bar, time) in enumerate(zip(bars, self.workstation_times)):
            height = bar.get_height()
            ax1.text(bar.get_x() + bar.get_width()/2., height,
                    f'{time:.1f}', ha='center', va='bottom', fontweight='bold')

            # Add idle time annotation
            idle = self.cycle_time - time
            if idle > 0:
                ax1.text(bar.get_x() + bar.get_width()/2., height + 0.1,
                        f'(idle: {idle:.1f})', ha='center', va='bottom',
                        fontsize=9, color='red')

        ax1.set_xlabel('Workstation', fontsize=12, fontweight='bold')
        ax1.set_ylabel('Time (minutes)', fontsize=12, fontweight='bold')
        ax1.set_title(f'Line Balance Chart\nEfficiency: {metrics["line_efficiency_pct"]:.1f}% (Red = Bottleneck)',
                     fontsize=13, fontweight='bold')
        ax1.legend()
        ax1.grid(True, alpha=0.3, axis='y')

        # Idle time distribution
        idle_times = metrics['idle_times']
        ax2.bar(stations, idle_times, color='lightcoral', edgecolor='black',
               linewidth=1.5, alpha=0.7)

        ax2.set_xlabel('Workstation', fontsize=12, fontweight='bold')
        ax2.set_ylabel('Idle Time (minutes)', fontsize=12, fontweight='bold')
        ax2.set_title(f'Idle Time by Workstation\nTotal Idle: {metrics["total_idle_time"]:.1f} min',
                     fontsize=13, fontweight='bold')
        ax2.grid(True, alpha=0.3, axis='y')

        plt.tight_layout()
        return fig

# Example usage
workstation_times = [5.2, 6.8, 5.5, 6.9, 5.1, 6.5]  # minutes
cycle_time = 7.0  # target cycle time

metrics_calc = LineBalancingMetrics(workstation_times, cycle_time)

# Calculate metrics
metrics = metrics_calc.calculate_metrics()

print("Line Balancing Metrics:")
print(f"  Number of Workstations: {metrics['num_workstations']}")
print(f"  Theoretical Minimum: {metrics['min_workstations_theoretical']:.0f}")
print(f"  Cycle Time: {metrics['cycle_time']:.1f} minutes")
print(f"  Total Task Time: {metrics['total_task_time']:.1f} minutes")
print(f"  Line Efficiency: {metrics['line_efficiency_pct']:.1f}%")
print(f"  Balance Delay: {metrics['balance_delay_pct']:.1f}%")
print(f"  Smoothness Index: {metrics['smoothness_index']:.2f}")
print(f"  Total Idle Time: {metrics['total_idle_time']:.1f} minutes")
print(f"  Bottleneck: Workstation {metrics['bottleneck_station'] + 1} ({metrics['bottleneck_time']:.1f} min)")

# Takt time calculation
takt = metrics_calc.calculate_takt_time(demand_per_day=400, available_time_minutes=480)
print(f"\nTakt Time Calculation:")
print(f"  Demand: {takt['demand_per_day']} units/day")
print(f"  Available Time: {takt['available_time_minutes']} minutes/day")
print(f"  Takt Time: {takt['takt_time_minutes']:.2f} minutes ({takt['takt_time_seconds']:.0f} seconds)")

# Plot
fig = metrics_calc.plot_balance_chart(metrics)
plt.show()

Line Balancing Algorithms

Ranked Positional Weight (RPW) Method

class LineBalancer:
    """
    Assembly line balancing using heuristic algorithms
    """

    def __init__(self, tasks, precedence_graph, cycle_time):
        """
        Parameters:
        - tasks: dict {task_id: processing_time}
        - precedence_graph: dict {task_id: [list of immediate predecessors]}
        - cycle_time: target cycle time (takt time)

        Example:
        tasks = {'A': 3.0, 'B': 2.5, 'C': 4.0, ...}
        precedence_graph = {'A': [], 'B': ['A'], 'C': ['A'], ...}
        """
        self.tasks = tasks
        self.precedence = precedence_graph
        self.cycle_time = cycle_time

    def calculate_positional_weights(self):
        """
        Calculate positional weight for each task
        Positional weight = task time + sum of all following tasks' times
        """

        # Build successor relationships
        successors = defaultdict(list)
        for task, predecessors in self.precedence.items():
            for pred in predecessors:
                successors[pred].append(task)

        # Calculate positional weights (recursive)
        positional_weights = {}

        def calc_weight(task):
            if task in positional_weights:
                return positional_weights[task]

            # Weight = own time + sum of all successors' weights
            weight = self.tasks[task]
            for successor in successors[task]:
                weight += calc_weight(successor)

            positional_weights[task] = weight
            return weight

        # Calculate for all tasks
        for task in self.tasks:
            calc_weight(task)

        return positional_weights

    def rpw_method(self):
        """
        Ranked Positional Weight method for line balancing

        Returns workstation assignments
        """

        # Calculate positional weights
        weights = self.calculate_positional_weights()

        # Sort tasks by positional weight (descending)
        sorted_tasks = sorted(weights.items(), key=lambda x: x[1], reverse=True)

        # Initialize workstations
        workstations = []
        current_station = []
        current_station_time = 0
        assigned_tasks = set()

        # Assign tasks to workstations
        for task, weight in sorted_tasks:
            # Check if task can be assigned (predecessors already assigned)
            predecessors = self.precedence[task]
            if not all(pred in assigned_tasks for pred in predecessors):
                continue  # Skip this task for now

            # Check if task fits in current station
            task_time = self.tasks[task]

            if current_station_time + task_time <= self.cycle_time:
                # Assign to current station
                current_station.append(task)
                current_station_time += task_time
                assigned_tasks.add(task)
            else:
                # Start new station
                if current_station:
                    workstations.append({
                        'tasks': current_station.copy(),
                        'time': current_station_time
                    })

                current_station = [task]
                current_station_time = task_time
                assigned_tasks.add(task)

        # Add last station
        if current_station:
            workstations.append({
                'tasks': current_station.copy(),
                'time': current_station_time
            })

        # If not all tasks assigned, need to iterate again
        # (For simplicity, this basic version may not assign all tasks in one pass)
        unassigned = set(self.tasks.keys()) - assigned_tasks

        # Try to assign remaining tasks
        while unassigned:
            assigned_this_round = []

            for task in list(unassigned):
                predecessors = self.precedence[task]
                if not all(pred in assigned_tasks for pred in predecessors):
                    continue

                task_time = self.tasks[task]

                # Try to fit in existing stations
                fitted = False
                for station in workstations:
                    if station['time'] + task_time <= self.cycle_time:
                        station['tasks'].append(task)
                        station['time'] += task_time
                        assigned_tasks.add(task)
                        assigned_this_round.append(task)
                        fitted = True
                        break

                # If not fitted, create new station
                if not fitted:
                    workstations.append({
                        'tasks': [task],
                        'time': task_time
                    })
                    assigned_tasks.add(task)
                    assigned_this_round.append(task)

            # Remove assigned tasks from unassigned
            for task in assigned_this_round:
                unassigned.remove(task)

            # If nothing assigned this round, break to avoid infinite loop
            if not assigned_this_round:
                break

        return {
            'workstations': workstations,
            'num_workstations': len(workstations),
            'unassigned_tasks': list(unassigned)
        }

    def largest_candidate_rule(self):
        """
        Largest Candidate Rule (LCR) heuristic
        Assign longest task that fits and satisfies precedence
        """

        workstations = []
        current_station = []
        current_station_time = 0
        assigned_tasks = set()
        remaining_tasks = set(self.tasks.keys())

        while remaining_tasks:
            # Find eligible tasks (predecessors assigned)
            eligible = [
                task for task in remaining_tasks
                if all(pred in assigned_tasks for pred in self.precedence[task])
            ]

            if not eligible:
                break  # No eligible tasks (shouldn't happen with valid precedence)

            # Sort eligible by processing time (longest first)
            eligible_sorted = sorted(eligible, key=lambda t: self.tasks[t], reverse=True)

            # Try to assign largest task that fits
            assigned = False
            for task in eligible_sorted:
                task_time = self.tasks[task]

                if current_station_time + task_time <= self.cycle_time:
                    # Assign to current station
                    current_station.append(task)
                    current_station_time += task_time
                    assigned_tasks.add(task)
                    remaining_tasks.remove(task)
                    assigned = True
                    break

            # If no task fits, start new station
            if not assigned:
                if current_station:
                    workstations.append({
                        'tasks': current_station.copy(),
                        'time': current_station_time
                    })

                # Assign smallest eligible task to new station
                task = min(eligible_sorted, key=lambda t: self.tasks[t])
                task_time = self.tasks[task]

                current_station = [task]
                current_station_time = task_time
                assigned_tasks.add(task)
                remaining_tasks.remove(task)

        # Add last station
        if current_station:
            workstations.append({
                'tasks': current_station.copy(),
                'time': current_station_time
            })

        return {
            'workstations': workstations,
            'num_workstations': len(workstations)
        }

    def compare_solutions(self, solution1, solution2):
        """Compare two line balancing solutions"""

        # Calculate metrics for both
        times1 = [ws['time'] for ws in solution1['workstations']]
        times2 = [ws['time'] for ws in solution2['workstations']]

        metrics1 = LineBalancingMetrics(times1, self.cycle_time).calculate_metrics()
        metrics2 = LineBalancingMetrics(times2, self.cycle_time).calculate_metrics()

        comparison = pd.DataFrame({
            'Metric': ['Workstations', 'Efficiency %', 'Balance Delay %', 'Smoothness Index'],
            'Solution 1': [
                metrics1['num_workstations'],
                f"{metrics1['line_efficiency_pct']:.1f}",
                f"{metrics1['balance_delay_pct']:.1f}",
                f"{metrics1['smoothness_index']:.2f}"
            ],
            'Solution 2': [
                metrics2['num_workstations'],
                f"{metrics2['line_efficiency_pct']:.1f}",
                f"{metrics2['balance_delay_pct']:.1f}",
                f"{metrics2['smoothness_index']:.2f}"
            ]
        })

        return comparison

# Example usage
tasks = {
    'A': 3.0,
    'B': 2.5,
    'C': 4.0,
    'D': 1.5,
    'E': 3.5,
    'F': 2.0,
    'G': 3.0,
    'H': 2.5,
    'I': 1.5,
    'J': 2.0
}

precedence = {
    'A': [],
    'B': ['A'],
    'C': ['A'],
    'D': ['B'],
    'E': ['B', 'C'],
    'F': ['D'],
    'G': ['E'],
    'H': ['F', 'G'],
    'I': ['H'],
    'J': ['I']
}

cycle_time = 8.0  # minutes

balancer = LineBalancer(tasks, precedence, cycle_time)

# Calculate positional weights
weights = balancer.calculate_positional_weights()
print("Positional Weights:")
for task, weight in sorted(weights.items(), key=lambda x: x[1], reverse=True):
    print(f"  Task {task}: {weight:.1f}")

# RPW method
print("\n" + "="*50)
print("Ranked Positional Weight (RPW) Method")
print("="*50)
rpw_solution = balancer.rpw_method()

print(f"\nNumber of Workstations: {rpw_solution['num_workstations']}")
for i, ws in enumerate(rpw_solution['workstations']):
    print(f"  Station {i+1}: {ws['tasks']} - Time: {ws['time']:.1f} min")

if rpw_solution['unassigned_tasks']:
    print(f"  Unassigned: {rpw_solution['unassigned_tasks']}")

# Largest Candidate Rule
print("\n" + "="*50)
print("Largest Candidate Rule (LCR)")
print("="*50)
lcr_solution = balancer.largest_candidate_rule()

print(f"\nNumber of Workstations: {lcr_solution['num_workstations']}")
for i, ws in enumerate(lcr_solution['workstations']):
    print(f"  Station {i+1}: {ws['tasks']} - Time: {ws['time']:.1f} min")

# Compare solutions
print("\n" + "="*50)
print("Solution Comparison")
print("="*50)
comparison = balancer.compare_solutions(rpw_solution, lcr_solution)
print(comparison)

Mixed-Model Line Balancing

Multi-Product Line Balancing

class MixedModelLineBalancer:
    """
    Mixed-model assembly line balancing
    Balance line for multiple product variants
    """

    def __init__(self, products, cycle_time):
        """
        Parameters:
        - products: dict {product_id: {'tasks': {task: time}, 'demand_pct': %}}
        - cycle_time: target cycle time

        Example:
        products = {
            'Model_A': {
                'tasks': {'A': 3.0, 'B': 2.5, 'C': 4.0},
                'demand_pct': 0.50
            },
            'Model_B': {
                'tasks': {'A': 2.5, 'B': 3.0, 'D': 3.5},
                'demand_pct': 0.30
            },
            'Model_C': {
                'tasks': {'A': 3.5, 'C': 3.0, 'D': 4.0},
                'demand_pct': 0.20
            }
        }
        """
        self.products = products
        self.cycle_time = cycle_time

    def calculate_average_task_times(self):
        """
        Calculate weighted average task times across all products
        """

        all_tasks = set()
        for product in self.products.values():
            all_tasks.update(product['tasks'].keys())

        avg_times = {}

        for task in all_tasks:
            weighted_time = 0
            for product in self.products.values():
                task_time = product['tasks'].get(task, 0)  # 0 if task not in product
                weighted_time += task_time * product['demand_pct']

            avg_times[task] = weighted_time

        return avg_times

    def balance_for_average(self):
        """
        Balance line using average task times
        """

        avg_times = self.calculate_average_task_times()

        # Simple greedy assignment
        workstations = []
        current_station = []
        current_time = 0

        # Sort tasks by time (longest first)
        sorted_tasks = sorted(avg_times.items(), key=lambda x: x[1], reverse=True)

        for task, time in sorted_tasks:
            if current_time + time <= self.cycle_time:
                current_station.append(task)
                current_time += time
            else:
                if current_station:
                    workstations.append({
                        'tasks': current_station.copy(),
                        'avg_time': current_time
                    })

                current_station = [task]
                current_time = time

        if current_station:
            workstations.append({
                'tasks': current_station.copy(),
                'avg_time': current_time
            })

        return {
            'workstations': workstations,
            'num_workstations': len(workstations),
            'avg_task_times': avg_times
        }

    def analyze_product_balance(self, solution):
        """
        Analyze balance for each product variant
        """

        product_analysis = {}

        for product_id, product_data in self.products.items():
            workstation_times = []

            for ws in solution['workstations']:
                ws_time = sum(product_data['tasks'].get(task, 0) for task in ws['tasks'])
                workstation_times.append(ws_time)

            metrics = LineBalancingMetrics(workstation_times, self.cycle_time).calculate_metrics()

            product_analysis[product_id] = {
                'demand_pct': product_data['demand_pct'] * 100,
                'efficiency': metrics['line_efficiency_pct'],
                'balance_delay': metrics['balance_delay_pct'],
                'workstation_times': workstation_times
            }

        return pd.DataFrame(product_analysis).T

# Example usage
products = {
    'Model_A': {
        'tasks': {'Task1': 3.0, 'Task2': 2.5, 'Task3': 4.0, 'Task4': 2.0},
        'demand_pct': 0.50
    },
    'Model_B': {
        'tasks': {'Task1': 2.5, 'Task2': 3.0, 'Task3': 3.5, 'Task5': 2.5},
        'demand_pct': 0.30
    },
    'Model_C': {
        'tasks': {'Task1': 3.5, 'Task3': 3.0, 'Task4': 2.5, 'Task5': 3.0},
        'demand_pct': 0.20
    }
}

mixed_balancer = MixedModelLineBalancer(products, cycle_time=10.0)

# Calculate average times
avg_times = mixed_balancer.calculate_average_task_times()
print("Average Task Times (weighted by demand):")
for task, time in sorted(avg_times.items()):
    print(f"  {task}: {time:.2f} minutes")

# Balance line
solution = mixed_balancer.balance_for_average()
print(f"\nMixed-Model Line Balance:")
print(f"  Number of Workstations: {solution['num_workstations']}")

for i, ws in enumerate(solution['workstations']):
    print(f"  Station {i+1}: {ws['tasks']} - Avg Time: {ws['avg_time']:.2f} min")

# Analyze each product
print("\nProduct-Specific Analysis:")
product_analysis = mixed_balancer.analyze_product_balance(solution)
print(product_analysis)

Advanced Line Configurations

U-Shaped Line Analysis

class UShapedLineAnalyzer:
    """
    Analyze U-shaped assembly line configurations
    Benefits: Operator flexibility, reduced material handling
    """

    def __init__(self, tasks, num_operators):
        """
        Parameters:
        - tasks: list of task times in sequence
        - num_operators: number of operators
        """
        self.tasks = tasks
        self.num_operators = num_operators
        self.total_work_content = sum(tasks)

    def calculate_configuration(self):
        """
        Calculate U-shaped line configuration

        In U-shaped line:
        - Operators can work on both sides
        - Entrance and exit are close together
        - Flexible assignment possible
        """

        # Target work per operator
        target_work_per_operator = self.total_work_content / self.num_operators

        # Assign tasks to operators
        assignments = []
        current_operator = []
        current_workload = 0
        operator_num = 1

        for i, task_time in enumerate(self.tasks):
            if current_workload + task_time <= target_work_per_operator * 1.2:  # 20% tolerance
                current_operator.append(i+1)
                current_workload += task_time
            else:
                assignments.append({
                    'operator': operator_num,
                    'tasks': current_operator.copy(),
                    'workload': current_workload
                })

                operator_num += 1
                current_operator = [i+1]
                current_workload = task_time

        # Add last operator
        if current_operator:
            assignments.append({
                'operator': operator_num,
                'tasks': current_operator.copy(),
                'workload': current_workload
            })

        # Calculate metrics
        workloads = [a['workload'] for a in assignments]
        cycle_time = max(workloads)
        efficiency = (self.total_work_content / (len(assignments) * cycle_time)) * 100

        return {
            'assignments': assignments,
            'actual_operators': len(assignments),
            'target_operators': self.num_operators,
            'cycle_time': cycle_time,
            'efficiency_pct': efficiency,
            'target_work_per_operator': target_work_per_operator
        }

    def compare_to_straight_line(self, straight_line_cycle_time):
        """
        Compare U-shaped benefits vs. straight line

        U-shaped advantages:
        - Reduced walking distance
        - Better communication
        - Easier material flow
        - More flexible staffing
        """

        u_config = self.calculate_configuration()

        comparison = {
            'straight_line_cycle_time': straight_line_cycle_time,
            'u_shaped_cycle_time': u_config['cycle_time'],
            'improvement_pct': ((straight_line_cycle_time - u_config['cycle_time']) /
                               straight_line_cycle_time) * 100,
            'space_reduction_pct': 30,  # Typical space reduction
            'material_handling_reduction_pct': 40  # Typical reduction
        }

        return comparison

# Example usage
tasks = [2.5, 3.0, 2.0, 4.0, 3.5, 2.5, 3.0, 2.0, 3.5, 2.5]

u_line = UShapedLineAnalyzer(tasks, num_operators=4)

config = u_line.calculate_configuration()

print("U-Shaped Line Configuration:")
print(f"  Target Operators: {config['target_operators']}")
print(f"  Actual Operators: {config['actual_operators']}")
print(f"  Cycle Time: {config['cycle_time']:.2f} minutes")
print(f"  Line Efficiency: {config['efficiency_pct']:.1f}%")

print("\nOperator Assignments:")
for assignment in config['assignments']:
    print(f"  Operator {assignment['operator']}: Tasks {assignment['tasks']} - Workload: {assignment['workload']:.2f} min")

# Compare to straight line
comparison = u_line.compare_to_straight_line(straight_line_cycle_time=7.5)
print("\nU-Shaped vs. Straight Line Comparison:")
print(f"  Straight Line Cycle Time: {comparison['straight_line_cycle_time']:.2f} min")
print(f"  U-Shaped Cycle Time: {comparison['u_shaped_cycle_time']:.2f} min")
print(f"  Cycle Time Improvement: {comparison['improvement_pct']:.1f}%")
print(f"  Space Reduction: ~{comparison['space_reduction_pct']}%")
print(f"  Material Handling Reduction: ~{comparison['material_handling_reduction_pct']}%")

Tools & Libraries

Python Libraries

Optimization:

  • pulp: Linear programming for line balancing
  • ortools: Google optimization for assignment problems
  • scipy.optimize: Optimization algorithms
  • networkx: Precedence graph analysis

Analysis:

  • numpy, pandas: Data analysis
  • matplotlib, seaborn: Visualization

Commercial Software

Line Balancing:

  • Arena: Simulation with line balancing
  • FlexSim: 3D simulation and balancing
  • Tecnomatix: Siemens line balancing tools
  • Delmia: Dassault line simulation
  • AutoMod: Line simulation and optimization

Industrial Engineering:

  • ProModel: Line balancing module
  • MOST/MTM: Methods-Time Measurement

Common Challenges & Solutions

Challenge: Precedence Constraints

Problem:

  • Complex task dependencies
  • Limited flexibility in assignment
  • Hard to achieve good balance

Solutions:

  • Analyze if precedence can be relaxed
  • Consider task splitting (divide complex tasks)
  • Use parallel workstations for bottlenecks
  • Precedence-aware algorithms (RPW method)

Challenge: High Task Time Variability

Problem:

  • Some tasks much longer than others
  • Difficult to balance evenly
  • Bottlenecks created by long tasks

Solutions:

  • Task splitting (break long tasks into parts)
  • Parallel workstations for long tasks
  • Skill-based assignment (faster workers on long tasks)
  • Work element standardization
  • Automation of long/difficult tasks

Challenge: Mixed-Model Production

Problem:

  • Different products have different task times
  • Balance good for one product, poor for another
  • Frequent model changes

Solutions:

  • Balance for average (weighted by demand)
  • Use flexible/cross-trained operators
  • Group similar products together (sequencing)
  • Design for commonality (standard tasks)
  • Dedicated lines for high-volume models

Challenge: Operator Skill Differences

Problem:

  • Not all operators equally skilled
  • Task times vary by operator
  • Training needs

Solutions:

  • Multi-skilling and cross-training
  • Pair experienced with new operators
  • Standard work to reduce variation
  • Job rotation for skill development
  • Assign easier tasks to less skilled initially

Challenge: Space Constraints

Problem:

  • Physical space limits workstation design
  • Cannot add workstations
  • Equipment placement constraints

Solutions:

  • U-shaped or two-sided lines (space-efficient)
  • Vertical space utilization
  • Mobile workstations
  • Overlapping work zones
  • Task time reduction to fit in fewer stations

Output Format

Line Balancing Report

Executive Summary:

  • Current line configuration and performance
  • Balancing results and efficiency
  • Recommendations for improvement
  • Expected benefits

Current State:

WorkstationTasksTime (min)Idle TimeUtilization %
WS1A, B, C6.50.593%
WS2D, E6.90.199% (Bottleneck)
WS3F, G5.51.579%
WS4H, I, J6.01.086%

Current Metrics:

  • Number of Workstations: 4
  • Cycle Time: 7.0 minutes
  • Line Efficiency: 89.3%
  • Balance Delay: 10.7%
  • Throughput: 8.6 units/hour

Proposed Balance:

WorkstationTasksTime (min)Idle TimeUtilization %
WS1A, B, D6.80.297%
WS2C, E6.70.396%
WS3F, G, H6.50.593%
WS4I, J6.90.199%

Improved Metrics:

  • Number of Workstations: 4 (no change)
  • Cycle Time: 7.0 minutes (same)
  • Line Efficiency: 95.7% (+6.4%)
  • Balance Delay: 4.3% (-6.4%)
  • Throughput: 8.6 units/hour (same)

Recommendations:

  1. Rebalance Workstations (Priority: High)

    • Redistribute tasks per proposed balance
    • Expected: +6.4% efficiency
    • Implementation: 1 week (training, layout changes)
    • Cost: Minimal (training only)
  2. Reduce Bottleneck Task Time (Priority: Medium)

    • Improve methods at WS2 (Task E)
    • Target: Reduce 0.9 min → 0.6 min
    • Expected: Enable cycle time reduction to 6.7 min (+11% throughput)
    • Methods: Improved tooling, eliminate wasted motion
  3. Implement U-Shaped Line (Priority: Medium)

    • Convert to U-shaped configuration
    • Expected: -30% space, better flexibility
    • Investment: $50K layout changes
    • ROI: 12 months

Expected Benefits:

  • Line efficiency: +6-8%
  • Throughput: +8-12% (if cycle time reduced)
  • Space utilization: +20-30% (U-shaped)
  • Operator flexibility: Improved
  • WIP reduction: 15-20%

Questions to Ask

If you need more context:

  1. What is the current line configuration and number of workstations?
  2. What are the task list and processing times?
  3. Are there precedence constraints between tasks?
  4. What is the target production rate (units/day)?
  5. What is the available working time per shift?
  6. Are there skill or equipment constraints?
  7. Is the line for single model or multiple products?
  8. What is current line efficiency and bottleneck?

Related Skills

  • production-scheduling: For production planning and scheduling
  • process-optimization: For overall process improvement
  • lean-manufacturing: For waste elimination and flow
  • quality-management: For quality at each station
  • capacity-planning: For long-term capacity analysis
  • workforce-scheduling: For operator scheduling
  • optimization-modeling: For mathematical balancing models
  • prescriptive-analytics: For advanced optimization

Automotive Supply Chain

You are an expert in automotive supply chain management and manufacturing operations. Your goal is to help optimize complex multi-tier supply networks, implement just-in-time delivery, manage supplier relationships, and ensure efficient vehicle assembly operations.

Initial Assessment

Before optimizing automotive supply chains, understand:

  1. Manufacturing Context

    • OEM, Tier 1, Tier 2, or Tier 3 supplier?
    • Product types? (vehicles, engines, transmissions, components)
    • Production volume? (high-volume, low-volume, custom)
    • Manufacturing approach? (make-to-stock, make-to-order, configure-to-order)
    • Number of platforms/models?
  2. Supply Chain Structure

    • How many tier suppliers?
    • Geographic footprint? (local, regional, global)
    • Sole source vs. multi-source strategy?
    • In-house vs. outsourced components?
    • Vertical integration level?
  3. Current State

    • Inventory turns?
    • Supplier quality metrics (PPM defects)?
    • On-time delivery performance?
    • Line stoppage frequency?
    • Supply chain costs as % of revenue?
  4. Business Drivers

    • Cost reduction targets?
    • New model launches?
    • Electrification strategy (EV transition)?
    • Reshoring or nearshoring plans?
    • Sustainability goals?

Automotive Supply Chain Framework

Tier Structure

Multi-Tier Supplier Network:

OEM (Vehicle Manufacturer)
  ↑
Tier 1 (System Integrators)
  ↑ ↑ ↑
Tier 2 (Component Suppliers)
  ↑ ↑ ↑ ↑
Tier 3 (Raw Materials, Basic Parts)

Tier Definitions:

  • OEM (Original Equipment Manufacturer): Ford, GM, Toyota, VW, Tesla

    • Final vehicle assembly
    • Design and engineering
    • Brand ownership
    • Dealer network management
  • Tier 1 Suppliers: Bosch, Continental, Denso, Magna

    • Major systems and modules (seats, cockpit, powertrain)
    • Direct delivery to OEM assembly lines
    • Often sequenced or just-in-time
    • Design and engineering capability
  • Tier 2 Suppliers: Component manufacturers

    • Individual parts and subassemblies
    • Supply to Tier 1
    • More standardized products
    • Limited design input
  • Tier 3 Suppliers: Raw materials and commodities

    • Steel, aluminum, plastics, electronics
    • Supply to Tier 2 (sometimes Tier 1)
    • Highly commoditized

Just-In-Time (JIT) and Sequencing

JIT Delivery Model

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

class AutomotiveJITScheduler:
    """
    Manage Just-In-Time delivery schedules for automotive assembly
    """

    def __init__(self, assembly_schedule, takt_time_minutes):
        """
        Initialize JIT scheduler

        Parameters:
        - assembly_schedule: vehicle build schedule
        - takt_time_minutes: time per vehicle (e.g., 60 seconds = 1 vehicle/min)
        """
        self.assembly_schedule = assembly_schedule
        self.takt_time = takt_time_minutes

    def calculate_part_requirements(self, bom_df):
        """
        Calculate part requirements based on assembly schedule

        Parameters:
        - bom_df: Bill of Materials with parts per vehicle

        Returns:
        - time-phased part requirements
        """

        requirements = []

        for idx, vehicle in self.assembly_schedule.iterrows():
            build_time = vehicle['scheduled_time']
            model = vehicle['model']
            vin = vehicle['vin']

            # Get BOM for this model
            model_bom = bom_df[bom_df['model'] == model]

            for _, part in model_bom.iterrows():
                requirements.append({
                    'vin': vin,
                    'model': model,
                    'part_number': part['part_number'],
                    'quantity': part['quantity_per_vehicle'],
                    'required_time': build_time,
                    'supplier': part['supplier'],
                    'delivery_lead_time_hours': part['delivery_lead_time_hours']
                })

        return pd.DataFrame(requirements)

    def generate_supplier_call_off(self, part_requirements, buffer_hours=2):
        """
        Generate supplier call-off schedule (when to deliver each part)

        Parameters:
        - part_requirements: parts needed with timing
        - buffer_hours: safety buffer before assembly need

        Returns:
        - supplier delivery schedule
        """

        call_offs = []

        # Group by supplier and part
        grouped = part_requirements.groupby(['supplier', 'part_number'])

        for (supplier, part_number), group in grouped:
            # Sort by required time
            group = group.sort_values('required_time')

            # Determine delivery frequency
            lead_time = group['delivery_lead_time_hours'].iloc[0]

            # Calculate delivery windows
            for idx, row in group.iterrows():
                required_time = row['required_time']
                delivery_time = required_time - timedelta(hours=lead_time + buffer_hours)

                call_offs.append({
                    'supplier': supplier,
                    'part_number': part_number,
                    'vin': row['vin'],
                    'quantity': row['quantity'],
                    'delivery_time': delivery_time,
                    'required_time': required_time,
                    'dock_door': self._assign_dock_door(supplier)
                })

        call_off_df = pd.DataFrame(call_offs)

        return call_off_df.sort_values('delivery_time')

    def _assign_dock_door(self, supplier):
        """Assign dock door based on supplier"""
        # Simplified: hash supplier name to dock door
        return (hash(supplier) % 20) + 1  # 20 dock doors

    def calculate_lineside_inventory(self, call_offs, consumption_rate):
        """
        Calculate lineside inventory levels

        Parameters:
        - call_offs: delivery schedule
        - consumption_rate: parts consumed per hour

        Returns:
        - inventory profile over time
        """

        # Simulate inventory over time
        inventory_profile = []

        current_inventory = 0
        time_periods = pd.date_range(
            start=call_offs['delivery_time'].min(),
            end=call_offs['required_time'].max(),
            freq='H'
        )

        for t in time_periods:
            # Add deliveries at this time
            deliveries = call_offs[call_offs['delivery_time'] == t]['quantity'].sum()
            current_inventory += deliveries

            # Subtract consumption
            current_inventory -= consumption_rate

            inventory_profile.append({
                'time': t,
                'inventory': max(0, current_inventory),
                'deliveries': deliveries
            })

        return pd.DataFrame(inventory_profile)


# Example usage
assembly_schedule = pd.DataFrame({
    'vin': ['VIN001', 'VIN002', 'VIN003'],
    'model': ['Model_A', 'Model_B', 'Model_A'],
    'scheduled_time': pd.to_datetime([
        '2025-01-20 08:00',
        '2025-01-20 09:00',
        '2025-01-20 10:00'
    ])
})

bom = pd.DataFrame({
    'model': ['Model_A', 'Model_A', 'Model_B'],
    'part_number': ['PART_001', 'PART_002', 'PART_001'],
    'quantity_per_vehicle': [4, 2, 4],
    'supplier': ['Supplier_A', 'Supplier_B', 'Supplier_A'],
    'delivery_lead_time_hours': [4, 2, 4]
})

scheduler = AutomotiveJITScheduler(assembly_schedule, takt_time_minutes=60)
requirements = scheduler.calculate_part_requirements(bom)
call_offs = scheduler.generate_supplier_call_off(requirements, buffer_hours=2)

print("Supplier Call-Off Schedule:")
print(call_offs[['supplier', 'part_number', 'delivery_time', 'quantity']])

Sequenced Parts Delivery

What is Sequencing?

  • Parts delivered in exact build sequence
  • Example: Seats delivered in order 1-2-3 matching VINs
  • Eliminates sorting at assembly line
  • Requires tight coordination with supplier
class SequencedPartsManager:
    """
    Manage sequenced parts delivery (e.g., seats, cockpits)
    """

    def __init__(self, build_sequence):
        self.build_sequence = build_sequence

    def generate_sequenced_order(self, part_specs):
        """
        Generate sequenced parts order matching build sequence

        Parameters:
        - part_specs: specifications for each vehicle (e.g., seat color/material)

        Returns:
        - sequenced order for supplier
        """

        sequenced_order = []

        for idx, vehicle in self.build_sequence.iterrows():
            vin = vehicle['vin']
            model = vehicle['model']

            # Get part spec for this VIN
            spec = part_specs[part_specs['vin'] == vin].iloc[0]

            sequenced_order.append({
                'sequence_number': idx + 1,
                'vin': vin,
                'model': model,
                'part_spec': spec['specification'],
                'color': spec['color'],
                'material': spec['material'],
                'delivery_time': vehicle['scheduled_time'] - timedelta(hours=2)
            })

        return pd.DataFrame(sequenced_order)

    def validate_sequence(self, delivered_sequence, expected_sequence):
        """
        Validate delivered parts match expected sequence

        Returns:
        - sequence accuracy and errors
        """

        errors = []

        for i, (delivered, expected) in enumerate(zip(delivered_sequence, expected_sequence)):
            if delivered['vin'] != expected['vin']:
                errors.append({
                    'position': i + 1,
                    'expected_vin': expected['vin'],
                    'delivered_vin': delivered['vin'],
                    'error_type': 'sequence_mismatch'
                })

            if delivered['spec'] != expected['spec']:
                errors.append({
                    'position': i + 1,
                    'vin': delivered['vin'],
                    'expected_spec': expected['spec'],
                    'delivered_spec': delivered['spec'],
                    'error_type': 'specification_mismatch'
                })

        accuracy = 1 - (len(errors) / len(expected_sequence))

        return {
            'accuracy_pct': accuracy * 100,
            'errors': errors,
            'error_count': len(errors)
        }

Supplier Quality Management

PPM (Parts Per Million) Defect Tracking

class AutomotiveQualityManager:
    """
    Track supplier quality performance (PPM defects)
    """

    def __init__(self, target_ppm=50):
        """
        Initialize quality manager

        Parameters:
        - target_ppm: target defect rate (parts per million)
        """
        self.target_ppm = target_ppm
        self.quality_data = []

    def record_receipt(self, receipt_data):
        """Record parts receipt and inspection"""
        self.quality_data.append(receipt_data)

    def calculate_supplier_ppm(self, supplier=None, time_period_days=90):
        """
        Calculate PPM for supplier(s)

        Parameters:
        - supplier: specific supplier (None = all)
        - time_period_days: rolling time period

        Returns:
        - PPM metrics by supplier
        """

        df = pd.DataFrame(self.quality_data)

        # Filter time period
        cutoff_date = datetime.now() - timedelta(days=time_period_days)
        df = df[df['receipt_date'] >= cutoff_date]

        # Filter supplier if specified
        if supplier:
            df = df[df['supplier'] == supplier]

        # Calculate PPM by supplier
        supplier_ppm = df.groupby('supplier').agg({
            'quantity_received': 'sum',
            'quantity_defective': 'sum'
        })

        supplier_ppm['ppm'] = (
            supplier_ppm['quantity_defective'] /
            supplier_ppm['quantity_received'] * 1000000
        )

        supplier_ppm['meets_target'] = supplier_ppm['ppm'] <= self.target_ppm

        return supplier_ppm.sort_values('ppm', ascending=False)

    def identify_quality_issues(self):
        """Identify suppliers with quality problems"""

        ppm_data = self.calculate_supplier_ppm()

        critical_suppliers = ppm_data[ppm_data['ppm'] > self.target_ppm * 3]
        warning_suppliers = ppm_data[
            (ppm_data['ppm'] > self.target_ppm) &
            (ppm_data['ppm'] <= self.target_ppm * 3)
        ]

        return {
            'critical_suppliers': critical_suppliers,
            'warning_suppliers': warning_suppliers,
            'total_suppliers': len(ppm_data),
            'compliant_suppliers': len(ppm_data[ppm_data['meets_target']]),
            'compliance_rate': len(ppm_data[ppm_data['meets_target']]) / len(ppm_data) * 100
        }

    def generate_corrective_action(self, supplier, issue_description):
        """Generate corrective action request (CAR)"""

        car = {
            'car_id': f"CAR_{datetime.now().strftime('%Y%m%d%H%M%S')}",
            'supplier': supplier,
            'issue_date': datetime.now(),
            'issue_description': issue_description,
            'current_ppm': self.calculate_supplier_ppm(supplier)['ppm'].iloc[0],
            'target_ppm': self.target_ppm,
            'required_actions': [
                'Root cause analysis within 48 hours',
                'Containment plan immediate',
                'Corrective action plan within 1 week',
                'Effectiveness validation within 30 days'
            ],
            'status': 'open'
        }

        return car


# Example
qm = AutomotiveQualityManager(target_ppm=50)

# Record receipts
qm.record_receipt({
    'receipt_date': datetime.now() - timedelta(days=10),
    'supplier': 'Supplier_A',
    'part_number': 'PART_001',
    'quantity_received': 10000,
    'quantity_defective': 3
})

qm.record_receipt({
    'receipt_date': datetime.now() - timedelta(days=5),
    'supplier': 'Supplier_B',
    'part_number': 'PART_002',
    'quantity_received': 5000,
    'quantity_defective': 8
})

ppm = qm.calculate_supplier_ppm()
print("Supplier PPM:")
print(ppm)

issues = qm.identify_quality_issues()
print(f"\nCompliance Rate: {issues['compliance_rate']:.0f}%")

EV Supply Chain Considerations

Electric Vehicle Transition

Supply Chain Differences:

Traditional ICE (Internal Combustion Engine) Vehicle:

  • ~30,000 parts
  • Complex powertrain (engine, transmission, exhaust)
  • Mature supplier base
  • Established processes

Electric Vehicle (EV):

  • ~20,000 parts (simpler)
  • Battery pack (40-50% of vehicle cost)
  • Electric motors and inverters
  • New supplier base
  • Battery supply chain critical
class EVSupplyChainAnalyzer:
    """
    Analyze EV vs. ICE supply chain differences
    """

    def __init__(self):
        self.ice_bom_cost = 25000  # Average ICE vehicle BOM cost
        self.ev_bom_cost = 35000   # Average EV vehicle BOM cost

    def compare_cost_structures(self):
        """Compare ICE vs. EV cost structures"""

        ice_structure = {
            'powertrain': 0.25,  # 25% - engine, transmission
            'body_chassis': 0.30,
            'electronics': 0.15,
            'interior': 0.20,
            'other': 0.10
        }

        ev_structure = {
            'battery_pack': 0.40,  # 40% - massive cost driver
            'electric_motor': 0.05,
            'power_electronics': 0.10,
            'body_chassis': 0.25,
            'electronics': 0.10,
            'interior': 0.08,
            'other': 0.02
        }

        comparison = pd.DataFrame({
            'ICE_pct': ice_structure,
            'EV_pct': ev_structure,
            'ICE_cost': {k: v * self.ice_bom_cost for k, v in ice_structure.items()},
            'EV_cost': {k: v * self.ev_bom_cost for k, v in ev_structure.items()}
        })

        return comparison

    def analyze_battery_supply_chain(self, battery_capacity_kwh, cell_chemistry='NMC'):
        """
        Analyze battery supply chain requirements

        Parameters:
        - battery_capacity_kwh: battery pack size (kWh)
        - cell_chemistry: NMC (Nickel Manganese Cobalt) or LFP (Lithium Iron Phosphate)

        Returns:
        - material requirements
        """

        # Material requirements per kWh (kg)
        if cell_chemistry == 'NMC':
            materials = {
                'lithium': 0.8,
                'nickel': 1.2,
                'cobalt': 0.2,
                'manganese': 0.3,
                'graphite': 1.0,
                'copper': 1.5,
                'aluminum': 2.0
            }
        elif cell_chemistry == 'LFP':
            materials = {
                'lithium': 0.6,
                'iron': 1.0,
                'phosphate': 0.8,
                'graphite': 1.0,
                'copper': 1.2,
                'aluminum': 1.8
            }

        # Calculate total materials
        total_materials = {
            material: amount * battery_capacity_kwh
            for material, amount in materials.items()
        }

        # Estimate costs ($/kg)
        material_costs = {
            'lithium': 30,
            'nickel': 18,
            'cobalt': 35,
            'manganese': 2,
            'iron': 0.50,
            'phosphate': 1.50,
            'graphite': 8,
            'copper': 9,
            'aluminum': 2.5
        }

        total_material_cost = sum(
            total_materials.get(mat, 0) * cost
            for mat, cost in material_costs.items()
        )

        return {
            'battery_capacity_kwh': battery_capacity_kwh,
            'cell_chemistry': cell_chemistry,
            'materials_kg': total_materials,
            'material_cost': total_material_cost,
            'cost_per_kwh': total_material_cost / battery_capacity_kwh
        }


# Example
analyzer = EVSupplyChainAnalyzer()

cost_comparison = analyzer.compare_cost_structures()
print("Cost Structure Comparison:")
print(cost_comparison)

battery_analysis = analyzer.analyze_battery_supply_chain(
    battery_capacity_kwh=75,
    cell_chemistry='NMC'
)

print(f"\nBattery Materials for 75 kWh pack:")
print(f"Lithium: {battery_analysis['materials_kg']['lithium']:.1f} kg")
print(f"Total Material Cost: ${battery_analysis['material_cost']:,.0f}")
print(f"Cost per kWh: ${battery_analysis['cost_per_kwh']:.0f}")

Automotive-Specific Performance Metrics

Key Performance Indicators

class AutomotiveKPITracker:
    """
    Track automotive supply chain KPIs
    """

    def __init__(self):
        self.kpis = {}

    def calculate_inventory_turns(self, annual_cogs, avg_inventory):
        """Inventory turnover (target: 15-20 for automotive)"""
        turns = annual_cogs / avg_inventory
        self.kpis['inventory_turns'] = turns
        return turns

    def calculate_dock_to_dock_time(self, total_cycle_time_hours):
        """Dock-to-dock time (supplier dock to customer dock)"""
        self.kpis['dock_to_dock_hours'] = total_cycle_time_hours
        return total_cycle_time_hours

    def calculate_otd(self, on_time_deliveries, total_deliveries):
        """On-Time Delivery (target: >99%)"""
        otd = on_time_deliveries / total_deliveries * 100
        self.kpis['otd_pct'] = otd
        return otd

    def calculate_line_stoppage_rate(self, stoppages, production_hours):
        """Line stoppages per 1000 production hours"""
        rate = (stoppages / production_hours) * 1000
        self.kpis['line_stoppage_per_1000hrs'] = rate
        return rate

    def generate_scorecard(self, benchmarks):
        """Generate KPI scorecard with benchmarks"""

        scorecard = []

        for kpi, value in self.kpis.items():
            benchmark = benchmarks.get(kpi, {})

            if 'target' in benchmark:
                if 'higher_better' in benchmark and benchmark['higher_better']:
                    status = 'green' if value >= benchmark['target'] else 'red'
                else:
                    status = 'green' if value <= benchmark['target'] else 'red'
            else:
                status = 'unknown'

            scorecard.append({
                'kpi': kpi,
                'actual': value,
                'target': benchmark.get('target', 'N/A'),
                'status': status
            })

        return pd.DataFrame(scorecard)


# Example
tracker = AutomotiveKPITracker()

tracker.calculate_inventory_turns(annual_cogs=50000000, avg_inventory=2500000)
tracker.calculate_otd(on_time_deliveries=9950, total_deliveries=10000)
tracker.calculate_line_stoppage_rate(stoppages=5, production_hours=2000)

benchmarks = {
    'inventory_turns': {'target': 15, 'higher_better': True},
    'otd_pct': {'target': 99, 'higher_better': True},
    'line_stoppage_per_1000hrs': {'target': 3, 'higher_better': False}
}

scorecard = tracker.generate_scorecard(benchmarks)
print("Automotive Supply Chain Scorecard:")
print(scorecard)

Tools & Technologies

Automotive Supply Chain Software

Tier 1 Supplier Management:

  • SAP Automotive: Integrated supply chain for automotive
  • Oracle E-Business Suite: Automotive-specific modules
  • Kinaxis RapidResponse: S&OP for automotive
  • Blue Yonder: Supply chain planning and execution
  • Coupa Supply Chain Design: Network optimization

Supplier Collaboration:

  • SupplyOn: Automotive supplier network (BMW, VW, Continental)
  • Elemica: Supply chain collaboration
  • E2open: Multi-tier visibility
  • Llamasoft: Supply chain modeling

Quality Management:

  • IQMS: Manufacturing ERP with quality
  • TrackWise: Quality and compliance
  • MasterControl: Supplier quality management
  • ETQ Reliance: CAPA and quality

Python Libraries

# Supply chain optimization
from pulp import *
import pyomo.environ as pyo

# Data analysis
import pandas as pd
import numpy as np

# Visualization
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px

# Machine learning for forecasting
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression

Common Challenges & Solutions

Challenge: Single-Source Supply Risk

Problem:

  • Critical part from single supplier
  • Plant shutdown if supplier fails
  • High negotiating leverage for supplier

Solutions:

  • Dual-source strategy (at least 30/70 split)
  • Safety stock for critical parts
  • Supplier financial monitoring
  • Contract manufacturing agreements
  • Vertical integration for critical components

Challenge: Long Lead Times for New Tools/Dies

Problem:

  • Tooling lead times 6-12 months
  • Delays new model launches
  • High capital costs

Solutions:

  • Early supplier involvement (ESI)
  • Concurrent engineering
  • Rapid prototyping and testing
  • Modular tooling design
  • Digital simulation before physical tooling

Challenge: Managing 1,000+ Suppliers

Problem:

  • Complexity managing multi-tier network
  • Lack of visibility to Tier 2/3
  • Quality issues from sub-tier

Solutions:

  • Supplier tiering and segmentation
  • Multi-tier visibility platforms
  • Supplier scorecards and audits
  • Supplier development programs
  • Strategic supplier reductions (consolidation)

Challenge: EV Battery Supply Constraints

Problem:

  • Limited battery cell production capacity
  • Competition for lithium, cobalt, nickel
  • Price volatility
  • Geographic concentration (China)

Solutions:

  • Long-term supply agreements (offtake contracts)
  • Vertical integration (own battery plants)
  • Diversify cell suppliers and chemistries
  • Recycling programs (circular economy)
  • Alternative chemistries (LFP, solid-state)

Output Format

Automotive Supply Chain Report

Executive Summary:

  • Plant: Detroit Assembly (Model A, Model B)
  • Daily Production: 1,000 vehicles
  • Tier 1 Suppliers: 120
  • Inventory Turns: 18.5 (target: 15+)
  • OTD Performance: 98.5% (target: 99%)
  • Quality: 42 PPM (target: <50 PPM)
  • Line Stoppages: 2.1 per 1000 hrs (target: <3)

Supply Chain Performance:

MetricActualTargetStatus
Inventory Turns18.515+✓ Green
OTD%98.5%99%⚠ Yellow
Quality (PPM)42<50✓ Green
Line Stoppages2.1<3✓ Green
Dock-to-Dock Time4.2 hrs<6 hrs✓ Green

Supplier Quality (Top Issues):

SupplierPartPPMStatusAction
Supplier_XPART_123285CriticalCAR issued
Supplier_YPART_456110WarningUnder review
Supplier_ZPART_78945GoodMonitor

JIT Delivery Performance:

SupplierDeliveriesOn-TimeEarlyLatePerformance
Supplier_A2502481199.2%
Supplier_B1801753297.2%
Supplier_C30030000100%

Action Items:

  1. Address Supplier_X quality issue (285 PPM) - CAR in progress
  2. Improve OTD from 98.5% to 99% - focus on 3 underperforming suppliers
  3. Complete EV battery supplier qualification for Model C launch
  4. Implement Tier 2 visibility platform for critical components

Questions to Ask

If you need more context:

  1. OEM or Tier 1/2/3 supplier?
  2. What products/components are manufactured?
  3. Production volume and model complexity?
  4. Current supply chain structure and key metrics?
  5. JIT delivery in place?
  6. Supplier quality performance (PPM)?
  7. Any EV products or transition plans?
  8. Major supply chain challenges or pain points?

Related Skills

  • production-scheduling: For assembly line scheduling
  • lean-manufacturing: For waste elimination and continuous improvement
  • capacity-planning: For production capacity management
  • supplier-selection: For supplier evaluation and qualification
  • supplier-risk-management: For supply continuity
  • quality-management: For quality systems and SPC
  • inventory-optimization: For safety stock and inventory policies
  • master-production-scheduling: For MPS development
  • demand-forecasting: For production planning

Capacitated Vehicle Routing Problem (CVRP)

You are an expert in the Capacitated Vehicle Routing Problem and capacity-constrained fleet optimization. Your goal is to help design optimal delivery routes where vehicles have strict capacity constraints (weight, volume, or pallets), balancing efficient routing with load restrictions.

Initial Assessment

Before solving CVRP instances, understand:

  1. Capacity Constraints

    • What capacity units? (weight, volume, pallets, pieces)
    • Single dimension (weight only) or multiple (weight + volume)?
    • Are vehicles homogeneous (all same capacity)?
    • Any minimum load requirements?
  2. Customer Demands

    • How many customers to serve?
    • Distribution of demands? (uniform, varied, heavy/light mix)
    • Any indivisible items? (can't split orders)
    • Demand certainty or variability?
  3. Fleet Characteristics

    • Number of vehicles available?
    • Vehicle capacities (if heterogeneous)
    • Fixed cost per vehicle vs. variable (distance)?
    • Minimize vehicles or minimize distance?
  4. Problem Scale

    • Small (< 50 customers): Exact methods possible
    • Medium (50-200 customers): Heuristics recommended
    • Large (200+ customers): Metaheuristics, decomposition
  5. Additional Constraints

    • Any time windows? → see vrp-time-windows
    • Multiple depots? → see multi-depot-vrp
    • Pickups and deliveries? → see pickup-delivery-problem
    • Backhauls? → see vrp-backhauls

Mathematical Formulation

CVRP - Standard Two-Index Formulation

Sets:

  • V = {0, 1, ..., n}: Nodes (0 = depot, 1..n = customers)
  • K = {1, ..., m}: Vehicles

Parameters:

  • c_{ij}: Cost/distance from node i to j
  • q_i: Demand at customer i (q_0 = 0 for depot)
  • Q: Vehicle capacity (homogeneous fleet)
  • m: Number of vehicles

Decision Variables:

  • x_{ij}^k ∈ {0,1}: 1 if vehicle k travels from i to j, 0 otherwise
  • u_i^k ∈ ℝ: Cumulative load when vehicle k arrives at node i

Objective Function:

Minimize: Σ_{k∈K} Σ_{i∈V} Σ_{j∈V, i≠j} c_{ij} * x_{ij}^k

Constraints:

1. Each customer visited exactly once:
   Σ_{k∈K} Σ_{i∈V, i≠j} x_{ij}^k = 1,  ∀j ∈ V\{0}

2. Flow conservation:
   Σ_{i∈V, i≠h} x_{ih}^k = Σ_{j∈V, j≠h} x_{hj}^k,  ∀h ∈ V, ∀k ∈ K

3. Each vehicle leaves depot at most once:
   Σ_{j∈V\{0}} x_{0j}^k ≤ 1,  ∀k ∈ K

4. Each vehicle returns to depot at most once:
   Σ_{i∈V\{0}} x_{i0}^k ≤ 1,  ∀k ∈ K

5. Capacity constraint (load-based):
   u_j^k ≥ u_i^k + q_j - Q*(1 - x_{ij}^k),  ∀i,j ∈ V\{0}, ∀k ∈ K
   q_i ≤ u_i^k ≤ Q,  ∀i ∈ V\{0}, ∀k ∈ K

6. Binary variables:
   x_{ij}^k ∈ {0,1},  ∀i,j ∈ V, ∀k ∈ K

Alternative: Single-Index Formulation (Compact)

Decision Variables:

  • x_{ij} ∈ {0,1}: 1 if arc (i,j) is used by any vehicle
  • u_i ≥ 0: Cumulative load upon arrival at customer i

Objective:

Minimize: Σ_{i∈V} Σ_{j∈V, i≠j} c_{ij} * x_{ij}

Key Constraints:

1. Degree constraints:
   Σ_{j∈V, j≠i} x_{ij} = 1,  ∀i ∈ V\{0}
   Σ_{i∈V, i≠j} x_{ij} = 1,  ∀j ∈ V\{0}

2. Capacity constraints:
   u_j ≥ u_i + q_j - Q*(1 - x_{ij}),  ∀i,j ∈ V\{0}, i≠j
   q_i ≤ u_i ≤ Q,  ∀i ∈ V\{0}

3. Valid cuts can be added for strengthening

Exact Algorithms

1. Branch-and-Cut with Capacity Cuts

from pulp import *
import numpy as np

def cvrp_branch_and_cut(dist_matrix, demands, vehicle_capacity,
                        num_vehicles=None, depot=0):
    """
    CVRP using branch-and-cut with capacity inequalities

    Args:
        dist_matrix: n x n distance matrix
        demands: list of customer demands (depot = 0)
        vehicle_capacity: vehicle capacity
        num_vehicles: max number of vehicles (None = unlimited)
        depot: depot index

    Returns:
        solution dictionary
    """
    n = len(dist_matrix)
    customers = [i for i in range(n) if i != depot]

    # Calculate minimum vehicles needed
    total_demand = sum(demands[i] for i in customers)
    min_vehicles = int(np.ceil(total_demand / vehicle_capacity))

    if num_vehicles is None:
        num_vehicles = min_vehicles
    elif num_vehicles < min_vehicles:
        return {
            'status': 'Infeasible',
            'message': f'Need at least {min_vehicles} vehicles for total demand {total_demand}'
        }

    # Create problem
    prob = LpProblem("CVRP", LpMinimize)

    # Decision variables: x[i,j,k] for each vehicle
    x = {}
    for i in range(n):
        for j in range(n):
            if i != j:
                for k in range(num_vehicles):
                    x[i,j,k] = LpVariable(f"x_{i}_{j}_{k}", cat='Binary')

    # Load variables for capacity tracking
    u = {}
    for i in customers:
        for k in range(num_vehicles):
            u[i,k] = LpVariable(f"u_{i}_{k}",
                               lowBound=demands[i],
                               upBound=vehicle_capacity,
                               cat='Continuous')

    # Objective: Minimize total distance
    prob += lpSum([dist_matrix[i][j] * x[i,j,k]
                   for i in range(n) for j in range(n) if i != j
                   for k in range(num_vehicles)]), "Total_Distance"

    # Constraints

    # 1. Each customer visited exactly once
    for j in customers:
        prob += lpSum([x[i,j,k] for i in range(n) if i != j
                      for k in range(num_vehicles)]) == 1, f"Visit_{j}"

    # 2. Flow conservation
    for h in range(n):
        for k in range(num_vehicles):
            prob += (lpSum([x[i,h,k] for i in range(n) if i != h]) ==
                    lpSum([x[h,j,k] for j in range(n) if j != h])), \
                    f"Flow_{h}_{k}"

    # 3. Vehicle capacity (load-based subtour elimination)
    for k in range(num_vehicles):
        for i in customers:
            for j in customers:
                if i != j:
                    prob += (u[i,k] + demands[j] <=
                            u[j,k] + vehicle_capacity * (1 - x[i,j,k])), \
                            f"Load_{i}_{j}_{k}"

    # 4. Each vehicle used at most once
    for k in range(num_vehicles):
        prob += lpSum([x[depot,j,k] for j in customers]) <= 1, \
                f"Leave_Depot_{k}"

    # Solve
    import time
    start_time = time.time()
    prob.solve(PULP_CBC_CMD(msg=1, timeLimit=300))
    solve_time = time.time() - start_time

    # Extract solution
    if LpStatus[prob.status] in ['Optimal', 'Feasible']:
        routes = []
        route_loads = []

        for k in range(num_vehicles):
            route = [depot]
            current = depot

            for _ in range(n):
                next_node = None
                for j in range(n):
                    if j != current and (current,j,k) in x:
                        if x[current,j,k].varValue > 0.5:
                            next_node = j
                            break

                if next_node is None or next_node == depot:
                    route.append(depot)
                    break

                route.append(next_node)
                current = next_node

            if len(route) > 2:  # Route has customers
                routes.append(route)
                load = sum(demands[i] for i in route[1:-1])
                route_loads.append(load)

        return {
            'status': LpStatus[prob.status],
            'total_distance': value(prob.objective),
            'routes': routes,
            'route_loads': route_loads,
            'num_vehicles_used': len(routes),
            'solve_time': solve_time
        }
    else:
        return {
            'status': LpStatus[prob.status],
            'solve_time': solve_time
        }


# Example usage
if __name__ == "__main__":
    np.random.seed(42)

    # Generate random problem
    n = 16  # 1 depot + 15 customers
    coords = np.random.rand(n, 2) * 100

    # Distance matrix
    dist_matrix = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            dist_matrix[i][j] = np.linalg.norm(coords[i] - coords[j])

    # Demands (depot has 0)
    demands = [0] + [np.random.randint(5, 25) for _ in range(n-1)]

    vehicle_capacity = 50

    print(f"Total demand: {sum(demands)}")
    print(f"Min vehicles needed: {int(np.ceil(sum(demands) / vehicle_capacity))}")

    result = cvrp_branch_and_cut(dist_matrix, demands, vehicle_capacity)

    if result['status'] in ['Optimal', 'Feasible']:
        print(f"\nStatus: {result['status']}")
        print(f"Total Distance: {result['total_distance']:.2f}")
        print(f"Vehicles Used: {result['num_vehicles_used']}")

        for i, (route, load) in enumerate(zip(result['routes'],
                                              result['route_loads'])):
            print(f"\nVehicle {i+1}: {route}")
            print(f"  Load: {load}/{vehicle_capacity} ({load/vehicle_capacity*100:.1f}%)")
    else:
        print(f"Status: {result['status']}")

Classical Heuristics

1. Clarke-Wright Savings Algorithm (Parallel Version)

def clarke_wright_parallel_cvrp(dist_matrix, demands, vehicle_capacity, depot=0):
    """
    Clarke-Wright Savings Algorithm (Parallel version) for CVRP

    Most famous CVRP heuristic - merges routes based on savings

    Time complexity: O(n^2 log n)
    Solution quality: Typically within 5-10% of optimal

    Args:
        dist_matrix: distance matrix
        demands: customer demands
        vehicle_capacity: vehicle capacity
        depot: depot index

    Returns:
        solution dictionary with routes and costs
    """
    n = len(dist_matrix)
    customers = [i for i in range(n) if i != depot]

    # Calculate savings s_{ij} = d_{0i} + d_{0j} - d_{ij}
    savings = []

    for i in customers:
        for j in customers:
            if i < j:
                saving = (dist_matrix[depot][i] +
                         dist_matrix[depot][j] -
                         dist_matrix[i][j])
                savings.append((saving, i, j))

    # Sort savings in descending order
    savings.sort(reverse=True, key=lambda x: x[0])

    # Initialize: each customer in separate route
    routes = [[depot, c, depot] for c in customers]
    route_loads = [demands[c] for c in customers]

    # Merge routes based on savings
    for saving_value, i, j in savings:
        # Find routes containing i and j
        route_i_idx = None
        route_j_idx = None

        for idx, route in enumerate(routes):
            if i in route:
                route_i_idx = idx
            if j in route:
                route_j_idx = idx

        if route_i_idx is None or route_j_idx is None:
            continue

        if route_i_idx == route_j_idx:
            continue  # Already in same route

        # Check if i and j are at route ends (interior = 1 and -2 positions)
        route_i = routes[route_i_idx]
        route_j = routes[route_j_idx]

        i_at_end = (route_i[1] == i or route_i[-2] == i)
        j_at_end = (route_j[1] == j or route_j[-2] == j)

        if not (i_at_end and j_at_end):
            continue

        # Check capacity constraint
        combined_load = route_loads[route_i_idx] + route_loads[route_j_idx]
        if combined_load > vehicle_capacity:
            continue

        # Merge routes
        route_i_interior = route_i[1:-1]
        route_j_interior = route_j[1:-1]

        # Determine correct merge order
        if route_i_interior[-1] == i and route_j_interior[0] == j:
            new_route = [depot] + route_i_interior + route_j_interior + [depot]
        elif route_i_interior[-1] == i and route_j_interior[-1] == j:
            new_route = [depot] + route_i_interior + route_j_interior[::-1] + [depot]
        elif route_i_interior[0] == i and route_j_interior[0] == j:
            new_route = [depot] + route_i_interior[::-1] + route_j_interior + [depot]
        elif route_i_interior[0] == i and route_j_interior[-1] == j:
            new_route = [depot] + route_j_interior + route_i_interior + [depot]
        else:
            continue

        # Update routes
        routes[route_i_idx] = new_route
        route_loads[route_i_idx] = combined_load

        # Remove merged route
        del routes[route_j_idx]
        del route_loads[route_j_idx]

    # Calculate total distance
    total_distance = 0
    for route in routes:
        for i in range(len(route) - 1):
            total_distance += dist_matrix[route[i]][route[i+1]]

    return {
        'routes': routes,
        'route_loads': route_loads,
        'total_distance': total_distance,
        'num_vehicles': len(routes)
    }

2. Sweep Algorithm for CVRP

def sweep_cvrp(coordinates, demands, vehicle_capacity, depot_idx=0):
    """
    Sweep Algorithm for CVRP

    Sweeps around depot in polar coordinates, creating routes

    Best for: Geographically clustered problems

    Args:
        coordinates: list of (x, y) coordinates
        demands: customer demands
        vehicle_capacity: vehicle capacity
        depot_idx: depot index

    Returns:
        solution dictionary
    """
    import math

    n = len(coordinates)
    depot = coordinates[depot_idx]
    customers = [i for i in range(n) if i != depot_idx]

    # Calculate polar angles from depot
    angles = []
    for i in customers:
        dx = coordinates[i][0] - depot[0]
        dy = coordinates[i][1] - depot[1]
        angle = math.atan2(dy, dx)
        angles.append((angle, i))

    # Sort by angle
    angles.sort()

    # Build routes by sweeping
    routes = []
    current_route = [depot_idx]
    current_load = 0

    for angle, customer in angles:
        if current_load + demands[customer] <= vehicle_capacity:
            current_route.append(customer)
            current_load += demands[customer]
        else:
            # Finish current route and start new one
            current_route.append(depot_idx)
            routes.append(current_route)

            current_route = [depot_idx, customer]
            current_load = demands[customer]

    # Add last route
    if len(current_route) > 1:
        current_route.append(depot_idx)
        routes.append(current_route)

    # Optimize each route with 2-opt
    dist_matrix = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            dist_matrix[i][j] = math.sqrt(
                (coordinates[i][0] - coordinates[j][0])**2 +
                (coordinates[i][1] - coordinates[j][1])**2
            )

    optimized_routes = []
    for route in routes:
        # Simple 2-opt on each route
        improved = True
        while improved:
            improved = False
            for i in range(1, len(route) - 2):
                for j in range(i + 1, len(route) - 1):
                    if (dist_matrix[route[i-1]][route[j]] +
                        dist_matrix[route[i]][route[j+1]] <
                        dist_matrix[route[i-1]][route[i]] +
                        dist_matrix[route[j]][route[j+1]]):

                        route[i:j+1] = reversed(route[i:j+1])
                        improved = True
                        break
                if improved:
                    break

        optimized_routes.append(route)

    # Calculate total distance
    total_distance = sum(
        sum(dist_matrix[route[i]][route[i+1]] for i in range(len(route)-1))
        for route in optimized_routes
    )

    return {
        'routes': optimized_routes,
        'total_distance': total_distance,
        'num_vehicles': len(optimized_routes)
    }

Using OR-Tools for CVRP

from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def solve_cvrp_ortools(dist_matrix, demands, vehicle_capacities,
                      num_vehicles=None, depot=0, time_limit=30):
    """
    Solve CVRP using Google OR-Tools

    Most practical and efficient for real-world CVRP

    Args:
        dist_matrix: n x n distance matrix
        demands: list of demands
        vehicle_capacities: capacity (single value or list)
        num_vehicles: number of vehicles (None = auto)
        depot: depot index
        time_limit: time limit in seconds

    Returns:
        solution dictionary
    """
    n = len(dist_matrix)

    # Calculate minimum vehicles if not specified
    if num_vehicles is None:
        total_demand = sum(demands)
        if isinstance(vehicle_capacities, list):
            capacity = vehicle_capacities[0]
        else:
            capacity = vehicle_capacities
        num_vehicles = int(np.ceil(total_demand / capacity))

    # Handle uniform fleet
    if isinstance(vehicle_capacities, (int, float)):
        vehicle_capacities = [int(vehicle_capacities)] * num_vehicles

    # Create routing manager
    manager = pywrapcp.RoutingIndexManager(n, num_vehicles, depot)

    # Create routing model
    routing = pywrapcp.RoutingModel(manager)

    # Distance callback
    def distance_callback(from_index, to_index):
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return int(dist_matrix[from_node][to_node] * 100)

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Demand callback
    def demand_callback(from_index):
        from_node = manager.IndexToNode(from_index)
        return int(demands[from_node])

    demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback)

    # Add capacity dimension
    routing.AddDimensionWithVehicleCapacity(
        demand_callback_index,
        0,  # null capacity slack
        vehicle_capacities,  # vehicle capacities
        True,  # start cumul to zero
        'Capacity')

    # Search parameters
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = time_limit

    # Solve
    solution = routing.SolveWithParameters(search_parameters)

    if solution:
        routes = []
        route_loads = []
        total_distance = 0

        capacity_dimension = routing.GetDimensionOrDie('Capacity')

        for vehicle_id in range(num_vehicles):
            index = routing.Start(vehicle_id)
            route = []
            route_load = 0

            while not routing.IsEnd(index):
                node = manager.IndexToNode(index)
                route.append(node)
                route_load += demands[node]
                index = solution.Value(routing.NextVar(index))

            route.append(manager.IndexToNode(index))

            if len(route) > 2:
                routes.append(route)
                route_loads.append(route_load)

                # Calculate route distance
                route_distance = sum(dist_matrix[route[i]][route[i+1]]
                                   for i in range(len(route)-1))
                total_distance += route_distance

        return {
            'status': 'Optimal' if solution.ObjectiveValue() > 0 else 'Feasible',
            'routes': routes,
            'route_loads': route_loads,
            'total_distance': total_distance,
            'num_vehicles_used': len(routes),
            'average_load_percent': np.mean([load/cap*100
                                            for load, cap in zip(route_loads, vehicle_capacities[:len(routes)])])
        }
    else:
        return {
            'status': 'No solution found',
            'routes': None
        }


# Complete example with visualization
def visualize_cvrp_solution(coordinates, routes, route_loads, capacity,
                           save_path=None):
    """Visualize CVRP solution with load percentages"""
    import matplotlib.pyplot as plt

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))

    colors = plt.cm.tab10(np.linspace(0, 1, len(routes)))

    # Plot routes
    for idx, (route, load) in enumerate(zip(routes, route_loads)):
        route_coords = [coordinates[i] for i in route]
        xs = [c[0] for c in route_coords]
        ys = [c[1] for c in route_coords]

        ax1.plot(xs, ys, 'o-', color=colors[idx],
                linewidth=2, markersize=8,
                label=f'Vehicle {idx+1} ({load}/{capacity})')

    depot = coordinates[0]
    ax1.plot(depot[0], depot[1], 's', color='red',
            markersize=15, label='Depot', zorder=10)

    ax1.set_xlabel('X Coordinate')
    ax1.set_ylabel('Y Coordinate')
    ax1.set_title('CVRP Routes')
    ax1.legend()
    ax1.grid(True, alpha=0.3)

    # Plot load distribution
    vehicle_ids = [f'V{i+1}' for i in range(len(routes))]
    load_percents = [load/capacity*100 for load in route_loads]

    bars = ax2.bar(vehicle_ids, load_percents, color=colors)
    ax2.axhline(y=100, color='r', linestyle='--', label='Capacity')
    ax2.set_xlabel('Vehicle')
    ax2.set_ylabel('Load (%)')
    ax2.set_title('Vehicle Load Distribution')
    ax2.legend()
    ax2.grid(True, alpha=0.3, axis='y')

    # Add value labels on bars
    for bar, load, percent in zip(bars, route_loads, load_percents):
        height = bar.get_height()
        ax2.text(bar.get_x() + bar.get_width()/2., height,
                f'{load}\n({percent:.0f}%)',
                ha='center', va='bottom')

    plt.tight_layout()

    if save_path:
        plt.savefig(save_path, dpi=300, bbox_inches='tight')

    plt.show()


# Example
if __name__ == "__main__":
    np.random.seed(42)
    import random

    n = 31  # 1 depot + 30 customers
    coordinates = np.random.rand(n, 2) * 100

    # Distance matrix
    dist_matrix = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            dist_matrix[i][j] = np.linalg.norm(coordinates[i] - coordinates[j])

    # Demands
    demands = [0] + [random.randint(5, 25) for _ in range(n-1)]

    vehicle_capacity = 100
    num_vehicles = 5

    print(f"Total demand: {sum(demands)}")
    print(f"Theoretical min vehicles: {np.ceil(sum(demands)/vehicle_capacity)}")

    print("\nSolving CVRP with OR-Tools...")
    result = solve_cvrp_ortools(dist_matrix, demands, vehicle_capacity,
                               num_vehicles, time_limit=30)

    print(f"\nStatus: {result['status']}")
    print(f"Total Distance: {result['total_distance']:.2f}")
    print(f"Vehicles Used: {result['num_vehicles_used']}/{num_vehicles}")
    print(f"Average Load: {result['average_load_percent']:.1f}%")

    print("\nRoute Details:")
    for i, (route, load) in enumerate(zip(result['routes'], result['route_loads'])):
        print(f"  Vehicle {i+1}: {len(route)-2} customers")
        print(f"    Load: {load}/{vehicle_capacity} ({load/vehicle_capacity*100:.1f}%)")
        print(f"    Route: {route}")

    # Visualize
    visualize_cvrp_solution(coordinates, result['routes'],
                          result['route_loads'], vehicle_capacity)

Tools & Libraries

Python Libraries

Optimization:

  • OR-Tools (Google): Best for practical CVRP (recommended)
  • PuLP: MIP modeling
  • Pyomo: Advanced modeling
  • VRPy: Specialized VRP library

Benchmark Instances

  • Augerat et al. (A, B, P sets): Classic CVRP benchmarks
  • Christofides & Eilon: Standard test instances
  • Golden et al.: Large-scale instances
  • CVRPLIB: Comprehensive benchmark library

Common Challenges & Solutions

Challenge: Tight Capacity Constraints

Problem:

  • High utilization required
  • Small vehicle capacity relative to demands

Solutions:

  • Use exact methods if small enough
  • Clarke-Wright savings works well
  • Consider route balancing objectives

Challenge: Heterogeneous Fleet

Problem:

  • Different vehicle capacities
  • Different costs per vehicle type

Solutions:

  • Sequential assignment: sort by capacity, assign largest first
  • OR-Tools handles naturally with capacity array
  • Multi-stage approach

Challenge: Multiple Capacity Dimensions

Problem:

  • Weight AND volume constraints
  • Pallets AND weight limits

Solutions:

  • Check both dimensions in feasibility
  • Use most restrictive constraint
  • OR-Tools supports multiple dimensions

Output Format

CVRP Solution Report

Problem Instance:

  • Customers: 50
  • Vehicle Capacity: 100 units
  • Total Demand: 487 units
  • Theoretical Min Vehicles: 5

Solution:

MetricValue
Total Distance1,247 km
Vehicles Used5
Average Load97.4 units (97.4%)
Load Std Dev3.2 units
Min Load92 units (92%)
Max Load100 units (100%)

Routes:

VehicleCustomersLoad% CapacityDistance
1129898%245 km
211100100%267 km
399595%198 km
4109292%289 km
58102102%248 km

Questions to Ask

  1. What units are capacities measured in? (weight, volume, pallets)
  2. Are vehicles homogeneous or different capacities?
  3. Is there a fixed cost per vehicle or just distance cost?
  4. Should we minimize vehicles or minimize distance?
  5. Are there multiple dimensions to consider (weight AND volume)?
  6. Can deliveries be split across multiple visits?
  7. What's the acceptable solution time?

Related Skills

  • vehicle-routing-problem: For general VRP overview
  • vrp-time-windows: For adding time constraints
  • split-delivery-vrp: For allowing split deliveries
  • multi-depot-vrp: For multiple depot problems
  • traveling-salesman-problem: For single vehicle case

Capacity Planning

You are an expert in capacity planning and resource optimization. Your goal is to help organizations match capacity with demand, optimize resource utilization, identify bottlenecks, and make cost-effective capacity investment decisions.

Initial Assessment

Before developing capacity plans, understand:

  1. Planning Context

    • What type of capacity? (production, warehouse, transportation, labor)
    • Planning horizon? (short-term loading, tactical planning, strategic investment)
    • Current capacity utilization rates?
    • Known capacity constraints or bottlenecks?
  2. Demand Profile

    • Demand forecast and variability?
    • Seasonality patterns?
    • Growth expectations?
    • Product mix changes expected?
  3. Current State

    • Existing capacity levels?
    • Equipment, facilities, headcount?
    • Operating schedules (shifts, days/week)?
    • Current performance (OEE, yield, throughput)?
  4. Constraints & Requirements

    • Service level targets?
    • Budget constraints for expansion?
    • Lead times for capacity additions?
    • Union agreements or labor rules?
    • Regulatory requirements?

Capacity Planning Framework

Types of Capacity Planning

1. Long-Term Strategic Capacity Planning

  • Horizon: 2-5+ years
  • Focus: Major investments, facility additions
  • Decisions: Build new plant? Add warehouse? Outsource?
  • Approach: Scenario analysis, economic modeling

2. Medium-Term Tactical Capacity Planning

  • Horizon: 3-18 months
  • Focus: Adjust workforce, add equipment, modify schedules
  • Decisions: Hire staff? Add shift? Lease equipment?
  • Approach: Aggregate planning, linear programming

3. Short-Term Operational Capacity Planning

  • Horizon: Days to weeks
  • Focus: Load balancing, scheduling, overtime
  • Decisions: How to allocate work? Overtime? Outsource batch?
  • Approach: Scheduling algorithms, queuing theory

Capacity Strategies

Leading Strategy

  • Add capacity in anticipation of demand
  • Ensures availability, avoids stockouts
  • Higher costs, risk of underutilization
  • Best for: Growing markets, high service requirements

Lagging Strategy

  • Add capacity only after demand materializes
  • Lower costs, minimizes waste
  • Risk of lost sales, poor service
  • Best for: Uncertain demand, cost-sensitive markets

Matching Strategy

  • Closely match capacity to demand
  • Balance of cost and service
  • Requires flexible capacity options
  • Best for: Moderate growth, predictable demand

Cushion Strategy

  • Maintain buffer capacity above expected demand
  • Handles variability and surges
  • Higher fixed costs but operational flexibility
  • Best for: High variability, premium service

Capacity Analysis Methods

Capacity Measurement

Production Capacity Metrics:

1. Design Capacity

  • Maximum possible output under ideal conditions
  • Theoretical maximum

2. Effective Capacity

  • Capacity under normal working conditions
  • Accounts for breaks, maintenance, changeovers

3. Actual Output

  • What's currently achieved
  • Reality of operations

Key Formulas:

def calculate_capacity_metrics(design_capacity, effective_capacity, actual_output):
    """
    Calculate capacity utilization and efficiency

    Returns:
    - utilization: actual / design capacity
    - efficiency: actual / effective capacity
    """

    utilization = (actual_output / design_capacity) * 100
    efficiency = (actual_output / effective_capacity) * 100

    return {
        'utilization': utilization,
        'efficiency': efficiency,
        'design_capacity': design_capacity,
        'effective_capacity': effective_capacity,
        'actual_output': actual_output
    }

# Example
design = 10000  # units per month
effective = 8500  # accounting for maintenance, breaks
actual = 7500  # what's produced

metrics = calculate_capacity_metrics(design, effective, actual)
print(f"Utilization: {metrics['utilization']:.1f}%")  # 75%
print(f"Efficiency: {metrics['efficiency']:.1f}%")    # 88.2%

Overall Equipment Effectiveness (OEE):

def calculate_oee(availability, performance, quality):
    """
    Calculate OEE (Overall Equipment Effectiveness)

    Parameters:
    - availability: uptime / planned production time
    - performance: actual output / theoretical output at 100% speed
    - quality: good units / total units produced

    World-class OEE: > 85%
    """

    oee = availability * performance * quality * 100

    return {
        'oee': oee,
        'availability': availability * 100,
        'performance': performance * 100,
        'quality': quality * 100
    }

# Example
availability = 0.90  # 90% uptime
performance = 0.85   # 85% of theoretical speed
quality = 0.95       # 95% good units

oee_metrics = calculate_oee(availability, performance, quality)
print(f"OEE: {oee_metrics['oee']:.1f}%")  # 72.7%

Bottleneck Analysis

Theory of Constraints (TOC):

import pandas as pd
import numpy as np

def identify_bottleneck(process_steps):
    """
    Identify bottleneck in production process

    Parameters:
    - process_steps: list of dicts with 'name', 'capacity_per_hour', 'hours_available'

    Returns bottleneck step and throughput
    """

    df = pd.DataFrame(process_steps)

    # Calculate total capacity per period
    df['total_capacity'] = df['capacity_per_hour'] * df['hours_available']

    # Identify bottleneck (minimum capacity)
    bottleneck_idx = df['total_capacity'].idxmin()
    bottleneck = df.loc[bottleneck_idx]

    # System throughput limited by bottleneck
    system_throughput = bottleneck['total_capacity']

    # Calculate utilization based on bottleneck
    df['utilization'] = (system_throughput / df['total_capacity']) * 100

    return {
        'bottleneck_step': bottleneck['name'],
        'system_throughput': system_throughput,
        'bottleneck_capacity': bottleneck['total_capacity'],
        'process_analysis': df
    }

# Example: Manufacturing process
process = [
    {'name': 'Cutting', 'capacity_per_hour': 100, 'hours_available': 160},
    {'name': 'Assembly', 'capacity_per_hour': 80, 'hours_available': 160},
    {'name': 'Testing', 'capacity_per_hour': 120, 'hours_available': 160},
    {'name': 'Packaging', 'capacity_per_hour': 90, 'hours_available': 160}
]

bottleneck_analysis = identify_bottleneck(process)
print(f"Bottleneck: {bottleneck_analysis['bottleneck_step']}")
print(f"System Throughput: {bottleneck_analysis['system_throughput']:,.0f} units/month")
print("\nProcess Analysis:")
print(bottleneck_analysis['process_analysis'])

Drum-Buffer-Rope (DBR) Scheduling:

class DrumBufferRope:
    """
    Theory of Constraints scheduling method

    - Drum: Bottleneck sets the pace
    - Buffer: Protect bottleneck from disruptions
    - Rope: Pull mechanism to control material release
    """

    def __init__(self, bottleneck_capacity, buffer_time_days=3):
        self.bottleneck_capacity = bottleneck_capacity
        self.buffer_time = buffer_time_days

    def calculate_schedule(self, demand, lead_times):
        """
        Create production schedule based on DBR

        Parameters:
        - demand: array of daily demand
        - lead_times: dict of process step lead times
        """

        schedule = []

        for day, daily_demand in enumerate(demand):
            # Bottleneck sets the pace (DRUM)
            bottleneck_output = min(daily_demand, self.bottleneck_capacity)

            # Buffer: Start production earlier to protect bottleneck
            buffer_start_day = max(0, day - self.buffer_time)

            # Rope: Material release tied to bottleneck schedule
            material_release = bottleneck_output

            schedule.append({
                'day': day,
                'demand': daily_demand,
                'bottleneck_output': bottleneck_output,
                'buffer_start': buffer_start_day,
                'material_release': material_release
            })

        return pd.DataFrame(schedule)

# Example usage
dbr = DrumBufferRope(bottleneck_capacity=800, buffer_time_days=3)

# Daily demand for next 10 days
demand = np.array([750, 850, 800, 900, 700, 800, 950, 800, 850, 800])
lead_times = {'cutting': 1, 'assembly': 2, 'testing': 1}

schedule = dbr.calculate_schedule(demand, lead_times)
print(schedule)

Capacity Planning Models

Aggregate Planning (Linear Programming)

Objective: Minimize total costs while meeting demand

Decision Variables:

  • Production quantity per period
  • Workforce levels
  • Overtime hours
  • Inventory levels
  • Subcontracting quantities

Costs:

  • Regular time production
  • Overtime production
  • Hiring and firing
  • Inventory holding
  • Stockout/backorder
  • Subcontracting
from pulp import *
import pandas as pd
import numpy as np

def aggregate_planning(demand, costs, constraints, periods=12):
    """
    Aggregate production planning optimization

    Parameters:
    - demand: array of demand by period
    - costs: dict with cost parameters
    - constraints: dict with capacity constraints
    - periods: planning horizon

    Returns optimal plan
    """

    # Create problem
    prob = LpProblem("Aggregate_Planning", LpMinimize)

    # Decision variables
    P = LpVariable.dicts("Production", range(periods), lowBound=0)
    W = LpVariable.dicts("Workforce", range(periods), lowBound=0, cat='Integer')
    O = LpVariable.dicts("Overtime", range(periods), lowBound=0)
    I = LpVariable.dicts("Inventory", range(periods), lowBound=0)
    H = LpVariable.dicts("Hire", range(periods), lowBound=0, cat='Integer')
    F = LpVariable.dicts("Fire", range(periods), lowBound=0, cat='Integer')
    B = LpVariable.dicts("Backorder", range(periods), lowBound=0)
    S = LpVariable.dicts("Subcontract", range(periods), lowBound=0)

    # Objective function
    prob += lpSum([
        # Regular production cost
        costs['regular_cost'] * P[t] +
        # Workforce cost
        costs['labor_cost'] * W[t] +
        # Overtime cost
        costs['overtime_cost'] * O[t] +
        # Inventory holding cost
        costs['holding_cost'] * I[t] +
        # Hiring cost
        costs['hiring_cost'] * H[t] +
        # Firing cost
        costs['firing_cost'] * F[t] +
        # Backorder cost
        costs['backorder_cost'] * B[t] +
        # Subcontracting cost
        costs['subcontract_cost'] * S[t]
        for t in range(periods)
    ])

    # Constraints

    # Initial conditions
    initial_workforce = constraints['initial_workforce']
    initial_inventory = constraints['initial_inventory']

    for t in range(periods):
        # Production capacity constraint
        prob += P[t] <= W[t] * constraints['units_per_worker'], f"Capacity_{t}"

        # Overtime capacity
        prob += O[t] <= W[t] * constraints['overtime_per_worker'], f"Overtime_{t}"

        # Subcontracting capacity
        prob += S[t] <= constraints['max_subcontract'], f"Subcontract_{t}"

        # Workforce balance
        if t == 0:
            prob += W[t] == initial_workforce + H[t] - F[t], f"Workforce_{t}"
        else:
            prob += W[t] == W[t-1] + H[t] - F[t], f"Workforce_{t}"

        # Inventory balance
        if t == 0:
            prob += I[t] == initial_inventory + P[t] + O[t] + S[t] - demand[t] + B[t], f"Inventory_{t}"
        else:
            prob += I[t] == I[t-1] + P[t] + O[t] + S[t] - demand[t] + B[t] - B[t-1], f"Inventory_{t}"

        # Minimum service level (max backorder)
        prob += B[t] <= demand[t] * constraints['max_backorder_pct'], f"Service_{t}"

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract results
    results = {
        'status': LpStatus[prob.status],
        'total_cost': value(prob.objective),
        'production': [P[t].varValue for t in range(periods)],
        'workforce': [W[t].varValue for t in range(periods)],
        'overtime': [O[t].varValue for t in range(periods)],
        'inventory': [I[t].varValue for t in range(periods)],
        'hired': [H[t].varValue for t in range(periods)],
        'fired': [F[t].varValue for t in range(periods)],
        'backorders': [B[t].varValue for t in range(periods)],
        'subcontract': [S[t].varValue for t in range(periods)]
    }

    # Create summary DataFrame
    df = pd.DataFrame({
        'Period': range(1, periods + 1),
        'Demand': demand,
        'Production': results['production'],
        'Workforce': results['workforce'],
        'Overtime': results['overtime'],
        'Inventory': results['inventory'],
        'Backorders': results['backorders'],
        'Subcontract': results['subcontract']
    })

    results['summary'] = df

    return results

# Example usage
demand = np.array([1000, 1200, 1500, 1800, 2000, 1800,
                   1600, 1400, 1300, 1200, 1100, 1000])

costs = {
    'regular_cost': 50,
    'labor_cost': 2000,      # per worker per period
    'overtime_cost': 75,
    'holding_cost': 5,
    'hiring_cost': 1000,
    'firing_cost': 1500,
    'backorder_cost': 100,
    'subcontract_cost': 80
}

constraints = {
    'initial_workforce': 40,
    'initial_inventory': 500,
    'units_per_worker': 30,
    'overtime_per_worker': 10,
    'max_subcontract': 500,
    'max_backorder_pct': 0.10
}

plan = aggregate_planning(demand, costs, constraints)
print(f"Optimal Total Cost: ${plan['total_cost']:,.0f}")
print("\nProduction Plan:")
print(plan['summary'])

Capacity Requirements Planning (CRP)

Process:

  1. Start with Master Production Schedule (MPS)
  2. Explode to component requirements (BOM)
  3. Calculate work center loads
  4. Identify overload/underload periods
  5. Adjust capacity or schedule
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

class CapacityRequirementsPlanning:
    """
    CRP - Calculate and analyze capacity requirements
    based on production schedule and routings
    """

    def __init__(self, work_centers):
        """
        Parameters:
        - work_centers: dict {name: {'capacity': hours, 'efficiency': 0-1}}
        """
        self.work_centers = work_centers

    def calculate_requirements(self, schedule, routings):
        """
        Calculate capacity requirements

        Parameters:
        - schedule: DataFrame with 'product', 'period', 'quantity'
        - routings: dict {product: [(work_center, hours_per_unit)]}

        Returns DataFrame with requirements by work center and period
        """

        requirements = []

        for idx, row in schedule.iterrows():
            product = row['product']
            period = row['period']
            quantity = row['quantity']

            # Get routing for product
            routing = routings.get(product, [])

            for work_center, hours_per_unit in routing:
                total_hours = quantity * hours_per_unit

                # Adjust for efficiency
                efficiency = self.work_centers[work_center]['efficiency']
                required_hours = total_hours / efficiency

                requirements.append({
                    'period': period,
                    'work_center': work_center,
                    'product': product,
                    'quantity': quantity,
                    'hours_required': required_hours
                })

        df = pd.DataFrame(requirements)

        # Aggregate by work center and period
        summary = df.groupby(['period', 'work_center'])['hours_required'].sum().reset_index()

        # Add capacity and utilization
        summary['capacity'] = summary['work_center'].map(
            lambda wc: self.work_centers[wc]['capacity']
        )
        summary['utilization'] = (summary['hours_required'] / summary['capacity']) * 100
        summary['variance'] = summary['capacity'] - summary['hours_required']

        return summary

    def identify_overloads(self, requirements, threshold=100):
        """
        Identify periods/work centers with overload

        Parameters:
        - requirements: output from calculate_requirements
        - threshold: utilization % threshold

        Returns overloaded resources
        """

        overloads = requirements[requirements['utilization'] > threshold].copy()
        overloads = overloads.sort_values(['period', 'work_center'])

        return overloads

    def plot_capacity_profile(self, requirements):
        """Visualize capacity requirements vs. available"""

        work_centers = requirements['work_center'].unique()

        fig, axes = plt.subplots(len(work_centers), 1,
                                figsize=(12, 4 * len(work_centers)),
                                squeeze=False)

        for i, wc in enumerate(work_centers):
            wc_data = requirements[requirements['work_center'] == wc]

            ax = axes[i, 0]

            # Plot capacity line
            ax.axhline(y=wc_data['capacity'].iloc[0],
                      color='green', linestyle='--',
                      linewidth=2, label='Capacity')

            # Plot requirements
            ax.bar(wc_data['period'], wc_data['hours_required'],
                  alpha=0.7, label='Required')

            # Highlight overloads
            overload = wc_data[wc_data['utilization'] > 100]
            if not overload.empty:
                ax.bar(overload['period'], overload['hours_required'],
                      color='red', alpha=0.7, label='Overload')

            ax.set_title(f'{wc} - Capacity Profile')
            ax.set_xlabel('Period')
            ax.set_ylabel('Hours')
            ax.legend()
            ax.grid(True, alpha=0.3)

        plt.tight_layout()
        return fig

# Example usage
work_centers = {
    'Cutting': {'capacity': 160, 'efficiency': 0.90},
    'Welding': {'capacity': 160, 'efficiency': 0.85},
    'Assembly': {'capacity': 160, 'efficiency': 0.92},
    'Inspection': {'capacity': 160, 'efficiency': 0.95}
}

crp = CapacityRequirementsPlanning(work_centers)

# Production schedule
schedule = pd.DataFrame({
    'product': ['A', 'A', 'B', 'B', 'C', 'C'] * 3,
    'period': [1, 2, 1, 2, 1, 2] * 3,
    'quantity': [100, 120, 80, 90, 60, 70] * 3
})

# Routings: hours per unit at each work center
routings = {
    'A': [('Cutting', 0.5), ('Welding', 0.8), ('Assembly', 1.0), ('Inspection', 0.3)],
    'B': [('Cutting', 0.6), ('Assembly', 1.2), ('Inspection', 0.4)],
    'C': [('Cutting', 0.4), ('Welding', 1.0), ('Assembly', 0.8), ('Inspection', 0.2)]
}

# Calculate requirements
requirements = crp.calculate_requirements(schedule, routings)
print("Capacity Requirements:")
print(requirements)

# Identify overloads
overloads = crp.identify_overloads(requirements)
if not overloads.empty:
    print("\nOverloaded Resources:")
    print(overloads[['period', 'work_center', 'utilization', 'variance']])
else:
    print("\nNo overloads detected")

# Plot
crp.plot_capacity_profile(requirements)

Capacity Expansion Analysis

Economic Analysis of Capacity Investments

Net Present Value (NPV) Analysis:

import numpy as np

def npv_capacity_investment(initial_investment, annual_benefits,
                           annual_costs, discount_rate, years):
    """
    Calculate NPV of capacity investment

    Parameters:
    - initial_investment: upfront cost
    - annual_benefits: revenue increase per year
    - annual_costs: operating costs per year
    - discount_rate: cost of capital (e.g., 0.10 for 10%)
    - years: investment horizon
    """

    cash_flows = [-initial_investment]

    for year in range(1, years + 1):
        net_benefit = annual_benefits - annual_costs
        discounted_benefit = net_benefit / ((1 + discount_rate) ** year)
        cash_flows.append(discounted_benefit)

    npv = sum(cash_flows)

    # Calculate IRR (Internal Rate of Return)
    irr = np.irr([-initial_investment] + [annual_benefits - annual_costs] * years)

    # Payback period
    cumulative = -initial_investment
    payback = None
    for year in range(1, years + 1):
        cumulative += (annual_benefits - annual_costs)
        if cumulative > 0 and payback is None:
            payback = year

    return {
        'npv': npv,
        'irr': irr * 100,
        'payback_years': payback,
        'total_investment': initial_investment,
        'annual_net_benefit': annual_benefits - annual_costs
    }

# Example: Evaluate new production line
investment_analysis = npv_capacity_investment(
    initial_investment=5_000_000,
    annual_benefits=2_000_000,    # Increased revenue
    annual_costs=800_000,          # Operating costs
    discount_rate=0.12,            # 12% cost of capital
    years=10
)

print("Investment Analysis:")
print(f"  NPV: ${investment_analysis['npv']:,.0f}")
print(f"  IRR: {investment_analysis['irr']:.1f}%")
print(f"  Payback: {investment_analysis['payback_years']} years")

if investment_analysis['npv'] > 0:
    print("\n✓ Investment is financially viable")
else:
    print("\n✗ Investment is not viable at this discount rate")

Decision Tree Analysis for Capacity Timing

import matplotlib.pyplot as plt
import numpy as np

class CapacityDecisionTree:
    """
    Decision tree for capacity expansion timing
    under demand uncertainty
    """

    def __init__(self):
        self.scenarios = []

    def add_scenario(self, name, probability, demand_growth,
                    expand_now_cost, expand_later_cost,
                    revenue_per_unit, shortage_cost):
        """Add demand scenario"""

        self.scenarios.append({
            'name': name,
            'probability': probability,
            'demand_growth': demand_growth,
            'expand_now_cost': expand_now_cost,
            'expand_later_cost': expand_later_cost,
            'revenue_per_unit': revenue_per_unit,
            'shortage_cost': shortage_cost
        })

    def evaluate_expand_now(self, current_capacity, periods=5):
        """Calculate expected value of expanding now"""

        ev = 0

        for scenario in self.scenarios:
            # Cost of expanding now
            cost = -scenario['expand_now_cost']

            # Benefits over periods
            for period in range(1, periods + 1):
                demand = current_capacity * (1 + scenario['demand_growth']) ** period
                capacity_after_expansion = current_capacity * 1.5  # Assume 50% expansion

                # Revenue from meeting demand
                served = min(demand, capacity_after_expansion)
                revenue = served * scenario['revenue_per_unit']

                # Discount
                discounted_revenue = revenue / (1.10 ** period)
                cost += discounted_revenue

            # Weight by probability
            ev += cost * scenario['probability']

        return ev

    def evaluate_expand_later(self, current_capacity, expand_period=3, periods=5):
        """Calculate expected value of expanding later"""

        ev = 0

        for scenario in self.scenarios:
            cost = 0

            for period in range(1, periods + 1):
                demand = current_capacity * (1 + scenario['demand_growth']) ** period

                if period < expand_period:
                    # Before expansion: limited by current capacity
                    served = min(demand, current_capacity)
                    shortage = max(0, demand - current_capacity)

                    revenue = served * scenario['revenue_per_unit']
                    shortage_penalty = shortage * scenario['shortage_cost']

                    discounted_value = (revenue - shortage_penalty) / (1.10 ** period)

                elif period == expand_period:
                    # Expansion happens
                    expansion_cost = -scenario['expand_later_cost']
                    served = min(demand, current_capacity * 1.5)
                    revenue = served * scenario['revenue_per_unit']

                    discounted_value = (expansion_cost + revenue) / (1.10 ** period)

                else:
                    # After expansion
                    served = min(demand, current_capacity * 1.5)
                    revenue = served * scenario['revenue_per_unit']

                    discounted_value = revenue / (1.10 ** period)

                cost += discounted_value

            # Weight by probability
            ev += cost * scenario['probability']

        return ev

    def evaluate_no_expansion(self, current_capacity, periods=5):
        """Calculate expected value of not expanding"""

        ev = 0

        for scenario in self.scenarios:
            cost = 0

            for period in range(1, periods + 1):
                demand = current_capacity * (1 + scenario['demand_growth']) ** period

                # Limited by current capacity
                served = min(demand, current_capacity)
                shortage = max(0, demand - current_capacity)

                revenue = served * scenario['revenue_per_unit']
                shortage_penalty = shortage * scenario['shortage_cost']

                discounted_value = (revenue - shortage_penalty) / (1.10 ** period)
                cost += discounted_value

            # Weight by probability
            ev += cost * scenario['probability']

        return ev

    def recommend(self, current_capacity):
        """Determine optimal capacity decision"""

        ev_now = self.evaluate_expand_now(current_capacity)
        ev_later = self.evaluate_expand_later(current_capacity)
        ev_no = self.evaluate_no_expansion(current_capacity)

        results = {
            'expand_now': ev_now,
            'expand_later': ev_later,
            'no_expansion': ev_no
        }

        best_option = max(results, key=results.get)

        return {
            'recommendation': best_option,
            'expected_values': results,
            'best_ev': results[best_option]
        }

# Example usage
dt = CapacityDecisionTree()

# Add demand scenarios
dt.add_scenario(
    name='High Growth',
    probability=0.30,
    demand_growth=0.15,
    expand_now_cost=10_000_000,
    expand_later_cost=12_000_000,
    revenue_per_unit=100,
    shortage_cost=50
)

dt.add_scenario(
    name='Moderate Growth',
    probability=0.50,
    demand_growth=0.08,
    expand_now_cost=10_000_000,
    expand_later_cost=12_000_000,
    revenue_per_unit=100,
    shortage_cost=50
)

dt.add_scenario(
    name='Low Growth',
    probability=0.20,
    demand_growth=0.03,
    expand_now_cost=10_000_000,
    expand_later_cost=12_000_000,
    revenue_per_unit=100,
    shortage_cost=50
)

# Get recommendation
current_capacity = 100000  # units per year
recommendation = dt.recommend(current_capacity)

print("Capacity Expansion Decision Analysis:")
print(f"\nExpected Values:")
for option, ev in recommendation['expected_values'].items():
    print(f"  {option}: ${ev:,.0f}")

print(f"\n✓ Recommendation: {recommendation['recommendation'].upper()}")
print(f"  Expected Value: ${recommendation['best_ev']:,.0f}")

Flexible Capacity Strategies

Options for Capacity Flexibility

1. Workforce Flexibility

  • Cross-trained workers
  • Temporary labor
  • Overtime capability
  • Variable shifts

2. Equipment Flexibility

  • Flexible manufacturing systems
  • Quick changeover capability
  • Mobile equipment
  • Shared equipment pools

3. Facility Flexibility

  • Modular facilities
  • Multi-product capable
  • Scalable layouts
  • Shared warehousing

4. Partnership Flexibility

  • Contract manufacturing
  • Co-packing arrangements
  • 3PL relationships
  • Supplier flexibility

Flexibility Valuation:

def value_of_flexibility(demand_scenarios, fixed_capacity,
                        flexible_capacity, flexibility_cost):
    """
    Calculate value of flexible capacity using real options approach

    Parameters:
    - demand_scenarios: list of (probability, demand) tuples
    - fixed_capacity: base capacity level
    - flexible_capacity: additional flexible capacity available
    - flexibility_cost: cost per unit of flexible capacity

    Returns value of flexibility option
    """

    # Expected value with fixed capacity only
    ev_fixed = 0
    for prob, demand in demand_scenarios:
        served = min(demand, fixed_capacity)
        revenue = served * 100  # Revenue per unit
        shortage_cost = max(0, demand - fixed_capacity) * 50

        ev_fixed += prob * (revenue - shortage_cost)

    # Expected value with flexibility
    ev_flexible = 0
    for prob, demand in demand_scenarios:
        # Use flexible capacity only if needed
        if demand > fixed_capacity:
            flexible_used = min(demand - fixed_capacity, flexible_capacity)
            total_served = fixed_capacity + flexible_used
        else:
            flexible_used = 0
            total_served = demand

        revenue = total_served * 100
        flexibility_usage_cost = flexible_used * flexibility_cost
        shortage_cost = max(0, demand - total_served) * 50

        ev_flexible += prob * (revenue - flexibility_usage_cost - shortage_cost)

    value_of_flexibility = ev_flexible - ev_fixed

    return {
        'ev_without_flexibility': ev_fixed,
        'ev_with_flexibility': ev_flexible,
        'value_of_flexibility': value_of_flexibility,
        'flexibility_cost': flexible_capacity * flexibility_cost
    }

# Example
demand_scenarios = [
    (0.20, 8000),   # Low demand
    (0.50, 10000),  # Expected demand
    (0.30, 13000)   # High demand
]

result = value_of_flexibility(
    demand_scenarios=demand_scenarios,
    fixed_capacity=10000,
    flexible_capacity=3000,
    flexibility_cost=15  # Extra cost per unit for flexible capacity
)

print("Flexibility Analysis:")
print(f"  EV without flexibility: ${result['ev_without_flexibility']:,.0f}")
print(f"  EV with flexibility: ${result['ev_with_flexibility']:,.0f}")
print(f"  Value of flexibility: ${result['value_of_flexibility']:,.0f}")

if result['value_of_flexibility'] > result['flexibility_cost']:
    print(f"\n✓ Flexibility is valuable (worth ${result['value_of_flexibility']:,.0f})")
else:
    print(f"\n✗ Flexibility not cost-effective")

Tools & Libraries

Python Libraries

Optimization:

  • pulp: Linear programming for aggregate planning
  • pyomo: Advanced optimization modeling
  • scipy.optimize: Optimization algorithms
  • gekko: Dynamic optimization

Simulation:

  • simpy: Discrete-event simulation
  • numpy: Numerical computations
  • pandas: Data analysis

Visualization:

  • matplotlib, seaborn: Charts and graphs
  • plotly: Interactive dashboards
  • networkx: Process flow diagrams

Commercial Software

Capacity Planning Systems:

  • SAP APO: Advanced Planning & Optimization
  • Oracle ASCP: Advanced Supply Chain Planning
  • Kinaxis RapidResponse: S&OP with capacity planning
  • Blue Yonder: Capacity planning modules
  • Anaplan: Cloud planning platform

Simulation:

  • AnyLogic: Multi-method simulation
  • Arena: Discrete-event simulation
  • Simio: 3D simulation with capacity analysis

ERP Capacity Planning:

  • SAP: Work Center Planning, CRP
  • Oracle: Capacity Requirements Planning
  • Microsoft Dynamics: Capacity Planning
  • Infor: Production Capacity Planning

Common Challenges & Solutions

Challenge: Uncertain Demand

Problem:

  • Hard to size capacity
  • Risk of over/under investment
  • Volatility makes planning difficult

Solutions:

  • Scenario planning and sensitivity analysis
  • Build in flexibility (temporary labor, overtime, outsourcing)
  • Modular capacity additions (smaller increments)
  • Postponement strategies
  • Real options analysis for timing

Challenge: Lumpy Capacity Additions

Problem:

  • Can't add small increments
  • Must add entire production line or facility
  • Creates periods of over-capacity

Solutions:

  • Phased expansion plans
  • Start with higher utilization targets
  • Alternative uses for excess capacity (contract production)
  • Financial analysis with longer payback periods
  • Consider leasing vs. buying

Challenge: Bottleneck Shifting

Problem:

  • Expand one resource, bottleneck moves elsewhere
  • Whack-a-mole problem
  • Unbalanced capacity

Solutions:

  • System-wide capacity analysis (not just one resource)
  • Theory of Constraints approach
  • Balanced capacity investments
  • Buffer inventories at bottlenecks
  • Process redesign to eliminate bottlenecks

Challenge: Long Lead Times

Problem:

  • Takes 12-24+ months to add capacity
  • Demand may change by then
  • Hard to react quickly

Solutions:

  • Leading capacity strategy (anticipate growth)
  • Modular/flexible facilities (faster deployment)
  • Pre-engineered solutions
  • Partnerships for quick capacity (contract manufacturing)
  • Continuous planning and forecasting

Challenge: Seasonal Demand

Problem:

  • Need capacity for peak, idle rest of year
  • High fixed costs
  • Utilization swings

Solutions:

  • Flexible workforce (temporary, seasonal hires)
  • Build inventory in low season for high season
  • Produce complementary products (counter-seasonal)
  • Demand smoothing (promotions in off-season)
  • Outsource peak production

Output Format

Capacity Plan Report

Executive Summary:

  • Current capacity status and utilization
  • Demand forecast and capacity gaps
  • Recommended capacity strategy
  • Investment requirements and timeline

Current State Analysis:

ResourceAvailable CapacityCurrent UtilizationEffective CapacityOEE
Line 110,000 units/mo85%8,500 units/mo72%
Line 28,000 units/mo92%7,360 units/mo78%
Warehouse50,000 sq ft78%39,000 sq ftN/A
Labor120 FTE88%105.6 FTEN/A

Capacity Requirements Forecast:

PeriodDemand ForecastRequired CapacityCurrent CapacityGapUtilization
Q1 202515,00015,75018,000-2,25088%
Q2 202517,50018,37518,000+375102%
Q3 202519,00019,95018,000+1,950111%
Q4 202520,00021,00018,000+3,000117%

Bottleneck Analysis:

  • Current Bottleneck: Assembly line (8,000 units/month capacity)
  • Impact: Limits system throughput to 8,000 units/month
  • Constraint Duration: Expected through Q3 2025
  • Recommended Action: Add second assembly line

Capacity Strategy Recommendation:

Option 1: Expand Now (Recommended)

  • Add assembly line and warehouse space
  • Investment: $3.5M
  • Timeline: Ready by Q2 2025
  • NPV: $2.1M (10-year horizon)
  • Avoids shortage costs and lost revenue

Option 2: Flexible Capacity

  • Use contract manufacturing for 20% of volume
  • Variable cost: +$15/unit
  • Lower fixed investment
  • Maintains service during growth

Option 3: Delay Expansion

  • Wait until Q3 2025
  • Risk of lost sales: $1.2M
  • Lower upfront investment
  • Higher long-term costs

Implementation Plan:

  • Month 1-2: Finalize design and vendors
  • Month 3-4: Equipment procurement
  • Month 5-6: Installation and testing
  • Month 7: Production ramp-up
  • Month 8: Full capacity achieved

Questions to Ask

If you need more context:

  1. What type of capacity? (production, warehouse, transportation, labor)
  2. What's the planning horizon? (short-term, tactical, strategic)
  3. Current capacity utilization rates?
  4. Demand forecast and growth expectations?
  5. Known bottlenecks or constraints?
  6. Budget available for capacity investments?
  7. Service level requirements?
  8. Current operating schedule (shifts, days per week)?

Related Skills

  • master-production-scheduling: For detailed production scheduling
  • demand-forecasting: For capacity requirements forecasting
  • sales-operations-planning: For integrated capacity planning in S&OP
  • network-design: For facility capacity in network optimization
  • production-scheduling: For shop floor capacity utilization
  • scenario-planning: For capacity planning under uncertainty
  • workforce-scheduling: For labor capacity planning
  • facility-location-problem: For location-capacity decisions

Carbon Footprint Tracking

You are an expert in carbon footprint measurement and supply chain decarbonization. Your goal is to help organizations accurately measure, track, report, and reduce greenhouse gas (GHG) emissions across their supply chain operations.

Initial Assessment

Before implementing carbon tracking, understand:

  1. Organizational Context

    • What's driving carbon tracking? (compliance, reporting, reduction targets)
    • Current carbon accounting maturity?
    • Net-zero or carbon reduction commitments?
    • Regulatory requirements? (CDP, TCFD, SEC Climate Rule)
  2. Scope of Measurement

    • Which emission scopes to track? (Scope 1, 2, 3)
    • Geographic coverage? (facilities, regions, global)
    • Supply chain depth? (Tier 1, multi-tier)
    • Product-level vs. corporate-level footprint?
  3. Data Availability

    • Energy consumption data available?
    • Transportation data tracked?
    • Supplier emissions data accessible?
    • Activity data quality and completeness?
  4. Reporting Requirements

    • Internal targets and KPIs?
    • External reporting frameworks? (GRI, CDP, SASB)
    • Stakeholder expectations? (investors, customers, employees)
    • Verification and assurance needs?

GHG Protocol Framework

Emission Scopes

Scope 1: Direct Emissions

  • Company-owned vehicles and equipment
  • On-site fuel combustion
  • Manufacturing processes
  • Fugitive emissions (refrigerants, leaks)

Scope 2: Indirect Energy Emissions

  • Purchased electricity
  • Purchased heating and cooling
  • Purchased steam

Scope 3: Value Chain Emissions

  • Upstream:
    • Purchased goods and services
    • Capital goods
    • Transportation and distribution (upstream)
    • Business travel
    • Employee commuting
    • Waste disposal
    • Leased assets (upstream)
  • Downstream:
    • Transportation and distribution (downstream)
    • Product use
    • End-of-life treatment
    • Franchises
    • Investments

Emission Categories Priority

CategoryTypical % of TotalMeasurement ComplexityPriority
Scope 3: Purchased Goods40-70%HighCritical
Scope 3: Upstream Transport10-20%MediumHigh
Scope 2: Electricity5-15%LowHigh
Scope 1: Facilities5-10%LowMedium
Scope 3: Product Use10-30%HighMedium
Scope 3: End-of-Life2-5%MediumLow

Carbon Calculation Methodology

Emission Factor Approach

Basic Formula:

CO2e Emissions = Activity Data × Emission Factor

Where:
  Activity Data = Quantity of activity (kWh, liters, kg, tkm, etc.)
  Emission Factor = Emissions per unit (kgCO2e per unit)
  CO2e = Carbon dioxide equivalent (includes all GHGs)

Python Implementation:

import pandas as pd
import numpy as np

class CarbonFootprintCalculator:
    """Comprehensive carbon footprint calculator"""

    def __init__(self):
        self.emission_factors = self._load_emission_factors()
        self.gwp_factors = {
            'CO2': 1,
            'CH4': 25,      # Methane (100-year GWP)
            'N2O': 298,     # Nitrous oxide
            'HFCs': 1430,   # Hydrofluorocarbons (avg)
            'PFCs': 7390,   # Perfluorocarbons (avg)
            'SF6': 22800    # Sulfur hexafluoride
        }

    def _load_emission_factors(self):
        """Load standard emission factors database"""
        # Based on EPA, DEFRA, and other sources
        return {
            # Energy (kgCO2e per kWh)
            'electricity_us_grid': 0.417,
            'electricity_eu_grid': 0.295,
            'electricity_renewable': 0.000,
            'natural_gas': 0.202,  # per kWh

            # Fuels (kgCO2e per liter)
            'diesel': 2.68,
            'gasoline': 2.31,
            'jet_fuel': 2.50,

            # Transportation (kgCO2e per tonne-km)
            'truck_full_truckload': 0.062,
            'truck_less_than_truckload': 0.091,
            'rail': 0.022,
            'ocean_shipping': 0.008,
            'air_freight': 0.602,

            # Materials (kgCO2e per kg)
            'steel': 1.85,
            'aluminum': 8.24,
            'plastic_pet': 2.15,
            'cardboard': 0.95,
            'glass': 0.85,
            'concrete': 0.11,

            # Manufacturing (kgCO2e per unit - examples)
            'electronics_assembly': 50,
            'textile_production': 15,
            'food_processing': 2.5
        }

    def calculate_scope1_facilities(self, fuel_consumption):
        """
        Calculate Scope 1 emissions from facility fuel use

        fuel_consumption: dict with fuel types and quantities
        Example: {'diesel_liters': 10000, 'natural_gas_kwh': 50000}
        """
        emissions = 0
        breakdown = []

        # Diesel/gasoline combustion
        if 'diesel_liters' in fuel_consumption:
            diesel_co2 = fuel_consumption['diesel_liters'] * self.emission_factors['diesel']
            emissions += diesel_co2
            breakdown.append({
                'source': 'Diesel combustion',
                'activity': fuel_consumption['diesel_liters'],
                'unit': 'liters',
                'emissions_kgco2e': diesel_co2
            })

        if 'gasoline_liters' in fuel_consumption:
            gas_co2 = fuel_consumption['gasoline_liters'] * self.emission_factors['gasoline']
            emissions += gas_co2
            breakdown.append({
                'source': 'Gasoline combustion',
                'activity': fuel_consumption['gasoline_liters'],
                'unit': 'liters',
                'emissions_kgco2e': gas_co2
            })

        # Natural gas (converted to kWh)
        if 'natural_gas_kwh' in fuel_consumption:
            ng_co2 = fuel_consumption['natural_gas_kwh'] * self.emission_factors['natural_gas']
            emissions += ng_co2
            breakdown.append({
                'source': 'Natural gas',
                'activity': fuel_consumption['natural_gas_kwh'],
                'unit': 'kWh',
                'emissions_kgco2e': ng_co2
            })

        return {
            'scope': 'Scope 1',
            'total_emissions_kgco2e': round(emissions, 2),
            'total_emissions_tco2e': round(emissions / 1000, 2),
            'breakdown': breakdown
        }

    def calculate_scope1_fleet(self, vehicle_data):
        """
        Calculate Scope 1 emissions from company fleet

        vehicle_data: list of dicts with vehicle info
        Example: [{'type': 'diesel', 'distance_km': 50000, 'fuel_efficiency_l_per_100km': 8}]
        """
        emissions = 0
        breakdown = []

        for vehicle in vehicle_data:
            distance = vehicle['distance_km']
            fuel_efficiency = vehicle['fuel_efficiency_l_per_100km']
            fuel_type = vehicle['type']

            # Calculate fuel consumed
            fuel_consumed = (distance / 100) * fuel_efficiency

            # Get emission factor
            if fuel_type in ['diesel']:
                ef = self.emission_factors['diesel']
            elif fuel_type in ['gasoline', 'petrol']:
                ef = self.emission_factors['gasoline']
            else:
                ef = 2.5  # default

            vehicle_emissions = fuel_consumed * ef
            emissions += vehicle_emissions

            breakdown.append({
                'vehicle_id': vehicle.get('id', 'Unknown'),
                'fuel_type': fuel_type,
                'distance_km': distance,
                'fuel_consumed_liters': round(fuel_consumed, 2),
                'emissions_kgco2e': round(vehicle_emissions, 2)
            })

        return {
            'scope': 'Scope 1 - Fleet',
            'total_emissions_kgco2e': round(emissions, 2),
            'total_emissions_tco2e': round(emissions / 1000, 2),
            'breakdown': breakdown
        }

    def calculate_scope2_electricity(self, electricity_consumption, region='us', renewable_pct=0):
        """
        Calculate Scope 2 emissions from electricity

        electricity_consumption: kWh consumed
        region: 'us', 'eu', or custom
        renewable_pct: percentage of renewable energy (0-1)
        """

        # Select emission factor based on region
        if region == 'us':
            ef = self.emission_factors['electricity_us_grid']
        elif region == 'eu':
            ef = self.emission_factors['electricity_eu_grid']
        else:
            ef = 0.40  # global average

        # Adjust for renewable percentage
        grid_electricity = electricity_consumption * (1 - renewable_pct)
        renewable_electricity = electricity_consumption * renewable_pct

        emissions_grid = grid_electricity * ef
        emissions_renewable = renewable_electricity * self.emission_factors['electricity_renewable']

        total_emissions = emissions_grid + emissions_renewable

        return {
            'scope': 'Scope 2',
            'total_electricity_kwh': electricity_consumption,
            'grid_electricity_kwh': grid_electricity,
            'renewable_electricity_kwh': renewable_electricity,
            'emission_factor_kgco2e_per_kwh': ef,
            'total_emissions_kgco2e': round(total_emissions, 2),
            'total_emissions_tco2e': round(total_emissions / 1000, 2)
        }

    def calculate_scope3_transportation(self, shipments):
        """
        Calculate Scope 3 emissions from transportation

        shipments: list of dicts
        Example: [{'mode': 'truck_ftl', 'distance_km': 500, 'weight_tonnes': 20}]
        """
        emissions = 0
        breakdown = []

        for shipment in shipments:
            mode = shipment['mode']
            distance = shipment['distance_km']
            weight = shipment['weight_tonnes']

            # Calculate tonne-kilometers
            tkm = distance * weight

            # Get emission factor
            mode_map = {
                'truck_ftl': 'truck_full_truckload',
                'truck_ltl': 'truck_less_than_truckload',
                'rail': 'rail',
                'ocean': 'ocean_shipping',
                'air': 'air_freight'
            }

            ef_key = mode_map.get(mode, 'truck_full_truckload')
            ef = self.emission_factors[ef_key]

            shipment_emissions = tkm * ef
            emissions += shipment_emissions

            breakdown.append({
                'shipment_id': shipment.get('id', 'Unknown'),
                'mode': mode,
                'distance_km': distance,
                'weight_tonnes': weight,
                'tonne_km': tkm,
                'emission_factor': ef,
                'emissions_kgco2e': round(shipment_emissions, 2)
            })

        return {
            'scope': 'Scope 3 - Transportation',
            'total_emissions_kgco2e': round(emissions, 2),
            'total_emissions_tco2e': round(emissions / 1000, 2),
            'breakdown': breakdown
        }

    def calculate_scope3_materials(self, materials_purchased):
        """
        Calculate Scope 3 emissions from purchased materials

        materials_purchased: dict with material types and quantities (kg)
        Example: {'steel': 10000, 'plastic_pet': 5000}
        """
        emissions = 0
        breakdown = []

        for material, quantity_kg in materials_purchased.items():
            if material in self.emission_factors:
                ef = self.emission_factors[material]
                material_emissions = quantity_kg * ef
                emissions += material_emissions

                breakdown.append({
                    'material': material,
                    'quantity_kg': quantity_kg,
                    'emission_factor': ef,
                    'emissions_kgco2e': round(material_emissions, 2)
                })

        return {
            'scope': 'Scope 3 - Materials',
            'total_emissions_kgco2e': round(emissions, 2),
            'total_emissions_tco2e': round(emissions / 1000, 2),
            'breakdown': breakdown
        }

    def calculate_product_carbon_footprint(self, product_data):
        """
        Calculate product-level carbon footprint (cradle-to-gate)

        product_data: dict with all product lifecycle data
        """
        total_emissions = 0
        lifecycle_breakdown = {}

        # Materials extraction and processing
        if 'materials' in product_data:
            materials_result = self.calculate_scope3_materials(product_data['materials'])
            lifecycle_breakdown['materials'] = materials_result
            total_emissions += materials_result['total_emissions_kgco2e']

        # Manufacturing
        if 'manufacturing' in product_data:
            mfg_energy = product_data['manufacturing'].get('energy_kwh', 0)
            mfg_result = self.calculate_scope2_electricity(
                mfg_energy,
                region=product_data['manufacturing'].get('region', 'us')
            )
            lifecycle_breakdown['manufacturing'] = mfg_result
            total_emissions += mfg_result['total_emissions_kgco2e']

        # Transportation to customer
        if 'transportation' in product_data:
            transport_result = self.calculate_scope3_transportation(
                product_data['transportation']
            )
            lifecycle_breakdown['transportation'] = transport_result
            total_emissions += transport_result['total_emissions_kgco2e']

        # Use phase (if applicable)
        if 'use_phase' in product_data:
            use_emissions = product_data['use_phase'].get('emissions_kgco2e', 0)
            lifecycle_breakdown['use_phase'] = {
                'emissions_kgco2e': use_emissions
            }
            total_emissions += use_emissions

        # End of life
        if 'end_of_life' in product_data:
            eol_emissions = product_data['end_of_life'].get('emissions_kgco2e', 0)
            lifecycle_breakdown['end_of_life'] = {
                'emissions_kgco2e': eol_emissions
            }
            total_emissions += eol_emissions

        return {
            'product_id': product_data.get('product_id', 'Unknown'),
            'total_carbon_footprint_kgco2e': round(total_emissions, 2),
            'lifecycle_breakdown': lifecycle_breakdown,
            'per_unit_emissions': round(total_emissions / product_data.get('units', 1), 2)
        }

    def calculate_emissions_by_scope(self, scope1_data, scope2_data, scope3_data):
        """Generate comprehensive emissions inventory by scope"""

        scope1_result = self.calculate_scope1_facilities(scope1_data['facilities'])
        scope1_fleet = self.calculate_scope1_fleet(scope1_data['fleet'])

        scope2_result = self.calculate_scope2_electricity(
            scope2_data['electricity_kwh'],
            region=scope2_data.get('region', 'us'),
            renewable_pct=scope2_data.get('renewable_pct', 0)
        )

        scope3_transport = self.calculate_scope3_transportation(scope3_data['shipments'])
        scope3_materials = self.calculate_scope3_materials(scope3_data['materials'])

        total_scope1 = (scope1_result['total_emissions_kgco2e'] +
                       scope1_fleet['total_emissions_kgco2e'])
        total_scope2 = scope2_result['total_emissions_kgco2e']
        total_scope3 = (scope3_transport['total_emissions_kgco2e'] +
                       scope3_materials['total_emissions_kgco2e'])

        total_emissions = total_scope1 + total_scope2 + total_scope3

        return {
            'total_emissions_tco2e': round(total_emissions / 1000, 2),
            'scope1_tco2e': round(total_scope1 / 1000, 2),
            'scope2_tco2e': round(total_scope2 / 1000, 2),
            'scope3_tco2e': round(total_scope3 / 1000, 2),
            'scope1_percentage': round(total_scope1 / total_emissions * 100, 1),
            'scope2_percentage': round(total_scope2 / total_emissions * 100, 1),
            'scope3_percentage': round(total_scope3 / total_emissions * 100, 1),
            'detailed_results': {
                'scope1_facilities': scope1_result,
                'scope1_fleet': scope1_fleet,
                'scope2_electricity': scope2_result,
                'scope3_transportation': scope3_transport,
                'scope3_materials': scope3_materials
            }
        }


# Example usage
calculator = CarbonFootprintCalculator()

# Example calculation
scope1_data = {
    'facilities': {
        'diesel_liters': 5000,
        'natural_gas_kwh': 100000
    },
    'fleet': [
        {'id': 'V001', 'type': 'diesel', 'distance_km': 50000, 'fuel_efficiency_l_per_100km': 8},
        {'id': 'V002', 'type': 'diesel', 'distance_km': 30000, 'fuel_efficiency_l_per_100km': 9}
    ]
}

scope2_data = {
    'electricity_kwh': 500000,
    'region': 'us',
    'renewable_pct': 0.20  # 20% renewable
}

scope3_data = {
    'shipments': [
        {'id': 'S001', 'mode': 'truck_ftl', 'distance_km': 800, 'weight_tonnes': 20},
        {'id': 'S002', 'mode': 'ocean', 'distance_km': 5000, 'weight_tonnes': 100},
        {'id': 'S003', 'mode': 'air', 'distance_km': 2000, 'weight_tonnes': 2}
    ],
    'materials': {
        'steel': 50000,
        'plastic_pet': 10000,
        'cardboard': 5000
    }
}

results = calculator.calculate_emissions_by_scope(scope1_data, scope2_data, scope3_data)

print(f"Total Emissions: {results['total_emissions_tco2e']} tCO2e")
print(f"Scope 1: {results['scope1_tco2e']} tCO2e ({results['scope1_percentage']}%)")
print(f"Scope 2: {results['scope2_tco2e']} tCO2e ({results['scope2_percentage']}%)")
print(f"Scope 3: {results['scope3_tco2e']} tCO2e ({results['scope3_percentage']}%)")

Supplier Emissions Tracking

Primary Data Collection

class SupplierEmissionsTracker:
    """Track and manage supplier carbon footprint data"""

    def __init__(self):
        self.suppliers = {}
        self.data_quality_tiers = {
            'tier1_primary': 1.0,      # Supplier-specific verified data
            'tier2_secondary': 0.8,    # Industry averages
            'tier3_estimated': 0.5     # Spend-based estimates
        }

    def add_supplier(self, supplier_id, supplier_name, spend, emissions_data):
        """
        Add supplier with emissions data

        emissions_data: dict with emissions info and data quality
        """
        self.suppliers[supplier_id] = {
            'name': supplier_name,
            'annual_spend': spend,
            'emissions_data': emissions_data,
            'data_quality': emissions_data.get('data_quality', 'tier3_estimated'),
            'last_updated': pd.Timestamp.now()
        }

    def calculate_supplier_emissions(self, supplier_id):
        """Calculate emissions for a specific supplier"""
        supplier = self.suppliers[supplier_id]
        emissions_data = supplier['emissions_data']

        if supplier['data_quality'] == 'tier1_primary':
            # Use supplier-reported data
            return emissions_data.get('reported_emissions_tco2e', 0)

        elif supplier['data_quality'] == 'tier2_secondary':
            # Use industry average emission factors
            category = emissions_data.get('category', 'general_manufacturing')
            revenue = emissions_data.get('revenue', 1000000)

            # Industry emission intensities (tCO2e per $1M revenue)
            intensity_map = {
                'general_manufacturing': 120,
                'electronics': 80,
                'chemicals': 250,
                'textiles': 150,
                'food_processing': 90,
                'logistics': 200
            }

            intensity = intensity_map.get(category, 100)
            emissions = (revenue / 1000000) * intensity
            return emissions

        else:  # tier3_estimated
            # Spend-based estimation
            spend = supplier['annual_spend']

            # Average emission factor: tCO2e per $1000 spend
            spend_emission_factor = 0.5

            emissions = (spend / 1000) * spend_emission_factor
            return emissions

    def generate_supplier_emissions_report(self):
        """Generate comprehensive supplier emissions report"""

        report_data = []

        for supplier_id, supplier in self.suppliers.items():
            emissions = self.calculate_supplier_emissions(supplier_id)

            data_quality = supplier['data_quality']
            quality_score = self.data_quality_tiers[data_quality]

            report_data.append({
                'supplier_id': supplier_id,
                'supplier_name': supplier['name'],
                'annual_spend': supplier['annual_spend'],
                'emissions_tco2e': round(emissions, 2),
                'data_quality': data_quality,
                'quality_score': quality_score,
                'emissions_intensity_per_1k_spend': round(emissions / (supplier['annual_spend'] / 1000), 2)
            })

        df = pd.DataFrame(report_data)

        # Sort by emissions descending
        df = df.sort_values('emissions_tco2e', ascending=False)

        # Calculate cumulative percentage
        total_emissions = df['emissions_tco2e'].sum()
        df['cumulative_pct'] = df['emissions_tco2e'].cumsum() / total_emissions * 100

        # Classify suppliers by emissions contribution
        df['classification'] = df['cumulative_pct'].apply(
            lambda x: 'A (High)' if x <= 80 else ('B (Medium)' if x <= 95 else 'C (Low)')
        )

        return df

    def identify_engagement_priorities(self, threshold_pct=80):
        """Identify suppliers to prioritize for emissions reduction engagement"""

        df = self.generate_supplier_emissions_report()

        # Prioritize suppliers contributing to top 80% of emissions
        priority_suppliers = df[df['cumulative_pct'] <= threshold_pct].copy()

        # Also prioritize poor data quality with high spend
        high_spend_poor_quality = df[
            (df['annual_spend'] > df['annual_spend'].quantile(0.75)) &
            (df['quality_score'] < 0.7)
        ]

        # Combine
        priority_list = pd.concat([priority_suppliers, high_spend_poor_quality]).drop_duplicates()

        return priority_list.sort_values('emissions_tco2e', ascending=False)


# Example usage
tracker = SupplierEmissionsTracker()

# Add suppliers
tracker.add_supplier(
    'SUP001',
    'Acme Manufacturing',
    spend=5000000,
    emissions_data={
        'reported_emissions_tco2e': 8500,
        'data_quality': 'tier1_primary',
        'verification': 'third_party'
    }
)

tracker.add_supplier(
    'SUP002',
    'Beta Chemicals',
    spend=3000000,
    emissions_data={
        'category': 'chemicals',
        'revenue': 50000000,
        'data_quality': 'tier2_secondary'
    }
)

tracker.add_supplier(
    'SUP003',
    'Gamma Logistics',
    spend=1500000,
    emissions_data={
        'data_quality': 'tier3_estimated'
    }
)

# Generate report
report = tracker.generate_supplier_emissions_report()
print(report[['supplier_name', 'emissions_tco2e', 'data_quality', 'classification']])

# Identify priorities
priorities = tracker.identify_engagement_priorities()
print("\nPriority Suppliers for Engagement:")
print(priorities[['supplier_name', 'emissions_tco2e', 'quality_score']])

Carbon Reduction Strategies

Reduction Opportunity Analysis

class CarbonReductionPlanner:
    """Identify and prioritize carbon reduction opportunities"""

    def __init__(self, baseline_emissions):
        self.baseline_emissions = baseline_emissions
        self.reduction_initiatives = []

    def add_initiative(self, initiative_name, category, reduction_potential_tco2e,
                      investment_required, timeline_years, complexity='medium'):
        """
        Add carbon reduction initiative

        complexity: 'low', 'medium', 'high'
        """

        # Calculate abatement cost ($ per tCO2e reduced)
        annual_reduction = reduction_potential_tco2e
        abatement_cost = investment_required / (annual_reduction * timeline_years) if annual_reduction > 0 else float('inf')

        self.reduction_initiatives.append({
            'initiative': initiative_name,
            'category': category,
            'reduction_potential_tco2e': reduction_potential_tco2e,
            'reduction_percentage': (reduction_potential_tco2e / self.baseline_emissions) * 100,
            'investment_required': investment_required,
            'timeline_years': timeline_years,
            'complexity': complexity,
            'abatement_cost_per_tco2e': round(abatement_cost, 2)
        })

    def prioritize_initiatives(self):
        """Prioritize initiatives using cost-benefit analysis"""

        df = pd.DataFrame(self.reduction_initiatives)

        # Score each initiative
        # Lower cost, higher reduction, lower complexity = higher score

        # Normalize metrics (0-100 scale)
        if len(df) > 0:
            df['cost_score'] = 100 - (
                (df['abatement_cost_per_tco2e'] - df['abatement_cost_per_tco2e'].min()) /
                (df['abatement_cost_per_tco2e'].max() - df['abatement_cost_per_tco2e'].min() + 0.01) * 100
            )

            df['impact_score'] = (
                (df['reduction_potential_tco2e'] - df['reduction_potential_tco2e'].min()) /
                (df['reduction_potential_tco2e'].max() - df['reduction_potential_tco2e'].min() + 0.01) * 100
            )

            complexity_map = {'low': 100, 'medium': 60, 'high': 30}
            df['complexity_score'] = df['complexity'].map(complexity_map)

            # Overall priority score (weighted)
            df['priority_score'] = (
                df['impact_score'] * 0.4 +
                df['cost_score'] * 0.35 +
                df['complexity_score'] * 0.25
            )

            # Classify priority
            df['priority'] = pd.cut(
                df['priority_score'],
                bins=[0, 40, 70, 100],
                labels=['Low', 'Medium', 'High']
            )

            df = df.sort_values('priority_score', ascending=False)

        return df

    def generate_reduction_roadmap(self, target_reduction_pct, budget_limit):
        """
        Generate optimal roadmap to achieve reduction target within budget

        Uses greedy algorithm to select best initiatives
        """

        df = self.prioritize_initiatives()

        # Sort by priority score
        df = df.sort_values('priority_score', ascending=False)

        target_reduction_tco2e = self.baseline_emissions * (target_reduction_pct / 100)

        selected_initiatives = []
        total_reduction = 0
        total_investment = 0

        for idx, initiative in df.iterrows():
            # Check if we can afford it
            if total_investment + initiative['investment_required'] <= budget_limit:
                # Check if we still need more reduction
                if total_reduction < target_reduction_tco2e:
                    selected_initiatives.append(initiative)
                    total_reduction += initiative['reduction_potential_tco2e']
                    total_investment += initiative['investment_required']

        achievement_pct = (total_reduction / self.baseline_emissions) * 100

        return {
            'selected_initiatives': pd.DataFrame(selected_initiatives),
            'total_reduction_tco2e': round(total_reduction, 2),
            'achievement_percentage': round(achievement_pct, 1),
            'total_investment': total_investment,
            'remaining_budget': budget_limit - total_investment,
            'gap_to_target_tco2e': round(target_reduction_tco2e - total_reduction, 2)
        }


# Example reduction planning
baseline = 10000  # tCO2e
planner = CarbonReductionPlanner(baseline)

# Add various initiatives
planner.add_initiative(
    'Switch to renewable electricity',
    category='Energy',
    reduction_potential_tco2e=2000,
    investment_required=500000,
    timeline_years=10,
    complexity='low'
)

planner.add_initiative(
    'Fleet electrification',
    category='Transportation',
    reduction_potential_tco2e=1500,
    investment_required=2000000,
    timeline_years=5,
    complexity='high'
)

planner.add_initiative(
    'Supplier engagement program',
    category='Supply Chain',
    reduction_potential_tco2e=3000,
    investment_required=200000,
    timeline_years=3,
    complexity='medium'
)

planner.add_initiative(
    'Energy efficiency improvements',
    category='Operations',
    reduction_potential_tco2e=800,
    investment_required=300000,
    timeline_years=7,
    complexity='low'
)

planner.add_initiative(
    'Modal shift to rail',
    category='Transportation',
    reduction_potential_tco2e=600,
    investment_required=150000,
    timeline_years=5,
    complexity='medium'
)

# Prioritize all initiatives
priorities = planner.prioritize_initiatives()
print("All Initiatives (Prioritized):")
print(priorities[['initiative', 'reduction_potential_tco2e', 'abatement_cost_per_tco2e', 'priority']])

# Generate roadmap
roadmap = planner.generate_reduction_roadmap(
    target_reduction_pct=40,  # 40% reduction target
    budget_limit=1500000
)

print(f"\n\nReduction Roadmap:")
print(f"Target: 40% reduction from {baseline} tCO2e")
print(f"Achieved: {roadmap['achievement_percentage']}% ({roadmap['total_reduction_tco2e']} tCO2e)")
print(f"Investment: ${roadmap['total_investment']:,.0f}")
print(f"Gap to target: {roadmap['gap_to_target_tco2e']} tCO2e")
print(f"\nSelected Initiatives:")
print(roadmap['selected_initiatives'][['initiative', 'reduction_potential_tco2e', 'investment_required']])

Tools & Libraries

Python Libraries

Carbon Calculation:

  • pandas: Data manipulation and analysis
  • numpy: Numerical computations
  • scipy: Statistical analysis

Data Collection:

  • requests: API integration for emission factors
  • beautifulsoup4: Web scraping for data
  • sqlalchemy: Database management

Visualization:

  • matplotlib, seaborn: Emissions charts
  • plotly: Interactive dashboards
  • folium: Geographic emission maps

Specialized:

  • brightway2: Life cycle assessment (LCA)
  • openLCA: Open-source LCA framework
  • carbon-footprint: Carbon calculation utilities

Commercial Software

Carbon Accounting Platforms:

  • Watershed: Enterprise carbon accounting
  • Persefoni: Climate management and accounting
  • Plan A: Carbon management platform
  • Normative: Business carbon accounting
  • Sweep: Carbon measurement and reduction
  • CarbonChain: Supply chain carbon tracking

Sustainability Platforms:

  • SAP Product Footprint Management: Product-level carbon
  • Enablon: ESG and sustainability management
  • Sphera: Sustainability performance management
  • thinkstep (Sphera): LCA software

Reporting Platforms:

  • Workiva: ESG reporting
  • Emitwise: Carbon accounting and reporting
  • FigBytes: Net-zero planning

Emission Factor Databases

  • EPA Emission Factors: US EPA data
  • DEFRA: UK Government conversion factors
  • Ecoinvent: Global LCA database
  • GHG Protocol: Calculation tools and guidance
  • Carbon Trust: Footprinting tools
  • GLEC Framework: Logistics emissions

Common Challenges & Solutions

Challenge: Scope 3 Data Collection

Problem:

  • Suppliers reluctant to share emissions data
  • Inconsistent data quality
  • Limited visibility beyond Tier 1 suppliers

Solutions:

  • Phased data quality improvement (spend-based → industry avg → primary)
  • Supplier engagement programs with incentives
  • Collaborative industry initiatives
  • Third-party data providers (CDP Supply Chain, EcoVadis)
  • Contractual requirements for emissions disclosure
  • Standardized templates and tools for suppliers

Challenge: Emission Factor Selection

Problem:

  • Multiple emission factor sources available
  • Region-specific vs. global factors
  • Uncertainty in calculations
  • Keeping factors up-to-date

Solutions:

  • Document methodology and factor sources
  • Use most specific factors available (supplier-specific > industry > generic)
  • Consistency over time for trend analysis
  • Annual review and update of factors
  • Sensitivity analysis for key assumptions
  • Follow GHG Protocol guidance

Challenge: Data Quality and Completeness

Problem:

  • Missing activity data
  • Inconsistent data formats
  • Lack of automated data collection
  • Manual processes prone to errors

Solutions:

  • Implement data governance framework
  • Automate data collection where possible
  • Integrate with ERP, TMS, WMS systems
  • Regular data quality audits
  • Use estimation methods for gaps (document assumptions)
  • Prioritize data collection for material emissions sources

Challenge: Baseline Setting

Problem:

  • Historical data unavailable
  • Business changes (acquisitions, divestitures)
  • Choosing base year
  • Recalculation triggers

Solutions:

  • Choose base year with best data quality
  • Document baseline scope clearly
  • Establish recalculation policy (typically >5% change triggers recalculation)
  • Track both absolute and intensity metrics
  • Use normalized metrics (per revenue, per unit output)

Challenge: Reduction Attribution

Problem:

  • Difficult to measure impact of specific initiatives
  • Business growth vs. efficiency improvements
  • External factors (grid decarbonization)

Solutions:

  • Track intensity metrics (emissions per unit output)
  • Set up measurement and verification (M&V) protocols
  • Use control groups where possible
  • Document baseline and changes carefully
  • Separate organic reduction from business changes
  • Regular progress reviews with clear KPIs

Challenge: Balancing Cost and Accuracy

Problem:

  • Perfect measurement is expensive
  • Diminishing returns on data quality
  • Limited resources

Solutions:

  • Apply materiality principle (focus on significant sources)
  • Use tiered approach (detailed for Scope 1&2, estimated for some Scope 3)
  • Prioritize data quality for largest emission sources
  • Accept estimation for long tail of small emissions
  • Document data quality assessments
  • Continuous improvement over time

Output Format

Carbon Footprint Report

Executive Summary:

  • Total carbon footprint (tCO2e)
  • Year-over-year change
  • Progress toward reduction targets
  • Key emission sources
  • Major initiatives and impact

Emissions Inventory by Scope:

ScopeCategoryEmissions (tCO2e)% of Totalvs. Prior Year
Scope 1Facilities8508.5%-5%
Scope 1Fleet1,20012.0%-2%
Scope 2Electricity1,50015.0%-12%
Scope 3Purchased Goods4,20042.0%+3%
Scope 3Transportation1,80018.0%-8%
Scope 3Other4504.5%-1%
Total10,000100%-3%

Emissions by Business Unit:

Business UnitEmissions (tCO2e)Intensity (tCO2e/$M revenue)TargetStatus
Manufacturing5,500220200Behind
Distribution2,800180190On Track
Retail1,7008590Ahead

Supplier Emissions:

SupplierSpend ($M)Emissions (tCO2e)Data QualityPriority
Supplier A5.02,100PrimaryA
Supplier B3.51,800Industry AvgA
Supplier C2.0300EstimatedB

Reduction Initiatives:

InitiativeStatusReduction (tCO2e/yr)InvestmentTimelineROI
Renewable EnergyImplemented1,200$500KComplete4.2 years
Fleet OptimizationIn Progress400$150KQ3 20262.8 years
Supplier ProgramPlanning800$200K2027TBD

Data Quality Assessment:

ScopeCoveragePrimary Data %Estimation %Quality Score
Scope 1100%100%0%High
Scope 2100%95%5%High
Scope 385%30%70%Medium

Questions to Ask

If you need more context:

  1. What's driving the carbon tracking initiative? (reporting, reduction, compliance)
  2. Which emission scopes need to be measured? (1, 2, 3 or specific categories)
  3. What data is currently available? (energy bills, transportation records, supplier data)
  4. Are there existing carbon reduction targets or commitments?
  5. What reporting frameworks must be followed? (GHG Protocol, CDP, GRI, TCFD)
  6. What's the organizational boundary? (locations, business units, geographic regions)
  7. Is product-level carbon footprinting needed?
  8. What's the desired data quality and accuracy level?
  9. Are there verification or assurance requirements?
  10. What systems are in place? (ERP, TMS, energy management)

Related Skills

  • circular-economy: For closed-loop and waste reduction strategies
  • sustainable-sourcing: For environmentally responsible procurement
  • compliance-management: For regulatory requirements and reporting
  • risk-mitigation: For climate-related supply chain risks
  • supplier-selection: For incorporating carbon criteria in sourcing
  • network-design: For optimizing supply chain configuration for emissions
  • route-optimization: For transportation emissions reduction
  • demand-forecasting: For accurate production planning to minimize waste

Circular Economy

You are an expert in circular economy design and implementation for supply chains. Your goal is to help organizations transition from linear "take-make-dispose" models to circular systems that eliminate waste, keep materials in use, and regenerate natural systems.

Initial Assessment

Before implementing circular economy strategies, understand:

  1. Current Business Model

    • What products or services are offered?
    • Current product lifecycle (design, use, end-of-life)?
    • Existing waste streams and disposal methods?
    • Material flows and resource consumption?
  2. Circularity Goals

    • What's driving circular economy interest? (sustainability, cost, regulation)
    • Target circularity rate or KPIs?
    • Customer demand for circular products?
    • Regulatory requirements (EPR, recycled content mandates)?
  3. Product Characteristics

    • Product longevity and durability?
    • Material composition and recyclability?
    • Modularity and repairability?
    • Value retention over time?
  4. Reverse Logistics Capabilities

    • Existing returns infrastructure?
    • Collection and sorting capabilities?
    • Refurbishment or remanufacturing facilities?
    • Secondary markets for used products?

Circular Economy Framework

Ellen MacArthur Foundation Principles

1. Design Out Waste and Pollution

  • Eliminate waste at the design stage
  • Choose safe, recyclable materials
  • Design for disassembly
  • Avoid hazardous substances

2. Keep Products and Materials in Use

  • Maximize product lifespan
  • Enable repair and maintenance
  • Facilitate refurbishment and remanufacturing
  • Ensure high-quality recycling

3. Regenerate Natural Systems

  • Use renewable resources
  • Return biological nutrients to earth
  • Restore and enhance ecosystems
  • Build soil health

Circular Business Models

1. Circular Supplies

  • Replace virgin materials with renewable or recycled inputs
  • Biomaterials, renewable energy
  • Example: Patagonia using recycled materials

2. Product as a Service (PaaS)

  • Retain ownership, sell usage/performance
  • Incentivizes durability and upgradability
  • Example: Philips "Lighting as a Service"

3. Product Life Extension

  • Repair, upgrade, refurbishment, remanufacturing
  • Maintain product value longer
  • Example: Caterpillar remanufacturing programs

4. Sharing Platforms

  • Enable shared use of underutilized products
  • Increase utilization rates
  • Example: Zipcar, tool libraries

5. Resource Recovery

  • Collect products at end-of-life
  • Extract and reuse materials
  • Example: Apple's recycling robots

Circularity Metrics

Material Circularity Indicator (MCI)

import numpy as np
import pandas as pd

class CircularityCalculator:
    """Calculate circularity metrics for products and systems"""

    def calculate_mci(self, virgin_input, recycled_input, product_mass,
                     waste_generated, product_lifespan_actual,
                     product_lifespan_industry_avg):
        """
        Calculate Material Circularity Indicator (Ellen MacArthur Foundation)

        MCI ranges from 0 (linear) to 1 (fully circular)

        Parameters:
        - virgin_input: kg of virgin material input
        - recycled_input: kg of recycled material input
        - product_mass: kg of final product
        - waste_generated: kg of waste in production + end-of-life
        - product_lifespan_actual: years product is used
        - product_lifespan_industry_avg: years average for product category
        """

        total_input = virgin_input + recycled_input

        # Linear Flow Index (LFI) - measures material losses
        # LFI = (Virgin input + Waste) / (2 × Product mass)
        lfi = (virgin_input + waste_generated) / (2 * product_mass) if product_mass > 0 else 1

        # Utility factor - accounts for product lifespan
        # Longer life = better circularity
        utility_factor = product_lifespan_actual / product_lifespan_industry_avg
        utility_factor = min(utility_factor, 5)  # Cap at 5x industry average

        # MCI calculation
        mci = (1 - lfi) * utility_factor

        # Ensure MCI is between 0 and 1
        mci = max(0, min(1, mci))

        return {
            'mci': round(mci, 3),
            'lfi': round(lfi, 3),
            'utility_factor': round(utility_factor, 2),
            'virgin_content_pct': round(virgin_input / total_input * 100, 1) if total_input > 0 else 0,
            'recycled_content_pct': round(recycled_input / total_input * 100, 1) if total_input > 0 else 0,
            'circularity_level': self._classify_mci(mci)
        }

    def _classify_mci(self, mci):
        """Classify circularity level"""
        if mci >= 0.9:
            return 'Highly Circular'
        elif mci >= 0.7:
            return 'Circular'
        elif mci >= 0.5:
            return 'Moderately Circular'
        elif mci >= 0.3:
            return 'Somewhat Circular'
        else:
            return 'Linear'

    def calculate_circularity_rate(self, cycled_materials, total_material_flow):
        """
        Calculate Circularity Rate

        Percentage of materials that are cycled back into the economy
        """

        circularity_rate = (cycled_materials / total_material_flow * 100) if total_material_flow > 0 else 0

        return {
            'circularity_rate_pct': round(circularity_rate, 1),
            'cycled_materials': cycled_materials,
            'total_material_flow': total_material_flow,
            'linear_materials': total_material_flow - cycled_materials
        }

    def calculate_r_strategies_impact(self, product_value, r_strategy,
                                     value_retention_rate):
        """
        Calculate value retention for different R-strategies

        R-strategies (9R framework):
        R0: Refuse, R1: Rethink, R2: Reduce
        R3: Reuse, R4: Repair, R5: Refurbish
        R6: Remanufacture, R7: Repurpose, R8: Recycle, R9: Recover
        """

        # Value retention rates by strategy (typical)
        retention_rates = {
            'refuse': 1.0,       # Prevent need
            'rethink': 1.0,      # Product-as-service
            'reduce': 1.0,       # More efficient use
            'reuse': 0.95,       # Direct reuse
            'repair': 0.90,      # Fix for same use
            'refurbish': 0.85,   # Restore to good condition
            'remanufacture': 0.80,  # Disassemble and rebuild
            'repurpose': 0.60,   # Different application
            'recycle': 0.40,     # Material recovery
            'recover': 0.20      # Energy recovery
        }

        default_retention = retention_rates.get(r_strategy, 0.5)
        actual_retention = value_retention_rate if value_retention_rate else default_retention

        retained_value = product_value * actual_retention

        return {
            'r_strategy': r_strategy,
            'original_value': product_value,
            'retention_rate': actual_retention,
            'retained_value': round(retained_value, 2),
            'value_lost': round(product_value - retained_value, 2)
        }


# Example usage
calculator = CircularityCalculator()

# Example 1: Calculate MCI for a product
mci_result = calculator.calculate_mci(
    virgin_input=8.0,       # kg virgin materials
    recycled_input=2.0,     # kg recycled materials
    product_mass=10.0,      # kg final product
    waste_generated=1.5,    # kg waste (production + end-of-life)
    product_lifespan_actual=8,  # years
    product_lifespan_industry_avg=5  # years
)

print("Material Circularity Indicator (MCI):")
print(f"  MCI Score: {mci_result['mci']}")
print(f"  Circularity Level: {mci_result['circularity_level']}")
print(f"  Virgin Content: {mci_result['virgin_content_pct']}%")
print(f"  Recycled Content: {mci_result['recycled_content_pct']}%")
print(f"  Utility Factor: {mci_result['utility_factor']}")

# Example 2: Circularity rate
circ_rate = calculator.calculate_circularity_rate(
    cycled_materials=3000,      # tonnes recycled/reused
    total_material_flow=10000   # tonnes total materials used
)

print(f"\nCircularity Rate: {circ_rate['circularity_rate_pct']}%")

# Example 3: R-strategy value retention
repair_value = calculator.calculate_r_strategies_impact(
    product_value=500,
    r_strategy='repair',
    value_retention_rate=0.90
)

print(f"\nRepair Strategy:")
print(f"  Original Value: ${repair_value['original_value']}")
print(f"  Retained Value: ${repair_value['retained_value']}")
print(f"  Value Retention Rate: {repair_value['retention_rate']*100}%")

Design for Circularity

Design Principles

class CircularDesignAssessment:
    """Assess product design for circularity"""

    def __init__(self, product_name):
        self.product_name = product_name
        self.assessment_criteria = {}

    def assess_design_for_disassembly(self, design_data):
        """
        Assess how easy product is to disassemble

        design_data: dict with design characteristics
        """
        score = 0
        max_score = 100
        feedback = []

        # Fastener type (0-20 points)
        fasteners = design_data.get('fasteners', 'permanent')
        if fasteners == 'snap_fit_reversible':
            score += 20
            feedback.append("✓ Reversible snap-fit fasteners")
        elif fasteners == 'screws_standard':
            score += 15
            feedback.append("✓ Standard screws used")
        elif fasteners == 'screws_proprietary':
            score += 10
            feedback.append("⚠ Proprietary fasteners (use standard)")
        else:
            score += 0
            feedback.append("✗ Permanent fasteners (welding, glue)")

        # Material variety (0-20 points)
        num_materials = design_data.get('num_material_types', 5)
        if num_materials <= 2:
            score += 20
            feedback.append("✓ Limited material types (≤2)")
        elif num_materials <= 4:
            score += 15
            feedback.append("⚠ Moderate material variety (3-4 types)")
        else:
            score += 5
            feedback.append("✗ High material variety (simplify)")

        # Material compatibility (0-20 points)
        incompatible_materials = design_data.get('incompatible_material_combos', 0)
        if incompatible_materials == 0:
            score += 20
            feedback.append("✓ No incompatible material combinations")
        elif incompatible_materials <= 2:
            score += 10
            feedback.append("⚠ Some incompatible combinations")
        else:
            score += 0
            feedback.append("✗ Many incompatible combinations")

        # Component labeling (0-15 points)
        if design_data.get('components_labeled', False):
            score += 15
            feedback.append("✓ Components labeled for recycling")
        else:
            score += 0
            feedback.append("✗ Components not labeled")

        # Modular design (0-25 points)
        modularity = design_data.get('modularity_level', 'none')
        if modularity == 'high':
            score += 25
            feedback.append("✓ Highly modular design")
        elif modularity == 'medium':
            score += 15
            feedback.append("⚠ Partially modular")
        else:
            score += 0
            feedback.append("✗ Not modular")

        return {
            'score': score,
            'max_score': max_score,
            'percentage': round(score / max_score * 100, 1),
            'rating': self._get_rating(score / max_score),
            'feedback': feedback
        }

    def assess_material_selection(self, material_data):
        """Assess material choices for circularity"""
        score = 0
        max_score = 100
        feedback = []

        # Recycled content (0-30 points)
        recycled_pct = material_data.get('recycled_content_pct', 0)
        if recycled_pct >= 50:
            score += 30
            feedback.append(f"✓ High recycled content ({recycled_pct}%)")
        elif recycled_pct >= 25:
            score += 20
            feedback.append(f"⚠ Moderate recycled content ({recycled_pct}%)")
        elif recycled_pct > 0:
            score += 10
            feedback.append(f"⚠ Low recycled content ({recycled_pct}%)")
        else:
            score += 0
            feedback.append("✗ No recycled content")

        # Recyclability (0-30 points)
        recyclability = material_data.get('recyclability', 'difficult')
        if recyclability == 'easily_recyclable':
            score += 30
            feedback.append("✓ Materials easily recyclable")
        elif recyclability == 'recyclable_with_effort':
            score += 20
            feedback.append("⚠ Materials recyclable with effort")
        else:
            score += 5
            feedback.append("✗ Materials difficult to recycle")

        # Renewable materials (0-20 points)
        renewable_pct = material_data.get('renewable_content_pct', 0)
        if renewable_pct >= 50:
            score += 20
            feedback.append(f"✓ High renewable content ({renewable_pct}%)")
        elif renewable_pct >= 25:
            score += 12
            feedback.append(f"⚠ Moderate renewable content ({renewable_pct}%)")
        elif renewable_pct > 0:
            score += 5
            feedback.append(f"⚠ Low renewable content ({renewable_pct}%)")

        # Hazardous substances (0-20 points)
        if material_data.get('hazardous_free', True):
            score += 20
            feedback.append("✓ No hazardous substances")
        else:
            score += 0
            feedback.append("✗ Contains hazardous substances")
            if material_data.get('hazardous_list'):
                feedback.append(f"  Substances: {', '.join(material_data['hazardous_list'])}")

        return {
            'score': score,
            'max_score': max_score,
            'percentage': round(score / max_score * 100, 1),
            'rating': self._get_rating(score / max_score),
            'feedback': feedback
        }

    def assess_durability_repairability(self, durability_data):
        """Assess product durability and ease of repair"""
        score = 0
        max_score = 100
        feedback = []

        # Expected lifespan (0-25 points)
        expected_years = durability_data.get('expected_lifespan_years', 0)
        industry_avg = durability_data.get('industry_avg_lifespan_years', 5)

        if expected_years >= industry_avg * 1.5:
            score += 25
            feedback.append(f"✓ Long lifespan ({expected_years} yrs, 1.5x industry avg)")
        elif expected_years >= industry_avg:
            score += 18
            feedback.append(f"✓ Good lifespan ({expected_years} yrs, meets industry avg)")
        else:
            score += 10
            feedback.append(f"⚠ Below average lifespan ({expected_years} yrs)")

        # Repairability (0-25 points)
        repair_score = durability_data.get('repair_score_out_of_10', 5)
        score += repair_score * 2.5
        if repair_score >= 8:
            feedback.append(f"✓ Highly repairable (score: {repair_score}/10)")
        elif repair_score >= 5:
            feedback.append(f"⚠ Moderately repairable (score: {repair_score}/10)")
        else:
            feedback.append(f"✗ Difficult to repair (score: {repair_score}/10)")

        # Spare parts availability (0-25 points)
        if durability_data.get('spare_parts_available', False):
            score += 25
            commitment_years = durability_data.get('spare_parts_commitment_years', 0)
            feedback.append(f"✓ Spare parts available ({commitment_years} years)")
        else:
            score += 0
            feedback.append("✗ Spare parts not available")

        # Repair documentation (0-25 points)
        if durability_data.get('repair_manual_available', False):
            score += 15
            feedback.append("✓ Repair manual available")
        else:
            feedback.append("✗ No repair manual")

        if durability_data.get('repair_videos_available', False):
            score += 10
            feedback.append("✓ Repair videos available")

        return {
            'score': score,
            'max_score': max_score,
            'percentage': round(score / max_score * 100, 1),
            'rating': self._get_rating(score / max_score),
            'feedback': feedback
        }

    def _get_rating(self, score_ratio):
        """Convert score to rating"""
        if score_ratio >= 0.9:
            return 'Excellent'
        elif score_ratio >= 0.75:
            return 'Good'
        elif score_ratio >= 0.60:
            return 'Fair'
        elif score_ratio >= 0.40:
            return 'Poor'
        else:
            return 'Very Poor'

    def generate_comprehensive_assessment(self, design_data, material_data,
                                          durability_data):
        """Generate full circularity assessment"""

        disassembly = self.assess_design_for_disassembly(design_data)
        materials = self.assess_material_selection(material_data)
        durability = self.assess_durability_repairability(durability_data)

        # Overall score (weighted average)
        overall_score = (
            disassembly['percentage'] * 0.35 +
            materials['percentage'] * 0.35 +
            durability['percentage'] * 0.30
        )

        return {
            'product': self.product_name,
            'overall_score': round(overall_score, 1),
            'overall_rating': self._get_rating(overall_score / 100),
            'design_for_disassembly': disassembly,
            'material_selection': materials,
            'durability_repairability': durability
        }


# Example assessment
product = CircularDesignAssessment('Acme Widget Pro')

design_data = {
    'fasteners': 'screws_standard',
    'num_material_types': 3,
    'incompatible_material_combos': 0,
    'components_labeled': True,
    'modularity_level': 'high'
}

material_data = {
    'recycled_content_pct': 60,
    'recyclability': 'easily_recyclable',
    'renewable_content_pct': 20,
    'hazardous_free': True
}

durability_data = {
    'expected_lifespan_years': 10,
    'industry_avg_lifespan_years': 6,
    'repair_score_out_of_10': 8,
    'spare_parts_available': True,
    'spare_parts_commitment_years': 10,
    'repair_manual_available': True,
    'repair_videos_available': True
}

assessment = product.generate_comprehensive_assessment(
    design_data, material_data, durability_data
)

print(f"Circular Design Assessment: {assessment['product']}")
print(f"Overall Score: {assessment['overall_score']}/100 ({assessment['overall_rating']})")
print(f"\nDesign for Disassembly: {assessment['design_for_disassembly']['percentage']}%")
print(f"Material Selection: {assessment['material_selection']['percentage']}%")
print(f"Durability & Repairability: {assessment['durability_repairability']['percentage']}%")

Reverse Logistics Optimization

Product Take-Back Program

class ReverseLogisticsOptimizer:
    """Optimize reverse logistics and product take-back operations"""

    def __init__(self):
        self.collection_sites = []
        self.processing_facilities = []

    def calculate_collection_coverage(self, collection_sites, customer_locations,
                                     max_distance_km=50):
        """
        Calculate coverage of collection network

        collection_sites: list of dicts with lat/lon
        customer_locations: list of dicts with lat/lon
        """

        def haversine_distance(lat1, lon1, lat2, lon2):
            """Calculate distance between two points on Earth"""
            from math import radians, sin, cos, sqrt, atan2

            R = 6371  # Earth radius in km

            lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
            dlat = lat2 - lat1
            dlon = lon2 - lon1

            a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
            c = 2 * atan2(sqrt(a), sqrt(1-a))

            return R * c

        covered_customers = 0

        for customer in customer_locations:
            cust_lat = customer['lat']
            cust_lon = customer['lon']

            # Check if any collection site is within max distance
            for site in collection_sites:
                distance = haversine_distance(
                    cust_lat, cust_lon,
                    site['lat'], site['lon']
                )

                if distance <= max_distance_km:
                    covered_customers += 1
                    break  # Customer is covered

        coverage_pct = (covered_customers / len(customer_locations) * 100) if customer_locations else 0

        return {
            'total_customers': len(customer_locations),
            'covered_customers': covered_customers,
            'coverage_percentage': round(coverage_pct, 1),
            'uncovered_customers': len(customer_locations) - covered_customers,
            'max_distance_km': max_distance_km
        }

    def calculate_return_rate_economics(self, product_data):
        """
        Calculate economics of product returns and refurbishment

        product_data: dict with product and return info
        """

        original_price = product_data['original_price']
        units_sold = product_data['units_sold']
        return_rate = product_data['return_rate']  # fraction (e.g., 0.15 for 15%)

        # Returns
        units_returned = units_sold * return_rate

        # Collection costs
        collection_cost_per_unit = product_data.get('collection_cost_per_unit', 5)
        collection_cost_total = units_returned * collection_cost_per_unit

        # Sorting and grading
        sorting_cost_per_unit = product_data.get('sorting_cost_per_unit', 2)
        sorting_cost_total = units_returned * sorting_cost_per_unit

        # Categorize returns
        grade_a_rate = product_data.get('grade_a_rate', 0.30)  # Resell as-is
        grade_b_rate = product_data.get('grade_b_rate', 0.40)  # Refurbish
        grade_c_rate = product_data.get('grade_c_rate', 0.20)  # Parts recovery
        grade_d_rate = product_data.get('grade_d_rate', 0.10)  # Recycle/dispose

        units_grade_a = units_returned * grade_a_rate
        units_grade_b = units_returned * grade_b_rate
        units_grade_c = units_returned * grade_c_rate
        units_grade_d = units_returned * grade_d_rate

        # Grade A: Resell as-is
        resale_price_a = original_price * 0.70  # 70% of original
        cleaning_cost_a = 3
        revenue_a = units_grade_a * (resale_price_a - cleaning_cost_a)

        # Grade B: Refurbish
        refurb_cost_b = original_price * 0.20  # 20% of original to refurbish
        resale_price_b = original_price * 0.60  # 60% of original
        revenue_b = units_grade_b * (resale_price_b - refurb_cost_b)

        # Grade C: Parts recovery
        parts_value_c = original_price * 0.30  # 30% parts value
        disassembly_cost_c = original_price * 0.10
        revenue_c = units_grade_c * (parts_value_c - disassembly_cost_c)

        # Grade D: Material recycling
        material_value_d = original_price * 0.05  # 5% material value
        processing_cost_d = original_price * 0.03
        revenue_d = units_grade_d * (material_value_d - processing_cost_d)

        # Total
        total_revenue = revenue_a + revenue_b + revenue_c + revenue_d
        total_cost = collection_cost_total + sorting_cost_total
        net_value = total_revenue - total_cost

        return {
            'units_returned': round(units_returned, 0),
            'return_rate_pct': round(return_rate * 100, 1),
            'distribution': {
                'grade_a_resell': round(units_grade_a, 0),
                'grade_b_refurbish': round(units_grade_b, 0),
                'grade_c_parts': round(units_grade_c, 0),
                'grade_d_recycle': round(units_grade_d, 0)
            },
            'revenue_by_grade': {
                'grade_a': round(revenue_a, 2),
                'grade_b': round(revenue_b, 2),
                'grade_c': round(revenue_c, 2),
                'grade_d': round(revenue_d, 2),
                'total': round(total_revenue, 2)
            },
            'costs': {
                'collection': round(collection_cost_total, 2),
                'sorting': round(sorting_cost_total, 2),
                'total': round(total_cost, 2)
            },
            'net_value': round(net_value, 2),
            'value_per_returned_unit': round(net_value / units_returned, 2) if units_returned > 0 else 0
        }

    def optimize_refurbishment_capacity(self, demand_data):
        """
        Optimize refurbishment facility capacity

        demand_data: dict with demand forecasts and cost info
        """

        # Demand parameters
        avg_monthly_returns = demand_data['avg_monthly_returns']
        returns_std_dev = demand_data['returns_std_dev']
        refurb_rate = demand_data.get('refurb_rate', 0.40)  # 40% need refurbishment

        refurb_demand_avg = avg_monthly_returns * refurb_rate
        refurb_demand_std = returns_std_dev * refurb_rate

        # Capacity options
        capacity_options = []

        for capacity_level in [0.8, 1.0, 1.2, 1.5, 2.0]:
            capacity = refurb_demand_avg * capacity_level

            # Fixed costs (facility, equipment, base staffing)
            fixed_cost_monthly = demand_data.get('fixed_cost_base', 50000) * capacity_level

            # Variable costs (per unit processed)
            variable_cost_per_unit = demand_data.get('variable_cost_per_unit', 20)

            # Calculate expected utilization
            # Assumes normal distribution of demand
            from scipy import stats
            prob_exceed = 1 - stats.norm.cdf(capacity, refurb_demand_avg, refurb_demand_std)
            utilization = min(1.0, refurb_demand_avg / capacity)

            # Units processed
            units_processed = min(capacity, refurb_demand_avg)

            # Backlog cost (if demand exceeds capacity)
            backlog_units = max(0, refurb_demand_avg - capacity)
            backlog_cost_per_unit = demand_data.get('backlog_cost_per_unit', 50)
            backlog_cost = backlog_units * backlog_cost_per_unit

            # Total cost
            total_cost = fixed_cost_monthly + (units_processed * variable_cost_per_unit) + backlog_cost
            cost_per_unit = total_cost / units_processed if units_processed > 0 else float('inf')

            capacity_options.append({
                'capacity_level': capacity_level,
                'capacity_units': round(capacity, 0),
                'expected_utilization': round(utilization * 100, 1),
                'units_processed': round(units_processed, 0),
                'backlog_units': round(backlog_units, 0),
                'fixed_cost': round(fixed_cost_monthly, 2),
                'variable_cost': round(units_processed * variable_cost_per_unit, 2),
                'backlog_cost': round(backlog_cost, 2),
                'total_cost': round(total_cost, 2),
                'cost_per_unit': round(cost_per_unit, 2)
            })

        # Find optimal (lowest cost per unit)
        optimal = min(capacity_options, key=lambda x: x['cost_per_unit'])

        return {
            'capacity_options': pd.DataFrame(capacity_options),
            'optimal_capacity': optimal,
            'recommendation': f"Build capacity for {optimal['capacity_level']}x average demand"
        }


# Example usage
rl_optimizer = ReverseLogisticsOptimizer()

# Example 1: Calculate return economics
product_data = {
    'original_price': 500,
    'units_sold': 10000,
    'return_rate': 0.12,  # 12% return rate
    'collection_cost_per_unit': 10,
    'sorting_cost_per_unit': 3,
    'grade_a_rate': 0.25,  # 25% can resell as-is
    'grade_b_rate': 0.45,  # 45% need refurbishment
    'grade_c_rate': 0.20,  # 20% for parts
    'grade_d_rate': 0.10   # 10% recycle
}

economics = rl_optimizer.calculate_return_rate_economics(product_data)

print("Return Economics:")
print(f"  Units Returned: {economics['units_returned']}")
print(f"  Total Revenue: ${economics['revenue_by_grade']['total']:,.2f}")
print(f"  Total Costs: ${economics['costs']['total']:,.2f}")
print(f"  Net Value: ${economics['net_value']:,.2f}")
print(f"  Value per Unit: ${economics['value_per_returned_unit']:.2f}")

# Example 2: Optimize refurbishment capacity
demand_data = {
    'avg_monthly_returns': 500,
    'returns_std_dev': 100,
    'refurb_rate': 0.45,
    'fixed_cost_base': 40000,
    'variable_cost_per_unit': 25,
    'backlog_cost_per_unit': 60
}

capacity_analysis = rl_optimizer.optimize_refurbishment_capacity(demand_data)

print("\n\nRefurbishment Capacity Options:")
print(capacity_analysis['capacity_options'][['capacity_level', 'capacity_units', 'expected_utilization', 'cost_per_unit']])
print(f"\n{capacity_analysis['recommendation']}")

Tools & Libraries

Python Libraries

Circularity Analysis:

  • pandas: Data manipulation
  • numpy: Numerical computations
  • scipy: Statistical analysis

Life Cycle Assessment:

  • brightway2: LCA framework
  • openLCA: Open-source LCA
  • lca_algebraic: Algebraic LCA

Optimization:

  • pulp: Linear programming
  • scipy.optimize: Optimization algorithms
  • pyomo: Optimization modeling

Visualization:

  • matplotlib, seaborn: Charts and plots
  • plotly: Interactive visualizations
  • sankey: Material flow diagrams

Commercial Software

Circular Economy Platforms:

  • Circularity Metrics: Ellen MacArthur Foundation tool
  • Circularise: Supply chain traceability
  • Rheaply: Asset management and reuse
  • Reconomy: Resource recovery platform
  • Excess Materials Exchange: Material marketplace

Product Design:

  • Autodesk Fusion 360: Design for circularity
  • Solidworks Sustainability: Environmental impact analysis
  • SimaPro: LCA software
  • GaBi: Life cycle assessment

Reverse Logistics:

  • Optoro: Returns optimization
  • ReverseLogix: Returns management
  • Inmar: Product returns and recycling
  • B-Stock: Liquidation marketplace

Material Passports:

  • Madaster: Material passport platform
  • Concular: Building material marketplace
  • Opalis: Circular material management

Common Challenges & Solutions

Challenge: Economic Viability

Problem:

  • Circular models may have higher upfront costs
  • Uncertain ROI on take-back programs
  • Competition with cheap linear alternatives

Solutions:

  • Start with high-value products (electronics, machinery)
  • Design for multiple lifecycles from start
  • Extended Producer Responsibility (EPR) can offset costs
  • Market refurbished products to value-conscious segments
  • Partner with specialists for reverse logistics
  • Calculate full lifecycle costs (including disposal)

Challenge: Consumer Behavior

Problem:

  • Customers prefer new over refurbished
  • Low participation in take-back programs
  • Resistance to product-as-service models

Solutions:

  • Offer incentives (trade-in credit, discounts)
  • Certification and warranties for refurbished products
  • Educate on quality and environmental benefits
  • Make returns convenient (free shipping, drop-off points)
  • Build circular features into brand identity
  • Start with B2B where circularity is valued

Challenge: Product Design Legacy

Problem:

  • Existing products not designed for circularity
  • Long product development cycles
  • Cost pressures favor cheap, disposable designs

Solutions:

  • Implement design guidelines for new products
  • Retrofit take-back for current products
  • Pilot circular design with new product lines
  • Calculate business case including end-of-life value
  • Regulatory pressure (right-to-repair, EPR)
  • Executive commitment to sustainability

Challenge: Reverse Logistics Complexity

Problem:

  • Collection network expensive to build
  • Variable product conditions
  • Unpredictable return volumes
  • Need for inspection, sorting, testing

Solutions:

  • Partner with existing logistics providers
  • Use retail locations as collection points
  • Implement grading standards and automation
  • Build data analytics for return prediction
  • Start in concentrated geographies
  • Third-party refurbishment specialists

Challenge: Material Traceability

Problem:

  • Unknown material composition of products
  • Mixed materials difficult to separate
  • Lack of information on product history

Solutions:

  • Implement material passports (digital records)
  • Label components with material information
  • Use blockchain for supply chain traceability
  • Design for easy material identification
  • Material libraries and databases
  • Industry standardization efforts

Challenge: Scale and Infrastructure

Problem:

  • Lack of recycling/refurbishment infrastructure
  • Limited markets for secondary materials
  • Technology for separation not available

Solutions:

  • Collaborate with industry players
  • Government support for circular infrastructure
  • Design for existing recycling systems
  • Build material marketplaces
  • Invest in separation technologies
  • Regional circular economy hubs

Output Format

Circular Economy Assessment Report

Executive Summary:

  • Current circularity rate
  • Material flows and waste streams
  • Circular economy opportunities identified
  • Recommended initiatives and ROI

Material Flow Analysis:

MaterialInput (tonnes)Virgin (%)Recycled (%)Output (tonnes)Waste (%)Circulated (%)
Steel1,00065%35%95010%40%
Plastic50080%20%48015%25%
Aluminum30040%60%2905%65%
Total1,80065%35%1,72011%42%

Product Circularity Assessment:

ProductMCI ScoreRecycled ContentLifespan vs AvgRepairabilityPriority
Product A0.7245%1.5x8/10High
Product B0.4520%1.0x5/10Medium
Product C0.2810%0.8x3/10Redesign

Circular Initiatives:

InitiativeStrategyInvestmentAnnual SavingsPaybackImpact (tCO2e)Priority
Product Take-BackRecovery$500K$180K2.8 yrs-1,200High
Design for DisassemblyDesign$200K$90K2.2 yrs-400High
Remanufacturing ProgramExtend$800K$350K2.3 yrs-2,000High
Material SubstitutionInputs$300K$120K2.5 yrs-600Medium

Financial Impact:

MetricCurrentTargetImprovement
Circularity Rate35%60%+25 pts
Waste to Landfill200 tonnes50 tonnes-75%
Material Cost$2.5M$2.0M-$500K
Revenue from Returns$100K$650K+$550K
Net Benefit$1.05M/year

Questions to Ask

If you need more context:

  1. What products or materials are in scope?
  2. What's the current end-of-life fate of products? (landfill, recycle, reuse)
  3. Are products designed for disassembly and repair?
  4. What's the return/take-back rate?
  5. Are there regulatory drivers? (EPR, right-to-repair, recycled content mandates)
  6. What circular business models are being considered? (PaaS, refurbishment, recycling)
  7. Is there infrastructure for collection and processing?
  8. What are material costs and availability of recycled alternatives?
  9. What's the customer attitude toward refurbished products?
  10. Are there existing circular economy partnerships or programs?

Related Skills

  • carbon-footprint-tracking: For emissions impact of circular strategies
  • sustainable-sourcing: For procurement of recycled and renewable materials
  • compliance-management: For EPR and circular economy regulations
  • network-design: For designing reverse logistics networks
  • route-optimization: For optimizing collection logistics
  • warehouse-design: For refurbishment and sorting facilities
  • demand-forecasting: For predicting product returns
  • inventory-optimization: For managing refurbished product inventory
  • quality-management: For grading and testing returned products

Clinical Trial Logistics

You are an expert in clinical trial supply chain management and logistics. Your goal is to ensure reliable, compliant supply of investigational medicinal products (IMPs) to clinical trial sites while maintaining product integrity, regulatory compliance, and study blinding.

Initial Assessment

Before optimizing clinical trial logistics, understand:

  1. Trial Characteristics

    • Trial phase? (Phase I, II, III, IV)
    • Number of sites and countries?
    • Patient enrollment targets and timeline?
    • Blinding requirements? (open-label, single-blind, double-blind)
    • Randomization complexity? (stratification factors)
  2. Product Requirements

    • Drug form? (tablets, injectables, biologics)
    • Storage conditions? (room temp, refrigerated, frozen)
    • Stability and shelf life?
    • Comparator/placebo requirements?
    • Packaging configuration?
  3. Supply Chain Infrastructure

    • IRT/IVRS/IWRS system in place?
    • Depot locations? (global, regional)
    • Direct-to-site vs. depot model?
    • Cold chain capabilities?
    • Backup supply strategy?
  4. Compliance & Regulations

    • GCP (Good Clinical Practice) requirements?
    • Country-specific regulations?
    • Import/export licenses needed?
    • Temperature excursion protocols?
    • Audit readiness?

Clinical Trial Supply Chain Framework

Trial Supply Models

1. Direct-to-Site (DTS)

  • Ship directly from manufacturing to sites
  • Pros: Reduced handling, faster delivery
  • Cons: No buffer stock, complex global logistics
  • Best for: Small trials, stable products

2. Depot-Based Distribution

  • Regional depots hold inventory
  • Ship to sites from nearest depot
  • Pros: Faster resupply, buffer stock, consolidation
  • Cons: Additional handling, storage costs
  • Best for: Large global trials

3. Hybrid Model

  • Depot for some regions, DTS for others
  • Optimize based on site density and logistics
  • Best for: Multi-regional trials with varied infrastructure

IRT/IVRS/IWRS System Design

Interactive Response Technology (IRT):

  • Randomization engine
  • Supply allocation and tracking
  • Temperature monitoring integration
  • Drug accountability
  • Resupply triggers

Core Functions:

from enum import Enum
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import List, Optional, Dict
import random

class TreatmentArm(Enum):
    INVESTIGATIONAL = "investigational"
    COMPARATOR = "comparator"
    PLACEBO = "placebo"

class PatientStatus(Enum):
    SCREENED = "screened"
    RANDOMIZED = "randomized"
    ON_TREATMENT = "on_treatment"
    COMPLETED = "completed"
    DISCONTINUED = "discontinued"

@dataclass
class StratificationFactor:
    """Stratification criteria for randomization"""
    factor_name: str
    value: str

@dataclass
class Patient:
    """Clinical trial patient"""
    patient_id: str
    site_id: str
    screening_date: datetime
    status: PatientStatus
    stratification_factors: List[StratificationFactor] = None
    treatment_arm: Optional[TreatmentArm] = None
    randomization_date: Optional[datetime] = None
    allocated_kits: List[str] = None

@dataclass
class DrugKit:
    """IMP drug kit"""
    kit_number: str
    treatment_arm: TreatmentArm
    lot_number: str
    expiry_date: datetime
    site_id: str
    status: str  # available, allocated, dispensed, returned, destroyed
    patient_id: Optional[str] = None
    dispensed_date: Optional[datetime] = None

class IRTSystem:
    """
    Interactive Response Technology for clinical trials
    """

    def __init__(self, trial_id, randomization_ratio, blinded=True):
        self.trial_id = trial_id
        self.randomization_ratio = randomization_ratio  # e.g., {'investigational': 2, 'comparator': 1}
        self.blinded = blinded
        self.patients = {}
        self.drug_kits = {}
        self.randomization_list = []
        self.site_inventory = {}

    def generate_randomization_list(self, total_patients, block_size=6,
                                    stratification_factors=None):
        """
        Generate randomization list with blocking and stratification

        Parameters:
        - total_patients: Total randomization codes to generate
        - block_size: Block size for randomization
        - stratification_factors: List of stratification combinations
        """

        if stratification_factors is None:
            stratification_factors = [None]  # No stratification

        randomization_list = []
        randomization_number = 1

        for strata in stratification_factors:
            num_patients_per_strata = total_patients // len(stratification_factors)

            # Generate treatment sequence based on ratio
            sequence = []
            for treatment, count in self.randomization_ratio.items():
                sequence.extend([TreatmentArm[treatment.upper()]] * count)

            # Generate blocks
            num_blocks = (num_patients_per_strata // block_size) + 1

            for block in range(num_blocks):
                # Shuffle within block
                random.shuffle(sequence)

                for treatment in sequence:
                    if len(randomization_list) >= total_patients:
                        break

                    randomization_list.append({
                        'randomization_number': f"RND-{randomization_number:05d}",
                        'treatment_arm': treatment,
                        'stratification': strata,
                        'block': block + 1
                    })

                    randomization_number += 1

        self.randomization_list = randomization_list[:total_patients]

        return self.randomization_list

    def randomize_patient(self, patient_id, site_id, stratification_values=None):
        """
        Randomize patient and allocate treatment

        Parameters:
        - patient_id: Patient identifier
        - site_id: Study site
        - stratification_values: Dict of stratification factor values
        """

        if patient_id in self.patients:
            raise ValueError(f"Patient {patient_id} already randomized")

        # Find next available randomization code for stratification
        # In real system, this would be from pre-generated randomization list
        available_codes = [
            code for code in self.randomization_list
            if not any(p['randomization_code']['randomization_number'] == code['randomization_number']
                      for p in self.patients.values() if 'randomization_code' in p)
        ]

        if not available_codes:
            raise ValueError("No randomization codes available")

        # Assign next code
        randomization_code = available_codes[0]

        # Create patient record
        patient = {
            'patient_id': patient_id,
            'site_id': site_id,
            'randomization_date': datetime.now(),
            'status': PatientStatus.RANDOMIZED,
            'randomization_code': randomization_code,
            'treatment_arm': randomization_code['treatment_arm'],
            'stratification_values': stratification_values,
            'allocated_kits': []
        }

        self.patients[patient_id] = patient

        # Allocate drug kit
        kit = self._allocate_kit(patient_id, site_id, randomization_code['treatment_arm'])

        if kit:
            patient['allocated_kits'].append(kit['kit_number'])

        return {
            'patient_id': patient_id,
            'randomization_number': randomization_code['randomization_number'],
            'kit_number': kit['kit_number'] if kit else None,
            'dispensing_instructions': self._get_dispensing_instructions()
        }

    def _allocate_kit(self, patient_id, site_id, treatment_arm):
        """
        Allocate drug kit to patient from site inventory
        """

        # Find available kits at site for treatment arm
        site_kits = [
            kit for kit_num, kit in self.drug_kits.items()
            if kit['site_id'] == site_id
            and kit['treatment_arm'] == treatment_arm
            and kit['status'] == 'available'
            and kit['expiry_date'] > datetime.now()
        ]

        if not site_kits:
            # Trigger resupply
            self._trigger_resupply(site_id, treatment_arm)
            return None

        # Allocate kit with earliest expiry (FEFO)
        site_kits.sort(key=lambda x: x['expiry_date'])
        kit = site_kits[0]

        kit['status'] = 'allocated'
        kit['patient_id'] = patient_id
        kit['allocated_date'] = datetime.now()

        return kit

    def dispense_kit(self, kit_number, patient_id, dispensed_by):
        """
        Record kit dispensing to patient
        """

        if kit_number not in self.drug_kits:
            raise ValueError(f"Kit {kit_number} not found")

        kit = self.drug_kits[kit_number]

        if kit['status'] != 'allocated':
            raise ValueError(f"Kit {kit_number} is not allocated (status: {kit['status']})")

        if kit['patient_id'] != patient_id:
            raise ValueError(f"Kit {kit_number} is allocated to different patient")

        kit['status'] = 'dispensed'
        kit['dispensed_date'] = datetime.now()
        kit['dispensed_by'] = dispensed_by

        # Update patient status
        if patient_id in self.patients:
            self.patients[patient_id]['status'] = PatientStatus.ON_TREATMENT

        return {
            'kit_number': kit_number,
            'patient_id': patient_id,
            'dispensed_date': kit['dispensed_date'],
            'accountability_required': True
        }

    def return_kit(self, kit_number, return_reason, returned_by):
        """
        Record kit return (unused or partially used)
        """

        if kit_number not in self.drug_kits:
            raise ValueError(f"Kit {kit_number} not found")

        kit = self.drug_kits[kit_number]

        kit['status'] = 'returned'
        kit['return_date'] = datetime.now()
        kit['return_reason'] = return_reason
        kit['returned_by'] = returned_by

        return kit

    def check_site_inventory(self, site_id):
        """
        Check site inventory levels and trigger resupply if needed
        """

        site_kits = [
            kit for kit in self.drug_kits.values()
            if kit['site_id'] == site_id and kit['status'] == 'available'
        ]

        # Group by treatment arm
        inventory_by_arm = {}
        for arm in TreatmentArm:
            arm_kits = [k for k in site_kits if k['treatment_arm'] == arm]
            inventory_by_arm[arm.value] = {
                'available_kits': len(arm_kits),
                'expiring_soon': len([k for k in arm_kits if k['expiry_date'] < datetime.now() + timedelta(days=90)])
            }

        return inventory_by_arm

    def _trigger_resupply(self, site_id, treatment_arm):
        """
        Trigger site resupply when inventory low
        """

        resupply_request = {
            'site_id': site_id,
            'treatment_arm': treatment_arm,
            'request_date': datetime.now(),
            'priority': 'high',
            'requested_quantity': 20  # Standard resupply quantity
        }

        # In real system, this would integrate with depot management
        print(f"RESUPPLY TRIGGERED: Site {site_id} needs {treatment_arm.value} kits")

        return resupply_request

    def _get_dispensing_instructions(self):
        """
        Generate dispensing instructions for site staff
        """

        if self.blinded:
            return "Dispense assigned kit to patient. DO NOT OPEN OR INSPECT CONTENTS."
        else:
            return "Dispense assigned kit to patient. Verify drug name and strength."

# Example usage
irt = IRTSystem(
    trial_id='TRIAL-2024-001',
    randomization_ratio={'investigational': 2, 'comparator': 1, 'placebo': 1},
    blinded=True
)

# Generate randomization list
random.seed(42)
rand_list = irt.generate_randomization_list(
    total_patients=100,
    block_size=8
)

print(f"Generated {len(rand_list)} randomization codes")

# Add drug kits to site inventory
for i in range(20):
    kit_num = f"KIT-001-{1000+i}"
    arm = random.choice(list(TreatmentArm))

    irt.drug_kits[kit_num] = {
        'kit_number': kit_num,
        'treatment_arm': arm,
        'lot_number': 'LOT-2024-A',
        'expiry_date': datetime.now() + timedelta(days=730),
        'site_id': 'SITE-001',
        'status': 'available',
        'patient_id': None
    }

# Randomize patient
randomization = irt.randomize_patient(
    patient_id='PT-001-001',
    site_id='SITE-001',
    stratification_values={'age_group': '>=65', 'disease_severity': 'moderate'}
)

print(f"\nPatient randomized:")
print(f"  Randomization Number: {randomization['randomization_number']}")
print(f"  Kit Number: {randomization['kit_number']}")

# Dispense kit
dispense = irt.dispense_kit(
    kit_number=randomization['kit_number'],
    patient_id='PT-001-001',
    dispensed_by='Investigator Dr. Smith'
)

print(f"\nKit dispensed: {dispense['kit_number']} on {dispense['dispensed_date']}")

# Check site inventory
inventory = irt.check_site_inventory('SITE-001')
print(f"\nSite inventory:")
for arm, counts in inventory.items():
    print(f"  {arm}: {counts['available_kits']} kits available")

Drug Accountability & Reconciliation

Accountability Requirements

GCP Requirements:

  • Receipt records
  • Dispensing records
  • Return records
  • Destruction records
  • Complete audit trail
import pandas as pd
from datetime import datetime

class DrugAccountabilitySystem:
    """
    Manage drug accountability and reconciliation for clinical trials
    """

    def __init__(self, site_id, trial_id):
        self.site_id = site_id
        self.trial_id = trial_id
        self.transactions = []
        self.inventory = {}

    def receive_shipment(self, shipment_id, kits, received_by,
                        condition, temperature_log=None):
        """
        Record receipt of IMP shipment at site
        """

        receipt_transaction = {
            'transaction_type': 'receipt',
            'transaction_date': datetime.now(),
            'shipment_id': shipment_id,
            'received_by': received_by,
            'condition': condition,
            'temperature_compliant': self._verify_temperature(temperature_log),
            'kits': kits
        }

        self.transactions.append(receipt_transaction)

        # Add to inventory
        for kit in kits:
            self.inventory[kit['kit_number']] = {
                'kit_number': kit['kit_number'],
                'lot_number': kit['lot_number'],
                'expiry_date': kit['expiry_date'],
                'status': 'available',
                'received_date': datetime.now(),
                'patient_id': None
            }

        return receipt_transaction

    def dispense_to_patient(self, kit_number, patient_id, visit_number,
                           dispensed_by, dispense_date=None):
        """
        Record kit dispensing to patient
        """

        if kit_number not in self.inventory:
            raise ValueError(f"Kit {kit_number} not in inventory")

        if self.inventory[kit_number]['status'] != 'available':
            raise ValueError(f"Kit {kit_number} is not available")

        dispense_transaction = {
            'transaction_type': 'dispensed',
            'transaction_date': dispense_date or datetime.now(),
            'kit_number': kit_number,
            'patient_id': patient_id,
            'visit_number': visit_number,
            'dispensed_by': dispensed_by
        }

        self.transactions.append(dispense_transaction)

        # Update inventory
        self.inventory[kit_number]['status'] = 'dispensed'
        self.inventory[kit_number]['patient_id'] = patient_id
        self.inventory[kit_number]['dispensed_date'] = dispense_date or datetime.now()

        return dispense_transaction

    def return_from_patient(self, kit_number, patient_id, return_date,
                           units_returned, units_used, returned_by):
        """
        Record kit return from patient (compliance check)
        """

        if kit_number not in self.inventory:
            raise ValueError(f"Kit {kit_number} not in inventory")

        return_transaction = {
            'transaction_type': 'returned_from_patient',
            'transaction_date': return_date or datetime.now(),
            'kit_number': kit_number,
            'patient_id': patient_id,
            'units_returned': units_returned,
            'units_used': units_used,
            'compliance_pct': (units_used / (units_used + units_returned) * 100) if (units_used + units_returned) > 0 else 0,
            'returned_by': returned_by
        }

        self.transactions.append(return_transaction)

        self.inventory[kit_number]['status'] = 'returned_from_patient'
        self.inventory[kit_number]['units_returned'] = units_returned
        self.inventory[kit_number]['units_used'] = units_used

        return return_transaction

    def quarantine_kit(self, kit_number, reason, quarantined_by):
        """
        Quarantine kit (temperature excursion, damaged, etc.)
        """

        if kit_number not in self.inventory:
            raise ValueError(f"Kit {kit_number} not in inventory")

        quarantine_transaction = {
            'transaction_type': 'quarantined',
            'transaction_date': datetime.now(),
            'kit_number': kit_number,
            'reason': reason,
            'quarantined_by': quarantined_by
        }

        self.transactions.append(quarantine_transaction)

        self.inventory[kit_number]['status'] = 'quarantined'
        self.inventory[kit_number]['quarantine_reason'] = reason

        return quarantine_transaction

    def destroy_kit(self, kit_number, destruction_method, witnessed_by,
                   destruction_certificate=None):
        """
        Record kit destruction
        """

        if kit_number not in self.inventory:
            raise ValueError(f"Kit {kit_number} not in inventory")

        destruction_transaction = {
            'transaction_type': 'destroyed',
            'transaction_date': datetime.now(),
            'kit_number': kit_number,
            'destruction_method': destruction_method,
            'witnessed_by': witnessed_by,
            'destruction_certificate': destruction_certificate
        }

        self.transactions.append(destruction_transaction)

        self.inventory[kit_number]['status'] = 'destroyed'
        self.inventory[kit_number]['destruction_date'] = datetime.now()

        return destruction_transaction

    def return_to_sponsor(self, kit_numbers, shipment_id, shipped_by,
                         tracking_number, return_reason):
        """
        Return kits to sponsor/depot
        """

        return_transaction = {
            'transaction_type': 'returned_to_sponsor',
            'transaction_date': datetime.now(),
            'kit_numbers': kit_numbers,
            'shipment_id': shipment_id,
            'shipped_by': shipped_by,
            'tracking_number': tracking_number,
            'return_reason': return_reason
        }

        self.transactions.append(return_transaction)

        for kit_number in kit_numbers:
            if kit_number in self.inventory:
                self.inventory[kit_number]['status'] = 'returned_to_sponsor'
                self.inventory[kit_number]['return_date'] = datetime.now()

        return return_transaction

    def reconcile_inventory(self, physical_count_by_kit):
        """
        Reconcile physical inventory with system records
        """

        discrepancies = []

        for kit_number, physical_status in physical_count_by_kit.items():
            system_status = self.inventory.get(kit_number, {}).get('status', 'NOT_IN_SYSTEM')

            if physical_status != system_status:
                discrepancies.append({
                    'kit_number': kit_number,
                    'system_status': system_status,
                    'physical_status': physical_status,
                    'discrepancy_type': self._classify_discrepancy(system_status, physical_status)
                })

        reconciliation = {
            'reconciliation_date': datetime.now(),
            'site_id': self.site_id,
            'total_kits_system': len(self.inventory),
            'total_kits_physical': len(physical_count_by_kit),
            'discrepancies': discrepancies,
            'reconciliation_status': 'CLEAN' if len(discrepancies) == 0 else 'DISCREPANCIES_FOUND'
        }

        return reconciliation

    def _classify_discrepancy(self, system_status, physical_status):
        """Classify type of discrepancy"""
        if system_status == 'NOT_IN_SYSTEM':
            return 'EXTRA_KIT_FOUND'
        elif physical_status == 'NOT_FOUND':
            return 'KIT_MISSING'
        else:
            return 'STATUS_MISMATCH'

    def _verify_temperature(self, temperature_log):
        """Verify temperature compliance during shipment"""
        if not temperature_log:
            return None

        # Check all readings in range
        compliant = all(
            log['min_temp'] <= log['temperature'] <= log['max_temp']
            for log in temperature_log
        )

        return compliant

    def accountability_report(self, report_date=None):
        """
        Generate drug accountability report
        """

        report_date = report_date or datetime.now()

        # Group inventory by status
        inventory_df = pd.DataFrame(self.inventory.values())

        if len(inventory_df) == 0:
            return None

        status_summary = inventory_df.groupby('status').size().to_dict()

        # Recent transactions
        recent_transactions = [
            t for t in self.transactions
            if t['transaction_date'] >= report_date - timedelta(days=30)
        ]

        report = {
            'site_id': self.site_id,
            'trial_id': self.trial_id,
            'report_date': report_date,
            'inventory_summary': status_summary,
            'total_kits': len(inventory_df),
            'dispensed_kits': len(inventory_df[inventory_df['status'] == 'dispensed']),
            'available_kits': len(inventory_df[inventory_df['status'] == 'available']),
            'recent_transactions': len(recent_transactions),
            'transactions': recent_transactions
        }

        return report

# Example usage
accountability = DrugAccountabilitySystem(
    site_id='SITE-001',
    trial_id='TRIAL-2024-001'
)

# Receive shipment
kits = [
    {'kit_number': 'KIT-001-1001', 'lot_number': 'LOT-A', 'expiry_date': datetime(2026, 12, 31)},
    {'kit_number': 'KIT-001-1002', 'lot_number': 'LOT-A', 'expiry_date': datetime(2026, 12, 31)},
    {'kit_number': 'KIT-001-1003', 'lot_number': 'LOT-A', 'expiry_date': datetime(2026, 12, 31)}
]

receipt = accountability.receive_shipment(
    shipment_id='SHIP-2024-0015',
    kits=kits,
    received_by='Study Coordinator Jane Doe',
    condition='Good',
    temperature_log=[{'temperature': 6, 'min_temp': 2, 'max_temp': 8}]
)

print(f"Received {len(kits)} kits")

# Dispense to patient
dispense = accountability.dispense_to_patient(
    kit_number='KIT-001-1001',
    patient_id='PT-001-001',
    visit_number='Visit 2',
    dispensed_by='Investigator Dr. Smith'
)

print(f"Dispensed kit {dispense['kit_number']} to patient {dispense['patient_id']}")

# Generate accountability report
report = accountability.accountability_report()
print(f"\nAccountability Report:")
print(f"  Total kits: {report['total_kits']}")
print(f"  Available: {report['available_kits']}")
print(f"  Dispensed: {report['dispensed_kits']}")
print(f"  Inventory summary: {report['inventory_summary']}")

Temperature-Controlled Logistics

Cold Chain Management for Clinical Trials

Temperature Ranges:

  • Room temperature: 15-25°C (59-77°F)
  • Refrigerated: 2-8°C (36-46°F)
  • Frozen: -20°C (-4°F)
  • Ultra-cold: -80°C (-112°F)
class ClinicalColdChainManager:
    """
    Manage temperature-controlled shipments for clinical trials
    """

    def __init__(self, trial_id):
        self.trial_id = trial_id
        self.shipments = {}
        self.excursions = []

    def create_shipment(self, shipment_id, product_name, from_location,
                       to_location, temp_requirement, packaging_type):
        """
        Create temperature-controlled shipment
        """

        shipment = {
            'shipment_id': shipment_id,
            'product_name': product_name,
            'from_location': from_location,
            'to_location': to_location,
            'temp_requirement': temp_requirement,  # e.g., (2, 8) for 2-8°C
            'packaging_type': packaging_type,
            'ship_date': None,
            'delivery_date': None,
            'temperature_log': [],
            'excursions_detected': [],
            'status': 'pending'
        }

        self.shipments[shipment_id] = shipment

        return shipment

    def ship(self, shipment_id, data_logger_id, carrier, tracking_number):
        """
        Ship temperature-controlled package
        """

        if shipment_id not in self.shipments:
            raise ValueError(f"Shipment {shipment_id} not found")

        shipment = self.shipments[shipment_id]

        shipment['ship_date'] = datetime.now()
        shipment['data_logger_id'] = data_logger_id
        shipment['carrier'] = carrier
        shipment['tracking_number'] = tracking_number
        shipment['status'] = 'in_transit'

        return shipment

    def record_temperature(self, shipment_id, timestamp, temperature, location='in transit'):
        """
        Record temperature reading from data logger
        """

        if shipment_id not in self.shipments:
            raise ValueError(f"Shipment {shipment_id} not found")

        shipment = self.shipments[shipment_id]
        min_temp, max_temp = shipment['temp_requirement']

        reading = {
            'timestamp': timestamp,
            'temperature': temperature,
            'location': location,
            'in_range': min_temp <= temperature <= max_temp
        }

        shipment['temperature_log'].append(reading)

        # Check for excursion
        if not reading['in_range']:
            excursion = {
                'shipment_id': shipment_id,
                'timestamp': timestamp,
                'temperature': temperature,
                'required_range': shipment['temp_requirement'],
                'deviation': abs(temperature - ((min_temp + max_temp) / 2)),
                'location': location
            }

            shipment['excursions_detected'].append(excursion)
            self.excursions.append(excursion)

            # Trigger alert
            self._temperature_excursion_alert(excursion)

        return reading

    def deliver_shipment(self, shipment_id, received_by, condition_assessment):
        """
        Record shipment delivery
        """

        if shipment_id not in self.shipments:
            raise ValueError(f"Shipment {shipment_id} not found")

        shipment = self.shipments[shipment_id]

        shipment['delivery_date'] = datetime.now()
        shipment['received_by'] = received_by
        shipment['condition_assessment'] = condition_assessment
        shipment['status'] = 'delivered'

        # Analyze temperature compliance
        compliance = self._analyze_temperature_compliance(shipment)

        shipment['temperature_compliance'] = compliance

        return {
            'shipment_id': shipment_id,
            'delivery_date': shipment['delivery_date'],
            'temperature_compliant': compliance['compliant'],
            'excursions': len(shipment['excursions_detected']),
            'disposition': self._determine_disposition(compliance)
        }

    def _analyze_temperature_compliance(self, shipment):
        """
        Analyze temperature compliance for shipment
        """

        temp_log = shipment['temperature_log']

        if not temp_log:
            return {'compliant': None, 'reason': 'No temperature data'}

        total_readings = len(temp_log)
        compliant_readings = sum(1 for r in temp_log if r['in_range'])
        compliance_rate = (compliant_readings / total_readings * 100) if total_readings > 0 else 0

        num_excursions = len(shipment['excursions_detected'])

        # Determine compliance
        compliant = (compliance_rate >= 95 and num_excursions == 0)

        return {
            'compliant': compliant,
            'compliance_rate': round(compliance_rate, 2),
            'num_excursions': num_excursions,
            'total_readings': total_readings,
            'compliant_readings': compliant_readings
        }

    def _determine_disposition(self, compliance):
        """
        Determine product disposition based on compliance
        """

        if compliance['compliant']:
            return 'ACCEPT - Use per protocol'
        elif compliance['num_excursions'] > 0:
            return 'QUARANTINE - Investigate excursion, stability assessment required'
        else:
            return 'QUARANTINE - Temperature compliance review required'

    def _temperature_excursion_alert(self, excursion):
        """
        Send alert for temperature excursion
        """

        print(f"⚠ TEMPERATURE EXCURSION ALERT")
        print(f"  Shipment: {excursion['shipment_id']}")
        print(f"  Temperature: {excursion['temperature']}°C")
        print(f"  Required range: {excursion['required_range']}")
        print(f"  Time: {excursion['timestamp']}")

    def excursion_investigation_report(self, shipment_id):
        """
        Generate excursion investigation report
        """

        if shipment_id not in self.shipments:
            raise ValueError(f"Shipment {shipment_id} not found")

        shipment = self.shipments[shipment_id]

        if not shipment['excursions_detected']:
            return {'investigation_required': False}

        # Analyze excursions
        excursions_df = pd.DataFrame(shipment['excursions_detected'])

        report = {
            'shipment_id': shipment_id,
            'product_name': shipment['product_name'],
            'investigation_required': True,
            'num_excursions': len(shipment['excursions_detected']),
            'excursion_details': excursions_df.to_dict('records'),
            'total_time_out_of_range': 'Calculate from timestamp data',
            'max_deviation': excursions_df['deviation'].max() if len(excursions_df) > 0 else 0,
            'recommended_action': self._excursion_recommended_action(shipment),
            'stability_data_required': True,
            'sponsor_notification_required': True
        }

        return report

    def _excursion_recommended_action(self, shipment):
        """
        Recommend action for excursion
        """

        excursions = shipment['excursions_detected']

        if not excursions:
            return 'No action required'

        max_deviation = max(e['deviation'] for e in excursions)

        if max_deviation > 10:
            return 'REJECT - Significant excursion, product unusable'
        elif max_deviation > 5:
            return 'QUARANTINE - Contact sponsor, stability data review required'
        else:
            return 'QUARANTINE - Minor excursion, sponsor review required'

# Example usage
cold_chain = ClinicalColdChainManager(trial_id='TRIAL-2024-001')

# Create shipment
shipment = cold_chain.create_shipment(
    shipment_id='SHIP-2024-0020',
    product_name='Investigational Biologic ABC-123',
    from_location='Depot - Amsterdam',
    to_location='Site 105 - Memorial Hospital',
    temp_requirement=(2, 8),  # 2-8°C
    packaging_type='Qualified shipper with dry ice'
)

# Ship
cold_chain.ship(
    shipment_id='SHIP-2024-0020',
    data_logger_id='LOGGER-5678',
    carrier='FedEx Priority Overnight',
    tracking_number='FX123456789'
)

# Simulate temperature readings
import numpy as np
np.random.seed(42)

for hour in range(36):  # 36 hours in transit
    temp = 5 + np.random.normal(0, 1.5)

    # Simulate excursion at hour 20
    if hour == 20:
        temp = 12  # Excursion

    cold_chain.record_temperature(
        shipment_id='SHIP-2024-0020',
        timestamp=datetime.now() + timedelta(hours=hour),
        temperature=round(temp, 1)
    )

# Deliver
delivery = cold_chain.deliver_shipment(
    shipment_id='SHIP-2024-0020',
    received_by='Study Coordinator at Site 105',
    condition_assessment='Package intact, data logger attached'
)

print(f"Shipment delivered:")
print(f"  Temperature compliant: {delivery['temperature_compliant']}")
print(f"  Excursions: {delivery['excursions']}")
print(f"  Disposition: {delivery['disposition']}")

# Excursion investigation
if delivery['excursions'] > 0:
    investigation = cold_chain.excursion_investigation_report('SHIP-2024-0020')
    print(f"\n Excursion Investigation Required:")
    print(f"  Number of excursions: {investigation['num_excursions']}")
    print(f"  Max deviation: {investigation['max_deviation']:.1f}°C")
    print(f"  Recommended action: {investigation['recommended_action']}")

Comparator Sourcing & Management

Commercial Comparator Procurement

Challenges:

  • Sourcing commercial drugs in different countries
  • Ensuring consistent quality across batches
  • Managing expiry dates
  • Blinding/overencapsulation
  • Import/export compliance
class ComparatorManager:
    """
    Manage comparator drug sourcing and inventory
    """

    def __init__(self, trial_id):
        self.trial_id = trial_id
        self.comparators = {}
        self.procurement_orders = []

    def add_comparator(self, comparator_id, drug_name, strength,
                      countries_needed, blinding_required):
        """
        Add comparator to trial requirements
        """

        self.comparators[comparator_id] = {
            'comparator_id': comparator_id,
            'drug_name': drug_name,
            'strength': strength,
            'countries_needed': countries_needed,
            'blinding_required': blinding_required,
            'sourcing_strategy': self._determine_sourcing_strategy(countries_needed)
        }

    def _determine_sourcing_strategy(self, countries_needed):
        """
        Determine optimal sourcing strategy
        """

        if len(countries_needed) == 1:
            return 'local_sourcing'
        elif len(countries_needed) <= 5:
            return 'regional_sourcing'
        else:
            return 'global_sourcing_multiple_suppliers'

    def create_procurement_order(self, comparator_id, country, quantity,
                                target_delivery_date, supplier=None):
        """
        Create procurement order for comparator
        """

        if comparator_id not in self.comparators:
            raise ValueError(f"Comparator {comparator_id} not defined")

        comparator = self.comparators[comparator_id]

        order = {
            'order_id': f"PO-{len(self.procurement_orders)+1:05d}",
            'comparator_id': comparator_id,
            'drug_name': comparator['drug_name'],
            'country': country,
            'quantity': quantity,
            'target_delivery_date': target_delivery_date,
            'supplier': supplier or 'To be determined',
            'order_date': datetime.now(),
            'status': 'pending',
            'import_license_required': self._check_import_requirements(country),
            'blinding_required': comparator['blinding_required']
        }

        self.procurement_orders.append(order)

        return order

    def _check_import_requirements(self, country):
        """Check if import license required"""
        # Simplified - would check regulatory database
        controlled_countries = ['US', 'CA', 'AU', 'JP']
        return country in controlled_countries

    def quality_assessment(self, order_id, batch_number, test_results):
        """
        Record quality assessment of received comparator
        """

        order = next((o for o in self.procurement_orders if o['order_id'] == order_id), None)

        if not order:
            raise ValueError(f"Order {order_id} not found")

        assessment = {
            'order_id': order_id,
            'batch_number': batch_number,
            'assessment_date': datetime.now(),
            'test_results': test_results,
            'acceptable': all(t['result'] == 'pass' for t in test_results),
            'release_status': 'released' if all(t['result'] == 'pass' for t in test_results) else 'rejected'
        }

        order['quality_assessment'] = assessment
        order['status'] = assessment['release_status']

        return assessment

# Example usage
comparator_mgr = ComparatorManager(trial_id='TRIAL-2024-001')

# Add comparator requirement
comparator_mgr.add_comparator(
    comparator_id='COMP-001',
    drug_name='Lipitor (Atorvastatin) 40mg',
    strength='40mg',
    countries_needed=['US', 'UK', 'Germany', 'France', 'Japan'],
    blinding_required=True
)

# Create procurement orders
order_us = comparator_mgr.create_procurement_order(
    comparator_id='COMP-001',
    country='US',
    quantity=5000,
    target_delivery_date=datetime.now() + timedelta(days=90),
    supplier='Cardinal Health'
)

print(f"Procurement order created: {order_us['order_id']}")
print(f"  Import license required: {order_us['import_license_required']}")
print(f"  Blinding required: {order_us['blinding_required']}")

# Quality assessment
test_results = [
    {'test': 'Identification', 'result': 'pass'},
    {'test': 'Assay', 'result': 'pass', 'value': '99.2% (90-110% spec)'},
    {'test': 'Dissolution', 'result': 'pass'},
    {'test': 'Uniformity of Dosage Units', 'result': 'pass'}
]

qa = comparator_mgr.quality_assessment(
    order_id=order_us['order_id'],
    batch_number='BATCH-US-2024-A',
    test_results=test_results
)

print(f"\nQuality Assessment:")
print(f"  Acceptable: {qa['acceptable']}")
print(f"  Release status: {qa['release_status']}")

Clinical Trial Supply Chain Metrics

Key Performance Indicators

def calculate_clinical_trial_kpis(supply_data, enrollment_data, shipment_data):
    """
    Calculate clinical trial supply chain KPIs

    Parameters:
    - supply_data: Site inventory and supply data
    - enrollment_data: Patient enrollment data
    - shipment_data: Shipment performance data
    """

    kpis = {}

    # Stockout rate (sites without adequate supply)
    if 'stockout_event' in supply_data.columns:
        kpis['stockout_rate'] = (supply_data['stockout_event'].sum() / len(supply_data) * 100)

    # Depot-to-site delivery time
    if 'delivery_time_days' in shipment_data.columns:
        kpis['avg_delivery_time_days'] = shipment_data['delivery_time_days'].mean()

    # Temperature compliance rate
    if 'temp_compliant' in shipment_data.columns:
        kpis['temp_compliance_rate'] = (shipment_data['temp_compliant'].sum() / len(shipment_data) * 100)

    # Drug accountability compliance
    if 'accountability_complete' in supply_data.columns:
        kpis['accountability_compliance'] = (supply_data['accountability_complete'].sum() / len(supply_data) * 100)

    # Expiry waste rate
    if 'expired_kits' in supply_data.columns and 'total_kits' in supply_data.columns:
        total_expired = supply_data['expired_kits'].sum()
        total_kits = supply_data['total_kits'].sum()
        kpis['expiry_waste_rate'] = (total_expired / total_kits * 100) if total_kits > 0 else 0

    # Randomization-to-supply time (time to get drug after randomization)
    if 'randomization_to_supply_hours' in enrollment_data.columns:
        kpis['avg_randomization_to_supply_hours'] = enrollment_data['randomization_to_supply_hours'].mean()

    # Forecasting accuracy (planned vs. actual enrollment)
    if all(col in enrollment_data.columns for col in ['planned_enrollment', 'actual_enrollment']):
        planned = enrollment_data['planned_enrollment'].sum()
        actual = enrollment_data['actual_enrollment'].sum()
        kpis['enrollment_vs_forecast_pct'] = (actual / planned * 100) if planned > 0 else 0

    # Format KPIs
    for key in kpis:
        if 'rate' in key or 'compliance' in key or 'pct' in key:
            kpis[key] = round(kpis[key], 2)
        else:
            kpis[key] = round(kpis[key], 1)

    return kpis

# Example data
supply_data = pd.DataFrame({
    'site_id': [f'SITE-{i:03d}' for i in range(1, 51)],
    'stockout_event': np.random.choice([True, False], 50, p=[0.05, 0.95]),
    'accountability_complete': np.random.choice([True, False], 50, p=[0.98, 0.02]),
    'expired_kits': np.random.randint(0, 5, 50),
    'total_kits': np.random.randint(20, 100, 50)
})

shipment_data = pd.DataFrame({
    'shipment_id': range(1, 201),
    'delivery_time_days': np.random.normal(5, 2, 200),
    'temp_compliant': np.random.choice([True, False], 200, p=[0.97, 0.03])
})

enrollment_data = pd.DataFrame({
    'site_id': [f'SITE-{i:03d}' for i in range(1, 51)],
    'planned_enrollment': [20] * 50,
    'actual_enrollment': np.random.randint(15, 25, 50),
    'randomization_to_supply_hours': np.random.normal(2, 0.5, 50)
})

kpis = calculate_clinical_trial_kpis(supply_data, enrollment_data, shipment_data)

print("Clinical Trial Supply Chain KPIs:")
for metric, value in kpis.items():
    suffix = '%' if any(x in metric for x in ['rate', 'pct', 'compliance']) else ''
    print(f"  {metric}: {value}{suffix}")

Tools & Libraries

Clinical Trial Supply Systems

IRT/IVRS/IWRS:

  • Almac IVRS: Interactive voice/web response
  • Perceptive MyTrials: Cloud-based IRT
  • Oracle InForm IWRS: Integrated with EDC
  • Signant SmartSignals: IRT with supply forecasting
  • DATATRAK eIVRS: Electronic interactive system

Supply Chain Management:

  • Marken: Clinical trial logistics and distribution
  • Thermo Fisher Clinical Trials: Depot and distribution
  • Almac Clinical Services: Packaging, labeling, distribution
  • Sharp Clinical Services: Clinical packaging and logistics
  • Catalent: Packaging and logistics

Temperature Monitoring:

  • Sensitech: Cold chain monitoring
  • Tive: Real-time tracking and monitoring
  • Emerson Cargo Solutions: Temperature monitoring
  • Controlant: Real-time supply chain visibility

Python Libraries

Data Analysis:

  • pandas: Data manipulation
  • numpy: Numerical computing
  • scipy: Statistical analysis

Randomization:

  • random: Random number generation
  • numpy.random: Advanced randomization

Optimization:

  • pulp: Linear programming (supply optimization)
  • scipy.optimize: Optimization algorithms

Visualization:

  • matplotlib, seaborn: Charts
  • plotly: Interactive dashboards

Common Challenges & Solutions

Challenge: Patient Randomization Without Supply Available

Problem:

  • Patient randomized but no kit available at site
  • Impacts patient care and protocol compliance
  • Site frustration

Solutions:

  • Conservative forecasting with buffer stock
  • Real-time inventory monitoring in IRT
  • Automatic resupply triggers
  • Emergency supply procedures
  • Alternative site supply (if blinding permits)

Challenge: Temperature Excursions During Shipment

Problem:

  • Product exposed to out-of-spec temperatures
  • Uncertainty about product integrity
  • Potential patient safety risk
  • Protocol deviation

Solutions:

  • Qualified packaging validation
  • Redundant temperature monitoring
  • Real-time alerts for excursions
  • Pre-defined disposition protocols
  • Stability data to support use decisions
  • Alternative routing/carriers for problem lanes

Challenge: Expired Product at Sites

Problem:

  • Kits expire before use
  • Waste and resupply costs
  • Enrollment delays if resupply needed

Solutions:

  • Just-in-time supply strategy
  • FEFO allocation in IRT
  • Expiry-based resupply triggers
  • Pooling/transfer between sites (if protocol allows)
  • Reduced PAR levels for slow-enrolling sites
  • Return programs for usable inventory

Challenge: Drug Accountability Discrepancies

Problem:

  • Physical count doesn't match system records
  • Regulatory compliance risk
  • Audit findings

Solutions:

  • Electronic drug accountability systems
  • Regular reconciliation (monthly minimum)
  • Two-person verification for high-value products
  • Training for site staff
  • Clear procedures and documentation
  • Root cause analysis for all discrepancies

Challenge: Global Import/Export Delays

Problem:

  • Regulatory delays at customs
  • Missing documentation
  • Import license delays
  • Product stuck at border

Solutions:

  • Early import license applications
  • Experienced customs brokers
  • Complete documentation packages
  • Regulatory intelligence monitoring
  • Buffer stock in-country
  • Pre-positioning inventory where possible

Challenge: Comparator Sourcing Complexity

Problem:

  • Different formulations/packaging by country
  • Quality consistency across batches
  • Blinding challenges
  • Supply availability

Solutions:

  • Early sourcing (12+ months before site activation)
  • Quality agreements with suppliers
  • Overencapsulation for blinding
  • Multiple supplier qualification
  • Central testing and release
  • Contingency suppliers identified

Output Format

Clinical Trial Supply Report

Executive Summary:

  • Trial overview (phase, sites, enrollment)
  • Supply chain model (depot vs. direct-to-site)
  • Key performance metrics
  • Critical issues and actions

Site Supply Status:

Site IDCountryEnrollmentAvailable Kits by ArmDays SupplyExpiry RiskLast ShipmentStatus
SITE-001USA12/20Inv:15, Comp:15, Pbo:1545 daysNone2024-02-01✓ OK
SITE-015UK8/20Inv:3, Comp:3, Pbo:312 daysNone2024-01-28⚠ Low
SITE-023Germany15/20Inv:8, Comp:7, Pbo:820 days2 kits <90d2024-02-05⚠ Expiry

Shipment Performance:

MetricCurrent MonthYTDTargetStatus
On-Time Delivery94.2%95.8%95%✓
Temperature Compliance97.1%98.3%98%✓
Avg Delivery Time4.8 days5.2 days<5 days✓
Customs Delays2 shipments8 shipments-⚠

Drug Accountability:

StatusKits%
Available1,24552%
Dispensed89237%
Returned2159%
Quarantined120.5%
Destroyed251%
Expired80.3%

Temperature Excursions:

Shipment IDRouteExcursion TypeMax DeviationDurationDisposition
SHIP-2024-0045Depot→Site-023High temp+6°C2 hoursUnder investigation
SHIP-2024-0031Depot→Site-008Low temp-3°C30 minAccepted - within stability

Action Items:

  1. Resupply SITE-015 (priority shipment initiated)
  2. Transfer expiring inventory from SITE-023 to SITE-029
  3. Complete excursion investigation for SHIP-2024-0045
  4. Address customs delays in Italy (2 shipments affected)

Questions to Ask

If you need more context:

  1. What phase is the clinical trial? (I, II, III, IV)
  2. How many sites and countries?
  3. What are the product storage requirements?
  4. Is the study blinded? (single, double, open-label)
  5. What's the enrollment target and timeline?
  6. Is an IRT system in place?
  7. What distribution model? (depot, direct-to-site, hybrid)
  8. Are there comparators or placebos?
  9. What are the main supply chain challenges currently?
  10. What's the regulatory landscape? (FDA, EMA, other)

Related Skills

  • pharmacy-supply-chain: Pharmaceutical supply chain management
  • hospital-logistics: Hospital materials management
  • medical-device-distribution: Medical device logistics
  • compliance-management: Regulatory compliance and quality
  • track-and-trace: Product traceability
  • inventory-optimization: Inventory optimization techniques
  • demand-forecasting: Forecasting for supply planning
  • cold-chain-logistics: Temperature-controlled logistics (if exists)
  • quality-management: Quality management systems

Co-Packing Management

You are an expert in co-packing (contract packaging/manufacturing) operations and supply chain management. Your goal is to help optimize co-packer selection, manage co-packer relationships, and ensure seamless integration of contract manufacturing into the supply chain.

Initial Assessment

Before managing co-packing operations, understand:

  1. Business Context

    • Why use co-packing? (capacity, seasonal surge, new products, geographic expansion)
    • What products for co-packing? (volume, SKU complexity)
    • Current manufacturing footprint? (own plants, co-packers)
    • What percentage outsourced vs. internal? (target mix)
  2. Product Characteristics

    • Product types? (beverages, snacks, personal care, etc.)
    • Packaging complexity? (pouches, bottles, cans, multi-pack)
    • Shelf stability? (ambient, refrigerated, frozen)
    • Quality requirements and specifications?
    • Regulatory compliance? (FDA, USDA, organic, kosher, etc.)
  3. Volume and Capacity

    • Annual volume requirements?
    • Seasonality patterns?
    • Minimum order quantities (MOQs)?
    • Lead times needed?
    • Growth projections?
  4. Current State

    • Existing co-packer relationships?
    • Current performance issues?
    • Quality metrics and defect rates?
    • Cost structure and competitiveness?

Co-Packing Strategy Framework

Make vs. Buy Decision

When to Use Co-Packers:

  1. Capacity Constraints

    • Own plants at capacity
    • Seasonal peaks exceed internal capacity
    • Faster time-to-market than building plant
  2. Geographic Expansion

    • Enter new markets without capital investment
    • Reduce freight costs with regional production
    • Meet local content requirements
  3. Product Specialization

    • Specialized equipment/processes (aseptic, HPP, freeze-dry)
    • Small volumes don't justify investment
    • Test market new products
  4. Cost Optimization

    • Lower cost than internal production
    • Variable cost structure (vs. fixed plant costs)
    • Avoid capital expenditure
  5. Risk Mitigation

    • Backup capacity for supply resilience
    • Diversify supplier base
    • Flexibility for demand uncertainty

When to Keep Internal:

  • Core products with high volume
  • Proprietary processes or trade secrets
  • Quality-critical products
  • High-margin products
  • Strategic capabilities

Co-Packer Selection Process

Selection Criteria Matrix

import pandas as pd
import numpy as np

def score_copacker_candidates(candidates_df, weights):
    """
    Score and rank co-packer candidates using weighted criteria

    Parameters:
    - candidates_df: DataFrame with candidate scores on each criterion
    - weights: dict with importance weights for each criterion

    Returns:
    - ranked candidates with total scores
    """

    criteria = [
        'quality_capability',
        'capacity_availability',
        'cost_competitiveness',
        'technical_expertise',
        'geographic_location',
        'financial_stability',
        'certifications',
        'equipment_technology',
        'flexibility',
        'customer_service',
        'lead_times',
        'track_record'
    ]

    # Calculate weighted scores
    candidates_df['total_score'] = 0

    for criterion in criteria:
        weight = weights.get(criterion, 1.0)
        candidates_df['total_score'] += (
            candidates_df[criterion] * weight
        )

    # Normalize to 100
    candidates_df['total_score'] = (
        candidates_df['total_score'] /
        candidates_df['total_score'].max() * 100
    )

    # Rank
    candidates_df['rank'] = candidates_df['total_score'].rank(
        ascending=False,
        method='dense'
    )

    return candidates_df.sort_values('rank')


# Example usage
candidates = pd.DataFrame({
    'copacker_name': ['CoPackA', 'CoPackB', 'CoPackC'],
    'quality_capability': [9, 8, 7],
    'capacity_availability': [7, 9, 8],
    'cost_competitiveness': [6, 8, 9],
    'technical_expertise': [9, 7, 6],
    'geographic_location': [8, 6, 9],
    'financial_stability': [9, 8, 7],
    'certifications': [9, 8, 8],
    'equipment_technology': [8, 9, 7],
    'flexibility': [7, 8, 9],
    'customer_service': [8, 7, 9],
    'lead_times': [7, 9, 8],
    'track_record': [9, 8, 8]
})

weights = {
    'quality_capability': 2.0,      # Double weight for quality
    'cost_competitiveness': 1.5,    # 1.5x for cost
    'capacity_availability': 1.5,   # 1.5x for capacity
    'certifications': 1.5,          # 1.5x for compliance
    # All others: 1.0 (default)
}

ranked = score_copacker_candidates(candidates, weights)
print(ranked[['copacker_name', 'rank', 'total_score']].head())

Due Diligence Checklist

Phase 1: Initial Qualification

  • Financial stability (D&B rating, financial statements)
  • Certifications (SQF, BRC, GMP, organic, kosher, halal)
  • Capacity and availability
  • Equipment and technology match
  • Geographic location
  • References from current customers

Phase 2: Detailed Assessment

  • Plant audit and quality assessment
  • Production trials and sample approval
  • Cost model and pricing structure
  • Lead times and MOQs
  • Service level agreements
  • IT systems and integration capabilities

Phase 3: Contract Negotiation

  • Pricing terms and escalation
  • Volume commitments and flexibility
  • Quality standards and specifications
  • Liability and insurance
  • IP protection and confidentiality
  • Exit terms and transition plan

Co-Packer Relationship Management

Contract Structure

class CoPackerContract:
    """
    Model co-packer contract terms and economics
    """

    def __init__(self, contract_terms):
        self.copacker = contract_terms['copacker_name']
        self.start_date = contract_terms['start_date']
        self.term_length = contract_terms['term_months']
        self.pricing = contract_terms['pricing']
        self.volumes = contract_terms['volume_commitments']
        self.quality_terms = contract_terms['quality_sla']

    def calculate_total_cost(self, actual_volume):
        """
        Calculate total cost including all fees

        Components:
        - Base manufacturing cost (per unit or per case)
        - Material cost (if co-packer sources)
        - Packaging cost
        - Storage fees
        - Setup/changeover fees
        - Quality testing fees
        - Other fees (expedite, special handling)
        """

        # Base cost (typically tiered by volume)
        base_cost = self._calculate_base_cost(actual_volume)

        # Materials (if applicable)
        material_cost = actual_volume * self.pricing.get('material_cost_per_unit', 0)

        # Packaging
        packaging_cost = actual_volume * self.pricing.get('packaging_cost_per_unit', 0)

        # Fixed fees
        setup_fees = self.pricing.get('setup_fee_per_run', 0) * \
                     self._calculate_production_runs(actual_volume)

        storage_fees = self.pricing.get('storage_fee_per_month', 0) * \
                      self._estimate_storage_months(actual_volume)

        testing_fees = self.pricing.get('testing_fee_per_lot', 0) * \
                      self._calculate_lots(actual_volume)

        total_cost = (
            base_cost +
            material_cost +
            packaging_cost +
            setup_fees +
            storage_fees +
            testing_fees
        )

        return {
            'total_cost': total_cost,
            'cost_per_unit': total_cost / actual_volume,
            'breakdown': {
                'base_cost': base_cost,
                'material_cost': material_cost,
                'packaging_cost': packaging_cost,
                'setup_fees': setup_fees,
                'storage_fees': storage_fees,
                'testing_fees': testing_fees
            }
        }

    def _calculate_base_cost(self, volume):
        """Calculate base manufacturing cost with volume tiers"""

        pricing_tiers = self.pricing['base_cost_tiers']

        for tier in sorted(pricing_tiers, key=lambda x: x['min_volume'], reverse=True):
            if volume >= tier['min_volume']:
                return volume * tier['cost_per_unit']

        # If below all tiers, use highest cost
        return volume * pricing_tiers[0]['cost_per_unit']

    def _calculate_production_runs(self, volume):
        """Estimate number of production runs"""
        lot_size = self.pricing.get('typical_lot_size', 10000)
        return int(np.ceil(volume / lot_size))

    def _calculate_lots(self, volume):
        """Calculate number of QC lots"""
        lot_size = self.pricing.get('qc_lot_size', 5000)
        return int(np.ceil(volume / lot_size))

    def _estimate_storage_months(self, volume):
        """Estimate storage duration"""
        # Simplified: assume storage for 1 month
        return 1

    def check_minimum_commitment(self, actual_volume):
        """Check if minimum volume commitment met"""

        min_annual = self.volumes.get('minimum_annual', 0)
        shortfall = max(0, min_annual - actual_volume)

        if shortfall > 0:
            penalty = shortfall * self.pricing.get('shortfall_penalty_per_unit', 0)
            return {
                'commitment_met': False,
                'shortfall': shortfall,
                'penalty': penalty
            }

        return {'commitment_met': True, 'shortfall': 0, 'penalty': 0}


# Example contract
contract_terms = {
    'copacker_name': 'ABC Co-Packing',
    'start_date': '2025-01-01',
    'term_months': 12,
    'pricing': {
        'base_cost_tiers': [
            {'min_volume': 100000, 'cost_per_unit': 2.50},
            {'min_volume': 50000, 'cost_per_unit': 2.75},
            {'min_volume': 0, 'cost_per_unit': 3.00}
        ],
        'material_cost_per_unit': 1.50,
        'packaging_cost_per_unit': 0.75,
        'setup_fee_per_run': 2500,
        'storage_fee_per_month': 1000,
        'testing_fee_per_lot': 500,
        'typical_lot_size': 10000,
        'qc_lot_size': 10000,
        'shortfall_penalty_per_unit': 0.50
    },
    'volume_commitments': {
        'minimum_annual': 75000
    },
    'quality_sla': {
        'max_defect_rate': 0.005,
        'on_time_delivery': 0.95
    }
}

contract = CoPackerContract(contract_terms)
cost_analysis = contract.calculate_total_cost(actual_volume=80000)

print(f"Total Cost: ${cost_analysis['total_cost']:,.0f}")
print(f"Cost per Unit: ${cost_analysis['cost_per_unit']:.2f}")

Supply Chain Coordination

Demand Planning and Forecasting

def plan_copacker_orders(demand_forecast, lead_time_weeks, safety_stock_weeks,
                          moq, lot_size):
    """
    Plan co-packer orders based on demand forecast

    Parameters:
    - demand_forecast: weekly demand forecast
    - lead_time_weeks: co-packer lead time
    - safety_stock_weeks: weeks of safety stock
    - moq: minimum order quantity
    - lot_size: production lot size (for rounding)

    Returns:
    - order plan with timing and quantities
    """

    order_plan = []

    for week, demand in enumerate(demand_forecast):
        # Calculate order point
        lead_time_demand = sum(demand_forecast[week:week+lead_time_weeks])
        safety_stock = demand * safety_stock_weeks

        order_point = lead_time_demand + safety_stock

        # Current inventory
        current_inventory = calculate_current_inventory(week)

        # Order if below order point
        if current_inventory < order_point:
            order_qty = order_point - current_inventory

            # Round up to MOQ
            if order_qty < moq:
                order_qty = moq

            # Round up to lot size
            order_qty = int(np.ceil(order_qty / lot_size) * lot_size)

            order_plan.append({
                'order_week': week,
                'order_qty': order_qty,
                'delivery_week': week + lead_time_weeks,
                'demand': demand,
                'inventory_before': current_inventory,
                'inventory_after': current_inventory + order_qty
            })

    return order_plan

Quality Management

class CoPackerQualityManager:
    """
    Manage quality metrics and SLA compliance for co-packers
    """

    def __init__(self, quality_sla):
        self.sla = quality_sla
        self.quality_data = []

    def record_lot_inspection(self, lot_data):
        """Record quality inspection results for a production lot"""

        inspection = {
            'lot_number': lot_data['lot_number'],
            'date': lot_data['date'],
            'quantity': lot_data['quantity'],
            'defects_found': lot_data['defects'],
            'defect_rate': lot_data['defects'] / lot_data['quantity'],
            'accepted': lot_data['defects'] / lot_data['quantity'] <= self.sla['max_defect_rate']
        }

        self.quality_data.append(inspection)

        return inspection

    def calculate_performance_metrics(self):
        """Calculate quality performance metrics"""

        if not self.quality_data:
            return None

        df = pd.DataFrame(self.quality_data)

        metrics = {
            'total_lots': len(df),
            'accepted_lots': df['accepted'].sum(),
            'rejected_lots': (~df['accepted']).sum(),
            'acceptance_rate': df['accepted'].mean() * 100,
            'avg_defect_rate': df['defect_rate'].mean() * 100,
            'total_defects': df['defects_found'].sum(),
            'total_units_inspected': df['quantity'].sum()
        }

        # SLA compliance
        metrics['meets_quality_sla'] = (
            metrics['avg_defect_rate'] <= self.sla['max_defect_rate'] * 100
        )

        return metrics

    def generate_quality_report(self):
        """Generate quality scorecard"""

        metrics = self.calculate_performance_metrics()

        if metrics is None:
            return "No quality data available"

        report = f"""
Co-Packer Quality Performance Report

Total Lots Inspected: {metrics['total_lots']}
Accepted: {metrics['accepted_lots']} ({metrics['acceptance_rate']:.1f}%)
Rejected: {metrics['rejected_lots']}

Average Defect Rate: {metrics['avg_defect_rate']:.2f}%
SLA Target: {self.sla['max_defect_rate']*100:.2f}%
SLA Status: {'✓ PASS' if metrics['meets_quality_sla'] else '✗ FAIL'}

Total Units Inspected: {metrics['total_units_inspected']:,}
Total Defects: {metrics['total_defects']}
"""

        return report


# Example usage
quality_sla = {'max_defect_rate': 0.005}  # 0.5% max defects
qm = CoPackerQualityManager(quality_sla)

# Record inspections
qm.record_lot_inspection({
    'lot_number': 'LOT001',
    'date': '2025-01-15',
    'quantity': 10000,
    'defects': 45
})

qm.record_lot_inspection({
    'lot_number': 'LOT002',
    'date': '2025-01-22',
    'quantity': 10000,
    'defects': 52
})

print(qm.generate_quality_report())

Cost Optimization

Make vs. Buy Economic Analysis

def make_vs_buy_analysis(internal_costs, copacker_costs, annual_volume):
    """
    Analyze economics of internal production vs. co-packing

    Parameters:
    - internal_costs: dict with internal cost structure
    - copacker_costs: dict with co-packer pricing
    - annual_volume: expected annual volume

    Returns:
    - cost comparison and recommendation
    """

    # Internal production costs
    internal_fixed = internal_costs.get('fixed_costs_annual', 0)
    internal_variable = internal_costs.get('variable_cost_per_unit', 0)
    internal_total = internal_fixed + (internal_variable * annual_volume)

    # Co-packer costs
    copacker_variable = copacker_costs.get('cost_per_unit', 0)
    copacker_fixed = copacker_costs.get('annual_fees', 0)
    copacker_total = copacker_fixed + (copacker_variable * annual_volume)

    # Comparison
    savings = internal_total - copacker_total
    savings_pct = savings / internal_total * 100 if internal_total > 0 else 0

    # Break-even volume
    if internal_variable < copacker_variable:
        # Internal has lower variable cost
        breakeven = internal_fixed / (copacker_variable - internal_variable)
    else:
        # Co-packer has lower variable cost
        breakeven = (copacker_fixed - internal_fixed) / (internal_variable - copacker_variable)

    recommendation = 'Make Internal' if internal_total < copacker_total else 'Use Co-Packer'

    return {
        'internal_cost': internal_total,
        'copacker_cost': copacker_total,
        'savings_with_copacker': savings,
        'savings_pct': savings_pct,
        'breakeven_volume': max(0, breakeven),
        'recommendation': recommendation,
        'cost_per_unit_internal': internal_total / annual_volume,
        'cost_per_unit_copacker': copacker_total / annual_volume
    }


# Example
analysis = make_vs_buy_analysis(
    internal_costs={
        'fixed_costs_annual': 500000,  # Plant overhead, equipment, staff
        'variable_cost_per_unit': 3.50  # Materials, labor, utilities
    },
    copacker_costs={
        'cost_per_unit': 4.25,
        'annual_fees': 50000  # Setup, tooling, etc.
    },
    annual_volume=100000
)

print(f"Internal Cost: ${analysis['internal_cost']:,.0f}")
print(f"Co-Packer Cost: ${analysis['copacker_cost']:,.0f}")
print(f"Savings: ${analysis['savings_with_copacker']:,.0f} ({analysis['savings_pct']:.1f}%)")
print(f"Recommendation: {analysis['recommendation']}")
print(f"Break-even Volume: {analysis['breakeven_volume']:,.0f} units")

Multi-Sourcing Optimization

from pulp import *

def optimize_copacker_allocation(demand, copackers, constraints):
    """
    Optimize allocation of production across multiple co-packers

    Parameters:
    - demand: total demand to fulfill
    - copackers: list of co-packers with costs and capacities
    - constraints: business rules

    Returns:
    - optimal allocation
    """

    # Create problem
    prob = LpProblem("CoPacker_Allocation", LpMinimize)

    # Decision variables: volume allocated to each co-packer
    allocation = LpVariable.dicts(
        "Allocation",
        [cp['name'] for cp in copackers],
        lowBound=0,
        cat='Continuous'
    )

    # Binary variables: is co-packer used?
    used = LpVariable.dicts(
        "Used",
        [cp['name'] for cp in copackers],
        cat='Binary'
    )

    # Objective: minimize total cost
    total_cost = 0

    for cp in copackers:
        name = cp['name']
        # Variable cost
        total_cost += allocation[name] * cp['cost_per_unit']
        # Fixed cost (if used)
        total_cost += used[name] * cp['fixed_cost']

    prob += total_cost

    # Constraints

    # 1. Meet demand
    prob += lpSum([allocation[cp['name']] for cp in copackers]) >= demand

    # 2. Capacity constraints
    for cp in copackers:
        name = cp['name']
        prob += allocation[name] <= cp['capacity']

    # 3. MOQ constraints
    for cp in copackers:
        name = cp['name']
        moq = cp.get('moq', 0)
        # If used, must meet MOQ
        prob += allocation[name] >= moq * used[name]
        # If not used, allocation = 0
        prob += allocation[name] <= cp['capacity'] * used[name]

    # 4. Single sourcing preference (optional)
    if constraints.get('prefer_single_source', False):
        prob += lpSum([used[cp['name']] for cp in copackers]) <= 2

    # 5. Minimum allocation for preferred suppliers
    preferred = constraints.get('preferred_suppliers', [])
    for pref in preferred:
        min_pct = pref.get('min_allocation_pct', 0)
        prob += allocation[pref['name']] >= demand * min_pct

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract results
    results = {
        'status': LpStatus[prob.status],
        'total_cost': value(prob.objective),
        'allocations': []
    }

    for cp in copackers:
        name = cp['name']
        if allocation[name].varValue > 0:
            results['allocations'].append({
                'copacker': name,
                'volume': allocation[name].varValue,
                'pct_of_demand': allocation[name].varValue / demand * 100,
                'cost': allocation[name].varValue * cp['cost_per_unit'] +
                        used[name].varValue * cp['fixed_cost']
            })

    return results


# Example
copackers = [
    {
        'name': 'CoPacker_A',
        'capacity': 50000,
        'cost_per_unit': 4.20,
        'fixed_cost': 10000,
        'moq': 5000
    },
    {
        'name': 'CoPacker_B',
        'capacity': 75000,
        'cost_per_unit': 4.00,
        'fixed_cost': 15000,
        'moq': 10000
    },
    {
        'name': 'CoPacker_C',
        'capacity': 40000,
        'cost_per_unit': 4.50,
        'fixed_cost': 5000,
        'moq': 2000
    }
]

result = optimize_copacker_allocation(
    demand=60000,
    copackers=copackers,
    constraints={'prefer_single_source': False}
)

print(f"Total Cost: ${result['total_cost']:,.0f}")
for alloc in result['allocations']:
    print(f"{alloc['copacker']}: {alloc['volume']:,.0f} units ({alloc['pct_of_demand']:.1f}%)")

Performance Management

Co-Packer Scorecard

class CoPackerScorecard:
    """
    Comprehensive co-packer performance tracking
    """

    def __init__(self, copacker_name, sla_targets):
        self.copacker = copacker_name
        self.sla = sla_targets
        self.performance_data = []

    def record_performance(self, period_data):
        """Record performance for a period"""
        self.performance_data.append(period_data)

    def calculate_scorecard(self):
        """Calculate overall performance scorecard"""

        if not self.performance_data:
            return None

        df = pd.DataFrame(self.performance_data)

        scorecard = {}

        # Quality metrics
        scorecard['quality_score'] = self._score_quality(df)

        # Delivery metrics
        scorecard['delivery_score'] = self._score_delivery(df)

        # Cost metrics
        scorecard['cost_score'] = self._score_cost(df)

        # Service metrics
        scorecard['service_score'] = self._score_service(df)

        # Overall score (weighted average)
        weights = {
            'quality_score': 0.35,
            'delivery_score': 0.25,
            'cost_score': 0.25,
            'service_score': 0.15
        }

        scorecard['overall_score'] = sum(
            scorecard[metric] * weight
            for metric, weight in weights.items()
        )

        scorecard['grade'] = self._assign_grade(scorecard['overall_score'])

        return scorecard

    def _score_quality(self, df):
        """Score quality performance (0-100)"""
        avg_defect_rate = df['defect_rate'].mean()
        target_defect_rate = self.sla.get('max_defect_rate', 0.005)

        if avg_defect_rate <= target_defect_rate:
            return 100
        elif avg_defect_rate <= target_defect_rate * 2:
            return 80
        elif avg_defect_rate <= target_defect_rate * 3:
            return 60
        else:
            return 40

    def _score_delivery(self, df):
        """Score delivery performance (0-100)"""
        on_time_pct = df['on_time'].mean()
        target = self.sla.get('on_time_delivery', 0.95)

        if on_time_pct >= target:
            return 100
        elif on_time_pct >= target - 0.05:
            return 80
        elif on_time_pct >= target - 0.10:
            return 60
        else:
            return 40

    def _score_cost(self, df):
        """Score cost competitiveness (0-100)"""
        avg_cost = df['cost_per_unit'].mean()
        target_cost = self.sla.get('target_cost', avg_cost)

        variance = (avg_cost - target_cost) / target_cost

        if variance <= 0:  # Under target
            return 100
        elif variance <= 0.05:
            return 90
        elif variance <= 0.10:
            return 70
        else:
            return 50

    def _score_service(self, df):
        """Score service and responsiveness (0-100)"""
        # Composite of various service metrics
        service_score = (
            df.get('responsiveness', 80).mean() * 0.4 +
            df.get('flexibility', 80).mean() * 0.3 +
            df.get('communication', 80).mean() * 0.3
        )

        return min(100, service_score)

    def _assign_grade(self, score):
        """Assign letter grade"""
        if score >= 90:
            return 'A'
        elif score >= 80:
            return 'B'
        elif score >= 70:
            return 'C'
        elif score >= 60:
            return 'D'
        else:
            return 'F'

Tools & Technologies

Co-Packer Management Software

Vendor Management:

  • SAP Ariba: Supplier management and collaboration
  • Coupa: Supplier management and procurement
  • Jaggaer: Supplier relationship management
  • Ivalua: Procurement and supplier management

Quality Management:

  • TraceGains: Supplier compliance and quality
  • MasterControl: Quality management system
  • Sparta Systems: Quality and compliance (TrackWise)
  • ETQ Reliance: Quality management

Contract Manufacturing Platforms:

  • SQFI: Safe Quality Food Institute certification
  • Selerant: Recipe and formulation management
  • Blue Yonder: Manufacturing planning and collaboration
  • E2open: Supply chain collaboration platform

Python Libraries

# Contract and supplier management
import pandas as pd
import numpy as np

# Optimization
from pulp import *
import scipy.optimize as opt

# Data visualization
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go

# Financial analysis
from scipy import stats
import statsmodels.api as sm

Common Challenges & Solutions

Challenge: Quality Inconsistency

Problem:

  • Batch-to-batch variation
  • Higher defect rates than internal
  • Quality disputes

Solutions:

  • Detailed specifications and approved samples
  • First article inspection for new runs
  • In-process quality checks
  • Statistical process control (SPC)
  • Regular audits and process reviews
  • Invest in co-packer training

Challenge: Long Lead Times

Problem:

  • 8-12 week lead times
  • Slow response to demand changes
  • Inventory challenges

Solutions:

  • Commit to longer-term forecasts
  • Build safety stock
  • Negotiate priority/expedite options
  • Multi-source for flexibility
  • Consider vendor-managed inventory (VMI)

Challenge: High MOQs

Problem:

  • MOQs larger than needed
  • Excess inventory
  • Cash flow impact

Solutions:

  • Negotiate lower MOQs (pay premium)
  • Combine SKUs in single run
  • Find smaller/flexible co-packers
  • Use tolling (bring your materials)
  • Build to stock during off-peak

Challenge: IP Protection

Problem:

  • Risk of formula theft
  • Proprietary process exposure
  • Competing products

Solutions:

  • Strong NDAs and contracts
  • Separate ingredients/pre-mix
  • Split production (multi co-packers)
  • Regular audits
  • Exclusive agreements
  • Patent protection

Challenge: Cost Creep

Problem:

  • Prices increase over time
  • Hidden fees and surcharges
  • Less competitive

Solutions:

  • Lock in multi-year pricing
  • Index to commodities (transparent)
  • Benchmark against alternatives
  • RFQ every 2-3 years
  • Volume commitments for discounts
  • Monitor total landed cost

Output Format

Co-Packer Evaluation Report

Executive Summary:

  • Co-Packer: ABC Co-Packing Inc.
  • Location: Memphis, TN
  • Products: Snack bars, granola
  • Evaluation Date: January 2025
  • Overall Score: 85/100 (Grade: B)
  • Recommendation: Approved for partnership

Scoring Detail:

CategoryScoreWeightWeightedTargetStatus
Quality9035%31.5>85✓
Delivery8525%21.25>90⚠
Cost8025%20.0>80✓
Service8215%12.3>80✓
Total85100%85>80✓

Strengths:

  • Excellent quality track record (0.3% defect rate)
  • SQF Level 3 certified
  • Modern equipment and technology
  • Competitive pricing
  • Strong technical expertise

Weaknesses:

  • Delivery performance below target (85% vs. 90%)
  • Limited surge capacity
  • Higher MOQs than desired

Recommendations:

  1. Negotiate improved lead times and on-time delivery
  2. Request MOQ reduction for initial SKUs
  3. Establish expedite process for urgent orders
  4. Proceed with pilot production (10,000 units)

Questions to Ask

If you need more context:

  1. What products do you want to co-pack? What volume?
  2. Why co-packing vs. internal production?
  3. Do you have existing co-packer relationships?
  4. What are your quality requirements and certifications needed?
  5. What lead times and MOQs can you accept?
  6. What's your budget and target cost per unit?
  7. Any geographic preferences?
  8. IP protection concerns?

Related Skills

  • capacity-planning: For production capacity analysis
  • supplier-selection: For vendor evaluation frameworks
  • supplier-risk-management: For co-packer risk assessment
  • quality-management: For quality systems and SPC
  • procurement-optimization: For contract negotiation
  • inventory-optimization: For co-packer inventory planning
  • master-production-scheduling: For production scheduling
  • network-design: For co-packer network strategy
  • compliance-management: For regulatory compliance

Column Generation

You are an expert in column generation and decomposition methods for large-scale supply chain optimization. Your goal is to help solve problems with exponentially many variables by generating only relevant columns (variables) on demand, making previously intractable problems solvable.

Initial Assessment

Before applying column generation, understand:

  1. Problem Structure

    • Does problem have exponentially many variables?
    • Can it be decomposed into master and subproblems?
    • Is there a natural decomposition structure?
    • Are constraints decomposable?
  2. Problem Characteristics

    • Problem type? (cutting stock, routing, crew scheduling, packing)
    • Size? (thousands to millions of variables)
    • Why is standard MIP approach failing?
    • Required solution quality?
  3. Computational Environment

    • Solver access? (need LP/MIP solver)
    • Subproblem complexity? (easy or hard to solve)
    • Time constraints?
    • Parallel computing available?
  4. Technical Expertise

    • Team familiarity with column generation?
    • Ability to formulate subproblem?
    • Need for exact vs. heuristic solutions?

Column Generation Framework

Core Concept

Problem Decomposition:

  • Master Problem: Restricted problem with subset of variables
  • Pricing Problem: Find new variables (columns) to improve solution
  • Iteration: Solve master → solve pricing → add columns → repeat
  • Termination: When no improving columns found

Mathematical Foundation

Original Problem (Set Partitioning):

min  Σ c_j x_j
s.t. Σ a_ij x_j = 1  ∀i  (cover each element exactly once)
     x_j ∈ {0,1}

Relaxed Master Problem:

min  Σ c_j x_j      (j ∈ J_current)
s.t. Σ a_ij x_j = 1  ∀i
     x_j ≥ 0

Dual variables: π_i

Pricing Problem:

Find column j with reduced cost: c_j - Σ a_ij π_i < 0

This becomes an optimization problem specific to the application

Cutting Stock Problem with Column Generation

Problem Description

1D Cutting Stock:

  • Cut large rolls of width W into smaller pieces
  • Meet demand for different piece widths
  • Minimize number of rolls used (minimize waste)

Implementation

import numpy as np
from pulp import *
from typing import List, Dict, Tuple
import matplotlib.pyplot as plt

class ColumnGenerationCuttingStock:
    """
    Column Generation for 1D Cutting Stock Problem

    Problem: Cut standard-width rolls into smaller pieces to meet demand
    Objective: Minimize number of rolls used
    """

    def __init__(self,
                 roll_width: float,
                 piece_widths: List[float],
                 piece_demands: List[int],
                 max_iterations: int = 100):
        """
        Initialize Column Generation for Cutting Stock

        roll_width: width of standard roll
        piece_widths: list of required piece widths
        piece_demands: demand for each piece width
        """

        self.roll_width = roll_width
        self.piece_widths = piece_widths
        self.piece_demands = piece_demands
        self.n_pieces = len(piece_widths)

        self.max_iterations = max_iterations

        # Pattern storage: each pattern is dict {piece_idx: quantity}
        self.patterns = []

        # Results
        self.optimal_patterns = None
        self.num_rolls = None
        self.iteration_history = []

    def _generate_initial_patterns(self) -> List[Dict[int, int]]:
        """
        Generate initial patterns (one piece type per pattern)

        Each pattern: maximum pieces of one width that fit in roll
        """

        patterns = []

        for i, width in enumerate(self.piece_widths):
            max_pieces = int(self.roll_width / width)
            pattern = {i: max_pieces}
            patterns.append(pattern)

        return patterns

    def _solve_master_problem(self, patterns: List[Dict[int, int]]) -> Tuple[float, List[float]]:
        """
        Solve Restricted Master Problem (RMP)

        Minimize number of rolls used
        Subject to: meet demand for each piece type

        Returns: objective value, dual values (shadow prices)
        """

        n_patterns = len(patterns)

        # Create LP model
        master = LpProblem("Master_Cutting_Stock", LpMinimize)

        # Decision variables: number of times to use each pattern
        pattern_vars = [LpVariable(f"Pattern_{j}", lowBound=0, cat='Continuous')
                       for j in range(n_patterns)]

        # Objective: minimize total number of rolls
        master += lpSum(pattern_vars), "Total_Rolls"

        # Constraints: meet demand for each piece type
        constraints = []
        for i in range(self.n_pieces):
            constraint = lpSum([
                patterns[j].get(i, 0) * pattern_vars[j]
                for j in range(n_patterns)
            ]) >= self.piece_demands[i]

            master += constraint, f"Demand_Piece_{i}"
            constraints.append(constraint)

        # Solve
        master.solve(PULP_CBC_CMD(msg=0))

        # Extract results
        obj_value = value(master.objective)

        # Extract dual values (shadow prices)
        dual_values = []
        for constraint in constraints:
            # Get dual value from constraint
            dual = constraint.pi if hasattr(constraint, 'pi') else 0
            dual_values.append(dual)

        # Fallback if dual extraction fails (use simplified approach)
        if all(d == 0 for d in dual_values):
            # Estimate duals from solution
            for i in range(self.n_pieces):
                total_produced = sum(patterns[j].get(i, 0) * pattern_vars[j].varValue
                                   for j in range(n_patterns))
                if total_produced > 0:
                    dual_values[i] = 1.0 / self.piece_widths[i]
                else:
                    dual_values[i] = 1.0

        return obj_value, dual_values

    def _solve_pricing_problem(self, dual_values: List[float]) -> Tuple[Dict[int, int], float]:
        """
        Solve Pricing Subproblem (knapsack problem)

        Find cutting pattern with negative reduced cost

        Reduced cost = 1 - Σ (pieces_i * dual_i)

        This is a knapsack problem:
        max  Σ dual_i * pieces_i
        s.t. Σ width_i * pieces_i ≤ roll_width
             pieces_i ≥ 0, integer

        Returns: new pattern, reduced cost
        """

        # Create knapsack model
        pricing = LpProblem("Pricing_Knapsack", LpMaximize)

        # Decision variables: number of pieces of each type in pattern
        pieces = [LpVariable(f"Piece_{i}", lowBound=0, cat='Integer')
                 for i in range(self.n_pieces)]

        # Objective: maximize value (dual values)
        pricing += lpSum([dual_values[i] * pieces[i]
                         for i in range(self.n_pieces)]), "Pattern_Value"

        # Constraint: don't exceed roll width
        pricing += lpSum([self.piece_widths[i] * pieces[i]
                         for i in range(self.n_pieces)]) <= self.roll_width, \
                   "Roll_Width"

        # Solve
        pricing.solve(PULP_CBC_CMD(msg=0))

        # Extract pattern
        new_pattern = {}
        for i in range(self.n_pieces):
            quantity = int(pieces[i].varValue)
            if quantity > 0:
                new_pattern[i] = quantity

        # Calculate reduced cost
        pattern_value = value(pricing.objective)
        reduced_cost = 1.0 - pattern_value

        return new_pattern, reduced_cost

    def optimize(self) -> Dict:
        """
        Run Column Generation algorithm

        Returns: optimization results
        """

        print(f"Starting Column Generation for Cutting Stock...")
        print(f"Roll Width: {self.roll_width}")
        print(f"Piece Types: {self.n_pieces}")
        print(f"Total Demand: {sum(self.piece_demands)}")

        # Initialize with simple patterns
        self.patterns = self._generate_initial_patterns()

        iteration = 0

        while iteration < self.max_iterations:
            iteration += 1

            # Solve master problem
            obj_value, dual_values = self._solve_master_problem(self.patterns)

            self.iteration_history.append({
                'iteration': iteration,
                'objective': obj_value,
                'num_patterns': len(self.patterns)
            })

            print(f"\nIteration {iteration}:")
            print(f"  Current Objective: {obj_value:.2f} rolls")
            print(f"  Number of Patterns: {len(self.patterns)}")
            print(f"  Dual Values: {[f'{d:.3f}' for d in dual_values]}")

            # Solve pricing problem
            new_pattern, reduced_cost = self._solve_pricing_problem(dual_values)

            print(f"  Reduced Cost: {reduced_cost:.6f}")

            # Check termination
            if reduced_cost >= -1e-6:  # No improving pattern found
                print(f"\nOptimality reached! No more improving patterns.")
                break

            # Add new pattern
            print(f"  Adding new pattern: {new_pattern}")
            self.patterns.append(new_pattern)

        # Final solve with integer variables
        print(f"\nSolving final MIP with {len(self.patterns)} patterns...")
        self.num_rolls, self.optimal_patterns = self._solve_final_mip(self.patterns)

        return {
            'num_rolls': self.num_rolls,
            'optimal_patterns': self.optimal_patterns,
            'all_patterns': self.patterns,
            'iterations': iteration,
            'iteration_history': self.iteration_history
        }

    def _solve_final_mip(self, patterns: List[Dict[int, int]]) -> Tuple[float, Dict]:
        """
        Solve final MIP with integer pattern variables

        Returns: optimal number of rolls, pattern usage
        """

        n_patterns = len(patterns)

        # Create MIP model
        final = LpProblem("Final_Cutting_Stock_MIP", LpMinimize)

        # Decision variables: integer number of times to use each pattern
        pattern_vars = [LpVariable(f"Pattern_{j}", lowBound=0, cat='Integer')
                       for j in range(n_patterns)]

        # Objective: minimize total number of rolls
        final += lpSum(pattern_vars), "Total_Rolls"

        # Constraints: meet demand for each piece type
        for i in range(self.n_pieces):
            final += lpSum([
                patterns[j].get(i, 0) * pattern_vars[j]
                for j in range(n_patterns)
            ]) >= self.piece_demands[i], f"Demand_Piece_{i}"

        # Solve
        final.solve(PULP_CBC_CMD(msg=0))

        # Extract solution
        num_rolls = value(final.objective)

        pattern_usage = {}
        for j in range(n_patterns):
            usage = pattern_vars[j].varValue
            if usage > 0.5:  # Used
                pattern_usage[j] = int(usage)

        return num_rolls, pattern_usage

    def print_solution(self):
        """Print detailed solution"""

        print("\n" + "="*70)
        print("OPTIMAL CUTTING STOCK SOLUTION")
        print("="*70)

        print(f"\nTotal Rolls Used: {self.num_rolls}")
        print(f"\nPatterns Used:")

        total_pieces_produced = {i: 0 for i in range(self.n_pieces)}

        for pattern_idx, usage in sorted(self.optimal_patterns.items()):
            pattern = self.patterns[pattern_idx]

            print(f"\n  Pattern {pattern_idx} (use {usage} times):")

            for piece_idx, quantity in sorted(pattern.items()):
                width = self.piece_widths[piece_idx]
                print(f"    - {quantity} pieces of width {width}")
                total_pieces_produced[piece_idx] += quantity * usage

            # Calculate waste
            used_width = sum(self.piece_widths[i] * quantity
                           for i, quantity in pattern.items())
            waste = self.roll_width - used_width
            waste_pct = (waste / self.roll_width) * 100
            print(f"    Waste: {waste:.2f} ({waste_pct:.1f}%)")

        # Verify demand met
        print(f"\nDemand Satisfaction:")
        for i in range(self.n_pieces):
            demand = self.piece_demands[i]
            produced = total_pieces_produced[i]
            status = "✓" if produced >= demand else "✗"
            print(f"  Width {self.piece_widths[i]}: "
                  f"Demand = {demand}, Produced = {produced} {status}")

        # Calculate total waste
        total_waste = 0
        for pattern_idx, usage in self.optimal_patterns.items():
            pattern = self.patterns[pattern_idx]
            used_width = sum(self.piece_widths[i] * quantity
                           for i, quantity in pattern.items())
            total_waste += (self.roll_width - used_width) * usage

        total_material = self.num_rolls * self.roll_width
        waste_pct = (total_waste / total_material) * 100

        print(f"\nTotal Waste: {total_waste:.2f} ({waste_pct:.1f}%)")
        print("="*70)

    def plot_convergence(self):
        """Plot convergence of objective value"""

        iterations = [h['iteration'] for h in self.iteration_history]
        objectives = [h['objective'] for h in self.iteration_history]

        plt.figure(figsize=(10, 6))
        plt.plot(iterations, objectives, 'b-o', linewidth=2, markersize=6)
        plt.xlabel('Iteration', fontsize=12)
        plt.ylabel('Number of Rolls (LP Relaxation)', fontsize=12)
        plt.title('Column Generation Convergence', fontsize=14)
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.show()

    def plot_patterns(self):
        """Visualize cutting patterns"""

        if not self.optimal_patterns:
            print("No solution to plot!")
            return

        fig, axes = plt.subplots(len(self.optimal_patterns), 1,
                                figsize=(14, 2*len(self.optimal_patterns)))

        if len(self.optimal_patterns) == 1:
            axes = [axes]

        colors = plt.cm.Set3(np.linspace(0, 1, self.n_pieces))

        for ax_idx, (pattern_idx, usage) in enumerate(sorted(self.optimal_patterns.items())):
            pattern = self.patterns[pattern_idx]

            ax = axes[ax_idx]

            # Draw roll
            ax.add_patch(plt.Rectangle((0, 0), self.roll_width, 1,
                                      fill=False, edgecolor='black', linewidth=2))

            # Draw pieces
            current_pos = 0
            for piece_idx in sorted(pattern.keys()):
                quantity = pattern[piece_idx]
                width = self.piece_widths[piece_idx]

                for _ in range(quantity):
                    ax.add_patch(plt.Rectangle((current_pos, 0), width, 1,
                                              facecolor=colors[piece_idx],
                                              edgecolor='black', linewidth=1))
                    # Add label
                    ax.text(current_pos + width/2, 0.5, f'{width}',
                           ha='center', va='center', fontsize=10, fontweight='bold')

                    current_pos += width

            # Waste
            waste = self.roll_width - current_pos
            if waste > 0:
                ax.add_patch(plt.Rectangle((current_pos, 0), waste, 1,
                                          facecolor='lightgray',
                                          edgecolor='black', linewidth=1,
                                          hatch='//'))
                ax.text(current_pos + waste/2, 0.5, 'Waste',
                       ha='center', va='center', fontsize=9, style='italic')

            ax.set_xlim(0, self.roll_width)
            ax.set_ylim(0, 1)
            ax.set_aspect('equal')
            ax.axis('off')
            ax.set_title(f'Pattern {pattern_idx} (use {usage} times)',
                        fontsize=11, fontweight='bold')

        plt.tight_layout()
        plt.show()


# Example usage
if __name__ == "__main__":
    # Example problem
    roll_width = 100  # Standard roll width

    # Required piece widths and demands
    piece_widths = [45, 36, 31, 14]
    piece_demands = [97, 610, 395, 211]

    print("Cutting Stock Problem:")
    print(f"  Standard Roll Width: {roll_width}")
    for i, (width, demand) in enumerate(zip(piece_widths, piece_demands)):
        print(f"  Piece {i}: Width = {width}, Demand = {demand}")

    # Create and solve
    cg_solver = ColumnGenerationCuttingStock(
        roll_width=roll_width,
        piece_widths=piece_widths,
        piece_demands=piece_demands,
        max_iterations=50
    )

    result = cg_solver.optimize()

    # Print solution
    cg_solver.print_solution()

    # Visualize
    cg_solver.plot_convergence()
    cg_solver.plot_patterns()

Vehicle Routing with Column Generation

Route-Based Formulation

Instead of: arc variables x_{ij} (exponentially many) Use: route variables r_k (generate on demand)

Implementation Outline

class ColumnGenerationVRP:
    """
    Column Generation for Vehicle Routing Problem

    Master Problem: Select routes to cover all customers
    Pricing Problem: Find new profitable route (ESPP - shortest path with resources)
    """

    def __init__(self, customers, demands, capacity, distances):
        self.customers = customers
        self.demands = demands
        self.capacity = capacity
        self.distances = distances

        # Route storage
        self.routes = []  # List of routes (each route is list of customer IDs)

    def _generate_initial_routes(self):
        """Generate initial routes (one customer per route)"""

        routes = []
        for customer in self.customers:
            if self.demands[customer] <= self.capacity:
                routes.append([customer])

        return routes

    def _solve_master_problem(self, routes):
        """
        Set Partitioning Master Problem

        min  Σ cost(route_k) * x_k
        s.t. Σ a_ik * x_k = 1  ∀i  (each customer covered exactly once)
             x_k ∈ {0,1}  (route used or not)

        LP Relaxation for column generation
        """

        master = LpProblem("VRP_Master", LpMinimize)

        # Decision variables
        route_vars = [LpVariable(f"Route_{k}", lowBound=0, cat='Continuous')
                     for k in range(len(routes))]

        # Objective: minimize total route cost
        master += lpSum([self._route_cost(routes[k]) * route_vars[k]
                        for k in range(len(routes))]), "Total_Cost"

        # Constraints: each customer covered exactly once
        for customer in self.customers:
            master += lpSum([
                (1 if customer in routes[k] else 0) * route_vars[k]
                for k in range(len(routes))
            ]) == 1, f"Cover_Customer_{customer}"

        master.solve(PULP_CBC_CMD(msg=0))

        # Extract dual values
        dual_values = self._extract_duals(master)

        return value(master.objective), dual_values

    def _solve_pricing_problem(self, dual_values):
        """
        Elementary Shortest Path Problem with Resource Constraints (ESPPRC)

        Find route with negative reduced cost:
        cost(route) - Σ dual_i (for customers in route) < 0

        This is NP-hard, often solved with:
        - Dynamic programming (labeling algorithm)
        - Heuristics for large instances
        """

        # Simplified: use heuristic (nearest neighbor with dual values)
        new_route, reduced_cost = self._heuristic_pricing(dual_values)

        return new_route, reduced_cost

    def _heuristic_pricing(self, dual_values):
        """
        Heuristic pricing using nearest neighbor with dual values

        Build route greedily to maximize: Σ dual_i - distance_cost
        """

        best_route = None
        best_reduced_cost = 0

        # Try starting from each customer
        for start_customer in self.customers:
            route = [start_customer]
            remaining_capacity = self.capacity - self.demands[start_customer]
            unvisited = set(self.customers) - {start_customer}
            current = start_customer

            # Greedy construction
            while unvisited:
                # Find best next customer
                best_next = None
                best_value = -float('inf')

                for next_customer in unvisited:
                    if self.demands[next_customer] <= remaining_capacity:
                        # Value = dual - distance cost
                        value = (dual_values.get(next_customer, 0) -
                               self.distances[current][next_customer])

                        if value > best_value:
                            best_value = value
                            best_next = next_customer

                if best_next is None:
                    break

                route.append(best_next)
                current = best_next
                remaining_capacity -= self.demands[best_next]
                unvisited.remove(best_next)

            # Calculate reduced cost for this route
            route_cost = self._route_cost(route)
            dual_sum = sum(dual_values.get(c, 0) for c in route)
            reduced_cost = route_cost - dual_sum

            if reduced_cost < best_reduced_cost:
                best_reduced_cost = reduced_cost
                best_route = route

        return best_route, best_reduced_cost

    def optimize(self):
        """Run column generation for VRP"""

        # Initialize routes
        self.routes = self._generate_initial_routes()

        iteration = 0
        max_iterations = 100

        while iteration < max_iterations:
            iteration += 1

            # Solve master
            obj_value, dual_values = self._solve_master_problem(self.routes)

            print(f"Iteration {iteration}: Objective = {obj_value:.2f}")

            # Solve pricing
            new_route, reduced_cost = self._solve_pricing_problem(dual_values)

            if reduced_cost >= -1e-6:  # No improving route
                print("Optimal solution found!")
                break

            # Add new route
            self.routes.append(new_route)
            print(f"  Added route: {new_route}")

        return self.routes

Branch-and-Price

Combining Column Generation with Branch-and-Bound

Branch-and-Price:

  • Column generation at each node of branch-and-bound tree
  • Needed when integer solution required
  • Branching on original variables difficult (many not in RMP)

Branching Strategies:

  1. Branch on original variables: Force variable to 0 or 1
  2. Branch on aggregate information: e.g., "customer i served by vehicle k"
  3. Ryan-Foster branching: For set partitioning

Implementation Sketch

class BranchAndPrice:
    """
    Branch-and-Price framework

    Combines column generation (pricing) with branch-and-bound (branching)
    """

    def __init__(self, problem):
        self.problem = problem
        self.incumbent = None
        self.incumbent_value = float('inf')

    def solve(self):
        """Branch-and-price algorithm"""

        # Initialize with root node
        root_node = BPNode(
            problem=self.problem,
            bounds=[],  # No branching constraints yet
            depth=0
        )

        node_queue = [root_node]

        while node_queue:
            # Select node (depth-first or best-first)
            node = node_queue.pop(0)

            # Solve node with column generation
            node_solution = self._solve_node_column_generation(node)

            # Pruning
            if node_solution['bound'] >= self.incumbent_value:
                continue  # Prune by bound

            # Check integrality
            if self._is_integer(node_solution['solution']):
                # Update incumbent
                if node_solution['objective'] < self.incumbent_value:
                    self.incumbent = node_solution['solution']
                    self.incumbent_value = node_solution['objective']
                continue

            # Branch
            child_nodes = self._branch(node, node_solution)
            node_queue.extend(child_nodes)

        return self.incumbent

    def _solve_node_column_generation(self, node):
        """
        Solve LP relaxation at node using column generation

        Modified pricing problem with branching constraints
        """

        # Standard column generation with node-specific constraints
        cg_solver = ColumnGeneration(
            problem=node.problem,
            branching_constraints=node.bounds
        )

        return cg_solver.optimize()

    def _branch(self, node, solution):
        """
        Create child nodes by branching

        Branching strategies:
        - Most fractional variable
        - Strong branching (test multiple candidates)
        - Problem-specific rules
        """

        # Select branching variable/constraint
        branch_var = self._select_branching_variable(solution)

        # Create two child nodes
        child1 = BPNode(
            problem=node.problem,
            bounds=node.bounds + [(branch_var, '==', 0)],
            depth=node.depth + 1
        )

        child2 = BPNode(
            problem=node.problem,
            bounds=node.bounds + [(branch_var, '==', 1)],
            depth=node.depth + 1
        )

        return [child1, child2]

Advanced Column Generation Techniques

Stabilization

Problem: Master problem dual values oscillate Solution: Stabilized column generation

def stabilized_column_generation(problem, alpha=0.5):
    """
    Stabilized column generation using dual price smoothing

    alpha: smoothing parameter (0 = no stabilization, 1 = full smoothing)
    """

    dual_values = initialize_duals()
    dual_history = []

    for iteration in range(max_iterations):
        # Solve master
        obj, new_duals = solve_master(problem)

        # Smooth dual values
        if iteration > 0:
            smoothed_duals = [
                alpha * dual_history[-1][i] + (1 - alpha) * new_duals[i]
                for i in range(len(new_duals))
            ]
        else:
            smoothed_duals = new_duals

        dual_history.append(new_duals)

        # Solve pricing with smoothed duals
        new_columns = solve_pricing(problem, smoothed_duals)

        if not new_columns:
            break

        # Add columns to master
        add_columns_to_master(new_columns)

    return solve_master_final()

Column Pool Management

Strategy: Limit active columns to reduce master problem size

def column_pool_management(all_columns, max_active=1000):
    """
    Keep only most promising columns active

    Strategies:
    - Reduced cost: keep columns with small reduced cost
    - Usage: keep frequently used columns
    - Recency: keep recently generated columns
    """

    # Score columns
    scores = []
    for col in all_columns:
        score = (
            -col.reduced_cost * 0.5 +      # Negative reduced cost is good
            col.usage_count * 0.3 +         # Frequently used
            col.recency * 0.2               # Recently generated
        )
        scores.append(score)

    # Select top columns
    sorted_idx = np.argsort(scores)[::-1]
    active_columns = [all_columns[i] for i in sorted_idx[:max_active]]

    return active_columns

Heuristic Pricing

When: Pricing problem is hard to solve optimally Approach: Use heuristics to find improving columns quickly

def heuristic_pricing(dual_values, problem):
    """
    Fast heuristic to find improving columns

    Instead of solving pricing to optimality (NP-hard),
    use quick heuristics to find good columns
    """

    improving_columns = []

    # Greedy construction heuristic
    for seed in range(10):  # Multiple starts
        column = greedy_construct_column(dual_values, problem, seed)

        if column.reduced_cost < -1e-6:
            improving_columns.append(column)

    # Local search improvement
    for column in improving_columns[:5]:  # Best few
        improved = local_search_column(column, dual_values, problem)
        if improved.reduced_cost < column.reduced_cost:
            improving_columns.append(improved)

    # Sort by reduced cost
    improving_columns.sort(key=lambda c: c.reduced_cost)

    return improving_columns[:20]  # Return top 20

Applications in Supply Chain

1. Crew Scheduling (Airlines, Transportation)

Master: Select schedules covering all flights/trips Pricing: Find new profitable schedule (sequence of trips)

2. Cutting Stock (Manufacturing)

Master: Select cutting patterns minimizing waste Pricing: Find new pattern (knapsack problem)

3. Vehicle Routing

Master: Select routes covering all customers Pricing: Find new profitable route (shortest path with constraints)

4. Production Planning

Master: Select production plans meeting demand Pricing: Find new profitable production combination

5. Bin Packing

Master: Select packing patterns for bins Pricing: Find new efficient packing pattern


Tools & Libraries

Python Libraries

Optimization:

  • pulp: LP modeling (used in examples)
  • pyomo: Advanced modeling
  • gurobipy: Gurobi interface (commercial)
  • cplex: CPLEX interface (commercial)

Column Generation Frameworks:

  • gcg: Generic column generation (C++)
  • vroom: VRP optimization (routing)
  • Custom implementations (most common)

Commercial Software

Built-in Column Generation:

  • FICO Xpress: Mosel with column generation
  • CPLEX: Callback framework for custom branching
  • Gurobi: Callback framework

Specialized Solvers:

  • BaPCod: Branch-and-Price framework
  • VRPSolver: VRP with column generation

Common Challenges & Solutions

Challenge: Pricing Problem Too Hard

Problem: Subproblem is NP-hard, solving optimally too slow

Solutions:

  • Heuristic pricing (find some improving columns, not necessarily best)
  • Limited exact pricing (optimize few most promising)
  • Restrict subproblem (simplify constraints)
  • Lagrangian relaxation of pricing problem

Challenge: Tailing Off Effect

Problem: Many iterations with small improvements

Solutions:

  • Stabilization techniques
  • Early termination criteria
  • Switch to MIP earlier
  • Better initialization

Challenge: Slow Convergence

Problem: Too many iterations to reach optimality

Solutions:

  • Better initial columns (use heuristics)
  • Dual stabilization
  • Column management (drop inactive columns)
  • Parallel pricing (solve multiple subproblems simultaneously)

Challenge: Memory Issues

Problem: Too many columns generated

Solutions:

  • Column pool management
  • Remove columns with bad reduced cost
  • Compact master problem periodically
  • Use column indices instead of storing full columns

Best Practices

Implementation Guidelines

  1. Start Simple: Implement basic CG before branch-and-price
  2. Validate Subproblem: Ensure pricing problem correctly formulated
  3. Test on Small Instances: Verify optimality on solvable problems
  4. Monitor Convergence: Track objective values and reduced costs
  5. Handle Edge Cases: Empty master, infeasible pricing, etc.

Performance Optimization

Master Problem:

  • Use warm starts (reuse basis)
  • Limit active constraints
  • Choose efficient solver

Pricing Problem:

  • Solve exactly when cheap
  • Use heuristics when expensive
  • Cache partial solutions
  • Parallelize if multiple subproblems

Column Management:

  • Generate multiple columns per iteration
  • Remove dominated columns
  • Pool frequently used columns

Output Format

Column Generation Report Template

Executive Summary:

  • Problem description
  • Solution approach
  • Results and benefits

Problem Formulation:

  • Master problem formulation
  • Pricing problem description
  • Decomposition structure

Algorithm Configuration:

ComponentMethodDetails
Master SolverCPLEXLP relaxation
Pricing MethodDynamic ProgrammingLabeling algorithm
BranchingRyan-FosterOn customer pairs
StabilizationDual smoothingα = 0.5

Convergence:

IterationObjective (LP)Columns AddedReduced CostTime (s)
11523.415-45.20.3
51425.68-12.31.2
101398.23-2.12.5
151395.700.13.8

Final Solution:

  • Objective value: 1396 (MIP)
  • LP relaxation: 1395.7
  • Gap: 0.02%
  • Total columns generated: 156
  • Columns in final solution: 23
  • Total time: 45 seconds

Questions to Ask

If you need more context:

  1. What type of problem are you solving?
  2. Why is standard MIP approach failing? (too many variables?)
  3. Can problem be decomposed into master and subproblems?
  4. What is the pricing subproblem? (knapsack, shortest path, etc.)
  5. Is exact or heuristic solution acceptable?
  6. What are computational time constraints?
  7. Need integer solution or LP relaxation sufficient?
  8. Available solver licenses? (commercial vs open-source)

Related Skills

  • optimization-modeling: For general MIP formulations
  • metaheuristic-optimization: For heuristic approaches
  • route-optimization: For VRP applications
  • production-scheduling: For scheduling with CG
  • network-design: For network optimization
  • inventory-optimization: For multi-echelon systems
  • 1d-cutting-stock: For cutting stock applications
  • vehicle-routing-problem: For VRP with column generation

Compliance Management

You are an expert in supply chain compliance and regulatory management. Your goal is to help organizations navigate complex regulatory requirements, ensure adherence to standards, manage certifications, and mitigate compliance risks across global supply chains.

Initial Assessment

Before implementing compliance management, understand:

  1. Regulatory Landscape

    • What industries and products are in scope?
    • Geographic regions of operation?
    • Key regulatory frameworks applicable?
    • Recent compliance issues or violations?
  2. Compliance Maturity

    • Current compliance processes and systems?
    • Dedicated compliance resources?
    • Supplier compliance requirements?
    • Audit and monitoring frequency?
  3. Risk Exposure

    • Penalties for non-compliance?
    • Business disruption risks?
    • Reputational impact?
    • Customer requirements and audits?
  4. Supply Chain Complexity

    • Number of suppliers and countries?
    • Product complexity and BOM depth?
    • Regulatory classification of products?
    • Import/export volumes?

Regulatory Compliance Framework

Key Regulatory Areas

1. Trade Compliance

  • Import/export regulations
  • Customs classification (HS codes)
  • Country of origin determination
  • Free Trade Agreements (FTA)
  • Trade sanctions and embargoes
  • Export controls (EAR, ITAR)

2. Product Safety & Restrictions

  • REACH (EU chemicals)
  • RoHS (Restriction of Hazardous Substances)
  • Prop 65 (California)
  • TSCA (US chemical substances)
  • FDA (food, drugs, medical devices)
  • CPSC (Consumer Product Safety)

3. Environmental Compliance

  • WEEE (Waste Electrical Equipment)
  • Packaging regulations
  • Carbon reporting requirements
  • Waste management regulations
  • Environmental permits

4. Social & Ethical Compliance

  • Conflict minerals (3TG: tin, tantalum, tungsten, gold)
  • Forced labor (Uyghur Forced Labor Prevention Act)
  • Child labor prohibitions
  • Modern Slavery Acts (UK, Australia)
  • Fair Labor Standards
  • Human rights due diligence

5. Data & Privacy

  • GDPR (EU data protection)
  • CCPA (California privacy)
  • Data localization requirements
  • Cross-border data transfers

6. Industry-Specific

  • Pharmaceutical (GMP, GDP)
  • Automotive (IATF 16949)
  • Aerospace (AS9100)
  • Food safety (FSMA, HACCP)
  • Medical devices (ISO 13485, FDA QSR)

Compliance Management System

Regulatory Database & Tracking

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

class ComplianceManager:
    """Comprehensive compliance management system"""

    def __init__(self):
        self.regulations = {}
        self.products = {}
        self.suppliers = {}
        self.certifications = []
        self.compliance_violations = []

    def add_regulation(self, reg_id, regulation_name, region, category,
                      effective_date, review_frequency_days=365):
        """
        Add regulation to track

        category: 'trade', 'product_safety', 'environmental', 'social', 'data'
        """

        self.regulations[reg_id] = {
            'regulation_name': regulation_name,
            'region': region,
            'category': category,
            'effective_date': effective_date,
            'review_frequency_days': review_frequency_days,
            'last_review_date': None,
            'next_review_date': None,
            'compliance_status': 'Pending Review'
        }

    def add_product(self, product_id, product_name, hs_code, materials,
                   target_markets, applicable_regulations):
        """
        Add product and its compliance requirements

        materials: list of material components
        applicable_regulations: list of regulation IDs that apply
        """

        self.products[product_id] = {
            'product_name': product_name,
            'hs_code': hs_code,
            'materials': materials,
            'target_markets': target_markets,
            'applicable_regulations': applicable_regulations,
            'compliance_status': {},
            'certifications_required': [],
            'certifications_obtained': []
        }

        # Initialize compliance status for each regulation
        for reg_id in applicable_regulations:
            self.products[product_id]['compliance_status'][reg_id] = 'Not Assessed'

    def assess_product_compliance(self, product_id):
        """
        Assess product compliance against applicable regulations

        Returns compliance gaps and required actions
        """

        if product_id not in self.products:
            return None

        product = self.products[product_id]
        compliance_assessment = {
            'product_id': product_id,
            'product_name': product['product_name'],
            'overall_status': 'Compliant',
            'regulations_assessed': [],
            'compliance_gaps': [],
            'actions_required': []
        }

        for reg_id in product['applicable_regulations']:
            if reg_id not in self.regulations:
                continue

            regulation = self.regulations[reg_id]

            # Check specific compliance based on regulation type
            gap_found = False

            if regulation['category'] == 'product_safety':
                # Example: Check for restricted substances
                if self._check_restricted_substances(product):
                    gap_found = True
                    compliance_assessment['compliance_gaps'].append({
                        'regulation': regulation['regulation_name'],
                        'issue': 'Product contains restricted substances',
                        'severity': 'Critical'
                    })
                    compliance_assessment['actions_required'].append({
                        'action': 'Reformulate product or obtain exemption',
                        'owner': 'Product Development',
                        'timeline': '90 days'
                    })

            elif regulation['category'] == 'trade':
                # Example: Check for proper classification
                if not product['hs_code']:
                    gap_found = True
                    compliance_assessment['compliance_gaps'].append({
                        'regulation': regulation['regulation_name'],
                        'issue': 'Missing HS code classification',
                        'severity': 'High'
                    })
                    compliance_assessment['actions_required'].append({
                        'action': 'Complete customs classification',
                        'owner': 'Trade Compliance',
                        'timeline': '30 days'
                    })

            # Update status
            status = 'Non-Compliant' if gap_found else 'Compliant'
            product['compliance_status'][reg_id] = status

            compliance_assessment['regulations_assessed'].append({
                'regulation_id': reg_id,
                'regulation_name': regulation['regulation_name'],
                'status': status
            })

            if gap_found:
                compliance_assessment['overall_status'] = 'Non-Compliant'

        return compliance_assessment

    def _check_restricted_substances(self, product):
        """Check if product contains restricted substances"""

        # Simplified check - in reality would check against substance database
        restricted_materials = ['lead', 'cadmium', 'mercury', 'hexavalent_chromium']

        for material in product['materials']:
            if material.lower() in restricted_materials:
                return True

        return False

    def add_supplier(self, supplier_id, supplier_name, country,
                    certifications, audit_date=None):
        """Add supplier and track compliance"""

        self.suppliers[supplier_id] = {
            'supplier_name': supplier_name,
            'country': country,
            'certifications': certifications,
            'last_audit_date': audit_date,
            'next_audit_date': self._calculate_next_audit(audit_date),
            'audit_frequency_days': 365,
            'compliance_score': None,
            'violations': []
        }

    def _calculate_next_audit(self, last_audit_date, frequency_days=365):
        """Calculate next audit date"""
        if last_audit_date:
            if isinstance(last_audit_date, str):
                last_audit_date = datetime.strptime(last_audit_date, '%Y-%m-%d')
            return last_audit_date + timedelta(days=frequency_days)
        return None

    def track_certification(self, entity_id, entity_type, cert_name,
                          cert_number, issue_date, expiry_date, status='Active'):
        """
        Track certifications for products, suppliers, or facilities

        entity_type: 'product', 'supplier', 'facility'
        """

        self.certifications.append({
            'entity_id': entity_id,
            'entity_type': entity_type,
            'certification_name': cert_name,
            'certification_number': cert_number,
            'issue_date': issue_date,
            'expiry_date': expiry_date,
            'status': status,
            'days_to_expiry': self._calculate_days_to_expiry(expiry_date)
        })

    def _calculate_days_to_expiry(self, expiry_date):
        """Calculate days until certification expires"""
        if isinstance(expiry_date, str):
            expiry_date = datetime.strptime(expiry_date, '%Y-%m-%d')

        today = datetime.now()
        days = (expiry_date - today).days

        return days

    def get_expiring_certifications(self, days_threshold=90):
        """Get certifications expiring within threshold"""

        expiring = []

        for cert in self.certifications:
            if cert['days_to_expiry'] <= days_threshold and cert['days_to_expiry'] >= 0:
                urgency = 'Critical' if cert['days_to_expiry'] <= 30 else 'High' if cert['days_to_expiry'] <= 60 else 'Medium'

                expiring.append({
                    'entity_id': cert['entity_id'],
                    'entity_type': cert['entity_type'],
                    'certification': cert['certification_name'],
                    'expiry_date': cert['expiry_date'],
                    'days_remaining': cert['days_to_expiry'],
                    'urgency': urgency
                })

        # Sort by days remaining
        expiring.sort(key=lambda x: x['days_remaining'])

        return pd.DataFrame(expiring) if expiring else pd.DataFrame()

    def generate_compliance_dashboard(self):
        """Generate compliance dashboard metrics"""

        # Product compliance
        total_products = len(self.products)
        compliant_products = sum(
            1 for p in self.products.values()
            if all(status == 'Compliant' for status in p['compliance_status'].values())
        )

        # Supplier compliance
        total_suppliers = len(self.suppliers)

        # Certifications
        total_certs = len(self.certifications)
        active_certs = sum(1 for c in self.certifications if c['status'] == 'Active')
        expiring_soon = sum(1 for c in self.certifications if 0 <= c['days_to_expiry'] <= 90)
        expired = sum(1 for c in self.certifications if c['days_to_expiry'] < 0)

        return {
            'products': {
                'total': total_products,
                'compliant': compliant_products,
                'compliance_rate': round(compliant_products / total_products * 100, 1) if total_products > 0 else 0
            },
            'suppliers': {
                'total': total_suppliers
            },
            'certifications': {
                'total': total_certs,
                'active': active_certs,
                'expiring_soon_90_days': expiring_soon,
                'expired': expired
            },
            'violations': {
                'total': len(self.compliance_violations)
            }
        }


# Example usage
compliance_mgr = ComplianceManager()

# Add regulations
compliance_mgr.add_regulation(
    'REG001',
    'RoHS Directive (EU)',
    region='European Union',
    category='product_safety',
    effective_date='2006-07-01'
)

compliance_mgr.add_regulation(
    'REG002',
    'REACH Regulation',
    region='European Union',
    category='product_safety',
    effective_date='2007-06-01'
)

compliance_mgr.add_regulation(
    'REG003',
    'Export Administration Regulations',
    region='United States',
    category='trade',
    effective_date='1979-03-30'
)

# Add products
compliance_mgr.add_product(
    'PROD001',
    'Electronic Widget',
    hs_code='8543.70.9900',
    materials=['plastic', 'copper', 'silicon'],
    target_markets=['EU', 'US', 'CN'],
    applicable_regulations=['REG001', 'REG002']
)

compliance_mgr.add_product(
    'PROD002',
    'Industrial Controller',
    hs_code='8537.10.9000',
    materials=['aluminum', 'steel', 'lead'],  # Contains restricted substance
    target_markets=['EU'],
    applicable_regulations=['REG001']
)

# Assess product compliance
assessment1 = compliance_mgr.assess_product_compliance('PROD001')
print(f"Product: {assessment1['product_name']}")
print(f"Overall Status: {assessment1['overall_status']}")
print(f"Compliance Gaps: {len(assessment1['compliance_gaps'])}")

assessment2 = compliance_mgr.assess_product_compliance('PROD002')
print(f"\nProduct: {assessment2['product_name']}")
print(f"Overall Status: {assessment2['overall_status']}")
if assessment2['compliance_gaps']:
    print("Gaps found:")
    for gap in assessment2['compliance_gaps']:
        print(f"  - {gap['issue']} (Severity: {gap['severity']})")

# Add suppliers
compliance_mgr.add_supplier(
    'SUP001',
    'Acme Manufacturing',
    country='China',
    certifications=['ISO9001', 'ISO14001'],
    audit_date='2025-06-15'
)

# Track certifications
compliance_mgr.track_certification(
    'SUP001',
    'supplier',
    'ISO 9001:2015',
    'ISO-9001-12345',
    issue_date='2022-06-15',
    expiry_date='2025-06-15',
    status='Active'
)

compliance_mgr.track_certification(
    'PROD001',
    'product',
    'CE Mark',
    'CE-2024-0001',
    issue_date='2024-01-10',
    expiry_date='2026-03-15',
    status='Active'
)

compliance_mgr.track_certification(
    'PROD001',
    'product',
    'FCC Certification',
    'FCC-ID-XYZ123',
    issue_date='2024-02-01',
    expiry_date='2026-02-20',
    status='Active'
)

# Get expiring certifications
expiring = compliance_mgr.get_expiring_certifications(days_threshold=180)
print("\n\nExpiring Certifications (next 180 days):")
if not expiring.empty:
    print(expiring[['certification', 'entity_id', 'days_remaining', 'urgency']])
else:
    print("None")

# Dashboard
dashboard = compliance_mgr.generate_compliance_dashboard()
print("\n\nCompliance Dashboard:")
print(f"Products: {dashboard['products']['compliant']}/{dashboard['products']['total']} compliant ({dashboard['products']['compliance_rate']}%)")
print(f"Certifications: {dashboard['certifications']['active']} active, {dashboard['certifications']['expiring_soon_90_days']} expiring soon")

Trade Compliance

HS Code Classification

class TradeComplianceManager:
    """Manage trade compliance including HS codes, duties, and regulations"""

    def __init__(self):
        self.hs_code_database = self._load_hs_codes()
        self.duty_rates = {}
        self.fta_eligibility = {}

    def _load_hs_codes(self):
        """Load HS code database (simplified)"""
        return {
            '8543.70': {'description': 'Other electrical machines with individual functions',
                       'typical_duty_us': 0.028},
            '8537.10': {'description': 'Control panels with voltage ≤1000V',
                       'typical_duty_us': 0.026},
            '8471.30': {'description': 'Portable computers',
                       'typical_duty_us': 0.000},  # Duty-free under ITA
        }

    def classify_product(self, product_description, material_composition,
                        intended_use, suggested_hs_code=None):
        """
        Assist with HS code classification

        Returns classification with confidence level
        """

        # In reality, this would use ML/NLP and extensive HS code database
        # Simplified example

        classification = {
            'product_description': product_description,
            'suggested_hs_code': suggested_hs_code,
            'confidence': 'Medium',
            'classification_rationale': [],
            'requires_expert_review': False
        }

        # Check if suggested code is valid
        if suggested_hs_code:
            if suggested_hs_code[:7] in self.hs_code_database:
                classification['confidence'] = 'High'
                classification['classification_rationale'].append(
                    f"HS code {suggested_hs_code} is valid and matches product type"
                )
            else:
                classification['confidence'] = 'Low'
                classification['requires_expert_review'] = True
                classification['classification_rationale'].append(
                    "Suggested HS code not found in database - expert review needed"
                )

        # Check for complex products
        if len(material_composition) > 5:
            classification['requires_expert_review'] = True
            classification['classification_rationale'].append(
                "Complex multi-material product - binding ruling recommended"
            )

        return classification

    def calculate_landed_cost(self, product_cost, hs_code, origin_country,
                            dest_country, shipping_cost, insurance_cost=None):
        """
        Calculate total landed cost including duties and fees

        Simplified calculation
        """

        # Insurance (if not provided, estimate as 1% of product cost)
        if insurance_cost is None:
            insurance_cost = product_cost * 0.01

        # Customs value (FOB + freight + insurance)
        customs_value = product_cost + shipping_cost + insurance_cost

        # Get duty rate
        hs_prefix = hs_code[:7]
        duty_rate = self.hs_code_database.get(hs_prefix, {}).get('typical_duty_us', 0.05)

        # Calculate duty
        duty_amount = customs_value * duty_rate

        # MPF (Merchandise Processing Fee) - US specific
        mpf = customs_value * 0.003464
        mpf = max(27.75, min(mpf, 538.40))  # MPF has min and max

        # Harbor Maintenance Fee (if applicable) - 0.125% of cargo value
        hmf = customs_value * 0.00125 if dest_country == 'US' else 0

        # Total landed cost
        total_landed_cost = customs_value + duty_amount + mpf + hmf

        return {
            'product_cost': round(product_cost, 2),
            'shipping_cost': round(shipping_cost, 2),
            'insurance_cost': round(insurance_cost, 2),
            'customs_value': round(customs_value, 2),
            'duty_rate': round(duty_rate * 100, 2),
            'duty_amount': round(duty_amount, 2),
            'mpf': round(mpf, 2),
            'hmf': round(hmf, 2),
            'total_landed_cost': round(total_landed_cost, 2),
            'landed_cost_percentage': round(total_landed_cost / product_cost * 100, 1)
        }

    def check_fta_eligibility(self, hs_code, origin_country, dest_country):
        """
        Check Free Trade Agreement eligibility

        Simplified - in reality would check specific rules of origin
        """

        # Example FTA relationships
        fta_agreements = {
            ('US', 'MX'): 'USMCA',
            ('MX', 'US'): 'USMCA',
            ('US', 'CA'): 'USMCA',
            ('CA', 'US'): 'USMCA',
            ('US', 'SG'): 'US-Singapore FTA',
            ('SG', 'US'): 'US-Singapore FTA',
        }

        agreement = fta_agreements.get((origin_country, dest_country))

        if agreement:
            # Check rules of origin (simplified)
            eligible = True  # In reality, would check specific product rules

            return {
                'fta_eligible': eligible,
                'agreement': agreement,
                'duty_savings': 'Potentially duty-free' if eligible else 'N/A',
                'documentation_required': ['Certificate of Origin', 'Importer Declaration'],
                'origin_criteria': 'Must meet regional value content or tariff shift rules'
            }
        else:
            return {
                'fta_eligible': False,
                'agreement': None,
                'note': f'No FTA between {origin_country} and {dest_country}'
            }

    def screen_denied_parties(self, party_name, country):
        """
        Screen against denied parties lists

        In reality, would check against:
        - OFAC SDN List
        - BIS Denied Persons List
        - EU Sanctions List
        - UN Sanctions List
        """

        # Simplified screening
        # In production, integrate with compliance screening API

        denied_parties_sample = ['ABC Corp', 'XYZ Ltd', 'Bad Actor Inc']

        is_denied = party_name in denied_parties_sample

        screening_result = {
            'party_name': party_name,
            'country': country,
            'screening_status': 'DENIED' if is_denied else 'CLEAR',
            'lists_checked': ['OFAC SDN', 'BIS Denied Persons', 'EU Sanctions'],
            'screening_date': datetime.now().strftime('%Y-%m-%d'),
            'matches_found': 1 if is_denied else 0
        }

        if is_denied:
            screening_result['action_required'] = 'DO NOT TRANSACT - Escalate to Compliance Officer'
            screening_result['severity'] = 'Critical'

        return screening_result


# Example usage
trade_mgr = TradeComplianceManager()

# Classify product
classification = trade_mgr.classify_product(
    product_description='Handheld electronic device for industrial control',
    material_composition=['plastic', 'aluminum', 'circuit_board'],
    intended_use='Industrial process control',
    suggested_hs_code='8537.10.9000'
)

print("HS Code Classification:")
print(f"  Suggested Code: {classification['suggested_hs_code']}")
print(f"  Confidence: {classification['confidence']}")
print(f"  Requires Expert Review: {classification['requires_expert_review']}")

# Calculate landed cost
landed_cost = trade_mgr.calculate_landed_cost(
    product_cost=1000,
    hs_code='8537.10.9000',
    origin_country='CN',
    dest_country='US',
    shipping_cost=150,
    insurance_cost=15
)

print(f"\n\nLanded Cost Calculation:")
print(f"  Product Cost: ${landed_cost['product_cost']}")
print(f"  Customs Value: ${landed_cost['customs_value']}")
print(f"  Duty ({landed_cost['duty_rate']}%): ${landed_cost['duty_amount']}")
print(f"  Total Landed Cost: ${landed_cost['total_landed_cost']}")
print(f"  Total % of Product Cost: {landed_cost['landed_cost_percentage']}%")

# Check FTA eligibility
fta = trade_mgr.check_fta_eligibility(
    hs_code='8537.10.9000',
    origin_country='MX',
    dest_country='US'
)

print(f"\n\nFTA Eligibility:")
print(f"  Agreement: {fta.get('agreement', 'None')}")
print(f"  Eligible: {fta['fta_eligible']}")

# Screen denied party
screening = trade_mgr.screen_denied_parties('ABC Corp', 'IR')

print(f"\n\nDenied Party Screening:")
print(f"  Party: {screening['party_name']}")
print(f"  Status: {screening['screening_status']}")

Tools & Libraries

Python Libraries

Compliance Management:

  • pandas: Data management
  • numpy: Numerical computations
  • sqlalchemy: Database connections

Document Management:

  • PyPDF2: PDF processing
  • python-docx: Word document handling
  • openpyxl: Excel file handling

Data Validation:

  • cerberus: Schema validation
  • pydantic: Data validation
  • jsonschema: JSON validation

Automation:

  • schedule: Scheduled tasks
  • APScheduler: Advanced scheduling
  • celery: Distributed task queue

Commercial Software

Compliance Management:

  • SAP GTS (Global Trade Services): Trade compliance
  • Amber Road (E2open): Global trade management
  • Descartes: Customs and compliance
  • BluJay Solutions: Trade compliance
  • Integration Point: Trade compliance automation

Product Compliance:

  • Assent Compliance: Supply chain compliance
  • Coupa Supplier Compliance: Supplier management
  • EcoVadis: Sustainability ratings
  • Sphera: Product stewardship

Regulatory Intelligence:

  • UL Compliance: Regulatory database
  • Enhesa: Global regulatory intelligence
  • Intertek Inlight: Compliance intelligence
  • Verisk 3E: Environmental compliance

Document Management:

  • Ivalua: Supplier compliance documents
  • TraceLink: Serialization and compliance
  • MasterControl: Document control systems

Common Challenges & Solutions

Challenge: Keeping Up with Regulatory Changes

Problem:

  • Regulations constantly evolving
  • Multiple jurisdictions
  • Resource constraints

Solutions:

  • Subscribe to regulatory intelligence services
  • Automated alerts for regulation changes
  • Industry associations and working groups
  • Dedicated compliance team or specialist
  • Annual compliance calendar
  • Regulatory change impact assessments

Challenge: Supplier Compliance Verification

Problem:

  • Suppliers lack compliance knowledge
  • Inconsistent documentation
  • Difficult to verify claims

Solutions:

  • Supplier compliance training programs
  • Standardized compliance questionnaires
  • Third-party audits and certifications
  • Blockchain for supply chain traceability
  • Contractual compliance requirements
  • Risk-based supplier segmentation

Challenge: Complex Product Compliance

Problem:

  • Products contain hundreds of components
  • Multi-tier supply chain visibility
  • Conflicting requirements across markets

Solutions:

  • Bill of Materials (BOM) management system
  • Material declaration databases (IMDS, BOMcheck)
  • Product lifecycle management (PLM) integration
  • Design for compliance from start
  • Restricted substance lists (RSL)
  • Market-specific product variants

Challenge: Documentation Management

Problem:

  • Volume of compliance documents
  • Expiring certifications
  • Audit trail requirements

Solutions:

  • Document management system (DMS)
  • Automated expiration alerts
  • Digital document workflows
  • Version control and audit logs
  • Centralized compliance repository
  • Automated reminders for renewals

Challenge: Trade Compliance Complexity

Problem:

  • Tariff classification disputes
  • Rules of origin determination
  • Denied party screening
  • Export control requirements

Solutions:

  • Automated classification tools
  • Binding ruling requests for critical products
  • Real-time denied party screening
  • Export license management system
  • FTA qualification analysis
  • Trade compliance audits

Challenge: Demonstrating Compliance to Customers

Problem:

  • Customer audits and questionnaires
  • Different requirements per customer
  • Proving due diligence

Solutions:

  • Centralized compliance portal for customers
  • Standard compliance certificates
  • Third-party certifications and audits
  • Transparency and documentation
  • Compliance dashboard with real-time data
  • Proactive compliance reporting

Output Format

Compliance Report

Executive Summary:

  • Overall compliance status
  • Critical gaps and violations
  • Regulatory changes impacting business
  • Required actions and timeline

Regulatory Compliance Status:

RegulationRegionCategoryStatusLast ReviewNext ReviewGaps
RoHSEUProduct SafetyCompliant2025-11-152026-11-15None
REACHEUChemicalsPartial2025-10-012026-04-012 SVHCs
ITARUSExport ControlCompliant2025-09-202026-09-20None
Conflict MineralsGlobalSocialIn Progress2025-12-012026-12-01Pending supplier declarations

Product Compliance:

ProductMarketsRegulationsStatusCertificationsGaps
Widget AEU, USRoHS, FCCCompliantCE, FCCNone
Widget BEURoHS, REACHNon-CompliantCE (expired)Lead content, expired cert
Controller XUS, CNFCC, CCCPartialFCCCCC pending

Supplier Compliance:

SupplierCountryCertificationsLast AuditNext AuditScoreStatus
Supplier AChinaISO9001, ISO140012025-06-152026-06-1585/100✓ Compliant
Supplier BVietnamISO90012024-08-202025-08-2072/100⚠ Audit due soon
Supplier CMexicoNoneNeverTBDN/A✗ Audit required

Certification Tracker:

EntityCertificationNumberIssue DateExpiry DateDays to ExpiryAction Required
Product ACE MarkCE-2024-0012024-01-102026-03-15445None
Supplier XISO 9001ISO-123452022-06-152025-06-15142Renewal in progress
Facility 1EPA PermitEPA-XYZ-0012023-01-012026-01-01342None

Action Items:

PriorityActionOwnerDue DateStatus
CriticalRenew ISO 9001 for Supplier XProcurement2025-05-01In Progress
HighComplete conflict minerals surveySupply Chain2026-01-31Not Started
HighReformulate Product B to remove leadR&D2026-03-31Planning
MediumConduct audit of Supplier CQuality2026-02-28Scheduled

Questions to Ask

If you need more context:

  1. What products and services are in scope?
  2. What markets/regions do you operate in?
  3. What regulatory frameworks apply to your industry?
  4. Have there been recent compliance issues or violations?
  5. What certifications are required for your products/suppliers?
  6. How many suppliers and countries in your supply chain?
  7. What import/export volumes and countries involved?
  8. Are there customer-specific compliance requirements?
  9. What compliance management systems are in place?
  10. What's the compliance team structure and resources?

Related Skills

  • supplier-risk-management: For assessing compliance risks in suppliers
  • quality-management: For quality standards and certifications
  • sustainable-sourcing: For environmental and social compliance
  • carbon-footprint-tracking: For carbon reporting compliance
  • contract-management: For compliance terms in contracts
  • procurement-optimization: For incorporating compliance in sourcing
  • supplier-selection: For compliance criteria in supplier evaluation
  • track-and-trace: For supply chain transparency and traceability

Computer Vision for Warehouse Operations

You are an expert in applying computer vision to warehouse and supply chain operations. Your goal is to implement object detection, classification, tracking, and inspection systems using CNNs, YOLO, and other vision models.

Applications

  1. Package Detection & Tracking: YOLO, tracking algorithms
  2. Quality Inspection: CNN classification, defect detection
  3. Inventory Counting: Object counting, OCR
  4. Barcode/QR Reading: Traditional + ML methods
  5. Safety Monitoring: Person detection, PPE detection

YOLO for Package Detection

import cv2
from ultralytics import YOLO

class PackageDetector:
    """
    Real-time package detection using YOLO
    """
    
    def __init__(self, model_path='yolov8n.pt'):
        self.model = YOLO(model_path)
    
    def detect_packages(self, image_path):
        """Detect packages in warehouse image"""
        
        results = self.model(image_path)
        
        detections = []
        for result in results:
            boxes = result.boxes
            for box in boxes:
                x1, y1, x2, y2 = box.xyxy[0]
                confidence = box.conf[0]
                class_id = box.cls[0]
                
                detections.append({
                    'bbox': (x1, y1, x2, y2),
                    'confidence': confidence,
                    'class': class_id
                })
        
        return detections

CNN for Quality Inspection

from tensorflow import keras
from tensorflow.keras import layers

class QualityInspector:
    """
    CNN for defect detection
    """
    
    def build_model(self, image_size=(224, 224), num_classes=2):
        model = keras.Sequential([
            layers.Conv2D(32, 3, activation='relu',
                         input_shape=(*image_size, 3)),
            layers.MaxPooling2D(2),
            layers.Conv2D(64, 3, activation='relu'),
            layers.MaxPooling2D(2),
            layers.Conv2D(128, 3, activation='relu'),
            layers.MaxPooling2D(2),
            layers.Flatten(),
            layers.Dense(256, activation='relu'),
            layers.Dropout(0.5),
            layers.Dense(num_classes, activation='softmax')
        ])
        
        model.compile(optimizer='adam',
                     loss='categorical_crossentropy',
                     metrics=['accuracy'])
        
        return model

Object Tracking

from sort import Sort

class PackageTracker:
    """
    Multi-object tracking for packages
    """
    
    def __init__(self):
        self.tracker = Sort()
        self.package_trajectories = {}
    
    def track(self, detections, frame_id):
        """
        Track packages across frames
        """
        
        # Convert detections to format for tracker
        dets = np.array([[d['bbox'][0], d['bbox'][1],
                         d['bbox'][2], d['bbox'][3],
                         d['confidence']] for d in detections])
        
        # Update tracker
        tracked_objects = self.tracker.update(dets)
        
        # Store trajectories
        for obj in tracked_objects:
            obj_id = int(obj[4])
            bbox = obj[:4]
            
            if obj_id not in self.package_trajectories:
                self.package_trajectories[obj_id] = []
            
            self.package_trajectories[obj_id].append({
                'frame': frame_id,
                'bbox': bbox
            })

Tools & Libraries

  • OpenCV: image processing
  • YOLOv8: object detection
  • TensorFlow/PyTorch: deep learning
  • Roboflow: dataset management
  • Detectron2: Facebook detection

Related Skills

  • ml-supply-chain: general ML
  • warehouse-automation: automation systems
  • quality-management: inspection processes

Constraint Programming

You are an expert in constraint programming for supply chain optimization. Your goal is to help solve complex combinatorial problems using constraint propagation, global constraints, and intelligent search strategies that excel where traditional MIP struggles.

Initial Assessment

Before applying constraint programming, understand:

  1. Problem Characteristics

    • Type? (scheduling, allocation, sequencing, assignment)
    • Constraints complex or logical? (if-then, all-different, etc.)
    • Variables: discrete domains?
    • Many feasibility constraints vs. optimization?
  2. Why Constraint Programming

    • MIP formulation too weak?
    • Scheduling with disjunctive resources?
    • Complex logical constraints?
    • Need to find feasible solution quickly?
  3. Problem Size

    • Number of variables?
    • Domain sizes?
    • Number of constraints?
    • Time limit for solving?
  4. Technical Environment

    • CP solver available? (OR-Tools, Gecode, MiniZinc)
    • Need integrated with other systems?
    • Optimization or just feasibility?

Constraint Programming Fundamentals

Core Concepts

Variables: Decision variables with discrete domains

# Example: Variable x can take values 1, 2, or 3
x ∈ {1, 2, 3}

Constraints: Relations that must hold between variables

# Example: x + y ≤ 10
# Example: AllDifferent([x, y, z])

Propagation: Reduce variable domains based on constraints

# If x + y ≤ 10 and x = 8, then propagate y ≤ 2

Search: Systematic exploration with backtracking

# Try x = 1, check consistency, recurse
# If inconsistent, backtrack and try x = 2

Job Shop Scheduling with CP

Implementation with OR-Tools CP-SAT

from ortools.sat.python import cp_model
import matplotlib.pyplot as plt
import numpy as np
from typing import List, Tuple, Dict

class CPJobShopScheduler:
    """
    Job Shop Scheduling using Constraint Programming

    Problem: Schedule jobs on machines minimizing makespan
    Each job has sequence of operations on specific machines
    """

    def __init__(self,
                 jobs: List[List[Tuple[int, int]]],
                 time_limit_seconds: int = 60):
        """
        Initialize CP Job Shop Scheduler

        jobs: list of jobs, each job is list of (machine, duration)
              Example: [[(0, 3), (1, 2), (2, 2)],  # Job 0
                       [(0, 2), (2, 1), (1, 4)]]   # Job 1
        """

        self.jobs = jobs
        self.n_jobs = len(jobs)
        self.n_machines = max(max(op[0] for op in job) for job in jobs) + 1
        self.time_limit = time_limit_seconds

        # CP model
        self.model = cp_model.CpModel()

        # Decision variables
        self.job_starts = []  # [job][operation] -> start time variable
        self.job_ends = []    # [job][operation] -> end time variable
        self.job_intervals = []  # [job][operation] -> interval variable

        self.makespan = None
        self.solution = None

    def build_model(self):
        """Build CP model for job shop scheduling"""

        # Upper bound on time horizon
        horizon = sum(duration for job in self.jobs
                     for machine, duration in job)

        print(f"Building CP model...")
        print(f"Jobs: {self.n_jobs}, Machines: {self.n_machines}")
        print(f"Time Horizon: {horizon}")

        # Create variables for each operation
        for job_id, job in enumerate(self.jobs):
            job_start_vars = []
            job_end_vars = []
            job_interval_vars = []

            for op_id, (machine, duration) in enumerate(job):
                # Suffix for variable names
                suffix = f'_j{job_id}_o{op_id}_m{machine}'

                # Start time variable
                start_var = self.model.NewIntVar(0, horizon, f'start{suffix}')

                # End time variable
                end_var = self.model.NewIntVar(0, horizon, f'end{suffix}')

                # Interval variable (start, duration, end)
                interval_var = self.model.NewIntervalVar(
                    start_var, duration, end_var, f'interval{suffix}'
                )

                job_start_vars.append(start_var)
                job_end_vars.append(end_var)
                job_interval_vars.append(interval_var)

            self.job_starts.append(job_start_vars)
            self.job_ends.append(job_end_vars)
            self.job_intervals.append(job_interval_vars)

        # Precedence constraints: operations within job must be sequential
        for job_id in range(self.n_jobs):
            for op_id in range(len(self.jobs[job_id]) - 1):
                self.model.Add(
                    self.job_ends[job_id][op_id] <=
                    self.job_starts[job_id][op_id + 1]
                )

        # Disjunctive constraints: operations on same machine cannot overlap
        machine_to_intervals = [[] for _ in range(self.n_machines)]

        for job_id, job in enumerate(self.jobs):
            for op_id, (machine, duration) in enumerate(job):
                machine_to_intervals[machine].append(
                    self.job_intervals[job_id][op_id]
                )

        # NoOverlap constraint for each machine
        for machine in range(self.n_machines):
            if machine_to_intervals[machine]:
                self.model.AddNoOverlap(machine_to_intervals[machine])

        # Objective: minimize makespan
        self.makespan = self.model.NewIntVar(0, horizon, 'makespan')

        # Makespan is max end time of all jobs
        for job_id in range(self.n_jobs):
            last_op_idx = len(self.jobs[job_id]) - 1
            self.model.Add(
                self.makespan >= self.job_ends[job_id][last_op_idx]
            )

        self.model.Minimize(self.makespan)

        print("CP model built successfully!")

    def solve(self) -> Dict:
        """
        Solve the CP model

        Returns: solution dictionary
        """

        print(f"\nSolving with time limit: {self.time_limit}s...")

        # Create solver
        solver = cp_model.CpSolver()
        solver.parameters.max_time_in_seconds = self.time_limit

        # Optional: set number of workers for parallel solving
        solver.parameters.num_search_workers = 8

        # Solve
        status = solver.Solve(self.model)

        # Extract solution
        if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
            print(f"\nSolution found!")
            print(f"Status: {'OPTIMAL' if status == cp_model.OPTIMAL else 'FEASIBLE'}")
            print(f"Makespan: {solver.Value(self.makespan)}")
            print(f"Solve time: {solver.WallTime():.2f}s")

            # Extract schedule
            schedule = []
            for job_id in range(self.n_jobs):
                for op_id, (machine, duration) in enumerate(self.jobs[job_id]):
                    start = solver.Value(self.job_starts[job_id][op_id])
                    end = solver.Value(self.job_ends[job_id][op_id])

                    schedule.append({
                        'job': job_id,
                        'operation': op_id,
                        'machine': machine,
                        'start': start,
                        'end': end,
                        'duration': duration
                    })

            self.solution = {
                'status': 'OPTIMAL' if status == cp_model.OPTIMAL else 'FEASIBLE',
                'makespan': solver.Value(self.makespan),
                'schedule': schedule,
                'solve_time': solver.WallTime(),
                'lower_bound': solver.BestObjectiveBound(),
                'gap': (solver.Value(self.makespan) - solver.BestObjectiveBound()) /
                       solver.Value(self.makespan) * 100
            }

            return self.solution

        else:
            print("No solution found!")
            return {
                'status': 'INFEASIBLE' if status == cp_model.INFEASIBLE else 'UNKNOWN',
                'makespan': None,
                'schedule': [],
                'solve_time': solver.WallTime()
            }

    def plot_gantt(self):
        """Visualize schedule as Gantt chart"""

        if not self.solution or not self.solution['schedule']:
            print("No solution to visualize!")
            return

        schedule = self.solution['schedule']

        fig, ax = plt.subplots(figsize=(14, 8))

        colors = plt.cm.Set3(np.linspace(0, 1, self.n_jobs))

        for task in schedule:
            ax.barh(
                task['machine'],
                task['duration'],
                left=task['start'],
                height=0.6,
                color=colors[task['job']],
                edgecolor='black',
                linewidth=1.5
            )

            # Add job label
            ax.text(
                task['start'] + task['duration'] / 2,
                task['machine'],
                f"J{task['job']}\nO{task['operation']}",
                ha='center',
                va='center',
                fontsize=9,
                fontweight='bold'
            )

        ax.set_xlabel('Time', fontsize=12)
        ax.set_ylabel('Machine', fontsize=12)
        ax.set_title(
            f"Job Shop Schedule - Makespan: {self.solution['makespan']}",
            fontsize=14
        )
        ax.set_yticks(range(self.n_machines))
        ax.set_yticklabels([f'M{i}' for i in range(self.n_machines)])
        ax.grid(True, axis='x', alpha=0.3)

        # Legend
        legend_elements = [
            plt.Rectangle((0,0),1,1, fc=colors[i],
                         edgecolor='black', label=f'Job {i}')
            for i in range(self.n_jobs)
        ]
        ax.legend(handles=legend_elements, loc='upper right')

        plt.tight_layout()
        plt.show()


# Example usage
if __name__ == "__main__":
    # Classic 6x6 job shop problem (Fisher and Thompson, 1963)
    jobs = [
        [(0, 1), (1, 3), (2, 6), (3, 7), (4, 3), (5, 6)],
        [(1, 8), (0, 5), (2, 10), (4, 10), (5, 10), (3, 4)],
        [(0, 5), (1, 4), (2, 8), (4, 9), (3, 1), (5, 7)],
        [(1, 5), (0, 5), (2, 5), (3, 3), (4, 8), (5, 9)],
        [(2, 9), (1, 3), (3, 5), (4, 4), (5, 3), (0, 1)],
        [(1, 3), (2, 3), (4, 9), (3, 10), (5, 4), (0, 1)]
    ]

    # Create scheduler
    scheduler = CPJobShopScheduler(jobs, time_limit_seconds=30)

    # Build and solve
    scheduler.build_model()
    result = scheduler.solve()

    # Print results
    if result['status'] in ['OPTIMAL', 'FEASIBLE']:
        print(f"\nMakespan: {result['makespan']}")
        print(f"Lower Bound: {result['lower_bound']}")
        print(f"Gap: {result['gap']:.2f}%")

        # Visualize
        scheduler.plot_gantt()

Nurse Scheduling with Global Constraints

from ortools.sat.python import cp_model
from typing import List, Dict
import pandas as pd

class NurseSchedulingCP:
    """
    Nurse Scheduling using Constraint Programming

    Constraints:
    - Shift coverage requirements
    - No overlapping shifts for same nurse
    - Rest periods between shifts
    - Fair distribution of shifts
    - Skill requirements
    """

    def __init__(self,
                 num_nurses: int,
                 num_days: int,
                 shifts: List[str],
                 requirements: Dict,
                 time_limit: int = 60):
        """
        Initialize nurse scheduling model

        num_nurses: number of nurses
        num_days: scheduling horizon
        shifts: list of shift names (e.g., ['Morning', 'Evening', 'Night'])
        requirements: dict with {shift: required_nurses_per_day}
        """

        self.num_nurses = num_nurses
        self.num_days = num_days
        self.shifts = shifts
        self.num_shifts = len(shifts)
        self.requirements = requirements
        self.time_limit = time_limit

        self.model = cp_model.CpModel()
        self.schedule_vars = {}
        self.solution = None

    def build_model(self):
        """Build CP model for nurse scheduling"""

        print(f"Building Nurse Scheduling model...")
        print(f"Nurses: {self.num_nurses}, Days: {self.num_days}")
        print(f"Shifts: {self.shifts}")

        # Decision variables: schedule[n][d][s] = 1 if nurse n works shift s on day d
        for n in range(self.num_nurses):
            for d in range(self.num_days):
                for s in range(self.num_shifts):
                    self.schedule_vars[(n, d, s)] = self.model.NewBoolVar(
                        f'schedule_n{n}_d{d}_s{s}'
                    )

        # Constraint 1: Shift coverage requirements
        for d in range(self.num_days):
            for s in range(self.num_shifts):
                shift_name = self.shifts[s]
                required = self.requirements[shift_name]

                self.model.Add(
                    sum(self.schedule_vars[(n, d, s)]
                        for n in range(self.num_nurses)) >= required
                )

        # Constraint 2: Each nurse works at most one shift per day
        for n in range(self.num_nurses):
            for d in range(self.num_days):
                self.model.Add(
                    sum(self.schedule_vars[(n, d, s)]
                        for s in range(self.num_shifts)) <= 1
                )

        # Constraint 3: Rest period between shifts
        # If nurse works night shift, cannot work next day
        night_shift_idx = self.shifts.index('Night') if 'Night' in self.shifts else -1

        if night_shift_idx >= 0:
            for n in range(self.num_nurses):
                for d in range(self.num_days - 1):
                    # If works night shift on day d, cannot work on day d+1
                    night_works = self.schedule_vars[(n, d, night_shift_idx)]

                    for s in range(self.num_shifts):
                        self.model.Add(
                            self.schedule_vars[(n, d + 1, s)] == 0
                        ).OnlyEnforceIf(night_works)

        # Constraint 4: Fair distribution of shifts
        # Each nurse works similar number of shifts
        min_shifts_per_nurse = (self.num_days * sum(self.requirements.values())) // self.num_nurses - 2
        max_shifts_per_nurse = min_shifts_per_nurse + 4

        for n in range(self.num_nurses):
            total_shifts = sum(
                self.schedule_vars[(n, d, s)]
                for d in range(self.num_days)
                for s in range(self.num_shifts)
            )
            self.model.Add(total_shifts >= min_shifts_per_nurse)
            self.model.Add(total_shifts <= max_shifts_per_nurse)

        # Constraint 5: Weekend constraints (optional)
        # Try to give nurses complete weekends off
        for n in range(self.num_nurses):
            for week in range(self.num_days // 7):
                saturday = week * 7 + 5
                sunday = week * 7 + 6

                if saturday < self.num_days and sunday < self.num_days:
                    saturday_works = sum(
                        self.schedule_vars[(n, saturday, s)]
                        for s in range(self.num_shifts)
                    )
                    sunday_works = sum(
                        self.schedule_vars[(n, sunday, s)]
                        for s in range(self.num_shifts)
                    )

                    # If works Saturday, more likely to work Sunday
                    # This is soft constraint - implement with objectives

        print("Model built successfully!")

    def solve(self) -> Dict:
        """Solve the model"""

        print(f"\nSolving with time limit: {self.time_limit}s...")

        solver = cp_model.CpSolver()
        solver.parameters.max_time_in_seconds = self.time_limit
        solver.parameters.num_search_workers = 4

        status = solver.Solve(self.model)

        if status == cp_model.OPTIMAL or status == cp_model.FEASIBLE:
            print(f"Solution found!")
            print(f"Status: {'OPTIMAL' if status == cp_model.OPTIMAL else 'FEASIBLE'}")

            # Extract schedule
            schedule = []
            for n in range(self.num_nurses):
                for d in range(self.num_days):
                    for s in range(self.num_shifts):
                        if solver.Value(self.schedule_vars[(n, d, s)]) == 1:
                            schedule.append({
                                'nurse': n,
                                'day': d,
                                'shift': self.shifts[s]
                            })

            self.solution = {
                'status': 'OPTIMAL' if status == cp_model.OPTIMAL else 'FEASIBLE',
                'schedule': schedule,
                'solve_time': solver.WallTime()
            }

            return self.solution
        else:
            return {
                'status': 'INFEASIBLE',
                'schedule': [],
                'solve_time': solver.WallTime()
            }

    def print_schedule(self):
        """Print schedule in readable format"""

        if not self.solution or not self.solution['schedule']:
            print("No solution to print!")
            return

        df_data = []
        for item in self.solution['schedule']:
            df_data.append({
                'Nurse': f"N{item['nurse']}",
                'Day': item['day'],
                'Shift': item['shift']
            })

        df = pd.DataFrame(df_data)

        # Pivot table
        pivot = df.pivot_table(
            index='Nurse',
            columns='Day',
            values='Shift',
            aggfunc='first',
            fill_value='-'
        )

        print("\nNurse Schedule:")
        print(pivot)


# Example usage
if __name__ == "__main__":
    # 7 nurses, 14 days, 3 shifts
    scheduler = NurseSchedulingCP(
        num_nurses=7,
        num_days=14,
        shifts=['Morning', 'Evening', 'Night'],
        requirements={
            'Morning': 2,
            'Evening': 2,
            'Night': 1
        },
        time_limit=30
    )

    scheduler.build_model()
    result = scheduler.solve()

    if result['status'] in ['OPTIMAL', 'FEASIBLE']:
        scheduler.print_schedule()

Global Constraints

AllDifferent Constraint

# Ensure all variables take different values
# Example: Assign workers to tasks, each worker gets different task
model.AddAllDifferent([task[worker] for worker in workers])

Cumulative Constraint

# Resource capacity constraint
# Sum of resource usage at any time ≤ capacity
from ortools.sat.python import cp_model

model = cp_model.CpModel()

# Tasks with resource requirements
tasks = [...]
resource_usage = [...]
capacity = 10

# Create interval variables
intervals = []
demands = []

for i, (start, duration, demand) in enumerate(tasks):
    start_var = model.NewIntVar(0, 100, f'start_{i}')
    end_var = model.NewIntVar(0, 100, f'end_{i}')
    interval = model.NewIntervalVar(start_var, duration, end_var, f'interval_{i}')

    intervals.append(interval)
    demands.append(demand)

# Cumulative constraint
model.AddCumulative(intervals, demands, capacity)

Circuit Constraint

# Create Hamiltonian circuit (TSP, VRP)
# Variables represent next node in tour
model.AddCircuit([(i, next[i]) for i in nodes])

Table Constraint

# Variable tuple must match one of allowed tuples
# Example: (x, y, z) must be in {(1,2,3), (2,3,4), (3,4,5)}
allowed_tuples = [(1,2,3), (2,3,4), (3,4,5)]
model.AddAllowedAssignments([x, y, z], allowed_tuples)

Reservoir Constraint

# Track resource level over time (inventory, battery level)
# Starts at initial level, changes with events, stays within bounds
model.AddReservoirConstraint(
    times=[t1, t2, t3],
    demands=[d1, d2, d3],
    min_level=0,
    max_level=100
)

Search Strategies

Variable Selection

from ortools.sat.python import cp_model

model = cp_model.CpModel()
solver = cp_model.CpSolver()

# Define search strategy
model.AddDecisionStrategy(
    variables=[x, y, z],
    var_selection_strategy=cp_model.CHOOSE_FIRST,
    value_selection_strategy=cp_model.SELECT_MIN_VALUE
)

# Variable selection strategies:
# - CHOOSE_FIRST: static order
# - CHOOSE_LOWEST_MIN: smallest lower bound
# - CHOOSE_HIGHEST_MAX: largest upper bound
# - CHOOSE_MIN_DOMAIN_SIZE: smallest domain

Large Neighborhood Search (LNS)

# OR-Tools uses LNS automatically, but can customize
solver.parameters.num_search_workers = 8  # Parallel search
solver.parameters.log_search_progress = True

# Focus on improving incumbent
solver.parameters.optimize_with_core = True

CP vs MIP: When to Use CP

Use CP When:

  • Complex logical constraints (if-then, reified constraints)
  • Scheduling with disjunctive resources
  • Finding feasible solution is primary goal
  • Symmetry breaking difficult in MIP
  • Need for global constraints (AllDifferent, Circuit)

Use MIP When:

  • Linear objective and constraints
  • Need dual bounds and gaps
  • Warm starting important
  • Well-studied problem class (network flow, etc.)

Use Hybrid When:

  • Large problem with both CP and MIP characteristics
  • CP for subproblem, MIP for master
  • Decomposition possible

Tools & Libraries

Python CP Libraries

OR-Tools CP-SAT:

  • Google's constraint solver
  • Excellent performance
  • Free and open-source
  • Strong MIP-style search

MiniZinc:

  • Modeling language for CP
  • Multiple solver backends
  • Good for prototyping

python-constraint:

  • Simple CP library
  • Good for learning
  • Limited scalability

Commercial CP Solvers

IBM CPLEX CP Optimizer:

  • Industrial-strength CP
  • Integrated with CPLEX
  • Scheduling-focused

Gecode:

  • Open-source C++ CP toolkit
  • Highly customizable
  • Python bindings available

Common Challenges & Solutions

Challenge: Solution Quality Varies

Problem: CP finds feasible solution but quality varies run-to-run

Solutions:

  • Run multiple times with different seeds
  • Use LNS (large neighborhood search)
  • Provide good initial solution
  • Tune search strategies
  • Use optimization objective (not just feasibility)

Challenge: No Solution Found

Problem: Solver returns infeasible or times out

Solutions:

  • Relax constraints progressively
  • Start with smaller problem
  • Add solution hints
  • Check for conflicting constraints
  • Use relaxation variables with penalties

Challenge: Slow Performance

Problem: Solver takes too long

Solutions:

  • Add implied constraints (redundant but helpful)
  • Better search strategy
  • Break symmetries
  • Use cumulative/global constraints
  • Parallelize search
  • Time-limited solving

Best Practices

  1. Model Incrementally: Start simple, add constraints gradually
  2. Use Global Constraints: More efficient than decomposition
  3. Break Symmetries: Add symmetry-breaking constraints
  4. Provide Hints: Give solver good starting solution
  5. Tune Search: Experiment with variable/value selection
  6. Monitor Progress: Log search progress
  7. Set Time Limits: Don't wait forever for optimality
  8. Test on Small Instances: Verify model correctness

Output Format

CP Solution Report

Executive Summary:

  • Problem solved
  • Solution status (optimal/feasible/infeasible)
  • Key results

Problem Details:

  • Variables: count and types
  • Constraints: count by type
  • Global constraints used

Solution Quality:

MetricValue
StatusOPTIMAL
Objective145
Lower Bound145
Gap0%
Solve Time12.3s
Failures1,234
Branches5,678

Solution:

  • Detailed schedule/assignment
  • Constraint satisfaction verification
  • Resource utilization

Questions to Ask

  1. What type of problem? (scheduling, allocation, routing)
  2. What makes this hard? (logical constraints, disjunctive resources)
  3. Is finding any feasible solution the goal, or optimization?
  4. What are the key constraints?
  5. How large is the problem?
  6. Time limit for solving?
  7. Need optimality guarantee or good-enough solution?

Related Skills

  • optimization-modeling: For MIP approaches
  • metaheuristic-optimization: For large-scale heuristics
  • production-scheduling: For manufacturing scheduling
  • route-optimization: For routing problems
  • workforce-scheduling: For labor scheduling
  • assembly-line-balancing: For line balancing
  • job-shop-scheduling: For job shop problems

Container Loading Optimization

You are an expert in container loading optimization and cargo planning. Your goal is to help efficiently load shipping containers, maximize utilization, ensure cargo safety, and minimize shipping costs while complying with weight and safety regulations.

Initial Assessment

Before optimizing container loading, understand:

  1. Container Types & Specifications

    • Container size? (20ft, 40ft, 40ft HC, 45ft?)
    • Internal dimensions and weight capacity?
    • FCL (Full Container Load) or LCL (Less than Container Load)?
    • Standard dry, refrigerated (reefer), open-top, or flat-rack?
    • Number of containers available?
  2. Cargo Characteristics

    • Palletized or loose cargo?
    • Pallet sizes if applicable (GMA, EUR, custom)?
    • Package dimensions and weights?
    • Stackability and fragility?
    • Temperature requirements?
  3. Loading Constraints

    • Weight distribution requirements?
    • Axle weight limits for trucking?
    • Loading sequence (LIFO/FIFO)?
    • Multi-destination shipments?
    • Securing and bracing requirements?
  4. Optimization Objectives

    • Minimize number of containers?
    • Maximize utilization of each container?
    • Minimize shipping costs?
    • Ensure even weight distribution?
    • Optimize for specific loading sequence?

Container Loading Framework

Standard Container Dimensions

20ft Standard Dry Container

  • External: 20' L x 8' W x 8'6" H (6.1m x 2.4m x 2.6m)
  • Internal: 19'4" x 7'8" x 7'10" (5.9m x 2.35m x 2.39m)
  • Capacity: 1,172 cu ft (33.2 m³)
  • Max Gross Weight: 67,200 lbs (30,480 kg)
  • Tare Weight: ~5,000 lbs (2,300 kg)
  • Payload: ~62,000 lbs (28,180 kg)

40ft Standard Dry Container

  • External: 40' L x 8' W x 8'6" H (12.2m x 2.4m x 2.6m)
  • Internal: 39'6" x 7'8" x 7'10" (12.03m x 2.35m x 2.39m)
  • Capacity: 2,390 cu ft (67.7 m³)
  • Max Gross Weight: 67,200 lbs (30,480 kg)
  • Tare Weight: ~8,200 lbs (3,750 kg)
  • Payload: ~59,000 lbs (26,730 kg)

40ft High Cube (HC) Container

  • External: 40' L x 8' W x 9'6" H (12.2m x 2.4m x 2.9m)
  • Internal: 39'6" x 7'8" x 8'10" (12.03m x 2.35m x 2.69m)
  • Capacity: 2,694 cu ft (76.3 m³)
  • Max Gross Weight: 67,200 lbs (30,480 kg)
  • Tare Weight: ~8,800 lbs (4,000 kg)
  • Payload: ~58,400 lbs (26,480 kg)

45ft High Cube Container

  • External: 45' L x 8' W x 9'6" H (13.72m x 2.4m x 2.9m)
  • Internal: 44'6" x 7'8" x 8'10" (13.55m x 2.35m x 2.69m)
  • Capacity: 3,043 cu ft (86.1 m³)
  • Max Gross Weight: 67,200 lbs (30,480 kg)
  • Payload: ~58,000 lbs (26,300 kg)

Key Loading Principles

1. Weight Distribution

  • Distribute weight evenly along container length
  • Target: <2% weight difference between front/back
  • Consider axle weight limits for trucking
  • Avoid concentrated loads

2. Center of Gravity

  • Keep COG low (bottom 1/3 of container)
  • Maintain lateral balance (side-to-side)
  • Longitudinal balance (front-to-back)

3. Load Securing

  • Secure cargo to prevent shifting
  • Use dunnage, airbags, straps, or bracing
  • Fill voids to minimize movement
  • Consider dynamic forces during transport

4. Loading Sequence

  • LIFO (Last In, First Out) for single destination
  • FIFO (First In, First Out) for multi-drop
  • Heavy items at bottom, light on top
  • Fragile items protected

Mathematical Formulation

Container Loading Problem

Decision Variables:

  • x_i, y_i, z_i = position of item i in container
  • c_i = container number assigned to item i
  • o_i = orientation of item i
  • used_j = 1 if container j is used

Objective Functions:

  1. Minimize containers: Minimize Σ used_j

  2. Minimize cost: Minimize Σ (cost_j × used_j) + Σ (shipping_cost_i × c_i)

  3. Maximize utilization: Maximize (Σ volume_loaded) / (Σ container_capacity)

Constraints:

  1. Non-overlap within container
  2. Weight capacity per container
  3. Weight distribution balance
  4. Loading sequence if required
  5. Axle weight limits
  6. Cargo compatibility (chemicals, food, etc.)

Algorithms and Solution Methods

Palletized Cargo Loading

class PalletizedContainerLoader:
    """
    Container loading optimizer for palletized cargo

    Handles standard pallets loaded into containers
    """

    def __init__(self, container_type='40HC'):
        """
        Initialize with container type

        Parameters:
        - container_type: '20', '40', '40HC', '45HC'
        """

        # Container internal dimensions (inches)
        containers = {
            '20': {'L': 232, 'W': 92, 'H': 94, 'capacity': 62000, 'cost': 1.0},
            '40': {'L': 474, 'W': 92, 'H': 94, 'capacity': 59000, 'cost': 1.5},
            '40HC': {'L': 474, 'W': 92, 'H': 106, 'capacity': 58400, 'cost': 1.6},
            '45HC': {'L': 534, 'W': 92, 'H': 106, 'capacity': 58000, 'cost': 1.8}
        }

        if container_type not in containers:
            raise ValueError(f"Unknown container type: {container_type}")

        self.container_type = container_type
        self.container_dims = containers[container_type]
        self.pallets = []
        self.solution = None

    def add_pallet(self, length, width, height, weight, quantity=1, pallet_id=None):
        """Add pallet to load"""
        for i in range(quantity):
            pid = f"{pallet_id}_{i}" if pallet_id and quantity > 1 else pallet_id or f"P{len(self.pallets)}"
            self.pallets.append({
                'id': pid,
                'dims': (length, width, height),
                'weight': weight
            })

    def optimize_loading(self, allow_rotation=True, double_stack=True):
        """
        Optimize pallet loading into containers

        Parameters:
        - allow_rotation: allow 90-degree rotation
        - double_stack: allow stacking pallets

        Returns loading plan
        """

        # Sort pallets by volume (largest first)
        sorted_pallets = sorted(self.pallets,
                               key=lambda p: p['dims'][0] * p['dims'][1] * p['dims'][2],
                               reverse=True)

        containers = []

        for pallet in sorted_pallets:
            placed = False

            # Try existing containers
            for container in containers:
                if self._try_place_pallet(container, pallet, allow_rotation, double_stack):
                    placed = True
                    break

            # Create new container if needed
            if not placed:
                new_container = {
                    'pallets': [],
                    'weight': 0,
                    'positions': [],
                    'grid': self._create_empty_grid()
                }

                if self._try_place_pallet(new_container, pallet, allow_rotation, double_stack):
                    containers.append(new_container)
                else:
                    print(f"Warning: Could not place pallet {pallet['id']}")

        # Calculate metrics
        self.solution = self._calculate_solution_metrics(containers)
        return self.solution

    def _try_place_pallet(self, container, pallet, allow_rotation, double_stack):
        """Try to place pallet in container"""

        L, W, H = self.container_dims['L'], self.container_dims['W'], self.container_dims['H']
        max_weight = self.container_dims['capacity']

        # Check weight
        if container['weight'] + pallet['weight'] > max_weight:
            return False

        # Try different positions and orientations
        orientations = [(pallet['dims'][0], pallet['dims'][1], pallet['dims'][2], False)]
        if allow_rotation:
            orientations.append((pallet['dims'][1], pallet['dims'][0], pallet['dims'][2], True))

        # Try floor positions first
        for l, w, h, rotated in orientations:
            # Try placing on floor
            for x in range(0, int(L - l) + 1, 4):  # 4-inch increments
                for y in range(0, int(W - w) + 1, 4):
                    if self._check_space_available(container['grid'], x, y, 0, l, w, h):
                        # Place pallet
                        self._occupy_space(container['grid'], x, y, 0, l, w, h)
                        container['pallets'].append(pallet)
                        container['weight'] += pallet['weight']
                        container['positions'].append({
                            'pallet': pallet,
                            'position': (x, y, 0),
                            'dims': (l, w, h),
                            'rotated': rotated,
                            'level': 'floor'
                        })
                        return True

        # Try stacking if allowed
        if double_stack:
            for l, w, h, rotated in orientations:
                # Find existing pallets to stack on
                for pos in container['positions']:
                    if pos['level'] == 'floor':
                        base_x, base_y, base_z = pos['position']
                        base_l, base_w, base_h = pos['dims']

                        # Check if new pallet fits on top
                        if (l <= base_l and w <= base_w and
                            base_z + base_h + h <= H):

                            stack_z = base_z + base_h

                            if self._check_space_available(container['grid'],
                                                          base_x, base_y, stack_z,
                                                          l, w, h):
                                # Stack pallet
                                self._occupy_space(container['grid'],
                                                  base_x, base_y, stack_z,
                                                  l, w, h)
                                container['pallets'].append(pallet)
                                container['weight'] += pallet['weight']
                                container['positions'].append({
                                    'pallet': pallet,
                                    'position': (base_x, base_y, stack_z),
                                    'dims': (l, w, h),
                                    'rotated': rotated,
                                    'level': 'stacked'
                                })
                                return True

        return False

    def _create_empty_grid(self):
        """Create 3D occupancy grid"""
        # Simplified grid (4-inch resolution)
        L = int(self.container_dims['L'] / 4)
        W = int(self.container_dims['W'] / 4)
        H = int(self.container_dims['H'] / 4)
        return [[[False for _ in range(H)] for _ in range(W)] for _ in range(L)]

    def _check_space_available(self, grid, x, y, z, l, w, h):
        """Check if space is available in grid"""
        x_cells = int(x / 4)
        y_cells = int(y / 4)
        z_cells = int(z / 4)
        l_cells = int((l + 3) / 4)
        w_cells = int((w + 3) / 4)
        h_cells = int((h + 3) / 4)

        try:
            for i in range(x_cells, x_cells + l_cells):
                for j in range(y_cells, y_cells + w_cells):
                    for k in range(z_cells, z_cells + h_cells):
                        if i >= len(grid) or j >= len(grid[0]) or k >= len(grid[0][0]):
                            return False
                        if grid[i][j][k]:
                            return False
            return True
        except:
            return False

    def _occupy_space(self, grid, x, y, z, l, w, h):
        """Mark space as occupied in grid"""
        x_cells = int(x / 4)
        y_cells = int(y / 4)
        z_cells = int(z / 4)
        l_cells = int((l + 3) / 4)
        w_cells = int((w + 3) / 4)
        h_cells = int((h + 3) / 4)

        for i in range(x_cells, min(x_cells + l_cells, len(grid))):
            for j in range(y_cells, min(y_cells + w_cells, len(grid[0]))):
                for k in range(z_cells, min(z_cells + h_cells, len(grid[0][0]))):
                    grid[i][j][k] = True

    def _calculate_solution_metrics(self, containers):
        """Calculate solution metrics"""

        L = self.container_dims['L']
        W = self.container_dims['W']
        H = self.container_dims['H']
        container_volume = L * W * H

        solution = {
            'num_containers': len(containers),
            'container_type': self.container_type,
            'containers': []
        }

        for idx, cont in enumerate(containers):
            # Calculate volume used
            volume_used = sum(
                pos['dims'][0] * pos['dims'][1] * pos['dims'][2]
                for pos in cont['positions']
            )

            utilization = (volume_used / container_volume * 100)

            solution['containers'].append({
                'container_id': idx,
                'num_pallets': len(cont['pallets']),
                'weight': cont['weight'],
                'volume_used': volume_used,
                'utilization': utilization,
                'positions': cont['positions']
            })

        return solution

    def print_solution(self):
        """Print loading solution"""

        if not self.solution:
            print("No solution available")
            return

        print("=" * 70)
        print("CONTAINER LOADING SOLUTION")
        print("=" * 70)
        print(f"Container Type: {self.solution['container_type']}")
        print(f"Pallets to load: {len(self.pallets)}")
        print(f"Containers used: {self.solution['num_containers']}")
        print()

        for cont in self.solution['containers']:
            print(f"Container {cont['container_id'] + 1}:")
            print(f"  Pallets: {cont['num_pallets']}")
            print(f"  Weight: {cont['weight']:,.0f} lbs")
            print(f"  Utilization: {cont['utilization']:.1f}%")
            print()


# Example Usage
if __name__ == "__main__":
    # Create loader for 40ft HC container
    loader = PalletizedContainerLoader(container_type='40HC')

    # Add GMA pallets (48x40x60 inches, 1500 lbs each)
    loader.add_pallet(48, 40, 60, 1500, quantity=20, pallet_id='GMA')

    # Add EUR pallets (47x32x55 inches, 1200 lbs each)
    loader.add_pallet(47, 32, 55, 1200, quantity=10, pallet_id='EUR')

    # Optimize
    solution = loader.optimize_loading(allow_rotation=True, double_stack=True)

    # Print results
    loader.print_solution()

Loose Cargo Loading

def optimize_loose_cargo_loading(items, container_type='40HC'):
    """
    Optimize loading of non-palletized (loose) cargo

    Uses 3D bin packing algorithms
    """

    from skills.three_d_bin_packing import ThreeDimensionalBinPacker

    # Container dimensions
    containers = {
        '20': (232, 92, 94, 62000),
        '40': (474, 92, 94, 59000),
        '40HC': (474, 92, 106, 58400),
        '45HC': (534, 92, 106, 58000)
    }

    L, W, H, max_weight = containers[container_type]

    # Use 3D bin packing
    packer = ThreeDimensionalBinPacker(L, W, H, max_weight)

    for item in items:
        packer.add_item(
            item['length'], item['width'], item['height'],
            item['weight'], item.get('id')
        )

    solution = packer.solve(algorithm='extreme_point', allow_rotation=True)

    return solution

Multi-Destination Loading

def optimize_multi_destination_loading(shipments, container_type='40HC'):
    """
    Optimize container loading for multi-destination shipments

    Ensures items are loaded in reverse delivery order (LIFO)

    Parameters:
    - shipments: list of dicts with 'destination', 'items', 'priority'
    - container_type: container size

    Returns: loading plan with zones
    """

    # Sort shipments by delivery order (last delivery first)
    sorted_shipments = sorted(shipments,
                             key=lambda s: s.get('priority', 0),
                             reverse=True)

    containers = []

    for shipment in sorted_shipments:
        destination = shipment['destination']
        items = shipment['items']

        # Try to add to existing container
        placed = False
        for container in containers:
            # Check if can add zone
            if container['remaining_capacity'] >= sum(i['volume'] for i in items):
                # Add zone
                container['zones'].append({
                    'destination': destination,
                    'items': items
                })
                placed = True
                break

        if not placed:
            # Create new container
            new_container = {
                'zones': [{
                    'destination': destination,
                    'items': items
                }],
                'remaining_capacity': 1000  # Simplified
            }
            containers.append(new_container)

    return {
        'containers': containers,
        'num_containers': len(containers)
    }

Common Challenges & Solutions

Challenge: Cube Out vs. Weight Out

Problem:

  • Container full by volume but under weight limit (cube out)
  • OR hit weight limit with space remaining (weight out)
  • Inefficient use of capacity

Solutions:

  • Mix dense and light cargo for balance
  • Calculate cubic weight ratio
  • Use appropriatecontainer size for cargo density
  • Consider consolidation with other shipments
  • For heavy cargo: use smaller containers or ship by weight
  • For light cargo: maximize volume usage

Challenge: Weight Distribution

Problem:

  • Uneven weight distribution
  • Axle weight violations
  • Container instability

Solutions:

  • Calculate weight per linear foot
  • Target even distribution (±2% variance)
  • Place heavy items in middle/bottom
  • Use load planning software
  • Balance left/right, front/back
  • Consider trucking axle limits

Challenge: Mixed Pallet Sizes

Problem:

  • GMA and EUR pallets don't pack well together
  • Wasted space between different sizes

Solutions:

  • Group similar pallet sizes
  • Load largest pallets first
  • Use filler cargo for gaps
  • Consider separate containers for different pallet types
  • Optimize pallet patterns before containerization

Output Format

Container Loading Plan

Summary:

  • Shipment: Order #12345
  • Containers Required: 2 x 40ft HC
  • Total Pallets: 22
  • Total Weight: 48,500 lbs
  • Average Utilization: 87%

Container 1 - 40ft HC:

  • Pallets Loaded: 11
  • Weight: 24,800 lbs (42% of capacity)
  • Volume Utilization: 89%
  • Weight Distribution: Front 48%, Rear 52% ✓

Loading Pattern:

[Front]                [Rear]
Row 1: P1 P2 P3 P4    P5 P6
Row 2: P7 P8 P9       P10 P11

Container 2 - 40ft HC:

  • Pallets Loaded: 11
  • Weight: 23,700 lbs (41% of capacity)
  • Volume Utilization: 85%
  • Weight Distribution: Front 51%, Rear 49% ✓

Securing Requirements:

  • Stretch wrap all pallets
  • Use load bars between rows
  • Airbags for void spaces
  • Secure doors with seal #ABC123

Questions to Ask

  1. What container size are you using? (20ft, 40ft, 40ft HC, 45ft HC)
  2. Are items palletized or loose cargo?
  3. What are the pallet dimensions and weights?
  4. Is there a weight limit or distribution requirement?
  5. Is this single destination or multi-drop delivery?
  6. Any special cargo (fragile, hazmat, temperature-controlled)?
  7. Loading sequence requirements (LIFO/FIFO)?

Related Skills

  • pallet-loading: For pallet-level optimization before container loading
  • 3d-bin-packing: For loose cargo packing
  • vehicle-loading-optimization: For truck loading
  • load-building-optimization: For order consolidation
  • freight-optimization: For shipping cost optimization

Contract Management

You are an expert in procurement contract management and negotiation. Your goal is to help organizations manage supplier contracts throughout their lifecycle, negotiate favorable terms, ensure compliance, and optimize contract value and performance.

Initial Assessment

Before managing contracts, understand:

  1. Contract Portfolio Context

    • How many active contracts?
    • Total contract value (TCV)?
    • Contract types? (MSA, SOW, purchase agreements)
    • Current pain points or issues?
  2. Management Maturity

    • Existing contract management process?
    • CLM (Contract Lifecycle Management) system in place?
    • Contract compliance monitoring?
    • Renewal tracking process?
  3. Business Objectives

    • Primary goal? (cost savings, risk mitigation, compliance)
    • Key performance indicators?
    • Contract standardization level?
    • Approval workflows?
  4. Resources & Systems

    • Legal team involvement?
    • Procurement team structure?
    • Document management system?
    • Integration with ERP/P2P?

Contract Lifecycle Management Framework

Contract Lifecycle Stages

1. Pre-Contract (Initiation)

  • Identify need
  • Business case approval
  • Supplier selection
  • RFP/negotiation preparation

2. Negotiation

  • Terms and conditions
  • Pricing and payment terms
  • SLAs and KPIs
  • Risk allocation
  • Legal review

3. Execution

  • Contract signing
  • Approvals and routing
  • Contract repository storage
  • Stakeholder notification

4. Administration

  • Obligation tracking
  • Performance monitoring
  • Invoice and payment management
  • Change requests
  • Relationship management

5. Renewal/Exit

  • Performance review
  • Renewal decision
  • Renegotiation
  • Transition planning
  • Contract closeout

Contract Negotiation Strategies

Negotiation Preparation

Research & Analysis:

  • Market benchmarks and pricing
  • Supplier financial health
  • BATNA (Best Alternative To Negotiated Agreement)
  • Walk-away point
  • Stakeholder requirements

Negotiation Leverage:

  • Volume/spend level
  • Multi-year commitment
  • Preferred supplier status
  • Payment terms (early payment)
  • Business growth potential
  • Reference/testimonial

Key Terms to Negotiate

1. Pricing Terms

class PricingStructure:
    """Model different pricing structures for negotiation"""

    @staticmethod
    def fixed_price(unit_price, volume, discount_tiers=None):
        """
        Fixed price with volume discounts

        discount_tiers: list of (volume_threshold, discount_pct)
        """
        total_cost = unit_price * volume

        if discount_tiers:
            applicable_discount = 0
            for threshold, discount in sorted(discount_tiers, reverse=True):
                if volume >= threshold:
                    applicable_discount = discount
                    break

            total_cost = total_cost * (1 - applicable_discount)

        return {
            'pricing_model': 'Fixed Price',
            'base_unit_price': unit_price,
            'volume': volume,
            'discount': applicable_discount if discount_tiers else 0,
            'total_cost': round(total_cost, 2),
            'effective_unit_price': round(total_cost / volume, 2)
        }

    @staticmethod
    def cost_plus(cost, markup_pct, volume):
        """Cost-plus pricing model"""
        unit_price = cost * (1 + markup_pct)
        total_cost = unit_price * volume

        return {
            'pricing_model': 'Cost Plus',
            'base_cost': cost,
            'markup_pct': markup_pct * 100,
            'unit_price': round(unit_price, 2),
            'volume': volume,
            'total_cost': round(total_cost, 2)
        }

    @staticmethod
    def index_based(base_price, index_value, base_index, volume, cap=None):
        """
        Index-linked pricing (e.g., commodity, inflation)

        cap: maximum % increase/decrease
        """
        index_adjustment = (index_value - base_index) / base_index

        if cap and abs(index_adjustment) > cap:
            index_adjustment = cap if index_adjustment > 0 else -cap

        adjusted_price = base_price * (1 + index_adjustment)
        total_cost = adjusted_price * volume

        return {
            'pricing_model': 'Index Based',
            'base_price': base_price,
            'base_index': base_index,
            'current_index': index_value,
            'adjustment_pct': round(index_adjustment * 100, 2),
            'adjusted_unit_price': round(adjusted_price, 2),
            'volume': volume,
            'total_cost': round(total_cost, 2),
            'cap_applied': cap is not None and abs(index_adjustment) > cap
        }

    @staticmethod
    def gain_share(baseline_cost, actual_cost, sharing_ratio, volume):
        """
        Gain-share pricing (savings split between parties)

        sharing_ratio: % of savings to buyer (e.g., 0.6 = 60/40 split)
        """
        savings = baseline_cost - actual_cost
        buyer_savings = savings * sharing_ratio
        supplier_savings = savings * (1 - sharing_ratio)

        buyer_price = actual_cost + supplier_savings
        total_cost = buyer_price * volume

        return {
            'pricing_model': 'Gain Share',
            'baseline_cost': baseline_cost,
            'actual_cost': actual_cost,
            'total_savings': round(savings, 2),
            'buyer_share': round(buyer_savings, 2),
            'supplier_share': round(supplier_savings, 2),
            'buyer_unit_price': round(buyer_price, 2),
            'volume': volume,
            'total_cost': round(total_cost, 2)
        }


# Example: Compare pricing models
volume = 100000

fixed = PricingStructure.fixed_price(
    unit_price=10.00,
    volume=volume,
    discount_tiers=[(50000, 0.05), (100000, 0.08)]
)

cost_plus = PricingStructure.cost_plus(
    cost=8.50,
    markup_pct=0.15,
    volume=volume
)

index = PricingStructure.index_based(
    base_price=10.00,
    index_value=105,
    base_index=100,
    volume=volume,
    cap=0.10  # 10% cap
)

print("Fixed Price:", fixed)
print("Cost Plus:", cost_plus)
print("Index Based:", index)

2. Payment Terms

  • Standard: Net 30, Net 60, Net 90
  • Early payment discount: 2/10 Net 30
  • Payment milestones (for services)
  • Advance payment vs. arrears
  • E-invoicing and auto-payment
def evaluate_payment_terms(invoice_amount, terms_options):
    """
    Evaluate different payment terms

    terms_options: list of dicts with payment terms
    """

    results = []

    for option in terms_options:
        term_type = option['type']
        days = option.get('days', 30)
        discount = option.get('discount_pct', 0)

        if term_type == 'standard':
            effective_cost = invoice_amount
            cash_impact_days = days

        elif term_type == 'early_discount':
            discount_days = option.get('discount_days', 10)
            if option.get('take_discount', True):
                effective_cost = invoice_amount * (1 - discount)
                cash_impact_days = discount_days
            else:
                effective_cost = invoice_amount
                cash_impact_days = days

        # Annualized cost of capital
        cost_of_capital_annual = 0.08  # 8% annual
        holding_cost = effective_cost * (cash_impact_days / 365) * cost_of_capital_annual

        total_cost = effective_cost + holding_cost

        results.append({
            'terms': option['name'],
            'payment_days': cash_impact_days,
            'effective_amount': round(effective_cost, 2),
            'holding_cost': round(holding_cost, 2),
            'total_cost': round(total_cost, 2),
            'savings_vs_baseline': 0  # Will calculate below
        })

    # Calculate savings vs. baseline (first option)
    baseline_cost = results[0]['total_cost']
    for result in results:
        result['savings_vs_baseline'] = round(baseline_cost - result['total_cost'], 2)

    return results


# Example
terms = [
    {'name': 'Net 30', 'type': 'standard', 'days': 30},
    {'name': 'Net 60', 'type': 'standard', 'days': 60},
    {'name': '2/10 Net 30 (take discount)', 'type': 'early_discount',
     'days': 30, 'discount_days': 10, 'discount_pct': 0.02, 'take_discount': True},
    {'name': '2/10 Net 30 (no discount)', 'type': 'early_discount',
     'days': 30, 'discount_days': 10, 'discount_pct': 0.02, 'take_discount': False},
]

payment_analysis = evaluate_payment_terms(invoice_amount=100000, terms_options=terms)

for result in payment_analysis:
    print(f"\n{result['terms']}")
    print(f"  Effective Amount: ${result['effective_amount']:,.2f}")
    print(f"  Total Cost: ${result['total_cost']:,.2f}")
    print(f"  Savings: ${result['savings_vs_baseline']:,.2f}")

3. Service Level Agreements (SLAs)

class SLAManager:
    """Manage and track Service Level Agreements"""

    def __init__(self, contract_id):
        self.contract_id = contract_id
        self.slas = []

    def add_sla(self, metric, target, measurement_period,
               penalty_structure=None):
        """
        Add SLA metric

        penalty_structure: list of (threshold, penalty_pct)
        """
        sla = {
            'metric': metric,
            'target': target,
            'measurement_period': measurement_period,
            'penalty_structure': penalty_structure or []
        }
        self.slas.append(sla)

    def calculate_performance(self, metric, actual_value):
        """Calculate performance vs. SLA target"""

        sla = next((s for s in self.slas if s['metric'] == metric), None)
        if not sla:
            return None

        target = sla['target']

        # Determine if higher or lower is better based on metric name
        higher_better = any(word in metric.lower()
                          for word in ['uptime', 'delivery', 'fill', 'accuracy'])

        if higher_better:
            performance_pct = (actual_value / target) * 100
            meets_target = actual_value >= target
        else:  # Lower is better (e.g., defect rate, lead time)
            performance_pct = (target / actual_value) * 100
            meets_target = actual_value <= target

        # Calculate penalty if applicable
        penalty_pct = 0
        if not meets_target and sla['penalty_structure']:
            variance = abs(actual_value - target) / target

            for threshold, penalty in sorted(sla['penalty_structure'], reverse=True):
                if variance >= threshold:
                    penalty_pct = penalty
                    break

        return {
            'metric': metric,
            'target': target,
            'actual': actual_value,
            'performance_%': round(performance_pct, 1),
            'meets_target': meets_target,
            'penalty_%': penalty_pct,
            'status': 'Met' if meets_target else 'Missed'
        }

    def generate_scorecard(self, actual_values):
        """
        Generate SLA performance scorecard

        actual_values: dict {metric: actual_value}
        """
        scorecard = []

        for metric, actual in actual_values.items():
            result = self.calculate_performance(metric, actual)
            if result:
                scorecard.append(result)

        # Calculate overall compliance
        total_slas = len(scorecard)
        met_slas = sum(1 for s in scorecard if s['meets_target'])
        compliance_rate = (met_slas / total_slas * 100) if total_slas > 0 else 0

        return {
            'contract_id': self.contract_id,
            'sla_details': scorecard,
            'total_slas': total_slas,
            'met_slas': met_slas,
            'compliance_rate_%': round(compliance_rate, 1)
        }


# Example usage
sla_manager = SLAManager(contract_id='CNT-12345')

# Add SLAs with penalty structures
sla_manager.add_sla(
    metric='On-Time Delivery %',
    target=95.0,
    measurement_period='monthly',
    penalty_structure=[
        (0.05, 0.02),  # 5% miss = 2% penalty
        (0.10, 0.05),  # 10% miss = 5% penalty
        (0.15, 0.10),  # 15% miss = 10% penalty
    ]
)

sla_manager.add_sla(
    metric='Defect Rate (PPM)',
    target=1000,
    measurement_period='monthly',
    penalty_structure=[
        (0.20, 0.03),  # 20% over = 3% penalty
        (0.50, 0.05),  # 50% over = 5% penalty
    ]
)

sla_manager.add_sla(
    metric='Lead Time (days)',
    target=21,
    measurement_period='monthly',
    penalty_structure=[
        (0.10, 0.01),  # 10% over = 1% penalty
        (0.25, 0.03),  # 25% over = 3% penalty
    ]
)

# Evaluate actual performance
actual_performance = {
    'On-Time Delivery %': 92.5,  # Below target
    'Defect Rate (PPM)': 1200,   # Above target
    'Lead Time (days)': 23       # Above target
}

scorecard = sla_manager.generate_scorecard(actual_performance)

print(f"\nSLA Scorecard for {scorecard['contract_id']}")
print(f"Compliance Rate: {scorecard['compliance_rate_%']}%")
print(f"Met {scorecard['met_slas']} of {scorecard['total_slas']} SLAs\n")

for sla in scorecard['sla_details']:
    print(f"{sla['metric']}:")
    print(f"  Target: {sla['target']}")
    print(f"  Actual: {sla['actual']}")
    print(f"  Status: {sla['status']}")
    if sla['penalty_%'] > 0:
        print(f"  Penalty: {sla['penalty_%']}%")

4. Risk Allocation & Indemnification

  • Liability caps
  • Insurance requirements
  • Warranty terms
  • Force majeure
  • IP indemnification
  • Data security and privacy

5. Change Management

  • Change request process
  • Pricing for scope changes
  • Timeline adjustments
  • Approval requirements

6. Termination Clauses

  • Termination for convenience
  • Termination for cause
  • Notice periods
  • Exit obligations
  • Transition assistance

Contract Compliance Monitoring

Obligation Tracking

import pandas as pd
from datetime import datetime, timedelta

class ContractObligationTracker:
    """Track contract obligations and deadlines"""

    def __init__(self):
        self.obligations = []

    def add_obligation(self, contract_id, obligation_type, description,
                      responsible_party, due_date, status='Pending'):
        """Add contract obligation"""

        self.obligations.append({
            'contract_id': contract_id,
            'type': obligation_type,
            'description': description,
            'responsible_party': responsible_party,
            'due_date': pd.to_datetime(due_date),
            'status': status,
            'added_date': datetime.now()
        })

    def get_upcoming_obligations(self, days_ahead=30):
        """Get obligations due in next N days"""

        df = pd.DataFrame(self.obligations)

        if df.empty:
            return df

        # Filter pending obligations
        df = df[df['status'] == 'Pending']

        # Filter by date range
        today = pd.Timestamp.now()
        future_date = today + timedelta(days=days_ahead)

        df = df[(df['due_date'] >= today) & (df['due_date'] <= future_date)]

        # Sort by due date
        df = df.sort_values('due_date')

        # Add days until due
        df['days_until_due'] = (df['due_date'] - today).dt.days

        return df

    def get_overdue_obligations(self):
        """Get overdue obligations"""

        df = pd.DataFrame(self.obligations)

        if df.empty:
            return df

        # Filter pending and overdue
        df = df[df['status'] == 'Pending']
        today = pd.Timestamp.now()
        df = df[df['due_date'] < today]

        # Sort by due date (oldest first)
        df = df.sort_values('due_date')

        # Add days overdue
        df['days_overdue'] = (today - df['due_date']).dt.days

        return df

    def update_status(self, contract_id, description, new_status):
        """Update obligation status"""

        for obligation in self.obligations:
            if (obligation['contract_id'] == contract_id and
                obligation['description'] == description):
                obligation['status'] = new_status
                obligation['completed_date'] = datetime.now()
                break


# Example usage
tracker = ContractObligationTracker()

# Add various obligations
tracker.add_obligation(
    contract_id='CNT-001',
    obligation_type='Deliverable',
    description='Submit quarterly business review',
    responsible_party='Supplier',
    due_date='2026-04-01'
)

tracker.add_obligation(
    contract_id='CNT-001',
    obligation_type='Payment',
    description='Monthly payment due',
    responsible_party='Buyer',
    due_date='2026-02-15'
)

tracker.add_obligation(
    contract_id='CNT-002',
    obligation_type='Audit',
    description='Annual security audit',
    responsible_party='Supplier',
    due_date='2026-03-15'
)

tracker.add_obligation(
    contract_id='CNT-003',
    obligation_type='Renewal Decision',
    description='Notify renewal or termination',
    responsible_party='Buyer',
    due_date='2026-01-30'  # Overdue
)

# Check upcoming obligations
upcoming = tracker.get_upcoming_obligations(days_ahead=60)
print("Upcoming Obligations:")
print(upcoming[['contract_id', 'description', 'due_date', 'days_until_due']])

# Check overdue
overdue = tracker.get_overdue_obligations()
print("\nOverdue Obligations:")
print(overdue[['contract_id', 'description', 'days_overdue']])

Spend Compliance Monitoring

def analyze_contract_compliance(actual_spend_df, contracts_df):
    """
    Analyze spend compliance with contracts

    actual_spend_df: DataFrame with actual purchases
    contracts_df: DataFrame with contract details
    """

    # Merge actual spend with contracts
    spend_with_contract = actual_spend_df.merge(
        contracts_df[['supplier_name', 'category', 'contract_id',
                     'contracted_price', 'volume_commitment']],
        on=['supplier_name', 'category'],
        how='left'
    )

    # Calculate compliance metrics
    compliance_summary = []

    for contract_id in contracts_df['contract_id'].unique():
        contract_data = spend_with_contract[
            spend_with_contract['contract_id'] == contract_id
        ]

        if len(contract_data) == 0:
            continue

        contract = contracts_df[contracts_df['contract_id'] == contract_id].iloc[0]

        total_spend = contract_data['spend_amount'].sum()
        total_volume = contract_data['volume'].sum()
        volume_commitment = contract['volume_commitment']

        # Volume compliance
        volume_achievement = total_volume / volume_commitment * 100

        # Price compliance
        contract_data['price_variance'] = (
            contract_data['unit_price'] - contract_data['contracted_price']
        ) / contract_data['contracted_price']

        avg_price_variance = contract_data['price_variance'].mean() * 100
        price_compliant = (contract_data['price_variance'].abs() < 0.02).mean() * 100

        compliance_summary.append({
            'contract_id': contract_id,
            'supplier': contract['supplier_name'],
            'category': contract['category'],
            'total_spend': total_spend,
            'volume_commitment': volume_commitment,
            'actual_volume': total_volume,
            'volume_achievement_%': round(volume_achievement, 1),
            'avg_price_variance_%': round(avg_price_variance, 1),
            'price_compliance_%': round(price_compliant, 1),
            'status': 'Compliant' if (volume_achievement >= 80 and
                                     abs(avg_price_variance) < 5) else 'Non-Compliant'
        })

    return pd.DataFrame(compliance_summary)

Contract Renewal Management

Renewal Decision Framework

class ContractRenewalAnalysis:
    """Analyze contract for renewal decision"""

    def __init__(self, contract_id, current_terms):
        self.contract_id = contract_id
        self.current_terms = current_terms
        self.performance_data = {}
        self.market_data = {}

    def add_performance_data(self, sla_compliance, quality_score,
                            delivery_score, relationship_score):
        """Add supplier performance data"""
        self.performance_data = {
            'sla_compliance_%': sla_compliance,
            'quality_score': quality_score,  # 0-10
            'delivery_score': delivery_score,  # 0-10
            'relationship_score': relationship_score  # 0-10
        }

    def add_market_data(self, market_price, inflation_rate,
                       competitive_alternatives):
        """Add market intelligence"""
        self.market_data = {
            'market_price': market_price,
            'current_price': self.current_terms['price'],
            'inflation_rate': inflation_rate,
            'competitive_alternatives': competitive_alternatives
        }

    def calculate_renewal_score(self):
        """Calculate overall renewal recommendation score"""

        score = 0
        max_score = 100
        factors = []

        # Performance scoring (40 points)
        if self.performance_data:
            perf = self.performance_data

            # SLA compliance (15 points)
            sla_points = (perf['sla_compliance_%'] / 100) * 15
            score += sla_points

            if perf['sla_compliance_%'] >= 95:
                factors.append("✓ Excellent SLA compliance")
            elif perf['sla_compliance_%'] < 90:
                factors.append("✗ Poor SLA compliance")

            # Quality (10 points)
            quality_points = (perf['quality_score'] / 10) * 10
            score += quality_points

            # Delivery (10 points)
            delivery_points = (perf['delivery_score'] / 10) * 10
            score += delivery_points

            # Relationship (5 points)
            relationship_points = (perf['relationship_score'] / 10) * 5
            score += relationship_points

        # Price competitiveness (30 points)
        if self.market_data:
            market = self.market_data

            price_variance = (market['current_price'] - market['market_price']) / market['market_price']

            if price_variance <= -0.05:  # 5% below market
                price_points = 30
                factors.append("✓ Very competitive pricing")
            elif price_variance <= 0:
                price_points = 25
                factors.append("✓ Competitive pricing")
            elif price_variance <= 0.05:
                price_points = 20
                factors.append("~ At market price")
            elif price_variance <= 0.10:
                price_points = 10
                factors.append("✗ Above market price")
            else:
                price_points = 0
                factors.append("✗✗ Significantly above market")

            score += price_points

            # Competitive alternatives (10 points)
            if market['competitive_alternatives'] == 0:
                score += 0
                factors.append("✗ No alternatives (locked in)")
            elif market['competitive_alternatives'] <= 2:
                score += 5
                factors.append("~ Limited alternatives")
            else:
                score += 10
                factors.append("✓ Multiple alternatives available")

        # Switching cost consideration (20 points)
        switching_cost = self.current_terms.get('switching_cost', 'medium')
        if switching_cost == 'low':
            score += 20
        elif switching_cost == 'medium':
            score += 12
        else:  # high
            score += 5
            factors.append("⚠ High switching cost")

        # Normalize to 100
        score = min(score, max_score)

        # Recommendation
        if score >= 80:
            recommendation = "Renew - Strong Performance"
        elif score >= 60:
            recommendation = "Renew with Renegotiation"
        elif score >= 40:
            recommendation = "Competitive Bid"
        else:
            recommendation = "Replace - Poor Value"

        return {
            'contract_id': self.contract_id,
            'renewal_score': round(score, 1),
            'recommendation': recommendation,
            'key_factors': factors,
            'performance_data': self.performance_data,
            'market_data': self.market_data
        }


# Example usage
renewal = ContractRenewalAnalysis(
    contract_id='CNT-12345',
    current_terms={
        'price': 105,
        'volume': 10000,
        'switching_cost': 'medium'
    }
)

renewal.add_performance_data(
    sla_compliance=94.5,
    quality_score=8.5,
    delivery_score=9.0,
    relationship_score=8.0
)

renewal.add_market_data(
    market_price=100,
    inflation_rate=0.03,
    competitive_alternatives=3
)

result = renewal.calculate_renewal_score()

print(f"\nRenewal Analysis: {result['contract_id']}")
print(f"Renewal Score: {result['renewal_score']}/100")
print(f"Recommendation: {result['recommendation']}")
print("\nKey Factors:")
for factor in result['key_factors']:
    print(f"  {factor}")

Contract Analytics

Portfolio Analytics

def contract_portfolio_analytics(contracts_df):
    """
    Analyze contract portfolio

    contracts_df: DataFrame with contract details
    """

    analytics = {}

    # Total contract value
    analytics['total_contract_value'] = contracts_df['annual_value'].sum()

    # Number of contracts
    analytics['total_contracts'] = len(contracts_df)

    # Contracts by status
    analytics['by_status'] = contracts_df.groupby('status')['annual_value'].agg([
        ('count', 'count'),
        ('value', 'sum')
    ]).to_dict('index')

    # Contracts expiring in next 90 days
    today = pd.Timestamp.now()
    expiry_threshold = today + timedelta(days=90)

    expiring_soon = contracts_df[
        (contracts_df['end_date'] >= today) &
        (contracts_df['end_date'] <= expiry_threshold)
    ]

    analytics['expiring_90_days'] = {
        'count': len(expiring_soon),
        'value': expiring_soon['annual_value'].sum(),
        'contracts': expiring_soon['contract_id'].tolist()
    }

    # Average contract value
    analytics['avg_contract_value'] = contracts_df['annual_value'].mean()

    # Contract concentration (top 10 by value)
    top_10_value = contracts_df.nlargest(10, 'annual_value')['annual_value'].sum()
    analytics['top_10_concentration_%'] = (
        top_10_value / analytics['total_contract_value'] * 100
    )

    # By category
    analytics['by_category'] = contracts_df.groupby('category')['annual_value'].agg([
        ('count', 'count'),
        ('value', 'sum')
    ]).to_dict('index')

    return analytics

Tools & Libraries

Python Libraries

Document Management:

  • python-docx: Microsoft Word documents
  • PyPDF2, pdfplumber: PDF parsing
  • spacy, nltk: Natural language processing
  • pandas: Data analysis

Contract Analytics:

  • numpy: Numerical analysis
  • matplotlib, seaborn: Visualization
  • sklearn: Machine learning for contract analysis

Commercial Software

Contract Lifecycle Management (CLM):

  • Coupa CLM: Contract management platform
  • SAP Ariba Contracts: Contract lifecycle
  • Icertis: Enterprise contract management
  • Agiloft: CLM with AI
  • DocuSign CLM (SpringCM): Digital contracting
  • Ironclad: Digital contracting platform
  • Concord: Contract management

Legal Tech:

  • Kira Systems: AI contract review
  • LawGeex: AI contract review
  • eBrevia: Contract analytics

Document Management:

  • SharePoint: Collaboration and storage
  • Box, Dropbox: Cloud storage
  • M-Files: Intelligent information management

Common Challenges & Solutions

Challenge: Contract Fragmentation

Problem:

  • Contracts stored in multiple locations
  • No central repository
  • Version control issues
  • Hard to find specific contracts

Solutions:

  • Implement CLM system
  • Centralized contract repository
  • Metadata tagging and indexing
  • Search functionality
  • Access controls and permissions
  • Regular audits and cleanup

Challenge: Renewal Tracking

Problem:

  • Missed renewal deadlines
  • Auto-renewals unnoticed
  • Last-minute scrambling
  • Lost negotiation leverage

Solutions:

  • Automated renewal reminders (90/60/30 days)
  • Contract calendar/dashboard
  • Renewal workflow process
  • Performance review requirement before renewal
  • Standard renewal timelines
  • Executive visibility on expirations

Challenge: Compliance Monitoring

Problem:

  • Can't track contract terms
  • Maverick spending
  • Price leakage
  • SLA non-compliance unnoticed

Solutions:

  • Obligation tracking system
  • Automated compliance alerts
  • Integration with P2P system
  • Regular compliance audits
  • Supplier scorecards
  • Penalty enforcement process

Challenge: Contract Negotiation Expertise

Problem:

  • Procurement lacks legal expertise
  • One-sided terms accepted
  • Inconsistent contract terms
  • Risk exposure

Solutions:

  • Standard contract templates
  • Legal team collaboration
  • Negotiation training
  • Playbooks for common terms
  • External legal counsel (complex deals)
  • Pre-approved terms matrix

Challenge: Value Realization

Problem:

  • Negotiated savings not realized
  • Price increases unmonitored
  • Volume commitments not tracked
  • No post-contract management

Solutions:

  • Contract vs. actual spend tracking
  • Regular business reviews
  • Performance dashboards
  • Value realization process
  • Stakeholder accountability
  • Contract compliance team

Output Format

Contract Summary Report

Executive Summary:

  • Total contract portfolio value
  • Number of active contracts
  • Key risks and opportunities
  • Action items

Portfolio Overview:

MetricValue
Total Contract Value$45.2M
Number of Contracts127
Average Contract Value$356K
Expiring in 90 Days15 contracts ($8.3M)
Compliance Rate87%
Top 10 Concentration62%

Contracts Requiring Action:

Contract IDSupplierCategoryValueExpiryAction Required
CNT-001Supplier AIT Services$3.2M2026-03-15Renewal decision
CNT-045Supplier BRaw Materials$2.8M2026-04-01Price renegotiation
CNT-078Supplier CLogistics$1.5MOngoingSLA non-compliance
CNT-092Supplier DMRO$0.8M2026-02-28Volume shortfall

Renewal Pipeline (Next 12 Months):

Q1 2026: 15 contracts, $8.3M
  - 8 recommend renew
  - 4 renegotiate
  - 3 competitive bid

Q2 2026: 23 contracts, $12.1M
  - 15 recommend renew
  - 6 renegotiate
  - 2 competitive bid

Q3 2026: 18 contracts, $6.8M
Q4 2026: 12 contracts, $4.5M

Compliance Issues:

  • Price Variance: 12 contracts with >5% price variance

    • Estimated leakage: $450K annually
    • Action: Enforce contracted pricing
  • Volume Commitments: 8 contracts below 80% of commitment

    • Risk: Price increase or penalty
    • Action: Consolidate demand or renegotiate
  • SLA Misses: 5 suppliers consistently missing SLAs

    • Action: Enforce penalties, develop improvement plans

Key Recommendations:

  1. Prioritize renewal of 15 contracts expiring in Q1
  2. Renegotiate pricing for 4 contracts above market
  3. Address SLA non-compliance with 5 suppliers
  4. Implement automated compliance monitoring
  5. Consolidate spend with top-performing suppliers

Questions to Ask

If you need more context:

  1. How many active contracts and what's the total value?
  2. Is there a CLM system in place?
  3. What contract types? (MSA, SOW, purchase orders)
  4. Primary concerns? (savings, compliance, risk, renewal management)
  5. How are contracts currently stored and tracked?
  6. Any upcoming renewals or expirations?
  7. Are there compliance or performance issues?
  8. Who are the key stakeholders? (procurement, legal, finance)
  9. What metrics or KPIs are tracked?
  10. Any specific contracts that need attention?

Related Skills

  • supplier-selection: For selecting suppliers before contracting
  • strategic-sourcing: For category sourcing strategies
  • procurement-optimization: For optimal contract terms
  • spend-analysis: For contract spend compliance
  • supplier-risk-management: For contract risk assessment
  • quality-management: For SLA monitoring and performance

Control Tower Design

You are an expert in supply chain control tower design and implementation. Your goal is to help organizations establish centralized visibility, monitoring, and coordination capabilities to proactively manage supply chain operations and respond rapidly to disruptions.

Initial Assessment

Before designing a control tower, understand:

  1. Business Drivers

    • What problems is the control tower solving? (visibility gaps, slow response, inefficiencies)
    • Target benefits? (cost reduction, service improvement, risk mitigation)
    • Triggering events? (disruptions, growth, complexity)
    • Executive sponsorship and budget?
  2. Scope & Coverage

    • What processes to cover? (planning, execution, logistics, procurement)
    • Geographic coverage? (regional, global)
    • Internal vs. extended (suppliers, partners, customers)?
    • End-to-end or domain-specific?
  3. Current State

    • Existing visibility capabilities?
    • Data sources and systems? (ERP, TMS, WMS, etc.)
    • Team structure and skills?
    • Performance monitoring processes?
  4. Organizational Readiness

    • Cross-functional collaboration maturity?
    • Data quality and integration capability?
    • Change management resources?
    • Technology infrastructure?

Control Tower Framework

Control Tower Types

1. Planning Control Tower

  • Demand-supply matching
  • Production planning coordination
  • S&OP process management
  • Scenario planning and what-if analysis
  • Forecast collaboration

2. Logistics Control Tower

  • Transportation visibility
  • Shipment tracking and monitoring
  • Carrier performance management
  • Freight spend optimization
  • Last-mile delivery coordination

3. Procurement Control Tower

  • Supplier performance monitoring
  • Order tracking (PO to delivery)
  • Supplier risk monitoring
  • Contract compliance
  • Spend analytics

4. Manufacturing Control Tower

  • Production schedule monitoring
  • Material availability tracking
  • Quality monitoring
  • Equipment performance
  • Yield optimization

5. End-to-End Control Tower

  • Comprehensive supply chain visibility
  • Cross-functional coordination
  • Integrated exception management
  • Multi-tier visibility
  • Strategic and operational integration

Control Tower Maturity Model

Level 1: Basic Visibility

  • Reactive monitoring
  • Manual data collection
  • Siloed dashboards
  • Limited integration
  • Email-based communication

Level 2: Integrated Monitoring

  • Automated data feeds
  • Consolidated dashboards
  • Exception alerts
  • Basic analytics
  • Standard KPIs

Level 3: Proactive Management

  • Predictive analytics
  • Automated workflows
  • Root cause analysis
  • Performance optimization
  • Collaboration tools

Level 4: Cognitive Operations

  • AI/ML-driven insights
  • Prescriptive recommendations
  • Automated decision-making
  • Self-healing processes
  • Continuous optimization

Level 5: Autonomous Supply Chain

  • Fully automated operations
  • Real-time optimization
  • Minimal human intervention
  • Ecosystem orchestration
  • Digital twin integration

Control Tower Design Architecture

Data Architecture

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json

class ControlTowerPlatform:
    """Supply Chain Control Tower platform for visibility and monitoring"""

    def __init__(self):
        self.data_sources = {}
        self.orders = []
        self.shipments = []
        self.exceptions = []
        self.kpis = {}
        self.alerts = []

    def register_data_source(self, source_name, source_type, update_frequency,
                           connection_params):
        """
        Register data source for control tower

        source_type: 'ERP', 'TMS', 'WMS', 'MES', 'API', 'EDI', etc.
        update_frequency: minutes between updates
        """

        self.data_sources[source_name] = {
            'type': source_type,
            'update_frequency_min': update_frequency,
            'last_update': None,
            'status': 'Connected',
            'connection_params': connection_params,
            'record_count': 0
        }

    def ingest_orders(self, orders_data):
        """
        Ingest order data from various sources

        orders_data: list of order dicts
        """

        for order in orders_data:
            order_enriched = {
                'order_id': order['order_id'],
                'customer_id': order.get('customer_id'),
                'order_date': order['order_date'],
                'requested_date': order['requested_date'],
                'promised_date': order.get('promised_date', order['requested_date']),
                'status': order.get('status', 'Open'),
                'value': order.get('value', 0),
                'priority': order.get('priority', 'Normal'),
                'items': order.get('items', []),
                'fulfillment_location': order.get('fulfillment_location'),
                'shipment_id': order.get('shipment_id'),
                'ingestion_timestamp': datetime.now()
            }

            # Calculate metrics
            order_enriched['days_to_requested'] = self._calculate_days_between(
                datetime.now(), order['requested_date']
            )

            # Flag exceptions
            if order_enriched['days_to_requested'] < 0:
                self._create_exception(
                    'ORDER_LATE',
                    f"Order {order['order_id']} is past requested date",
                    'High',
                    order_id=order['order_id']
                )

            self.orders.append(order_enriched)

    def ingest_shipments(self, shipments_data):
        """
        Ingest shipment tracking data

        shipments_data: list of shipment dicts with tracking info
        """

        for shipment in shipments_data:
            shipment_enriched = {
                'shipment_id': shipment['shipment_id'],
                'order_ids': shipment.get('order_ids', []),
                'carrier': shipment.get('carrier'),
                'tracking_number': shipment.get('tracking_number'),
                'origin': shipment.get('origin'),
                'destination': shipment.get('destination'),
                'ship_date': shipment.get('ship_date'),
                'planned_delivery_date': shipment.get('planned_delivery_date'),
                'actual_delivery_date': shipment.get('actual_delivery_date'),
                'current_location': shipment.get('current_location'),
                'status': shipment.get('status', 'In Transit'),
                'milestones': shipment.get('milestones', []),
                'ingestion_timestamp': datetime.now()
            }

            # Calculate delivery performance
            if shipment_enriched['actual_delivery_date']:
                shipment_enriched['delivery_performance_days'] = self._calculate_days_between(
                    shipment_enriched['planned_delivery_date'],
                    shipment_enriched['actual_delivery_date']
                )

                if shipment_enriched['delivery_performance_days'] < 0:
                    self._create_exception(
                        'SHIPMENT_DELAYED',
                        f"Shipment {shipment['shipment_id']} delivered late",
                        'Medium',
                        shipment_id=shipment['shipment_id']
                    )

            # Check for in-transit issues
            if shipment_enriched['status'] == 'Delayed':
                self._create_exception(
                    'SHIPMENT_DELAYED',
                    f"Shipment {shipment['shipment_id']} is experiencing delays",
                    'High',
                    shipment_id=shipment['shipment_id']
                )

            self.shipments.append(shipment_enriched)

    def _calculate_days_between(self, date1, date2):
        """Calculate days between two dates (date2 - date1)"""

        if isinstance(date1, str):
            date1 = datetime.strptime(date1, '%Y-%m-%d')
        if isinstance(date2, str):
            date2 = datetime.strptime(date2, '%Y-%m-%d')

        return (date2 - date1).days

    def _create_exception(self, exception_type, description, severity,
                         order_id=None, shipment_id=None, supplier_id=None):
        """Create exception for exception management"""

        exception = {
            'exception_id': f"EXC_{len(self.exceptions) + 1:06d}",
            'timestamp': datetime.now(),
            'type': exception_type,
            'description': description,
            'severity': severity,
            'status': 'Open',
            'order_id': order_id,
            'shipment_id': shipment_id,
            'supplier_id': supplier_id,
            'assigned_to': None,
            'resolution': None,
            'resolution_time': None
        }

        self.exceptions.append(exception)

        # Create alert if high severity
        if severity in ['High', 'Critical']:
            self._create_alert(exception)

    def _create_alert(self, exception):
        """Create alert for critical exceptions"""

        alert = {
            'alert_id': f"ALT_{len(self.alerts) + 1:06d}",
            'timestamp': datetime.now(),
            'exception_id': exception['exception_id'],
            'type': exception['type'],
            'severity': exception['severity'],
            'message': exception['description'],
            'status': 'New',
            'acknowledged_by': None,
            'acknowledgment_time': None
        }

        self.alerts.append(alert)

    def calculate_kpis(self):
        """Calculate key performance indicators"""

        # Order KPIs
        total_orders = len(self.orders)
        late_orders = len([o for o in self.orders if o['days_to_requested'] < 0])
        on_time_pct = ((total_orders - late_orders) / total_orders * 100) if total_orders > 0 else 100

        # Shipment KPIs
        total_shipments = len(self.shipments)
        delivered_shipments = [s for s in self.shipments if s.get('actual_delivery_date')]
        late_deliveries = len([s for s in delivered_shipments if s.get('delivery_performance_days', 0) < 0])
        otd_pct = ((len(delivered_shipments) - late_deliveries) / len(delivered_shipments) * 100) if delivered_shipments else 100

        # Exception KPIs
        open_exceptions = len([e for e in self.exceptions if e['status'] == 'Open'])
        high_severity_exceptions = len([e for e in self.exceptions if e['severity'] in ['High', 'Critical']])

        self.kpis = {
            'orders': {
                'total': total_orders,
                'late': late_orders,
                'on_time_percentage': round(on_time_pct, 1)
            },
            'shipments': {
                'total': total_shipments,
                'delivered': len(delivered_shipments),
                'late_deliveries': late_deliveries,
                'on_time_delivery_percentage': round(otd_pct, 1)
            },
            'exceptions': {
                'total': len(self.exceptions),
                'open': open_exceptions,
                'high_severity': high_severity_exceptions
            },
            'alerts': {
                'total': len(self.alerts),
                'new': len([a for a in self.alerts if a['status'] == 'New'])
            }
        }

        return self.kpis

    def get_exceptions_dashboard(self):
        """Generate exceptions dashboard"""

        if not self.exceptions:
            return pd.DataFrame()

        df = pd.DataFrame(self.exceptions)

        # Summary by type
        by_type = df.groupby(['type', 'severity']).size().reset_index(name='count')

        # Summary by status
        by_status = df.groupby('status').size().reset_index(name='count')

        return {
            'all_exceptions': df,
            'by_type': by_type,
            'by_status': by_status,
            'open_high_priority': df[(df['status'] == 'Open') & (df['severity'].isin(['High', 'Critical']))]
        }

    def get_alerts_requiring_action(self):
        """Get alerts that need immediate attention"""

        new_alerts = [a for a in self.alerts if a['status'] == 'New']

        return pd.DataFrame(new_alerts) if new_alerts else pd.DataFrame()

    def generate_control_tower_dashboard(self):
        """Generate comprehensive control tower dashboard"""

        kpis = self.calculate_kpis()

        dashboard = {
            'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'kpis': kpis,
            'data_sources': {
                'connected': len([s for s in self.data_sources.values() if s['status'] == 'Connected']),
                'total': len(self.data_sources)
            },
            'alerts': {
                'new_alerts': kpis['alerts']['new'],
                'requires_action': len([a for a in self.alerts if a['status'] == 'New'])
            },
            'exceptions': {
                'open_exceptions': kpis['exceptions']['open'],
                'high_severity': kpis['exceptions']['high_severity']
            },
            'performance_summary': {
                'order_on_time': f"{kpis['orders']['on_time_percentage']}%",
                'delivery_on_time': f"{kpis['shipments']['on_time_delivery_percentage']}%"
            }
        }

        return dashboard


# Example usage
control_tower = ControlTowerPlatform()

# Register data sources
control_tower.register_data_source(
    'ERP_System',
    'ERP',
    update_frequency=15,
    connection_params={'host': 'erp.company.com', 'api_key': 'xxx'}
)

control_tower.register_data_source(
    'TMS_System',
    'TMS',
    update_frequency=5,
    connection_params={'host': 'tms.company.com', 'api_key': 'yyy'}
)

# Ingest orders
orders = [
    {
        'order_id': 'ORD001',
        'customer_id': 'CUST001',
        'order_date': '2025-12-01',
        'requested_date': '2025-12-15',
        'promised_date': '2025-12-15',
        'status': 'Processing',
        'value': 50000,
        'priority': 'High'
    },
    {
        'order_id': 'ORD002',
        'customer_id': 'CUST002',
        'order_date': '2025-11-20',
        'requested_date': '2025-12-05',  # Past date - will trigger exception
        'promised_date': '2025-12-10',
        'status': 'Delayed',
        'value': 30000,
        'priority': 'Normal'
    }
]

control_tower.ingest_orders(orders)

# Ingest shipments
shipments = [
    {
        'shipment_id': 'SHP001',
        'order_ids': ['ORD001'],
        'carrier': 'FedEx',
        'tracking_number': 'TRK123456',
        'origin': 'Chicago, IL',
        'destination': 'New York, NY',
        'ship_date': '2025-12-10',
        'planned_delivery_date': '2025-12-12',
        'actual_delivery_date': '2025-12-14',  # Late
        'status': 'Delivered'
    },
    {
        'shipment_id': 'SHP002',
        'order_ids': ['ORD002'],
        'carrier': 'UPS',
        'tracking_number': 'TRK789012',
        'origin': 'Los Angeles, CA',
        'destination': 'Seattle, WA',
        'ship_date': '2025-12-08',
        'planned_delivery_date': '2025-12-10',
        'status': 'Delayed',  # Currently delayed
        'current_location': 'Portland, OR'
    }
]

control_tower.ingest_shipments(shipments)

# Generate dashboard
dashboard = control_tower.generate_control_tower_dashboard()

print("=== CONTROL TOWER DASHBOARD ===")
print(f"Timestamp: {dashboard['timestamp']}")
print(f"\nKPIs:")
print(f"  Orders: {dashboard['kpis']['orders']['total']} total, {dashboard['kpis']['orders']['late']} late ({dashboard['performance_summary']['order_on_time']} on-time)")
print(f"  Shipments: {dashboard['kpis']['shipments']['delivered']} delivered, {dashboard['kpis']['shipments']['late_deliveries']} late ({dashboard['performance_summary']['delivery_on_time']} on-time)")
print(f"  Exceptions: {dashboard['kpis']['exceptions']['open']} open ({dashboard['kpis']['exceptions']['high_severity']} high severity)")
print(f"  Alerts: {dashboard['alerts']['new_alerts']} new alerts requiring action")

# Get exceptions
exceptions_dashboard = control_tower.get_exceptions_dashboard()
print(f"\n\nOpen High-Priority Exceptions:")
if not exceptions_dashboard['open_high_priority'].empty:
    print(exceptions_dashboard['open_high_priority'][['exception_id', 'type', 'description', 'severity']])

# Get alerts
alerts = control_tower.get_alerts_requiring_action()
print(f"\n\nAlerts Requiring Action:")
if not alerts.empty:
    print(alerts[['alert_id', 'type', 'severity', 'message']])

Tools & Libraries

Python Libraries

Data Processing:

  • pandas: Data manipulation
  • numpy: Numerical computations
  • sqlalchemy: Database connections

Real-Time Processing:

  • kafka-python: Apache Kafka integration
  • paho-mqtt: MQTT messaging
  • redis: Real-time data store

Visualization:

  • dash: Interactive dashboards
  • plotly: Interactive charts
  • streamlit: Dashboard apps
  • bokeh: Real-time visualizations

APIs & Integration:

  • requests: HTTP requests
  • fastapi: API development
  • flask: Web framework

Commercial Software

Control Tower Platforms:

  • Blue Yonder (JDA): Luminate Control Tower
  • Kinaxis: RapidResponse
  • o9 Solutions: Digital brain platform
  • E2open: Control tower platform
  • SAP: Integrated Business Planning with Control Tower
  • Oracle: Supply Chain Management Cloud

Visibility Platforms:

  • FourKites: Real-time visibility
  • project44: Transportation visibility
  • Shippeo: Supply chain visibility
  • ClearMetal: Predictive logistics
  • Descartes MacroPoint: Load tracking

Integration & IoT:

  • MuleSoft: API integration
  • Boomi: Integration platform
  • PTC ThingWorx: IoT platform
  • AWS IoT: IoT services

Common Challenges & Solutions

Challenge: Data Integration Complexity

Problem:

  • Multiple disparate systems
  • Different data formats and standards
  • Real-time vs. batch data
  • Data quality issues

Solutions:

  • Phased integration approach (start with critical systems)
  • Master data management (MDM)
  • API-first architecture
  • Data quality rules and validation
  • Middleware/integration platform
  • Standardized data models

Challenge: Organization Silos

Problem:

  • Resistance to centralized control
  • Competing priorities
  • Lack of collaboration culture
  • Unclear ownership

Solutions:

  • Executive sponsorship and governance
  • Cross-functional team structure
  • Clear roles and responsibilities (RACI)
  • Shared KPIs and incentives
  • Change management program
  • Quick wins to demonstrate value

Challenge: Alert Fatigue

Problem:

  • Too many alerts
  • False positives
  • Important signals missed
  • Reduced responsiveness

Solutions:

  • Intelligent alert thresholds
  • Machine learning for anomaly detection
  • Alert prioritization and routing
  • Escalation rules
  • Alert aggregation and suppression
  • Continuous tuning

Challenge: ROI Justification

Problem:

  • High implementation costs
  • Intangible benefits
  • Long payback period
  • Competing investments

Solutions:

  • Start with pilot (limited scope)
  • Quantify benefits (cost savings, revenue protection)
  • Benchmark against manual processes
  • Value case studies and references
  • Phased investment approach
  • Track and communicate wins

Challenge: User Adoption

Problem:

  • Resistance to new tools
  • Workflow disruption
  • Training requirements
  • Habit change needed

Solutions:

  • User-centric design
  • Training and enablement
  • Change champions
  • Gradual rollout
  • Continuous improvement based on feedback
  • Gamification and incentives

Challenge: Scalability

Problem:

  • Growing data volumes
  • More users and use cases
  • Performance degradation
  • Infrastructure costs

Solutions:

  • Cloud-based architecture
  • Microservices design
  • Data archiving and retention policies
  • Performance optimization
  • Horizontal scaling
  • Cost monitoring and optimization

Output Format

Control Tower Dashboard

Executive Summary:

  • Overall supply chain health score
  • Critical alerts requiring action
  • Key performance trends
  • Major disruptions or risks

KPI Scoreboard:

KPICurrentTargetTrendStatus
Order Fill Rate94.2%96.0%↘ -1.2%⚠ Below
On-Time Delivery89.5%92.0%↗ +0.8%⚠ Below
Perfect Order %85.3%90.0%→ 0.0%⚠ Below
Order Cycle Time4.2 days4.0 days↗ +0.1⚠ Above
Supply Chain Cost as % Revenue8.2%8.0%↘ -0.2%✓ On Track

Exception Summary:

CategoryOpenCriticalHighMediumAging (>48h)
Orders2338125
Shipments1826103
Inventory121472
Suppliers80351
Total616213411

Critical Alerts:

Alert IDTimeTypeDescriptionAssigned ToStatus
ALT-004208:15Shipment DelayedContainer stuck at port - 50 orders affectedJohn D.In Progress
ALT-004107:30Supplier IssueSupplier XYZ production halt - capacity shortfallMary S.New
ALT-0038YesterdayInventory StockoutSKU-12345 out of stock at DC3Tom R.Resolving

Shipment Tracking:

Shipment IDOriginDestinationStatusETADelayRisk
SHP-10234ShanghaiLA PortIn TransitJan 28On Time✓ Low
SHP-10235MumbaiNY PortDelayedJan 30+3 days⚠ High
SHP-10236HamburgChicagoCustoms HoldTBD+5 days⚠⚠ Critical

Supplier Performance:

SupplierOn-Time DeliveryQualityLead TimeRisk ScoreTrending
Supplier A96.2%99.8%12 daysLow✓ Improving
Supplier B88.5%97.2%18 daysMedium⚠ Declining
Supplier C92.1%95.5%15 daysHigh→ Stable

Questions to Ask

If you need more context:

  1. What business problem is the control tower solving?
  2. What scope of operations to cover? (planning, execution, logistics, etc.)
  3. What data sources need integration? (ERP, TMS, WMS, suppliers, etc.)
  4. What are the critical KPIs to monitor?
  5. Who are the users and stakeholders?
  6. What's the current visibility and monitoring maturity?
  7. What technology infrastructure exists?
  8. What's the budget and timeline?
  9. Is this internal or extended (suppliers, customers)?
  10. What are the success criteria?

Related Skills

  • track-and-trace: For product and shipment tracking
  • supplier-collaboration: For supplier integration and communication
  • demand-supply-matching: For demand-supply balancing
  • risk-mitigation: For disruption monitoring and response
  • network-design: For optimizing control tower scope
  • inventory-optimization: For inventory visibility and management
  • route-optimization: For transportation monitoring
  • demand-forecasting: For demand visibility integration

CPG Network Design

You are an expert in CPG (Consumer Packaged Goods) distribution network design and retail supply chain optimization. Your goal is to help design cost-effective distribution networks that balance inventory investment, transportation costs, and service levels to retail customers.

Initial Assessment

Before designing CPG networks, understand:

  1. Business Context

    • What product categories? (food, beverage, personal care, household)
    • What channels? (grocery, mass, club, convenience, DSD, e-commerce)
    • What's the geographic scope? (regional, national, international)
    • Current network? (# DCs, flow patterns, costs)
    • Growth plans or channel expansion?
  2. Customer Requirements

    • Retailer order lead times? (2-7 days typical)
    • Order frequency? (daily, weekly)
    • Case fill rates? (>98% expected)
    • Delivery windows and appointment scheduling?
    • Drop ship vs. warehouse delivery?
  3. Product Characteristics

    • SKU complexity? (100s to 10,000+ SKUs)
    • Velocity distribution? (A/B/C analysis)
    • Shelf life? (days, months, years)
    • Storage requirements? (ambient, refrigerated, frozen)
    • Cube density and weight?
  4. Economic Drivers

    • Current transportation spend?
    • Current DC operating costs?
    • Inventory carrying costs?
    • Service level performance and fill rates?
    • Target cost reduction or service improvement?

CPG Network Design Framework

CPG-Specific Network Characteristics

vs. General Industrial:

  • High SKU complexity (1,000-10,000+ SKUs typical)
  • Fast-moving products (high velocity)
  • Short lead times (2-5 days)
  • High service level requirements (>98%)
  • Promotional variability (30-50% lift)
  • Multi-channel distribution (retail, DSD, e-commerce)
  • Thin margins (2-5% operating margin)

Network Echelon Options:

1. Direct-to-Store (Plant → Store)

  • Fresh/DSD products (bread, milk, snacks)
  • High frequency, small drops
  • Driver merchandising
  • See dsd-route-optimization

2. Single-Tier (Plant → DC → Store)

  • Most common for shelf-stable
  • Regional DCs (3-6 typically)
  • Full product line at each DC
  • Economic order quantities

3. Two-Tier (Plant → RDC → Forward DC → Store)

  • National brand with broad coverage
  • RDCs for slow movers (1-2 large)
  • Forward DCs for fast movers (10-15 smaller)
  • Inventory optimization across tiers

4. Hybrid (Multiple Strategies)

  • Fast movers: Forward DCs
  • Slow movers: Direct ship from RDC
  • Promotional: Special builds
  • E-commerce: Dedicated fulfillment centers

Network Design Models

CPG Facility Location Model

from pulp import *
import pandas as pd
import numpy as np
from scipy.spatial.distance import cdist

class CPGNetworkOptimizer:
    """
    CPG-specific network design optimization
    """

    def __init__(self, customers_df, potential_dcs_df, plants_df):
        """
        Initialize CPG network optimizer

        Parameters:
        - customers_df: retailers with demand ['customer_id', 'lat', 'lon',
                       'demand_cases', 'service_level_days']
        - potential_dcs_df: potential DC locations ['dc_id', 'lat', 'lon',
                           'fixed_cost', 'variable_cost_per_case', 'capacity']
        - plants_df: manufacturing plants ['plant_id', 'lat', 'lon', 'capacity']
        """
        self.customers = customers_df
        self.dcs = potential_dcs_df
        self.plants = plants_df

        # Calculate distance matrices
        self.dc_to_customer_dist = self._calc_distances(
            self.dcs[['lat', 'lon']],
            self.customers[['lat', 'lon']]
        )

        self.plant_to_dc_dist = self._calc_distances(
            self.plants[['lat', 'lon']],
            self.dcs[['lat', 'lon']]
        )

    def _calc_distances(self, from_coords, to_coords):
        """Calculate distance matrix (miles)"""
        distances = cdist(from_coords.values, to_coords.values, metric='euclidean')
        return distances * 69  # Convert degrees to miles (approximate)

    def optimize_network(self, max_dcs=None, service_distance=None,
                          transport_rate_tl=2.50, transport_rate_ltl=25.0):
        """
        Optimize CPG distribution network

        Parameters:
        - max_dcs: maximum number of DCs to open (None = no limit)
        - service_distance: max miles for service level (None = no constraint)
        - transport_rate_tl: truckload rate ($/mile)
        - transport_rate_ltl: LTL rate ($/cwt)

        Returns:
        - optimal network configuration
        """

        prob = LpProblem("CPG_Network", LpMinimize)

        # Decision variables
        C = range(len(self.customers))
        D = range(len(self.dcs))
        P = range(len(self.plants))

        # y[d] = 1 if DC d is opened
        y = LpVariable.dicts("DC_Open", D, cat='Binary')

        # x[c,d] = flow from DC d to customer c (cases)
        x = LpVariable.dicts("Customer_Flow",
                              [(c,d) for c in C for d in D],
                              lowBound=0)

        # z[p,d] = flow from plant p to DC d (cases)
        z = LpVariable.dicts("DC_Flow",
                              [(p,d) for p in P for d in D],
                              lowBound=0)

        # Objective: Minimize total cost
        objective = 0

        # Fixed DC costs
        for d in D:
            objective += self.dcs.iloc[d]['fixed_cost'] * y[d]

        # DC variable costs
        for c in C:
            for d in D:
                handling_cost = self.dcs.iloc[d]['variable_cost_per_case']
                objective += x[c,d] * handling_cost

        # Outbound transportation (DC → Customer)
        for c in C:
            for d in D:
                distance = self.dc_to_customer_dist[d,c]
                demand = self.customers.iloc[c]['demand_cases']

                # Simplified: LTL for <20,000 lbs, TL otherwise
                if demand < 400:  # 400 cases ~= 20,000 lbs
                    cost = distance * transport_rate_ltl / 100 * demand * 50 / 100  # $/cwt
                else:
                    cost = distance * transport_rate_tl

                objective += x[c,d] * cost / demand  # Cost per case

        # Inbound transportation (Plant → DC)
        for p in P:
            for d in D:
                distance = self.plant_to_dc_dist[p,d]
                # Assume truckload shipments to DCs
                cost_per_mile = transport_rate_tl
                objective += z[p,d] * distance * cost_per_mile / 1000  # Per case

        prob += objective

        # Constraints

        # 1. Each customer served by exactly one DC
        for c in C:
            prob += lpSum([x[c,d] for d in D]) >= self.customers.iloc[c]['demand_cases']

        # 2. DC capacity constraints
        for d in D:
            prob += lpSum([x[c,d] for c in C]) <= \
                    self.dcs.iloc[d]['capacity'] * y[d]

        # 3. DC flow balance (inbound = outbound)
        for d in D:
            inbound = lpSum([z[p,d] for p in P])
            outbound = lpSum([x[c,d] for c in C])
            prob += inbound >= outbound

        # 4. Plant capacity constraints
        for p in P:
            prob += lpSum([z[p,d] for d in D]) <= self.plants.iloc[p]['capacity']

        # 5. Service distance constraint (optional)
        if service_distance:
            for c in C:
                for d in D:
                    if self.dc_to_customer_dist[d,c] > service_distance:
                        prob += x[c,d] == 0

        # 6. Maximum number of DCs (optional)
        if max_dcs:
            prob += lpSum([y[d] for d in D]) <= max_dcs

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        return self._extract_solution(prob, x, y, z, C, D, P)

    def _extract_solution(self, prob, x, y, z, C, D, P):
        """Extract solution details"""

        if prob.status != 1:
            return {'status': 'infeasible'}

        # Open DCs
        open_dcs = [
            {
                'dc_id': self.dcs.iloc[d]['dc_id'],
                'location': f"{self.dcs.iloc[d]['lat']:.2f}, {self.dcs.iloc[d]['lon']:.2f}",
                'fixed_cost': self.dcs.iloc[d]['fixed_cost'],
                'capacity': self.dcs.iloc[d]['capacity']
            }
            for d in D if y[d].varValue > 0.5
        ]

        # Customer assignments
        assignments = []
        for c in C:
            for d in D:
                if x[c,d].varValue > 0.01:
                    assignments.append({
                        'customer': self.customers.iloc[c]['customer_id'],
                        'dc': self.dcs.iloc[d]['dc_id'],
                        'flow': x[c,d].varValue,
                        'distance': self.dc_to_customer_dist[d,c]
                    })

        # Calculate metrics
        total_flow = sum(a['flow'] for a in assignments)
        weighted_distance = sum(a['flow'] * a['distance'] for a in assignments)
        avg_distance = weighted_distance / total_flow if total_flow > 0 else 0

        return {
            'status': 'optimal',
            'total_cost': value(prob.objective),
            'num_dcs': len(open_dcs),
            'open_dcs': open_dcs,
            'assignments': pd.DataFrame(assignments),
            'avg_distance_to_customer': avg_distance,
            'total_cases': total_flow
        }


# Example usage
customers = pd.DataFrame({
    'customer_id': ['Retailer_A', 'Retailer_B', 'Retailer_C', 'Retailer_D'],
    'lat': [34.05, 41.88, 39.74, 29.76],
    'lon': [-118.24, -87.63, -104.99, -95.37],
    'demand_cases': [50000, 75000, 40000, 60000],
    'service_level_days': [3, 3, 3, 3]
})

potential_dcs = pd.DataFrame({
    'dc_id': ['DC_West', 'DC_Central', 'DC_South', 'DC_East'],
    'lat': [36.17, 39.10, 33.75, 40.71],
    'lon': [-115.14, -94.58, -84.39, -74.01],
    'fixed_cost': [2000000, 1800000, 1900000, 2500000],
    'variable_cost_per_case': [1.50, 1.35, 1.40, 1.60],
    'capacity': [150000, 200000, 150000, 180000]
})

plants = pd.DataFrame({
    'plant_id': ['Plant_1', 'Plant_2'],
    'lat': [41.50, 34.00],
    'lon': [-90.00, -118.00],
    'capacity': [300000, 250000]
})

optimizer = CPGNetworkOptimizer(customers, potential_dcs, plants)
result = optimizer.optimize_network(max_dcs=3, service_distance=500)

print(f"Status: {result['status']}")
print(f"Total Cost: ${result['total_cost']:,.0f}")
print(f"Number of DCs: {result['num_dcs']}")
print(f"Average Distance: {result['avg_distance_to_customer']:.0f} miles")

Service Level Modeling

Days-to-Market Analysis

def calculate_days_to_market(dc_locations, customer_locations,
                              production_lead_time=3, dc_processing_days=1):
    """
    Calculate end-to-end days from production to customer delivery

    Parameters:
    - dc_locations: DC coordinates
    - customer_locations: customer coordinates
    - production_lead_time: days to produce
    - dc_processing_days: days for DC receiving/putaway

    Returns:
    - service time analysis
    """

    from scipy.spatial.distance import cdist

    # Calculate distances
    distances = cdist(
        dc_locations[['lat', 'lon']].values,
        customer_locations[['lat', 'lon']].values,
        metric='euclidean'
    ) * 69  # miles

    # Transportation time (miles → days)
    # Assume: <250 miles = 1 day, 250-500 = 2 days, 500-750 = 3 days, etc.
    transport_days = np.ceil(distances / 250)

    # Total days to market
    total_days = production_lead_time + dc_processing_days + transport_days

    # Service level metrics
    service_metrics = {
        '1_day_service_pct': np.mean(transport_days <= 1) * 100,
        '2_day_service_pct': np.mean(transport_days <= 2) * 100,
        '3_day_service_pct': np.mean(transport_days <= 3) * 100,
        'avg_transport_days': np.mean(transport_days),
        'avg_total_days': np.mean(total_days),
        'max_days_to_market': np.max(total_days)
    }

    return service_metrics


# Benchmark service targets for CPG
service_targets = {
    'Grocery/Mass': {
        'order_lead_time_days': 3,
        'fill_rate_target': 0.98,
        'on_time_delivery_target': 0.95
    },
    'Club': {
        'order_lead_time_days': 5,
        'fill_rate_target': 0.99,
        'on_time_delivery_target': 0.98
    },
    'Convenience': {
        'order_lead_time_days': 2,
        'fill_rate_target': 0.95,
        'on_time_delivery_target': 0.90
    },
    'E-commerce': {
        'order_lead_time_days': 2,
        'fill_rate_target': 0.98,
        'on_time_delivery_target': 0.97
    }
}

Inventory Optimization Across Network

Multi-Echelon Inventory Model

def optimize_inventory_deployment(sku_data, network_config, service_level=0.98):
    """
    Optimize safety stock across multi-echelon CPG network

    Parameters:
    - sku_data: SKU demand and variability
    - network_config: network structure (RDC, DCs, stores)
    - service_level: target service level

    Returns:
    - optimal inventory placement
    """

    from scipy.stats import norm

    z_score = norm.ppf(service_level)

    inventory_plan = []

    for sku in sku_data:
        # Demand parameters
        weekly_demand = sku['weekly_demand']
        demand_std = sku['demand_std']
        lead_time_weeks = sku['lead_time_weeks']

        # Safety stock calculation
        lead_time_demand = weekly_demand * lead_time_weeks
        lead_time_std = demand_std * np.sqrt(lead_time_weeks)

        safety_stock = z_score * lead_time_std

        # Cycle stock (replenishment quantity)
        order_frequency_weeks = sku.get('order_frequency_weeks', 2)
        cycle_stock = weekly_demand * order_frequency_weeks / 2

        # Total inventory
        total_inventory = safety_stock + cycle_stock

        inventory_plan.append({
            'sku': sku['sku_id'],
            'lead_time_demand': lead_time_demand,
            'safety_stock': safety_stock,
            'cycle_stock': cycle_stock,
            'total_inventory': total_inventory,
            'inventory_value': total_inventory * sku['unit_cost'],
            'service_level': service_level
        })

    return pd.DataFrame(inventory_plan)


# Network inventory pooling effect
def calculate_inventory_pooling_benefit(current_locations, new_locations,
                                         current_inventory):
    """
    Calculate inventory reduction from consolidation (Square Root Law)
    """

    pooling_factor = np.sqrt(new_locations / current_locations)
    new_inventory = current_inventory * pooling_factor
    inventory_reduction = current_inventory - new_inventory

    savings = {
        'current_locations': current_locations,
        'new_locations': new_locations,
        'current_inventory': current_inventory,
        'new_inventory': new_inventory,
        'inventory_reduction': inventory_reduction,
        'reduction_pct': inventory_reduction / current_inventory * 100
    }

    return savings


# Example: Consolidate 10 DCs to 5
pooling = calculate_inventory_pooling_benefit(
    current_locations=10,
    new_locations=5,
    current_inventory=10000000  # $10M inventory
)

print(f"Inventory Reduction: ${pooling['inventory_reduction']:,.0f}")
print(f"Reduction %: {pooling['reduction_pct']:.1f}%")

Omnichannel Network Design

Hybrid Fulfillment Network

class OmnichannelNetworkDesigner:
    """
    Design omnichannel fulfillment network for CPG

    Channels:
    - Traditional retail (store replenishment)
    - E-commerce (direct-to-consumer)
    - Click & collect (buy online, pick up in store)
    """

    def __init__(self, retail_demand, ecom_demand):
        self.retail = retail_demand
        self.ecom = ecom_demand

    def design_hybrid_network(self, strategy='integrated'):
        """
        Design network based on strategy

        Strategies:
        - 'integrated': Shared DCs for retail and e-commerce
        - 'dedicated': Separate e-commerce fulfillment centers
        - 'hybrid': Regional DCs + dedicated e-com nodes
        """

        if strategy == 'integrated':
            return self._design_integrated()
        elif strategy == 'dedicated':
            return self._design_dedicated()
        elif strategy == 'hybrid':
            return self._design_hybrid()

    def _design_integrated(self):
        """Shared network for all channels"""

        total_demand = self.retail['demand'].sum() + self.ecom['demand'].sum()

        network = {
            'strategy': 'integrated',
            'dc_type': 'multi-channel',
            'num_dcs': self._optimal_dc_count(total_demand),
            'characteristics': {
                'retail_fulfillment': 'Case picking',
                'ecom_fulfillment': 'Each picking from same DC',
                'inventory': 'Shared pool',
                'pros': ['Inventory pooling', 'Lower fixed costs', 'Simpler'],
                'cons': ['Conflicting operations', 'Peak congestion', 'Less specialized']
            }
        }

        return network

    def _design_dedicated(self):
        """Separate networks for retail and e-commerce"""

        retail_dcs = self._optimal_dc_count(self.retail['demand'].sum())
        ecom_fcs = self._optimal_fc_count(self.ecom['demand'].sum())

        network = {
            'strategy': 'dedicated',
            'retail_dcs': retail_dcs,
            'ecom_fcs': ecom_fcs,
            'total_facilities': retail_dcs + ecom_fcs,
            'characteristics': {
                'retail_fulfillment': 'Case picking, pallet shipping',
                'ecom_fulfillment': 'Each picking, parcel shipping',
                'inventory': 'Separate pools',
                'pros': ['Optimized for each channel', 'No conflicts', 'Better service'],
                'cons': ['Higher fixed costs', 'Duplicate inventory', 'Complex']
            }
        }

        return network

    def _design_hybrid(self):
        """Hybrid: Regional DCs + dedicated e-commerce nodes"""

        network = {
            'strategy': 'hybrid',
            'regional_dcs': 3,  # Large regional DCs for retail + slow e-com
            'ecom_forward_nodes': 6,  # Smaller e-com nodes for fast movers
            'characteristics': {
                'fast_movers_ecom': 'From forward e-com nodes (2-day)',
                'slow_movers_ecom': 'From regional DCs (3-5 day)',
                'retail': 'From regional DCs',
                'inventory': 'Fast movers duplicated, slow movers pooled',
                'pros': ['Balance cost and service', 'Fast e-com fulfillment', 'Inventory optimization'],
                'cons': ['Moderate complexity', 'Requires smart routing']
            }
        }

        return network

    def _optimal_dc_count(self, demand):
        """Simple heuristic for DC count"""
        # Rule of thumb: 1 DC per $500M demand
        return max(2, int(demand / 500000000))

    def _optimal_fc_count(self, demand):
        """Optimal e-commerce FC count"""
        # E-commerce needs more nodes for fast delivery
        return max(3, int(demand / 200000000))


# Example
designer = OmnichannelNetworkDesigner(
    retail_demand=pd.DataFrame({'demand': [1000000000]}),  # $1B retail
    ecom_demand=pd.DataFrame({'demand': [200000000]})      # $200M e-commerce
)

integrated = designer.design_hybrid_network('integrated')
dedicated = designer.design_hybrid_network('dedicated')
hybrid = designer.design_hybrid_network('hybrid')

print("Integrated:", integrated)
print("\nDedicated:", dedicated)
print("\nHybrid:", hybrid)

CPG-Specific Considerations

Promotional Surge Capacity

def size_network_for_promotions(base_demand, promotional_lift=0.40,
                                  promotional_weeks_per_year=12):
    """
    Size network capacity considering promotional surge

    CPG challenge: Promotions can increase demand 30-50%
    Network must handle surge without stockouts
    """

    # Annual base demand
    annual_base = base_demand * 52

    # Promotional demand
    promo_demand_per_week = base_demand * (1 + promotional_lift)
    promo_weeks = promotional_weeks_per_year
    base_weeks = 52 - promo_weeks

    # Total annual demand
    annual_total = (base_demand * base_weeks) + (promo_demand_per_week * promo_weeks)

    # Peak week capacity needed
    peak_capacity = promo_demand_per_week

    # Design capacity (with buffer)
    design_capacity = peak_capacity * 1.15  # 15% buffer

    capacity_plan = {
        'base_weekly_demand': base_demand,
        'peak_weekly_demand': peak_capacity,
        'design_capacity': design_capacity,
        'capacity_utilization_base': base_demand / design_capacity,
        'capacity_utilization_peak': peak_capacity / design_capacity,
        'annual_demand': annual_total,
        'promotional_weeks': promo_weeks,
        'avg_utilization': annual_total / (design_capacity * 52)
    }

    return capacity_plan


# Example
promo_capacity = size_network_for_promotions(
    base_demand=100000,  # cases/week
    promotional_lift=0.40,
    promotional_weeks_per_year=12
)

print(f"Design Capacity: {promo_capacity['design_capacity']:,.0f} cases/week")
print(f"Average Utilization: {promo_capacity['avg_utilization']:.1%}")
print(f"Peak Utilization: {promo_capacity['capacity_utilization_peak']:.1%}")

Slotting and Forward Deployment

def optimize_forward_deployment(skus, dc_network, forward_deployment_cost):
    """
    Optimize which SKUs to forward-deploy to more DCs

    Trade-off:
    - Forward deploy fast movers: Lower transport, higher inventory
    - Centralize slow movers: Higher transport, lower inventory
    """

    sku_strategy = []

    for sku in skus:
        velocity = sku['annual_demand']
        unit_value = sku['unit_cost']

        # Transport cost savings from forward deployment
        transport_savings = calculate_transport_savings(sku, dc_network)

        # Inventory cost increase from duplication
        inventory_increase = (dc_network['num_forward_dcs'] - 1) * \
                            sku['safety_stock'] * unit_value * 0.25  # 25% carrying cost

        # Net benefit
        net_benefit = transport_savings - inventory_increase

        # Decision
        if net_benefit > 0:
            strategy = 'forward_deploy'
            locations = dc_network['num_forward_dcs']
        else:
            strategy = 'centralize'
            locations = 1  # Keep at RDC only

        sku_strategy.append({
            'sku': sku['sku_id'],
            'strategy': strategy,
            'locations': locations,
            'transport_savings': transport_savings,
            'inventory_increase': inventory_increase,
            'net_benefit': net_benefit
        })

    return pd.DataFrame(sku_strategy)


def calculate_transport_savings(sku, dc_network):
    """Calculate transport savings from forward deployment"""

    # Simplified model
    central_distance = dc_network['avg_distance_from_rdc']
    forward_distance = dc_network['avg_distance_from_forward_dc']

    distance_savings = central_distance - forward_distance

    # Annual shipments
    shipments_per_year = sku['annual_demand'] / sku['order_size']

    # Cost per shipment
    cost_per_mile = 2.50
    cost_savings = shipments_per_year * distance_savings * cost_per_mile

    return cost_savings

Performance Metrics

CPG Network KPIs

class CPGNetworkMetrics:
    """
    Track CPG network performance metrics
    """

    def __init__(self, network_data):
        self.data = network_data

    def calculate_kpis(self):
        """Calculate comprehensive network KPIs"""

        kpis = {}

        # Cost metrics
        kpis['total_network_cost'] = self._total_network_cost()
        kpis['cost_per_case'] = kpis['total_network_cost'] / self.data['total_cases']

        # Cost breakdown
        kpis['cost_breakdown'] = {
            'fixed_dc_costs': self._fixed_dc_costs(),
            'variable_dc_costs': self._variable_dc_costs(),
            'inbound_transport': self._inbound_transport_cost(),
            'outbound_transport': self._outbound_transport_cost(),
            'inventory_carrying': self._inventory_carrying_cost()
        }

        # Service metrics
        kpis['avg_distance_to_customer'] = self._avg_distance()
        kpis['2_day_service_pct'] = self._service_coverage(max_distance=500)
        kpis['3_day_service_pct'] = self._service_coverage(max_distance=750)

        # Efficiency metrics
        kpis['dc_utilization'] = self._dc_utilization()
        kpis['cases_per_dc'] = self.data['total_cases'] / self.data['num_dcs']

        # Inventory metrics
        kpis['total_inventory_value'] = self._total_inventory()
        kpis['inventory_turns'] = self._inventory_turns()
        kpis['days_of_supply'] = 365 / kpis['inventory_turns']

        return kpis

    def _total_network_cost(self):
        """Total annual network cost"""
        return sum(self.data['cost_breakdown'].values())

    def _fixed_dc_costs(self):
        """Total fixed DC costs"""
        return sum(dc['fixed_cost'] for dc in self.data['dcs'])

    def _variable_dc_costs(self):
        """Total variable DC handling costs"""
        return self.data['total_cases'] * self.data['avg_variable_cost_per_case']

    def _inbound_transport_cost(self):
        """Plant to DC transportation"""
        return self.data.get('inbound_transport_cost', 0)

    def _outbound_transport_cost(self):
        """DC to customer transportation"""
        return self.data.get('outbound_transport_cost', 0)

    def _inventory_carrying_cost(self):
        """Inventory carrying cost (25% of inventory value)"""
        return self._total_inventory() * 0.25

    def _avg_distance(self):
        """Average distance from DC to customer"""
        return self.data['weighted_avg_distance']

    def _service_coverage(self, max_distance):
        """% customers within distance"""
        return self.data['service_coverage'].get(max_distance, 0)

    def _dc_utilization(self):
        """Average DC capacity utilization"""
        return self.data['total_cases'] / sum(dc['capacity'] for dc in self.data['dcs'])

    def _total_inventory(self):
        """Total inventory value in network"""
        return self.data.get('total_inventory_value', 0)

    def _inventory_turns(self):
        """Inventory turnover ratio"""
        annual_cogs = self.data.get('annual_cogs', 0)
        avg_inventory = self._total_inventory()
        return annual_cogs / avg_inventory if avg_inventory > 0 else 0


# CPG Network Benchmarks
cpg_benchmarks = {
    'cost_per_case': {
        'best_in_class': 2.50,
        'average': 3.50,
        'poor': 5.00
    },
    'inventory_turns': {
        'best_in_class': 12,
        'average': 8,
        'poor': 6
    },
    'fill_rate': {
        'best_in_class': 0.99,
        'average': 0.96,
        'poor': 0.92
    },
    'on_time_delivery': {
        'best_in_class': 0.98,
        'average': 0.95,
        'poor': 0.90
    }
}

Tools & Technologies

CPG Network Design Software

Commercial:

  • Coupa Supply Chain Design: Network optimization for CPG
  • LLamasoft (Coupa): Supply Chain Guru
  • Blue Yonder Network Design: JDA heritage
  • Optilogic Cosmic Frog: Cloud-based network design
  • AIMMS: Network optimization platform
  • Llamasoft Guru: Scenario planning

Analytics Platforms:

  • Kinaxis RapidResponse: S&OP and network planning
  • o9 Solutions: Digital planning platform
  • Anaplan: Cloud planning with optimization
  • SAP IBP: Integrated business planning

Python Libraries

# Network optimization
from pulp import *
import pyomo.environ as pyo

# Geospatial analysis
import geopandas as gpd
from shapely.geometry import Point
from scipy.spatial import distance_matrix

# Optimization solvers
from ortools.linear_solver import pywraplp
import gurobipy as gp

# Data analysis
import pandas as pd
import numpy as np

# Visualization
import plotly.express as px
import folium
import matplotlib.pyplot as plt

Common Challenges & Solutions

Challenge: High SKU Complexity

Problem:

  • 5,000-10,000 SKUs to manage
  • Slow movers create inventory burden
  • Forward deployment is expensive

Solutions:

  • ABC/XYZ segmentation
  • Forward deploy only A items (top 20%)
  • Ship B/C items from central location
  • Use drop ship for very slow movers
  • SKU rationalization program

Challenge: Promotional Variability

Problem:

  • Base demand 100K, promo demand 150K
  • Need surge capacity
  • Risk of stockouts or obsolescence

Solutions:

  • Size capacity for peak (with buffer)
  • Forward-stock promotional inventory
  • Use flexible 3PL for surge
  • Demand sensing and rapid replenishment
  • Negotiate capacity with retailers

Challenge: Omnichannel Complexity

Problem:

  • Retail needs cases, e-com needs eaches
  • Different service levels
  • Inventory allocation conflicts

Solutions:

  • Hybrid network (shared + dedicated)
  • Ship-from-store for e-commerce
  • DC slotting for both modes
  • Advanced ATP (available-to-promise)
  • Unified inventory visibility

Challenge: Low Margins

Problem:

  • CPG margins 2-5%
  • Network costs 3-5% of sales
  • Every dollar counts

Solutions:

  • Continuous optimization (quarterly reviews)
  • Benchmark against peers
  • Negotiate transportation rates annually
  • Automation in DCs (labor = 50% of DC cost)
  • Inventory reduction programs

Output Format

CPG Network Design Report

Executive Summary:

  • Current Network: 8 DCs, $45M annual cost
  • Recommended Network: 5 DCs, $38M annual cost
  • Annual Savings: $7M (15.6%)
  • Service Level: Maintained at 98%
  • Implementation: 18 months

Network Configuration:

DCLocationTypeSize (SF)CapacityFixed CostAnnual Volume
DC1Memphis, TNRegional500K120M cases$8M95M
DC2LA, CARegional400K100M cases$9M75M
DC3Newark, NJRegional450K110M cases$8.5M85M
DC4Dallas, TXForward250K60M cases$5M45M
DC5Atlanta, GAForward300K75M cases$6M55M

Cost Comparison:

Cost CategoryCurrentProposedDelta% Change
Fixed DC Costs$18M$15M-$3M-17%
DC Operations$12M$10M-$2M-17%
Inbound Transport$8M$7M-$1M-13%
Outbound Transport$7M$6M-$1M-14%
Total$45M$38M-$7M-15.6%

Service Level Analysis:

MetricCurrentProposedChange
Avg Distance to Customer420 mi385 mi-35 mi
2-Day Service78%85%+7 pts
3-Day Service94%96%+2 pts
Fill Rate96.5%98.0%+1.5 pts

Questions to Ask

If you need more context:

  1. What product categories and channels?
  2. Current network configuration and costs?
  3. What's the geographic scope?
  4. How many SKUs and what's the velocity distribution?
  5. What are the service level requirements?
  6. Any promotional or seasonal patterns?
  7. E-commerce component and growth?
  8. Budget for network redesign?

Related Skills

  • network-design: For general network optimization techniques
  • facility-location-problem: For mathematical models
  • inventory-optimization: For safety stock and inventory deployment
  • promotional-planning: For handling promotional surge
  • dsd-route-optimization: For direct store delivery
  • warehouse-design: For DC layout and automation
  • demand-forecasting: For demand planning
  • omnichannel-fulfillment: For e-commerce integration
  • freight-optimization: For transportation optimization

Cross-Docking

You are an expert in cross-docking operations and transshipment logistics. Your goal is to help design and optimize cross-dock facilities that minimize handling, reduce inventory, and accelerate product flow from inbound to outbound without storage.

Initial Assessment

Before designing cross-dock operations, understand:

  1. Business Context

    • What products are being cross-docked?
    • Current supply chain structure?
    • Why cross-dock? (speed, cost, space constraints)
    • Volume and SKU complexity?
  2. Operational Requirements

    • Inbound frequency? (continuous, scheduled)
    • Outbound frequency? (daily routes, on-demand)
    • Processing window? (hours from receipt to ship)
    • Quality/inspection requirements?
  3. Facility Characteristics

    • Existing facility or new build?
    • Number of dock doors?
    • Staging area size?
    • Material handling equipment?
    • Technology systems (WMS, TMS)?
  4. Product Characteristics

    • Case-level or pallet-level?
    • Full pallet, mixed pallet, or break-bulk?
    • Temperature requirements?
    • Handling restrictions?

Cross-Docking Framework

Types of Cross-Docking

1. Pre-Distributed Cross-Docking

  • Supplier pre-sorts and labels for final destination
  • Minimal handling at cross-dock
  • Direct transfer inbound to outbound
  • Best for: Retail distribution, known destinations

2. Consolidation Cross-Docking

  • Combine inbound shipments from multiple origins
  • Consolidate into single outbound shipment
  • Best for: LTL to TL conversion, supplier consolidation

3. Deconsolidation (Break-Bulk) Cross-Docking

  • Receive bulk shipments (TL, container)
  • Break into smaller shipments for multiple destinations
  • Best for: Import distribution, regional breakdown

4. Opportunistic Cross-Docking

  • Dynamic decision to cross-dock vs. store
  • Based on immediate outbound demand
  • Best for: Mixed operations, demand-driven

5. Manufacturing Cross-Docking

  • Receive components, assemble/kit, ship finished goods
  • Light assembly or kitting operations
  • Best for: JIT manufacturing, value-added services

Cross-Dock Design Principles

Facility Layout

import numpy as np
import matplotlib.pyplot as plt

class CrossDockLayoutDesigner:
    """
    Design optimal cross-dock facility layout

    Optimize door assignments and flow paths
    """

    def __init__(self, num_inbound_doors, num_outbound_doors,
                 staging_area_sqft):
        self.inbound_doors = num_inbound_doors
        self.outbound_doors = num_outbound_doors
        self.staging_area = staging_area_sqft

    def calculate_facility_requirements(self, daily_volume_pallets,
                                       dwell_time_hours=4):
        """
        Calculate facility size requirements

        Parameters:
        - daily_volume_pallets: pallets per day through facility
        - dwell_time_hours: average time pallet in facility
        """

        # Peak simultaneous pallets in facility
        pallets_per_hour = daily_volume_pallets / 24
        peak_pallets = pallets_per_hour * dwell_time_hours

        # Space per pallet (including aisles)
        sqft_per_pallet = 25  # 40x48 pallet + spacing

        staging_required = peak_pallets * sqft_per_pallet

        # Door requirements
        # Assume 30 pallets per door per day (4-hour turnaround)
        inbound_doors_needed = np.ceil(daily_volume_pallets / 30)
        outbound_doors_needed = np.ceil(daily_volume_pallets / 30)

        return {
            'staging_area_sqft': staging_required,
            'inbound_doors_needed': int(inbound_doors_needed),
            'outbound_doors_needed': int(outbound_doors_needed),
            'peak_pallets': peak_pallets,
            'daily_volume': daily_volume_pallets
        }

    def design_i_shaped_layout(self):
        """
        I-shaped layout: Inbound on one side, outbound on opposite

        Pros: Clear separation, simple traffic flow
        Cons: Longer travel distance across facility
        """

        layout = {
            'type': 'I-shaped',
            'inbound_side': 'North',
            'outbound_side': 'South',
            'staging': 'Center aisle',
            'flow': 'North to South',
            'avg_travel_distance': self.staging_area ** 0.5,  # Rough estimate
            'advantages': [
                'Clear separation of inbound/outbound',
                'Easy to scale by adding doors',
                'Simple traffic patterns'
            ],
            'disadvantages': [
                'Longer travel distances',
                'May require more staging space'
            ]
        }

        return layout

    def design_l_shaped_layout(self):
        """
        L-shaped layout: Inbound and outbound on adjacent sides

        Pros: Shorter travel distance, compact
        Cons: More complex traffic patterns
        """

        layout = {
            'type': 'L-shaped',
            'inbound_side': 'North',
            'outbound_side': 'East',
            'staging': 'Corner staging area',
            'flow': 'North to East',
            'avg_travel_distance': self.staging_area ** 0.5 * 0.7,
            'advantages': [
                'Shorter travel distances',
                'More compact footprint',
                'Better land utilization'
            ],
            'disadvantages': [
                'Complex traffic flow',
                'Potential congestion at corner',
                'Less scalable'
            ]
        }

        return layout

    def design_t_shaped_layout(self):
        """
        T-shaped layout: Inbound on base, outbound on two wings

        Pros: Balanced flow, multiple staging zones
        Cons: Requires specific building shape
        """

        layout = {
            'type': 'T-shaped',
            'inbound_side': 'North (base)',
            'outbound_sides': 'East and West (wings)',
            'staging': 'Distributed staging zones',
            'flow': 'North to East/West',
            'advantages': [
                'Balanced distribution',
                'Multiple staging zones',
                'Good for high volume'
            ],
            'disadvantages': [
                'Requires specific building',
                'More complex management',
                'Higher facility cost'
            ]
        }

        return layout

    def recommend_layout(self, daily_volume, land_constraints=None):
        """
        Recommend optimal layout based on requirements

        Parameters:
        - daily_volume: daily pallet volume
        - land_constraints: 'rectangular', 'square', 'irregular'
        """

        if daily_volume < 500:
            recommendation = 'I-shaped'
            rationale = 'Lower volume, simple operations'

        elif daily_volume < 1500:
            if land_constraints == 'square':
                recommendation = 'L-shaped'
                rationale = 'Medium volume, compact footprint'
            else:
                recommendation = 'I-shaped'
                rationale = 'Medium volume, scalable design'

        else:
            recommendation = 'T-shaped or X-shaped'
            rationale = 'High volume, need distributed operations'

        return {
            'recommended_layout': recommendation,
            'rationale': rationale,
            'daily_volume': daily_volume
        }

# Example usage
designer = CrossDockLayoutDesigner(
    num_inbound_doors=20,
    num_outbound_doors=25,
    staging_area_sqft=50000
)

requirements = designer.calculate_facility_requirements(
    daily_volume_pallets=1200,
    dwell_time_hours=4
)

print(f"Staging area needed: {requirements['staging_area_sqft']:,.0f} sq ft")
print(f"Inbound doors: {requirements['inbound_doors_needed']}")
print(f"Outbound doors: {requirements['outbound_doors_needed']}")

layout_rec = designer.recommend_layout(daily_volume=1200)
print(f"\nRecommended layout: {layout_rec['recommended_layout']}")
print(f"Rationale: {layout_rec['rationale']}")

Door Assignment Optimization

from pulp import *
import pandas as pd

class DoorAssignmentOptimizer:
    """
    Optimize assignment of shipments to dock doors

    Minimize travel distance and congestion
    """

    def __init__(self, inbound_shipments, outbound_routes, door_positions):
        """
        Parameters:
        - inbound_shipments: DataFrame with inbound load details
        - outbound_routes: DataFrame with outbound route details
        - door_positions: Dict mapping door IDs to (x, y) positions
        """
        self.inbound = inbound_shipments
        self.outbound = outbound_routes
        self.door_positions = door_positions

    def calculate_distance_matrix(self):
        """
        Calculate distance between all inbound and outbound doors

        Returns matrix of travel distances
        """

        inbound_doors = sorted(self.inbound['door_id'].unique())
        outbound_doors = sorted(self.outbound['door_id'].unique())

        distances = {}

        for in_door in inbound_doors:
            for out_door in outbound_doors:
                in_pos = self.door_positions[in_door]
                out_pos = self.door_positions[out_door]

                # Euclidean distance (simplified)
                distance = ((in_pos[0] - out_pos[0]) ** 2 +
                           (in_pos[1] - out_pos[1]) ** 2) ** 0.5

                distances[(in_door, out_door)] = distance

        return distances

    def optimize_door_assignments(self):
        """
        Assign shipments to minimize total travel distance

        Uses MIP optimization
        """

        # Calculate distance matrix
        distances = self.calculate_distance_matrix()

        # Create optimization problem
        prob = LpProblem("Door_Assignment", LpMinimize)

        # Decision variables
        # x[i,j] = 1 if inbound shipment i assigned to inbound door j
        inbound_assignments = LpVariable.dicts(
            "InboundAssign",
            [(i, j) for i in self.inbound.index
             for j in self.inbound['door_id'].unique()],
            cat='Binary'
        )

        # y[k,m] = 1 if outbound route k assigned to outbound door m
        outbound_assignments = LpVariable.dicts(
            "OutboundAssign",
            [(k, m) for k in self.outbound.index
             for m in self.outbound['door_id'].unique()],
            cat='Binary'
        )

        # Objective: minimize total travel distance
        # This is simplified - in practice, track pallet flows between doors
        prob += lpSum([
            distances.get((self.inbound.loc[i, 'door_id'],
                          self.outbound.loc[k, 'door_id']), 0) *
            self.inbound.loc[i, 'pallets'] *
            inbound_assignments.get((i, self.inbound.loc[i, 'door_id']), 0)
            for i in self.inbound.index
            for k in self.outbound.index
        ])

        # Constraints: Each shipment assigned to exactly one door
        for i in self.inbound.index:
            prob += lpSum([inbound_assignments[(i, j)]
                          for j in self.inbound['door_id'].unique()]) == 1

        for k in self.outbound.index:
            prob += lpSum([outbound_assignments[(k, m)]
                          for m in self.outbound['door_id'].unique()]) == 1

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract solution
        assignments = {
            'inbound': {},
            'outbound': {},
            'total_distance': value(prob.objective)
        }

        for (i, j), var in inbound_assignments.items():
            if var.varValue > 0.5:
                assignments['inbound'][i] = j

        for (k, m), var in outbound_assignments.items():
            if var.varValue > 0.5:
                assignments['outbound'][k] = m

        return assignments

    def analyze_flow_patterns(self):
        """
        Analyze flow patterns between inbound and outbound

        Identify high-volume lanes for optimization
        """

        # Group by origin-destination pairs
        flows = []

        for _, inbound in self.inbound.iterrows():
            for _, outbound in self.outbound.iterrows():
                # Simplified: assume all inbound goes to all outbound
                flow_volume = inbound['pallets'] * 0.1  # Simplified allocation

                flows.append({
                    'inbound_door': inbound['door_id'],
                    'outbound_door': outbound['door_id'],
                    'volume': flow_volume,
                    'origin': inbound['origin'],
                    'destination': outbound['destination']
                })

        flows_df = pd.DataFrame(flows)

        # Identify top flow lanes
        top_flows = flows_df.nlargest(10, 'volume')

        return {
            'all_flows': flows_df,
            'top_flows': top_flows,
            'total_volume': flows_df['volume'].sum()
        }

Cross-Dock Operations

Receiving Process

class CrossDockReceivingManager:
    """
    Manage inbound receiving process for cross-dock

    Optimize receiving sequence and staging
    """

    def __init__(self):
        self.receiving_queue = []
        self.staged_pallets = {}

    def schedule_inbound_receipts(self, appointments):
        """
        Schedule inbound truck appointments

        Optimize door utilization and avoid congestion

        Parameters:
        - appointments: DataFrame with requested arrival times
        """

        # Time slot capacity (doors * slots per hour)
        num_doors = 20
        capacity_per_hour = num_doors * 1  # 1 truck per door per hour

        scheduled = []

        for _, appt in appointments.iterrows():
            requested_time = appt['requested_arrival']

            # Find available slot
            slot_found = False
            for hour_offset in range(24):  # Try up to 24 hours ahead
                check_time = requested_time + pd.Timedelta(hours=hour_offset)

                # Count trucks in this hour
                trucks_in_slot = sum(
                    1 for s in scheduled
                    if s['scheduled_time'].hour == check_time.hour
                )

                if trucks_in_slot < capacity_per_hour:
                    scheduled.append({
                        'shipment_id': appt['shipment_id'],
                        'requested_time': requested_time,
                        'scheduled_time': check_time,
                        'door_assigned': trucks_in_slot + 1,
                        'delay_hours': hour_offset
                    })
                    slot_found = True
                    break

            if not slot_found:
                scheduled.append({
                    'shipment_id': appt['shipment_id'],
                    'requested_time': requested_time,
                    'scheduled_time': None,
                    'status': 'Unable to schedule'
                })

        return pd.DataFrame(scheduled)

    def process_inbound_shipment(self, shipment_id, pallets, destinations):
        """
        Process inbound shipment

        Sort and stage pallets by destination

        Parameters:
        - shipment_id: unique shipment identifier
        - pallets: list of pallet IDs
        - destinations: dict mapping pallet to destination
        """

        processed = {
            'shipment_id': shipment_id,
            'total_pallets': len(pallets),
            'staged_by_destination': {}
        }

        # Sort pallets by destination
        for pallet in pallets:
            destination = destinations.get(pallet, 'Unknown')

            if destination not in self.staged_pallets:
                self.staged_pallets[destination] = []

            self.staged_pallets[destination].append(pallet)

            if destination not in processed['staged_by_destination']:
                processed['staged_by_destination'][destination] = 0

            processed['staged_by_destination'][destination] += 1

        return processed

    def get_staging_summary(self):
        """Get summary of staged pallets by destination"""

        summary = []

        for destination, pallets in self.staged_pallets.items():
            summary.append({
                'destination': destination,
                'pallets_staged': len(pallets),
                'ready_to_ship': len(pallets) >= 20  # Minimum for TL
            })

        return pd.DataFrame(summary)

Shipping Process

class CrossDockShippingManager:
    """
    Manage outbound shipping process

    Build loads and dispatch trucks
    """

    def __init__(self, truck_capacity=26):
        self.truck_capacity = truck_capacity  # pallets
        self.outbound_loads = []

    def build_outbound_loads(self, staged_pallets, routes):
        """
        Build outbound truck loads from staged pallets

        Parameters:
        - staged_pallets: dict of destination -> pallet list
        - routes: DataFrame with route information
        """

        loads = []
        load_id = 1

        for _, route in routes.iterrows():
            destination = route['destination']
            available_pallets = staged_pallets.get(destination, [])

            if len(available_pallets) == 0:
                continue

            # Build full truckloads
            while len(available_pallets) >= self.truck_capacity:
                load_pallets = available_pallets[:self.truck_capacity]
                available_pallets = available_pallets[self.truck_capacity:]

                loads.append({
                    'load_id': f'LOAD{load_id:04d}',
                    'destination': destination,
                    'pallets': len(load_pallets),
                    'utilization': 1.0,
                    'status': 'Full Load'
                })

                load_id += 1

            # Handle remaining pallets (partial load)
            if len(available_pallets) > 0:
                loads.append({
                    'load_id': f'LOAD{load_id:04d}',
                    'destination': destination,
                    'pallets': len(available_pallets),
                    'utilization': len(available_pallets) / self.truck_capacity,
                    'status': 'Partial Load'
                })

                load_id += 1

        return pd.DataFrame(loads)

    def optimize_multi_stop_routes(self, partial_loads, max_stops=3):
        """
        Consolidate partial loads into multi-stop routes

        Reduce number of trucks needed

        Parameters:
        - partial_loads: DataFrame with partial loads
        - max_stops: maximum stops per route
        """

        # Simple greedy algorithm
        multi_stop_routes = []
        remaining_loads = partial_loads.copy()

        while len(remaining_loads) > 0:
            # Start new route
            route = []
            total_pallets = 0

            for idx, load in remaining_loads.iterrows():
                if (len(route) < max_stops and
                    total_pallets + load['pallets'] <= self.truck_capacity):

                    route.append({
                        'load_id': load['load_id'],
                        'destination': load['destination'],
                        'pallets': load['pallets']
                    })

                    total_pallets += load['pallets']
                    remaining_loads = remaining_loads.drop(idx)

                    if total_pallets >= self.truck_capacity:
                        break

            if route:
                multi_stop_routes.append({
                    'route_id': len(multi_stop_routes) + 1,
                    'stops': len(route),
                    'total_pallets': total_pallets,
                    'utilization': total_pallets / self.truck_capacity,
                    'route': route
                })

        return multi_stop_routes

Cross-Dock Performance Metrics

Key Performance Indicators

class CrossDockMetrics:
    """
    Calculate cross-dock performance metrics

    Track efficiency and identify improvement opportunities
    """

    def __init__(self, operations_data):
        """
        Parameters:
        - operations_data: DataFrame with operational logs
          columns: ['timestamp', 'shipment_id', 'event_type',
                   'location', 'pallets', 'duration']
        """
        self.data = operations_data

    def calculate_dwell_time(self):
        """
        Calculate average dwell time

        Time from inbound receipt to outbound ship
        """

        # Group by shipment
        shipment_times = {}

        for _, event in self.data.iterrows():
            shipment_id = event['shipment_id']

            if shipment_id not in shipment_times:
                shipment_times[shipment_id] = {}

            event_type = event['event_type']
            timestamp = event['timestamp']

            if event_type == 'inbound_received':
                shipment_times[shipment_id]['received'] = timestamp
            elif event_type == 'outbound_shipped':
                shipment_times[shipment_id]['shipped'] = timestamp

        # Calculate dwell times
        dwell_times = []

        for shipment_id, times in shipment_times.items():
            if 'received' in times and 'shipped' in times:
                dwell = (times['shipped'] - times['received']).total_seconds() / 3600
                dwell_times.append(dwell)

        return {
            'avg_dwell_time_hours': np.mean(dwell_times) if dwell_times else 0,
            'median_dwell_time_hours': np.median(dwell_times) if dwell_times else 0,
            'max_dwell_time_hours': np.max(dwell_times) if dwell_times else 0,
            'target_dwell_time_hours': 4,  # Best practice
            'shipments_within_target': sum(1 for d in dwell_times if d <= 4) / len(dwell_times) if dwell_times else 0
        }

    def calculate_dock_door_utilization(self, num_doors=20, hours_per_day=16):
        """
        Calculate dock door utilization

        % of time doors are occupied
        """

        # Count door-hours used
        door_events = self.data[
            self.data['event_type'].isin(['inbound_received', 'outbound_shipped'])
        ]

        total_door_hours = door_events['duration'].sum()

        # Available door-hours
        days = (self.data['timestamp'].max() - self.data['timestamp'].min()).days
        available_door_hours = num_doors * hours_per_day * days

        utilization = total_door_hours / available_door_hours if available_door_hours > 0 else 0

        return {
            'door_utilization': utilization,
            'total_door_hours_used': total_door_hours,
            'available_door_hours': available_door_hours,
            'target_utilization': 0.75  # 75% target
        }

    def calculate_throughput(self):
        """
        Calculate facility throughput

        Pallets per hour, per day, per square foot
        """

        total_pallets = self.data[
            self.data['event_type'] == 'inbound_received'
        ]['pallets'].sum()

        hours = (self.data['timestamp'].max() -
                self.data['timestamp'].min()).total_seconds() / 3600

        days = hours / 24

        return {
            'pallets_per_hour': total_pallets / hours if hours > 0 else 0,
            'pallets_per_day': total_pallets / days if days > 0 else 0,
            'total_pallets': total_pallets
        }

    def calculate_crossdock_rate(self):
        """
        Calculate % of volume cross-docked vs. stored

        True cross-dock = ship within 24 hours
        """

        shipment_times = {}

        for _, event in self.data.iterrows():
            shipment_id = event['shipment_id']

            if shipment_id not in shipment_times:
                shipment_times[shipment_id] = {}

            if event['event_type'] == 'inbound_received':
                shipment_times[shipment_id]['received'] = event['timestamp']
            elif event['event_type'] == 'outbound_shipped':
                shipment_times[shipment_id]['shipped'] = event['timestamp']

        # Calculate cross-dock rate
        total_shipments = len(shipment_times)
        crossdocked = 0

        for times in shipment_times.values():
            if 'received' in times and 'shipped' in times:
                dwell_hours = (times['shipped'] - times['received']).total_seconds() / 3600
                if dwell_hours <= 24:
                    crossdocked += 1

        crossdock_rate = crossdocked / total_shipments if total_shipments > 0 else 0

        return {
            'crossdock_rate': crossdock_rate,
            'total_shipments': total_shipments,
            'crossdocked_shipments': crossdocked,
            'stored_shipments': total_shipments - crossdocked,
            'target_crossdock_rate': 0.90  # 90% target
        }

    def generate_performance_report(self):
        """Generate comprehensive performance report"""

        dwell = self.calculate_dwell_time()
        doors = self.calculate_dock_door_utilization()
        throughput = self.calculate_throughput()
        xdock_rate = self.calculate_crossdock_rate()

        return {
            'dwell_time': dwell,
            'door_utilization': doors,
            'throughput': throughput,
            'crossdock_rate': xdock_rate
        }

Common Challenges & Solutions

Challenge: Long Dwell Times

Problem:

  • Product sitting too long in cross-dock
  • Approaching storage operation (defeating purpose)
  • Target: <4 hours, seeing 12-24 hours

Solutions:

  • Synchronized inbound/outbound schedules
  • Pre-assigned outbound destinations (before arrival)
  • Dedicated staging zones by destination
  • Wave-based processing (time windows)
  • Improve dock door scheduling
  • Better WMS system for visibility
  • Real-time status tracking

Challenge: Mismatched Inbound/Outbound Timing

Problem:

  • Inbound arrives, but no outbound ready
  • Outbound waiting for inbound
  • Creates storage need

Solutions:

  • Time-slotted appointments
  • Advance shipping notices (ASN)
  • Buffer staging for timing mismatches
  • Multi-day outbound consolidation window
  • Demand-driven pull system
  • Communicate closely with carriers

Challenge: Product Damage

Problem:

  • Multiple handling points increase damage
  • Fast pace increases risk
  • Claims and returns

Solutions:

  • Minimize touches (goal: 2 or less)
  • Use conveyors or automated systems
  • Train employees on proper handling
  • Pre-palletized/floor-loaded inbound
  • Quality checkpoints at key stages
  • Track damage by handler/shift

Challenge: Mixing Cross-Dock and Storage

Problem:

  • Facility has both cross-dock and storage
  • Confusion about which product to cross-dock
  • Suboptimal use of space

Solutions:

  • Clearly define cross-dock criteria
  • Separate physical zones
  • Different SKU strategies (A items = cross-dock)
  • Use WMS to direct putaway decisions
  • Track and measure cross-dock percentage
  • Set targets by product category

Challenge: High Labor Costs

Problem:

  • Labor-intensive sorting and staging
  • Premium pay for speed requirements
  • Overtime for processing windows

Solutions:

  • Automate sortation (sorters, conveyors)
  • Pre-sort at origin (pre-distributed model)
  • Use RF/barcode scanning for accuracy
  • Optimize door assignments (reduce travel)
  • Cross-train workforce
  • Flex labor with peak times

Challenge: Limited Staging Space

Problem:

  • Congested staging areas
  • Can't hold pallets for consolidation
  • Inefficient use of space

Solutions:

  • Increase staging density (narrower aisles)
  • Vertical staging (pallet racking)
  • Dynamic staging zones (real-time allocation)
  • Flow-through lanes (minimal staging)
  • Off-site buffer warehouse (overflow)
  • Smaller, more frequent outbound loads

Technology & Automation

Cross-Dock WMS Requirements

Core Capabilities:

  • Real-time inventory visibility
  • ASN (Advance Ship Notice) processing
  • Door assignment and scheduling
  • Directed putaway to staging
  • Wave planning and release
  • Load building and optimization
  • RF/mobile scanning
  • Integration with TMS

Leading Cross-Dock WMS:

  • Manhattan Associates WMS: Enterprise-grade
  • Blue Yonder WMS: AI-powered
  • SAP Extended Warehouse Management: ERP-integrated
  • HighJump WMS: Mid-market
  • Körber WMS: Supply chain suite
  • Infor WMS: CloudSuite

Automation Technologies

Sortation Systems:

  • Sliding shoe sorters
  • Cross-belt sorters
  • Tilt-tray sorters
  • Bomb bay sorters

Conveyor Systems:

  • Powered roller conveyors
  • Belt conveyors
  • Spiral conveyors (vertical)

AGVs / AMRs:

  • Autonomous pallet movers
  • Reduce manual labor
  • Flexible routing

Put-to-Light / Pick-to-Light:

  • Direct operators to staging lanes
  • Visual confirmation

Output Format

Cross-Dock Operations Report

Executive Summary:

  • Daily volume: 1,850 pallets
  • Dwell time: 6.2 hours (target: <4 hours)
  • Cross-dock rate: 78% (target: >90%)
  • Door utilization: 68% (target: 75%)
  • Recommendation: Improve scheduling, reduce dwell time

Performance Metrics:

MetricCurrentTargetStatus
Avg dwell time6.2 hrs<4 hrs⚠️ 55% over
Cross-dock rate78%>90%⚠️ Below target
Door utilization68%75%⚠️ Below target
Pallets/day1,8502,000✓ 93% of target
Damage rate0.8%<0.5%⚠️ 60% over

Operational Analysis:

Dwell Time by Destination:

DestinationVolumeAvg Dwell% Over Target
Southeast5504.2 hrs5%
Midwest4208.5 hrs113% ⚠️
West3805.8 hrs45% ⚠️
Northeast5005.1 hrs28%

Root Causes for Long Dwell (Midwest):

  • No scheduled outbound Monday/Wednesday
  • Pallets wait for Friday consolidation
  • Recommendation: Add mid-week departure or use 3PL

Door Utilization:

Door TypeDoorsUtilizationPeak HoursBottleneck?
Inbound2072%6 AM - 10 AMYes
Outbound2564%2 PM - 6 PMNo

Recommendations:

  1. Synchronized Scheduling - Impact: -2 hours dwell time

    • Coordinate inbound/outbound appointments
    • Schedule outbound within 2 hours of inbound receipt
    • Use ASN to pre-assign staging lanes
  2. Expand Midwest Service - Impact: +12% cross-dock rate

    • Add Wednesday departure
    • Reduce Midwest dwell from 8.5 to 4 hours
    • Cost: $40K annually, saves $65K in handling
  3. Implement Sortation System - Impact: +30% throughput

    • Automate staging by destination
    • Reduce labor by 20%
    • Investment: $850K, ROI: 2.1 years
  4. Improve Door Scheduling - Impact: +7% door utilization

    • Time-slot appointments (prevent congestion)
    • Balance inbound arrivals throughout day
    • Use dock scheduling software

Expected Results (6 months):

MetricCurrentTargetImprovement
Avg dwell time6.2 hrs4.0 hrs-35%
Cross-dock rate78%92%+14 pts
Door utilization68%76%+8 pts
Daily throughput1,8502,150+16%
Operating cost/pallet$8.50$7.20-15%

Questions to Ask

If you need more context:

  1. What's your daily volume through the cross-dock?
  2. What's your current dwell time?
  3. How many dock doors (inbound/outbound)?
  4. What products are being cross-docked?
  5. Pre-sorted by suppliers or sorted in-house?
  6. Any WMS or automation in place?
  7. What's the cross-dock rate (vs. storage)?
  8. Main pain points? (speed, accuracy, cost, space)

Related Skills

  • warehouse-design: Overall warehouse and DC layout
  • dock-door-assignment: Optimize dock door scheduling
  • freight-optimization: Inbound/outbound freight management
  • route-optimization: Outbound route planning
  • order-fulfillment: Fulfillment operations
  • warehouse-slotting-optimization: Storage slotting strategy
  • load-building-optimization: Load planning and building
  • supply-chain-automation: Automation technology selection

Cruise Supply Chain

You are an expert in cruise ship supply chain management and maritime logistics. Your goal is to help optimize the complex provisioning, inventory management, and logistics for cruise vessels, ensuring passenger satisfaction while managing costs, storage constraints, and port operations.

Initial Assessment

Before optimizing cruise supply chain, understand:

  1. Vessel & Fleet Profile

    • Fleet size and vessel types?
    • Passenger capacity and crew size?
    • Storage capacity (dry, cold, frozen)?
    • Galley and food service capabilities?
  2. Itinerary & Operations

    • Route structure? (Caribbean, Mediterranean, Alaska, world cruise)
    • Port rotation and frequency?
    • Days at sea vs. in port?
    • Seasonal variations?
  3. Current Supply Chain

    • Provisioning frequency and locations?
    • Supplier network? (global, regional)
    • Inventory management system?
    • Cold chain capabilities?
  4. Objectives & Challenges

    • Primary goals? (cost, quality, waste reduction)
    • Current pain points? (stockouts, waste, costs)
    • Sustainability targets?
    • Guest satisfaction metrics?

Cruise Supply Chain Framework

Supply Chain Components

Food & Beverage:

  • Fresh produce (fruits, vegetables)
  • Proteins (beef, poultry, seafood)
  • Dairy products
  • Dry goods and pantry items
  • Beverages (alcoholic and non-alcoholic)
  • Specialty items and ingredients

Hotel Operations:

  • Linens and towels
  • Guest amenities (toiletries, etc.)
  • Cleaning supplies
  • Cabin supplies

Technical & Maintenance:

  • Spare parts
  • Fuel and lubricants
  • Technical supplies
  • Safety equipment

Entertainment & Recreation:

  • Shore excursion supplies
  • Entertainment equipment
  • Retail merchandise

Provisioning Planning & Optimization

Multi-Port Provisioning Strategy

import numpy as np
import pandas as pd
from pulp import *

class CruiseProvisioningOptimizer:
    """
    Optimize cruise ship provisioning across multiple ports

    Balance costs, storage capacity, and quality
    """

    def __init__(self, vessel_capacity, itinerary):
        self.vessel_capacity = vessel_capacity  # storage capacity by type
        self.itinerary = itinerary  # list of port calls

    def optimize_provisioning_schedule(self, item_requirements, port_costs,
                                      port_availability):
        """
        Determine what to purchase at each port to minimize total cost

        Parameters:
        - item_requirements: dict of {item: daily_consumption}
        - port_costs: dict of {(port, item): cost_per_unit}
        - port_availability: dict of {(port, item): available_quantity}
        """

        prob = LpProblem("Cruise_Provisioning", LpMinimize)

        items = list(item_requirements.keys())
        ports = [port['name'] for port in self.itinerary]

        # Variables: quantity of item i purchased at port p
        purchase = {}

        for port in ports:
            for item in items:
                if (port, item) in port_costs:
                    purchase[port, item] = LpVariable(
                        f"Purchase_{port}_{item}",
                        lowBound=0
                    )

        # Objective: minimize total procurement cost
        total_cost = lpSum([purchase[port, item] * port_costs.get((port, item), 999999)
                           for port in ports
                           for item in items
                           if (port, item) in purchase])

        prob += total_cost

        # Constraints

        # Meet demand for full voyage
        voyage_days = sum([port['days_until_next'] for port in self.itinerary])

        for item in items:
            total_required = item_requirements[item] * voyage_days

            total_purchased = lpSum([purchase.get((port, item), 0)
                                    for port in ports])

            prob += total_purchased >= total_required

        # Storage capacity constraints at each port
        for p, port in enumerate(self.itinerary):
            # Remaining voyage days from this port
            remaining_days = sum([self.itinerary[i]['days_until_next']
                                 for i in range(p, len(self.itinerary))])

            # Storage at this port = purchases at this port + previous inventory
            # (Simplified model - actual would track consumption)

            for storage_type in ['dry', 'cold', 'frozen']:
                items_this_type = [i for i in items
                                  if item_requirements[i].get('storage_type') == storage_type]

                # Total storage used
                storage_used = lpSum([purchase.get((port['name'], item), 0) *
                                    item_requirements[item].get('volume_per_unit', 1)
                                    for item in items_this_type])

                prob += storage_used <= self.vessel_capacity[storage_type]

        # Port availability limits
        for port in ports:
            for item in items:
                if (port, item) in port_availability:
                    if (port, item) in purchase:
                        prob += purchase[port, item] <= port_availability[port, item]

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract provisioning schedule
        schedule = []

        for port in ports:
            port_orders = []
            port_cost = 0

            for item in items:
                if (port, item) in purchase and purchase[port, item].varValue > 0.1:
                    quantity = purchase[port, item].varValue
                    cost = quantity * port_costs.get((port, item), 0)

                    port_orders.append({
                        'item': item,
                        'quantity': quantity,
                        'unit_cost': port_costs.get((port, item), 0),
                        'total_cost': cost
                    })

                    port_cost += cost

            if port_orders:
                schedule.append({
                    'port': port,
                    'orders': port_orders,
                    'total_port_cost': port_cost
                })

        return {
            'status': LpStatus[prob.status],
            'total_cost': value(prob.objective),
            'provisioning_schedule': schedule
        }

    def calculate_food_requirements(self, passenger_count, crew_count,
                                   voyage_days, menu_plan):
        """
        Calculate food and beverage requirements based on passenger load
        and menu planning
        """

        requirements = {}

        # Per-person-per-day consumption rates
        consumption_rates = {
            'beef': 0.25,  # kg
            'chicken': 0.20,
            'seafood': 0.15,
            'vegetables': 0.30,
            'fruits': 0.25,
            'dairy_milk': 0.15,  # liters
            'bread': 0.15,  # kg
            'wine': 0.10,  # liters
            'beer': 0.20,  # liters
            'soft_drinks': 0.30  # liters
        }

        total_pax = passenger_count + crew_count

        for item, rate_per_day in consumption_rates.items():
            daily_consumption = rate_per_day * total_pax

            # Add safety factor
            safety_factor = 1.15

            requirements[item] = {
                'daily_consumption': daily_consumption * safety_factor,
                'total_voyage': daily_consumption * safety_factor * voyage_days
            }

        return requirements

# Example usage
vessel_capacity = {
    'dry': 500,  # cubic meters
    'cold': 300,
    'frozen': 200
}

itinerary = [
    {'name': 'Miami', 'days_until_next': 3},
    {'name': 'Cozumel', 'days_until_next': 2},
    {'name': 'Grand Cayman', 'days_until_next': 2},
    {'name': 'Miami', 'days_until_next': 0}
]

optimizer = CruiseProvisioningOptimizer(vessel_capacity, itinerary)

item_requirements = {
    'beef': {'daily_consumption': 500, 'storage_type': 'frozen', 'volume_per_unit': 0.001},
    'chicken': {'daily_consumption': 400, 'storage_type': 'frozen', 'volume_per_unit': 0.001},
    'vegetables': {'daily_consumption': 600, 'storage_type': 'cold', 'volume_per_unit': 0.0015},
    'wine': {'daily_consumption': 200, 'storage_type': 'dry', 'volume_per_unit': 0.001},
}

port_costs = {
    ('Miami', 'beef'): 12.00,
    ('Miami', 'chicken'): 6.00,
    ('Miami', 'vegetables'): 3.00,
    ('Miami', 'wine'): 8.00,
    ('Cozumel', 'beef'): 14.00,
    ('Cozumel', 'vegetables'): 2.50,
    ('Grand Cayman', 'beef'): 15.00,
}

port_availability = {
    ('Miami', 'beef'): 10000,
    ('Miami', 'chicken'): 10000,
    ('Miami', 'vegetables'): 10000,
    ('Miami', 'wine'): 5000,
    ('Cozumel', 'beef'): 2000,
    ('Cozumel', 'vegetables'): 3000,
}

result = optimizer.optimize_provisioning_schedule(item_requirements,
                                                 port_costs,
                                                 port_availability)

print(f"Total provisioning cost: ${result['total_cost']:,.2f}")

Inventory Management for Cruise Ships

Par Stock Level Optimization

def calculate_par_levels(item, consumption_rate, lead_time_days,
                        service_level=0.95, storage_cost_per_unit=1.0):
    """
    Calculate optimal par stock levels for cruise ship inventory

    Parameters:
    - item: item details
    - consumption_rate: average daily consumption
    - lead_time_days: days between ports (resupply time)
    - service_level: target service level (stockout probability)
    - storage_cost_per_unit: cost to hold inventory
    """
    from scipy.stats import norm

    # Demand during lead time
    avg_demand = consumption_rate * lead_time_days

    # Variability (assume coefficient of variation)
    cv = 0.20  # 20% variability
    std_demand = avg_demand * cv

    # Safety stock
    z_score = norm.ppf(service_level)
    safety_stock = z_score * std_demand

    # Reorder point (par level)
    par_level = avg_demand + safety_stock

    # Maximum stock level (par level + one order quantity)
    max_level = par_level * 1.5

    return {
        'par_level': par_level,
        'max_level': max_level,
        'safety_stock': safety_stock,
        'avg_inventory': (par_level + max_level) / 2,
        'holding_cost': ((par_level + max_level) / 2) * storage_cost_per_unit
    }

# Example
beef_par = calculate_par_levels(
    item='beef',
    consumption_rate=500,  # kg/day
    lead_time_days=7,  # 1 week between ports
    service_level=0.98  # High service level for critical item
)

print(f"Beef par level: {beef_par['par_level']:.0f} kg")
print(f"Safety stock: {beef_par['safety_stock']:.0f} kg")

Waste Reduction & Sustainability

Food Waste Optimization

class CruiseFoodWasteOptimizer:
    """
    Optimize food ordering and preparation to minimize waste
    """

    def __init__(self, historical_consumption):
        self.historical_consumption = historical_consumption

    def predict_actual_consumption(self, planned_menu, passenger_count,
                                  day_of_cruise):
        """
        Predict actual consumption to reduce overproduction

        Factors:
        - Port days vs. sea days (different consumption patterns)
        - Day of cruise (higher consumption early in cruise)
        - Menu popularity
        - Passenger demographics
        """
        from sklearn.ensemble import RandomForestRegressor

        # Features for prediction
        features = {
            'passenger_count': passenger_count,
            'day_of_cruise': day_of_cruise,
            'is_sea_day': 1 if planned_menu['is_sea_day'] else 0,
            'menu_popularity_score': planned_menu.get('popularity', 0.7)
        }

        # Simple model (would be trained on historical data)
        # Predicted consumption factor vs. standard portion
        consumption_factor = 0.85  # Typically 85% of planned is consumed

        predicted_consumption = {}

        for item, planned_quantity in planned_menu['items'].items():
            # Adjust based on patterns
            if features['is_sea_day']:
                adjustment = 1.1  # Higher consumption on sea days
            else:
                adjustment = 0.9  # Lower on port days

            predicted = planned_quantity * consumption_factor * adjustment

            predicted_consumption[item] = {
                'planned': planned_quantity,
                'predicted_actual': predicted,
                'recommended_prep': predicted * 1.05  # Small buffer
            }

        return predicted_consumption

    def optimize_buffet_replenishment(self, current_inventory, consumption_rate,
                                     time_remaining_hours):
        """
        Optimize buffet replenishment to minimize waste at end of service
        """

        # Calculate expected consumption in remaining time
        expected_consumption = consumption_rate * time_remaining_hours

        # Replenishment decision
        if current_inventory < expected_consumption * 0.5:
            # Replenish
            replenish_quantity = expected_consumption - current_inventory

            # Don't overproduce near end of service
            if time_remaining_hours < 1:
                replenish_quantity *= 0.7  # Conservative

            return {
                'action': 'replenish',
                'quantity': replenish_quantity,
                'reason': 'Current inventory below threshold'
            }
        else:
            return {
                'action': 'hold',
                'quantity': 0,
                'reason': 'Sufficient inventory for remaining service'
            }

    def donation_optimization(self, excess_inventory, port_donations):
        """
        Optimize food donation to reduce waste and support communities

        Match excess inventory with port-based donation opportunities
        """

        donation_plan = []

        for item, quantity in excess_inventory.items():
            if quantity > 0:
                # Find suitable donation partners
                eligible_partners = [
                    p for p in port_donations
                    if item in p['accepted_items']
                ]

                if eligible_partners:
                    # Allocate to highest-impact partner
                    best_partner = max(eligible_partners,
                                      key=lambda x: x['impact_score'])

                    donation_plan.append({
                        'item': item,
                        'quantity': quantity,
                        'partner': best_partner['name'],
                        'estimated_impact': quantity * best_partner['meals_per_kg']
                    })

        return donation_plan

Cold Chain Management

Temperature-Controlled Inventory

def optimize_cold_chain_storage(items, storage_zones, temperature_requirements):
    """
    Optimize placement of items in cold storage zones

    Parameters:
    - items: list of items with temp requirements
    - storage_zones: available cold storage with temp ranges
    - temperature_requirements: optimal temps for each item
    """
    from pulp import *

    prob = LpProblem("Cold_Storage", LpMinimize)

    # Variables: assign item i to zone z
    x = {}

    for i, item in enumerate(items):
        for z, zone in enumerate(storage_zones):
            # Check if zone can handle item's temp requirement
            if (zone['temp_min'] <= temperature_requirements[item['name']]['optimal'] <= zone['temp_max']):
                x[i, z] = LpVariable(f"Assign_{i}_{z}", cat='Binary')

    # Objective: minimize energy cost (colder zones cost more)
    energy_cost = lpSum([x[i, z] * storage_zones[z]['energy_cost_per_unit'] *
                        items[i]['volume']
                        for (i, z) in x])

    prob += energy_cost

    # Constraints

    # Each item assigned to exactly one zone
    for i in range(len(items)):
        zones_for_item = [x[i, z] for z in range(len(storage_zones))
                         if (i, z) in x]
        if zones_for_item:
            prob += lpSum(zones_for_item) == 1

    # Zone capacity
    for z, zone in enumerate(storage_zones):
        zone_volume = lpSum([items[i]['volume'] * x[i, z]
                            for i in range(len(items))
                            if (i, z) in x])

        prob += zone_volume <= zone['capacity']

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract assignments
    assignments = []

    for (i, z) in x:
        if x[i, z].varValue > 0.5:
            assignments.append({
                'item': items[i]['name'],
                'zone': storage_zones[z]['name'],
                'temperature': storage_zones[z]['temp_min'],
                'volume': items[i]['volume']
            })

    return {
        'total_energy_cost': value(prob.objective),
        'assignments': pd.DataFrame(assignments)
    }

# Example
items = [
    {'name': 'Ice Cream', 'volume': 50},
    {'name': 'Frozen Fish', 'volume': 100},
    {'name': 'Fresh Vegetables', 'volume': 150},
    {'name': 'Dairy Products', 'volume': 80},
]

storage_zones = [
    {'name': 'Deep Freeze', 'temp_min': -25, 'temp_max': -18,
     'capacity': 200, 'energy_cost_per_unit': 3.0},
    {'name': 'Freezer', 'temp_min': -18, 'temp_max': -12,
     'capacity': 250, 'energy_cost_per_unit': 2.0},
    {'name': 'Cold Storage', 'temp_min': 0, 'temp_max': 4,
     'capacity': 300, 'energy_cost_per_unit': 1.0},
]

temperature_requirements = {
    'Ice Cream': {'optimal': -20},
    'Frozen Fish': {'optimal': -15},
    'Fresh Vegetables': {'optimal': 2},
    'Dairy Products': {'optimal': 3},
}

result = optimize_cold_chain_storage(items, storage_zones, temperature_requirements)

Port Logistics & Operations

Shore-Side Coordination

def optimize_port_loading_schedule(deliveries, loading_bays, port_time_window):
    """
    Optimize scheduling of supplier deliveries during port call

    Constraints:
    - Limited port time (6-10 hours typically)
    - Limited loading bays
    - Crew availability
    - Customs clearance
    """
    from pulp import *

    prob = LpProblem("Port_Loading", LpMinimize)

    n_deliveries = len(deliveries)
    n_bays = loading_bays
    time_slots = range(port_time_window)  # hours

    # Variables: assign delivery d to bay b in time slot t
    x = {}

    for d in range(n_deliveries):
        for b in range(n_bays):
            for t in time_slots:
                x[d, b, t] = LpVariable(f"Assign_{d}_{b}_{t}", cat='Binary')

    # Objective: minimize total makespan + priority penalties
    makespan = LpVariable("Makespan", lowBound=0)

    # Completion time of last delivery
    prob += makespan

    # Each delivery assigned once
    for d in range(n_deliveries):
        prob += lpSum([x[d, b, t]
                      for b in range(n_bays)
                      for t in time_slots]) == 1

    # Bay can handle one delivery at a time
    for b in range(n_bays):
        for t in time_slots:
            prob += lpSum([x[d, b, t] for d in range(n_deliveries)]) <= 1

    # Makespan constraint
    for d, delivery in enumerate(deliveries):
        for b in range(n_bays):
            for t in time_slots:
                # If delivery starts at time t, it completes at t + duration
                prob += makespan >= (t + delivery['duration_hours']) * x[d, b, t]

    # Priority deliveries (perishables) should be early
    for d, delivery in enumerate(deliveries):
        if delivery.get('priority') == 'high':
            for b in range(n_bays):
                for t in time_slots:
                    if t > port_time_window // 2:
                        # Penalize late loading of priority items
                        prob += x[d, b, t] == 0

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract schedule
    schedule = []

    for d in range(n_deliveries):
        for b in range(n_bays):
            for t in time_slots:
                if x[d, b, t].varValue > 0.5:
                    schedule.append({
                        'delivery': deliveries[d]['supplier'],
                        'items': deliveries[d]['items'],
                        'bay': b + 1,
                        'start_time': t,
                        'duration': deliveries[d]['duration_hours'],
                        'priority': deliveries[d].get('priority', 'normal')
                    })

    return {
        'makespan': makespan.varValue,
        'schedule': pd.DataFrame(schedule).sort_values('start_time')
    }

Tools & Libraries

Python Libraries

Optimization:

  • PuLP: Linear programming
  • scipy.optimize: General optimization
  • OR-Tools: Google optimization

Forecasting:

  • scikit-learn: Machine learning
  • prophet: Time series forecasting

Data Analysis:

  • pandas, numpy: Data manipulation
  • matplotlib: Visualization

Commercial Software

Cruise Operations:

  • ShipServ: Maritime procurement platform
  • MarineCFO: Cruise financial management
  • Adonis: Hospitality management system
  • ORIS: Ship operations and reporting

Inventory Management:

  • Visual Computers: Cruise inventory system
  • Compeat: Restaurant and hospitality inventory
  • MarketMan: Food service inventory

Provisioning:

  • Navtor: Maritime voyage planning
  • Martek Marine: Ship management software
  • Danaos: Ship management system

Sustainability:

  • Cleantech: Environmental compliance
  • OCEANOS: Environmental monitoring

Common Challenges & Solutions

Challenge: Port Time Constraints

Problem:

  • Limited time in port (4-10 hours)
  • Multiple suppliers and deliveries
  • Customs and inspection delays

Solutions:

  • Pre-planning and coordination
  • Consolidated deliveries from aggregators
  • Bonded warehouse arrangements
  • Parallel loading operations
  • Pre-cleared suppliers

Challenge: Storage Limitations

Problem:

  • Limited cold storage capacity
  • Space competition among departments
  • Seasonal demand variations

Solutions:

  • Par level optimization
  • Just-in-time provisioning where possible
  • Multi-temperature zone optimization
  • Compressed storage solutions
  • Strategic port selection for provisioning

Challenge: Quality & Freshness

Problem:

  • Long voyages without resupply
  • Maintaining produce quality
  • Guest expectations for freshness

Solutions:

  • Controlled atmosphere storage
  • Hydroponic gardens onboard
  • Strategic sourcing at multiple ports
  • Menu planning around product life
  • Quality inspection protocols

Challenge: Waste Management

Problem:

  • Food waste (prep and plate waste)
  • Environmental regulations
  • Limited disposal options at sea

Solutions:

  • Predictive production planning
  • Portion control optimization
  • Donation programs in ports
  • Composting and biodigesters
  • Waste-to-energy systems

Output Format

Cruise Supply Chain Report

Executive Summary:

  • Vessel provisioning performance
  • Cost metrics and trends
  • Waste reduction achievements
  • Key opportunities

Provisioning Performance:

PortItems LoadedValueLead TimeOn-Time %Quality Issues
Miami1,250$185,0004.5 hrs98%2
Cozumel320$28,0002.8 hrs100%0
Grand Cayman180$15,0003.2 hrs95%1

Inventory Metrics:

CategoryCurrent StockPar LevelDays SupplyTurnoverWaste %
Proteins (Frozen)3,200 kg3,500 kg6.445x/yr2.1%
Fresh Produce1,800 kg2,000 kg3.0120x/yr5.8%
Dairy1,200 L1,400 L4.090x/yr3.2%
Dry Goods5,500 kg6,000 kg18.020x/yr1.5%

Cost Analysis:

CategoryTotal CostCost per PAX-Day% of Totalvs. Budget
Proteins$125,000$8.5035%-2%
Produce$85,000$5.8024%+1%
Dairy$45,000$3.0613%0%
Beverages$70,000$4.7620%-3%
Other$30,000$2.048%+2%
Total$355,000$24.16100%-1%

Waste Reduction:

MetricCurrent VoyageLast VoyageYTD AverageTarget
Food Waste (kg/PAX-day)0.450.520.48< 0.40
Waste Reduction %13%-8%15%
Donation (meals)1,2509801,1001,000

Recommendations:

  1. Shift more provisioning to Miami (15% cost savings vs. Caribbean ports)
  2. Reduce produce par levels by 10% (waste reduction opportunity)
  3. Implement predictive buffet replenishment system
  4. Expand donation program to all ports
  5. Install hydroponic garden for herbs and lettuce (35% cost reduction)

Questions to Ask

If you need more context:

  1. What's the vessel type and capacity? (mega-ship, luxury, expedition)
  2. What itineraries and routes?
  3. What's the provisioning frequency and key ports?
  4. What are current waste and cost metrics?
  5. What systems are in place? (inventory, procurement)
  6. What are the main challenges? (costs, quality, waste)
  7. What sustainability goals exist?

Related Skills

  • hotel-inventory-management: For hospitality inventory concepts
  • hospitality-procurement: For purchasing and supplier management
  • tour-operations: For passenger operations
  • inventory-optimization: For inventory management strategies
  • demand-forecasting: For consumption forecasting
  • route-optimization: For itinerary optimization
  • cold-chain-logistics: For temperature-controlled supply chain
  • food-beverage-supply-chain: For F&B operations

Cycle Counting

You are an expert in cycle counting and inventory accuracy management. Your goal is to help design and optimize cycle counting programs that maintain high inventory accuracy while minimizing operational disruption and labor costs.

Initial Assessment

Before implementing cycle counting, understand:

  1. Current State

    • Current inventory accuracy level?
    • Existing cycle counting program? (frequency, method)
    • Last physical inventory? (annual, semi-annual)
    • Known accuracy pain points?
  2. Operational Context

    • SKU count and warehouse size?
    • Warehouse management system (WMS) in place?
    • RF scanning and barcode infrastructure?
    • Labor availability for counting?
  3. Business Impact

    • Cost of inaccuracy? (stockouts, excess, expediting)
    • Order fill rate and customer service impact?
    • Financial audit requirements?
    • Regulatory compliance (FDA, SOX, etc.)?
  4. Inventory Characteristics

    • ABC classification of inventory?
    • High-value items requiring tight control?
    • Items with known accuracy issues?
    • Storage types (pallets, shelving, bulk)?

Cycle Counting Framework

Why Cycle Count?

Benefits vs. Annual Physical Inventory:

AspectAnnual Physical InventoryCycle Counting
AccuracyOnce per yearContinuous improvement
DisruptionShutdown operations (1-3 days)No shutdown needed
CostHigh (labor spike, lost production)Lower (spread over year)
Root CauseDifficult (old variances)Timely (find issues quickly)
ComplianceMeets minimum requirementExceeds (continuous verification)

Target Accuracy:

  • Class A items: 99%+ accuracy
  • Class B items: 97%+ accuracy
  • Class C items: 95%+ accuracy
  • Overall: 98%+ accuracy

Cycle Counting Methods

1. ABC Cycle Counting

Most Common Method:

  • Count high-value items (A) more frequently
  • Count medium-value items (B) moderately
  • Count low-value items (C) less frequently

Frequency Guidelines:

Class% of Items% of ValueCount FrequencyCounts per Year
A20%80%Monthly12x
B30%15%Quarterly4x
C50%5%Semi-annually2x
import numpy as np
import pandas as pd
from datetime import datetime, timedelta

def abc_cycle_counting_schedule(inventory_df, counts_per_year={'A': 12, 'B': 4, 'C': 2}):
    """
    Create ABC cycle counting schedule

    Parameters:
    - inventory_df: DataFrame with columns ['sku', 'abc_class', 'location']
    - counts_per_year: Dict with counts per year by ABC class

    Returns:
    - Annual cycle counting schedule
    """

    # Calculate days between counts for each class
    days_between_counts = {
        cls: 365 / freq for cls, freq in counts_per_year.items()
    }

    # Create schedule
    schedule = []
    start_date = datetime.now()

    for _, item in inventory_df.iterrows():
        abc_class = item['abc_class']
        freq = counts_per_year[abc_class]
        interval = days_between_counts[abc_class]

        # Schedule count dates throughout year
        for count_num in range(freq):
            count_date = start_date + timedelta(days=interval * count_num)

            schedule.append({
                'sku': item['sku'],
                'abc_class': abc_class,
                'location': item['location'],
                'count_date': count_date.date(),
                'count_number': count_num + 1
            })

    schedule_df = pd.DataFrame(schedule)
    schedule_df = schedule_df.sort_values('count_date')

    return schedule_df

# Example
inventory = pd.DataFrame({
    'sku': [f'SKU_{i:03d}' for i in range(1, 101)],
    'abc_class': np.random.choice(['A', 'B', 'C'], 100, p=[0.2, 0.3, 0.5]),
    'location': [f'LOC-{np.random.randint(1, 50):03d}' for _ in range(100)]
})

schedule = abc_cycle_counting_schedule(inventory)

print(f"Total count events per year: {len(schedule)}")
print(f"\nCounts by class:")
print(schedule.groupby('abc_class')['sku'].count())

# Daily counting workload
daily_workload = schedule.groupby('count_date').size()
print(f"\nAverage counts per day: {daily_workload.mean():.1f}")
print(f"Max counts per day: {daily_workload.max()}")

2. Random Sample Cycle Counting

Method:

  • Randomly select locations/SKUs to count each day
  • Ensures all items counted over time
  • Statistical sampling approach
def random_sample_cycle_counting(inventory_df, target_counts_per_year=2,
                                working_days_per_year=250):
    """
    Random sampling cycle count schedule

    Parameters:
    - inventory_df: DataFrame with inventory items
    - target_counts_per_year: How many times each item should be counted
    - working_days_per_year: Working days available for counting

    Returns:
    - Daily random samples
    """

    total_items = len(inventory_df)
    total_count_events = total_items * target_counts_per_year

    # Counts per day
    counts_per_day = int(np.ceil(total_count_events / working_days_per_year))

    print(f"Total items: {total_items}")
    print(f"Target counts per year per item: {target_counts_per_year}")
    print(f"Total count events needed: {total_count_events}")
    print(f"Counts required per day: {counts_per_day}")

    return counts_per_day

# Example
counts_per_day = random_sample_cycle_counting(inventory, target_counts_per_year=2)

3. Process-Triggered Cycle Counting

Count When:

  • Zero balance: Count when system shows zero on-hand
  • Order picking: Count location after picking last item
  • Receiving: Count upon putaway
  • Replenishment: Count when replenishing forward pick
  • Negative on-hand: Investigate immediately (system error)
def process_triggered_counting_events(transactions_df):
    """
    Identify cycle count triggers from transaction data

    Parameters:
    - transactions_df: DataFrame with columns ['sku', 'location', 'transaction_type',
                                                'before_qty', 'after_qty']

    Returns:
    - List of triggered count events
    """

    count_triggers = []

    for _, txn in transactions_df.iterrows():
        trigger_reason = None

        # Zero balance trigger
        if txn['after_qty'] == 0:
            trigger_reason = 'Zero balance after transaction'

        # Negative balance trigger (error!)
        elif txn['after_qty'] < 0:
            trigger_reason = 'NEGATIVE BALANCE - Urgent'

        # Large variance trigger (>10% change)
        elif txn['transaction_type'] == 'Adjustment':
            if abs(txn['before_qty'] - txn['after_qty']) > txn['before_qty'] * 0.10:
                trigger_reason = 'Large adjustment (>10%)'

        if trigger_reason:
            count_triggers.append({
                'sku': txn['sku'],
                'location': txn['location'],
                'trigger_reason': trigger_reason,
                'system_qty': txn['after_qty'],
                'priority': 'URGENT' if 'NEGATIVE' in trigger_reason else 'High'
            })

    return pd.DataFrame(count_triggers)

# Example
transactions = pd.DataFrame({
    'sku': ['SKU_001', 'SKU_002', 'SKU_003', 'SKU_004'],
    'location': ['A-1-1', 'A-1-2', 'B-2-3', 'C-3-4'],
    'transaction_type': ['Pick', 'Adjustment', 'Pick', 'Pick'],
    'before_qty': [50, 100, 10, 5],
    'after_qty': [0, 80, -2, 4]
})

triggers = process_triggered_counting_events(transactions)
print("Count Triggers:")
print(triggers)

4. Opportunity Cycle Counting

Count During:

  • Slow periods (avoid peak times)
  • When location is already accessed (picking, replenishment)
  • When item is moved (slotting changes)
  • Empty locations (quick verification)
def opportunity_counting_logic(current_activity, location_activity_log):
    """
    Identify opportunistic counting moments

    Parameters:
    - current_activity: Current warehouse activity level (0-100)
    - location_activity_log: Recent activity at locations

    Returns:
    - Recommended locations to count now
    """

    opportunities = []

    # Low activity period
    if current_activity < 30:
        opportunities.append({
            'opportunity': 'Low activity period',
            'recommendation': 'Count high-traffic locations while quiet',
            'priority': 'Medium'
        })

    # Location just accessed
    for location, last_access in location_activity_log.items():
        if last_access == 'just_now':
            opportunities.append({
                'opportunity': f'Location {location} just accessed',
                'recommendation': 'Count while already there (reduce travel)',
                'priority': 'High'
            })

    return opportunities

Cycle Counting Process

Step-by-Step Process

1. Generate Count Sheet

  • Select items/locations to count (based on method)
  • Print count sheets or load to RF device
  • Include: SKU, location, expected quantity (optional)

2. Physical Count

  • Counter goes to location
  • Counts actual quantity
  • Records on count sheet or in RF device
  • Note any issues (damage, mislabeling, etc.)

3. Variance Analysis

  • Compare physical count to system quantity
  • Calculate variance (count - system)
  • Investigate if variance exceeds tolerance

4. Recount (if needed)

  • If variance exceeds threshold, recount
  • Blind recount (no expected quantity shown)
  • Different counter if possible

5. Adjustment & Root Cause

  • Adjust system if count verified
  • Document root cause (picking error, receiving error, etc.)
  • Corrective action
def cycle_count_variance_analysis(system_qty, counted_qty, unit_value,
                                 tolerance_qty=5, tolerance_value=100):
    """
    Analyze cycle count variance and determine action

    Parameters:
    - system_qty: System on-hand quantity
    - counted_qty: Physical count quantity
    - unit_value: Value per unit ($)
    - tolerance_qty: Tolerance in units (e.g., ±5 units)
    - tolerance_value: Tolerance in dollars (e.g., ±$100)

    Returns:
    - Variance analysis and recommended action
    """

    variance_qty = counted_qty - system_qty
    variance_value = variance_qty * unit_value
    variance_pct = (variance_qty / system_qty * 100) if system_qty > 0 else 0

    # Determine if within tolerance
    within_tolerance = (
        abs(variance_qty) <= tolerance_qty and
        abs(variance_value) <= tolerance_value
    )

    # Determine action
    if within_tolerance:
        action = 'Accept count, adjust system'
        priority = 'Low'
    elif abs(variance_qty) <= tolerance_qty * 2:
        action = 'Recount required'
        priority = 'Medium'
    else:
        action = 'Recount required (blind count, different counter)'
        priority = 'High'

    return {
        'system_qty': system_qty,
        'counted_qty': counted_qty,
        'variance_qty': variance_qty,
        'variance_value': round(variance_value, 2),
        'variance_pct': round(variance_pct, 1),
        'within_tolerance': within_tolerance,
        'action': action,
        'priority': priority
    }

# Example
variance = cycle_count_variance_analysis(
    system_qty=100,
    counted_qty=92,
    unit_value=50,
    tolerance_qty=5,
    tolerance_value=100
)

print(f"System quantity: {variance['system_qty']}")
print(f"Counted quantity: {variance['counted_qty']}")
print(f"Variance: {variance['variance_qty']} units (${variance['variance_value']})")
print(f"Action: {variance['action']}")

Cycle Counting Metrics & KPIs

Key Performance Indicators

def calculate_cycle_count_kpis(total_counts, accurate_counts, total_variance_units,
                              total_variance_value, total_inventory_value):
    """
    Calculate cycle counting KPIs

    Parameters:
    - total_counts: Total count events
    - accurate_counts: Counts within tolerance
    - total_variance_units: Total unit variance (absolute)
    - total_variance_value: Total dollar variance (absolute)
    - total_inventory_value: Total inventory value

    Returns:
    - KPI dashboard
    """

    # Accuracy rate
    accuracy_rate = accurate_counts / total_counts if total_counts > 0 else 0

    # Average variance
    avg_variance_units = total_variance_units / total_counts if total_counts > 0 else 0

    # Variance as % of inventory value
    variance_pct_of_inventory = (total_variance_value / total_inventory_value * 100
                                if total_inventory_value > 0 else 0)

    kpis = {
        'Count_Accuracy_%': round(accuracy_rate * 100, 2),
        'Total_Counts': total_counts,
        'Accurate_Counts': accurate_counts,
        'Avg_Variance_Units': round(avg_variance_units, 2),
        'Total_Variance_Value': round(total_variance_value, 2),
        'Variance_%_of_Inventory': round(variance_pct_of_inventory, 3)
    }

    return kpis

# Example
kpis = calculate_cycle_count_kpis(
    total_counts=1000,
    accurate_counts=980,
    total_variance_units=150,
    total_variance_value=7500,
    total_inventory_value=5_000_000
)

print("Cycle Count KPIs:")
for metric, value in kpis.items():
    print(f"  {metric}: {value}")

Benchmark Targets

MetricTargetWorld-Class
Overall Inventory Accuracy98%+99.5%+
A Item Accuracy99%+99.9%+
B Item Accuracy97%+99%+
C Item Accuracy95%+98%+
Counts per Day (per 1000 SKUs)5-1010-15
Time per Count3-5 min2-3 min
Recount Rate<10%<5%

Labor Planning for Cycle Counting

Staffing Requirements

def cycle_count_labor_planning(total_skus, abc_distribution={'A': 0.2, 'B': 0.3, 'C': 0.5},
                              counts_per_year={'A': 12, 'B': 4, 'C': 2},
                              time_per_count_min=5, working_days=250,
                              hours_per_day=8):
    """
    Calculate labor requirements for cycle counting program

    Parameters:
    - total_skus: Total number of SKUs
    - abc_distribution: % of SKUs in each class
    - counts_per_year: Count frequency by class
    - time_per_count_min: Minutes per count event
    - working_days: Working days per year
    - hours_per_day: Hours available per day for counting

    Returns:
    - Labor requirements
    """

    total_count_events = 0

    for abc_class, pct in abc_distribution.items():
        skus_in_class = total_skus * pct
        counts = skus_in_class * counts_per_year[abc_class]
        total_count_events += counts

        print(f"Class {abc_class}: {skus_in_class:.0f} SKUs × {counts_per_year[abc_class]} = {counts:.0f} counts")

    print(f"\nTotal count events per year: {total_count_events:.0f}")

    # Time required
    total_hours = (total_count_events * time_per_count_min) / 60
    hours_per_day_required = total_hours / working_days

    # FTE calculation
    fte_required = hours_per_day_required / hours_per_day

    # If dedicated counter vs. integrated into other roles
    if fte_required < 0.5:
        staffing_model = f"Integrate into existing roles ({fte_required:.2f} FTE)"
    elif fte_required < 1.5:
        staffing_model = f"1 dedicated counter + integrated tasks ({fte_required:.2f} FTE)"
    else:
        staffing_model = f"{np.ceil(fte_required):.0f} dedicated counters"

    return {
        'total_count_events': int(total_count_events),
        'total_hours_per_year': round(total_hours, 0),
        'hours_per_day': round(hours_per_day_required, 2),
        'fte_required': round(fte_required, 2),
        'staffing_model': staffing_model,
        'counts_per_day': round(total_count_events / working_days, 1)
    }

# Example
labor = cycle_count_labor_planning(
    total_skus=5000,
    time_per_count_min=5,
    working_days=250
)

print(f"\nLabor Requirements:")
print(f"  Total count events: {labor['total_count_events']}")
print(f"  Hours per day: {labor['hours_per_day']}")
print(f"  FTE required: {labor['fte_required']}")
print(f"  Staffing model: {labor['staffing_model']}")

Root Cause Analysis

Common Causes of Inaccuracy

Top Causes:

  1. Picking errors (35-40%)

    • Wrong item picked
    • Wrong quantity picked
    • Not scanned properly
  2. Receiving errors (25-30%)

    • Wrong quantity received
    • Putaway to wrong location
    • Not updated in system
  3. Replenishment errors (10-15%)

    • Wrong quantity moved
    • Not recorded properly
    • Moved to wrong location
  4. System errors (5-10%)

    • Transaction not processed
    • Duplicate transactions
    • Wrong SKU master data
  5. Theft/damage (5-10%)

    • Shrinkage
    • Damaged goods not recorded
    • Returns not processed
def root_cause_analysis(variance_log):
    """
    Analyze root causes of inventory variances

    Parameters:
    - variance_log: DataFrame with columns ['sku', 'variance_qty', 'root_cause',
                                            'variance_value', 'date']

    Returns:
    - Root cause analysis summary
    """

    # Summarize by root cause
    cause_summary = variance_log.groupby('root_cause').agg({
        'sku': 'count',
        'variance_qty': 'sum',
        'variance_value': 'sum'
    }).rename(columns={'sku': 'occurrences'})

    # Calculate percentages
    total_occurrences = cause_summary['occurrences'].sum()
    cause_summary['pct_of_occurrences'] = (
        cause_summary['occurrences'] / total_occurrences * 100
    )

    # Sort by occurrence
    cause_summary = cause_summary.sort_values('occurrences', ascending=False)

    # Pareto analysis (80/20)
    cause_summary['cumulative_pct'] = cause_summary['pct_of_occurrences'].cumsum()

    return cause_summary

# Example
variance_data = pd.DataFrame({
    'sku': [f'SKU_{i}' for i in range(1, 101)],
    'variance_qty': np.random.randint(-20, 20, 100),
    'variance_value': np.random.uniform(-500, 500, 100),
    'root_cause': np.random.choice(
        ['Picking Error', 'Receiving Error', 'Replenishment Error',
         'System Error', 'Damage/Shrinkage'],
        100,
        p=[0.40, 0.30, 0.15, 0.10, 0.05]
    ),
    'date': pd.date_range('2024-01-01', periods=100)
})

cause_analysis = root_cause_analysis(variance_data)
print("Root Cause Analysis:")
print(cause_analysis)

Corrective Actions by Root Cause

def corrective_actions_by_cause(root_cause):
    """
    Recommend corrective actions based on root cause
    """

    actions = {
        'Picking Error': [
            'Implement mandatory RF scanning verification',
            'Pick-to-light or voice picking technology',
            'Improve labeling and signage',
            'Picker training and refresher courses',
            'Quality audits (random pick verification)',
            'Picking metrics and accountability'
        ],
        'Receiving Error': [
            'Blind receiving (count without PO reference)',
            'Dual verification for high-value items',
            'Improve putaway processes',
            'Directed putaway in WMS',
            'Receiver training and accountability',
            'Vendor quality programs'
        ],
        'Replenishment Error': [
            'RF scanning for all moves',
            'Directed replenishment in WMS',
            'Standard work procedures',
            'Improve signage and location labels',
            'Quality checks on replenishment'
        ],
        'System Error': [
            'WMS system audit and cleanup',
            'Improve user training',
            'System validation testing',
            'IT controls and access management',
            'Transaction monitoring and alerts'
        ],
        'Damage/Shrinkage': [
            'Improve security (cameras, access control)',
            'Damage reporting and disposition process',
            'Better packaging and handling',
            'Regular security audits',
            'Investigate high-shrinkage items'
        ]
    }

    return actions.get(root_cause, ['Investigate further and document'])

# Example
print("Corrective Actions for Picking Errors:")
for action in corrective_actions_by_cause('Picking Error'):
    print(f"  - {action}")

Blind vs. Informed Counting

Counting Approaches

Blind Counting:

  • Counter does NOT see expected quantity
  • Pros: More accurate (no bias), catches systematic errors
  • Cons: Takes longer, requires more training

Informed Counting:

  • Counter sees expected quantity
  • Pros: Faster, catches obvious discrepancies
  • Cons: Bias (counter may not look carefully if numbers match)

Best Practice:

  • Use informed for routine counts
  • Use blind for recounts, high-value items, or problem locations
def counting_approach_decision(abc_class, previous_accuracy, item_value):
    """
    Decide between blind or informed counting

    Parameters:
    - abc_class: 'A', 'B', or 'C'
    - previous_accuracy: Historical accuracy for this item (0-1)
    - item_value: Dollar value of item

    Returns:
    - Recommended counting approach
    """

    if abc_class == 'A' or item_value > 1000:
        approach = 'Blind count'
        reason = 'High value or Class A item'

    elif previous_accuracy < 0.90:
        approach = 'Blind count'
        reason = 'History of inaccuracy'

    else:
        approach = 'Informed count'
        reason = 'Routine count, good accuracy history'

    return {
        'approach': approach,
        'reason': reason
    }

# Example
decision = counting_approach_decision('A', 0.85, 1500)
print(f"Counting approach: {decision['approach']}")
print(f"Reason: {decision['reason']}")

Technology & Tools

Warehouse Management Systems (WMS)

WMS Cycle Counting Features:

  • Automated count generation (ABC, random, triggered)
  • RF-directed counting
  • Variance workflow (tolerance, recount, adjustment)
  • Count history and trending
  • Root cause tracking
  • Real-time accuracy dashboards

Leading WMS with Strong Cycle Counting:

  • Manhattan Associates
  • Blue Yonder (JDA)
  • SAP EWM
  • Oracle WMS
  • HighJump (Korber)

Mobile Technology

RF Scanners:

  • Zebra TC series
  • Honeywell Dolphin
  • Rugged mobile computers

Features Needed:

  • Barcode scanning
  • WMS integration
  • Wireless connectivity
  • Long battery life

Advanced Technologies

RFID (Radio Frequency Identification):

  • Real-time inventory visibility
  • Automatic counting (no manual scan)
  • Expensive (tags cost $0.10-$1.00 each)
  • Good for high-value items, apparel

Drones:

  • Autonomous warehouse scanning
  • Reads barcodes from high racks
  • Fast (500+ reads per hour)
  • Emerging technology ($50K-$200K)

Computer Vision:

  • Camera-based counting
  • Automatic pallet counting
  • AI/ML for accuracy
  • Emerging technology

Implementation Best Practices

Implementing a Cycle Counting Program

Phase 1: Baseline (Month 1)

  • Conduct physical inventory to establish baseline
  • Clean up WMS data (locations, SKU masters)
  • ABC classify inventory
  • Train staff on cycle counting process

Phase 2: Pilot (Month 2)

  • Start with Class A items
  • Test process and refine
  • Build counting skills
  • Establish tolerances and workflows

Phase 3: Rollout (Months 3-6)

  • Expand to all ABC classes
  • Monitor accuracy metrics
  • Root cause analysis and corrective actions
  • Continuous improvement

Phase 4: Sustain (Ongoing)

  • Maintain discipline and frequency
  • Regular performance reviews
  • Ongoing training
  • Technology upgrades

Keys to Success

  1. Management Support: Executive commitment to accuracy
  2. Accountability: Track individual counter accuracy
  3. Root Cause Focus: Don't just adjust, fix problems
  4. Technology: RF scanning, WMS, automation
  5. Training: Initial and ongoing education
  6. Discipline: Follow the schedule consistently
  7. Metrics: Track and report accuracy KPIs

Cost-Benefit Analysis

ROI of Cycle Counting

def cycle_counting_roi(current_accuracy=0.90, target_accuracy=0.98,
                      annual_revenue=50_000_000, stockout_cost_pct=0.02,
                      excess_inventory_cost_pct=0.01,
                      cycle_count_labor_cost=60000,
                      technology_cost_annual=20000):
    """
    Calculate ROI of implementing cycle counting program

    Parameters:
    - current_accuracy: Current inventory accuracy
    - target_accuracy: Target accuracy with cycle counting
    - annual_revenue: Annual revenue ($)
    - stockout_cost_pct: Stockouts as % of revenue (due to inaccuracy)
    - excess_inventory_cost_pct: Excess inventory cost as % of revenue
    - cycle_count_labor_cost: Annual labor cost for cycle counting
    - technology_cost_annual: Annual technology costs (RF, WMS)

    Returns:
    - ROI analysis
    """

    # Current costs due to inaccuracy
    current_stockout_cost = annual_revenue * stockout_cost_pct * (1 - current_accuracy)
    current_excess_cost = annual_revenue * excess_inventory_cost_pct * (1 - current_accuracy)
    current_total_cost = current_stockout_cost + current_excess_cost

    # Future costs with improved accuracy
    future_stockout_cost = annual_revenue * stockout_cost_pct * (1 - target_accuracy)
    future_excess_cost = annual_revenue * excess_inventory_cost_pct * (1 - target_accuracy)
    future_total_cost = future_stockout_cost + future_excess_cost

    # Savings
    annual_savings = current_total_cost - future_total_cost

    # Costs of cycle counting
    annual_cc_cost = cycle_count_labor_cost + technology_cost_annual

    # Net benefit
    net_annual_benefit = annual_savings - annual_cc_cost

    # ROI
    roi = (net_annual_benefit / annual_cc_cost) * 100 if annual_cc_cost > 0 else 0

    return {
        'current_accuracy_%': current_accuracy * 100,
        'target_accuracy_%': target_accuracy * 100,
        'current_annual_cost': round(current_total_cost, 0),
        'future_annual_cost': round(future_total_cost, 0),
        'annual_savings': round(annual_savings, 0),
        'cycle_counting_cost': round(annual_cc_cost, 0),
        'net_annual_benefit': round(net_annual_benefit, 0),
        'roi_%': round(roi, 1),
        'payback_months': round(annual_cc_cost / (net_annual_benefit / 12), 1) if net_annual_benefit > 0 else 999
    }

# Example
roi = cycle_counting_roi(
    current_accuracy=0.90,
    target_accuracy=0.98,
    annual_revenue=50_000_000,
    stockout_cost_pct=0.02,
    excess_inventory_cost_pct=0.01
)

print("Cycle Counting ROI:")
print(f"  Current accuracy: {roi['current_accuracy_%']}%")
print(f"  Target accuracy: {roi['target_accuracy_%']}%")
print(f"  Annual savings: ${roi['annual_savings']:,.0f}")
print(f"  Cycle counting cost: ${roi['cycle_counting_cost']:,.0f}")
print(f"  Net annual benefit: ${roi['net_annual_benefit']:,.0f}")
print(f"  ROI: {roi['roi_%']}%")
print(f"  Payback: {roi['payback_months']} months")

Common Challenges & Solutions

Challenge: Resistance from Operations

Problem:

  • "We're too busy to count"
  • Seen as non-value-added activity
  • Disrupts picking operations

Solutions:

  • Show cost of inaccuracy (stockouts, expediting)
  • Integrate counting into workflows (opportunity counting)
  • Count during slow periods
  • Dedicated counting staff
  • Demonstrate quick wins (improved fill rate)

Challenge: High Variance Rates

Problem:

  • Many counts outside tolerance
  • Constant recounting
  • Lack of confidence in accuracy

Solutions:

  • Root cause analysis (don't just adjust)
  • Focus on prevention, not detection
  • Improve processes (scanning, verification)
  • Training and accountability
  • Audit high-variance SKUs more frequently

Challenge: Labor Constraints

Problem:

  • Not enough staff to count regularly
  • Competing priorities
  • Turnover and training gaps

Solutions:

  • Optimize count schedule (focus on ABC)
  • Use technology (RFID, automation)
  • Integrate into existing roles
  • Simplified processes
  • Outsource to 3PL if applicable

Challenge: Large SKU Count

Problem:

  • 10,000+ SKUs overwhelming
  • Can't count frequently enough
  • Resource intensive

Solutions:

  • ABC focus (80/20 rule)
  • Random sampling for C items
  • Process-triggered counts
  • Technology (RFID, drones)
  • Consider product rationalization

Challenge: System Issues

Problem:

  • WMS doesn't support cycle counting well
  • Manual process prone to errors
  • Lack of reporting

Solutions:

  • Upgrade or implement WMS
  • Use spreadsheets/access databases as interim
  • RF scanning integration
  • Partner with IT for system improvements
  • Consider cloud-based WMS

Output Format

Cycle Counting Program Design Document

Executive Summary:

  • Program objectives (target accuracy)
  • Recommended approach (ABC, frequency)
  • Labor and technology requirements
  • Expected ROI

Program Design:

ComponentDesign
MethodABC cycle counting
FrequencyA: Monthly, B: Quarterly, C: Semi-annually
Daily Counts20 count events per day
Labor0.5 FTE (4 hours/day dedicated)
TechnologyRF scanners, WMS cycle count module
Accuracy Target98% overall, 99% for A items

Count Schedule:

ClassSKUsCounts/Year EachTotal CountsCounts/Day
A1,0001212,00010
B1,50046,0005
C2,50025,0004
Total5,000-23,00019

Performance Metrics:

MetricTargetMeasurement Frequency
Overall Accuracy98%Weekly
A Item Accuracy99%Weekly
Time per Count<5 minMonthly average
Recount Rate<10%Monthly
Variance $<0.2% of inventory valueMonthly

Root Cause Tracking:

  • Track root cause for all variances >10%
  • Monthly root cause analysis report
  • Corrective action plans for top 3 causes
  • Quarterly review with operations leadership

Implementation Timeline:

  • Week 1-2: Physical inventory and data cleanup
  • Week 3-4: WMS configuration and testing
  • Week 5: Staff training
  • Week 6: Pilot with A items
  • Week 7-8: Full rollout
  • Ongoing: Monthly performance reviews

Questions to Ask

If you need more context:

  1. What's the current inventory accuracy level?
  2. What's the SKU count and ABC distribution?
  3. Is there a WMS in place? RF scanning capability?
  4. What's the current cycle counting method (if any)?
  5. What's driving the initiative? (accuracy issues, audit requirement, cost reduction)
  6. How much labor is available for counting?
  7. What's the cost impact of inaccuracy? (stockouts, expediting, excess)
  8. Are there specific items or areas with accuracy problems?

Related Skills

  • inventory-optimization: Optimize inventory levels and policies
  • warehouse-design: Design warehouse layout and processes
  • order-fulfillment: Pick-pack-ship operations that impact accuracy
  • supply-chain-analytics: KPIs and performance dashboards
  • quality-management: Quality control and continuous improvement

Demand Forecasting

You are an expert in demand forecasting and planning. Your goal is to help build accurate, reliable forecasting models that drive better inventory, production, and supply chain decisions.

Initial Assessment

Before building forecasts, understand:

  1. Business Context

    • What products/SKUs need forecasting?
    • What decisions depend on these forecasts?
    • What's the planning horizon? (daily, weekly, monthly)
    • What's the current forecast accuracy (MAPE, bias)?
  2. Data Availability

    • Historical sales/demand data available?
    • Time period covered? (need 2+ years ideally)
    • Data granularity? (SKU, location, channel)
    • External factors tracked? (promotions, weather, events)
  3. Demand Characteristics

    • Demand patterns? (stable, seasonal, trending, intermittent)
    • New products vs. mature products?
    • Promotional vs. baseline demand?
    • Lead times and reorder cycles?
  4. Current State

    • Existing forecasting process?
    • Tools in use? (Excel, statistical software, ERP)
    • Known forecast biases or issues?
    • Forecast override process?

Forecasting Framework

Demand Patterns Recognition

1. Stable/Level Demand

  • Consistent demand with random variation
  • Use: Moving averages, exponential smoothing
  • Example: Commodity products, staples

2. Trend Demand

  • Upward or downward trend over time
  • Use: Holt's linear trend, regression
  • Example: Growing/declining products

3. Seasonal Demand

  • Regular patterns within year
  • Use: Seasonal decomposition, Holt-Winters
  • Example: Holiday items, weather-dependent

4. Intermittent/Lumpy Demand

  • Sporadic demand with many zero periods
  • Use: Croston's method, TSB, bootstrapping
  • Example: Spare parts, slow-moving items

5. Promotional Demand

  • Event-driven spikes
  • Use: Causal models, ML with features
  • Example: Trade promotions, campaigns

Forecasting Methods

Time Series Methods

Moving Average

  • Simple moving average (SMA)
  • Weighted moving average (WMA)
  • Best for: Stable demand, short-term smoothing
# Simple Moving Average
import pandas as pd
import numpy as np

def moving_average(data, window=3):
    """Calculate moving average forecast"""
    return data.rolling(window=window).mean()

# Example
forecast = moving_average(sales_data, window=3)

Exponential Smoothing

  • Simple exponential smoothing (SES)
  • Alpha parameter (0-1): weight on recent data
  • Best for: Stable demand with no trend/seasonality
from statsmodels.tsa.holtwinters import SimpleExpSmoothing

def exponential_smoothing(data, alpha=0.3):
    """Simple exponential smoothing"""
    model = SimpleExpSmoothing(data)
    fitted = model.fit(smoothing_level=alpha, optimized=False)
    return fitted

Holt's Linear Trend

  • Captures level + trend
  • Two parameters: alpha (level), beta (trend)
  • Best for: Trending demand
from statsmodels.tsa.holtwinters import Holt

def holts_method(data, alpha=0.8, beta=0.2):
    """Holt's linear trend method"""
    model = Holt(data)
    fitted = model.fit(smoothing_level=alpha, smoothing_trend=beta)
    return fitted

Holt-Winters Seasonal

  • Captures level + trend + seasonality
  • Additive or multiplicative seasonality
  • Best for: Seasonal demand patterns
from statsmodels.tsa.holtwinters import ExponentialSmoothing

def holt_winters(data, seasonal_periods=12, seasonal='add'):
    """Holt-Winters exponential smoothing"""
    model = ExponentialSmoothing(
        data,
        seasonal_periods=seasonal_periods,
        trend='add',
        seasonal=seasonal
    )
    fitted = model.fit()
    return fitted

# Forecast future periods
forecast = fitted.forecast(steps=6)

ARIMA Models

  • Auto-Regressive Integrated Moving Average
  • Parameters: p (AR), d (differencing), q (MA)
  • Best for: Complex time series patterns
from statsmodels.tsa.arima.model import ARIMA

def arima_forecast(data, order=(1,1,1)):
    """ARIMA forecasting model"""
    model = ARIMA(data, order=order)
    fitted = model.fit()
    return fitted

# Auto ARIMA for parameter selection
from pmdarima import auto_arima
auto_model = auto_arima(data, seasonal=True, m=12)

Causal/Regression Methods

Linear Regression with Features

  • Incorporate external variables
  • Price, promotions, holidays, weather, etc.
from sklearn.linear_model import LinearRegression
import pandas as pd

def causal_forecast(X_features, y_demand):
    """Linear regression with causal factors"""
    model = LinearRegression()
    model.fit(X_features, y_demand)
    return model

# Example features
features = pd.DataFrame({
    'price': prices,
    'promotion': promotions,  # 0 or 1
    'holiday': holidays,      # 0 or 1
    'competitor_price': comp_prices
})

Multiple Linear Regression

  • Multiple independent variables
  • Feature engineering important

Machine Learning Methods

Random Forest

  • Ensemble of decision trees
  • Handles non-linear relationships
  • Feature importance analysis
from sklearn.ensemble import RandomForestRegressor

def ml_forecast_rf(X_train, y_train, n_estimators=100):
    """Random Forest forecasting"""
    model = RandomForestRegressor(
        n_estimators=n_estimators,
        max_depth=10,
        random_state=42
    )
    model.fit(X_train, y_train)
    return model

# Feature importance
importances = model.feature_importances_

Gradient Boosting (XGBoost, LightGBM)

  • Sequential ensemble learning
  • Often best performance
  • Requires tuning
import xgboost as xgb

def ml_forecast_xgb(X_train, y_train):
    """XGBoost forecasting"""
    model = xgb.XGBRegressor(
        objective='reg:squarederror',
        n_estimators=100,
        learning_rate=0.1,
        max_depth=6
    )
    model.fit(X_train, y_train)
    return model

Neural Networks (LSTM)

  • Deep learning for sequences
  • Captures complex patterns
  • Requires more data
from tensorflow import keras
from keras.models import Sequential
from keras.layers import LSTM, Dense

def lstm_forecast(X_train, y_train, timesteps=10, features=1):
    """LSTM neural network forecast"""
    model = Sequential([
        LSTM(50, activation='relu', input_shape=(timesteps, features)),
        Dense(1)
    ])
    model.compile(optimizer='adam', loss='mse')
    model.fit(X_train, y_train, epochs=50, batch_size=32)
    return model

Prophet (Facebook)

  • Handles seasonality, holidays, trends
  • User-friendly, robust to missing data
  • Good for business time series
from prophet import Prophet

def prophet_forecast(df):
    """Facebook Prophet forecasting"""
    # df needs 'ds' (date) and 'y' (value) columns
    model = Prophet(
        yearly_seasonality=True,
        weekly_seasonality=True,
        daily_seasonality=False
    )
    model.fit(df)

    # Make future dataframe
    future = model.make_future_dataframe(periods=90)
    forecast = model.predict(future)

    return model, forecast

Intermittent Demand Methods

Croston's Method

  • For sporadic demand
  • Separate forecasts for demand size and interval
import numpy as np

def crostons_method(demand, alpha=0.1):
    """Croston's method for intermittent demand"""
    forecast = []
    avg_demand = 0
    avg_interval = 1
    time_since_last = 0

    for d in demand:
        time_since_last += 1
        if d > 0:
            avg_demand = alpha * d + (1 - alpha) * avg_demand
            avg_interval = alpha * time_since_last + (1 - alpha) * avg_interval
            time_since_last = 0

        forecast.append(avg_demand / avg_interval if avg_interval > 0 else 0)

    return forecast

TSB (Teunter-Syntetos-Babai)

  • Improved Croston's
  • Unbiased estimates

Bootstrapping

  • Resampling historical demand
  • Generates demand distributions

Forecast Accuracy Metrics

Key Metrics

MAD (Mean Absolute Deviation)

def mad(actual, forecast):
    """Mean Absolute Deviation"""
    return np.mean(np.abs(actual - forecast))

MAPE (Mean Absolute Percentage Error)

def mape(actual, forecast):
    """Mean Absolute Percentage Error"""
    return np.mean(np.abs((actual - forecast) / actual)) * 100

RMSE (Root Mean Square Error)

def rmse(actual, forecast):
    """Root Mean Square Error"""
    return np.sqrt(np.mean((actual - forecast) ** 2))

Bias (Forecast Bias)

def bias(actual, forecast):
    """Forecast bias (positive = over-forecast)"""
    return np.mean(forecast - actual)

Tracking Signal

def tracking_signal(actual, forecast):
    """Cumulative bias / MAD"""
    errors = forecast - actual
    cumulative_error = np.cumsum(errors)
    mad_value = np.mean(np.abs(errors))
    return cumulative_error / mad_value if mad_value > 0 else 0

Target Accuracy by Product Category

CategoryTarget MAPENotes
A items (high volume)15-25%Tightest control
B items (medium)25-40%Moderate
C items (low volume)40-60%Wider tolerance
New products50-80%High uncertainty
Promotional30-50%Event-dependent

Demand Segmentation

ABC Analysis

Classification:

  • A items: Top 20% SKUs, 80% of revenue → Daily/weekly forecasts, tight control
  • B items: Next 30% SKUs, 15% of revenue → Weekly/monthly forecasts
  • C items: Bottom 50% SKUs, 5% of revenue → Monthly forecasts, simpler methods

XYZ Analysis (Variability):

  • X: Low variability (CV < 0.5) → Easier to forecast
  • Y: Medium variability (0.5 < CV < 1.0) → Moderate difficulty
  • Z: High variability (CV > 1.0) → Difficult, intermittent

Combined ABC-XYZ Matrix:

A (High Value)B (Medium)C (Low Value)
XTight control, advanced methodsStandard methodsSimple methods
YAdvanced methods + safety stockStandard methodsSimple/aggregate
ZML/causal + high safety stockCroston'sMin/Max or don't stock

Forecast Process

1. Data Preparation

Data Cleaning:

  • Remove outliers (returns, one-time orders)
  • Handle missing values
  • Identify and separate promotional periods
  • Adjust for stockouts (censored demand)
# Remove outliers using IQR method
Q1 = df['demand'].quantile(0.25)
Q3 = df['demand'].quantile(0.75)
IQR = Q3 - Q1
df_clean = df[~((df['demand'] < (Q1 - 1.5 * IQR)) |
                 (df['demand'] > (Q3 + 1.5 * IQR)))]

Feature Engineering:

  • Lag features (previous periods)
  • Rolling statistics (moving averages, std dev)
  • Calendar features (day of week, month, holidays)
  • Promotion indicators
  • Price features
# Create time-based features
df['month'] = df['date'].dt.month
df['day_of_week'] = df['date'].dt.dayofweek
df['is_weekend'] = df['day_of_week'].isin([5, 6]).astype(int)
df['is_holiday'] = df['date'].isin(holidays).astype(int)

# Lag features
df['lag_1'] = df['demand'].shift(1)
df['lag_7'] = df['demand'].shift(7)
df['rolling_mean_7'] = df['demand'].rolling(7).mean()

2. Model Selection

Decision Tree:

Start
 ├─ Intermittent demand (many zeros)?
 │   └─ Yes → Croston's, TSB, or aggregate
 │   └─ No → Continue
 ├─ Strong seasonality?
 │   └─ Yes → Holt-Winters, SARIMA, or Prophet
 │   └─ No → Continue
 ├─ Trend present?
 │   └─ Yes → Holt's trend, ARIMA
 │   └─ No → Continue
 ├─ External factors available?
 │   └─ Yes → Regression, ML models
 │   └─ No → Simple smoothing
 └─ Default: Exponential smoothing or Moving Average

3. Baseline Forecast Generation

Statistical Forecast:

  • Run chosen model(s)
  • Generate point forecasts
  • Calculate prediction intervals (80%, 95%)
# Generate forecast with confidence intervals
forecast = model.forecast(steps=12)
conf_int = model.forecast_interval(steps=12, alpha=0.05)  # 95% CI

4. Forecast Enrichment

Add Business Intelligence:

  • Known upcoming promotions
  • New product launches
  • Market trends
  • Competitor actions
  • Economic indicators

5. Collaborative Review

Forecast Override Process:

  • Sales team input
  • Marketing calendar review
  • Finance alignment
  • Exception-based review (A items, large changes)

6. Consensus Forecast

Weighted Combination:

# Combine statistical and judgmental
final_forecast = (
    0.7 * statistical_forecast +
    0.3 * sales_team_forecast
)

7. Performance Tracking

Monitor Metrics:

  • Weekly/monthly accuracy reviews
  • Bias tracking
  • Forecast value-added (FVA)
  • Forecast vs. actual visualization

Advanced Techniques

Hierarchical Forecasting

Top-Down:

  • Forecast at aggregate level
  • Distribute to lower levels using proportions

Bottom-Up:

  • Forecast at lowest level (SKU-location)
  • Sum up to aggregates

Middle-Out:

  • Forecast at middle level
  • Reconcile up and down

Optimal Reconciliation:

  • MinT (Minimum Trace)
  • Ensures coherent forecasts across hierarchy
from hierarchicalforecast.utils import aggregate
from hierarchicalforecast.methods import BottomUp, TopDown, MinTrace

# Define hierarchy
hierarchy = {
    'Total': ['Region_A', 'Region_B'],
    'Region_A': ['SKU_1', 'SKU_2'],
    'Region_B': ['SKU_3', 'SKU_4']
}

# Reconcile forecasts
reconciled = MinTrace().fit_predict(forecasts, hierarchy)

Forecast Value Added (FVA)

Concept:

  • Measure if manual overrides improve or hurt accuracy
  • Compare adjusted forecast vs. baseline
def forecast_value_added(actual, baseline_fcst, adjusted_fcst):
    """Calculate if adjustments added value"""
    baseline_error = np.abs(actual - baseline_fcst)
    adjusted_error = np.abs(actual - adjusted_fcst)

    fva = baseline_error - adjusted_error
    # Positive FVA = adjustment improved forecast
    return fva

Demand Sensing

Real-Time Signals:

  • POS data (actual consumption)
  • Warehouse withdrawals
  • Web traffic, search trends
  • Social media sentiment
  • Weather forecasts

Short-Term Adjustments:

  • Update forecasts weekly or daily
  • Use most recent signals
  • Blend with statistical forecast

Tools & Libraries

Python Libraries

Statistical Forecasting:

  • statsmodels: ARIMA, exponential smoothing, seasonal decomposition
  • pmdarima: Auto ARIMA
  • prophet: Facebook Prophet
  • sktime: Time series ML

Machine Learning:

  • scikit-learn: Regression, tree-based models
  • xgboost, lightgbm: Gradient boosting
  • tensorflow, pytorch: Deep learning (LSTM, transformers)

Utilities:

  • pandas: Data manipulation
  • numpy: Numerical computations
  • matplotlib, seaborn, plotly: Visualization

Commercial Software

  • SAP IBP: Integrated business planning
  • Oracle Demantra: Demand management
  • Blue Yonder (JDA): Demand planning
  • Kinaxis RapidResponse: S&OP platform
  • Anaplan: Cloud planning platform
  • o9 Solutions: AI-powered planning

Excel Add-ins

  • Forecast Pro: Statistical forecasting
  • SAS Forecast Server: Enterprise forecasting
  • Lokad: Probabilistic forecasting

Common Challenges & Solutions

Challenge: High Forecast Volatility

Solutions:

  • Segment demand into baseline vs. promotional
  • Use hierarchical forecasting (aggregate more stable)
  • Increase forecast frequency
  • Implement min/max rules or dampening

Challenge: New Product Forecasting

Solutions:

  • Analog/reference product approach
  • Market research & test markets
  • Use category-level trends
  • Gradual ramp profiles
  • Monitor closely and adjust quickly

Challenge: Promotional Forecasting

Solutions:

  • Separate baseline from lift
  • Build promotional database (past events)
  • Use regression with promotion features
  • Collaboration with marketing/sales
  • Post-event analysis to improve

Challenge: Long Tail / Intermittent Demand

Solutions:

  • Aggregate to higher levels (product family)
  • Use Croston's or TSB methods
  • Probabilistic forecasting (distributions)
  • Set min/max inventory rules
  • Consider not stocking (order on demand)

Challenge: Data Quality Issues

Solutions:

  • Clean historical data (remove outliers, stockouts)
  • Implement data governance
  • Validate inputs (range checks, anomaly detection)
  • Regular data audits

Challenge: Forecast Bias

Solutions:

  • Track bias metrics
  • Review incentives (sales teams often over-forecast)
  • Separate responsibilities (forecast vs. targets)
  • Use unbiased statistical baseline
  • Forecast value-added analysis

Output Format

Forecast Report Structure

Executive Summary:

  • Overall forecast accuracy (current period)
  • Key changes from prior forecast
  • Major assumptions and risks

Demand Forecast by Segment:

Product/SKULocationPeriodStatistical FcstAdjusted FcstActual (Prior)MAPEBias
Product ADC1Jan 202510,00010,5009,8007.1%+7.1%
........................

Forecast Assumptions:

  • Promotional calendar
  • Market trends
  • New product launches
  • Known supply constraints

Accuracy Metrics:

  • MAPE by category
  • Bias analysis
  • Tracking signals
  • Forecast vs. actual charts

Action Items:

  • Items requiring review
  • Forecast overrides needed
  • Data quality issues
  • Process improvements

Questions to Ask

If you need more context:

  1. What products/SKUs need forecasting? What granularity?
  2. What's the planning horizon? (weeks, months, years)
  3. How much historical data is available?
  4. What external factors impact demand? (promotions, seasonality, events)
  5. What's the current forecast accuracy and known issues?
  6. What tools/systems are in use?
  7. Who uses the forecasts and for what decisions?

Related Skills

  • sales-operations-planning: For integrating forecasts into S&OP
  • capacity-planning: For production capacity based on forecasts
  • inventory-optimization: For safety stock and reorder points
  • supply-chain-analytics: For KPIs and performance tracking
  • ml-supply-chain: For advanced ML forecasting techniques
  • seasonal-planning: For retail seasonal demand
  • promotional-planning: For CPG promotional forecasts

Demand-Supply Matching

You are an expert in demand-supply matching and fulfillment optimization. Your goal is to help organizations effectively balance demand and supply, optimize allocation decisions, and maximize customer service while minimizing costs and inefficiencies.

Initial Assessment

Before implementing demand-supply matching, understand:

  1. Business Context

    • What's driving matching needs? (supply constraints, demand volatility, growth)
    • Current matching process and pain points?
    • Service level objectives by customer/channel?
    • Cost of mismatches (shortages vs. excess)?
  2. Demand Characteristics

    • Demand predictability and variability?
    • Customer/channel segmentation?
    • Priority rules and commitments?
    • Seasonality and promotions?
  3. Supply Constraints

    • Production capacity limitations?
    • Supplier capacity and lead times?
    • Inventory availability across network?
    • Transportation and logistics constraints?
  4. Complexity Factors

    • Multi-plant, multi-DC network?
    • Global vs. regional operations?
    • Product complexity (BOM depth, variants)?
    • Perishability or shelf-life issues?

Demand-Supply Matching Framework

Matching Scenarios

1. Unconstrained (Supply > Demand)

  • Fulfill all demand
  • Optimize fulfillment source
  • Minimize costs
  • Manage excess inventory

2. Constrained (Demand > Supply)

  • Allocate limited supply
  • Prioritize customers/orders
  • Balance service and revenue
  • Communicate shortfalls

3. Balanced (Supply ≈ Demand)

  • Optimize matching
  • Buffer for uncertainty
  • Monitor closely
  • Prepare for swings

Allocation Strategies

1. First-Come, First-Served (FCFS)

  • Simple, fair
  • No prioritization
  • May not optimize value
  • Risk of strategic orders

2. Pro-Rata Allocation

  • Proportional to demand
  • Fair across customers
  • Doesn't consider customer value
  • Simple to implement

3. Priority-Based Allocation

  • Strategic customer priority
  • Contract commitments first
  • Revenue or margin optimization
  • May strain low-priority customers

4. Optimization-Based Allocation

  • Maximize objective (revenue, margin, service)
  • Consider constraints
  • Most complex
  • Best financial outcome

Available-to-Promise (ATP) Logic

ATP Calculation

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

class ATPEngine:
    """Available-to-Promise calculation engine"""

    def __init__(self):
        self.inventory_positions = {}
        self.supply_schedule = []
        self.demand_schedule = []
        self.allocations = []

    def add_inventory_position(self, location, product_id, on_hand, in_transit=0):
        """
        Add current inventory position

        on_hand: Physical inventory
        in_transit: Confirmed receipts en route
        """

        key = (location, product_id)
        self.inventory_positions[key] = {
            'location': location,
            'product_id': product_id,
            'on_hand': on_hand,
            'in_transit': in_transit,
            'available': on_hand,  # Available = on_hand - allocated
            'allocated': 0
        }

    def add_supply(self, location, product_id, quantity, receipt_date):
        """Add future supply (production, purchases, transfers)"""

        self.supply_schedule.append({
            'location': location,
            'product_id': product_id,
            'quantity': quantity,
            'receipt_date': receipt_date,
            'type': 'supply'
        })

    def add_demand(self, location, product_id, quantity, required_date, priority=5):
        """
        Add demand requirement

        priority: 1 (highest) to 10 (lowest)
        """

        self.demand_schedule.append({
            'location': location,
            'product_id': product_id,
            'quantity': quantity,
            'required_date': required_date,
            'priority': priority,
            'type': 'demand',
            'allocated_quantity': 0,
            'status': 'Pending'
        })

    def calculate_atp(self, location, product_id, horizon_days=30):
        """
        Calculate Available-to-Promise for a product-location

        Returns ATP by time period
        """

        key = (location, product_id)

        if key not in self.inventory_positions:
            return None

        # Starting position
        current_available = self.inventory_positions[key]['on_hand']

        # Get relevant supply and demand
        supplies = [s for s in self.supply_schedule
                   if s['location'] == location and s['product_id'] == product_id]

        demands = [d for d in self.demand_schedule
                  if d['location'] == location and d['product_id'] == product_id]

        # Sort by date
        supplies.sort(key=lambda x: x['receipt_date'])
        demands.sort(key=lambda x: x['required_date'])

        # Calculate ATP by period
        today = datetime.now().date()
        atp_schedule = []

        for day_offset in range(horizon_days + 1):
            target_date = today + timedelta(days=day_offset)

            # Add supplies arriving on or before this date
            supplies_today = sum(s['quantity'] for s in supplies
                               if s['receipt_date'] <= target_date)

            # Subtract demands required on or before this date
            demands_today = sum(d['quantity'] for d in demands
                              if d['required_date'] <= target_date)

            atp = current_available + supplies_today - demands_today

            atp_schedule.append({
                'date': target_date,
                'day_offset': day_offset,
                'atp': max(0, atp),  # ATP cannot be negative
                'cumulative_supply': supplies_today,
                'cumulative_demand': demands_today
            })

        return pd.DataFrame(atp_schedule)

    def allocate_supply(self, allocation_method='priority'):
        """
        Allocate available supply to demands

        allocation_method: 'priority', 'fcfs', 'pro_rata'
        """

        if allocation_method == 'priority':
            return self._allocate_by_priority()
        elif allocation_method == 'fcfs':
            return self._allocate_fcfs()
        elif allocation_method == 'pro_rata':
            return self._allocate_pro_rata()
        else:
            raise ValueError(f"Unknown allocation method: {allocation_method}")

    def _allocate_by_priority(self):
        """Allocate supply based on demand priority"""

        # Sort demands by priority (1 = highest) then by date
        sorted_demands = sorted(self.demand_schedule,
                               key=lambda x: (x['priority'], x['required_date']))

        allocations = []

        for demand in sorted_demands:
            location = demand['location']
            product_id = demand['product_id']
            quantity_needed = demand['quantity']

            key = (location, product_id)

            if key not in self.inventory_positions:
                continue

            available = self.inventory_positions[key]['available']

            if available > 0:
                # Allocate as much as possible
                allocated = min(quantity_needed, available)

                # Update available inventory
                self.inventory_positions[key]['available'] -= allocated
                self.inventory_positions[key]['allocated'] += allocated

                # Update demand
                demand['allocated_quantity'] = allocated
                demand['status'] = 'Fulfilled' if allocated == quantity_needed else 'Partial'

                allocations.append({
                    'location': location,
                    'product_id': product_id,
                    'required_date': demand['required_date'],
                    'priority': demand['priority'],
                    'requested_quantity': quantity_needed,
                    'allocated_quantity': allocated,
                    'shortfall': quantity_needed - allocated
                })

        return pd.DataFrame(allocations)

    def _allocate_fcfs(self):
        """Allocate supply first-come, first-served (by date)"""

        # Sort by required date
        sorted_demands = sorted(self.demand_schedule, key=lambda x: x['required_date'])

        allocations = []

        for demand in sorted_demands:
            location = demand['location']
            product_id = demand['product_id']
            quantity_needed = demand['quantity']

            key = (location, product_id)

            if key not in self.inventory_positions:
                continue

            available = self.inventory_positions[key]['available']

            if available > 0:
                allocated = min(quantity_needed, available)

                self.inventory_positions[key]['available'] -= allocated
                self.inventory_positions[key]['allocated'] += allocated

                demand['allocated_quantity'] = allocated
                demand['status'] = 'Fulfilled' if allocated == quantity_needed else 'Partial'

                allocations.append({
                    'location': location,
                    'product_id': product_id,
                    'required_date': demand['required_date'],
                    'requested_quantity': quantity_needed,
                    'allocated_quantity': allocated,
                    'shortfall': quantity_needed - allocated
                })

        return pd.DataFrame(allocations)

    def _allocate_pro_rata(self):
        """Allocate supply proportionally across all demands"""

        # Group demands by location and product
        demand_groups = {}

        for demand in self.demand_schedule:
            key = (demand['location'], demand['product_id'])
            if key not in demand_groups:
                demand_groups[key] = []
            demand_groups[key].append(demand)

        allocations = []

        for key, demands in demand_groups.items():
            location, product_id = key

            if key not in self.inventory_positions:
                continue

            available = self.inventory_positions[key]['available']
            total_demand = sum(d['quantity'] for d in demands)

            if total_demand == 0:
                continue

            # Calculate allocation ratio
            allocation_ratio = min(1.0, available / total_demand)

            for demand in demands:
                allocated = int(demand['quantity'] * allocation_ratio)

                demand['allocated_quantity'] = allocated
                demand['status'] = 'Fulfilled' if allocated == demand['quantity'] else 'Partial'

                allocations.append({
                    'location': location,
                    'product_id': product_id,
                    'required_date': demand['required_date'],
                    'priority': demand.get('priority', 5),
                    'requested_quantity': demand['quantity'],
                    'allocated_quantity': allocated,
                    'allocation_ratio': allocation_ratio,
                    'shortfall': demand['quantity'] - allocated
                })

            self.inventory_positions[key]['allocated'] = sum(a['allocated_quantity'] for a in allocations if a['location'] == location and a['product_id'] == product_id)
            self.inventory_positions[key]['available'] = available - self.inventory_positions[key]['allocated']

        return pd.DataFrame(allocations)

    def generate_shortage_report(self):
        """Generate report of unfulfilled demands"""

        shortages = []

        for demand in self.demand_schedule:
            if demand['status'] in ['Pending', 'Partial']:
                shortfall = demand['quantity'] - demand['allocated_quantity']

                shortages.append({
                    'location': demand['location'],
                    'product_id': demand['product_id'],
                    'required_date': demand['required_date'],
                    'priority': demand['priority'],
                    'requested_quantity': demand['quantity'],
                    'allocated_quantity': demand['allocated_quantity'],
                    'shortfall': shortfall,
                    'status': demand['status']
                })

        return pd.DataFrame(shortages) if shortages else pd.DataFrame()


# Example ATP and allocation
atp_engine = ATPEngine()

# Add inventory positions
atp_engine.add_inventory_position('DC1', 'PROD001', on_hand=1000, in_transit=500)
atp_engine.add_inventory_position('DC2', 'PROD001', on_hand=800, in_transit=300)

# Add future supply
atp_engine.add_supply('DC1', 'PROD001', 500, datetime.now().date() + timedelta(days=10))
atp_engine.add_supply('DC1', 'PROD001', 700, datetime.now().date() + timedelta(days=20))

# Add demands with priorities
atp_engine.add_demand('DC1', 'PROD001', 600, datetime.now().date() + timedelta(days=5), priority=1)  # High priority
atp_engine.add_demand('DC1', 'PROD001', 400, datetime.now().date() + timedelta(days=7), priority=3)
atp_engine.add_demand('DC1', 'PROD001', 500, datetime.now().date() + timedelta(days=12), priority=2)
atp_engine.add_demand('DC1', 'PROD001', 300, datetime.now().date() + timedelta(days=15), priority=5)  # Low priority

# Calculate ATP
atp = atp_engine.calculate_atp('DC1', 'PROD001', horizon_days=30)
print("Available-to-Promise Schedule:")
print(atp[atp['day_offset'] % 5 == 0][['day_offset', 'atp', 'cumulative_supply', 'cumulative_demand']])  # Show every 5 days

# Allocate supply (priority-based)
print("\n\nPriority-Based Allocation:")
allocations = atp_engine.allocate_supply(allocation_method='priority')
print(allocations[['product_id', 'required_date', 'priority', 'requested_quantity', 'allocated_quantity', 'shortfall']])

# Generate shortage report
shortages = atp_engine.generate_shortage_report()
print("\n\nShortage Report:")
if not shortages.empty:
    print(shortages[['product_id', 'required_date', 'priority', 'shortfall', 'status']])
else:
    print("No shortages - all demands fulfilled")

Optimization-Based Allocation

Multi-Objective Allocation Optimization

from scipy.optimize import linprog
import numpy as np

class OptimizedAllocation:
    """Optimization-based demand-supply matching"""

    def optimize_allocation(self, supply_data, demand_data, customer_priorities):
        """
        Optimize allocation to maximize weighted service level

        supply_data: dict {location: {product: quantity}}
        demand_data: list of dicts with customer, product, quantity, location
        customer_priorities: dict {customer: weight} (1-10, higher = more important)
        """

        # Build optimization problem
        # Decision variables: allocation[i] for each demand i

        n_demands = len(demand_data)

        # Objective: Maximize weighted fulfillment
        # Higher priority customers get more weight
        c = []  # Coefficients for objective (negative because linprog minimizes)
        for demand in demand_data:
            customer = demand['customer']
            weight = customer_priorities.get(customer, 5)  # Default weight 5
            c.append(-weight * demand['quantity'])  # Negative for maximization

        c = np.array(c)

        # Constraints: Supply constraints
        # Sum of allocations for each product-location <= available supply

        A_ub = []  # Inequality constraint matrix
        b_ub = []  # Inequality constraint bounds

        # Group demands by product-location
        product_location_demands = {}
        for i, demand in enumerate(demand_data):
            key = (demand['product'], demand['location'])
            if key not in product_location_demands:
                product_location_demands[key] = []
            product_location_demands[key].append(i)

        # Create constraint for each product-location
        for (product, location), demand_indices in product_location_demands.items():
            constraint_row = np.zeros(n_demands)
            for idx in demand_indices:
                constraint_row[idx] = 1  # Sum allocations for this product-location

            A_ub.append(constraint_row)

            # Available supply for this product-location
            available_supply = supply_data.get(location, {}).get(product, 0)
            b_ub.append(available_supply)

        A_ub = np.array(A_ub)
        b_ub = np.array(b_ub)

        # Bounds: 0 <= allocation[i] <= demand[i]
        bounds = [(0, demand['quantity']) for demand in demand_data]

        # Solve
        result = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='highs')

        if result.success:
            allocations = result.x

            # Create allocation results
            allocation_results = []
            for i, demand in enumerate(demand_data):
                allocated = round(allocations[i], 2)
                fulfillment_rate = (allocated / demand['quantity'] * 100) if demand['quantity'] > 0 else 100

                allocation_results.append({
                    'customer': demand['customer'],
                    'product': demand['product'],
                    'location': demand['location'],
                    'requested': demand['quantity'],
                    'allocated': allocated,
                    'fulfillment_rate': round(fulfillment_rate, 1),
                    'priority_weight': customer_priorities.get(demand['customer'], 5)
                })

            return {
                'success': True,
                'allocations': pd.DataFrame(allocation_results),
                'objective_value': -result.fun,  # Negative because we minimized negative
                'solver_status': result.message
            }
        else:
            return {
                'success': False,
                'message': result.message
            }


# Example optimization
optimizer = OptimizedAllocation()

# Supply availability
supply = {
    'DC1': {'PROD001': 1000, 'PROD002': 800},
    'DC2': {'PROD001': 600, 'PROD002': 500}
}

# Demands
demands = [
    {'customer': 'CUST_A', 'product': 'PROD001', 'location': 'DC1', 'quantity': 600},
    {'customer': 'CUST_B', 'product': 'PROD001', 'location': 'DC1', 'quantity': 500},
    {'customer': 'CUST_C', 'product': 'PROD001', 'location': 'DC1', 'quantity': 400},
    {'customer': 'CUST_A', 'product': 'PROD002', 'location': 'DC1', 'quantity': 300},
    {'customer': 'CUST_D', 'product': 'PROD002', 'location': 'DC1', 'quantity': 700},
]

# Customer priorities (1-10, 10 = highest)
priorities = {
    'CUST_A': 10,  # Strategic customer
    'CUST_B': 7,
    'CUST_C': 5,
    'CUST_D': 3
}

# Optimize
result = optimizer.optimize_allocation(supply, demands, priorities)

if result['success']:
    print("Optimized Allocation:")
    print(result['allocations'])
    print(f"\nObjective Value (Weighted Fulfillment): {result['objective_value']:.2f}")
else:
    print(f"Optimization failed: {result['message']}")

Tools & Libraries

Python Libraries

Optimization:

  • scipy.optimize: Linear and non-linear optimization
  • pulp: Linear programming
  • pyomo: Optimization modeling
  • ortools: Google OR-Tools

Data Processing:

  • pandas: Data manipulation
  • numpy: Numerical computations

Forecasting Integration:

  • statsmodels: Statistical models
  • prophet: Forecasting

Commercial Software

Planning & Allocation:

  • Blue Yonder: Allocation and fulfillment
  • Kinaxis RapidResponse: S&OP and allocation
  • o9 Solutions: Demand-supply matching
  • SAP IBP: Integrated business planning
  • Oracle Demantra: Demand and supply planning

Order Management:

  • Manhattan OMS: Order management and allocation
  • Blue Yonder Order Management: Fulfillment optimization
  • Fluent Commerce: Order orchestration
  • Salesforce Order Management: Commerce cloud

ATP/CTP Engines:

  • SAP ATP: Available-to-promise
  • Oracle ATP: Global order promising
  • Kinaxis ATP: Real-time promising

Common Challenges & Solutions

Challenge: Conflicting Objectives

Problem:

  • Maximize revenue vs. customer fairness
  • Short-term profit vs. long-term relationships
  • Service level vs. cost
  • Competing stakeholder interests

Solutions:

  • Multi-objective optimization with weights
  • Clear prioritization framework
  • Scenario analysis to show trade-offs
  • Executive governance for conflicts
  • Customer tier classification
  • Balanced scorecards

Challenge: Dynamic Conditions

Problem:

  • Demand and supply constantly changing
  • Need for frequent re-optimization
  • Orders arriving continuously
  • Real-time updates required

Solutions:

  • Event-driven matching (trigger on changes)
  • Periodic re-optimization cycles
  • Rolling horizon approach
  • Reservation and release logic
  • Buffer for uncertainty
  • Near-real-time systems

Challenge: Data Quality

Problem:

  • Inaccurate inventory positions
  • Outdated supply schedules
  • Forecast errors
  • System delays

Solutions:

  • Real-time inventory visibility
  • Automated data feeds
  • Data validation and reconciliation
  • Buffer for data uncertainty
  • Regular cycle counting
  • Safety margins in ATP

Challenge: Customer Communication

Problem:

  • Managing expectations on allocation
  • Explaining shortfalls
  • Transparency vs. competitive information
  • Fairness perception

Solutions:

  • Clear allocation policies communicated upfront
  • Proactive shortage notifications
  • Alternative options offered
  • Historical allocation transparency
  • Customer portal with visibility
  • Regular business reviews

Challenge: Complexity at Scale

Problem:

  • Large number of SKUs, locations, customers
  • Computational time for optimization
  • Combinatorial explosion
  • Network constraints

Solutions:

  • Hierarchical optimization (aggregate then detail)
  • Heuristic approaches for large problems
  • Parallel processing
  • Incremental updates vs. full re-optimization
  • Simplification where possible
  • High-performance computing

Challenge: Cross-Functional Alignment

Problem:

  • Sales wants maximum fulfillment
  • Finance wants inventory reduction
  • Operations wants stability
  • Misaligned incentives

Solutions:

  • Shared KPIs and goals
  • Integrated S&OP process
  • Cross-functional governance
  • Transparent decision rules
  • Regular alignment meetings
  • Executive sponsorship

Output Format

Demand-Supply Matching Report

Executive Summary:

  • Overall demand-supply balance
  • Allocation decisions made
  • Shortfalls and impacts
  • Actions required

Supply-Demand Balance:

ProductTotal DemandTotal SupplyBalanceStatus
PROD0012,5002,800+300✓ Surplus
PROD0021,8001,500-300⚠ Shortage
PROD0031,2001,2000✓ Balanced
PROD004950600-350⚠⚠ Critical Shortage

Allocation Results:

CustomerProductRequestedAllocatedFulfillment %PriorityStatus
CUST_APROD001600600100%1Fulfilled
CUST_BPROD001500500100%3Fulfilled
CUST_CPROD00280060075%2Partial
CUST_DPROD00250000%5Unfulfilled

Shortage Impact:

ProductShortage QtyAffected CustomersRevenue at RiskMitigation Actions
PROD0023002$45KExpedite production, substitute PROD003
PROD0043503$28KAllocate to strategic customers only

ATP Horizon:

ProductLocationTodayWeek 1Week 2Week 3Week 4
PROD001DC14006501,1001,3001,200
PROD002DC10200600800750

Action Items:

PriorityActionOwnerDue DateStatus
CriticalExpedite PROD002 productionOperationsTomorrowIn Progress
HighCommunicate shortfalls to affected customersSalesTodayPending
MediumEvaluate substitute products for PROD004Product MgmtThis weekPlanning

Questions to Ask

If you need more context:

  1. What's the current demand-supply balance situation?
  2. What allocation method is preferred? (priority, pro-rata, optimization)
  3. What customer segmentation or prioritization exists?
  4. What are the service level objectives?
  5. What supply constraints exist? (capacity, inventory, logistics)
  6. How frequently does matching need to occur?
  7. What systems provide demand and supply data?
  8. What's the cost of shortages vs. excess?
  9. Are there substitutable products?
  10. What decision authority exists for allocation?

Related Skills

  • demand-forecasting: For accurate demand inputs
  • sales-operations-planning: For integrated demand-supply planning
  • inventory-optimization: For safety stock and buffer decisions
  • capacity-planning: For supply capacity constraints
  • supplier-collaboration: For collaborative supply planning
  • control-tower-design: For real-time visibility and monitoring
  • network-design: For optimizing fulfillment network
  • route-optimization: For logistics constraints in matching

Digital Twin Modeling

You are an expert in digital twin modeling and supply chain simulation. Your goal is to help build virtual replicas of supply chain systems that enable testing, scenario analysis, optimization, and predictive insights without disrupting real operations.

Initial Assessment

Before building a digital twin, understand:

  1. Business Context

    • What supply chain system needs a digital twin? (warehouse, network, production line)
    • What decisions will the twin support? (capacity planning, layout design, policy testing)
    • Current pain points? (bottlenecks, unpredictable performance, risky changes)
    • Expected ROI or value from digital twin?
  2. System Scope

    • Physical assets to model? (facilities, equipment, vehicles, inventory)
    • Processes to simulate? (order fulfillment, production, transportation)
    • System boundaries? (single facility, network, end-to-end supply chain)
    • Level of detail needed? (high-level vs. detailed operations)
  3. Data Availability

    • Historical operational data? (transaction logs, sensor data, timestamps)
    • System parameters? (capacities, speeds, processing times)
    • Demand patterns and variability?
    • Real-time data feeds available? (IoT, ERP, WMS, TMS)
  4. Technical Environment

    • Simulation expertise in team?
    • Preferred tools? (Python, Arena, AnyLogic, FlexSim)
    • Integration requirements? (ERP, real-time dashboards)
    • Computational resources available?

Digital Twin Framework

Digital Twin Maturity Levels

Level 1: Descriptive Twin (What happened?)

  • Static 3D model or visualization
  • Historical data replay
  • Basic reporting
  • No predictive capability

Level 2: Informative Twin (Why did it happen?)

  • Real-time data integration
  • Performance monitoring
  • KPI dashboards
  • Diagnostic analytics

Level 3: Predictive Twin (What will happen?)

  • Simulation models
  • Scenario analysis
  • Forecasting capabilities
  • What-if testing

Level 4: Prescriptive Twin (What should we do?)

  • Optimization integration
  • Automated recommendations
  • Autonomous decision-making
  • Continuous learning (ML integration)

Level 5: Autonomous Twin (Self-optimizing)

  • Fully autonomous operations
  • Self-healing capabilities
  • Continuous adaptation
  • Closed-loop control

Digital Twin Architecture

┌─────────────────────────────────────────────────────────┐
│                    Digital Twin Layer                    │
├─────────────────────────────────────────────────────────┤
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │ Visualization│  │  Simulation  │  │ Optimization │ │
│  │    Layer     │  │    Engine    │  │    Engine    │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
├─────────────────────────────────────────────────────────┤
│                    Analytics Layer                       │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │   Real-Time  │  │  Predictive  │  │ Prescriptive │ │
│  │   Analytics  │  │    Models    │  │   Analytics  │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
├─────────────────────────────────────────────────────────┤
│                 Data Integration Layer                   │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │  Historical  │  │  Real-Time   │  │   External   │ │
│  │     Data     │  │  Streaming   │  │  Data APIs   │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
├─────────────────────────────────────────────────────────┤
│                   Physical Assets Layer                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  │  Warehouses  │  │ Transportation│  │  Production  │ │
│  │   & DCs      │  │    Fleet     │  │  Facilities  │ │
│  └──────────────┘  └──────────────┘  └──────────────┘ │
└─────────────────────────────────────────────────────────┘

Simulation Modeling Approaches

Discrete Event Simulation (DES)

Best For:

  • Order fulfillment processes
  • Manufacturing operations
  • Warehouse operations
  • Transportation networks

Key Concepts:

  • Events occur at discrete points in time
  • Entities (orders, products, trucks) move through system
  • Resources (workers, equipment) constrain flow
  • Queues form when demand exceeds capacity

Python Implementation with SimPy:

import simpy
import random
import pandas as pd
import numpy as np

class WarehouseDigitalTwin:
    """
    Digital twin of warehouse operations using discrete event simulation
    """

    def __init__(self, env, config):
        """
        Initialize warehouse digital twin

        config: dictionary with warehouse parameters
        - num_receiving_docks
        - num_pickers
        - num_packing_stations
        - num_shipping_docks
        """
        self.env = env
        self.config = config

        # Resources
        self.receiving_docks = simpy.Resource(env, config['num_receiving_docks'])
        self.pickers = simpy.Resource(env, config['num_pickers'])
        self.packing_stations = simpy.Resource(env, config['num_packing_stations'])
        self.shipping_docks = simpy.Resource(env, config['num_shipping_docks'])

        # Performance tracking
        self.metrics = {
            'orders_completed': 0,
            'total_cycle_time': 0,
            'receiving_queue_times': [],
            'picking_queue_times': [],
            'packing_queue_times': [],
            'shipping_queue_times': []
        }

    def receive_inventory(self, shipment_id):
        """Simulate receiving process"""

        arrival_time = self.env.now

        # Wait for receiving dock
        with self.receiving_docks.request() as request:
            yield request

            queue_time = self.env.now - arrival_time
            self.metrics['receiving_queue_times'].append(queue_time)

            # Unloading time (varies by shipment size)
            unload_time = random.uniform(30, 60)  # minutes
            yield self.env.timeout(unload_time)

            # Put-away time
            putaway_time = random.uniform(20, 40)
            yield self.env.timeout(putaway_time)

    def fulfill_order(self, order_id, num_items):
        """Simulate order fulfillment process"""

        order_start = self.env.now

        # Picking process
        pick_arrival = self.env.now
        with self.pickers.request() as request:
            yield request

            pick_queue_time = self.env.now - pick_arrival
            self.metrics['picking_queue_times'].append(pick_queue_time)

            # Picking time depends on number of items
            pick_time = num_items * random.uniform(2, 4)  # minutes per item
            yield self.env.timeout(pick_time)

        # Packing process
        pack_arrival = self.env.now
        with self.packing_stations.request() as request:
            yield request

            pack_queue_time = self.env.now - pack_arrival
            self.metrics['packing_queue_times'].append(pack_queue_time)

            # Packing time
            pack_time = random.uniform(5, 15)  # minutes
            yield self.env.timeout(pack_time)

        # Shipping process
        ship_arrival = self.env.now
        with self.shipping_docks.request() as request:
            yield request

            ship_queue_time = self.env.now - ship_arrival
            self.metrics['shipping_queue_times'].append(ship_queue_time)

            # Loading time
            load_time = random.uniform(5, 10)  # minutes
            yield self.env.timeout(load_time)

        # Record completion
        cycle_time = self.env.now - order_start
        self.metrics['orders_completed'] += 1
        self.metrics['total_cycle_time'] += cycle_time

    def generate_orders(self, arrival_rate=5):
        """
        Generate order arrivals (Poisson process)

        arrival_rate: average orders per hour
        """
        order_num = 0

        while True:
            # Inter-arrival time (exponential distribution)
            inter_arrival = random.expovariate(arrival_rate / 60)  # convert to minutes
            yield self.env.timeout(inter_arrival)

            # Create order
            order_num += 1
            num_items = random.randint(1, 10)

            # Start order fulfillment process
            self.env.process(self.fulfill_order(order_num, num_items))

    def run_simulation(self, duration_hours):
        """Run simulation for specified duration"""

        # Start order generation
        self.env.process(self.generate_orders(arrival_rate=5))

        # Run simulation
        self.env.run(until=duration_hours * 60)  # convert to minutes

        # Calculate summary metrics
        return self.get_performance_metrics()

    def get_performance_metrics(self):
        """Calculate and return performance metrics"""

        metrics = {
            'orders_completed': self.metrics['orders_completed'],
            'avg_cycle_time_min': (self.metrics['total_cycle_time'] /
                                   self.metrics['orders_completed']
                                   if self.metrics['orders_completed'] > 0 else 0),
            'avg_receiving_queue_min': (np.mean(self.metrics['receiving_queue_times'])
                                        if self.metrics['receiving_queue_times'] else 0),
            'avg_picking_queue_min': (np.mean(self.metrics['picking_queue_times'])
                                      if self.metrics['picking_queue_times'] else 0),
            'avg_packing_queue_min': (np.mean(self.metrics['packing_queue_times'])
                                      if self.metrics['packing_queue_times'] else 0),
            'avg_shipping_queue_min': (np.mean(self.metrics['shipping_queue_times'])
                                       if self.metrics['shipping_queue_times'] else 0),
            'throughput_orders_per_hour': (self.metrics['orders_completed'] /
                                          (self.env.now / 60))
        }

        return metrics

# Run simulation
env = simpy.Environment()

config = {
    'num_receiving_docks': 3,
    'num_pickers': 10,
    'num_packing_stations': 5,
    'num_shipping_docks': 4
}

warehouse_twin = WarehouseDigitalTwin(env, config)
results = warehouse_twin.run_simulation(duration_hours=8)

print("Warehouse Performance Metrics:")
print(f"Orders Completed: {results['orders_completed']}")
print(f"Average Cycle Time: {results['avg_cycle_time_min']:.1f} minutes")
print(f"Throughput: {results['throughput_orders_per_hour']:.1f} orders/hour")
print(f"Average Picking Queue Time: {results['avg_picking_queue_min']:.1f} minutes")

Scenario Analysis with Digital Twin

def scenario_analysis(base_config, scenarios, num_replications=10):
    """
    Run multiple scenarios to compare performance

    scenarios: dict of scenario configs to test
    num_replications: number of simulation runs per scenario
    """

    results = []

    for scenario_name, scenario_config in scenarios.items():
        print(f"\nRunning scenario: {scenario_name}")

        scenario_results = []

        for rep in range(num_replications):
            # Create new environment
            env = simpy.Environment()

            # Merge base config with scenario config
            config = {**base_config, **scenario_config}

            # Run simulation
            warehouse = WarehouseDigitalTwin(env, config)
            metrics = warehouse.run_simulation(duration_hours=8)

            metrics['scenario'] = scenario_name
            metrics['replication'] = rep
            scenario_results.append(metrics)

        results.extend(scenario_results)

    # Convert to DataFrame for analysis
    results_df = pd.DataFrame(results)

    # Calculate summary statistics by scenario
    summary = results_df.groupby('scenario').agg({
        'orders_completed': ['mean', 'std'],
        'avg_cycle_time_min': ['mean', 'std'],
        'throughput_orders_per_hour': ['mean', 'std']
    }).round(2)

    return results_df, summary

# Define scenarios
base_config = {
    'num_receiving_docks': 3,
    'num_pickers': 10,
    'num_packing_stations': 5,
    'num_shipping_docks': 4
}

scenarios = {
    'Baseline': {},
    'Add_Pickers': {'num_pickers': 15},
    'Add_Packing': {'num_packing_stations': 8},
    'Add_Both': {'num_pickers': 15, 'num_packing_stations': 8}
}

results_df, summary = scenario_analysis(base_config, scenarios, num_replications=20)

print("\nScenario Comparison:")
print(summary)

# Visualize results
import matplotlib.pyplot as plt
import seaborn as sns

fig, axes = plt.subplots(1, 2, figsize=(14, 5))

# Cycle time comparison
sns.boxplot(data=results_df, x='scenario', y='avg_cycle_time_min', ax=axes[0])
axes[0].set_title('Cycle Time by Scenario')
axes[0].set_ylabel('Average Cycle Time (minutes)')
axes[0].set_xlabel('Scenario')

# Throughput comparison
sns.boxplot(data=results_df, x='scenario', y='throughput_orders_per_hour', ax=axes[1])
axes[1].set_title('Throughput by Scenario')
axes[1].set_ylabel('Orders per Hour')
axes[1].set_xlabel('Scenario')

plt.tight_layout()
plt.show()

Advanced Digital Twin Components

Agent-Based Modeling (ABM)

Best For:

  • Complex adaptive systems
  • Distributed decision-making
  • Emergent behaviors
  • Multi-actor supply chains
import mesa
import numpy as np

class SupplierAgent(mesa.Agent):
    """Supplier agent in supply chain network"""

    def __init__(self, unique_id, model, capacity, lead_time, reliability):
        super().__init__(unique_id, model)
        self.capacity = capacity
        self.lead_time = lead_time
        self.reliability = reliability  # 0-1 probability of on-time delivery
        self.current_orders = []
        self.fulfilled_orders = 0
        self.revenue = 0

    def step(self):
        """Process orders each time step"""

        # Process pending orders
        orders_to_remove = []

        for order in self.current_orders:
            order['time_remaining'] -= 1

            if order['time_remaining'] <= 0:
                # Order ready
                if random.random() < self.reliability:
                    # Successfully deliver
                    order['customer'].receive_order(order)
                    self.fulfilled_orders += 1
                    self.revenue += order['value']
                else:
                    # Delayed delivery
                    order['time_remaining'] = random.randint(1, 3)

                if order['time_remaining'] <= 0:
                    orders_to_remove.append(order)

        for order in orders_to_remove:
            self.current_orders.remove(order)

    def accept_order(self, order):
        """Accept new order if capacity available"""

        if len(self.current_orders) < self.capacity:
            order['time_remaining'] = self.lead_time
            self.current_orders.append(order)
            return True
        return False


class ManufacturerAgent(mesa.Agent):
    """Manufacturer agent"""

    def __init__(self, unique_id, model, inventory_target, reorder_point):
        super().__init__(unique_id, model)
        self.inventory = inventory_target
        self.inventory_target = inventory_target
        self.reorder_point = reorder_point
        self.pending_orders = []
        self.demand_fulfilled = 0
        self.stockouts = 0

    def step(self):
        """Simulate manufacturer operations"""

        # Check inventory and place orders if needed
        if self.inventory < self.reorder_point:
            order_qty = self.inventory_target - self.inventory

            # Find best supplier
            suppliers = [agent for agent in self.model.schedule.agents
                        if isinstance(agent, SupplierAgent)]

            if suppliers:
                # Choose supplier based on reliability and capacity
                supplier = max(suppliers, key=lambda s: s.reliability)

                order = {
                    'quantity': order_qty,
                    'customer': self,
                    'value': order_qty * 100
                }

                if supplier.accept_order(order):
                    self.pending_orders.append(order)

        # Simulate customer demand
        demand = random.poisson(50)  # Daily demand

        if self.inventory >= demand:
            self.inventory -= demand
            self.demand_fulfilled += demand
        else:
            self.demand_fulfilled += self.inventory
            self.stockouts += (demand - self.inventory)
            self.inventory = 0

    def receive_order(self, order):
        """Receive order from supplier"""
        self.inventory += order['quantity']
        if order in self.pending_orders:
            self.pending_orders.remove(order)


class SupplyChainModel(mesa.Model):
    """Agent-based supply chain digital twin"""

    def __init__(self, num_suppliers, num_manufacturers):
        self.schedule = mesa.time.RandomActivation(self)
        self.running = True

        # Create agents
        agent_id = 0

        # Suppliers
        for _ in range(num_suppliers):
            supplier = SupplierAgent(
                agent_id,
                self,
                capacity=random.randint(5, 10),
                lead_time=random.randint(3, 7),
                reliability=random.uniform(0.85, 0.98)
            )
            self.schedule.add(supplier)
            agent_id += 1

        # Manufacturers
        for _ in range(num_manufacturers):
            manufacturer = ManufacturerAgent(
                agent_id,
                self,
                inventory_target=random.randint(500, 1000),
                reorder_point=random.randint(200, 400)
            )
            self.schedule.add(manufacturer)
            agent_id += 1

        # Data collector
        self.datacollector = mesa.DataCollector(
            model_reporters={
                "Total_Inventory": lambda m: sum(
                    agent.inventory for agent in m.schedule.agents
                    if isinstance(agent, ManufacturerAgent)
                ),
                "Total_Stockouts": lambda m: sum(
                    agent.stockouts for agent in m.schedule.agents
                    if isinstance(agent, ManufacturerAgent)
                ),
                "Total_Revenue": lambda m: sum(
                    agent.revenue for agent in m.schedule.agents
                    if isinstance(agent, SupplierAgent)
                )
            }
        )

    def step(self):
        """Advance model by one step"""
        self.datacollector.collect(self)
        self.schedule.step()

# Run agent-based model
model = SupplyChainModel(num_suppliers=5, num_manufacturers=3)

for _ in range(365):  # Simulate 1 year
    model.step()

# Extract results
results = model.datacollector.get_model_vars_dataframe()

print(f"Average Inventory: {results['Total_Inventory'].mean():.0f}")
print(f"Total Stockouts: {results['Total_Stockouts'].sum():.0f}")
print(f"Total Revenue: {results['Total_Revenue'].sum():.0f}")

# Plot results
results.plot(subplots=True, figsize=(12, 8))
plt.tight_layout()
plt.show()

Network Digital Twin

import networkx as nx
import matplotlib.pyplot as plt

class SupplyChainNetworkTwin:
    """
    Digital twin of supply chain network
    """

    def __init__(self):
        self.network = nx.DiGraph()
        self.node_data = {}
        self.flow_data = {}

    def add_facility(self, facility_id, facility_type, location, capacity, cost):
        """Add facility node to network"""

        self.network.add_node(
            facility_id,
            type=facility_type,
            location=location,
            capacity=capacity,
            cost=cost
        )

        self.node_data[facility_id] = {
            'type': facility_type,
            'location': location,
            'capacity': capacity,
            'cost': cost,
            'current_inventory': 0,
            'utilization': 0
        }

    def add_lane(self, from_facility, to_facility, distance, transport_cost,
                 transit_time, mode):
        """Add transportation lane between facilities"""

        self.network.add_edge(
            from_facility,
            to_facility,
            distance=distance,
            cost=transport_cost,
            transit_time=transit_time,
            mode=mode,
            flow=0
        )

    def simulate_flow(self, demand_by_customer, days=30):
        """
        Simulate product flow through network

        demand_by_customer: dict {customer_id: daily_demand}
        """

        results = {
            'day': [],
            'total_cost': [],
            'avg_delivery_time': [],
            'fill_rate': []
        }

        for day in range(days):
            daily_cost = 0
            deliveries = []
            unmet_demand = 0

            # Process each customer's demand
            for customer_id, demand in demand_by_customer.items():
                # Find path from supplier to customer
                # (simplified: assume single source)

                source = [n for n, d in self.network.nodes(data=True)
                         if d['type'] == 'supplier'][0]

                try:
                    path = nx.shortest_path(
                        self.network,
                        source,
                        customer_id,
                        weight='cost'
                    )

                    # Calculate delivery time and cost
                    delivery_time = 0
                    transport_cost = 0

                    for i in range(len(path) - 1):
                        edge_data = self.network[path[i]][path[i+1]]
                        delivery_time += edge_data['transit_time']
                        transport_cost += edge_data['cost'] * demand

                        # Update flow
                        self.network[path[i]][path[i+1]]['flow'] += demand

                    daily_cost += transport_cost
                    deliveries.append(delivery_time)

                except nx.NetworkXNoPath:
                    unmet_demand += demand

            # Record metrics
            results['day'].append(day)
            results['total_cost'].append(daily_cost)
            results['avg_delivery_time'].append(
                np.mean(deliveries) if deliveries else 0
            )

            total_demand = sum(demand_by_customer.values())
            results['fill_rate'].append(
                (total_demand - unmet_demand) / total_demand * 100
            )

        return pd.DataFrame(results)

    def visualize_network(self, show_flows=True):
        """Visualize supply chain network"""

        pos = nx.spring_layout(self.network, k=2, iterations=50)

        plt.figure(figsize=(14, 10))

        # Color nodes by type
        node_colors = []
        for node in self.network.nodes():
            node_type = self.network.nodes[node]['type']
            if node_type == 'supplier':
                node_colors.append('lightgreen')
            elif node_type == 'dc':
                node_colors.append('lightblue')
            elif node_type == 'customer':
                node_colors.append('lightcoral')
            else:
                node_colors.append('lightgray')

        # Draw nodes
        nx.draw_networkx_nodes(
            self.network,
            pos,
            node_color=node_colors,
            node_size=1000,
            alpha=0.8
        )

        # Draw edges with width proportional to flow
        if show_flows:
            max_flow = max([self.network[u][v]['flow']
                           for u, v in self.network.edges()] or [1])

            for u, v in self.network.edges():
                flow = self.network[u][v]['flow']
                width = (flow / max_flow) * 5 if max_flow > 0 else 1

                nx.draw_networkx_edges(
                    self.network,
                    pos,
                    [(u, v)],
                    width=width,
                    alpha=0.6,
                    edge_color='gray',
                    arrows=True,
                    arrowsize=20
                )
        else:
            nx.draw_networkx_edges(
                self.network,
                pos,
                alpha=0.5,
                arrows=True
            )

        # Draw labels
        nx.draw_networkx_labels(
            self.network,
            pos,
            font_size=10,
            font_weight='bold'
        )

        plt.title("Supply Chain Network Digital Twin")
        plt.axis('off')
        plt.tight_layout()
        plt.show()

    def analyze_bottlenecks(self):
        """Identify network bottlenecks"""

        bottlenecks = []

        for node in self.network.nodes():
            node_data = self.node_data[node]

            if node_data['type'] in ['dc', 'supplier']:
                # Check utilization
                utilization = node_data.get('utilization', 0)

                if utilization > 0.85:  # 85% threshold
                    bottlenecks.append({
                        'facility': node,
                        'type': node_data['type'],
                        'utilization': utilization,
                        'capacity': node_data['capacity'],
                        'issue': 'High utilization'
                    })

        # Check for high-flow edges
        for u, v in self.network.edges():
            flow = self.network[u][v]['flow']
            # Assume edge capacity is 1000 units/day
            if flow > 800:
                bottlenecks.append({
                    'facility': f"{u} -> {v}",
                    'type': 'lane',
                    'utilization': flow / 1000,
                    'capacity': 1000,
                    'issue': 'High lane flow'
                })

        return pd.DataFrame(bottlenecks)

# Example usage
network_twin = SupplyChainNetworkTwin()

# Add facilities
network_twin.add_facility('Supplier_1', 'supplier', (0, 0), 10000, 1000000)
network_twin.add_facility('DC_East', 'dc', (5, 2), 5000, 500000)
network_twin.add_facility('DC_West', 'dc', (2, 5), 5000, 500000)
network_twin.add_facility('Customer_A', 'customer', (8, 3), None, 0)
network_twin.add_facility('Customer_B', 'customer', (3, 7), None, 0)

# Add lanes
network_twin.add_lane('Supplier_1', 'DC_East', 500, 2.5, 2, 'truck')
network_twin.add_lane('Supplier_1', 'DC_West', 400, 2.5, 2, 'truck')
network_twin.add_lane('DC_East', 'Customer_A', 150, 2.0, 1, 'truck')
network_twin.add_lane('DC_West', 'Customer_B', 200, 2.0, 1, 'truck')

# Simulate
demand = {
    'Customer_A': 100,
    'Customer_B': 150
}

results = network_twin.simulate_flow(demand, days=30)

print("Average Daily Cost:", results['total_cost'].mean())
print("Average Delivery Time:", results['avg_delivery_time'].mean())
print("Average Fill Rate:", results['fill_rate'].mean())

# Visualize
network_twin.visualize_network(show_flows=True)

Real-Time Digital Twin with IoT Integration

import time
from datetime import datetime
import threading

class RealTimeWarehouseTwin:
    """
    Real-time digital twin with live data integration
    """

    def __init__(self):
        self.state = {
            'timestamp': None,
            'active_orders': 0,
            'picking_queue': 0,
            'packing_queue': 0,
            'inventory_levels': {},
            'equipment_status': {},
            'alerts': []
        }

        self.historical_data = []
        self.is_running = False

    def connect_to_wms(self, wms_api_endpoint):
        """Connect to warehouse management system API"""
        # In production, connect to real WMS API
        pass

    def connect_to_iot_sensors(self, sensor_endpoints):
        """Connect to IoT sensor streams"""
        # In production, connect to real IoT platform
        pass

    def update_from_live_data(self):
        """Update digital twin state from live data sources"""

        while self.is_running:
            # Simulate data fetch (in production, call actual APIs)
            new_state = self.fetch_live_data()

            # Update state
            self.state = new_state
            self.state['timestamp'] = datetime.now()

            # Store historical data
            self.historical_data.append(self.state.copy())

            # Check for alerts
            self.check_alerts()

            # Sleep before next update
            time.sleep(5)  # Update every 5 seconds

    def fetch_live_data(self):
        """Fetch live data from various sources"""

        # Simulate live data (replace with real API calls)
        return {
            'timestamp': datetime.now(),
            'active_orders': random.randint(50, 150),
            'picking_queue': random.randint(10, 50),
            'packing_queue': random.randint(5, 30),
            'inventory_levels': {
                f'SKU_{i}': random.randint(0, 1000)
                for i in range(1, 11)
            },
            'equipment_status': {
                'Forklift_1': 'active',
                'Forklift_2': 'active',
                'Conveyor_1': 'active',
                'Sorter_1': 'active'
            },
            'alerts': []
        }

    def check_alerts(self):
        """Check for anomalies and generate alerts"""

        alerts = []

        # High queue alert
        if self.state['picking_queue'] > 40:
            alerts.append({
                'severity': 'HIGH',
                'type': 'Queue Buildup',
                'message': f"Picking queue at {self.state['picking_queue']} orders",
                'timestamp': datetime.now()
            })

        # Low inventory alert
        for sku, level in self.state['inventory_levels'].items():
            if level < 100:
                alerts.append({
                    'severity': 'MEDIUM',
                    'type': 'Low Inventory',
                    'message': f"{sku} below reorder point: {level} units",
                    'timestamp': datetime.now()
                })

        self.state['alerts'] = alerts

    def predict_future_state(self, hours_ahead=4):
        """
        Predict future warehouse state using historical patterns

        Uses simple time series forecasting
        """

        if len(self.historical_data) < 50:
            return None  # Need more historical data

        # Extract time series
        df = pd.DataFrame(self.historical_data)
        df['timestamp'] = pd.to_datetime(df['timestamp'])
        df = df.set_index('timestamp')

        # Simple moving average prediction
        predictions = {
            'active_orders': df['active_orders'].rolling(20).mean().iloc[-1],
            'picking_queue': df['picking_queue'].rolling(20).mean().iloc[-1],
            'packing_queue': df['packing_queue'].rolling(20).mean().iloc[-1]
        }

        return predictions

    def start(self):
        """Start real-time monitoring"""
        self.is_running = True

        # Start update thread
        update_thread = threading.Thread(target=self.update_from_live_data)
        update_thread.daemon = True
        update_thread.start()

    def stop(self):
        """Stop real-time monitoring"""
        self.is_running = False

    def get_dashboard_data(self):
        """Get current state for dashboard display"""
        return {
            'current_state': self.state,
            'predictions': self.predict_future_state(),
            'alerts': self.state['alerts']
        }

# Example usage
twin = RealTimeWarehouseTwin()
twin.start()

# Run for some time
time.sleep(60)

# Get dashboard data
dashboard_data = twin.get_dashboard_data()
print("Current Active Orders:", dashboard_data['current_state']['active_orders'])
print("Alerts:", len(dashboard_data['current_state']['alerts']))

twin.stop()

Tools & Technologies

Simulation Software

Commercial:

  • AnyLogic: Multi-method simulation (DES, ABM, SD)
  • Arena (Rockwell): Discrete event simulation
  • FlexSim: 3D simulation for manufacturing and logistics
  • Simul8: Process simulation
  • ExtendSim: Simulation for logistics and supply chain
  • Plant Simulation (Siemens): Manufacturing simulation
  • SIMIO: Object-based simulation

Open Source:

  • SimPy (Python): Discrete event simulation
  • Mesa (Python): Agent-based modeling
  • Salabim (Python): Discrete event simulation
  • des.js (JavaScript): Browser-based DES
  • AnyLogic PLE: Free personal learning edition

Python Libraries

Simulation:

  • simpy: Discrete event simulation
  • mesa: Agent-based modeling
  • salabim: Advanced DES with animation
  • ciw: Queueing network simulation

Network Modeling:

  • networkx: Graph and network analysis
  • pyvis: Interactive network visualization
  • graph-tool: Large-scale network analysis

Visualization:

  • matplotlib: Basic plotting
  • plotly: Interactive 3D visualization
  • mayavi: Advanced 3D visualization
  • pygame: Real-time animation

Data Integration:

  • pandas: Data manipulation
  • numpy: Numerical operations
  • sqlalchemy: Database connections
  • requests: API integration
  • mqtt: IoT data streaming

Digital Twin Platforms

Enterprise:

  • Azure Digital Twins (Microsoft): Cloud-based digital twin platform
  • AWS IoT TwinMaker: Build digital twins with AWS
  • GE Digital Twin: Industrial IoT platform
  • Siemens MindSphere: IoT operating system
  • PTC ThingWorx: IoT and AR platform
  • IBM Maximo: Asset management and digital twin

Supply Chain Specific:

  • Blue Yonder Luminate: Digital supply chain platform
  • o9 Solutions: Digital brain platform with simulation
  • Kinaxis RapidResponse: Concurrent planning with scenarios
  • LLamasoft (Coupa): Supply chain design and simulation

Common Challenges & Solutions

Challenge: Data Quality and Availability

Problem:

  • Insufficient historical data
  • Missing parameters (processing times, failure rates)
  • Inconsistent data formats

Solutions:

  • Use time studies to collect missing parameters
  • Implement data collection systems (IoT sensors, automated logging)
  • Start with simplified model, add detail iteratively
  • Use industry benchmarks where data unavailable
  • Validate model with subject matter experts

Challenge: Model Complexity vs. Usability

Problem:

  • Too detailed = slow, hard to maintain
  • Too simple = inaccurate, limited value

Solutions:

  • Start simple, add complexity only where needed
  • Use appropriate level of detail for decisions being made
  • Modular design (swap detailed/simplified components)
  • Separate strategic (high-level) and operational (detailed) models
  • Clear documentation of assumptions and limitations

Challenge: Real-Time Integration

Problem:

  • Legacy systems without APIs
  • Data latency issues
  • Integration complexity

Solutions:

  • Use middleware or integration platforms
  • Implement data buffering and caching
  • Start with batch updates, evolve to real-time
  • Use event-driven architecture
  • Consider cloud-based integration services

Challenge: Stakeholder Buy-In

Problem:

  • Resistance to simulation results
  • "Black box" perception
  • Lack of trust in model

Solutions:

  • Involve stakeholders in model development
  • Validate model against known scenarios
  • Transparent documentation of logic and assumptions
  • Show sensitivity analysis to build confidence
  • Start with pilot/proof-of-concept
  • Visualize results effectively (3D animation helps)

Challenge: Keeping Model Updated

Problem:

  • Operations change, model becomes obsolete
  • Maintenance overhead
  • No clear owner

Solutions:

  • Assign clear model ownership and governance
  • Automate data updates where possible
  • Regular validation against actual performance
  • Version control for model changes
  • Schedule periodic reviews and updates
  • Design for maintainability from start

Output Format

Digital Twin Report Template

Executive Summary:

  • Purpose of digital twin
  • Key findings from simulation
  • Recommended decisions
  • Expected impact and ROI

Model Overview:

  • Scope and boundaries
  • Components modeled
  • Level of detail
  • Key assumptions

Scenario Analysis Results:

ScenarioThroughputAvg Cycle TimeUtilizationCostRecommendation
Baseline500/day4.2 hrs78%$125K/moCurrent state
Add Resources650/day3.1 hrs82%$145K/mo⭐ Recommended
Optimize Layout580/day3.8 hrs85%$130K/moConsider
Peak Demand720/day3.5 hrs91%$155K/moGrowth scenario

Sensitivity Analysis:

  • Impact of demand variability (+/-20%)
  • Resource availability (equipment downtime)
  • Process time variations
  • Confidence intervals

Bottleneck Analysis:

  • Identified constraints
  • Impact on overall performance
  • Mitigation options

Implementation Plan:

  • Recommended changes
  • Phasing and timeline
  • Resource requirements
  • Risk mitigation

Model Validation:

  • Validation approach
  • Comparison to actual performance
  • Statistical tests
  • Limitations and caveats

Questions to Ask

If you need more context:

  1. What system do you want to model? (warehouse, network, production, transportation)
  2. What decisions will the digital twin support?
  3. What level of detail is needed? (strategic vs. operational)
  4. What data is available? (historical performance, parameters, real-time feeds)
  5. What scenarios do you want to test?
  6. Do you need real-time integration or batch simulation?
  7. What tools/platforms are you using or prefer?
  8. What's the expected timeline and budget for this initiative?

Related Skills

  • supply-chain-automation: For automated control systems
  • optimization-modeling: For optimization within digital twin
  • prescriptive-analytics: For decision recommendations
  • ml-supply-chain: For predictive components
  • supply-chain-analytics: For KPI tracking and dashboards
  • network-design: For network modeling and optimization
  • warehouse-design: For facility layout simulation
  • production-scheduling: For manufacturing simulation
  • scenario-planning: For strategic scenario analysis

Distribution Center Network Design

You are an expert in distribution center network design and multi-echelon supply chain optimization. Your goal is to help design optimal distribution networks that minimize total costs while meeting service requirements, considering flows from plants through DCs to customers.

Initial Assessment

Before designing DC networks, understand:

  1. Network Structure

    • Current network configuration?
    • Single-echelon (DCs → customers only)?
    • Multi-echelon (plants → DCs → customers)?
    • Direct shipments allowed? (plants → customers)
    • Cross-docking operations?
  2. Facility Tiers

    • Manufacturing plants/sources?
    • Regional distribution centers (RDCs)?
    • Local distribution centers (LDCs)?
    • Forward stocking locations (FSLs)?
    • Customer locations?
  3. Product Characteristics

    • Product variety (SKUs)?
    • Product families or categories?
    • Storage requirements (ambient, refrigerated, hazmat)?
    • Value density (value per volume/weight)?
    • Shelf life and perishability?
  4. Flow Patterns

    • Where do products originate? (domestic plants, imports, suppliers)
    • Where is demand? (customers, markets, retail stores)
    • Volume by lane (origin-destination pairs)?
    • Seasonal patterns?
    • Growth projections?
  5. Cost Structure

    • Plant/source costs (production, handling)?
    • DC fixed costs (lease, capital, setup)?
    • DC operating costs (handling, labor, utilities)?
    • Transportation costs (inbound, inter-DC, outbound)?
    • Inventory costs (working inventory, safety stock)?
    • Service penalty costs (late delivery, lost sales)?

Distribution Network Design Framework

Network Configuration Options

1. Direct Shipment (0-Echelon)

Plants/Sources → Customers
  • Pros: No intermediate handling, lowest transit time
  • Cons: High transportation costs for small shipments
  • Best for: High-value, time-sensitive, large orders

2. Single-Echelon (1-Echelon)

Plants/Sources → Distribution Centers → Customers
  • Pros: Consolidation benefits, economies of scale
  • Cons: Additional handling, inventory at DCs
  • Best for: Most B2B and retail distribution

3. Two-Echelon (2-Echelon)

Plants → Regional DCs → Local DCs → Customers
  • Pros: Better market coverage, faster delivery
  • Cons: More complex, higher inventory, more facilities
  • Best for: Large geographic areas, high service requirements

4. Hybrid Network

Plants ─→ Regional DCs ─→ Customers
     └─→ Direct ────────┘
  • Pros: Flexibility, optimize by product/customer
  • Cons: Complex planning and execution
  • Best for: Differentiated service strategies

Key Design Decisions

Strategic (Long-term):

  • Number of echelons
  • Number and location of DCs
  • DC sizes and capacities
  • Technology and automation levels
  • Ownership (own vs. outsource/3PL)

Tactical (Medium-term):

  • Product-DC assignments
  • Customer-DC assignments
  • Inventory positioning
  • Transportation modes
  • Seasonality strategies

Operational (Short-term):

  • Order fulfillment assignments
  • Replenishment decisions
  • Vehicle routing
  • Load consolidation

Mathematical Formulations

Multi-Echelon DC Network Design Model

Sets:

  • P: Plants/sources
  • D: Potential DC locations
  • C: Customers
  • K: Products

Parameters:

  • f_d: Fixed cost to open DC d
  • Q_d: Capacity of DC d
  • c_{pd}: Unit cost from plant p to DC d
  • c_{dc}: Unit cost from DC d to customer c
  • c_{pc}: Unit cost from plant p directly to customer c (if allowed)
  • d_{ck}: Demand of customer c for product k
  • α_k: Unit inventory cost for product k at DC
  • s_{pk}: Supply/production capacity of plant p for product k

Decision Variables:

  • y_d ∈ {0,1}: 1 if DC d is opened
  • x_{pdk}: Flow of product k from plant p to DC d
  • z_{dck}: Flow of product k from DC d to customer c
  • w_{pck}: Flow of product k from plant p directly to customer c (if direct shipping allowed)

Objective Function:

Minimize:
  DC fixed costs:
    Σ_d f_d × y_d

  + Inbound transportation (plant → DC):
    Σ_p Σ_d Σ_k c_{pd} × x_{pdk}

  + Outbound transportation (DC → customer):
    Σ_d Σ_c Σ_k c_{dc} × z_{dck}

  + Direct shipment costs (if allowed):
    Σ_p Σ_c Σ_k c_{pc} × w_{pck}

  + DC inventory costs:
    Σ_d Σ_k α_k × (Σ_c z_{dck})

Constraints:

1. Demand satisfaction:
   Σ_d z_{dck} + Σ_p w_{pck} = d_{ck},  ∀c ∈ C, ∀k ∈ K

2. DC capacity:
   Σ_c Σ_k z_{dck} ≤ Q_d × y_d,  ∀d ∈ D

3. Flow balance at DCs:
   Σ_p x_{pdk} = Σ_c z_{dck},  ∀d ∈ D, ∀k ∈ K

4. Plant capacity:
   Σ_d x_{pdk} + Σ_c w_{pck} ≤ s_{pk},  ∀p ∈ P, ∀k ∈ K

5. Serve only from open DCs:
   z_{dck} ≤ M × y_d,  ∀d ∈ D, ∀c ∈ C, ∀k ∈ K
   where M is a large constant (customer demand sum)

6. Non-negativity and binary:
   y_d ∈ {0,1},  ∀d ∈ D
   x_{pdk}, z_{dck}, w_{pck} ≥ 0

Service-Level Constrained Model

Additional Parameters:

  • T_c: Maximum acceptable delivery time for customer c
  • t_{dc}: Delivery time from DC d to customer c
  • SL: Minimum service level (e.g., 95% of demand met within time)

Service Constraints:

1. Each customer must be within service time of at least one DC:
   Σ_{d: t_{dc} ≤ T_c} y_d ≥ 1,  ∀c ∈ C

2. Or aggregate service level:
   Σ_c Σ_{d: t_{dc} ≤ T_c} z_{dck} ≥ SL × Σ_c d_{ck},  ∀k ∈ K

Solution Methods

1. Multi-Echelon MIP Model

from pulp import *
import numpy as np
import pandas as pd

def solve_dc_network_design(plants, dcs, customers, products,
                           dc_costs, capacities, inbound_costs,
                           outbound_costs, demands,
                           plant_capacities=None, allow_direct=False):
    """
    Solve multi-echelon DC network design problem

    Args:
        plants: list of plant IDs
        dcs: list of potential DC IDs
        customers: list of customer IDs
        products: list of product IDs
        dc_costs: dict {dc_id: fixed_cost}
        capacities: dict {dc_id: capacity}
        inbound_costs: dict {(plant, dc, product): cost}
        outbound_costs: dict {(dc, customer, product): cost}
        demands: dict {(customer, product): demand}
        plant_capacities: optional dict {(plant, product): capacity}
        allow_direct: allow direct plant-to-customer shipments

    Returns:
        optimal network design solution
    """

    # Create problem
    prob = LpProblem("DC_Network_Design", LpMinimize)

    # Decision variables
    # y[d] = 1 if DC d is opened
    y = LpVariable.dicts("DC", dcs, cat='Binary')

    # x[p,d,k] = flow from plant p to DC d for product k
    x = {}
    for p in plants:
        for d in dcs:
            for k in products:
                x[p,d,k] = LpVariable(f"inbound_{p}_{d}_{k}",
                                     lowBound=0, cat='Continuous')

    # z[d,c,k] = flow from DC d to customer c for product k
    z = {}
    for d in dcs:
        for c in customers:
            for k in products:
                z[d,c,k] = LpVariable(f"outbound_{d}_{c}_{k}",
                                     lowBound=0, cat='Continuous')

    # w[p,c,k] = direct flow from plant p to customer c (if allowed)
    w = {}
    if allow_direct:
        for p in plants:
            for c in customers:
                for k in products:
                    w[p,c,k] = LpVariable(f"direct_{p}_{c}_{k}",
                                         lowBound=0, cat='Continuous')

    # Objective: Minimize total cost
    # DC fixed costs
    fixed_cost_expr = lpSum([dc_costs[d] * y[d] for d in dcs])

    # Inbound transportation costs
    inbound_expr = lpSum([
        inbound_costs.get((p,d,k), 0) * x[p,d,k]
        for p in plants for d in dcs for k in products
    ])

    # Outbound transportation costs
    outbound_expr = lpSum([
        outbound_costs.get((d,c,k), 0) * z[d,c,k]
        for d in dcs for c in customers for k in products
    ])

    prob += fixed_cost_expr + inbound_expr + outbound_expr, "Total_Cost"

    # Constraints

    # 1. Demand satisfaction
    for c in customers:
        for k in products:
            if (c, k) in demands:
                if allow_direct:
                    prob += (
                        lpSum([z[d,c,k] for d in dcs]) +
                        lpSum([w[p,c,k] for p in plants]) ==
                        demands[c,k],
                        f"Demand_{c}_{k}"
                    )
                else:
                    prob += (
                        lpSum([z[d,c,k] for d in dcs]) == demands[c,k],
                        f"Demand_{c}_{k}"
                    )

    # 2. DC capacity constraints
    for d in dcs:
        prob += (
            lpSum([z[d,c,k]
                   for c in customers for k in products]) <=
            capacities[d] * y[d],
            f"Capacity_DC_{d}"
        )

    # 3. Flow balance at DCs
    for d in dcs:
        for k in products:
            prob += (
                lpSum([x[p,d,k] for p in plants]) ==
                lpSum([z[d,c,k] for c in customers]),
                f"Flow_Balance_{d}_{k}"
            )

    # 4. Plant capacity constraints (if specified)
    if plant_capacities:
        for p in plants:
            for k in products:
                if (p, k) in plant_capacities:
                    if allow_direct:
                        prob += (
                            lpSum([x[p,d,k] for d in dcs]) +
                            lpSum([w[p,c,k] for c in customers]) <=
                            plant_capacities[p,k],
                            f"Plant_Capacity_{p}_{k}"
                        )
                    else:
                        prob += (
                            lpSum([x[p,d,k] for d in dcs]) <=
                            plant_capacities[p,k],
                            f"Plant_Capacity_{p}_{k}"
                        )

    # 5. Serve only from open DCs (big-M constraint)
    for d in dcs:
        for c in customers:
            for k in products:
                if (c, k) in demands:
                    M = demands[c,k]  # Big-M value
                    prob += (
                        z[d,c,k] <= M * y[d],
                        f"Open_DC_{d}_{c}_{k}"
                    )

    # Solve
    import time
    start_time = time.time()
    prob.solve(PULP_CBC_CMD(msg=1, timeLimit=900))
    solve_time = time.time() - start_time

    # Extract solution
    if LpStatus[prob.status] in ['Optimal', 'Feasible']:
        open_dcs = [d for d in dcs if y[d].varValue > 0.5]

        # Extract flows
        inbound_flows = {}
        for p in plants:
            for d in dcs:
                for k in products:
                    if x[p,d,k].varValue > 0.01:
                        inbound_flows[p,d,k] = x[p,d,k].varValue

        outbound_flows = {}
        for d in dcs:
            for c in customers:
                for k in products:
                    if z[d,c,k].varValue > 0.01:
                        outbound_flows[d,c,k] = z[d,c,k].varValue

        # Calculate DC utilization
        dc_utilization = {}
        for d in open_dcs:
            total_flow = sum(z[d,c,k].varValue
                           for c in customers for k in products)
            dc_utilization[d] = (total_flow / capacities[d]) * 100

        # Cost breakdown
        total_fixed = sum(dc_costs[d] for d in open_dcs)
        total_inbound = sum(
            inbound_costs.get((p,d,k), 0) * x[p,d,k].varValue
            for p in plants for d in dcs for k in products
        )
        total_outbound = sum(
            outbound_costs.get((d,c,k), 0) * z[d,c,k].varValue
            for d in dcs for c in customers for k in products
        )

        return {
            'status': LpStatus[prob.status],
            'total_cost': value(prob.objective),
            'fixed_cost': total_fixed,
            'inbound_cost': total_inbound,
            'outbound_cost': total_outbound,
            'open_dcs': open_dcs,
            'num_dcs': len(open_dcs),
            'inbound_flows': inbound_flows,
            'outbound_flows': outbound_flows,
            'dc_utilization': dc_utilization,
            'solve_time': solve_time
        }
    else:
        return {
            'status': LpStatus[prob.status],
            'solve_time': solve_time
        }


# Example usage
if __name__ == "__main__":
    # Network data
    plants = ['P1', 'P2', 'P3']
    dcs = ['DC1', 'DC2', 'DC3', 'DC4', 'DC5']
    customers = [f'C{i}' for i in range(1, 21)]  # 20 customers
    products = ['ProductA', 'ProductB', 'ProductC']

    # DC costs and capacities
    dc_costs = {
        'DC1': 500000, 'DC2': 450000, 'DC3': 480000,
        'DC4': 520000, 'DC5': 470000
    }
    capacities = {
        'DC1': 10000, 'DC2': 8000, 'DC3': 9000,
        'DC4': 11000, 'DC5': 8500
    }

    # Generate random costs (simplified)
    np.random.seed(42)

    inbound_costs = {}
    for p in plants:
        for d in dcs:
            for k in products:
                inbound_costs[p,d,k] = np.random.uniform(10, 50)

    outbound_costs = {}
    for d in dcs:
        for c in customers:
            for k in products:
                outbound_costs[d,c,k] = np.random.uniform(5, 30)

    # Customer demands
    demands = {}
    for c in customers:
        for k in products:
            demands[c,k] = np.random.uniform(50, 200)

    # Plant capacities
    plant_capacities = {}
    for p in plants:
        for k in products:
            plant_capacities[p,k] = 5000

    print("="*70)
    print("DISTRIBUTION CENTER NETWORK DESIGN")
    print("="*70)
    print(f"Plants: {len(plants)}")
    print(f"Potential DCs: {len(dcs)}")
    print(f"Customers: {len(customers)}")
    print(f"Products: {len(products)}")
    print(f"Total demand: {sum(demands.values()):,.0f} units")

    # Solve
    result = solve_dc_network_design(
        plants, dcs, customers, products,
        dc_costs, capacities,
        inbound_costs, outbound_costs, demands,
        plant_capacities
    )

    print(f"\n{'='*70}")
    print(f"OPTIMAL SOLUTION")
    print(f"{'='*70}")
    print(f"Status: {result['status']}")
    print(f"Total Cost: ${result['total_cost']:,.2f}")
    print(f"  Fixed Costs: ${result['fixed_cost']:,.2f} "
          f"({result['fixed_cost']/result['total_cost']*100:.1f}%)")
    print(f"  Inbound Transport: ${result['inbound_cost']:,.2f} "
          f"({result['inbound_cost']/result['total_cost']*100:.1f}%)")
    print(f"  Outbound Transport: ${result['outbound_cost']:,.2f} "
          f"({result['outbound_cost']/result['total_cost']*100:.1f}%)")

    print(f"\nOpen DCs: {result['num_dcs']}")
    for dc in result['open_dcs']:
        print(f"  {dc}: Utilization={result['dc_utilization'][dc]:.1f}%, "
              f"Capacity={capacities[dc]:,.0f}")

    print(f"\nSolve Time: {result['solve_time']:.2f} seconds")

    print(f"\nSample Flows (first 10):")
    count = 0
    for (d, c, k), flow in result['outbound_flows'].items():
        if count >= 10:
            break
        print(f"  {d} → {c} ({k}): {flow:.2f} units")
        count += 1

2. Network Flow Optimization

def optimize_network_flows(open_dcs, plants, customers, products,
                          inbound_costs, outbound_costs, demands,
                          dc_capacities, plant_capacities):
    """
    Optimize flows through given DC network

    Given fixed DC locations, optimize product flows

    Args:
        open_dcs: list of open DC locations
        plants, customers, products: network nodes
        costs, demands, capacities: network parameters

    Returns:
        optimal flow pattern
    """

    prob = LpProblem("Network_Flow", LpMinimize)

    # Variables: flows only (DCs already decided)
    x = {}  # inbound flows
    for p in plants:
        for d in open_dcs:
            for k in products:
                x[p,d,k] = LpVariable(f"inbound_{p}_{d}_{k}",
                                     lowBound=0, cat='Continuous')

    z = {}  # outbound flows
    for d in open_dcs:
        for c in customers:
            for k in products:
                z[d,c,k] = LpVariable(f"outbound_{d}_{c}_{k}",
                                     lowBound=0, cat='Continuous')

    # Objective: Minimize transportation costs
    prob += (
        lpSum([inbound_costs.get((p,d,k), 0) * x[p,d,k]
               for p in plants for d in open_dcs for k in products]) +
        lpSum([outbound_costs.get((d,c,k), 0) * z[d,c,k]
               for d in open_dcs for c in customers for k in products]),
        "Total_Transport_Cost"
    )

    # Constraints

    # Demand satisfaction
    for c in customers:
        for k in products:
            if (c, k) in demands:
                prob += (
                    lpSum([z[d,c,k] for d in open_dcs]) == demands[c,k],
                    f"Demand_{c}_{k}"
                )

    # DC capacity
    for d in open_dcs:
        prob += (
            lpSum([z[d,c,k] for c in customers for k in products]) <=
            dc_capacities[d],
            f"DC_Capacity_{d}"
        )

    # Flow balance
    for d in open_dcs:
        for k in products:
            prob += (
                lpSum([x[p,d,k] for p in plants]) ==
                lpSum([z[d,c,k] for c in customers]),
                f"Balance_{d}_{k}"
            )

    # Plant capacity
    for p in plants:
        for k in products:
            if (p, k) in plant_capacities:
                prob += (
                    lpSum([x[p,d,k] for d in open_dcs]) <=
                    plant_capacities[p,k],
                    f"Plant_{p}_{k}"
                )

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    if LpStatus[prob.status] in ['Optimal', 'Feasible']:
        inbound_flows = {
            (p,d,k): x[p,d,k].varValue
            for p in plants for d in open_dcs for k in products
            if x[p,d,k].varValue > 0.01
        }

        outbound_flows = {
            (d,c,k): z[d,c,k].varValue
            for d in open_dcs for c in customers for k in products
            if z[d,c,k].varValue > 0.01
        }

        return {
            'status': LpStatus[prob.status],
            'total_cost': value(prob.objective),
            'inbound_flows': inbound_flows,
            'outbound_flows': outbound_flows
        }

    return {'status': LpStatus[prob.status]}

Heuristic Approaches

1. Clustering-Based DC Selection

from sklearn.cluster import KMeans

def clustering_based_dc_selection(customer_locations, customer_demands,
                                  potential_dc_locations, num_dcs):
    """
    Use demand-weighted clustering to select DC locations

    Args:
        customer_locations: array of customer coordinates
        customer_demands: customer demand weights
        potential_dc_locations: candidate DC coordinates
        num_dcs: number of DCs to select

    Returns:
        selected DC indices
    """

    # Cluster customers into num_dcs groups
    weights = (customer_demands / customer_demands.min()).astype(int)
    weighted_locations = []

    for i, loc in enumerate(customer_locations):
        weighted_locations.extend([loc] * weights[i])

    weighted_locations = np.array(weighted_locations)

    # K-means clustering
    kmeans = KMeans(n_clusters=num_dcs, random_state=42)
    kmeans.fit(weighted_locations)

    cluster_centers = kmeans.cluster_centers_

    # Match cluster centers to nearest potential DC locations
    selected_dcs = []
    for center in cluster_centers:
        # Find nearest potential DC to cluster center
        distances = [np.linalg.norm(center - dc_loc)
                    for dc_loc in potential_dc_locations]
        nearest_dc = np.argmin(distances)

        if nearest_dc not in selected_dcs:
            selected_dcs.append(nearest_dc)

    # If we have fewer DCs than requested (due to duplicates),
    # add next best options
    while len(selected_dcs) < num_dcs:
        best_dc = None
        best_total_dist = float('inf')

        for dc_idx in range(len(potential_dc_locations)):
            if dc_idx in selected_dcs:
                continue

            # Calculate total distance from this DC to all customers
            total_dist = sum(
                customer_demands[i] *
                np.linalg.norm(potential_dc_locations[dc_idx] - customer_locations[i])
                for i in range(len(customer_locations))
            )

            if total_dist < best_total_dist:
                best_total_dist = total_dist
                best_dc = dc_idx

        if best_dc is not None:
            selected_dcs.append(best_dc)
        else:
            break

    return selected_dcs

2. Iterative Location-Allocation

def iterative_location_allocation(potential_dcs, customers, demands,
                                 transport_costs, dc_costs, capacities,
                                 num_dcs, max_iterations=50):
    """
    Iterative heuristic: alternate between location and allocation

    Args:
        potential_dcs: list of potential DC locations
        customers: list of customers
        demands: customer demands
        transport_costs: outbound transport costs
        dc_costs: DC fixed costs
        capacities: DC capacities
        num_dcs: number of DCs to open
        max_iterations: maximum iterations

    Returns:
        heuristic solution
    """

    # Initialize: select random DCs
    current_dcs = random.sample(potential_dcs, num_dcs)

    def allocate_customers(dcs):
        """Allocate each customer to nearest DC with capacity"""
        assignments = {}
        remaining_capacity = {d: capacities[d] for d in dcs}

        # Sort customers by total demand (largest first)
        sorted_customers = sorted(customers,
                                key=lambda c: demands[c],
                                reverse=True)

        for c in sorted_customers:
            # Find nearest DC with capacity
            best_dc = None
            min_cost = float('inf')

            for d in dcs:
                if remaining_capacity[d] >= demands[c]:
                    cost = transport_costs.get((d, c), float('inf'))
                    if cost < min_cost:
                        min_cost = cost
                        best_dc = d

            if best_dc:
                assignments[c] = best_dc
                remaining_capacity[best_dc] -= demands[c]
            else:
                # No capacity, assign to nearest anyway (infeasible)
                best_dc = min(dcs, key=lambda d: transport_costs.get((d,c), float('inf')))
                assignments[c] = best_dc

        return assignments

    def calculate_cost(dcs, assignments):
        """Calculate total cost"""
        fixed = sum(dc_costs[d] for d in dcs)
        transport = sum(
            transport_costs.get((assignments[c], c), 0) * demands[c]
            for c in customers if c in assignments
        )
        return fixed + transport

    best_dcs = current_dcs.copy()
    best_assignments = allocate_customers(current_dcs)
    best_cost = calculate_cost(current_dcs, best_assignments)

    for iteration in range(max_iterations):
        # Allocate customers to current DCs
        current_assignments = allocate_customers(current_dcs)

        # Relocate DCs: try swapping each open DC with each closed DC
        improved = False

        for open_dc in current_dcs:
            for closed_dc in potential_dcs:
                if closed_dc in current_dcs:
                    continue

                # Test swap
                test_dcs = [d if d != open_dc else closed_dc
                           for d in current_dcs]

                test_assignments = allocate_customers(test_dcs)
                test_cost = calculate_cost(test_dcs, test_assignments)

                if test_cost < best_cost - 1e-6:
                    best_cost = test_cost
                    best_dcs = test_dcs.copy()
                    best_assignments = test_assignments
                    current_dcs = test_dcs
                    improved = True
                    break

            if improved:
                break

        if not improved:
            break

    return {
        'open_dcs': best_dcs,
        'assignments': best_assignments,
        'total_cost': best_cost,
        'method': 'Iterative Location-Allocation'
    }

Complete DC Network Solver

class DCNetworkSolver:
    """
    Comprehensive Distribution Center Network Design Solver
    """

    def __init__(self):
        self.plants = None
        self.dcs = None
        self.customers = None
        self.products = None
        self.loaded = False

    def load_problem(self, network_data):
        """
        Load network design problem

        Args:
            network_data: dict with all problem data
                - plants, dcs, customers, products
                - costs, capacities, demands
        """
        self.plants = network_data['plants']
        self.dcs = network_data['dcs']
        self.customers = network_data['customers']
        self.products = network_data.get('products', ['Product1'])

        self.dc_costs = network_data['dc_costs']
        self.capacities = network_data['capacities']
        self.inbound_costs = network_data['inbound_costs']
        self.outbound_costs = network_data['outbound_costs']
        self.demands = network_data['demands']
        self.plant_capacities = network_data.get('plant_capacities')

        self.loaded = True

        print(f"Loaded DC network problem:")
        print(f"  Plants: {len(self.plants)}")
        print(f"  Potential DCs: {len(self.dcs)}")
        print(f"  Customers: {len(self.customers)}")
        print(f"  Products: {len(self.products)}")
        print(f"  Total demand: {sum(self.demands.values()):,.0f}")

    def solve_exact(self, allow_direct=False, time_limit=900):
        """Solve with exact MIP"""
        if not self.loaded:
            raise ValueError("Problem not loaded")

        print("\nSolving with exact MIP...")
        return solve_dc_network_design(
            self.plants, self.dcs, self.customers, self.products,
            self.dc_costs, self.capacities,
            self.inbound_costs, self.outbound_costs,
            self.demands, self.plant_capacities,
            allow_direct
        )

    def solve_heuristic(self, method='clustering', num_dcs=None):
        """Solve with heuristic method"""
        print(f"\nSolving with {method} heuristic...")

        # Methods require different inputs
        # Implementation would depend on available data
        raise NotImplementedError("Heuristic methods need coordinates")

    def analyze_scenarios(self, dc_counts):
        """
        Analyze different numbers of DCs

        Args:
            dc_counts: list of DC counts to test

        Returns:
            comparison of scenarios
        """
        import pandas as pd

        results = []

        for num_dcs in dc_counts:
            print(f"\nAnalyzing scenario with {num_dcs} DCs...")

            # This would require solving with a constraint on number of DCs
            # or using heuristics

            # Placeholder
            results.append({
                'Num_DCs': num_dcs,
                'Total_Cost': None,
                'Fixed_Cost': None,
                'Transport_Cost': None
            })

        return pd.DataFrame(results)

    def visualize_network(self, solution, coordinates=None):
        """Visualize DC network"""
        import matplotlib.pyplot as plt

        if coordinates is None:
            print("Coordinates required for visualization")
            return

        # Visualization code
        # Similar to previous examples
        pass


# Example usage
if __name__ == "__main__":
    # Create sample network data
    network_data = {
        'plants': ['P1', 'P2'],
        'dcs': ['DC1', 'DC2', 'DC3', 'DC4'],
        'customers': [f'C{i}' for i in range(1, 16)],
        'products': ['ProductA', 'ProductB'],
        'dc_costs': {
            'DC1': 400000, 'DC2': 380000,
            'DC3': 420000, 'DC4': 390000
        },
        'capacities': {
            'DC1': 8000, 'DC2': 7000,
            'DC3': 9000, 'DC4': 7500
        },
        'inbound_costs': {},
        'outbound_costs': {},
        'demands': {},
        'plant_capacities': {}
    }

    # Generate costs and demands
    np.random.seed(42)

    for p in network_data['plants']:
        for d in network_data['dcs']:
            for k in network_data['products']:
                network_data['inbound_costs'][p,d,k] = np.random.uniform(15, 40)

    for d in network_data['dcs']:
        for c in network_data['customers']:
            for k in network_data['products']:
                network_data['outbound_costs'][d,c,k] = np.random.uniform(8, 25)

    for c in network_data['customers']:
        for k in network_data['products']:
            network_data['demands'][c,k] = np.random.uniform(30, 150)

    for p in network_data['plants']:
        for k in network_data['products']:
            network_data['plant_capacities'][p,k] = 3000

    # Solve
    solver = DCNetworkSolver()
    solver.load_problem(network_data)

    solution = solver.solve_exact()

    print(f"\n{'='*70}")
    print(f"OPTIMAL NETWORK CONFIGURATION")
    print(f"{'='*70}")
    print(f"Total Cost: ${solution['total_cost']:,.2f}")
    print(f"DCs Opened: {solution['num_dcs']}")
    print(f"DC IDs: {solution['open_dcs']}")

Tools & Libraries

Python Libraries

  • PuLP/Pyomo: MIP modeling
  • OR-Tools: Network optimization
  • NetworkX: Network analysis
  • scikit-learn: Clustering
  • pandas/numpy: Data handling

Commercial Software

  • Llamasoft: Network design platform
  • SAP IBP: Integrated planning
  • Blue Yonder: Supply chain suite
  • AIMMS: Optimization modeling

Common Challenges & Solutions

Challenge: Large-Scale Networks

Solution: Decomposition, aggregation, heuristics

Challenge: Multi-Product Complexity

Solution: Product aggregation, ABC analysis

Challenge: Dynamic Demand

Solution: Stochastic models, robust optimization

Challenge: Service Requirements

Solution: Service-level constraints, penalty costs


Output Format

Network Configuration:

  • Total Cost: $X
  • Open DCs: Y locations
  • Capacity utilization: Z%
  • Service level: W%

Questions to Ask

  1. Network scope? (regional, national, global)
  2. Current vs. greenfield design?
  3. Number of plants/sources?
  4. Product variety and characteristics?
  5. Demand locations and volumes?
  6. Service requirements?
  7. Cost structure?
  8. Planning horizon?

Related Skills

  • facility-location-problem: General location theory
  • warehouse-location-optimization: Warehouse specifics
  • hub-location-problem: Hub networks
  • network-flow-optimization: Flow optimization
  • inventory-routing-problem: Integrated inventory-routing
  • multi-echelon-inventory: Inventory positioning

Dock Door Assignment

You are an expert in dock door assignment optimization and yard management. Your goal is to help optimize the assignment of inbound/outbound shipments to dock doors to minimize congestion, reduce dwell time, maximize throughput, and improve overall warehouse efficiency.

Initial Assessment

Before optimizing dock door assignments, understand:

  1. Facility Layout

    • Number of dock doors (inbound, outbound, shared)?
    • Door capabilities (height, width, equipment)?
    • Distance from doors to storage zones?
    • Staging area capacity near each door?
    • Cross-dock lanes vs. put-away lanes?
  2. Operations Profile

    • Daily truck arrivals (inbound/outbound)?
    • Peak vs. off-peak times?
    • Average unload/load time per truck?
    • Mix of loads (full truckload, LTL, parcel)?
    • Appointment system in place?
  3. Product Characteristics

    • Product types and storage zones?
    • Temperature requirements?
    • Hazmat or special handling?
    • High-velocity vs. slow-moving items?
    • Cross-dock percentage?
  4. Current Challenges

    • Door utilization rates?
    • Truck waiting times?
    • Congestion hot spots?
    • Detention costs?
    • Labor allocation issues?

Dock Door Assignment Framework

Assignment Objectives

Primary Goals:

  1. Minimize Travel Distance: Assign doors closest to destination storage zone
  2. Maximize Throughput: Optimize door utilization and avoid congestion
  3. Balance Workload: Even distribution across dock workers
  4. Minimize Detention: Reduce truck waiting and dwell time
  5. Support Cross-Docking: Align inbound/outbound for direct transfer

Key Metrics:

  • Door utilization rate (target: 70-85%)
  • Average truck dwell time (target: <90 minutes)
  • Distance traveled (forklift feet/day)
  • Detention costs ($ per day)
  • Dock-to-stock time

Assignment Strategies

1. Zone-Based Assignment

  • Group doors by destination zone
  • Inbound Door 1-5 → Zone A
  • Inbound Door 6-10 → Zone B
  • Minimizes average travel distance

2. Product-Based Assignment

  • Hazmat doors (isolated, special equipment)
  • Refrigerated doors (near cold storage)
  • High-velocity doors (near forward pick)
  • Bulk doors (larger staging area)

3. Time-Slotted Assignment

  • Appointments in 30-60 minute windows
  • Prevent arrival conflicts
  • Smooth labor demand

4. Cross-Dock Pairing

  • Pair inbound/outbound doors
  • Direct transfer lanes
  • Minimize re-handling

Mathematical Formulation

Assignment Problem Formulation

Decision Variables:

  • x[i,j,t] = 1 if truck i assigned to door j at time t, 0 otherwise

Parameters:

  • d[j,z] = distance from door j to storage zone z
  • z[i] = destination zone for truck i
  • p[i] = processing time for truck i
  • a[i] = arrival time of truck i
  • c[j] = capacity (trucks/day) of door j
  • cap[j] = staging area capacity at door j

Objective Function:

Minimize:
  α × Σ Σ Σ (d[j,z[i]] × x[i,j,t])  # Travel distance
  + β × Σ Σ Σ (max(0, t - a[i]) × x[i,j,t])  # Waiting time
  + γ × Σ max_truck_overlap[j]  # Congestion penalty

where:
  α, β, γ = weights for different objectives

Constraints:

# 1. Each truck assigned to exactly one door at one time
for i in trucks:
    Σ Σ x[i,j,t] = 1  for all j, t

# 2. Door capacity (trucks per time slot)
for j in doors:
    for t in time_slots:
        Σ x[i,j,t] ≤ door_capacity[j]  for all i

# 3. No overlap (truck occupies door for processing time)
for j in doors:
    for t in time_slots:
        Σ x[i,j,t'] ≤ 1  for all i, where t' in [t, t+p[i]]

# 4. Truck can't be assigned before arrival
for i in trucks:
    for t < a[i]:
        Σ x[i,j,t] = 0  for all j

# 5. Staging area capacity
for j in doors:
    Σ (volume[i] × x[i,j,t]) ≤ staging_capacity[j]  for all i, t

Assignment Algorithms

Greedy Assignment (Simple)

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

def greedy_dock_assignment(trucks, doors, distances, processing_times):
    """
    Greedy heuristic for dock door assignment

    Assign each truck to the nearest available door

    Parameters:
    -----------
    trucks : list of dict
        [{truck_id, arrival_time, destination_zone, volume}, ...]
    doors : list of dict
        [{door_id, capacity, zone_affinity}, ...]
    distances : dict
        {(door_id, zone): distance}
    processing_times : dict
        {truck_id: duration_minutes}

    Returns:
    --------
    Assignment schedule
    """

    # Sort trucks by arrival time
    trucks_sorted = sorted(trucks, key=lambda x: x['arrival_time'])

    # Track door availability (door_id -> next_available_time)
    door_availability = {door['door_id']: datetime.min for door in doors}

    assignments = []

    for truck in trucks_sorted:
        truck_id = truck['truck_id']
        arrival = truck['arrival_time']
        dest_zone = truck['destination_zone']
        process_time = processing_times.get(truck_id, 60)  # default 60 min

        # Find best door
        best_door = None
        best_score = float('inf')

        for door in doors:
            door_id = door['door_id']
            available_time = door_availability[door_id]

            # Can't assign before door is available and truck arrives
            start_time = max(arrival, available_time)

            # Calculate score: distance + waiting time
            distance = distances.get((door_id, dest_zone), 1000)
            waiting_time = (start_time - arrival).total_seconds() / 60

            score = distance * 1.0 + waiting_time * 0.5

            if score < best_score:
                best_score = score
                best_door = door_id
                best_start = start_time

        # Assign truck to best door
        end_time = best_start + timedelta(minutes=process_time)
        door_availability[best_door] = end_time

        assignments.append({
            'truck_id': truck_id,
            'door_id': best_door,
            'scheduled_start': best_start,
            'scheduled_end': end_time,
            'arrival_time': arrival,
            'wait_time_min': (best_start - arrival).total_seconds() / 60,
            'destination_zone': dest_zone
        })

    return pd.DataFrame(assignments)


# Example usage
trucks = [
    {'truck_id': 'T001', 'arrival_time': datetime(2024, 1, 1, 8, 0),
     'destination_zone': 'A', 'volume': 1000},
    {'truck_id': 'T002', 'arrival_time': datetime(2024, 1, 1, 8, 15),
     'destination_zone': 'B', 'volume': 800},
    {'truck_id': 'T003', 'arrival_time': datetime(2024, 1, 1, 8, 30),
     'destination_zone': 'A', 'volume': 1200},
    {'truck_id': 'T004', 'arrival_time': datetime(2024, 1, 1, 9, 0),
     'destination_zone': 'C', 'volume': 900},
]

doors = [
    {'door_id': 'D1', 'capacity': 3, 'zone_affinity': 'A'},
    {'door_id': 'D2', 'capacity': 3, 'zone_affinity': 'B'},
    {'door_id': 'D3', 'capacity': 3, 'zone_affinity': 'C'},
]

distances = {
    ('D1', 'A'): 50, ('D1', 'B'): 150, ('D1', 'C'): 200,
    ('D2', 'A'): 150, ('D2', 'B'): 50, ('D2', 'C'): 180,
    ('D3', 'A'): 200, ('D3', 'B'): 180, ('D3', 'C'): 50,
}

processing_times = {
    'T001': 45, 'T002': 60, 'T003': 50, 'T004': 55
}

schedule = greedy_dock_assignment(trucks, doors, distances, processing_times)
print("Dock Assignment Schedule:")
print(schedule[['truck_id', 'door_id', 'scheduled_start', 'wait_time_min']])

Hungarian Algorithm for Optimal Assignment

from scipy.optimize import linear_sum_assignment
import numpy as np

def hungarian_dock_assignment(trucks, doors, cost_matrix):
    """
    Optimal one-to-one assignment using Hungarian algorithm

    Use when number of trucks = number of available door slots

    Parameters:
    -----------
    trucks : list
        Truck identifiers
    doors : list
        Door identifiers
    cost_matrix : 2D numpy array
        cost[i,j] = cost of assigning truck i to door j

    Returns:
    --------
    Optimal assignments
    """

    # Solve assignment problem
    row_ind, col_ind = linear_sum_assignment(cost_matrix)

    assignments = []
    total_cost = 0

    for i, j in zip(row_ind, col_ind):
        assignments.append({
            'truck_id': trucks[i],
            'door_id': doors[j],
            'cost': cost_matrix[i, j]
        })
        total_cost += cost_matrix[i, j]

    return {
        'assignments': assignments,
        'total_cost': total_cost
    }


# Example
trucks = ['T1', 'T2', 'T3', 'T4']
doors = ['D1', 'D2', 'D3', 'D4']

# Cost matrix: distance + penalty
cost_matrix = np.array([
    [50, 150, 200, 180],  # T1 costs to each door
    [150, 50, 180, 160],  # T2
    [50, 140, 210, 190],  # T3
    [200, 180, 50, 70],   # T4
])

result = hungarian_dock_assignment(trucks, doors, cost_matrix)
print("Optimal Assignment (Hungarian):")
for assignment in result['assignments']:
    print(f"  {assignment['truck_id']} → {assignment['door_id']} "
          f"(cost: {assignment['cost']})")
print(f"Total Cost: {result['total_cost']}")

Mixed-Integer Programming Model

from pulp import *
import pandas as pd

def optimize_dock_assignment(trucks, doors, time_slots, distances,
                             processing_times, arrivals):
    """
    Comprehensive dock assignment using MIP

    Parameters:
    -----------
    trucks : list
        Truck identifiers
    doors : list
        Door identifiers
    time_slots : list
        Time slot identifiers (e.g., [0, 1, 2, ...])
    distances : dict
        {(truck, door): distance_to_zone}
    processing_times : dict
        {truck: slots_required}
    arrivals : dict
        {truck: earliest_slot}

    Returns:
    --------
    Optimal assignment with timing
    """

    prob = LpProblem("Dock_Assignment", LpMinimize)

    # Decision variables
    # x[i,j,t] = 1 if truck i assigned to door j starting at time t
    x = LpVariable.dicts("assign",
                        [(i, j, t) for i in trucks
                                   for j in doors
                                   for t in time_slots],
                        cat='Binary')

    # Waiting time variables
    wait = LpVariable.dict("wait",
                          trucks,
                          lowBound=0,
                          cat='Continuous')

    # Objective: minimize weighted sum of distance and waiting
    alpha = 1.0  # distance weight
    beta = 0.5   # waiting time weight

    prob += (
        alpha * lpSum([
            distances.get((i, j), 1000) * x[i, j, t]
            for i in trucks for j in doors for t in time_slots
        ]) +
        beta * lpSum([wait[i] for i in trucks])
    ), "Total_Cost"

    # Constraints

    # 1. Each truck assigned to exactly one door-time combination
    for i in trucks:
        prob += lpSum([
            x[i, j, t] for j in doors for t in time_slots
        ]) == 1, f"Truck_{i}_Assignment"

    # 2. Door capacity: no overlapping assignments
    for j in doors:
        for t in time_slots:
            # Count trucks using this door at this time
            prob += lpSum([
                x[i, j, t_start]
                for i in trucks
                for t_start in range(max(0, t - processing_times.get(i, 1) + 1), t + 1)
                if t_start in time_slots
            ]) <= 1, f"Door_{j}_Time_{t}_Capacity"

    # 3. Truck can't be assigned before arrival
    for i in trucks:
        arrival_slot = arrivals.get(i, 0)
        for t in time_slots:
            if t < arrival_slot:
                for j in doors:
                    prob += x[i, j, t] == 0, f"Truck_{i}_Arrival_Time_{t}"

    # 4. Calculate waiting time
    for i in trucks:
        arrival_slot = arrivals.get(i, 0)
        prob += wait[i] >= lpSum([
            (t - arrival_slot) * x[i, j, t]
            for j in doors for t in time_slots
        ]), f"Wait_{i}"

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract solution
    assignments = []
    for i in trucks:
        for j in doors:
            for t in time_slots:
                if x[i, j, t].varValue > 0.5:
                    assignments.append({
                        'truck_id': i,
                        'door_id': j,
                        'time_slot': t,
                        'wait_slots': wait[i].varValue if wait[i].varValue else 0
                    })

    return {
        'status': LpStatus[prob.status],
        'objective_value': value(prob.objective),
        'assignments': pd.DataFrame(assignments)
    }


# Example
trucks = ['T1', 'T2', 'T3', 'T4', 'T5']
doors = ['D1', 'D2', 'D3']
time_slots = list(range(0, 20))  # 20 time slots (e.g., 30-min each)

# Distance from each truck's destination zone to each door
distances = {
    ('T1', 'D1'): 50, ('T1', 'D2'): 150, ('T1', 'D3'): 200,
    ('T2', 'D1'): 150, ('T2', 'D2'): 50, ('T2', 'D3'): 180,
    ('T3', 'D1'): 50, ('T3', 'D2'): 140, ('T3', 'D3'): 210,
    ('T4', 'D1'): 200, ('T4', 'D2'): 180, ('T4', 'D3'): 50,
    ('T5', 'D1'): 100, ('T5', 'D2'): 100, ('T5', 'D3'): 100,
}

# Processing time in time slots (e.g., 2 slots = 1 hour)
processing_times = {'T1': 2, 'T2': 3, 'T3': 2, 'T4': 3, 'T5': 2}

# Arrival times (time slot)
arrivals = {'T1': 0, 'T2': 2, 'T3': 3, 'T4': 5, 'T5': 6}

result = optimize_dock_assignment(
    trucks, doors, time_slots, distances, processing_times, arrivals
)

print(f"Optimization Status: {result['status']}")
print(f"Objective Value: {result['objective_value']:.2f}")
print("\nAssignments:")
print(result['assignments'])

Advanced Techniques

Cross-Dock Door Pairing

def optimize_crossdock_pairing(inbound_trucks, outbound_trucks,
                               crossdock_items, doors, distances):
    """
    Optimize door assignment for cross-docking operations

    Match inbound and outbound doors to minimize transfer distance

    Parameters:
    -----------
    inbound_trucks : list of dict
        [{truck_id, arrival_time, items: [sku_list]}, ...]
    outbound_trucks : list of dict
        [{truck_id, departure_time, items: [sku_list]}, ...]
    crossdock_items : dict
        {inbound_truck: {outbound_truck: [items_to_transfer]}}
    doors : dict
        {'inbound': [door_list], 'outbound': [door_list]}
    distances : dict
        {(inbound_door, outbound_door): transfer_distance}

    Returns:
    --------
    Paired door assignments
    """

    prob = LpProblem("CrossDock_Pairing", LpMinimize)

    inbound_ids = [t['truck_id'] for t in inbound_trucks]
    outbound_ids = [t['truck_id'] for t in outbound_trucks]
    inbound_doors = doors['inbound']
    outbound_doors = doors['outbound']

    # Decision variables
    # y_in[i,d] = 1 if inbound truck i assigned to door d
    y_in = LpVariable.dicts("inbound",
                           [(i, d) for i in inbound_ids for d in inbound_doors],
                           cat='Binary')

    # y_out[i,d] = 1 if outbound truck i assigned to door d
    y_out = LpVariable.dicts("outbound",
                            [(i, d) for i in outbound_ids for d in outbound_doors],
                            cat='Binary')

    # Flow variables: f[in_door, out_door] = volume transferred
    f = LpVariable.dicts("flow",
                        [(d1, d2) for d1 in inbound_doors for d2 in outbound_doors],
                        lowBound=0,
                        cat='Continuous')

    # Objective: minimize transfer distance
    prob += lpSum([
        distances.get((d1, d2), 100) * f[d1, d2]
        for d1 in inbound_doors for d2 in outbound_doors
    ]), "Transfer_Distance"

    # Constraints

    # Each truck assigned to one door
    for i in inbound_ids:
        prob += lpSum([y_in[i, d] for d in inbound_doors]) == 1

    for i in outbound_ids:
        prob += lpSum([y_out[i, d] for d in outbound_doors]) == 1

    # Link flow to door assignments
    # (Simplified: would need actual crossdock volumes)
    for d1 in inbound_doors:
        for d2 in outbound_doors:
            # Flow limited by door assignments
            prob += f[d1, d2] <= 1000, f"Flow_{d1}_{d2}"

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract solution
    inbound_assignments = {}
    outbound_assignments = {}

    for i in inbound_ids:
        for d in inbound_doors:
            if y_in[i, d].varValue > 0.5:
                inbound_assignments[i] = d

    for i in outbound_ids:
        for d in outbound_doors:
            if y_out[i, d].varValue > 0.5:
                outbound_assignments[i] = d

    flows = {}
    for d1 in inbound_doors:
        for d2 in outbound_doors:
            if f[d1, d2].varValue > 0.01:
                flows[(d1, d2)] = f[d1, d2].varValue

    return {
        'status': LpStatus[prob.status],
        'inbound_assignments': inbound_assignments,
        'outbound_assignments': outbound_assignments,
        'flows': flows,
        'total_distance': value(prob.objective)
    }

Appointment Scheduling System

from datetime import datetime, timedelta

class DockAppointmentScheduler:
    """
    Manage dock appointment scheduling with time windows
    """

    def __init__(self, doors, operating_hours, slot_duration=30):
        """
        Initialize scheduler

        Parameters:
        -----------
        doors : list
            Available door IDs
        operating_hours : dict
            {'start': time, 'end': time}
        slot_duration : int
            Minutes per appointment slot
        """
        self.doors = doors
        self.operating_hours = operating_hours
        self.slot_duration = slot_duration
        self.appointments = {}  # {(door, datetime): truck_id}
        self.truck_schedules = {}  # {truck_id: (door, start_time, end_time)}

    def generate_time_slots(self, date):
        """Generate available time slots for a date"""
        slots = []
        current = datetime.combine(date, self.operating_hours['start'])
        end = datetime.combine(date, self.operating_hours['end'])

        while current < end:
            slots.append(current)
            current += timedelta(minutes=self.slot_duration)

        return slots

    def find_available_slots(self, date, duration_minutes, preferred_doors=None):
        """
        Find available appointment slots

        Parameters:
        -----------
        date : datetime.date
            Target date
        duration_minutes : int
            Required duration
        preferred_doors : list, optional
            Preferred door IDs

        Returns:
        --------
        List of available (door, start_time) tuples
        """
        time_slots = self.generate_time_slots(date)
        slots_needed = int(np.ceil(duration_minutes / self.slot_duration))

        available = []
        doors_to_check = preferred_doors if preferred_doors else self.doors

        for door in doors_to_check:
            for i, start_time in enumerate(time_slots[:-slots_needed + 1]):
                # Check if all required slots are free
                all_free = True
                for offset in range(slots_needed):
                    slot_time = time_slots[i + offset]
                    if (door, slot_time) in self.appointments:
                        all_free = False
                        break

                if all_free:
                    end_time = time_slots[i + slots_needed - 1] + \
                              timedelta(minutes=self.slot_duration)
                    available.append({
                        'door': door,
                        'start_time': start_time,
                        'end_time': end_time,
                        'duration': duration_minutes
                    })

        return available

    def book_appointment(self, truck_id, door, start_time, duration_minutes):
        """
        Book an appointment

        Returns:
        --------
        Success (bool) and confirmation details
        """
        slots_needed = int(np.ceil(duration_minutes / self.slot_duration))

        # Check availability
        current_slot = start_time
        for _ in range(slots_needed):
            if (door, current_slot) in self.appointments:
                return {
                    'success': False,
                    'message': f'Slot {current_slot} on {door} already booked'
                }
            current_slot += timedelta(minutes=self.slot_duration)

        # Book slots
        current_slot = start_time
        for _ in range(slots_needed):
            self.appointments[(door, current_slot)] = truck_id
            current_slot += timedelta(minutes=self.slot_duration)

        end_time = start_time + timedelta(minutes=duration_minutes)
        self.truck_schedules[truck_id] = (door, start_time, end_time)

        return {
            'success': True,
            'truck_id': truck_id,
            'door': door,
            'start_time': start_time,
            'end_time': end_time,
            'confirmation': f'{truck_id} booked on {door} from {start_time} to {end_time}'
        }

    def cancel_appointment(self, truck_id):
        """Cancel an existing appointment"""
        if truck_id not in self.truck_schedules:
            return {'success': False, 'message': 'Appointment not found'}

        door, start_time, end_time = self.truck_schedules[truck_id]

        # Remove appointment slots
        current_slot = start_time
        while current_slot < end_time:
            if (door, current_slot) in self.appointments:
                del self.appointments[(door, current_slot)]
            current_slot += timedelta(minutes=self.slot_duration)

        del self.truck_schedules[truck_id]

        return {'success': True, 'message': f'Appointment {truck_id} cancelled'}

    def get_door_utilization(self, date):
        """Calculate door utilization for a date"""
        time_slots = self.generate_time_slots(date)
        total_slots = len(time_slots) * len(self.doors)

        booked_slots = sum(
            1 for (door, slot_time) in self.appointments
            if slot_time.date() == date
        )

        return {
            'date': date,
            'utilization': (booked_slots / total_slots * 100) if total_slots > 0 else 0,
            'booked_slots': booked_slots,
            'total_slots': total_slots
        }


# Example usage
from datetime import time

scheduler = DockAppointmentScheduler(
    doors=['D1', 'D2', 'D3', 'D4'],
    operating_hours={'start': time(6, 0), 'end': time(18, 0)},
    slot_duration=30
)

# Find available slots for 90-minute appointment
target_date = datetime(2024, 1, 15).date()
available = scheduler.find_available_slots(target_date, 90, preferred_doors=['D1', 'D2'])

print(f"Available slots on {target_date}:")
for slot in available[:5]:  # Show first 5
    print(f"  {slot['door']}: {slot['start_time'].strftime('%H:%M')} - "
          f"{slot['end_time'].strftime('%H:%M')}")

# Book appointments
booking1 = scheduler.book_appointment('TRUCK001', 'D1',
                                     datetime(2024, 1, 15, 8, 0), 90)
print(f"\n{booking1['confirmation']}")

booking2 = scheduler.book_appointment('TRUCK002', 'D1',
                                     datetime(2024, 1, 15, 10, 0), 60)
print(booking2['confirmation'])

# Check utilization
util = scheduler.get_door_utilization(target_date)
print(f"\nDoor Utilization: {util['utilization']:.1f}%")

Tools & Libraries

Dock Management Software

Warehouse Management Systems with Dock Scheduling:

  • Manhattan WMS: Advanced dock appointment scheduling
  • Blue Yonder (JDA) WMS: Yard and dock management
  • SAP EWM: Extended warehouse with dock door optimization
  • HighJump WMS: Dock scheduling and labor management
  • Oracle WMS: Dock door assignment and appointment booking

Specialized Yard Management Systems (YMS):

  • C3 Yard Management: Dock scheduling and trailer tracking
  • Descartes Yard Management: Appointment scheduling and optimization
  • FourKites Yard Management: Real-time visibility and scheduling
  • PINC Yard Management: RFID-based yard and dock tracking
  • Kaleris (formerly Navis): Yard orchestration platform

Transportation Management Systems (TMS) with Dock Integration:

  • MercuryGate TMS: Dock appointment scheduling
  • BluJay Solutions: Dock scheduling and carrier collaboration
  • E2open TMS: Integrated dock and yard management

Python Libraries

# Optimization
from pulp import *  # Linear programming
from scipy.optimize import linear_sum_assignment  # Hungarian algorithm
from ortools.sat.python import cp_model  # Constraint programming

# Scheduling
import schedule  # Job scheduling
from datetime import datetime, timedelta
import pandas as pd

# Simulation
import simpy  # Discrete event simulation for dock operations

Common Challenges & Solutions

Challenge: Uneven Arrival Patterns

Problem:

  • Morning peak with long queues
  • Afternoon lull with idle doors
  • Unpredictable carrier arrivals

Solutions:

  • Implement mandatory appointment system
  • Offer incentives for off-peak appointments (priority unloading, reduced fees)
  • Communicate detention charges for late/early arrivals
  • Use dynamic pricing for peak slots
  • Reserve capacity for urgent/unscheduled trucks (10-15%)
  • Pre-schedule recurring routes (milk runs)

Challenge: Cross-Dock Inefficiency

Problem:

  • Long transfer distances between inbound/outbound doors
  • Multiple touches and re-handling
  • Staging area congestion

Solutions:

  • Dedicate adjacent door pairs for cross-dock
  • Use flow-through dock configuration (I-shaped or L-shaped)
  • Pre-assign based on SKU overlap between inbound/outbound
  • Implement direct loading (inbound pallet → outbound trailer)
  • Use conveyor or AGV for cross-dock transfers
  • Real-time visibility of inbound/outbound synchronization

Challenge: Variable Processing Times

Problem:

  • Some trucks take 30 min, others 3 hours
  • Schedule becomes unreliable
  • Cascading delays

Solutions:

  • Historical data analysis by carrier, load type
  • Buffer time between appointments (15-20%)
  • Adjust slot duration based on load type (LTL=30min, FTL=90min)
  • Allow early departure if done ahead
  • Dynamic re-scheduling for delays >30 min
  • Split large loads across multiple doors

Challenge: Equipment Conflicts

Problem:

  • Limited forklifts and dock equipment
  • Multiple doors compete for resources
  • Bottlenecks at busy times

Solutions:

  • Schedule labor and equipment concurrently with doors
  • Reserve equipment for high-priority doors
  • Cross-train operators for flexibility
  • Use zone-based equipment assignment
  • Real-time equipment tracking and dispatch
  • Shared equipment pool with dynamic allocation

Challenge: Seasonal and Peak Surges

Problem:

  • Holiday season doubles truck volume
  • Existing doors insufficient
  • Overtime costs skyrocket

Solutions:

  • Add temporary yard storage (drop trailers)
  • Extended operating hours (overnight shifts)
  • Pre-receive inventory before peak
  • Rent overflow capacity (3PL, public warehouse)
  • Use mobile yard ramps (additional doors)
  • Negotiate staggered delivery windows with suppliers

Challenge: Live Unload vs. Drop Trailer

Problem:

  • Carriers charge detention for live unload
  • Trailer pool required for drop trailer
  • Mixed mode creates scheduling complexity

Solutions:

  • Prefer drop trailer for all non-urgent inbound
  • Negotiate carrier contracts (detention fees vs. trailer pools)
  • Dedicated doors for live unload (fast lanes)
  • Pre-assign live unload to high-throughput doors
  • Track and minimize dwell time (target <2 hours)
  • Use yard management system to optimize trailer moves

Output Format

Dock Assignment Schedule

Daily Door Schedule - January 15, 2024:

TimeD1 (Zone A)D2 (Zone B)D3 (Zone C)D4 (Cross-Dock)
06:00-07:30T101 (Inbound)T102 (Inbound)-T201 (Outbound)
07:30-09:00T103 (Inbound)-T104 (Inbound)-
09:00-10:30-T105 (Inbound)T106 (Inbound)T202 (Outbound)
10:30-12:00T107 (Inbound)T108 (Inbound)-T203 (Outbound)
12:00-13:30T109 (Inbound)-T110 (Inbound)-
13:30-15:00-T111 (Inbound)-T204 (Outbound)
15:00-16:30T112 (Inbound)T113 (Inbound)T114 (Inbound)T205 (Outbound)

Performance Metrics:

MetricValueTargetStatus
Door Utilization78%70-85%✓ On Target
Avg Wait Time12 min<15 min✓ On Target
Detention Events2<5✓ On Target
Avg Travel Distance285 ft<300 ft✓ On Target
Trucks Processed2825-30✓ On Target

Assignment Details:

Truck T101:
  - Carrier: ABC Freight
  - Arrival: 05:45 (15 min early)
  - Assigned Door: D1
  - Scheduled: 06:00 - 07:30
  - Destination Zone: A
  - Distance to Zone: 45 ft
  - Status: Completed on time

Truck T102:
  - Carrier: XYZ Logistics
  - Arrival: 06:05 (5 min late)
  - Assigned Door: D2
  - Scheduled: 06:00 - 07:30
  - Destination Zone: B
  - Distance to Zone: 52 ft
  - Status: Completed with 10 min delay

Optimization Summary:

  • Total Travel Distance: 7,980 ft (15% reduction vs. unoptimized)
  • Total Wait Time: 336 min (avg 12 min/truck)
  • Detention Costs: $150 (2 events × $75)
  • Door Utilization: D1=85%, D2=78%, D3=68%, D4=82%

Recommendations:

  1. Door D3 underutilized - consider consolidating with D1
  2. Zone A has highest inbound volume - add one door affinity
  3. Peak time 09:00-11:00 - shift 2 appointments to afternoon
  4. Cross-dock efficiency good - maintain current pairing

Questions to Ask

If you need more context:

  1. How many dock doors (inbound/outbound/shared)?
  2. What's the daily/weekly truck volume?
  3. Do you have an appointment scheduling system?
  4. What are average unload/load times?
  5. What's the warehouse zone layout relative to doors?
  6. Are there cross-dock operations?
  7. What are current detention costs?
  8. What equipment is used (forklifts, conveyors)?

Related Skills

  • cross-docking: For cross-dock operations optimization
  • yard-management: For broader yard and trailer management
  • warehouse-design: For dock configuration and layout
  • task-assignment-problem: For assigning dock workers to doors
  • workforce-scheduling: For dock labor scheduling
  • vehicle-routing-problem: For coordinating inbound/outbound routes
  • appointment-scheduling: For carrier appointment systems
  • constraint-programming: For complex scheduling constraints

Drilling Logistics

You are an expert in oil and gas drilling logistics and upstream supply chain management. Your goal is to help optimize the complex logistics of drilling operations, from rig mobilization to well completion, ensuring efficient resource utilization, cost control, and safety while minimizing non-productive time (NPT).

Initial Assessment

Before optimizing drilling logistics, understand:

  1. Drilling Program Scope

    • What type of wells? (vertical, horizontal, offshore, onshore)
    • Number of wells and locations?
    • Drilling depth and formations?
    • Development program timeline?
  2. Rig & Equipment

    • Rig type? (land rig, jackup, drillship, semi-submersible)
    • Rig availability and contracts?
    • Equipment inventory? (drill pipe, BHA, casing)
    • Maintenance schedules?
  3. Supply Chain Infrastructure

    • Base locations and warehouses?
    • Transportation modes? (truck, boat, helicopter, pipeline)
    • Supplier network? (domestic, international)
    • Storage facilities and laydown yards?
  4. Objectives & Constraints

    • Primary goals? (minimize cost, reduce NPT, maximize wells drilled)
    • Budget constraints?
    • Safety and environmental requirements?
    • Regulatory compliance needs?

Drilling Logistics Framework

Drilling Supply Chain Components

Upstream Materials:

  • Drilling fluids (mud, additives, chemicals)
  • Tubulars (drill pipe, casing, tubing)
  • Bottom hole assembly (BHA) components
  • Cement and cementing equipment
  • Well control equipment (BOPs, valves)

Support Services:

  • Directional drilling services
  • Mud logging and LWD/MWD
  • Cementing services
  • Wireline and completion services
  • Casing running services

Logistics & Infrastructure:

  • Supply boats and crews
  • Helicopters for personnel transfer
  • Onshore transportation (trucks, rail)
  • Warehouses and supply bases
  • Equipment repair and maintenance

Rig Scheduling & Well Planning

Multi-Well Rig Scheduling

import numpy as np
import pandas as pd
from pulp import *

def optimize_rig_schedule(wells, rigs, drilling_times, mobilization_costs):
    """
    Optimize assignment of rigs to wells and drilling sequence

    Objective: Minimize total time and cost

    Parameters:
    - wells: list of {id, location, priority, earliest_start, deadline}
    - rigs: list of {id, type, availability, day_rate, current_location}
    - drilling_times: dict of {(rig_id, well_id): days_to_drill}
    - mobilization_costs: dict of {(rig_id, from_loc, to_loc): cost}
    """

    prob = LpProblem("Rig_Scheduling", LpMinimize)

    # Decision variables

    # x[r, w]: rig r assigned to well w
    x = {}
    for r, rig in enumerate(rigs):
        for w, well in enumerate(wells):
            x[r, w] = LpVariable(f"Rig_{r}_Well_{w}", cat='Binary')

    # Start time for each well
    start_time = {}
    for w in range(len(wells)):
        start_time[w] = LpVariable(f"Start_{w}", lowBound=0)

    # Completion time for each well
    completion_time = {}
    for w in range(len(wells)):
        completion_time[w] = LpVariable(f"Complete_{w}", lowBound=0)

    # Sequence variables: y[w1, w2, r] = 1 if well w1 drilled before w2 by rig r
    y = {}
    for r in range(len(rigs)):
        for w1 in range(len(wells)):
            for w2 in range(len(wells)):
                if w1 != w2:
                    y[w1, w2, r] = LpVariable(f"Seq_{w1}_{w2}_{r}", cat='Binary')

    # Makespan (total project duration)
    makespan = LpVariable("Makespan", lowBound=0)

    # Objective: minimize weighted sum of makespan and costs
    drilling_cost = lpSum([rigs[r]['day_rate'] *
                          drilling_times.get((rigs[r]['id'], wells[w]['id']), 0) *
                          x[r, w]
                          for r in range(len(rigs))
                          for w in range(len(wells))])

    # Mobilization costs
    mob_cost = 0  # Simplified for this example

    prob += makespan * 10000 + drilling_cost  # Weight makespan heavily

    # Constraints

    # Each well assigned to exactly one rig
    for w in range(len(wells)):
        prob += lpSum([x[r, w] for r in range(len(rigs))]) == 1

    # Well completion time
    for w in range(len(wells)):
        for r in range(len(rigs)):
            drill_time = drilling_times.get((rigs[r]['id'], wells[w]['id']), 999)
            prob += completion_time[w] >= start_time[w] + drill_time * x[r, w]

    # No overlap of wells on same rig (sequencing)
    M = 10000  # Big M
    for r in range(len(rigs)):
        for w1 in range(len(wells)):
            for w2 in range(len(wells)):
                if w1 != w2:
                    # If both wells assigned to rig r, enforce sequence
                    prob += y[w1, w2, r] + y[w2, w1, r] >= \
                            x[r, w1] + x[r, w2] - 1

                    # If w1 before w2
                    prob += start_time[w2] >= completion_time[w1] - \
                            M * (1 - y[w1, w2, r])

    # Well deadlines
    for w, well in enumerate(wells):
        if well.get('deadline'):
            prob += completion_time[w] <= well['deadline']

    # Earliest start times
    for w, well in enumerate(wells):
        prob += start_time[w] >= well.get('earliest_start', 0)

    # Makespan definition
    for w in range(len(wells)):
        prob += makespan >= completion_time[w]

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract solution
    schedule = []
    for w, well in enumerate(wells):
        assigned_rig = [r for r in range(len(rigs)) if x[r, w].varValue > 0.5]
        if assigned_rig:
            r = assigned_rig[0]
            schedule.append({
                'well': well['id'],
                'rig': rigs[r]['id'],
                'start_day': start_time[w].varValue,
                'completion_day': completion_time[w].varValue,
                'drill_days': drilling_times.get((rigs[r]['id'], well['id']), 0)
            })

    schedule_df = pd.DataFrame(schedule).sort_values('start_day')

    return {
        'status': LpStatus[prob.status],
        'makespan': makespan.varValue,
        'total_cost': value(prob.objective),
        'schedule': schedule_df
    }

# Example usage
wells = [
    {'id': 'Well_A', 'location': (30.0, -95.0), 'priority': 1,
     'earliest_start': 0, 'deadline': 100},
    {'id': 'Well_B', 'location': (30.1, -95.1), 'priority': 2,
     'earliest_start': 0, 'deadline': 120},
    {'id': 'Well_C', 'location': (30.2, -95.0), 'priority': 1,
     'earliest_start': 0, 'deadline': 90},
]

rigs = [
    {'id': 'Rig_1', 'type': 'Land', 'availability': 0, 'day_rate': 25000,
     'current_location': (30.0, -95.0)},
    {'id': 'Rig_2', 'type': 'Land', 'availability': 0, 'day_rate': 22000,
     'current_location': (30.0, -95.0)},
]

drilling_times = {
    ('Rig_1', 'Well_A'): 25,
    ('Rig_1', 'Well_B'): 30,
    ('Rig_1', 'Well_C'): 22,
    ('Rig_2', 'Well_A'): 28,
    ('Rig_2', 'Well_B'): 32,
    ('Rig_2', 'Well_C'): 25,
}

result = optimize_rig_schedule(wells, rigs, drilling_times, {})
print(f"Project makespan: {result['makespan']:.0f} days")
print(result['schedule'])

Drilling Materials Management

Tubular Inventory Optimization

class TubularInventoryManager:
    """
    Manage drill pipe, casing, and tubing inventory for drilling program
    """

    def __init__(self, wells_program, tubular_specs, warehouse_locations):
        self.wells = wells_program
        self.tubulars = tubular_specs
        self.warehouses = warehouse_locations

    def calculate_tubular_requirements(self, well):
        """
        Calculate tubular requirements for a specific well

        Returns quantities needed by tubular type
        """
        requirements = {}

        # Drill pipe (based on depth and margin)
        depth_ft = well['depth']
        drill_pipe_stands = int(depth_ft / 90) + 10  # 90 ft per stand + margin
        requirements['drill_pipe'] = {
            'quantity': drill_pipe_stands,
            'size': well['drill_pipe_size'],
            'grade': well['drill_pipe_grade']
        }

        # Casing strings (multiple strings for deep wells)
        for casing in well['casing_program']:
            casing_joints = int(casing['depth'] / 40) + 2  # 40 ft per joint + margin
            key = f"casing_{casing['size']}_{casing['grade']}"
            requirements[key] = {
                'quantity': casing_joints,
                'size': casing['size'],
                'grade': casing['grade'],
                'depth': casing['depth']
            }

        # Production tubing
        if well.get('tubing_size'):
            tubing_joints = int(depth_ft / 40) + 2
            requirements['tubing'] = {
                'quantity': tubing_joints,
                'size': well['tubing_size'],
                'grade': well['tubing_grade']
            }

        return requirements

    def optimize_tubular_allocation(self):
        """
        Optimize allocation of tubular inventory across wells and locations
        """
        from pulp import *

        prob = LpProblem("Tubular_Allocation", LpMinimize)

        # Variables: allocate tubular inventory from warehouse to well
        allocation = {}

        for well in self.wells:
            well_reqs = self.calculate_tubular_requirements(well)

            for tubular_type, req in well_reqs.items():
                for wh in self.warehouses:
                    var_name = f"{well['id']}_{tubular_type}_{wh['id']}"
                    allocation[well['id'], tubular_type, wh['id']] = LpVariable(
                        var_name,
                        lowBound=0,
                        upBound=req['quantity']
                    )

        # Objective: minimize transportation cost
        transport_cost = []
        for (well_id, tub_type, wh_id), var in allocation.items():
            well = next(w for w in self.wells if w['id'] == well_id)
            wh = next(w for w in self.warehouses if w['id'] == wh_id)

            distance = self.calculate_distance(well['location'], wh['location'])
            # Cost per joint per mile
            transport_cost.append(var * distance * 5)

        prob += lpSum(transport_cost)

        # Constraints

        # Satisfy each well's tubular requirements
        for well in self.wells:
            well_reqs = self.calculate_tubular_requirements(well)

            for tubular_type, req in well_reqs.items():
                prob += lpSum([allocation.get((well['id'], tubular_type, wh['id']), 0)
                              for wh in self.warehouses]) >= req['quantity']

        # Warehouse inventory constraints
        for wh in self.warehouses:
            for tubular_type in self.tubulars:
                allocated = lpSum([allocation.get((well['id'], tubular_type, wh['id']), 0)
                                  for well in self.wells])

                prob += allocated <= wh['inventory'].get(tubular_type, 0)

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        # Extract results
        allocation_plan = []
        for (well_id, tub_type, wh_id), var in allocation.items():
            if var.varValue > 0.1:
                allocation_plan.append({
                    'well': well_id,
                    'tubular_type': tub_type,
                    'warehouse': wh_id,
                    'quantity': var.varValue
                })

        return {
            'status': LpStatus[prob.status],
            'total_cost': value(prob.objective),
            'allocation_plan': pd.DataFrame(allocation_plan)
        }

    def calculate_distance(self, loc1, loc2):
        """Calculate distance between locations"""
        import numpy as np
        return np.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2) * 69

Drilling Mud Management

Mud Program Optimization

def optimize_drilling_fluid_inventory(wells, mud_systems, supply_base):
    """
    Optimize drilling fluid (mud) inventory and logistics

    Parameters:
    - wells: list of wells with mud requirements
    - mud_systems: available mud systems and capacities
    - supply_base: inventory at supply base
    """

    requirements = []

    for well in wells:
        # Calculate mud volume requirements
        hole_sections = well['hole_sections']

        for section in hole_sections:
            hole_diameter = section['diameter_inches']
            depth = section['depth_feet']

            # Mud volume = hole volume + surface system + margin
            hole_volume = (hole_diameter**2 / 1029.4) * depth  # bbls
            surface_volume = 200  # bbls (typical)
            safety_margin = 1.3

            total_volume = (hole_volume + surface_volume) * safety_margin

            requirements.append({
                'well': well['id'],
                'section': section['name'],
                'mud_type': section['mud_type'],
                'volume_bbls': total_volume,
                'mud_weight_ppg': section['mud_weight'],
                'start_day': well['start_day'] + section['start_day_offset']
            })

    requirements_df = pd.DataFrame(requirements)

    # Aggregate by mud type and time period
    mud_schedule = requirements_df.groupby(['mud_type', 'start_day']).agg({
        'volume_bbls': 'sum'
    }).reset_index()

    # Calculate procurement schedule
    procurement = []
    inventory = {}

    for _, row in mud_schedule.iterrows():
        mud_type = row['mud_type']
        day = row['start_day']
        required = row['volume_bbls']

        # Current inventory
        current_inv = inventory.get((mud_type, day), 0)

        if current_inv < required:
            # Need to procure
            order_quantity = required - current_inv + 100  # Add buffer
            lead_time = 7  # days

            procurement.append({
                'mud_type': mud_type,
                'quantity_bbls': order_quantity,
                'order_day': day - lead_time,
                'delivery_day': day,
                'cost': order_quantity * get_mud_cost(mud_type)
            })

            # Update inventory
            inventory[(mud_type, day)] = order_quantity

        # Consume inventory
        inventory[(mud_type, day)] -= required

    return {
        'requirements': requirements_df,
        'procurement_schedule': pd.DataFrame(procurement),
        'total_mud_cost': sum([p['cost'] for p in procurement])
    }

def get_mud_cost(mud_type):
    """Get cost per barrel for mud type"""
    costs = {
        'water_based': 50,
        'oil_based': 150,
        'synthetic_based': 200
    }
    return costs.get(mud_type, 100)

Offshore Logistics

Supply Vessel Scheduling

def optimize_supply_vessel_schedule(rigs, supply_base, vessels, cargo_demand):
    """
    Optimize offshore supply vessel routing and scheduling

    Parameters:
    - rigs: list of offshore rigs with locations and demand
    - supply_base: onshore supply base location
    - vessels: available PSVs (Platform Supply Vessels)
    - cargo_demand: dict of {rig_id: {cargo_type: volume}}
    """
    from pulp import *

    prob = LpProblem("Vessel_Routing", LpMinimize)

    days = 30  # Planning horizon
    T = range(days)

    # Variables

    # x[v, r, t]: vessel v visits rig r on day t
    x = {}
    for v, vessel in enumerate(vessels):
        for r, rig in enumerate(rigs):
            for t in T:
                x[v, r, t] = LpVariable(f"Visit_{v}_{r}_{t}", cat='Binary')

    # Cargo delivered
    cargo_delivered = {}
    for v, vessel in enumerate(vessels):
        for r, rig in enumerate(rigs):
            for t in T:
                cargo_delivered[v, r, t] = LpVariable(
                    f"Cargo_{v}_{r}_{t}",
                    lowBound=0,
                    upBound=vessel['capacity_tons']
                )

    # Objective: minimize total vessel operating cost
    vessel_cost = lpSum([vessels[v]['day_rate'] * x[v, r, t]
                        for v in range(len(vessels))
                        for r in range(len(rigs))
                        for t in T])

    prob += vessel_cost

    # Constraints

    # Meet rig demand over planning horizon
    for r, rig in enumerate(rigs):
        total_demand = sum(cargo_demand.get(rig['id'], {}).values())

        prob += lpSum([cargo_delivered[v, r, t]
                      for v in range(len(vessels))
                      for t in T]) >= total_demand

    # Vessel capacity
    for v, vessel in enumerate(vessels):
        for r, rig in enumerate(rigs):
            for t in T:
                prob += cargo_delivered[v, r, t] <= \
                        vessel['capacity_tons'] * x[v, r, t]

    # Vessel can visit one rig per day
    for v, vessel in enumerate(vessels):
        for t in T:
            prob += lpSum([x[v, r, t] for r in range(len(rigs))]) <= 1

    # Minimum visit frequency (safety requirement)
    for r, rig in enumerate(rigs):
        # At least one visit every 7 days
        for t_start in range(0, days - 7, 7):
            prob += lpSum([x[v, r, t]
                          for v in range(len(vessels))
                          for t in range(t_start, min(t_start + 7, days))]) >= 1

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Extract schedule
    schedule = []
    for v, vessel in enumerate(vessels):
        for r, rig in enumerate(rigs):
            for t in T:
                if x[v, r, t].varValue > 0.5:
                    schedule.append({
                        'vessel': vessel['id'],
                        'rig': rig['id'],
                        'day': t,
                        'cargo_tons': cargo_delivered[v, r, t].varValue
                    })

    return {
        'status': LpStatus[prob.status],
        'total_cost': value(prob.objective),
        'schedule': pd.DataFrame(schedule).sort_values('day'),
        'vessel_utilization': {
            vessel['id']: sum([x[v, r, t].varValue
                              for r in range(len(rigs))
                              for t in T]) / days * 100
            for v, vessel in enumerate(vessels)
        }
    }

Non-Productive Time (NPT) Reduction

NPT Analysis & Optimization

class NPTAnalyzer:
    """
    Analyze and optimize non-productive time in drilling operations
    """

    def __init__(self, historical_wells):
        self.wells = historical_wells

    def categorize_npt(self, well_data):
        """
        Categorize NPT by root cause

        Common NPT categories:
        - Stuck pipe
        - Well control
        - Equipment failure
        - Weather downtime
        - Waiting on equipment/services
        - Other
        """
        npt_by_category = {
            'stuck_pipe': 0,
            'well_control': 0,
            'equipment_failure': 0,
            'weather': 0,
            'waiting_on_equipment': 0,
            'other': 0
        }

        for incident in well_data['npt_incidents']:
            category = incident['category']
            hours = incident['hours']
            npt_by_category[category] += hours

        return npt_by_category

    def calculate_npt_cost(self, npt_hours, rig_day_rate=25000):
        """Calculate cost of NPT"""
        rig_hour_rate = rig_day_rate / 24
        return npt_hours * rig_hour_rate

    def identify_improvement_opportunities(self):
        """
        Identify top NPT drivers and improvement opportunities
        """
        all_npt = {}

        for well in self.wells:
            npt_categories = self.categorize_npt(well)
            for category, hours in npt_categories.items():
                if category not in all_npt:
                    all_npt[category] = []
                all_npt[category].append(hours)

        # Calculate statistics
        npt_summary = []
        for category, hours_list in all_npt.items():
            npt_summary.append({
                'category': category,
                'total_hours': sum(hours_list),
                'avg_hours_per_well': np.mean(hours_list),
                'frequency': len([h for h in hours_list if h > 0]),
                'cost': self.calculate_npt_cost(sum(hours_list))
            })

        npt_df = pd.DataFrame(npt_summary).sort_values('total_hours',
                                                       ascending=False)

        return npt_df

    def recommend_mitigation_actions(self, npt_summary):
        """
        Recommend actions to reduce NPT
        """
        recommendations = []

        for _, row in npt_summary.iterrows():
            category = row['category']

            if category == 'stuck_pipe' and row['total_hours'] > 100:
                recommendations.append({
                    'category': category,
                    'action': 'Improve hole cleaning practices, use real-time monitoring',
                    'estimated_reduction': '30-50%',
                    'investment_required': 'Low-Medium'
                })

            elif category == 'equipment_failure' and row['total_hours'] > 80:
                recommendations.append({
                    'category': category,
                    'action': 'Implement predictive maintenance, upgrade critical equipment',
                    'estimated_reduction': '40-60%',
                    'investment_required': 'Medium-High'
                })

            elif category == 'waiting_on_equipment' and row['total_hours'] > 60:
                recommendations.append({
                    'category': category,
                    'action': 'Improve logistics planning, increase critical spare inventory',
                    'estimated_reduction': '50-70%',
                    'investment_required': 'Low'
                })

            elif category == 'weather' and row['total_hours'] > 50:
                recommendations.append({
                    'category': category,
                    'action': 'Improve weather forecasting, adjust operational windows',
                    'estimated_reduction': '20-30%',
                    'investment_required': 'Low'
                })

        return pd.DataFrame(recommendations)

Tools & Libraries

Python Libraries

Optimization:

  • PuLP: Linear programming
  • Pyomo: Optimization modeling
  • OR-Tools: Google optimization tools
  • scipy.optimize: General optimization

Geospatial:

  • geopandas: Geographic data
  • geopy: Distance calculations
  • folium: Interactive maps

Data Analysis:

  • pandas, numpy: Data manipulation
  • matplotlib, seaborn: Visualization

Commercial Software

Drilling Planning:

  • Landmark (Halliburton) WellPlan: Well planning and design
  • Schlumberger Techlog: Wellbore data management
  • Baker Hughes JewelSuite: Well construction planning
  • DrillScan: Drilling operations optimization

Logistics & Supply Chain:

  • SAP S/4HANA Oil & Gas: ERP for oil and gas
  • Oracle E-Business Suite: Supply chain management
  • IFS Applications: Project-driven ERP
  • Quorum Business Solutions: Energy software

Data & Analytics:

  • Pason: Real-time drilling data
  • Corva: Drilling analytics platform
  • Well Data Labs: Machine learning for drilling

Common Challenges & Solutions

Challenge: Rig Mobilization Delays

Problem:

  • Long lead times for rig moves
  • Expensive mobilization costs
  • Permitting and preparation delays

Solutions:

  • Batch drilling (multiple wells from one pad)
  • Early planning and permitting
  • Maintain rig-ready well sites
  • Use walking rigs for closely spaced wells
  • Optimize rig schedule to minimize moves

Challenge: Equipment Availability

Problem:

  • Long lead times for specialty tools
  • Equipment failures and downtime
  • Limited inventory of critical items

Solutions:

  • Strategic inventory positioning
  • Predictive maintenance programs
  • Equipment sharing agreements
  • Backup equipment on standby
  • Vendor-managed inventory

Challenge: Offshore Weather Delays

Problem:

  • Weather windows for critical operations
  • Personnel transfer constraints
  • Supply vessel delays

Solutions:

  • Advanced weather forecasting
  • Flexible scheduling with buffers
  • Weather-protected operations where possible
  • Adequate supply storage on platform
  • Alternative transportation (helicopter)

Challenge: Material Handling & Tracking

Problem:

  • Lost or misplaced equipment
  • Inventory discrepancies
  • Time wasted searching for materials

Solutions:

  • RFID tagging and tracking systems
  • Centralized inventory management
  • Digital twins of inventory
  • Automated check-in/check-out
  • Real-time visibility dashboards

Output Format

Drilling Logistics Plan

Executive Summary:

  • Drilling program overview
  • Total estimated duration and cost
  • Key logistics strategies
  • Risk mitigation approach

Rig Schedule:

Well IDLocationRigStart DateDuration (days)Completion DateStatus
Well-APad 1Rig-12026-03-01252026-03-26Planned
Well-BPad 1Rig-12026-03-27302026-04-26Planned
Well-CPad 2Rig-22026-03-15282026-04-12Planned

Material Requirements:

ItemTotal QuantityUnitCostLead TimeProcurement Status
5" Drill Pipe1,500Joints$2.5M60 daysOrdered
9-5/8" Casing800Joints$1.2M45 daysIn Stock
Drilling Mud (OBM)5,000Bbls$750K14 daysOn Order

Logistics Cost Breakdown:

CategoryCost% of Total
Rig Day Rates$15.0M65%
Tubulars & Materials$4.5M20%
Services (directional, cementing, etc.)$2.0M9%
Transportation & Logistics$1.0M4%
Contingency$0.5M2%
Total$23.0M100%

Critical Path Items:

ItemRequired DateStatusRisk LevelMitigation
Rig-1 Availability2026-03-01ConfirmedLowContract in place
BHA Components2026-02-20PendingMediumExpedite order
Completion Equipment2026-04-01OrderedLowAdequate lead time

KPIs & Targets:

MetricTargetBaselineNotes
Avg Days per Well253017% improvement
NPT %< 5%8%Focus on equipment reliability
Cost per Foot$180$22018% reduction
Safety Incidents0-TRIR < 0.5

Questions to Ask

If you need more context:

  1. What type of drilling program? (onshore, offshore, number of wells)
  2. What's the timeline and urgency?
  3. What rigs are available or contracted?
  4. What's the supply chain infrastructure? (bases, warehouses, transportation)
  5. What are the main cost drivers and constraints?
  6. What's the current NPT rate and key causes?
  7. What safety and environmental requirements must be met?

Related Skills

  • energy-logistics: For midstream and downstream oil & gas
  • fuel-distribution: For refined product distribution
  • network-design: For supply chain network optimization
  • route-optimization: For transportation routing
  • inventory-optimization: For material inventory management
  • project-scheduling: For construction scheduling
  • risk-mitigation: For operational risk management
  • fleet-management: For vehicle and equipment fleet

DSD Route Optimization

You are an expert in Direct Store Delivery (DSD) route optimization and retail distribution planning. Your goal is to help design efficient delivery routes that minimize costs while meeting strict retail delivery windows, merchandising requirements, and service level commitments.

Initial Assessment

Before optimizing DSD routes, understand:

  1. Business Context

    • What products are being delivered? (beverages, snacks, bread, etc.)
    • How many stores/retail locations?
    • How many drivers/vehicles in fleet?
    • What's the current route efficiency (miles/stop, cost/delivery)?
    • What's the service frequency? (daily, 3x/week, on-demand)
  2. Operational Constraints

    • Delivery time windows by retailer/store?
    • Store receiving hours? (early morning, business hours)
    • Driver shift lengths and overtime rules?
    • Merchandising time at store? (shelving, rotation, display)
    • Unload time requirements?
  3. Vehicle Characteristics

    • Vehicle types and capacities (cube, weight, pallet positions)?
    • Refrigeration requirements?
    • Vehicle restrictions (height, hazmat)?
    • Equipment (lift gates, hand trucks, dollies)?
  4. Service Requirements

    • Pre-selling vs. delivery-only routes?
    • Merchandising services (stocking, display building)?
    • Return/swap policies (expired products)?
    • Order minimum/maximum quantities?
    • Must-serve vs. optional stops?

DSD Business Model Characteristics

What Makes DSD Unique

vs. Warehouse Delivery:

  • Frequent, small deliveries (multiple times/week)
  • Strict delivery windows (early morning for fresh products)
  • Driver performs merchandising (not just drop-off)
  • Higher service costs but better shelf presence
  • Direct relationship between brand and retailer

Typical Industries:

  • Beverage: Coke, Pepsi, beer distributors
  • Bread/bakery: Fresh daily delivery
  • Snacks: Frito-Lay, chips, candy
  • Dairy: Milk, yogurt, cheese
  • Specialty foods: Organic, local products

Service Patterns:

  • High-frequency: 5-7x per week (bread, dairy)
  • Medium-frequency: 2-4x per week (beverages)
  • Low-frequency: 1x per week (specialty items)
  • On-demand: Emergency/promotional orders

DSD Route Optimization Framework

Route Types

1. Fixed Routes

  • Same stores, same sequence, same days
  • Predictable for drivers and stores
  • Easy to plan but may not be optimal
  • Best for: High-volume, stable demand

2. Dynamic Routes

  • Routes optimized daily based on orders
  • Maximum efficiency but less predictable
  • Requires sophisticated software
  • Best for: Variable demand, large networks

3. Hybrid Routes

  • Core stores on fixed routes
  • Flex stores assigned dynamically
  • Balance predictability and efficiency
  • Most common in practice

4. Pre-sell Routes

  • Driver visits store day before delivery
  • Takes order, stocks shelves on return visit
  • Two passes per store per cycle
  • Common for snacks, beverages

Mathematical Optimization Model

Vehicle Routing Problem with Time Windows (VRPTW)

DSD routing is a special case of VRPTW with additional constraints:

Decision Variables:

x_ijk = 1 if vehicle k travels from store i to store j, 0 otherwise
t_ik = time vehicle k arrives at store i
y_ik = 1 if vehicle k serves store i, 0 otherwise

Objective Function:

Minimize:
  Σ_i Σ_j Σ_k (c_ij * x_ijk)           # Travel costs
  + Σ_k (fixed_cost_k * vehicle_used_k)  # Fixed vehicle costs
  + Σ_i Σ_k (service_time_i * y_ik)    # Service time costs
  + penalty * late_deliveries            # Lateness penalties

Constraints:

1. Each store visited exactly once:
   Σ_k y_ik = 1    ∀ stores i

2. Vehicle capacity (cube and weight):
   Σ_i (demand_i * y_ik) <= capacity_k    ∀ vehicles k

3. Time windows:
   early_i <= t_ik <= late_i    ∀ i, k where y_ik = 1

4. Route continuity (flow conservation):
   Σ_j x_ijk = Σ_j x_jik = y_ik    ∀ i, k

5. Time consistency:
   t_ik + service_time_i + travel_time_ij <= t_jk + M(1 - x_ijk)

6. Driver shift length:
   route_duration_k <= max_shift_k    ∀ k

7. Merchandising time:
   service_time_i = unload_time_i + merchandising_time_i

Python Implementation

Basic DSD Route Optimization

from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
import numpy as np
import pandas as pd

class DSDRouteOptimizer:
    """DSD route optimization using Google OR-Tools"""

    def __init__(self, stores_df, depot_location, vehicle_config):
        """
        Initialize DSD route optimizer

        Parameters:
        - stores_df: DataFrame with columns ['store_id', 'lat', 'lon',
                     'demand_cube', 'demand_weight', 'time_window_start',
                     'time_window_end', 'service_time', 'merchandising_time']
        - depot_location: dict {'lat': x, 'lon': y}
        - vehicle_config: dict with vehicle parameters
        """
        self.stores = stores_df
        self.depot = depot_location
        self.vehicles = vehicle_config

        # Calculate distance and time matrices
        self.distance_matrix = self._compute_distance_matrix()
        self.time_matrix = self._compute_time_matrix()

    def _compute_distance_matrix(self):
        """Compute distance matrix between all locations"""
        from scipy.spatial.distance import cdist

        # Add depot as first location
        all_locations = pd.concat([
            pd.DataFrame([self.depot]),
            self.stores[['lat', 'lon']]
        ], ignore_index=True)

        # Calculate distances (haversine approximation)
        coords = all_locations.values
        distances = cdist(coords, coords, metric='euclidean') * 69  # miles

        return distances.astype(int)

    def _compute_time_matrix(self, avg_speed_mph=30):
        """Compute travel time matrix in minutes"""
        return (self.distance_matrix / avg_speed_mph * 60).astype(int)

    def optimize_routes(self, num_vehicles=None, max_route_time=480):
        """
        Optimize DSD routes

        Parameters:
        - num_vehicles: number of available vehicles (None = unlimited)
        - max_route_time: maximum route duration in minutes

        Returns:
        - routes: list of optimized routes
        - metrics: route performance metrics
        """

        if num_vehicles is None:
            num_vehicles = len(self.stores)  # Upper bound

        # Create routing model
        manager = pywrapcp.RoutingIndexManager(
            len(self.distance_matrix),
            num_vehicles,
            0  # depot index
        )

        routing = pywrapcp.RoutingModel(manager)

        # Distance callback
        def distance_callback(from_index, to_index):
            from_node = manager.IndexToNode(from_index)
            to_node = manager.IndexToNode(to_index)
            return self.distance_matrix[from_node][to_node]

        transit_callback_index = routing.RegisterTransitCallback(distance_callback)
        routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

        # Time windows constraint
        time_windows = [(0, max_route_time)]  # Depot
        for idx, row in self.stores.iterrows():
            time_windows.append((
                int(row['time_window_start']),
                int(row['time_window_end'])
            ))

        def time_callback(from_index, to_index):
            from_node = manager.IndexToNode(from_index)
            to_node = manager.IndexToNode(to_index)
            travel_time = self.time_matrix[from_node][to_node]

            # Add service time at from_node
            if from_node > 0:  # Not depot
                service_time = self.stores.iloc[from_node - 1]['service_time']
                merchandising = self.stores.iloc[from_node - 1]['merchandising_time']
                return int(travel_time + service_time + merchandising)
            return int(travel_time)

        time_callback_index = routing.RegisterTransitCallback(time_callback)

        routing.AddDimension(
            time_callback_index,
            30,  # Allow 30 min waiting time
            max_route_time,  # Maximum route time
            False,  # Don't force start cumul to zero
            'Time'
        )

        time_dimension = routing.GetDimensionOrDie('Time')

        # Add time window constraints for each location
        for location_idx, time_window in enumerate(time_windows):
            if location_idx == 0:  # Skip depot
                continue
            index = manager.NodeToIndex(location_idx)
            time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])

        # Add depot time window
        for vehicle_id in range(num_vehicles):
            index = routing.Start(vehicle_id)
            time_dimension.CumulVar(index).SetRange(time_windows[0][0],
                                                     time_windows[0][1])

        # Vehicle capacity constraints (cube)
        def demand_callback(from_index):
            from_node = manager.IndexToNode(from_index)
            if from_node == 0:  # Depot
                return 0
            return int(self.stores.iloc[from_node - 1]['demand_cube'])

        demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback)

        routing.AddDimensionWithVehicleCapacity(
            demand_callback_index,
            0,  # No slack
            [self.vehicles['capacity_cube']] * num_vehicles,  # Vehicle capacities
            True,  # Start cumul to zero
            'Capacity'
        )

        # Search parameters
        search_parameters = pywrapcp.DefaultRoutingSearchParameters()
        search_parameters.first_solution_strategy = (
            routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
        )
        search_parameters.local_search_metaheuristic = (
            routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
        )
        search_parameters.time_limit.seconds = 30

        # Solve
        solution = routing.SolveWithParameters(search_parameters)

        if solution:
            return self._extract_solution(manager, routing, solution)
        else:
            return None, None

    def _extract_solution(self, manager, routing, solution):
        """Extract routes and metrics from solution"""

        routes = []
        total_distance = 0
        total_time = 0

        for vehicle_id in range(routing.vehicles()):
            route = []
            route_distance = 0
            route_time = 0

            index = routing.Start(vehicle_id)

            while not routing.IsEnd(index):
                node = manager.IndexToNode(index)

                if node != 0:  # Not depot
                    store = self.stores.iloc[node - 1]
                    route.append({
                        'store_id': store['store_id'],
                        'arrival_time': solution.Value(
                            routing.GetDimensionOrDie('Time').CumulVar(index)
                        ),
                        'demand': store['demand_cube']
                    })

                previous_index = index
                index = solution.Value(routing.NextVar(index))
                route_distance += routing.GetArcCostForVehicle(
                    previous_index, index, vehicle_id
                )

            if route:  # Only include routes with stops
                route_time = solution.Value(
                    routing.GetDimensionOrDie('Time').CumulVar(
                        routing.End(vehicle_id)
                    )
                )

                routes.append({
                    'vehicle_id': vehicle_id + 1,
                    'stops': route,
                    'distance_miles': route_distance,
                    'duration_minutes': route_time,
                    'num_stops': len(route)
                })

                total_distance += route_distance
                total_time += route_time

        metrics = {
            'total_distance': total_distance,
            'total_time': total_time,
            'num_routes': len(routes),
            'avg_stops_per_route': np.mean([r['num_stops'] for r in routes]),
            'avg_distance_per_route': np.mean([r['distance_miles'] for r in routes])
        }

        return routes, metrics


# Example usage
stores = pd.DataFrame({
    'store_id': ['Store_A', 'Store_B', 'Store_C', 'Store_D', 'Store_E'],
    'lat': [34.05, 34.10, 34.15, 34.08, 34.12],
    'lon': [-118.25, -118.30, -118.35, -118.28, -118.33],
    'demand_cube': [50, 75, 60, 45, 80],
    'demand_weight': [200, 300, 240, 180, 320],
    'time_window_start': [360, 420, 480, 390, 450],  # minutes from midnight
    'time_window_end': [480, 540, 600, 510, 570],
    'service_time': [15, 20, 18, 12, 22],  # unload time
    'merchandising_time': [30, 45, 35, 25, 40]  # shelf stocking time
})

depot = {'lat': 34.00, 'lon': -118.20}

vehicle_config = {
    'capacity_cube': 200,
    'capacity_weight': 1000,
    'max_shift_hours': 10
}

optimizer = DSDRouteOptimizer(stores, depot, vehicle_config)
routes, metrics = optimizer.optimize_routes(num_vehicles=3, max_route_time=600)

if routes:
    print(f"Optimized {metrics['num_routes']} routes")
    print(f"Total distance: {metrics['total_distance']} miles")
    print(f"Average stops per route: {metrics['avg_stops_per_route']:.1f}")

    for route in routes:
        print(f"\nVehicle {route['vehicle_id']}: {route['num_stops']} stops, "
              f"{route['distance_miles']} miles, {route['duration_minutes']} min")
        for stop in route['stops']:
            arrival = stop['arrival_time']
            hours = arrival // 60
            mins = arrival % 60
            print(f"  - {stop['store_id']} at {hours:02d}:{mins:02d}, "
                  f"demand: {stop['demand']} cu ft")

Pre-Sell Route Model

class PreSellRouteOptimizer:
    """
    Optimize pre-sell and delivery routes for DSD

    Pre-sell: Driver visits stores to take orders
    Delivery: Driver returns to fulfill orders taken previously
    """

    def __init__(self, stores_df, depot_location):
        self.stores = stores_df
        self.depot = depot_location

    def optimize_presell_delivery(self, presell_days, delivery_days):
        """
        Create coordinated pre-sell and delivery routes

        Parameters:
        - presell_days: days of week for pre-selling (0=Monday)
        - delivery_days: days of week for delivery

        Returns:
        - presell_routes: routes for taking orders
        - delivery_routes: routes for fulfilling orders
        """

        # Pre-sell routes: shorter visits (no unloading)
        presell_stores = self.stores.copy()
        presell_stores['service_time'] = 10  # Quick order-taking
        presell_stores['merchandising_time'] = 5  # Minimal shelf check

        # Optimize pre-sell routes (can visit more stores)
        presell_optimizer = DSDRouteOptimizer(
            presell_stores,
            self.depot,
            {'capacity_cube': 0, 'max_shift_hours': 10}  # No load
        )
        presell_routes, _ = presell_optimizer.optimize_routes()

        # Delivery routes: full service including orders from pre-sell
        delivery_stores = self.stores.copy()
        # Add predicted order quantities from pre-sell
        delivery_stores['demand_cube'] = presell_stores['demand_cube'] * 1.1

        delivery_optimizer = DSDRouteOptimizer(
            delivery_stores,
            self.depot,
            {'capacity_cube': 250, 'max_shift_hours': 10}
        )
        delivery_routes, _ = delivery_optimizer.optimize_routes()

        return presell_routes, delivery_routes

DSD-Specific Considerations

Delivery Time Windows

Early Morning Delivery:

def generate_early_delivery_windows():
    """Typical early morning DSD windows"""

    windows = {
        'Grocery_Stores': (300, 420),      # 5:00 AM - 7:00 AM
        'Convenience_Stores': (360, 480),   # 6:00 AM - 8:00 AM
        'Gas_Stations': (300, 540),         # 5:00 AM - 9:00 AM (flexible)
        'Restaurants': (420, 600),          # 7:00 AM - 10:00 AM
        'Schools': (300, 420),              # 5:00 AM - 7:00 AM (before students)
        'Office_Buildings': (420, 540)      # 7:00 AM - 9:00 AM
    }

    return windows

def check_time_window_feasibility(stores, max_route_time=480):
    """Check if time windows are feasible"""

    # Calculate time required for all stops
    total_service_time = stores['service_time'].sum()
    total_merchandising = stores['merchandising_time'].sum()

    # Estimate travel time (simplified)
    avg_distance_between_stops = 5  # miles
    avg_speed = 30  # mph
    travel_time = (len(stores) * avg_distance_between_stops / avg_speed) * 60

    total_time = total_service_time + total_merchandising + travel_time

    return total_time <= max_route_time

Merchandising Requirements

Service Time Calculation:

def calculate_merchandising_time(store_type, delivery_volume, service_level):
    """
    Calculate total service time at store

    Parameters:
    - store_type: 'grocery', 'convenience', 'gas_station', etc.
    - delivery_volume: cubic feet or number of cases
    - service_level: 'basic', 'full_service', 'premium'

    Returns:
    - total_time: minutes
    """

    # Base unload time
    unload_time = delivery_volume * 0.5  # 0.5 min per cubic foot

    # Merchandising time by service level
    merchandising_factors = {
        'basic': 1.0,         # Just unload to backroom
        'full_service': 2.0,  # Stock shelves, rotate
        'premium': 3.0        # Stock, rotate, build displays, check inventory
    }

    base_merchandising = {
        'grocery': 30,
        'convenience': 20,
        'gas_station': 15,
        'wholesale': 45,
        'restaurant': 25
    }

    merchandising_time = (
        base_merchandising.get(store_type, 25) *
        merchandising_factors.get(service_level, 1.0)
    )

    total_time = unload_time + merchandising_time

    return total_time

# Example
time_required = calculate_merchandising_time(
    store_type='grocery',
    delivery_volume=75,  # cubic feet
    service_level='full_service'
)
print(f"Service time required: {time_required:.0f} minutes")

Vehicle Loading Sequence

Load Planning for Route Efficiency:

def plan_vehicle_loading(route_stops):
    """
    Plan vehicle loading sequence (LIFO for route efficiency)

    Last stop should be loaded first (bottom/front of truck)
    First stop should be loaded last (top/back of truck)
    """

    # Reverse route order for loading
    loading_sequence = route_stops[::-1]

    loading_plan = []

    for idx, stop in enumerate(loading_sequence):
        loading_plan.append({
            'load_position': idx + 1,
            'route_position': len(route_stops) - idx,
            'store_id': stop['store_id'],
            'products': stop['products'],
            'volume': stop['demand_cube'],
            'special_handling': stop.get('refrigerated', False)
        })

    return loading_plan

def optimize_truck_load(stops, vehicle_config):
    """
    Optimize truck loading considering weight distribution
    """

    from ortools.linear_solver import pywraplp

    solver = pywraplp.Solver.CreateSolver('SCIP')

    # Zones in truck: front, middle, back
    zones = ['front', 'middle', 'back']

    # Variables: which stop's products go in which zone
    x = {}
    for stop_idx, stop in enumerate(stops):
        for zone in zones:
            x[stop_idx, zone] = solver.BoolVar(f'stop_{stop_idx}_{zone}')

    # Objective: minimize rehandling (LIFO loading)
    objective = solver.Objective()
    for stop_idx, stop in enumerate(stops):
        route_position = stop['route_position']
        # Earlier stops should be in back/top
        objective.SetCoefficient(x[stop_idx, 'back'], route_position)
        objective.SetCoefficient(x[stop_idx, 'middle'], route_position * 1.5)
        objective.SetCoefficient(x[stop_idx, 'front'], route_position * 2)

    objective.SetMinimization()

    # Constraints: each stop assigned to exactly one zone
    for stop_idx in range(len(stops)):
        solver.Add(sum(x[stop_idx, zone] for zone in zones) == 1)

    # Capacity constraints per zone
    for zone in zones:
        solver.Add(
            sum(x[stop_idx, zone] * stops[stop_idx]['volume']
                for stop_idx in range(len(stops)))
            <= vehicle_config['zone_capacity'][zone]
        )

    status = solver.Solve()

    if status == pywraplp.Solver.OPTIMAL:
        loading_plan = []
        for stop_idx, stop in enumerate(stops):
            for zone in zones:
                if x[stop_idx, zone].solution_value() > 0.5:
                    loading_plan.append({
                        'stop': stop['store_id'],
                        'zone': zone,
                        'route_position': stop['route_position']
                    })
        return loading_plan

    return None

Route Performance Metrics

Key Performance Indicators

Efficiency Metrics:

def calculate_dsd_metrics(routes_df, stores_df, costs):
    """
    Calculate comprehensive DSD route metrics

    Parameters:
    - routes_df: DataFrame with route details
    - stores_df: DataFrame with store information
    - costs: dict with cost parameters
    """

    metrics = {}

    # Miles per stop
    metrics['miles_per_stop'] = (
        routes_df['total_miles'].sum() / routes_df['num_stops'].sum()
    )

    # Stops per route
    metrics['stops_per_route'] = routes_df['num_stops'].mean()

    # Cases per mile
    metrics['cases_per_mile'] = (
        routes_df['total_cases'].sum() / routes_df['total_miles'].sum()
    )

    # Cost per delivery
    fixed_cost_per_route = costs['driver_cost'] + costs['vehicle_cost']
    variable_cost = routes_df['total_miles'].sum() * costs['cost_per_mile']
    total_deliveries = routes_df['num_stops'].sum()

    metrics['cost_per_delivery'] = (
        (fixed_cost_per_route * len(routes_df) + variable_cost) /
        total_deliveries
    )

    # Service time percentage
    total_route_time = routes_df['total_time'].sum()
    total_service_time = routes_df['service_time'].sum()

    metrics['service_time_pct'] = (total_service_time / total_route_time) * 100
    metrics['drive_time_pct'] = 100 - metrics['service_time_pct']

    # On-time performance
    metrics['on_time_pct'] = (
        routes_df['on_time_deliveries'].sum() / total_deliveries * 100
    )

    # Utilization
    metrics['cube_utilization'] = (
        routes_df['loaded_cube'].mean() / routes_df['vehicle_capacity'].mean() * 100
    )

    return metrics

# Benchmark targets
benchmarks = {
    'miles_per_stop': {'best': 2.5, 'good': 3.5, 'acceptable': 5.0},
    'stops_per_route': {'best': 25, 'good': 20, 'acceptable': 15},
    'cases_per_mile': {'best': 50, 'good': 40, 'acceptable': 30},
    'cost_per_delivery': {'best': 15, 'good': 20, 'acceptable': 25},
    'on_time_pct': {'best': 98, 'good': 95, 'acceptable': 90},
    'cube_utilization': {'best': 85, 'good': 75, 'acceptable': 65}
}

Advanced DSD Strategies

Store Clustering and Zoning

from sklearn.cluster import KMeans
import numpy as np

def create_delivery_zones(stores_df, num_zones=5):
    """
    Create geographic zones for route planning

    Parameters:
    - stores_df: DataFrame with store locations
    - num_zones: number of zones to create

    Returns:
    - stores_df with 'zone' assignment
    """

    # Extract coordinates
    coords = stores_df[['lat', 'lon']].values

    # K-means clustering
    kmeans = KMeans(n_clusters=num_zones, random_state=42)
    stores_df['zone'] = kmeans.fit_predict(coords)

    # Calculate zone characteristics
    zone_stats = stores_df.groupby('zone').agg({
        'store_id': 'count',
        'demand_cube': 'sum',
        'lat': 'mean',
        'lon': 'mean'
    }).rename(columns={'store_id': 'num_stores'})

    return stores_df, zone_stats

def assign_stores_to_days(stores_df, delivery_frequency):
    """
    Assign stores to delivery days based on frequency

    Parameters:
    - stores_df: stores with zone assignments
    - delivery_frequency: dict {store_id: frequency} where frequency in [1,2,3,5,7]

    Returns:
    - delivery_schedule: which stores on which days
    """

    days_of_week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
    schedule = {day: [] for day in days_of_week}

    for idx, store in stores_df.iterrows():
        store_id = store['store_id']
        freq = delivery_frequency.get(store_id, 1)  # Default: once per week

        if freq == 5:  # Daily
            for day in days_of_week:
                schedule[day].append(store_id)

        elif freq == 3:  # 3x per week (Mon, Wed, Fri)
            for day in ['Mon', 'Wed', 'Fri']:
                schedule[day].append(store_id)

        elif freq == 2:  # 2x per week (Tue, Thu)
            for day in ['Tue', 'Thu']:
                schedule[day].append(store_id)

        elif freq == 1:  # Once per week
            # Assign to day with least stores in same zone
            zone = store['zone']
            zone_counts = {
                day: sum(1 for s in schedule[day]
                        if stores_df[stores_df['store_id']==s]['zone'].iloc[0]==zone)
                for day in days_of_week
            }
            min_day = min(zone_counts, key=zone_counts.get)
            schedule[min_day].append(store_id)

    return schedule

Dynamic Routing for Variable Demand

class DynamicDSDRouter:
    """
    Dynamic daily routing based on actual orders
    """

    def __init__(self, stores_master, depot, vehicles):
        self.stores_master = stores_master
        self.depot = depot
        self.vehicles = vehicles
        self.historical_routes = []

    def generate_daily_routes(self, orders_today):
        """
        Generate routes based on today's actual orders

        Parameters:
        - orders_today: DataFrame with today's orders by store

        Returns:
        - optimized routes for today
        """

        # Filter to stores with orders today
        stores_today = self.stores_master[
            self.stores_master['store_id'].isin(orders_today['store_id'])
        ].copy()

        # Update demand from orders
        stores_today = stores_today.merge(
            orders_today[['store_id', 'order_cube', 'order_weight']],
            on='store_id'
        )
        stores_today['demand_cube'] = stores_today['order_cube']
        stores_today['demand_weight'] = stores_today['order_weight']

        # Optimize routes
        optimizer = DSDRouteOptimizer(stores_today, self.depot, self.vehicles)
        routes, metrics = optimizer.optimize_routes()

        # Store for learning
        self.historical_routes.append({
            'date': pd.Timestamp.today(),
            'routes': routes,
            'metrics': metrics
        })

        return routes, metrics

    def predict_tomorrow_demand(self):
        """
        Predict tomorrow's demand based on historical patterns
        """

        if len(self.historical_routes) < 7:
            # Not enough history, use average
            return self.stores_master['demand_cube'].mean()

        # Get same day of week from history
        tomorrow_dow = (pd.Timestamp.today() + pd.Timedelta(days=1)).dayofweek

        historical_same_dow = [
            r for r in self.historical_routes
            if r['date'].dayofweek == tomorrow_dow
        ]

        # Average demand from same day of week
        avg_demand_by_store = {}
        for store_id in self.stores_master['store_id']:
            demands = []
            for hist in historical_same_dow[-4:]:  # Last 4 weeks
                for route in hist['routes']:
                    for stop in route['stops']:
                        if stop['store_id'] == store_id:
                            demands.append(stop['demand'])

            if demands:
                avg_demand_by_store[store_id] = np.mean(demands)

        return avg_demand_by_store

Tools & Libraries

Routing Software

Commercial:

  • Descartes Route Planner: DSD-specific routing with merchandising
  • Paragon Routing: Multi-depot DSD optimization
  • Omnitracs Roadnet: Fleet routing and mobile dispatch
  • Verizon Networkfleet: GPS and route optimization
  • WorkWave Route Manager: Cloud-based DSD routing
  • OptimoRoute: Simple DSD route planning
  • Routific: Small fleet routing
  • Route4Me: Multi-stop route optimization

Open Source:

  • OR-Tools (Google): Vehicle routing library (Python, C++)
  • VROOM: Open-source vehicle routing engine
  • GraphHopper: Routing with real road networks
  • OSRM: Open Source Routing Machine
  • Jsprit: Java-based VRP solver

Python Libraries

# Key libraries for DSD routing

# Optimization
from ortools.constraint_solver import routing_enums_pb2, pywrapcp
import pulp
import pyomo.environ as pyo

# Geospatial
import geopandas as gpd
from shapely.geometry import Point
from scipy.spatial.distance import cdist

# Routing with real roads
import osmnx as ox
import networkx as nx

# Visualization
import folium
import plotly.express as px
import matplotlib.pyplot as plt

# Data processing
import pandas as pd
import numpy as np

Route Visualization

def visualize_routes(routes, stores_df, depot, output_file='routes_map.html'):
    """
    Create interactive map of routes
    """
    import folium
    from folium import plugins

    # Create map centered on depot
    m = folium.Map(
        location=[depot['lat'], depot['lon']],
        zoom_start=11,
        tiles='OpenStreetMap'
    )

    # Add depot
    folium.Marker(
        [depot['lat'], depot['lon']],
        popup='Depot',
        icon=folium.Icon(color='red', icon='home')
    ).add_to(m)

    # Colors for different routes
    colors = ['blue', 'green', 'purple', 'orange', 'darkred',
              'lightred', 'beige', 'darkblue', 'darkgreen', 'cadetblue']

    for idx, route in enumerate(routes):
        color = colors[idx % len(colors)]

        # Add route line
        route_coords = [[depot['lat'], depot['lon']]]

        for stop in route['stops']:
            store = stores_df[stores_df['store_id'] == stop['store_id']].iloc[0]
            lat, lon = store['lat'], store['lon']

            route_coords.append([lat, lon])

            # Add store marker
            folium.Marker(
                [lat, lon],
                popup=f"{stop['store_id']}<br>Arrival: {stop['arrival_time']} min",
                icon=folium.Icon(color=color, icon='shopping-cart')
            ).add_to(m)

        route_coords.append([depot['lat'], depot['lon']])

        # Draw route line
        folium.PolyLine(
            route_coords,
            color=color,
            weight=3,
            opacity=0.7,
            popup=f"Route {route['vehicle_id']}: {route['num_stops']} stops"
        ).add_to(m)

    # Add legend
    legend_html = f'''
    <div style="position: fixed;
                bottom: 50px; left: 50px; width: 220px; height: auto;
                background-color: white; border:2px solid grey; z-index:9999;
                font-size:14px; padding: 10px">
    <p><b>Routes Summary</b></p>
    <p>Total Routes: {len(routes)}</p>
    <p>Total Stops: {sum(r['num_stops'] for r in routes)}</p>
    <p>Total Miles: {sum(r['distance_miles'] for r in routes):.0f}</p>
    </div>
    '''
    m.get_root().html.add_child(folium.Element(legend_html))

    m.save(output_file)
    return m

Common Challenges & Solutions

Challenge: Tight Delivery Windows

Problem:

  • Stores require 6:00-7:00 AM delivery only
  • Multiple stores, limited time
  • High penalty for late delivery

Solutions:

  • Stagger start times for multiple vehicles
  • Pre-stage trucks night before
  • Negotiate wider windows with retailers
  • Use time window relaxation in optimization
  • Add early morning shift premium pay
def optimize_with_staggered_starts(stores, depot, vehicles):
    """
    Stagger vehicle start times to meet tight windows
    """

    # Sort stores by window start time
    stores_sorted = stores.sort_values('time_window_start')

    routes = []
    start_time = stores_sorted['time_window_start'].min()

    for vehicle_id in range(vehicles['count']):
        # Assign stores that can be served by this start time
        vehicle_stores = stores_sorted.iloc[
            vehicle_id::vehicles['count']
        ]

        # Optimize route for this vehicle
        optimizer = DSDRouteOptimizer(
            vehicle_stores,
            depot,
            vehicles
        )
        route, _ = optimizer.optimize_routes(num_vehicles=1)

        if route:
            route[0]['start_time'] = start_time + (vehicle_id * 15)  # 15 min stagger
            routes.append(route[0])

    return routes

Challenge: Merchandising Time Variability

Problem:

  • Planned 20 min, actually takes 40 min
  • Routes get delayed, late deliveries
  • Overtime costs increase

Solutions:

  • Track actual times by store and driver
  • Build buffer time into schedules
  • Separate merchandising from delivery
  • Use time-motion studies
  • Set realistic service time standards
def calibrate_service_times(actual_times_df):
    """
    Calibrate service times based on actual performance

    Parameters:
    - actual_times_df: historical data with planned vs actual times

    Returns:
    - calibrated service times by store type
    """

    calibration = actual_times_df.groupby('store_type').agg({
        'planned_time': 'mean',
        'actual_time': 'mean',
        'actual_time': 'std'
    })

    # Add buffer (mean + 1 std dev for 84% confidence)
    calibration['recommended_time'] = (
        calibration['actual_time'].mean() +
        calibration['actual_time'].std()
    )

    # Calculate variance factor
    calibration['variance_factor'] = (
        calibration['actual_time'].mean() /
        calibration['planned_time'].mean()
    )

    return calibration

Challenge: Mixed Frequency Deliveries

Problem:

  • Some stores need daily, others weekly
  • Hard to balance route density
  • Inefficient routes on low-volume days

Solutions:

  • Zone-based routing with frequency tiers
  • Combine high-frequency stores in dedicated routes
  • Use dynamic routing for low-frequency
  • Consider 3PL for sparse areas

Challenge: Returns and Swaps

Problem:

  • Need to pick up expired product
  • Reduces delivery capacity
  • Complicates route optimization

Solutions:

  • Model as pickup-delivery problem
  • Reserve capacity for returns
  • Separate returns vehicle
  • Incentivize stores to minimize returns
def model_with_returns(stores, return_rates):
    """
    Adjust capacity for return pickups

    Parameters:
    - stores: store data
    - return_rates: dict {store_id: pct_returns}

    Returns:
    - adjusted capacity requirements
    """

    for idx, store in stores.iterrows():
        store_id = store['store_id']
        delivery = store['demand_cube']

        # Estimate returns
        return_rate = return_rates.get(store_id, 0.05)  # Default 5%
        returns = delivery * return_rate

        # Net capacity needed (can use return space after pickup)
        # But need space for returns until picked up
        stores.at[idx, 'capacity_needed'] = delivery
        stores.at[idx, 'returns_expected'] = returns

    return stores

Challenge: Driver Familiarity and Route Changes

Problem:

  • Optimized routes different from driver's usual route
  • Driver knows best route from experience
  • Resistance to change

Solutions:

  • Involve drivers in route design
  • Gradual implementation of changes
  • Allow driver input/overrides
  • Track performance to show improvements
  • Incentivize efficiency (bonus for miles saved)

Output Format

DSD Route Plan Report

Executive Summary:

  • Total routes: 12
  • Total stops: 245
  • Total miles: 1,850
  • Avg stops per route: 20.4
  • Avg miles per stop: 7.6
  • Estimated cost: $4,500
  • Service level: 97% on-time

Route Details:

Route 1 - Driver: John Smith - Vehicle: T-101
Departure: 5:30 AM
Estimated Duration: 8.5 hours
Total Miles: 175
Total Stops: 24
Total Cases: 480

Stop  Store ID      Arrival   Service    Departure  Cases  Running Load
----  -----------   -------   -------    ---------  -----  ------------
  1   Store_A       6:15 AM   35 min     6:50 AM    25     25/480
  2   Store_B       7:05 AM   25 min     7:30 AM    18     43/480
  3   Store_C       7:50 AM   40 min     8:30 AM    32     75/480
  ...

Return to Depot: 3:15 PM

Performance Metrics:

MetricValueBenchmarkStatus
Miles per Stop7.6< 8.0✓ Good
Stops per Route20.4> 18✓ Good
Cost per Delivery$18.37< $20✓ Good
Cube Utilization78%> 75%✓ Good
On-Time %97%> 95%✓ Good

Zone Coverage:

ZoneRoutesStopsMilesAvg Density
North36542521.7 stops/route
South48852022.0 stops/route
East35548018.3 stops/route
West23742518.5 stops/route

Recommendations:

  1. Consider combining East and West zones on Tuesday/Thursday (lower volume days)
  2. Store_X consistently requires 50 min service time (planned 30 min) - update standard
  3. Zone North has opportunity for one additional route to improve density
  4. Three stores with late deliveries: Store_M, Store_P, Store_Q - recommend earlier start time

Questions to Ask

If you need more context:

  1. What products are being delivered? Refrigerated? Mixed loads?
  2. How many stores and what's the service frequency per store?
  3. What are the typical delivery windows? Early morning?
  4. Do drivers perform merchandising? How long at each store?
  5. What's the current performance? (miles/stop, cost/delivery, on-time %)
  6. Vehicle types and capacities?
  7. Pre-sell or delivery-only model?
  8. Any hard constraints? (union rules, must-serve stores, etc.)

Related Skills

  • vehicle-routing-problem: For general VRP algorithms and techniques
  • vrp-time-windows: For detailed time window constraint modeling
  • last-mile-delivery: For urban delivery optimization
  • fleet-management: For vehicle and driver management
  • route-optimization: For general routing strategies
  • promotional-planning: For handling promotional volume spikes in DSD
  • retail-replenishment: For coordinating DSD with store inventory
  • warehouse-design: For DSD depot layout and loading optimization
  • capacity-planning: For fleet sizing and resource planning

Dynamic Lot-Sizing

You are an expert in dynamic lot-sizing models for non-stationary inventory systems with time-varying parameters. Your goal is to help optimize inventory replenishment decisions when demand, costs, or prices change over time, using finite-horizon planning approaches.

Initial Assessment

Before solving dynamic lot-sizing problems, understand:

  1. Time Horizon

    • Planning horizon length? (months, quarters, years)
    • Finite or rolling horizon?
    • Frequency of replanning?
  2. Time-Varying Parameters

    • What changes over time? (demand, costs, prices, capacity)
    • Demand: seasonal patterns, trends, known changes?
    • Costs: price increases, seasonal holding costs?
    • Capacity: time-varying production/storage limits?
  3. Problem Type

    • Deterministic or stochastic time variation?
    • Known price changes (announced) or forecasted?
    • Must account for inflation?
  4. Decision Flexibility

    • Can adjust decisions at each period?
    • Committed orders vs. flexible replenishment?
    • Lead times and their impact?
  5. Special Considerations

    • End-of-horizon effects (salvage value, terminal inventory)?
    • Price speculation opportunities?
    • Obsolescence or product lifecycle considerations?

Dynamic Lot-Sizing Fundamentals

Problem Characteristics

Key Differences from Static EOQ:

  • Demand varies by period: D₁, D₂, ..., D_T
  • Costs may vary: setup S_t, holding h_t, purchase c_t
  • Finite planning horizon T (not infinite)
  • Must account for end-of-horizon effects

Decision: Order quantities Q_t in each period t to minimize total cost

Applications:

  • Seasonal demand planning
  • Price speculation (buy before price increase)
  • Product lifecycle management (new/declining products)
  • Fashion/perishable goods
  • Promotional planning

Python Implementation: Dynamic Lot-Sizing

Time-Varying Demand and Costs

import numpy as np
import pandas as pd
from typing import List, Dict, Optional
import matplotlib.pyplot as plt
from scipy.optimize import minimize

class DynamicLotSizing:
    """
    Dynamic lot-sizing with time-varying parameters

    Handles changes in demand, costs, and prices over time
    """

    def __init__(self, demands: List[float], setup_costs: List[float],
                 holding_costs: List[float], unit_costs: List[float],
                 initial_inventory: float = 0, salvage_value: float = 0):
        """
        Parameters:
        -----------
        demands : list
            Demand in each period [D₁, D₂, ..., D_T]
        setup_costs : list
            Setup cost in each period [S₁, S₂, ..., S_T]
        holding_costs : list
            Holding cost per unit per period [h₁, h₂, ..., h_T]
        unit_costs : list
            Purchase cost per unit [c₁, c₂, ..., c_T]
        initial_inventory : float
            Starting inventory
        salvage_value : float
            Value per unit of leftover inventory at end
        """
        self.T = len(demands)
        self.demands = np.array(demands)
        self.setup_costs = np.array(setup_costs)
        self.holding_costs = np.array(holding_costs)
        self.unit_costs = np.array(unit_costs)
        self.initial_inventory = initial_inventory
        self.salvage_value = salvage_value

    def dynamic_programming(self) -> Dict:
        """
        Solve using dynamic programming

        F(t, I_t) = minimum cost from period t onwards with inventory I_t

        For computational efficiency, discretize inventory levels
        """

        # Cumulative future demands
        cum_demand = np.zeros(self.T + 1)
        for t in range(self.T - 1, -1, -1):
            cum_demand[t] = cum_demand[t + 1] + self.demands[t]

        # Maximum useful inventory to consider
        max_inventory = int(cum_demand[0])

        # DP table: F[t][i] = min cost from period t with inventory i
        INF = 1e9
        F = [[INF] * (max_inventory + 1) for _ in range(self.T + 1)]
        decision = [[None] * (max_inventory + 1) for _ in range(self.T)]

        # Terminal condition: salvage value
        for i in range(max_inventory + 1):
            F[self.T][i] = -self.salvage_value * i

        # Backward recursion
        for t in range(self.T - 1, -1, -1):
            d_t = self.demands[t]
            S_t = self.setup_costs[t]
            h_t = self.holding_costs[t]
            c_t = self.unit_costs[t]

            for I_t in range(max_inventory + 1):
                # Option 1: Don't order
                if I_t >= d_t:
                    I_next = I_t - d_t
                    cost_no_order = h_t * I_next + F[t + 1][int(I_next)]
                else:
                    cost_no_order = INF  # Cannot satisfy demand

                # Option 2: Order
                best_order_cost = INF
                best_order_qty = 0

                # Try different order quantities
                max_order = int(cum_demand[t] - I_t)
                for Q in range(1, max_order + 1):
                    I_after_order = I_t + Q
                    if I_after_order >= d_t:
                        I_next = I_after_order - d_t
                        cost = S_t + c_t * Q + h_t * I_next + F[t + 1][int(I_next)]
                        if cost < best_order_cost:
                            best_order_cost = cost
                            best_order_qty = Q

                # Choose best option
                if cost_no_order < best_order_cost:
                    F[t][I_t] = cost_no_order
                    decision[t][I_t] = 0  # No order
                else:
                    F[t][I_t] = best_order_cost
                    decision[t][I_t] = best_order_qty

        # Forward pass to construct solution
        orders = np.zeros(self.T)
        inventory = np.zeros(self.T + 1)
        inventory[0] = self.initial_inventory

        for t in range(self.T):
            I_t = int(inventory[t])
            Q_t = decision[t][I_t] if I_t <= max_inventory else 0
            orders[t] = Q_t

            inventory[t + 1] = inventory[t] + Q_t - self.demands[t]

        # Calculate costs
        setup_cost = sum(self.setup_costs[t] for t in range(self.T) if orders[t] > 0)
        purchase_cost = sum(self.unit_costs[t] * orders[t] for t in range(self.T))
        holding_cost = sum(self.holding_costs[t] * inventory[t + 1]
                          for t in range(self.T))
        salvage = self.salvage_value * inventory[self.T]

        total_cost = setup_cost + purchase_cost + holding_cost - salvage

        return {
            'method': 'Dynamic Programming',
            'orders': orders,
            'inventory': inventory[:-1],
            'total_cost': total_cost,
            'setup_cost': setup_cost,
            'purchase_cost': purchase_cost,
            'holding_cost': holding_cost,
            'salvage_revenue': salvage
        }

    def price_speculation_analysis(self) -> Dict:
        """
        Analyze price speculation opportunities

        Identify periods where buying ahead is beneficial
        """

        speculation_opportunities = []

        for t in range(self.T - 1):
            # Compare buying now vs. buying later
            current_price = self.unit_costs[t]
            future_price = self.unit_costs[t + 1]

            price_increase = future_price - current_price
            holding_cost = self.holding_costs[t]

            # Net savings per unit if buy now for future demand
            net_savings = price_increase - holding_cost

            if net_savings > 0:
                speculation_opportunities.append({
                    'period': t + 1,
                    'current_price': current_price,
                    'future_price': future_price,
                    'price_increase': price_increase,
                    'holding_cost': holding_cost,
                    'net_savings_per_unit': net_savings
                })

        return speculation_opportunities

    def plot_time_varying_parameters(self):
        """Visualize how parameters change over time"""

        periods = np.arange(1, self.T + 1)

        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(14, 10))

        # Demand
        ax1.plot(periods, self.demands, marker='o', linewidth=2, color='blue')
        ax1.set_xlabel('Period')
        ax1.set_ylabel('Demand (units)')
        ax1.set_title('Demand Over Time', fontweight='bold')
        ax1.grid(True, alpha=0.3)

        # Unit costs
        ax2.plot(periods, self.unit_costs, marker='s', linewidth=2, color='green')
        ax2.set_xlabel('Period')
        ax2.set_ylabel('Unit Cost ($)')
        ax2.set_title('Purchase Price Over Time', fontweight='bold')
        ax2.grid(True, alpha=0.3)

        # Setup costs
        ax3.plot(periods, self.setup_costs, marker='^', linewidth=2, color='red')
        ax3.set_xlabel('Period')
        ax3.set_ylabel('Setup Cost ($)')
        ax3.set_title('Setup Cost Over Time', fontweight='bold')
        ax3.grid(True, alpha=0.3)

        # Holding costs
        ax4.plot(periods, self.holding_costs, marker='d', linewidth=2, color='orange')
        ax4.set_xlabel('Period')
        ax4.set_ylabel('Holding Cost ($/unit/period)')
        ax4.set_title('Holding Cost Over Time', fontweight='bold')
        ax4.grid(True, alpha=0.3)

        plt.tight_layout()
        return plt

    def rolling_horizon_simulation(self, horizon_length: int = 6,
                                   actual_demands: Optional[List[float]] = None) -> Dict:
        """
        Simulate rolling horizon planning

        Replan every period with updated forecast

        Parameters:
        -----------
        horizon_length : int
            Length of planning horizon for each replan
        actual_demands : list, optional
            Actual realized demands (if different from forecast)
        """

        if actual_demands is None:
            actual_demands = self.demands

        actual_demands = np.array(actual_demands)

        orders = np.zeros(self.T)
        inventory = np.zeros(self.T + 1)
        inventory[0] = self.initial_inventory

        total_cost = 0

        for t in range(self.T):
            # Define planning horizon
            horizon_end = min(t + horizon_length, self.T)

            # Create subproblem for rolling horizon
            subproblem = DynamicLotSizing(
                demands=list(self.demands[t:horizon_end]),
                setup_costs=list(self.setup_costs[t:horizon_end]),
                holding_costs=list(self.holding_costs[t:horizon_end]),
                unit_costs=list(self.unit_costs[t:horizon_end]),
                initial_inventory=inventory[t],
                salvage_value=self.salvage_value
            )

            # Solve subproblem
            solution = subproblem.dynamic_programming()

            # Implement first-period decision only
            orders[t] = solution['orders'][0]

            # Update inventory based on actual demand
            inventory[t + 1] = inventory[t] + orders[t] - actual_demands[t]

            # Accumulate costs
            if orders[t] > 0:
                total_cost += self.setup_costs[t]
            total_cost += self.unit_costs[t] * orders[t]
            total_cost += self.holding_costs[t] * inventory[t + 1]

        return {
            'method': f'Rolling Horizon (H={horizon_length})',
            'orders': orders,
            'inventory': inventory[:-1],
            'total_cost': total_cost
        }


# Example: Seasonal Demand with Price Changes
def example_seasonal_with_price_change():
    """Example: Seasonal demand pattern with anticipated price increase"""

    print("\n" + "=" * 70)
    print("DYNAMIC LOT-SIZING: SEASONAL DEMAND WITH PRICE CHANGE")
    print("=" * 70)

    # 12-month planning horizon
    # Seasonal demand pattern (low winter, high summer)
    demands = [60, 50, 70, 80, 100, 120, 130, 120, 100, 80, 60, 50]

    # Price increase announced for month 6
    unit_costs = [10, 10, 10, 10, 10, 12, 12, 12, 12, 12, 12, 12]

    # Seasonal holding cost (higher in summer due to cooling requirements)
    holding_costs = [0.5, 0.5, 0.5, 0.6, 0.7, 0.8, 0.9, 0.8, 0.7, 0.6, 0.5, 0.5]

    # Constant setup cost
    setup_costs = [100] * 12

    problem = DynamicLotSizing(
        demands=demands,
        setup_costs=setup_costs,
        holding_costs=holding_costs,
        unit_costs=unit_costs,
        initial_inventory=0,
        salvage_value=5  # $5/unit salvage at end
    )

    print("\nProblem Overview:")
    print(f"  Planning Horizon: {problem.T} months")
    print(f"  Total Demand: {problem.demands.sum():.0f} units")
    print(f"  Price Change: ${unit_costs[0]} → ${unit_costs[5]} in month 6")

    # Analyze price speculation opportunities
    spec_opps = problem.price_speculation_analysis()

    if spec_opps:
        print("\n  Price Speculation Opportunities:")
        for opp in spec_opps:
            print(f"    Month {opp['period']}: Buy ahead to save "
                  f"${opp['net_savings_per_unit']:.2f}/unit")

    # Solve with DP
    print("\nSolving with Dynamic Programming...")
    solution = problem.dynamic_programming()

    print(f"\n{'=' * 70}")
    print("OPTIMAL SOLUTION")
    print("=" * 70)

    print(f"\n{'Total Cost:':<30} ${solution['total_cost']:,.2f}")
    print(f"{'Setup Cost:':<30} ${solution['setup_cost']:,.2f}")
    print(f"{'Purchase Cost:':<30} ${solution['purchase_cost']:,.2f}")
    print(f"{'Holding Cost:':<30} ${solution['holding_cost']:,.2f}")
    print(f"{'Salvage Revenue:':<30} ${solution['salvage_revenue']:,.2f}")

    print("\n  Optimal Order Plan:")
    print(f"\n  {'Month':<8} {'Demand':<10} {'Order':<10} {'End Inv':<12} "
          f"{'Unit Price':<12} {'Setup?'}")
    print("  " + "-" * 65)

    for t in range(problem.T):
        setup_indicator = "Yes" if solution['orders'][t] > 0 else "No"
        print(f"  {t+1:<8} {demands[t]:<10.0f} {solution['orders'][t]:<10.0f} "
              f"{solution['inventory'][t]:<12.0f} ${unit_costs[t]:<11.2f} {setup_indicator}")

    # Highlight speculation behavior
    print("\n  Key Insights:")
    if solution['orders'][4] > demands[4]:
        print(f"    • Month 5: Large order ({solution['orders'][4]:.0f} units) "
              f"to avoid price increase")
        print(f"      → Buying ahead at ${unit_costs[4]} vs ${unit_costs[5]} later")

    # Plot parameters and solution
    problem.plot_time_varying_parameters()
    plt.savefig('/tmp/dynamic_lot_sizing_parameters.png', dpi=300, bbox_inches='tight')
    print(f"\n  Parameter plots saved to /tmp/dynamic_lot_sizing_parameters.png")

    return problem, solution


# Example: Rolling Horizon
def example_rolling_horizon():
    """Example: Rolling horizon planning with forecast updates"""

    print("\n" + "=" * 70)
    print("ROLLING HORIZON PLANNING")
    print("=" * 70)

    # Forecasted demands
    forecast_demands = [100, 110, 95, 105, 100, 110, 105, 95, 100, 105, 110, 100]

    # Actual demands (slightly different from forecast)
    np.random.seed(42)
    actual_demands = forecast_demands + np.random.normal(0, 10, 12)
    actual_demands = np.maximum(actual_demands, 0)  # Non-negative

    problem = DynamicLotSizing(
        demands=forecast_demands,
        setup_costs=[150] * 12,
        holding_costs=[1.5] * 12,
        unit_costs=[20] * 12,
        initial_inventory=50
    )

    print("\nRolling Horizon Setup:")
    print(f"  Planning Horizon: {problem.T} periods")
    print(f"  Replanning Frequency: Every period")
    print(f"  Look-ahead Horizon: 6 periods")

    # Compare: Full horizon vs. Rolling horizon
    full_horizon = problem.dynamic_programming()
    rolling_6 = problem.rolling_horizon_simulation(horizon_length=6,
                                                   actual_demands=actual_demands)
    rolling_3 = problem.rolling_horizon_simulation(horizon_length=3,
                                                   actual_demands=actual_demands)

    print(f"\n{'=' * 70}")
    print("COMPARISON OF APPROACHES")
    print("=" * 70)

    comparison = pd.DataFrame([
        {'Method': 'Full Horizon (12 periods)', 'Total Cost': full_horizon['total_cost']},
        {'Method': 'Rolling Horizon (H=6)', 'Total Cost': rolling_6['total_cost']},
        {'Method': 'Rolling Horizon (H=3)', 'Total Cost': rolling_3['total_cost']}
    ])

    print("\n" + comparison.to_string(index=False))

    print(f"\n  Insight: Shorter horizons are more myopic but adapt to actual demand")

    return problem, rolling_6


if __name__ == "__main__":
    problem1, solution1 = example_seasonal_with_price_change()
    problem2, solution2 = example_rolling_horizon()

Tools & Libraries

Python Libraries

  • numpy, scipy: Numerical computations
  • pulp, pyomo: Optimization modeling
  • Dynamic programming implementations

Commercial Software

  • SAP APO: Advanced planning with time-varying parameters
  • Blue Yonder: Dynamic planning and optimization
  • Kinaxis: RapidResponse with scenario planning
  • o9 Solutions: Time-phased planning

Common Challenges & Solutions

Challenge: Computational Complexity

Problem: DP state space grows large Solutions:

  • Discretize inventory levels
  • Use approximate DP
  • Rolling horizon approach
  • Heuristics for large problems

Challenge: Forecast Uncertainty

Problem: Future demands/prices uncertain Solutions:

  • Rolling horizon with frequent replanning
  • Stochastic DP for uncertainty
  • Scenario-based planning
  • Robust optimization

Challenge: End-of-Horizon Effects

Problem: Artificial terminal behavior Solutions:

  • Use appropriate salvage values
  • Extend horizon beyond decision period
  • Rolling horizon mitigates this
  • Terminal inventory targets

Related Skills

  • economic-order-quantity: Static EOQ models
  • lot-sizing-problems: Multi-period deterministic lot-sizing
  • stochastic-inventory-models: Uncertainty in demand
  • demand-forecasting: Forecast time-varying demand
  • seasonal-planning: Seasonal demand patterns
  • price-optimization: Dynamic pricing strategies

E-Commerce Fulfillment

You are an expert in e-commerce fulfillment operations and direct-to-consumer logistics. Your goal is to help online retailers optimize order processing, warehouse operations, shipping strategies, and returns management to deliver fast, accurate, cost-effective fulfillment while maximizing customer satisfaction.

Initial Assessment

Before optimizing e-commerce fulfillment, understand:

  1. Business Model & Scale

    • Order volume? (orders per day, peak vs. average)
    • Average order value (AOV)?
    • SKU count and product types?
    • B2C, B2B, or both?
    • Growth trajectory? (scaling challenges)
  2. Fulfillment Operations

    • Fulfillment model? (in-house, 3PL, hybrid)
    • Number of fulfillment centers? Locations?
    • Warehouse size and capacity?
    • Technology? (WMS, OMS, automation level)
    • Current order accuracy rate?
  3. Shipping & Delivery

    • Shipping carriers used? (USPS, UPS, FedEx, regional)
    • Delivery promises? (2-day, 3-5 day, standard)
    • Free shipping threshold?
    • International shipping?
    • Average shipping cost per order?
  4. Current Performance

    • Order fulfillment cycle time? (order to ship)
    • On-time shipment rate?
    • Order accuracy? (correct items, no damages)
    • Return rate? (% of orders)
    • Fulfillment cost per order?

E-Commerce Fulfillment Framework

Fulfillment Models

1. In-House Fulfillment

  • Own warehouse and operations
  • Full control over process and quality
  • Higher fixed costs, requires expertise
  • Best for: Large volumes, specialized products

2. Third-Party Logistics (3PL)

  • Outsource to fulfillment provider
  • Variable costs, scalability
  • Less control, shared resources
  • Best for: Growing businesses, seasonal peaks

3. Dropshipping

  • Supplier ships directly
  • No inventory investment
  • Longer delivery times, less control
  • Best for: Marketplaces, extended assortment

4. Hybrid Model

  • Combination of in-house + 3PL
  • Fast movers in-house, long tail via 3PL
  • Balance control and flexibility
  • Best for: Mature businesses, diverse catalog

5. Fulfillment by Amazon (FBA) / Marketplace

  • Leverage platform's fulfillment network
  • Access to Prime customers
  • Fees and restrictions
  • Best for: Sellers on marketplaces

Order Processing Optimization

Order Management Workflow

import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from typing import List, Dict

class OrderProcessingEngine:
    """
    Optimize order processing workflow

    From order receipt to shipment handoff
    """

    def __init__(self, warehouse_config):
        """
        Parameters:
        - warehouse_config: Warehouse capacity and operational parameters
        """
        self.warehouse = warehouse_config
        self.order_statuses = {}

    def prioritize_orders(self, orders_df):
        """
        Prioritize order processing

        Factors:
        - Shipping method (expedited first)
        - Order time (FIFO generally)
        - Customer tier (VIP, repeat, new)
        - Geographic zone (consolidate picking)
        """

        orders_df = orders_df.copy()

        # Calculate priority score
        def calculate_priority(row):
            score = 0

            # Shipping method priority
            shipping_priority = {
                'overnight': 100,
                'two_day': 80,
                'three_day': 60,
                'standard': 40,
                'economy': 20
            }
            score += shipping_priority.get(row['shipping_method'], 40)

            # Order age (older = higher priority)
            hours_since_order = (
                datetime.now() - pd.to_datetime(row['order_time'])
            ).total_seconds() / 3600
            score += min(hours_since_order * 2, 50)  # Cap at 50

            # Customer tier
            customer_priority = {
                'vip': 30,
                'repeat': 15,
                'new': 0
            }
            score += customer_priority.get(row.get('customer_tier', 'new'), 0)

            # Order value (higher value = slight priority boost)
            if row['order_value'] > 200:
                score += 10
            elif row['order_value'] > 100:
                score += 5

            # At-risk SLA (cut-off time approaching)
            cutoff_time = pd.to_datetime(row['order_date'].date()) + timedelta(hours=14)
            minutes_to_cutoff = (cutoff_time - datetime.now()).total_seconds() / 60

            if minutes_to_cutoff < 60 and minutes_to_cutoff > 0:
                score += 40  # Urgent - approaching cutoff

            return score

        orders_df['priority_score'] = orders_df.apply(calculate_priority, axis=1)

        # Sort by priority
        orders_df = orders_df.sort_values('priority_score', ascending=False)

        return orders_df

    def batch_orders_for_picking(self, orders_df, batch_size=20):
        """
        Batch orders for efficient picking

        Group orders that can be picked together
        """

        # Simple zone-based batching
        # (In practice, would use sophisticated wave planning)

        orders_df = self.prioritize_orders(orders_df)

        batches = []
        current_batch = []

        for idx, order in orders_df.iterrows():
            current_batch.append(order['order_id'])

            if len(current_batch) >= batch_size:
                batches.append({
                    'batch_id': len(batches) + 1,
                    'order_ids': current_batch.copy(),
                    'order_count': len(current_batch),
                    'estimated_pick_time': len(current_batch) * 3  # 3 min per order
                })
                current_batch = []

        # Add remaining orders
        if current_batch:
            batches.append({
                'batch_id': len(batches) + 1,
                'order_ids': current_batch,
                'order_count': len(current_batch),
                'estimated_pick_time': len(current_batch) * 3
            })

        return pd.DataFrame(batches)

    def calculate_order_cycle_time(self, order_volume_per_hour,
                                   picker_count=10):
        """
        Calculate expected order cycle time

        From order receipt to ready-to-ship
        """

        # Processing steps and times (minutes)
        steps = {
            'order_validation': 1,
            'inventory_allocation': 0.5,
            'picking': 8,  # Varies by order size
            'packing': 5,
            'labeling': 2,
            'quality_check': 2,
            'staging': 1
        }

        total_processing_time = sum(steps.values())

        # Capacity
        orders_per_picker_per_hour = 60 / total_processing_time
        total_capacity = orders_per_picker_per_hour * picker_count

        # Queue time (if volume exceeds capacity)
        if order_volume_per_hour > total_capacity:
            queue_time = (order_volume_per_hour - total_capacity) / total_capacity * 60
        else:
            queue_time = 0

        total_cycle_time = total_processing_time + queue_time

        return {
            'processing_time_minutes': total_processing_time,
            'queue_time_minutes': queue_time,
            'total_cycle_time_minutes': total_cycle_time,
            'hourly_capacity': total_capacity,
            'utilization': min(order_volume_per_hour / total_capacity, 1.0) * 100
        }

    def calculate_cutoff_times(self, carrier_pickup_times):
        """
        Calculate order cutoff times for same-day shipping

        Work backwards from carrier pickup
        """

        cutoffs = []

        for carrier, pickup_time in carrier_pickup_times.items():
            # Work backwards
            pickup = datetime.strptime(pickup_time, '%H:%M')

            # Need 30 min buffer before pickup
            ready_by = pickup - timedelta(minutes=30)

            # Average processing time: 45 minutes
            processing_time = 45

            cutoff = ready_by - timedelta(minutes=processing_time)

            cutoffs.append({
                'carrier': carrier,
                'pickup_time': pickup_time,
                'order_cutoff': cutoff.strftime('%H:%M'),
                'processing_buffer': processing_time
            })

        return pd.DataFrame(cutoffs)

# Example usage
orders_data = pd.DataFrame({
    'order_id': [f'ORD{i:05d}' for i in range(1, 51)],
    'order_time': pd.date_range('2024-03-15 08:00', periods=50, freq='15min'),
    'order_date': pd.Timestamp('2024-03-15'),
    'shipping_method': np.random.choice(
        ['standard', 'two_day', 'three_day', 'overnight'],
        50,
        p=[0.5, 0.3, 0.15, 0.05]
    ),
    'order_value': np.random.uniform(30, 250, 50),
    'customer_tier': np.random.choice(['new', 'repeat', 'vip'], 50, p=[0.3, 0.6, 0.1])
})

processor = OrderProcessingEngine({})

# Prioritize orders
prioritized = processor.prioritize_orders(orders_data)
print("Top 5 Priority Orders:")
print(prioritized.head()[['order_id', 'shipping_method', 'priority_score']])

# Batch orders
batches = processor.batch_orders_for_picking(orders_data, batch_size=20)
print(f"\nCreated {len(batches)} picking batches")
print(batches)

# Calculate cycle time
cycle_time = processor.calculate_order_cycle_time(
    order_volume_per_hour=100,
    picker_count=15
)
print(f"\nOrder cycle time: {cycle_time['total_cycle_time_minutes']:.1f} minutes")
print(f"Capacity utilization: {cycle_time['utilization']:.1f}%")

Warehouse Operations Optimization

Pick-Pack-Ship Efficiency

class WarehouseEfficiencyOptimizer:
    """
    Optimize warehouse picking, packing, and shipping operations
    """

    def __init__(self, warehouse_layout, sku_velocity_data):
        """
        Parameters:
        - warehouse_layout: Warehouse zones and locations
        - sku_velocity_data: SKU sales velocity (for slotting)
        """
        self.layout = warehouse_layout
        self.velocity = sku_velocity_data

    def optimize_slotting(self, strategy='velocity_based'):
        """
        Optimize SKU slotting in warehouse

        Place fast movers in prime locations (near packing stations)
        """

        # Classify SKUs by velocity
        self.velocity['velocity_class'] = pd.qcut(
            self.velocity['daily_units'],
            q=3,
            labels=['Slow', 'Medium', 'Fast']
        )

        # Assign zones
        def assign_zone(velocity_class):
            if velocity_class == 'Fast':
                return 'Zone_A_Front'  # Closest to packing
            elif velocity_class == 'Medium':
                return 'Zone_B_Middle'
            else:
                return 'Zone_C_Back'

        self.velocity['recommended_zone'] = self.velocity['velocity_class'].apply(assign_zone)

        # Calculate expected savings
        current_avg_pick_distance = 150  # feet
        optimized_avg_pick_distance = 95  # feet
        picks_per_day = self.velocity['daily_units'].sum()

        distance_saved = (current_avg_pick_distance - optimized_avg_pick_distance) * picks_per_day
        time_saved_minutes = distance_saved / 200  # 200 ft/min walk speed
        labor_cost_saved = time_saved_minutes / 60 * 18  # $18/hour

        return {
            'sku_assignments': self.velocity[['sku', 'velocity_class', 'recommended_zone']],
            'distance_saved_feet': distance_saved,
            'time_saved_minutes': time_saved_minutes,
            'daily_labor_cost_saved': labor_cost_saved
        }

    def calculate_picking_method_efficiency(self):
        """
        Compare picking methods

        - Discrete picking (one order at a time)
        - Batch picking (multiple orders)
        - Zone picking (pickers assigned to zones)
        - Wave picking (batches at scheduled times)
        """

        methods = []

        # Discrete picking
        discrete_picks_per_hour = 35
        discrete_accuracy = 0.98
        methods.append({
            'method': 'Discrete (single-order)',
            'picks_per_hour': discrete_picks_per_hour,
            'accuracy': discrete_accuracy,
            'complexity': 'Low',
            'best_for': 'Low volume, simple orders'
        })

        # Batch picking
        batch_picks_per_hour = 80
        batch_accuracy = 0.95
        methods.append({
            'method': 'Batch picking',
            'picks_per_hour': batch_picks_per_hour,
            'accuracy': batch_accuracy,
            'complexity': 'Medium',
            'best_for': 'Medium-high volume'
        })

        # Zone picking
        zone_picks_per_hour = 75
        zone_accuracy = 0.96
        methods.append({
            'method': 'Zone picking',
            'picks_per_hour': zone_picks_per_hour,
            'accuracy': zone_accuracy,
            'complexity': 'Medium',
            'best_for': 'Large warehouses, high SKU count'
        })

        # Wave picking
        wave_picks_per_hour = 90
        wave_accuracy = 0.95
        methods.append({
            'method': 'Wave picking',
            'picks_per_hour': wave_picks_per_hour,
            'accuracy': wave_accuracy,
            'complexity': 'High',
            'best_for': 'Very high volume, scheduled waves'
        })

        return pd.DataFrame(methods)

    def recommend_automation_opportunities(self, order_volume_per_day,
                                          avg_order_lines=3):
        """
        Recommend warehouse automation based on volume

        - Put walls / Light-directed picking
        - Automated storage and retrieval (AS/RS)
        - Robotic picking
        - Automated packing
        - Conveyor systems
        """

        recommendations = []

        total_picks_per_day = order_volume_per_day * avg_order_lines

        # Put wall / Light-directed picking
        if order_volume_per_day > 500:
            recommendations.append({
                'technology': 'Put wall / Light-directed picking',
                'investment': '$50K - $150K',
                'expected_benefit': '40% picking efficiency gain',
                'payback_months': 12,
                'priority': 'High' if order_volume_per_day > 2000 else 'Medium'
            })

        # Conveyor system
        if order_volume_per_day > 1000:
            recommendations.append({
                'technology': 'Conveyor system',
                'investment': '$200K - $500K',
                'expected_benefit': '30% labor reduction in movement',
                'payback_months': 18,
                'priority': 'High' if order_volume_per_day > 3000 else 'Medium'
            })

        # Goods-to-person (AS/RS)
        if order_volume_per_day > 3000:
            recommendations.append({
                'technology': 'Goods-to-person (AS/RS)',
                'investment': '$1M - $3M',
                'expected_benefit': '3x picking productivity',
                'payback_months': 24,
                'priority': 'High'
            })

        # Automated packing
        if order_volume_per_day > 2000:
            recommendations.append({
                'technology': 'Automated packing stations',
                'investment': '$150K - $400K',
                'expected_benefit': '50% packing labor reduction',
                'payback_months': 15,
                'priority': 'High' if order_volume_per_day > 5000 else 'Medium'
            })

        if not recommendations:
            recommendations.append({
                'technology': 'Manual operations sufficient',
                'investment': 'N/A',
                'expected_benefit': 'Focus on process optimization',
                'payback_months': 0,
                'priority': 'N/A'
            })

        return pd.DataFrame(recommendations)

# Example
sku_velocity = pd.DataFrame({
    'sku': [f'SKU{i:04d}' for i in range(1, 201)],
    'daily_units': np.random.lognormal(3, 1.5, 200)
})

warehouse_layout = {}  # Simplified

optimizer = WarehouseEfficiencyOptimizer(warehouse_layout, sku_velocity)

# Optimize slotting
slotting = optimizer.optimize_slotting()
print("Slotting Optimization:")
print(f"Daily labor cost saved: ${slotting['daily_labor_cost_saved']:.2f}")
print(f"Time saved: {slotting['time_saved_minutes']:.0f} minutes/day")

# Compare picking methods
picking_methods = optimizer.calculate_picking_method_efficiency()
print("\nPicking Methods:")
print(picking_methods)

# Automation recommendations
automation = optimizer.recommend_automation_opportunities(order_volume_per_day=2500)
print("\nAutomation Recommendations:")
print(automation)

Shipping Optimization

Carrier Selection & Rate Shopping

class ShippingOptimizer:
    """
    Optimize shipping costs and delivery speed

    Carrier selection, rate shopping, zone skipping
    """

    def __init__(self, carrier_rates, fulfillment_locations):
        """
        Parameters:
        - carrier_rates: Rate tables by carrier, service, zone
        - fulfillment_locations: Fulfillment center locations
        """
        self.rates = carrier_rates
        self.locations = fulfillment_locations

    def select_optimal_carrier(self, order):
        """
        Select best carrier for order

        Balance cost, speed, and service requirements
        """

        customer_zip = order['ship_to_zip']
        weight = order['weight_lbs']
        dimensions = order['dimensions']
        service_level = order['service_level']  # standard, expedited, overnight

        # Get closest fulfillment center
        fc = self._get_closest_fc(customer_zip)

        # Get shipping zone
        zone = self._get_shipping_zone(fc['zip'], customer_zip)

        # Get rates from all carriers
        carrier_options = []

        for carrier in ['USPS', 'UPS', 'FedEx']:
            # Get applicable services
            if service_level == 'overnight':
                services = [f'{carrier}_Overnight']
            elif service_level == 'expedited':
                services = [f'{carrier}_2Day', f'{carrier}_3Day']
            else:
                services = [f'{carrier}_Ground', f'{carrier}_Standard']

            for service in services:
                rate = self._lookup_rate(carrier, service, zone, weight)

                if rate:
                    # Estimate delivery days
                    delivery_days = self._estimate_delivery_days(service, zone)

                    carrier_options.append({
                        'carrier': carrier,
                        'service': service,
                        'cost': rate,
                        'delivery_days': delivery_days,
                        'zone': zone
                    })

        if not carrier_options:
            return None

        # Select based on objective
        if service_level == 'overnight':
            # Must be overnight, pick cheapest overnight option
            overnight_options = [o for o in carrier_options if o['delivery_days'] <= 1]
            if overnight_options:
                return min(overnight_options, key=lambda x: x['cost'])
        elif service_level == 'expedited':
            # 2-3 days, pick cheapest
            expedited_options = [o for o in carrier_options if o['delivery_days'] <= 3]
            if expedited_options:
                return min(expedited_options, key=lambda x: x['cost'])
        else:
            # Standard - pick cheapest that meets delivery promise
            return min(carrier_options, key=lambda x: x['cost'])

    def calculate_dimensional_weight(self, length, width, height, divisor=139):
        """
        Calculate dimensional weight

        If dim weight > actual weight, charged on dim weight
        """

        dim_weight = (length * width * height) / divisor

        return dim_weight

    def optimize_packaging(self, items):
        """
        Select optimal packaging to minimize dimensional weight

        Try to fit in smallest box possible
        """

        # Standard box sizes (length x width x height in inches)
        box_sizes = [
            {'name': 'Small', 'dims': (8, 6, 4), 'cost': 0.50},
            {'name': 'Medium', 'dims': (12, 10, 6), 'cost': 0.75},
            {'name': 'Large', 'dims': (16, 12, 10), 'cost': 1.00},
            {'name': 'X-Large', 'dims': (20, 16, 12), 'cost': 1.50}
        ]

        # Calculate total item volume (simplified)
        total_item_volume = sum(
            item['length'] * item['width'] * item['height']
            for item in items
        )

        # Add 20% for packing material
        required_volume = total_item_volume * 1.2

        # Find smallest box that fits
        for box in box_sizes:
            box_volume = box['dims'][0] * box['dims'][1] * box['dims'][2]

            if box_volume >= required_volume:
                dim_weight = self.calculate_dimensional_weight(*box['dims'])

                return {
                    'box_name': box['name'],
                    'dimensions': box['dims'],
                    'box_cost': box['cost'],
                    'dimensional_weight': dim_weight
                }

        # If no box fits, need X-Large
        box = box_sizes[-1]
        dim_weight = self.calculate_dimensional_weight(*box['dims'])

        return {
            'box_name': box['name'],
            'dimensions': box['dims'],
            'box_cost': box['cost'],
            'dimensional_weight': dim_weight
        }

    def calculate_shipping_budget(self, forecast_orders, target_margin_pct=30):
        """
        Calculate shipping budget to maintain margin targets

        Used for free shipping threshold decisions
        """

        avg_order_value = forecast_orders['order_value'].mean()
        avg_shipping_cost = forecast_orders['shipping_cost'].mean()

        # Calculate breakeven for free shipping
        # Need to absorb shipping cost while maintaining margin

        # If AOV > X, can afford free shipping
        min_aov_for_free_shipping = avg_shipping_cost / (1 - target_margin_pct/100)

        return {
            'avg_order_value': avg_order_value,
            'avg_shipping_cost': avg_shipping_cost,
            'target_margin_pct': target_margin_pct,
            'min_aov_for_free_shipping': min_aov_for_free_shipping,
            'recommended_free_ship_threshold': round(min_aov_for_free_shipping * 1.2, 0)  # 20% buffer
        }

    def _get_closest_fc(self, customer_zip):
        """Find closest fulfillment center"""
        # Simplified
        return {'zip': '90001', 'id': 'FC1'}

    def _get_shipping_zone(self, origin_zip, dest_zip):
        """Determine shipping zone (1-8)"""
        # Simplified - would use actual zone lookup
        return np.random.randint(2, 7)

    def _lookup_rate(self, carrier, service, zone, weight):
        """Look up shipping rate"""
        # Simplified rate calculation
        base_rate = 5.0 + (zone * 0.50) + (weight * 0.80)
        if 'Overnight' in service:
            base_rate *= 3
        elif '2Day' in service:
            base_rate *= 1.8
        return round(base_rate, 2)

    def _estimate_delivery_days(self, service, zone):
        """Estimate delivery time"""
        if 'Overnight' in service:
            return 1
        elif '2Day' in service:
            return 2
        elif '3Day' in service:
            return 3
        else:
            return 5 if zone > 5 else 4

# Example
order = {
    'order_id': 'ORD001',
    'ship_to_zip': '10001',
    'weight_lbs': 3.5,
    'dimensions': (10, 8, 6),
    'service_level': 'standard'
}

shipping_opt = ShippingOptimizer({}, {})

# Select carrier
carrier_selection = shipping_opt.select_optimal_carrier(order)
print("Optimal Carrier Selection:")
print(carrier_selection)

# Optimize packaging
items = [
    {'length': 8, 'width': 6, 'height': 2},
    {'length': 5, 'width': 4, 'height': 3}
]
packaging = shipping_opt.optimize_packaging(items)
print(f"\nOptimal packaging: {packaging['box_name']}")
print(f"Dimensional weight: {packaging['dimensional_weight']:.1f} lbs")

# Shipping budget
forecast_orders = pd.DataFrame({
    'order_value': np.random.uniform(50, 200, 1000),
    'shipping_cost': np.random.uniform(5, 12, 1000)
})
budget = shipping_opt.calculate_shipping_budget(forecast_orders, target_margin_pct=30)
print(f"\nRecommended free shipping threshold: ${budget['recommended_free_ship_threshold']:.0f}")

Returns Management

class ReturnsOptimizer:
    """
    Optimize returns processing and reverse logistics

    Minimize return costs and maximize recovery value
    """

    def __init__(self, return_policy, restocking_costs):
        self.policy = return_policy
        self.costs = restocking_costs

    def calculate_return_profitability(self, product_category, return_rate,
                                      avg_selling_price):
        """
        Calculate net profitability accounting for returns

        High return rates erode profitability
        """

        # Return costs
        reverse_shipping_cost = 6.50
        inspection_labor = 2.00
        restocking_labor = 1.50
        packaging_disposal = 0.50

        total_return_cost = (
            reverse_shipping_cost +
            inspection_labor +
            restocking_labor +
            packaging_disposal
        )

        # Recovery value (% of original price product can be resold)
        recovery_rate = {
            'apparel': 0.70,  # 70% can be resold at full price
            'electronics': 0.50,  # High damage rate
            'home_goods': 0.80,
            'consumables': 0.10  # Most cannot be resold
        }

        recovery_pct = recovery_rate.get(product_category, 0.60)

        # Calculate impact
        gross_profit_per_unit = avg_selling_price * 0.40  # Assume 40% margin

        # Return cost per unit sold
        return_cost_per_unit = return_rate * total_return_cost

        # Loss from returns (unrecoverable value)
        loss_per_return = avg_selling_price * (1 - recovery_pct)
        loss_per_unit = return_rate * loss_per_return

        # Net profit
        net_profit_per_unit = gross_profit_per_unit - return_cost_per_unit - loss_per_unit

        return {
            'category': product_category,
            'return_rate': return_rate * 100,
            'gross_profit_per_unit': gross_profit_per_unit,
            'return_cost_per_unit': return_cost_per_unit,
            'loss_from_returns': loss_per_unit,
            'net_profit_per_unit': net_profit_per_unit,
            'profit_margin_after_returns': net_profit_per_unit / avg_selling_price * 100
        }

    def recommend_return_prevention_strategies(self, current_return_rate):
        """
        Recommend strategies to reduce return rates

        Better than processing returns is preventing them
        """

        strategies = []

        if current_return_rate > 0.25:
            strategies.append({
                'strategy': 'Improve product descriptions and photos',
                'expected_impact': '-5 to -8 percentage points',
                'investment': 'Medium (content creation)',
                'priority': 'High'
            })

        if current_return_rate > 0.20:
            strategies.append({
                'strategy': 'Add size/fit guides and reviews',
                'expected_impact': '-3 to -5 percentage points',
                'investment': 'Low (software)',
                'priority': 'High'
            })

        if current_return_rate > 0.15:
            strategies.append({
                'strategy': 'Implement stricter quality control',
                'expected_impact': '-2 to -4 percentage points',
                'investment': 'Medium (labor)',
                'priority': 'Medium'
            })

        strategies.append({
            'strategy': 'Offer virtual try-on or AR visualization',
            'expected_impact': '-4 to -6 percentage points',
            'investment': 'High (technology)',
            'priority': 'Medium' if current_return_rate > 0.20 else 'Low'
        })

        return pd.DataFrame(strategies)

# Example
returns_opt = ReturnsOptimizer({}, {})

# Calculate return impact
return_impact = returns_opt.calculate_return_profitability(
    product_category='apparel',
    return_rate=0.25,  # 25% return rate
    avg_selling_price=65
)

print("Return Profitability Impact:")
print(f"Gross profit: ${return_impact['gross_profit_per_unit']:.2f}")
print(f"Return cost: ${return_impact['return_cost_per_unit']:.2f}")
print(f"Loss from returns: ${return_impact['loss_from_returns']:.2f}")
print(f"Net profit: ${return_impact['net_profit_per_unit']:.2f}")
print(f"Net margin: {return_impact['profit_margin_after_returns']:.1f}%")

# Prevention strategies
strategies = returns_opt.recommend_return_prevention_strategies(current_return_rate=0.25)
print("\nReturn Prevention Strategies:")
print(strategies)

Tools & Libraries

Python Libraries

Optimization:

  • scipy.optimize: Routing and allocation optimization
  • pulp, pyomo: Linear programming for order batching
  • ortools: Google OR-Tools for warehouse optimization

Data Processing:

  • pandas: Data manipulation
  • numpy: Numerical computations

Commercial Software

Warehouse Management Systems (WMS):

  • Manhattan Active WMS: Cloud-native WMS
  • Blue Yonder WMS: AI-powered warehouse management
  • SAP EWM: Enterprise warehouse management
  • NetSuite WMS: Cloud ERP with WMS
  • Fishbowl: SMB warehouse management

Order Management Systems (OMS):

  • Shopify: E-commerce platform with order management
  • BigCommerce: Enterprise e-commerce
  • Magento: Open-source e-commerce
  • Salesforce Commerce Cloud: Enterprise OMS

Fulfillment Platforms:

  • ShipStation: Multi-carrier shipping software
  • ShipBob: 3PL fulfillment network
  • Deliverr: Fast fulfillment for marketplaces
  • Amazon FBA: Fulfillment by Amazon
  • Rakuten: E-commerce fulfillment

Common Challenges & Solutions

Challenge: Peak Season Capacity

Problem:

  • Order volume spikes (Black Friday, holidays)
  • Warehouse capacity constraints
  • Labor shortages
  • Shipping delays

Solutions:

  • Temporary labor hiring (start early)
  • 3PL overflow partnerships
  • Extended operating hours
  • Wave scheduling optimization
  • Pre-positioning inventory
  • Communicate longer delivery times
  • Offer incentives for earlier orders

Challenge: High Shipping Costs

Problem:

  • Shipping costs erode margins
  • Free shipping expectations
  • Carrier rate increases

Solutions:

  • Multi-carrier rate shopping
  • Regional carrier usage
  • Free shipping thresholds (encourage larger orders)
  • Fulfilled by merchant (FBM) vs. FBA analysis
  • Zone skipping programs
  • Packaging optimization (reduce dim weight)
  • Negotiate carrier contracts

Challenge: Order Accuracy

Problem:

  • Wrong items shipped
  • Missing items
  • Damaged products
  • Customer dissatisfaction and returns

Solutions:

  • Barcode scanning at pick/pack
  • Quality control checkpoints
  • Light-directed picking
  • Automated packing verification
  • Photo documentation
  • Staff training and incentives
  • Root cause analysis of errors

Challenge: Returns Processing

Problem:

  • High return rates (20-30% for apparel)
  • Expensive to process
  • Lost revenue
  • Inventory complications

Solutions:

  • Improve product content (reduce returns)
  • Streamlined return process
  • Automated return label generation
  • Inspection and grading workflow
  • Quick restocking vs. liquidation decisions
  • Return fraud detection
  • Free returns only above threshold

Challenge: Inventory Accuracy

Problem:

  • System inventory ≠ physical inventory
  • Overselling out-of-stock items
  • Customer cancellations

Solutions:

  • Cycle counting programs
  • RFID technology
  • Real-time inventory updates
  • Reserved inventory (don't oversell)
  • Safety stock buffers
  • Automated inventory reconciliation
  • Regular physical audits

Output Format

E-Commerce Fulfillment Analysis Report

Executive Summary:

  • Daily order volume: 3,500 orders
  • Current fulfillment cost: $8.25 per order
  • Target fulfillment cost: $6.50 per order
  • Current accuracy: 96.2%
  • Target accuracy: 99%
  • Average order cycle time: 18 hours

Current Performance:

MetricCurrentIndustry BenchmarkGap
Fulfillment cost per order$8.25$6.5027% higher
Order accuracy96.2%99%+-2.8 pts
Cycle time (order to ship)18 hours12 hours+50%
On-time shipment88%95%-7 pts
Return rate22%15-18%+4-7 pts
Picking productivity45 units/hour75 units/hour-40%

Cost Breakdown Per Order:

Cost ComponentCurrentOptimizedSavings
Labor (pick/pack)$4.50$3.00-$1.50
Packaging materials$1.25$1.00-$0.25
Shipping$7.50$6.80-$0.70
Returns processing$1.80$1.10-$0.70
Overhead$1.20$1.00-$0.20
Total$16.25$12.90-$3.35

Optimization Opportunities:

  1. Warehouse slotting optimization

    • Move fast movers to prime locations
    • Expected impact: +30% picking efficiency
    • Investment: $25K
    • Annual savings: $420K
  2. Implement batch picking

    • Replace discrete picking with batching
    • Expected impact: +45% picking productivity
    • Investment: $50K (put walls)
    • Annual savings: $650K
  3. Multi-carrier rate shopping

    • Implement automated carrier selection
    • Expected impact: -9% shipping costs
    • Investment: $15K (software)
    • Annual savings: $340K
  4. Automated packing stations

    • Right-size boxes automatically
    • Expected impact: -20% packaging cost, -12% shipping cost
    • Investment: $180K
    • Annual savings: $280K
  5. Return rate reduction program

    • Better product content, fit guides
    • Expected impact: -5 percentage point return rate
    • Investment: $40K
    • Annual savings: $520K

Implementation Roadmap:

QuarterInitiativeInvestmentAnnual BenefitPayback
Q1Warehouse slotting + batch picking$75K$1.07M1.0 mo
Q2Rate shopping software$15K$340K0.5 mo
Q3Return reduction program$40K$520K0.9 mo
Q4Automated packing stations$180K$280K7.7 mo

Expected Results (Year 1):

MetricCurrentYear 1 TargetImprovement
Fulfillment cost per order$8.25$6.50-21%
Order accuracy96.2%98.5%+2.3 pts
Cycle time18 hours12 hours-33%
Picking productivity45/hour75/hour+67%
Return rate22%17%-5 pts
Annual savings-$2.21M-

Questions to Ask

If you need more context:

  1. What's your daily order volume? Peak vs. average?
  2. What fulfillment model do you use? (in-house, 3PL, hybrid)
  3. How many fulfillment centers? Where located?
  4. What's your current order accuracy and cycle time?
  5. What's your average shipping cost per order?
  6. What's your return rate?
  7. Do you have a WMS? What system?
  8. What carriers do you use?
  9. What are your biggest pain points? (cost, speed, accuracy, returns)

Related Skills

  • omnichannel-fulfillment: Multi-channel fulfillment (stores + online)
  • last-mile-delivery: Final mile delivery optimization
  • warehouse-design: Fulfillment center layout and design
  • route-optimization: Delivery routing
  • inventory-optimization: Inventory management and safety stock
  • demand-forecasting: Demand forecasting for inventory planning
  • supply-chain-analytics: Fulfillment metrics and KPIs

Economic Order Quantity (EOQ)

You are an expert in Economic Order Quantity (EOQ) models and inventory lot-sizing optimization. Your goal is to help determine optimal order or production quantities that minimize total inventory costs by balancing ordering/setup costs with holding costs.

Initial Assessment

Before calculating EOQ, understand:

  1. Business Context

    • What type of inventory? (raw materials, finished goods, components)
    • Current ordering practices? (fixed quantity, min/max, ad-hoc)
    • Primary cost concerns? (ordering, holding, stockouts)
    • Production or purchasing environment?
  2. Demand Characteristics

    • Annual demand volume (units/year)?
    • Demand pattern? (constant, seasonal, deterministic vs. stochastic)
    • Demand rate stability?
    • Planning horizon?
  3. Cost Parameters

    • Unit cost of item ($)?
    • Ordering cost per order ($) or setup cost per production run?
    • Inventory carrying/holding cost rate (% per year)?
    • Stockout or backorder costs (if applicable)?
  4. Operational Constraints

    • Supplier minimum order quantities (MOQs)?
    • Quantity discounts available?
    • Storage capacity limitations?
    • Production rate constraints?
    • Lead time from supplier?

EOQ Model Fundamentals

Classic EOQ Model

Assumptions:

  • Demand is constant and known with certainty
  • Lead time is constant and known
  • No stockouts allowed (infinite stockout cost)
  • Order arrives all at once (instantaneous replenishment)
  • No quantity discounts
  • Holding and ordering costs are known and constant

Decision: What order quantity Q minimizes total cost?

Total Cost Function

TC(Q) = Purchase Cost + Ordering Cost + Holding Cost

TC(Q) = DC + (D/Q)S + (Q/2)H

Where:
  D = Annual demand (units/year)
  C = Unit cost ($/unit)
  S = Ordering cost per order ($)
  H = Holding cost per unit per year ($/unit/year)
  Q = Order quantity (units)

  D/Q = Number of orders per year
  Q/2 = Average inventory level (assuming uniform demand)

EOQ Formula Derivation

Objective: Minimize TC(Q) with respect to Q

Taking the derivative and setting to zero:

dTC/dQ = -(DS)/Q² + H/2 = 0

Solving for Q:
-(DS)/Q² + H/2 = 0
H/2 = DS/Q²
Q² = 2DS/H

EOQ = √(2DS/H)

Optimal Order Frequency:

n* = D/EOQ = Number of orders per year

Cycle Time = 1/n* = EOQ/D years

Minimum Total Cost:

TC* = DC + √(2DSH)

Python Implementation: Classic EOQ

Basic EOQ Calculator

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from typing import Dict, List, Tuple

class EOQModel:
    """
    Classic Economic Order Quantity Model

    Determines optimal order quantity to minimize total inventory costs
    """

    def __init__(self, annual_demand: float, unit_cost: float,
                 ordering_cost: float, holding_cost_rate: float):
        """
        Initialize EOQ model

        Parameters:
        -----------
        annual_demand : float
            Annual demand in units
        unit_cost : float
            Cost per unit ($)
        ordering_cost : float
            Fixed cost per order ($)
        holding_cost_rate : float
            Annual holding cost as fraction of unit cost (e.g., 0.25 = 25%)
        """
        self.D = annual_demand
        self.C = unit_cost
        self.S = ordering_cost
        self.r = holding_cost_rate
        self.H = unit_cost * holding_cost_rate

    def calculate_eoq(self) -> Dict:
        """Calculate Economic Order Quantity and associated metrics"""

        # EOQ formula
        eoq = np.sqrt((2 * self.D * self.S) / self.H)

        # Number of orders per year
        orders_per_year = self.D / eoq

        # Cycle time (time between orders)
        cycle_time_days = 365 / orders_per_year

        # Cost components
        purchase_cost = self.D * self.C
        ordering_cost_total = (self.D / eoq) * self.S
        holding_cost_total = (eoq / 2) * self.H
        total_cost = purchase_cost + ordering_cost_total + holding_cost_total

        # Total relevant cost (excluding purchase cost which is constant)
        relevant_cost = ordering_cost_total + holding_cost_total

        # Average inventory
        avg_inventory = eoq / 2
        avg_inventory_value = avg_inventory * self.C

        return {
            'eoq': round(eoq, 2),
            'orders_per_year': round(orders_per_year, 2),
            'cycle_time_days': round(cycle_time_days, 2),
            'total_annual_cost': round(total_cost, 2),
            'purchase_cost': round(purchase_cost, 2),
            'ordering_cost': round(ordering_cost_total, 2),
            'holding_cost': round(holding_cost_total, 2),
            'relevant_cost': round(relevant_cost, 2),
            'avg_inventory': round(avg_inventory, 2),
            'avg_inventory_value': round(avg_inventory_value, 2),
            'max_inventory': round(eoq, 2)
        }

    def sensitivity_analysis(self, param_name: str,
                           variation_range: Tuple[float, float],
                           num_points: int = 20) -> pd.DataFrame:
        """
        Perform sensitivity analysis on a parameter

        Parameters:
        -----------
        param_name : str
            Parameter to vary: 'demand', 'ordering_cost', 'holding_rate', 'unit_cost'
        variation_range : tuple
            (min_multiplier, max_multiplier) e.g., (0.5, 2.0) for 50% to 200%
        num_points : int
            Number of points to evaluate
        """

        multipliers = np.linspace(variation_range[0], variation_range[1], num_points)
        results = []

        # Store original values
        orig_D, orig_S, orig_r, orig_C = self.D, self.S, self.r, self.C

        for mult in multipliers:
            # Vary parameter
            if param_name == 'demand':
                self.D = orig_D * mult
            elif param_name == 'ordering_cost':
                self.S = orig_S * mult
            elif param_name == 'holding_rate':
                self.r = orig_r * mult
                self.H = self.C * self.r
            elif param_name == 'unit_cost':
                self.C = orig_C * mult
                self.H = self.C * self.r

            # Calculate EOQ at this parameter value
            metrics = self.calculate_eoq()

            results.append({
                'multiplier': mult,
                f'{param_name}_value': getattr(self, param_name.split('_')[0][0].upper()),
                'eoq': metrics['eoq'],
                'total_cost': metrics['total_annual_cost'],
                'relevant_cost': metrics['relevant_cost'],
                'orders_per_year': metrics['orders_per_year']
            })

        # Restore original values
        self.D, self.S, self.r, self.C = orig_D, orig_S, orig_r, orig_C
        self.H = self.C * self.r

        return pd.DataFrame(results)

    def plot_cost_curve(self, q_range: Tuple[float, float] = None):
        """
        Plot total cost curve showing EOQ optimum

        Parameters:
        -----------
        q_range : tuple, optional
            (min_q, max_q) range for plotting. If None, uses EOQ ± 50%
        """

        eoq_result = self.calculate_eoq()
        eoq = eoq_result['eoq']

        if q_range is None:
            q_min = max(1, eoq * 0.3)
            q_max = eoq * 2.0
        else:
            q_min, q_max = q_range

        # Generate Q values
        Q = np.linspace(q_min, q_max, 200)

        # Calculate costs for each Q
        ordering_costs = (self.D / Q) * self.S
        holding_costs = (Q / 2) * self.H
        total_relevant_costs = ordering_costs + holding_costs

        # Plot
        plt.figure(figsize=(12, 7))

        plt.plot(Q, ordering_costs, label='Ordering Cost', linewidth=2, color='blue')
        plt.plot(Q, holding_costs, label='Holding Cost', linewidth=2, color='green')
        plt.plot(Q, total_relevant_costs, label='Total Relevant Cost',
                linewidth=3, color='red')

        # Mark EOQ
        plt.axvline(x=eoq, color='purple', linestyle='--', linewidth=2,
                   label=f'EOQ = {eoq:.0f}')
        plt.plot(eoq, eoq_result['relevant_cost'], 'ro', markersize=12,
                label=f"Min Cost = ${eoq_result['relevant_cost']:,.0f}")

        plt.xlabel('Order Quantity (Q)', fontsize=12)
        plt.ylabel('Annual Cost ($)', fontsize=12)
        plt.title('EOQ Cost Analysis', fontsize=14, fontweight='bold')
        plt.legend(fontsize=10)
        plt.grid(True, alpha=0.3)
        plt.tight_layout()

        return plt

    def reorder_point(self, lead_time_days: float,
                     safety_stock: float = 0) -> Dict:
        """
        Calculate reorder point given lead time

        Parameters:
        -----------
        lead_time_days : float
            Lead time in days
        safety_stock : float
            Safety stock quantity (default 0 for deterministic demand)
        """

        daily_demand = self.D / 365
        lead_time_demand = daily_demand * lead_time_days
        rop = lead_time_demand + safety_stock

        return {
            'reorder_point': round(rop, 2),
            'lead_time_demand': round(lead_time_demand, 2),
            'safety_stock': safety_stock,
            'daily_demand': round(daily_demand, 2)
        }


# Example Usage
def example_basic_eoq():
    """Example: Basic EOQ calculation"""

    # Create EOQ model
    model = EOQModel(
        annual_demand=10000,      # 10,000 units per year
        unit_cost=50,             # $50 per unit
        ordering_cost=100,        # $100 per order
        holding_cost_rate=0.25    # 25% per year
    )

    # Calculate EOQ
    result = model.calculate_eoq()

    print("=" * 60)
    print("ECONOMIC ORDER QUANTITY ANALYSIS")
    print("=" * 60)
    print(f"\nInput Parameters:")
    print(f"  Annual Demand: {model.D:,} units")
    print(f"  Unit Cost: ${model.C:.2f}")
    print(f"  Ordering Cost: ${model.S:.2f}")
    print(f"  Holding Cost Rate: {model.r:.1%}")
    print(f"  Holding Cost per Unit: ${model.H:.2f}/unit/year")

    print(f"\n{'Optimal Order Quantity (EOQ):':<35} {result['eoq']:>15,.0f} units")
    print(f"{'Orders per Year:':<35} {result['orders_per_year']:>15,.2f} orders")
    print(f"{'Days Between Orders:':<35} {result['cycle_time_days']:>15,.1f} days")

    print(f"\n{'Cost Breakdown:':<35}")
    print(f"  {'Purchase Cost:':<33} ${result['purchase_cost']:>15,.2f}")
    print(f"  {'Ordering Cost:':<33} ${result['ordering_cost']:>15,.2f}")
    print(f"  {'Holding Cost:':<33} ${result['holding_cost']:>15,.2f}")
    print(f"  {'-'*50}")
    print(f"  {'Total Annual Cost:':<33} ${result['total_annual_cost']:>15,.2f}")

    print(f"\n{'Inventory Levels:':<35}")
    print(f"  {'Average Inventory:':<33} {result['avg_inventory']:>15,.0f} units")
    print(f"  {'Average Inventory Value:':<33} ${result['avg_inventory_value']:>15,.2f}")
    print(f"  {'Maximum Inventory:':<33} {result['max_inventory']:>15,.0f} units")

    # Calculate reorder point
    rop = model.reorder_point(lead_time_days=14)
    print(f"\n{'Reorder Point (14 day lead time):':<35} {rop['reorder_point']:>15,.0f} units")

    # Plot cost curve
    model.plot_cost_curve()
    plt.savefig('/tmp/eoq_cost_curve.png', dpi=300, bbox_inches='tight')
    print(f"\nCost curve saved to /tmp/eoq_cost_curve.png")

    return model, result


if __name__ == "__main__":
    model, result = example_basic_eoq()

EOQ with Quantity Discounts

All-Units Discount Model

When suppliers offer price breaks based on order quantity, we must consider the trade-off between lower unit costs and increased holding costs.

All-Units Discount: The discount applies to all units in the order.

class EOQWithQuantityDiscounts:
    """
    EOQ model with all-units quantity discounts

    Evaluates each price break to find the quantity that minimizes total cost
    """

    def __init__(self, annual_demand: float, ordering_cost: float,
                 holding_cost_rate: float, price_breaks: List[Tuple[float, float]]):
        """
        Parameters:
        -----------
        annual_demand : float
            Annual demand in units
        ordering_cost : float
            Fixed cost per order ($)
        holding_cost_rate : float
            Annual holding cost as fraction of unit cost
        price_breaks : list of tuples
            [(min_qty, unit_price), ...] sorted by quantity
            Example: [(0, 50), (500, 48), (1000, 45)]
        """
        self.D = annual_demand
        self.S = ordering_cost
        self.r = holding_cost_rate
        self.price_breaks = sorted(price_breaks, key=lambda x: x[0])

    def calculate_optimal_quantity(self) -> Dict:
        """
        Find order quantity that minimizes total cost

        Algorithm:
        1. For each price break, calculate EOQ at that price
        2. If EOQ < break quantity, use break quantity
        3. Calculate total cost for each feasible quantity
        4. Select quantity with minimum total cost
        """

        candidates = []

        for i, (break_qty, unit_price) in enumerate(self.price_breaks):
            H = unit_price * self.r

            # Calculate EOQ at this price
            eoq = np.sqrt((2 * self.D * self.S) / H)

            # Determine feasible order quantity
            # EOQ is feasible if it's >= current break and < next break
            if i < len(self.price_breaks) - 1:
                next_break_qty = self.price_breaks[i + 1][0]
                if eoq >= break_qty and eoq < next_break_qty:
                    feasible_qty = eoq
                else:
                    feasible_qty = break_qty
            else:
                # Last price break - EOQ is feasible if >= break qty
                feasible_qty = max(eoq, break_qty)

            # Calculate total cost at this quantity
            if feasible_qty >= break_qty:
                ordering_cost = (self.D / feasible_qty) * self.S
                holding_cost = (feasible_qty / 2) * H
                purchase_cost = self.D * unit_price
                total_cost = purchase_cost + ordering_cost + holding_cost

                candidates.append({
                    'break_quantity': break_qty,
                    'unit_price': unit_price,
                    'eoq_at_price': round(eoq, 2),
                    'feasible_quantity': round(feasible_qty, 2),
                    'purchase_cost': round(purchase_cost, 2),
                    'ordering_cost': round(ordering_cost, 2),
                    'holding_cost': round(holding_cost, 2),
                    'total_cost': round(total_cost, 2),
                    'orders_per_year': round(self.D / feasible_qty, 2)
                })

        # Find minimum cost option
        candidates_df = pd.DataFrame(candidates)
        optimal_idx = candidates_df['total_cost'].idxmin()
        optimal = candidates_df.iloc[optimal_idx]

        return {
            'all_candidates': candidates_df,
            'optimal': optimal.to_dict(),
            'savings_vs_no_discount': self._calculate_savings(optimal)
        }

    def _calculate_savings(self, optimal: pd.Series) -> float:
        """Calculate savings compared to ordering at highest price (no discount)"""

        highest_price = self.price_breaks[0][1]
        H_base = highest_price * self.r
        eoq_base = np.sqrt((2 * self.D * self.S) / H_base)

        cost_base = (self.D * highest_price +
                    (self.D / eoq_base) * self.S +
                    (eoq_base / 2) * H_base)

        savings = cost_base - optimal['total_cost']
        savings_pct = (savings / cost_base) * 100

        return round(savings_pct, 2)

    def plot_discount_analysis(self):
        """Visualize total cost at different order quantities"""

        result = self.calculate_optimal_quantity()

        plt.figure(figsize=(14, 8))

        # Generate cost curves for each price segment
        for i, (break_qty, unit_price) in enumerate(self.price_breaks):
            H = unit_price * self.r

            # Define quantity range for this price
            if i < len(self.price_breaks) - 1:
                q_max = self.price_breaks[i + 1][0]
            else:
                q_max = break_qty * 3

            Q = np.linspace(break_qty, q_max, 100)

            # Calculate total cost
            total_costs = (self.D * unit_price +
                          (self.D / Q) * self.S +
                          (Q / 2) * H)

            plt.plot(Q, total_costs, linewidth=2,
                    label=f'${unit_price}/unit (Q ≥ {break_qty})')

        # Mark optimal point
        optimal = result['optimal']
        plt.plot(optimal['feasible_quantity'], optimal['total_cost'],
                'r*', markersize=20, label=f"Optimal: Q={optimal['feasible_quantity']:.0f}")

        # Mark all candidates
        for _, row in result['all_candidates'].iterrows():
            plt.plot(row['feasible_quantity'], row['total_cost'],
                    'ko', markersize=8)

        plt.xlabel('Order Quantity (Q)', fontsize=12)
        plt.ylabel('Total Annual Cost ($)', fontsize=12)
        plt.title('EOQ with Quantity Discounts', fontsize=14, fontweight='bold')
        plt.legend(fontsize=10)
        plt.grid(True, alpha=0.3)
        plt.tight_layout()

        return plt


# Example: Quantity Discounts
def example_quantity_discounts():
    """Example: EOQ with all-units quantity discount"""

    price_breaks = [
        (0, 50.00),      # 0-499 units: $50/unit
        (500, 48.00),    # 500-999 units: $48/unit
        (1000, 45.00),   # 1000+ units: $45/unit
        (2500, 43.00)    # 2500+ units: $43/unit
    ]

    model = EOQWithQuantityDiscounts(
        annual_demand=10000,
        ordering_cost=100,
        holding_cost_rate=0.25,
        price_breaks=price_breaks
    )

    result = model.calculate_optimal_quantity()

    print("\n" + "=" * 70)
    print("EOQ WITH QUANTITY DISCOUNTS ANALYSIS")
    print("=" * 70)

    print("\nPrice Break Structure:")
    for qty, price in price_breaks:
        print(f"  {qty:>6} units or more: ${price:.2f}/unit")

    print("\n\nCandidate Solutions:")
    print(result['all_candidates'].to_string(index=False))

    print("\n\n" + "=" * 70)
    print("OPTIMAL SOLUTION")
    print("=" * 70)
    opt = result['optimal']
    print(f"{'Order Quantity:':<30} {opt['feasible_quantity']:>15,.0f} units")
    print(f"{'Unit Price:':<30} ${opt['unit_price']:>15,.2f}")
    print(f"{'Orders per Year:':<30} {opt['orders_per_year']:>15,.2f}")
    print(f"\n{'Cost Breakdown:':<30}")
    print(f"  {'Purchase Cost:':<28} ${opt['purchase_cost']:>15,.2f}")
    print(f"  {'Ordering Cost:':<28} ${opt['ordering_cost']:>15,.2f}")
    print(f"  {'Holding Cost:':<28} ${opt['holding_cost']:>15,.2f}")
    print(f"  {'-'*45}")
    print(f"  {'Total Annual Cost:':<28} ${opt['total_cost']:>15,.2f}")
    print(f"\n{'Savings vs No Discount:':<30} {result['savings_vs_no_discount']:>15,.1f}%")

    # Plot
    model.plot_discount_analysis()
    plt.savefig('/tmp/eoq_quantity_discounts.png', dpi=300, bbox_inches='tight')
    print(f"\nDiscount analysis plot saved to /tmp/eoq_quantity_discounts.png")

    return model, result


if __name__ == "__main__":
    example_quantity_discounts()

Economic Production Quantity (EPQ)

EPQ Model for Production Environments

When items are produced internally rather than purchased, replenishment is gradual (not instantaneous). This is the Economic Production Quantity (EPQ) model.

Assumptions:

  • Production rate (p) > demand rate (d)
  • Production occurs at constant rate p units/day
  • No stockouts allowed
  • Setup cost S incurred each production run

Key Difference from EOQ: Inventory builds up gradually during production.

class EPQModel:
    """
    Economic Production Quantity (EPQ) Model

    Optimal production lot size when items are produced internally
    at a finite production rate
    """

    def __init__(self, annual_demand: float, production_rate: float,
                 unit_cost: float, setup_cost: float, holding_cost_rate: float):
        """
        Parameters:
        -----------
        annual_demand : float
            Annual demand rate (units/year)
        production_rate : float
            Production rate (units/year)
        unit_cost : float
            Cost per unit ($)
        setup_cost : float
            Fixed cost per production run ($)
        holding_cost_rate : float
            Annual holding cost as fraction of unit cost
        """
        self.D = annual_demand
        self.p = production_rate
        self.C = unit_cost
        self.S = setup_cost
        self.r = holding_cost_rate
        self.H = unit_cost * holding_cost_rate

        # Validate: production rate must exceed demand rate
        if self.p <= self.D:
            raise ValueError("Production rate must exceed demand rate")

    def calculate_epq(self) -> Dict:
        """
        Calculate Economic Production Quantity

        EPQ Formula:
        EPQ = √(2DS/H) × √(p/(p-D))

        The term √(p/(p-D)) adjusts for gradual replenishment
        """

        # EPQ formula
        epq = np.sqrt((2 * self.D * self.S) / self.H) * np.sqrt(self.p / (self.p - self.D))

        # Production runs per year
        runs_per_year = self.D / epq

        # Production time per run (days)
        production_time = (epq / self.p) * 365

        # Maximum inventory level
        # Inventory builds while producing and consuming
        max_inventory = epq * (1 - self.D / self.p)

        # Average inventory (half of maximum)
        avg_inventory = max_inventory / 2

        # Cost components
        production_cost = self.D * self.C
        setup_cost_total = runs_per_year * self.S
        holding_cost_total = avg_inventory * self.H
        total_cost = production_cost + setup_cost_total + holding_cost_total

        # Cycle time
        cycle_time_days = 365 / runs_per_year

        return {
            'epq': round(epq, 2),
            'runs_per_year': round(runs_per_year, 2),
            'production_time_days': round(production_time, 2),
            'cycle_time_days': round(cycle_time_days, 2),
            'max_inventory': round(max_inventory, 2),
            'avg_inventory': round(avg_inventory, 2),
            'total_annual_cost': round(total_cost, 2),
            'production_cost': round(production_cost, 2),
            'setup_cost': round(setup_cost_total, 2),
            'holding_cost': round(holding_cost_total, 2),
            'utilization': round((self.D / self.p) * 100, 2)
        }

    def simulate_inventory_cycle(self, num_cycles: int = 3) -> pd.DataFrame:
        """
        Simulate inventory levels over multiple production cycles

        Returns DataFrame with daily inventory levels
        """

        result = self.calculate_epq()
        epq = result['epq']
        cycle_time = result['cycle_time_days']
        production_time = result['production_time_days']

        daily_demand = self.D / 365
        daily_production = self.p / 365

        inventory_data = []
        current_inventory = 0

        total_days = int(cycle_time * num_cycles)

        for day in range(total_days):
            cycle_day = day % cycle_time

            # During production phase
            if cycle_day < production_time:
                # Inventory increases by net production
                current_inventory += (daily_production - daily_demand)
            else:
                # Only consuming inventory
                current_inventory -= daily_demand

            # Prevent negative inventory (numerical precision)
            current_inventory = max(0, current_inventory)

            inventory_data.append({
                'day': day,
                'cycle': day // cycle_time + 1,
                'cycle_day': cycle_day,
                'inventory': current_inventory,
                'producing': cycle_day < production_time
            })

        return pd.DataFrame(inventory_data)

    def plot_inventory_cycle(self, num_cycles: int = 3):
        """Visualize inventory levels over production cycles"""

        df = self.simulate_inventory_cycle(num_cycles)
        result = self.calculate_epq()

        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10))

        # Plot 1: Inventory over time
        production_periods = df[df['producing'] == True]
        consumption_periods = df[df['producing'] == False]

        ax1.plot(df['day'], df['inventory'], linewidth=2, color='blue')
        ax1.fill_between(production_periods['day'], 0, production_periods['inventory'],
                         alpha=0.3, color='green', label='Production Phase')
        ax1.axhline(y=result['avg_inventory'], color='red', linestyle='--',
                   linewidth=2, label=f"Avg Inventory = {result['avg_inventory']:.0f}")
        ax1.axhline(y=result['max_inventory'], color='orange', linestyle='--',
                   linewidth=2, label=f"Max Inventory = {result['max_inventory']:.0f}")

        ax1.set_xlabel('Day', fontsize=12)
        ax1.set_ylabel('Inventory Level (units)', fontsize=12)
        ax1.set_title('EPQ Inventory Cycle', fontsize=14, fontweight='bold')
        ax1.legend(fontsize=10)
        ax1.grid(True, alpha=0.3)

        # Plot 2: Single cycle detail
        single_cycle = df[df['cycle'] == 1]
        ax2.plot(single_cycle['cycle_day'], single_cycle['inventory'],
                linewidth=3, color='blue', marker='o', markersize=4)
        ax2.axvline(x=result['production_time_days'], color='red',
                   linestyle='--', linewidth=2,
                   label=f"Production Time = {result['production_time_days']:.1f} days")
        ax2.fill_between(single_cycle['cycle_day'], 0, single_cycle['inventory'],
                        where=single_cycle['producing'], alpha=0.3, color='green',
                        label='Producing')
        ax2.fill_between(single_cycle['cycle_day'], 0, single_cycle['inventory'],
                        where=~single_cycle['producing'], alpha=0.3, color='red',
                        label='Only Consuming')

        ax2.set_xlabel('Days in Cycle', fontsize=12)
        ax2.set_ylabel('Inventory Level (units)', fontsize=12)
        ax2.set_title('Single Production Cycle Detail', fontsize=14, fontweight='bold')
        ax2.legend(fontsize=10)
        ax2.grid(True, alpha=0.3)

        plt.tight_layout()
        return plt


# Example: EPQ
def example_epq():
    """Example: Economic Production Quantity calculation"""

    model = EPQModel(
        annual_demand=10000,       # 10,000 units/year demand
        production_rate=50000,     # Can produce 50,000 units/year
        unit_cost=50,              # $50 per unit
        setup_cost=500,            # $500 setup cost per run
        holding_cost_rate=0.25     # 25% holding cost
    )

    result = model.calculate_epq()

    print("\n" + "=" * 70)
    print("ECONOMIC PRODUCTION QUANTITY (EPQ) ANALYSIS")
    print("=" * 70)

    print(f"\nInput Parameters:")
    print(f"  Annual Demand: {model.D:,} units/year")
    print(f"  Production Rate: {model.p:,} units/year")
    print(f"  Unit Cost: ${model.C:.2f}")
    print(f"  Setup Cost: ${model.S:.2f}")
    print(f"  Holding Cost Rate: {model.r:.1%}")

    print(f"\n{'Optimal Production Quantity (EPQ):':<40} {result['epq']:>15,.0f} units")
    print(f"{'Production Runs per Year:':<40} {result['runs_per_year']:>15,.2f} runs")
    print(f"{'Days Between Production Runs:':<40} {result['cycle_time_days']:>15,.1f} days")
    print(f"{'Production Time per Run:':<40} {result['production_time_days']:>15,.1f} days")

    print(f"\n{'Inventory Levels:':<40}")
    print(f"  {'Maximum Inventory:':<38} {result['max_inventory']:>15,.0f} units")
    print(f"  {'Average Inventory:':<38} {result['avg_inventory']:>15,.0f} units")

    print(f"\n{'Cost Breakdown:':<40}")
    print(f"  {'Production Cost:':<38} ${result['production_cost']:>15,.2f}")
    print(f"  {'Setup Cost:':<38} ${result['setup_cost']:>15,.2f}")
    print(f"  {'Holding Cost:':<38} ${result['holding_cost']:>15,.2f}")
    print(f"  {'-'*55}")
    print(f"  {'Total Annual Cost:':<38} ${result['total_annual_cost']:>15,.2f}")

    print(f"\n{'Production Capacity Utilization:':<40} {result['utilization']:>15,.1f}%")

    # Plot
    model.plot_inventory_cycle(num_cycles=3)
    plt.savefig('/tmp/epq_inventory_cycle.png', dpi=300, bbox_inches='tight')
    print(f"\nInventory cycle plot saved to /tmp/epq_inventory_cycle.png")

    return model, result


if __name__ == "__main__":
    example_epq()

EOQ with Planned Backorders

Backorder Model

When backorders are allowed and incur a penalty cost, it may be economical to deliberately plan for stockouts.

Decision Variables:

  • Q = Order quantity
  • S = Maximum inventory level (< Q)
  • Q - S = Planned backorder quantity
class EOQWithBackorders:
    """
    EOQ model with planned backorders

    Allows intentional stockouts when backorder cost is lower than holding cost
    """

    def __init__(self, annual_demand: float, unit_cost: float,
                 ordering_cost: float, holding_cost_rate: float,
                 backorder_cost_rate: float):
        """
        Parameters:
        -----------
        annual_demand : float
            Annual demand in units
        unit_cost : float
            Cost per unit ($)
        ordering_cost : float
            Fixed cost per order ($)
        holding_cost_rate : float
            Annual holding cost as fraction of unit cost
        backorder_cost_rate : float
            Annual backorder cost per unit ($/unit/year)
        """
        self.D = annual_demand
        self.C = unit_cost
        self.S_cost = ordering_cost
        self.H = unit_cost * holding_cost_rate
        self.B = backorder_cost_rate

    def calculate_optimal(self) -> Dict:
        """
        Calculate optimal order quantity and maximum inventory level

        Formulas:
        Q* = √(2DS/H) × √((H+B)/B)
        S* = Q* × (B/(H+B))

        Where S* is the maximum inventory level (peak before stockout)
        """

        # Basic EOQ (without backorders)
        eoq_basic = np.sqrt((2 * self.D * self.S_cost) / self.H)

        # Optimal order quantity with backorders
        Q_opt = eoq_basic * np.sqrt((self.H + self.B) / self.B)

        # Maximum inventory level
        S_opt = Q_opt * (self.B / (self.H + self.B))

        # Maximum backorder level
        backorder_max = Q_opt - S_opt

        # Time fractions
        time_with_inventory = S_opt / self.D  # years
        time_with_backorders = backorder_max / self.D  # years
        cycle_time = Q_opt / self.D  # years

        # Cost calculation
        orders_per_year = self.D / Q_opt
        ordering_cost = orders_per_year * self.S_cost

        # Average inventory (triangular distribution)
        avg_inventory = (S_opt ** 2) / (2 * Q_opt)
        holding_cost = avg_inventory * self.H

        # Average backorders
        avg_backorders = (backorder_max ** 2) / (2 * Q_opt)
        backorder_cost_total = avg_backorders * self.B

        purchase_cost = self.D * self.C
        total_cost = purchase_cost + ordering_cost + holding_cost + backorder_cost_total

        # Compare with basic EOQ (no backorders)
        cost_basic = (purchase_cost +
                     (self.D / eoq_basic) * self.S_cost +
                     (eoq_basic / 2) * self.H)

        savings = cost_basic - total_cost
        savings_pct = (savings / cost_basic) * 100

        return {
            'order_quantity': round(Q_opt, 2),
            'max_inventory': round(S_opt, 2),
            'max_backorders': round(backorder_max, 2),
            'orders_per_year': round(orders_per_year, 2),
            'cycle_time_days': round(cycle_time * 365, 2),
            'time_with_inventory_days': round(time_with_inventory * 365, 2),
            'time_with_backorders_days': round(time_with_backorders * 365, 2),
            'avg_inventory': round(avg_inventory, 2),
            'avg_backorders': round(avg_backorders, 2),
            'total_cost': round(total_cost, 2),
            'ordering_cost': round(ordering_cost, 2),
            'holding_cost': round(holding_cost, 2),
            'backorder_cost': round(backorder_cost_total, 2),
            'cost_without_backorders': round(cost_basic, 2),
            'savings': round(savings, 2),
            'savings_pct': round(savings_pct, 2)
        }

    def plot_backorder_cycle(self):
        """Visualize inventory cycle with planned backorders"""

        result = self.calculate_optimal()
        Q = result['order_quantity']
        S = result['max_inventory']

        # Time points (in fractions of year)
        t1 = S / self.D  # Time to deplete inventory
        t2 = Q / self.D  # Full cycle time

        # Convert to days for plotting
        t1_days = t1 * 365
        t2_days = t2 * 365

        # Create time array for one cycle
        t_positive = np.linspace(0, t1_days, 100)
        t_negative = np.linspace(t1_days, t2_days, 100)

        # Inventory levels
        inv_positive = S - (self.D / 365) * t_positive
        inv_negative = -(self.D / 365) * (t_negative - t1_days)

        plt.figure(figsize=(14, 8))

        # Plot inventory (positive)
        plt.fill_between(t_positive, 0, inv_positive, alpha=0.3, color='green',
                        label='On-hand Inventory')
        plt.plot(t_positive, inv_positive, linewidth=3, color='green')

        # Plot backorders (negative)
        plt.fill_between(t_negative, 0, inv_negative, alpha=0.3, color='red',
                        label='Backorders')
        plt.plot(t_negative, inv_negative, linewidth=3, color='red')

        # Mark key points
        plt.plot(0, S, 'go', markersize=12, label=f'Order Arrives: +{S:.0f} units')
        plt.plot(t1_days, 0, 'yo', markersize=12, label='Stockout Begins')
        plt.plot(t2_days, -result['max_backorders'], 'ro', markersize=12,
                label=f"Max Backorder: {result['max_backorders']:.0f} units")

        # Add average lines
        plt.axhline(y=result['avg_inventory'], color='green', linestyle='--',
                   linewidth=2, alpha=0.7, label=f"Avg Inventory: {result['avg_inventory']:.1f}")
        plt.axhline(y=-result['avg_backorders'], color='red', linestyle='--',
                   linewidth=2, alpha=0.7, label=f"Avg Backorders: {result['avg_backorders']:.1f}")

        plt.axhline(y=0, color='black', linewidth=1)
        plt.axvline(x=t1_days, color='gray', linestyle=':', linewidth=2)

        plt.xlabel('Days', fontsize=12)
        plt.ylabel('Inventory Level (units)', fontsize=12)
        plt.title('EOQ with Planned Backorders - Inventory Cycle',
                 fontsize=14, fontweight='bold')
        plt.legend(fontsize=10, loc='upper right')
        plt.grid(True, alpha=0.3)
        plt.tight_layout()

        return plt


# Example: Backorders
def example_backorders():
    """Example: EOQ with planned backorders"""

    model = EOQWithBackorders(
        annual_demand=10000,
        unit_cost=50,
        ordering_cost=100,
        holding_cost_rate=0.25,
        backorder_cost_rate=5.0  # $5 per unit per year backordered
    )

    result = model.calculate_optimal()

    print("\n" + "=" * 70)
    print("EOQ WITH PLANNED BACKORDERS ANALYSIS")
    print("=" * 70)

    print(f"\nInput Parameters:")
    print(f"  Annual Demand: {model.D:,} units")
    print(f"  Holding Cost: ${model.H:.2f}/unit/year")
    print(f"  Backorder Cost: ${model.B:.2f}/unit/year")
    print(f"  Ordering Cost: ${model.S_cost:.2f}/order")

    print(f"\n{'Optimal Policy:':<45}")
    print(f"  {'Order Quantity:':<43} {result['order_quantity']:>15,.0f} units")
    print(f"  {'Maximum Inventory (before stockout):':<43} {result['max_inventory']:>15,.0f} units")
    print(f"  {'Maximum Backorders:':<43} {result['max_backorders']:>15,.0f} units")

    print(f"\n{'Cycle Characteristics:':<45}")
    print(f"  {'Orders per Year:':<43} {result['orders_per_year']:>15,.2f}")
    print(f"  {'Cycle Time:':<43} {result['cycle_time_days']:>15,.1f} days")
    print(f"  {'Time with Inventory:':<43} {result['time_with_inventory_days']:>15,.1f} days")
    print(f"  {'Time with Backorders:':<43} {result['time_with_backorders_days']:>15,.1f} days")

    print(f"\n{'Average Levels:':<45}")
    print(f"  {'Average Inventory:':<43} {result['avg_inventory']:>15,.1f} units")
    print(f"  {'Average Backorders:':<43} {result['avg_backorders']:>15,.1f} units")

    print(f"\n{'Cost Analysis:':<45}")
    print(f"  {'Ordering Cost:':<43} ${result['ordering_cost']:>15,.2f}")
    print(f"  {'Holding Cost:':<43} ${result['holding_cost']:>15,.2f}")
    print(f"  {'Backorder Cost:':<43} ${result['backorder_cost']:>15,.2f}")
    print(f"  {'-'*60}")
    print(f"  {'Total Annual Cost (with backorders):':<43} ${result['total_cost']:>15,.2f}")
    print(f"  {'Total Cost without Backorders:':<43} ${result['cost_without_backorders']:>15,.2f}")
    print(f"  {'-'*60}")
    print(f"  {'Annual Savings:':<43} ${result['savings']:>15,.2f}")
    print(f"  {'Savings Percentage:':<43} {result['savings_pct']:>15,.1f}%")

    # Plot
    model.plot_backorder_cycle()
    plt.savefig('/tmp/eoq_backorders.png', dpi=300, bbox_inches='tight')
    print(f"\nBackorder cycle plot saved to /tmp/eoq_backorders.png")

    return model, result


if __name__ == "__main__":
    example_backorders()

Tools & Libraries

Python Libraries

Numerical & Scientific:

  • numpy: Array operations, mathematical functions
  • scipy: Optimization, statistical distributions
  • pandas: Data manipulation and analysis

Optimization:

  • pulp: Linear programming for constrained EOQ
  • scipy.optimize: Non-linear optimization

Visualization:

  • matplotlib: Plotting cost curves, inventory cycles
  • seaborn: Statistical visualizations
  • plotly: Interactive dashboards

Commercial Software

ERP Systems with EOQ:

  • SAP: Material Requirements Planning (MRP) with lot sizing
  • Oracle EBS: Order Management with EOQ rules
  • Microsoft Dynamics: Inventory optimization modules
  • NetSuite: Demand planning with EOQ

Specialized Inventory Planning:

  • Blue Yonder: Advanced inventory optimization
  • Logility: Lot sizing and replenishment planning
  • Kinaxis RapidResponse: Inventory policy optimization
  • Llamasoft: Supply chain design with inventory analysis

Common Challenges & Solutions

Challenge: Uncertain Demand

Problem:

  • Classic EOQ assumes constant, known demand
  • Real demand is variable and uncertain

Solutions:

  • Use expected demand D for EOQ calculation
  • Add safety stock for demand variability (see stochastic-inventory-models)
  • Implement periodic EOQ recalculation (monthly/quarterly)
  • Consider robust optimization with demand scenarios
  • Use (Q, r) continuous review policy with reorder point

Challenge: Unknown Holding Cost

Problem:

  • Difficult to estimate true holding cost rate
  • Includes capital, storage, obsolescence, damage

Solutions:

  • Use industry benchmarks (typically 15-35% of unit cost)
  • Calculate weighted average cost of capital (WACC) as minimum
  • Add storage costs ($/sq ft × space per unit)
  • Include insurance and obsolescence
  • Perform sensitivity analysis on holding cost rate
  • Start with 25% as reasonable default

Challenge: Quantity Constraints

Problem:

  • Supplier MOQs may differ from EOQ
  • Packaging constraints (must order in multiples)
  • Storage capacity limits

Solutions:

  • If MOQ > EOQ: Order MOQ (accept higher holding cost)
  • If MOQ < EOQ: Order EOQ rounded to package size
  • For capacity constraints: Use constrained optimization
  • Negotiate with supplier for smaller MOQs
  • Consider multi-item EOQ with shared capacity constraint

Challenge: Multiple Items with Budget Constraints

Problem:

  • EOQ calculated independently for each SKU
  • Total budget or storage capacity is limited

Solutions:

  • Formulate as constrained optimization problem
  • Use Lagrange multipliers for continuous relaxation
  • Implement ABC analysis - focus on A items
  • Use dynamic programming for exact solution
  • Consider proportional allocation based on EOQ ratios
from scipy.optimize import minimize

def multi_item_eoq_constrained(items: List[Dict], budget: float) -> Dict:
    """
    Multi-item EOQ with budget constraint

    items: list of dicts with keys: demand, ordering_cost, holding_cost
    budget: total budget for average inventory investment
    """

    n = len(items)

    def objective(Q):
        """Minimize total relevant cost"""
        total_cost = 0
        for i, q in enumerate(Q):
            item = items[i]
            ordering_cost = (item['demand'] / q) * item['ordering_cost']
            holding_cost = (q / 2) * item['holding_cost']
            total_cost += ordering_cost + holding_cost
        return total_cost

    def budget_constraint(Q):
        """Average inventory value <= budget"""
        total_inventory_value = 0
        for i, q in enumerate(Q):
            avg_inventory = q / 2
            total_inventory_value += avg_inventory * items[i]['unit_cost']
        return budget - total_inventory_value

    # Initial guess: unconstrained EOQ
    Q0 = [np.sqrt(2 * item['demand'] * item['ordering_cost'] / item['holding_cost'])
          for item in items]

    # Constraints
    cons = [{'type': 'ineq', 'fun': budget_constraint}]

    # Bounds: positive quantities
    bounds = [(1, None) for _ in range(n)]

    # Solve
    result = minimize(objective, Q0, method='SLSQP', bounds=bounds, constraints=cons)

    return {
        'optimal_quantities': result.x,
        'total_cost': result.fun,
        'success': result.success
    }

Challenge: Time-Varying Parameters

Problem:

  • Demand, costs, or prices change over time
  • Seasonal demand patterns
  • Inflation

Solutions:

  • Recalculate EOQ periodically (monthly/quarterly)
  • Use rolling average demand for D
  • Consider finite horizon lot-sizing models (see dynamic-lot-sizing)
  • Implement dynamic EOQ with forecast updates
  • For seasonality: Calculate separate EOQs per season

Challenge: Lead Time Uncertainty

Problem:

  • EOQ doesn't account for lead time variability
  • Risk of stockouts during replenishment

Solutions:

  • EOQ determines Q, separate reorder point (r) handles lead time
  • Calculate safety stock for lead time variability
  • Use (Q, r) policy: Order Q when inventory hits r
  • See stochastic-inventory-models for safety stock calculation
  • Monitor supplier performance and adjust lead time estimates

Output Format

EOQ Analysis Report

Executive Summary:

  • Current ordering practice: Order 2,000 units every 73 days
  • Recommended EOQ: 1,265 units every 46 days
  • Annual savings: $3,450 (12% cost reduction)
  • Implementation: Adjust order quantities and frequency

Input Parameters:

ParameterValue
Annual Demand10,000 units
Unit Cost$50.00
Ordering Cost$100/order
Holding Cost Rate25%/year
Holding Cost$12.50/unit/year

Optimal Policy:

MetricCurrentOptimal (EOQ)Improvement
Order Quantity2,0001,265N/A
Orders per Year57.9+58%
Days Between Orders7346-37%
Avg Inventory1,000633-37%
Total Annual Cost$531,250$527,800-$3,450 (-0.65%)

Cost Breakdown:

Cost ComponentCurrentOptimal (EOQ)Difference
Purchase Cost$500,000$500,000$0
Ordering Cost$500$790+$290
Holding Cost$12,500$7,910-$4,590
Total$513,000$508,700-$4,300

Reorder Point:

  • Lead time: 14 days
  • Average daily demand: 27.4 units
  • Lead time demand: 384 units
  • Recommended reorder point: 385 units (with zero safety stock)

Implementation Recommendations:

  1. Adjust order quantity to 1,265 units (round to 1,250 if packaging constraints)
  2. Set reorder point at 385 units
  3. Monitor inventory and place orders when reaching reorder point
  4. Review and recalculate EOQ quarterly
  5. Consider demand variability for safety stock adjustment

Questions to Ask

If you need more context:

  1. What is the annual demand for this item? (units/year)
  2. What is the cost per unit?
  3. What is the cost to place an order? (fixed cost per order)
  4. What is the inventory holding cost rate? (% of unit cost per year)
  5. Are there quantity discounts available from the supplier?
  6. Is this item purchased or produced internally?
  7. If produced: What is the production rate?
  8. Are stockouts acceptable? If yes, what is the backorder penalty cost?
  9. What is the lead time from order to delivery?
  10. Are there any constraints? (MOQ, storage capacity, budget limits)

Related Skills

  • inventory-optimization: Comprehensive inventory management framework
  • lot-sizing-problems: Multi-period lot-sizing models
  • dynamic-lot-sizing: Time-varying demand lot-sizing
  • stochastic-inventory-models: Probabilistic inventory models with uncertainty
  • newsvendor-problem: Single-period inventory decisions
  • multi-echelon-inventory: Network-wide inventory optimization
  • demand-forecasting: Demand estimation for EOQ inputs
  • supply-chain-analytics: Performance metrics and KPIs

Electronics Supply Chain

You are an expert in electronics manufacturing supply chain management and semiconductor operations. Your goal is to help optimize complex global supply networks, manage component sourcing and allocation, implement efficient assembly operations, and navigate the unique challenges of electronics manufacturing.

Initial Assessment

Before optimizing electronics supply chains, understand:

  1. Manufacturing Model

    • OEM, ODM, EMS, or internal manufacturing?
    • Product types? (consumer electronics, industrial, automotive, medical)
    • Production volume? (high-volume, mid-volume, prototype)
    • Manufacturing approach? (make-to-stock, make-to-order, configure-to-order)
    • Where in value chain? (component, module, finished product)
  2. Component Profile

    • Semiconductor dependency level? (ICs, processors, memory, analog)
    • Passive components volume? (resistors, capacitors, connectors)
    • Long lead-time components? (FPGAs, custom ASICs, displays)
    • Single-source vs. multi-source components?
    • Allocation status? (open market, allocated, allocated critical)
  3. Supply Chain Structure

    • Geographic footprint? (Asia-heavy, diversified, nearshore)
    • Number of tier suppliers and CMs?
    • Direct vs. distributor sourcing?
    • Consignment vs. turnkey model?
    • VMI (Vendor Managed Inventory) programs?
  4. Current Challenges

    • Component availability and allocation issues?
    • Lead time volatility?
    • Excess and obsolete (E&O) inventory?
    • Product lifecycle management?
    • Cost reduction targets?

Electronics Supply Chain Framework

Value Chain Structure

Electronics Manufacturing Ecosystem:

Raw Materials (Silicon, Metals, Plastics)
  ↓
Component Manufacturers (Semiconductors, Passives, Connectors)
  ↓
Distributors / Brokers
  ↓
EMS/ODM (Contract Manufacturers)
  ↓
OEM (Brand Owners)
  ↓
Distribution / Retail
  ↓
End Customers

Key Players by Tier:

  • Component Manufacturers: Intel, Samsung, TSMC, TI, Analog Devices, Infineon
  • Distributors: Arrow, Avnet, Digi-Key, Mouser, Future Electronics
  • EMS/ODM: Foxconn, Flex, Jabil, Pegatron, Wistron, Quanta
  • OEMs: Apple, Dell, HP, Cisco, Huawei, Lenovo

Component Sourcing & Allocation Management

Allocation Strategy

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

class ComponentAllocationManager:
    """
    Manage component allocation in constrained supply environment
    """

    def __init__(self, components_df):
        """
        Initialize allocation manager

        Parameters:
        - components_df: component data with lead times, allocation status
        """
        self.components = components_df
        self.allocation_tiers = {
            'strategic': 1,
            'preferred': 2,
            'standard': 3,
            'new': 4
        }

    def assess_allocation_risk(self, bom_df, production_plan):
        """
        Assess component allocation risk for production plan

        Parameters:
        - bom_df: Bill of Materials
        - production_plan: planned production volumes by period

        Returns:
        - risk assessment by component
        """

        risk_assessment = []

        for idx, component in bom_df.iterrows():
            part_number = component['part_number']
            qty_per_unit = component['quantity_per_unit']

            # Get component details
            comp_info = self.components[
                self.components['part_number'] == part_number
            ].iloc[0] if len(self.components[
                self.components['part_number'] == part_number
            ]) > 0 else None

            if comp_info is None:
                continue

            # Calculate requirements
            total_requirement = production_plan['units'].sum() * qty_per_unit

            # Allocation status
            allocation_status = comp_info.get('allocation_status', 'open')
            lead_time_weeks = comp_info.get('lead_time_weeks', 12)
            available_inventory = comp_info.get('available_inventory', 0)
            allocated_qty = comp_info.get('allocated_qty', 0)

            # Calculate risk score
            risk_score = self._calculate_risk_score(
                allocation_status,
                lead_time_weeks,
                total_requirement,
                available_inventory + allocated_qty
            )

            risk_assessment.append({
                'part_number': part_number,
                'description': comp_info.get('description', ''),
                'manufacturer': comp_info.get('manufacturer', ''),
                'total_requirement': total_requirement,
                'available_inventory': available_inventory,
                'allocated_qty': allocated_qty,
                'shortfall': max(0, total_requirement - available_inventory - allocated_qty),
                'allocation_status': allocation_status,
                'lead_time_weeks': lead_time_weeks,
                'risk_score': risk_score,
                'risk_category': self._categorize_risk(risk_score)
            })

        return pd.DataFrame(risk_assessment).sort_values('risk_score', ascending=False)

    def _calculate_risk_score(self, allocation_status, lead_time, requirement, supply):
        """Calculate component risk score (0-100)"""

        # Allocation multiplier
        allocation_multiplier = {
            'open': 1.0,
            'watch': 2.0,
            'allocated': 4.0,
            'critical': 8.0,
            'unobtainable': 10.0
        }.get(allocation_status, 1.0)

        # Lead time factor (longer = higher risk)
        lt_factor = min(lead_time / 52, 2.0)  # Cap at 2x

        # Supply coverage (weeks)
        coverage = (supply / requirement) if requirement > 0 else 999
        coverage_factor = max(0, 2 - coverage)  # Higher if coverage < 2x

        risk_score = (allocation_multiplier * 20 +
                     lt_factor * 20 +
                     coverage_factor * 30)

        return min(100, risk_score)

    def _categorize_risk(self, risk_score):
        """Categorize risk level"""
        if risk_score >= 70:
            return 'critical'
        elif risk_score >= 50:
            return 'high'
        elif risk_score >= 30:
            return 'medium'
        else:
            return 'low'

    def optimize_allocation_strategy(self, risk_assessment, supplier_relationships):
        """
        Generate allocation strategy recommendations

        Parameters:
        - risk_assessment: output from assess_allocation_risk
        - supplier_relationships: customer tier with suppliers

        Returns:
        - recommended actions by component
        """

        recommendations = []

        critical_parts = risk_assessment[risk_assessment['risk_category'] == 'critical']

        for idx, part in critical_parts.iterrows():
            actions = []

            # Determine customer tier
            customer_tier = supplier_relationships.get(
                part['manufacturer'], 'standard'
            )

            # Strategy based on risk and relationship
            if part['allocation_status'] == 'critical':
                actions.append('escalate_to_executive_level')
                actions.append('request_emergency_allocation')
                actions.append('explore_authorized_distributors')

            if part['lead_time_weeks'] > 26:
                actions.append('increase_forecast_horizon')
                actions.append('commit_to_longer_term_contract')

            if part['shortfall'] > 0:
                actions.append('identify_alternative_components')
                actions.append('engage_design_engineering_for_redesign')
                actions.append('search_broker_market')

            if customer_tier == 'new':
                actions.append('establish_strategic_relationship')
                actions.append('increase_volumes_to_gain_priority')

            recommendations.append({
                'part_number': part['part_number'],
                'manufacturer': part['manufacturer'],
                'risk_category': part['risk_category'],
                'customer_tier': customer_tier,
                'recommended_actions': actions,
                'priority': 'immediate' if part['risk_score'] > 80 else 'urgent'
            })

        return pd.DataFrame(recommendations)


# Example usage
components_data = pd.DataFrame({
    'part_number': ['IC_001', 'IC_002', 'CAP_001', 'RES_001'],
    'description': ['MCU STM32', 'Power IC', 'MLCC 10uF', 'Resistor 10K'],
    'manufacturer': ['STMicro', 'TI', 'Murata', 'Yageo'],
    'allocation_status': ['allocated', 'critical', 'open', 'open'],
    'lead_time_weeks': [32, 52, 8, 4],
    'available_inventory': [5000, 0, 100000, 500000],
    'allocated_qty': [10000, 5000, 0, 0]
})

bom = pd.DataFrame({
    'part_number': ['IC_001', 'IC_002', 'CAP_001', 'RES_001'],
    'quantity_per_unit': [1, 1, 12, 45]
})

production_plan = pd.DataFrame({
    'month': ['2025-02', '2025-03', '2025-04'],
    'units': [10000, 12000, 15000]
})

manager = ComponentAllocationManager(components_data)
risk_assessment = manager.assess_allocation_risk(bom, production_plan)

print("Component Risk Assessment:")
print(risk_assessment[['part_number', 'allocation_status', 'shortfall',
                       'risk_score', 'risk_category']])

PCB Assembly Optimization

Line Balancing for SMT Lines

class SMTLineOptimizer:
    """
    Optimize Surface Mount Technology (SMT) line operations
    """

    def __init__(self, line_config):
        """
        Initialize SMT line optimizer

        Parameters:
        - line_config: SMT line configuration (machines, feeders, speed)
        """
        self.line_config = line_config

    def calculate_line_capacity(self, board_config):
        """
        Calculate SMT line capacity for given board

        Parameters:
        - board_config: PCB specifications and component placement

        Returns:
        - theoretical capacity (boards/hour)
        """

        # Component placement time
        num_components = board_config['component_count']
        avg_placement_time_sec = board_config.get('avg_placement_time', 0.3)

        # Machine parameters
        num_placement_heads = self.line_config.get('placement_heads', 8)
        machine_efficiency = self.line_config.get('efficiency', 0.85)

        # Calculate placement time per board
        placement_time = (num_components * avg_placement_time_sec) / num_placement_heads

        # Add process times
        screen_print_time = 15  # seconds
        reflow_time = 180  # seconds
        inspection_time = 30  # seconds
        board_handling_time = 10  # seconds

        total_cycle_time = (placement_time + screen_print_time +
                           reflow_time + inspection_time + board_handling_time)

        # Apply efficiency factor
        effective_cycle_time = total_cycle_time / machine_efficiency

        # Capacity (boards per hour)
        capacity_per_hour = 3600 / effective_cycle_time

        return {
            'capacity_boards_per_hour': capacity_per_hour,
            'cycle_time_seconds': effective_cycle_time,
            'placement_time': placement_time,
            'bottleneck': self._identify_bottleneck(
                placement_time, screen_print_time, reflow_time
            )
        }

    def _identify_bottleneck(self, placement_time, print_time, reflow_time):
        """Identify process bottleneck"""
        times = {
            'placement': placement_time,
            'screen_print': print_time,
            'reflow': reflow_time
        }
        return max(times, key=times.get)

    def optimize_feeder_setup(self, bom_df, feeder_slots=120):
        """
        Optimize feeder setup for component loading

        Parameters:
        - bom_df: Bill of Materials with component usage
        - feeder_slots: available feeder slots on machine

        Returns:
        - feeder assignment plan
        """

        # Sort components by usage frequency
        bom_sorted = bom_df.sort_values('quantity_per_board', ascending=False)

        # Assign to feeders (most used components get priority positions)
        feeder_assignments = []

        for idx, component in bom_sorted.iterrows():
            if idx < feeder_slots:
                # Optimal position: center positions for high-usage parts
                if idx < 20:
                    position = 60 + (idx - 10)  # Center positions
                else:
                    position = idx

                feeder_assignments.append({
                    'part_number': component['part_number'],
                    'feeder_position': position,
                    'quantity_per_board': component['quantity_per_board'],
                    'priority': 'high' if idx < 20 else 'medium'
                })
            else:
                # Bulk feeders or manual loading required
                feeder_assignments.append({
                    'part_number': component['part_number'],
                    'feeder_position': None,
                    'quantity_per_board': component['quantity_per_board'],
                    'priority': 'low',
                    'loading_method': 'manual_or_bulk'
                })

        return pd.DataFrame(feeder_assignments)

    def calculate_changeover_time(self, current_bom, next_bom, feeder_change_time=60):
        """
        Calculate line changeover time between products

        Parameters:
        - current_bom: current product BOM
        - next_bom: next product BOM
        - feeder_change_time: seconds per feeder change

        Returns:
        - estimated changeover time
        """

        # Components unique to each product
        current_parts = set(current_bom['part_number'])
        next_parts = set(next_bom['part_number'])

        # Components to remove and add
        parts_to_remove = current_parts - next_parts
        parts_to_add = next_parts - current_parts

        total_changes = len(parts_to_remove) + len(parts_to_add)

        # Changeover time
        feeder_changeover = total_changes * feeder_change_time
        program_change = 300  # 5 minutes for program change
        first_article_inspection = 600  # 10 minutes

        total_changeover = feeder_changeover + program_change + first_article_inspection

        return {
            'total_changeover_minutes': total_changeover / 60,
            'feeder_changes': total_changes,
            'parts_to_remove': len(parts_to_remove),
            'parts_to_add': len(parts_to_add),
            'common_parts': len(current_parts & next_parts)
        }


# Example
line_config = {
    'placement_heads': 8,
    'efficiency': 0.85,
    'feeder_slots': 120
}

board_config = {
    'component_count': 450,
    'avg_placement_time': 0.3,
    'board_size': '300x200mm'
}

optimizer = SMTLineOptimizer(line_config)
capacity = optimizer.calculate_line_capacity(board_config)

print(f"Line Capacity: {capacity['capacity_boards_per_hour']:.1f} boards/hour")
print(f"Cycle Time: {capacity['cycle_time_seconds']:.1f} seconds")
print(f"Bottleneck: {capacity['bottleneck']}")

Lead Time Management

Dynamic Lead Time Planning

class LeadTimeManager:
    """
    Manage component lead times and procurement planning
    """

    def __init__(self, components_df):
        self.components = components_df

    def calculate_procurement_dates(self, production_schedule, bom_df):
        """
        Calculate when to order components based on lead times

        Parameters:
        - production_schedule: planned production dates
        - bom_df: Bill of Materials with quantities

        Returns:
        - component order schedule
        """

        procurement_schedule = []

        for idx, production in production_schedule.iterrows():
            production_date = production['production_date']
            product_id = production['product_id']
            quantity = production['quantity']

            # Get BOM for this product
            product_bom = bom_df[bom_df['product_id'] == product_id]

            for _, component in product_bom.iterrows():
                part_number = component['part_number']
                qty_per_unit = component['quantity_per_unit']
                total_needed = quantity * qty_per_unit

                # Get component lead time
                comp_info = self.components[
                    self.components['part_number'] == part_number
                ].iloc[0]

                lead_time_weeks = comp_info['lead_time_weeks']
                safety_buffer_weeks = comp_info.get('safety_buffer_weeks', 2)

                # Calculate order date
                total_lead_time = timedelta(weeks=lead_time_weeks + safety_buffer_weeks)
                order_date = production_date - total_lead_time

                procurement_schedule.append({
                    'part_number': part_number,
                    'manufacturer': comp_info['manufacturer'],
                    'order_date': order_date,
                    'need_by_date': production_date,
                    'quantity': total_needed,
                    'lead_time_weeks': lead_time_weeks,
                    'production_order': product_id,
                    'days_until_order': (order_date - datetime.now()).days
                })

        return pd.DataFrame(procurement_schedule).sort_values('order_date')

    def simulate_lead_time_variability(self, component, order_quantity,
                                      num_simulations=1000):
        """
        Monte Carlo simulation of lead time variability

        Parameters:
        - component: component details with lead time distribution
        - order_quantity: quantity to order
        - num_simulations: number of Monte Carlo runs

        Returns:
        - lead time distribution and risk metrics
        """

        # Lead time distribution parameters
        lt_mean = component['lead_time_weeks']
        lt_std = component.get('lead_time_std', lt_mean * 0.2)

        # Simulate lead times
        simulated_lts = np.random.normal(lt_mean, lt_std, num_simulations)
        simulated_lts = np.maximum(simulated_lts, lt_mean * 0.5)  # Floor

        # Calculate percentiles
        p50 = np.percentile(simulated_lts, 50)
        p80 = np.percentile(simulated_lts, 80)
        p95 = np.percentile(simulated_lts, 95)

        return {
            'mean_lt_weeks': lt_mean,
            'p50_lt_weeks': p50,
            'p80_lt_weeks': p80,
            'p95_lt_weeks': p95,
            'recommended_buffer_weeks': p95 - lt_mean,
            'variability_coefficient': lt_std / lt_mean
        }


# Example
components_data = pd.DataFrame({
    'part_number': ['IC_001', 'IC_002'],
    'manufacturer': ['STMicro', 'TI'],
    'lead_time_weeks': [32, 52],
    'lead_time_std': [6, 12],
    'safety_buffer_weeks': [4, 8]
})

production_schedule = pd.DataFrame({
    'production_date': pd.to_datetime(['2025-06-01', '2025-07-01']),
    'product_id': ['PROD_A', 'PROD_A'],
    'quantity': [5000, 6000]
})

bom = pd.DataFrame({
    'product_id': ['PROD_A', 'PROD_A'],
    'part_number': ['IC_001', 'IC_002'],
    'quantity_per_unit': [1, 2]
})

lt_manager = LeadTimeManager(components_data)
procurement = lt_manager.calculate_procurement_dates(production_schedule, bom)

print("Procurement Schedule:")
print(procurement[['part_number', 'order_date', 'need_by_date',
                   'quantity', 'days_until_order']])

Excess & Obsolete (E&O) Management

class EOInventoryManager:
    """
    Manage excess and obsolete inventory in electronics
    """

    def __init__(self, inventory_df, bom_df, forecast_df):
        self.inventory = inventory_df
        self.bom = bom_df
        self.forecast = forecast_df

    def identify_excess_obsolete(self, time_horizon_months=12):
        """
        Identify excess and obsolete inventory

        Parameters:
        - time_horizon_months: planning horizon for demand

        Returns:
        - E&O classification by component
        """

        eo_analysis = []

        for idx, inv in self.inventory.iterrows():
            part_number = inv['part_number']
            on_hand_qty = inv['on_hand_quantity']
            unit_cost = inv['unit_cost']

            # Calculate future demand
            future_demand = self._calculate_future_demand(
                part_number, time_horizon_months
            )

            # Calculate excess
            excess_qty = max(0, on_hand_qty - future_demand)
            excess_value = excess_qty * unit_cost

            # Determine obsolescence risk
            lifecycle_status = inv.get('lifecycle_status', 'active')
            last_usage_date = inv.get('last_usage_date', datetime.now())
            months_since_use = (datetime.now() - last_usage_date).days / 30

            # Classification
            if lifecycle_status == 'discontinued' or months_since_use > 24:
                classification = 'obsolete'
            elif excess_qty > future_demand * 0.5 or months_since_use > 12:
                classification = 'excess'
            elif excess_qty > future_demand * 0.2:
                classification = 'watch'
            else:
                classification = 'normal'

            eo_analysis.append({
                'part_number': part_number,
                'on_hand_qty': on_hand_qty,
                'future_demand_12m': future_demand,
                'excess_qty': excess_qty,
                'excess_value': excess_value,
                'unit_cost': unit_cost,
                'lifecycle_status': lifecycle_status,
                'months_since_use': months_since_use,
                'classification': classification,
                'recommended_action': self._recommend_action(
                    classification, excess_qty, excess_value
                )
            })

        return pd.DataFrame(eo_analysis)

    def _calculate_future_demand(self, part_number, months):
        """Calculate future demand for component"""

        # Get products using this part
        products_using = self.bom[self.bom['part_number'] == part_number]

        total_demand = 0
        for _, product in products_using.iterrows():
            product_id = product['product_id']
            qty_per_unit = product['quantity_per_unit']

            # Get forecast for product
            product_forecast = self.forecast[
                self.forecast['product_id'] == product_id
            ]['forecast_units'].sum() if len(
                self.forecast[self.forecast['product_id'] == product_id]
            ) > 0 else 0

            total_demand += product_forecast * qty_per_unit

        return total_demand

    def _recommend_action(self, classification, excess_qty, excess_value):
        """Recommend disposition action"""

        if classification == 'obsolete':
            if excess_value > 50000:
                return 'scrap_with_recovery_value_analysis'
            else:
                return 'scrap_dispose'
        elif classification == 'excess':
            if excess_value > 100000:
                return 'sell_to_brokers_or_redistribute'
            elif excess_value > 10000:
                return 'return_to_supplier_negotiation'
            else:
                return 'consume_in_production_if_possible'
        elif classification == 'watch':
            return 'monitor_and_reduce_future_buys'
        else:
            return 'no_action_required'

    def calculate_eo_provision(self, eo_analysis):
        """
        Calculate accounting provision for E&O inventory

        Returns:
        - provision amount by category
        """

        provision_rates = {
            'normal': 0.0,
            'watch': 0.25,
            'excess': 0.50,
            'obsolete': 1.0
        }

        eo_analysis['provision_rate'] = eo_analysis['classification'].map(provision_rates)
        eo_analysis['provision_amount'] = (
            eo_analysis['excess_value'] * eo_analysis['provision_rate']
        )

        total_provision = eo_analysis['provision_amount'].sum()

        summary = eo_analysis.groupby('classification').agg({
            'excess_qty': 'sum',
            'excess_value': 'sum',
            'provision_amount': 'sum'
        })

        return {
            'total_provision': total_provision,
            'summary_by_classification': summary
        }


# Example would require full inventory, BOM, and forecast data

Product Lifecycle Management

New Product Introduction (NPI) Planning

class NPIManager:
    """
    Manage New Product Introduction process for electronics
    """

    def __init__(self):
        self.npi_phases = [
            'concept',
            'design',
            'prototype',
            'pilot',
            'ramp',
            'mass_production'
        ]

    def create_npi_timeline(self, product_spec, target_launch_date):
        """
        Create NPI timeline with key milestones

        Parameters:
        - product_spec: product specifications
        - target_launch_date: desired production start

        Returns:
        - detailed timeline with activities
        """

        # Standard phase durations (weeks)
        phase_durations = {
            'concept': 4,
            'design': 12,
            'prototype': 8,
            'pilot': 6,
            'ramp': 8,
            'mass_production': 0  # ongoing
        }

        # Adjust for product complexity
        complexity_factor = product_spec.get('complexity_factor', 1.0)

        timeline = []
        current_date = target_launch_date

        # Work backwards from launch
        for phase in reversed(self.npi_phases[:-1]):
            duration_weeks = phase_durations[phase] * complexity_factor
            phase_start = current_date - timedelta(weeks=duration_weeks)

            timeline.append({
                'phase': phase,
                'start_date': phase_start,
                'end_date': current_date,
                'duration_weeks': duration_weeks,
                'key_activities': self._get_phase_activities(phase),
                'deliverables': self._get_phase_deliverables(phase)
            })

            current_date = phase_start

        # Reverse to chronological order
        timeline.reverse()

        return pd.DataFrame(timeline)

    def _get_phase_activities(self, phase):
        """Get key activities for NPI phase"""

        activities = {
            'concept': ['Market research', 'Feature definition', 'Cost target'],
            'design': ['Schematic design', 'PCB layout', 'Component selection',
                      'DFM review'],
            'prototype': ['Prototype build', 'Functional testing', 'Design validation'],
            'pilot': ['Pilot run 100-500 units', 'Process validation',
                     'Supplier qualification'],
            'ramp': ['Ramp to volume', 'Yield optimization', 'Cost reduction']
        }

        return activities.get(phase, [])

    def _get_phase_deliverables(self, phase):
        """Get deliverables for NPI phase"""

        deliverables = {
            'concept': ['Product requirements document', 'Cost model'],
            'design': ['Final schematic', 'Gerber files', 'BOM', 'AVL'],
            'prototype': ['Working prototypes', 'Test reports', 'Design changes'],
            'pilot': ['Pilot build report', 'Qualified suppliers', 'Manufacturing docs'],
            'ramp': ['Volume production', 'Quality metrics', 'Cost targets met']
        }

        return deliverables.get(phase, [])

    def assess_component_risk_npi(self, bom_df, components_df):
        """
        Assess component risks for NPI

        Focus on:
        - Long lead time parts
        - Sole source components
        - Lifecycle risks
        - Allocation risks
        """

        risks = []

        for idx, component in bom_df.iterrows():
            part_number = component['part_number']

            # Get component details
            comp_info = components_df[
                components_df['part_number'] == part_number
            ].iloc[0]

            # Risk factors
            risk_factors = []
            risk_score = 0

            # Lead time risk
            if comp_info['lead_time_weeks'] > 26:
                risk_factors.append('long_lead_time_>6months')
                risk_score += 30

            # Sole source risk
            if comp_info.get('alternate_sources', 0) == 0:
                risk_factors.append('sole_source')
                risk_score += 25

            # Lifecycle risk
            if comp_info.get('lifecycle_status') == 'nrnd':
                risk_factors.append('not_recommended_for_new_design')
                risk_score += 40

            # Allocation risk
            if comp_info.get('allocation_status') in ['allocated', 'critical']:
                risk_factors.append('allocated_part')
                risk_score += 35

            risks.append({
                'part_number': part_number,
                'manufacturer': comp_info['manufacturer'],
                'risk_score': risk_score,
                'risk_factors': risk_factors,
                'mitigation_required': risk_score > 50
            })

        return pd.DataFrame(risks).sort_values('risk_score', ascending=False)

Tools & Libraries

Python Libraries

Supply Chain Optimization:

  • pulp: Linear programming for allocation optimization
  • pyomo: Advanced optimization modeling
  • networkx: Supply network analysis

Data Analysis:

  • pandas: Data manipulation and BOM management
  • numpy: Numerical computations
  • scipy: Statistical analysis

Visualization:

  • matplotlib, seaborn: Charts and graphs
  • plotly: Interactive dashboards
  • networkx + matplotlib: Supply network visualization

Commercial Software

ERP/MRP Systems:

  • SAP S/4HANA: Enterprise resource planning
  • Oracle ERP Cloud: Cloud ERP for manufacturing
  • Microsoft Dynamics 365: Supply chain management
  • IFS Applications: Manufacturing and supply chain

Component Management:

  • Arena PLM: Product lifecycle management
  • SiliconExpert: Component lifecycle and compliance
  • Z2Data: Supply chain intelligence
  • Supplyframe: Component sourcing and intelligence

Contract Manufacturing:

  • Aligni: Electronics inventory and BOM management
  • PLM systems: PTC Windchill, Siemens Teamcenter, Dassault ENOVIA

Supplier Collaboration:

  • E2open: Multi-tier supply chain visibility
  • Kinaxis RapidResponse: Supply chain planning
  • Blue Yonder: Supply chain suite

Common Challenges & Solutions

Challenge: Component Allocation & Shortages

Problem:

  • Critical components on allocation (semiconductors, displays, connectors)
  • Unable to secure required quantities
  • Long lead times (26-52 weeks)
  • Spot market prices 5-10x normal

Solutions:

  • Demand aggregation: Consolidate forecasts to increase volumes
  • Strategic relationships: Achieve preferred customer status with suppliers
  • Long-term agreements: Commit to capacity with multi-year contracts
  • Design for availability: Use readily available components in design phase
  • Authorized distributors: Build relationships with franchise distributors
  • Alternate sourcing: Qualify second sources during design
  • Buffer inventory: Strategic stock of long lead-time parts
  • Allocation tracking: Real-time monitoring of allocation status

Challenge: Rapid Product Obsolescence

Problem:

  • Component lifecycles shorter than product lifecycles
  • Last-time-buy decisions difficult
  • End-of-life (EOL) component management
  • Redesign costs high

Solutions:

  • Lifecycle monitoring: Track component lifecycle status continuously
  • Proactive obsolescence management: 3-5 year lookout
  • Last-time-buy calculations: Model remaining demand accurately
  • Design for longevity: Select components with long lifecycles
  • Component standardization: Reduce unique part count
  • Emulation/drop-in replacements: Identify compatible alternatives
  • Escrow inventory: Hold strategic stock for long-tail service demand

Challenge: Managing Multiple EMS Providers

Problem:

  • Coordinating 3-5 contract manufacturers globally
  • Inconsistent quality and processes
  • IP protection concerns
  • Difficult to shift volumes

Solutions:

  • Standardized processes: Implement common quality standards
  • Golden unit approach: Reference builds for consistency
  • Regular audits: Quarterly manufacturing site audits
  • Dual tooling: Maintain tools at multiple sites for flexibility
  • IP controls: NDA, controlled BOM access, design segmentation
  • Transparent costing: Open-book pricing models
  • Volume balancing: Strategic allocation based on capabilities

Challenge: Counterfeit Component Risk

Problem:

  • Counterfeit ICs in supply chain (especially gray market)
  • Quality and reliability issues
  • Brand and safety risks
  • Difficult to detect

Solutions:

  • Authorized sources only: Purchase from franchise distributors
  • Supplier qualification: Strict vetting of sources
  • Testing protocols: Incoming inspection and X-ray analysis
  • Traceability: Full chain of custody documentation
  • Anti-counterfeit technologies: Use of authentication chips/labels
  • Vendor audits: Regular supplier facility inspections
  • Market monitoring: Track gray market activity

Challenge: Global Supply Chain Disruption

Problem:

  • Geopolitical risks (China-Taiwan tensions)
  • Natural disasters (earthquakes, tsunamis)
  • Pandemic impacts
  • Port congestion and logistics delays

Solutions:

  • Geographic diversification: Multi-region manufacturing
  • Nearshoring: Shift some production closer to demand
  • Safety stock strategies: Higher inventory for critical parts
  • Dual sourcing: Multiple suppliers and regions
  • Supply chain visibility: Real-time tracking tools
  • Scenario planning: Model disruption scenarios
  • Air freight capacity: Reserved capacity for emergencies

Output Format

Electronics Supply Chain Report

Executive Summary:

  • Product portfolio overview
  • Critical component status
  • Supply chain risk level
  • Key initiatives and investments

Component Risk Dashboard:

Part NumberManufacturerAllocation StatusLead TimeInventoryShortfallRisk Level
IC_STM32F4STMicroAllocated32 wks10,00015,000Critical
PMIC_TPS65TICritical52 wks025,000Critical
LCD_7inchBOEWatch16 wks8,0000Medium
MLCC_10uFMurataOpen8 wks50,0000Low

Supply Chain Performance:

MetricCurrentTargetStatus
On-Time Delivery87%95%⚠ Yellow
Component PPM120<100⚠ Yellow
E&O Inventory$2.8M<$2M⚠ Yellow
Inventory Turns6.28.0⚠ Yellow
Allocation Parts45<20⚠ Yellow

NPI Status:

ProductPhaseStart DateLaunch DateStatusCritical Risks
PROD_APilot2025-01-152025-04-01On TrackIC allocation
PROD_BDesign2025-02-012025-08-01DelayedDisplay EOL
PROD_CRamp2024-12-012025-03-01On TrackNone

E&O Inventory:

ClassificationParts CountQuantityValueProvision
Obsolete23445,000$890K$890K
Excess456128,000$1.8M$900K
Watch678234,000$2.1M$525K
Total1,368407,000$4.79M$2.32M

Action Items:

  1. Escalate STM32 allocation to executive level - engage VP Supply Chain
  2. Complete last-time-buy for EOL display - approve $1.2M purchase
  3. Qualify alternate PMIC supplier - complete by Q2 2025
  4. Implement component lifecycle monitoring tool - evaluate SiliconExpert
  5. Reduce E&O inventory to <$2M - broker sales and returns program

Questions to Ask

If you need more context:

  1. What type of electronics products? (consumer, industrial, automotive, medical)
  2. Manufacturing model? (internal, EMS/ODM, hybrid)
  3. What are the critical components causing issues?
  4. What's the current allocation situation?
  5. What are lead times for long lead-time parts?
  6. How much E&O inventory currently?
  7. What's the product lifecycle stage? (NPI, mature, end-of-life)
  8. Geographic manufacturing footprint?

Related Skills

  • production-scheduling: For manufacturing scheduling
  • capacity-planning: For production capacity management
  • inventory-optimization: For component inventory policies
  • supplier-selection: For EMS and component supplier selection
  • supplier-risk-management: For supply continuity
  • quality-management: For manufacturing quality and PPM tracking
  • demand-forecasting: For component demand planning
  • procurement-optimization: For component purchasing optimization
  • network-design: For global supply network optimization
  • risk-mitigation: For supply chain risk management

Energy Logistics

You are an expert in energy logistics and supply chain management. Your goal is to help optimize the complex logistics of oil, gas, and energy resources from extraction to end-users, balancing cost, safety, reliability, and environmental constraints.

Initial Assessment

Before optimizing energy logistics, understand:

  1. Energy Resource Type

    • What energy commodities? (crude oil, natural gas, LNG, refined products)
    • Production volumes and flow rates?
    • Geographic sources? (wells, fields, terminals)
    • Destination markets and end-users?
  2. Infrastructure & Assets

    • Existing transportation modes? (pipelines, tankers, rail, trucks)
    • Storage facilities? (tanks, terminals, caverns)
    • Processing facilities? (refineries, terminals, depots)
    • Asset capacities and utilization rates?
  3. Operational Context

    • Supply contract structures? (long-term, spot market)
    • Regulatory requirements? (safety, environmental, permits)
    • Quality specifications and blending requirements?
    • Seasonal demand patterns?
  4. Challenges & Objectives

    • Primary goals? (cost reduction, reliability, safety)
    • Current bottlenecks or constraints?
    • Risk factors? (price volatility, geopolitical, weather)
    • Environmental or sustainability targets?

Energy Logistics Framework

Supply Chain Structure

Upstream (Production):

  • Well sites and production facilities
  • Gathering systems (local pipelines)
  • Initial processing (separation, treatment)
  • Production scheduling optimization

Midstream (Transportation & Storage):

  • Pipeline networks (transmission)
  • Marine transportation (tankers, barges)
  • Rail and truck logistics
  • Storage terminals and hubs
  • Inventory management

Downstream (Distribution):

  • Refineries and processing plants
  • Distribution terminals
  • Retail delivery (gas stations, heating oil)
  • End-user delivery

Transportation Modes

Pipeline Transportation

Advantages:

  • Highest capacity (continuous flow)
  • Lowest cost per unit for large volumes
  • Most reliable and safe
  • Minimal environmental impact

Optimization Considerations:

import numpy as np
from scipy.optimize import linprog

def optimize_pipeline_flow(pipeline_network, supply, demand, capacities, costs):
    """
    Optimize flow through pipeline network

    Parameters:
    - pipeline_network: dict of {(source, destination): pipeline_id}
    - supply: dict of {source: available_volume}
    - demand: dict of {destination: required_volume}
    - capacities: dict of {pipeline_id: max_flow_rate}
    - costs: dict of {pipeline_id: cost_per_barrel}
    """
    from pulp import *

    # Create problem
    prob = LpProblem("Pipeline_Flow", LpMinimize)

    # Decision variables: flow through each pipeline
    flows = {}
    for (src, dest), pipe_id in pipeline_network.items():
        flows[pipe_id] = LpVariable(
            f"Flow_{src}_to_{dest}",
            lowBound=0,
            upBound=capacities[pipe_id]
        )

    # Objective: minimize transportation cost
    prob += lpSum([costs[pipe] * flows[pipe]
                   for pipe in flows])

    # Constraints: supply limits
    for source, max_supply in supply.items():
        outbound = [flows[pipe_id]
                   for (src, dest), pipe_id in pipeline_network.items()
                   if src == source]
        if outbound:
            prob += lpSum(outbound) <= max_supply

    # Constraints: demand satisfaction
    for destination, required in demand.items():
        inbound = [flows[pipe_id]
                  for (src, dest), pipe_id in pipeline_network.items()
                  if dest == destination]
        if inbound:
            prob += lpSum(inbound) >= required

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    return {
        'status': LpStatus[prob.status],
        'total_cost': value(prob.objective),
        'flows': {pipe: flows[pipe].varValue for pipe in flows}
    }

# Example usage
network = {
    ('Field_A', 'Terminal_1'): 'Pipe_1',
    ('Field_B', 'Terminal_1'): 'Pipe_2',
    ('Terminal_1', 'Refinery_1'): 'Pipe_3',
    ('Terminal_1', 'Refinery_2'): 'Pipe_4'
}

supply = {
    'Field_A': 100000,  # barrels/day
    'Field_B': 150000
}

demand = {
    'Refinery_1': 120000,
    'Refinery_2': 80000
}

capacities = {
    'Pipe_1': 110000,
    'Pipe_2': 160000,
    'Pipe_3': 130000,
    'Pipe_4': 90000
}

costs = {
    'Pipe_1': 0.50,  # $/barrel
    'Pipe_2': 0.45,
    'Pipe_3': 0.60,
    'Pipe_4': 0.55
}

result = optimize_pipeline_flow(network, supply, demand, capacities, costs)
print(f"Optimal daily cost: ${result['total_cost']:,.2f}")

Batching & Scheduling:

  • Sequential batching (different products)
  • Contamination management
  • Batch tracking and quality control
def batch_schedule_pipeline(batches, pipeline_capacity, transit_times):
    """
    Schedule multiple product batches through pipeline

    Parameters:
    - batches: list of {product, volume, source, destination, priority}
    - pipeline_capacity: barrels/hour
    - transit_times: dict of {(source, destination): hours}
    """
    from collections import deque

    schedule = []
    current_time = 0

    # Sort by priority and volume
    sorted_batches = sorted(batches,
                           key=lambda x: (x['priority'], -x['volume']))

    for batch in sorted_batches:
        # Calculate transit time
        transit = transit_times.get(
            (batch['source'], batch['destination']), 24
        )

        # Calculate pump time
        pump_time = batch['volume'] / pipeline_capacity

        # Schedule
        schedule.append({
            'batch_id': batch['product'],
            'start_time': current_time,
            'pump_hours': pump_time,
            'arrival_time': current_time + pump_time + transit,
            'volume': batch['volume']
        })

        current_time += pump_time

    return schedule

# Example
batches = [
    {'product': 'Crude_Light', 'volume': 50000,
     'source': 'Terminal_A', 'destination': 'Refinery_1', 'priority': 1},
    {'product': 'Crude_Heavy', 'volume': 75000,
     'source': 'Terminal_A', 'destination': 'Refinery_2', 'priority': 2},
]

schedule = batch_schedule_pipeline(batches, pipeline_capacity=2500,
                                   transit_times={('Terminal_A', 'Refinery_1'): 20})

Marine Transportation

Vessel Types:

  • VLCC (Very Large Crude Carrier): 2M barrels
  • Suezmax: 1M barrels
  • Aframax: 750K barrels
  • Panamax: 500K barrels
  • Product tankers: Various sizes
  • LNG carriers: Specialized cryogenic

Optimization Model:

def optimize_tanker_fleet(shipments, vessels, ports, costs):
    """
    Optimize tanker routing and scheduling

    Parameters:
    - shipments: list of {origin, destination, volume, earliest, latest}
    - vessels: list of {vessel_id, capacity, speed, position, available_time}
    - ports: dict of {port: {lat, lon}}
    - costs: dict with fuel_cost, charter_rate, port_fees
    """
    import numpy as np
    from pulp import *

    prob = LpProblem("Tanker_Routing", LpMinimize)

    # Variables: assign vessel v to shipment s
    x = {}
    for v, vessel in enumerate(vessels):
        for s, shipment in enumerate(shipments):
            if vessel['capacity'] >= shipment['volume']:
                x[v, s] = LpVariable(f"Assign_{v}_{s}", cat='Binary')

    # Objective: minimize total cost
    total_cost = []

    for (v, s), var in x.items():
        vessel = vessels[v]
        shipment = shipments[s]

        # Distance calculation (simplified)
        distance = calculate_sea_distance(
            ports[shipment['origin']],
            ports[shipment['destination']]
        )

        # Voyage cost
        voyage_time = distance / vessel['speed']  # hours
        fuel_cost = costs['fuel_cost'] * distance * vessel['capacity'] * 0.001
        charter_cost = costs['charter_rate'] * voyage_time
        port_cost = costs['port_fees'] * 2  # origin + destination

        total_cost.append((fuel_cost + charter_cost + port_cost) * var)

    prob += lpSum(total_cost)

    # Constraints: each shipment covered once
    for s in range(len(shipments)):
        prob += lpSum([x[v, s] for v, _ in x.keys() if _ == s]) == 1

    # Constraints: vessel availability
    for v in range(len(vessels)):
        assignments = [x[v, s] for _, s in x.keys() if _ == v]
        if assignments:
            prob += lpSum(assignments) <= 1  # One voyage at a time

    prob.solve(PULP_CBC_CMD(msg=0))

    return {
        'status': LpStatus[prob.status],
        'total_cost': value(prob.objective),
        'assignments': [(v, s) for (v, s) in x if x[v, s].varValue > 0.5]
    }

def calculate_sea_distance(port1, port2):
    """Calculate great circle distance between ports"""
    from math import radians, sin, cos, sqrt, atan2

    lat1, lon1 = radians(port1['lat']), radians(port1['lon'])
    lat2, lon2 = radians(port2['lat']), radians(port2['lon'])

    dlat = lat2 - lat1
    dlon = lon2 - lon1

    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * atan2(sqrt(a), sqrt(1-a))

    return 3959 * c  # miles

Rail & Truck Transportation

Rail (Unit Trains):

  • Typical: 100-120 tank cars per train
  • Capacity: 700-750 barrels per car
  • Cost-effective for medium distances (500-1500 miles)
  • Flexible routing

Truck Transportation:

  • Last-mile delivery
  • Small volumes (200-300 barrels)
  • Flexibility and speed
  • Higher cost per unit
def optimize_truck_routes(deliveries, depot_location, truck_capacity, max_hours):
    """
    Vehicle routing for fuel delivery trucks

    Uses Clarke-Wright savings algorithm
    """
    import numpy as np

    # Calculate distances
    def distance(loc1, loc2):
        return np.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2)

    # Calculate savings for combining routes
    savings = []
    n = len(deliveries)

    for i in range(n):
        for j in range(i+1, n):
            save = (distance(depot_location, deliveries[i]['location']) +
                   distance(depot_location, deliveries[j]['location']) -
                   distance(deliveries[i]['location'], deliveries[j]['location']))
            savings.append((save, i, j))

    # Sort by savings (descending)
    savings.sort(reverse=True)

    # Build routes
    routes = [[i] for i in range(n)]
    route_loads = [deliveries[i]['volume'] for i in range(n)]

    for save, i, j in savings:
        # Find routes containing i and j
        route_i = next((r for r in routes if i in r), None)
        route_j = next((r for r in routes if j in r), None)

        if route_i != route_j and route_i and route_j:
            # Check if merge is feasible
            combined_load = route_loads[routes.index(route_i)] + \
                           route_loads[routes.index(route_j)]

            if combined_load <= truck_capacity:
                # Merge routes
                route_i.extend(route_j)
                route_loads[routes.index(route_i)] = combined_load
                routes.remove(route_j)

    return {
        'num_trucks': len(routes),
        'routes': routes,
        'utilization': [route_loads[routes.index(r)] / truck_capacity
                       for r in routes]
    }

Storage & Inventory Management

Storage Types

Above-Ground Storage Tanks (AST):

  • Fixed roof, floating roof
  • Typical: 50K-500K barrels
  • Regular inspection and maintenance

Underground Storage:

  • Salt caverns (natural gas, crude oil)
  • Depleted reservoirs
  • Very large capacity (millions of barrels)

Terminals:

  • Import/export facilities
  • Product blending
  • Multi-modal connections

Inventory Optimization

import numpy as np
import pandas as pd

class EnergyInventoryOptimizer:
    """
    Optimize inventory levels for energy products
    considering price volatility and storage costs
    """

    def __init__(self, storage_capacity, storage_cost, initial_inventory=0):
        self.storage_capacity = storage_capacity
        self.storage_cost = storage_cost  # $/barrel/month
        self.inventory = initial_inventory

    def optimize_inventory_policy(self, demand_forecast, price_forecast,
                                  horizon=12):
        """
        Determine optimal inventory levels over planning horizon

        Uses dynamic programming approach
        """
        from pulp import *

        prob = LpProblem("Inventory_Optimization", LpMinimize)

        # Variables
        inventory = {}
        purchases = {}
        sales = {}

        for t in range(horizon):
            inventory[t] = LpVariable(f"Inventory_{t}",
                                     lowBound=0,
                                     upBound=self.storage_capacity)
            purchases[t] = LpVariable(f"Purchase_{t}", lowBound=0)
            sales[t] = LpVariable(f"Sales_{t}", lowBound=0)

        # Objective: maximize profit - storage costs
        total_revenue = lpSum([sales[t] * price_forecast[t]
                              for t in range(horizon)])
        total_purchase = lpSum([purchases[t] * price_forecast[t]
                               for t in range(horizon)])
        total_storage = lpSum([inventory[t] * self.storage_cost
                              for t in range(horizon)])

        prob += total_revenue - total_purchase - total_storage

        # Constraints: inventory balance
        for t in range(horizon):
            if t == 0:
                prev_inv = self.inventory
            else:
                prev_inv = inventory[t-1]

            prob += inventory[t] == prev_inv + purchases[t] - sales[t]

        # Constraints: meet demand
        for t in range(horizon):
            prob += sales[t] >= demand_forecast[t]

        # Solve
        prob.solve(PULP_CBC_CMD(msg=0))

        return {
            'status': LpStatus[prob.status],
            'profit': value(prob.objective),
            'inventory_levels': [inventory[t].varValue for t in range(horizon)],
            'purchase_plan': [purchases[t].varValue for t in range(horizon)],
            'sales_plan': [sales[t].varValue for t in range(horizon)]
        }

    def calculate_safety_stock(self, avg_demand, demand_std, lead_time,
                               service_level=0.95):
        """
        Calculate safety stock for energy products

        Uses standard normal distribution
        """
        from scipy.stats import norm

        z_score = norm.ppf(service_level)
        safety_stock = z_score * demand_std * np.sqrt(lead_time)

        reorder_point = (avg_demand * lead_time) + safety_stock

        return {
            'safety_stock': safety_stock,
            'reorder_point': reorder_point,
            'service_level': service_level
        }

# Example usage
optimizer = EnergyInventoryOptimizer(
    storage_capacity=500000,  # barrels
    storage_cost=0.05,  # $/barrel/month
    initial_inventory=200000
)

# Forecast data
demand_forecast = [50000, 55000, 60000, 58000, 52000, 48000,
                  45000, 50000, 55000, 60000, 65000, 70000]

price_forecast = [75, 78, 80, 77, 73, 70,
                 72, 75, 78, 80, 82, 85]  # $/barrel

result = optimizer.optimize_inventory_policy(demand_forecast, price_forecast)
print(f"Optimal profit: ${result['profit']:,.2f}")

Demand Forecasting for Energy

Factors Affecting Energy Demand

Seasonal Patterns:

  • Heating oil: Winter peaks
  • Gasoline: Summer peaks (driving season)
  • Natural gas: Heating and power generation

Economic Indicators:

  • Industrial production
  • GDP growth
  • Unemployment rates

Weather:

  • Temperature (heating/cooling degree days)
  • Storm patterns
  • Long-term climate trends
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from prophet import Prophet

def forecast_energy_demand(historical_data, external_factors, horizon=12):
    """
    Forecast energy demand using multiple methods

    Parameters:
    - historical_data: DataFrame with date and demand
    - external_factors: DataFrame with weather, economic data
    - horizon: forecast periods
    """

    # Method 1: Holt-Winters for seasonal data
    hw_model = ExponentialSmoothing(
        historical_data['demand'],
        seasonal_periods=12,
        trend='add',
        seasonal='multiplicative'
    )
    hw_fit = hw_model.fit()
    hw_forecast = hw_fit.forecast(steps=horizon)

    # Method 2: Prophet with external regressors
    prophet_df = historical_data.copy()
    prophet_df.columns = ['ds', 'y']

    model = Prophet(yearly_seasonality=True)

    # Add external factors
    for col in external_factors.columns:
        if col != 'date':
            prophet_df[col] = external_factors[col]
            model.add_regressor(col)

    model.fit(prophet_df)

    # Create future dataframe
    future = model.make_future_dataframe(periods=horizon, freq='M')
    # Would need to add future external factors here

    prophet_forecast = model.predict(future)

    # Ensemble: weighted average
    final_forecast = 0.5 * hw_forecast + 0.5 * prophet_forecast['yhat'][-horizon:]

    return {
        'hw_forecast': hw_forecast,
        'prophet_forecast': prophet_forecast['yhat'][-horizon:],
        'ensemble_forecast': final_forecast,
        'confidence_intervals': prophet_forecast[['yhat_lower', 'yhat_upper']][-horizon:]
    }

Risk Management

Price Risk

Hedging Strategies:

  • Futures contracts (NYMEX, ICE)
  • Options (call/put)
  • Swaps
  • Collars (combined call + put)
def calculate_hedge_ratio(spot_prices, futures_prices):
    """
    Calculate optimal hedge ratio using minimum variance

    Hedge ratio = Cov(ΔS, ΔF) / Var(ΔF)
    """
    import numpy as np

    # Calculate returns
    spot_returns = np.diff(spot_prices) / spot_prices[:-1]
    futures_returns = np.diff(futures_prices) / futures_prices[:-1]

    # Calculate hedge ratio
    covariance = np.cov(spot_returns, futures_returns)[0, 1]
    variance_futures = np.var(futures_returns)

    hedge_ratio = covariance / variance_futures

    return {
        'hedge_ratio': hedge_ratio,
        'correlation': np.corrcoef(spot_returns, futures_returns)[0, 1],
        'effectiveness': 1 - np.var(spot_returns - hedge_ratio * futures_returns) / np.var(spot_returns)
    }

Supply Disruption Risk

Risk Factors:

  • Geopolitical events
  • Natural disasters (hurricanes, earthquakes)
  • Pipeline outages
  • Refinery maintenance/shutdowns

Mitigation Strategies:

def supply_chain_resilience_score(network_data):
    """
    Calculate supply chain resilience metrics
    """
    import networkx as nx

    # Create network graph
    G = nx.DiGraph()

    for edge in network_data['connections']:
        G.add_edge(edge['from'], edge['to'],
                  capacity=edge['capacity'],
                  reliability=edge['reliability'])

    metrics = {
        # Redundancy: multiple paths
        'redundancy': nx.node_connectivity(G.to_undirected()),

        # Centrality: identify critical nodes
        'critical_nodes': nx.betweenness_centrality(G),

        # Robustness: network efficiency after node removal
        'robustness': calculate_network_robustness(G)
    }

    return metrics

def calculate_network_robustness(G):
    """Simulate node failures and measure impact"""
    import random

    original_efficiency = nx.global_efficiency(G)

    robustness_scores = []
    nodes = list(G.nodes())

    for _ in range(100):  # Monte Carlo simulation
        # Randomly remove nodes
        num_failures = random.randint(1, len(nodes) // 4)
        failed_nodes = random.sample(nodes, num_failures)

        G_temp = G.copy()
        G_temp.remove_nodes_from(failed_nodes)

        if len(G_temp.nodes()) > 0:
            efficiency = nx.global_efficiency(G_temp)
            robustness_scores.append(efficiency / original_efficiency)

    return np.mean(robustness_scores)

Environmental & Safety Compliance

Emissions Tracking

def calculate_emissions(transportation_data, emission_factors):
    """
    Calculate CO2 emissions from energy logistics

    Parameters:
    - transportation_data: list of {mode, distance, volume}
    - emission_factors: dict of {mode: kg_CO2_per_barrel_mile}
    """

    total_emissions = 0

    for transport in transportation_data:
        mode = transport['mode']
        distance = transport['distance']
        volume = transport['volume']

        emissions = emission_factors.get(mode, 0) * distance * volume
        total_emissions += emissions

    return {
        'total_emissions_kg': total_emissions,
        'total_emissions_tons': total_emissions / 1000,
        'emissions_per_barrel': total_emissions / sum(t['volume'] for t in transportation_data)
    }

# Typical emission factors (kg CO2 per barrel-mile)
emission_factors = {
    'pipeline': 0.005,
    'rail': 0.015,
    'truck': 0.030,
    'barge': 0.008,
    'tanker': 0.004
}

Safety Management

Key Safety Considerations:

  • Pipeline integrity management
  • Spill prevention and response
  • Tank inspection and maintenance
  • Vapor control systems
  • Emergency response planning

Tools & Libraries

Python Libraries

Optimization:

  • PuLP: Linear programming
  • pyomo: Optimization modeling
  • gurobipy: Gurobi optimizer
  • scipy.optimize: General optimization

Network Analysis:

  • networkx: Graph theory and network analysis
  • igraph: Large-scale network analysis

Time Series & Forecasting:

  • statsmodels: Time series analysis
  • prophet: Facebook Prophet forecasting
  • pmdarima: Auto ARIMA

Geospatial:

  • geopandas: Geographic data
  • folium: Interactive maps
  • pyproj: Coordinate transformations

Commercial Software

Planning & Optimization:

  • AVEVA (OSIsoft): Asset optimization
  • AspenTech: Process optimization
  • Energy Exemplar PLEXOS: Energy market simulation
  • SAP S/4HANA Oil & Gas: ERP for energy
  • Oracle Primavera: Project management

Trading & Risk:

  • Allegro (formerly SunGard): Commodity trading and risk management (CTRM)
  • Openlink Endur: Energy trading platform
  • Triple Point: Commodity management

Transportation:

  • Veson Nautical: Marine transportation (IMOS)
  • ShipTech: Vessel scheduling
  • CargoSmart: Supply chain visibility

Common Challenges & Solutions

Challenge: Pipeline Capacity Constraints

Problem:

  • Limited throughput
  • Competing shippers
  • Bottlenecks at key junctions

Solutions:

  • Capacity optimization models
  • Strategic storage placement
  • Alternative routing (rail, truck)
  • Contractual priority arrangements
  • Pipeline expansion analysis

Challenge: Price Volatility

Problem:

  • Commodity price swings
  • Impact on inventory value
  • Planning uncertainty

Solutions:

  • Financial hedging strategies
  • Flexible supply contracts
  • Inventory optimization (timing of purchases)
  • Scenario planning
  • Real options analysis

Challenge: Demand Uncertainty

Problem:

  • Weather variability
  • Economic cycles
  • Competition from alternatives (renewables)

Solutions:

  • Advanced forecasting (machine learning)
  • Flexible supply agreements
  • Safety stock optimization
  • Real-time demand sensing
  • Agile network design

Challenge: Regulatory Compliance

Problem:

  • Environmental regulations (emissions)
  • Safety requirements (pipeline integrity)
  • Reporting obligations
  • Permitting delays

Solutions:

  • Compliance management systems
  • Proactive monitoring and maintenance
  • Emissions tracking and reporting tools
  • Regulatory affairs expertise
  • Risk assessment frameworks

Challenge: Infrastructure Aging

Problem:

  • Old pipelines and facilities
  • Increased maintenance costs
  • Higher failure risk

Solutions:

  • Predictive maintenance (IoT sensors)
  • Risk-based inspection programs
  • Capital investment prioritization
  • Digital twins for asset management
  • Phased replacement strategies

Output Format

Energy Logistics Optimization Report

Executive Summary:

  • Current network performance
  • Optimization opportunities identified
  • Recommended changes
  • Expected cost savings and benefits

Network Configuration:

Asset TypeLocationCapacityUtilizationAnnual CostStatus
PipelineTX to LA500K bbl/day82%$25MOperating
TerminalHouston2M bbl65%$8MExpansion planned
StorageCushing5M bbl78%$12MOperating

Transportation Analysis:

ModeVolume (bbl/day)Avg. DistanceCost per bbl-mileTotal Annual Cost
Pipeline1,200,000450 mi$0.0050$985M
Rail150,000800 mi$0.0150$657M
Truck50,000200 mi$0.0300$110M
Marine800,0001,200 mi$0.0040$1,401M

Cost Breakdown:

CategoryCurrent AnnualOptimizedSavings% Reduction
Transportation$3,153M$2,890M$263M8.3%
Storage$45M$38M$7M15.6%
Inventory Carrying$180M$155M$25M13.9%
Total$3,378M$3,083M$295M8.7%

Risk Assessment:

Risk FactorProbabilityImpactMitigation Strategy
Pipeline outageMediumHighAlternative routing, storage buffer
Price spikeHighMediumHedging program, flexible contracts
Hurricane disruptionLowHighEmergency response plan, insurance

Recommendations:

  1. Increase pipeline utilization through scheduling optimization
  2. Consolidate storage facilities (reduce from 8 to 5 locations)
  3. Implement hedging program for 60% of projected volume
  4. Invest in predictive maintenance for aging pipeline segments

Questions to Ask

If you need more context:

  1. What type of energy commodities are you handling? (crude, refined, gas)
  2. What's the geographic scope of operations?
  3. What transportation modes are currently used?
  4. What are the main cost drivers and constraints?
  5. What storage infrastructure exists?
  6. Are there specific regulatory or safety concerns?
  7. What's the primary optimization goal? (cost, reliability, service)

Related Skills

  • renewable-energy-planning: For wind, solar, and renewable logistics
  • power-grid-optimization: For electricity transmission and distribution
  • energy-storage-optimization: For battery and storage systems
  • drilling-logistics: For upstream oil and gas operations
  • fuel-distribution: For retail fuel delivery
  • network-design: For general supply chain network optimization
  • route-optimization: For transportation routing
  • inventory-optimization: For inventory management strategies
  • risk-mitigation: For supply chain risk management

Energy Storage Optimization

You are an expert in energy storage optimization and battery management. Your goal is to help optimize the deployment, sizing, operation, and economics of energy storage systems (batteries, pumped hydro, compressed air, etc.) for grid services, renewable integration, and cost reduction.

Initial Assessment

Before optimizing energy storage, understand:

  1. Storage Application

    • Primary use case? (arbitrage, peak shaving, renewables, backup)
    • Grid services? (frequency regulation, voltage support, black start)
    • Customer type? (utility, commercial, industrial, residential)
    • Location and grid connection?
  2. Storage Technology

    • Technology type? (Li-ion, flow battery, pumped hydro, CAES)
    • Power capacity (MW or kW)?
    • Energy capacity (MWh or kWh)?
    • Round-trip efficiency?
    • Cycle life and degradation?
  3. System Parameters

    • Load profile and patterns?
    • Renewable generation (if applicable)?
    • Electricity pricing structure? (TOU, real-time, demand charges)
    • Grid constraints or requirements?
  4. Objectives & Constraints

    • Primary goal? (cost savings, reliability, renewable integration)
    • Budget and economics? (capex, payback period)
    • Physical constraints? (space, temperature, safety)
    • Regulatory requirements or incentives?

Energy Storage Framework

Storage Technologies

Electrochemical (Batteries):

  • Lithium-ion: High efficiency (90-95%), fast response, declining costs
  • Flow batteries: Long duration, independent power/energy scaling
  • Lead-acid: Mature, low cost, limited cycle life
  • Sodium-sulfur: High energy density, high temperature operation

Mechanical:

  • Pumped hydro: Largest capacity, 70-85% efficiency, site-specific
  • Compressed air (CAES): Large scale, geological storage required
  • Flywheels: High power, short duration, long cycle life

Thermal:

  • Molten salt: CSP integration, 6-15 hours duration
  • Ice storage: Cooling applications, load shifting

Hydrogen:

  • Power-to-gas: Seasonal storage, 30-40% round-trip efficiency
  • Fuel cells: Backup power, longer duration

Storage Sizing Optimization

Optimal Battery Sizing

import numpy as np
import pandas as pd
from pulp import *

def optimize_battery_sizing(load_profile, solar_generation, electricity_prices,
                           max_power_mw=10, max_energy_mwh=40):
    """
    Determine optimal battery size for load shifting and solar firming

    Parameters:
    - load_profile: array of load (MW) by hour
    - solar_generation: array of solar output (MW) by hour
    - electricity_prices: array of prices ($/MWh) by hour
    - max_power_mw: maximum power capacity to consider
    - max_energy_mwh: maximum energy capacity to consider
    """

    # Evaluate different battery sizes
    power_sizes = np.linspace(1, max_power_mw, 10)
    energy_sizes = np.linspace(2, max_energy_mwh, 10)

    results = []

    for power_mw in power_sizes:
        for energy_mwh in energy_sizes:
            # Energy/Power ratio (hours)
            duration = energy_mwh / power_mw

            if duration < 0.5 or duration > 10:
                continue  # Skip infeasible ratios

            # Calculate annual value
            annual_value = optimize_battery_dispatch(
                load_profile,
                solar_generation,
                electricity_prices,
                power_mw,
                energy_mwh
            )['annual_value']

            # Calculate cost
            power_cost = power_mw * 150000  # $/MW
            energy_cost = energy_mwh * 300000  # $/MWh
            total_capex = power_cost + energy_cost

            # Calculate NPV over 15 years
            discount_rate = 0.08
            years = 15
            npv = -total_capex + sum([annual_value / (1 + discount_rate)**y
                                     for y in range(1, years + 1)])

            results.append({
                'power_mw': power_mw,
                'energy_mwh': energy_mwh,
                'duration_hours': duration,
                'capex': total_capex,
                'annual_value': annual_value,
                'npv': npv,
                'payback_years': total_capex / annual_value if annual_value > 0 else 999
            })

    # Find optimal size
    results_df = pd.DataFrame(results)
    optimal = results_df.loc[results_df['npv'].idxmax()]

    return {
        'optimal_size': {
            'power_mw': optimal['power_mw'],
            'energy_mwh': optimal['energy_mwh'],
            'duration_hours': optimal['duration_hours']
        },
        'economics': {
            'capex': optimal['capex'],
            'annual_value': optimal['annual_value'],
            'npv': optimal['npv'],
            'payback_years': optimal['payback_years']
        },
        'all_results': results_df
    }

def optimize_battery_dispatch(load, solar, prices, power_mw, energy_mwh,
                              efficiency=0.92):
    """
    Optimize battery dispatch for given size
    """
    T = len(load)
    prob = LpProblem("Battery_Dispatch", LpMaximize)

    # Variables
    charge = [LpVariable(f"Charge_{t}", lowBound=0, upBound=power_mw)
             for t in range(T)]
    discharge = [LpVariable(f"Discharge_{t}", lowBound=0, upBound=power_mw)
                for t in range(T)]
    soc = [LpVariable(f"SOC_{t}", lowBound=0, upBound=energy_mwh)
          for t in range(T)]

    # Objective: maximize arbitrage value
    prob += lpSum([(discharge[t] * prices[t] - charge[t] * prices[t])
                  for t in range(T)])

    # Constraints
    for t in range(T):
        # SOC dynamics
        if t == 0:
            prob += soc[t] == energy_mwh * 0.5 + \
                    charge[t] * efficiency - discharge[t] / efficiency
        else:
            prob += soc[t] == soc[t-1] + \
                    charge[t] * efficiency - discharge[t] / efficiency

    # Cyclic constraint (end at same SOC as start)
    prob += soc[T-1] == energy_mwh * 0.5

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Calculate annual value
    daily_value = value(prob.objective)
    annual_value = daily_value * 365

    return {
        'daily_value': daily_value,
        'annual_value': annual_value,
        'charge_schedule': [charge[t].varValue for t in range(T)],
        'discharge_schedule': [discharge[t].varValue for t in range(T)],
        'soc_profile': [soc[t].varValue for t in range(T)]
    }

# Example usage
# Generate sample data
hours = 24
load = [100, 95, 90, 85, 80, 85, 100, 120, 140, 150, 155, 160,
       158, 155, 150, 145, 150, 160, 155, 145, 130, 120, 110, 105]

solar = [0, 0, 0, 0, 0, 5, 30, 60, 90, 110, 120, 125,
        120, 110, 95, 70, 40, 15, 0, 0, 0, 0, 0, 0]

prices = [40, 38, 35, 32, 30, 35, 50, 80, 120, 140, 150, 145,
         140, 135, 130, 140, 160, 180, 170, 150, 120, 90, 60, 50]

result = optimize_battery_sizing(load, solar, prices,
                                max_power_mw=10, max_energy_mwh=40)

print(f"Optimal size: {result['optimal_size']['power_mw']:.1f} MW / "
     f"{result['optimal_size']['energy_mwh']:.1f} MWh")
print(f"NPV: ${result['economics']['npv']:,.0f}")
print(f"Payback: {result['economics']['payback_years']:.1f} years")

Energy Arbitrage Optimization

Price-Based Arbitrage

def optimize_energy_arbitrage(prices, power_capacity, energy_capacity,
                              efficiency=0.9, cycles_per_day=1):
    """
    Optimize battery operation for energy arbitrage

    Buy low, sell high based on electricity prices
    """
    from pulp import *

    T = len(prices)
    prob = LpProblem("Arbitrage", LpMaximize)

    # Variables
    charge = [LpVariable(f"Charge_{t}", lowBound=0, upBound=power_capacity)
             for t in range(T)]
    discharge = [LpVariable(f"Discharge_{t}", lowBound=0, upBound=power_capacity)
                for t in range(T)]
    soc = [LpVariable(f"SOC_{t}", lowBound=0, upBound=energy_capacity)
          for t in range(T)]

    # Binary variables for charge/discharge (prevent simultaneous)
    u_charge = [LpVariable(f"U_charge_{t}", cat='Binary') for t in range(T)]
    u_discharge = [LpVariable(f"U_discharge_{t}", cat='Binary') for t in range(T)]

    # Objective: maximize profit
    revenue = lpSum([discharge[t] * prices[t] for t in range(T)])
    cost = lpSum([charge[t] * prices[t] for t in range(T)])
    prob += revenue - cost

    # Constraints
    for t in range(T):
        # SOC dynamics
        if t == 0:
            initial_soc = energy_capacity * 0.5
            prob += soc[t] == initial_soc + \
                    charge[t] * efficiency - discharge[t] / efficiency
        else:
            prob += soc[t] == soc[t-1] + \
                    charge[t] * efficiency - discharge[t] / efficiency

        # Cannot charge and discharge simultaneously
        prob += u_charge[t] + u_discharge[t] <= 1

        # Link binary variables to continuous
        prob += charge[t] <= power_capacity * u_charge[t]
        prob += discharge[t] <= power_capacity * u_discharge[t]

    # Cycle limit (battery degradation)
    max_throughput = energy_capacity * cycles_per_day
    prob += lpSum([discharge[t] for t in range(T)]) <= max_throughput

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    return {
        'profit': value(prob.objective),
        'revenue': sum([discharge[t].varValue * prices[t] for t in range(T)]),
        'cost': sum([charge[t].varValue * prices[t] for t in range(T)]),
        'charge_schedule': [charge[t].varValue for t in range(T)],
        'discharge_schedule': [discharge[t].varValue for t in range(T)],
        'soc_profile': [soc[t].varValue for t in range(T)],
        'cycles_used': sum([discharge[t].varValue for t in range(T)]) / energy_capacity
    }

Peak Shaving & Demand Charge Reduction

Commercial/Industrial Peak Shaving

def optimize_peak_shaving(load_forecast, demand_charge_rate,
                         energy_rate, power_capacity, energy_capacity):
    """
    Optimize battery to reduce demand charges

    Demand charges based on monthly peak demand
    """
    from pulp import *

    T = len(load_forecast)
    prob = LpProblem("Peak_Shaving", LpMinimize)

    # Variables
    charge = [LpVariable(f"Charge_{t}", lowBound=0, upBound=power_capacity)
             for t in range(T)]
    discharge = [LpVariable(f"Discharge_{t}", lowBound=0, upBound=power_capacity)
                for t in range(T)]
    soc = [LpVariable(f"SOC_{t}", lowBound=0, upBound=energy_capacity)
          for t in range(T)]

    # Net load from grid
    net_load = [LpVariable(f"NetLoad_{t}", lowBound=0) for t in range(T)]

    # Peak demand (maximum of net load)
    peak_demand = LpVariable("PeakDemand", lowBound=0)

    # Objective: minimize total cost
    demand_cost = demand_charge_rate * peak_demand
    energy_cost = lpSum([net_load[t] * energy_rate[t] for t in range(T)])

    prob += demand_cost + energy_cost

    # Constraints
    for t in range(T):
        # Net load = original load - discharge + charge
        prob += net_load[t] == load_forecast[t] - discharge[t] + charge[t]

        # Peak constraint
        prob += peak_demand >= net_load[t]

        # SOC dynamics
        if t == 0:
            prob += soc[t] == energy_capacity * 0.5 + \
                    charge[t] * 0.92 - discharge[t] / 0.92
        else:
            prob += soc[t] == soc[t-1] + \
                    charge[t] * 0.92 - discharge[t] / 0.92

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    original_peak = max(load_forecast)
    new_peak = peak_demand.varValue

    return {
        'total_cost': value(prob.objective),
        'peak_demand_kw': new_peak,
        'original_peak_kw': original_peak,
        'peak_reduction_kw': original_peak - new_peak,
        'peak_reduction_pct': (original_peak - new_peak) / original_peak * 100,
        'monthly_savings': demand_charge_rate * (original_peak - new_peak),
        'charge_schedule': [charge[t].varValue for t in range(T)],
        'discharge_schedule': [discharge[t].varValue for t in range(T)],
        'net_load_profile': [net_load[t].varValue for t in range(T)]
    }

# Example
load_forecast = [800, 750, 700, 680, 700, 750, 850, 920, 980, 1020, 1050, 1080,
                1100, 1090, 1070, 1050, 1080, 1100, 1050, 980, 920, 880, 850, 820]

demand_charge = 15  # $/kW
energy_rate = [0.08] * 24  # $/kWh

result = optimize_peak_shaving(load_forecast, demand_charge, energy_rate,
                               power_capacity=200, energy_capacity=400)

print(f"Peak reduction: {result['peak_reduction_kw']:.0f} kW "
     f"({result['peak_reduction_pct']:.1f}%)")
print(f"Monthly savings: ${result['monthly_savings']:,.0f}")

Renewable Energy Firming

Solar + Storage Optimization

def optimize_solar_plus_storage(solar_generation, load, power_capacity,
                                energy_capacity, tariff_structure):
    """
    Optimize storage with solar to maximize self-consumption
    and minimize grid imports
    """
    from pulp import *

    T = len(solar_generation)
    prob = LpProblem("Solar_Storage", LpMinimize)

    # Variables
    charge = [LpVariable(f"Charge_{t}", lowBound=0, upBound=power_capacity)
             for t in range(T)]
    discharge = [LpVariable(f"Discharge_{t}", lowBound=0, upBound=power_capacity)
                for t in range(T)]
    soc = [LpVariable(f"SOC_{t}", lowBound=0, upBound=energy_capacity)
          for t in range(T)]

    grid_import = [LpVariable(f"Import_{t}", lowBound=0) for t in range(T)]
    grid_export = [LpVariable(f"Export_{t}", lowBound=0) for t in range(T)]

    # Objective: minimize electricity cost
    import_cost = lpSum([grid_import[t] * tariff_structure['import_rate'][t]
                        for t in range(T)])
    export_revenue = lpSum([grid_export[t] * tariff_structure['export_rate'][t]
                           for t in range(T)])

    prob += import_cost - export_revenue

    # Constraints
    for t in range(T):
        # Energy balance
        # Load = Solar + Discharge - Charge + Import - Export
        prob += load[t] == solar_generation[t] + discharge[t] - charge[t] + \
                grid_import[t] - grid_export[t]

        # Battery can only charge from solar
        prob += charge[t] <= solar_generation[t]

        # SOC dynamics
        if t == 0:
            prob += soc[t] == energy_capacity * 0.2 + \
                    charge[t] * 0.92 - discharge[t] / 0.92
        else:
            prob += soc[t] == soc[t-1] + \
                    charge[t] * 0.92 - discharge[t] / 0.92

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Calculate metrics
    total_import = sum([grid_import[t].varValue for t in range(T)])
    total_export = sum([grid_export[t].varValue for t in range(T)])
    total_load = sum(load)
    total_solar = sum(solar_generation)

    self_consumption = total_solar - total_export
    self_consumption_rate = self_consumption / total_solar * 100

    return {
        'total_cost': value(prob.objective),
        'grid_import_kwh': total_import,
        'grid_export_kwh': total_export,
        'self_consumption_kwh': self_consumption,
        'self_consumption_rate_pct': self_consumption_rate,
        'charge_schedule': [charge[t].varValue for t in range(T)],
        'discharge_schedule': [discharge[t].varValue for t in range(T)],
        'soc_profile': [soc[t].varValue for t in range(T)]
    }

Grid Services & Frequency Regulation

Frequency Regulation Bidding

def optimize_frequency_regulation(regulation_prices, energy_prices,
                                 power_capacity, energy_capacity,
                                 performance_score=0.95):
    """
    Optimize battery participation in frequency regulation market

    Parameters:
    - regulation_prices: dict with 'reg_up' and 'reg_down' prices ($/MW)
    - energy_prices: real-time energy prices ($/MWh)
    - power_capacity: battery power rating (MW)
    - energy_capacity: battery energy capacity (MWh)
    - performance_score: historical performance (affects payment)
    """
    from pulp import *

    T = len(regulation_prices['reg_up'])
    prob = LpProblem("Frequency_Regulation", LpMaximize)

    # Variables
    reg_up_capacity = [LpVariable(f"RegUp_{t}", lowBound=0, upBound=power_capacity)
                      for t in range(T)]
    reg_down_capacity = [LpVariable(f"RegDown_{t}", lowBound=0, upBound=power_capacity)
                        for t in range(T)]

    energy_position = [LpVariable(f"Energy_{t}") for t in range(T)]

    # Objective: maximize regulation revenue
    reg_up_revenue = lpSum([reg_up_capacity[t] * regulation_prices['reg_up'][t] *
                           performance_score for t in range(T)])
    reg_down_revenue = lpSum([reg_down_capacity[t] * regulation_prices['reg_down'][t] *
                             performance_score for t in range(T)])

    prob += reg_up_revenue + reg_down_revenue

    # Constraints
    for t in range(T):
        # Power capacity constraint
        prob += reg_up_capacity[t] + reg_down_capacity[t] <= power_capacity

        # Energy capacity constraint (must be able to sustain regulation)
        # Assume 50% deployment over hour
        prob += energy_position[t] + 0.5 * reg_up_capacity[t] <= energy_capacity
        prob += energy_position[t] - 0.5 * reg_down_capacity[t] >= 0

        # Energy neutrality (return to same SOC)
        if t > 0:
            prob += energy_position[t] == energy_position[t-1]

    prob += energy_position[0] == energy_capacity * 0.5

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    return {
        'total_revenue': value(prob.objective),
        'reg_up_capacity': [reg_up_capacity[t].varValue for t in range(T)],
        'reg_down_capacity': [reg_down_capacity[t].varValue for t in range(T)],
        'avg_capacity_offered': np.mean([reg_up_capacity[t].varValue + reg_down_capacity[t].varValue
                                        for t in range(T)])
    }

Battery Degradation & Lifetime Management

Degradation Modeling

class BatteryDegradationModel:
    """
    Model battery degradation from cycling and calendar aging
    """

    def __init__(self, initial_capacity_mwh, chemistry='li-ion'):
        self.initial_capacity = initial_capacity_mwh
        self.current_capacity = initial_capacity_mwh
        self.chemistry = chemistry
        self.total_cycles = 0
        self.total_throughput = 0

    def calculate_cycle_aging(self, depth_of_discharge, num_cycles):
        """
        Calculate capacity loss from cycling

        Cycle life depends on DOD:
        - 10% DOD: ~100,000 cycles
        - 50% DOD: ~10,000 cycles
        - 80% DOD: ~5,000 cycles
        - 100% DOD: ~3,000 cycles
        """
        if self.chemistry == 'li-ion':
            # Empirical cycle life model
            cycle_life_100 = 3000  # cycles at 100% DOD

            # Cycle life increases with lower DOD (roughly exponential)
            cycle_life = cycle_life_100 * (1 / depth_of_discharge) ** 0.5

            # Capacity loss per cycle
            loss_per_cycle = 0.2 / cycle_life  # 20% loss at EOL

            capacity_loss = loss_per_cycle * num_cycles

        elif self.chemistry == 'flow-battery':
            # Flow batteries have minimal cycle degradation
            capacity_loss = 0.0001 * num_cycles

        else:
            capacity_loss = 0

        self.current_capacity -= capacity_loss
        self.total_cycles += num_cycles

        return capacity_loss

    def calculate_calendar_aging(self, days, avg_soc=0.5, avg_temp_c=25):
        """
        Calculate capacity loss from calendar aging

        Higher SOC and temperature accelerate aging
        """
        if self.chemistry == 'li-ion':
            # Base calendar aging: 2-3% per year at 25°C, 50% SOC
            base_rate = 0.025 / 365  # per day

            # Temperature factor (Arrhenius-like)
            temp_factor = np.exp((avg_temp_c - 25) * 0.05)

            # SOC stress factor
            soc_factor = 1 + (avg_soc - 0.5)

            daily_loss_rate = base_rate * temp_factor * soc_factor
            capacity_loss = daily_loss_rate * days * self.initial_capacity

        else:
            capacity_loss = 0

        self.current_capacity -= capacity_loss

        return capacity_loss

    def calculate_state_of_health(self):
        """Return current state of health (%)"""
        return (self.current_capacity / self.initial_capacity) * 100

    def estimate_remaining_life(self, daily_cycles, avg_dod):
        """
        Estimate remaining useful life

        Returns days until 80% capacity threshold
        """
        target_capacity = self.initial_capacity * 0.8
        remaining_capacity_to_lose = self.current_capacity - target_capacity

        if remaining_capacity_to_lose <= 0:
            return 0  # Already below threshold

        # Daily degradation from cycling
        cycle_loss_per_day = self.calculate_cycle_aging(avg_dod, daily_cycles)

        # Daily calendar aging
        calendar_loss_per_day = self.calculate_calendar_aging(1)

        total_daily_loss = cycle_loss_per_day + calendar_loss_per_day

        if total_daily_loss <= 0:
            return float('inf')

        remaining_days = remaining_capacity_to_lose / total_daily_loss

        return remaining_days

# Example usage
battery = BatteryDegradationModel(initial_capacity_mwh=10, chemistry='li-ion')

# Simulate 1 year of operation
for day in range(365):
    # 1 cycle per day at 80% DOD
    battery.calculate_cycle_aging(depth_of_discharge=0.8, num_cycles=1)
    # Calendar aging
    battery.calculate_calendar_aging(days=1, avg_soc=0.6, avg_temp_c=25)

print(f"State of Health after 1 year: {battery.calculate_state_of_health():.1f}%")
print(f"Estimated remaining life: {battery.estimate_remaining_life(1, 0.8)/365:.1f} years")

Multi-Use Case Value Stacking

Stacked Revenue Optimization

def optimize_multi_use_storage(use_cases, power_capacity, energy_capacity,
                               time_horizon=24):
    """
    Optimize battery across multiple revenue streams (value stacking)

    Use cases can include:
    - Energy arbitrage
    - Demand charge reduction
    - Frequency regulation
    - Capacity market
    - Renewable firming
    """
    from pulp import *

    prob = LpProblem("Value_Stacking", LpMaximize)

    T = time_horizon

    # Variables: power allocation to each use case
    allocation = {}
    for use_case in use_cases:
        for t in range(T):
            allocation[use_case['name'], t] = LpVariable(
                f"{use_case['name']}_{t}",
                lowBound=0,
                upBound=power_capacity
            )

    # Objective: maximize total revenue
    total_revenue = []

    for use_case in use_cases:
        for t in range(T):
            value_rate = use_case['value_per_mw_hour'][t]
            total_revenue.append(allocation[use_case['name'], t] * value_rate)

    prob += lpSum(total_revenue)

    # Constraints

    # Total power allocation cannot exceed capacity
    for t in range(T):
        prob += lpSum([allocation[uc['name'], t] for uc in use_cases]) <= power_capacity

    # Use case specific constraints
    for use_case in use_cases:
        if 'min_commitment' in use_case:
            # Some services require minimum commitment
            for t in range(T):
                prob += allocation[use_case['name'], t] >= \
                        use_case['min_commitment'] * power_capacity

        if 'max_hours' in use_case:
            # Some services limited to certain hours per day
            prob += lpSum([allocation[use_case['name'], t]
                          for t in range(T)]) <= use_case['max_hours'] * power_capacity

    # Solve
    prob.solve(PULP_CBC_CMD(msg=0))

    # Calculate revenue by use case
    revenue_breakdown = {}
    for use_case in use_cases:
        revenue = sum([allocation[use_case['name'], t].varValue *
                      use_case['value_per_mw_hour'][t]
                      for t in range(T)])
        revenue_breakdown[use_case['name']] = revenue

    return {
        'total_revenue': value(prob.objective),
        'revenue_breakdown': revenue_breakdown,
        'allocation_schedule': {
            use_case['name']: [allocation[use_case['name'], t].varValue
                              for t in range(T)]
            for use_case in use_cases
        }
    }

# Example
use_cases = [
    {
        'name': 'Energy_Arbitrage',
        'value_per_mw_hour': [5, 4, 3, 2, 2, 3, 8, 15, 20, 22, 24, 23,
                             22, 21, 20, 22, 25, 28, 26, 22, 18, 12, 8, 6]
    },
    {
        'name': 'Frequency_Regulation',
        'value_per_mw_hour': [12] * 24,
        'min_commitment': 0.5,  # Must commit at least 50% if participating
    },
    {
        'name': 'Demand_Response',
        'value_per_mw_hour': [0]*14 + [50, 50, 50, 50] + [0]*6,
        'max_hours': 4  # Only 4 hours per day
    }
]

result = optimize_multi_use_storage(use_cases, power_capacity=10,
                                   energy_capacity=40, time_horizon=24)

print(f"Total daily revenue: ${result['total_revenue']:,.0f}")
for uc, rev in result['revenue_breakdown'].items():
    print(f"  {uc}: ${rev:,.0f} ({rev/result['total_revenue']*100:.1f}%)")

Tools & Libraries

Python Libraries

Optimization:

  • PuLP: Linear programming
  • Pyomo: Advanced optimization modeling
  • cvxpy: Convex optimization
  • gurobipy: Gurobi optimizer

Battery Modeling:

  • PyBaMM: Physics-based battery modeling
  • scikit-learn: Machine learning for degradation

Energy Analysis:

  • pvlib: Solar PV modeling
  • pandapower: Power system analysis
  • SAM (NREL): System Advisor Model

Data & Visualization:

  • pandas, numpy: Data manipulation
  • matplotlib, plotly: Visualization

Commercial Software

Energy Storage:

  • Energy Toolbase: Battery storage analysis and proposals
  • Homer Energy: Hybrid renewable energy system design
  • CAISO BESS: Battery energy storage system tools
  • Stem Athena: AI-powered storage optimization

Grid Integration:

  • AutoGrid Flex: Distributed energy resource optimization
  • Greensmith GEMS: Grid energy management system
  • Fluence Mosaic: Battery energy storage platform
  • Tesla Autobidder: Automated energy trading

Financial Analysis:

  • Aurora: Energy market modeling
  • Ascend Analytics: Storage valuation
  • NREL REopt: Renewable energy integration

Common Challenges & Solutions

Challenge: Revenue Uncertainty

Problem:

  • Volatile electricity prices
  • Changing market rules
  • Technology cost trends

Solutions:

  • Conservative financial projections
  • Diversified revenue streams (value stacking)
  • Flexible contracts and PPAs
  • Real options analysis
  • Scenario-based planning

Challenge: Degradation Management

Problem:

  • Battery capacity fade over time
  • Warranty compliance
  • Optimal replacement timing

Solutions:

  • Degradation-aware dispatch algorithms
  • State-of-health monitoring
  • Conservative DOD and cycle limits
  • Predictive maintenance
  • Augmentation strategies

Challenge: Grid Integration

Problem:

  • Interconnection delays and costs
  • Grid service requirements
  • Utility coordination

Solutions:

  • Early interconnection applications
  • Pre-approved equipment lists
  • Clear operating procedures
  • Regular communication with utility
  • Compliance testing and certification

Challenge: Optimal Sizing

Problem:

  • Uncertain future load/generation
  • Technology cost evolution
  • Competing use cases

Solutions:

  • Sensitivity analysis on key parameters
  • Modular/scalable designs
  • Option value of waiting
  • Pilot programs before full deployment
  • Multi-year optimization

Output Format

Energy Storage Optimization Report

Executive Summary:

  • Recommended storage system configuration
  • Economic analysis and payback
  • Primary value drivers
  • Implementation roadmap

System Specifications:

ParameterValueNotes
TechnologyLi-ion NMCHigh energy density
Power Capacity5 MWAC rating
Energy Capacity20 MWhUsable capacity
Duration4 hoursAt rated power
Round-trip Efficiency88%AC-AC
Warranty10 years / 5,000 cycles80% EOL capacity

Economic Analysis:

MetricValue
Capital Cost$7.5M
Installation & EPC$1.5M
Total Project Cost$9.0M
Annual Revenue$1.2M
Annual O&M$75K
Net Annual Benefit$1.125M
Simple Payback8.0 years
NPV (15 years, 8%)$3.2M
IRR12.5%

Revenue Streams:

Revenue SourceAnnual Value% of Total
Energy Arbitrage$450K37%
Demand Charge Reduction$380K32%
Frequency Regulation$270K22%
Capacity Market$100K8%
Total$1,200K100%

Operational Strategy:

Time PeriodPrimary UseSecondary UseAvg. SOC Target
00:00-06:00Charge (arbitrage)-80%
06:00-10:00Frequency regulation-50%
10:00-14:00Solar firmingRegulation40%
14:00-20:00Peak shavingArbitrage20%
20:00-24:00Discharge (arbitrage)-40%

Performance Metrics:

MetricTargetMonitoring
Daily Cycles1.2SCADA logging
Avg. DOD70%BMS data
Availability> 95%Uptime tracking
Response Time< 1 secMarket compliance
SOH Degradation< 2.5%/yearQuarterly testing

Questions to Ask

If you need more context:

  1. What's the primary application? (arbitrage, peak shaving, renewables, grid services)
  2. What's the scale? (residential, commercial, utility)
  3. What's the grid tariff structure? (TOU, demand charges, real-time pricing)
  4. What renewable generation exists or is planned?
  5. What's the available budget or target payback period?
  6. Are there space, temperature, or safety constraints?
  7. What's the expected project lifetime?

Related Skills

  • power-grid-optimization: For grid integration and dispatch
  • renewable-energy-planning: For solar and wind pairing
  • energy-logistics: For energy supply chain management
  • demand-forecasting: For load and generation forecasting
  • optimization-modeling: For advanced optimization techniques
  • capacity-planning: For long-term capacity planning
  • risk-mitigation: For financial and operational risk management

Facility Location Problem (FLP)

You are an expert in facility location problems and strategic site selection optimization. Your goal is to help determine optimal locations for facilities (warehouses, plants, distribution centers) to minimize total costs while meeting customer demand and capacity constraints.

Initial Assessment

Before solving facility location problems, understand:

  1. Problem Type

    • Uncapacitated Facility Location (UFLP)? (no capacity limits)
    • Capacitated Facility Location (CFLP)? (facilities have capacity limits)
    • p-Median Problem? (locate exactly p facilities)
    • p-Center Problem? (minimize maximum distance)
    • Fixed Charge Location? (fixed opening costs + variable costs)
  2. Facility Characteristics

    • How many potential facility locations?
    • Fixed opening costs per facility?
    • Operating costs (capacity-dependent)?
    • Facility capacities (if capacitated)?
    • Can facilities serve multiple customers?
  3. Customer Requirements

    • How many customers/demand points?
    • Customer demands (quantities)?
    • Service requirements (coverage distance/time)?
    • Single-sourcing or multi-sourcing allowed?
  4. Cost Structure

    • Fixed costs to open facilities?
    • Transportation/distribution costs?
    • Operating costs per unit shipped?
    • Economies of scale?
  5. Constraints

    • Must open exactly p facilities? (p-median)
    • Budget constraints?
    • Capacity constraints?
    • Coverage requirements?
    • Minimum/maximum number of facilities?

Problem Classification

1. Uncapacitated Facility Location Problem (UFLP)

Description:

  • Decide which facilities to open (no capacity limits)
  • Assign customers to open facilities
  • Minimize total fixed + transportation costs

Characteristics:

  • Each facility can serve unlimited demand
  • Most basic FLP variant
  • NP-hard but solvable for moderate instances

Applications:

  • Initial network design
  • Strategic long-term planning
  • High-level site selection

2. Capacitated Facility Location Problem (CFLP)

Description:

  • Facilities have capacity constraints
  • More realistic than UFLP
  • Each customer can be served by multiple facilities

Characteristics:

  • Capacity constraints make problem harder
  • May require more facilities than UFLP
  • More complex solution methods needed

Applications:

  • Warehouse network design
  • Production facility location
  • Service center placement

3. p-Median Problem

Description:

  • Locate exactly p facilities
  • Minimize total (weighted) distance from customers to facilities
  • No fixed costs, no capacity constraints

Characteristics:

  • Number of facilities predetermined
  • Focus on minimizing transportation distance
  • Classic location science problem

Applications:

  • Emergency service location
  • Retail store placement
  • School/hospital location

4. p-Center Problem

Description:

  • Locate p facilities
  • Minimize the maximum distance from any customer to nearest facility
  • Minimax objective (equity-focused)

Characteristics:

  • Ensures no customer too far from service
  • Different objective than p-median
  • Good for emergency services

Applications:

  • Ambulance station location
  • Fire station placement
  • Emergency response planning

Mathematical Formulations

Uncapacitated Facility Location Problem (UFLP)

Sets:

  • I = {1, ..., m}: Set of potential facility locations
  • J = {1, ..., n}: Set of customers

Parameters:

  • f_i: Fixed cost to open facility at location i
  • c_{ij}: Cost to serve customer j from facility i (transportation cost)
  • d_j: Demand of customer j

Decision Variables:

  • y_i ∈ {0,1}: 1 if facility i is opened, 0 otherwise
  • x_{ij} ∈ [0,1]: Fraction of customer j's demand served by facility i

Objective Function:

Minimize: Σ_i f_i * y_i + Σ_i Σ_j c_{ij} * d_j * x_{ij}
          \_____________/   \___________________________/
          Fixed costs       Transportation costs

Constraints:

1. Demand satisfaction: Each customer fully served
   Σ_i x_{ij} = 1,  ∀j ∈ J

2. Facility opening: Can only serve from open facilities
   x_{ij} ≤ y_i,  ∀i ∈ I, ∀j ∈ J

3. Binary facility decisions:
   y_i ∈ {0,1},  ∀i ∈ I

4. Assignment variables:
   x_{ij} ≥ 0,  ∀i ∈ I, ∀j ∈ J

Complexity: NP-hard

Capacitated Facility Location Problem (CFLP)

Additional Parameters:

  • Q_i: Capacity of facility i

Modified Constraints:

1. Demand satisfaction:
   Σ_i x_{ij} = 1,  ∀j ∈ J

2. Capacity constraints:
   Σ_j d_j * x_{ij} ≤ Q_i * y_i,  ∀i ∈ I

3. Opening constraints:
   x_{ij} ≤ y_i,  ∀i ∈ I, ∀j ∈ J

4. Binary variables:
   y_i ∈ {0,1},  ∀i ∈ I
   x_{ij} ≥ 0,  ∀i ∈ I, ∀j ∈ J

p-Median Problem

Objective:

Minimize: Σ_i Σ_j c_{ij} * x_{ij}

Constraints:

1. Each customer assigned to exactly one facility:
   Σ_i x_{ij} = 1,  ∀j ∈ J

2. Exactly p facilities opened:
   Σ_i y_i = p

3. Assignment only to open facilities:
   x_{ij} ≤ y_i,  ∀i ∈ I, ∀j ∈ J

4. Binary variables:
   y_i ∈ {0,1},  ∀i ∈ I
   x_{ij} ∈ {0,1},  ∀i ∈ I, ∀j ∈ J

Exact Solution Methods

1. MIP Formulation with PuLP (UFLP)

from pulp import *
import numpy as np

def solve_uflp(fixed_costs, transport_costs, demands):
    """
    Solve Uncapacitated Facility Location Problem

    Args:
        fixed_costs: list of fixed costs for each facility
        transport_costs: 2D array [facilities x customers] of unit transport costs
        demands: list of customer demands

    Returns:
        dict with optimal solution
    """
    m = len(fixed_costs)  # Number of potential facilities
    n = len(demands)       # Number of customers

    # Create problem
    prob = LpProblem("UFLP", LpMinimize)

    # Decision variables
    # y[i] = 1 if facility i is opened
    y = LpVariable.dicts("facility", range(m), cat='Binary')

    # x[i,j] = fraction of customer j's demand served by facility i
    x = LpVariable.dicts("assign",
                         [(i, j) for i in range(m) for j in range(n)],
                         lowBound=0, upBound=1, cat='Continuous')

    # Objective: Minimize total cost (fixed + transportation)
    prob += (
        lpSum([fixed_costs[i] * y[i] for i in range(m)]) +
        lpSum([transport_costs[i][j] * demands[j] * x[i,j]
               for i in range(m) for j in range(n)]),
        "Total_Cost"
    )

    # Constraints

    # 1. Each customer must be fully served
    for j in range(n):
        prob += (
            lpSum([x[i,j] for i in range(m)]) == 1,
            f"Demand_Customer_{j}"
        )

    # 2. Can only serve from open facilities
    for i in range(m):
        for j in range(n):
            prob += (
                x[i,j] <= y[i],
                f"Open_Facility_{i}_{j}"
            )

    # Solve
    import time
    start_time = time.time()
    prob.solve(PULP_CBC_CMD(msg=1, timeLimit=300))
    solve_time = time.time() - start_time

    # Extract solution
    if LpStatus[prob.status] in ['Optimal', 'Feasible']:
        open_facilities = [i for i in range(m) if y[i].varValue > 0.5]

        assignments = {}
        for j in range(n):
            assignments[j] = []
            for i in range(m):
                if x[i,j].varValue > 0.01:  # Threshold for numerical issues
                    assignments[j].append((i, x[i,j].varValue))

        # Calculate cost breakdown
        fixed_cost_total = sum(fixed_costs[i] for i in open_facilities)
        transport_cost_total = sum(
            transport_costs[i][j] * demands[j] * x[i,j].varValue
            for i in range(m) for j in range(n)
        )

        return {
            'status': LpStatus[prob.status],
            'total_cost': value(prob.objective),
            'fixed_cost': fixed_cost_total,
            'transport_cost': transport_cost_total,
            'open_facilities': open_facilities,
            'num_facilities': len(open_facilities),
            'assignments': assignments,
            'solve_time': solve_time
        }
    else:
        return {
            'status': LpStatus[prob.status],
            'total_cost': None,
            'open_facilities': [],
            'solve_time': solve_time
        }


# Example usage
if __name__ == "__main__":
    # Problem data: 5 potential facilities, 10 customers
    np.random.seed(42)

    # Fixed costs to open each facility
    fixed_costs = [5000, 4500, 6000, 5500, 4800]

    # Transportation costs (facility x customer)
    # Lower cost = closer proximity
    transport_costs = np.array([
        [10, 15, 8, 20, 12, 18, 22, 14, 16, 11],
        [18, 12, 16, 14, 10, 15, 20, 25, 13, 19],
        [14, 20, 18, 10, 16, 12, 15, 18, 22, 14],
        [22, 18, 14, 16, 20, 10, 12, 16, 14, 18],
        [16, 14, 20, 18, 14, 16, 10, 12, 15, 20]
    ])

    # Customer demands
    demands = [100, 150, 80, 120, 90, 110, 130, 95, 105, 125]

    result = solve_uflp(fixed_costs, transport_costs, demands)

    print(f"\n{'='*70}")
    print(f"UNCAPACITATED FACILITY LOCATION PROBLEM - SOLUTION")
    print(f"{'='*70}")
    print(f"Status: {result['status']}")
    print(f"Total Cost: ${result['total_cost']:,.2f}")
    print(f"  Fixed Costs: ${result['fixed_cost']:,.2f}")
    print(f"  Transport Costs: ${result['transport_cost']:,.2f}")
    print(f"\nFacilities Opened: {result['num_facilities']}")
    print(f"Facility IDs: {result['open_facilities']}")
    print(f"\nSolve Time: {result['solve_time']:.2f} seconds")

    print(f"\nCustomer Assignments:")
    for customer_id, assignment in result['assignments'].items():
        print(f"  Customer {customer_id} (demand={demands[customer_id]}):")
        for facility_id, fraction in assignment:
            print(f"    → Facility {facility_id}: {fraction*100:.1f}%")

2. Capacitated Facility Location Problem (CFLP)

def solve_cflp(fixed_costs, transport_costs, demands, capacities):
    """
    Solve Capacitated Facility Location Problem

    Args:
        fixed_costs: list of fixed costs for each facility
        transport_costs: 2D array [facilities x customers]
        demands: list of customer demands
        capacities: list of facility capacities

    Returns:
        dict with optimal solution
    """
    m = len(fixed_costs)
    n = len(demands)

    # Create problem
    prob = LpProblem("CFLP", LpMinimize)

    # Decision variables
    y = LpVariable.dicts("facility", range(m), cat='Binary')
    x = LpVariable.dicts("assign",
                         [(i, j) for i in range(m) for j in range(n)],
                         lowBound=0, cat='Continuous')

    # Objective
    prob += (
        lpSum([fixed_costs[i] * y[i] for i in range(m)]) +
        lpSum([transport_costs[i][j] * demands[j] * x[i,j]
               for i in range(m) for j in range(n)]),
        "Total_Cost"
    )

    # Constraints

    # 1. Each customer fully served
    for j in range(n):
        prob += (
            lpSum([x[i,j] for i in range(m)]) == 1,
            f"Demand_{j}"
        )

    # 2. Capacity constraints at each facility
    for i in range(m):
        prob += (
            lpSum([demands[j] * x[i,j] for j in range(n)]) <= capacities[i] * y[i],
            f"Capacity_{i}"
        )

    # 3. Can only serve from open facilities
    for i in range(m):
        for j in range(n):
            prob += (
                x[i,j] <= y[i],
                f"Open_{i}_{j}"
            )

    # Solve
    start_time = time.time()
    prob.solve(PULP_CBC_CMD(msg=1, timeLimit=300))
    solve_time = time.time() - start_time

    # Extract solution
    if LpStatus[prob.status] in ['Optimal', 'Feasible']:
        open_facilities = [i for i in range(m) if y[i].varValue > 0.5]

        # Calculate utilization for each open facility
        utilization = {}
        for i in open_facilities:
            used_capacity = sum(demands[j] * x[i,j].varValue for j in range(n))
            utilization[i] = (used_capacity / capacities[i]) * 100

        assignments = {}
        for j in range(n):
            assignments[j] = []
            for i in range(m):
                if x[i,j].varValue > 0.01:
                    assignments[j].append((i, x[i,j].varValue))

        return {
            'status': LpStatus[prob.status],
            'total_cost': value(prob.objective),
            'open_facilities': open_facilities,
            'num_facilities': len(open_facilities),
            'utilization': utilization,
            'assignments': assignments,
            'solve_time': solve_time
        }
    else:
        return {
            'status': LpStatus[prob.status],
            'solve_time': solve_time
        }


# Example usage
fixed_costs = [8000, 7500, 9000, 8500, 7800]
transport_costs = np.array([
    [10, 15, 8, 20, 12, 18, 22, 14, 16, 11],
    [18, 12, 16, 14, 10, 15, 20, 25, 13, 19],
    [14, 20, 18, 10, 16, 12, 15, 18, 22, 14],
    [22, 18, 14, 16, 20, 10, 12, 16, 14, 18],
    [16, 14, 20, 18, 14, 16, 10, 12, 15, 20]
])
demands = [100, 150, 80, 120, 90, 110, 130, 95, 105, 125]
capacities = [400, 350, 450, 380, 420]  # Facility capacities

result = solve_cflp(fixed_costs, transport_costs, demands, capacities)

print(f"\n{'='*70}")
print(f"CAPACITATED FACILITY LOCATION PROBLEM - SOLUTION")
print(f"{'='*70}")
print(f"Status: {result['status']}")
print(f"Total Cost: ${result['total_cost']:,.2f}")
print(f"Facilities Opened: {result['num_facilities']}")

print(f"\nFacility Utilization:")
for facility_id in result['open_facilities']:
    print(f"  Facility {facility_id}: {result['utilization'][facility_id]:.1f}% "
          f"(capacity={capacities[facility_id]})")

3. p-Median Problem

def solve_p_median(distances, demands, p):
    """
    Solve p-Median Problem

    Locate exactly p facilities to minimize total weighted distance

    Args:
        distances: 2D array of distances [facilities x customers]
        demands: customer demands (weights)
        p: number of facilities to open

    Returns:
        optimal solution
    """
    m = len(distances)     # Potential facility locations
    n = len(demands)       # Customers

    prob = LpProblem("p_Median", LpMinimize)

    # Decision variables
    y = LpVariable.dicts("facility", range(m), cat='Binary')
    x = LpVariable.dicts("assign",
                         [(i, j) for i in range(m) for j in range(n)],
                         cat='Binary')

    # Objective: Minimize total weighted distance
    prob += (
        lpSum([distances[i][j] * demands[j] * x[i,j]
               for i in range(m) for j in range(n)]),
        "Total_Weighted_Distance"
    )

    # Constraints

    # 1. Each customer assigned to exactly one facility
    for j in range(n):
        prob += (
            lpSum([x[i,j] for i in range(m)]) == 1,
            f"Assign_{j}"
        )

    # 2. Exactly p facilities opened
    prob += (
        lpSum([y[i] for i in range(m)]) == p,
        "p_Facilities"
    )

    # 3. Assignment only to open facilities
    for i in range(m):
        for j in range(n):
            prob += (
                x[i,j] <= y[i],
                f"Open_{i}_{j}"
            )

    # Solve
    start_time = time.time()
    prob.solve(PULP_CBC_CMD(msg=0))
    solve_time = time.time() - start_time

    if LpStatus[prob.status] in ['Optimal', 'Feasible']:
        open_facilities = [i for i in range(m) if y[i].varValue > 0.5]

        assignments = {}
        for j in range(n):
            for i in range(m):
                if x[i,j].varValue > 0.5:
                    assignments[j] = i
                    break

        return {
            'status': LpStatus[prob.status],
            'total_distance': value(prob.objective),
            'open_facilities': open_facilities,
            'assignments': assignments,
            'solve_time': solve_time
        }
    else:
        return {'status': LpStatus[prob.status]}


# Example: Locate 3 facilities among 8 candidates to serve 12 customers
np.random.seed(42)

# Generate random coordinates
facility_coords = np.random.rand(8, 2) * 100
customer_coords = np.random.rand(12, 2) * 100

# Calculate Euclidean distance matrix
distances = np.zeros((8, 12))
for i in range(8):
    for j in range(12):
        distances[i][j] = np.linalg.norm(facility_coords[i] - customer_coords[j])

demands = [100, 150, 80, 120, 90, 110, 130, 95, 105, 125, 115, 140]
p = 3  # Open exactly 3 facilities

result = solve_p_median(distances, demands, p)

print(f"\n{'='*70}")
print(f"p-MEDIAN PROBLEM - SOLUTION")
print(f"{'='*70}")
print(f"Status: {result['status']}")
print(f"Total Weighted Distance: {result['total_distance']:,.2f}")
print(f"Facilities Opened (p={p}): {result['open_facilities']}")
print(f"\nCustomer Assignments:")
for customer_id, facility_id in result['assignments'].items():
    dist = distances[facility_id][customer_id]
    print(f"  Customer {customer_id} → Facility {facility_id} "
          f"(distance={dist:.2f}, demand={demands[customer_id]})")

Greedy Heuristics

1. Greedy Add Algorithm (p-Median)

def greedy_add_p_median(distances, demands, p):
    """
    Greedy heuristic for p-Median Problem

    Iteratively add facility that gives maximum cost reduction

    Time complexity: O(p * m * n)
    Quality: Typically within 10-20% of optimal

    Args:
        distances: distance matrix [facilities x customers]
        demands: customer demands
        p: number of facilities to open

    Returns:
        heuristic solution
    """
    m, n = distances.shape

    open_facilities = []
    assignments = {}

    # Initialize: assign all customers to closest potential facility
    for j in range(n):
        assignments[j] = np.argmin(distances[:, j])

    # Greedily add p facilities
    for _ in range(p):
        best_facility = None
        best_improvement = 0

        for i in range(m):
            if i in open_facilities:
                continue

            # Calculate improvement if we add facility i
            improvement = 0
            for j in range(n):
                current_dist = distances[assignments[j]][j]
                new_dist = distances[i][j]

                if new_dist < current_dist:
                    improvement += demands[j] * (current_dist - new_dist)

            if improvement > best_improvement:
                best_improvement = improvement
                best_facility = i

        if best_facility is not None:
            open_facilities.append(best_facility)

            # Update assignments
            for j in range(n):
                current_dist = distances[assignments[j]][j]
                new_dist = distances[best_facility][j]

                if new_dist < current_dist:
                    assignments[j] = best_facility

    # Calculate total cost
    total_cost = sum(
        distances[assignments[j]][j] * demands[j]
        for j in range(n)
    )

    return {
        'open_facilities': open_facilities,
        'assignments': assignments,
        'total_distance': total_cost,
        'method': 'Greedy Add'
    }

2. Greedy Drop Algorithm

def greedy_drop_p_median(distances, demands, p):
    """
    Greedy drop heuristic for p-Median

    Start with all facilities, iteratively close facility
    with least impact until p remain

    Args:
        distances: distance matrix
        demands: customer demands
        p: number of facilities to keep

    Returns:
        heuristic solution
    """
    m, n = distances.shape

    # Start with all facilities open
    open_facilities = set(range(m))

    # Close facilities until only p remain
    while len(open_facilities) > p:
        best_facility_to_close = None
        min_cost_increase = float('inf')

        for i in open_facilities:
            # Test closing facility i
            test_facilities = open_facilities - {i}

            # Calculate cost with this facility closed
            cost = 0
            for j in range(n):
                min_dist = min(distances[f][j] for f in test_facilities)
                cost += min_dist * demands[j]

            if cost < min_cost_increase:
                min_cost_increase = cost
                best_facility_to_close = i

        open_facilities.remove(best_facility_to_close)

    # Final assignments
    assignments = {}
    for j in range(n):
        best_facility = min(open_facilities,
                          key=lambda f: distances[f][j])
        assignments[j] = best_facility

    total_cost = sum(
        distances[assignments[j]][j] * demands[j]
        for j in range(n)
    )

    return {
        'open_facilities': list(open_facilities),
        'assignments': assignments,
        'total_distance': total_cost,
        'method': 'Greedy Drop'
    }

3. Savings-Based Heuristic (UFLP)

def savings_heuristic_uflp(fixed_costs, transport_costs, demands):
    """
    Savings-based heuristic for UFLP

    Compute savings from opening each facility and open
    facilities in order of savings

    Args:
        fixed_costs: fixed facility costs
        transport_costs: transportation costs
        demands: customer demands

    Returns:
        heuristic solution
    """
    m = len(fixed_costs)
    n = len(demands)

    # Calculate savings for each facility
    # Savings = reduction in transport cost - fixed cost
    savings = []

    for i in range(m):
        # Calculate transport cost if facility i serves customers
        transport_saving = 0

        # Assume without facility i, customers served by most expensive option
        for j in range(n):
            # Cost to serve customer j from facility i
            cost_from_i = transport_costs[i][j] * demands[j]

            # Cost to serve from next best facility
            other_costs = [transport_costs[k][j] * demands[j]
                          for k in range(m) if k != i]

            if other_costs:
                min_other_cost = min(other_costs)
                transport_saving += max(0, min_other_cost - cost_from_i)

        net_saving = transport_saving - fixed_costs[i]
        savings.append((net_saving, i))

    # Sort by savings (descending)
    savings.sort(reverse=True)

    # Open facilities with positive savings
    open_facilities = []
    for saving, facility_id in savings:
        if saving > 0:
            open_facilities.append(facility_id)

    # If no positive savings, open at least one facility
    if not open_facilities:
        # Open facility with lowest total cost for all customers
        best_facility = None
        min_cost = float('inf')

        for i in range(m):
            cost = fixed_costs[i] + sum(
                transport_costs[i][j] * demands[j] for j in range(n)
            )
            if cost < min_cost:
                min_cost = cost
                best_facility = i

        open_facilities = [best_facility]

    # Assign customers to nearest open facility
    assignments = {}
    for j in range(n):
        best_facility = min(open_facilities,
                          key=lambda i: transport_costs[i][j])
        assignments[j] = best_facility

    # Calculate total cost
    fixed_cost_total = sum(fixed_costs[i] for i in open_facilities)
    transport_cost_total = sum(
        transport_costs[assignments[j]][j] * demands[j]
        for j in range(n)
    )
    total_cost = fixed_cost_total + transport_cost_total

    return {
        'open_facilities': open_facilities,
        'assignments': assignments,
        'total_cost': total_cost,
        'fixed_cost': fixed_cost_total,
        'transport_cost': transport_cost_total,
        'method': 'Savings Heuristic'
    }

Local Search Improvements

1. Facility Swap Neighborhood

def facility_swap_local_search(distances, demands, initial_solution, p):
    """
    Local search with facility swap moves for p-Median

    Swap an open facility with a closed one if it improves objective

    Args:
        distances: distance matrix
        demands: customer demands
        initial_solution: starting solution
        p: number of facilities

    Returns:
        improved solution
    """
    m, n = distances.shape

    open_facilities = set(initial_solution['open_facilities'])
    closed_facilities = set(range(m)) - open_facilities

    def calculate_cost(facilities):
        """Calculate total cost for given facility set"""
        cost = 0
        for j in range(n):
            min_dist = min(distances[f][j] for f in facilities)
            cost += min_dist * demands[j]
        return cost

    current_cost = calculate_cost(open_facilities)
    improved = True

    while improved:
        improved = False
        best_swap = None
        best_cost = current_cost

        # Try all swaps
        for facility_in in closed_facilities:
            for facility_out in open_facilities:
                # Test swap
                test_facilities = (open_facilities - {facility_out}) | {facility_in}
                test_cost = calculate_cost(test_facilities)

                if test_cost < best_cost:
                    best_cost = test_cost
                    best_swap = (facility_in, facility_out)
                    improved = True

        if improved:
            facility_in, facility_out = best_swap
            open_facilities = (open_facilities - {facility_out}) | {facility_in}
            closed_facilities = (closed_facilities - {facility_in}) | {facility_out}
            current_cost = best_cost

    # Final assignments
    assignments = {}
    for j in range(n):
        best_facility = min(open_facilities,
                          key=lambda f: distances[f][j])
        assignments[j] = best_facility

    return {
        'open_facilities': list(open_facilities),
        'assignments': assignments,
        'total_distance': current_cost,
        'method': 'Facility Swap Local Search'
    }

2. Customer Reassignment

def customer_reassignment(open_facilities, distances, demands):
    """
    Improve solution by optimally reassigning customers

    Given open facilities, assign each customer to nearest facility

    Args:
        open_facilities: list of open facility indices
        distances: distance matrix
        demands: customer demands

    Returns:
        optimal assignments for given facilities
    """
    n = distances.shape[1]

    assignments = {}
    for j in range(n):
        best_facility = min(open_facilities,
                          key=lambda i: distances[i][j])
        assignments[j] = best_facility

    total_cost = sum(
        distances[assignments[j]][j] * demands[j]
        for j in range(n)
    )

    return {
        'assignments': assignments,
        'total_cost': total_cost
    }

Metaheuristics

1. Simulated Annealing for p-Median

import random
import math

def simulated_annealing_p_median(distances, demands, p,
                                 initial_temp=1000, cooling_rate=0.95,
                                 max_iterations=5000):
    """
    Simulated Annealing for p-Median Problem

    Args:
        distances: distance matrix
        demands: customer demands
        p: number of facilities
        initial_temp: starting temperature
        cooling_rate: temperature reduction factor
        max_iterations: maximum iterations

    Returns:
        best solution found
    """
    m, n = distances.shape

    def calculate_cost(facilities):
        cost = 0
        for j in range(n):
            min_dist = min(distances[f][j] for f in facilities)
            cost += min_dist * demands[j]
        return cost

    # Initial solution: random p facilities
    current_facilities = set(random.sample(range(m), p))
    current_cost = calculate_cost(current_facilities)

    best_facilities = current_facilities.copy()
    best_cost = current_cost

    temperature = initial_temp

    for iteration in range(max_iterations):
        # Generate neighbor: swap one facility
        closed = list(set(range(m)) - current_facilities)

        if not closed:
            break

        facility_out = random.choice(list(current_facilities))
        facility_in = random.choice(closed)

        neighbor_facilities = (current_facilities - {facility_out}) | {facility_in}
        neighbor_cost = calculate_cost(neighbor_facilities)

        delta = neighbor_cost - current_cost

        # Accept or reject
        if delta < 0 or random.random() < math.exp(-delta / temperature):
            current_facilities = neighbor_facilities
            current_cost = neighbor_cost

            if current_cost < best_cost:
                best_facilities = current_facilities.copy()
                best_cost = current_cost

        # Cool down
        temperature *= cooling_rate

        if temperature < 0.1:
            break

    # Final assignments
    assignments = {}
    for j in range(n):
        best_facility = min(best_facilities,
                          key=lambda f: distances[f][j])
        assignments[j] = best_facility

    return {
        'open_facilities': list(best_facilities),
        'assignments': assignments,
        'total_distance': best_cost,
        'method': 'Simulated Annealing'
    }

2. Genetic Algorithm for UFLP

def genetic_algorithm_uflp(fixed_costs, transport_costs, demands,
                          population_size=50, generations=200,
                          mutation_rate=0.15):
    """
    Genetic Algorithm for Uncapacitated Facility Location

    Args:
        fixed_costs: facility fixed costs
        transport_costs: transportation costs
        demands: customer demands
        population_size: GA population size
        generations: number of generations
        mutation_rate: mutation probability

    Returns:
        best solution
    """
    m = len(fixed_costs)
    n = len(demands)

    def decode_chromosome(chromosome):
        """Convert binary chromosome to open facilities"""
        return [i for i in range(m) if chromosome[i] == 1]

    def calculate_fitness(chromosome):
        """Calculate fitness (inverse of cost)"""
        open_facilities = decode_chromosome(chromosome)

        if not open_facilities:
            return 0  # Invalid solution

        # Fixed costs
        fixed_cost = sum(fixed_costs[i] for i in open_facilities)

        # Transportation costs
        transport_cost = 0
        for j in range(n):
            min_cost = min(transport_costs[i][j] for i in open_facilities)
            transport_cost += min_cost * demands[j]

        total_cost = fixed_cost + transport_cost
        return 1.0 / (1.0 + total_cost)

    def create_individual():
        """Create random chromosome"""
        # Ensure at least one facility open
        chromosome = [random.randint(0, 1) for _ in range(m)]
        if sum(chromosome) == 0:
            chromosome[random.randint(0, m-1)] = 1
        return chromosome

    def crossover(parent1, parent2):
        """Uniform crossover"""
        child = []
        for i in range(m):
            child.append(parent1[i] if random.random() < 0.5 else parent2[i])

        # Ensure at least one facility
        if sum(child) == 0:
            child[random.randint(0, m-1)] = 1

        return child

    def mutate(chromosome):
        """Bit flip mutation"""
        for i in range(m):
            if random.random() < mutation_rate:
                chromosome[i] = 1 - chromosome[i]

        # Ensure at least one facility
        if sum(chromosome) == 0:
            chromosome[random.randint(0, m-1)] = 1

        return chromosome

    # Initialize population
    population = [create_individual() for _ in range(population_size)]

    best_chromosome = None
    best_fitness = 0

    for generation in range(generations):
        # Evaluate fitness
        fitnesses = [calculate_fitness(ind) for ind in population]

        # Track best
        max_fitness = max(fitnesses)
        if max_fitness > best_fitness:
            best_fitness = max_fitness
            best_chromosome = population[fitnesses.index(max_fitness)].copy()

        # Selection and reproduction
        new_population = []

        # Elitism
        elite_count = int(0.1 * population_size)
        elite_indices = sorted(range(len(fitnesses)),
                             key=lambda i: fitnesses[i],
                             reverse=True)[:elite_count]
        new_population = [population[i].copy() for i in elite_indices]

        # Create offspring
        while len(new_population) < population_size:
            # Tournament selection
            parent1 = max(random.sample(list(zip(population, fitnesses)), 3),
                         key=lambda x: x[1])[0]
            parent2 = max(random.sample(list(zip(population, fitnesses)), 3),
                         key=lambda x: x[1])[0]

            child = crossover(parent1, parent2)
            child = mutate(child)

            new_population.append(child)

        population = new_population

    # Decode best solution
    open_facilities = decode_chromosome(best_chromosome)

    # Assign customers
    assignments = {}
    for j in range(n):
        best_facility = min(open_facilities,
                          key=lambda i: transport_costs[i][j])
        assignments[j] = best_facility

    # Calculate costs
    fixed_cost = sum(fixed_costs[i] for i in open_facilities)
    transport_cost = sum(
        transport_costs[assignments[j]][j] * demands[j]
        for j in range(n)
    )

    return {
        'open_facilities': open_facilities,
        'assignments': assignments,
        'total_cost': fixed_cost + transport_cost,
        'fixed_cost': fixed_cost,
        'transport_cost': transport_cost,
        'method': 'Genetic Algorithm'
    }

Complete Facility Location Solver

import time

class FacilityLocationSolver:
    """
    Comprehensive Facility Location Problem Solver

    Supports UFLP, CFLP, p-Median, and multiple solution methods
    """

    def __init__(self):
        self.fixed_costs = None
        self.transport_costs = None
        self.demands = None
        self.capacities = None
        self.problem_type = None

    def load_problem(self, fixed_costs=None, transport_costs=None,
                    demands=None, capacities=None, problem_type='UFLP'):
        """
        Load problem data

        Args:
            fixed_costs: list of facility fixed costs
            transport_costs: 2D array [facilities x customers]
            demands: customer demands
            capacities: facility capacities (for CFLP)
            problem_type: 'UFLP', 'CFLP', or 'p-Median'
        """
        self.fixed_costs = np.array(fixed_costs) if fixed_costs else None
        self.transport_costs = np.array(transport_costs)
        self.demands = np.array(demands)
        self.capacities = np.array(capacities) if capacities else None
        self.problem_type = problem_type

        print(f"Loaded {problem_type} problem:")
        print(f"  Facilities: {len(transport_costs)}")
        print(f"  Customers: {len(demands)}")
        print(f"  Total demand: {sum(demands)}")
        if capacities:
            print(f"  Total capacity: {sum(capacities)}")

    def solve_exact(self, time_limit=300):
        """
        Solve using exact MIP method

        Args:
            time_limit: time limit in seconds

        Returns:
            optimal/best solution
        """
        print(f"\nSolving {self.problem_type} with MIP (exact)...")

        if self.problem_type == 'UFLP':
            return solve_uflp(self.fixed_costs, self.transport_costs, self.demands)
        elif self.problem_type == 'CFLP':
            return solve_cflp(self.fixed_costs, self.transport_costs,
                            self.demands, self.capacities)
        else:
            raise ValueError(f"Exact solve not implemented for {self.problem_type}")

    def solve_heuristic(self, method='greedy', p=None):
        """
        Solve using heuristic method

        Args:
            method: 'greedy_add', 'greedy_drop', 'savings', 'sa', 'ga'
            p: number of facilities (for p-median)

        Returns:
            heuristic solution
        """
        print(f"\nSolving with {method} heuristic...")

        if method == 'greedy_add' and self.problem_type == 'p-Median':
            return greedy_add_p_median(self.transport_costs, self.demands, p)

        elif method == 'greedy_drop' and self.problem_type == 'p-Median':
            return greedy_drop_p_median(self.transport_costs, self.demands, p)

        elif method == 'savings' and self.problem_type == 'UFLP':
            return savings_heuristic_uflp(self.fixed_costs,
                                         self.transport_costs,
                                         self.demands)

        elif method == 'sa':
            if self.problem_type == 'p-Median':
                return simulated_annealing_p_median(
                    self.transport_costs, self.demands, p)
            else:
                raise ValueError("SA only for p-Median currently")

        elif method == 'ga' and self.problem_type == 'UFLP':
            return genetic_algorithm_uflp(self.fixed_costs,
                                         self.transport_costs,
                                         self.demands)

        else:
            raise ValueError(f"Unknown method {method} for {self.problem_type}")

    def compare_methods(self, methods, p=None):
        """
        Compare multiple solution methods

        Args:
            methods: list of method names
            p: number of facilities (for p-median)

        Returns:
            comparison dataframe
        """
        import pandas as pd

        results = []

        for method in methods:
            start_time = time.time()

            try:
                if method == 'exact':
                    solution = self.solve_exact()
                    cost_key = 'total_cost' if 'total_cost' in solution else 'total_distance'
                else:
                    solution = self.solve_heuristic(method, p)
                    cost_key = 'total_cost' if 'total_cost' in solution else 'total_distance'

                solve_time = time.time() - start_time

                results.append({
                    'Method': method,
                    'Cost': solution[cost_key],
                    'Facilities': len(solution['open_facilities']),
                    'Status': solution.get('status', 'Heuristic'),
                    'Time (s)': f"{solve_time:.3f}"
                })

            except Exception as e:
                print(f"  Error with {method}: {e}")

        df = pd.DataFrame(results)

        # Calculate gap from best
        if len(df) > 0:
            best_cost = df['Cost'].min()
            df['Gap %'] = ((df['Cost'] - best_cost) / best_cost * 100).round(2)

        return df

    def visualize_solution(self, solution, facility_coords, customer_coords):
        """
        Visualize facility location solution

        Args:
            solution: solution dictionary
            facility_coords: array of facility coordinates
            customer_coords: array of customer coordinates
        """
        import matplotlib.pyplot as plt

        plt.figure(figsize=(12, 8))

        # Plot all potential facilities (gray)
        for i, coord in enumerate(facility_coords):
            if i not in solution['open_facilities']:
                plt.plot(coord[0], coord[1], 's', color='lightgray',
                        markersize=10, alpha=0.5)

        # Plot open facilities (red)
        for i in solution['open_facilities']:
            coord = facility_coords[i]
            plt.plot(coord[0], coord[1], 's', color='red',
                    markersize=15, label='Open Facility' if i == solution['open_facilities'][0] else '')

        # Plot customers (blue)
        for j, coord in enumerate(customer_coords):
            plt.plot(coord[0], coord[1], 'o', color='blue',
                    markersize=8, alpha=0.7)

        # Draw assignments
        if 'assignments' in solution:
            for customer_id, assignment in solution['assignments'].items():
                if isinstance(assignment, int):
                    facility_id = assignment
                    fraction = 1.0
                else:
                    facility_id, fraction = assignment[0] if isinstance(assignment, list) else (assignment, 1.0)

                customer_coord = customer_coords[customer_id]
                facility_coord = facility_coords[facility_id]

                plt.plot([customer_coord[0], facility_coord[0]],
                        [customer_coord[1], facility_coord[1]],
                        'k-', alpha=0.2, linewidth=0.5)

        plt.xlabel('X Coordinate')
        plt.ylabel('Y Coordinate')
        plt.title(f'Facility Location Solution - {solution.get("method", "Unknown Method")}')
        plt.legend()
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.show()


# Complete example
if __name__ == "__main__":
    print("="*70)
    print("FACILITY LOCATION PROBLEM - COMPREHENSIVE EXAMPLE")
    print("="*70)

    # Generate problem data
    np.random.seed(42)

    n_facilities = 10
    n_customers = 20

    # Generate coordinates
    facility_coords = np.random.rand(n_facilities, 2) * 100
    customer_coords = np.random.rand(n_customers, 2) * 100

    # Calculate distance matrix
    distances = np.zeros((n_facilities, n_customers))
    for i in range(n_facilities):
        for j in range(n_customers):
            distances[i][j] = np.linalg.norm(
                facility_coords[i] - customer_coords[j]
            )

    # Problem parameters
    fixed_costs = np.random.uniform(5000, 8000, n_facilities)
    transport_costs = distances * 10  # Cost per unit per distance
    demands = np.random.uniform(50, 200, n_customers)
    capacities = np.random.uniform(800, 1200, n_facilities)

    # Solve UFLP
    print("\n" + "="*70)
    print("UNCAPACITATED FACILITY LOCATION PROBLEM")
    print("="*70)

    solver = FacilityLocationSolver()
    solver.load_problem(fixed_costs, transport_costs, demands, problem_type='UFLP')

    # Compare methods
    comparison = solver.compare_methods(['exact', 'savings', 'ga'])
    print("\nMethod Comparison:")
    print(comparison.to_string(index=False))

    # Solve and visualize best solution
    best_solution = solver.solve_exact()
    print(f"\nBest Solution:")
    print(f"  Total Cost: ${best_solution['total_cost']:,.2f}")
    print(f"  Fixed Cost: ${best_solution['fixed_cost']:,.2f}")
    print(f"  Transport Cost: ${best_solution['transport_cost']:,.2f}")
    print(f"  Facilities Opened: {len(best_solution['open_facilities'])}")
    print(f"  Facility IDs: {best_solution['open_facilities']}")

    # Visualize
    solver.visualize_solution(best_solution, facility_coords, customer_coords)

Tools & Libraries

Python Libraries

Optimization:

  • PuLP: MIP modeling (recommended for UFLP/CFLP)
  • Pyomo: Advanced optimization modeling
  • OR-Tools (Google): Fast heuristics and exact methods
  • Gurobi: Commercial solver (academic license available)
  • CPLEX: IBM commercial solver

Specialized:

  • scikit-learn: Clustering for facility location
  • scipy.optimize: General optimization
  • geopy: Distance calculations with real coordinates

Visualization:

  • matplotlib: Basic visualization
  • plotly: Interactive maps
  • folium: Geographic visualization
  • seaborn: Statistical visualization

Commercial Software

  • Gurobi Optimizer: State-of-art MIP solver
  • IBM ILOG CPLEX: Enterprise optimization
  • FICO Xpress: Optimization suite
  • AMPL: Modeling language + solvers

Cloud Services

  • Google Maps Platform: Distance Matrix API
  • AWS Location Service: Location-based services
  • Azure Maps: Microsoft mapping service

Common Challenges & Solutions

Challenge: Large-Scale Problems

Problem:

  • 1000s of potential facilities
  • 10,000s of customers
  • Exact methods too slow

Solutions:

  • Use heuristics (savings, greedy add/drop)
  • Lagrangian relaxation
  • Decomposition methods (Benders)
  • Metaheuristics (SA, GA, Tabu Search)
  • Preprocessing to reduce problem size
  • Clustering customers before solving

Challenge: Capacity Constraints

Problem:

  • CFLP is harder than UFLP
  • May need many facilities
  • Difficult to get tight bounds

Solutions:

  • Valid inequalities to strengthen formulation
  • Branch-and-price algorithms
  • Column generation
  • Specialized heuristics
  • Consider multi-sourcing if allowed

Challenge: Multiple Objectives

Problem:

  • Minimize cost AND maximize service
  • Trade-off between # facilities and service quality
  • Stakeholder preferences vary

Solutions:

  • Multi-objective optimization
  • Weighted sum method
  • Epsilon-constraint method
  • Pareto frontier analysis
  • Scenario analysis with different weights

Challenge: Dynamic Demand

Problem:

  • Demand changes over time
  • Seasonal variations
  • Facility decisions long-term

Solutions:

  • Robust optimization
  • Stochastic programming
  • Scenario-based planning
  • Flexible/modular facility design
  • Rolling horizon approach

Challenge: Real-World Distances

Problem:

  • Euclidean distances unrealistic
  • Need actual road networks
  • Traffic considerations

Solutions:

  • Use Google Maps Distance Matrix API
  • Pre-compute actual distances
  • Consider time-of-day effects
  • Use real logistics data

Output Format

Facility Location Solution Report

Problem Instance:

  • Problem Type: Uncapacitated Facility Location
  • Potential Facilities: 10
  • Customers: 20
  • Total Demand: 2,450 units
  • Optimization: Minimize fixed + transportation costs

Optimal Solution:

MetricValue
Total Cost$87,342
Fixed Costs$23,500
Transportation Costs$63,842
Facilities Opened4
Average Demand per Facility612.5 units
Solution Time3.7 seconds
Solution StatusOptimal

Open Facilities:

Facility IDLocationFixed CostCustomers ServedTotal Demand
2(34.2, 67.8)$6,2006720 units
5(78.1, 23.4)$5,8005590 units
7(12.5, 45.9)$5,9004480 units
9(56.3, 89.2)$5,6005660 units

Customer Assignments:

CustomerDemandAssigned FacilityDistanceTransport Cost
C01120Facility 212.3 km$1,476
C02150Facility 58.7 km$1,305
...............

Cost Breakdown:

  • Fixed costs: 26.9% of total
  • Transportation costs: 73.1% of total
  • Average cost per unit: $35.67

Questions to Ask

If you need more context:

  1. What type of facility location problem? (UFLP, CFLP, p-Median, p-Center)
  2. How many potential facility locations? How many customers?
  3. What are the fixed costs to open facilities?
  4. Are there capacity constraints on facilities?
  5. What are the transportation/service costs?
  6. Do you have coordinates or a distance matrix?
  7. Is demand fixed or variable/uncertain?
  8. Are there minimum or maximum number of facilities?
  9. Single-sourcing (one facility per customer) or multi-sourcing allowed?
  10. What's the planning horizon? (short-term tactical vs. long-term strategic)
  11. Any special requirements? (coverage distance, service levels)
  12. Budget constraints on total capital investment?

Related Skills

  • hub-location-problem: For hub-and-spoke networks
  • warehouse-location-optimization: Warehouse-specific considerations
  • distribution-center-network: Distribution network design
  • network-design: Broader supply chain network design
  • set-covering-problem: Coverage-based facility location
  • network-flow-optimization: Flow-based facility allocation
  • optimization-modeling: General MIP formulation techniques
  • multi-objective-optimization: Multiple criteria optimization
  • stochastic-optimization: Uncertain demand scenarios
  • inventory-routing-problem: Joint location-inventory-routing

Fleet Management

You are an expert in transportation fleet management and optimization. Your goal is to help design cost-effective fleet strategies, optimize fleet size and composition, manage vehicle lifecycle, and maximize fleet utilization while maintaining service levels.

Initial Assessment

Before developing fleet strategies, understand:

  1. Current Fleet Composition

    • How many vehicles in fleet?
    • Vehicle types and ages?
    • Owned, leased, or mixed?
    • Current utilization rates?
  2. Business Requirements

    • Service area and coverage?
    • Demand patterns (seasonal, daily)?
    • Service level requirements?
    • Growth projections?
  3. Cost Structure

    • Acquisition costs (purchase, lease)?
    • Operating costs (fuel, maintenance, insurance)?
    • Driver labor costs?
    • Disposal/residual values?
  4. Operational Constraints

    • Regulatory requirements (DOT, emissions)?
    • Driver availability?
    • Garage/parking capacity?
    • Technology systems (GPS, telematics)?

Fleet Management Framework

Strategic Fleet Decisions

1. Fleet Sizing

  • Minimum fleet size to meet demand
  • Trade-off: fixed costs vs. service flexibility
  • Peak vs. average demand planning
  • Reserve capacity buffer

2. Fleet Composition

  • Vehicle types and capabilities
  • Payload capacities
  • Specialized equipment needs
  • Multi-temperature, liftgates, etc.

3. Acquisition Strategy

  • Buy vs. lease vs. rent
  • New vs. used vehicles
  • Replacement cycles
  • Residual value considerations

4. Utilization Optimization

  • Route efficiency
  • Backhaul optimization
  • Asset sharing
  • Cross-functional use

Fleet Sizing Models

Peak Demand Method

import numpy as np
import pandas as pd

def fleet_size_peak_demand(daily_demand, vehicle_capacity,
                          utilization_target=0.85,
                          peak_percentile=95):
    """
    Calculate fleet size based on peak demand

    Parameters:
    - daily_demand: historical daily demand data
    - vehicle_capacity: capacity per vehicle (units, weight, volume)
    - utilization_target: target utilization (0.0-1.0)
    - peak_percentile: percentile for peak planning (e.g., 95)
    """

    # Calculate peak demand at specified percentile
    peak_demand = np.percentile(daily_demand, peak_percentile)

    # Calculate required fleet size
    fleet_size = np.ceil(peak_demand / (vehicle_capacity * utilization_target))

    # Calculate statistics
    avg_demand = np.mean(daily_demand)
    avg_utilization = avg_demand / (fleet_size * vehicle_capacity)

    return {
        'fleet_size': int(fleet_size),
        'peak_demand': peak_demand,
        'avg_demand': avg_demand,
        'peak_utilization': utilization_target,
        'avg_utilization': avg_utilization,
        'days_at_full_capacity': np.sum(daily_demand >= fleet_size * vehicle_capacity)
    }

# Example usage
daily_deliveries = np.random.normal(1200, 250, 365)  # 365 days of data
result = fleet_size_peak_demand(daily_deliveries, vehicle_capacity=80)

print(f"Required fleet size: {result['fleet_size']} vehicles")
print(f"Peak demand (95th percentile): {result['peak_demand']:.0f} deliveries")
print(f"Average utilization: {result['avg_utilization']:.1%}")

Queue Theory Approach

from scipy.stats import poisson
import math

def fleet_size_queue_theory(avg_requests_per_hour, avg_service_time_hours,
                           service_level=0.95):
    """
    Calculate fleet size using queue theory (M/M/c model)

    Parameters:
    - avg_requests_per_hour: arrival rate (λ)
    - avg_service_time_hours: average time per delivery (1/μ)
    - service_level: target probability of no wait
    """

    # Calculate traffic intensity
    lambda_rate = avg_requests_per_hour
    mu_rate = 1 / avg_service_time_hours
    rho = lambda_rate / mu_rate

    # Minimum servers (vehicles) needed
    min_servers = math.ceil(rho)

    # Find minimum servers to meet service level
    for c in range(min_servers, min_servers + 20):
        # Erlang C formula (probability of waiting)
        prob_wait = erlang_c(lambda_rate, mu_rate, c)

        if prob_wait <= (1 - service_level):
            return {
                'fleet_size': c,
                'utilization': rho / c,
                'prob_wait': prob_wait,
                'avg_queue_length': prob_wait * rho / (c - rho)
            }

    return {'fleet_size': min_servers + 20, 'message': 'Service level not achievable'}

def erlang_c(lambda_rate, mu_rate, c):
    """Calculate Erlang C probability (probability of waiting)"""
    rho = lambda_rate / mu_rate
    numerator = (c * rho) ** c / math.factorial(c)
    denominator = sum((c * rho) ** k / math.factorial(k) for k in range(c))
    denominator += (c * rho) ** c / (math.factorial(c) * (1 - rho / c))

    erlang_b = numerator / denominator
    erlang_c = erlang_b / (1 + erlang_b * (1 - rho / c))

    return erlang_c

Simulation-Based Sizing

import numpy as np
import simpy

class FleetSimulation:
    """
    Discrete-event simulation for fleet sizing

    Simulates daily operations to determine optimal fleet size
    """

    def __init__(self, env, num_vehicles):
        self.env = env
        self.vehicles = simpy.Resource(env, capacity=num_vehicles)
        self.completed_deliveries = 0
        self.total_wait_time = 0
        self.waiting_customers = 0

    def delivery_process(self, customer_id, arrival_time, service_time):
        """Simulate a single delivery"""
        # Wait for available vehicle
        with self.vehicles.request() as request:
            wait_start = self.env.now
            yield request

            wait_time = self.env.now - wait_start
            self.total_wait_time += wait_time

            if wait_time > 0:
                self.waiting_customers += 1

            # Perform delivery
            yield self.env.timeout(service_time)
            self.completed_deliveries += 1

def run_fleet_simulation(num_vehicles, num_days=30,
                        avg_orders_per_day=100,
                        avg_service_time=2.0):
    """
    Run fleet simulation

    Parameters:
    - num_vehicles: fleet size to test
    - num_days: simulation duration
    - avg_orders_per_day: average daily orders
    - avg_service_time: average hours per delivery
    """

    env = simpy.Environment()
    fleet = FleetSimulation(env, num_vehicles)

    # Generate delivery requests
    def generate_orders():
        for day in range(num_days):
            # Daily orders (Poisson distribution)
            num_orders = np.random.poisson(avg_orders_per_day)

            for order in range(num_orders):
                # Arrival time (throughout business day)
                arrival_time = day * 24 + np.random.uniform(8, 18)

                # Service time (lognormal distribution)
                service_time = np.random.lognormal(
                    mean=np.log(avg_service_time),
                    sigma=0.5
                )

                env.process(fleet.delivery_process(
                    customer_id=f"D{day}_O{order}",
                    arrival_time=arrival_time,
                    service_time=service_time
                ))

                yield env.timeout(0)

    env.process(generate_orders())
    env.run(until=num_days * 24)

    # Calculate metrics
    service_level = 1 - (fleet.waiting_customers / fleet.completed_deliveries)
    avg_wait = fleet.total_wait_time / fleet.completed_deliveries if fleet.completed_deliveries > 0 else 0
    utilization = fleet.completed_deliveries * avg_service_time / (num_vehicles * num_days * 24)

    return {
        'fleet_size': num_vehicles,
        'completed_deliveries': fleet.completed_deliveries,
        'service_level': service_level,
        'avg_wait_time': avg_wait,
        'utilization': utilization
    }

# Find optimal fleet size through simulation
def find_optimal_fleet_size(target_service_level=0.90):
    """Test different fleet sizes to find optimal"""

    results = []

    for fleet_size in range(5, 25):
        result = run_fleet_simulation(num_vehicles=fleet_size, num_days=30)
        results.append(result)

        if result['service_level'] >= target_service_level:
            print(f"Optimal fleet size: {fleet_size} vehicles")
            print(f"Service level: {result['service_level']:.2%}")
            print(f"Utilization: {result['utilization']:.2%}")
            return result

    return results

Total Cost of Ownership (TCO)

TCO Components

1. Acquisition Costs

  • Purchase price or lease payments
  • Registration and licensing
  • Initial equipment (GPS, racks, etc.)

2. Operating Costs

  • Fuel
  • Maintenance and repairs
  • Tires
  • Insurance
  • Tolls and permits

3. Overhead Costs

  • Depreciation (owned vehicles)
  • Storage/parking
  • Fleet management systems
  • Administrative overhead

4. Disposal Costs

  • Residual value (owned)
  • Lease-end charges (leased)
  • Remarketing costs

TCO Calculator

class VehicleTCO:
    """
    Calculate Total Cost of Ownership for vehicles

    Compares buy vs. lease scenarios
    """

    def __init__(self, vehicle_type):
        self.vehicle_type = vehicle_type

    def calculate_purchase_tco(self, purchase_price, useful_life_years,
                               annual_miles, residual_value_pct=0.20):
        """
        Calculate TCO for purchased vehicle

        Parameters:
        - purchase_price: initial purchase cost
        - useful_life_years: ownership period
        - annual_miles: expected annual mileage
        - residual_value_pct: estimated residual value as % of purchase
        """

        # Annual operating costs
        fuel_cost_per_mile = 0.35  # varies by vehicle type
        maintenance_per_mile = 0.15
        insurance_annual = 2500
        registration_annual = 500
        depreciation_annual = purchase_price * (1 - residual_value_pct) / useful_life_years

        # Calculate annual cost
        annual_cost = {
            'fuel': annual_miles * fuel_cost_per_mile,
            'maintenance': annual_miles * maintenance_per_mile,
            'insurance': insurance_annual,
            'registration': registration_annual,
            'depreciation': depreciation_annual
        }

        total_annual = sum(annual_cost.values())

        # Total cost over ownership
        total_operating = total_annual * useful_life_years
        residual_value = purchase_price * residual_value_pct
        net_cost = purchase_price + total_operating - residual_value

        # Cost per mile
        total_miles = annual_miles * useful_life_years
        cost_per_mile = net_cost / total_miles if total_miles > 0 else 0

        return {
            'annual_cost': total_annual,
            'annual_breakdown': annual_cost,
            'total_cost': net_cost,
            'cost_per_mile': cost_per_mile,
            'cost_per_month': total_annual / 12,
            'residual_value': residual_value
        }

    def calculate_lease_tco(self, monthly_lease_payment, lease_term_years,
                           annual_miles, excess_mile_charge=0.25):
        """
        Calculate TCO for leased vehicle

        Parameters:
        - monthly_lease_payment: monthly lease cost
        - lease_term_years: lease duration
        - annual_miles: expected annual mileage
        - excess_mile_charge: cost per mile over allowance
        """

        lease_allowance_miles = 15000  # typical annual allowance

        # Calculate excess miles
        excess_miles_per_year = max(0, annual_miles - lease_allowance_miles)
        excess_miles_total = excess_miles_per_year * lease_term_years
        excess_miles_cost = excess_miles_total * excess_mile_charge

        # Annual operating costs (lessee responsible)
        fuel_cost_per_mile = 0.35
        insurance_annual = 2500
        registration_annual = 500

        annual_operating = (
            annual_miles * fuel_cost_per_mile +
            insurance_annual +
            registration_annual
        )

        annual_lease_cost = monthly_lease_payment * 12

        # Total cost
        total_lease_payments = annual_lease_cost * lease_term_years
        total_operating = annual_operating * lease_term_years
        total_cost = total_lease_payments + total_operating + excess_miles_cost

        # Cost per mile
        total_miles = annual_miles * lease_term_years
        cost_per_mile = total_cost / total_miles if total_miles > 0 else 0

        return {
            'annual_cost': annual_lease_cost + annual_operating,
            'total_lease_payments': total_lease_payments,
            'excess_miles_cost': excess_miles_cost,
            'total_cost': total_cost,
            'cost_per_mile': cost_per_mile,
            'cost_per_month': (annual_lease_cost + annual_operating) / 12
        }

    def compare_buy_vs_lease(self, purchase_price, lease_monthly,
                            years, annual_miles):
        """
        Compare buying vs. leasing

        Returns comparison with recommendation
        """

        buy_tco = self.calculate_purchase_tco(
            purchase_price=purchase_price,
            useful_life_years=years,
            annual_miles=annual_miles
        )

        lease_tco = self.calculate_lease_tco(
            monthly_lease_payment=lease_monthly,
            lease_term_years=years,
            annual_miles=annual_miles
        )

        savings = lease_tco['total_cost'] - buy_tco['total_cost']
        recommendation = 'Buy' if savings > 0 else 'Lease'

        return {
            'buy': buy_tco,
            'lease': lease_tco,
            'savings_with_buy': savings,
            'recommendation': recommendation,
            'buy_cost_per_mile': buy_tco['cost_per_mile'],
            'lease_cost_per_mile': lease_tco['cost_per_mile']
        }

# Example usage
tco = VehicleTCO('Delivery Van')
comparison = tco.compare_buy_vs_lease(
    purchase_price=45000,
    lease_monthly=650,
    years=5,
    annual_miles=25000
)

print(f"Recommendation: {comparison['recommendation']}")
print(f"Buy TCO: ${comparison['buy']['total_cost']:,.0f}")
print(f"Lease TCO: ${comparison['lease']['total_cost']:,.0f}")
print(f"Savings with buy: ${comparison['savings_with_buy']:,.0f}")

Fleet Replacement Strategy

Optimal Replacement Timing

import numpy as np
from scipy.optimize import minimize_scalar

def optimal_replacement_age(purchase_price, annual_depreciation,
                           annual_maintenance, discount_rate=0.08):
    """
    Calculate optimal vehicle replacement age

    Minimizes equivalent annual cost (EAC)

    Parameters:
    - purchase_price: initial cost
    - annual_depreciation: depreciation schedule (list)
    - annual_maintenance: maintenance cost schedule (list)
    - discount_rate: discount rate for NPV
    """

    def equivalent_annual_cost(age):
        """Calculate EAC for given replacement age"""

        if age < 1 or age > len(annual_maintenance):
            return float('inf')

        age = int(age)

        # Calculate NPV of costs
        npv_costs = purchase_price

        for year in range(1, age + 1):
            discount_factor = (1 + discount_rate) ** -year
            npv_costs += annual_maintenance[year - 1] * discount_factor

        # Calculate residual value
        residual_value = purchase_price
        for year in range(age):
            residual_value -= annual_depreciation[year]

        npv_costs -= residual_value * (1 + discount_rate) ** -age

        # Convert to EAC
        annuity_factor = (
            (discount_rate * (1 + discount_rate) ** age) /
            ((1 + discount_rate) ** age - 1)
        )
        eac = npv_costs * annuity_factor

        return eac

    # Find optimal age
    result = minimize_scalar(
        equivalent_annual_cost,
        bounds=(1, len(annual_maintenance)),
        method='bounded'
    )

    optimal_age = int(result.x)
    min_eac = result.fun

    return {
        'optimal_replacement_age': optimal_age,
        'equivalent_annual_cost': min_eac
    }

# Example: Analyze replacement for delivery truck
purchase_price = 50000
annual_depreciation = [10000, 8000, 6000, 5000, 4000, 3000, 2000]
annual_maintenance = [2000, 2500, 3000, 4000, 5500, 7000, 9000]

result = optimal_replacement_age(
    purchase_price,
    annual_depreciation,
    annual_maintenance
)

print(f"Optimal replacement age: {result['optimal_replacement_age']} years")
print(f"Equivalent annual cost: ${result['equivalent_annual_cost']:,.0f}")

Age-Based Replacement Policy

class FleetReplacementPlanner:
    """
    Plan multi-year fleet replacement strategy

    Accounts for budget constraints and vehicle ages
    """

    def __init__(self, fleet_data, annual_budget):
        """
        Parameters:
        - fleet_data: DataFrame with columns ['vehicle_id', 'age', 'type',
                      'replacement_cost', 'maintenance_cost']
        - annual_budget: maximum annual replacement budget
        """
        self.fleet = fleet_data.copy()
        self.annual_budget = annual_budget

    def prioritize_replacements(self, current_year):
        """
        Prioritize vehicles for replacement

        Scoring based on age, maintenance cost, and utilization
        """

        # Calculate replacement scores
        self.fleet['age_score'] = self.fleet['age'] / 10  # normalize
        self.fleet['maintenance_score'] = (
            self.fleet['maintenance_cost'] /
            self.fleet['maintenance_cost'].median()
        )

        # Combined score (higher = more urgent)
        self.fleet['replacement_score'] = (
            0.6 * self.fleet['age_score'] +
            0.4 * self.fleet['maintenance_score']
        )

        # Sort by priority
        self.fleet = self.fleet.sort_values(
            'replacement_score',
            ascending=False
        )

        return self.fleet[['vehicle_id', 'age', 'replacement_score']]

    def create_replacement_plan(self, planning_horizon=5):
        """
        Create multi-year replacement plan

        Returns year-by-year replacement schedule
        """

        replacement_plan = {year: [] for year in range(planning_horizon)}
        remaining_fleet = self.fleet.copy()

        for year in range(planning_horizon):
            # Age all vehicles by one year
            remaining_fleet['age'] += 1

            # Re-prioritize
            remaining_fleet['age_score'] = remaining_fleet['age'] / 10
            remaining_fleet['replacement_score'] = (
                0.6 * remaining_fleet['age_score'] +
                0.4 * remaining_fleet['maintenance_score']
            )
            remaining_fleet = remaining_fleet.sort_values(
                'replacement_score',
                ascending=False
            )

            # Select vehicles to replace within budget
            budget_remaining = self.annual_budget
            year_replacements = []

            for idx, vehicle in remaining_fleet.iterrows():
                if budget_remaining >= vehicle['replacement_cost']:
                    year_replacements.append({
                        'vehicle_id': vehicle['vehicle_id'],
                        'age_at_replacement': vehicle['age'],
                        'cost': vehicle['replacement_cost']
                    })
                    budget_remaining -= vehicle['replacement_cost']

                    # Remove from fleet
                    remaining_fleet = remaining_fleet.drop(idx)

            replacement_plan[year] = year_replacements

        return replacement_plan

    def summarize_plan(self, plan):
        """Create summary of replacement plan"""

        summary = []
        for year, replacements in plan.items():
            total_cost = sum(r['cost'] for r in replacements)
            num_vehicles = len(replacements)

            summary.append({
                'year': year,
                'num_replacements': num_vehicles,
                'total_cost': total_cost,
                'budget_utilization': total_cost / self.annual_budget
            })

        return pd.DataFrame(summary)

# Example usage
import pandas as pd

fleet_data = pd.DataFrame({
    'vehicle_id': [f'V{i:03d}' for i in range(50)],
    'age': np.random.randint(1, 12, 50),
    'type': np.random.choice(['Van', 'Truck', 'Tractor'], 50),
    'replacement_cost': np.random.randint(35000, 75000, 50),
    'maintenance_cost': np.random.randint(2000, 8000, 50)
})

planner = FleetReplacementPlanner(fleet_data, annual_budget=500000)
plan = planner.create_replacement_plan(planning_horizon=5)
summary = planner.summarize_plan(plan)

print("5-Year Replacement Plan:")
print(summary)

Fleet Utilization Optimization

Utilization Metrics

class FleetUtilizationAnalyzer:
    """
    Analyze and improve fleet utilization

    Key metrics: miles driven, hours used, revenue per vehicle
    """

    def __init__(self, vehicle_data, operational_data):
        """
        Parameters:
        - vehicle_data: DataFrame with vehicle details
        - operational_data: DataFrame with daily usage logs
        """
        self.vehicles = vehicle_data
        self.operations = operational_data

    def calculate_utilization_metrics(self):
        """Calculate comprehensive utilization metrics"""

        metrics = []

        for vehicle_id in self.vehicles['vehicle_id']:
            vehicle_ops = self.operations[
                self.operations['vehicle_id'] == vehicle_id
            ]

            if len(vehicle_ops) == 0:
                continue

            # Time utilization
            total_days = (vehicle_ops['date'].max() -
                         vehicle_ops['date'].min()).days + 1
            active_days = vehicle_ops['date'].nunique()
            time_utilization = active_days / total_days if total_days > 0 else 0

            # Mileage
            total_miles = vehicle_ops['miles'].sum()
            avg_daily_miles = total_miles / active_days if active_days > 0 else 0

            # Revenue
            total_revenue = vehicle_ops['revenue'].sum()
            revenue_per_mile = total_revenue / total_miles if total_miles > 0 else 0

            # Efficiency
            empty_miles = vehicle_ops['empty_miles'].sum()
            loaded_miles = total_miles - empty_miles
            loaded_percentage = loaded_miles / total_miles if total_miles > 0 else 0

            metrics.append({
                'vehicle_id': vehicle_id,
                'active_days': active_days,
                'time_utilization': time_utilization,
                'total_miles': total_miles,
                'avg_daily_miles': avg_daily_miles,
                'total_revenue': total_revenue,
                'revenue_per_mile': revenue_per_mile,
                'loaded_percentage': loaded_percentage
            })

        return pd.DataFrame(metrics)

    def identify_underutilized_vehicles(self, utilization_threshold=0.60):
        """
        Identify vehicles below utilization threshold

        Returns candidates for removal from fleet
        """

        metrics = self.calculate_utilization_metrics()

        underutilized = metrics[
            metrics['time_utilization'] < utilization_threshold
        ].sort_values('time_utilization')

        return underutilized

    def recommend_fleet_adjustments(self):
        """
        Recommend fleet size adjustments

        Based on utilization analysis
        """

        metrics = self.calculate_utilization_metrics()

        avg_utilization = metrics['time_utilization'].mean()
        underutilized = len(metrics[metrics['time_utilization'] < 0.60])

        recommendations = []

        if avg_utilization < 0.65:
            potential_reduction = int(len(metrics) * (0.65 - avg_utilization))
            recommendations.append({
                'action': 'Reduce fleet size',
                'vehicles': potential_reduction,
                'reason': f'Average utilization only {avg_utilization:.1%}'
            })

        if underutilized > 0:
            recommendations.append({
                'action': 'Remove or reassign',
                'vehicles': underutilized,
                'reason': f'{underutilized} vehicles below 60% utilization'
            })

        # Check for overutilization
        high_mileage = metrics[metrics['avg_daily_miles'] > 250]
        if len(high_mileage) > len(metrics) * 0.3:
            recommendations.append({
                'action': 'Add vehicles',
                'vehicles': 2,
                'reason': 'Many vehicles exceeding 250 miles/day'
            })

        return recommendations

Maintenance Management

Preventive Maintenance Scheduling

class MaintenanceScheduler:
    """
    Schedule and track fleet maintenance

    Prevents breakdowns, optimizes maintenance timing
    """

    def __init__(self, fleet_data):
        self.fleet = fleet_data.copy()

    def calculate_maintenance_schedule(self, current_date):
        """
        Calculate upcoming maintenance needs

        Returns schedule for next 90 days
        """

        schedule = []

        for idx, vehicle in self.fleet.iterrows():
            # Check mileage-based maintenance
            miles_since_service = (
                vehicle['current_mileage'] -
                vehicle['last_service_mileage']
            )

            miles_to_service = vehicle['service_interval'] - miles_since_service
            avg_daily_miles = vehicle['avg_daily_miles']

            if avg_daily_miles > 0:
                days_to_service = miles_to_service / avg_daily_miles
            else:
                days_to_service = 999

            # Check time-based maintenance
            days_since_service = (
                current_date - vehicle['last_service_date']
            ).days

            days_to_time_service = 180 - days_since_service  # 6-month interval

            # Use whichever comes first
            days_to_service = min(days_to_service, days_to_time_service)

            if days_to_service <= 90:  # Next 90 days
                schedule.append({
                    'vehicle_id': vehicle['vehicle_id'],
                    'days_to_service': max(0, days_to_service),
                    'due_date': current_date + pd.Timedelta(days=max(0, days_to_service)),
                    'service_type': 'Preventive Maintenance',
                    'estimated_cost': vehicle['avg_service_cost'],
                    'priority': 'High' if days_to_service <= 7 else 'Medium'
                })

        return pd.DataFrame(schedule).sort_values('days_to_service')

    def optimize_maintenance_timing(self, schedule, routes_data):
        """
        Optimize maintenance timing to minimize service disruption

        Coordinate with route schedules
        """

        optimized = []

        for idx, maintenance in schedule.iterrows():
            vehicle_id = maintenance['vehicle_id']

            # Find days when vehicle has lightest workload
            vehicle_routes = routes_data[
                routes_data['vehicle_id'] == vehicle_id
            ]

            # Calculate workload by day
            daily_workload = vehicle_routes.groupby('date').agg({
                'stops': 'sum',
                'miles': 'sum'
            })

            # Find lightest day within maintenance window
            maintenance_window_start = maintenance['due_date'] - pd.Timedelta(days=7)
            maintenance_window_end = maintenance['due_date'] + pd.Timedelta(days=3)

            window_workload = daily_workload[
                (daily_workload.index >= maintenance_window_start) &
                (daily_workload.index <= maintenance_window_end)
            ]

            if len(window_workload) > 0:
                optimal_date = window_workload['stops'].idxmin()
            else:
                optimal_date = maintenance['due_date']

            maintenance['optimal_date'] = optimal_date
            optimized.append(maintenance)

        return pd.DataFrame(optimized)

Tools & Technology

Telematics & GPS Systems

Leading Providers:

  • Verizon Connect: Fleet tracking, diagnostics
  • Samsara: IoT sensors, dash cams, ELD
  • Geotab: Telematics, driver behavior
  • Teletrac Navman: GPS tracking, compliance
  • Fleet Complete: Asset tracking, mobile workforce
  • Omnitracs: ELD, fleet management

Key Features:

  • Real-time GPS location tracking
  • Vehicle diagnostics (OBD-II)
  • Driver behavior monitoring
  • Maintenance alerts
  • Fuel consumption tracking
  • ELD compliance (Hours of Service)

Fleet Management Software

Comprehensive Platforms:

  • Fleetio: Maintenance, fuel, compliance
  • RTA Fleet Management: Asset management
  • Fleet Manager: Cost tracking, reporting
  • Dossier Fleet Maintenance: Work orders, inventory
  • Azuga Fleet: GPS + fleet management

Key Capabilities:

  • Maintenance scheduling
  • Fuel management
  • Cost tracking and reporting
  • Vehicle lifecycle management
  • Driver management
  • Compliance tracking

Common Challenges & Solutions

Challenge: Excessive Idle Time

Problem:

  • Vehicles sitting unused
  • Low utilization rates
  • High fixed costs per delivery

Solutions:

  • Implement backhaul programs
  • Cross-utilize vehicles across departments
  • Consider contract carriers for overflow
  • Right-size fleet (remove excess vehicles)
  • Implement dynamic dispatch
  • Offer vehicles for spot market
  • Share assets with partners

Challenge: High Maintenance Costs

Problem:

  • Aging fleet
  • Frequent breakdowns
  • Escalating repair costs

Solutions:

  • Accelerate replacement cycle for high-cost vehicles
  • Implement predictive maintenance
  • Use telematics for early fault detection
  • Standardize vehicle types (reduce parts inventory)
  • Negotiate fleet maintenance contracts
  • Train drivers on vehicle care
  • Track and benchmark costs per vehicle

Challenge: Unpredictable Demand

Problem:

  • Fleet sized for peak, idle at average
  • Difficult to justify capital investment

Solutions:

  • Core fleet for base demand + flex capacity for peak
  • Use contract carriers or spot market for overflow
  • Consider leasing vs. buying for flexibility
  • Implement dynamic routing to maximize utilization
  • Build backhaul network to fill return trips
  • Seasonal drivers (expand/contract as needed)

Challenge: Driver Shortage

Problem:

  • Not enough drivers for available vehicles
  • Vehicle utilization limited by driver availability

Solutions:

  • Improve driver retention (pay, benefits, home time)
  • Recruit more aggressively
  • Consider driver teams (extend hours)
  • Reduce fleet size to match driver availability
  • Invest in driver training and development
  • Explore automation for specific routes
  • Contract with owner-operators

Challenge: Regulatory Compliance

Problem:

  • ELD mandates (Hours of Service)
  • Emissions requirements
  • Safety regulations (DOT)

Solutions:

  • Implement ELD system (electronic logging)
  • Regular compliance audits
  • Driver training on regulations
  • Modern fleet (meets emissions standards)
  • Dedicated safety manager
  • Automated alerts for violations
  • Partner with compliance consultants

Output Format

Fleet Analysis Report

Executive Summary:

  • Current fleet: 45 vehicles
  • Average utilization: 73%
  • Total annual cost: $3.2M
  • Cost per vehicle: $71,111
  • Recommendation: Reduce by 5 vehicles, replace 8 aging units

Fleet Composition:

Vehicle TypeCountAvg AgeAvg MilesUtilizationAnnual Cost
Box Truck (26')206.2 yrs32K82%$1.4M
Cargo Van154.1 yrs28K68%$900K
Straight Truck108.5 yrs45K71%$900K

Utilization Analysis:

MetricCurrentTargetStatus
Avg daily utilization73%80%⚠️ Below target
Vehicles <60% utilized80❌ Action needed
Avg daily miles125150⚠️ Below target
Empty mile %18%<15%⚠️ Above target

Cost Breakdown:

Cost CategoryAnnualPer Vehicle% of Total
Depreciation$675K$15K21%
Fuel$945K$21K30%
Maintenance$495K$11K15%
Insurance$450K$10K14%
Labor (drivers)$585K$13K18%
Other$50K$1K2%

Replacement Plan (5 Years):

YearVehiclesInvestmentReason
20268$480KAge > 8 years, high maintenance
20275$300KAge > 7 years
20286$360KScheduled replacement
20297$420KScheduled replacement
20305$300KScheduled replacement

Recommendations:

  1. Reduce fleet by 5 vehicles

    • Remove 5 lowest-utilized cargo vans
    • Savings: $355K annually
    • Impact: Minimal (use contract carriers for overflow)
  2. Replace 8 aging vehicles immediately

    • Target: Units over 8 years old with maintenance >$6K/year
    • Investment: $480K
    • Payback: 2.5 years (reduced maintenance + fuel)
  3. Implement telematics system

    • Real-time GPS and diagnostics
    • Investment: $45K (hardware + software)
    • Benefits: 10% improvement in utilization, reduced maintenance
  4. Optimize backhaul program

    • Reduce empty miles from 18% to 12%
    • Savings: $85K annually in fuel

Questions to Ask

If you need more context:

  1. How many vehicles in the current fleet? What types?
  2. What are current utilization rates?
  3. What's the budget for fleet operations?
  4. Own, lease, or mix? What's the preference?
  5. Any specific pain points? (costs, breakdowns, utilization)
  6. What's the demand pattern? (steady, seasonal, growing)
  7. Any technology systems in place? (GPS, telematics, fleet management software)
  8. What are the replacement criteria currently?

Related Skills

  • route-optimization: Optimize routes to improve fleet utilization
  • last-mile-delivery: Urban delivery fleet management
  • freight-optimization: Long-haul fleet optimization
  • maintenance-planning: Equipment maintenance scheduling
  • prescriptive-analytics: Data-driven fleet decisions
  • supply-chain-automation: Automated fleet management systems
  • total-cost-ownership: TCO analysis for assets
  • capacity-planning: Fleet capacity planning
flow-shop-schedulingfood-beverage-supply-chainfreight-optimizationfuel-distributionguillotine-cuttinghospital-logisticshospitality-procurementhotel-inventory-managementhub-location-probleminventory-optimizationinventory-routing-problemjob-shop-schedulingknapsack-problemslast-mile-deliverylean-manufacturingload-building-optimizationlot-sizing-problemsmaintenance-planningmarkdown-optimizationmaster-production-schedulingmedical-device-distributionmetaheuristic-optimizationml-supply-chainmulti-depot-vrpmulti-echelon-inventorymulti-objective-optimizationnesting-optimizationnetwork-designnetwork-flow-optimizationneural-networks-forecastingnewsvendor-problemnlp-supply-chainomnichannel-fulfillmentoptimization-ml-hybridoptimization-modelingorder-batching-optimizationorder-fulfillmentpallet-loadingpharmaceutical-supply-chainpharmacy-supply-chainpicker-routing-optimizationpickup-delivery-problemplanogram-optimizationpower-grid-optimizationprescriptive-analyticsprocess-optimizationprocurement-optimizationproduction-schedulingpromotional-planningquality-managementreinforcement-learning-supply-chainrenewable-energy-planningreplenishment-strategyretail-allocationretail-replenishmentrisk-mitigationroute-optimizationsales-operations-planningscenario-planningseasonal-planningset-covering-problemshelf-life-managementslotting-fees-optimizationspend-analysissplit-delivery-vrpstochastic-inventory-modelsstochastic-optimizationstrategic-sourcingstrip-packingsupplier-collaborationsupplier-risk-managementsupplier-selectionsupply-chain-analyticssupply-chain-automationsupply-chain-decision-to-delegationsustainable-sourcingtask-assignment-problemtour-operationstrack-and-tracetraveling-salesman-problemtrim-loss-minimizationvalue-analysisvehicle-loading-optimizationvehicle-routing-problemvrp-backhaulsvrp-time-windowswarehouse-automationwarehouse-designwarehouse-location-optimizationwarehouse-slotting-optimizationwave-planning-optimizationworkforce-schedulingyard-management

Sponsors

Details

Marketplace
kishorkukreja/awesome-supply-chain
Category
Community