File size: 6,619 Bytes
8ba58ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""
mock_data.py β€” Mock data generator for Nurse Rostering Demo

Generates:
  β€’ 20 ICU nurses with realistic Singaporean names
  β€’ A 2-week (14-day) roster with 3 shifts/day, 4 nurses/shift
  β€’ Exactly 80 of 84 shifts filled per week (4 unfilled/week β†’ 8 total gaps)
  β€’ No nurse exceeds 5 shifts/week or is double-booked on the same day
"""

from __future__ import annotations

import random
from dataclasses import dataclass, field
from datetime import date, timedelta
from typing import Optional

# ── Constants ─────────────────────────────────────────────────────────────────
SHIFTS = [
    ("Morning",  "08:00–16:00"),
    ("Afternoon", "16:00–00:00"),
    ("Night",    "00:00–08:00"),
]
NURSES_PER_SHIFT = 4
MAX_SHIFTS_PER_WEEK = 5
NUM_NURSES = 20
NUM_DAYS = 14
SHIFTS_PER_DAY = 3
TOTAL_SLOTS_PER_WEEK = NURSES_PER_SHIFT * SHIFTS_PER_DAY * 7  # 84
UNFILLED_PER_WEEK = 4  # intentionally leave 4 gaps per week

# Realistic Singaporean nurse names
NURSE_NAMES = [
    "Nurse Priya Nair",
    "Nurse Mei Ling Tan",
    "Nurse Aisha Binte Hassan",
    "Nurse Siti Nurhaliza",
    "Nurse Rachel Lim",
    "Nurse Kavitha Devi",
    "Nurse Nurul Izzah",
    "Nurse Chen Wei Ting",
    "Nurse Fatimah Zahra",
    "Nurse Amanda Koh",
    "Nurse Dewi Sari",
    "Nurse Jasmine Teo",
    "Nurse Lakshmi Rao",
    "Nurse Hazel Ong",
    "Nurse Nadiah Ismail",
    "Nurse Ying Xuan Lee",
    "Nurse Deepa Menon",
    "Nurse Sarah Tan",
    "Nurse Farah Abdullah",
    "Nurse Grace Wong",
]


@dataclass
class Nurse:
    id: int
    name: str
    phone: str  # mock SG number

    def __hash__(self):
        return self.id

    def __eq__(self, other):
        return isinstance(other, Nurse) and self.id == other.id


@dataclass
class ShiftSlot:
    """One shift on one day."""
    day: date
    shift_name: str       # Morning / Afternoon / Night
    shift_hours: str      # e.g. "08:00–16:00"
    assigned: list[Nurse] = field(default_factory=list)

    @property
    def is_filled(self) -> bool:
        return len(self.assigned) >= NURSES_PER_SHIFT

    @property
    def vacancies(self) -> int:
        return max(0, NURSES_PER_SHIFT - len(self.assigned))

    @property
    def key(self) -> str:
        return f"{self.day.isoformat()}|{self.shift_name}"


def generate_nurses() -> list[Nurse]:
    """Create 20 nurses with mock phone numbers."""
    nurses = []
    for i, name in enumerate(NURSE_NAMES[:NUM_NURSES]):
        phone = f"659{random.randint(1000_0000, 9999_9999)}"
        nurses.append(Nurse(id=i, name=name, phone=phone))
    return nurses


def generate_roster(
    nurses: list[Nurse],
    start_date: date | None = None,
    seed: int = 42,
) -> list[ShiftSlot]:
    """Build a 14-day roster with exactly 8 intentional gaps.

    Strategy per week (7 days):
      1. Create all 21 shift-slots (7 days Γ— 3 shifts).
      2. Need to fill 84 nurse-slots (21 Γ— 4 nurses each).
      3. Fill only 80 β†’ leave 4 random slots with 3 nurses instead of 4.
      4. Distribute using round-robin so no nurse > 5 shifts / week
         and no nurse works two shifts on the same day.
    """
    rng = random.Random(seed)

    if start_date is None:
        # Next Monday
        today = date.today()
        start_date = today + timedelta(days=(7 - today.weekday()) % 7 or 7)

    all_slots: list[ShiftSlot] = []

    for week_offset in range(2):
        week_start = start_date + timedelta(weeks=week_offset)

        # Build empty slots for this week
        week_slots: list[ShiftSlot] = []
        for d in range(7):
            day = week_start + timedelta(days=d)
            for shift_name, shift_hours in SHIFTS:
                week_slots.append(ShiftSlot(day=day, shift_name=shift_name, shift_hours=shift_hours))

        # Pick 4 slots that will be intentionally short-staffed (3 nurses instead of 4)
        gap_indices = set(rng.sample(range(len(week_slots)), UNFILLED_PER_WEEK))

        # Target nurse-slots to fill
        # full slot = 4, gap slot = 3
        target_per_slot = [
            NURSES_PER_SHIFT - 1 if i in gap_indices else NURSES_PER_SHIFT
            for i in range(len(week_slots))
        ]

        # Track per-nurse constraints
        nurse_week_count = {n.id: 0 for n in nurses}
        nurse_day_set: dict[int, set[date]] = {n.id: set() for n in nurses}

        # Fill each slot
        for slot_idx, slot in enumerate(week_slots):
            needed = target_per_slot[slot_idx]
            eligible = [
                n for n in nurses
                if nurse_week_count[n.id] < MAX_SHIFTS_PER_WEEK
                and slot.day not in nurse_day_set[n.id]
            ]
            rng.shuffle(eligible)
            chosen = eligible[:needed]
            slot.assigned = chosen
            for n in chosen:
                nurse_week_count[n.id] += 1
                nurse_day_set[n.id].add(slot.day)

        all_slots.extend(week_slots)

    return all_slots


# ── Convenience helpers ───────────────────────────────────────────────────────

def get_unfilled_slots(roster: list[ShiftSlot]) -> list[ShiftSlot]:
    """Return only the slots that have vacancies."""
    return [s for s in roster if not s.is_filled]


def week_number(slot: ShiftSlot, roster: list[ShiftSlot]) -> int:
    """1-based week number relative to the roster start."""
    roster_start = roster[0].day
    return (slot.day - roster_start).days // 7 + 1


def nurse_shifts_in_week(nurse: Nurse, roster: list[ShiftSlot], week: int) -> int:
    """Count how many shifts a nurse already has in a given week."""
    return sum(
        1 for s in roster
        if week_number(s, roster) == week and nurse in s.assigned
    )


def nurse_works_on_day(nurse: Nurse, roster: list[ShiftSlot], day: date) -> bool:
    """Check if a nurse is already assigned to any shift on a given day."""
    return any(
        s.day == day and nurse in s.assigned
        for s in roster
    )


def eligible_nurses_for_slot(
    slot: ShiftSlot,
    nurses: list[Nurse],
    roster: list[ShiftSlot],
) -> list[Nurse]:
    """Nurses who can fill a vacancy: not on that day, < 5 shifts that week."""
    week = week_number(slot, roster)
    return [
        n for n in nurses
        if n not in slot.assigned
        and not nurse_works_on_day(n, roster, slot.day)
        and nurse_shifts_in_week(n, roster, week) < MAX_SHIFTS_PER_WEEK
    ]