Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,536 +1,536 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import numpy as np
|
| 3 |
-
import matplotlib.pyplot as plt
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import io
|
| 6 |
-
from scipy.stats import norm # Using scipy.stats, but it's a common numpy-adjacent lib for stats. If not allowed, can be replaced.
|
| 7 |
-
# Let's stick to numpy. We can use norm.ppf or just ask for Z-score.
|
| 8 |
-
# User said NO new concepts. Z-score is simple. I will just ask for the Z-score directly.
|
| 9 |
-
|
| 10 |
-
# --- Calculation Functions ---
|
| 11 |
-
|
| 12 |
-
def calculate_basic_eoq(annual_demand, order_cost, holding_cost_per_unit):
|
| 13 |
-
"""Calculates EOQ and related metrics for the basic model."""
|
| 14 |
-
if annual_demand <= 0 or order_cost <= 0 or holding_cost_per_unit <= 0:
|
| 15 |
-
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan
|
| 16 |
-
|
| 17 |
-
eoq = np.sqrt((2 * annual_demand * order_cost) / holding_cost_per_unit)
|
| 18 |
-
num_orders_per_year = annual_demand / eoq if eoq > 0 else np.inf
|
| 19 |
-
avg_inventory = eoq / 2
|
| 20 |
-
annual_ordering_cost = num_orders_per_year * order_cost
|
| 21 |
-
annual_holding_cost = avg_inventory * holding_cost_per_unit
|
| 22 |
-
total_annual_cost = annual_ordering_cost + annual_holding_cost
|
| 23 |
-
|
| 24 |
-
demand_per_day = annual_demand / 365
|
| 25 |
-
|
| 26 |
-
return eoq, num_orders_per_year, avg_inventory, annual_ordering_cost, annual_holding_cost, total_annual_cost, demand_per_day
|
| 27 |
-
|
| 28 |
-
def calculate_eoq_with_discount(annual_demand, order_cost, holding_cost_rate, unit_cost, discount_tiers):
|
| 29 |
-
"""Calculates EOQ with quantity discounts."""
|
| 30 |
-
if annual_demand <= 0 or order_cost <= 0 or holding_cost_rate <= 0 or unit_cost <= 0:
|
| 31 |
-
return pd.DataFrame(), np.nan, np.nan, np.nan, np.nan, "Invalid inputs for discount model."
|
| 32 |
-
|
| 33 |
-
results = []
|
| 34 |
-
best_total_cost = np.inf
|
| 35 |
-
best_eoq = np.nan
|
| 36 |
-
best_unit_cost = np.nan
|
| 37 |
-
best_tier = ""
|
| 38 |
-
|
| 39 |
-
discount_tiers = sorted(discount_tiers, key=lambda x: x[0])
|
| 40 |
-
|
| 41 |
-
for i, (min_qty, max_qty, tier_unit_cost) in enumerate(discount_tiers):
|
| 42 |
-
holding_cost_per_unit = holding_cost_rate * tier_unit_cost
|
| 43 |
-
|
| 44 |
-
tier_eoq, _, _, _, _, _, _ = calculate_basic_eoq(annual_demand, order_cost, holding_cost_per_unit)
|
| 45 |
-
|
| 46 |
-
if tier_eoq < min_qty:
|
| 47 |
-
relevant_qty = min_qty
|
| 48 |
-
elif tier_eoq > max_qty and max_qty != np.inf:
|
| 49 |
-
relevant_qty = max_qty
|
| 50 |
-
else:
|
| 51 |
-
relevant_qty = tier_eoq
|
| 52 |
-
|
| 53 |
-
if relevant_qty <= 0:
|
| 54 |
-
num_orders = np.inf
|
| 55 |
-
ordering_cost = np.inf
|
| 56 |
-
holding_cost = 0
|
| 57 |
-
purchase_cost = annual_demand * tier_unit_cost
|
| 58 |
-
total_cost = np.inf
|
| 59 |
-
else:
|
| 60 |
-
num_orders = annual_demand / relevant_qty
|
| 61 |
-
ordering_cost = num_orders * order_cost
|
| 62 |
-
holding_cost = (relevant_qty / 2) * holding_cost_per_unit
|
| 63 |
-
purchase_cost = annual_demand * tier_unit_cost
|
| 64 |
-
total_cost = ordering_cost + holding_cost + purchase_cost
|
| 65 |
-
|
| 66 |
-
results.append({
|
| 67 |
-
"Tier": f"Tier {i+1} ({min_qty}-{max_qty if max_qty != np.inf else 'β'})",
|
| 68 |
-
"Unit Cost ($)": tier_unit_cost,
|
| 69 |
-
"Holding Cost/Unit/Year ($)": f"{holding_cost_per_unit:.2f}",
|
| 70 |
-
"Theoretical EOQ (Units)": f"{tier_eoq:.0f}",
|
| 71 |
-
"Relevant Q (Units)": f"{relevant_qty:.0f}",
|
| 72 |
-
"Annual Ordering Cost ($)": f"{ordering_cost:.2f}",
|
| 73 |
-
"Annual Holding Cost ($)": f"{holding_cost:.2f}",
|
| 74 |
-
"Annual Purchase Cost ($)": f"{purchase_cost:.2f}",
|
| 75 |
-
"Total Annual Cost ($)": f"{total_cost:.2f}"
|
| 76 |
-
})
|
| 77 |
-
|
| 78 |
-
if total_cost < best_total_cost:
|
| 79 |
-
best_total_cost = total_cost
|
| 80 |
-
best_eoq = relevant_qty
|
| 81 |
-
best_unit_cost = tier_unit_cost
|
| 82 |
-
best_tier = f"Tier {i+1}"
|
| 83 |
-
|
| 84 |
-
df = pd.DataFrame(results)
|
| 85 |
-
|
| 86 |
-
return df, best_eoq, best_total_cost, best_unit_cost, best_tier, "Analysis complete."
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def calculate_poq(annual_demand, order_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate):
|
| 90 |
-
"""Calculates Production Order Quantity (POQ) and related metrics."""
|
| 91 |
-
if annual_demand <= 0 or order_cost <= 0 or holding_cost_per_unit <= 0 or \
|
| 92 |
-
daily_production_rate <= 0 or daily_demand_rate <= 0:
|
| 93 |
-
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan
|
| 94 |
-
|
| 95 |
-
if daily_production_rate <= daily_demand_rate:
|
| 96 |
-
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, "Production rate must be greater than demand rate."
|
| 97 |
-
|
| 98 |
-
poq = np.sqrt((2 * annual_demand * order_cost) / (holding_cost_per_unit * (1 - (daily_demand_rate / daily_production_rate))))
|
| 99 |
-
|
| 100 |
-
num_setups_per_year = annual_demand / poq if poq > 0 else np.inf
|
| 101 |
-
max_inventory_level = poq * (1 - (daily_demand_rate / daily_production_rate))
|
| 102 |
-
avg_inventory = max_inventory_level / 2
|
| 103 |
-
|
| 104 |
-
annual_setup_cost = num_setups_per_year * order_cost
|
| 105 |
-
annual_holding_cost = avg_inventory * holding_cost_per_unit
|
| 106 |
-
total_annual_cost = annual_setup_cost + annual_holding_cost
|
| 107 |
-
|
| 108 |
-
production_run_days = poq / daily_production_rate
|
| 109 |
-
inventory_cycle_days = poq / daily_demand_rate
|
| 110 |
-
|
| 111 |
-
return poq, num_setups_per_year, max_inventory_level, avg_inventory, annual_setup_cost, \
|
| 112 |
-
annual_holding_cost, total_annual_cost, production_run_days, inventory_cycle_days
|
| 113 |
-
|
| 114 |
-
def calculate_rop_and_ss(avg_daily_demand, lead_time_days, std_dev_daily_demand, service_level_z):
|
| 115 |
-
"""Calculates Reorder Point and Safety Stock."""
|
| 116 |
-
if avg_daily_demand < 0 or lead_time_days < 0 or std_dev_daily_demand < 0 or service_level_z < 0:
|
| 117 |
-
return 0, 0, 0, "Inputs must be non-negative."
|
| 118 |
-
|
| 119 |
-
std_dev_lead_time = std_dev_daily_demand * np.sqrt(lead_time_days)
|
| 120 |
-
safety_stock = std_dev_lead_time * service_level_z
|
| 121 |
-
demand_during_lead_time = avg_daily_demand * lead_time_days
|
| 122 |
-
reorder_point = demand_during_lead_time + safety_stock
|
| 123 |
-
|
| 124 |
-
return safety_stock, demand_during_lead_time, reorder_point, "Calculation successful."
|
| 125 |
-
|
| 126 |
-
def calculate_sma_forecast(demand_data_str, window_size):
|
| 127 |
-
"""Calculates Simple Moving Average (SMA) forecast."""
|
| 128 |
-
if not demand_data_str:
|
| 129 |
-
return pd.DataFrame(), None, "Please enter demand data."
|
| 130 |
-
|
| 131 |
-
try:
|
| 132 |
-
demand_values = [float(d.strip()) for d in demand_data_str.split(',') if d.strip()]
|
| 133 |
-
if len(demand_values) < window_size:
|
| 134 |
-
return pd.DataFrame(), None, f"Not enough data for window size {window_size}. Need at least {window_size} data points."
|
| 135 |
-
|
| 136 |
-
df = pd.DataFrame({'Demand': demand_values})
|
| 137 |
-
df['Period'] = range(1, len(df) + 1)
|
| 138 |
-
|
| 139 |
-
# Calculate SMA
|
| 140 |
-
df[f'SMA (Window={window_size})'] = df['Demand'].rolling(window=window_size).mean()
|
| 141 |
-
|
| 142 |
-
# Forecast next period
|
| 143 |
-
forecast_next_period = df['Demand'].tail(window_size).mean()
|
| 144 |
-
|
| 145 |
-
# Create plot
|
| 146 |
-
fig, ax = plt.subplots(figsize=(8, 4))
|
| 147 |
-
ax.plot(df['Period'], df['Demand'], label='Actual Demand', marker='o', linestyle='-')
|
| 148 |
-
ax.plot(df['Period'], df[f'SMA (Window={window_size})'], label='SMA', marker='x', linestyle='--')
|
| 149 |
-
|
| 150 |
-
ax.set_title('Simple Moving Average (SMA) Forecast', fontsize=14)
|
| 151 |
-
ax.set_xlabel('Period', fontsize=10)
|
| 152 |
-
ax.set_ylabel('Demand', fontsize=10)
|
| 153 |
-
ax.legend()
|
| 154 |
-
ax.grid(True, linestyle=':', alpha=0.7)
|
| 155 |
-
plt.tight_layout()
|
| 156 |
-
plt.close(fig)
|
| 157 |
-
|
| 158 |
-
return df, fig, f"Forecast for next period: {forecast_next_period:.2f}"
|
| 159 |
-
|
| 160 |
-
except Exception as e:
|
| 161 |
-
return pd.DataFrame(), None, f"Error: {e}. Ensure data is comma-separated numbers."
|
| 162 |
-
|
| 163 |
-
# --- Plotting Function ---
|
| 164 |
-
|
| 165 |
-
def create_eoq_plot(annual_demand, order_cost, holding_cost_per_unit, min_q=1, max_q_multiplier=2.5, current_eoq=None):
|
| 166 |
-
"""Generates the EOQ cost curves plot."""
|
| 167 |
-
if annual_demand <= 0 or order_cost <= 0 or holding_cost_per_unit <= 0:
|
| 168 |
-
fig, ax = plt.subplots(figsize=(6, 4))
|
| 169 |
-
ax.text(0.5, 0.5, "Invalid input for plot.", horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
|
| 170 |
-
ax.axis('off')
|
| 171 |
-
plt.close(fig)
|
| 172 |
-
return fig
|
| 173 |
-
|
| 174 |
-
if current_eoq is None or np.isnan(current_eoq) or current_eoq <= 0:
|
| 175 |
-
current_eoq = np.sqrt((2 * annual_demand * order_cost) / holding_cost_per_unit)
|
| 176 |
-
if np.isnan(current_eoq) or current_eoq <= 0:
|
| 177 |
-
current_eoq = 100
|
| 178 |
-
|
| 179 |
-
quantity_range = np.linspace(min_q, current_eoq * max_q_multiplier, 300)
|
| 180 |
-
|
| 181 |
-
quantity_range = quantity_range[quantity_range > 0]
|
| 182 |
-
|
| 183 |
-
ordering_costs = (annual_demand / quantity_range) * order_cost
|
| 184 |
-
holding_costs = (quantity_range / 2) * holding_cost_per_unit
|
| 185 |
-
total_costs = ordering_costs + holding_costs
|
| 186 |
-
|
| 187 |
-
fig, ax = plt.subplots(figsize=(6, 4))
|
| 188 |
-
|
| 189 |
-
ax.plot(quantity_range, holding_costs, label='Annual Holding Cost', color='orange')
|
| 190 |
-
ax.plot(quantity_range, ordering_costs, label='Annual Ordering Cost', color='blue')
|
| 191 |
-
ax.plot(quantity_range, total_costs, label='Total Cost', color='green', linewidth=2.5)
|
| 192 |
-
|
| 193 |
-
if not np.isnan(current_eoq) and current_eoq > 0:
|
| 194 |
-
ax.axvline(x=current_eoq, color='red', linestyle='--', label=f'EOQ: {current_eoq:.0f} units')
|
| 195 |
-
total_cost_at_eoq_idx = np.argmin(np.abs(quantity_range - current_eoq))
|
| 196 |
-
total_cost_at_eoq = total_costs[total_cost_at_eoq_idx]
|
| 197 |
-
ax.plot(current_eoq, total_cost_at_eoq, 'ro')
|
| 198 |
-
|
| 199 |
-
ax.set_title('EOQ Cost Analysis', fontsize=12)
|
| 200 |
-
ax.set_xlabel('Order Quantity (Units)', fontsize=10)
|
| 201 |
-
ax.set_ylabel('Annual Cost ($)', fontsize=10)
|
| 202 |
-
ax.legend(fontsize=8, loc='upper right')
|
| 203 |
-
ax.grid(True, linestyle=':', alpha=0.7)
|
| 204 |
-
ax.set_ylim(bottom=0)
|
| 205 |
-
ax.set_xlim(left=0)
|
| 206 |
-
ax.tick_params(axis='both', which='major', labelsize=8)
|
| 207 |
-
|
| 208 |
-
plt.tight_layout()
|
| 209 |
-
plt.close(fig)
|
| 210 |
-
return fig
|
| 211 |
-
|
| 212 |
-
# --- Combined Interface Function for Basic EOQ ---
|
| 213 |
-
|
| 214 |
-
def update_basic_eoq(annual_demand, order_cost, holding_cost_per_unit, lead_time_days):
|
| 215 |
-
"""Updates all outputs for the Basic EOQ tab."""
|
| 216 |
-
if any(x <= 0 for x in [annual_demand, order_cost, holding_cost_per_unit]):
|
| 217 |
-
return None, 0, 0, 0, 0, 0, 0, 0, "Please enter positive values for all basic EOQ parameters."
|
| 218 |
-
|
| 219 |
-
eoq, num_orders, avg_inventory, annual_ordering_cost, annual_holding_cost, total_annual_cost, demand_per_day = \
|
| 220 |
-
calculate_basic_eoq(annual_demand, order_cost, holding_cost_per_unit)
|
| 221 |
-
|
| 222 |
-
# Simple Reorder Point (no safety stock)
|
| 223 |
-
reorder_point = demand_per_day * lead_time_days
|
| 224 |
-
|
| 225 |
-
plot_fig = create_eoq_plot(annual_demand, order_cost, holding_cost_per_unit, current_eoq=eoq)
|
| 226 |
-
|
| 227 |
-
return plot_fig, eoq, num_orders, avg_inventory, annual_ordering_cost, annual_holding_cost, \
|
| 228 |
-
total_annual_cost, reorder_point, "Calculation successful."
|
| 229 |
-
|
| 230 |
-
# --- Combined Interface Function for POQ ---
|
| 231 |
-
def update_poq_model(annual_demand, setup_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate):
|
| 232 |
-
"""Updates all outputs for the POQ tab."""
|
| 233 |
-
if any(x <= 0 for x in [annual_demand, setup_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate]):
|
| 234 |
-
return None, 0, 0, 0, 0, 0, 0, 0, 0, "Please enter positive values for all POQ parameters."
|
| 235 |
-
|
| 236 |
-
if daily_production_rate <= daily_demand_rate:
|
| 237 |
-
return None, 0, 0, 0, 0, 0, 0, 0, 0, "Production rate must be greater than demand rate."
|
| 238 |
-
|
| 239 |
-
poq, num_setups, max_inv, avg_inv, annual_setup_cost, annual_holding_cost, total_cost, prod_days, cycle_days = \
|
| 240 |
-
calculate_poq(annual_demand, setup_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate)
|
| 241 |
-
|
| 242 |
-
plot_fig = create_eoq_plot(annual_demand, setup_cost, holding_cost_per_unit, current_eoq=poq, max_q_multiplier=2.0)
|
| 243 |
-
|
| 244 |
-
return plot_fig, poq, num_setups, max_inv, avg_inv, annual_setup_cost, annual_holding_cost, total_cost, \
|
| 245 |
-
prod_days, cycle_days, "Calculation successful."
|
| 246 |
-
|
| 247 |
-
# --- Helper for Discount Tiers ---
|
| 248 |
-
def create_discount_tiers_df(tier1_min, tier1_max, tier1_uc,
|
| 249 |
-
tier2_min, tier2_max, tier2_uc,
|
| 250 |
-
tier3_min, tier3_max, tier3_uc):
|
| 251 |
-
"""Helper to create the discount_tiers list from Gradio inputs."""
|
| 252 |
-
tiers = []
|
| 253 |
-
if tier1_min is not None and tier1_uc is not None and tier1_min >= 0 and tier1_uc >= 0:
|
| 254 |
-
tiers.append((tier1_min, tier1_max if tier1_max is not None else np.inf, tier1_uc))
|
| 255 |
-
if tier2_min is not None and tier2_uc is not None and tier2_min >= 0 and tier2_uc >= 0:
|
| 256 |
-
tiers.append((tier2_min, tier2_max if tier2_max is not None else np.inf, tier2_uc))
|
| 257 |
-
if tier3_min is not None and tier3_uc is not None and tier3_min >= 0 and tier3_uc >= 0:
|
| 258 |
-
tiers.append((tier3_min, tier3_max if tier3_max is not None else np.inf, tier3_uc))
|
| 259 |
-
|
| 260 |
-
valid_tiers = []
|
| 261 |
-
for t in tiers:
|
| 262 |
-
if t[1] != np.inf and t[0] >= t[1]:
|
| 263 |
-
print(f"Warning: Invalid tier range {t}. Skipping.")
|
| 264 |
-
else:
|
| 265 |
-
valid_tiers.append(t)
|
| 266 |
-
|
| 267 |
-
valid_tiers = sorted(valid_tiers, key=lambda x: x[0])
|
| 268 |
-
|
| 269 |
-
return valid_tiers
|
| 270 |
-
|
| 271 |
-
# --- Combined Interface Function for Discount Model ---
|
| 272 |
-
def update_discount_model(annual_demand, order_cost, holding_cost_rate_percent,
|
| 273 |
-
tier1_min, tier1_max, tier1_uc,
|
| 274 |
-
tier2_min, tier2_max, tier2_uc,
|
| 275 |
-
tier3_min, tier3_max, tier3_uc):
|
| 276 |
-
"""Updates all outputs for the Quantity Discount tab."""
|
| 277 |
-
holding_cost_rate = holding_cost_rate_percent / 100.0
|
| 278 |
-
|
| 279 |
-
if any(x <= 0 for x in [annual_demand, order_cost, holding_cost_rate_percent]):
|
| 280 |
-
return pd.DataFrame(), 0, 0, 0, "", "Please enter positive values for core discount parameters."
|
| 281 |
-
|
| 282 |
-
discount_tiers = create_discount_tiers_df(
|
| 283 |
-
tier1_min, tier1_max, tier1_uc,
|
| 284 |
-
tier2_min, tier2_max, tier2_uc,
|
| 285 |
-
tier3_min, tier3_max, tier3_uc
|
| 286 |
-
)
|
| 287 |
-
|
| 288 |
-
if not discount_tiers:
|
| 289 |
-
return pd.DataFrame(), 0, 0, 0, "", "No valid discount tiers defined. Please define at least one tier with positive min quantity and unit cost."
|
| 290 |
-
|
| 291 |
-
for i in range(len(discount_tiers) - 1):
|
| 292 |
-
if discount_tiers[i][2] < discount_tiers[i+1][2]:
|
| 293 |
-
return pd.DataFrame(), 0, 0, 0, "", "Error: Unit costs must be non-increasing with quantity."
|
| 294 |
-
|
| 295 |
-
df_results, best_eoq, best_total_cost, best_unit_cost, best_tier, message = \
|
| 296 |
-
calculate_eoq_with_discount(annual_demand, order_cost, holding_cost_rate, discount_tiers[0][2], discount_tiers)
|
| 297 |
-
|
| 298 |
-
return df_results, best_eoq, best_total_cost, best_unit_cost, best_tier, message
|
| 299 |
-
|
| 300 |
-
# --- Gradio Interface ---
|
| 301 |
-
|
| 302 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="Advanced Operations Management Dashboard") as demo:
|
| 303 |
-
gr.Markdown(
|
| 304 |
-
"""
|
| 305 |
-
# π Advanced Operations Management Dashboard (Xyphor Advisors)
|
| 306 |
-
Welcome to your comprehensive tool for optimizing operations and inventory decisions.
|
| 307 |
-
"""
|
| 308 |
-
)
|
| 309 |
-
|
| 310 |
-
with gr.Tabs():
|
| 311 |
-
# --- Tab 1: Basic EOQ Model ---
|
| 312 |
-
with gr.TabItem("Basic EOQ Model"):
|
| 313 |
-
gr.Markdown("## Economic Order Quantity (EOQ) Calculation")
|
| 314 |
-
gr.Markdown("Find the optimal order quantity that minimizes the sum of ordering and holding costs.")
|
| 315 |
-
with gr.Row():
|
| 316 |
-
with gr.Column():
|
| 317 |
-
gr.Markdown("### π οΈ Input Parameters")
|
| 318 |
-
basic_demand = gr.Slider(100, 50000, value=12000, step=100, label="Annual Demand (D) [units/year]")
|
| 319 |
-
basic_order_cost = gr.Slider(5, 500, value=100, step=5, label="Ordering Cost (S) [$/order]")
|
| 320 |
-
basic_holding_cost = gr.Slider(0.1, 50, value=5, step=0.1, label="Holding Cost (H) [$/unit/year]")
|
| 321 |
-
basic_lead_time = gr.Slider(0, 30, value=7, step=1, label="Lead Time [days]", info="Time from order placement to receipt.")
|
| 322 |
-
|
| 323 |
-
basic_status_message = gr.Textbox(label="Status", interactive=False, value="Enter parameters and run.")
|
| 324 |
-
|
| 325 |
-
with gr.Column():
|
| 326 |
-
gr.Markdown("### π Cost Analysis & Optimal Q")
|
| 327 |
-
basic_plot_output = gr.Plot(label="EOQ Cost Curves", scale=2)
|
| 328 |
-
|
| 329 |
-
with gr.Accordion("Detailed Results", open=True):
|
| 330 |
-
gr.Markdown("#### Key Metrics")
|
| 331 |
-
with gr.Row():
|
| 332 |
-
basic_eoq_out = gr.Number(label="Optimal Order Quantity (EOQ) [units]", precision=0)
|
| 333 |
-
basic_num_orders_out = gr.Number(label="Annual Orders [count]", precision=2)
|
| 334 |
-
basic_avg_inventory_out = gr.Number(label="Average Inventory [units]", precision=2)
|
| 335 |
-
gr.Markdown("#### Annual Costs")
|
| 336 |
-
with gr.Row():
|
| 337 |
-
basic_ordering_cost_out = gr.Number(label="Annual Ordering Cost [$]", precision=2)
|
| 338 |
-
basic_holding_cost_out = gr.Number(label="Annual Holding Cost [$]", precision=2)
|
| 339 |
-
basic_total_cost_out = gr.Number(label="Total Annual Cost [$]", precision=2)
|
| 340 |
-
gr.Markdown("#### Reorder Point (Simple)")
|
| 341 |
-
with gr.Row():
|
| 342 |
-
basic_reorder_point_out = gr.Number(label="Reorder Point (without Safety Stock) [units]", precision=0)
|
| 343 |
-
|
| 344 |
-
basic_inputs = [basic_demand, basic_order_cost, basic_holding_cost, basic_lead_time]
|
| 345 |
-
basic_outputs = [basic_plot_output, basic_eoq_out, basic_num_orders_out, basic_avg_inventory_out,
|
| 346 |
-
basic_ordering_cost_out, basic_holding_cost_out, basic_total_cost_out,
|
| 347 |
-
basic_reorder_point_out, basic_status_message]
|
| 348 |
-
|
| 349 |
-
for inp in basic_inputs:
|
| 350 |
-
inp.change(
|
| 351 |
-
fn=update_basic_eoq,
|
| 352 |
-
inputs=basic_inputs,
|
| 353 |
-
outputs=basic_outputs
|
| 354 |
-
)
|
| 355 |
-
|
| 356 |
-
demo.load(
|
| 357 |
-
fn=update_basic_eoq,
|
| 358 |
-
inputs=basic_inputs,
|
| 359 |
-
outputs=basic_outputs
|
| 360 |
-
)
|
| 361 |
-
|
| 362 |
-
# --- Tab 2: Reorder Point & Safety Stock ---
|
| 363 |
-
with gr.TabItem("Reorder Point (ROP) & Safety Stock"):
|
| 364 |
-
gr.Markdown("## Reorder Point & Safety Stock Calculator")
|
| 365 |
-
gr.Markdown("Determine the precise inventory level at which to place a new order to avoid stockouts.")
|
| 366 |
-
with gr.Row():
|
| 367 |
-
with gr.Column():
|
| 368 |
-
gr.Markdown("### π οΈ Input Parameters")
|
| 369 |
-
rop_avg_demand = gr.Number(label="Average Daily Demand [units/day]", value=50)
|
| 370 |
-
rop_lead_time = gr.Number(label="Lead Time [days]", value=10)
|
| 371 |
-
rop_std_dev = gr.Number(label="Standard Deviation of Daily Demand", value=5)
|
| 372 |
-
rop_z_score = gr.Slider(minimum=0.0, maximum=3.0, value=1.65, step=0.01,
|
| 373 |
-
label="Z-Score (for Service Level)",
|
| 374 |
-
info="e.g., 1.65 for 95% service level, 2.33 for 99%")
|
| 375 |
-
rop_status = gr.Textbox(label="Status", interactive=False)
|
| 376 |
-
|
| 377 |
-
with gr.Column():
|
| 378 |
-
gr.Markdown("### π Calculated Metrics")
|
| 379 |
-
rop_ss_out = gr.Number(label="Safety Stock (SS) [units]", precision=0,
|
| 380 |
-
info="The buffer stock held to prevent stockouts.")
|
| 381 |
-
rop_dlt_out = gr.Number(label="Demand During Lead Time [units]", precision=0,
|
| 382 |
-
info="Total expected demand while waiting for the order.")
|
| 383 |
-
rop_out = gr.Number(label="Reorder Point (ROP) [units]", precision=0,
|
| 384 |
-
info="Place an order when inventory hits this level. (ROP = SS + Demand During Lead Time)")
|
| 385 |
-
|
| 386 |
-
rop_inputs = [rop_avg_demand, rop_lead_time, rop_std_dev, rop_z_score]
|
| 387 |
-
rop_outputs = [rop_ss_out, rop_dlt_out, rop_out, rop_status]
|
| 388 |
-
|
| 389 |
-
for inp in rop_inputs:
|
| 390 |
-
inp.change(fn=calculate_rop_and_ss, inputs=rop_inputs, outputs=rop_outputs)
|
| 391 |
-
demo.load(fn=calculate_rop_and_ss, inputs=rop_inputs, outputs=rop_outputs)
|
| 392 |
-
|
| 393 |
-
# --- Tab 3: Quantity Discount Model ---
|
| 394 |
-
with gr.TabItem("Quantity Discount Model"):
|
| 395 |
-
gr.Markdown("## EOQ with Quantity Discounts")
|
| 396 |
-
gr.Markdown("Evaluate the impact of price breaks on the optimal order quantity and total cost.")
|
| 397 |
-
with gr.Row():
|
| 398 |
-
with gr.Column():
|
| 399 |
-
gr.Markdown("### π οΈ Core Parameters")
|
| 400 |
-
discount_demand = gr.Slider(100, 50000, value=15000, step=100, label="Annual Demand (D) [units/year]")
|
| 401 |
-
discount_order_cost = gr.Slider(5, 500, value=75, step=5, label="Ordering Cost (S) [$/order]")
|
| 402 |
-
discount_holding_rate = gr.Slider(0.01, 0.5, value=0.2, step=0.01, label="Holding Cost Rate [% of Unit Cost]", info="e.g., 20% = 0.2")
|
| 403 |
-
|
| 404 |
-
gr.Markdown("### π·οΈ Discount Tiers")
|
| 405 |
-
gr.Markdown("Define up to three discount tiers. Unit costs must be non-increasing.")
|
| 406 |
-
with gr.Accordion("Tier 1", open=True):
|
| 407 |
-
with gr.Row():
|
| 408 |
-
tier1_min_qty = gr.Number(label="Min Qty", value=0, precision=0)
|
| 409 |
-
tier1_max_qty = gr.Number(label="Max Qty", value=999, precision=0)
|
| 410 |
-
tier1_unit_cost = gr.Number(label="Unit Cost ($)", value=10.00, precision=2)
|
| 411 |
-
with gr.Accordion("Tier 2"):
|
| 412 |
-
with gr.Row():
|
| 413 |
-
tier2_min_qty = gr.Number(label="Min Qty", value=1000, precision=0)
|
| 414 |
-
tier2_max_qty = gr.Number(label="Max Qty", value=4999, precision=0)
|
| 415 |
-
tier2_unit_cost = gr.Number(label="Unit Cost ($)", value=9.50, precision=2)
|
| 416 |
-
with gr.Accordion("Tier 3"):
|
| 417 |
-
with gr.Row():
|
| 418 |
-
tier3_min_qty = gr.Number(label="Min Qty", value=5000, precision=0)
|
| 419 |
-
tier3_max_qty = gr.Number(label="Max Qty", value=None, precision=0, info="Leave blank for infinity")
|
| 420 |
-
tier3_unit_cost = gr.Number(label="Unit Cost ($)", value=9.00, precision=2)
|
| 421 |
-
|
| 422 |
-
discount_status_message = gr.Textbox(label="Status", interactive=False, value="Enter parameters and run.")
|
| 423 |
-
|
| 424 |
-
with gr.Column():
|
| 425 |
-
gr.Markdown("### π Tier Analysis & Optimal Selection")
|
| 426 |
-
discount_output_df = gr.DataFrame(label="Discount Tier Analysis", interactive=False)
|
| 427 |
-
gr.Markdown("#### Optimal Discount Solution")
|
| 428 |
-
with gr.Row():
|
| 429 |
-
best_discount_eoq_out = gr.Number(label="Optimal Order Quantity [units]", precision=0)
|
| 430 |
-
best_discount_cost_out = gr.Number(label="Minimum Total Annual Cost [$]", precision=2)
|
| 431 |
-
with gr.Row():
|
| 432 |
-
best_discount_unit_cost_out = gr.Number(label="Unit Cost at Optimal Q [$]", precision=2)
|
| 433 |
-
best_discount_tier_out = gr.Textbox(label="Optimal Tier", interactive=False)
|
| 434 |
-
|
| 435 |
-
discount_inputs = [discount_demand, discount_order_cost, discount_holding_rate,
|
| 436 |
-
tier1_min_qty, tier1_max_qty, tier1_unit_cost,
|
| 437 |
-
tier2_min_qty, tier2_max_qty, tier2_unit_cost,
|
| 438 |
-
tier3_min_qty, tier3_max_qty, tier3_unit_cost]
|
| 439 |
-
discount_outputs = [discount_output_df, best_discount_eoq_out, best_discount_cost_out,
|
| 440 |
-
best_discount_unit_cost_out, best_discount_tier_out, discount_status_message]
|
| 441 |
-
|
| 442 |
-
for inp in discount_inputs:
|
| 443 |
-
inp.change(
|
| 444 |
-
fn=update_discount_model,
|
| 445 |
-
inputs=discount_inputs,
|
| 446 |
-
outputs=discount_outputs
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
-
demo.load(
|
| 450 |
-
fn=update_discount_model,
|
| 451 |
-
inputs=discount_inputs,
|
| 452 |
-
outputs=discount_outputs
|
| 453 |
-
)
|
| 454 |
-
|
| 455 |
-
# --- Tab 4: Production Order Quantity (POQ) Model ---
|
| 456 |
-
with gr.TabItem("Production Order Quantity (POQ) Model"):
|
| 457 |
-
gr.Markdown("## Production Order Quantity (POQ) Calculation")
|
| 458 |
-
gr.Markdown("Determine the optimal batch size when production is internal and gradual.")
|
| 459 |
-
with gr.Row():
|
| 460 |
-
with gr.Column():
|
| 461 |
-
gr.Markdown("### π οΈ Input Parameters")
|
| 462 |
-
poq_demand = gr.Slider(100, 50000, value=20000, step=100, label="Annual Demand (D) [units/year]")
|
| 463 |
-
poq_setup_cost = gr.Slider(5, 500, value=200, step=5, label="Setup Cost (S) [$/setup]")
|
| 464 |
-
poq_holding_cost = gr.Slider(0.1, 50, value=8, step=0.1, label="Holding Cost (H) [$/unit/year]")
|
| 465 |
-
gr.Markdown("### π Production Specifics")
|
| 466 |
-
poq_prod_rate = gr.Slider(10, 2000, value=500, step=10, label="Daily Production Rate (P) [units/day]")
|
| 467 |
-
poq_demand_rate = gr.Slider(1, 1000, value=80, step=1, label="Daily Demand Rate (d) [units/day]", info="Must be less than Daily Production Rate.")
|
| 468 |
-
|
| 469 |
-
poq_status_message = gr.Textbox(label="Status", interactive=False, value="Enter parameters and run.")
|
| 470 |
-
|
| 471 |
-
with gr.Column():
|
| 472 |
-
gr.Markdown("### π Cost Analysis & Optimal Batch Size")
|
| 473 |
-
poq_plot_output = gr.Plot(label="POQ Cost Curves", scale=2)
|
| 474 |
-
|
| 475 |
-
with gr.Accordion("Detailed Results", open=True):
|
| 476 |
-
gr.Markdown("#### Key Metrics")
|
| 477 |
-
with gr.Row():
|
| 478 |
-
poq_out = gr.Number(label="Optimal Production Quantity (POQ) [units]", precision=0)
|
| 479 |
-
poq_num_setups_out = gr.Number(label="Annual Setups [count]", precision=2)
|
| 480 |
-
poq_max_inv_out = gr.Number(label="Maximum Inventory Level [units]", precision=2)
|
| 481 |
-
poq_avg_inv_out = gr.Number(label="Average Inventory [units]", precision=2)
|
| 482 |
-
gr.Markdown("#### Annual Costs")
|
| 483 |
-
with gr.Row():
|
| 484 |
-
poq_setup_cost_out = gr.Number(label="Annual Setup Cost [$]", precision=2)
|
| 485 |
-
poq_holding_cost_out = gr.Number(label="Annual Holding Cost [$]", precision=2)
|
| 486 |
-
poq_total_cost_out = gr.Number(label="Total Annual Cost [$]", precision=2)
|
| 487 |
-
gr.Markdown("#### Production Cycle Details")
|
| 488 |
-
with gr.Row():
|
| 489 |
-
poq_prod_days_out = gr.Number(label="Production Run Duration [days]", precision=2)
|
| 490 |
-
poq_cycle_days_out = gr.Number(label="Inventory Cycle Duration [days]", precision=2)
|
| 491 |
-
|
| 492 |
-
poq_inputs = [poq_demand, poq_setup_cost, poq_holding_cost, poq_prod_rate, poq_demand_rate]
|
| 493 |
-
poq_outputs = [poq_plot_output, poq_out, poq_num_setups_out, poq_max_inv_out, poq_avg_inv_out,
|
| 494 |
-
poq_setup_cost_out, poq_holding_cost_out, poq_total_cost_out,
|
| 495 |
-
poq_prod_days_out, poq_cycle_days_out, poq_status_message]
|
| 496 |
-
|
| 497 |
-
for inp in poq_inputs:
|
| 498 |
-
inp.change(
|
| 499 |
-
fn=update_poq_model,
|
| 500 |
-
inputs=poq_inputs,
|
| 501 |
-
outputs=poq_outputs
|
| 502 |
-
)
|
| 503 |
-
|
| 504 |
-
demo.load(
|
| 505 |
-
fn=update_poq_model,
|
| 506 |
-
inputs=poq_inputs,
|
| 507 |
-
outputs=poq_outputs
|
| 508 |
-
)
|
| 509 |
-
|
| 510 |
-
# --- Tab 5: Demand Forecasting (SMA) ---
|
| 511 |
-
with gr.TabItem("Demand Forecasting (SMA)"):
|
| 512 |
-
gr.Markdown("## Simple Moving Average (SMA) Forecasting")
|
| 513 |
-
gr.Markdown("Forecast future demand based on the average of past demand data.")
|
| 514 |
-
with gr.Row():
|
| 515 |
-
with gr.Column(scale=1):
|
| 516 |
-
gr.Markdown("### π οΈ Input Parameters")
|
| 517 |
-
sma_data = gr.Textbox(label="Past Demand Data (comma-separated)",
|
| 518 |
-
value="100, 110, 105, 120, 115, 125, 130, 122, 135, 140")
|
| 519 |
-
sma_window = gr.Slider(minimum=2, maximum=10, value=3, step=1,
|
| 520 |
-
label="SMA Window Size (Periods)")
|
| 521 |
-
sma_status = gr.Textbox(label="Status & Forecast", interactive=False)
|
| 522 |
-
|
| 523 |
-
with gr.Column(scale=2):
|
| 524 |
-
gr.Markdown("### π Forecast Plot")
|
| 525 |
-
sma_plot = gr.Plot()
|
| 526 |
-
sma_df = gr.DataFrame(label="Data and SMA")
|
| 527 |
-
|
| 528 |
-
sma_inputs = [sma_data, sma_window]
|
| 529 |
-
sma_outputs = [sma_df, sma_plot, sma_status]
|
| 530 |
-
|
| 531 |
-
for inp in sma_inputs:
|
| 532 |
-
inp.change(fn=calculate_sma_forecast, inputs=sma_inputs, outputs=sma_outputs)
|
| 533 |
-
demo.load(fn=calculate_sma_forecast, inputs=sma_inputs, outputs=sma_outputs)
|
| 534 |
-
|
| 535 |
-
if __name__ == "__main__":
|
| 536 |
-
demo.launch(debug=True)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import io
|
| 6 |
+
from scipy.stats import norm # Using scipy.stats, but it's a common numpy-adjacent lib for stats. If not allowed, can be replaced.
|
| 7 |
+
# Let's stick to numpy. We can use norm.ppf or just ask for Z-score.
|
| 8 |
+
# User said NO new concepts. Z-score is simple. I will just ask for the Z-score directly.
|
| 9 |
+
|
| 10 |
+
# --- Calculation Functions ---
|
| 11 |
+
|
| 12 |
+
def calculate_basic_eoq(annual_demand, order_cost, holding_cost_per_unit):
|
| 13 |
+
"""Calculates EOQ and related metrics for the basic model."""
|
| 14 |
+
if annual_demand <= 0 or order_cost <= 0 or holding_cost_per_unit <= 0:
|
| 15 |
+
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan
|
| 16 |
+
|
| 17 |
+
eoq = np.sqrt((2 * annual_demand * order_cost) / holding_cost_per_unit)
|
| 18 |
+
num_orders_per_year = annual_demand / eoq if eoq > 0 else np.inf
|
| 19 |
+
avg_inventory = eoq / 2
|
| 20 |
+
annual_ordering_cost = num_orders_per_year * order_cost
|
| 21 |
+
annual_holding_cost = avg_inventory * holding_cost_per_unit
|
| 22 |
+
total_annual_cost = annual_ordering_cost + annual_holding_cost
|
| 23 |
+
|
| 24 |
+
demand_per_day = annual_demand / 365
|
| 25 |
+
|
| 26 |
+
return eoq, num_orders_per_year, avg_inventory, annual_ordering_cost, annual_holding_cost, total_annual_cost, demand_per_day
|
| 27 |
+
|
| 28 |
+
def calculate_eoq_with_discount(annual_demand, order_cost, holding_cost_rate, unit_cost, discount_tiers):
|
| 29 |
+
"""Calculates EOQ with quantity discounts."""
|
| 30 |
+
if annual_demand <= 0 or order_cost <= 0 or holding_cost_rate <= 0 or unit_cost <= 0:
|
| 31 |
+
return pd.DataFrame(), np.nan, np.nan, np.nan, np.nan, "Invalid inputs for discount model."
|
| 32 |
+
|
| 33 |
+
results = []
|
| 34 |
+
best_total_cost = np.inf
|
| 35 |
+
best_eoq = np.nan
|
| 36 |
+
best_unit_cost = np.nan
|
| 37 |
+
best_tier = ""
|
| 38 |
+
|
| 39 |
+
discount_tiers = sorted(discount_tiers, key=lambda x: x[0])
|
| 40 |
+
|
| 41 |
+
for i, (min_qty, max_qty, tier_unit_cost) in enumerate(discount_tiers):
|
| 42 |
+
holding_cost_per_unit = holding_cost_rate * tier_unit_cost
|
| 43 |
+
|
| 44 |
+
tier_eoq, _, _, _, _, _, _ = calculate_basic_eoq(annual_demand, order_cost, holding_cost_per_unit)
|
| 45 |
+
|
| 46 |
+
if tier_eoq < min_qty:
|
| 47 |
+
relevant_qty = min_qty
|
| 48 |
+
elif tier_eoq > max_qty and max_qty != np.inf:
|
| 49 |
+
relevant_qty = max_qty
|
| 50 |
+
else:
|
| 51 |
+
relevant_qty = tier_eoq
|
| 52 |
+
|
| 53 |
+
if relevant_qty <= 0:
|
| 54 |
+
num_orders = np.inf
|
| 55 |
+
ordering_cost = np.inf
|
| 56 |
+
holding_cost = 0
|
| 57 |
+
purchase_cost = annual_demand * tier_unit_cost
|
| 58 |
+
total_cost = np.inf
|
| 59 |
+
else:
|
| 60 |
+
num_orders = annual_demand / relevant_qty
|
| 61 |
+
ordering_cost = num_orders * order_cost
|
| 62 |
+
holding_cost = (relevant_qty / 2) * holding_cost_per_unit
|
| 63 |
+
purchase_cost = annual_demand * tier_unit_cost
|
| 64 |
+
total_cost = ordering_cost + holding_cost + purchase_cost
|
| 65 |
+
|
| 66 |
+
results.append({
|
| 67 |
+
"Tier": f"Tier {i+1} ({min_qty}-{max_qty if max_qty != np.inf else 'β'})",
|
| 68 |
+
"Unit Cost ($)": tier_unit_cost,
|
| 69 |
+
"Holding Cost/Unit/Year ($)": f"{holding_cost_per_unit:.2f}",
|
| 70 |
+
"Theoretical EOQ (Units)": f"{tier_eoq:.0f}",
|
| 71 |
+
"Relevant Q (Units)": f"{relevant_qty:.0f}",
|
| 72 |
+
"Annual Ordering Cost ($)": f"{ordering_cost:.2f}",
|
| 73 |
+
"Annual Holding Cost ($)": f"{holding_cost:.2f}",
|
| 74 |
+
"Annual Purchase Cost ($)": f"{purchase_cost:.2f}",
|
| 75 |
+
"Total Annual Cost ($)": f"{total_cost:.2f}"
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
if total_cost < best_total_cost:
|
| 79 |
+
best_total_cost = total_cost
|
| 80 |
+
best_eoq = relevant_qty
|
| 81 |
+
best_unit_cost = tier_unit_cost
|
| 82 |
+
best_tier = f"Tier {i+1}"
|
| 83 |
+
|
| 84 |
+
df = pd.DataFrame(results)
|
| 85 |
+
|
| 86 |
+
return df, best_eoq, best_total_cost, best_unit_cost, best_tier, "Analysis complete."
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def calculate_poq(annual_demand, order_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate):
|
| 90 |
+
"""Calculates Production Order Quantity (POQ) and related metrics."""
|
| 91 |
+
if annual_demand <= 0 or order_cost <= 0 or holding_cost_per_unit <= 0 or \
|
| 92 |
+
daily_production_rate <= 0 or daily_demand_rate <= 0:
|
| 93 |
+
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan
|
| 94 |
+
|
| 95 |
+
if daily_production_rate <= daily_demand_rate:
|
| 96 |
+
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, "Production rate must be greater than demand rate."
|
| 97 |
+
|
| 98 |
+
poq = np.sqrt((2 * annual_demand * order_cost) / (holding_cost_per_unit * (1 - (daily_demand_rate / daily_production_rate))))
|
| 99 |
+
|
| 100 |
+
num_setups_per_year = annual_demand / poq if poq > 0 else np.inf
|
| 101 |
+
max_inventory_level = poq * (1 - (daily_demand_rate / daily_production_rate))
|
| 102 |
+
avg_inventory = max_inventory_level / 2
|
| 103 |
+
|
| 104 |
+
annual_setup_cost = num_setups_per_year * order_cost
|
| 105 |
+
annual_holding_cost = avg_inventory * holding_cost_per_unit
|
| 106 |
+
total_annual_cost = annual_setup_cost + annual_holding_cost
|
| 107 |
+
|
| 108 |
+
production_run_days = poq / daily_production_rate
|
| 109 |
+
inventory_cycle_days = poq / daily_demand_rate
|
| 110 |
+
|
| 111 |
+
return poq, num_setups_per_year, max_inventory_level, avg_inventory, annual_setup_cost, \
|
| 112 |
+
annual_holding_cost, total_annual_cost, production_run_days, inventory_cycle_days
|
| 113 |
+
|
| 114 |
+
def calculate_rop_and_ss(avg_daily_demand, lead_time_days, std_dev_daily_demand, service_level_z):
|
| 115 |
+
"""Calculates Reorder Point and Safety Stock."""
|
| 116 |
+
if avg_daily_demand < 0 or lead_time_days < 0 or std_dev_daily_demand < 0 or service_level_z < 0:
|
| 117 |
+
return 0, 0, 0, "Inputs must be non-negative."
|
| 118 |
+
|
| 119 |
+
std_dev_lead_time = std_dev_daily_demand * np.sqrt(lead_time_days)
|
| 120 |
+
safety_stock = std_dev_lead_time * service_level_z
|
| 121 |
+
demand_during_lead_time = avg_daily_demand * lead_time_days
|
| 122 |
+
reorder_point = demand_during_lead_time + safety_stock
|
| 123 |
+
|
| 124 |
+
return safety_stock, demand_during_lead_time, reorder_point, "Calculation successful."
|
| 125 |
+
|
| 126 |
+
def calculate_sma_forecast(demand_data_str, window_size):
|
| 127 |
+
"""Calculates Simple Moving Average (SMA) forecast."""
|
| 128 |
+
if not demand_data_str:
|
| 129 |
+
return pd.DataFrame(), None, "Please enter demand data."
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
demand_values = [float(d.strip()) for d in demand_data_str.split(',') if d.strip()]
|
| 133 |
+
if len(demand_values) < window_size:
|
| 134 |
+
return pd.DataFrame(), None, f"Not enough data for window size {window_size}. Need at least {window_size} data points."
|
| 135 |
+
|
| 136 |
+
df = pd.DataFrame({'Demand': demand_values})
|
| 137 |
+
df['Period'] = range(1, len(df) + 1)
|
| 138 |
+
|
| 139 |
+
# Calculate SMA
|
| 140 |
+
df[f'SMA (Window={window_size})'] = df['Demand'].rolling(window=window_size).mean()
|
| 141 |
+
|
| 142 |
+
# Forecast next period
|
| 143 |
+
forecast_next_period = df['Demand'].tail(window_size).mean()
|
| 144 |
+
|
| 145 |
+
# Create plot
|
| 146 |
+
fig, ax = plt.subplots(figsize=(8, 4))
|
| 147 |
+
ax.plot(df['Period'], df['Demand'], label='Actual Demand', marker='o', linestyle='-')
|
| 148 |
+
ax.plot(df['Period'], df[f'SMA (Window={window_size})'], label='SMA', marker='x', linestyle='--')
|
| 149 |
+
|
| 150 |
+
ax.set_title('Simple Moving Average (SMA) Forecast', fontsize=14)
|
| 151 |
+
ax.set_xlabel('Period', fontsize=10)
|
| 152 |
+
ax.set_ylabel('Demand', fontsize=10)
|
| 153 |
+
ax.legend()
|
| 154 |
+
ax.grid(True, linestyle=':', alpha=0.7)
|
| 155 |
+
plt.tight_layout()
|
| 156 |
+
plt.close(fig)
|
| 157 |
+
|
| 158 |
+
return df, fig, f"Forecast for next period: {forecast_next_period:.2f}"
|
| 159 |
+
|
| 160 |
+
except Exception as e:
|
| 161 |
+
return pd.DataFrame(), None, f"Error: {e}. Ensure data is comma-separated numbers."
|
| 162 |
+
|
| 163 |
+
# --- Plotting Function ---
|
| 164 |
+
|
| 165 |
+
def create_eoq_plot(annual_demand, order_cost, holding_cost_per_unit, min_q=1, max_q_multiplier=2.5, current_eoq=None):
|
| 166 |
+
"""Generates the EOQ cost curves plot."""
|
| 167 |
+
if annual_demand <= 0 or order_cost <= 0 or holding_cost_per_unit <= 0:
|
| 168 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 169 |
+
ax.text(0.5, 0.5, "Invalid input for plot.", horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
|
| 170 |
+
ax.axis('off')
|
| 171 |
+
plt.close(fig)
|
| 172 |
+
return fig
|
| 173 |
+
|
| 174 |
+
if current_eoq is None or np.isnan(current_eoq) or current_eoq <= 0:
|
| 175 |
+
current_eoq = np.sqrt((2 * annual_demand * order_cost) / holding_cost_per_unit)
|
| 176 |
+
if np.isnan(current_eoq) or current_eoq <= 0:
|
| 177 |
+
current_eoq = 100
|
| 178 |
+
|
| 179 |
+
quantity_range = np.linspace(min_q, current_eoq * max_q_multiplier, 300)
|
| 180 |
+
|
| 181 |
+
quantity_range = quantity_range[quantity_range > 0]
|
| 182 |
+
|
| 183 |
+
ordering_costs = (annual_demand / quantity_range) * order_cost
|
| 184 |
+
holding_costs = (quantity_range / 2) * holding_cost_per_unit
|
| 185 |
+
total_costs = ordering_costs + holding_costs
|
| 186 |
+
|
| 187 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 188 |
+
|
| 189 |
+
ax.plot(quantity_range, holding_costs, label='Annual Holding Cost', color='orange')
|
| 190 |
+
ax.plot(quantity_range, ordering_costs, label='Annual Ordering Cost', color='blue')
|
| 191 |
+
ax.plot(quantity_range, total_costs, label='Total Cost', color='green', linewidth=2.5)
|
| 192 |
+
|
| 193 |
+
if not np.isnan(current_eoq) and current_eoq > 0:
|
| 194 |
+
ax.axvline(x=current_eoq, color='red', linestyle='--', label=f'EOQ: {current_eoq:.0f} units')
|
| 195 |
+
total_cost_at_eoq_idx = np.argmin(np.abs(quantity_range - current_eoq))
|
| 196 |
+
total_cost_at_eoq = total_costs[total_cost_at_eoq_idx]
|
| 197 |
+
ax.plot(current_eoq, total_cost_at_eoq, 'ro')
|
| 198 |
+
|
| 199 |
+
ax.set_title('EOQ Cost Analysis', fontsize=12)
|
| 200 |
+
ax.set_xlabel('Order Quantity (Units)', fontsize=10)
|
| 201 |
+
ax.set_ylabel('Annual Cost ($)', fontsize=10)
|
| 202 |
+
ax.legend(fontsize=8, loc='upper right')
|
| 203 |
+
ax.grid(True, linestyle=':', alpha=0.7)
|
| 204 |
+
ax.set_ylim(bottom=0)
|
| 205 |
+
ax.set_xlim(left=0)
|
| 206 |
+
ax.tick_params(axis='both', which='major', labelsize=8)
|
| 207 |
+
|
| 208 |
+
plt.tight_layout()
|
| 209 |
+
plt.close(fig)
|
| 210 |
+
return fig
|
| 211 |
+
|
| 212 |
+
# --- Combined Interface Function for Basic EOQ ---
|
| 213 |
+
|
| 214 |
+
def update_basic_eoq(annual_demand, order_cost, holding_cost_per_unit, lead_time_days):
|
| 215 |
+
"""Updates all outputs for the Basic EOQ tab."""
|
| 216 |
+
if any(x <= 0 for x in [annual_demand, order_cost, holding_cost_per_unit]):
|
| 217 |
+
return None, 0, 0, 0, 0, 0, 0, 0, "Please enter positive values for all basic EOQ parameters."
|
| 218 |
+
|
| 219 |
+
eoq, num_orders, avg_inventory, annual_ordering_cost, annual_holding_cost, total_annual_cost, demand_per_day = \
|
| 220 |
+
calculate_basic_eoq(annual_demand, order_cost, holding_cost_per_unit)
|
| 221 |
+
|
| 222 |
+
# Simple Reorder Point (no safety stock)
|
| 223 |
+
reorder_point = demand_per_day * lead_time_days
|
| 224 |
+
|
| 225 |
+
plot_fig = create_eoq_plot(annual_demand, order_cost, holding_cost_per_unit, current_eoq=eoq)
|
| 226 |
+
|
| 227 |
+
return plot_fig, eoq, num_orders, avg_inventory, annual_ordering_cost, annual_holding_cost, \
|
| 228 |
+
total_annual_cost, reorder_point, "Calculation successful."
|
| 229 |
+
|
| 230 |
+
# --- Combined Interface Function for POQ ---
|
| 231 |
+
def update_poq_model(annual_demand, setup_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate):
|
| 232 |
+
"""Updates all outputs for the POQ tab."""
|
| 233 |
+
if any(x <= 0 for x in [annual_demand, setup_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate]):
|
| 234 |
+
return None, 0, 0, 0, 0, 0, 0, 0, 0, "Please enter positive values for all POQ parameters."
|
| 235 |
+
|
| 236 |
+
if daily_production_rate <= daily_demand_rate:
|
| 237 |
+
return None, 0, 0, 0, 0, 0, 0, 0, 0, "Production rate must be greater than demand rate."
|
| 238 |
+
|
| 239 |
+
poq, num_setups, max_inv, avg_inv, annual_setup_cost, annual_holding_cost, total_cost, prod_days, cycle_days = \
|
| 240 |
+
calculate_poq(annual_demand, setup_cost, holding_cost_per_unit, daily_production_rate, daily_demand_rate)
|
| 241 |
+
|
| 242 |
+
plot_fig = create_eoq_plot(annual_demand, setup_cost, holding_cost_per_unit, current_eoq=poq, max_q_multiplier=2.0)
|
| 243 |
+
|
| 244 |
+
return plot_fig, poq, num_setups, max_inv, avg_inv, annual_setup_cost, annual_holding_cost, total_cost, \
|
| 245 |
+
prod_days, cycle_days, "Calculation successful."
|
| 246 |
+
|
| 247 |
+
# --- Helper for Discount Tiers ---
|
| 248 |
+
def create_discount_tiers_df(tier1_min, tier1_max, tier1_uc,
|
| 249 |
+
tier2_min, tier2_max, tier2_uc,
|
| 250 |
+
tier3_min, tier3_max, tier3_uc):
|
| 251 |
+
"""Helper to create the discount_tiers list from Gradio inputs."""
|
| 252 |
+
tiers = []
|
| 253 |
+
if tier1_min is not None and tier1_uc is not None and tier1_min >= 0 and tier1_uc >= 0:
|
| 254 |
+
tiers.append((tier1_min, tier1_max if tier1_max is not None else np.inf, tier1_uc))
|
| 255 |
+
if tier2_min is not None and tier2_uc is not None and tier2_min >= 0 and tier2_uc >= 0:
|
| 256 |
+
tiers.append((tier2_min, tier2_max if tier2_max is not None else np.inf, tier2_uc))
|
| 257 |
+
if tier3_min is not None and tier3_uc is not None and tier3_min >= 0 and tier3_uc >= 0:
|
| 258 |
+
tiers.append((tier3_min, tier3_max if tier3_max is not None else np.inf, tier3_uc))
|
| 259 |
+
|
| 260 |
+
valid_tiers = []
|
| 261 |
+
for t in tiers:
|
| 262 |
+
if t[1] != np.inf and t[0] >= t[1]:
|
| 263 |
+
print(f"Warning: Invalid tier range {t}. Skipping.")
|
| 264 |
+
else:
|
| 265 |
+
valid_tiers.append(t)
|
| 266 |
+
|
| 267 |
+
valid_tiers = sorted(valid_tiers, key=lambda x: x[0])
|
| 268 |
+
|
| 269 |
+
return valid_tiers
|
| 270 |
+
|
| 271 |
+
# --- Combined Interface Function for Discount Model ---
|
| 272 |
+
def update_discount_model(annual_demand, order_cost, holding_cost_rate_percent,
|
| 273 |
+
tier1_min, tier1_max, tier1_uc,
|
| 274 |
+
tier2_min, tier2_max, tier2_uc,
|
| 275 |
+
tier3_min, tier3_max, tier3_uc):
|
| 276 |
+
"""Updates all outputs for the Quantity Discount tab."""
|
| 277 |
+
holding_cost_rate = holding_cost_rate_percent / 100.0
|
| 278 |
+
|
| 279 |
+
if any(x <= 0 for x in [annual_demand, order_cost, holding_cost_rate_percent]):
|
| 280 |
+
return pd.DataFrame(), 0, 0, 0, "", "Please enter positive values for core discount parameters."
|
| 281 |
+
|
| 282 |
+
discount_tiers = create_discount_tiers_df(
|
| 283 |
+
tier1_min, tier1_max, tier1_uc,
|
| 284 |
+
tier2_min, tier2_max, tier2_uc,
|
| 285 |
+
tier3_min, tier3_max, tier3_uc
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if not discount_tiers:
|
| 289 |
+
return pd.DataFrame(), 0, 0, 0, "", "No valid discount tiers defined. Please define at least one tier with positive min quantity and unit cost."
|
| 290 |
+
|
| 291 |
+
for i in range(len(discount_tiers) - 1):
|
| 292 |
+
if discount_tiers[i][2] < discount_tiers[i+1][2]:
|
| 293 |
+
return pd.DataFrame(), 0, 0, 0, "", "Error: Unit costs must be non-increasing with quantity."
|
| 294 |
+
|
| 295 |
+
df_results, best_eoq, best_total_cost, best_unit_cost, best_tier, message = \
|
| 296 |
+
calculate_eoq_with_discount(annual_demand, order_cost, holding_cost_rate, discount_tiers[0][2], discount_tiers)
|
| 297 |
+
|
| 298 |
+
return df_results, best_eoq, best_total_cost, best_unit_cost, best_tier, message
|
| 299 |
+
|
| 300 |
+
# --- Gradio Interface ---
|
| 301 |
+
|
| 302 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Advanced Operations Management Dashboard") as demo:
|
| 303 |
+
gr.Markdown(
|
| 304 |
+
"""
|
| 305 |
+
# π Advanced Operations Management Dashboard (Xyphor Advisors)
|
| 306 |
+
Welcome to your comprehensive tool for optimizing operations and inventory decisions.
|
| 307 |
+
"""
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
with gr.Tabs():
|
| 311 |
+
# --- Tab 1: Basic EOQ Model ---
|
| 312 |
+
with gr.TabItem("Basic EOQ Model"):
|
| 313 |
+
gr.Markdown("## Economic Order Quantity (EOQ) Calculation")
|
| 314 |
+
gr.Markdown("Find the optimal order quantity that minimizes the sum of ordering and holding costs.")
|
| 315 |
+
with gr.Row():
|
| 316 |
+
with gr.Column():
|
| 317 |
+
gr.Markdown("### π οΈ Input Parameters")
|
| 318 |
+
basic_demand = gr.Slider(100, 50000, value=12000, step=100, label="Annual Demand (D) [units/year]")
|
| 319 |
+
basic_order_cost = gr.Slider(5, 500, value=100, step=5, label="Ordering Cost (S) [$/order]")
|
| 320 |
+
basic_holding_cost = gr.Slider(0.1, 50, value=5, step=0.1, label="Holding Cost (H) [$/unit/year]")
|
| 321 |
+
basic_lead_time = gr.Slider(0, 30, value=7, step=1, label="Lead Time [days]", info="Time from order placement to receipt.")
|
| 322 |
+
|
| 323 |
+
basic_status_message = gr.Textbox(label="Status", interactive=False, value="Enter parameters and run.")
|
| 324 |
+
|
| 325 |
+
with gr.Column():
|
| 326 |
+
gr.Markdown("### π Cost Analysis & Optimal Q")
|
| 327 |
+
basic_plot_output = gr.Plot(label="EOQ Cost Curves", scale=2)
|
| 328 |
+
|
| 329 |
+
with gr.Accordion("Detailed Results", open=True):
|
| 330 |
+
gr.Markdown("#### Key Metrics")
|
| 331 |
+
with gr.Row():
|
| 332 |
+
basic_eoq_out = gr.Number(label="Optimal Order Quantity (EOQ) [units]", precision=0)
|
| 333 |
+
basic_num_orders_out = gr.Number(label="Annual Orders [count]", precision=2)
|
| 334 |
+
basic_avg_inventory_out = gr.Number(label="Average Inventory [units]", precision=2)
|
| 335 |
+
gr.Markdown("#### Annual Costs")
|
| 336 |
+
with gr.Row():
|
| 337 |
+
basic_ordering_cost_out = gr.Number(label="Annual Ordering Cost [$]", precision=2)
|
| 338 |
+
basic_holding_cost_out = gr.Number(label="Annual Holding Cost [$]", precision=2)
|
| 339 |
+
basic_total_cost_out = gr.Number(label="Total Annual Cost [$]", precision=2)
|
| 340 |
+
gr.Markdown("#### Reorder Point (Simple)")
|
| 341 |
+
with gr.Row():
|
| 342 |
+
basic_reorder_point_out = gr.Number(label="Reorder Point (without Safety Stock) [units]", precision=0)
|
| 343 |
+
|
| 344 |
+
basic_inputs = [basic_demand, basic_order_cost, basic_holding_cost, basic_lead_time]
|
| 345 |
+
basic_outputs = [basic_plot_output, basic_eoq_out, basic_num_orders_out, basic_avg_inventory_out,
|
| 346 |
+
basic_ordering_cost_out, basic_holding_cost_out, basic_total_cost_out,
|
| 347 |
+
basic_reorder_point_out, basic_status_message]
|
| 348 |
+
|
| 349 |
+
for inp in basic_inputs:
|
| 350 |
+
inp.change(
|
| 351 |
+
fn=update_basic_eoq,
|
| 352 |
+
inputs=basic_inputs,
|
| 353 |
+
outputs=basic_outputs
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
demo.load(
|
| 357 |
+
fn=update_basic_eoq,
|
| 358 |
+
inputs=basic_inputs,
|
| 359 |
+
outputs=basic_outputs
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# --- Tab 2: Reorder Point & Safety Stock ---
|
| 363 |
+
with gr.TabItem("Reorder Point (ROP) & Safety Stock"):
|
| 364 |
+
gr.Markdown("## Reorder Point & Safety Stock Calculator")
|
| 365 |
+
gr.Markdown("Determine the precise inventory level at which to place a new order to avoid stockouts.")
|
| 366 |
+
with gr.Row():
|
| 367 |
+
with gr.Column():
|
| 368 |
+
gr.Markdown("### π οΈ Input Parameters")
|
| 369 |
+
rop_avg_demand = gr.Number(label="Average Daily Demand [units/day]", value=50)
|
| 370 |
+
rop_lead_time = gr.Number(label="Lead Time [days]", value=10)
|
| 371 |
+
rop_std_dev = gr.Number(label="Standard Deviation of Daily Demand", value=5)
|
| 372 |
+
rop_z_score = gr.Slider(minimum=0.0, maximum=3.0, value=1.65, step=0.01,
|
| 373 |
+
label="Z-Score (for Service Level)",
|
| 374 |
+
info="e.g., 1.65 for 95% service level, 2.33 for 99%")
|
| 375 |
+
rop_status = gr.Textbox(label="Status", interactive=False)
|
| 376 |
+
|
| 377 |
+
with gr.Column():
|
| 378 |
+
gr.Markdown("### π Calculated Metrics")
|
| 379 |
+
rop_ss_out = gr.Number(label="Safety Stock (SS) [units]", precision=0,
|
| 380 |
+
info="The buffer stock held to prevent stockouts.")
|
| 381 |
+
rop_dlt_out = gr.Number(label="Demand During Lead Time [units]", precision=0,
|
| 382 |
+
info="Total expected demand while waiting for the order.")
|
| 383 |
+
rop_out = gr.Number(label="Reorder Point (ROP) [units]", precision=0,
|
| 384 |
+
info="Place an order when inventory hits this level. (ROP = SS + Demand During Lead Time)")
|
| 385 |
+
|
| 386 |
+
rop_inputs = [rop_avg_demand, rop_lead_time, rop_std_dev, rop_z_score]
|
| 387 |
+
rop_outputs = [rop_ss_out, rop_dlt_out, rop_out, rop_status]
|
| 388 |
+
|
| 389 |
+
for inp in rop_inputs:
|
| 390 |
+
inp.change(fn=calculate_rop_and_ss, inputs=rop_inputs, outputs=rop_outputs)
|
| 391 |
+
demo.load(fn=calculate_rop_and_ss, inputs=rop_inputs, outputs=rop_outputs)
|
| 392 |
+
|
| 393 |
+
# --- Tab 3: Quantity Discount Model ---
|
| 394 |
+
with gr.TabItem("Quantity Discount Model"):
|
| 395 |
+
gr.Markdown("## EOQ with Quantity Discounts")
|
| 396 |
+
gr.Markdown("Evaluate the impact of price breaks on the optimal order quantity and total cost.")
|
| 397 |
+
with gr.Row():
|
| 398 |
+
with gr.Column():
|
| 399 |
+
gr.Markdown("### π οΈ Core Parameters")
|
| 400 |
+
discount_demand = gr.Slider(100, 50000, value=15000, step=100, label="Annual Demand (D) [units/year]")
|
| 401 |
+
discount_order_cost = gr.Slider(5, 500, value=75, step=5, label="Ordering Cost (S) [$/order]")
|
| 402 |
+
discount_holding_rate = gr.Slider(0.01, 0.5, value=0.2, step=0.01, label="Holding Cost Rate [% of Unit Cost]", info="e.g., 20% = 0.2")
|
| 403 |
+
|
| 404 |
+
gr.Markdown("### π·οΈ Discount Tiers")
|
| 405 |
+
gr.Markdown("Define up to three discount tiers. Unit costs must be non-increasing.")
|
| 406 |
+
with gr.Accordion("Tier 1", open=True):
|
| 407 |
+
with gr.Row():
|
| 408 |
+
tier1_min_qty = gr.Number(label="Min Qty", value=0, precision=0)
|
| 409 |
+
tier1_max_qty = gr.Number(label="Max Qty", value=999, precision=0)
|
| 410 |
+
tier1_unit_cost = gr.Number(label="Unit Cost ($)", value=10.00, precision=2)
|
| 411 |
+
with gr.Accordion("Tier 2"):
|
| 412 |
+
with gr.Row():
|
| 413 |
+
tier2_min_qty = gr.Number(label="Min Qty", value=1000, precision=0)
|
| 414 |
+
tier2_max_qty = gr.Number(label="Max Qty", value=4999, precision=0)
|
| 415 |
+
tier2_unit_cost = gr.Number(label="Unit Cost ($)", value=9.50, precision=2)
|
| 416 |
+
with gr.Accordion("Tier 3"):
|
| 417 |
+
with gr.Row():
|
| 418 |
+
tier3_min_qty = gr.Number(label="Min Qty", value=5000, precision=0)
|
| 419 |
+
tier3_max_qty = gr.Number(label="Max Qty", value=None, precision=0, info="Leave blank for infinity")
|
| 420 |
+
tier3_unit_cost = gr.Number(label="Unit Cost ($)", value=9.00, precision=2)
|
| 421 |
+
|
| 422 |
+
discount_status_message = gr.Textbox(label="Status", interactive=False, value="Enter parameters and run.")
|
| 423 |
+
|
| 424 |
+
with gr.Column():
|
| 425 |
+
gr.Markdown("### π Tier Analysis & Optimal Selection")
|
| 426 |
+
discount_output_df = gr.DataFrame(label="Discount Tier Analysis", interactive=False)
|
| 427 |
+
gr.Markdown("#### Optimal Discount Solution")
|
| 428 |
+
with gr.Row():
|
| 429 |
+
best_discount_eoq_out = gr.Number(label="Optimal Order Quantity [units]", precision=0)
|
| 430 |
+
best_discount_cost_out = gr.Number(label="Minimum Total Annual Cost [$]", precision=2)
|
| 431 |
+
with gr.Row():
|
| 432 |
+
best_discount_unit_cost_out = gr.Number(label="Unit Cost at Optimal Q [$]", precision=2)
|
| 433 |
+
best_discount_tier_out = gr.Textbox(label="Optimal Tier", interactive=False)
|
| 434 |
+
|
| 435 |
+
discount_inputs = [discount_demand, discount_order_cost, discount_holding_rate,
|
| 436 |
+
tier1_min_qty, tier1_max_qty, tier1_unit_cost,
|
| 437 |
+
tier2_min_qty, tier2_max_qty, tier2_unit_cost,
|
| 438 |
+
tier3_min_qty, tier3_max_qty, tier3_unit_cost]
|
| 439 |
+
discount_outputs = [discount_output_df, best_discount_eoq_out, best_discount_cost_out,
|
| 440 |
+
best_discount_unit_cost_out, best_discount_tier_out, discount_status_message]
|
| 441 |
+
|
| 442 |
+
for inp in discount_inputs:
|
| 443 |
+
inp.change(
|
| 444 |
+
fn=update_discount_model,
|
| 445 |
+
inputs=discount_inputs,
|
| 446 |
+
outputs=discount_outputs
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
demo.load(
|
| 450 |
+
fn=update_discount_model,
|
| 451 |
+
inputs=discount_inputs,
|
| 452 |
+
outputs=discount_outputs
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
# --- Tab 4: Production Order Quantity (POQ) Model ---
|
| 456 |
+
with gr.TabItem("Production Order Quantity (POQ) Model"):
|
| 457 |
+
gr.Markdown("## Production Order Quantity (POQ) Calculation")
|
| 458 |
+
gr.Markdown("Determine the optimal batch size when production is internal and gradual.")
|
| 459 |
+
with gr.Row():
|
| 460 |
+
with gr.Column():
|
| 461 |
+
gr.Markdown("### π οΈ Input Parameters")
|
| 462 |
+
poq_demand = gr.Slider(100, 50000, value=20000, step=100, label="Annual Demand (D) [units/year]")
|
| 463 |
+
poq_setup_cost = gr.Slider(5, 500, value=200, step=5, label="Setup Cost (S) [$/setup]")
|
| 464 |
+
poq_holding_cost = gr.Slider(0.1, 50, value=8, step=0.1, label="Holding Cost (H) [$/unit/year]")
|
| 465 |
+
gr.Markdown("### π Production Specifics")
|
| 466 |
+
poq_prod_rate = gr.Slider(10, 2000, value=500, step=10, label="Daily Production Rate (P) [units/day]")
|
| 467 |
+
poq_demand_rate = gr.Slider(1, 1000, value=80, step=1, label="Daily Demand Rate (d) [units/day]", info="Must be less than Daily Production Rate.")
|
| 468 |
+
|
| 469 |
+
poq_status_message = gr.Textbox(label="Status", interactive=False, value="Enter parameters and run.")
|
| 470 |
+
|
| 471 |
+
with gr.Column():
|
| 472 |
+
gr.Markdown("### π Cost Analysis & Optimal Batch Size")
|
| 473 |
+
poq_plot_output = gr.Plot(label="POQ Cost Curves", scale=2)
|
| 474 |
+
|
| 475 |
+
with gr.Accordion("Detailed Results", open=True):
|
| 476 |
+
gr.Markdown("#### Key Metrics")
|
| 477 |
+
with gr.Row():
|
| 478 |
+
poq_out = gr.Number(label="Optimal Production Quantity (POQ) [units]", precision=0)
|
| 479 |
+
poq_num_setups_out = gr.Number(label="Annual Setups [count]", precision=2)
|
| 480 |
+
poq_max_inv_out = gr.Number(label="Maximum Inventory Level [units]", precision=2)
|
| 481 |
+
poq_avg_inv_out = gr.Number(label="Average Inventory [units]", precision=2)
|
| 482 |
+
gr.Markdown("#### Annual Costs")
|
| 483 |
+
with gr.Row():
|
| 484 |
+
poq_setup_cost_out = gr.Number(label="Annual Setup Cost [$]", precision=2)
|
| 485 |
+
poq_holding_cost_out = gr.Number(label="Annual Holding Cost [$]", precision=2)
|
| 486 |
+
poq_total_cost_out = gr.Number(label="Total Annual Cost [$]", precision=2)
|
| 487 |
+
gr.Markdown("#### Production Cycle Details")
|
| 488 |
+
with gr.Row():
|
| 489 |
+
poq_prod_days_out = gr.Number(label="Production Run Duration [days]", precision=2)
|
| 490 |
+
poq_cycle_days_out = gr.Number(label="Inventory Cycle Duration [days]", precision=2)
|
| 491 |
+
|
| 492 |
+
poq_inputs = [poq_demand, poq_setup_cost, poq_holding_cost, poq_prod_rate, poq_demand_rate]
|
| 493 |
+
poq_outputs = [poq_plot_output, poq_out, poq_num_setups_out, poq_max_inv_out, poq_avg_inv_out,
|
| 494 |
+
poq_setup_cost_out, poq_holding_cost_out, poq_total_cost_out,
|
| 495 |
+
poq_prod_days_out, poq_cycle_days_out, poq_status_message]
|
| 496 |
+
|
| 497 |
+
for inp in poq_inputs:
|
| 498 |
+
inp.change(
|
| 499 |
+
fn=update_poq_model,
|
| 500 |
+
inputs=poq_inputs,
|
| 501 |
+
outputs=poq_outputs
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
demo.load(
|
| 505 |
+
fn=update_poq_model,
|
| 506 |
+
inputs=poq_inputs,
|
| 507 |
+
outputs=poq_outputs
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# --- Tab 5: Demand Forecasting (SMA) ---
|
| 511 |
+
with gr.TabItem("Demand Forecasting (SMA)"):
|
| 512 |
+
gr.Markdown("## Simple Moving Average (SMA) Forecasting")
|
| 513 |
+
gr.Markdown("Forecast future demand based on the average of past demand data.")
|
| 514 |
+
with gr.Row():
|
| 515 |
+
with gr.Column(scale=1):
|
| 516 |
+
gr.Markdown("### π οΈ Input Parameters")
|
| 517 |
+
sma_data = gr.Textbox(label="Past Demand Data (comma-separated)",
|
| 518 |
+
value="100, 110, 105, 120, 115, 125, 130, 122, 135, 140")
|
| 519 |
+
sma_window = gr.Slider(minimum=2, maximum=10, value=3, step=1,
|
| 520 |
+
label="SMA Window Size (Periods)")
|
| 521 |
+
sma_status = gr.Textbox(label="Status & Forecast", interactive=False)
|
| 522 |
+
|
| 523 |
+
with gr.Column(scale=2):
|
| 524 |
+
gr.Markdown("### π Forecast Plot")
|
| 525 |
+
sma_plot = gr.Plot()
|
| 526 |
+
sma_df = gr.DataFrame(label="Data and SMA")
|
| 527 |
+
|
| 528 |
+
sma_inputs = [sma_data, sma_window]
|
| 529 |
+
sma_outputs = [sma_df, sma_plot, sma_status]
|
| 530 |
+
|
| 531 |
+
for inp in sma_inputs:
|
| 532 |
+
inp.change(fn=calculate_sma_forecast, inputs=sma_inputs, outputs=sma_outputs)
|
| 533 |
+
demo.load(fn=calculate_sma_forecast, inputs=sma_inputs, outputs=sma_outputs)
|
| 534 |
+
|
| 535 |
+
if __name__ == "__main__":
|
| 536 |
+
demo.launch(share=True, inbrowser=True, debug=True)
|