File size: 11,679 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
from __future__ import annotations

import time
from dataclasses import dataclass

from ortools.sat.python import cp_model

from src.domain import (
    AssignmentInstance,
    AssignmentRow,
    Family,
    InventoryInstance,
    InventoryOrder,
    ScheduleInstance,
    ScheduleStart,
    Solution,
    SolveStatus,
    parse_instance,
)


@dataclass
class SolverOutcome:
    solution: Solution
    seconds: float
    solver_name: str
    message: str


def _status(model_status: int) -> SolveStatus:
    if model_status == cp_model.OPTIMAL:
        return SolveStatus.OPTIMAL
    if model_status == cp_model.FEASIBLE:
        return SolveStatus.FEASIBLE
    if model_status == cp_model.INFEASIBLE:
        return SolveStatus.INFEASIBLE
    if model_status in {cp_model.UNKNOWN, cp_model.MODEL_INVALID}:
        return SolveStatus.TIMEOUT
    return SolveStatus.ERROR


def _status_name(model_status: int) -> str:
    names = {
        cp_model.OPTIMAL: "OPTIMAL",
        cp_model.FEASIBLE: "FEASIBLE",
        cp_model.INFEASIBLE: "INFEASIBLE",
        cp_model.UNKNOWN: "UNKNOWN",
        cp_model.MODEL_INVALID: "MODEL_INVALID",
    }
    return names.get(model_status, str(model_status))


def solve_inventory(instance: InventoryInstance, seconds: float, threads: int = 1) -> SolverOutcome:
    started = time.perf_counter()
    model = cp_model.CpModel()
    periods = instance.periods
    skus = instance.skus
    order: dict[tuple[str, int], cp_model.IntVar] = {}
    inv: dict[tuple[str, int], cp_model.IntVar] = {}
    short: dict[tuple[str, int], cp_model.IntVar] = {}
    sold: dict[tuple[str, int], cp_model.IntVar] = {}

    max_demand = max((max(sku.demand) for sku in skus), default=1)
    max_pack = max((sku.pack_size for sku in skus), default=1)
    max_order = max(max_demand * periods + max_pack * 4, 1)

    for sku in skus:
        for t in range(1, periods + 1):
            packs = model.NewIntVar(0, max_order // sku.pack_size + 1, f"packs_{sku.sku_id}_{t}")
            qty = model.NewIntVar(0, max_order, f"ord_{sku.sku_id}_{t}")
            model.Add(qty == packs * sku.pack_size)
            order[(sku.sku_id, t)] = qty
            inv[(sku.sku_id, t)] = model.NewIntVar(0, instance.warehouse_capacity, f"inv_{sku.sku_id}_{t}")
            demand = int(sku.demand[t - 1])
            short[(sku.sku_id, t)] = model.NewIntVar(0, demand, f"sh_{sku.sku_id}_{t}")
            sold[(sku.sku_id, t)] = model.NewIntVar(0, demand, f"sd_{sku.sku_id}_{t}")
            prev = sku.initial_stock if t == 1 else inv[(sku.sku_id, t - 1)]
            model.Add(inv[(sku.sku_id, t)] + sold[(sku.sku_id, t)] == prev + qty)
            model.Add(sold[(sku.sku_id, t)] + short[(sku.sku_id, t)] == demand)
            if instance.cover_required:
                model.Add(short[(sku.sku_id, t)] == 0)

    for t in range(1, periods + 1):
        model.Add(sum(inv[(sku.sku_id, t)] for sku in skus) <= instance.warehouse_capacity)

    model.Add(
        sum(sku.unit_cost * order[(sku.sku_id, t)] for sku in skus for t in range(1, periods + 1)) <= instance.budget
    )

    objective = []
    for sku in skus:
        for t in range(1, periods + 1):
            objective.append(sku.unit_cost * order[(sku.sku_id, t)])
            objective.append(sku.holding_cost * inv[(sku.sku_id, t)])
            objective.append(sku.shortage_cost * short[(sku.sku_id, t)])
    model.Minimize(sum(objective))

    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = float(seconds)
    solver.parameters.num_search_workers = int(threads)
    raw = solver.Solve(model)
    status = _status(raw)
    elapsed = time.perf_counter() - started
    message = _status_name(raw)
    if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}:
        orders = [
            InventoryOrder(sku_id=sku.sku_id, period=t, qty=int(solver.Value(order[(sku.sku_id, t)])))
            for sku in skus
            for t in range(1, periods + 1)
        ]
        obj = float(solver.ObjectiveValue())
        bound = float(solver.BestObjectiveBound()) if status == SolveStatus.FEASIBLE else obj
        return SolverOutcome(
            Solution(
                family=Family.INVENTORY,
                status=status,
                objective=obj,
                bound=bound,
                orders=orders,
                message=message,
            ),
            elapsed,
            "ortools-cpsat",
            message,
        )
    return SolverOutcome(
        Solution(family=Family.INVENTORY, status=status, message=message),
        elapsed,
        "ortools-cpsat",
        message,
    )


def solve_assignment(instance: AssignmentInstance, seconds: float, threads: int = 1) -> SolverOutcome:
    started = time.perf_counter()
    model = cp_model.CpModel()
    x: dict[tuple[str, str], cp_model.IntVar] = {}
    costs = instance.cost_map()
    for task in instance.tasks:
        for agent in instance.agents:
            if instance.eligible(task, agent) and (task.task_id, agent.agent_id) in costs:
                x[(task.task_id, agent.agent_id)] = model.NewBoolVar(f"x_{task.task_id}_{agent.agent_id}")

    unassigned: dict[str, cp_model.IntVar] = {}
    for task in instance.tasks:
        assigned = [x[(task.task_id, agent.agent_id)] for agent in instance.agents if (task.task_id, agent.agent_id) in x]
        miss = model.NewBoolVar(f"u_{task.task_id}")
        unassigned[task.task_id] = miss
        model.Add(sum(assigned) + miss == 1)
        if task.required:
            model.Add(miss == 0)

    for agent in instance.agents:
        load = [
            task.size * x[(task.task_id, agent.agent_id)]
            for task in instance.tasks
            if (task.task_id, agent.agent_id) in x
        ]
        if load:
            model.Add(sum(load) <= agent.capacity)

    obj_terms = []
    for (task_id, agent_id), var in x.items():
        obj_terms.append(costs[(task_id, agent_id)] * var)
    for task in instance.tasks:
        obj_terms.append(task.penalty * unassigned[task.task_id])
    model.Minimize(sum(obj_terms) if obj_terms else 0)

    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = float(seconds)
    solver.parameters.num_search_workers = int(threads)
    raw = solver.Solve(model)
    status = _status(raw)
    elapsed = time.perf_counter() - started
    message = _status_name(raw)
    if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}:
        rows = [
            AssignmentRow(task_id=task_id, agent_id=agent_id)
            for (task_id, agent_id), var in x.items()
            if solver.Value(var)
        ]
        leftover = [task_id for task_id, var in unassigned.items() if solver.Value(var)]
        obj = float(solver.ObjectiveValue())
        bound = float(solver.BestObjectiveBound()) if status == SolveStatus.FEASIBLE else obj
        return SolverOutcome(
            Solution(
                family=Family.ASSIGNMENT,
                status=status,
                objective=obj,
                bound=bound,
                assignments=rows,
                unassigned=leftover,
                message=message,
            ),
            elapsed,
            "ortools-cpsat",
            message,
        )
    return SolverOutcome(
        Solution(family=Family.ASSIGNMENT, status=status, message=message),
        elapsed,
        "ortools-cpsat",
        message,
    )


def solve_scheduling(instance: ScheduleInstance, seconds: float, threads: int = 1) -> SolverOutcome:
    started = time.perf_counter()
    model = cp_model.CpModel()
    horizon = max(instance.horizon, sum(job.duration for job in instance.jobs) + max((job.release for job in instance.jobs), default=0) + 2)
    intervals_by_machine: dict[str, list] = {machine: [] for machine in instance.machines}
    start: dict[str, cp_model.IntVar] = {}
    end: dict[str, cp_model.IntVar] = {}
    tardy: dict[str, cp_model.IntVar] = {}
    assign: dict[tuple[str, str], cp_model.IntVar] = {}

    for job in instance.jobs:
        start[job.job_id] = model.NewIntVar(job.release, horizon, f"s_{job.job_id}")
        end[job.job_id] = model.NewIntVar(job.release + job.duration, horizon + job.duration, f"e_{job.job_id}")
        model.Add(end[job.job_id] == start[job.job_id] + job.duration)
        tardy[job.job_id] = model.NewIntVar(0, horizon + job.duration, f"tard_{job.job_id}")
        model.Add(tardy[job.job_id] >= end[job.job_id] - job.due)
        if job.hard_due:
            model.Add(end[job.job_id] <= job.due)
        eligible = [machine for machine in instance.machines if machine in set(job.machine_eligible)]
        if not eligible:
            eligible = list(instance.machines)
        machine_bools = []
        for machine in eligible:
            flag = model.NewBoolVar(f"m_{job.job_id}_{machine}")
            assign[(job.job_id, machine)] = flag
            interval = model.NewOptionalIntervalVar(start[job.job_id], job.duration, end[job.job_id], flag, f"iv_{job.job_id}_{machine}")
            intervals_by_machine[machine].append(interval)
            machine_bools.append(flag)
        model.AddExactlyOne(machine_bools)

    for machine, intervals in intervals_by_machine.items():
        if intervals:
            model.AddNoOverlap(intervals)

    job_ids = {job.job_id for job in instance.jobs}
    for edge in instance.precedences:
        if edge.before in job_ids and edge.after in job_ids:
            model.Add(end[edge.before] <= start[edge.after])

    makespan = model.NewIntVar(0, horizon + 8, "makespan")
    for job in instance.jobs:
        model.Add(makespan >= end[job.job_id])
    model.Minimize(sum(job.weight * tardy[job.job_id] for job in instance.jobs) * 100 + makespan)

    solver = cp_model.CpSolver()
    solver.parameters.max_time_in_seconds = float(seconds)
    solver.parameters.num_search_workers = int(threads)
    raw = solver.Solve(model)
    status = _status(raw)
    elapsed = time.perf_counter() - started
    message = _status_name(raw)
    if status in {SolveStatus.OPTIMAL, SolveStatus.FEASIBLE}:
        starts = []
        for job in instance.jobs:
            machine_id = next(machine for machine in instance.machines if (job.job_id, machine) in assign and solver.Value(assign[(job.job_id, machine)]))
            starts.append(
                ScheduleStart(
                    job_id=job.job_id,
                    machine_id=machine_id,
                    start=int(solver.Value(start[job.job_id])),
                    end=int(solver.Value(end[job.job_id])),
                )
            )
        weighted = sum(job.weight * max(0, int(solver.Value(end[job.job_id])) - job.due) for job in instance.jobs)
        obj = float(weighted)
        return SolverOutcome(
            Solution(
                family=Family.SCHEDULING,
                status=status,
                objective=obj,
                bound=obj if status == SolveStatus.OPTIMAL else None,
                starts=starts,
                message=message,
            ),
            elapsed,
            "ortools-cpsat",
            message,
        )
    return SolverOutcome(
        Solution(family=Family.SCHEDULING, status=status, message=message),
        elapsed,
        "ortools-cpsat",
        message,
    )


def solve_instance(family: Family | str, payload: dict, seconds: float, threads: int = 1) -> SolverOutcome:
    family = Family(family)
    instance = parse_instance(family, payload)
    if family == Family.INVENTORY:
        return solve_inventory(instance, seconds, threads)
    if family == Family.ASSIGNMENT:
        return solve_assignment(instance, seconds, threads)
    return solve_scheduling(instance, seconds, threads)