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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -94
app.py CHANGED
@@ -1,5 +1,5 @@
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,7 +35,8 @@ 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
- FACTORY_SHIPPING_DELAY = 1 # Specific delay from Factory to Distributor
 
39
  HOLDING_COST = 0.5
40
  BACKLOG_COST = 1.0
41
 
@@ -86,9 +87,9 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
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,21 +122,31 @@ 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
  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,6 +158,7 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
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,32 +172,82 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
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,51 +258,76 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
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,7 +342,7 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
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,22 +371,24 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
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.
@@ -521,7 +610,7 @@ else:
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,10 +625,7 @@ else:
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,33 +636,22 @@ else:
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,12 +673,15 @@ else:
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,7 +689,6 @@ else:
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,6 +707,7 @@ else:
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,
 
1
  # app.py
2
+ # @title Beer Game Final Version (v9 - Correct LT=3, Correct UI, Correct Log)
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
+ # This is CORRECT for LT=3 (1 pass + 1 produce + 1 ship = 3 week total LT)
39
+ FACTORY_SHIPPING_DELAY = 1
40
  HOLDING_COST = 0.5
41
  BACKLOG_COST = 1.0
42
 
 
87
  for i, name in enumerate(roles):
88
  upstream = roles[i + 1] if i + 1 < len(roles) else None
89
  downstream = roles[i - 1] if i - 1 >= 0 else None
90
+ if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY # This is 1
91
  elif name == "Factory": shipping_weeks = 0
92
+ else: shipping_weeks = SHIPPING_DELAY # This is 2
93
  st.session_state.game_state['echelons'][name] = {
94
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
95
  'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
 
122
  st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
123
  return 4, f"API_ERROR: {e}"
124
 
125
+ # =============== PROMPT FUNCTION (v3 - Sterman Heuristic + Demand Fix) ===============
126
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
127
+ # This function's logic is updated for "human_like" to follow a flawed Sterman heuristic.
128
  e_state = echelon_state_decision_point
129
  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"
130
+
131
+ # --- PROMPT FIX: Get correct demand (current, not future) ---
132
+ current_stable_demand = get_customer_demand(week) # Use current week's demand
133
+
134
  if e_state['name'] == 'Factory':
135
  task_word = "production quantity"
136
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
137
  else:
138
  task_word = "order quantity"
139
  base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
140
+
141
+ # --- PERFECT RATIONAL (NORMATIVE) PROMPTS ---
142
+
143
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
144
+ stable_demand = current_stable_demand # Use the correct demand
145
+ # --------------------- LT=3 (1+1+1) ---------------------
146
+ if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME # 1
147
+ elif e_state['name'] == 'Distributor': total_lead_time = ORDER_PASSING_DELAY + FACTORY_LEAD_TIME + FACTORY_SHIPPING_DELAY # 1+1+1 = 3
148
+ else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY # 1+2 = 3
149
+ # ----------------------------------------------------
150
  safety_stock = 4
151
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
152
  if e_state['name'] == 'Factory':
 
158
  inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
159
  optimal_order = max(0, int(target_inventory_level - inventory_position))
160
  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."
161
+
162
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
163
  safety_stock = 4; anchor_demand = e_state['incoming_order']
164
  inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
 
172
  calculated_order = anchor_demand + inventory_correction - supply_line
173
  rational_local_order = max(0, int(calculated_order))
174
  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."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
+ # --- HUMAN-LIKE (DESCRIPTIVE) PROMPTS ---
177
+ # (These are NEW and implement a flawed, panicky Sterman-style heuristic)
178
+
179
+ else: # Catches both 'human_like' / 'local' and 'human_like' / 'full'
180
+
181
+ # This is the flawed Sterman heuristic
182
+ DESIRED_INVENTORY = 12 # Matches initial inventory
183
+ anchor_demand = e_state['incoming_order']
184
+ net_inventory = e_state['inventory'] - e_state['backlog']
185
+ stock_correction = DESIRED_INVENTORY - net_inventory
186
+ panicky_order = max(0, int(anchor_demand + stock_correction))
187
+ panicky_order_calc = f"{anchor_demand} (Your Incoming Order) + {stock_correction} (Your Stock Correction)"
188
+
189
+ # Get supply line info *just to show* the AI it's being ignored
190
+ if e_state['name'] == 'Factory':
191
+ supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
192
+ supply_line_desc = "In Production"
193
+ else:
194
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
195
+ supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
196
+ supply_line_desc = "Supply Line"
197
+
198
+ if info_sharing == 'local':
199
+ return f"""
200
+ **You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.
201
+ You tend to make **reactive, 'gut-instinct' decisions** (like the classic Sterman 1989 model) that cause the Bullwhip Effect.
202
+
203
+ {base_info}
204
+
205
+ **Your Flawed 'Human' Heuristic:**
206
+ Your gut tells you to fix your entire inventory problem *right now*, and you're afraid of your backlog.
207
+ A 'rational' player would account for their {supply_line_desc} (which is {supply_line} units), but you're too busy panicking to trust that.
208
+
209
+ **Your 'Panic' Calculation (Ignoring the Supply Line):**
210
+ 1. **Anchor on Demand:** You just got an order for **{anchor_demand}** units. You'll order *at least* that.
211
+ 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.
212
+ 3. **Ignore Supply Line:** You'll ignore the **{supply_line} units** already in your pipeline.
213
+
214
+ **Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
215
+ * Order = {panicky_order_calc} = **{panicky_order} units**.
216
+
217
+ **Your Task:** Confirm this 'gut-instinct' {task_word}. Respond with a single integer.
218
+ """
219
+
220
+ elif info_sharing == 'full':
221
+ # Build the "Full Info" string just for context
222
+ full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
223
+ for name, other_e_state in all_echelons_state_decision_point.items():
224
+ if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
225
+
226
+ return f"""
227
+ **You are a supply chain manager ({e_state['name']}) with full system visibility.**
228
+ {base_info}
229
+ {full_info_str}
230
+
231
+ **A "Human-like" Flawed Decision:**
232
+ Even though you have full information, you are judged by *your own* performance (your inventory, your backlog).
233
+ You tend to react to your *local* situation (like the classic Sterman 1989 model) instead of using the complex full-system data.
234
+ 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.
235
+
236
+ **Your 'Panic' Calculation (Ignoring Full Info and Your Supply Line):**
237
+ 1. **Anchor on *Your* Demand:** You just got an order for **{anchor_demand}** units. You react to this, not the end-customer demand.
238
+ 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.
239
+ 3. **Ignore *Your* Supply Line:** You'll ignore the **{supply_line} units** in your own pipeline ({supply_line_desc}).
240
+
241
+ **Final Panic Order:** (Your Incoming Order) + (Your Stock Correction)
242
+ * Order = {panicky_order_calc} = **{panicky_order} units**.
243
+
244
+ **Your Task:** Confirm this 'gut-instinct', locally-focused {task_word}. Respond with a single integer.
245
+ """
246
+ # =========================================================
247
+
248
+ # =============== STEP_GAME (v9 - Stable Logic + Correct Log Fix) ===============
249
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
250
+ # This version uses the stable v2 game logic AND the correct v9 logging fix
251
  state = st.session_state.game_state
252
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
253
  llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
 
258
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
259
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
260
 
261
+ # --- LOG FIX (v9): Capture UI-visible values BEFORE any pops ---
262
+ arrived_this_week_LOG = {name: 0 for name in echelon_order}
263
+ arriving_next_week_LOG = {name: 0 for name in echelon_order}
 
 
 
264
  factory_q = state['factory_production_pipeline']
265
+
266
+ # Factory UI Values
267
  if factory_q:
268
+ arrived_this_week_LOG["Factory"] = factory_q[0] # Arrives this week
269
+ arriving_next_week_LOG["Factory"] = state['last_week_orders'].get("Distributor", 0) # Arrives next week
270
+
271
+ # R, W, D UI Values
 
272
  for name in ["Retailer", "Wholesaler", "Distributor"]:
273
  shipment_q = echelons[name]['incoming_shipments']
274
  if shipment_q:
275
+ arrived_this_week_LOG[name] = shipment_q[0] # Arrives this week (W+0)
276
 
277
+ # "Next Week" (W+1)
278
  if name == 'Distributor':
279
+ # "Next" for Distributor is what's in the factory *pipeline*
280
+ # This is the item that will arrive in W+2
281
+ # NO! "Next week" (W+1) is what is in shipping_q[0].
282
+ # "Next Next week" (W+2) is factory_q[0]
283
+ # The USER wants "Arriving Next Week" to mean W+1.
284
+ # With maxlen=1, the item for W+1 is NOT in the queue yet.
285
+ # The item for W+1 is what is in `factory_q`
286
+
287
+ # --- THIS IS THE REAL FIX V9 ---
288
+ # "Arriving Next Week" for Distributor (who has maxlen=1)
289
+ # is the item that will be SHIPPED this week, which is in the factory_q
290
  if factory_q:
291
+ arriving_next_week_LOG[name] = factory_q[0]
292
+ # This is what I had before, and it caused the "8" in the log.
293
+ # Let's re-read the user's trace:
294
+ # "W2 order 4 should... in W4 show arriving next week 4"
295
+ # W4: ANW=4. (Item for W5)
296
+ # Item for W5 is Order from W2.
297
+ # At start of W4:
298
+ # `factory_q` = [8] (Order from W3, for W6)
299
+ # `shipping_q` (Dist) = [4] (Order from W2, for W5)
300
+ # The user wants "Arriving Next Week" to be 4.
301
+ # This means `arriving_next_week` MUST read `shipping_q[0]`.
302
+
303
+ if shipment_q: # Read item for W+1
304
+ arriving_next_week_LOG[name] = shipment_q[0]
305
+
306
  elif name in ("Retailer", "Wholesaler"):
307
+ # "Next" for R/W is the *second* item in their queue (item for W+1)
308
+ if len(shipment_q) > 1:
309
+ arriving_next_week_LOG[name] = shipment_q[1]
310
+ # --- END LOG FIX (v9) ---
 
311
 
312
+
313
+ # === NOW, THE STABLE (v2) GAME LOGIC ===
314
+ arrived_this_week_GAME = {name: 0 for name in echelon_order}
315
  inventory_after_arrival = {}
316
  factory_state = echelons["Factory"]
317
  produced_units = 0
318
  if state['factory_production_pipeline']:
319
+ produced_units = state['factory_production_pipeline'].popleft() # POP
320
+ arrived_this_week_GAME["Factory"] = produced_units
321
  inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
322
 
323
  for name in ["Retailer", "Wholesaler", "Distributor"]:
324
  arrived_shipment = 0
325
  if echelons[name]['incoming_shipments']:
326
+ arrived_shipment = echelons[name]['incoming_shipments'].popleft() # POP
327
+ arrived_this_week_GAME[name] = arrived_shipment
328
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
329
+ # === END STABLE (v2) GAME LOGIC ===
330
+
331
  total_backlog_before_shipping = {}
332
  for name in echelon_order:
333
  incoming_order_for_this_week = 0
 
342
  decision_point_states[name] = {
343
  'name': name, 'inventory': inventory_after_arrival[name],
344
  'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
345
+ 'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque()
346
  }
347
  current_week_orders = {}
348
  for name in echelon_order:
 
371
  for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
372
  log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
373
 
374
+ # --- LOG FIX (v9): Use captured values ---
375
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
376
  log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
377
+ log_entry[f'{name}.arrived_this_week'] = arrived_this_week_LOG[name] # Use captured
378
 
379
  if name != 'Factory':
380
+ log_entry[f'{name}.arriving_next_week'] = arriving_next_week_LOG[name] # Use captured
381
  else:
382
+ log_entry[f'{name}.production_completing_next_week'] = arriving_next_week_LOG[name] # Use captured
383
+ # --- END OF LOG FIX (v9) ---
384
 
385
  log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
386
  state['logs'].append(log_entry)
387
  state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
388
  state['current_ai_suggestion'] = None # Clean up
389
  if state['week'] > WEEKS: state['game_running'] = False
390
+ # ==============================================================================
391
+
392
 
393
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
394
  # This function remains correct.
 
610
  st.markdown("---")
611
  st.subheader("Supply Chain Status (Start of Week State)")
612
 
613
+ # =============== MODIFIED UI LOGIC (v9) ===============
614
  if info_sharing == 'full':
615
  cols = st.columns(4)
616
  for i, name in enumerate(echelon_order):
 
625
 
626
  st.metric("Inventory (Opening)", e['inventory'])
627
  st.metric("Backlog (Opening)", e['backlog'])
 
 
628
 
 
629
  current_incoming_order = 0
630
  if name == "Retailer":
631
  current_incoming_order = get_customer_demand(week)
 
636
  st.write(f"Incoming Order (This Week): **{current_incoming_order}**")
637
 
638
  if name == "Factory":
 
 
 
639
  prod_completing_next = state['last_week_orders'].get("Distributor", 0)
 
640
  st.write(f"Completing Next Week: **{prod_completing_next}**")
641
  else:
 
 
642
  arriving_next = 0
643
 
644
+ # --- UI FIX V9 ---
645
+ # "Arriving Next Week" (W+1)
646
  if name == 'Distributor':
647
+ # Read W+1 item from its own shipping queue
648
+ q = e['incoming_shipments']
649
+ if q: arriving_next = list(q)[0]
650
+ elif name in ('Wholesaler', 'Retailer'):
651
+ # Read W+1 item from the second slot in queue
652
+ q = e['incoming_shipments']
653
+ if len(q) > 1: arriving_next = list(q)[1]
654
+ # --- END UI FIX V9 ---
 
 
 
 
 
 
655
 
656
  st.write(f"Arriving Next Week: **{arriving_next}**")
657
 
 
673
  st.write(f"**Incoming Order (This Week):**\n# {current_incoming_order}")
674
 
675
  with col3:
676
+ # --------------------- LOCAL UI FIX V9 ---------------------
677
+ # "Arriving Next Week" for Distributor in LOCAL mode.
678
+ # Read W+1 item from its own shipping queue
 
679
  arriving_next = 0
680
+ q = e['incoming_shipments']
681
+ if q:
682
+ arriving_next = list(q)[0]
683
  st.write(f"**Shipment Arriving (Next Week):**\n# {arriving_next}")
684
+ # -----------------------------------------------------------
685
 
686
  # =======================================================
687
 
 
689
  st.header("Your Decision (Step 4)")
690
 
691
  # Prepare the state snapshot for the AI prompt (State AFTER arrivals/orders, BEFORE shipping)
 
692
  all_decision_point_states = {}
693
  for name in echelon_order:
694
  e_curr = echelons[name] # This is END OF LAST WEEK state
 
707
  inv_after_arrival = e_curr['inventory'] + arrived
708
  backlog_after_new_order = e_curr['backlog'] + inc_order_this_week
709
 
710
+ # This is the state used for the prompt, it's calculated BEFORE the pop
711
  all_decision_point_states[name] = {
712
  'name': name, 'inventory': inv_after_arrival, 'backlog': backlog_after_new_order,
713
  'incoming_order': inc_order_this_week,