Spaces:
Sleeping
Sleeping
Subhash Vadaparthi commited on
Commit ·
21129f1
0
Parent(s):
Initial commit: Healthcare Appointment Scheduling RL Environment
Browse filesFiles changed (19)
- DockerfileAdded+17
- README.mdAdded+76
- app/__init__.pyAdded+1
- app/__pycache__/__init__.cpython-310.pycAdded
- app/__pycache__/__init__.cpython-313.pycAdded
- app/__pycache__/agent.cpython-310.pycAdded
- app/__pycache__/agent.cpython-313.pycAdded
- app/__pycache__/env.cpython-310.pycAdded
- app/__pycache__/env.cpython-313.pycAdded
- app/__pycache__/tasks.cpython-310.pycAdded
- app/__pycache__/tasks.cpython-313.pycAdded
- app/agent.pyAdded+57
- app/env.pyAdded+167
- app/main.pyAdded+76
- app/models.pyAdded+32
- app/tasks.pyAdded+64
- openenv.yamlAdded+24
- requirements.txtAdded+4
- test_env.pyAdded+42
1234567891011121314151617# Use an official Python runtime as a parent imageFROM python:3.9-slim
# Set the working directory in the containerWORKDIR /app
# Copy the current directory contents into the container at /appCOPY . /app
# Install any needed packages specified in requirements.txtRUN pip install --no-cache-dir -r requirements.txt
# Make port 7860 available to the world outside this containerEXPOSE 7860
# Run main.py when the container launchesCMD ["python", "app/main.py"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Healthcare Appointment Scheduling RL Environment
This project implements a complete OpenEnv-compatible reinforcement learning environment simulating a real-world hospital appointment booking system.
## Environment Design
The environment simulates a hospital with multiple doctors and patients. The goal is to efficiently schedule appointments while considering patient priorities, doctor availability, and patient preferences.
### Observation SpaceThe state is a dictionary containing:- `doctor_slots`: Availability of each doctor for each time slot.- `patients`: Information about patients (priority, preferred doctor, status).- `waiting_queue`: List of patient IDs currently waiting for an appointment.
### Action SpaceActions are dictionaries:- `type`: "book", "reschedule", "cancel", or "waitlist".- `patient_id`: ID of the patient.- `doctor_id`: ID of the doctor (required for "book" and "reschedule").- `slot_id`: ID of the time slot (required for "book" and "reschedule").
### Reward Function- **+1.0**: Successful booking.- **+0.2 bonus**: Booking with preferred doctor.- **+0.3**: Waitlisting a patient (partial progress).- **-1.0**: Conflicts (trying to book an occupied slot) or invalid actions.- **-0.2**: Cancellations.- **+0.5**: Successful rescheduling.
## Tasks & Grading
1. **Task 1 (Easy)**: Successfully book an appointment when slots are available.2. **Task 2 (Medium)**: Handle scheduling conflicts and rescheduling efficiently.3. **Task 3 (Hard)**: Optimize scheduling for multiple patients with different priorities (Priority 1 > Priority 2 > Priority 3).
The `/grader` endpoint returns a score between 0.0 and 1.0 for each task based on efficiency and priority fulfillment.
## Setup & Usage
### Local Development
1. Clone the repository.2. Install dependencies: ```bash pip install -r requirements.txt ```3. Run the FastAPI server: ```bash python app/main.py ```4. The API will be available at `http://localhost:7860`.
### Running with Docker
```bashdocker build -t healthcare-rl-env .docker run -p 7860:7860 healthcare-rl-env```
### Deployment
This environment is fully compatible with Hugging Face Spaces. Simply upload the files to a Space and select "Docker" configuration.
## API Endpoints
- `GET /`: Root endpoint.- `POST /reset`: Resets the environment.- `POST /step`: Performs an action.- `GET /state`: Gets current state.- `GET /tasks`: Lists all available tasks.- `GET /grader`: Returns scores for each task.- `GET /baseline`: Runs a rule-based baseline agent and returns its performance.
## License
MIT1# Initializing app module123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657from typing import Dict, Any, List
class BaselineAgent: """ Rule-based agent for appointment scheduling. Strategy: 1. Iterate through waiting queue. 2. Sort patients by priority. 3. Book the patient's preferred doctor if a slot is available. 4. If not available, book any available slot with any doctor. 5. If no slots, waitlist. """ def __init__(self, env): self.env = env
def select_action(self, obs: Dict[str, Any]) -> Dict[str, Any]: waiting_queue = obs.get("waiting_queue", []) if not waiting_queue: return {"type": "waitlist", "patient_id": -1}
patients = obs.get("patients", {}) doctor_slots = obs.get("doctor_slots", {}) # Sort waiting patients by priority (1 is highest) waiting_patients = [patients[pid] for pid in waiting_queue] waiting_patients.sort(key=lambda x: x["priority"]) for patient in waiting_patients: pid = patient["id"] preferred_doctor = patient["preferred_doctor"] # 1. Try preferred doctor if preferred_doctor in doctor_slots: for sid, available in enumerate(doctor_slots[preferred_doctor]): if available: return { "type": "book", "patient_id": pid, "doctor_id": preferred_doctor, "slot_id": sid } # 2. Try any other doctor for did, slots in doctor_slots.items(): if did == preferred_doctor: continue for sid, available in enumerate(slots): if available: return { "type": "book", "patient_id": pid, "doctor_id": did, "slot_id": sid }
# 3. No slots available, waitlist the first patient in queue return {"type": "waitlist", "patient_id": waiting_queue[0]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import randomfrom typing import Dict, List, Any, Optional
class HealthcareEnv: """ Healthcare Appointment Scheduling RL Environment. Simulates a hospital appointment booking system with doctors, patients, and time slots. """ def __init__(self): self.num_doctors = 3 self.num_slots = 5 # 5 slots per doctor (e.g., 9 AM to 2 PM) self.num_patients = 10 self.priorities = [1, 2, 3] # 1: High, 2: Medium, 3: Low self.reset()
def reset(self): """Resets the environment to initial state.""" # Doctors availability: {doctor_id: [slot_0_available, slot_1_available, ...]} # True means slot is available (free), False means booked. self.doctor_slots = {i: [True] * self.num_slots for i in range(self.num_doctors)} # Patients: {patient_id: {"priority": p, "preferred_doctor": d, "status": "waiting/booked/cancelled"}} self.patients = {} for i in range(self.num_patients): self.patients[i] = { "id": i, "priority": random.choice(self.priorities), "preferred_doctor": random.randint(0, self.num_doctors - 1), "status": "waiting", "booked_slot": None, "booked_doctor": None } self.waiting_queue = list(self.patients.keys()) self.current_step = 0 self.max_steps = self.num_patients * 2 # Allow some buffer for rescheduling self.done = False return self._get_obs()
def _get_obs(self) -> Dict[str, Any]: """Returns the current observation of the environment.""" return { "doctor_slots": self.doctor_slots, "patients": self.patients, "waiting_queue": self.waiting_queue, "current_step": self.current_step }
def state(self) -> Dict[str, Any]: """Returns the full state of the environment (OpenEnv API).""" return self._get_obs()
def step(self, action: Dict[str, Any]) -> tuple: """ Performs an action in the environment. Action format: {"type": "book/reschedule/cancel/waitlist", "patient_id": pid, "doctor_id": did, "slot_id": sid} """ if self.done: return self._get_obs(), 0, True, {"error": "Environment done"}
action_type = action.get("type") patient_id = action.get("patient_id") doctor_id = action.get("doctor_id") slot_id = action.get("slot_id")
reward = 0 info = {}
if action_type == "book": reward, info = self._handle_book(patient_id, doctor_id, slot_id) elif action_type == "reschedule": reward, info = self._handle_reschedule(patient_id, doctor_id, slot_id) elif action_type == "cancel": reward, info = self._handle_cancel(patient_id) elif action_type == "waitlist": reward, info = self._handle_waitlist(patient_id) else: reward = -1 info = {"error": "Invalid action type"}
self.current_step += 1 if self.current_step >= self.max_steps or not self.waiting_queue: self.done = True
return self._get_obs(), reward, self.done, info
def _handle_book(self, patient_id, doctor_id, slot_id) -> tuple: if patient_id not in self.patients or self.patients[patient_id]["status"] != "waiting": return -1, {"error": "Patient not in waiting queue or invalid ID"} if doctor_id not in self.doctor_slots or slot_id < 0 or slot_id >= self.num_slots: return -1, {"error": "Invalid doctor or slot ID"}
if not self.doctor_slots[doctor_id][slot_id]: return -1, {"error": "Slot already booked (conflict)"}
# Successful booking self.doctor_slots[doctor_id][slot_id] = False self.patients[patient_id].update({ "status": "booked", "booked_slot": slot_id, "booked_doctor": doctor_id }) if patient_id in self.waiting_queue: self.waiting_queue.remove(patient_id) # Reward based on priority and preference reward = 1.0 if self.patients[patient_id]["preferred_doctor"] == doctor_id: reward += 0.2 # Bonus for preferred doctor # Priority multiplier: higher priority (lower value) gets more weight? # Actually, let's just use fixed +1 and +0.3 for waitlist. return reward, {"status": "success"}
def _handle_reschedule(self, patient_id, doctor_id, slot_id) -> tuple: if patient_id not in self.patients or self.patients[patient_id]["status"] != "booked": return -1, {"error": "Patient not booked"}
if doctor_id not in self.doctor_slots or slot_id < 0 or slot_id >= self.num_slots: return -1, {"error": "Invalid doctor or slot ID"}
if not self.doctor_slots[doctor_id][slot_id]: return -1, {"error": "Slot already booked (conflict)"}
# Free old slot old_doctor = self.patients[patient_id]["booked_doctor"] old_slot = self.patients[patient_id]["booked_slot"] self.doctor_slots[old_doctor][old_slot] = True
# Book new slot self.doctor_slots[doctor_id][slot_id] = False self.patients[patient_id].update({ "booked_slot": slot_id, "booked_doctor": doctor_id }) return 0.5, {"status": "success"} # Partial reward for rescheduling
def _handle_cancel(self, patient_id) -> tuple: if patient_id not in self.patients or self.patients[patient_id]["status"] == "waiting": return -1, {"error": "Patient not booked"}
# Free slot if booked if self.patients[patient_id]["status"] == "booked": doctor_id = self.patients[patient_id]["booked_doctor"] slot_id = self.patients[patient_id]["booked_slot"] self.doctor_slots[doctor_id][slot_id] = True
self.patients[patient_id].update({ "status": "waiting", "booked_slot": None, "booked_doctor": None }) if patient_id not in self.waiting_queue: self.waiting_queue.append(patient_id) return -0.2, {"status": "cancelled"} # Penalty for cancellation
def _handle_waitlist(self, patient_id) -> tuple: if patient_id not in self.patients or self.patients[patient_id]["status"] != "waiting": return -1, {"error": "Patient not in waiting or already booked"} # Just keep them in waiting queue, maybe prioritize later? # In this simple model, waitlist action is like "skip for now" return 0.3, {"status": "waitlisted"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576from fastapi import FastAPI, HTTPExceptionfrom app.env import HealthcareEnvfrom app.agent import BaselineAgentfrom app.tasks import TASKS, TaskGraderfrom app.models import Action, StepResponse, ResetResponse, StateResponse, TaskResponse, GraderResponse, BaselineResponsefrom typing import List, Dict, Any
app = FastAPI(title="Healthcare Appointment Scheduling RL Environment")
# Global environment instanceenv = HealthcareEnv()
@app.get("/")def read_root(): return {"message": "Healthcare Appointment Scheduling RL Environment API"}
@app.post("/reset", response_model=ResetResponse)def reset_env(): obs = env.reset() return {"obs": obs}
@app.post("/step", response_model=StepResponse)def step_env(action: Action): obs, reward, done, info = env.step(action.dict()) return { "obs": obs, "reward": reward, "done": done, "info": info }
@app.get("/state", response_model=StateResponse)def get_state(): return {"state": env.state()}
@app.get("/tasks", response_model=List[TaskResponse])def list_tasks(): return [task.__dict__ for task in TASKS]
@app.get("/grader", response_model=GraderResponse)def get_grader_scores(): grader = TaskGrader(env) return { "task_scores": { "task_1": grader.grade_task_1(), "task_2": grader.grade_task_2(), "task_3": grader.grade_task_3() } }
@app.get("/baseline", response_model=BaselineResponse)def run_baseline(): """ Runs the rule-based baseline agent and returns scores. """ env.reset() agent = BaselineAgent(env) observations = [] while not env.done: obs = env._get_obs() observations.append(obs) action = agent.select_action(obs) env.step(action) grader = TaskGrader(env) return { "task_scores": { "task_1": grader.grade_task_1(), "task_2": grader.grade_task_2(), "task_3": grader.grade_task_3() }, "observations": observations }
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)1234567891011121314151617181920212223242526272829303132from pydantic import BaseModelfrom typing import Dict, Any, List, Optional
class Action(BaseModel): type: str # book/reschedule/cancel/waitlist patient_id: int doctor_id: Optional[int] = None slot_id: Optional[int] = None
class StepResponse(BaseModel): obs: Dict[str, Any] reward: float done: bool info: Dict[str, Any]
class ResetResponse(BaseModel): obs: Dict[str, Any]
class StateResponse(BaseModel): state: Dict[str, Any]
class TaskResponse(BaseModel): name: str difficulty: str description: str
class GraderResponse(BaseModel): task_scores: Dict[str, float]
class BaselineResponse(BaseModel): task_scores: Dict[str, float] observations: List[Dict[str, Any]]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from typing import List, Dict, Any
class Task: def __init__(self, name: str, difficulty: str, description: str): self.name = name self.difficulty = difficulty self.description = description
class TaskGrader: """ Grader for Healthcare Scheduling Tasks. Returns a score between 0.0 and 1.0. """ def __init__(self, env): self.env = env
def grade_task_1(self) -> float: """ Task 1 (Easy): successfully book an appointment when slots are available. Score based on number of waiting patients booked. """ booked_count = sum(1 for p in self.env.patients.values() if p["status"] == "booked") total_patients = len(self.env.patients) return min(1.0, booked_count / (total_patients * 0.5)) # 50% booking is enough for full score here
def grade_task_2(self) -> float: """ Task 2 (Medium): Handle scheduling conflicts and rescheduling. Score based on rescheduling success and slot utilization. """ # We can track successful reschedules in the info dict if we want, # but for simplicity, let's use efficiency. booked_count = sum(1 for p in self.env.patients.values() if p["status"] == "booked") # In Task 2, we expect some rescheduling to happen. return min(1.0, booked_count / (len(self.env.patients) * 0.7))
def grade_task_3(self) -> float: """ Task 3 (Hard): Optimize scheduling for multiple patients with different priorities. Score based on priority completion. Priority 1 should be booked FIRST. """ p1_total = sum(1 for p in self.env.patients.values() if p["priority"] == 1) p1_booked = sum(1 for p in self.env.patients.values() if p["priority"] == 1 and p["status"] == "booked") p2_total = sum(1 for p in self.env.patients.values() if p["priority"] == 2) p2_booked = sum(1 for p in self.env.patients.values() if p["priority"] == 2 and p["status"] == "booked") if p1_total == 0: p1_score = 1.0 else: p1_score = p1_booked / p1_total
if p2_total == 0: p2_score = 1.0 else: p2_score = p2_booked / p2_total return (p1_score * 0.7) + (p2_score * 0.3)
TASKS = [ Task("Task 1", "Easy", "Successfully book an appointment when slots are available."), Task("Task 2", "Medium", "Handle scheduling conflicts and rescheduling."), Task("Task 3", "Hard", "Optimize scheduling for multiple patients with different priorities.")]123456789101112131415161718192021222324version: "1.0"metadata: name: "Healthcare Appointment Scheduling" description: "A reinforcement learning environment simulating a hospital appointment booking system." version: "1.0.0" author: "Antigravity AI" tags: ["healthcare", "scheduling", "optimization", "RL"]
environment: type: "discrete" observation_space: type: "dict" description: "Contains doctor slots, patient info, and waiting queue." action_space: type: "dict" description: "Actions include book, reschedule, cancel, and waitlist."
endpoints: reset: "/reset" step: "/step" state: "/state" tasks: "/tasks" grader: "/grader" baseline: "/baseline"1234fastapiuvicornpydantictyping-extensions123456789101112131415161718192021222324252627282930313233343536373839404142import sysimport ossys.path.append('d:/Meta_Hackathon')
from app.env import HealthcareEnvfrom app.agent import BaselineAgentfrom app.tasks import TaskGrader
def test(): print("Testing Healthcare RL Environment...") env = HealthcareEnv() obs = env.reset() print("Reset successful.") agent = BaselineAgent(env) print("Agent initialized.") steps = 0 while not env.done: action = agent.select_action(obs) obs, reward, done, info = env.step(action) steps += 1 print(f"Environment finished in {steps} steps.") grader = TaskGrader(env) scores = { "task_1": grader.grade_task_1(), "task_2": grader.grade_task_2(), "task_3": grader.grade_task_3() } print(f"Grader Scores: {scores}") assert scores["task_1"] > 0 assert scores["task_2"] > 0 assert scores["task_3"] > 0 print("Verification successful!")
if __name__ == "__main__": test()DockerfileAdded+17
README.mdAdded+76
app/__init__.pyAdded+1
app/__pycache__/__init__.cpython-310.pycAdded
app/__pycache__/__init__.cpython-313.pycAdded
app/__pycache__/agent.cpython-310.pycAdded
app/__pycache__/agent.cpython-313.pycAdded
app/__pycache__/env.cpython-310.pycAdded
app/__pycache__/env.cpython-313.pycAdded
app/__pycache__/tasks.cpython-310.pycAdded
app/__pycache__/tasks.cpython-313.pycAdded
app/agent.pyAdded+57
app/env.pyAdded+167
app/main.pyAdded+76
app/models.pyAdded+32
app/tasks.pyAdded+64
openenv.yamlAdded+24
requirements.txtAdded+4
test_env.pyAdded+42