anujkum0x commited on
Commit
98b2567
·
verified ·
1 Parent(s): 81e3fbe

Create hourlheck.py

Browse files
Files changed (1) hide show
  1. hourlheck.py +841 -0
hourlheck.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import pulp as pl
4
+ import matplotlib.pyplot as plt
5
+ import gradio as gr
6
+ from itertools import product
7
+ import io
8
+ import base64
9
+ import tempfile
10
+ import os
11
+ from datetime import datetime
12
+
13
+ def am_pm(hour):
14
+ """Converts 24-hour time to AM/PM format."""
15
+ period = "AM"
16
+ if hour >= 12:
17
+ period = "PM"
18
+ if hour > 12:
19
+ hour -= 12
20
+ elif hour == 0:
21
+ hour = 12 # Midnight
22
+ return f"{int(hour):02d}:00 {period}"
23
+
24
+ def show_dataframe(csv_path):
25
+ """Reads a CSV file and returns a Pandas DataFrame."""
26
+ try:
27
+ df = pd.read_csv(csv_path)
28
+ return df
29
+ except Exception as e:
30
+ return f"Error loading CSV: {e}"
31
+
32
+ def optimize_staffing(
33
+ csv_file,
34
+ beds_per_staff,
35
+ max_hours_per_staff, # This will now be interpreted as hours per 28-day period
36
+ hours_per_cycle,
37
+ rest_days_per_week,
38
+ clinic_start,
39
+ clinic_end,
40
+ overlap_time,
41
+ max_start_time_change,
42
+ exact_staff_count=None,
43
+ overtime_percent=100
44
+ ):
45
+ # Load data
46
+ try:
47
+ if isinstance(csv_file, str):
48
+ # Handle the case when a filepath is passed directly
49
+ data = pd.read_csv(csv_file)
50
+ else:
51
+ # Handle the case when file object is uploaded through Gradio
52
+ data = pd.read_csv(io.StringIO(csv_file.decode('utf-8')))
53
+ except Exception as e:
54
+ print(f"Error loading CSV file: {e}")
55
+ return f"Error loading CSV file: {e}", None, None, None, None
56
+
57
+ # Rename the index column if necessary
58
+ if data.columns[0] not in ['day', 'Day', 'DAY']:
59
+ data = data.rename(columns={data.columns[0]: 'day'})
60
+
61
+ # Fill missing values
62
+ for col in data.columns:
63
+ if col.startswith('cycle'):
64
+ data[col] = data[col].fillna(0)
65
+
66
+ # Calculate clinic hours
67
+ if clinic_end < clinic_start:
68
+ clinic_hours = 24 - clinic_start + clinic_end
69
+ else:
70
+ clinic_hours = clinic_end - clinic_start
71
+
72
+ # Get number of days in the dataset
73
+ num_days = len(data)
74
+
75
+ # Parameters
76
+ BEDS_PER_STAFF = float(beds_per_staff)
77
+ STANDARD_PERIOD_DAYS = 30 # Standard 4-week period
78
+
79
+ # Scale MAX_HOURS_PER_STAFF based on the ratio of actual days to standard period
80
+ BASE_MAX_HOURS = float(max_hours_per_staff) # This is for a 28-day period
81
+ MAX_HOURS_PER_STAFF = BASE_MAX_HOURS * (num_days / STANDARD_PERIOD_DAYS)
82
+
83
+ # Log the adjustment for transparency
84
+ original_results = f"Input max hours per staff (28-day period): {BASE_MAX_HOURS}\n"
85
+ original_results += f"Adjusted max hours for {num_days}-day period: {MAX_HOURS_PER_STAFF:.1f}\n\n"
86
+
87
+ HOURS_PER_CYCLE = float(hours_per_cycle)
88
+ REST_DAYS_PER_WEEK = int(rest_days_per_week)
89
+ SHIFT_TYPES = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] # More flexible shift types from 3 to 12 hours
90
+ OVERLAP_TIME = float(overlap_time)
91
+ CLINIC_START = int(clinic_start)
92
+ CLINIC_END = int(clinic_end)
93
+ CLINIC_HOURS = clinic_hours
94
+ MAX_START_TIME_CHANGE = int(max_start_time_change)
95
+ OVERTIME_ALLOWED = 1 + (overtime_percent / 100) # Convert percentage to multiplier
96
+
97
+ # Calculate staff needed per cycle (beds/BEDS_PER_STAFF, rounded up)
98
+ for col in data.columns:
99
+ if col.startswith('cycle') and not col.endswith('_staff'):
100
+ data[f'{col}_staff'] = np.ceil(data[col] / BEDS_PER_STAFF)
101
+
102
+ # Get cycle names and number of cycles
103
+ cycle_cols = [col for col in data.columns if col.startswith('cycle') and not col.endswith('_staff')]
104
+ num_cycles = len(cycle_cols)
105
+
106
+ # Define cycle times
107
+ cycle_times = {}
108
+ for i, cycle in enumerate(cycle_cols):
109
+ cycle_start = (CLINIC_START + i * HOURS_PER_CYCLE) % 24
110
+ cycle_end = (CLINIC_START + (i + 1) * HOURS_PER_CYCLE) % 24
111
+ cycle_times[cycle] = (cycle_start, cycle_end)
112
+
113
+ # Get staff requirements
114
+ max_staff_needed = max([data[f'{cycle}_staff'].max() for cycle in cycle_cols])
115
+
116
+ # Define possible shift start times
117
+ shift_start_times = list(range(CLINIC_START, CLINIC_START + int(CLINIC_HOURS) - min(SHIFT_TYPES) + 1))
118
+
119
+ # Generate all possible shifts
120
+ possible_shifts = []
121
+ for duration in SHIFT_TYPES:
122
+ for start_time in shift_start_times:
123
+ end_time = (start_time + duration) % 24
124
+
125
+ # Create a shift with its coverage of cycles
126
+ shift = {
127
+ 'id': f"{duration}hr_{start_time:02d}",
128
+ 'start': start_time,
129
+ 'end': end_time,
130
+ 'duration': duration,
131
+ 'cycles_covered': set()
132
+ }
133
+
134
+ # Determine which cycles this shift covers with hourly granularity
135
+ for cycle, (cycle_start, cycle_end) in cycle_times.items():
136
+ # Convert to 24-hour range for easier comparison
137
+ cycle_hours = []
138
+
139
+ # Handle overnight cycles
140
+ if cycle_end < cycle_start: # overnight cycle
141
+ # Add all hours from cycle_start to midnight
142
+ cycle_hours.extend(range(int(cycle_start), 24))
143
+ # Add all hours from midnight to cycle_end
144
+ cycle_hours.extend(range(0, int(cycle_end)))
145
+ else: # normal cycle
146
+ # Add all hours from cycle_start to cycle_end
147
+ cycle_hours.extend(range(int(cycle_start), int(cycle_end)))
148
+
149
+ # Get shift hours
150
+ shift_hours = []
151
+
152
+ # Handle overnight shifts
153
+ if end_time < start_time: # overnight shift
154
+ # Add all hours from start_time to midnight
155
+ shift_hours.extend(range(int(start_time), 24))
156
+ # Add all hours from midnight to end_time
157
+ shift_hours.extend(range(0, int(end_time)))
158
+ else: # normal shift
159
+ # Add all hours from start_time to end_time
160
+ shift_hours.extend(range(int(start_time), int(end_time)))
161
+
162
+ # Check if all cycle hours are covered by the shift
163
+ if all(hour in shift_hours for hour in cycle_hours):
164
+ shift['cycles_covered'].add(cycle)
165
+
166
+ if shift['cycles_covered']: # Only add shifts that cover at least one cycle
167
+ possible_shifts.append(shift)
168
+
169
+ # Estimate minimum number of staff needed - more precise calculation
170
+ total_staff_hours = 0
171
+ for _, row in data.iterrows():
172
+ for cycle in cycle_cols:
173
+ total_staff_hours += row[f'{cycle}_staff'] * HOURS_PER_CYCLE
174
+
175
+ # Calculate theoretical minimum staff with perfect utilization
176
+ theoretical_min_staff = np.ceil(total_staff_hours / MAX_HOURS_PER_STAFF)
177
+
178
+ # Add a small buffer for rest day constraints
179
+ min_staff_estimate = np.ceil(theoretical_min_staff * (7 / (7 - REST_DAYS_PER_WEEK)))
180
+
181
+ # Use exact_staff_count if provided, otherwise estimate
182
+ if exact_staff_count is not None and exact_staff_count > 0:
183
+ # When exact staff count is provided, only create that many staff in the model
184
+ estimated_staff = exact_staff_count
185
+ num_staff_to_create = exact_staff_count # Only create exactly this many staff
186
+ else:
187
+ # Add some buffer for constraints like rest days and shift changes
188
+ estimated_staff = max(min_staff_estimate, max_staff_needed + 1)
189
+ num_staff_to_create = int(estimated_staff) # Create the estimated number of staff
190
+
191
+ def optimize_schedule(num_staff, time_limit=600):
192
+ try:
193
+ # Create a binary linear programming model
194
+ model = pl.LpProblem("Staff_Scheduling", pl.LpMinimize)
195
+
196
+ # Decision variables
197
+ x = pl.LpVariable.dicts("shift",
198
+ [(s, d, shift['id']) for s in range(1, num_staff+1)
199
+ for d in range(1, num_days+1)
200
+ for shift in possible_shifts],
201
+ cat='Binary')
202
+
203
+ # Staff usage variable (1 if staff s is used at all, 0 otherwise)
204
+ staff_used = pl.LpVariable.dicts("staff_used", range(1, num_staff+1), cat='Binary')
205
+
206
+ # Total hours worked by all staff
207
+ total_hours = pl.LpVariable("total_hours", lowBound=0)
208
+
209
+ # CRITICAL CHANGE: Remove coverage violation variables - make coverage a hard constraint
210
+ # CRITICAL CHANGE: Remove overtime variables - make overtime a hard constraint
211
+
212
+ # Objective function now only focuses on minimizing staff count and total hours
213
+ # Increase the weight on staff count to aggressively minimize staff
214
+ model += (
215
+ 10**12 * pl.lpSum(staff_used[s] for s in range(1, num_staff+1)) +
216
+ 1 * total_hours
217
+ )
218
+
219
+ # Link total_hours to the sum of all hours worked
220
+ model += total_hours == pl.lpSum(x[(s, d, shift['id'])] * shift['duration']
221
+ for s in range(1, num_staff+1)
222
+ for d in range(1, num_days+1)
223
+ for shift in possible_shifts)
224
+
225
+ # Link staff_used variable with shift assignments
226
+ for s in range(1, num_staff+1):
227
+ model += pl.lpSum(x[(s, d, shift['id'])]
228
+ for d in range(1, num_days+1)
229
+ for shift in possible_shifts) <= num_days * staff_used[s]
230
+
231
+ # If staff is used, they must work at least one shift
232
+ model += pl.lpSum(x[(s, d, shift['id'])]
233
+ for d in range(1, num_days+1)
234
+ for shift in possible_shifts) >= staff_used[s]
235
+
236
+ # Maintain staff ordering (to avoid symmetrical solutions)
237
+ for s in range(1, num_staff):
238
+ model += staff_used[s] >= staff_used[s+1]
239
+
240
+ # Each staff works at most one shift per day
241
+ for s in range(1, num_staff+1):
242
+ for d in range(1, num_days+1):
243
+ model += pl.lpSum(x[(s, d, shift['id'])] for shift in possible_shifts) <= 1
244
+
245
+ # Rest day constraints (with more flexibility)
246
+ min_rest_days = max(1, REST_DAYS_PER_WEEK - 1) # Reduce minimum rest days by 1
247
+ for s in range(1, num_staff+1):
248
+ for w in range((num_days + 6) // 7):
249
+ week_start = w*7 + 1
250
+ week_end = min(week_start + 6, num_days)
251
+ days_in_this_week = week_end - week_start + 1
252
+
253
+ if days_in_this_week < 7:
254
+ adjusted_rest_days = max(1, int(min_rest_days * days_in_this_week / 7))
255
+ else:
256
+ adjusted_rest_days = min_rest_days
257
+
258
+ model += pl.lpSum(x[(s, d, shift['id'])]
259
+ for d in range(week_start, week_end+1)
260
+ for shift in possible_shifts) <= days_in_this_week - adjusted_rest_days
261
+
262
+ # HARD CONSTRAINT: Maximum hours per week for each staff - relaxed to allow more flexibility
263
+ for s in range(1, num_staff+1):
264
+ for w in range((num_days + 6) // 7):
265
+ week_start = w*7 + 1
266
+ week_end = min(week_start + 6, num_days)
267
+
268
+ # Calculate total hours worked by this staff in this week
269
+ weekly_hours = pl.lpSum(x[(s, d, shift['id'])] * shift['duration']
270
+ for d in range(week_start, week_end+1)
271
+ for shift in possible_shifts)
272
+
273
+ # RELAXED constraint: Allow up to 72 hours per week (was 60)
274
+ model += weekly_hours <= 72
275
+
276
+ # HARD CONSTRAINT: Full coverage required
277
+ for d in range(1, num_days+1):
278
+ day_index = d - 1 # 0-indexed for DataFrame
279
+
280
+ for cycle in cycle_cols:
281
+ staff_needed = data.iloc[day_index][f'{cycle}_staff']
282
+
283
+ # Get all shifts that cover this cycle
284
+ covering_shifts = [shift for shift in possible_shifts if cycle in shift['cycles_covered']]
285
+
286
+ # Staff assigned must be at least staff_needed - NO VIOLATIONS ALLOWED
287
+ model += (pl.lpSum(x[(s, d, shift['id'])]
288
+ for s in range(1, num_staff+1)
289
+ for shift in covering_shifts) >= staff_needed)
290
+
291
+ # Solve with extended time limit
292
+ solver = pl.PULP_CBC_CMD(timeLimit=time_limit, msg=1, gapRel=0.01) # Tighter gap for better solutions
293
+ model.solve(solver)
294
+
295
+ # Check if a feasible solution was found
296
+ if model.status == pl.LpStatusOptimal or model.status == pl.LpStatusNotSolved:
297
+ # Extract the solution
298
+ schedule = []
299
+ for s in range(1, num_staff+1):
300
+ for d in range(1, num_days+1):
301
+ for shift in possible_shifts:
302
+ if pl.value(x[(s, d, shift['id'])]) == 1:
303
+ # Find the shift details
304
+ shift_details = next((sh for sh in possible_shifts if sh['id'] == shift['id']), None)
305
+
306
+ schedule.append({
307
+ 'staff_id': s,
308
+ 'day': d,
309
+ 'shift_id': shift['id'],
310
+ 'start': shift_details['start'],
311
+ 'end': shift_details['end'],
312
+ 'duration': shift_details['duration'],
313
+ 'cycles_covered': list(shift_details['cycles_covered'])
314
+ })
315
+
316
+ return schedule, model.objective.value()
317
+ else:
318
+ return None, None
319
+ except Exception as e:
320
+ print(f"Error in optimization: {e}")
321
+ return None, None
322
+
323
+ # Try to solve with estimated number of staff
324
+ if exact_staff_count is not None and exact_staff_count > 0:
325
+ # If exact staff count is specified, only try with that count
326
+ staff_count = int(exact_staff_count)
327
+ results = f"Using exactly {staff_count} staff as specified...\n"
328
+
329
+ # Try to solve with exactly this many staff
330
+ schedule, objective = optimize_schedule(staff_count, time_limit=1200) # Increase time limit
331
+
332
+ if schedule is None:
333
+ results += f"Failed to find a feasible solution with exactly {staff_count} staff.\n"
334
+ results += "Try increasing the staff count.\n"
335
+ return results, None, None, None, None, None
336
+ else:
337
+ # Start from theoretical minimum and work up
338
+ min_staff = max(1, int(theoretical_min_staff)) # Start from theoretical minimum
339
+ max_staff = int(min_staff_estimate) + 5 # Allow some buffer
340
+
341
+ results = f"Theoretical minimum staff needed: {theoretical_min_staff:.1f}\n"
342
+ results += f"Searching for minimum staff count starting from {min_staff}...\n"
343
+
344
+ # Try each staff count from min to max
345
+ for staff_count in range(min_staff, max_staff + 1):
346
+ results += f"Trying with {staff_count} staff...\n"
347
+
348
+ # Increase time limit for each attempt to give the solver more time
349
+ time_limit = 600 + (staff_count - min_staff) * 200 # More time for larger staff counts
350
+ schedule, objective = optimize_schedule(staff_count, time_limit)
351
+
352
+ if schedule is not None:
353
+ results += f"Found feasible solution with {staff_count} staff.\n"
354
+ break
355
+
356
+ if schedule is None:
357
+ results += "Failed to find a feasible solution with the attempted staff counts.\n"
358
+ results += "Try increasing the staff count manually or relaxing constraints.\n"
359
+ return results, None, None, None, None, None
360
+
361
+ results += f"Optimal solution found with {staff_count} staff\n"
362
+ results += f"Total staff hours: {objective}\n"
363
+
364
+ # Convert to DataFrame for analysis
365
+ schedule_df = pd.DataFrame(schedule)
366
+
367
+ # Analyze staff workload
368
+ staff_hours = {}
369
+ for s in range(1, staff_count+1):
370
+ staff_shifts = schedule_df[schedule_df['staff_id'] == s]
371
+ total_hours = staff_shifts['duration'].sum()
372
+ staff_hours[s] = total_hours
373
+
374
+ # After calculating staff hours, filter out staff with 0 hours before displaying
375
+ active_staff_hours = {s: hours for s, hours in staff_hours.items() if hours > 0}
376
+
377
+ results += "\nStaff Hours:\n"
378
+ for staff_id, hours in active_staff_hours.items():
379
+ utilization = (hours / MAX_HOURS_PER_STAFF) * 100
380
+ results += f"Staff {staff_id}: {hours} hours ({utilization:.1f}% utilization)\n"
381
+ # Add overtime information
382
+ if hours > MAX_HOURS_PER_STAFF:
383
+ overtime = hours - MAX_HOURS_PER_STAFF
384
+ overtime_percent = (overtime / MAX_HOURS_PER_STAFF) * 100
385
+ results += f" Overtime: {overtime:.1f} hours ({overtime_percent:.1f}%)\n"
386
+
387
+ # Use active_staff_hours for average utilization calculation
388
+ active_staff_count = len(active_staff_hours)
389
+ avg_utilization = sum(active_staff_hours.values()) / (active_staff_count * MAX_HOURS_PER_STAFF) * 100
390
+ results += f"\nAverage staff utilization: {avg_utilization:.1f}%\n"
391
+
392
+ # Check coverage for each day and cycle
393
+ coverage_check = []
394
+ for d in range(1, num_days+1):
395
+ day_index = d - 1 # 0-indexed for DataFrame
396
+
397
+ day_schedule = schedule_df[schedule_df['day'] == d]
398
+
399
+ for cycle in cycle_cols:
400
+ required = data.iloc[day_index][f'{cycle}_staff']
401
+
402
+ # Count staff covering this cycle (must fully cover all hours)
403
+ assigned = sum(1 for _, shift in day_schedule.iterrows()
404
+ if cycle in shift['cycles_covered'])
405
+
406
+ coverage_check.append({
407
+ 'day': d,
408
+ 'cycle': cycle,
409
+ 'required': required,
410
+ 'assigned': assigned,
411
+ 'satisfied': assigned >= required
412
+ })
413
+
414
+ coverage_df = pd.DataFrame(coverage_check)
415
+ satisfaction = coverage_df['satisfied'].mean() * 100
416
+ results += f"Coverage satisfaction: {satisfaction:.1f}%\n"
417
+
418
+ if satisfaction < 100:
419
+ results += "Warning: Not all staffing requirements are met!\n"
420
+ unsatisfied = coverage_df[~coverage_df['satisfied']]
421
+ results += unsatisfied.to_string() + "\n"
422
+
423
+ # Generate detailed schedule report
424
+ detailed_schedule = "Detailed Schedule:\n"
425
+ for d in range(1, num_days+1):
426
+ day_schedule = schedule_df[schedule_df['day'] == d]
427
+ day_schedule = day_schedule.sort_values(['start'])
428
+
429
+ detailed_schedule += f"\nDay {d}:\n"
430
+ for _, shift in day_schedule.iterrows():
431
+ start_hour = shift['start']
432
+ end_hour = shift['end']
433
+
434
+ start_str = am_pm(start_hour)
435
+ end_str = am_pm(end_hour)
436
+
437
+ cycles = ", ".join(shift['cycles_covered'])
438
+ detailed_schedule += f" Staff {shift['staff_id']}: {start_str}-{end_str} ({shift['duration']} hrs), Cycles: {cycles}\n"
439
+
440
+ # Generate schedule visualization
441
+ fig, ax = plt.subplots(figsize=(15, 8))
442
+
443
+ # Prepare schedule for plotting
444
+ staff_days = {}
445
+ for s in range(1, staff_count+1):
446
+ staff_days[s] = [0] * num_days # 0 means off duty
447
+
448
+ for _, shift in schedule_df.iterrows():
449
+ staff_id = shift['staff_id']
450
+ day = shift['day'] - 1 # 0-indexed
451
+ staff_days[staff_id][day] = shift['duration']
452
+
453
+ # Plot the schedule
454
+ for s, hours in staff_days.items():
455
+ ax.bar(range(1, num_days+1), hours, label=f'Staff {s}')
456
+
457
+ ax.set_xlabel('Day')
458
+ ax.set_ylabel('Shift Hours')
459
+ ax.set_title('Staff Schedule')
460
+ ax.set_xticks(range(1, num_days+1))
461
+ ax.legend()
462
+
463
+ # Save the figure to a temporary file
464
+ plot_path = None
465
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
466
+ plt.savefig(f.name)
467
+ plt.close(fig)
468
+ plot_path = f.name
469
+
470
+ # Create a Gantt chart with advanced visuals and alternating labels - only showing active staff
471
+ gantt_path = create_gantt_chart(schedule_df, num_days, staff_count)
472
+
473
+ # Convert schedule to CSV data
474
+ schedule_df['start_ampm'] = schedule_df['start'].apply(am_pm)
475
+ schedule_df['end_ampm'] = schedule_df['end'].apply(am_pm)
476
+ schedule_csv = schedule_df[['staff_id', 'day', 'start_ampm', 'end_ampm', 'duration', 'cycles_covered']].to_csv(index=False)
477
+
478
+ # Create a temporary file and write the CSV data into it
479
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".csv") as temp_file:
480
+ temp_file.write(schedule_csv)
481
+ schedule_csv_path = temp_file.name
482
+
483
+ # Create staff assignment table
484
+ staff_assignment_data = []
485
+ for d in range(1, num_days + 1):
486
+ cycle_staff = {}
487
+ for cycle in cycle_cols:
488
+ # Get staff IDs assigned to this cycle on this day
489
+ staff_ids = schedule_df[(schedule_df['day'] == d) & (schedule_df['cycles_covered'].apply(lambda x: cycle in x))]['staff_id'].tolist()
490
+ cycle_staff[cycle] = len(staff_ids)
491
+ staff_assignment_data.append([d] + [cycle_staff[cycle] for cycle in cycle_cols])
492
+
493
+ staff_assignment_df = pd.DataFrame(staff_assignment_data, columns=['Day'] + cycle_cols)
494
+
495
+ # Create CSV files for download
496
+ staff_assignment_csv_path = None
497
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".csv") as temp_file:
498
+ staff_assignment_df.to_csv(temp_file.name, index=False)
499
+ staff_assignment_csv_path = temp_file.name
500
+
501
+ # Return all required values in the correct order
502
+ return results, staff_assignment_df, gantt_path, schedule_df, plot_path, schedule_csv_path, staff_assignment_csv_path
503
+
504
+ def convert_to_24h(time_str):
505
+ """Converts AM/PM time string to 24-hour format."""
506
+ try:
507
+ time_obj = datetime.strptime(time_str, "%I:00 %p")
508
+ return time_obj.hour
509
+ except ValueError:
510
+ return None
511
+
512
+ def gradio_wrapper(
513
+ csv_file, beds_per_staff, max_hours_per_staff, hours_per_cycle,
514
+ rest_days_per_week, clinic_start_ampm, clinic_end_ampm, overlap_time, max_start_time_change,
515
+ exact_staff_count=None, overtime_percent=100
516
+ ):
517
+ try:
518
+ print("Starting gradio_wrapper function...")
519
+ print(f"Input parameters: beds_per_staff={beds_per_staff}, max_hours={max_hours_per_staff}, hours_per_cycle={hours_per_cycle}")
520
+ print(f"Clinic times: {clinic_start_ampm} to {clinic_end_ampm}")
521
+
522
+ # Convert AM/PM times to 24-hour format
523
+ clinic_start = convert_to_24h(clinic_start_ampm)
524
+ clinic_end = convert_to_24h(clinic_end_ampm)
525
+ print(f"Converted clinic times: {clinic_start} to {clinic_end}")
526
+
527
+ # Check if CSV file is provided
528
+ if csv_file is None:
529
+ print("Error: No CSV file provided")
530
+ empty_staff_df = pd.DataFrame(columns=["Day"])
531
+ return empty_staff_df, None, None, None, None, None
532
+
533
+ # Call the optimization function
534
+ print("Calling optimize_staffing function...")
535
+ results, staff_assignment_df, gantt_path, schedule_df, plot_path, schedule_csv_path, staff_assignment_csv_path = optimize_staffing(
536
+ csv_file, beds_per_staff, max_hours_per_staff, hours_per_cycle,
537
+ rest_days_per_week, clinic_start, clinic_end, overlap_time, max_start_time_change,
538
+ exact_staff_count, overtime_percent
539
+ )
540
+
541
+ print("Optimization completed successfully")
542
+ # Return the results
543
+ return staff_assignment_df, gantt_path, schedule_df, plot_path, schedule_csv_path, staff_assignment_csv_path
544
+ except Exception as e:
545
+ # If there's an error in the optimization process, return a meaningful error message
546
+ import traceback
547
+ print(f"Error during optimization: {str(e)}")
548
+ print(traceback.format_exc()) # Print the full traceback for debugging
549
+ empty_staff_df = pd.DataFrame(columns=["Day"])
550
+ # Return error in the first output
551
+ return empty_staff_df, None, None, None, None, None
552
+
553
+ # Create a Gantt chart with advanced visuals and alternating labels - only showing active staff
554
+ def create_gantt_chart(schedule_df, num_days, staff_count):
555
+ # Get the list of active staff IDs (staff who have at least one shift)
556
+ active_staff_ids = sorted(schedule_df['staff_id'].unique())
557
+ active_staff_count = len(active_staff_ids)
558
+
559
+ # Create a mapping from original staff ID to position in the chart
560
+ staff_position = {staff_id: i+1 for i, staff_id in enumerate(active_staff_ids)}
561
+
562
+ # Create a larger figure with higher DPI
563
+ plt.figure(figsize=(max(30, num_days * 1.5), max(12, active_staff_count * 0.8)), dpi=200)
564
+
565
+ # Use a more sophisticated color palette - only for active staff
566
+ colors = plt.cm.viridis(np.linspace(0.1, 0.9, active_staff_count))
567
+
568
+ # Set a modern style
569
+ plt.style.use('seaborn-v0_8-whitegrid')
570
+
571
+ # Create a new axis with a slight background color
572
+ ax = plt.gca()
573
+ ax.set_facecolor('#f8f9fa')
574
+
575
+ # Sort by staff then day
576
+ schedule_df = schedule_df.sort_values(['staff_id', 'day'])
577
+
578
+ # Plot Gantt chart - only for active staff
579
+ for i, staff_id in enumerate(active_staff_ids):
580
+ staff_shifts = schedule_df[schedule_df['staff_id'] == staff_id]
581
+
582
+ y_pos = active_staff_count - i # Position based on index in active staff list
583
+
584
+ # Add staff label with a background box
585
+ ax.text(-0.7, y_pos, f"Staff {staff_id}", fontsize=12, fontweight='bold',
586
+ ha='right', va='center', bbox=dict(facecolor='white', edgecolor='gray',
587
+ boxstyle='round,pad=0.5', alpha=0.9))
588
+
589
+ # Add a subtle background for each staff row
590
+ ax.axhspan(y_pos-0.4, y_pos+0.4, color='white', alpha=0.4, zorder=-5)
591
+
592
+ # Track shift positions to avoid label overlap
593
+ shift_positions = []
594
+
595
+ for idx, shift in enumerate(staff_shifts.iterrows()):
596
+ _, shift = shift
597
+ day = shift['day']
598
+ start_hour = shift['start']
599
+ end_hour = shift['end']
600
+ duration = shift['duration']
601
+
602
+ # Format times for display
603
+ start_ampm = am_pm(start_hour)
604
+ end_ampm = am_pm(end_hour)
605
+
606
+ # Calculate shift position
607
+ shift_start_pos = day-1+start_hour/24
608
+
609
+ # Handle overnight shifts
610
+ if end_hour < start_hour: # Overnight shift
611
+ # First part of shift (until midnight)
612
+ rect1 = ax.barh(y_pos, (24-start_hour)/24, left=shift_start_pos,
613
+ height=0.6, color=colors[i], alpha=0.9,
614
+ edgecolor='black', linewidth=1, zorder=10)
615
+
616
+ # Add gradient effect
617
+ for r in rect1:
618
+ r.set_edgecolor('black')
619
+ r.set_linewidth(1)
620
+
621
+ # Second part of shift (after midnight)
622
+ rect2 = ax.barh(y_pos, end_hour/24, left=day,
623
+ height=0.6, color=colors[i], alpha=0.9,
624
+ edgecolor='black', linewidth=1, zorder=10)
625
+
626
+ # Add gradient effect
627
+ for r in rect2:
628
+ r.set_edgecolor('black')
629
+ r.set_linewidth(1)
630
+
631
+ # For overnight shifts, we'll place the label in the first part if it's long enough
632
+ shift_width = (24-start_hour)/24
633
+ if shift_width >= 0.1: # Only add label if there's enough space
634
+ label_pos = shift_start_pos + shift_width/2
635
+
636
+ # Alternate labels above and below
637
+ y_offset = 0.35 if idx % 2 == 0 else -0.35
638
+
639
+ # Add label with background for better readability
640
+ label = f"{start_ampm}-{end_ampm}"
641
+ text = ax.text(label_pos, y_pos + y_offset, label,
642
+ ha='center', va='center', fontsize=9, fontweight='bold',
643
+ color='black', bbox=dict(facecolor='white', alpha=0.9, pad=3,
644
+ boxstyle='round,pad=0.3', edgecolor='gray'),
645
+ zorder=20)
646
+
647
+ shift_positions.append(label_pos)
648
+ else:
649
+ # Regular shift
650
+ shift_width = duration/24
651
+ rect = ax.barh(y_pos, shift_width, left=shift_start_pos,
652
+ height=0.6, color=colors[i], alpha=0.9,
653
+ edgecolor='black', linewidth=1, zorder=10)
654
+
655
+ # Add gradient effect
656
+ for r in rect:
657
+ r.set_edgecolor('black')
658
+ r.set_linewidth(1)
659
+
660
+ # Only add label if there's enough space
661
+ if shift_width >= 0.1:
662
+ label_pos = shift_start_pos + shift_width/2
663
+
664
+ # Alternate labels above and below
665
+ y_offset = 0.35 if idx % 2 == 0 else -0.35
666
+
667
+ # Add label with background for better readability
668
+ label = f"{start_ampm}-{end_ampm}"
669
+ text = ax.text(label_pos, y_pos + y_offset, label,
670
+ ha='center', va='center', fontsize=9, fontweight='bold',
671
+ color='black', bbox=dict(facecolor='white', alpha=0.9, pad=3,
672
+ boxstyle='round,pad=0.3', edgecolor='gray'),
673
+ zorder=20)
674
+
675
+ shift_positions.append(label_pos)
676
+
677
+ # Add weekend highlighting with a more sophisticated look
678
+ for day in range(1, num_days + 1):
679
+ # Determine if this is a weekend (assuming day 1 is Monday)
680
+ is_weekend = (day % 7 == 0) or (day % 7 == 6) # Saturday or Sunday
681
+
682
+ if is_weekend:
683
+ ax.axvspan(day-1, day, alpha=0.15, color='#ff9999', zorder=-10)
684
+ day_label = "Saturday" if day % 7 == 6 else "Sunday"
685
+ ax.text(day-0.5, 0.2, day_label, ha='center', fontsize=10, color='#cc0000',
686
+ fontweight='bold', bbox=dict(facecolor='white', alpha=0.7, pad=2, boxstyle='round'))
687
+
688
+ # Set x-axis ticks for each day with better formatting
689
+ ax.set_xticks(np.arange(0.5, num_days, 1))
690
+ day_labels = [f"Day {d}" for d in range(1, num_days+1)]
691
+ ax.set_xticklabels(day_labels, rotation=0, ha='center', fontsize=10)
692
+
693
+ # Add vertical lines between days with better styling
694
+ for day in range(1, num_days):
695
+ ax.axvline(x=day, color='#aaaaaa', linestyle='-', alpha=0.5, zorder=-5)
696
+
697
+ # Set y-axis ticks for each staff
698
+ ax.set_yticks(np.arange(1, active_staff_count+1))
699
+ ax.set_yticklabels([]) # Remove default labels as we've added custom ones
700
+
701
+ # Set axis limits with some padding
702
+ ax.set_xlim(-0.8, num_days)
703
+ ax.set_ylim(0.5, active_staff_count + 0.5)
704
+
705
+ # Add grid for hours (every 6 hours) with better styling
706
+ for day in range(num_days):
707
+ for hour in [6, 12, 18]:
708
+ ax.axvline(x=day + hour/24, color='#cccccc', linestyle=':', alpha=0.5, zorder=-5)
709
+ # Add small hour markers at the bottom
710
+ hour_label = "6AM" if hour == 6 else "Noon" if hour == 12 else "6PM"
711
+ ax.text(day + hour/24, 0, hour_label, ha='center', va='bottom', fontsize=7,
712
+ color='#666666', rotation=90, alpha=0.7)
713
+
714
+ # Add title and labels with more sophisticated styling
715
+ plt.title(f'Staff Schedule ({active_staff_count} Active Staff)', fontsize=24, fontweight='bold', pad=20, color='#333333')
716
+ plt.xlabel('Day', fontsize=16, labelpad=10, color='#333333')
717
+
718
+ # Add a legend for time reference with better styling
719
+ time_box = plt.figtext(0.01, 0.01, "Time Reference:", ha='left', fontsize=10,
720
+ fontweight='bold', color='#333333')
721
+ time_markers = ['6 AM', 'Noon', '6 PM', 'Midnight']
722
+ for i, time in enumerate(time_markers):
723
+ plt.figtext(0.08 + i*0.06, 0.01, time, ha='left', fontsize=9, color='#555555')
724
+
725
+ # Remove spines
726
+ for spine in ['top', 'right', 'left']:
727
+ ax.spines[spine].set_visible(False)
728
+
729
+ # Add a note about weekends with better styling
730
+ weekend_note = plt.figtext(0.01, 0.97, "Red areas = Weekends", fontsize=12,
731
+ color='#cc0000', fontweight='bold',
732
+ bbox=dict(facecolor='white', alpha=0.7, pad=5, boxstyle='round'))
733
+
734
+ # Add a subtle border around the entire chart
735
+ plt.box(False)
736
+
737
+ # Save the Gantt chart with high quality
738
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
739
+ plt.tight_layout()
740
+ plt.savefig(f.name, dpi=200, bbox_inches='tight', facecolor='white')
741
+ plt.close()
742
+ return f.name
743
+
744
+ # Define Gradio UI
745
+ am_pm_times = [f"{i:02d}:00 AM" for i in range(1, 13)] + [f"{i:02d}:00 PM" for i in range(1, 13)]
746
+
747
+ with gr.Blocks(title="Staff Scheduling Optimizer", css="""
748
+ #staff_assignment_table {
749
+ width: 100% !important;
750
+ }
751
+ #csv_schedule {
752
+ width: 100% !important;
753
+ }
754
+ .container {
755
+ max-width: 100% !important;
756
+ padding: 0 !important;
757
+ }
758
+ .download-btn {
759
+ margin-top: 10px !important;
760
+ }
761
+ """) as iface:
762
+
763
+ gr.Markdown("# Staff Scheduling Optimizer")
764
+ gr.Markdown("Upload a CSV file with cycle data and configure parameters to generate an optimal staff schedule.")
765
+
766
+ with gr.Row():
767
+ # LEFT PANEL - Inputs
768
+ with gr.Column(scale=1):
769
+ gr.Markdown("### Input Parameters")
770
+
771
+ # Input parameters
772
+ csv_input = gr.File(label="Upload CSV")
773
+ beds_per_staff = gr.Number(label="Beds per Staff", value=3)
774
+ max_hours_per_staff = gr.Number(label="Maximum monthly hours", value=160)
775
+ hours_per_cycle = gr.Number(label="Hours per Cycle", value=4)
776
+ rest_days_per_week = gr.Number(label="Rest Days per Week", value=2)
777
+ clinic_start_ampm = gr.Dropdown(label="Clinic Start Hour (AM/PM)", choices=am_pm_times, value="08:00 AM")
778
+ clinic_end_ampm = gr.Dropdown(label="Clinic End Hour (AM/PM)", choices=am_pm_times, value="08:00 PM")
779
+ overlap_time = gr.Number(label="Overlap Time", value=0)
780
+ max_start_time_change = gr.Number(label="Max Start Time Change", value=2)
781
+ exact_staff_count = gr.Number(label="Exact Staff Count (optional)", value=None)
782
+ overtime_percent = gr.Slider(label="Overtime Allowed (%)", minimum=0, maximum=100, value=100, step=10)
783
+
784
+ optimize_btn = gr.Button("Optimize Schedule", variant="primary", size="lg")
785
+
786
+ # RIGHT PANEL - Outputs
787
+ with gr.Column(scale=2):
788
+ gr.Markdown("### Results")
789
+
790
+ # Tabs for different outputs - reordered
791
+ with gr.Tabs():
792
+ with gr.TabItem("Detailed Schedule"):
793
+ with gr.Row():
794
+ csv_schedule = gr.Dataframe(label="Detailed Schedule", elem_id="csv_schedule")
795
+
796
+ with gr.Row():
797
+ schedule_download_file = gr.File(label="Download Detailed Schedule", visible=True)
798
+
799
+ with gr.TabItem("Gantt Chart"):
800
+ gantt_chart = gr.Image(label="Staff Schedule Visualization", elem_id="gantt_chart")
801
+
802
+ with gr.TabItem("Staff Coverage by Cycle"):
803
+ with gr.Row():
804
+ staff_assignment_table = gr.Dataframe(label="Staff Count in Each Cycle (Staff May Overlap)", elem_id="staff_assignment_table")
805
+
806
+ with gr.Row():
807
+ staff_download_file = gr.File(label="Download Coverage Table", visible=True)
808
+
809
+ with gr.TabItem("Hours Visualization"):
810
+ schedule_visualization = gr.Image(label="Hours by Day Visualization", elem_id="schedule_visualization")
811
+
812
+ # Define download functions
813
+ def create_download_link(df, filename="data.csv"):
814
+ """Create a CSV download link for a dataframe"""
815
+ if df is None or df.empty:
816
+ return None
817
+
818
+ csv_data = df.to_csv(index=False)
819
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.csv') as f:
820
+ f.write(csv_data)
821
+ return f.name
822
+
823
+ # Connect the button to the optimization function
824
+ optimize_btn.click(
825
+ fn=gradio_wrapper,
826
+ inputs=[
827
+ csv_input, beds_per_staff, max_hours_per_staff, hours_per_cycle,
828
+ rest_days_per_week, clinic_start_ampm, clinic_end_ampm,
829
+ overlap_time, max_start_time_change, exact_staff_count, overtime_percent
830
+ ],
831
+ outputs=[
832
+ staff_assignment_table, gantt_chart, csv_schedule, schedule_visualization,
833
+ staff_download_file, schedule_download_file
834
+ ]
835
+ )
836
+
837
+ # Launch the Gradio app
838
+ if __name__ == "__main__":
839
+ print("Starting Gradio interface...")
840
+ iface.launch(share=True)
841
+ print("Gradio interface launched")