| from dataclasses import dataclass, field
|
| from typing import List, Optional, Tuple, Dict
|
| import heapq
|
| import math
|
| import pandas as pd
|
| import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
| @dataclass
|
| class Job:
|
| id: str
|
| size_gb: float
|
| weight: float
|
| deadline_hr: Optional[float] = None
|
| meta: Dict = field(default_factory=dict)
|
|
|
| @dataclass
|
| class Device:
|
| id: str
|
| speed_gb_per_hr: float
|
| setup_overhead_hr: float = 0.0
|
| media_capacity_gb: Optional[float] = None
|
|
|
| @dataclass
|
| class Assignment:
|
| job_id: str
|
| device_id: str
|
| start_hr: float
|
| finish_hr: float
|
| ptime_hr: float
|
|
|
| @dataclass
|
| class ScheduleResult:
|
| assignments: List[Assignment]
|
| rejected_for_media: List[str]
|
| spilled_by_deadline: List[str]
|
| obj_weighted_completion: float
|
| makespan_hr: float
|
|
|
|
|
|
|
|
|
|
|
| def proc_time(job: Job, dev: Device) -> float:
|
| return job.size_gb / dev.speed_gb_per_hr + dev.setup_overhead_hr
|
|
|
| def best_device_index(job: Job, devices: List[Device]) -> Tuple[float, Device, float]:
|
| best = None
|
| for d in devices:
|
| p = proc_time(job, d)
|
| if p <= 0:
|
| continue
|
| idx = job.weight / p
|
| if (best is None) or (idx > best[0]):
|
| best = (idx, d, p)
|
| return best if best is not None else (0.0, devices[0], float("inf"))
|
|
|
| def greedy_media_pruning(jobs: List[Job], media_limit_gb: Optional[float]) -> Tuple[List[Job], List[Job]]:
|
| if media_limit_gb is None or math.isinf(media_limit_gb):
|
| return jobs, []
|
| ordered = sorted(jobs, key=lambda j: (j.weight / max(j.size_gb, 1e-9)), reverse=True)
|
| picked, dropped, used = [], [], 0.0
|
| for j in ordered:
|
| if used + j.size_gb <= media_limit_gb:
|
| picked.append(j)
|
| used += j.size_gb
|
| else:
|
| dropped.append(j)
|
| return picked, dropped
|
|
|
| def schedule_window(
|
| jobs: List[Job],
|
| devices: List[Device],
|
| window_hr: float,
|
| media_limit_gb: Optional[float] = None,
|
| honor_deadlines: bool = True,
|
| tie_break_edd: bool = True,
|
| ) -> ScheduleResult:
|
|
|
| selected, media_dropped = greedy_media_pruning(jobs, media_limit_gb)
|
|
|
| scored = []
|
| for j in selected:
|
| idx, best_dev, pbest = best_device_index(j, devices)
|
| scored.append((idx, j, pbest))
|
|
|
| if tie_break_edd:
|
| scored.sort(key=lambda t: (t[0], -(float("inf") if t[1].deadline_hr is None else -t[1].deadline_hr)), reverse=True)
|
| else:
|
| scored.sort(key=lambda t: t[0], reverse=True)
|
|
|
| heap = [(0.0, d.id, 0.0) for d in devices]
|
| dev_by_id = {d.id: d for d in devices}
|
|
|
| assignments: List[Assignment] = []
|
| spilled: List[str] = []
|
| wC_sum = 0.0
|
|
|
| for _, job, _ in scored:
|
| best_choice = None
|
| for idx_heap, (avail, dev_id, media_used) in enumerate(heap):
|
| d = dev_by_id[dev_id]
|
| p = proc_time(job, d)
|
| start = avail
|
| finish = start + p
|
|
|
| if d.media_capacity_gb is not None:
|
| if media_used + job.size_gb > d.media_capacity_gb:
|
| continue
|
|
|
| if (best_choice is None) or (finish < best_choice[0]):
|
| best_choice = (finish, idx_heap, start, d, p)
|
|
|
| if best_choice is None:
|
| spilled.append(job.id)
|
| continue
|
|
|
| finish, idx_heap, start, d, p = best_choice
|
| deadline = window_hr if honor_deadlines else None
|
| if job.deadline_hr is not None and honor_deadlines:
|
| deadline = min(deadline, job.deadline_hr) if deadline is not None else job.deadline_hr
|
| if (deadline is not None) and (finish > deadline):
|
| spilled.append(job.id)
|
| continue
|
|
|
| avail, dev_id, media_used = heap[idx_heap]
|
| heap[idx_heap] = (finish, dev_id, media_used + job.size_gb)
|
| heapq.heapify(heap)
|
|
|
| assignments.append(Assignment(
|
| job_id=job.id,
|
| device_id=d.id,
|
| start_hr=start,
|
| finish_hr=finish,
|
| ptime_hr=p
|
| ))
|
| wC_sum += job.weight * finish
|
|
|
| makespan = max((a.finish_hr for a in assignments), default=0.0)
|
| return ScheduleResult(
|
| assignments=sorted(assignments, key=lambda a: a.start_hr),
|
| rejected_for_media=[j.id for j in media_dropped],
|
| spilled_by_deadline=spilled,
|
| obj_weighted_completion=wC_sum,
|
| makespan_hr=makespan
|
| )
|
|
|
|
|
|
|
|
|
|
|
| DEVICES_DEFAULT = pd.DataFrame([
|
| {"id": "VTL_A", "speed_gb_per_hr": 800.0, "setup_overhead_hr": 0.05, "media_capacity_gb": 120_000.0},
|
| {"id": "FITA_B", "speed_gb_per_hr": 200.0, "setup_overhead_hr": 0.15, "media_capacity_gb": 40_000.0},
|
| {"id": "DISCO_C", "speed_gb_per_hr": 120.0, "setup_overhead_hr": 0.02, "media_capacity_gb": None},
|
| ])
|
|
|
| JOBS_DEFAULT = pd.DataFrame([
|
| {"id": "Oracle_FIN", "size_gb": 18_000.0, "weight": 8.0, "deadline_hr": 8.0},
|
| {"id": "SQL_A", "size_gb": 500.0, "weight": 2.0, "deadline_hr": 8.0},
|
| {"id": "SQL_B", "size_gb": 800.0, "weight": 2.0, "deadline_hr": 8.0},
|
| {"id": "MySQL_X", "size_gb": 120.0, "weight": 1.0, "deadline_hr": 8.0},
|
| {"id": "Oracle_HCM", "size_gb": 22_000.0, "weight": 8.0, "deadline_hr": 8.0},
|
| {"id": "Pg_ETL", "size_gb": 900.0, "weight": 3.0, "deadline_hr": 8.0},
|
| {"id": "Adabas_RPT", "size_gb": 6_000.0, "weight": 4.0, "deadline_hr": 8.0},
|
| ])
|
|
|
|
|
|
|
|
|
|
|
| def df_to_devices(df: pd.DataFrame) -> List[Device]:
|
| records = df.fillna(value={"media_capacity_gb": None}).to_dict(orient="records")
|
| devices = []
|
| for r in records:
|
| try:
|
| devices.append(Device(
|
| id=str(r["id"]).strip(),
|
| speed_gb_per_hr=float(r["speed_gb_per_hr"]),
|
| setup_overhead_hr=float(r.get("setup_overhead_hr", 0.0)),
|
| media_capacity_gb=None if r.get("media_capacity_gb", None) in [None, "", "None"] else float(r["media_capacity_gb"])
|
| ))
|
| except Exception as e:
|
| raise ValueError(f"Erro ao converter device {r}: {e}")
|
| if not devices:
|
| raise ValueError("Nenhum device válido informado.")
|
| return devices
|
|
|
| def df_to_jobs(df: pd.DataFrame) -> List[Job]:
|
| records = df.fillna(value={"deadline_hr": None}).to_dict(orient="records")
|
| jobs = []
|
| for r in records:
|
| try:
|
| jobs.append(Job(
|
| id=str(r["id"]).strip(),
|
| size_gb=float(r["size_gb"]),
|
| weight=float(r["weight"]),
|
| deadline_hr=None if r.get("deadline_hr", None) in [None, "", "None"] else float(r["deadline_hr"])
|
| ))
|
| except Exception as e:
|
| raise ValueError(f"Erro ao converter job {r}: {e}")
|
| if not jobs:
|
| raise ValueError("Nenhum job válido informado.")
|
| return jobs
|
|
|
| def run_schedule(devices_df, jobs_df, window_hr, media_limit_gb, honor_deadlines, tie_break_edd):
|
| devices = df_to_devices(devices_df)
|
| jobs = df_to_jobs(jobs_df)
|
|
|
| media_limit = None if (media_limit_gb is None or media_limit_gb == "" or float(media_limit_gb) <= 0) else float(media_limit_gb)
|
|
|
| result = schedule_window(
|
| jobs=jobs,
|
| devices=devices,
|
| window_hr=float(window_hr),
|
| media_limit_gb=media_limit,
|
| honor_deadlines=bool(honor_deadlines),
|
| tie_break_edd=bool(tie_break_edd)
|
| )
|
|
|
|
|
| df_assign = pd.DataFrame([{
|
| "job_id": a.job_id,
|
| "device_id": a.device_id,
|
| "start_hr": round(a.start_hr, 4),
|
| "finish_hr": round(a.finish_hr, 4),
|
| "ptime_hr": round(a.ptime_hr, 4),
|
| } for a in result.assignments])
|
|
|
|
|
| resumo = (
|
| f"Rejeitados por mídia: {result.rejected_for_media}\n"
|
| f"Spill por deadline: {result.spilled_by_deadline}\n"
|
| f"Σ w*C = {result.obj_weighted_completion:,.4f}\n"
|
| f"Makespan = {result.makespan_hr:.4f} h"
|
| )
|
|
|
| return df_assign, resumo
|
|
|
|
|
|
|
|
|
|
|
| with gr.Blocks(title="Scheduler de Backups (WSPT + List Scheduling)") as demo:
|
| gr.Markdown(
|
| """
|
| # Scheduler de Backups (WSPT + List Scheduling)
|
| Edite os **devices** e **jobs**, defina os parâmetros e clique em **Executar**.
|
| - Devices: `id`, `speed_gb_per_hr`, `setup_overhead_hr`, `media_capacity_gb`
|
| - Jobs: `id`, `size_gb`, `weight`, `deadline_hr`
|
| """
|
| )
|
| with gr.Row():
|
| with gr.Column():
|
| gr.Markdown("### Devices")
|
| devices_df = gr.Dataframe(
|
| value=DEVICES_DEFAULT,
|
| headers=list(DEVICES_DEFAULT.columns),
|
| datatype=["str", "number", "number", "number"],
|
| row_count=(3, "dynamic"),
|
| col_count=(4, "fixed"),
|
| wrap=True,
|
| interactive=True,
|
| label="Editar dispositivos"
|
| )
|
| with gr.Column():
|
| gr.Markdown("### Jobs")
|
| jobs_df = gr.Dataframe(
|
| value=JOBS_DEFAULT,
|
| headers=list(JOBS_DEFAULT.columns),
|
| datatype=["str", "number", "number", "number"],
|
| row_count=(7, "dynamic"),
|
| col_count=(4, "fixed"),
|
| wrap=True,
|
| interactive=True,
|
| label="Editar jobs"
|
| )
|
|
|
| with gr.Row():
|
| window_hr = gr.Number(value=8.0, label="Janela (horas)", precision=2)
|
| media_limit_gb = gr.Textbox(value="60000", label="Limite de mídia total (GB). Vazio/≤0 = sem limite")
|
| honor_deadlines = gr.Checkbox(value=True, label="Respeitar deadlines")
|
| tie_break_edd = gr.Checkbox(value=True, label="Desempate por EDD (menor deadline)")
|
|
|
| run_btn = gr.Button("Executar escalonamento")
|
|
|
| with gr.Row():
|
| out_df = gr.Dataframe(label="Assignments (Ordem e Tempos)", interactive=False)
|
| out_text = gr.Textbox(label="Resumo", lines=6)
|
|
|
| run_btn.click(
|
| fn=run_schedule,
|
| inputs=[devices_df, jobs_df, window_hr, media_limit_gb, honor_deadlines, tie_break_edd],
|
| outputs=[out_df, out_text]
|
| )
|
|
|
| if __name__ == "__main__":
|
| demo.launch()
|
|
|