-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject_scheduler.py
More file actions
232 lines (196 loc) · 7.05 KB
/
project_scheduler.py
File metadata and controls
232 lines (196 loc) · 7.05 KB
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
"""Example: Project scheduling with resource constraints.
Demonstrates optimization, precedence constraints, and makespan minimization.
"""
import asyncio
from chuk_mcp_solver.models import SolveConstraintModelRequest
from chuk_mcp_solver.solver import get_solver
def build_project_model(
tasks: list[dict],
dependencies: list[tuple[str, str]],
resources: dict[str, int],
) -> dict:
"""Build a project scheduling model.
Args:
tasks: List of tasks with id, duration, and resource.
dependencies: List of (predecessor, successor) task ID pairs.
resources: Dict of resource_name -> max_parallel_tasks.
Returns:
Model dictionary.
"""
variables = []
constraints = []
# Create start time variables for each task
max_time = sum(t["duration"] for t in tasks) # Upper bound
for task in tasks:
variables.append(
{
"id": f"start_{task['id']}",
"domain": {"type": "integer", "lower": 0, "upper": max_time},
"metadata": {"task_id": task["id"], "type": "start_time"},
}
)
# Also need end time for makespan
variables.append(
{
"id": f"end_{task['id']}",
"domain": {"type": "integer", "lower": 0, "upper": max_time},
"metadata": {"task_id": task["id"], "type": "end_time"},
}
)
# Add makespan variable (max end time)
variables.append(
{
"id": "makespan",
"domain": {"type": "integer", "lower": 0, "upper": max_time},
"metadata": {"type": "makespan"},
}
)
# Duration constraints: end = start + duration
for task in tasks:
constraints.append(
{
"id": f"duration_{task['id']}",
"kind": "linear",
"params": {
"terms": [
{"var": f"end_{task['id']}", "coef": 1},
{"var": f"start_{task['id']}", "coef": -1},
],
"sense": "==",
"rhs": task["duration"],
},
"metadata": {"description": f"Duration of task {task['id']}"},
}
)
# Precedence constraints: successor starts after predecessor ends
for pred, succ in dependencies:
constraints.append(
{
"id": f"precedence_{pred}_to_{succ}",
"kind": "linear",
"params": {
"terms": [
{"var": f"start_{succ}", "coef": 1},
{"var": f"end_{pred}", "coef": -1},
],
"sense": ">=",
"rhs": 0,
},
"metadata": {"description": f"Task {succ} starts after {pred} finishes"},
}
)
# Makespan constraints: makespan >= end time of all tasks
for task in tasks:
constraints.append(
{
"id": f"makespan_{task['id']}",
"kind": "linear",
"params": {
"terms": [
{"var": "makespan", "coef": 1},
{"var": f"end_{task['id']}", "coef": -1},
],
"sense": ">=",
"rhs": 0,
},
"metadata": {"description": f"Makespan covers task {task['id']}"},
}
)
# Objective: minimize makespan
objective = {
"sense": "min",
"terms": [{"var": "makespan", "coef": 1}],
"metadata": {"description": "Minimize project duration"},
}
return {
"mode": "optimize",
"variables": variables,
"constraints": constraints,
"objective": objective,
}
def display_schedule(solution_vars: list, tasks: list[dict]) -> None:
"""Display the project schedule.
Args:
solution_vars: List of SolutionVariable objects.
tasks: Original task definitions.
"""
# Extract values
values = {var.id: int(var.value) for var in solution_vars}
makespan = values["makespan"]
print("\nOptimal Schedule:")
print(f"Total Project Duration: {makespan} time units\n")
# Build task schedule
schedule = []
for task in tasks:
start = values[f"start_{task['id']}"]
end = values[f"end_{task['id']}"]
schedule.append(
{
"id": task["id"],
"start": start,
"end": end,
"duration": task["duration"],
"resource": task.get("resource", "default"),
}
)
# Sort by start time
schedule.sort(key=lambda x: x["start"])
# Print schedule
print("Task | Start | End | Duration | Resource")
print("-----|-------|-----|----------|----------")
for item in schedule:
print(
f"{item['id']:4} | {item['start']:5} | {item['end']:3} | "
f"{item['duration']:8} | {item['resource']}"
)
# Print Gantt-like view
print("\nGantt Chart:")
for item in schedule:
bar = " " * item["start"] + "█" * item["duration"]
print(f"{item['id']:4} |{bar}")
print(f" 0{' ' * (makespan - 1)}{makespan}")
async def main() -> None:
"""Run the project scheduler example."""
print("=== Project Scheduler Example ===\n")
# Define tasks
tasks = [
{"id": "A", "duration": 3, "resource": "alice"},
{"id": "B", "duration": 2, "resource": "bob"},
{"id": "C", "duration": 4, "resource": "alice"},
{"id": "D", "duration": 2, "resource": "bob"},
]
# Define dependencies (A -> C, B -> D)
dependencies = [
("A", "C"),
("B", "D"),
]
# Resources (not enforcing capacity in this simple example)
resources = {"alice": 1, "bob": 1}
print("Tasks:")
for task in tasks:
print(f" {task['id']}: duration={task['duration']}, resource={task['resource']}")
print("\nDependencies:")
for pred, succ in dependencies:
print(f" {pred} -> {succ}")
# Build model
model_dict = build_project_model(tasks, dependencies, resources)
request = SolveConstraintModelRequest(**model_dict)
# Solve
print("\nOptimizing schedule...")
solver = get_solver("ortools")
response = await solver.solve_constraint_model(request)
# Display results
print(f"\nStatus: {response.status}")
if response.objective_value is not None:
print(f"Objective Value (Makespan): {response.objective_value:.0f}")
if response.solutions:
display_schedule(response.solutions[0].variables, tasks)
if response.explanation:
print(f"\n{response.explanation.summary}")
if response.explanation.binding_constraints:
print("\nBinding Constraints (critical path indicators):")
for bc in response.explanation.binding_constraints[:3]:
desc = bc.metadata.get("description", bc.id) if bc.metadata else bc.id
print(f" - {desc}")
if __name__ == "__main__":
asyncio.run(main())