-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulator.py
More file actions
188 lines (154 loc) · 7.3 KB
/
Copy pathsimulator.py
File metadata and controls
188 lines (154 loc) · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import time
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from models import QueuePredictionModels
class StreamingSimulator:
def __init__(self, speedup=60): # 60x speed
self.speedup = speedup
self.models = QueuePredictionModels()
self.load_data()
def load_data(self):
"""Load events for replay"""
print("Loading event data for simulation...")
# Load all events and create replay timeline
orders = pd.read_csv('data/orders.csv', parse_dates=['ts'])
trades = pd.read_csv('data/trades.csv', parse_dates=['ts'])
scans = pd.read_csv('data/scans.csv', parse_dates=['ts'])
# Create event timeline
events = []
# Add order events
for _, row in orders.iterrows():
events.append({
'ts': row['ts'],
'type': 'order',
'outlet_id': row['outlet_id'],
'data': {'order_id': row['order_id'], 'prep_time': row['prep_time_estimated']}
})
# Add token events (only redemptions)
token_redemptions = trades[trades['trade_type'] == 'redemption']
for _, row in token_redemptions.iterrows():
events.append({
'ts': row['ts'],
'type': 'token_spend',
'outlet_id': row['outlet_id'],
'data': {'student_id': row['student_id'], 'tokens': abs(row['tokens_delta'])}
})
# Add scan events
for _, row in scans.iterrows():
events.append({
'ts': row['ts'],
'type': 'scan',
'outlet_id': row['outlet_id'],
'data': {'count': row['count_since_last']}
})
# Sort by timestamp
self.events = pd.DataFrame(events).sort_values('ts').reset_index(drop=True)
print(f"Loaded {len(self.events)} events from {self.events.ts.min()} to {self.events.ts.max()}")
def compute_features_for_ts(self, current_ts, outlet_id):
"""Compute current features for prediction"""
# Look back 5 minutes for rolling features
lookback_start = current_ts - timedelta(minutes=5)
# Get recent events
recent_events = self.events[
(self.events.ts >= lookback_start) &
(self.events.ts <= current_ts) &
(self.events.outlet_id == outlet_id)
]
# Count different event types
orders_5min = len(recent_events[recent_events.type == 'order']) / 5.0
tokens_spent = len(recent_events[recent_events.type == 'token_spend']) / 5.0
scans_5min = recent_events[recent_events.type == 'scan']['data'].apply(
lambda x: x.get('count', 0) if isinstance(x, dict) else 0
).sum() / 5.0
# Current minute features
orders_current = len(recent_events[
(recent_events.type == 'order') &
(recent_events.ts >= current_ts - timedelta(minutes=1))
])
# Time features
minute_of_day = current_ts.hour * 60 + current_ts.minute
day_of_week = current_ts.weekday()
# Classes ending soon (simplified - use time patterns)
if 50 <= minute_of_day <= 60: # Around class end times
classes_ending = 3
elif minute_of_day in [170, 230, 290, 350]: # Common class end times
classes_ending = 2
else:
classes_ending = 0
return {
'orders_per_min': orders_current,
'orders_5min': orders_5min,
'scans_per_min': scans_5min,
'minute_of_day': minute_of_day,
'day_of_week': day_of_week,
'classes_ending_10min': classes_ending,
'tokens_spent': tokens_spent
}
def run_simulation(self, demo_duration_minutes=10):
"""Run streaming simulation"""
print(f"\n🚀 Starting Streaming Simulation (Demo)")
print("=" * 60)
print("Simulating AI-powered dining optimization in real-time...")
print("Watch as the system predicts queue lengths and adjusts token pricing!")
print("=" * 60)
start_time = self.events.ts.min()
current_sim_time = start_time
demo_end_time = start_time + timedelta(minutes=demo_duration_minutes)
# Sample events at regular intervals for demo
demo_events = []
while current_sim_time < demo_end_time:
demo_events.append(current_sim_time)
current_sim_time += timedelta(minutes=2) # Every 2 minutes
print(f"Demo timeline: {len(demo_events)} prediction points over {demo_duration_minutes} minutes\n")
for i, event_time in enumerate(demo_events):
# Simulate brief delay for dramatic effect
time.sleep(0.5)
outlet = 'dining_hall_1'
# Compute features
features = self.compute_features_for_ts(event_time, outlet)
# Make predictions
queue_pred = self.models.predict_queue(features)
token_pred = self.models.predict_tokens(features)
eta = self.models.compute_eta(queue_pred)
multiplier = self.models.compute_multiplier(token_pred)
# Format time nicely
time_str = event_time.strftime('%H:%M')
# Decision logic
action = "No change"
if abs(multiplier - 1.0) > 0.05:
if multiplier > 1.0:
action = f"🔴 INCREASE token price ({multiplier:.2f}x) - High demand predicted"
else:
action = f"🟢 DECREASE token price ({multiplier:.2f}x) - Low demand predicted"
# Print status
print(f"[{time_str}] Queue: {queue_pred:.1f} orders | ETA: {eta:.1f} min | Tokens: {token_pred:.1f}")
print(f" 🎯 {action}")
# Special annotations for interesting periods
hour = event_time.hour
if hour == 12:
print(" 📊 Lunch rush - AI optimizing for peak demand")
elif hour == 8:
print(" 🌅 Breakfast period - Managing morning class conflicts")
elif hour == 18:
print(" 🌙 Dinner time - Balancing evening availability")
print()
print("=" * 60)
print("✅ Simulation Complete!")
print("🎯 Key Insights Demonstrated:")
print(" • Real-time queue length prediction")
print(" • Dynamic token pricing based on demand")
print(" • Academic schedule integration")
print(" • Proactive capacity management")
print("=" * 60)
def main():
print("🏛️ PALANTIR AI DINING OPTIMIZATION - LIVE DEMO")
print("Real-time streaming simulation of intelligent queue management\n")
# Initialize simulator
sim = StreamingSimulator()
# Run demo
sim.run_simulation(demo_duration_minutes=8) # 8 minutes demo
print("\n🎉 Ready for hackathon presentation!")
print("This demo shows how Palantir's AI platform optimizes dining operations in real-time.")
if __name__ == "__main__":
main()