Lilli98 commited on
Commit
2dd72e3
·
verified ·
1 Parent(s): ecf8061

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -159
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # app.py
2
- # @title Beer Game Final Version (Manual Setting Selection)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
@@ -120,9 +120,9 @@ def init_game_state(llm_personality: str, info_sharing: str, participant_id: str
120
  for i, name in enumerate(roles):
121
  upstream = roles[i + 1] if i + 1 < len(roles) else None
122
  downstream = roles[i - 1] if i - 1 >= 0 else None
123
- if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY # This is 1
124
  elif name == "Factory": shipping_weeks = 0
125
- else: shipping_weeks = SHIPPING_DELAY # This is 2
126
  st.session_state.game_state['echelons'][name] = {
127
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
128
  'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
@@ -147,23 +147,23 @@ def get_llm_order_decision(prompt: str, echelon_name: str) -> (int, str):
147
  raw_text = response.choices[0].message.content.strip()
148
  match = re.search(r'\d+', raw_text)
149
  if match: return int(match.group(0)), raw_text
 
150
  return 4, raw_text
151
  except Exception as e:
152
- st.error(f"API call failed for {echelon_name}: {e}.")
153
  return 4, f"API_ERROR: {e}"
154
 
155
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
156
  e_state = echelon_state_decision_point
157
  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"
158
-
159
- current_stable_demand = get_customer_demand(week)
160
  if e_state['name'] == 'Factory':
161
  task_word = "production quantity"
162
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
163
  else:
164
  task_word = "order quantity"
165
  base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
166
-
 
167
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
168
  stable_demand = current_stable_demand
169
  if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
@@ -171,84 +171,70 @@ def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personalit
171
  else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
172
  safety_stock = 4
173
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
174
- order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
175
-
176
  if e_state['name'] == 'Factory':
177
- supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
178
- inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
179
- inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={supply_line})"
180
- elif e_state['name'] == 'Distributor':
181
- in_shipping = sum(e_state['incoming_shipments'])
182
- in_production = sum(st.session_state.game_state['factory_production_pipeline'])
183
- supply_line = in_shipping + in_production + order_in_transit_to_supplier
184
- inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
185
- inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={in_shipping} + InProd={in_production} + OrderToSupplier={order_in_transit_to_supplier})"
186
  else:
187
- in_shipping = sum(e_state['incoming_shipments'])
188
- supply_line = in_shipping + order_in_transit_to_supplier
189
- inventory_position = (e_state['inventory'] - e_state['backlog'] + supply_line)
190
- inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={in_shipping} + OrderToSupplier={order_in_transit_to_supplier})"
191
-
192
  optimal_order = max(0, int(target_inventory_level - inventory_position))
193
  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."
194
-
195
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
196
  safety_stock = 4; anchor_demand = e_state['incoming_order']
197
  inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
198
  if e_state['name'] == 'Factory':
199
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
200
  supply_line_desc = "In Production"
201
- elif e_state['name'] == 'Distributor':
202
- supply_line = sum(e_state['incoming_shipments'])
203
- supply_line_desc = "Supply Line (In Transit Shipments)"
204
  else:
205
- supply_line = sum(e_state['incoming_shipments'])
206
- supply_line_desc = "Supply Line (In Transit Shipments)"
207
-
208
  calculated_order = anchor_demand + inventory_correction - supply_line
209
  rational_local_order = max(0, int(calculated_order))
210
- 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 (that you can see). These should be subtracted from your new decision.\n\n**Final Calculation:**\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."
211
-
212
- else:
213
- DESIRED_INVENTORY = 12
214
- net_inventory = e_state['inventory'] - e_state['backlog']
215
- stock_correction = DESIRED_INVENTORY - net_inventory
216
- if e_state['name'] == 'Factory':
217
- supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
218
- supply_line_desc = "In Production"
219
- else:
220
- order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
221
- supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
222
- supply_line_desc = "Supply Line"
223
-
224
- if info_sharing == 'local':
225
- anchor_demand = e_state['incoming_order']
226
- panicky_order = max(0, int(anchor_demand + stock_correction))
227
- return f"""**You are a reactive supply chain manager for the {e_state['name']}.** You have a limited (local) view.\n{base_info}\n**Your 'Panic' Calculation:**\n1. Anchor on Demand ({anchor_demand} units).\n2. Correct for Stock (Need {stock_correction} more units).\n3. Ignore Supply Line ({supply_line} units).\n**Final Panic Order:** **{panicky_order} units**. Respond with a single integer."""
228
- elif info_sharing == 'full':
229
- local_anchor = e_state['incoming_order']
230
- global_anchor = current_stable_demand
231
- anchor_demand = int((local_anchor + global_anchor) / 2)
232
- panicky_order = max(0, int(anchor_demand + stock_correction))
233
- full_info_str = f"\n**Full Supply Chain Information:**\n- End-Customer Demand this week: {current_stable_demand} units.\n"
234
- for name, other_e_state in all_echelons_state_decision_point.items():
235
- if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
236
- return f"""**You are a supply chain manager ({e_state['name']}) with full system visibility.**\n{base_info}\n{full_info_str}\n**Your 'Panic' Calculation:**\n1. Anchor on Conflict (Average of local {local_anchor} and global {global_anchor} = {anchor_demand}).\n2. Correct for Stock (Need {stock_correction} more units).\n3. Ignore Supply Line.\n**Final Panic Order:** **{panicky_order} units**. Respond with a single integer."""
237
 
238
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
 
239
  state = st.session_state.game_state
240
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
241
  llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
242
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
243
  llm_raw_responses = {}
 
 
244
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
245
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
246
-
247
  arrived_this_week = {name: 0 for name in echelon_order}
248
  opening_arriving_next_week_UI_VALUE = {name: 0 for name in echelon_order}
249
 
 
250
  factory_q = state['factory_production_pipeline']
251
- if factory_q: arrived_this_week["Factory"] = factory_q[0]
 
252
  opening_arriving_next_week_UI_VALUE["Factory"] = state['last_week_orders'].get("Distributor", 0)
253
 
254
  for name in ["Retailer", "Wholesaler", "Distributor"]:
@@ -261,62 +247,74 @@ def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: i
261
  opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
262
 
263
  inventory_after_arrival = {}
264
- produced_units = state['factory_production_pipeline'].popleft() if state['factory_production_pipeline'] else 0
265
- inventory_after_arrival["Factory"] = echelons["Factory"]['inventory'] + produced_units
266
-
 
 
 
267
  for name in ["Retailer", "Wholesaler", "Distributor"]:
268
  arrived_shipment = arrived_this_week[name]
269
- if echelons[name]['incoming_shipments']: echelons[name]['incoming_shipments'].popleft()
 
270
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
271
 
272
  total_backlog_before_shipping = {}
273
  for name in echelon_order:
274
- incoming_order_for_this_week = get_customer_demand(week) if name == "Retailer" else state['last_week_orders'].get(echelons[name]['downstream_name'], 0)
 
 
 
 
275
  echelons[name]['incoming_order'] = incoming_order_for_this_week
276
  total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
277
-
278
  decision_point_states = {}
279
  for name in echelon_order:
280
- decision_point_states[name] = {
281
- 'name': name, 'inventory': inventory_after_arrival[name],
282
- 'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
283
- 'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
284
- }
285
 
286
  current_week_orders = {}
287
  for name in echelon_order:
 
288
  if name == human_role: order_amount, raw_resp = human_final_order, "HUMAN_FINAL_INPUT"
289
  else:
290
- prompt = get_llm_prompt(decision_point_states[name], week, llm_personality, info_sharing, decision_point_states)
291
  order_amount, raw_resp = get_llm_order_decision(prompt, name)
292
- llm_raw_responses[name] = raw_resp; echelons[name]['order_placed'] = max(0, order_amount); current_week_orders[name] = echelons[name]['order_placed']
293
-
294
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
295
  units_shipped = {name: 0 for name in echelon_order}
296
  for name in echelon_order:
297
- demand = total_backlog_before_shipping[name]; avail = inventory_after_arrival[name]
298
- echelons[name]['shipment_sent'] = min(avail, demand); units_shipped[name] = echelons[name]['shipment_sent']
299
- echelons[name]['inventory'] = avail - units_shipped[name]; echelons[name]['backlog'] = demand - units_shipped[name]
300
-
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
-
305
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
306
  del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
 
 
307
  for name in echelon_order:
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}.opening_inventory'] = opening_inventories[name]
311
  log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
312
  log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
313
  if name != 'Factory': log_entry[f'{name}.arriving_next_week'] = opening_arriving_next_week_UI_VALUE[name]
314
  else: log_entry[f'{name}.production_completing_next_week'] = opening_arriving_next_week_UI_VALUE[name]
315
-
316
  log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
317
  state['logs'].append(log_entry)
318
  state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
319
- state['current_ai_suggestion'] = None
320
  if state['week'] > WEEKS: state['game_running'] = False
321
 
322
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
@@ -333,15 +331,19 @@ def plot_results(df: pd.DataFrame, title: str, human_role: str):
333
  inventory_pivot = plot_df.pivot(index='week', columns='echelon', values='inventory').reindex(columns=echelons)
334
  inventory_pivot.plot(ax=axes[0], kind='line', marker='o', markersize=4); axes[0].set_title('Inventory Levels (End of Week)'); axes[0].grid(True, linestyle='--'); axes[0].set_ylabel('Stock (Units)')
335
  order_pivot = plot_df.pivot(index='week', columns='echelon', values='order_placed').reindex(columns=echelons)
336
- order_pivot.plot(ax=axes[1], style='--'); axes[1].plot(range(1, WEEKS + 1), [get_customer_demand(w) for w in range(1, WEEKS + 1)], label='Customer Demand', color='black', lw=2.5); axes[1].set_title('Order Quantities / Production Decisions'); axes[1].grid(True, linestyle='--'); axes[1].legend(); axes[1].set_ylabel('Ordered/Produced (Units)')
337
- total_costs = plot_df.loc[plot_df.groupby('echelon')['week'].idxmax()].set_index('echelon')['total_cost'].reindex(echelons, fill_value=0)
 
338
  total_costs.plot(kind='bar', ax=axes[2], rot=0); axes[2].set_title('Total Cumulative Cost'); axes[2].set_ylabel('Cost ($)')
339
  human_cols = [f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed']
340
  human_df_cols = ['week'] + [col for col in human_cols if col in df.columns]
341
  try:
342
- human_df = df[human_df_cols].copy().rename(columns={f'{human_role}.initial_order': 'Your Initial Order', f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order'})
343
- human_df.plot(x='week', ax=axes[3], marker='o', linestyle='-'); axes[3].set_title(f'Analysis of Your ({human_role}) Decisions'); axes[3].set_ylabel('Order Quantity'); axes[3].grid(True, linestyle='--'); axes[3].set_xlabel('Week')
344
- except: axes[3].text(0.5, 0.5, "No human decision data", ha='center', va='center')
 
 
 
345
  plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
346
 
347
  @st.cache_data(ttl=60)
@@ -350,20 +352,27 @@ def load_leaderboard_data():
350
  try:
351
  local_path = hf_hub_download(repo_id=HF_REPO_ID, repo_type="dataset", filename=LEADERBOARD_FILE, token=HF_TOKEN, cache_dir=LOCAL_LOG_DIR / "hf_cache")
352
  with open(local_path, 'r', encoding='utf-8') as f: return json.load(f)
353
- except: return {}
 
 
 
 
354
 
355
  def save_leaderboard_data(data):
356
  if not hf_api or not HF_REPO_ID or not HF_TOKEN: return
357
  try:
358
  local_path = LOCAL_LOG_DIR / LEADERBOARD_FILE
359
  with open(local_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False)
360
- hf_api.upload_file(path_or_fileobj=str(local_path), path_in_repo=LEADERBOARD_FILE, repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN)
361
  st.cache_data.clear()
362
- except: pass
 
363
 
364
  def display_rankings(df, top_n=200):
365
- if df.empty: return
366
- df['distributor_cost'] = pd.to_numeric(df.get('total_cost'), errors='coerce')
 
 
367
  df['total_chain_cost'] = pd.to_numeric(df.get('total_chain_cost'), errors='coerce')
368
  df['order_std_dev'] = pd.to_numeric(df.get('order_std_dev'), errors='coerce')
369
  c1, c2, c3 = st.columns(3)
@@ -372,56 +381,97 @@ def display_rankings(df, top_n=200):
372
  champs_df = df.dropna(subset=['total_chain_cost']).sort_values('total_chain_cost', ascending=True).head(top_n).copy()
373
  if not champs_df.empty:
374
  champs_df['total_chain_cost'] = champs_df['total_chain_cost'].map('${:,.2f}'.format)
375
- st.dataframe(champs_df[['id', 'total_chain_cost']], use_container_width=True, hide_index=True)
 
376
  with c2:
377
  st.subheader("👤 Distributor Champions")
378
  dist_df = df.dropna(subset=['distributor_cost']).sort_values('distributor_cost', ascending=True).head(top_n).copy()
379
  if not dist_df.empty:
380
  dist_df['distributor_cost'] = dist_df['distributor_cost'].map('${:,.2f}'.format)
381
- st.dataframe(dist_df[['id', 'distributor_cost']], use_container_width=True, hide_index=True)
 
382
  with c3:
383
  st.subheader("🧘 Mr. Smooth")
384
  smooth_df = df.dropna(subset=['order_std_dev']).sort_values('order_std_dev', ascending=True).head(top_n).copy()
385
  if not smooth_df.empty:
386
  smooth_df['order_std_dev'] = smooth_df['order_std_dev'].map('{:,.2f}'.format)
387
- st.dataframe(smooth_df[['id', 'order_std_dev']], use_container_width=True, hide_index=True)
 
388
 
389
  def show_leaderboard_ui():
390
  st.markdown("---")
391
  st.header("📊 The Bullwhip Leaderboard")
392
  leaderboard_data = load_leaderboard_data()
393
- if leaderboard_data:
394
- df = pd.DataFrame(leaderboard_data.values())
395
- if 'id' not in df.columns: df['id'] = list(leaderboard_data.keys())
396
- groups = sorted(df.setting.unique())
397
- tabs = st.tabs(["**Overall**"] + groups)
398
- with tabs[0]: display_rankings(df)
399
- for i, group_name in enumerate(groups):
400
- with tabs[i+1]: display_rankings(df[df.setting == group_name].copy())
 
 
 
 
 
 
 
 
 
 
401
 
402
  def save_logs_and_upload(state: dict):
403
- if not state.get('logs'): return
 
 
404
  participant_id = state['participant_id']
 
405
  try:
406
  logs_df = pd.json_normalize(state['logs'])
407
- fname = LOCAL_LOG_DIR / f"log_{participant_id}_{int(time.time())}.csv"
 
408
  logs_df['experiment_end_timestamp'] = datetime.utcnow().isoformat() + "Z"
409
- logs_df['consent_given_timestamp'] = st.session_state.get('consent_timestamp', "N/A")
 
 
 
 
410
  logs_df.to_csv(fname, index=False)
411
- st.download_button("📥 Download Log CSV", data=open(fname, "rb"), file_name=fname.name, mime="text/csv")
 
412
  if HF_TOKEN and HF_REPO_ID and hf_api:
413
- hf_api.upload_file(path_or_fileobj=str(fname), path_in_repo=f"logs/{fname.name}", repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN)
414
- except: return
 
 
 
 
 
 
 
415
  try:
416
  human_role = state['human_role']
417
- dist_cost = logs_df[f'{human_role}.total_cost'].iloc[-1]
418
- total_chain_cost = sum(logs_df[f'{e}.total_cost'].iloc[-1] for e in ["Retailer", "Wholesaler", "Distributor", "Factory"])
 
 
 
419
  order_std_dev = logs_df[f'{human_role}.order_placed'].std()
420
- new_entry = {'id': participant_id, 'setting': f"{state['llm_personality']} / {state['info_sharing']}", 'total_cost': float(dist_cost), 'total_chain_cost': float(total_chain_cost), 'order_std_dev': float(order_std_dev) if pd.notna(order_std_dev) else 0.0, 'start_timestamp': state.get('start_timestamp'), 'consent_timestamp': st.session_state.get('consent_timestamp')}
 
 
 
 
 
 
 
 
421
  leaderboard_data = load_leaderboard_data()
422
- leaderboard_data[participant_id] = new_entry
423
  save_leaderboard_data(leaderboard_data)
424
- except: pass
 
425
 
426
  # -----------------------------------------------------------------------------
427
  # 4. Streamlit UI
@@ -435,14 +485,13 @@ if 'comprehension_passed' not in st.session_state: st.session_state['comprehensi
435
 
436
  if st.session_state.get('initialization_error'):
437
  st.error(st.session_state.initialization_error)
438
-
439
  elif not st.session_state['consent_given']:
440
  st.header("📝 Participant Consent Form")
441
- st.markdown("... (Consent Text) ...")
442
  with st.form("consent_form"):
443
- choice = st.radio("**Do you agree to take part?**", ('Yes', 'No'), index=None)
444
  if st.form_submit_button("Continue"):
445
- if choice == 'Yes':
446
  st.session_state['consent_given'] = True
447
  st.session_state['consent_timestamp'] = datetime.utcnow().isoformat() + "Z"
448
  st.rerun()
@@ -450,29 +499,41 @@ elif not st.session_state['consent_given']:
450
 
451
  elif not st.session_state['comprehension_passed']:
452
  st.header("🧠 Comprehension Check")
453
- with st.form("quiz"):
454
- correct = True
455
- for i, q in enumerate(COMPRE_QUESTIONS := COMPREHENSION_QUESTIONS):
456
- ans = st.radio(q['q'], q['options'], index=None)
457
- if ans != q['options'][q['correct_index']]: correct = False
458
- if st.form_submit_button("Submit"):
459
- if correct: st.session_state['comprehension_passed'] = True; st.rerun()
 
 
 
 
460
  else: st.error("Incorrect answers.")
461
 
462
  else:
463
- is_game_over = st.session_state.get('game_state') and not st.session_state.game_state.get('game_running') and st.session_state.game_state.get('week', 0) > WEEKS
 
 
 
464
  if is_game_over:
465
  st.header("🎉 Game Over!")
466
  state = st.session_state.game_state
467
- url = f"{QUALTRICS_BASE_URL}?{PID_FIELD_NAME}={state['participant_id']}"
468
- st.info(f"ID: **{state['participant_id']}**. [Complete Survey]({url})")
469
- save_logs_and_upload(state)
470
- if st.button("✨ Start New Game"):
 
 
 
 
 
471
  for k in ['consent_timestamp', 'consent_given', 'comprehension_passed', 'game_state']:
472
  if k in st.session_state: del st.session_state[k]
473
  st.rerun()
474
 
475
- elif st.session_state.get('game_state', {}).get('game_running'):
476
  state = st.session_state.game_state
477
  week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
478
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
@@ -483,8 +544,9 @@ else:
483
  for i, name in enumerate(echelon_order):
484
  with cols[i]:
485
  e = echelons[name]
486
- label = f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px;'>{'👤' if name==human_role else '🤖'} {name} {'(You)' if name==human_role else ''}</span>**" if name==human_role else f"##### {'🤖'} {name}"
487
- st.markdown(label, unsafe_allow_html=True)
 
488
  st.metric("Inventory", e['inventory']); st.metric("Backlog", e['backlog'])
489
  st.write(f"Incoming Order: **{e['incoming_order']}**")
490
  if name == "Factory": st.write(f"Completing Next: **{state['last_week_orders'].get('Distributor', 0)}**")
@@ -493,54 +555,52 @@ else:
493
  e = echelons[human_role]
494
  st.markdown(f"### <span style='color:#FF4B4B;'>👤 {human_role} (Your Dashboard)</span>", unsafe_allow_html=True)
495
  c1, c2, c3 = st.columns(3)
496
- c1.metric("Inventory", e['inventory']); c1.metric("Backlog", e['backlog'])
497
- c2.write(f"**Incoming Order:**\n# {e['incoming_order']}")
498
- c3.write(f"**Arriving Next:**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
499
 
500
  st.markdown("---")
501
- # Decision Step logic re-integrated correctly
502
  if state['decision_step'] == 'initial_order':
503
- with st.form("init_form"):
504
- val = st.number_input("Initial Order:", min_value=0, step=1, value=None)
505
- if st.form_submit_button("Next"):
506
- state['human_initial_order'] = int(val) if val is not None else 0
507
  state['decision_step'] = 'final_order'
508
- snap = {n: {'name': n, 'inventory': echelons[n]['inventory'], 'backlog': echelons[n]['backlog'], 'incoming_order': echelons[n]['incoming_order']} for n in echelon_order}
509
- state['current_ai_suggestion'], _ = get_llm_order_decision(get_llm_prompt(snap[human_role], week, state['llm_personality'], info_sharing, snap), human_role)
 
 
510
  st.rerun()
511
  else:
512
- with st.form("final_form"):
513
- st.write(f"AI Suggests: **{state['current_ai_suggestion']}**")
514
- val = st.number_input("Final Order:", min_value=0, step=1, key="final_order_input", value=None)
515
- if st.form_submit_button("Submit"):
516
- step_game(int(val) if val is not None else 0, state['human_initial_order'], state['current_ai_suggestion'])
 
517
  st.rerun()
518
 
519
- st.sidebar.image(IMAGE_PATH, use_column_width=True) if Path(IMAGE_PATH).exists() else None
520
- if st.sidebar.button("🔄 Reset"):
521
- if 'game_state' in st.session_state: del st.session_state.game_state
522
- st.rerun()
523
-
524
  else:
525
  st.header("⚙️ Game Configuration")
526
- pid = st.text_input("Name/Team ID:", key="pid_input")
527
 
528
- # --- MODIFIED: Manual Setting Selection ---
529
  c1, c2 = st.columns(2)
530
  with c1:
531
- llm_p = st.selectbox("AI Personality", ('human_like', 'perfect_rational'), format_func=lambda x: x.replace('_', ' ').title())
532
  with c2:
533
- info_s = st.selectbox("Information Sharing", ('local', 'full'), format_func=lambda x: x.title())
534
 
535
  if st.button("🚀 Start Game", type="primary"):
536
- if pid:
537
- init_game_state(llm_p, info_s, pid)
538
  st.rerun()
539
- else: st.error("Enter ID.")
540
  show_leaderboard_ui()
541
 
542
  # --- Instructor Zone ---
543
  st.sidebar.markdown("---")
544
  with st.sidebar.expander("🔐 Instructor Zone"):
545
  if st.text_input("Admin Password:", type="password") == ADMIN_PASSWORD:
546
- if st.checkbox("Show Leaderboard"): show_leaderboard_ui()
 
1
  # app.py
2
+ # @title Beer Game Final Version (Verbatim Restore with Manual Settings)
3
 
4
  # -----------------------------------------------------------------------------
5
  # 1. Import Libraries
 
120
  for i, name in enumerate(roles):
121
  upstream = roles[i + 1] if i + 1 < len(roles) else None
122
  downstream = roles[i - 1] if i - 1 >= 0 else None
123
+ if name == "Distributor": shipping_weeks = FACTORY_SHIPPING_DELAY
124
  elif name == "Factory": shipping_weeks = 0
125
+ else: shipping_weeks = SHIPPING_DELAY
126
  st.session_state.game_state['echelons'][name] = {
127
  'name': name, 'inventory': INITIAL_INVENTORY, 'backlog': INITIAL_BACKLOG,
128
  'incoming_shipments': deque([0] * shipping_weeks, maxlen=shipping_weeks),
 
147
  raw_text = response.choices[0].message.content.strip()
148
  match = re.search(r'\d+', raw_text)
149
  if match: return int(match.group(0)), raw_text
150
+ st.warning(f"LLM for {echelon_name} did not return a valid number. Defaulting to 4. Raw Response: '{raw_text}'")
151
  return 4, raw_text
152
  except Exception as e:
153
+ st.error(f"API call failed for {echelon_name}: {e}. Defaulting to 4.")
154
  return 4, f"API_ERROR: {e}"
155
 
156
  def get_llm_prompt(echelon_state_decision_point: dict, week: int, llm_personality: str, info_sharing: str, all_echelons_state_decision_point: dict) -> str:
157
  e_state = echelon_state_decision_point
158
  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"
 
 
159
  if e_state['name'] == 'Factory':
160
  task_word = "production quantity"
161
  base_info += f"- Your Production Pipeline (completing next week onwards): {list(st.session_state.game_state['factory_production_pipeline'])}"
162
  else:
163
  task_word = "order quantity"
164
  base_info += f"- Shipments In Transit To You (arriving next week onwards): {list(e_state['incoming_shipments'])}"
165
+
166
+ current_stable_demand = get_customer_demand(week)
167
  if llm_personality == 'perfect_rational' and info_sharing == 'full':
168
  stable_demand = current_stable_demand
169
  if e_state['name'] == 'Factory': total_lead_time = FACTORY_LEAD_TIME
 
171
  else: total_lead_time = ORDER_PASSING_DELAY + SHIPPING_DELAY
172
  safety_stock = 4
173
  target_inventory_level = (stable_demand * total_lead_time) + safety_stock
 
 
174
  if e_state['name'] == 'Factory':
175
+ inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(st.session_state.game_state['factory_production_pipeline']))
176
+ inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InProd={sum(st.session_state.game_state['factory_production_pipeline'])})"
 
 
 
 
 
 
 
177
  else:
178
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
179
+ inventory_position = (e_state['inventory'] - e_state['backlog'] + sum(e_state['incoming_shipments']) + order_in_transit_to_supplier)
180
+ inv_pos_components = f"(Inv={e_state['inventory']} - Backlog={e_state['backlog']} + InTransitShip={sum(e_state['incoming_shipments'])} + OrderToSupplier={order_in_transit_to_supplier})"
 
 
181
  optimal_order = max(0, int(target_inventory_level - inventory_position))
182
  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."
 
183
  elif llm_personality == 'perfect_rational' and info_sharing == 'local':
184
  safety_stock = 4; anchor_demand = e_state['incoming_order']
185
  inventory_correction = safety_stock - (e_state['inventory'] - e_state['backlog'])
186
  if e_state['name'] == 'Factory':
187
  supply_line = sum(st.session_state.game_state['factory_production_pipeline'])
188
  supply_line_desc = "In Production"
 
 
 
189
  else:
190
+ order_in_transit_to_supplier = st.session_state.game_state['last_week_orders'].get(e_state['name'], 0)
191
+ supply_line = sum(e_state['incoming_shipments']) + order_in_transit_to_supplier
192
+ supply_line_desc = "Supply Line (In Transit Shipments + Order To Supplier)"
193
  calculated_order = anchor_demand + inventory_correction - supply_line
194
  rational_local_order = max(0, int(calculated_order))
195
+ 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_correction} - {supply_line} = **{rational_local_order} units**.\n**Your Task:** Confirm this locally rational {task_word}. Respond with a single integer."
196
+ elif llm_personality == 'human_like' and info_sharing == 'full':
197
+ full_info_str = f"\n**Full Supply Chain Information (State Before Shipping):**\n- End-Customer Demand this week: {get_customer_demand(week)} units.\n"
198
+ for name, other_e_state in all_echelons_state_decision_point.items():
199
+ if name != e_state['name']: full_info_str += f"- {name}: Inv={other_e_state['inventory']}, Backlog={other_e_state['backlog']}\n"
200
+ return f"""
201
+ **You are a supply chain manager ({e_state['name']}) with full system visibility.**
202
+ You can see everyone's current inventory and backlog before shipping, and the real customer demand.
203
+ {base_info}
204
+ {full_info_str}
205
+ **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']}.
206
+ 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.
207
+ You are still human and might get anxious about your own stock levels.
208
+ What {task_word} should you decide on this week? Respond with a single integer.
209
+ """
210
+ elif llm_personality == 'human_like' and info_sharing == 'local':
211
+ return f"""
212
+ **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.
213
+ Your top priority is to NOT have a backlog.
214
+ {base_info}
215
+ **Your Task:** You just received an incoming order for **{e_state['incoming_order']}** units, adding to your total backlog.
216
+ 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.
217
+ **React emotionally.** What is your knee-jerk {task_word}? Respond with a single integer.
218
+ """
 
 
 
219
 
220
  def step_game(human_final_order: int, human_initial_order: int, ai_suggestion: int):
221
+ # This is the correct logic from v4.17
222
  state = st.session_state.game_state
223
  week, echelons, human_role = state['week'], state['echelons'], state['human_role']
224
  llm_personality, info_sharing = state['llm_personality'], state['info_sharing']
225
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
226
  llm_raw_responses = {}
227
+
228
+ # Capture opening state for logging
229
  opening_inventories = {name: e['inventory'] for name, e in echelons.items()}
230
  opening_backlogs = {name: e['backlog'] for name, e in echelons.items()}
 
231
  arrived_this_week = {name: 0 for name in echelon_order}
232
  opening_arriving_next_week_UI_VALUE = {name: 0 for name in echelon_order}
233
 
234
+ # Logic from v4.17
235
  factory_q = state['factory_production_pipeline']
236
+ if factory_q:
237
+ arrived_this_week["Factory"] = factory_q[0]
238
  opening_arriving_next_week_UI_VALUE["Factory"] = state['last_week_orders'].get("Distributor", 0)
239
 
240
  for name in ["Retailer", "Wholesaler", "Distributor"]:
 
247
  opening_arriving_next_week_UI_VALUE[name] = shipment_q[0]
248
 
249
  inventory_after_arrival = {}
250
+ factory_state = echelons["Factory"]
251
+ produced_units = 0
252
+ if state['factory_production_pipeline']:
253
+ produced_units = state['factory_production_pipeline'].popleft()
254
+ inventory_after_arrival["Factory"] = factory_state['inventory'] + produced_units
255
+
256
  for name in ["Retailer", "Wholesaler", "Distributor"]:
257
  arrived_shipment = arrived_this_week[name]
258
+ if echelons[name]['incoming_shipments']:
259
+ echelons[name]['incoming_shipments'].popleft()
260
  inventory_after_arrival[name] = echelons[name]['inventory'] + arrived_shipment
261
 
262
  total_backlog_before_shipping = {}
263
  for name in echelon_order:
264
+ incoming_order_for_this_week = 0
265
+ if name == "Retailer": incoming_order_for_this_week = get_customer_demand(week)
266
+ else:
267
+ downstream_name = echelons[name]['downstream_name']
268
+ if downstream_name: incoming_order_for_this_week = state['last_week_orders'].get(downstream_name, 0)
269
  echelons[name]['incoming_order'] = incoming_order_for_this_week
270
  total_backlog_before_shipping[name] = echelons[name]['backlog'] + incoming_order_for_this_week
271
+
272
  decision_point_states = {}
273
  for name in echelon_order:
274
+ decision_point_states[name] = {
275
+ 'name': name, 'inventory': inventory_after_arrival[name],
276
+ 'backlog': total_backlog_before_shipping[name], 'incoming_order': echelons[name]['incoming_order'],
277
+ 'incoming_shipments': echelons[name]['incoming_shipments'].copy() if name != "Factory" else deque(),
278
+ }
279
 
280
  current_week_orders = {}
281
  for name in echelon_order:
282
+ e = echelons[name]; prompt_state = decision_point_states[name]
283
  if name == human_role: order_amount, raw_resp = human_final_order, "HUMAN_FINAL_INPUT"
284
  else:
285
+ prompt = get_llm_prompt(prompt_state, week, llm_personality, info_sharing, decision_point_states)
286
  order_amount, raw_resp = get_llm_order_decision(prompt, name)
287
+ llm_raw_responses[name] = raw_resp; e['order_placed'] = max(0, order_amount); current_week_orders[name] = e['order_placed']
288
+
289
  state['factory_production_pipeline'].append(echelons["Factory"]['order_placed'])
290
  units_shipped = {name: 0 for name in echelon_order}
291
  for name in echelon_order:
292
+ e = echelons[name]; demand_to_meet = total_backlog_before_shipping[name]; available_inv = inventory_after_arrival[name]
293
+ e['shipment_sent'] = min(available_inv, demand_to_meet); units_shipped[name] = e['shipment_sent']
294
+ e['inventory'] = available_inv - e['shipment_sent']; e['backlog'] = demand_to_meet - e['shipment_sent']
295
+
296
  if units_shipped["Factory"] > 0: echelons['Distributor']['incoming_shipments'].append(units_shipped["Factory"])
297
  if units_shipped['Distributor'] > 0: echelons['Wholesaler']['incoming_shipments'].append(units_shipped['Distributor'])
298
  if units_shipped['Wholesaler'] > 0: echelons['Retailer']['incoming_shipments'].append(units_shipped['Wholesaler'])
299
+
300
  log_entry = {'timestamp': datetime.utcnow().isoformat() + "Z", 'week': week, **state}
301
  del log_entry['echelons'], log_entry['factory_production_pipeline'], log_entry['logs'], log_entry['last_week_orders']
302
+ if 'current_ai_suggestion' in log_entry: del log_entry['current_ai_suggestion']
303
+
304
  for name in echelon_order:
305
  e = echelons[name]; e['weekly_cost'] = (e['inventory'] * HOLDING_COST) + (e['backlog'] * BACKLOG_COST); e['total_cost'] += e['weekly_cost']
306
  for key in ['inventory', 'backlog', 'incoming_order', 'order_placed', 'shipment_sent', 'weekly_cost', 'total_cost']: log_entry[f'{name}.{key}'] = e[key]
307
+ log_entry[f'{name}.llm_raw_response'] = llm_raw_responses.get(name, "")
308
  log_entry[f'{name}.opening_inventory'] = opening_inventories[name]
309
  log_entry[f'{name}.opening_backlog'] = opening_backlogs[name]
310
  log_entry[f'{name}.arrived_this_week'] = arrived_this_week[name]
311
  if name != 'Factory': log_entry[f'{name}.arriving_next_week'] = opening_arriving_next_week_UI_VALUE[name]
312
  else: log_entry[f'{name}.production_completing_next_week'] = opening_arriving_next_week_UI_VALUE[name]
313
+
314
  log_entry[f'{human_role}.initial_order'] = human_initial_order; log_entry[f'{human_role}.ai_suggestion'] = ai_suggestion
315
  state['logs'].append(log_entry)
316
  state['week'] += 1; state['decision_step'] = 'initial_order'; state['last_week_orders'] = current_week_orders
317
+ state['current_ai_suggestion'] = None # Clean up
318
  if state['week'] > WEEKS: state['game_running'] = False
319
 
320
  def plot_results(df: pd.DataFrame, title: str, human_role: str):
 
331
  inventory_pivot = plot_df.pivot(index='week', columns='echelon', values='inventory').reindex(columns=echelons)
332
  inventory_pivot.plot(ax=axes[0], kind='line', marker='o', markersize=4); axes[0].set_title('Inventory Levels (End of Week)'); axes[0].grid(True, linestyle='--'); axes[0].set_ylabel('Stock (Units)')
333
  order_pivot = plot_df.pivot(index='week', columns='echelon', values='order_placed').reindex(columns=echelons)
334
+ order_pivot.plot(ax=axes[1], style='--'); axes[1].plot(range(1, WEEKS + 1), [get_customer_demand(week) for week in range(1, WEEKS + 1)], label='Customer Demand', color='black', lw=2.5); axes[1].set_title('Order Quantities / Production Decisions'); axes[1].grid(True, linestyle='--'); axes[1].legend(); axes[1].set_ylabel('Ordered/Produced (Units)')
335
+ total_costs = plot_df.loc[plot_df.groupby('echelon')['week'].idxmax()]
336
+ total_costs = total_costs.set_index('echelon')['total_cost'].reindex(echelons, fill_value=0)
337
  total_costs.plot(kind='bar', ax=axes[2], rot=0); axes[2].set_title('Total Cumulative Cost'); axes[2].set_ylabel('Cost ($)')
338
  human_cols = [f'{human_role}.initial_order', f'{human_role}.ai_suggestion', f'{human_role}.order_placed']
339
  human_df_cols = ['week'] + [col for col in human_cols if col in df.columns]
340
  try:
341
+ human_df = df[human_df_cols].copy()
342
+ human_df.rename(columns={ f'{human_role}.initial_order': 'Your Initial Order', f'{human_role}.ai_suggestion': 'AI Suggestion', f'{human_role}.order_placed': 'Your Final Order'}, inplace=True)
343
+ if len(human_df.columns) > 1: human_df.plot(x='week', ax=axes[3], marker='o', linestyle='-'); axes[3].set_title(f'Analysis of Your ({human_role}) Decisions'); axes[3].set_ylabel('Order Quantity'); axes[3].grid(True, linestyle='--'); axes[3].set_xlabel('Week')
344
+ else: raise ValueError("No human decision data columns found.")
345
+ except (KeyError, ValueError) as plot_err:
346
+ axes[3].set_title(f'Analysis of Your ({human_role}) Decisions - Error Plotting Data'); axes[3].text(0.5, 0.5, f"Error: {plot_err}", ha='center', va='center'); axes[3].grid(True, linestyle='--'); axes[3].set_xlabel('Week')
347
  plt.tight_layout(rect=[0, 0, 1, 0.96]); return fig
348
 
349
  @st.cache_data(ttl=60)
 
352
  try:
353
  local_path = hf_hub_download(repo_id=HF_REPO_ID, repo_type="dataset", filename=LEADERBOARD_FILE, token=HF_TOKEN, cache_dir=LOCAL_LOG_DIR / "hf_cache")
354
  with open(local_path, 'r', encoding='utf-8') as f: return json.load(f)
355
+ except EntryNotFoundError:
356
+ return {}
357
+ except Exception as e:
358
+ st.sidebar.error(f"Could not load leaderboard: {e}")
359
+ return {}
360
 
361
  def save_leaderboard_data(data):
362
  if not hf_api or not HF_REPO_ID or not HF_TOKEN: return
363
  try:
364
  local_path = LOCAL_LOG_DIR / LEADERBOARD_FILE
365
  with open(local_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False)
366
+ hf_api.upload_file(path_or_fileobj=str(local_path), path_in_repo=LEADERBOARD_FILE, repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN, commit_message="Update leaderboard")
367
  st.cache_data.clear()
368
+ except Exception as e:
369
+ st.sidebar.error(f"Failed to upload leaderboard: {e}")
370
 
371
  def display_rankings(df, top_n=200):
372
+ if df.empty:
373
+ st.info("No completed games for this category yet. Be the first!")
374
+ return
375
+ df['distributor_cost'] = pd.to_numeric(df.get('total_cost'), errors='coerce')
376
  df['total_chain_cost'] = pd.to_numeric(df.get('total_chain_cost'), errors='coerce')
377
  df['order_std_dev'] = pd.to_numeric(df.get('order_std_dev'), errors='coerce')
378
  c1, c2, c3 = st.columns(3)
 
381
  champs_df = df.dropna(subset=['total_chain_cost']).sort_values('total_chain_cost', ascending=True).head(top_n).copy()
382
  if not champs_df.empty:
383
  champs_df['total_chain_cost'] = champs_df['total_chain_cost'].map('${:,.2f}'.format)
384
+ champs_df.rename(columns={'id': 'Participant', 'total_chain_cost': 'Total Chain Cost'}, inplace=True)
385
+ st.dataframe(champs_df[['Participant', 'Total Chain Cost']], use_container_width=True, hide_index=True)
386
  with c2:
387
  st.subheader("👤 Distributor Champions")
388
  dist_df = df.dropna(subset=['distributor_cost']).sort_values('distributor_cost', ascending=True).head(top_n).copy()
389
  if not dist_df.empty:
390
  dist_df['distributor_cost'] = dist_df['distributor_cost'].map('${:,.2f}'.format)
391
+ dist_df.rename(columns={'id': 'Participant', 'distributor_cost': 'Your Cost'}, inplace=True)
392
+ st.dataframe(dist_df[['Participant', 'Your Cost']], use_container_width=True, hide_index=True)
393
  with c3:
394
  st.subheader("🧘 Mr. Smooth")
395
  smooth_df = df.dropna(subset=['order_std_dev']).sort_values('order_std_dev', ascending=True).head(top_n).copy()
396
  if not smooth_df.empty:
397
  smooth_df['order_std_dev'] = smooth_df['order_std_dev'].map('{:,.2f}'.format)
398
+ smooth_df.rename(columns={'id': 'Participant', 'order_std_dev': 'Order Std. Dev.'}, inplace=True)
399
+ st.dataframe(smooth_df[['Participant', 'Order Std. Dev.']], use_container_width=True, hide_index=True)
400
 
401
  def show_leaderboard_ui():
402
  st.markdown("---")
403
  st.header("📊 The Bullwhip Leaderboard")
404
  leaderboard_data = load_leaderboard_data()
405
+ if not leaderboard_data:
406
+ st.info("No leaderboard data yet. Be the first to finish a game!")
407
+ else:
408
+ try:
409
+ df = pd.DataFrame(leaderboard_data.values())
410
+ if 'id' not in df.columns and not df.empty: df['id'] = list(leaderboard_data.keys())
411
+ if 'total_cost' not in df.columns or 'order_std_dev' not in df.columns or 'setting' not in df.columns:
412
+ st.error("Leaderboard data is corrupted or incomplete.")
413
+ return
414
+ groups = sorted(df.setting.unique())
415
+ tabs = st.tabs(["**Overall**"] + groups)
416
+ with tabs[0]: display_rankings(df)
417
+ for i, group_name in enumerate(groups):
418
+ with tabs[i+1]:
419
+ df_group = df[df.setting == group_name].copy()
420
+ display_rankings(df_group)
421
+ except Exception as e:
422
+ st.error(f"Error displaying leaderboard: {e}")
423
 
424
  def save_logs_and_upload(state: dict):
425
+ if not state.get('logs'):
426
+ st.warning("No log data to save.")
427
+ return
428
  participant_id = state['participant_id']
429
+ logs_df = None
430
  try:
431
  logs_df = pd.json_normalize(state['logs'])
432
+ safe_participant_id = re.sub(r'[^a-zA-Z0-9_-]', '_', participant_id)
433
+ fname = LOCAL_LOG_DIR / f"log_{safe_participant_id}_{int(time.time())}.csv"
434
  logs_df['experiment_end_timestamp'] = datetime.utcnow().isoformat() + "Z"
435
+ if st.session_state.get('consent_timestamp'):
436
+ logs_df['consent_given_timestamp'] = st.session_state['consent_timestamp']
437
+ else:
438
+ logs_df['consent_given_timestamp'] = "N/A"
439
+ for col in logs_df.select_dtypes(include=['object']).columns: logs_df[col] = logs_df[col].astype(str)
440
  logs_df.to_csv(fname, index=False)
441
+ st.success(f"Log successfully saved locally: `{fname}`")
442
+ with open(fname, "rb") as f: st.download_button("📥 Download Log CSV", data=f, file_name=fname.name, mime="text/csv")
443
  if HF_TOKEN and HF_REPO_ID and hf_api:
444
+ with st.spinner("Uploading log CSV to Hugging Face Hub..."):
445
+ try:
446
+ url = hf_api.upload_file( path_or_fileobj=str(fname), path_in_repo=f"logs/{fname.name}", repo_id=HF_REPO_ID, repo_type="dataset", token=HF_TOKEN)
447
+ st.success(f"✅ Log CSV successfully uploaded! [View File]({url})")
448
+ except Exception as e_upload: st.error(f"Upload to Hugging Face failed: {e_upload}")
449
+ except Exception as e_save:
450
+ st.error(f"Error processing or saving log CSV: {e_save}")
451
+ return
452
+ if logs_df is None: return
453
  try:
454
  human_role = state['human_role']
455
+ distributor_cost = logs_df[f'{human_role}.total_cost'].iloc[-1]
456
+ r_cost = logs_df['Retailer.total_cost'].iloc[-1]
457
+ w_cost = logs_df['Wholesaler.total_cost'].iloc[-1]
458
+ f_cost = logs_df['Factory.total_cost'].iloc[-1]
459
+ total_chain_cost = r_cost + w_cost + distributor_cost + f_cost
460
  order_std_dev = logs_df[f'{human_role}.order_placed'].std()
461
+ setting_name = f"{state['llm_personality']} / {state['info_sharing']}"
462
+ new_entry = {
463
+ 'id': participant_id, 'setting': setting_name,
464
+ 'total_cost': float(distributor_cost),
465
+ 'total_chain_cost': float(total_chain_cost),
466
+ 'order_std_dev': float(order_std_dev) if pd.notna(order_std_dev) else 0.0,
467
+ 'start_timestamp': state.get('start_timestamp'),
468
+ 'consent_timestamp': st.session_state.get('consent_timestamp')
469
+ }
470
  leaderboard_data = load_leaderboard_data()
471
+ leaderboard_data[participant_id] = new_entry
472
  save_leaderboard_data(leaderboard_data)
473
+ except Exception as e_board:
474
+ st.error(f"Error calculating or saving leaderboard score: {e_board}")
475
 
476
  # -----------------------------------------------------------------------------
477
  # 4. Streamlit UI
 
485
 
486
  if st.session_state.get('initialization_error'):
487
  st.error(st.session_state.initialization_error)
 
488
  elif not st.session_state['consent_given']:
489
  st.header("📝 Participant Consent Form")
490
+ st.markdown("""**Lead Researcher:** Xinyu Li...""") # (Long text same as before)
491
  with st.form("consent_form"):
492
+ consent_choice = st.radio("**Do you agree?**", ('Yes', 'No'), index=None)
493
  if st.form_submit_button("Continue"):
494
+ if consent_choice == 'Yes':
495
  st.session_state['consent_given'] = True
496
  st.session_state['consent_timestamp'] = datetime.utcnow().isoformat() + "Z"
497
  st.rerun()
 
499
 
500
  elif not st.session_state['comprehension_passed']:
501
  st.header("🧠 Comprehension Check")
502
+ with st.form("comprehension_quiz"):
503
+ user_answers = {}
504
+ for i, q_data in enumerate(COMPREHENSION_QUESTIONS):
505
+ st.subheader(q_data['q'])
506
+ user_answers[i] = st.radio("Select:", q_data['options'], key=f"comp_q_{i}", index=None)
507
+ if st.form_submit_button("Submit Answers"):
508
+ all_correct = True
509
+ for i, q_data in enumerate(COMPREHENSION_QUESTIONS):
510
+ if user_answers.get(i) != q_data['options'][q_data['correct_index']]:
511
+ all_correct = False
512
+ if all_correct: st.session_state['comprehension_passed'] = True; st.rerun()
513
  else: st.error("Incorrect answers.")
514
 
515
  else:
516
+ is_game_state_present = st.session_state.get('game_state') is not None
517
+ is_game_running = st.session_state.get('game_state', {}).get('game_running', False)
518
+ is_game_over = is_game_state_present and not is_game_running and st.session_state.get('game_state', {}).get('week', 0) > WEEKS
519
+
520
  if is_game_over:
521
  st.header("🎉 Game Over!")
522
  state = st.session_state.game_state
523
+ participant_id = state['participant_id']
524
+ url = f"{QUALTRICS_BASE_URL}?{PID_FIELD_NAME}={participant_id}"
525
+ st.markdown(f'<a href="{url}" target="_blank"><button style="...">Click Start Survey</button></a>', unsafe_allow_html=True)
526
+ try:
527
+ logs_df = pd.json_normalize(state['logs'])
528
+ st.pyplot(plot_results(logs_df, f"Beer Game (Human: {state['human_role']})", state['human_role']))
529
+ save_logs_and_upload(state)
530
+ except Exception as e: st.error(f"Error: {e}")
531
+ if st.button("✨ Start a New Game"):
532
  for k in ['consent_timestamp', 'consent_given', 'comprehension_passed', 'game_state']:
533
  if k in st.session_state: del st.session_state[k]
534
  st.rerun()
535
 
536
+ elif is_game_running:
537
  state = st.session_state.game_state
538
  week, human_role, echelons, info_sharing = state['week'], state['human_role'], state['echelons'], state['info_sharing']
539
  echelon_order = ["Retailer", "Wholesaler", "Distributor", "Factory"]
 
544
  for i, name in enumerate(echelon_order):
545
  with cols[i]:
546
  e = echelons[name]
547
+ if name == human_role:
548
+ st.markdown(f"##### **<span style='border: 1px solid #FF4B4B; padding: 2px 5px;'>👤 {name} (You)</span>**", unsafe_allow_html=True)
549
+ else: st.markdown(f"##### 🤖 {name}")
550
  st.metric("Inventory", e['inventory']); st.metric("Backlog", e['backlog'])
551
  st.write(f"Incoming Order: **{e['incoming_order']}**")
552
  if name == "Factory": st.write(f"Completing Next: **{state['last_week_orders'].get('Distributor', 0)}**")
 
555
  e = echelons[human_role]
556
  st.markdown(f"### <span style='color:#FF4B4B;'>👤 {human_role} (Your Dashboard)</span>", unsafe_allow_html=True)
557
  c1, c2, c3 = st.columns(3)
558
+ with c1: st.metric("Inventory", e['inventory']); st.metric("Backlog", e['backlog'])
559
+ with c2: st.write(f"**Incoming Order:**\n# {e['incoming_order']}")
560
+ with c3: st.write(f"**Arriving Next:**\n# {list(e['incoming_shipments'])[0] if e['incoming_shipments'] else 0}")
561
 
562
  st.markdown("---")
563
+ st.header("Your Decision")
564
  if state['decision_step'] == 'initial_order':
565
+ with st.form(key="initial_order_form"):
566
+ initial_order = st.number_input("Your Initial Order Quantity:", min_value=0, step=1, value=None)
567
+ if st.form_submit_button("Submit Initial Order & See AI Suggestion", type="primary"):
568
+ state['human_initial_order'] = int(initial_order) if initial_order is not None else 0
569
  state['decision_step'] = 'final_order'
570
+ snap = {n: {'name': n, 'inventory': echelons[n]['inventory'], 'backlog': echelons[n]['backlog'], 'incoming_order': echelons[n]['incoming_order']} for n in echelon_order}
571
+ prompt_sugg = get_llm_prompt(snap[human_role], week, state['llm_personality'], info_sharing, snap)
572
+ ai_suggestion, _ = get_llm_order_decision(prompt_sugg, human_role)
573
+ state['current_ai_suggestion'] = ai_suggestion
574
  st.rerun()
575
  else:
576
+ ai_suggestion = state.get('current_ai_suggestion', 4)
577
+ with st.form(key="final_order_form"):
578
+ st.write(f"#### AI Suggestion: **{ai_suggestion}** units")
579
+ final_order = st.number_input("Your Final Order Quantity:", min_value=0, step=1, key='final_order_input', value=None)
580
+ if st.form_submit_button("Submit Final Order & Advance"):
581
+ step_game(int(final_order) if final_order is not None else 0, state['human_initial_order'], ai_suggestion)
582
  st.rerun()
583
 
 
 
 
 
 
584
  else:
585
  st.header("⚙️ Game Configuration")
586
+ participant_id = st.text_input("Enter Your Name or Team ID:", key="participant_id_input")
587
 
588
+ # --- 恢复手动选择配置 ---
589
  c1, c2 = st.columns(2)
590
  with c1:
591
+ llm_personality = st.selectbox("AI Agent Personality", ('human_like', 'perfect_rational'), format_func=lambda x: x.replace('_', ' ').title())
592
  with c2:
593
+ info_sharing = st.selectbox("Information Sharing Level", ('local', 'full'), format_func=lambda x: x.title())
594
 
595
  if st.button("🚀 Start Game", type="primary"):
596
+ if participant_id:
597
+ init_game_state(llm_personality, info_sharing, participant_id)
598
  st.rerun()
599
+ else: st.error("Please enter an ID.")
600
  show_leaderboard_ui()
601
 
602
  # --- Instructor Zone ---
603
  st.sidebar.markdown("---")
604
  with st.sidebar.expander("🔐 Instructor Zone"):
605
  if st.text_input("Admin Password:", type="password") == ADMIN_PASSWORD:
606
+ if st.checkbox("Show Global Leaderboard"): show_leaderboard_ui()