1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
| import numpy as np import matplotlib.pyplot as plt from scipy.optimize import linprog import pandas as pd from mpl_toolkits.mplot3d import Axes3D import seaborn as sns
print("=== Petroleum Refinery Optimization Problem ===") print("Maximizing profit from gasoline, diesel, and fuel oil production") print()
c = [-80, -60, -40]
A = [ [0.3, 0.2, 0.1], [0.4, 0.3, 0.1], [1, 0, 0], [0, 1, 0], [0, 0, 1] ]
b = [2000, 1800, 4000, 3000, 2000]
x_bounds = [(0, None), (0, None), (0, None)]
print("Solving the optimization problem...") result = linprog(c, A_ub=A, b_ub=b, bounds=x_bounds, method='highs')
print("\n=== OPTIMIZATION RESULTS ===") if result.success: gasoline_prod = result.x[0] diesel_prod = result.x[1] fuel_oil_prod = result.x[2] max_profit = -result.fun print(f"Optimal Production Plan:") print(f" Gasoline: {gasoline_prod:.2f} barrels/day") print(f" Diesel: {diesel_prod:.2f} barrels/day") print(f" Fuel Oil: {fuel_oil_prod:.2f} barrels/day") print(f" Maximum Daily Profit: ${max_profit:.2f}") cdu_usage = 0.3*gasoline_prod + 0.2*diesel_prod + 0.1*fuel_oil_prod ccu_usage = 0.4*gasoline_prod + 0.3*diesel_prod + 0.1*fuel_oil_prod print(f"\nResource Utilization:") print(f" CDU Usage: {cdu_usage:.2f}/2000 ({cdu_usage/2000*100:.1f}%)") print(f" CCU Usage: {ccu_usage:.2f}/1800 ({ccu_usage/1800*100:.1f}%)") production_data = { 'Product': ['Gasoline', 'Diesel', 'Fuel Oil'], 'Production (barrels/day)': [gasoline_prod, diesel_prod, fuel_oil_prod], 'Unit Profit ($/barrel)': [80, 60, 40], 'Total Revenue ($)': [gasoline_prod*80, diesel_prod*60, fuel_oil_prod*40] } utilization_data = { 'Resource': ['CDU', 'CCU'], 'Usage': [cdu_usage, ccu_usage], 'Capacity': [2000, 1800], 'Utilization (%)': [cdu_usage/2000*100, ccu_usage/1800*100] } else: print("Optimization failed!") print(result.message)
print("\n=== SENSITIVITY ANALYSIS ===") print("Analyzing how profit changes with different gasoline prices...")
gasoline_prices = np.linspace(60, 100, 20) profits = []
for price in gasoline_prices: c_temp = [-price, -60, -40] result_temp = linprog(c_temp, A_ub=A, b_ub=b, bounds=x_bounds, method='highs') if result_temp.success: profits.append(-result_temp.fun) else: profits.append(0)
sensitivity_data = pd.DataFrame({ 'Gasoline_Price': gasoline_prices, 'Max_Profit': profits })
print("Sensitivity analysis complete. Results will be visualized in graphs.")
fig = plt.figure(figsize=(20, 15))
ax1 = plt.subplot(2, 3, 1) products = ['Gasoline', 'Diesel', 'Fuel Oil'] production_values = [gasoline_prod, diesel_prod, fuel_oil_prod] colors = ['#FF6B6B', '#4ECDC4', '#45B7D1'] plt.pie(production_values, labels=products, autopct='%1.1f%%', colors=colors, startangle=90) plt.title('Optimal Production Mix\n(Barrels per Day)', fontsize=14, fontweight='bold')
ax2 = plt.subplot(2, 3, 2) revenues = [gasoline_prod*80, diesel_prod*60, fuel_oil_prod*40] bars = plt.bar(products, revenues, color=colors, alpha=0.8) plt.title('Revenue Contribution by Product', fontsize=14, fontweight='bold') plt.ylabel('Revenue ($)') plt.xticks(rotation=45)
for bar, revenue in zip(bars, revenues): plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 1000, f'${revenue:,.0f}', ha='center', va='bottom', fontweight='bold')
ax3 = plt.subplot(2, 3, 3) resources = ['CDU', 'CCU'] usage = [cdu_usage, ccu_usage] capacity = [2000, 1800] utilization_pct = [u/c*100 for u, c in zip(usage, capacity)]
x_pos = np.arange(len(resources)) bars1 = plt.bar(x_pos - 0.2, usage, 0.4, label='Current Usage', color='#FF6B6B', alpha=0.8) bars2 = plt.bar(x_pos + 0.2, capacity, 0.4, label='Total Capacity', color='#4ECDC4', alpha=0.8)
plt.title('Resource Utilization', fontsize=14, fontweight='bold') plt.ylabel('Capacity (units)') plt.xlabel('Processing Units') plt.xticks(x_pos, resources) plt.legend()
for i, (usage_val, util_pct) in enumerate(zip(usage, utilization_pct)): plt.text(i - 0.2, usage_val + 50, f'{util_pct:.1f}%', ha='center', va='bottom', fontweight='bold')
ax4 = plt.subplot(2, 3, 4) plt.plot(gasoline_prices, profits, 'o-', color='#45B7D1', linewidth=3, markersize=6) plt.title('Profit Sensitivity to Gasoline Price', fontsize=14, fontweight='bold') plt.xlabel('Gasoline Price ($/barrel)') plt.ylabel('Maximum Daily Profit ($)') plt.grid(True, alpha=0.3) plt.axvline(x=80, color='red', linestyle='--', alpha=0.7, label='Current Price') plt.legend()
ax5 = plt.subplot(2, 3, 5)
x1_range = np.linspace(0, 5000, 100) x2_range = np.linspace(0, 4000, 100)
x2_cdu = (2000 - 0.3*x1_range) / 0.2
x2_ccu = (1800 - 0.4*x1_range) / 0.3
plt.plot(x1_range, x2_cdu, label='CDU Constraint', color='red', linewidth=2) plt.plot(x1_range, x2_ccu, label='CCU Constraint', color='blue', linewidth=2) plt.axhline(y=3000, color='green', linestyle='--', label='Diesel Demand Limit') plt.axvline(x=4000, color='orange', linestyle='--', label='Gasoline Demand Limit')
plt.plot(gasoline_prod, diesel_prod, 'ro', markersize=10, label='Optimal Solution')
plt.xlim(0, 5000) plt.ylim(0, 4000) plt.xlabel('Gasoline Production (barrels/day)') plt.ylabel('Diesel Production (barrels/day)') plt.title('Feasible Region (2D Projection)', fontsize=14, fontweight='bold') plt.legend() plt.grid(True, alpha=0.3)
ax6 = plt.subplot(2, 3, 6) profit_breakdown = [gasoline_prod*80, diesel_prod*60, fuel_oil_prod*40] cumulative_profit = np.cumsum([0] + profit_breakdown)
for i, (product, profit) in enumerate(zip(products, profit_breakdown)): plt.barh(0, profit, left=cumulative_profit[i], height=0.5, color=colors[i], alpha=0.8, label=f'{product}: ${profit:,.0f}')
plt.title('Profit Breakdown by Product', fontsize=14, fontweight='bold') plt.xlabel('Cumulative Profit ($)') plt.yticks([]) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout() plt.show()
print("\n=== DETAILED ANALYSIS ===") print(f"1. PRODUCTION EFFICIENCY:") print(f" - Total production: {sum(production_values):,.0f} barrels/day") print(f" - Gasoline dominates at {gasoline_prod/sum(production_values)*100:.1f}% of total production") print(f" - This reflects gasoline's higher profit margin (${80}/barrel)")
print(f"\n2. RESOURCE BOTTLENECKS:") if ccu_usage/1800 > cdu_usage/2000: print(f" - CCU is the limiting factor at {ccu_usage/1800*100:.1f}% utilization") print(f" - CDU has spare capacity at {cdu_usage/2000*100:.1f}% utilization") print(f" - Consider expanding CCU capacity for further optimization") else: print(f" - CDU is the limiting factor at {cdu_usage/2000*100:.1f}% utilization") print(f" - CCU has spare capacity at {ccu_usage/1800*100:.1f}% utilization") print(f" - Consider expanding CDU capacity for further optimization")
print(f"\n3. MARKET POSITION:") print(f" - Gasoline: Using {gasoline_prod/4000*100:.1f}% of market demand") print(f" - Diesel: Using {diesel_prod/3000*100:.1f}% of market demand") print(f" - Fuel Oil: Using {fuel_oil_prod/2000*100:.1f}% of market demand")
print(f"\n4. PROFITABILITY INSIGHTS:") print(f" - Revenue per barrel (weighted avg): ${max_profit/sum(production_values):.2f}") print(f" - Gasoline contributes {gasoline_prod*80/max_profit*100:.1f}% of total profit") print(f" - High gasoline focus aligns with profit maximization strategy")
print(f"\n5. SENSITIVITY INSIGHTS:") max_profit_idx = np.argmax(profits) optimal_gas_price = gasoline_prices[max_profit_idx] print(f" - Current gasoline price ($80/barrel) vs optimal range") print(f" - Profit increases linearly with gasoline price in current range") print(f" - At $100/barrel gasoline price, profit would be ${profits[-1]:,.2f}")
print("\n=== OPTIMIZATION COMPLETE ===") print("The refinery should focus on maximizing gasoline production while") print("efficiently utilizing both processing units to achieve optimal profitability.")
|