In a scheduling problem I also want to minimize the total hired days.
A employee is hired in a given day if he/she works before that day and also after that day.
Here is a small working example:
import random
from ortools.sat.python import cp_model
model = cp_model.CpModel()
solver = cp_model.CpSolver()
employees = range(3)
days = range(10)
works_day = {(e, d): model.NewBoolVar(f'{e}_works_{d}')
for e in employees for d in days}
hired_day = {(e, d): model.NewBoolVar(f'{e}_employed_{d}')
for e in employees for d in days}
# random example
for boolean in works_day.values():
model.Add(boolean == random.choice([0, 1]))
# give value to hired_day
add_hired_days()
# solve
print('Variables:', len(model.Proto().variables))
print('Constraints:', len(model.Proto().constraints))
status = solver.Solve(model)
for e in employees:
print()
print('Employee', e)
for d in days:
print('Works', solver.Value(works_day[e, d]),
'Hired', solver.Value(hired_day[e, d]))
Where add_hired_days
is:
def add_hired_days():
for idx, d in enumerate(days):
for e in employees:
model.AddImplication(works_day[e, d], hired_day[e, d])
previous = [works_day[e, d] for d in days[:idx + 1]]
following = [works_day[e, d] for d in days[idx:]]
# too many variables
works_previous = model.NewBoolVar('')
works_following = model.NewBoolVar('')
model.AddBoolOr(previous).OnlyEnforceIf(works_previous)
model.AddBoolAnd([d.Not() for d in previous
]).OnlyEnforceIf(works_previous.Not())
model.AddBoolOr(following).OnlyEnforceIf(works_following)
model.AddBoolAnd([d.Not() for d in following
]).OnlyEnforceIf(works_following.Not())
model.AddBoolAnd([works_previous, works_following
]).OnlyEnforceIf(hired_day[e, d])
model.AddBoolOr([works_previous.Not(),
works_following.Not()
]).OnlyEnforceIf(hired_day[e, d].Not())
Is there any way to do this without creating this many variables and constraints?
if an employee works n days in a month, he needs to be hired n - 2 times.