tamerpedro commited on
Commit
4dba648
·
verified ·
1 Parent(s): 42f1886

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +22 -3
  2. app.py +301 -0
  3. requirements.txt +2 -0
README.md CHANGED
@@ -1,3 +1,22 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Scheduler de Backups (WSPT + List Scheduling)
2
+
3
+ Este Space implementa um escalonador heurístico para backups:
4
+ - Pré-seleção gulosa por mídia total (peso/GB)
5
+ - Ordenação por WSPT (peso/tempo de processamento)
6
+ - Alocação com list scheduling em múltiplos devices
7
+
8
+ ## Como usar
9
+ 1. Edite as tabelas **Devices** e **Jobs**:
10
+ - Devices: `id`, `speed_gb_per_hr`, `setup_overhead_hr`, `media_capacity_gb`
11
+ - Jobs: `id`, `size_gb`, `weight`, `deadline_hr`
12
+ 2. Informe a **janela (horas)** e, se desejar, o **limite de mídia total (GB)**.
13
+ 3. Clique em **Executar escalonamento**.
14
+
15
+ ## Saídas
16
+ - **Assignments**: ordem de execução por device, com `start_hr`, `finish_hr`, `ptime_hr`.
17
+ - **Resumo**: rejeitados por mídia, spill por deadline, `Σ w*C`, e `makespan`.
18
+
19
+ ## Observações
20
+ - `media_capacity_gb` em branco (ou `None`) = sem limite por device.
21
+ - `deadline_hr` em branco = sem deadline específico para o job (usa só a janela global).
22
+ - `limite de mídia total` vazio ou ≤ 0 = sem limite global.
app.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import List, Optional, Tuple, Dict
3
+ import heapq
4
+ import math
5
+ import pandas as pd
6
+ import gradio as gr
7
+
8
+ # =========================
9
+ # MODELOS DE DADOS
10
+ # =========================
11
+
12
+ @dataclass
13
+ class Job:
14
+ id: str
15
+ size_gb: float # tamanho a ser copiado
16
+ weight: float # criticidade (peso)
17
+ deadline_hr: Optional[float] = None # fim de janela (opcional)
18
+ meta: Dict = field(default_factory=dict)
19
+
20
+ @dataclass
21
+ class Device:
22
+ id: str
23
+ speed_gb_per_hr: float # throughput efetivo (GB/h)
24
+ setup_overhead_hr: float = 0.0 # overhead fixo por job
25
+ media_capacity_gb: Optional[float] = None # capacidade por janela (GB)
26
+
27
+ @dataclass
28
+ class Assignment:
29
+ job_id: str
30
+ device_id: str
31
+ start_hr: float
32
+ finish_hr: float
33
+ ptime_hr: float # tempo efetivo de processamento
34
+
35
+ @dataclass
36
+ class ScheduleResult:
37
+ assignments: List[Assignment]
38
+ rejected_for_media: List[str]
39
+ spilled_by_deadline: List[str]
40
+ obj_weighted_completion: float
41
+ makespan_hr: float
42
+
43
+ # =========================
44
+ # NÚCLEO DO ALGORITMO
45
+ # =========================
46
+
47
+ def proc_time(job: Job, dev: Device) -> float:
48
+ return job.size_gb / dev.speed_gb_per_hr + dev.setup_overhead_hr
49
+
50
+ def best_device_index(job: Job, devices: List[Device]) -> Tuple[float, Device, float]:
51
+ best = None
52
+ for d in devices:
53
+ p = proc_time(job, d)
54
+ if p <= 0:
55
+ continue
56
+ idx = job.weight / p
57
+ if (best is None) or (idx > best[0]):
58
+ best = (idx, d, p)
59
+ return best if best is not None else (0.0, devices[0], float("inf"))
60
+
61
+ def greedy_media_pruning(jobs: List[Job], media_limit_gb: Optional[float]) -> Tuple[List[Job], List[Job]]:
62
+ if media_limit_gb is None or math.isinf(media_limit_gb):
63
+ return jobs, []
64
+ ordered = sorted(jobs, key=lambda j: (j.weight / max(j.size_gb, 1e-9)), reverse=True)
65
+ picked, dropped, used = [], [], 0.0
66
+ for j in ordered:
67
+ if used + j.size_gb <= media_limit_gb:
68
+ picked.append(j)
69
+ used += j.size_gb
70
+ else:
71
+ dropped.append(j)
72
+ return picked, dropped
73
+
74
+ def schedule_window(
75
+ jobs: List[Job],
76
+ devices: List[Device],
77
+ window_hr: float,
78
+ media_limit_gb: Optional[float] = None,
79
+ honor_deadlines: bool = True,
80
+ tie_break_edd: bool = True,
81
+ ) -> ScheduleResult:
82
+
83
+ selected, media_dropped = greedy_media_pruning(jobs, media_limit_gb)
84
+
85
+ scored = []
86
+ for j in selected:
87
+ idx, best_dev, pbest = best_device_index(j, devices)
88
+ scored.append((idx, j, pbest))
89
+
90
+ if tie_break_edd:
91
+ scored.sort(key=lambda t: (t[0], -(float("inf") if t[1].deadline_hr is None else -t[1].deadline_hr)), reverse=True)
92
+ else:
93
+ scored.sort(key=lambda t: t[0], reverse=True)
94
+
95
+ heap = [(0.0, d.id, 0.0) for d in devices] # (finish_time, device_id, media_used_gb)
96
+ dev_by_id = {d.id: d for d in devices}
97
+
98
+ assignments: List[Assignment] = []
99
+ spilled: List[str] = []
100
+ wC_sum = 0.0
101
+
102
+ for _, job, _ in scored:
103
+ best_choice = None
104
+ for idx_heap, (avail, dev_id, media_used) in enumerate(heap):
105
+ d = dev_by_id[dev_id]
106
+ p = proc_time(job, d)
107
+ start = avail
108
+ finish = start + p
109
+
110
+ if d.media_capacity_gb is not None:
111
+ if media_used + job.size_gb > d.media_capacity_gb:
112
+ continue
113
+
114
+ if (best_choice is None) or (finish < best_choice[0]):
115
+ best_choice = (finish, idx_heap, start, d, p)
116
+
117
+ if best_choice is None:
118
+ spilled.append(job.id)
119
+ continue
120
+
121
+ finish, idx_heap, start, d, p = best_choice
122
+ deadline = window_hr if honor_deadlines else None
123
+ if job.deadline_hr is not None and honor_deadlines:
124
+ deadline = min(deadline, job.deadline_hr) if deadline is not None else job.deadline_hr
125
+ if (deadline is not None) and (finish > deadline):
126
+ spilled.append(job.id)
127
+ continue
128
+
129
+ avail, dev_id, media_used = heap[idx_heap]
130
+ heap[idx_heap] = (finish, dev_id, media_used + job.size_gb)
131
+ heapq.heapify(heap)
132
+
133
+ assignments.append(Assignment(
134
+ job_id=job.id,
135
+ device_id=d.id,
136
+ start_hr=start,
137
+ finish_hr=finish,
138
+ ptime_hr=p
139
+ ))
140
+ wC_sum += job.weight * finish
141
+
142
+ makespan = max((a.finish_hr for a in assignments), default=0.0)
143
+ return ScheduleResult(
144
+ assignments=sorted(assignments, key=lambda a: a.start_hr),
145
+ rejected_for_media=[j.id for j in media_dropped],
146
+ spilled_by_deadline=spilled,
147
+ obj_weighted_completion=wC_sum,
148
+ makespan_hr=makespan
149
+ )
150
+
151
+ # =========================
152
+ # DADOS EXEMPLO (pré-carregados)
153
+ # =========================
154
+
155
+ DEVICES_DEFAULT = pd.DataFrame([
156
+ {"id": "VTL_A", "speed_gb_per_hr": 800.0, "setup_overhead_hr": 0.05, "media_capacity_gb": 120_000.0},
157
+ {"id": "FITA_B", "speed_gb_per_hr": 200.0, "setup_overhead_hr": 0.15, "media_capacity_gb": 40_000.0},
158
+ {"id": "DISCO_C", "speed_gb_per_hr": 120.0, "setup_overhead_hr": 0.02, "media_capacity_gb": None},
159
+ ])
160
+
161
+ JOBS_DEFAULT = pd.DataFrame([
162
+ {"id": "Oracle_FIN", "size_gb": 18_000.0, "weight": 8.0, "deadline_hr": 8.0},
163
+ {"id": "SQL_A", "size_gb": 500.0, "weight": 2.0, "deadline_hr": 8.0},
164
+ {"id": "SQL_B", "size_gb": 800.0, "weight": 2.0, "deadline_hr": 8.0},
165
+ {"id": "MySQL_X", "size_gb": 120.0, "weight": 1.0, "deadline_hr": 8.0},
166
+ {"id": "Oracle_HCM", "size_gb": 22_000.0, "weight": 8.0, "deadline_hr": 8.0},
167
+ {"id": "Pg_ETL", "size_gb": 900.0, "weight": 3.0, "deadline_hr": 8.0},
168
+ {"id": "Adabas_RPT", "size_gb": 6_000.0, "weight": 4.0, "deadline_hr": 8.0},
169
+ ])
170
+
171
+ # =========================
172
+ # UTILITÁRIOS DE CONVERSÃO
173
+ # =========================
174
+
175
+ def df_to_devices(df: pd.DataFrame) -> List[Device]:
176
+ records = df.fillna(value={"media_capacity_gb": None}).to_dict(orient="records")
177
+ devices = []
178
+ for r in records:
179
+ try:
180
+ devices.append(Device(
181
+ id=str(r["id"]).strip(),
182
+ speed_gb_per_hr=float(r["speed_gb_per_hr"]),
183
+ setup_overhead_hr=float(r.get("setup_overhead_hr", 0.0)),
184
+ media_capacity_gb=None if r.get("media_capacity_gb", None) in [None, "", "None"] else float(r["media_capacity_gb"])
185
+ ))
186
+ except Exception as e:
187
+ raise ValueError(f"Erro ao converter device {r}: {e}")
188
+ if not devices:
189
+ raise ValueError("Nenhum device válido informado.")
190
+ return devices
191
+
192
+ def df_to_jobs(df: pd.DataFrame) -> List[Job]:
193
+ records = df.fillna(value={"deadline_hr": None}).to_dict(orient="records")
194
+ jobs = []
195
+ for r in records:
196
+ try:
197
+ jobs.append(Job(
198
+ id=str(r["id"]).strip(),
199
+ size_gb=float(r["size_gb"]),
200
+ weight=float(r["weight"]),
201
+ deadline_hr=None if r.get("deadline_hr", None) in [None, "", "None"] else float(r["deadline_hr"])
202
+ ))
203
+ except Exception as e:
204
+ raise ValueError(f"Erro ao converter job {r}: {e}")
205
+ if not jobs:
206
+ raise ValueError("Nenhum job válido informado.")
207
+ return jobs
208
+
209
+ def run_schedule(devices_df, jobs_df, window_hr, media_limit_gb, honor_deadlines, tie_break_edd):
210
+ devices = df_to_devices(devices_df)
211
+ jobs = df_to_jobs(jobs_df)
212
+
213
+ media_limit = None if (media_limit_gb is None or media_limit_gb == "" or float(media_limit_gb) <= 0) else float(media_limit_gb)
214
+
215
+ result = schedule_window(
216
+ jobs=jobs,
217
+ devices=devices,
218
+ window_hr=float(window_hr),
219
+ media_limit_gb=media_limit,
220
+ honor_deadlines=bool(honor_deadlines),
221
+ tie_break_edd=bool(tie_break_edd)
222
+ )
223
+
224
+ # Tabela de assignments
225
+ df_assign = pd.DataFrame([{
226
+ "job_id": a.job_id,
227
+ "device_id": a.device_id,
228
+ "start_hr": round(a.start_hr, 4),
229
+ "finish_hr": round(a.finish_hr, 4),
230
+ "ptime_hr": round(a.ptime_hr, 4),
231
+ } for a in result.assignments])
232
+
233
+ # Resumos
234
+ resumo = (
235
+ f"Rejeitados por mídia: {result.rejected_for_media}\n"
236
+ f"Spill por deadline: {result.spilled_by_deadline}\n"
237
+ f"Σ w*C = {result.obj_weighted_completion:,.4f}\n"
238
+ f"Makespan = {result.makespan_hr:.4f} h"
239
+ )
240
+
241
+ return df_assign, resumo
242
+
243
+ # =========================
244
+ # UI GRADIO
245
+ # =========================
246
+
247
+ with gr.Blocks(title="Scheduler de Backups (WSPT + List Scheduling)") as demo:
248
+ gr.Markdown(
249
+ """
250
+ # Scheduler de Backups (WSPT + List Scheduling)
251
+ Edite os **devices** e **jobs**, defina os parâmetros e clique em **Executar**.
252
+ - Devices: `id`, `speed_gb_per_hr`, `setup_overhead_hr`, `media_capacity_gb`
253
+ - Jobs: `id`, `size_gb`, `weight`, `deadline_hr`
254
+ """
255
+ )
256
+ with gr.Row():
257
+ with gr.Column():
258
+ gr.Markdown("### Devices")
259
+ devices_df = gr.Dataframe(
260
+ value=DEVICES_DEFAULT,
261
+ headers=list(DEVICES_DEFAULT.columns),
262
+ datatype=["str", "number", "number", "number"],
263
+ row_count=(3, "dynamic"),
264
+ col_count=(4, "fixed"),
265
+ wrap=True,
266
+ interactive=True,
267
+ label="Editar dispositivos"
268
+ )
269
+ with gr.Column():
270
+ gr.Markdown("### Jobs")
271
+ jobs_df = gr.Dataframe(
272
+ value=JOBS_DEFAULT,
273
+ headers=list(JOBS_DEFAULT.columns),
274
+ datatype=["str", "number", "number", "number"],
275
+ row_count=(7, "dynamic"),
276
+ col_count=(4, "fixed"),
277
+ wrap=True,
278
+ interactive=True,
279
+ label="Editar jobs"
280
+ )
281
+
282
+ with gr.Row():
283
+ window_hr = gr.Number(value=8.0, label="Janela (horas)", precision=2)
284
+ media_limit_gb = gr.Textbox(value="60000", label="Limite de mídia total (GB). Vazio/≤0 = sem limite")
285
+ honor_deadlines = gr.Checkbox(value=True, label="Respeitar deadlines")
286
+ tie_break_edd = gr.Checkbox(value=True, label="Desempate por EDD (menor deadline)")
287
+
288
+ run_btn = gr.Button("Executar escalonamento")
289
+
290
+ with gr.Row():
291
+ out_df = gr.Dataframe(label="Assignments (Ordem e Tempos)", interactive=False)
292
+ out_text = gr.Textbox(label="Resumo", lines=6)
293
+
294
+ run_btn.click(
295
+ fn=run_schedule,
296
+ inputs=[devices_df, jobs_df, window_hr, media_limit_gb, honor_deadlines, tie_break_edd],
297
+ outputs=[out_df, out_text]
298
+ )
299
+
300
+ if __name__ == "__main__":
301
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ gradio>=4.20.0
2
+ pandas>=2.0.0