Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# @title Beer Game Final Version (v4.25 -
|
| 3 |
|
| 4 |
# -----------------------------------------------------------------------------
|
| 5 |
# 1. Import Libraries
|
|
@@ -121,9 +121,8 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
|
|
| 121 |
st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
|
| 122 |
return 4, f"API_ERROR: {e}"
|
| 123 |
|
| 124 |
-
# =============== NEW PROMPT FUNCTION (v2) - Sterman Heuristic ===============
|
| 125 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 126 |
-
# This function's logic
|
| 127 |
e_state = echelon_state_decision_point
|
| 128 |
base_info = f"Your Current Status at the **{e_state['name']}** for **Week {week}** (Before Shipping):\n- On-hand inventory: {e_state['inventory']} units.\n- Backlog (total unfilled orders): {e_state['backlog']} units.\n- Incoming order this week (just received): {e_state['incoming_order']} units.\n"
|
| 129 |
if e_state['name'] == 'Factory':
|
|
@@ -132,10 +131,6 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 132 |
else:
|
| 133 |
task_word = "order quantity"
|
| 134 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
| 135 |
-
|
| 136 |
-
# --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
|
| 137 |
-
# (These prompts are already good and remain unchanged)
|
| 138 |
-
|
| 139 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 140 |
stable_demand = 8
|
| 141 |
if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
|
|
@@ -152,7 +147,6 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 152 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 153 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 154 |
return f"**You are a perfectly rational supply chain AI with full system visibility.**\nYour only goal is to maintain stability and minimize costs based on mathematical optimization.\n**System Analysis:**\n* **Known Stable End-Customer Demand:** {stable_demand} units/week.\n* **Your Current Total Inventory Position:** {inventory_position} units. {inv_pos_components}\n* **Optimal Target Inventory Level:** {target_inventory_level} units (Target for {total_lead_time} weeks lead time).\n* **Mathematically Optimal {task_word.title()}:** The optimal decision is **{optimal_order} units**.\n**Your Task:** Confirm this optimal {task_word}. Respond with a single integer."
|
| 155 |
-
|
| 156 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 157 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 158 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
@@ -166,108 +160,87 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
|
|
| 166 |
calculated_order = anchor_demand + inventory_correction - supply_line
|
| 167 |
rational_local_order = max(0, int(calculated_order))
|
| 168 |
return f"**You are a perfectly rational supply chain AI with ONLY LOCAL information.**\nYou must use a logical heuristic to make a stable decision. A proven method is \"Anchoring and Adjustment\".\n\n{base_info}\n\n**Rational Calculation (Anchoring & Adjustment):**\n1. **Anchor on Demand:** Your best guess for future demand is your last incoming order: **{anchor_demand} units**.\n2. **Adjust for Inventory:** You want to hold a safety stock of {safety_stock} units. Your current stock (before shipping) is {e_state['inventory'] - e_state['backlog']}. You need to order an extra **{inventory_correction} units** to correct this.\n3. **Account for {supply_line_desc}:** You already have **{supply_line} units** being processed. These should be subtracted from your new decision.\n\n**Final Calculation:**\n* Decision = (Anchor Demand) + (Inventory Adjustment) - ({supply_line_desc})\n* Decision = {anchor_demand} + {inventory_correction} - {supply_line} = **{rational_local_order} units**.\n**Your Task:** Confirm this locally rational {task_word}. Respond with a single integer."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
# --- HUMAN-LIKE (DESCRIPTIVE) PROMPTS ---
|
| 171 |
-
# (These are NEW and implement a flawed, panicky Sterman-style heuristic)
|
| 172 |
-
|
| 173 |
-
else: # Catches both 'human_like' / 'local' and 'human_like' / 'full'
|
| 174 |
-
|
| 175 |
-
# This is the flawed Sterman heuristic
|
| 176 |
-
DESIRED_INVENTORY = 12 # Matches initial inventory
|
| 177 |
-
anchor_demand = e_state['incoming_order']
|
| 178 |
-
net_inventory = e_state['inventory'] - e_state['backlog']
|
| 179 |
-
stock_correction = DESIRED_INVENTORY - net_inventory
|
| 180 |
-
panicky_order = max(0, int(anchor_demand + stock_correction))
|
| 181 |
-
panicky_order_calc = f"{anchor_demand} (Your Incoming Order) + {stock_correction} (Your Stock Correction)"
|
| 182 |
-
|
| 183 |
-
# Get supply line info *just to show* the AI it's being ignored
|
| 184 |
-
if e_state['name'] == 'Factory':
|
| 185 |
-
supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
|
| 186 |
-
supply_line_desc = "In Production"
|
| 187 |
-
else:
|
| 188 |
-
order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
|
| 189 |
-
supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
|
| 190 |
-
supply_line_desc = "Supply Line"
|
| 191 |
-
|
| 192 |
-
if info_sharing == 'local':
|
| 193 |
-
return f"""
|
| 194 |
-
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
|
| 195 |
-
You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
|
| 196 |
-
|
| 197 |
-
{base_info}
|
| 198 |
-
|
| 199 |
-
**Your Flawed 'Human' Heuristic:**
|
| 200 |
-
Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
|
| 201 |
-
A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
|
| 202 |
-
|
| 203 |
-
**Your 'Panic' Calculation (Ignoring the Supply Line):**
|
| 204 |
-
1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
|
| 205 |
-
2. **Correct for Stock:** Your desired 'safe' inventory is {DESIRED_INVENTORY}. Your current net inventory is {net_inventory}. You need to order **{stock_correction}** more units to feel safe again.
|
| 206 |
-
3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
|
| 207 |
-
|
| 208 |
-
**Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
|
| 209 |
-
* Order = {panicky_order_calc} = **{panicky_order} units**.
|
| 210 |
-
|
| 211 |
-
**Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
|
| 212 |
-
"""
|
| 213 |
-
|
| 214 |
-
elif info_sharing == 'full':
|
| 215 |
-
# Build the "Full Info" string just for context
|
| 216 |
-
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
|
| 217 |
-
for name, other_e_state in all_echelons_state_decision_point.items():
|
| 218 |
-
if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
|
| 219 |
-
|
| 220 |
-
return f"""
|
| 221 |
-
**You are a supply chain manager ({e_state['name']}) with full system visibility.**
|
| 222 |
-
{base_info}
|
| 223 |
-
{full_info_str}
|
| 224 |
-
|
| 225 |
-
**A "Human-like" Flawed Decision:**
|
| 226 |
-
Even though you have full information, you are judged by *your own* performance (your inventory, your backlog).
|
| 227 |
-
You tend to react to your *local* situation (like the classic Sterman 1989 model) instead of using the complex full-system data.
|
| 228 |
-
A 'rational' player would use the end-customer demand (8) and account for the *entire* system, but your gut-instinct is to panic about *your* numbers.
|
| 229 |
-
|
| 230 |
-
**Your 'Panic' Calculation (Ignoring Full Info and Your Supply Line):**
|
| 231 |
-
1. **Anchor on *Your* Demand:** You just got an order for **{anchor_demand}** units. You react to this, not the end-customer demand.
|
| 232 |
-
2. **Correct for *Your* Stock:** Your desired 'safe' inventory is {DESIRED_INVENTORY}. Your current net inventory is {net_inventory}. You need to order **{stock_correction}** more units.
|
| 233 |
-
3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
|
| 234 |
-
|
| 235 |
-
**Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
|
| 236 |
-
* Order = {panicky_order_calc} = **{panicky_order} units**.
|
| 237 |
-
|
| 238 |
-
**Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
|
| 239 |
-
"""
|
| 240 |
-
# =========================================================
|
| 241 |
-
|
| 242 |
-
# =============== REVERTED `step_game` (v2) - The stable logic ===============
|
| 243 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 244 |
-
# This is the correct logic from v4.17
|
| 245 |
state = st.session_state.game_state
|
| 246 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 247 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 248 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 249 |
llm_raw_responses = {}
|
|
|
|
|
|
|
| 250 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 251 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
| 252 |
-
|
| 253 |
-
#
|
| 254 |
arrived_this_week = {name: 0 for name in echelon_order}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
inventory_after_arrival = {}
|
| 256 |
factory_state = echelons["Factory"]
|
| 257 |
produced_units = 0
|
| 258 |
if state['factory_production_pipeline']:
|
| 259 |
produced_units = state['factory_production_pipeline'].popleft()
|
| 260 |
-
arrived_this_week["Factory"] = produced_units
|
| 261 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 262 |
|
| 263 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 264 |
arrived_shipment = 0
|
| 265 |
if echelons[name]['incoming_shipments']:
|
| 266 |
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
| 267 |
-
arrived_this_week[name] = arrived_shipment
|
| 268 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 269 |
-
|
| 270 |
-
|
| 271 |
total_backlog_before_shipping = {}
|
| 272 |
for name in echelon_order:
|
| 273 |
incoming_order_for_this_week = 0
|
|
@@ -301,6 +274,8 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 301 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 302 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 303 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
|
|
|
|
|
|
| 304 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 305 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 306 |
if 'current_ai_suggestion' in log_entry: del log_entry['current_ai_suggestion']
|
|
@@ -308,19 +283,23 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
|
|
| 308 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 309 |
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
|
| 310 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
| 311 |
-
log_entry[f'{name}.opening_inventory'] = opening_inventories[name]; log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
|
| 312 |
-
log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
|
| 313 |
|
| 314 |
-
#
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 319 |
state['logs'].append(log_entry)
|
| 320 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 321 |
state['current_ai_suggestion'] = None # Clean up
|
| 322 |
if state['week'] > WEEKS: state['game_running'] = False
|
| 323 |
-
# ==============================================================================
|
| 324 |
|
| 325 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
| 326 |
# This function remains correct.
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# @title Beer Game Final Version (v4.25 - Based on v4.21 Logic + UI Fixes v3 - Log Fix)
|
| 3 |
|
| 4 |
# -----------------------------------------------------------------------------
|
| 5 |
# 1. Import Libraries
|
|
|
|
| 121 |
st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
|
| 122 |
return 4, f"API_ERROR: {e}"
|
| 123 |
|
|
|
|
| 124 |
def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
|
| 125 |
+
# This function's logic remains correct (from v4.21).
|
| 126 |
e_state = echelon_state_decision_point
|
| 127 |
base_info = f"Your Current Status at the **{e_state['name']}** for **Week {week}** (Before Shipping):\n- On-hand inventory: {e_state['inventory']} units.\n- Backlog (total unfilled orders): {e_state['backlog']} units.\n- Incoming order this week (just received): {e_state['incoming_order']} units.\n"
|
| 128 |
if e_state['name'] == 'Factory':
|
|
|
|
| 131 |
else:
|
| 132 |
task_word = "order quantity"
|
| 133 |
base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
if llm_personality == 'perfect_rational' and info_sharing == 'full':
|
| 135 |
stable_demand = 8
|
| 136 |
if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
|
|
|
|
| 147 |
inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
|
| 148 |
optimal_order = max(0, int(target_inventory_level - inventory_position))
|
| 149 |
return f"**You are a perfectly rational supply chain AI with full system visibility.**\nYour only goal is to maintain stability and minimize costs based on mathematical optimization.\n**System Analysis:**\n* **Known Stable End-Customer Demand:** {stable_demand} units/week.\n* **Your Current Total Inventory Position:** {inventory_position} units. {inv_pos_components}\n* **Optimal Target Inventory Level:** {target_inventory_level} units (Target for {total_lead_time} weeks lead time).\n* **Mathematically Optimal {task_word.title()}:** The optimal decision is **{optimal_order} units**.\n**Your Task:** Confirm this optimal {task_word}. Respond with a single integer."
|
|
|
|
| 150 |
elif llm_personality == 'perfect_rational' and info_sharing == 'local':
|
| 151 |
safety_stock = 4; anchor_demand = e_state['incoming_order']
|
| 152 |
inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
|
|
|
|
| 160 |
calculated_order = anchor_demand + inventory_correction - supply_line
|
| 161 |
rational_local_order = max(0, int(calculated_order))
|
| 162 |
return f"**You are a perfectly rational supply chain AI with ONLY LOCAL information.**\nYou must use a logical heuristic to make a stable decision. A proven method is \"Anchoring and Adjustment\".\n\n{base_info}\n\n**Rational Calculation (Anchoring & Adjustment):**\n1. **Anchor on Demand:** Your best guess for future demand is your last incoming order: **{anchor_demand} units**.\n2. **Adjust for Inventory:** You want to hold a safety stock of {safety_stock} units. Your current stock (before shipping) is {e_state['inventory'] - e_state['backlog']}. You need to order an extra **{inventory_correction} units** to correct this.\n3. **Account for {supply_line_desc}:** You already have **{supply_line} units** being processed. These should be subtracted from your new decision.\n\n**Final Calculation:**\n* Decision = (Anchor Demand) + (Inventory Adjustment) - ({supply_line_desc})\n* Decision = {anchor_demand} + {inventory_correction} - {supply_line} = **{rational_local_order} units**.\n**Your Task:** Confirm this locally rational {task_word}. Respond with a single integer."
|
| 163 |
+
elif llm_personality == 'human_like' and info_sharing == 'full':
|
| 164 |
+
full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
|
| 165 |
+
for name, other_e_state in all_echelons_state_decision_point.items():
|
| 166 |
+
if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
|
| 167 |
+
return f"""
|
| 168 |
+
**You are a supply chain manager ({e_state['name']}) with full system visibility.**
|
| 169 |
+
You can see everyone's current inventory and backlog before shipping, and the real customer demand.
|
| 170 |
+
{base_info}
|
| 171 |
+
{full_info_str}
|
| 172 |
+
**Your Task:** Your primary responsibility is to meet the demand from your direct customer (your `Incoming order this week`: **{e_state['incoming_order']}** units), which contributes to your total current backlog of {e_state['backlog']}.
|
| 173 |
+
While you can see the stable end-customer demand ({get_customer_demand(week)} units), your priority is to fulfill the order you just received and manage your inventory/backlog.
|
| 174 |
+
You are still human and might get anxious about your own stock levels.
|
| 175 |
+
What {task_word} should you decide on this week? Respond with a single integer.
|
| 176 |
+
"""
|
| 177 |
+
elif llm_personality == 'human_like' and info_sharing == 'local':
|
| 178 |
+
return f"""
|
| 179 |
+
**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited view and tend to over-correct based on fear.
|
| 180 |
+
Your top priority is to NOT have a backlog.
|
| 181 |
+
{base_info}
|
| 182 |
+
**Your Task:** You just received an incoming order for **{e_state['incoming_order']}** units, adding to your total backlog.
|
| 183 |
+
Your gut instinct is to panic and {task_word.split(' ')[0]} enough to ensure you are never caught with a backlog again, considering your current inventory.
|
| 184 |
+
**React emotionally.** What is your knee-jerk {task_word}? Respond with a single integer.
|
| 185 |
+
"""
|
| 186 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
|
| 188 |
+
# This is the correct logic from v4.17
|
| 189 |
state = st.session_state.game_state
|
| 190 |
week, echelons, human_role = state['week'], state['echelons'], state['human_role']
|
| 191 |
llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
|
| 192 |
echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
|
| 193 |
llm_raw_responses = {}
|
| 194 |
+
|
| 195 |
+
# Capture opening state for logging
|
| 196 |
opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
|
| 197 |
opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
|
| 198 |
+
|
| 199 |
+
# --- LOG FIX (v3): Capture arrival data BEFORE mutation ---
|
| 200 |
arrived_this_week = {name: 0 for name in echelon_order}
|
| 201 |
+
# This dict will store the value shown on the UI for "next week"
|
| 202 |
+
opening_arriving_next_week_UI_VALUE = {name: 0 for name in echelon_order}
|
| 203 |
+
|
| 204 |
+
# Factory
|
| 205 |
+
factory_q = state['factory_production_pipeline']
|
| 206 |
+
if factory_q:
|
| 207 |
+
arrived_this_week["Factory"] = factory_q[0] # Read before pop
|
| 208 |
+
if len(factory_q) > 1:
|
| 209 |
+
opening_arriving_next_week_UI_VALUE["Factory"] = factory_q[1] # Read [1] before pop
|
| 210 |
+
|
| 211 |
+
# R, W, D
|
| 212 |
+
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 213 |
+
shipment_q = echelons[name]['incoming_shipments']
|
| 214 |
+
if shipment_q:
|
| 215 |
+
arrived_this_week[name] = shipment_q[0] # Read before pop
|
| 216 |
+
|
| 217 |
+
# This logic MUST match the v2 UI logic
|
| 218 |
+
if name == 'Distributor':
|
| 219 |
+
# "Next" for Distributor is what's at the front of the Factory's pipeline
|
| 220 |
+
if factory_q:
|
| 221 |
+
opening_arriving_next_week_UI_VALUE[name] = factory_q[0]
|
| 222 |
+
elif name in ("Retailer", "Wholesaler"):
|
| 223 |
+
if len(shipment_q) > 1: # q_len=2
|
| 224 |
+
opening_arriving_next_week_UI_VALUE[name] = shipment_q[1]
|
| 225 |
+
elif len(shipment_q) == 1: # q_len=1
|
| 226 |
+
opening_arriving_next_week_UI_VALUE[name] = shipment_q[0] # Match the v2 UI
|
| 227 |
+
# --- END OF LOG FIX (v3) ---
|
| 228 |
+
|
| 229 |
+
# Now, the *actual* state mutation (popping)
|
| 230 |
inventory_after_arrival = {}
|
| 231 |
factory_state = echelons["Factory"]
|
| 232 |
produced_units = 0
|
| 233 |
if state['factory_production_pipeline']:
|
| 234 |
produced_units = state['factory_production_pipeline'].popleft()
|
|
|
|
| 235 |
inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
|
| 236 |
|
| 237 |
for name in ["Retailer", "Wholesaler", "Distributor"]:
|
| 238 |
arrived_shipment = 0
|
| 239 |
if echelons[name]['incoming_shipments']:
|
| 240 |
arrived_shipment = echelons[name]['incoming_shipments'].popleft()
|
|
|
|
| 241 |
inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
|
| 242 |
+
|
| 243 |
+
# (Rest of game logic)
|
| 244 |
total_backlog_before_shipping = {}
|
| 245 |
for name in echelon_order:
|
| 246 |
incoming_order_for_this_week = 0
|
|
|
|
| 274 |
if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
|
| 275 |
if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
|
| 276 |
if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
|
| 277 |
+
|
| 278 |
+
# (Logging)
|
| 279 |
log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
|
| 280 |
del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
|
| 281 |
if 'current_ai_suggestion' in log_entry: del log_entry['current_ai_suggestion']
|
|
|
|
| 283 |
e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
|
| 284 |
for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
|
| 285 |
log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
|
|
|
|
|
|
|
| 286 |
|
| 287 |
+
# --- LOG FIX (v3): Use captured values ---
|
| 288 |
+
log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
|
| 289 |
+
log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
|
| 290 |
+
log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name] # Use captured value
|
| 291 |
+
|
| 292 |
+
if name != 'Factory':
|
| 293 |
+
log_entry[f'{name}.arriving_next_week'] = opening_arriving_next_week_UI_VALUE[name]
|
| 294 |
+
else:
|
| 295 |
+
log_entry[f'{name}.production_completing_next_week'] = opening_arriving_next_week_UI_VALUE[name]
|
| 296 |
+
# --- END OF LOG FIX (v3) ---
|
| 297 |
+
|
| 298 |
log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
|
| 299 |
state['logs'].append(log_entry)
|
| 300 |
state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
|
| 301 |
state['current_ai_suggestion'] = None # Clean up
|
| 302 |
if state['week'] > WEEKS: state['game_running'] = False
|
|
|
|
| 303 |
|
| 304 |
def plot_results(df: pd.DataFrame, title: str, human_role: str):
|
| 305 |
# This function remains correct.
|