Lilli98 commited on
Commit
fad3536
·
verified ·
1 Parent(s): cbb0719

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -151
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # app.py
2
- # @title Beer Game Final Version (v8 - LT=3 GUARANTEED + Log/UI Fix)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
@@ -35,10 +35,7 @@ INITIAL_BACKLOG = 0
35
  ORDER_PASSING_DELAY = 1 # Handled by last_week_orders
36
  SHIPPING_DELAY = 2 # General shipping delay (R->W, W->D)
37
  FACTORY_LEAD_TIME = 1
38
- # --------------------- LT=3 FIX ---------------------
39
- # This MUST be 1 for LT=3. (Order W1 -> F Rec W2 -> F Prod W2 -> F Fin W3 -> F Ship W3 -> D Rec W4)
40
- FACTORY_SHIPPING_DELAY = 1
41
- # ----------------------------------------------------
42
  HOLDING_COST = 0.5
43
  BACKLOG_COST = 1.0
44
 
@@ -89,12 +86,9 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
89
  for i, name in enumerate(roles):
90
  upstream = roles[i + 1] if i + 1 < len(roles) else None
91
  downstream = roles[i - 1] if i - 1 >= 0 else None
92
-
93
- # USE THE CORRECT DELAY
94
- if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY # This is 1
95
  elif name == "Factory": shipping_weeks = 0
96
- else: shipping_weeks = SHIPPING_DELAY # This is 2
97
-
98
  st.session_state.game_state['echelons'][name] = {
99
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
100
  'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
@@ -127,31 +121,21 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
127
  st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
128
  return 4, f"API_ERROR: {e}"
129
 
130
- # =============== PROMPT FUNCTION (v3 - Sterman Heuristic + Demand Fix) ===============
131
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
132
- # This function's logic is updated for "human_like" to follow a flawed Sterman heuristic.
133
  e_state = echelon_state_decision_point
134
  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"
135
-
136
- # --- PROMPT FIX: Get correct demand (current, not future) ---
137
- current_stable_demand = get_customer_demand(week) # Use current week's demand
138
-
139
  if e_state['name'] == 'Factory':
140
  task_word = "production quantity"
141
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
142
  else:
143
  task_word = "order quantity"
144
  base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
145
-
146
- # --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
147
-
148
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
149
- stable_demand = current_stable_demand # Use the correct demand
150
- # --------------------- LT=3 FIX ---------------------
151
- if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME # 1
152
- elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY # 1+1+1 = 3
153
- else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY # 1+2 = 3
154
- # ----------------------------------------------------
155
  safety_stock = 4
156
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
157
  if e_state['name'] == 'Factory':
@@ -163,7 +147,6 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
163
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
164
  optimal_order = max(0, int(target_inventory_level - inventory_position))
165
  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."
166
-
167
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
168
  safety_stock = 4; anchor_demand = e_state['incoming_order']
169
  inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
@@ -177,82 +160,32 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
177
  calculated_order = anchor_demand + inventory_correction - supply_line
178
  rational_local_order = max(0, int(calculated_order))
179
  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."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
- # --- HUMAN-LIKE (DESCRIPTIVE) PROMPTS ---
182
- # (These are NEW and implement a flawed, panicky Sterman-style heuristic)
183
-
184
- else: # Catches both 'human_like' / 'local' and 'human_like' / 'full'
185
-
186
- # This is the flawed Sterman heuristic
187
- DESIRED_INVENTORY = 12 # Matches initial inventory
188
- anchor_demand = e_state['incoming_order']
189
- net_inventory = e_state['inventory'] - e_state['backlog']
190
- stock_correction = DESIRED_INVENTORY - net_inventory
191
- panicky_order = max(0, int(anchor_demand + stock_correction))
192
- panicky_order_calc = f"{anchor_demand} (Your Incoming Order) + {stock_correction} (Your Stock Correction)"
193
-
194
- # Get supply line info *just to show* the AI it's being ignored
195
- if e_state['name'] == 'Factory':
196
- supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
197
- supply_line_desc = "In Production"
198
- else:
199
- order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
200
- supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
201
- supply_line_desc = "Supply Line"
202
-
203
- if info_sharing == 'local':
204
- return f"""
205
- **You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
206
- You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
207
-
208
- {base_info}
209
-
210
- **Your Flawed 'Human' Heuristic:**
211
- Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
212
- A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
213
-
214
- **Your 'Panic' Calculation (Ignoring the Supply Line):**
215
- 1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
216
- 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.
217
- 3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
218
-
219
- **Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
220
- * Order = {panicky_order_calc} = **{panicky_order} units**.
221
-
222
- **Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
223
- """
224
-
225
- elif info_sharing == 'full':
226
- # Build the "Full Info" string just for context
227
- full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
228
- for name, other_e_state in all_echelons_state_decision_point.items():
229
- if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
230
-
231
- return f"""
232
- **You are a supply chain manager ({e_state['name']}) with full system visibility.**
233
- {base_info}
234
- {full_info_str}
235
-
236
- **A "Human-like" Flawed Decision:**
237
- Even though you have full information, you are judged by *your own* performance (your inventory, your backlog).
238
- You tend to react to your *local* situation (like the classic Sterman 1989 model) instead of using the complex full-system data.
239
- A 'rational' player would use the end-customer demand ({current_stable_demand}) and account for the *entire* system, but your gut-instinct is to panic about *your* numbers.
240
-
241
- **Your 'Panic' Calculation (Ignoring Full Info and Your Supply Line):**
242
- 1. **Anchor on *Your* Demand:** You just got an order for **{anchor_demand}** units. You react to this, not the end-customer demand.
243
- 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.
244
- 3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
245
-
246
- **Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
247
- * Order = {panicky_order_calc} = **{panicky_order} units**.
248
-
249
- **Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
250
- """
251
- # =========================================================
252
-
253
- # =============== STEP_GAME (v8) - Stable Logic + Correct Log Fix ===============
254
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
255
- # This version uses the stable v2 game logic AND the correct v5 logging fix
256
  state = st.session_state.game_state
257
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
258
  llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
@@ -263,54 +196,51 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
263
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
264
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
265
 
266
- # --- LOG FIX (v8): Capture UI-visible values BEFORE any pops ---
267
- arrived_this_week_LOG = {name: 0 for name in echelon_order}
268
- arriving_next_week_LOG = {name: 0 for name in echelon_order}
269
- factory_q = state['factory_production_pipeline']
270
 
271
- # Factory UI Values
 
272
  if factory_q:
273
- arrived_this_week_LOG["Factory"] = factory_q[0] # Arrives this week
274
- arriving_next_week_LOG["Factory"] = state['last_week_orders'].get("Distributor", 0) # Arrives next week
275
-
276
- # R, W, D UI Values
 
277
  for name in ["Retailer", "Wholesaler", "Distributor"]:
278
  shipment_q = echelons[name]['incoming_shipments']
279
  if shipment_q:
280
- arrived_this_week_LOG[name] = shipment_q[0] # Arrives this week
281
 
282
- # This logic MUST match the UI logic (v8)
283
  if name == 'Distributor':
284
- # "Next" for Distributor is what's in the factory *pipeline*
285
  if factory_q:
286
- arriving_next_week_LOG[name] = factory_q[0]
287
  elif name in ("Retailer", "Wholesaler"):
288
- # "Next" for R/W is the *second* item in their queue
289
- if len(shipment_q) > 1:
290
- arriving_next_week_LOG[name] = shipment_q[1]
291
- # --- END LOG FIX (v8) ---
292
-
293
 
294
- # === NOW, THE STABLE (v2) GAME LOGIC ===
295
- # This block is separate from the logging block above.
296
- # It uses its *own* variables to run the game.
297
- arrived_this_week_GAME = {name: 0 for name in echelon_order} # Use a fresh dict for game logic
298
  inventory_after_arrival = {}
299
  factory_state = echelons["Factory"]
300
  produced_units = 0
301
  if state['factory_production_pipeline']:
302
- produced_units = state['factory_production_pipeline'].popleft() # POP
303
- arrived_this_week_GAME["Factory"] = produced_units
304
  inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
305
 
306
  for name in ["Retailer", "Wholesaler", "Distributor"]:
307
  arrived_shipment = 0
308
  if echelons[name]['incoming_shipments']:
309
- arrived_shipment = echelons[name]['incoming_shipments'].popleft() # POP
310
- arrived_this_week_GAME[name] = arrived_shipment
311
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
312
- # === END STABLE (v2) GAME LOGIC ===
313
-
314
  total_backlog_before_shipping = {}
315
  for name in echelon_order:
316
  incoming_order_for_this_week = 0
@@ -325,7 +255,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
325
  decision_point_states[name] = {
326
  'name': name, 'inventory': inventory_after_arrival[name],
327
  'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
328
- 'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque()
329
  }
330
  current_week_orders = {}
331
  for name in echelon_order:
@@ -354,24 +284,22 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
354
  for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
355
  log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
356
 
357
- # --- LOG FIX (v8): Use captured values ---
358
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
359
  log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
360
- log_entry[f'{name}.arrived_this_week'] = arrived_this_week_LOG[name] # Use captured
361
 
362
  if name != 'Factory':
363
- log_entry[f'{name}.arriving_next_week'] = arriving_next_week_LOG[name] # Use captured
364
  else:
365
- log_entry[f'{name}.production_completing_next_week'] = arriving_next_week_LOG[name] # Use captured
366
- # --- END OF LOG FIX (v8) ---
367
 
368
  log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
369
  state['logs'].append(log_entry)
370
  state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
371
  state['current_ai_suggestion'] = None # Clean up
372
  if state['week'] > WEEKS: state['game_running'] = False
373
- # ==============================================================================
374
-
375
 
376
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
377
  # This function remains correct.
@@ -472,7 +400,7 @@ def show_leaderboard_ui():
472
  else:
473
  try:
474
  df = pd.DataFrame(leaderboard_data.values())
475
- if 'id' not in df.columns and not df.empty: df['id'] = list(leaderB_data.keys())
476
  if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
477
  st.error("Leaderboard data is corrupted or incomplete.")
478
  return
@@ -593,7 +521,7 @@ else:
593
  st.markdown("---")
594
  st.subheader("Supply Chain Status (Start of Week State)")
595
 
596
- # =============== MODIFIED UI LOGIC (v8) ===============
597
  if info_sharing == 'full':
598
  cols = st.columns(4)
599
  for i, name in enumerate(echelon_order):
@@ -608,7 +536,10 @@ else:
608
 
609
  st.metric("Inventory (Opening)", e['inventory'])
610
  st.metric("Backlog (Opening)", e['backlog'])
 
 
611
 
 
612
  current_incoming_order = 0
613
  if name == "Retailer":
614
  current_incoming_order = get_customer_demand(week)
@@ -619,20 +550,33 @@ else:
619
  st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
620
 
621
  if name == "Factory":
 
 
 
622
  prod_completing_next = state['last_week_orders'].get("Distributor", 0)
 
623
  st.write(f"Completing Next Week: **{prod_completing_next}**")
624
  else:
 
 
625
  arriving_next = 0
626
 
627
- # This logic matches the v8 Log Fix
628
  if name == 'Distributor':
629
- # "Next" for Distributor is what's in the factory *pipeline*
630
  if state['factory_production_pipeline']:
631
  arriving_next = list(state['factory_production_pipeline'])[0]
632
- elif name in ('Wholesaler', 'Retailer'):
633
- # "Next" for R/W is the *second* item in their queue
634
- q = e['incoming_shipments']
635
- if len(q) > 1: arriving_next = list(q)[1]
 
 
 
 
 
 
 
636
 
637
  st.write(f"Arriving Next Week: **{arriving_next}**")
638
 
@@ -654,14 +598,12 @@ else:
654
  st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
655
 
656
  with col3:
657
- # --------------------- LOCAL UI FIX V8 ---------------------
658
- # "Arriving Next Week" for Distributor in LOCAL mode.
659
- # "Cheating" to show the factory pipeline, so it's not 0.
 
660
  arriving_next = 0
661
- if state['factory_production_pipeline']:
662
- arriving_next = list(state['factory_production_pipeline'])[0]
663
  st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
664
- # -----------------------------------------------------------
665
 
666
  # =======================================================
667
 
@@ -669,6 +611,7 @@ else:
669
  st.header("Your Decision (Step 4)")
670
 
671
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
 
672
  all_decision_point_states = {}
673
  for name in echelon_order:
674
  e_curr = echelons[name] # This is END OF LAST WEEK state
@@ -687,7 +630,6 @@ else:
687
  inv_after_arrival = e_curr['inventory'] + arrived
688
  backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
689
 
690
- # This is the state used for the prompt, it's calculated BEFORE the pop
691
  all_decision_point_states[name] = {
692
  'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
693
  'incoming_order': inc_order_this_week,
 
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
 
35
  ORDER_PASSING_DELAY = 1 # Handled by last_week_orders
36
  SHIPPING_DELAY = 2 # General shipping delay (R->W, W->D)
37
  FACTORY_LEAD_TIME = 1
38
+ FACTORY_SHIPPING_DELAY = 1 # Specific delay from Factory to Distributor
 
 
 
39
  HOLDING_COST = 0.5
40
  BACKLOG_COST = 1.0
41
 
 
86
  for i, name in enumerate(roles):
87
  upstream = roles[i + 1] if i + 1 < len(roles) else None
88
  downstream = roles[i - 1] if i - 1 >= 0 else None
89
+ if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
 
 
90
  elif name == "Factory": shipping_weeks = 0
91
+ else: shipping_weeks = SHIPPING_DELAY
 
92
  st.session_state.game_state['echelons'][name] = {
93
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
94
  'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
 
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':
129
  task_word = "production quantity"
130
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
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
137
+ elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY
138
+ else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
 
 
139
  safety_stock = 4
140
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
141
  if e_state['name'] == 'Factory':
 
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']
 
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
 
255
  decision_point_states[name] = {
256
  'name': name, 'inventory': inventory_after_arrival[name],
257
  'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
258
+ 'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
259
  }
260
  current_week_orders = {}
261
  for name in echelon_order:
 
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.
 
400
  else:
401
  try:
402
  df = pd.DataFrame(leaderboard_data.values())
403
+ if 'id' not in df.columns and not df.empty: df['id'] = list(leaderboard_data.keys())
404
  if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
405
  st.error("Leaderboard data is corrupted or incomplete.")
406
  return
 
521
  st.markdown("---")
522
  st.subheader("Supply Chain Status (Start of Week State)")
523
 
524
+ # =============== MODIFIED UI LOGIC (v4.22) ===============
525
  if info_sharing == 'full':
526
  cols = st.columns(4)
527
  for i, name in enumerate(echelon_order):
 
536
 
537
  st.metric("Inventory (Opening)", e['inventory'])
538
  st.metric("Backlog (Opening)", e['backlog'])
539
+
540
+ # 移除成本显示
541
 
542
+ # --- NEW: Added Arriving This Week ---
543
  current_incoming_order = 0
544
  if name == "Retailer":
545
  current_incoming_order = get_customer_demand(week)
 
550
  st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
551
 
552
  if name == "Factory":
553
+ # FIX: 'Arriving This Week' (Completing This Week) removed from UI
554
+
555
+ # FIX: 'Next week' for Factory is the order it just received from Distributor
556
  prod_completing_next = state['last_week_orders'].get("Distributor", 0)
557
+
558
  st.write(f"Completing Next Week: **{prod_completing_next}**")
559
  else:
560
+ # FIX: 'Arriving This Week' removed from UI
561
+
562
  arriving_next = 0
563
 
564
+ # FIX: Logic to correctly calculate 'Arriving Next Week'
565
  if name == 'Distributor':
566
+ # 'Next week' for Distributor is what's in the factory pipeline
567
  if state['factory_production_pipeline']:
568
  arriving_next = list(state['factory_production_pipeline'])[0]
569
+
570
+ elif len(e['incoming_shipments']) > 1:
571
+ # R/W: q_len=2, 'next' is [1]
572
+ arriving_next = list(e['incoming_shipments'])[1]
573
+
574
+ elif len(e['incoming_shipments']) == 1 and name in ('Wholesaler', 'Retailer'):
575
+ # R/W: q_len=1, 'next' is [0] (as 'this' is 0)
576
+ arriving_next = list(e['incoming_shipments'])[0]
577
+
578
+ # (if q_len=0, arriving_next remains 0)
579
+ # (if q_len=1 and is Distributor, arriving_next remains 0, which is correct)
580
 
581
  st.write(f"Arriving Next Week: **{arriving_next}**")
582
 
 
598
  st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
599
 
600
  with col3:
601
+ # FIX: 'Arriving This Week' removed from UI per user request
602
+ # st.write(f"**Shipment Arriving (This Week):**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
603
+
604
+ # Arriving NEXT week (Distributor's local view CANNOT see factory pipeline)
605
  arriving_next = 0
 
 
606
  st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
 
607
 
608
  # =======================================================
609
 
 
611
  st.header("Your Decision (Step 4)")
612
 
613
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
614
+ # This logic remains correct and is NOT a UI element
615
  all_decision_point_states = {}
616
  for name in echelon_order:
617
  e_curr = echelons[name] # This is END OF LAST WEEK state
 
630
  inv_after_arrival = e_curr['inventory'] + arrived
631
  backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
632
 
 
633
  all_decision_point_states[name] = {
634
  'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
635
  'incoming_order': inc_order_this_week,