File size: 11,599 Bytes
3dfd4ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
from __future__ import annotations

from collections import defaultdict

from src.domain import (
    AssignmentInstance,
    Family,
    InventoryInstance,
    ScheduleInstance,
    Solution,
    ValidationIssue,
    ValidationReport,
    parse_instance,
)


def _issue(code: str, message: str, entity_id: str | None = None, passed: bool = False) -> ValidationIssue:
    return ValidationIssue(code=code, message=message, entity_id=entity_id, passed=passed)


def validate_schema(family: Family | str, payload: dict) -> ValidationReport:
    issues: list[ValidationIssue] = []
    checked = ["schema", "ids", "values"]
    try:
        instance = parse_instance(family, payload)
    except Exception as exc:
        return ValidationReport(ok=False, issues=[_issue("schema", f"schema rejected: {exc}")], checked=checked)

    if isinstance(instance, InventoryInstance):
        ids = [sku.sku_id for sku in instance.skus]
        if len(ids) != len(set(ids)):
            issues.append(_issue("ids", "duplicate SKU ids"))
        if not instance.skus:
            issues.append(_issue("schema", "inventory needs at least one SKU"))
        for sku in instance.skus:
            if len(sku.demand) != instance.periods:
                issues.append(_issue("values", f"{sku.sku_id} demand length must equal periods", sku.sku_id))
            if any(value < 0 for value in sku.demand):
                issues.append(_issue("values", f"{sku.sku_id} demand must be non-negative", sku.sku_id))
    elif isinstance(instance, AssignmentInstance):
        if not instance.tasks or not instance.agents:
            issues.append(_issue("schema", "assignment needs tasks and agents"))
        task_ids = [task.task_id for task in instance.tasks]
        agent_ids = [agent.agent_id for agent in instance.agents]
        if len(task_ids) != len(set(task_ids)) or len(agent_ids) != len(set(agent_ids)):
            issues.append(_issue("ids", "duplicate task or agent ids"))
        known = {(task.task_id, agent.agent_id) for task in instance.tasks for agent in instance.agents}
        for row in instance.costs:
            if (row.task_id, row.agent_id) not in known:
                issues.append(_issue("references", f"cost for unknown pair {row.task_id}/{row.agent_id}"))
    else:
        job_ids = [job.job_id for job in instance.jobs]
        if len(job_ids) != len(set(job_ids)):
            issues.append(_issue("ids", "duplicate job ids"))
        if not instance.machines or not instance.jobs:
            issues.append(_issue("schema", "scheduling needs jobs and machines"))
        seen = set()
        for edge in instance.precedences:
            if edge.before not in job_ids or edge.after not in job_ids:
                issues.append(_issue("references", f"precedence {edge.before}->{edge.after} is unknown"))
            if edge.before == edge.after:
                issues.append(_issue("values", f"self precedence on {edge.before}", edge.before))
            pair = (edge.before, edge.after)
            if pair in seen:
                continue
            seen.add(pair)
        if _has_cycle(instance.precedences):
            issues.append(_issue("values", "precedence graph has a cycle"))
    return ValidationReport(ok=not issues, issues=issues, checked=checked)


def _has_cycle(edges) -> bool:
    graph: dict[str, list[str]] = defaultdict(list)
    nodes: set[str] = set()
    for edge in edges:
        graph[edge.before].append(edge.after)
        nodes.add(edge.before)
        nodes.add(edge.after)
    state: dict[str, int] = {}

    def visit(node: str) -> bool:
        state[node] = 1
        for nxt in graph.get(node, []):
            if state.get(nxt) == 1:
                return True
            if state.get(nxt, 0) == 0 and visit(nxt):
                return True
        state[node] = 2
        return False

    return any(state.get(node, 0) == 0 and visit(node) for node in nodes)


def validate_solution(family: Family | str, payload: dict, solution: Solution | dict) -> ValidationReport:
    family = Family(family)
    schema_report = validate_schema(family, payload)
    if not schema_report.ok:
        return schema_report
    instance = parse_instance(family, payload)
    if not isinstance(solution, Solution):
        solution = Solution.model_validate(solution)
    if family == Family.INVENTORY:
        return _validate_inventory(instance, solution)
    if family == Family.ASSIGNMENT:
        return _validate_assignment(instance, solution)
    return _validate_schedule(instance, solution)


def _validate_inventory(instance: InventoryInstance, solution: Solution) -> ValidationReport:
    issues: list[ValidationIssue] = []
    checked = ["pack", "budget", "balance", "capacity", "cover", "objective"]
    qty = {(row.sku_id, int(row.period)): int(row.qty) for row in solution.orders}
    spend = 0
    hold_cost = 0
    short_cost = 0
    stock = {sku.sku_id: sku.initial_stock for sku in instance.skus}
    for t in range(1, instance.periods + 1):
        ending = 0
        for sku in instance.skus:
            order = int(qty.get((sku.sku_id, t), 0))
            if order < 0:
                issues.append(_issue("values", f"negative order {sku.sku_id}@{t}", sku.sku_id))
            if sku.pack_size and order % sku.pack_size != 0:
                issues.append(_issue("pack", f"{sku.sku_id}@{t} qty {order} is not a multiple of pack {sku.pack_size}", sku.sku_id))
            spend += order * sku.unit_cost
            demand = int(sku.demand[t - 1])
            available = stock[sku.sku_id] + order
            sold = min(available, demand)
            short = demand - sold
            stock[sku.sku_id] = available - sold
            if stock[sku.sku_id] < 0:
                issues.append(_issue("balance", f"negative inventory {sku.sku_id}@{t}", sku.sku_id))
            if instance.cover_required and short:
                issues.append(_issue("cover", f"{sku.sku_id}@{t} shortage {short} while cover is required", sku.sku_id))
            ending += stock[sku.sku_id]
            hold_cost += stock[sku.sku_id] * sku.holding_cost
            short_cost += short * sku.shortage_cost
        if ending > instance.warehouse_capacity:
            issues.append(_issue("capacity", f"period {t} inventory {ending} exceeds capacity {instance.warehouse_capacity}"))
    if spend > instance.budget:
        issues.append(_issue("budget", f"purchase {spend} exceeds budget {instance.budget}"))
    objective = float(spend + hold_cost + short_cost)
    return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=objective)


def _validate_assignment(instance: AssignmentInstance, solution: Solution) -> ValidationReport:
    issues: list[ValidationIssue] = []
    checked = ["unique", "eligible", "capacity", "required", "objective"]
    seen_tasks: set[str] = set()
    load: dict[str, int] = defaultdict(int)
    cost_map = instance.cost_map()
    agents = {agent.agent_id: agent for agent in instance.agents}
    tasks = {task.task_id: task for task in instance.tasks}
    spend = 0
    for row in solution.assignments:
        if row.task_id in seen_tasks:
            issues.append(_issue("unique", f"task {row.task_id} assigned more than once", row.task_id))
        seen_tasks.add(row.task_id)
        task = tasks.get(row.task_id)
        agent = agents.get(row.agent_id)
        if task is None or agent is None:
            issues.append(_issue("references", f"unknown pair {row.task_id}/{row.agent_id}", row.task_id))
            continue
        if not instance.eligible(task, agent):
            issues.append(_issue("eligible", f"{row.task_id} is not eligible for {row.agent_id}", row.task_id))
        if (row.task_id, row.agent_id) not in cost_map:
            issues.append(_issue("references", f"no cost for {row.task_id}/{row.agent_id}", row.task_id))
        else:
            spend += cost_map[(row.task_id, row.agent_id)]
        load[row.agent_id] += task.size
    for agent in instance.agents:
        if load[agent.agent_id] > agent.capacity:
            issues.append(_issue("capacity", f"{agent.agent_id} load {load[agent.agent_id]} exceeds {agent.capacity}", agent.agent_id))
    leftover = set(solution.unassigned)
    for task in instance.tasks:
        assigned = task.task_id in seen_tasks
        if task.required and not assigned:
            issues.append(_issue("required", f"required task {task.task_id} is unassigned", task.task_id))
        if not assigned:
            leftover.add(task.task_id)
            spend += task.penalty
        if assigned and task.task_id in leftover:
            leftover.discard(task.task_id)
    return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=float(spend))


def _validate_schedule(instance: ScheduleInstance, solution: Solution) -> ValidationReport:
    issues: list[ValidationIssue] = []
    checked = ["unique", "eligible", "release", "overlap", "precedence", "hard_due", "duration", "objective"]
    jobs = {job.job_id: job for job in instance.jobs}
    seen: set[str] = set()
    by_machine: dict[str, list[tuple[int, int, str]]] = defaultdict(list)
    ends: dict[str, int] = {}
    starts: dict[str, int] = {}
    tardy = 0
    for row in solution.starts:
        if row.job_id in seen:
            issues.append(_issue("unique", f"job {row.job_id} starts more than once", row.job_id))
        seen.add(row.job_id)
        job = jobs.get(row.job_id)
        if job is None:
            issues.append(_issue("references", f"unknown job {row.job_id}", row.job_id))
            continue
        if row.machine_id not in instance.machines:
            issues.append(_issue("references", f"unknown machine {row.machine_id}", row.job_id))
        if job.machine_eligible and row.machine_id not in set(job.machine_eligible):
            issues.append(_issue("eligible", f"{row.job_id} cannot use {row.machine_id}", row.job_id))
        if row.start < job.release:
            issues.append(_issue("release", f"{row.job_id} starts at {row.start} before release {job.release}", row.job_id))
        if row.end - row.start != job.duration:
            issues.append(_issue("duration", f"{row.job_id} duration {row.end - row.start} != {job.duration}", row.job_id))
        if job.hard_due and row.end > job.due:
            issues.append(_issue("hard_due", f"{row.job_id} ends at {row.end} after hard due {job.due}", row.job_id))
        by_machine[row.machine_id].append((row.start, row.end, row.job_id))
        ends[row.job_id] = row.end
        starts[row.job_id] = row.start
        tardy += job.weight * max(0, row.end - job.due)
    for job in instance.jobs:
        if job.job_id not in seen:
            issues.append(_issue("cover", f"job {job.job_id} has no start", job.job_id))
    for machine, blocks in by_machine.items():
        ordered = sorted(blocks)
        for prev, cur in zip(ordered, ordered[1:]):
            if prev[1] > cur[0]:
                issues.append(_issue("overlap", f"{machine} overlap {prev[2]} and {cur[2]}", machine))
    for edge in instance.precedences:
        if edge.before in ends and edge.after in starts and ends[edge.before] > starts[edge.after]:
            issues.append(_issue("precedence", f"{edge.before} must finish before {edge.after}", edge.after))
    return ValidationReport(ok=not issues, issues=issues, checked=checked, recomputed_objective=float(tardy))


def format_input_error(report: ValidationReport) -> str:
    if report.ok:
        return ""
    return " | ".join(f"{item.code}: {item.message}" for item in report.issues[:8])