index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/ShiftTypeSkillRequirement.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
public class ShiftTypeSkillRequirement extends AbstractPersistable {
private ShiftType shiftType;
private Skill skill;
public ShiftTypeSkillRequirement() {
}
public ShiftTypeSkillRequirement(long id, ShiftType shiftType, Skill skill) {
super(id);
this.shiftType = shiftType;
this.skill = skill;
}
public ShiftType getShiftType() {
return shiftType;
}
public void setShiftType(ShiftType shiftType) {
this.shiftType = shiftType;
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
@Override
public String toString() {
return shiftType + "-" + skill;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/Skill.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Skill extends AbstractPersistable {
private String code;
public Skill() {
}
public Skill(long id, String code) {
super(id);
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/SkillProficiency.java | package ai.timefold.solver.examples.nurserostering.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
public class SkillProficiency extends AbstractPersistable {
private Employee employee;
private Skill skill;
public SkillProficiency() {
}
public SkillProficiency(long id, Employee employee, Skill skill) {
super(id);
this.employee = employee;
this.skill = skill;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Skill getSkill() {
return skill;
}
public void setSkill(Skill skill) {
this.skill = skill;
}
@Override
public String toString() {
return employee + "-" + skill;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/WeekendDefinition.java | package ai.timefold.solver.examples.nurserostering.domain;
import java.time.DayOfWeek;
import java.util.EnumSet;
public enum WeekendDefinition {
SATURDAY_SUNDAY("SaturdaySunday",
DayOfWeek.SATURDAY, DayOfWeek.SUNDAY),
FRIDAY_SATURDAY_SUNDAY("FridaySaturdaySunday",
DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY),
FRIDAY_SATURDAY_SUNDAY_MONDAY("FridaySaturdaySundayMonday",
DayOfWeek.FRIDAY, DayOfWeek.SATURDAY, DayOfWeek.SUNDAY, DayOfWeek.MONDAY),
SATURDAY_SUNDAY_MONDAY("SaturdaySundayMonday",
DayOfWeek.SATURDAY, DayOfWeek.SUNDAY, DayOfWeek.MONDAY);
private EnumSet<DayOfWeek> dayOfWeekSet;
private DayOfWeek firstDayOfWeekend;
private DayOfWeek lastDayOfWeekend;
public static WeekendDefinition valueOfCode(String code) {
for (WeekendDefinition weekendDefinition : values()) {
if (code.equalsIgnoreCase(weekendDefinition.getCode())) {
return weekendDefinition;
}
}
return null;
}
private String code;
private WeekendDefinition(String code, DayOfWeek dayOfWeekend1, DayOfWeek dayOfWeekend2) {
this.code = code;
this.dayOfWeekSet = EnumSet.of(dayOfWeekend1, dayOfWeekend2);
this.firstDayOfWeekend = dayOfWeekend1;
this.lastDayOfWeekend = dayOfWeekend2;
}
private WeekendDefinition(String code, DayOfWeek dayOfWeekend1, DayOfWeek dayOfWeekend2, DayOfWeek dayOfWeekend3) {
this.code = code;
this.dayOfWeekSet = EnumSet.of(dayOfWeekend1, dayOfWeekend2, dayOfWeekend3);
this.firstDayOfWeekend = dayOfWeekend1;
this.lastDayOfWeekend = dayOfWeekend3;
}
private WeekendDefinition(String code, DayOfWeek dayOfWeekend1, DayOfWeek dayOfWeekend2, DayOfWeek dayOfWeekend3,
DayOfWeek dayOfWeekend4) {
this.code = code;
this.dayOfWeekSet = EnumSet.of(dayOfWeekend1, dayOfWeekend2, dayOfWeekend3, dayOfWeekend4);
this.firstDayOfWeekend = dayOfWeekend1;
this.lastDayOfWeekend = dayOfWeekend4;
}
public String getCode() {
return code;
}
public DayOfWeek getFirstDayOfWeekend() {
return firstDayOfWeekend;
}
public DayOfWeek getLastDayOfWeekend() {
return lastDayOfWeekend;
}
@Override
public String toString() {
return code;
}
public boolean isWeekend(DayOfWeek dayOfWeek) {
return dayOfWeekSet.contains(dayOfWeek);
}
public int getWeekendLength() {
return dayOfWeekSet.size();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/contract/BooleanContractLine.java | package ai.timefold.solver.examples.nurserostering.domain.contract;
public class BooleanContractLine extends ContractLine {
private boolean enabled;
private int weight;
public BooleanContractLine() {
}
public BooleanContractLine(long id, Contract contract, ContractLineType contractLineType, boolean enabled, int weight) {
super(id, contract, contractLineType);
this.enabled = enabled;
this.weight = weight;
}
@Override
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/contract/Contract.java | package ai.timefold.solver.examples.nurserostering.domain.contract;
import java.util.List;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.nurserostering.domain.WeekendDefinition;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Contract extends AbstractPersistable {
private String code;
private String description;
private WeekendDefinition weekendDefinition;
private List<ContractLine> contractLineList;
public Contract() {
}
public Contract(long id) {
super(id);
}
public Contract(long id, String code, String description) {
super(id);
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public WeekendDefinition getWeekendDefinition() {
return weekendDefinition;
}
public void setWeekendDefinition(WeekendDefinition weekendDefinition) {
this.weekendDefinition = weekendDefinition;
}
public List<ContractLine> getContractLineList() {
return contractLineList;
}
public void setContractLineList(List<ContractLine> contractLineList) {
this.contractLineList = contractLineList;
}
@Override
public String toString() {
return code;
}
@JsonIgnore
public int getWeekendLength() {
return weekendDefinition.getWeekendLength();
}
@JsonIgnore
public ContractLine getFirstConstractLine() {
return contractLineList.get(0);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/contract/ContractLine.java | package ai.timefold.solver.examples.nurserostering.domain.contract;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(value = BooleanContractLine.class, name = "boolean"),
@JsonSubTypes.Type(value = MinMaxContractLine.class, name = "minMax"),
})
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public abstract class ContractLine extends AbstractPersistable {
private Contract contract;
private ContractLineType contractLineType;
protected ContractLine() {
}
protected ContractLine(long id, Contract contract, ContractLineType contractLineType) {
super(id);
this.contract = contract;
this.contractLineType = contractLineType;
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
public ContractLineType getContractLineType() {
return contractLineType;
}
public void setContractLineType(ContractLineType contractLineType) {
this.contractLineType = contractLineType;
}
public abstract boolean isEnabled();
@Override
public String toString() {
return contract + "-" + contractLineType;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/contract/ContractLineType.java | package ai.timefold.solver.examples.nurserostering.domain.contract;
public enum ContractLineType {
SINGLE_ASSIGNMENT_PER_DAY,
TOTAL_ASSIGNMENTS,
CONSECUTIVE_WORKING_DAYS,
CONSECUTIVE_FREE_DAYS,
CONSECUTIVE_WORKING_WEEKENDS,
TOTAL_WORKING_WEEKENDS_IN_FOUR_WEEKS,
COMPLETE_WEEKENDS,
IDENTICAL_SHIFT_TYPES_DURING_WEEKEND,
NO_NIGHT_SHIFT_BEFORE_FREE_WEEKEND,
ALTERNATIVE_SKILL_CATEGORY
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/contract/MinMaxContractLine.java | package ai.timefold.solver.examples.nurserostering.domain.contract;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class MinMaxContractLine extends ContractLine {
private boolean minimumEnabled;
private int minimumValue;
private int minimumWeight;
private boolean maximumEnabled;
private int maximumValue;
private int maximumWeight;
public MinMaxContractLine() {
}
public MinMaxContractLine(long id, Contract contract, ContractLineType contractLineType, boolean minimumEnabled,
boolean maximumEnabled) {
super(id, contract, contractLineType);
this.minimumEnabled = minimumEnabled;
this.maximumEnabled = maximumEnabled;
}
public boolean isViolated(int count) {
return getViolationAmount(count) != 0;
}
public int getViolationAmount(int count) {
if (minimumEnabled && count < minimumValue) {
return (minimumValue - count) * minimumWeight;
} else if (maximumEnabled && count > maximumValue) {
return (count - maximumValue) * maximumWeight;
} else {
return 0;
}
}
public boolean isMinimumEnabled() {
return minimumEnabled;
}
public void setMinimumEnabled(boolean minimumEnabled) {
this.minimumEnabled = minimumEnabled;
}
public int getMinimumValue() {
return minimumValue;
}
public void setMinimumValue(int minimumValue) {
this.minimumValue = minimumValue;
}
public int getMinimumWeight() {
return minimumWeight;
}
public void setMinimumWeight(int minimumWeight) {
this.minimumWeight = minimumWeight;
}
public boolean isMaximumEnabled() {
return maximumEnabled;
}
public void setMaximumEnabled(boolean maximumEnabled) {
this.maximumEnabled = maximumEnabled;
}
public int getMaximumValue() {
return maximumValue;
}
public void setMaximumValue(int maximumValue) {
this.maximumValue = maximumValue;
}
public int getMaximumWeight() {
return maximumWeight;
}
public void setMaximumWeight(int maximumWeight) {
this.maximumWeight = maximumWeight;
}
@Override
@JsonIgnore
public boolean isEnabled() {
return minimumEnabled || maximumEnabled;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/contract/PatternContractLine.java | package ai.timefold.solver.examples.nurserostering.domain.contract;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.nurserostering.domain.pattern.Pattern;
public class PatternContractLine extends AbstractPersistable {
private Contract contract;
private Pattern pattern;
public PatternContractLine() {
}
public PatternContractLine(long id) {
super(id);
}
public PatternContractLine(long id, Contract contract, Pattern pattern) {
super(id);
this.contract = contract;
this.pattern = pattern;
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
public Pattern getPattern() {
return pattern;
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
@Override
public String toString() {
return contract + "-" + pattern;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/pattern/FreeBefore2DaysWithAWorkDayPattern.java | package ai.timefold.solver.examples.nurserostering.domain.pattern;
import java.time.DayOfWeek;
public class FreeBefore2DaysWithAWorkDayPattern extends Pattern {
private DayOfWeek freeDayOfWeek;
public FreeBefore2DaysWithAWorkDayPattern() {
}
public FreeBefore2DaysWithAWorkDayPattern(long id, String code) {
super(id, code);
}
public FreeBefore2DaysWithAWorkDayPattern(long id, String code, DayOfWeek freeDayOfWeek) {
this(id, code);
this.freeDayOfWeek = freeDayOfWeek;
}
public DayOfWeek getFreeDayOfWeek() {
return freeDayOfWeek;
}
public void setFreeDayOfWeek(DayOfWeek freeDayOfWeek) {
this.freeDayOfWeek = freeDayOfWeek;
}
@Override
public String toString() {
return "Free on " + freeDayOfWeek + " followed by a work day within 2 days";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/pattern/Pattern.java | package ai.timefold.solver.examples.nurserostering.domain.pattern;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(value = ShiftType2DaysPattern.class, name = "shiftType2"),
@JsonSubTypes.Type(value = ShiftType3DaysPattern.class, name = "shiftType3"),
@JsonSubTypes.Type(value = WorkBeforeFreeSequencePattern.class, name = "workBeforeFree"),
@JsonSubTypes.Type(value = FreeBefore2DaysWithAWorkDayPattern.class, name = "freeBeforeWork"),
})
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public abstract class Pattern extends AbstractPersistable {
protected String code;
protected int weight;
protected Pattern() {
}
protected Pattern(long id, String code) {
super(id);
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return code;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/pattern/ShiftType2DaysPattern.java | package ai.timefold.solver.examples.nurserostering.domain.pattern;
import ai.timefold.solver.examples.nurserostering.domain.ShiftType;
public class ShiftType2DaysPattern extends Pattern {
private ShiftType dayIndex0ShiftType;
private ShiftType dayIndex1ShiftType;
public ShiftType2DaysPattern() {
}
public ShiftType2DaysPattern(long id, String code) {
super(id, code);
}
public ShiftType getDayIndex0ShiftType() {
return dayIndex0ShiftType;
}
public void setDayIndex0ShiftType(ShiftType dayIndex0ShiftType) {
this.dayIndex0ShiftType = dayIndex0ShiftType;
}
public ShiftType getDayIndex1ShiftType() {
return dayIndex1ShiftType;
}
public void setDayIndex1ShiftType(ShiftType dayIndex1ShiftType) {
this.dayIndex1ShiftType = dayIndex1ShiftType;
}
@Override
public String toString() {
return "Work pattern: " + dayIndex0ShiftType + ", " + dayIndex1ShiftType;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/pattern/ShiftType3DaysPattern.java | package ai.timefold.solver.examples.nurserostering.domain.pattern;
import ai.timefold.solver.examples.nurserostering.domain.ShiftType;
public class ShiftType3DaysPattern extends Pattern {
private ShiftType dayIndex0ShiftType;
private ShiftType dayIndex1ShiftType;
private ShiftType dayIndex2ShiftType;
public ShiftType3DaysPattern() {
}
public ShiftType3DaysPattern(long id, String code) {
super(id, code);
}
public ShiftType getDayIndex0ShiftType() {
return dayIndex0ShiftType;
}
public void setDayIndex0ShiftType(ShiftType dayIndex0ShiftType) {
this.dayIndex0ShiftType = dayIndex0ShiftType;
}
public ShiftType getDayIndex1ShiftType() {
return dayIndex1ShiftType;
}
public void setDayIndex1ShiftType(ShiftType dayIndex1ShiftType) {
this.dayIndex1ShiftType = dayIndex1ShiftType;
}
public ShiftType getDayIndex2ShiftType() {
return dayIndex2ShiftType;
}
public void setDayIndex2ShiftType(ShiftType dayIndex2ShiftType) {
this.dayIndex2ShiftType = dayIndex2ShiftType;
}
@Override
public String toString() {
return "Work pattern: " + dayIndex0ShiftType + ", " + dayIndex1ShiftType + ", " + dayIndex2ShiftType;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/pattern/WorkBeforeFreeSequencePattern.java | package ai.timefold.solver.examples.nurserostering.domain.pattern;
import java.time.DayOfWeek;
import ai.timefold.solver.examples.nurserostering.domain.ShiftType;
public class WorkBeforeFreeSequencePattern extends Pattern {
private DayOfWeek workDayOfWeek; // null means any
private ShiftType workShiftType; // null means any
private int freeDayLength;
public WorkBeforeFreeSequencePattern() {
}
public WorkBeforeFreeSequencePattern(long id, String code, DayOfWeek workDayOfWeek, ShiftType workShiftType,
int freeDayLength) {
super(id, code);
this.workDayOfWeek = workDayOfWeek;
this.workShiftType = workShiftType;
this.freeDayLength = freeDayLength;
}
public DayOfWeek getWorkDayOfWeek() {
return workDayOfWeek;
}
public void setWorkDayOfWeek(DayOfWeek workDayOfWeek) {
this.workDayOfWeek = workDayOfWeek;
}
public ShiftType getWorkShiftType() {
return workShiftType;
}
public void setWorkShiftType(ShiftType workShiftType) {
this.workShiftType = workShiftType;
}
public int getFreeDayLength() {
return freeDayLength;
}
public void setFreeDayLength(int freeDayLength) {
this.freeDayLength = freeDayLength;
}
@Override
public String toString() {
return "Work " + workShiftType + " on " + workDayOfWeek + " followed by " + freeDayLength + " free days";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/request/DayOffRequest.java | package ai.timefold.solver.examples.nurserostering.domain.request;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class DayOffRequest extends AbstractPersistable {
private Employee employee;
private ShiftDate shiftDate;
private int weight;
public DayOffRequest() {
}
public DayOffRequest(long id, Employee employee, ShiftDate shiftDate, int weight) {
super(id);
this.employee = employee;
this.shiftDate = shiftDate;
this.weight = weight;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public ShiftDate getShiftDate() {
return shiftDate;
}
public void setShiftDate(ShiftDate shiftDate) {
this.shiftDate = shiftDate;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return shiftDate + "_OFF_" + employee;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/request/DayOnRequest.java | package ai.timefold.solver.examples.nurserostering.domain.request;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class DayOnRequest extends AbstractPersistable {
private Employee employee;
private ShiftDate shiftDate;
private int weight;
public DayOnRequest() {
}
public DayOnRequest(long id, Employee employee, ShiftDate shiftDate, int weight) {
super(id);
this.employee = employee;
this.shiftDate = shiftDate;
this.weight = weight;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public ShiftDate getShiftDate() {
return shiftDate;
}
public void setShiftDate(ShiftDate shiftDate) {
this.shiftDate = shiftDate;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return shiftDate + "_ON_" + employee;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/request/ShiftOffRequest.java | package ai.timefold.solver.examples.nurserostering.domain.request;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class ShiftOffRequest extends AbstractPersistable {
private Employee employee;
private Shift shift;
private int weight;
public ShiftOffRequest() {
}
public ShiftOffRequest(long id, Employee employee, Shift shift, int weight) {
super(id);
this.employee = employee;
this.shift = shift;
this.weight = weight;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Shift getShift() {
return shift;
}
public void setShift(Shift shift) {
this.shift = shift;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return shift + "_OFF_" + employee;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/request/ShiftOnRequest.java | package ai.timefold.solver.examples.nurserostering.domain.request;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class ShiftOnRequest extends AbstractPersistable {
private Employee employee;
private Shift shift;
private int weight;
public ShiftOnRequest() {
}
public ShiftOnRequest(long id, Employee employee, Shift shift, int weight) {
super(id);
this.employee = employee;
this.shift = shift;
this.weight = weight;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Shift getShift() {
return shift;
}
public void setShift(Shift shift) {
this.shift = shift;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public String toString() {
return shift + "_ON_" + employee;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/solver/EmployeeStrengthComparator.java | package ai.timefold.solver.examples.nurserostering.domain.solver;
import static java.util.Comparator.comparingInt;
import java.util.Comparator;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
public class EmployeeStrengthComparator implements Comparator<Employee> {
private static final Comparator<Employee> COMPARATOR = comparingInt((Employee employee) -> -employee.getWeekendLength()) // Descending
.thenComparingLong(Employee::getId);
@Override
public int compare(Employee a, Employee b) {
// TODO refactor to DifficultyWeightFactory and use getContract().getContractLineList()
// to sum maximumValue and minimumValue etc
return COMPARATOR.compare(a, b);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/solver/MovableShiftAssignmentSelectionFilter.java | package ai.timefold.solver.examples.nurserostering.domain.solver;
import ai.timefold.solver.core.api.domain.entity.PinningFilter;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
public class MovableShiftAssignmentSelectionFilter implements SelectionFilter<NurseRoster, ShiftAssignment> {
private final PinningFilter<NurseRoster, ShiftAssignment> pinningFilter =
new ShiftAssignmentPinningFilter();
@Override
public boolean accept(ScoreDirector<NurseRoster> scoreDirector, ShiftAssignment selection) {
return !pinningFilter.accept(scoreDirector.getWorkingSolution(), selection);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/solver/ShiftAssignmentDifficultyComparator.java | package ai.timefold.solver.examples.nurserostering.domain.solver;
import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingLong;
import java.util.Collections;
import java.util.Comparator;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import ai.timefold.solver.examples.nurserostering.domain.ShiftType;
public class ShiftAssignmentDifficultyComparator implements Comparator<ShiftAssignment> {
private static final Comparator<Shift> COMPARATOR = comparing(Shift::getShiftDate,
Collections.reverseOrder(comparing(ShiftDate::getDate)))
.thenComparing(Shift::getShiftType, comparingLong(ShiftType::getId).reversed())
.thenComparingInt(Shift::getRequiredEmployeeSize);
@Override
public int compare(ShiftAssignment a, ShiftAssignment b) {
Shift aShift = a.getShift();
Shift bShift = b.getShift();
return COMPARATOR.compare(aShift, bShift);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/domain/solver/ShiftAssignmentPinningFilter.java | package ai.timefold.solver.examples.nurserostering.domain.solver;
import ai.timefold.solver.core.api.domain.entity.PinningFilter;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
public class ShiftAssignmentPinningFilter implements PinningFilter<NurseRoster, ShiftAssignment> {
@Override
public boolean accept(NurseRoster nurseRoster, ShiftAssignment shiftAssignment) {
ShiftDate shiftDate = shiftAssignment.getShift().getShiftDate();
return !nurseRoster.getNurseRosterParametrization().isInPlanningWindow(shiftDate);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/benchmark/NurseRosteringBenchmarkApp.java | package ai.timefold.solver.examples.nurserostering.optional.benchmark;
import ai.timefold.solver.examples.common.app.CommonBenchmarkApp;
public class NurseRosteringBenchmarkApp extends CommonBenchmarkApp {
public static void main(String[] args) {
new NurseRosteringBenchmarkApp().buildAndBenchmark(args);
}
public NurseRosteringBenchmarkApp() {
super(
new ArgOption("sprint",
"ai/timefold/solver/examples/nurserostering/optional/benchmark/nurseRosteringSprintBenchmarkConfig.xml"),
new ArgOption("medium",
"ai/timefold/solver/examples/nurserostering/optional/benchmark/nurseRosteringMediumBenchmarkConfig.xml"),
new ArgOption("long",
"ai/timefold/solver/examples/nurserostering/optional/benchmark/nurseRosteringLongBenchmarkConfig.xml"),
new ArgOption("stepLimit",
"ai/timefold/solver/examples/nurserostering/optional/benchmark/nurseRosteringStepLimitBenchmarkConfig.xml"));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeConsecutiveAssignmentEnd.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.time.DayOfWeek;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import ai.timefold.solver.examples.nurserostering.domain.WeekendDefinition;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
public class EmployeeConsecutiveAssignmentEnd implements Comparable<EmployeeConsecutiveAssignmentEnd> {
public static boolean isWeekendAndNotLastDayOfWeekend(Employee employee, ShiftDate shiftDate) {
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shiftDate.getDayOfWeek();
return weekendDefinition.isWeekend(dayOfWeek) && weekendDefinition.getLastDayOfWeekend() != dayOfWeek;
}
public static int getDistanceToLastDayOfWeekend(Employee employee, ShiftDate shiftDate) {
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shiftDate.getDayOfWeek();
DayOfWeek lastDayOfWeekend = weekendDefinition.getLastDayOfWeekend();
int distance = lastDayOfWeekend.getValue() - dayOfWeek.getValue();
if (distance < 0) {
distance += 7;
}
return distance;
}
private static final Comparator<EmployeeConsecutiveAssignmentEnd> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveAssignmentEnd::getEmployee)
.thenComparing(EmployeeConsecutiveAssignmentEnd::getShiftDate);
private Employee employee;
private ShiftDate shiftDate;
public EmployeeConsecutiveAssignmentEnd(Employee employee, ShiftDate shiftDate) {
this.employee = employee;
this.shiftDate = shiftDate;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public ShiftDate getShiftDate() {
return shiftDate;
}
public void setShiftDate(ShiftDate shiftDate) {
this.shiftDate = shiftDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveAssignmentEnd other = (EmployeeConsecutiveAssignmentEnd) o;
return Objects.equals(employee, other.employee) &&
Objects.equals(shiftDate, other.shiftDate);
}
@Override
public int hashCode() {
return Objects.hash(employee, shiftDate);
}
@Override
public int compareTo(EmployeeConsecutiveAssignmentEnd other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " ... - " + shiftDate;
}
public Contract getContract() {
return employee.getContract();
}
public int getShiftDateDayIndex() {
return shiftDate.getDayIndex();
}
public boolean isWeekendAndNotLastDayOfWeekend() {
return isWeekendAndNotLastDayOfWeekend(employee, shiftDate);
}
public int getDistanceToLastDayOfWeekend() {
return getDistanceToLastDayOfWeekend(employee, shiftDate);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeConsecutiveAssignmentStart.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.time.DayOfWeek;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import ai.timefold.solver.examples.nurserostering.domain.WeekendDefinition;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
public class EmployeeConsecutiveAssignmentStart implements Comparable<EmployeeConsecutiveAssignmentStart> {
public static boolean isWeekendAndNotFirstDayOfWeekend(Employee employee, ShiftDate shiftDate) {
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shiftDate.getDayOfWeek();
return weekendDefinition.isWeekend(dayOfWeek) && weekendDefinition.getFirstDayOfWeekend() != dayOfWeek;
}
public static int getDistanceToFirstDayOfWeekend(Employee employee, ShiftDate shiftDate) {
WeekendDefinition weekendDefinition = employee.getContract().getWeekendDefinition();
DayOfWeek dayOfWeek = shiftDate.getDayOfWeek();
DayOfWeek firstDayOfWeekend = weekendDefinition.getFirstDayOfWeekend();
int distance = dayOfWeek.getValue() - firstDayOfWeekend.getValue();
if (distance < 0) {
distance += 7;
}
return distance;
}
private static final Comparator<EmployeeConsecutiveAssignmentStart> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveAssignmentStart::getEmployee)
.thenComparing(EmployeeConsecutiveAssignmentStart::getShiftDate);
private Employee employee;
private ShiftDate shiftDate;
public EmployeeConsecutiveAssignmentStart(Employee employee, ShiftDate shiftDate) {
this.employee = employee;
this.shiftDate = shiftDate;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public ShiftDate getShiftDate() {
return shiftDate;
}
public void setShiftDate(ShiftDate shiftDate) {
this.shiftDate = shiftDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveAssignmentStart other = (EmployeeConsecutiveAssignmentStart) o;
return Objects.equals(employee, other.employee) &&
Objects.equals(shiftDate, other.shiftDate);
}
@Override
public int hashCode() {
return Objects.hash(employee, shiftDate);
}
@Override
public int compareTo(EmployeeConsecutiveAssignmentStart other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " " + shiftDate + " - ...";
}
public Contract getContract() {
return employee.getContract();
}
public int getShiftDateDayIndex() {
return shiftDate.getDayIndex();
}
public boolean isWeekendAndNotFirstDayOfWeekend() {
return isWeekendAndNotFirstDayOfWeekend(employee, shiftDate);
}
public int getDistanceToFirstDayOfWeekend() {
return getDistanceToFirstDayOfWeekend(employee, shiftDate);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeConsecutiveWeekendAssignmentEnd.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
public class EmployeeConsecutiveWeekendAssignmentEnd implements Comparable<EmployeeConsecutiveWeekendAssignmentEnd> {
private static final Comparator<EmployeeConsecutiveWeekendAssignmentEnd> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveWeekendAssignmentEnd::getEmployee)
.thenComparingInt(EmployeeConsecutiveWeekendAssignmentEnd::getSundayIndex);
private Employee employee;
private int sundayIndex;
public EmployeeConsecutiveWeekendAssignmentEnd(Employee employee, int sundayIndex) {
this.employee = employee;
this.sundayIndex = sundayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getSundayIndex() {
return sundayIndex;
}
public void setSundayIndex(int sundayIndex) {
this.sundayIndex = sundayIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveWeekendAssignmentEnd other = (EmployeeConsecutiveWeekendAssignmentEnd) o;
return Objects.equals(employee, other.employee) &&
sundayIndex == other.sundayIndex;
}
@Override
public int hashCode() {
return Objects.hash(employee, sundayIndex);
}
@Override
public int compareTo(EmployeeConsecutiveWeekendAssignmentEnd other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " weekend ... - " + sundayIndex;
}
public Contract getContract() {
return employee.getContract();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeConsecutiveWeekendAssignmentStart.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
public class EmployeeConsecutiveWeekendAssignmentStart implements Comparable<EmployeeConsecutiveWeekendAssignmentStart> {
private static final Comparator<EmployeeConsecutiveWeekendAssignmentStart> COMPARATOR = Comparator
.comparing(EmployeeConsecutiveWeekendAssignmentStart::getEmployee)
.thenComparingInt(EmployeeConsecutiveWeekendAssignmentStart::getSundayIndex);
private Employee employee;
private int sundayIndex;
public EmployeeConsecutiveWeekendAssignmentStart(Employee employee, int sundayIndex) {
this.employee = employee;
this.sundayIndex = sundayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getSundayIndex() {
return sundayIndex;
}
public void setSundayIndex(int sundayIndex) {
this.sundayIndex = sundayIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeConsecutiveWeekendAssignmentStart other = (EmployeeConsecutiveWeekendAssignmentStart) o;
return Objects.equals(employee, other.employee) &&
sundayIndex == other.sundayIndex;
}
@Override
public int hashCode() {
return Objects.hash(employee, sundayIndex);
}
@Override
public int compareTo(EmployeeConsecutiveWeekendAssignmentStart other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " weekend " + sundayIndex + " - ...";
}
public Contract getContract() {
return employee.getContract();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeFreeSequence.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
public class EmployeeFreeSequence implements Comparable<EmployeeFreeSequence> {
private static final Comparator<EmployeeFreeSequence> COMPARATOR = Comparator.comparing(EmployeeFreeSequence::getEmployee)
.thenComparingInt(EmployeeFreeSequence::getFirstDayIndex)
.thenComparingInt(EmployeeFreeSequence::getLastDayIndex);
private Employee employee;
private int firstDayIndex;
private int lastDayIndex;
public EmployeeFreeSequence(Employee employee, int firstDayIndex, int lastDayIndex) {
this.employee = employee;
this.firstDayIndex = firstDayIndex;
this.lastDayIndex = lastDayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getFirstDayIndex() {
return firstDayIndex;
}
public void setFirstDayIndex(int firstDayIndex) {
this.firstDayIndex = firstDayIndex;
}
public int getLastDayIndex() {
return lastDayIndex;
}
public void setLastDayIndex(int lastDayIndex) {
this.lastDayIndex = lastDayIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeFreeSequence other = (EmployeeFreeSequence) o;
return Objects.equals(employee, other.employee) &&
firstDayIndex == other.firstDayIndex &&
lastDayIndex == other.lastDayIndex;
}
@Override
public int hashCode() {
return Objects.hash(employee, firstDayIndex, lastDayIndex);
}
@Override
public int compareTo(EmployeeFreeSequence other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " is free between " + firstDayIndex + " - " + lastDayIndex;
}
public int getDayLength() {
return lastDayIndex - firstDayIndex + 1;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeWeekendSequence.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
public class EmployeeWeekendSequence implements Comparable<EmployeeWeekendSequence> {
private static final Comparator<EmployeeWeekendSequence> COMPARATOR = Comparator
.comparing(EmployeeWeekendSequence::getEmployee)
.thenComparingInt(EmployeeWeekendSequence::getFirstSundayIndex)
.thenComparingInt(EmployeeWeekendSequence::getLastSundayIndex);
private Employee employee;
private int firstSundayIndex;
private int lastSundayIndex;
public EmployeeWeekendSequence(Employee employee, int firstSundayIndex, int lastSundayIndex) {
this.employee = employee;
this.firstSundayIndex = firstSundayIndex;
this.lastSundayIndex = lastSundayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getFirstSundayIndex() {
return firstSundayIndex;
}
public void setFirstSundayIndex(int firstSundayIndex) {
this.firstSundayIndex = firstSundayIndex;
}
public int getLastSundayIndex() {
return lastSundayIndex;
}
public void setLastSundayIndex(int lastSundayIndex) {
this.lastSundayIndex = lastSundayIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeWeekendSequence other = (EmployeeWeekendSequence) o;
return Objects.equals(employee, other.employee) &&
firstSundayIndex == other.firstSundayIndex &&
lastSundayIndex == other.lastSundayIndex;
}
@Override
public int hashCode() {
return Objects.hash(employee, firstSundayIndex, lastSundayIndex);
}
@Override
public int compareTo(EmployeeWeekendSequence other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " is working the weekend of " + firstSundayIndex + " - " + lastSundayIndex;
}
public int getWeekendLength() {
return ((lastSundayIndex - firstSundayIndex) / 7) + 1;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/optional/score/EmployeeWorkSequence.java | package ai.timefold.solver.examples.nurserostering.optional.score;
import java.util.Comparator;
import java.util.Objects;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
public class EmployeeWorkSequence implements Comparable<EmployeeWorkSequence> {
private static final Comparator<EmployeeWorkSequence> COMPARATOR = Comparator.comparing(EmployeeWorkSequence::getEmployee)
.thenComparingInt(EmployeeWorkSequence::getFirstDayIndex)
.thenComparingInt(EmployeeWorkSequence::getLastDayIndex);
private Employee employee;
private int firstDayIndex;
private int lastDayIndex;
public EmployeeWorkSequence(Employee employee, int firstDayIndex, int lastDayIndex) {
this.employee = employee;
this.firstDayIndex = firstDayIndex;
this.lastDayIndex = lastDayIndex;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public int getFirstDayIndex() {
return firstDayIndex;
}
public void setFirstDayIndex(int firstDayIndex) {
this.firstDayIndex = firstDayIndex;
}
public int getLastDayIndex() {
return lastDayIndex;
}
public void setLastDayIndex(int lastDayIndex) {
this.lastDayIndex = lastDayIndex;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeWorkSequence other = (EmployeeWorkSequence) o;
return Objects.equals(employee, other.employee) &&
firstDayIndex == other.firstDayIndex &&
lastDayIndex == other.lastDayIndex;
}
@Override
public int hashCode() {
return Objects.hash(employee, firstDayIndex, lastDayIndex);
}
@Override
public int compareTo(EmployeeWorkSequence other) {
return COMPARATOR.compare(this, other);
}
@Override
public String toString() {
return employee + " is working between " + firstDayIndex + " - " + lastDayIndex;
}
public int getDayLength() {
return lastDayIndex - firstDayIndex + 1;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/persistence/NurseRosterSolutionFileIO.java | package ai.timefold.solver.examples.nurserostering.persistence;
import java.io.File;
import java.util.function.Function;
import java.util.stream.Collectors;
import ai.timefold.solver.examples.common.persistence.AbstractJsonSolutionFileIO;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
public class NurseRosterSolutionFileIO extends AbstractJsonSolutionFileIO<NurseRoster> {
public NurseRosterSolutionFileIO() {
super(NurseRoster.class);
}
@Override
public NurseRoster read(File inputSolutionFile) {
NurseRoster nurseRoster = super.read(inputSolutionFile);
/*
* Replace the duplicate Shift/ShiftDate instances by references to instances from the shiftList/shiftDateList.
*/
var requestsById = nurseRoster.getShiftDateList().stream()
.collect(Collectors.toMap(ShiftDate::getId, Function.identity()));
var shiftsById = nurseRoster.getShiftList().stream()
.collect(Collectors.toMap(Shift::getId, Function.identity()));
for (Employee employee : nurseRoster.getEmployeeList()) {
employee.setDayOffRequestMap(deduplicateMap(employee.getDayOffRequestMap(), requestsById, ShiftDate::getId));
employee.setDayOnRequestMap(deduplicateMap(employee.getDayOnRequestMap(), requestsById, ShiftDate::getId));
employee.setShiftOffRequestMap(deduplicateMap(employee.getShiftOffRequestMap(), shiftsById, Shift::getId));
employee.setShiftOnRequestMap(deduplicateMap(employee.getShiftOnRequestMap(), shiftsById, Shift::getId));
}
return nurseRoster;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/persistence/NurseRosteringExporter.java | package ai.timefold.solver.examples.nurserostering.persistence;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import ai.timefold.solver.examples.common.persistence.AbstractXmlSolutionExporter;
import ai.timefold.solver.examples.common.persistence.SolutionConverter;
import ai.timefold.solver.examples.nurserostering.app.NurseRosteringApp;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import org.jdom2.Element;
public class NurseRosteringExporter extends AbstractXmlSolutionExporter<NurseRoster> {
public static void main(String[] args) {
SolutionConverter<NurseRoster> converter = SolutionConverter.createExportConverter(NurseRosteringApp.DATA_DIR_NAME,
new NurseRosteringExporter(), new NurseRosterSolutionFileIO());
converter.convertAll();
}
@Override
public XmlOutputBuilder<NurseRoster> createXmlOutputBuilder() {
return new NurseRosteringOutputBuilder();
}
public static class NurseRosteringOutputBuilder extends XmlOutputBuilder<NurseRoster> {
private NurseRoster nurseRoster;
@Override
public void setSolution(NurseRoster solution) {
nurseRoster = solution;
}
@Override
public void writeSolution() throws IOException {
Element solutionElement = new Element("Solution");
document.setRootElement(solutionElement);
Element schedulingPeriodIDElement = new Element("SchedulingPeriodID");
schedulingPeriodIDElement.setText(nurseRoster.getCode());
solutionElement.addContent(schedulingPeriodIDElement);
Element competitorElement = new Element("Competitor");
competitorElement.setText("Geoffrey De Smet with Timefold");
solutionElement.addContent(competitorElement);
Element softConstraintsPenaltyElement = new Element("SoftConstraintsPenalty");
softConstraintsPenaltyElement.setText(Integer.toString(nurseRoster.getScore().softScore()));
solutionElement.addContent(softConstraintsPenaltyElement);
for (ShiftAssignment shiftAssignment : nurseRoster.getShiftAssignmentList()) {
Shift shift = shiftAssignment.getShift();
if (shift != null) {
Element assignmentElement = new Element("Assignment");
solutionElement.addContent(assignmentElement);
Element dateElement = new Element("Date");
dateElement.setText(shift.getShiftDate().getDate().format(DateTimeFormatter.ISO_DATE));
assignmentElement.addContent(dateElement);
Element employeeElement = new Element("Employee");
employeeElement.setText(shiftAssignment.getEmployee().getCode());
assignmentElement.addContent(employeeElement);
Element shiftTypeElement = new Element("ShiftType");
shiftTypeElement.setText(shift.getShiftType().getCode());
assignmentElement.addContent(shiftTypeElement);
}
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/persistence/NurseRosteringImporter.java | package ai.timefold.solver.examples.nurserostering.persistence;
import static java.time.temporal.ChronoUnit.DAYS;
import java.io.IOException;
import java.math.BigInteger;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.examples.common.persistence.AbstractXmlSolutionImporter;
import ai.timefold.solver.examples.common.persistence.SolutionConverter;
import ai.timefold.solver.examples.nurserostering.app.NurseRosteringApp;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.NurseRosterParametrization;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import ai.timefold.solver.examples.nurserostering.domain.ShiftType;
import ai.timefold.solver.examples.nurserostering.domain.ShiftTypeSkillRequirement;
import ai.timefold.solver.examples.nurserostering.domain.Skill;
import ai.timefold.solver.examples.nurserostering.domain.SkillProficiency;
import ai.timefold.solver.examples.nurserostering.domain.WeekendDefinition;
import ai.timefold.solver.examples.nurserostering.domain.contract.BooleanContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.Contract;
import ai.timefold.solver.examples.nurserostering.domain.contract.ContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.ContractLineType;
import ai.timefold.solver.examples.nurserostering.domain.contract.MinMaxContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.PatternContractLine;
import ai.timefold.solver.examples.nurserostering.domain.pattern.FreeBefore2DaysWithAWorkDayPattern;
import ai.timefold.solver.examples.nurserostering.domain.pattern.Pattern;
import ai.timefold.solver.examples.nurserostering.domain.pattern.ShiftType2DaysPattern;
import ai.timefold.solver.examples.nurserostering.domain.pattern.ShiftType3DaysPattern;
import ai.timefold.solver.examples.nurserostering.domain.pattern.WorkBeforeFreeSequencePattern;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOnRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOnRequest;
import org.jdom2.DataConversionException;
import org.jdom2.Element;
import org.jdom2.JDOMException;
public class NurseRosteringImporter extends AbstractXmlSolutionImporter<NurseRoster> {
public static void main(String[] args) {
SolutionConverter<NurseRoster> converter = SolutionConverter.createImportConverter(NurseRosteringApp.DATA_DIR_NAME,
new NurseRosteringImporter(), new NurseRosterSolutionFileIO());
converter.convertAll();
}
@Override
public XmlInputBuilder<NurseRoster> createXmlInputBuilder() {
return new NurseRosteringInputBuilder();
}
public static class NurseRosteringInputBuilder extends XmlInputBuilder<NurseRoster> {
protected Map<LocalDate, ShiftDate> shiftDateMap;
protected Map<String, Skill> skillMap;
protected Map<String, ShiftType> shiftTypeMap;
protected Map<Pair<LocalDate, String>, Shift> dateAndShiftTypeToShiftMap;
protected Map<Pair<DayOfWeek, ShiftType>, List<Shift>> dayOfWeekAndShiftTypeToShiftListMap;
protected Map<String, Pattern> patternMap;
protected Map<String, Contract> contractMap;
protected Map<String, Employee> employeeMap;
@Override
public NurseRoster readSolution() throws IOException, JDOMException {
// Note: javax.xml is terrible. JDom is much, much easier.
Element schedulingPeriodElement = document.getRootElement();
assertElementName(schedulingPeriodElement, "SchedulingPeriod");
NurseRoster nurseRoster = new NurseRoster(0L);
nurseRoster.setCode(schedulingPeriodElement.getAttribute("ID").getValue());
generateShiftDateList(nurseRoster,
schedulingPeriodElement.getChild("StartDate"),
schedulingPeriodElement.getChild("EndDate"));
generateNurseRosterInfo(nurseRoster);
readSkillList(nurseRoster, schedulingPeriodElement.getChild("Skills"));
readShiftTypeList(nurseRoster, schedulingPeriodElement.getChild("ShiftTypes"));
generateShiftList(nurseRoster);
readPatternList(nurseRoster, schedulingPeriodElement.getChild("Patterns"));
readContractList(nurseRoster, schedulingPeriodElement.getChild("Contracts"));
readEmployeeList(nurseRoster, schedulingPeriodElement.getChild("Employees"));
readRequiredEmployeeSizes(schedulingPeriodElement.getChild("CoverRequirements"));
readDayOffRequestList(nurseRoster, schedulingPeriodElement.getChild("DayOffRequests"));
readDayOnRequestList(nurseRoster, schedulingPeriodElement.getChild("DayOnRequests"));
readShiftOffRequestList(nurseRoster, schedulingPeriodElement.getChild("ShiftOffRequests"));
readShiftOnRequestList(nurseRoster, schedulingPeriodElement.getChild("ShiftOnRequests"));
createShiftAssignmentList(nurseRoster);
BigInteger possibleSolutionSize = BigInteger.valueOf(nurseRoster.getEmployeeList().size()).pow(
nurseRoster.getShiftAssignmentList().size());
logger.info("NurseRoster {} has {} skills, {} shiftTypes, {} patterns, {} contracts, {} employees," +
" {} shiftDates, {} shiftAssignments and {} requests with a search space of {}.",
getInputId(),
nurseRoster.getSkillList().size(),
nurseRoster.getShiftTypeList().size(),
nurseRoster.getPatternList().size(),
nurseRoster.getContractList().size(),
nurseRoster.getEmployeeList().size(),
nurseRoster.getShiftDateList().size(),
nurseRoster.getShiftAssignmentList().size(),
nurseRoster.getDayOffRequestList().size() + nurseRoster.getDayOnRequestList().size()
+ nurseRoster.getShiftOffRequestList().size() + nurseRoster.getShiftOnRequestList().size(),
getFlooredPossibleSolutionSize(possibleSolutionSize));
return nurseRoster;
}
private void generateShiftDateList(NurseRoster nurseRoster, Element startDateElement, Element endDateElement) {
LocalDate startDate;
try {
startDate = LocalDate.parse(startDateElement.getText(), DateTimeFormatter.ISO_DATE);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Invalid startDate (" + startDateElement.getText() + ").", e);
}
LocalDate endDate;
try {
endDate = LocalDate.parse(endDateElement.getText(), DateTimeFormatter.ISO_DATE);
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Invalid endDate (" + endDateElement.getText() + ").", e);
}
if (startDate.compareTo(endDate) >= 0) {
throw new IllegalStateException("The startDate (" + startDate + " must be before endDate (" + endDate + ").");
}
int maxDayIndex = Math.toIntExact(DAYS.between(startDate, endDate));
int shiftDateSize = maxDayIndex + 1;
List<ShiftDate> shiftDateList = new ArrayList<>(shiftDateSize);
shiftDateMap = new LinkedHashMap<>(shiftDateSize);
long id = 0L;
int dayIndex = 0;
LocalDate date = startDate;
for (int i = 0; i < shiftDateSize; i++) {
ShiftDate shiftDate = new ShiftDate(id, dayIndex, date);
shiftDate.setShiftList(new ArrayList<>());
shiftDateList.add(shiftDate);
shiftDateMap.put(date, shiftDate);
id++;
dayIndex++;
date = date.plusDays(1);
}
nurseRoster.setShiftDateList(shiftDateList);
}
private void generateNurseRosterInfo(NurseRoster nurseRoster) {
List<ShiftDate> shiftDateList = nurseRoster.getShiftDateList();
NurseRosterParametrization nurseRosterParametrization = new NurseRosterParametrization(0L,
shiftDateList.get(0), shiftDateList.get(shiftDateList.size() - 1), shiftDateList.get(0));
nurseRoster.setNurseRosterParametrization(nurseRosterParametrization);
}
private void readSkillList(NurseRoster nurseRoster, Element skillsElement) {
List<Skill> skillList;
if (skillsElement == null) {
skillList = Collections.emptyList();
} else {
List<Element> skillElementList = skillsElement.getChildren();
skillList = new ArrayList<>(skillElementList.size());
skillMap = new LinkedHashMap<>(skillElementList.size());
long id = 0L;
for (Element element : skillElementList) {
assertElementName(element, "Skill");
Skill skill = new Skill(id, element.getText());
skillList.add(skill);
if (skillMap.containsKey(skill.getCode())) {
throw new IllegalArgumentException("There are 2 skills with the same code ("
+ skill.getCode() + ").");
}
skillMap.put(skill.getCode(), skill);
id++;
}
}
nurseRoster.setSkillList(skillList);
}
private void readShiftTypeList(NurseRoster nurseRoster, Element shiftTypesElement) {
List<Element> shiftTypeElementList = shiftTypesElement.getChildren();
List<ShiftType> shiftTypeList = new ArrayList<>(shiftTypeElementList.size());
shiftTypeMap = new LinkedHashMap<>(shiftTypeElementList.size());
long id = 0L;
int index = 0;
List<ShiftTypeSkillRequirement> shiftTypeSkillRequirementList = new ArrayList<>(shiftTypeElementList.size() * 2);
long shiftTypeSkillRequirementId = 0L;
for (Element element : shiftTypeElementList) {
assertElementName(element, "Shift");
String startTimeString = element.getChild("StartTime").getText();
String endTimeString = element.getChild("EndTime").getText();
ShiftType shiftType = new ShiftType(id, element.getAttribute("ID").getValue(), index,
startTimeString, endTimeString, startTimeString.compareTo(endTimeString) > 0,
element.getChild("Description").getText());
Element skillsElement = element.getChild("Skills");
if (skillsElement != null) {
List<Element> skillElementList = skillsElement.getChildren();
for (Element skillElement : skillElementList) {
assertElementName(skillElement, "Skill");
Skill skill = skillMap.get(skillElement.getText());
if (skill == null) {
throw new IllegalArgumentException("The skill (" + skillElement.getText()
+ ") of shiftType (" + shiftType.getCode() + ") does not exist.");
}
ShiftTypeSkillRequirement shiftTypeSkillRequirement =
new ShiftTypeSkillRequirement(shiftTypeSkillRequirementId, shiftType, skill);
shiftTypeSkillRequirementList.add(shiftTypeSkillRequirement);
shiftTypeSkillRequirementId++;
}
}
shiftTypeList.add(shiftType);
if (shiftTypeMap.containsKey(shiftType.getCode())) {
throw new IllegalArgumentException("There are 2 shiftTypes with the same code ("
+ shiftType.getCode() + ").");
}
shiftTypeMap.put(shiftType.getCode(), shiftType);
id++;
index++;
}
nurseRoster.setShiftTypeList(shiftTypeList);
nurseRoster.setShiftTypeSkillRequirementList(shiftTypeSkillRequirementList);
}
private void generateShiftList(NurseRoster nurseRoster) {
List<ShiftType> shiftTypeList = nurseRoster.getShiftTypeList();
int shiftListSize = shiftDateMap.size() * shiftTypeList.size();
List<Shift> shiftList = new ArrayList<>(shiftListSize);
dateAndShiftTypeToShiftMap = new LinkedHashMap<>(shiftListSize);
dayOfWeekAndShiftTypeToShiftListMap = new LinkedHashMap<>(7 * shiftTypeList.size());
long id = 0L;
int index = 0;
for (ShiftDate shiftDate : nurseRoster.getShiftDateList()) {
for (ShiftType shiftType : shiftTypeList) {
// Required employee size filled in later.
Shift shift = new Shift(id, shiftDate, shiftType, index, 0);
shiftDate.getShiftList().add(shift);
shiftList.add(shift);
LocalDate key = shiftDate.getDate();
String value = shiftType.getCode();
dateAndShiftTypeToShiftMap.put(new Pair<>(key, value), shift);
addShiftToDayOfWeekAndShiftTypeToShiftListMap(shiftDate, shiftType, shift);
id++;
index++;
}
}
nurseRoster.setShiftList(shiftList);
}
private void addShiftToDayOfWeekAndShiftTypeToShiftListMap(ShiftDate shiftDate, ShiftType shiftType, Shift shift) {
DayOfWeek key1 = shiftDate.getDayOfWeek();
Pair<DayOfWeek, ShiftType> key = new Pair<>(key1, shiftType);
List<Shift> dayOfWeekAndShiftTypeToShiftList = dayOfWeekAndShiftTypeToShiftListMap.computeIfAbsent(key,
k -> new ArrayList<>((shiftDateMap.size() + 6) / 7));
dayOfWeekAndShiftTypeToShiftList.add(shift);
}
private void readPatternList(NurseRoster nurseRoster, Element patternsElement) throws JDOMException {
List<Pattern> patternList;
if (patternsElement == null) {
patternList = Collections.emptyList();
} else {
List<Element> patternElementList = patternsElement.getChildren();
patternList = new ArrayList<>(patternElementList.size());
patternMap = new LinkedHashMap<>(patternElementList.size());
long id = 0L;
for (Element element : patternElementList) {
assertElementName(element, "Pattern");
String code = element.getAttribute("ID").getValue();
int weight = element.getAttribute("weight").getIntValue();
List<Element> patternEntryElementList = element.getChild("PatternEntries")
.getChildren();
if (patternEntryElementList.size() < 2) {
throw new IllegalArgumentException("The size of PatternEntries ("
+ patternEntryElementList.size() + ") of pattern (" + code + ") should be at least 2.");
}
Pattern pattern;
if (patternEntryElementList.get(0).getChild("ShiftType").getText().equals("None")) {
pattern = new FreeBefore2DaysWithAWorkDayPattern(id, code);
if (patternEntryElementList.size() != 3) {
throw new IllegalStateException("boe");
}
} else if (patternEntryElementList.get(1).getChild("ShiftType").getText().equals("None")) {
throw new UnsupportedOperationException("The pattern (" + code + ") is not supported."
+ " None of the test data exhibits such a pattern.");
} else {
switch (patternEntryElementList.size()) {
case 2:
pattern = new ShiftType2DaysPattern(id, code);
break;
case 3:
pattern = new ShiftType3DaysPattern(id, code);
break;
default:
throw new IllegalArgumentException("A size of PatternEntries ("
+ patternEntryElementList.size() + ") of pattern (" + code
+ ") above 3 is not supported.");
}
}
pattern.setWeight(weight);
int patternEntryIndex = 0;
DayOfWeek firstDayOfWeek = null;
for (Element patternEntryElement : patternEntryElementList) {
assertElementName(patternEntryElement, "PatternEntry");
Element shiftTypeElement = patternEntryElement.getChild("ShiftType");
boolean shiftTypeIsNone;
ShiftType shiftType;
if (shiftTypeElement.getText().equals("Any")) {
shiftTypeIsNone = false;
shiftType = null;
} else if (shiftTypeElement.getText().equals("None")) {
shiftTypeIsNone = true;
shiftType = null;
} else {
shiftTypeIsNone = false;
shiftType = shiftTypeMap.get(shiftTypeElement.getText());
if (shiftType == null) {
throw new IllegalArgumentException("The shiftType (" + shiftTypeElement.getText()
+ ") of pattern (" + pattern.getCode() + ") does not exist.");
}
}
Element dayElement = patternEntryElement.getChild("Day");
DayOfWeek dayOfWeek;
if (dayElement.getText().equals("Any")) {
dayOfWeek = null;
} else {
dayOfWeek = null;
for (DayOfWeek possibleDayOfWeek : DayOfWeek.values()) {
if (possibleDayOfWeek.name().equalsIgnoreCase(dayElement.getText())) {
dayOfWeek = possibleDayOfWeek;
break;
}
}
if (dayOfWeek == null) {
throw new IllegalArgumentException("The dayOfWeek (" + dayElement.getText()
+ ") of pattern (" + pattern.getCode() + ") does not exist.");
}
}
if (patternEntryIndex == 0) {
firstDayOfWeek = dayOfWeek;
} else {
if (firstDayOfWeek != null) {
int distance = dayOfWeek.getValue() - firstDayOfWeek.getValue();
if (distance < 0) {
distance += 7;
}
if (distance != patternEntryIndex) {
throw new IllegalArgumentException("On patternEntryIndex (" + patternEntryIndex
+ ") of pattern (" + pattern.getCode()
+ ") the dayOfWeek (" + dayOfWeek
+ ") is not valid with previous entries.");
}
} else {
if (dayOfWeek != null) {
throw new IllegalArgumentException("On patternEntryIndex (" + patternEntryIndex
+ ") of pattern (" + pattern.getCode()
+ ") the dayOfWeek should be (Any), in line with previous entries.");
}
}
}
if (pattern instanceof FreeBefore2DaysWithAWorkDayPattern castedPattern) {
if (patternEntryIndex == 0) {
if (dayOfWeek == null) {
throw new UnsupportedOperationException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the dayOfWeek should not be (Any)."
+ "\n None of the test data exhibits such a pattern.");
}
castedPattern.setFreeDayOfWeek(dayOfWeek);
}
if (patternEntryIndex == 1) {
if (shiftType != null) {
throw new UnsupportedOperationException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the shiftType should be (Any)."
+ "\n None of the test data exhibits such a pattern.");
}
}
if (patternEntryIndex != 0 && shiftTypeIsNone) {
throw new IllegalArgumentException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the shiftType cannot be (None).");
}
} else if (pattern instanceof WorkBeforeFreeSequencePattern castedPattern) {
if (patternEntryIndex == 0) {
castedPattern.setWorkDayOfWeek(dayOfWeek);
castedPattern.setWorkShiftType(shiftType);
castedPattern.setFreeDayLength(patternEntryElementList.size() - 1);
}
if (patternEntryIndex != 0 && !shiftTypeIsNone) {
throw new IllegalArgumentException("On patternEntryIndex (" + patternEntryIndex
+ ") of WorkBeforeFreeSequence pattern (" + pattern.getCode()
+ ") the shiftType should be (None).");
}
} else if (pattern instanceof ShiftType2DaysPattern castedPattern) {
if (patternEntryIndex == 0) {
if (dayOfWeek != null) {
throw new UnsupportedOperationException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the dayOfWeek should be (Any)."
+ "\n None of the test data exhibits such a pattern.");
}
}
if (shiftType == null) {
throw new UnsupportedOperationException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the shiftType should not be (Any)."
+ "\n None of the test data exhibits such a pattern.");
}
switch (patternEntryIndex) {
case 0:
castedPattern.setDayIndex0ShiftType(shiftType);
break;
case 1:
castedPattern.setDayIndex1ShiftType(shiftType);
break;
default:
throw new IllegalArgumentException("The patternEntryIndex ("
+ patternEntryIndex + ") is not supported.");
}
} else if (pattern instanceof ShiftType3DaysPattern castedPattern) {
if (patternEntryIndex == 0) {
if (dayOfWeek != null) {
throw new UnsupportedOperationException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the dayOfWeek should be (Any)."
+ "\n None of the test data exhibits such a pattern.");
}
}
if (shiftType == null) {
throw new UnsupportedOperationException("On patternEntryIndex (" + patternEntryIndex
+ ") of FreeBeforeWorkSequence pattern (" + pattern.getCode()
+ ") the shiftType should not be (Any)."
+ "\n None of the test data exhibits such a pattern.");
}
switch (patternEntryIndex) {
case 0:
castedPattern.setDayIndex0ShiftType(shiftType);
break;
case 1:
castedPattern.setDayIndex1ShiftType(shiftType);
break;
case 2:
castedPattern.setDayIndex2ShiftType(shiftType);
break;
default:
throw new IllegalArgumentException("The patternEntryIndex ("
+ patternEntryIndex + ") is not supported.");
}
} else {
throw new IllegalStateException("Unsupported patternClass (" + pattern.getClass() + ").");
}
patternEntryIndex++;
}
patternList.add(pattern);
if (patternMap.containsKey(pattern.getCode())) {
throw new IllegalArgumentException("There are 2 patterns with the same code ("
+ pattern.getCode() + ").");
}
patternMap.put(pattern.getCode(), pattern);
id++;
}
}
nurseRoster.setPatternList(patternList);
}
private void readContractList(NurseRoster nurseRoster, Element contractsElement) throws JDOMException {
int contractLineTypeListSize = ContractLineType.values().length;
List<Element> contractElementList = contractsElement.getChildren();
List<Contract> contractList = new ArrayList<>(contractElementList.size());
contractMap = new LinkedHashMap<>(contractElementList.size());
long id = 0L;
List<ContractLine> contractLineList = new ArrayList<>(
contractElementList.size() * contractLineTypeListSize);
long contractLineId = 0L;
List<PatternContractLine> patternContractLineList = new ArrayList<>(
contractElementList.size() * 3);
long patternContractLineId = 0L;
for (Element element : contractElementList) {
assertElementName(element, "Contract");
Contract contract = new Contract(id, element.getAttribute("ID").getValue(),
element.getChild("Description").getText());
List<ContractLine> contractLineListOfContract = new ArrayList<>(contractLineTypeListSize);
contractLineId = readBooleanContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("SingleAssignmentPerDay"),
ContractLineType.SINGLE_ASSIGNMENT_PER_DAY);
contractLineId = readMinMaxContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("MinNumAssignments"),
element.getChild("MaxNumAssignments"),
ContractLineType.TOTAL_ASSIGNMENTS);
contractLineId = readMinMaxContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("MinConsecutiveWorkingDays"),
element.getChild("MaxConsecutiveWorkingDays"),
ContractLineType.CONSECUTIVE_WORKING_DAYS);
contractLineId = readMinMaxContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("MinConsecutiveFreeDays"),
element.getChild("MaxConsecutiveFreeDays"),
ContractLineType.CONSECUTIVE_FREE_DAYS);
contractLineId = readMinMaxContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("MinConsecutiveWorkingWeekends"),
element.getChild("MaxConsecutiveWorkingWeekends"),
ContractLineType.CONSECUTIVE_WORKING_WEEKENDS);
contractLineId = readMinMaxContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, null,
element.getChild("MaxWorkingWeekendsInFourWeeks"),
ContractLineType.TOTAL_WORKING_WEEKENDS_IN_FOUR_WEEKS);
WeekendDefinition weekendDefinition = WeekendDefinition.valueOfCode(
element.getChild("WeekendDefinition").getText());
contract.setWeekendDefinition(weekendDefinition);
contractLineId = readBooleanContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("CompleteWeekends"),
ContractLineType.COMPLETE_WEEKENDS);
contractLineId = readBooleanContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("IdenticalShiftTypesDuringWeekend"),
ContractLineType.IDENTICAL_SHIFT_TYPES_DURING_WEEKEND);
contractLineId = readBooleanContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("NoNightShiftBeforeFreeWeekend"),
ContractLineType.NO_NIGHT_SHIFT_BEFORE_FREE_WEEKEND);
contractLineId = readBooleanContractLine(contract, contractLineList, contractLineListOfContract,
contractLineId, element.getChild("AlternativeSkillCategory"),
ContractLineType.ALTERNATIVE_SKILL_CATEGORY);
contract.setContractLineList(contractLineListOfContract);
List<Element> unwantedPatternElementList = element.getChild("UnwantedPatterns")
.getChildren();
for (Element patternElement : unwantedPatternElementList) {
assertElementName(patternElement, "Pattern");
Pattern pattern = patternMap.get(patternElement.getText());
if (pattern == null) {
throw new IllegalArgumentException("The pattern (" + patternElement.getText()
+ ") of contract (" + contract.getCode() + ") does not exist.");
}
PatternContractLine patternContractLine = new PatternContractLine(patternContractLineId, contract, pattern);
patternContractLineList.add(patternContractLine);
patternContractLineId++;
}
contractList.add(contract);
if (contractMap.containsKey(contract.getCode())) {
throw new IllegalArgumentException("There are 2 contracts with the same code ("
+ contract.getCode() + ").");
}
contractMap.put(contract.getCode(), contract);
id++;
}
nurseRoster.setContractList(contractList);
nurseRoster.setContractLineList(contractLineList);
nurseRoster.setPatternContractLineList(patternContractLineList);
}
private long readBooleanContractLine(Contract contract, List<ContractLine> contractLineList,
List<ContractLine> contractLineListOfContract, long contractLineId, Element element,
ContractLineType contractLineType) throws DataConversionException {
boolean enabled = Boolean.parseBoolean(element.getText());
int weight;
if (enabled) {
weight = element.getAttribute("weight").getIntValue();
if (weight < 0) {
throw new IllegalArgumentException("The weight (" + weight
+ ") of contract (" + contract.getCode() + ") and contractLineType (" + contractLineType
+ ") should be 0 or at least 1.");
} else if (weight == 0) {
// If the weight is zero, the constraint should not be considered.
enabled = false;
logger.warn("In contract ({}), the contractLineType ({}) is enabled with weight 0.",
contract.getCode(), contractLineType);
}
} else {
weight = 0;
}
if (enabled) {
BooleanContractLine contractLine =
new BooleanContractLine(contractLineId, contract, contractLineType, enabled, weight);
contractLineList.add(contractLine);
contractLineListOfContract.add(contractLine);
contractLineId++;
}
return contractLineId;
}
private long readMinMaxContractLine(Contract contract, List<ContractLine> contractLineList,
List<ContractLine> contractLineListOfContract, long contractLineId,
Element minElement, Element maxElement,
ContractLineType contractLineType) throws DataConversionException {
boolean minimumEnabled = minElement != null && minElement.getAttribute("on").getBooleanValue();
int minimumWeight;
if (minimumEnabled) {
minimumWeight = minElement.getAttribute("weight").getIntValue();
if (minimumWeight < 0) {
throw new IllegalArgumentException("The minimumWeight (" + minimumWeight
+ ") of contract (" + contract.getCode() + ") and contractLineType (" + contractLineType
+ ") should be 0 or at least 1.");
} else if (minimumWeight == 0) {
// If the weight is zero, the constraint should not be considered.
minimumEnabled = false;
logger.warn("In contract ({}), the contractLineType ({}) minimum is enabled with weight 0.",
contract.getCode(), contractLineType);
}
} else {
minimumWeight = 0;
}
boolean maximumEnabled = maxElement != null && maxElement.getAttribute("on").getBooleanValue();
int maximumWeight;
if (maximumEnabled) {
maximumWeight = maxElement.getAttribute("weight").getIntValue();
if (maximumWeight < 0) {
throw new IllegalArgumentException("The maximumWeight (" + maximumWeight
+ ") of contract (" + contract.getCode() + ") and contractLineType (" + contractLineType
+ ") should be 0 or at least 1.");
} else if (maximumWeight == 0) {
// If the weight is zero, the constraint should not be considered.
maximumEnabled = false;
logger.warn("In contract ({}), the contractLineType ({}) maximum is enabled with weight 0.",
contract.getCode(), contractLineType);
}
} else {
maximumWeight = 0;
}
if (minimumEnabled || maximumEnabled) {
MinMaxContractLine contractLine =
new MinMaxContractLine(contractLineId, contract, contractLineType, minimumEnabled, maximumEnabled);
if (minimumEnabled) {
int minimumValue = Integer.parseInt(minElement.getText());
if (minimumValue < 1) {
throw new IllegalArgumentException("The minimumValue (" + minimumValue
+ ") of contract (" + contract.getCode() + ") and contractLineType ("
+ contractLineType + ") should be at least 1.");
}
contractLine.setMinimumValue(minimumValue);
contractLine.setMinimumWeight(minimumWeight);
}
if (maximumEnabled) {
int maximumValue = Integer.parseInt(maxElement.getText());
if (maximumValue < 0) {
throw new IllegalArgumentException("The maximumValue (" + maximumValue
+ ") of contract (" + contract.getCode() + ") and contractLineType ("
+ contractLineType + ") should be at least 0.");
}
contractLine.setMaximumValue(maximumValue);
contractLine.setMaximumWeight(maximumWeight);
}
contractLineList.add(contractLine);
contractLineListOfContract.add(contractLine);
contractLineId++;
}
return contractLineId;
}
private void readEmployeeList(NurseRoster nurseRoster, Element employeesElement) {
List<Element> employeeElementList = employeesElement.getChildren();
List<Employee> employeeList = new ArrayList<>(employeeElementList.size());
employeeMap = new LinkedHashMap<>(employeeElementList.size());
long id = 0L;
List<SkillProficiency> skillProficiencyList = new ArrayList<>(employeeElementList.size() * 2);
long skillProficiencyId = 0L;
for (Element element : employeeElementList) {
assertElementName(element, "Employee");
String code = element.getAttribute("ID").getValue();
Element contractElement = element.getChild("ContractID");
Contract contract = contractMap.get(contractElement.getText());
if (contract == null) {
throw new IllegalArgumentException("The contract (" + contractElement.getText()
+ ") of employee (" + code + ") does not exist.");
}
Employee employee = new Employee(id, code, element.getChild("Name").getText(), contract);
int estimatedRequestSize = (shiftDateMap.size() / employeeElementList.size()) + 1;
employee.setDayOffRequestMap(new LinkedHashMap<>(estimatedRequestSize));
employee.setDayOnRequestMap(new LinkedHashMap<>(estimatedRequestSize));
employee.setShiftOffRequestMap(new LinkedHashMap<>(estimatedRequestSize));
employee.setShiftOnRequestMap(new LinkedHashMap<>(estimatedRequestSize));
Element skillsElement = element.getChild("Skills");
if (skillsElement != null) {
List<Element> skillElementList = skillsElement.getChildren();
for (Element skillElement : skillElementList) {
assertElementName(skillElement, "Skill");
Skill skill = skillMap.get(skillElement.getText());
if (skill == null) {
throw new IllegalArgumentException("The skill (" + skillElement.getText()
+ ") of employee (" + employee.getCode() + ") does not exist.");
}
SkillProficiency skillProficiency = new SkillProficiency(skillProficiencyId, employee, skill);
skillProficiencyList.add(skillProficiency);
skillProficiencyId++;
}
}
employeeList.add(employee);
if (employeeMap.containsKey(employee.getCode())) {
throw new IllegalArgumentException("There are 2 employees with the same code ("
+ employee.getCode() + ").");
}
employeeMap.put(employee.getCode(), employee);
id++;
}
nurseRoster.setEmployeeList(employeeList);
nurseRoster.setSkillProficiencyList(skillProficiencyList);
}
private void readRequiredEmployeeSizes(Element coverRequirementsElement) {
List<Element> coverRequirementElementList = coverRequirementsElement.getChildren();
for (Element element : coverRequirementElementList) {
if (element.getName().equals("DayOfWeekCover")) {
Element dayOfWeekElement = element.getChild("Day");
DayOfWeek dayOfWeek = null;
for (DayOfWeek possibleDayOfWeek : DayOfWeek.values()) {
if (possibleDayOfWeek.name().equalsIgnoreCase(dayOfWeekElement.getText())) {
dayOfWeek = possibleDayOfWeek;
break;
}
}
if (dayOfWeek == null) {
throw new IllegalArgumentException("The dayOfWeek (" + dayOfWeekElement.getText()
+ ") of an entity DayOfWeekCover does not exist.");
}
List<Element> coverElementList = element.getChildren("Cover");
for (Element coverElement : coverElementList) {
Element shiftTypeElement = coverElement.getChild("Shift");
ShiftType shiftType = shiftTypeMap.get(shiftTypeElement.getText());
if (shiftType == null) {
if (shiftTypeElement.getText().equals("Any")) {
throw new IllegalStateException("The shiftType Any is not supported on DayOfWeekCover.");
} else if (shiftTypeElement.getText().equals("None")) {
throw new IllegalStateException("The shiftType None is not supported on DayOfWeekCover.");
} else {
throw new IllegalArgumentException("The shiftType (" + shiftTypeElement.getText()
+ ") of an entity DayOfWeekCover does not exist.");
}
}
Pair<DayOfWeek, ShiftType> key = new Pair<>(dayOfWeek, shiftType);
List<Shift> shiftList = dayOfWeekAndShiftTypeToShiftListMap.get(key);
if (shiftList == null) {
throw new IllegalArgumentException("The dayOfWeek (" + dayOfWeekElement.getText()
+ ") with the shiftType (" + shiftTypeElement.getText()
+ ") of an entity DayOfWeekCover does not have any shifts.");
}
int requiredEmployeeSize = Integer.parseInt(coverElement.getChild("Preferred").getText());
for (Shift shift : shiftList) {
shift.setRequiredEmployeeSize(shift.getRequiredEmployeeSize() + requiredEmployeeSize);
}
}
} else if (element.getName().equals("DateSpecificCover")) {
Element dateElement = element.getChild("Date");
List<Element> coverElementList = element.getChildren("Cover");
for (Element coverElement : coverElementList) {
Element shiftTypeElement = coverElement.getChild("Shift");
LocalDate date = LocalDate.parse(dateElement.getText(), DateTimeFormatter.ISO_DATE);
String value = shiftTypeElement.getText();
Shift shift = dateAndShiftTypeToShiftMap.get(new Pair<>(date, value));
if (shift == null) {
throw new IllegalArgumentException("The date (" + dateElement.getText()
+ ") with the shiftType (" + shiftTypeElement.getText()
+ ") of an entity DateSpecificCover does not have a shift.");
}
int requiredEmployeeSize = Integer.parseInt(coverElement.getChild("Preferred").getText());
shift.setRequiredEmployeeSize(shift.getRequiredEmployeeSize() + requiredEmployeeSize);
}
} else {
throw new IllegalArgumentException("Unknown cover entity (" + element.getName() + ").");
}
}
}
private void readDayOffRequestList(NurseRoster nurseRoster, Element dayOffRequestsElement) throws JDOMException {
List<DayOffRequest> dayOffRequestList;
if (dayOffRequestsElement == null) {
dayOffRequestList = Collections.emptyList();
} else {
List<Element> dayOffElementList = dayOffRequestsElement.getChildren();
dayOffRequestList = new ArrayList<>(dayOffElementList.size());
long id = 0L;
for (Element element : dayOffElementList) {
assertElementName(element, "DayOff");
Element employeeElement = element.getChild("EmployeeID");
Employee employee = employeeMap.get(employeeElement.getText());
if (employee == null) {
throw new IllegalArgumentException("The shiftDate (" + employeeElement.getText()
+ ") of dayOffRequest (" + id + ") does not exist.");
}
Element dateElement = element.getChild("Date");
ShiftDate shiftDate = shiftDateMap.get(LocalDate.parse(dateElement.getText(), DateTimeFormatter.ISO_DATE));
if (shiftDate == null) {
throw new IllegalArgumentException("The date (" + dateElement.getText()
+ ") of dayOffRequest (" + id + ") does not exist.");
}
DayOffRequest dayOffRequest =
new DayOffRequest(id, employee, shiftDate, element.getAttribute("weight").getIntValue());
dayOffRequestList.add(dayOffRequest);
employee.getDayOffRequestMap().put(shiftDate, dayOffRequest);
id++;
}
}
nurseRoster.setDayOffRequestList(dayOffRequestList);
}
private void readDayOnRequestList(NurseRoster nurseRoster, Element dayOnRequestsElement) throws JDOMException {
List<DayOnRequest> dayOnRequestList;
if (dayOnRequestsElement == null) {
dayOnRequestList = Collections.emptyList();
} else {
List<Element> dayOnElementList = dayOnRequestsElement.getChildren();
dayOnRequestList = new ArrayList<>(dayOnElementList.size());
long id = 0L;
for (Element element : dayOnElementList) {
assertElementName(element, "DayOn");
Element employeeElement = element.getChild("EmployeeID");
Employee employee = employeeMap.get(employeeElement.getText());
if (employee == null) {
throw new IllegalArgumentException("The shiftDate (" + employeeElement.getText()
+ ") of dayOnRequest (" + id + ") does not exist.");
}
Element dateElement = element.getChild("Date");
ShiftDate shiftDate = shiftDateMap.get(LocalDate.parse(dateElement.getText(), DateTimeFormatter.ISO_DATE));
if (shiftDate == null) {
throw new IllegalArgumentException("The date (" + dateElement.getText()
+ ") of dayOnRequest (" + id + ") does not exist.");
}
DayOnRequest dayOnRequest =
new DayOnRequest(id, employee, shiftDate, element.getAttribute("weight").getIntValue());
dayOnRequestList.add(dayOnRequest);
employee.getDayOnRequestMap().put(shiftDate, dayOnRequest);
id++;
}
}
nurseRoster.setDayOnRequestList(dayOnRequestList);
}
private void readShiftOffRequestList(NurseRoster nurseRoster, Element shiftOffRequestsElement) throws JDOMException {
List<ShiftOffRequest> shiftOffRequestList;
if (shiftOffRequestsElement == null) {
shiftOffRequestList = Collections.emptyList();
} else {
List<Element> shiftOffElementList = shiftOffRequestsElement.getChildren();
shiftOffRequestList = new ArrayList<>(shiftOffElementList.size());
long id = 0L;
for (Element element : shiftOffElementList) {
assertElementName(element, "ShiftOff");
Element employeeElement = element.getChild("EmployeeID");
Employee employee = employeeMap.get(employeeElement.getText());
if (employee == null) {
throw new IllegalArgumentException("The shift (" + employeeElement.getText()
+ ") of shiftOffRequest (" + id + ") does not exist.");
}
Element dateElement = element.getChild("Date");
Element shiftTypeElement = element.getChild("ShiftTypeID");
LocalDate date = LocalDate.parse(dateElement.getText(), DateTimeFormatter.ISO_DATE);
String value = shiftTypeElement.getText();
Shift shift = dateAndShiftTypeToShiftMap.get(new Pair<>(date, value));
if (shift == null) {
throw new IllegalArgumentException("The date (" + dateElement.getText()
+ ") or the shiftType (" + shiftTypeElement.getText()
+ ") of shiftOffRequest (" + id + ") does not exist.");
}
ShiftOffRequest shiftOffRequest =
new ShiftOffRequest(id, employee, shift, element.getAttribute("weight").getIntValue());
shiftOffRequestList.add(shiftOffRequest);
employee.getShiftOffRequestMap().put(shift, shiftOffRequest);
id++;
}
}
nurseRoster.setShiftOffRequestList(shiftOffRequestList);
}
private void readShiftOnRequestList(NurseRoster nurseRoster, Element shiftOnRequestsElement) throws JDOMException {
List<ShiftOnRequest> shiftOnRequestList;
if (shiftOnRequestsElement == null) {
shiftOnRequestList = Collections.emptyList();
} else {
List<Element> shiftOnElementList = shiftOnRequestsElement.getChildren();
shiftOnRequestList = new ArrayList<>(shiftOnElementList.size());
long id = 0L;
for (Element element : shiftOnElementList) {
assertElementName(element, "ShiftOn");
Element employeeElement = element.getChild("EmployeeID");
Employee employee = employeeMap.get(employeeElement.getText());
if (employee == null) {
throw new IllegalArgumentException("The shift (" + employeeElement.getText()
+ ") of shiftOnRequest (" + id + ") does not exist.");
}
Element dateElement = element.getChild("Date");
Element shiftTypeElement = element.getChild("ShiftTypeID");
LocalDate date = LocalDate.parse(dateElement.getText(), DateTimeFormatter.ISO_DATE);
String value = shiftTypeElement.getText();
Shift shift = dateAndShiftTypeToShiftMap.get(new Pair<>(date, value));
if (shift == null) {
throw new IllegalArgumentException("The date (" + dateElement.getText()
+ ") or the shiftType (" + shiftTypeElement.getText()
+ ") of shiftOnRequest (" + id + ") does not exist.");
}
ShiftOnRequest shiftOnRequest =
new ShiftOnRequest(id, employee, shift, element.getAttribute("weight").getIntValue());
shiftOnRequestList.add(shiftOnRequest);
employee.getShiftOnRequestMap().put(shift, shiftOnRequest);
id++;
}
}
nurseRoster.setShiftOnRequestList(shiftOnRequestList);
}
private void createShiftAssignmentList(NurseRoster nurseRoster) {
List<Shift> shiftList = nurseRoster.getShiftList();
List<ShiftAssignment> shiftAssignmentList = new ArrayList<>(shiftList.size());
long id = 0L;
for (Shift shift : shiftList) {
for (int i = 0; i < shift.getRequiredEmployeeSize(); i++) {
ShiftAssignment shiftAssignment = new ShiftAssignment(id, shift, i);
id++;
// Notice that we leave the PlanningVariable properties on null
shiftAssignmentList.add(shiftAssignment);
}
}
nurseRoster.setShiftAssignmentList(shiftAssignmentList);
}
}
private record Pair<A, B>(A key, B value) {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/score/NurseRosteringConstraintProvider.java | package ai.timefold.solver.examples.nurserostering.score;
import static ai.timefold.solver.examples.nurserostering.optional.score.EmployeeConsecutiveAssignmentEnd.getDistanceToLastDayOfWeekend;
import static ai.timefold.solver.examples.nurserostering.optional.score.EmployeeConsecutiveAssignmentEnd.isWeekendAndNotLastDayOfWeekend;
import static ai.timefold.solver.examples.nurserostering.optional.score.EmployeeConsecutiveAssignmentStart.getDistanceToFirstDayOfWeekend;
import static ai.timefold.solver.examples.nurserostering.optional.score.EmployeeConsecutiveAssignmentStart.isWeekendAndNotFirstDayOfWeekend;
import java.time.DayOfWeek;
import java.util.Arrays;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintCollectors;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.core.api.score.stream.bi.BiConstraintStream;
import ai.timefold.solver.core.api.score.stream.common.SequenceChain;
import ai.timefold.solver.core.api.score.stream.tri.TriConstraintStream;
import ai.timefold.solver.core.api.score.stream.tri.TriJoiner;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRosterParametrization;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import ai.timefold.solver.examples.nurserostering.domain.ShiftTypeSkillRequirement;
import ai.timefold.solver.examples.nurserostering.domain.SkillProficiency;
import ai.timefold.solver.examples.nurserostering.domain.contract.BooleanContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.ContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.ContractLineType;
import ai.timefold.solver.examples.nurserostering.domain.contract.MinMaxContractLine;
import ai.timefold.solver.examples.nurserostering.domain.contract.PatternContractLine;
import ai.timefold.solver.examples.nurserostering.domain.pattern.FreeBefore2DaysWithAWorkDayPattern;
import ai.timefold.solver.examples.nurserostering.domain.pattern.ShiftType2DaysPattern;
import ai.timefold.solver.examples.nurserostering.domain.pattern.ShiftType3DaysPattern;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.DayOnRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOffRequest;
import ai.timefold.solver.examples.nurserostering.domain.request.ShiftOnRequest;
public class NurseRosteringConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
oneShiftPerDay(constraintFactory),
minimumAndMaximumNumberOfAssignments(constraintFactory),
consecutiveWorkingDays(constraintFactory),
consecutiveFreeDays(constraintFactory),
maximumConsecutiveFreeDaysNoAssignments(constraintFactory),
consecutiveWorkingWeekends(constraintFactory),
startOnNotFirstDayOfWeekend(constraintFactory),
endOnNotLastDayOfWeekend(constraintFactory),
identicalShiftTypesDuringWeekend(constraintFactory),
dayOffRequest(constraintFactory),
dayOnRequest(constraintFactory),
shiftOffRequest(constraintFactory),
shiftOnRequest(constraintFactory),
alternativeSkill(constraintFactory),
unwantedPatternFreeBefore2DaysWithAWorkDayPattern(constraintFactory),
unwantedPatternShiftType2DaysPattern(constraintFactory),
unwantedPatternShiftType3DaysPattern(constraintFactory),
};
}
// ############################################################################
// Hard constraints
// ############################################################################
// A nurse can only work one shift per day, i.e. no two shift can be assigned to the same nurse on a day.
Constraint oneShiftPerDay(ConstraintFactory constraintFactory) {
return constraintFactory.forEachUniquePair(ShiftAssignment.class,
Joiners.equal(ShiftAssignment::getEmployee),
Joiners.equal(ShiftAssignment::getShiftDate))
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("oneShiftPerDay");
}
// ############################################################################
// Soft constraints
// ############################################################################
private static <A, B, C> TriConstraintStream<A, B, C> outerJoin(BiConstraintStream<A, B> source,
Class<C> joinedClass, TriJoiner<A, B, C> joiner) {
return source.join(joinedClass, joiner)
.concat(source.ifNotExists(joinedClass, joiner));
}
Constraint minimumAndMaximumNumberOfAssignments(ConstraintFactory constraintFactory) {
var assignmentLimitedEmployeeStream = constraintFactory
.forEach(MinMaxContractLine.class)
.filter(minMaxContractLine -> minMaxContractLine
.getContractLineType() == ContractLineType.TOTAL_ASSIGNMENTS && minMaxContractLine.isEnabled())
.join(Employee.class, Joiners.equal(ContractLine::getContract, Employee::getContract));
var assignmentLimitedOrUnassignedEmployeeStream =
outerJoin(assignmentLimitedEmployeeStream, ShiftAssignment.class,
Joiners.equal((contractLine, employee) -> employee, ShiftAssignment::getEmployee));
return assignmentLimitedOrUnassignedEmployeeStream
.groupBy((line, employee, shift) -> employee,
(line, employee, shift) -> line,
ConstraintCollectors.conditionally(
(line, employee, shift) -> shift != null,
ConstraintCollectors.countTri()))
.map((employee, contract, shiftCount) -> employee,
(employee, contract, shiftCount) -> contract,
(employee, contract, shiftCount) -> contract.getViolationAmount(shiftCount))
.filter((employee, contract, violationAmount) -> violationAmount != 0)
.penalize(HardSoftScore.ONE_SOFT, (employee, contract, violationAmount) -> violationAmount)
.indictWith((employee, contract, violationAmount) -> Arrays.asList(employee, contract))
.asConstraint("Minimum and maximum number of assignments");
}
// Min/Max consecutive working days
Constraint consecutiveWorkingDays(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(MinMaxContractLine.class)
.filter(minMaxContractLine -> minMaxContractLine
.getContractLineType() == ContractLineType.CONSECUTIVE_WORKING_DAYS &&
minMaxContractLine.isEnabled())
.join(ShiftAssignment.class,
Joiners.equal(ContractLine::getContract, ShiftAssignment::getContract))
.groupBy((contract, shift) -> shift.getEmployee(),
(contract, shift) -> contract,
ConstraintCollectors.toConsecutiveSequences((contract, shift) -> shift.getShiftDate(),
ShiftDate::getDayIndex))
.flattenLast(SequenceChain::getConsecutiveSequences)
.map((employee, contract, shiftList) -> employee,
(employee, contract, shiftList) -> contract,
(employee, contract, shiftList) -> contract.getViolationAmount(shiftList.getLength()))
.filter((contract, employee, violationAmount) -> violationAmount != 0)
.penalize(HardSoftScore.ONE_SOFT, (contract, employee, violationAmount) -> violationAmount)
.indictWith((contract, employee, violationAmount) -> Arrays.asList(employee, contract))
.asConstraint("consecutiveWorkingDays");
}
// Min/Max consecutive free days
Constraint consecutiveFreeDays(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(MinMaxContractLine.class)
.filter(minMaxContractLine -> minMaxContractLine
.getContractLineType() == ContractLineType.CONSECUTIVE_FREE_DAYS &&
minMaxContractLine.isEnabled())
.join(ShiftAssignment.class,
Joiners.equal(ContractLine::getContract, ShiftAssignment::getContract))
.groupBy((contract, shift) -> shift.getEmployee(),
(contract, shift) -> contract,
ConstraintCollectors.toConsecutiveSequences((contract, shift) -> shift.getShiftDate(),
ShiftDate::getDayIndex))
.flattenLast(SequenceChain::getConsecutiveSequences)
.join(NurseRosterParametrization.class)
.map((employee, contract, shiftSequence, nrp) -> employee,
(employee, contract, shiftSequence, nrp) -> contract,
(employee, contract, shiftSequence, nrp) -> {
// Use NurseRosterParametrization to compute and cache violations.
int total = 0;
if (!shiftSequence.isFirst()
&& contract.isViolated(shiftSequence.getPreviousBreak().getLength() - 1)) {
total += contract.getViolationAmount(shiftSequence.getPreviousBreak().getLength() - 1);
}
if (shiftSequence.isFirst()) {
int length = shiftSequence.getFirstItem().getDayIndex() - nrp.getFirstShiftDateDayIndex();
if (length > 0 && contract.isViolated(length)) {
total += contract.getViolationAmount(length);
}
}
if (shiftSequence.isLast()) {
int length = nrp.getLastShiftDateDayIndex() - shiftSequence.getLastItem().getDayIndex();
if (length > 0 && contract.isViolated(length)) {
total += contract.getViolationAmount(length);
}
}
return total;
})
.filter((employee, contract, violationAmount) -> violationAmount != 0)
.penalize(HardSoftScore.ONE_SOFT, (employee, contract, violationAmount) -> violationAmount)
.indictWith((employee, contract, violationAmount) -> Arrays.asList(employee, contract))
.asConstraint("consecutiveFreeDays");
}
Constraint maximumConsecutiveFreeDaysNoAssignments(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(MinMaxContractLine.class)
.filter(minMaxContractLine -> minMaxContractLine
.getContractLineType() == ContractLineType.CONSECUTIVE_FREE_DAYS &&
minMaxContractLine.isMaximumEnabled())
.join(Employee.class,
Joiners.equal(MinMaxContractLine::getContract, Employee::getContract))
.ifNotExists(ShiftAssignment.class,
Joiners.equal((contract, employee) -> employee, ShiftAssignment::getEmployee))
.join(NurseRosterParametrization.class,
Joiners.lessThan((contract, employee) -> contract.getMaximumValue(),
nrp -> nrp.getLastShiftDateDayIndex() - nrp.getFirstShiftDateDayIndex() + 1))
.penalize(HardSoftScore.ONE_SOFT,
(contract, employee, nrp) -> contract
.getViolationAmount(nrp.getLastShiftDateDayIndex() - nrp.getFirstShiftDateDayIndex() + 1))
.indictWith((contract, employee, nrp) -> Arrays.asList(employee, contract))
.asConstraint("maximumConsecutiveFreeDays (no shifts)");
}
// Min/Max consecutive working weekends
Constraint consecutiveWorkingWeekends(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(MinMaxContractLine.class)
.filter(minMaxContractLine -> minMaxContractLine
.getContractLineType() == ContractLineType.CONSECUTIVE_WORKING_WEEKENDS &&
minMaxContractLine.isEnabled())
.join(constraintFactory.forEach(ShiftAssignment.class)
.filter(ShiftAssignment::isWeekend),
Joiners.equal(ContractLine::getContract, ShiftAssignment::getContract))
.groupBy((contract, shift) -> shift.getEmployee(),
(contract, shift) -> contract,
ConstraintCollectors.toConsecutiveSequences((contract, shift) -> shift.getShiftDate(),
shiftDate -> shiftDate.getWeekendSundayIndex() / 7))
.flattenLast(SequenceChain::getConsecutiveSequences)
.map((employee, contract, shiftList) -> employee,
(employee, contract, shiftList) -> contract,
(employee, contract, shiftList) -> contract.getViolationAmount(shiftList.getLength()))
.filter((employee, contract, violationAmount) -> violationAmount != 0)
.penalize(HardSoftScore.ONE_SOFT, (employee, contract, violationAmount) -> violationAmount)
.indictWith((employee, contract, violationAmount) -> Arrays.asList(employee, contract))
.asConstraint("consecutiveWorkingWeekends");
}
// Complete Weekends
Constraint startOnNotFirstDayOfWeekend(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(BooleanContractLine.class)
.filter(booleanContractLine -> booleanContractLine.getContractLineType() == ContractLineType.COMPLETE_WEEKENDS
&& booleanContractLine.isEnabled())
.join(ShiftAssignment.class,
Joiners.equal(ContractLine::getContract, ShiftAssignment::getContract))
.groupBy((contract, shift) -> shift.getEmployee(),
(contract, shift) -> contract,
ConstraintCollectors.toConsecutiveSequences((contract, shift) -> shift.getShiftDate(),
ShiftDate::getDayIndex))
.flattenLast(SequenceChain::getConsecutiveSequences)
.filter((employee, contract, shiftList) -> isWeekendAndNotFirstDayOfWeekend(employee,
shiftList.getFirstItem()))
.penalize(HardSoftScore.ONE_SOFT,
(employee, contract, shiftList) -> getDistanceToFirstDayOfWeekend(employee, shiftList.getFirstItem())
* contract.getWeight())
.indictWith((employee, contract, shiftList) -> Arrays.asList(employee, contract))
.asConstraint("startOnNotFirstDayOfWeekend");
}
Constraint endOnNotLastDayOfWeekend(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(BooleanContractLine.class)
.filter(booleanContractLine -> booleanContractLine
.getContractLineType() == ContractLineType.COMPLETE_WEEKENDS &&
booleanContractLine.isEnabled())
.join(ShiftAssignment.class,
Joiners.equal(ContractLine::getContract, ShiftAssignment::getContract))
.groupBy((contract, shift) -> shift.getEmployee(),
(contract, shift) -> contract,
ConstraintCollectors.toConsecutiveSequences((contract, shift) -> shift.getShiftDate(),
ShiftDate::getDayIndex))
.flattenLast(SequenceChain::getConsecutiveSequences)
.filter((employee, contract, shiftList) -> isWeekendAndNotLastDayOfWeekend(employee,
shiftList.getLastItem()))
.penalize(HardSoftScore.ONE_SOFT,
(employee, contract, shiftList) -> getDistanceToLastDayOfWeekend(employee, shiftList.getLastItem())
* contract.getWeight())
.indictWith((employee, contract, shiftList) -> Arrays.asList(employee, contract))
.asConstraint("endOnNotLastDayOfWeekend");
}
// Identical shiftTypes during a weekend
Constraint identicalShiftTypesDuringWeekend(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(BooleanContractLine.class)
.filter(booleanContractLine -> booleanContractLine
.getContractLineType() == ContractLineType.IDENTICAL_SHIFT_TYPES_DURING_WEEKEND &&
booleanContractLine.isEnabled())
.join(constraintFactory.forEach(ShiftDate.class)
.filter(date -> date.getDayOfWeek() == DayOfWeek.SUNDAY))
.join(constraintFactory.forEach(ShiftAssignment.class)
.filter(ShiftAssignment::isWeekend),
Joiners.equal((contract, date) -> date.getWeekendSundayIndex(), ShiftAssignment::getWeekendSundayIndex),
Joiners.equal((contract, date) -> contract.getContract(), ShiftAssignment::getContract))
.groupBy((contract, date, sa) -> contract,
(contract, date, sa) -> sa.getEmployee(),
(contract, date, sa) -> {
ai.timefold.solver.examples.nurserostering.domain.ShiftType key = sa.getShiftType();
return new Pair<>(key, date);
}, // No 4-key groupBy overload
ConstraintCollectors.countTri())
.filter((contract, employee, type, count) -> count < employee.getWeekendLength())
.penalize(HardSoftScore.ONE_SOFT,
(contract, employee, type, count) -> (employee.getWeekendLength() - count) * contract.getWeight())
.indictWith((contract, employee, type, count) -> Arrays.asList(employee, contract))
.asConstraint("identicalShiftTypesDuringWeekend");
}
// Requested day on/off
Constraint dayOffRequest(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(DayOffRequest.class)
.join(ShiftAssignment.class, Joiners.equal(DayOffRequest::getEmployee, ShiftAssignment::getEmployee),
Joiners.equal(DayOffRequest::getShiftDate, ShiftAssignment::getShiftDate))
.penalize(HardSoftScore.ONE_SOFT,
(dayOffRequest, shiftAssignment) -> dayOffRequest.getWeight())
.asConstraint("dayOffRequest");
}
Constraint dayOnRequest(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(DayOnRequest.class)
.ifNotExists(ShiftAssignment.class, Joiners.equal(DayOnRequest::getEmployee, ShiftAssignment::getEmployee),
Joiners.equal(DayOnRequest::getShiftDate, ShiftAssignment::getShiftDate))
.penalize(HardSoftScore.ONE_SOFT, DayOnRequest::getWeight)
.asConstraint("dayOnRequest");
}
// Requested shift on/off
Constraint shiftOffRequest(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(ShiftOffRequest.class)
.join(ShiftAssignment.class, Joiners.equal(ShiftOffRequest::getEmployee, ShiftAssignment::getEmployee),
Joiners.equal(ShiftOffRequest::getShift, ShiftAssignment::getShift))
.penalize(HardSoftScore.ONE_SOFT,
(shiftOffRequest, shiftAssignment) -> shiftOffRequest.getWeight())
.asConstraint("shiftOffRequest");
}
Constraint shiftOnRequest(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(ShiftOnRequest.class)
.ifNotExists(ShiftAssignment.class, Joiners.equal(ShiftOnRequest::getEmployee, ShiftAssignment::getEmployee),
Joiners.equal(ShiftOnRequest::getShift, ShiftAssignment::getShift))
.penalize(HardSoftScore.ONE_SOFT, ShiftOnRequest::getWeight)
.asConstraint("shiftOnRequest");
}
// Alternative skill
Constraint alternativeSkill(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(BooleanContractLine.class)
.filter(booleanContractLine -> booleanContractLine.getContractLineType()
.equals(ContractLineType.ALTERNATIVE_SKILL_CATEGORY))
.join(ShiftAssignment.class, Joiners.equal(BooleanContractLine::getContract, ShiftAssignment::getContract))
.join(ShiftTypeSkillRequirement.class,
Joiners.equal((contract, shiftAssignment) -> shiftAssignment.getShiftType(),
ShiftTypeSkillRequirement::getShiftType))
.ifNotExists(SkillProficiency.class,
Joiners.equal((contract, shiftAssignment, skillRequirement) -> shiftAssignment.getEmployee(),
SkillProficiency::getEmployee),
Joiners.equal((contract, shiftAssignment, skillRequirement) -> skillRequirement.getSkill(),
SkillProficiency::getSkill))
.penalize(HardSoftScore.ONE_SOFT,
(contractLine, shiftAssignment, skillRequirement) -> contractLine.getWeight())
.asConstraint("alternativeSkill");
}
// Unwanted patterns
Constraint unwantedPatternFreeBefore2DaysWithAWorkDayPattern(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(PatternContractLine.class)
.filter(patternContractLine -> patternContractLine.getPattern() instanceof FreeBefore2DaysWithAWorkDayPattern)
.join(ShiftDate.class,
Joiners.equal(
contract -> ((FreeBefore2DaysWithAWorkDayPattern) contract.getPattern()).getFreeDayOfWeek(),
ShiftDate::getDayOfWeek))
.join(Employee.class,
Joiners.equal((contractLine, date) -> contractLine.getContract(), Employee::getContract))
.ifNotExists(ShiftAssignment.class,
Joiners.equal((contractLine, date, employee) -> employee, ShiftAssignment::getEmployee),
Joiners.equal((contractLine, date, employee) -> date.getDayIndex(),
ShiftAssignment::getShiftDateDayIndex))
.ifExists(ShiftAssignment.class,
Joiners.equal((contractLine, date, employee) -> employee, ShiftAssignment::getEmployee),
Joiners.lessThanOrEqual((contractLine, date, employee) -> date.getDayIndex() + 1,
ShiftAssignment::getShiftDateDayIndex),
Joiners.greaterThanOrEqual((contractLine, date, employee) -> date.getDayIndex() + 2,
ShiftAssignment::getShiftDateDayIndex))
.penalize(HardSoftScore.ONE_SOFT,
(contractLine, date, employee) -> contractLine.getPattern().getWeight())
.asConstraint("unwantedPatternFreeBefore2DaysWithAWorkDayPattern");
}
Constraint unwantedPatternShiftType2DaysPattern(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(PatternContractLine.class)
.filter(patternContractLine -> patternContractLine.getPattern() instanceof ShiftType2DaysPattern)
.join(ShiftAssignment.class,
Joiners.equal(
contractLine -> ((ShiftType2DaysPattern) contractLine.getPattern()).getDayIndex0ShiftType(),
ShiftAssignment::getShiftType),
Joiners.equal(PatternContractLine::getContract, ShiftAssignment::getContract))
.join(ShiftAssignment.class,
Joiners.equal((contractLine, shift) -> shift.getEmployee(), ShiftAssignment::getEmployee),
Joiners.equal((contractLine, shift) -> shift.getShiftDateDayIndex() + 1,
ShiftAssignment::getShiftDateDayIndex),
Joiners.filtering((contractLine, shift1, shift2) -> {
ShiftType2DaysPattern pattern = (ShiftType2DaysPattern) contractLine.getPattern();
return pattern.getDayIndex1ShiftType() == null
|| shift2.getShiftType() == pattern.getDayIndex1ShiftType();
}))
.penalize(HardSoftScore.ONE_SOFT,
(contractLine, shift1, shift2) -> contractLine.getPattern().getWeight())
.asConstraint("unwantedPatternShiftType2DaysPattern");
}
Constraint unwantedPatternShiftType3DaysPattern(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(PatternContractLine.class) // ShiftType3DaysPattern
.filter(patternContractLine -> patternContractLine.getPattern() instanceof ShiftType3DaysPattern)
.join(ShiftAssignment.class,
Joiners.equal(
contractLine -> ((ShiftType3DaysPattern) contractLine.getPattern()).getDayIndex0ShiftType(),
ShiftAssignment::getShiftType),
Joiners.equal(PatternContractLine::getContract, ShiftAssignment::getContract))
// Join and not if exist for consistency with DRL (which is removed)
.join(ShiftAssignment.class,
Joiners.equal((contractLine, shift) -> shift.getEmployee(), ShiftAssignment::getEmployee),
Joiners.equal((contractLine, shift) -> shift.getShiftDateDayIndex() + 1,
ShiftAssignment::getShiftDateDayIndex),
Joiners.equal(
(contractLine, shift) -> ((ShiftType3DaysPattern) contractLine.getPattern())
.getDayIndex1ShiftType(),
ShiftAssignment::getShiftType))
.join(ShiftAssignment.class,
Joiners.equal((contractLine, shift1, shift2) -> shift1.getEmployee(),
ShiftAssignment::getEmployee),
Joiners.equal((contractLine, shift1, shift2) -> shift1.getShiftDateDayIndex() + 2,
ShiftAssignment::getShiftDateDayIndex),
Joiners.equal(
(contractLine, shift1, shift2) -> ((ShiftType3DaysPattern) contractLine.getPattern())
.getDayIndex2ShiftType(),
ShiftAssignment::getShiftType))
.penalize(HardSoftScore.ONE_SOFT,
(contractLine, shift1, shift2, shift3) -> contractLine.getPattern().getWeight())
.asConstraint("unwantedPatternShiftType3DaysPattern");
}
public record Pair<A, B>(A a, B b) {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/solver | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/solver/move/EmployeeMultipleChangeMove.java | package ai.timefold.solver.examples.nurserostering.solver.move;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.core.impl.heuristic.move.AbstractMove;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
public class EmployeeMultipleChangeMove extends AbstractMove<NurseRoster> {
private Employee fromEmployee;
private List<ShiftAssignment> shiftAssignmentList;
private Employee toEmployee;
public EmployeeMultipleChangeMove(Employee fromEmployee, List<ShiftAssignment> shiftAssignmentList, Employee toEmployee) {
this.fromEmployee = fromEmployee;
this.shiftAssignmentList = shiftAssignmentList;
this.toEmployee = toEmployee;
}
@Override
public boolean isMoveDoable(ScoreDirector<NurseRoster> scoreDirector) {
return !Objects.equals(fromEmployee, toEmployee);
}
@Override
public EmployeeMultipleChangeMove createUndoMove(ScoreDirector<NurseRoster> scoreDirector) {
return new EmployeeMultipleChangeMove(toEmployee, shiftAssignmentList, fromEmployee);
}
@Override
protected void doMoveOnGenuineVariables(ScoreDirector<NurseRoster> scoreDirector) {
for (ShiftAssignment shiftAssignment : shiftAssignmentList) {
if (!shiftAssignment.getEmployee().equals(fromEmployee)) {
throw new IllegalStateException("The shiftAssignment (" + shiftAssignment + ") should have the same employee ("
+ shiftAssignment.getEmployee() + ") as the fromEmployee (" + fromEmployee + ").");
}
NurseRosteringMoveHelper.moveEmployee(scoreDirector, shiftAssignment, toEmployee);
}
}
@Override
public EmployeeMultipleChangeMove rebase(ScoreDirector<NurseRoster> destinationScoreDirector) {
return new EmployeeMultipleChangeMove(destinationScoreDirector.lookUpWorkingObject(fromEmployee),
rebaseList(shiftAssignmentList, destinationScoreDirector),
destinationScoreDirector.lookUpWorkingObject(toEmployee));
}
@Override
public Collection<? extends Object> getPlanningEntities() {
return Collections.singletonList(shiftAssignmentList);
}
@Override
public Collection<? extends Object> getPlanningValues() {
return Arrays.asList(fromEmployee, toEmployee);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EmployeeMultipleChangeMove other = (EmployeeMultipleChangeMove) o;
return Objects.equals(fromEmployee, other.fromEmployee) &&
Objects.equals(shiftAssignmentList, other.shiftAssignmentList) &&
Objects.equals(toEmployee, other.toEmployee);
}
@Override
public int hashCode() {
return Objects.hash(fromEmployee, shiftAssignmentList, toEmployee);
}
@Override
public String toString() {
return shiftAssignmentList + " {? -> " + toEmployee + "}";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/solver | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/solver/move/NurseRosteringMoveHelper.java | package ai.timefold.solver.examples.nurserostering.solver.move;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
public class NurseRosteringMoveHelper {
public static void moveEmployee(ScoreDirector<NurseRoster> scoreDirector, ShiftAssignment shiftAssignment,
Employee toEmployee) {
scoreDirector.beforeVariableChanged(shiftAssignment, "employee");
shiftAssignment.setEmployee(toEmployee);
scoreDirector.afterVariableChanged(shiftAssignment, "employee");
}
private NurseRosteringMoveHelper() {
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/solver/move | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/solver/move/factory/ShiftAssignmentPillarPartSwapMoveFactory.java | package ai.timefold.solver.examples.nurserostering.solver.move.factory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import ai.timefold.solver.core.api.domain.entity.PinningFilter;
import ai.timefold.solver.core.impl.heuristic.move.CompositeMove;
import ai.timefold.solver.core.impl.heuristic.move.Move;
import ai.timefold.solver.core.impl.heuristic.selector.move.factory.MoveListFactory;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.solver.ShiftAssignmentPinningFilter;
import ai.timefold.solver.examples.nurserostering.solver.move.EmployeeMultipleChangeMove;
public class ShiftAssignmentPillarPartSwapMoveFactory implements MoveListFactory<NurseRoster> {
private PinningFilter<NurseRoster, ShiftAssignment> filter = new ShiftAssignmentPinningFilter();
@Override
public List<Move<NurseRoster>> createMoveList(NurseRoster nurseRoster) {
List<Employee> employeeList = nurseRoster.getEmployeeList();
// This code assumes the shiftAssignmentList is sorted
// Filter out every pinned ShiftAssignment
List<ShiftAssignment> shiftAssignmentList = new ArrayList<>(
nurseRoster.getShiftAssignmentList());
shiftAssignmentList.removeIf(shiftAssignment -> filter.accept(nurseRoster, shiftAssignment));
// Hash the assignments per employee
Map<Employee, List<AssignmentSequence>> employeeToAssignmentSequenceListMap = new HashMap<>(employeeList.size());
int assignmentSequenceCapacity = nurseRoster.getShiftDateList().size() + 1 / 2;
for (Employee employee : employeeList) {
employeeToAssignmentSequenceListMap.put(employee,
new ArrayList<>(assignmentSequenceCapacity));
}
for (ShiftAssignment shiftAssignment : shiftAssignmentList) {
Employee employee = shiftAssignment.getEmployee();
List<AssignmentSequence> assignmentSequenceList = employeeToAssignmentSequenceListMap.get(employee);
if (assignmentSequenceList.isEmpty()) {
AssignmentSequence assignmentSequence = new AssignmentSequence(employee, shiftAssignment);
assignmentSequenceList.add(assignmentSequence);
} else {
AssignmentSequence lastAssignmentSequence = assignmentSequenceList // getLast()
.get(assignmentSequenceList.size() - 1);
if (lastAssignmentSequence.belongsHere(shiftAssignment)) {
lastAssignmentSequence.add(shiftAssignment);
} else {
AssignmentSequence assignmentSequence = new AssignmentSequence(employee, shiftAssignment);
assignmentSequenceList.add(assignmentSequence);
}
}
}
// The create the move list
List<Move<NurseRoster>> moveList = new ArrayList<>();
// For every 2 distinct employees
for (ListIterator<Employee> leftEmployeeIt = employeeList.listIterator(); leftEmployeeIt.hasNext();) {
Employee leftEmployee = leftEmployeeIt.next();
List<AssignmentSequence> leftAssignmentSequenceList = employeeToAssignmentSequenceListMap.get(leftEmployee);
for (ListIterator<Employee> rightEmployeeIt = employeeList.listIterator(leftEmployeeIt.nextIndex()); rightEmployeeIt
.hasNext();) {
Employee rightEmployee = rightEmployeeIt.next();
List<AssignmentSequence> rightAssignmentSequenceList = employeeToAssignmentSequenceListMap.get(
rightEmployee);
LowestDayIndexAssignmentSequenceIterator lowestIt = new LowestDayIndexAssignmentSequenceIterator(
leftAssignmentSequenceList, rightAssignmentSequenceList);
// For every pillar part duo
while (lowestIt.hasNext()) {
AssignmentSequence pillarPartAssignmentSequence = lowestIt.next();
// Note: the initialCapacity is probably too high,
// which is bad for memory, but the opposite is bad for performance (which is worse)
List<EmployeeMultipleChangeMove> moveListByPillarPartDuo = new ArrayList<>(
leftAssignmentSequenceList.size() + rightAssignmentSequenceList.size());
int lastDayIndex = pillarPartAssignmentSequence.getLastDayIndex();
Employee otherEmployee;
int leftMinimumFirstDayIndex = Integer.MIN_VALUE;
int rightMinimumFirstDayIndex = Integer.MIN_VALUE;
if (lowestIt.isLastNextWasLeft()) {
otherEmployee = rightEmployee;
leftMinimumFirstDayIndex = lastDayIndex;
} else {
otherEmployee = leftEmployee;
rightMinimumFirstDayIndex = lastDayIndex;
}
moveListByPillarPartDuo.add(new EmployeeMultipleChangeMove(
pillarPartAssignmentSequence.getEmployee(),
pillarPartAssignmentSequence.getShiftAssignmentList(),
otherEmployee));
// For every AssignmentSequence in that pillar part duo
while (lowestIt.hasNextWithMaximumFirstDayIndexes(
leftMinimumFirstDayIndex, rightMinimumFirstDayIndex)) {
pillarPartAssignmentSequence = lowestIt.next();
lastDayIndex = pillarPartAssignmentSequence.getLastDayIndex();
if (lowestIt.isLastNextWasLeft()) {
otherEmployee = rightEmployee;
leftMinimumFirstDayIndex = Math.max(leftMinimumFirstDayIndex, lastDayIndex);
} else {
otherEmployee = leftEmployee;
rightMinimumFirstDayIndex = Math.max(rightMinimumFirstDayIndex, lastDayIndex);
}
moveListByPillarPartDuo.add(new EmployeeMultipleChangeMove(
pillarPartAssignmentSequence.getEmployee(),
pillarPartAssignmentSequence.getShiftAssignmentList(),
otherEmployee));
}
moveList.add(CompositeMove.buildMove(moveListByPillarPartDuo));
}
}
}
return moveList;
}
private static class AssignmentSequence {
private Employee employee;
private List<ShiftAssignment> shiftAssignmentList;
private int firstDayIndex;
private int lastDayIndex;
private AssignmentSequence(Employee employee, ShiftAssignment shiftAssignment) {
this.employee = employee;
shiftAssignmentList = new ArrayList<>();
shiftAssignmentList.add(shiftAssignment);
firstDayIndex = shiftAssignment.getShiftDateDayIndex();
lastDayIndex = firstDayIndex;
}
public Employee getEmployee() {
return employee;
}
public List<ShiftAssignment> getShiftAssignmentList() {
return shiftAssignmentList;
}
public int getFirstDayIndex() {
return firstDayIndex;
}
public int getLastDayIndex() {
return lastDayIndex;
}
private void add(ShiftAssignment shiftAssignment) {
shiftAssignmentList.add(shiftAssignment);
int dayIndex = shiftAssignment.getShiftDateDayIndex();
if (dayIndex < lastDayIndex) {
throw new IllegalStateException("The shiftAssignmentList is expected to be sorted by shiftDate.");
}
lastDayIndex = dayIndex;
}
private boolean belongsHere(ShiftAssignment shiftAssignment) {
return shiftAssignment.getShiftDateDayIndex() <= (lastDayIndex + 1);
}
}
private static class LowestDayIndexAssignmentSequenceIterator implements Iterator<AssignmentSequence> {
private Iterator<AssignmentSequence> leftIterator;
private Iterator<AssignmentSequence> rightIterator;
private boolean leftHasNext = true;
private boolean rightHasNext = true;
private AssignmentSequence nextLeft;
private AssignmentSequence nextRight;
private boolean lastNextWasLeft;
public LowestDayIndexAssignmentSequenceIterator(
List<AssignmentSequence> leftAssignmentList, List<AssignmentSequence> rightAssignmentList) {
// Buffer the nextLeft and nextRight
leftIterator = leftAssignmentList.iterator();
if (leftIterator.hasNext()) {
nextLeft = leftIterator.next();
} else {
leftHasNext = false;
nextLeft = null;
}
rightIterator = rightAssignmentList.iterator();
if (rightIterator.hasNext()) {
nextRight = rightIterator.next();
} else {
rightHasNext = false;
nextRight = null;
}
}
@Override
public boolean hasNext() {
return leftHasNext || rightHasNext;
}
public boolean hasNextWithMaximumFirstDayIndexes(
int leftMinimumFirstDayIndex, int rightMinimumFirstDayIndex) {
if (!hasNext()) {
return false;
}
boolean nextIsLeft = nextIsLeft();
if (nextIsLeft) {
int firstDayIndex = nextLeft.getFirstDayIndex();
// It should not be conflict in the same pillar and it should be in conflict with the other pillar
return firstDayIndex > leftMinimumFirstDayIndex && firstDayIndex <= rightMinimumFirstDayIndex;
} else {
int firstDayIndex = nextRight.getFirstDayIndex();
// It should not be conflict in the same pillar and it should be in conflict with the other pillar
return firstDayIndex > rightMinimumFirstDayIndex && firstDayIndex <= leftMinimumFirstDayIndex;
}
}
@Override
public AssignmentSequence next() {
lastNextWasLeft = nextIsLeft();
// Buffer the nextLeft or nextRight
AssignmentSequence lowest;
if (lastNextWasLeft) {
lowest = nextLeft;
if (leftIterator.hasNext()) {
nextLeft = leftIterator.next();
} else {
leftHasNext = false;
nextLeft = null;
}
} else {
lowest = nextRight;
if (rightIterator.hasNext()) {
nextRight = rightIterator.next();
} else {
rightHasNext = false;
nextRight = null;
}
}
return lowest;
}
private boolean nextIsLeft() {
boolean returnLeft;
if (leftHasNext) {
if (rightHasNext) {
int leftFirstDayIndex = nextLeft.getFirstDayIndex();
int rightFirstDayIndex = nextRight.getFirstDayIndex();
returnLeft = leftFirstDayIndex <= rightFirstDayIndex;
} else {
returnLeft = true;
}
} else {
if (rightHasNext) {
returnLeft = false;
} else {
throw new NoSuchElementException();
}
}
return returnLeft;
}
@Override
public void remove() {
throw new UnsupportedOperationException("The optional operation remove() is not supported.");
}
public boolean isLastNextWasLeft() {
return lastNextWasLeft;
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/swingui/EmployeePanel.java | package ai.timefold.solver.examples.nurserostering.swingui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import ai.timefold.solver.examples.common.swingui.components.LabeledComboBoxRenderer;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
import ai.timefold.solver.examples.nurserostering.domain.ShiftType;
import ai.timefold.solver.examples.nurserostering.domain.WeekendDefinition;
import ai.timefold.solver.swing.impl.SwingUtils;
import ai.timefold.solver.swing.impl.TangoColorFactory;
public class EmployeePanel extends JPanel {
public static final int WEST_HEADER_WIDTH = 160;
public static final int EAST_HEADER_WIDTH = 130;
private final NurseRosteringPanel nurseRosteringPanel;
private List<ShiftDate> shiftDateList;
private List<Shift> shiftList;
private Employee employee;
private JButton deleteButton;
private JPanel shiftDateListPanel = null;
private Map<ShiftDate, JPanel> shiftDatePanelMap;
private Map<Shift, JPanel> shiftPanelMap;
private JLabel numberOfShiftAssignmentsLabel;
private Map<ShiftAssignment, JButton> shiftAssignmentButtonMap = new HashMap<>();
public EmployeePanel(NurseRosteringPanel nurseRosteringPanel, List<ShiftDate> shiftDateList, List<Shift> shiftList,
Employee employee) {
super(new BorderLayout());
this.nurseRosteringPanel = nurseRosteringPanel;
this.shiftDateList = shiftDateList;
this.shiftList = shiftList;
this.employee = employee;
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(1, 2, 1, 2),
BorderFactory.createLineBorder(Color.BLACK)),
BorderFactory.createEmptyBorder(1, 1, 1, 1)));
createUI();
}
public Employee getEmployee() {
return employee;
}
private String getEmployeeLabel() {
return employee == null ? "Unassigned" : employee.getLabel();
}
public void setShiftDateListAndShiftList(List<ShiftDate> shiftDateList, List<Shift> shiftList) {
this.shiftDateList = shiftDateList;
this.shiftList = shiftList;
resetShiftListPanel();
}
private void createUI() {
JPanel labelAndDeletePanel = new JPanel(new BorderLayout(5, 0));
if (employee != null) {
labelAndDeletePanel.add(new JLabel(nurseRosteringPanel.getEmployeeIcon()), BorderLayout.WEST);
}
JLabel employeeLabel = new JLabel(getEmployeeLabel());
employeeLabel.setEnabled(false);
labelAndDeletePanel.add(employeeLabel, BorderLayout.CENTER);
if (employee != null) {
JPanel deletePanel = new JPanel(new BorderLayout());
deleteButton = SwingUtils.makeSmallButton(new JButton(nurseRosteringPanel.getDeleteEmployeeIcon()));
deleteButton.setToolTipText("Delete");
deleteButton.addActionListener(e -> nurseRosteringPanel.deleteEmployee(employee));
deletePanel.add(deleteButton, BorderLayout.NORTH);
labelAndDeletePanel.add(deletePanel, BorderLayout.EAST);
}
labelAndDeletePanel.setPreferredSize(new Dimension(WEST_HEADER_WIDTH,
(int) labelAndDeletePanel.getPreferredSize().getHeight()));
add(labelAndDeletePanel, BorderLayout.WEST);
resetShiftListPanel();
numberOfShiftAssignmentsLabel = new JLabel("0 assignments", JLabel.RIGHT);
numberOfShiftAssignmentsLabel.setPreferredSize(new Dimension(EAST_HEADER_WIDTH, 20));
numberOfShiftAssignmentsLabel.setEnabled(false);
add(numberOfShiftAssignmentsLabel, BorderLayout.EAST);
}
public void resetShiftListPanel() {
if (shiftDateListPanel != null) {
remove(shiftDateListPanel);
}
WeekendDefinition weekendDefinition = (employee == null) ? WeekendDefinition.SATURDAY_SUNDAY
: employee.getContract().getWeekendDefinition();
shiftDateListPanel = new JPanel(new GridLayout(1, 0));
shiftDatePanelMap = new LinkedHashMap<>(shiftDateList.size());
for (ShiftDate shiftDate : shiftDateList) {
JPanel shiftDatePanel = new JPanel(new GridLayout(1, 0));
Color backgroundColor = weekendDefinition.isWeekend(shiftDate.getDayOfWeek())
? TangoColorFactory.ALUMINIUM_2
: shiftDatePanel.getBackground();
if (employee != null) {
if (employee.getDayOffRequestMap().containsKey(shiftDate)) {
backgroundColor = TangoColorFactory.ALUMINIUM_4;
} else if (employee.getDayOnRequestMap().containsKey(shiftDate)) {
backgroundColor = TangoColorFactory.SCARLET_1;
}
}
shiftDatePanel.setBackground(backgroundColor);
boolean inPlanningWindow = nurseRosteringPanel.getSolution().getNurseRosterParametrization()
.isInPlanningWindow(shiftDate);
shiftDatePanel.setEnabled(inPlanningWindow);
shiftDatePanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory
.createLineBorder(inPlanningWindow ? TangoColorFactory.ALUMINIUM_6 : TangoColorFactory.ALUMINIUM_3),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
shiftDatePanelMap.put(shiftDate, shiftDatePanel);
if (employee == null) {
// TODO HACK should be in NurseRosterPanel.createHeaderPanel
JPanel wrappingShiftDatePanel = new JPanel(new BorderLayout());
JLabel shiftDateLabel = new JLabel(shiftDate.getLabel(), JLabel.CENTER);
shiftDateLabel.setEnabled(shiftDatePanel.isEnabled());
wrappingShiftDatePanel.add(shiftDateLabel, BorderLayout.NORTH);
wrappingShiftDatePanel.add(shiftDatePanel, BorderLayout.CENTER);
shiftDateListPanel.add(wrappingShiftDatePanel);
} else {
shiftDateListPanel.add(shiftDatePanel);
}
}
shiftPanelMap = new LinkedHashMap<>(shiftList.size());
for (Shift shift : shiftList) {
JPanel shiftDatePanel = shiftDatePanelMap.get(shift.getShiftDate());
JPanel shiftPanel = new JPanel();
shiftPanel.setEnabled(shiftDatePanel.isEnabled());
shiftPanel.setLayout(new BoxLayout(shiftPanel, BoxLayout.Y_AXIS));
Color backgroundColor = shiftDatePanel.getBackground();
if (employee != null) {
if (employee.getShiftOffRequestMap().containsKey(shift)) {
backgroundColor = TangoColorFactory.ALUMINIUM_4;
} else if (employee.getShiftOnRequestMap().containsKey(shift)) {
backgroundColor = TangoColorFactory.SCARLET_1;
}
}
shiftPanel.setBackground(backgroundColor);
shiftPanel.setToolTipText("<html>Date: " + shift.getShiftDate().getLabel() + "<br/>"
+ "Employee: " + (employee == null ? "unassigned" : employee.getLabel())
+ "</html>");
shiftPanelMap.put(shift, shiftPanel);
shiftDatePanel.add(shiftPanel);
}
add(shiftDateListPanel, BorderLayout.CENTER);
}
public void addShiftAssignment(ShiftAssignment shiftAssignment) {
Shift shift = shiftAssignment.getShift();
JPanel shiftPanel = shiftPanelMap.get(shift);
JButton shiftAssignmentButton = SwingUtils.makeSmallButton(new JButton(new ShiftAssignmentAction(shiftAssignment)));
shiftAssignmentButton.setEnabled(shiftPanel.isEnabled());
if (employee != null) {
if (employee.getDayOffRequestMap().containsKey(shift.getShiftDate())
|| employee.getShiftOffRequestMap().containsKey(shift)) {
shiftAssignmentButton.setForeground(TangoColorFactory.SCARLET_1);
}
}
Color color = nurseRosteringPanel.determinePlanningEntityColor(shiftAssignment, shift.getShiftType());
shiftAssignmentButton.setBackground(color);
String toolTip = nurseRosteringPanel.determinePlanningEntityTooltip(shiftAssignment);
shiftAssignmentButton.setToolTipText(toolTip);
shiftPanel.add(shiftAssignmentButton);
shiftPanel.repaint();
shiftAssignmentButtonMap.put(shiftAssignment, shiftAssignmentButton);
}
public void clearShiftAssignments() {
for (JPanel shiftPanel : shiftPanelMap.values()) {
shiftPanel.removeAll();
shiftPanel.repaint();
}
shiftAssignmentButtonMap.clear();
}
public void update() {
numberOfShiftAssignmentsLabel.setText(shiftAssignmentButtonMap.size() + " assignments");
}
private class ShiftAssignmentAction extends AbstractAction {
private ShiftAssignment shiftAssignment;
public ShiftAssignmentAction(ShiftAssignment shiftAssignment) {
super(shiftAssignment.getShift().getShiftType().getCode());
this.shiftAssignment = shiftAssignment;
Shift shift = shiftAssignment.getShift();
ShiftType shiftType = shift.getShiftType();
// Tooltip
putValue(SHORT_DESCRIPTION, "<html>Date: " + shift.getShiftDate().getLabel() + "<br/>"
+ "Shift type: " + shiftType.getLabel() + " (from " + shiftType.getStartTimeString()
+ " to " + shiftType.getEndTimeString() + ")<br/>"
+ "Employee: " + (employee == null ? "unassigned" : employee.getLabel())
+ "</html>");
}
@Override
public void actionPerformed(ActionEvent e) {
List<Employee> employeeList = nurseRosteringPanel.getSolution().getEmployeeList();
// Add 1 to array size to add null, which makes the entity unassigned
JComboBox employeeListField = new JComboBox(
employeeList.toArray(new Object[employeeList.size() + 1]));
LabeledComboBoxRenderer.applyToComboBox(employeeListField);
employeeListField.setSelectedItem(shiftAssignment.getEmployee());
int result = JOptionPane.showConfirmDialog(EmployeePanel.this.getRootPane(), employeeListField,
"Select employee", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
Employee toEmployee = (Employee) employeeListField.getSelectedItem();
nurseRosteringPanel.moveShiftAssignmentToEmployee(shiftAssignment, toEmployee);
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/nurserostering/swingui/NurseRosteringPanel.java | package ai.timefold.solver.examples.nurserostering.swingui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
import ai.timefold.solver.examples.nurserostering.domain.Employee;
import ai.timefold.solver.examples.nurserostering.domain.NurseRoster;
import ai.timefold.solver.examples.nurserostering.domain.NurseRosterParametrization;
import ai.timefold.solver.examples.nurserostering.domain.Shift;
import ai.timefold.solver.examples.nurserostering.domain.ShiftAssignment;
import ai.timefold.solver.examples.nurserostering.domain.ShiftDate;
public class NurseRosteringPanel extends SolutionPanel<NurseRoster> {
public static final String LOGO_PATH = "/ai/timefold/solver/examples/nurserostering/swingui/nurseRosteringLogo.png";
private final ImageIcon employeeIcon;
private final ImageIcon deleteEmployeeIcon;
private JPanel employeeListPanel;
private JTextField planningWindowStartField;
private AbstractAction advancePlanningWindowStartAction;
private EmployeePanel unassignedPanel;
private Map<Employee, EmployeePanel> employeeToPanelMap;
public NurseRosteringPanel() {
employeeIcon = new ImageIcon(getClass().getResource("employee.png"));
deleteEmployeeIcon = new ImageIcon(getClass().getResource("deleteEmployee.png"));
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
createEmployeeListPanel();
JPanel headerPanel = createHeaderPanel();
layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(headerPanel).addComponent(employeeListPanel));
layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(headerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE)
.addComponent(employeeListPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
GroupLayout.PREFERRED_SIZE));
}
public ImageIcon getEmployeeIcon() {
return employeeIcon;
}
public ImageIcon getDeleteEmployeeIcon() {
return deleteEmployeeIcon;
}
private JPanel createHeaderPanel() {
JPanel headerPanel = new JPanel(new BorderLayout(20, 0));
JPanel planningWindowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
planningWindowPanel.add(new JLabel("Planning window start:"));
planningWindowStartField = new JTextField(10);
planningWindowStartField.setEditable(false);
planningWindowPanel.add(planningWindowStartField);
advancePlanningWindowStartAction = new AbstractAction("Advance 1 day into the future") {
@Override
public void actionPerformed(ActionEvent e) {
advancePlanningWindowStart();
}
};
advancePlanningWindowStartAction.setEnabled(false);
planningWindowPanel.add(new JButton(advancePlanningWindowStartAction));
headerPanel.add(planningWindowPanel, BorderLayout.WEST);
JLabel shiftTypeExplanation = new JLabel("E = Early shift, L = Late shift, ...");
headerPanel.add(shiftTypeExplanation, BorderLayout.CENTER);
return headerPanel;
}
private void createEmployeeListPanel() {
employeeListPanel = new JPanel();
employeeListPanel.setLayout(new BoxLayout(employeeListPanel, BoxLayout.Y_AXIS));
unassignedPanel = new EmployeePanel(this, Collections.emptyList(), Collections.emptyList(),
null);
employeeListPanel.add(unassignedPanel);
employeeToPanelMap = new LinkedHashMap<>();
employeeToPanelMap.put(null, unassignedPanel);
}
@Override
public void resetPanel(NurseRoster nurseRoster) {
for (EmployeePanel employeePanel : employeeToPanelMap.values()) {
if (employeePanel.getEmployee() != null) {
employeeListPanel.remove(employeePanel);
}
}
employeeToPanelMap.clear();
employeeToPanelMap.put(null, unassignedPanel);
unassignedPanel.clearShiftAssignments();
preparePlanningEntityColors(nurseRoster.getShiftAssignmentList());
List<ShiftDate> shiftDateList = nurseRoster.getShiftDateList();
List<Shift> shiftList = nurseRoster.getShiftList();
unassignedPanel.setShiftDateListAndShiftList(shiftDateList, shiftList);
updatePanel(nurseRoster);
advancePlanningWindowStartAction.setEnabled(true);
planningWindowStartField.setText(nurseRoster.getNurseRosterParametrization().getPlanningWindowStart().getLabel());
}
@Override
public void updatePanel(NurseRoster nurseRoster) {
preparePlanningEntityColors(nurseRoster.getShiftAssignmentList());
List<ShiftDate> shiftDateList = nurseRoster.getShiftDateList();
List<Shift> shiftList = nurseRoster.getShiftList();
Set<Employee> deadEmployeeSet = new LinkedHashSet<>(employeeToPanelMap.keySet());
deadEmployeeSet.remove(null);
for (Employee employee : nurseRoster.getEmployeeList()) {
deadEmployeeSet.remove(employee);
EmployeePanel employeePanel = employeeToPanelMap.get(employee);
if (employeePanel == null) {
employeePanel = new EmployeePanel(this, shiftDateList, shiftList, employee);
employeeListPanel.add(employeePanel);
employeeToPanelMap.put(employee, employeePanel);
}
employeePanel.clearShiftAssignments();
}
unassignedPanel.clearShiftAssignments();
for (ShiftAssignment shiftAssignment : nurseRoster.getShiftAssignmentList()) {
Employee employee = shiftAssignment.getEmployee();
EmployeePanel employeePanel = employeeToPanelMap.get(employee);
employeePanel.addShiftAssignment(shiftAssignment);
}
for (Employee deadEmployee : deadEmployeeSet) {
EmployeePanel deadEmployeePanel = employeeToPanelMap.remove(deadEmployee);
employeeListPanel.remove(deadEmployeePanel);
}
for (EmployeePanel employeePanel : employeeToPanelMap.values()) {
employeePanel.update();
}
}
@Override
public boolean isIndictmentHeatMapEnabled() {
return true;
}
private void advancePlanningWindowStart() {
logger.info("Advancing planningWindowStart.");
if (solutionBusiness.isSolving()) {
JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
"The GUI does not support this action yet during solving.\nTimefold itself does support it.\n"
+ "\nTerminate solving first and try again.",
"Unsupported in GUI", JOptionPane.INFORMATION_MESSAGE);
return;
}
doProblemChange((nurseRoster, problemChangeDirector) -> {
NurseRosterParametrization nurseRosterParametrization = nurseRoster.getNurseRosterParametrization();
List<ShiftDate> shiftDateList = nurseRoster.getShiftDateList();
ShiftDate planningWindowStart = nurseRosterParametrization.getPlanningWindowStart();
int windowStartIndex = shiftDateList.indexOf(planningWindowStart);
if (windowStartIndex < 0) {
throw new IllegalStateException("The planningWindowStart ("
+ planningWindowStart + ") must be in the shiftDateList ("
+ shiftDateList + ").");
}
ShiftDate oldLastShiftDate = shiftDateList.get(shiftDateList.size() - 1);
ShiftDate newShiftDate = new ShiftDate(oldLastShiftDate.getId() + 1L,
oldLastShiftDate.getDayIndex() + 1, oldLastShiftDate.getDate().plusDays(1));
List<Shift> refShiftList = planningWindowStart.getShiftList();
List<Shift> newShiftList = new ArrayList<>(refShiftList.size());
newShiftDate.setShiftList(newShiftList);
problemChangeDirector.addProblemFact(newShiftDate, nurseRoster.getShiftDateList()::add);
Shift oldLastShift = nurseRoster.getShiftList().get(nurseRoster.getShiftList().size() - 1);
long shiftId = oldLastShift.getId() + 1L;
int shiftIndex = oldLastShift.getIndex() + 1;
long shiftAssignmentId = nurseRoster.getShiftAssignmentList().get(
nurseRoster.getShiftAssignmentList().size() - 1).getId() + 1L;
for (Shift refShift : refShiftList) {
Shift newShift = new Shift(shiftId, newShiftDate, refShift.getShiftType(), shiftIndex,
refShift.getRequiredEmployeeSize());
shiftId++;
shiftIndex++;
newShiftList.add(newShift);
problemChangeDirector.addProblemFact(newShift, nurseRoster.getShiftList()::add);
for (int indexInShift = 0; indexInShift < newShift.getRequiredEmployeeSize(); indexInShift++) {
ShiftAssignment newShiftAssignment = new ShiftAssignment(shiftAssignmentId, newShift, indexInShift);
shiftAssignmentId++;
problemChangeDirector.addEntity(newShiftAssignment, nurseRoster.getShiftAssignmentList()::add);
}
}
windowStartIndex++;
ShiftDate newPlanningWindowStart = shiftDateList.get(windowStartIndex);
problemChangeDirector.changeProblemProperty(nurseRosterParametrization,
workingNurseRosterParametrization -> {
workingNurseRosterParametrization.setPlanningWindowStart(newPlanningWindowStart);
workingNurseRosterParametrization.setLastShiftDate(newShiftDate);
});
}, true);
}
public void deleteEmployee(final Employee employee) {
logger.info("Scheduling delete of employee ({}).", employee);
doProblemChange((nurseRoster, problemChangeDirector) -> problemChangeDirector.lookUpWorkingObject(employee)
.ifPresentOrElse(workingEmployee -> {
// First remove the problem fact from all planning entities that use it
for (ShiftAssignment shiftAssignment : nurseRoster.getShiftAssignmentList()) {
if (shiftAssignment.getEmployee() == workingEmployee) {
problemChangeDirector.changeVariable(shiftAssignment, "employee",
workingShiftAssignment -> workingShiftAssignment.setEmployee(null));
}
}
// A SolutionCloner does not clone problem fact lists (such as employeeList)
// Shallow clone the employeeList so only workingSolution is affected, not bestSolution or guiSolution
ArrayList<Employee> employeeList = new ArrayList<>(nurseRoster.getEmployeeList());
nurseRoster.setEmployeeList(employeeList);
// Remove it the problem fact itself
problemChangeDirector.removeProblemFact(workingEmployee, employeeList::remove);
}, () -> logger.info("Skipping problem change due to employee ({}) already deleted.", employee)));
}
public void moveShiftAssignmentToEmployee(ShiftAssignment shiftAssignment, Employee toEmployee) {
doProblemChange(
(workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(shiftAssignment, "employee",
sa -> sa.setEmployee(toEmployee)));
solverAndPersistenceFrame.resetScreen();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/app/ProjectJobSchedulingApp.java | package ai.timefold.solver.examples.projectjobscheduling.app;
import java.util.Collections;
import java.util.Set;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
import ai.timefold.solver.examples.projectjobscheduling.persistence.ProjectJobSchedulingImporter;
import ai.timefold.solver.examples.projectjobscheduling.persistence.ProjectJobSchedulingSolutionFileIO;
import ai.timefold.solver.examples.projectjobscheduling.swingui.ProjectJobSchedulingPanel;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
public class ProjectJobSchedulingApp extends CommonApp<Schedule> {
public static final String SOLVER_CONFIG =
"ai/timefold/solver/examples/projectjobscheduling/projectJobSchedulingSolverConfig.xml";
public static final String DATA_DIR_NAME = "projectjobscheduling";
public static void main(String[] args) {
prepareSwingEnvironment();
new ProjectJobSchedulingApp().init();
}
public ProjectJobSchedulingApp() {
super("Project job scheduling",
"Official competition name:" +
" multi-mode resource-constrained multi-project scheduling problem (MRCMPSP)\n\n" +
"Schedule all jobs in time and execution mode.\n\n" +
"Minimize project delays.",
SOLVER_CONFIG, DATA_DIR_NAME,
ProjectJobSchedulingPanel.LOGO_PATH);
}
@Override
protected ProjectJobSchedulingPanel createSolutionPanel() {
return new ProjectJobSchedulingPanel();
}
@Override
public SolutionFileIO<Schedule> createSolutionFileIO() {
return new ProjectJobSchedulingSolutionFileIO();
}
@Override
protected Set<AbstractSolutionImporter<Schedule>> createSolutionImporters() {
return Collections.singleton(new ProjectJobSchedulingImporter());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/Allocation.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.valuerange.CountableValueRange;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeFactory;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import ai.timefold.solver.examples.projectjobscheduling.domain.solver.DelayStrengthComparator;
import ai.timefold.solver.examples.projectjobscheduling.domain.solver.ExecutionModeStrengthWeightFactory;
import ai.timefold.solver.examples.projectjobscheduling.domain.solver.NotSourceOrSinkAllocationFilter;
import ai.timefold.solver.examples.projectjobscheduling.domain.solver.PredecessorsDoneDateUpdatingVariableListener;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
@PlanningEntity(pinningFilter = NotSourceOrSinkAllocationFilter.class)
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Allocation extends AbstractPersistable implements Labeled {
private Job job;
private Allocation sourceAllocation;
private Allocation sinkAllocation;
private List<Allocation> predecessorAllocationList;
private List<Allocation> successorAllocationList;
// Planning variables: changes during planning, between score calculations.
private ExecutionMode executionMode;
private Integer delay; // In days
// Shadow variables
private Integer predecessorsDoneDate;
// Filled from shadow variables
private Integer startDate;
private Integer endDate;
private List<Integer> busyDates;
public Allocation() {
}
public Allocation(long id, Job job) {
super(id);
this.job = job;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public Allocation getSourceAllocation() {
return sourceAllocation;
}
public void setSourceAllocation(Allocation sourceAllocation) {
this.sourceAllocation = sourceAllocation;
}
public Allocation getSinkAllocation() {
return sinkAllocation;
}
public void setSinkAllocation(Allocation sinkAllocation) {
this.sinkAllocation = sinkAllocation;
}
public List<Allocation> getPredecessorAllocationList() {
return predecessorAllocationList;
}
public void setPredecessorAllocationList(List<Allocation> predecessorAllocationList) {
this.predecessorAllocationList = predecessorAllocationList;
}
public List<Allocation> getSuccessorAllocationList() {
return successorAllocationList;
}
public void setSuccessorAllocationList(List<Allocation> successorAllocationList) {
this.successorAllocationList = successorAllocationList;
}
@PlanningVariable(strengthWeightFactoryClass = ExecutionModeStrengthWeightFactory.class)
public ExecutionMode getExecutionMode() {
return executionMode;
}
public void setExecutionMode(ExecutionMode executionMode) {
this.executionMode = executionMode;
invalidateComputedVariables();
}
private void invalidateComputedVariables() {
this.startDate = null;
this.endDate = null;
this.busyDates = null;
}
@PlanningVariable(strengthComparatorClass = DelayStrengthComparator.class)
public Integer getDelay() {
return delay;
}
public void setDelay(Integer delay) {
this.delay = delay;
invalidateComputedVariables();
}
@ShadowVariable(variableListenerClass = PredecessorsDoneDateUpdatingVariableListener.class,
sourceVariableName = "executionMode")
@ShadowVariable(variableListenerClass = PredecessorsDoneDateUpdatingVariableListener.class, sourceVariableName = "delay")
public Integer getPredecessorsDoneDate() {
return predecessorsDoneDate;
}
public void setPredecessorsDoneDate(Integer predecessorsDoneDate) {
this.predecessorsDoneDate = predecessorsDoneDate;
invalidateComputedVariables();
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public Integer getStartDate() {
if (startDate == null && predecessorsDoneDate != null) {
startDate = predecessorsDoneDate + Objects.requireNonNullElse(delay, 0);
}
return startDate;
}
@JsonIgnore
public Integer getEndDate() {
if (endDate == null && predecessorsDoneDate != null) {
endDate = getStartDate() + (executionMode == null ? 0 : executionMode.getDuration());
}
return endDate;
}
@JsonIgnore
public List<Integer> getBusyDates() {
if (busyDates == null) {
if (predecessorsDoneDate == null) {
busyDates = Collections.emptyList();
} else {
var startDate = getStartDate();
var endDate = getEndDate();
var dates = new Integer[endDate - startDate];
for (int i = 0; i < dates.length; i++) {
dates[i] = startDate + i;
}
busyDates = Arrays.asList(dates);
}
}
return busyDates;
}
@JsonIgnore
public Project getProject() {
return job.getProject();
}
@JsonIgnore
public int getProjectCriticalPathEndDate() {
return job.getProject().getCriticalPathEndDate();
}
@JsonIgnore
public JobType getJobType() {
return job.getJobType();
}
@Override
public String getLabel() {
return "Job " + job.getId();
}
// ************************************************************************
// Ranges
// ************************************************************************
@ValueRangeProvider
@JsonIgnore
public List<ExecutionMode> getExecutionModeRange() {
return job.getExecutionModeList();
}
@ValueRangeProvider
@JsonIgnore
public CountableValueRange<Integer> getDelayRange() {
return ValueRangeFactory.createIntValueRange(0, 500);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/ExecutionMode.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
import java.util.List;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class ExecutionMode extends AbstractPersistable {
private Job job;
private int duration; // In days
public ExecutionMode() {
}
public ExecutionMode(long id, Job job) {
super(id);
this.job = job;
}
private List<ResourceRequirement> resourceRequirementList;
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public List<ResourceRequirement> getResourceRequirementList() {
return resourceRequirementList;
}
public void setResourceRequirementList(List<ResourceRequirement> resourceRequirementList) {
this.resourceRequirementList = resourceRequirementList;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/Job.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
import java.util.List;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Job extends AbstractPersistable {
private Project project;
private JobType jobType;
private List<ExecutionMode> executionModeList;
private List<Job> successorJobList;
public Job() {
}
public Job(long id, Project project) {
super(id);
this.project = project;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
public JobType getJobType() {
return jobType;
}
public void setJobType(JobType jobType) {
this.jobType = jobType;
}
public List<ExecutionMode> getExecutionModeList() {
return executionModeList;
}
public void setExecutionModeList(List<ExecutionMode> executionModeList) {
this.executionModeList = executionModeList;
}
public List<Job> getSuccessorJobList() {
return successorJobList;
}
public void setSuccessorJobList(List<Job> successorJobList) {
this.successorJobList = successorJobList;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/JobType.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
public enum JobType {
SOURCE,
STANDARD,
SINK;
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/Project.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
import java.util.List;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.LocalResource;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Project extends AbstractPersistable implements Labeled {
private int releaseDate;
private int criticalPathDuration;
private List<LocalResource> localResourceList;
private List<Job> jobList;
public Project() {
}
public Project(long id, int releaseDate, int criticalPathDuration) {
super(id);
this.releaseDate = releaseDate;
this.criticalPathDuration = criticalPathDuration;
}
public int getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(int releaseDate) {
this.releaseDate = releaseDate;
}
public int getCriticalPathDuration() {
return criticalPathDuration;
}
public void setCriticalPathDuration(int criticalPathDuration) {
this.criticalPathDuration = criticalPathDuration;
}
public List<LocalResource> getLocalResourceList() {
return localResourceList;
}
public void setLocalResourceList(List<LocalResource> localResourceList) {
this.localResourceList = localResourceList;
}
public List<Job> getJobList() {
return jobList;
}
public void setJobList(List<Job> jobList) {
this.jobList = jobList;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public int getCriticalPathEndDate() {
return releaseDate + criticalPathDuration;
}
@Override
public String getLabel() {
return "Project " + id;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/ResourceRequirement.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class ResourceRequirement extends AbstractPersistable {
private ExecutionMode executionMode;
private Resource resource;
private int requirement;
public ResourceRequirement() {
}
public ResourceRequirement(long id, ExecutionMode executionMode, Resource resource, int requirement) {
super(id);
this.executionMode = executionMode;
this.resource = resource;
this.requirement = requirement;
}
public ExecutionMode getExecutionMode() {
return executionMode;
}
public void setExecutionMode(ExecutionMode executionMode) {
this.executionMode = executionMode;
}
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
public int getRequirement() {
return requirement;
}
public void setRequirement(int requirement) {
this.requirement = requirement;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public boolean isResourceRenewable() {
return resource.isRenewable();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/Schedule.java | package ai.timefold.solver.examples.projectjobscheduling.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
@PlanningSolution
public class Schedule extends AbstractPersistable {
private List<Project> projectList;
private List<Job> jobList;
private List<ExecutionMode> executionModeList;
private List<Resource> resourceList;
private List<ResourceRequirement> resourceRequirementList;
private List<Allocation> allocationList;
private HardMediumSoftScore score;
public Schedule() {
}
public Schedule(long id) {
super(id);
}
@ProblemFactCollectionProperty
public List<Project> getProjectList() {
return projectList;
}
public void setProjectList(List<Project> projectList) {
this.projectList = projectList;
}
@ProblemFactCollectionProperty
public List<Job> getJobList() {
return jobList;
}
public void setJobList(List<Job> jobList) {
this.jobList = jobList;
}
@ProblemFactCollectionProperty
public List<ExecutionMode> getExecutionModeList() {
return executionModeList;
}
public void setExecutionModeList(List<ExecutionMode> executionModeList) {
this.executionModeList = executionModeList;
}
@ProblemFactCollectionProperty
public List<Resource> getResourceList() {
return resourceList;
}
public void setResourceList(List<Resource> resourceList) {
this.resourceList = resourceList;
}
@ProblemFactCollectionProperty
public List<ResourceRequirement> getResourceRequirementList() {
return resourceRequirementList;
}
public void setResourceRequirementList(List<ResourceRequirement> resourceRequirementList) {
this.resourceRequirementList = resourceRequirementList;
}
@PlanningEntityCollectionProperty
public List<Allocation> getAllocationList() {
return allocationList;
}
public void setAllocationList(List<Allocation> allocationList) {
this.allocationList = allocationList;
}
@PlanningScore
public HardMediumSoftScore getScore() {
return score;
}
public void setScore(HardMediumSoftScore score) {
this.score = score;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/resource/GlobalResource.java | package ai.timefold.solver.examples.projectjobscheduling.domain.resource;
public class GlobalResource extends Resource {
public GlobalResource() {
}
public GlobalResource(long id, int capacity) {
super(id, capacity);
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public boolean isRenewable() {
return true;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/resource/LocalResource.java | package ai.timefold.solver.examples.projectjobscheduling.domain.resource;
import ai.timefold.solver.examples.projectjobscheduling.domain.Project;
public class LocalResource extends Resource {
private Project project;
private boolean renewable;
public LocalResource() {
}
public LocalResource(long id, Project project, boolean renewable) {
super(id, 0);
this.project = project;
this.renewable = renewable;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
@Override
public boolean isRenewable() {
return renewable;
}
public void setRenewable(boolean renewable) {
this.renewable = renewable;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/resource/Resource.java | package ai.timefold.solver.examples.projectjobscheduling.domain.resource;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
@JsonSubTypes.Type(value = GlobalResource.class, name = "global"),
@JsonSubTypes.Type(value = LocalResource.class, name = "local"),
})
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public abstract class Resource extends AbstractPersistable {
private int capacity;
protected Resource() {
}
protected Resource(long id, int capacity) {
super(id);
this.capacity = capacity;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
// ************************************************************************
// Complex methods
// ************************************************************************
public abstract boolean isRenewable();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/solver/DelayStrengthComparator.java | package ai.timefold.solver.examples.projectjobscheduling.domain.solver;
import java.util.Comparator;
public class DelayStrengthComparator implements Comparator<Integer> {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/solver/ExecutionModeStrengthWeightFactory.java | package ai.timefold.solver.examples.projectjobscheduling.domain.solver;
import static java.util.Comparator.comparingDouble;
import static java.util.Comparator.comparingLong;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import ai.timefold.solver.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory;
import ai.timefold.solver.examples.projectjobscheduling.domain.ExecutionMode;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
public class ExecutionModeStrengthWeightFactory implements SelectionSorterWeightFactory<Schedule, ExecutionMode> {
@Override
public ExecutionModeStrengthWeight createSorterWeight(Schedule schedule, ExecutionMode executionMode) {
Map<Resource, Integer> requirementTotalMap = new HashMap<>(
executionMode.getResourceRequirementList().size());
for (ResourceRequirement resourceRequirement : executionMode.getResourceRequirementList()) {
requirementTotalMap.put(resourceRequirement.getResource(), 0);
}
for (ResourceRequirement resourceRequirement : schedule.getResourceRequirementList()) {
Resource resource = resourceRequirement.getResource();
Integer total = requirementTotalMap.get(resource);
if (total != null) {
total += resourceRequirement.getRequirement();
requirementTotalMap.put(resource, total);
}
}
double requirementDesirability = 0.0;
for (ResourceRequirement resourceRequirement : executionMode.getResourceRequirementList()) {
Resource resource = resourceRequirement.getResource();
int total = requirementTotalMap.get(resource);
if (total > resource.getCapacity()) {
requirementDesirability += (total - resource.getCapacity())
* (double) resourceRequirement.getRequirement()
* (resource.isRenewable() ? 1.0 : 100.0);
}
}
return new ExecutionModeStrengthWeight(executionMode, requirementDesirability);
}
public static class ExecutionModeStrengthWeight implements Comparable<ExecutionModeStrengthWeight> {
private static final Comparator<ExecutionModeStrengthWeight> COMPARATOR = comparingDouble(
(ExecutionModeStrengthWeight weight) -> weight.requirementDesirability)
.thenComparing(weight -> weight.executionMode, comparingLong(ExecutionMode::getId));
private final ExecutionMode executionMode;
private final double requirementDesirability;
public ExecutionModeStrengthWeight(ExecutionMode executionMode, double requirementDesirability) {
this.executionMode = executionMode;
this.requirementDesirability = requirementDesirability;
}
@Override
public int compareTo(ExecutionModeStrengthWeight other) {
return COMPARATOR.compare(this, other);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/solver/NotSourceOrSinkAllocationFilter.java | package ai.timefold.solver.examples.projectjobscheduling.domain.solver;
import ai.timefold.solver.core.api.domain.entity.PinningFilter;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.JobType;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
public class NotSourceOrSinkAllocationFilter implements PinningFilter<Schedule, Allocation> {
@Override
public boolean accept(Schedule schedule, Allocation allocation) {
JobType jobType = allocation.getJob().getJobType();
return jobType == JobType.SOURCE || jobType == JobType.SINK;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/domain/solver/PredecessorsDoneDateUpdatingVariableListener.java | package ai.timefold.solver.examples.projectjobscheduling.domain.solver;
import java.util.ArrayDeque;
import java.util.Objects;
import java.util.Queue;
import ai.timefold.solver.core.api.domain.variable.VariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
public class PredecessorsDoneDateUpdatingVariableListener implements VariableListener<Schedule, Allocation> {
@Override
public void beforeEntityAdded(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
@Override
public void afterEntityAdded(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
updateAllocation(scoreDirector, allocation);
}
@Override
public void beforeVariableChanged(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
@Override
public void afterVariableChanged(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
updateAllocation(scoreDirector, allocation);
}
@Override
public void beforeEntityRemoved(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
@Override
public void afterEntityRemoved(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// Do nothing
}
protected void updateAllocation(ScoreDirector<Schedule> scoreDirector, Allocation originalAllocation) {
Queue<Allocation> uncheckedSuccessorQueue = new ArrayDeque<>();
uncheckedSuccessorQueue.addAll(originalAllocation.getSuccessorAllocationList());
while (!uncheckedSuccessorQueue.isEmpty()) {
Allocation allocation = uncheckedSuccessorQueue.remove();
boolean updated = updatePredecessorsDoneDate(scoreDirector, allocation);
if (updated) {
uncheckedSuccessorQueue.addAll(allocation.getSuccessorAllocationList());
}
}
}
/**
* @param scoreDirector never null
* @param allocation never null
* @return true if the startDate changed
*/
protected boolean updatePredecessorsDoneDate(ScoreDirector<Schedule> scoreDirector, Allocation allocation) {
// For the source the doneDate must be 0.
Integer doneDate = 0;
for (Allocation predecessorAllocation : allocation.getPredecessorAllocationList()) {
int endDate = predecessorAllocation.getEndDate();
doneDate = Math.max(doneDate, endDate);
}
if (Objects.equals(doneDate, allocation.getPredecessorsDoneDate())) {
return false;
}
scoreDirector.beforeVariableChanged(allocation, "predecessorsDoneDate");
allocation.setPredecessorsDoneDate(doneDate);
scoreDirector.afterVariableChanged(allocation, "predecessorsDoneDate");
return true;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/benchmark/ProjectJobSchedulingBenchmarkApp.java | package ai.timefold.solver.examples.projectjobscheduling.optional.benchmark;
import ai.timefold.solver.examples.common.app.CommonBenchmarkApp;
public class ProjectJobSchedulingBenchmarkApp extends CommonBenchmarkApp {
public static void main(String[] args) {
new ProjectJobSchedulingBenchmarkApp().buildAndBenchmark(args);
}
public ProjectJobSchedulingBenchmarkApp() {
super(
new ArgOption("template",
"ai/timefold/solver/examples/projectjobscheduling/optional/benchmark/projectJobSchedulingBenchmarkConfigTemplate.xml.ftl",
true));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score/ProjectJobSchedulingIncrementalScoreCalculator.java | package ai.timefold.solver.examples.projectjobscheduling.optional.score;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.calculator.IncrementalScoreCalculator;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.ExecutionMode;
import ai.timefold.solver.examples.projectjobscheduling.domain.JobType;
import ai.timefold.solver.examples.projectjobscheduling.domain.Project;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
import ai.timefold.solver.examples.projectjobscheduling.optional.score.common.NonrenewableResourceCapacityTracker;
import ai.timefold.solver.examples.projectjobscheduling.optional.score.common.RenewableResourceCapacityTracker;
import ai.timefold.solver.examples.projectjobscheduling.optional.score.common.ResourceCapacityTracker;
public class ProjectJobSchedulingIncrementalScoreCalculator
implements IncrementalScoreCalculator<Schedule, HardMediumSoftScore> {
private Map<Resource, ResourceCapacityTracker> resourceCapacityTrackerMap;
private Map<Project, Integer> projectEndDateMap;
private int maximumProjectEndDate;
private int hardScore;
private int mediumScore;
private int softScore;
@Override
public void resetWorkingSolution(Schedule schedule) {
List<Resource> resourceList = schedule.getResourceList();
resourceCapacityTrackerMap = new HashMap<>(resourceList.size());
for (Resource resource : resourceList) {
resourceCapacityTrackerMap.put(resource, resource.isRenewable()
? new RenewableResourceCapacityTracker(resource)
: new NonrenewableResourceCapacityTracker(resource));
}
List<Project> projectList = schedule.getProjectList();
projectEndDateMap = new HashMap<>(projectList.size());
maximumProjectEndDate = 0;
hardScore = 0;
mediumScore = 0;
softScore = 0;
int minimumReleaseDate = Integer.MAX_VALUE;
for (Project p : projectList) {
minimumReleaseDate = Math.min(p.getReleaseDate(), minimumReleaseDate);
}
softScore += minimumReleaseDate;
for (Allocation allocation : schedule.getAllocationList()) {
insert(allocation);
}
}
@Override
public void beforeEntityAdded(Object entity) {
// Do nothing
}
@Override
public void afterEntityAdded(Object entity) {
insert((Allocation) entity);
}
@Override
public void beforeVariableChanged(Object entity, String variableName) {
retract((Allocation) entity);
}
@Override
public void afterVariableChanged(Object entity, String variableName) {
insert((Allocation) entity);
}
@Override
public void beforeEntityRemoved(Object entity) {
retract((Allocation) entity);
}
@Override
public void afterEntityRemoved(Object entity) {
// Do nothing
}
private void insert(Allocation allocation) {
// Job precedence is built-in
// Resource capacity
ExecutionMode executionMode = allocation.getExecutionMode();
if (executionMode != null && allocation.getJob().getJobType() == JobType.STANDARD) {
for (ResourceRequirement resourceRequirement : executionMode.getResourceRequirementList()) {
ResourceCapacityTracker tracker = resourceCapacityTrackerMap.get(
resourceRequirement.getResource());
hardScore -= tracker.getHardScore();
tracker.insert(resourceRequirement, allocation);
hardScore += tracker.getHardScore();
}
}
// Total project delay and total make span
if (allocation.getJob().getJobType() == JobType.SINK) {
Integer endDate = allocation.getEndDate();
if (endDate != null) {
Project project = allocation.getProject();
projectEndDateMap.put(project, endDate);
// Total project delay
mediumScore -= endDate - project.getCriticalPathEndDate();
// Total make span
if (endDate > maximumProjectEndDate) {
softScore -= endDate - maximumProjectEndDate;
maximumProjectEndDate = endDate;
}
}
}
}
private void retract(Allocation allocation) {
// Job precedence is built-in
// Resource capacity
ExecutionMode executionMode = allocation.getExecutionMode();
if (executionMode != null && allocation.getJob().getJobType() == JobType.STANDARD) {
for (ResourceRequirement resourceRequirement : executionMode.getResourceRequirementList()) {
ResourceCapacityTracker tracker = resourceCapacityTrackerMap.get(
resourceRequirement.getResource());
hardScore -= tracker.getHardScore();
tracker.retract(resourceRequirement, allocation);
hardScore += tracker.getHardScore();
}
}
// Total project delay and total make span
if (allocation.getJob().getJobType() == JobType.SINK) {
Integer endDate = allocation.getEndDate();
if (endDate != null) {
Project project = allocation.getProject();
projectEndDateMap.remove(project);
// Total project delay
mediumScore += endDate - project.getCriticalPathEndDate();
// Total make span
if (endDate == maximumProjectEndDate) {
updateMaximumProjectEndDate();
softScore += endDate - maximumProjectEndDate;
}
}
}
}
private void updateMaximumProjectEndDate() {
int maximum = 0;
for (Integer endDate : projectEndDateMap.values()) {
if (endDate > maximum) {
maximum = endDate;
}
}
maximumProjectEndDate = maximum;
}
@Override
public HardMediumSoftScore calculateScore() {
return HardMediumSoftScore.of(hardScore, mediumScore, softScore);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score/common/NonrenewableResourceCapacityTracker.java | package ai.timefold.solver.examples.projectjobscheduling.optional.score.common;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
public class NonrenewableResourceCapacityTracker extends ResourceCapacityTracker {
protected int capacity;
protected int used;
public NonrenewableResourceCapacityTracker(Resource resource) {
super(resource);
if (resource.isRenewable()) {
throw new IllegalArgumentException("The resource (" + resource + ") is expected to be nonrenewable.");
}
capacity = resource.getCapacity();
used = 0;
}
@Override
public void insert(ResourceRequirement resourceRequirement, Allocation allocation) {
used += resourceRequirement.getRequirement();
}
@Override
public void retract(ResourceRequirement resourceRequirement, Allocation allocation) {
used -= resourceRequirement.getRequirement();
}
@Override
public int getHardScore() {
if (capacity >= used) {
return 0;
}
return capacity - used;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score/common/RenewableResourceCapacityTracker.java | package ai.timefold.solver.examples.projectjobscheduling.optional.score.common;
import java.util.HashMap;
import java.util.Map;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
public class RenewableResourceCapacityTracker extends ResourceCapacityTracker {
protected int capacityEveryDay;
protected Map<Integer, Integer> usedPerDay;
protected int hardScore;
public RenewableResourceCapacityTracker(Resource resource) {
super(resource);
if (!resource.isRenewable()) {
throw new IllegalArgumentException("The resource (" + resource + ") is expected to be renewable.");
}
capacityEveryDay = resource.getCapacity();
usedPerDay = new HashMap<>();
hardScore = 0;
}
@Override
public void insert(ResourceRequirement resourceRequirement, Allocation allocation) {
int startDate = allocation.getStartDate();
int endDate = allocation.getEndDate();
int requirement = resourceRequirement.getRequirement();
for (int i = startDate; i < endDate; i++) {
Integer used = usedPerDay.get(i);
if (used == null) {
used = 0;
}
if (used > capacityEveryDay) {
hardScore += (used - capacityEveryDay);
}
used += requirement;
if (used > capacityEveryDay) {
hardScore -= (used - capacityEveryDay);
}
usedPerDay.put(i, used);
}
}
@Override
public void retract(ResourceRequirement resourceRequirement, Allocation allocation) {
int startDate = allocation.getStartDate();
int endDate = allocation.getEndDate();
int requirement = resourceRequirement.getRequirement();
for (int i = startDate; i < endDate; i++) {
Integer used = usedPerDay.get(i);
if (used == null) {
used = 0;
}
if (used > capacityEveryDay) {
hardScore += (used - capacityEveryDay);
}
used -= requirement;
if (used > capacityEveryDay) {
hardScore -= (used - capacityEveryDay);
}
usedPerDay.put(i, used);
}
}
@Override
public int getHardScore() {
return hardScore;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score/common/RenewableResourceUsedDay.java | package ai.timefold.solver.examples.projectjobscheduling.optional.score.common;
import java.util.Objects;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
public class RenewableResourceUsedDay {
private final Resource resource;
private final int usedDay;
public RenewableResourceUsedDay(Resource resource, int usedDay) {
this.resource = resource;
this.usedDay = usedDay;
}
public Resource getResource() {
return resource;
}
public int getUsedDay() {
return usedDay;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final RenewableResourceUsedDay other = (RenewableResourceUsedDay) o;
return usedDay == other.usedDay &&
Objects.equals(resource, other.resource);
}
@Override
public int hashCode() {
return Objects.hash(resource, usedDay);
}
@Override
public String toString() {
return resource + " on " + usedDay;
}
public int getResourceCapacity() {
return resource.getCapacity();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/optional/score/common/ResourceCapacityTracker.java | package ai.timefold.solver.examples.projectjobscheduling.optional.score.common;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
public abstract class ResourceCapacityTracker {
protected Resource resource;
public ResourceCapacityTracker(Resource resource) {
this.resource = resource;
}
public abstract void insert(ResourceRequirement resourceRequirement, Allocation allocation);
public abstract void retract(ResourceRequirement resourceRequirement, Allocation allocation);
public abstract int getHardScore();
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/persistence/ProjectJobSchedulingImporter.java | package ai.timefold.solver.examples.projectjobscheduling.persistence;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import ai.timefold.solver.examples.common.persistence.AbstractTxtSolutionImporter;
import ai.timefold.solver.examples.common.persistence.SolutionConverter;
import ai.timefold.solver.examples.projectjobscheduling.app.ProjectJobSchedulingApp;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.ExecutionMode;
import ai.timefold.solver.examples.projectjobscheduling.domain.Job;
import ai.timefold.solver.examples.projectjobscheduling.domain.JobType;
import ai.timefold.solver.examples.projectjobscheduling.domain.Project;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.GlobalResource;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.LocalResource;
import ai.timefold.solver.examples.projectjobscheduling.domain.resource.Resource;
public class ProjectJobSchedulingImporter extends AbstractTxtSolutionImporter<Schedule> {
public static void main(String[] args) {
SolutionConverter<Schedule> converter = SolutionConverter.createImportConverter(ProjectJobSchedulingApp.DATA_DIR_NAME,
new ProjectJobSchedulingImporter(), new ProjectJobSchedulingSolutionFileIO());
converter.convertAll();
}
@Override
public TxtInputBuilder<Schedule> createTxtInputBuilder() {
return new ProjectJobSchedulingInputBuilder();
}
public static class ProjectJobSchedulingInputBuilder extends TxtInputBuilder<Schedule> {
private Schedule schedule;
private int projectListSize;
private int resourceListSize;
private int globalResourceListSize;
private long projectId = 0L;
private long resourceId = 0L;
private long jobId = 0L;
private long executionModeId = 0L;
private long resourceRequirementId = 0L;
private Map<Project, File> projectFileMap;
@Override
public Schedule readSolution() throws IOException {
schedule = new Schedule(0L);
readProjectList();
readResourceList();
for (Map.Entry<Project, File> entry : projectFileMap.entrySet()) {
readProjectFile(entry.getKey(), entry.getValue());
}
removePointlessExecutionModes();
createAllocationList();
logger.info("Schedule {} has {} projects, {} jobs, {} execution modes, {} resources"
+ " and {} resource requirements.",
getInputId(),
schedule.getProjectList().size(),
schedule.getJobList().size(),
schedule.getExecutionModeList().size(),
schedule.getResourceList().size(),
schedule.getResourceRequirementList().size());
return schedule;
}
private void readProjectList() throws IOException {
projectListSize = readIntegerValue();
List<Project> projectList = new ArrayList<>(projectListSize);
projectFileMap = new LinkedHashMap<>(projectListSize);
for (int i = 0; i < projectListSize; i++) {
Project project = new Project(projectId, readIntegerValue(), readIntegerValue());
File projectFile = new File(inputFile.getParentFile(), readStringValue());
if (!projectFile.exists()) {
throw new IllegalArgumentException("The projectFile (" + projectFile + ") does not exist.");
}
projectFileMap.put(project, projectFile);
projectList.add(project);
projectId++;
}
schedule.setProjectList(projectList);
schedule.setJobList(new ArrayList<>(projectListSize * 10));
schedule.setExecutionModeList(new ArrayList<>(projectListSize * 10 * 5));
}
private void readResourceList() throws IOException {
resourceListSize = readIntegerValue();
String[] tokens = splitBySpacesOrTabs(readStringValue(), resourceListSize);
List<Resource> resourceList = new ArrayList<>(resourceListSize * projectListSize * 10);
for (int i = 0; i < resourceListSize; i++) {
int capacity = Integer.parseInt(tokens[i]);
if (capacity != -1) {
GlobalResource resource = new GlobalResource(resourceId, capacity);
resourceList.add(resource);
resourceId++;
}
}
globalResourceListSize = resourceList.size();
schedule.setResourceList(resourceList);
schedule.setResourceRequirementList(new ArrayList<>(
projectListSize * 10 * 5 * resourceListSize));
}
private void readProjectFile(Project project, File projectFile) {
try (BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(projectFile), "UTF-8"))) {
ProjectFileInputBuilder projectFileInputBuilder = new ProjectFileInputBuilder(schedule, project);
projectFileInputBuilder.setInputFile(projectFile);
projectFileInputBuilder.setBufferedReader(bufferedReader);
try {
projectFileInputBuilder.readSolution();
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Exception in projectFile (" + projectFile + ")", e);
} catch (IllegalStateException e) {
throw new IllegalStateException("Exception in projectFile (" + projectFile + ")", e);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read the projectFile (" + projectFile + ").", e);
}
}
public class ProjectFileInputBuilder extends TxtInputBuilder {
private Schedule schedule;
private Project project;
private int jobListSize;
private int renewableLocalResourceSize;
private int nonrenewableLocalResourceSize;
public ProjectFileInputBuilder(Schedule schedule, Project project) {
this.schedule = schedule;
this.project = project;
}
@Override
public Schedule readSolution() throws IOException {
readHeader();
readResourceList();
readProjectInformation();
readPrecedenceRelations();
readRequestDurations();
readResourceAvailabilities();
detectPointlessSuccessor();
return null; // Hack so the code can reuse read methods from TxtInputBuilder
}
private void readHeader() throws IOException {
readConstantLine("\\*+");
readStringValue("file with basedata *:");
readStringValue("initial value random generator *:");
readConstantLine("\\*+");
int projects = readIntegerValue("projects *:");
if (projects != 1) {
throw new IllegalArgumentException("The projects value (" + projects + ") should always be 1.");
}
jobListSize = readIntegerValue("jobs \\(incl\\. supersource/sink *\\) *:");
int horizon = readIntegerValue("horizon *:");
// Ignore horizon
}
private void readResourceList() throws IOException {
readConstantLine("RESOURCES");
int renewableResourceSize = readIntegerValue("\\- renewable *:", "R");
if (renewableResourceSize < globalResourceListSize) {
throw new IllegalArgumentException("The renewableResourceSize (" + renewableResourceSize
+ ") cannot be less than globalResourceListSize (" + globalResourceListSize + ").");
}
renewableLocalResourceSize = renewableResourceSize - globalResourceListSize;
nonrenewableLocalResourceSize = readIntegerValue("\\- nonrenewable *:", "N");
int doublyConstrainedResourceSize = readIntegerValue("\\- doubly constrained *:", "D");
if (doublyConstrainedResourceSize != 0) {
throw new IllegalArgumentException("The doublyConstrainedResourceSize ("
+ doublyConstrainedResourceSize + ") should always be 0.");
}
List<LocalResource> localResourceList = new ArrayList<>(
globalResourceListSize + renewableLocalResourceSize + nonrenewableLocalResourceSize);
for (int i = 0; i < renewableLocalResourceSize; i++) {
LocalResource localResource = new LocalResource(resourceId, project, true);
resourceId++;
localResourceList.add(localResource);
}
for (int i = 0; i < nonrenewableLocalResourceSize; i++) {
LocalResource localResource = new LocalResource(resourceId, project, false);
resourceId++;
localResourceList.add(localResource);
}
project.setLocalResourceList(localResourceList);
schedule.getResourceList().addAll(localResourceList);
readConstantLine("\\*+");
}
private void readProjectInformation() throws IOException {
readConstantLine("PROJECT INFORMATION:");
readConstantLine("pronr\\. +\\#jobs +rel\\.date +duedate +tardcost +MPM\\-Time");
String[] tokens = splitBySpacesOrTabs(readStringValue(), 6);
if (Integer.parseInt(tokens[0]) != 1) {
throw new IllegalArgumentException("The project information tokens (" + Arrays.toString(tokens)
+ ") index 0 should be 1.");
}
if (Integer.parseInt(tokens[1]) != jobListSize - 2) {
throw new IllegalArgumentException("The project information tokens (" + Arrays.toString(tokens)
+ ") index 1 should be " + (jobListSize - 2) + ".");
}
// Ignore releaseDate, dueDate, tardinessCost and mpmTime
readConstantLine("\\*+");
}
private void readPrecedenceRelations() throws IOException {
readConstantLine("PRECEDENCE RELATIONS:");
readConstantLine("jobnr\\. +\\#modes +\\#successors +successors");
List<Job> jobList = new ArrayList<>(jobListSize);
for (int i = 0; i < jobListSize; i++) {
Job job = new Job(jobId, project);
if (i == 0) {
job.setJobType(JobType.SOURCE);
} else if (i == jobListSize - 1) {
job.setJobType(JobType.SINK);
} else {
job.setJobType(JobType.STANDARD);
}
jobList.add(job);
jobId++;
}
project.setJobList(jobList);
schedule.getJobList().addAll(jobList);
for (int i = 0; i < jobListSize; i++) {
Job job = jobList.get(i);
String[] tokens = splitBySpacesOrTabs(readStringValue());
if (tokens.length < 3) {
throw new IllegalArgumentException("The tokens (" + Arrays.toString(tokens)
+ ") should be at least 3 in length.");
}
if (Integer.parseInt(tokens[0]) != i + 1) {
throw new IllegalArgumentException("The tokens (" + Arrays.toString(tokens)
+ ") index 0 should be " + (i + 1) + ".");
}
int executionModeListSize = Integer.parseInt(tokens[1]);
List<ExecutionMode> executionModeList = new ArrayList<>(executionModeListSize);
for (int j = 0; j < executionModeListSize; j++) {
ExecutionMode executionMode = new ExecutionMode(executionModeId, job);
executionModeList.add(executionMode);
executionModeId++;
}
job.setExecutionModeList(executionModeList);
schedule.getExecutionModeList().addAll(executionModeList);
int successorJobListSize = Integer.parseInt(tokens[2]);
if (tokens.length != 3 + successorJobListSize) {
throw new IllegalArgumentException("The tokens (" + Arrays.toString(tokens)
+ ") should be " + (3 + successorJobListSize) + " in length.");
}
List<Job> successorJobList = new ArrayList<>(successorJobListSize);
for (int j = 0; j < successorJobListSize; j++) {
int successorIndex = Integer.parseInt(tokens[3 + j]);
Job successorJob = project.getJobList().get(successorIndex - 1);
successorJobList.add(successorJob);
}
job.setSuccessorJobList(successorJobList);
}
readConstantLine("\\*+");
}
private void readRequestDurations() throws IOException {
readConstantLine("REQUESTS/DURATIONS:");
splitBySpacesOrTabs(readStringValue());
readConstantLine("\\-+");
int resourceSize = globalResourceListSize + renewableLocalResourceSize + nonrenewableLocalResourceSize;
for (int i = 0; i < jobListSize; i++) {
Job job = project.getJobList().get(i);
int executionModeSize = job.getExecutionModeList().size();
for (int j = 0; j < executionModeSize; j++) {
ExecutionMode executionMode = job.getExecutionModeList().get(j);
boolean first = j == 0;
String[] tokens = splitBySpacesOrTabs(readStringValue(), (first ? 3 : 2) + resourceSize);
if (first && Integer.parseInt(tokens[0]) != i + 1) {
throw new IllegalArgumentException("The tokens (" + Arrays.toString(tokens)
+ ") index 0 should be " + (i + 1) + ".");
}
if (Integer.parseInt(tokens[first ? 1 : 0]) != j + 1) {
throw new IllegalArgumentException("The tokens (" + Arrays.toString(tokens)
+ ") index " + (first ? 1 : 0) + " should be " + (j + 1) + ".");
}
int duration = Integer.parseInt(tokens[first ? 2 : 1]);
executionMode.setDuration(duration);
List<ResourceRequirement> resourceRequirementList = new ArrayList<>(
resourceSize);
for (int k = 0; k < resourceSize; k++) {
int requirement = Integer.parseInt(tokens[(first ? 3 : 2) + k]);
if (requirement != 0) {
Resource resource = (k < globalResourceListSize)
? schedule.getResourceList().get(k)
: project.getLocalResourceList().get(k - globalResourceListSize);
ResourceRequirement resourceRequirement =
new ResourceRequirement(resourceRequirementId, executionMode, resource, requirement);
resourceRequirementList.add(resourceRequirement);
resourceRequirementId++;
}
}
executionMode.setResourceRequirementList(resourceRequirementList);
schedule.getResourceRequirementList().addAll(resourceRequirementList);
}
}
readConstantLine("\\*+");
}
private void readResourceAvailabilities() throws IOException {
readConstantLine("RESOURCEAVAILABILITIES:");
splitBySpacesOrTabs(readStringValue());
int resourceSize = globalResourceListSize + renewableLocalResourceSize + nonrenewableLocalResourceSize;
String[] tokens = splitBySpacesOrTabs(readStringValue(), resourceSize);
for (int i = 0; i < resourceSize; i++) {
int capacity = Integer.parseInt(tokens[i]);
if (i < globalResourceListSize) {
// Overwritten by global resource
} else {
Resource resource = project.getLocalResourceList().get(i - globalResourceListSize);
resource.setCapacity(capacity);
}
}
readConstantLine("\\*+");
}
private void detectPointlessSuccessor() {
for (Job baseJob : project.getJobList()) {
Set<Job> baseSuccessorJobSet = new HashSet<>(baseJob.getSuccessorJobList());
Set<Job> checkedSuccessorSet = new HashSet<>(project.getJobList().size());
Queue<Job> uncheckedSuccessorQueue = new ArrayDeque<>(project.getJobList().size());
for (Job baseSuccessorJob : baseJob.getSuccessorJobList()) {
uncheckedSuccessorQueue.addAll(baseSuccessorJob.getSuccessorJobList());
}
while (!uncheckedSuccessorQueue.isEmpty()) {
Job uncheckedJob = uncheckedSuccessorQueue.remove();
if (checkedSuccessorSet.contains(uncheckedJob)) {
continue;
}
if (baseSuccessorJobSet.contains(uncheckedJob)) {
throw new IllegalStateException("The baseJob (" + baseJob
+ ") has a direct successor (" + uncheckedJob
+ ") that is also an indirect successor. That's pointless.");
}
uncheckedSuccessorQueue.addAll(uncheckedJob.getSuccessorJobList());
}
}
}
}
private void removePointlessExecutionModes() {
// TODO iterate through schedule.getJobList(), find pointless ExecutionModes
// and delete them both from the job and from schedule.getExecutionModeList()
}
private void createAllocationList() {
List<Job> jobList = schedule.getJobList();
List<Allocation> allocationList = new ArrayList<>(jobList.size());
Map<Job, Allocation> jobToAllocationMap = new HashMap<>(jobList.size());
Map<Project, Allocation> projectToSourceAllocationMap = new HashMap<>(projectListSize);
Map<Project, Allocation> projectToSinkAllocationMap = new HashMap<>(projectListSize);
for (Job job : jobList) {
Allocation allocation = new Allocation(job.getId(), job);
allocation.setPredecessorAllocationList(new ArrayList<>(job.getSuccessorJobList().size()));
allocation.setSuccessorAllocationList(new ArrayList<>(job.getSuccessorJobList().size()));
// Uninitialized allocations take no time, but don't break the predecessorsDoneDate cascade to sink.
allocation.setPredecessorsDoneDate(job.getProject().getReleaseDate());
if (job.getJobType() == JobType.SOURCE) {
allocation.setDelay(0);
if (job.getExecutionModeList().size() != 1) {
throw new IllegalArgumentException("The job (" + job
+ ")'s executionModeList (" + job.getExecutionModeList()
+ ") is expected to be a singleton.");
}
allocation.setExecutionMode(job.getExecutionModeList().get(0));
projectToSourceAllocationMap.put(job.getProject(), allocation);
} else if (job.getJobType() == JobType.SINK) {
allocation.setDelay(0);
if (job.getExecutionModeList().size() != 1) {
throw new IllegalArgumentException("The job (" + job
+ ")'s executionModeList (" + job.getExecutionModeList()
+ ") is expected to be a singleton.");
}
allocation.setExecutionMode(job.getExecutionModeList().get(0));
projectToSinkAllocationMap.put(job.getProject(), allocation);
}
allocationList.add(allocation);
jobToAllocationMap.put(job, allocation);
}
for (Allocation allocation : allocationList) {
Job job = allocation.getJob();
allocation.setSourceAllocation(projectToSourceAllocationMap.get(job.getProject()));
allocation.setSinkAllocation(projectToSinkAllocationMap.get(job.getProject()));
for (Job successorJob : job.getSuccessorJobList()) {
Allocation successorAllocation = jobToAllocationMap.get(successorJob);
allocation.getSuccessorAllocationList().add(successorAllocation);
successorAllocation.getPredecessorAllocationList().add(allocation);
}
}
for (Allocation sourceAllocation : projectToSourceAllocationMap.values()) {
for (Allocation allocation : sourceAllocation.getSuccessorAllocationList()) {
allocation.setPredecessorsDoneDate(sourceAllocation.getEndDate());
}
}
schedule.setAllocationList(allocationList);
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/persistence/ProjectJobSchedulingSolutionFileIO.java | package ai.timefold.solver.examples.projectjobscheduling.persistence;
import ai.timefold.solver.examples.common.persistence.AbstractJsonSolutionFileIO;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
public class ProjectJobSchedulingSolutionFileIO extends AbstractJsonSolutionFileIO<Schedule> {
public ProjectJobSchedulingSolutionFileIO() {
super(Schedule.class);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/score/ProjectJobSchedulingConstraintProvider.java | package ai.timefold.solver.examples.projectjobscheduling.score;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintCollectors;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.Joiners;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.JobType;
import ai.timefold.solver.examples.projectjobscheduling.domain.ResourceRequirement;
public class ProjectJobSchedulingConstraintProvider implements ConstraintProvider {
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
nonRenewableResourceCapacity(constraintFactory),
renewableResourceCapacity(constraintFactory),
totalProjectDelay(constraintFactory),
totalMakespan(constraintFactory)
};
}
protected Constraint nonRenewableResourceCapacity(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(ResourceRequirement.class)
.filter(resource -> !resource.isResourceRenewable())
.join(Allocation.class,
Joiners.equal(ResourceRequirement::getExecutionMode, Allocation::getExecutionMode))
.groupBy((requirement, allocation) -> requirement.getResource(),
ConstraintCollectors.sum((requirement, allocation) -> requirement.getRequirement()))
.filter((resource, requirements) -> requirements > resource.getCapacity())
.penalize(HardMediumSoftScore.ONE_HARD,
(resource, requirements) -> requirements - resource.getCapacity())
.asConstraint("Non-renewable resource capacity");
}
protected Constraint renewableResourceCapacity(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(ResourceRequirement.class)
.filter(ResourceRequirement::isResourceRenewable)
.join(Allocation.class,
Joiners.equal(ResourceRequirement::getExecutionMode, Allocation::getExecutionMode))
.flattenLast(Allocation::getBusyDates)
.groupBy((resourceReq, date) -> resourceReq.getResource(),
(resourceReq, date) -> date,
ConstraintCollectors.sum((resourceReq, date) -> resourceReq.getRequirement()))
.filter((resourceReq, date, totalRequirement) -> totalRequirement > resourceReq.getCapacity())
.penalize(HardMediumSoftScore.ONE_HARD,
(resourceReq, date, totalRequirement) -> totalRequirement - resourceReq.getCapacity())
.asConstraint("Renewable resource capacity");
}
protected Constraint totalProjectDelay(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Allocation.class)
.filter(allocation -> allocation.getEndDate() != null && allocation.getJobType() == JobType.SINK)
.impact(HardMediumSoftScore.ONE_MEDIUM,
allocation -> allocation.getProjectCriticalPathEndDate() - allocation.getEndDate())
.asConstraint("Total project delay");
}
protected Constraint totalMakespan(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Allocation.class)
.filter(allocation -> allocation.getEndDate() != null && allocation.getJobType() == JobType.SINK)
.groupBy(ConstraintCollectors.max(Allocation::getEndDate))
.penalize(HardMediumSoftScore.ONE_SOFT, maxEndDate -> maxEndDate)
.asConstraint("Total makespan");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/projectjobscheduling/swingui/ProjectJobSchedulingPanel.java | package ai.timefold.solver.examples.projectjobscheduling.swingui;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.util.LinkedHashMap;
import java.util.Map;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
import ai.timefold.solver.examples.projectjobscheduling.domain.Allocation;
import ai.timefold.solver.examples.projectjobscheduling.domain.Project;
import ai.timefold.solver.examples.projectjobscheduling.domain.Schedule;
import ai.timefold.solver.swing.impl.TangoColorFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.YIntervalRenderer;
import org.jfree.data.xy.YIntervalSeries;
import org.jfree.data.xy.YIntervalSeriesCollection;
public class ProjectJobSchedulingPanel extends SolutionPanel<Schedule> {
public static final String LOGO_PATH =
"/ai/timefold/solver/examples/projectjobscheduling/swingui/projectJobSchedulingLogo.png";
public ProjectJobSchedulingPanel() {
setLayout(new BorderLayout());
}
@Override
public void resetPanel(Schedule schedule) {
removeAll();
ChartPanel chartPanel = new ChartPanel(createChart(schedule));
add(chartPanel, BorderLayout.CENTER);
}
private JFreeChart createChart(Schedule schedule) {
YIntervalSeriesCollection seriesCollection = new YIntervalSeriesCollection();
Map<Project, YIntervalSeries> projectSeriesMap = new LinkedHashMap<>(
schedule.getProjectList().size());
YIntervalRenderer renderer = new YIntervalRenderer();
int maximumEndDate = 0;
int seriesIndex = 0;
TangoColorFactory tangoColorFactory = new TangoColorFactory();
for (Project project : schedule.getProjectList()) {
YIntervalSeries projectSeries = new YIntervalSeries(project.getLabel());
seriesCollection.addSeries(projectSeries);
projectSeriesMap.put(project, projectSeries);
renderer.setSeriesShape(seriesIndex, new Rectangle());
renderer.setSeriesStroke(seriesIndex, new BasicStroke(3.0f));
renderer.setSeriesPaint(seriesIndex, tangoColorFactory.pickColor(project));
seriesIndex++;
}
for (Allocation allocation : schedule.getAllocationList()) {
int startDate = allocation.getStartDate();
int endDate = allocation.getEndDate();
YIntervalSeries projectSeries = projectSeriesMap.get(allocation.getProject());
projectSeries.add(allocation.getId(), (startDate + endDate) / 2.0,
startDate, endDate);
maximumEndDate = Math.max(maximumEndDate, endDate);
}
NumberAxis domainAxis = new NumberAxis("Job");
domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
domainAxis.setRange(-0.5, schedule.getAllocationList().size() - 0.5);
domainAxis.setInverted(true);
NumberAxis rangeAxis = new NumberAxis("Day (start to end date)");
rangeAxis.setRange(-0.5, maximumEndDate + 0.5);
XYPlot plot = new XYPlot(seriesCollection, domainAxis, rangeAxis, renderer);
plot.setOrientation(PlotOrientation.HORIZONTAL);
plot.setDomainGridlinePaint(TangoColorFactory.ALUMINIUM_5);
plot.setRangeGridlinePaint(TangoColorFactory.ALUMINIUM_5);
return new JFreeChart("Project Job Scheduling", JFreeChart.DEFAULT_TITLE_FONT,
plot, true);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/app/TaskAssigningApp.java | package ai.timefold.solver.examples.taskassigning.app;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.taskassigning.domain.TaskAssigningSolution;
import ai.timefold.solver.examples.taskassigning.persistence.TaskAssigningSolutionFileIO;
import ai.timefold.solver.examples.taskassigning.swingui.TaskAssigningPanel;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
public class TaskAssigningApp extends CommonApp<TaskAssigningSolution> {
public static final String SOLVER_CONFIG =
"ai/timefold/solver/examples/taskassigning/taskAssigningSolverConfig.xml";
public static final String DATA_DIR_NAME = "taskassigning";
public static void main(String[] args) {
prepareSwingEnvironment();
new TaskAssigningApp().init();
}
public TaskAssigningApp() {
super("Task assigning",
"Assign tasks to employees in a sequence.\n\n"
+ "Match skills and affinity.\n"
+ "Prioritize critical tasks.\n"
+ "Minimize the makespan.",
SOLVER_CONFIG, DATA_DIR_NAME,
TaskAssigningPanel.LOGO_PATH);
}
@Override
protected TaskAssigningPanel createSolutionPanel() {
return new TaskAssigningPanel();
}
@Override
public SolutionFileIO<TaskAssigningSolution> createSolutionFileIO() {
return new TaskAssigningSolutionFileIO();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/Affinity.java | package ai.timefold.solver.examples.taskassigning.domain;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
public enum Affinity implements Labeled {
NONE(4),
LOW(3),
MEDIUM(2),
HIGH(1);
private final int durationMultiplier;
Affinity(int durationMultiplier) {
this.durationMultiplier = durationMultiplier;
}
public int getDurationMultiplier() {
return durationMultiplier;
}
@Override
public String getLabel() {
switch (this) {
case NONE:
return "No affinity";
case LOW:
return "Low affinity";
case MEDIUM:
return "Medium affinity";
case HIGH:
return "High affinity";
default:
throw new IllegalStateException("The affinity (" + this + ") is not implemented.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/Customer.java | package ai.timefold.solver.examples.taskassigning.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Customer extends AbstractPersistable implements Labeled {
private String name;
public Customer() {
}
public Customer(long id) {
super(id);
}
public Customer(long id, String name) {
this(id);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public String getLabel() {
return name;
}
@Override
public String toString() {
return name;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/CustomerKeyDeserializer.java | package ai.timefold.solver.examples.taskassigning.domain;
import ai.timefold.solver.examples.common.persistence.jackson.AbstractKeyDeserializer;
final class CustomerKeyDeserializer extends AbstractKeyDeserializer<Customer> {
public CustomerKeyDeserializer() {
super(Customer.class);
}
@Override
protected Customer createInstance(long id) {
return new Customer(id);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/Employee.java | package ai.timefold.solver.examples.taskassigning.domain;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningListVariable;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.persistence.jackson.KeySerializer;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@PlanningEntity
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Employee extends AbstractPersistable implements Labeled {
private String fullName;
private Set<Skill> skillSet;
private Map<Customer, Affinity> affinityMap;
@PlanningListVariable(allowsUnassignedValues = true)
private List<Task> tasks;
// TODO pinning: https://issues.redhat.com/browse/PLANNER-2633.
public Employee() {
}
public Employee(long id, String fullName) {
super(id);
this.fullName = fullName;
skillSet = new LinkedHashSet<>();
affinityMap = new LinkedHashMap<>();
tasks = new ArrayList<>();
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Set<Skill> getSkillSet() {
return skillSet;
}
public void setSkillSet(Set<Skill> skillSet) {
this.skillSet = skillSet;
}
public Map<Customer, Affinity> getAffinityMap() {
return affinityMap;
}
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = CustomerKeyDeserializer.class)
public void setAffinityMap(Map<Customer, Affinity> affinityMap) {
this.affinityMap = affinityMap;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
// ************************************************************************
// Complex methods
// ************************************************************************
/**
* @param customer never null
* @return never null
*/
@JsonIgnore
public Affinity getAffinity(Customer customer) {
Affinity affinity = affinityMap.get(customer);
if (affinity == null) {
affinity = Affinity.NONE;
}
return affinity;
}
@JsonIgnore
public Integer getEndTime() {
return tasks.isEmpty() ? 0 : tasks.get(tasks.size() - 1).getEndTime();
}
@Override
public String getLabel() {
return fullName;
}
@JsonIgnore
public String getToolText() {
StringBuilder toolText = new StringBuilder();
toolText.append("<html><center><b>").append(fullName).append("</b><br/><br/>");
toolText.append("Skills:<br/>");
for (Skill skill : skillSet) {
toolText.append(skill.getLabel()).append("<br/>");
}
toolText.append("</center></html>");
return toolText.toString();
}
@Override
public String toString() {
return fullName;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/Priority.java | package ai.timefold.solver.examples.taskassigning.domain;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
public enum Priority implements Labeled {
MINOR,
MAJOR,
CRITICAL;
@Override
public String getLabel() {
switch (this) {
case MINOR:
return "Minor priority";
case MAJOR:
return "Major priority";
case CRITICAL:
return "Critical priority";
default:
throw new IllegalStateException("The priority (" + this + ") is not implemented.");
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/Skill.java | package ai.timefold.solver.examples.taskassigning.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Skill extends AbstractPersistable implements Labeled {
private String name;
public Skill() {
}
public Skill(long id, String name) {
super(id);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public String getLabel() {
return name;
}
@Override
public String toString() {
return name;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/Task.java | package ai.timefold.solver.examples.taskassigning.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.InverseRelationShadowVariable;
import ai.timefold.solver.core.api.domain.variable.ShadowVariable;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import ai.timefold.solver.examples.taskassigning.domain.solver.StartTimeUpdatingVariableListener;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
@PlanningEntity
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Task extends AbstractPersistable implements Labeled {
private TaskType taskType;
private int indexInTaskType;
private Customer customer;
private int minStartTime;
private Priority priority;
// Shadow variables
@InverseRelationShadowVariable(sourceVariableName = "tasks")
private Employee employee;
@ShadowVariable(variableListenerClass = StartTimeUpdatingVariableListener.class,
sourceEntityClass = Employee.class, sourceVariableName = "tasks")
private Integer startTime; // In minutes
public Task() {
}
public Task(long id, TaskType taskType, int indexInTaskType, Customer customer, int minStartTime, Priority priority) {
super(id);
this.taskType = taskType;
this.indexInTaskType = indexInTaskType;
this.customer = customer;
this.minStartTime = minStartTime;
this.priority = priority;
}
public TaskType getTaskType() {
return taskType;
}
public void setTaskType(TaskType taskType) {
this.taskType = taskType;
}
public int getIndexInTaskType() {
return indexInTaskType;
}
public void setIndexInTaskType(int indexInTaskType) {
this.indexInTaskType = indexInTaskType;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getMinStartTime() {
return minStartTime;
}
public void setMinStartTime(int minStartTime) {
this.minStartTime = minStartTime;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Integer getStartTime() {
return startTime;
}
public void setStartTime(Integer startTime) {
this.startTime = startTime;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public int getMissingSkillCount() {
if (employee == null) {
return 0;
}
int count = 0;
for (Skill skill : taskType.getRequiredSkillList()) {
if (!employee.getSkillSet().contains(skill)) {
count++;
}
}
return count;
}
/**
* In minutes
*
* @return at least 1 minute
*/
@JsonIgnore
public int getDuration() {
Affinity affinity = getAffinity();
return taskType.getBaseDuration() * affinity.getDurationMultiplier();
}
@JsonIgnore
public Affinity getAffinity() {
return (employee == null) ? Affinity.NONE : employee.getAffinity(customer);
}
@JsonIgnore
public Integer getEndTime() {
if (startTime == null) {
return null;
}
return startTime + getDuration();
}
@JsonIgnore
public String getCode() {
return taskType + "-" + indexInTaskType;
}
@JsonIgnore
public String getTitle() {
return taskType.getTitle();
}
@Override
public String getLabel() {
return getCode() + ": " + taskType.getTitle();
}
@JsonIgnore
public String getToolText() {
StringBuilder toolText = new StringBuilder();
toolText.append("<html><center><b>").append(getLabel()).append("</b><br/>")
.append(priority.getLabel()).append("<br/><br/>");
toolText.append("Required skills:<br/>");
for (Skill skill : taskType.getRequiredSkillList()) {
toolText.append(skill.getLabel()).append("<br/>");
}
toolText.append("<br/>Customer:<br/>").append(customer.getName()).append("<br/>(")
.append(getAffinity().getLabel()).append(")<br/>");
toolText.append("</center></html>");
return toolText.toString();
}
@Override
public String toString() {
return getCode();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/TaskAssigningSolution.java | package ai.timefold.solver.examples.taskassigning.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
@PlanningSolution
public class TaskAssigningSolution extends AbstractPersistable {
@ProblemFactCollectionProperty
private List<Skill> skillList;
@ProblemFactCollectionProperty
private List<TaskType> taskTypeList;
@ProblemFactCollectionProperty
private List<Customer> customerList;
@ValueRangeProvider
@PlanningEntityCollectionProperty
private List<Task> taskList;
@PlanningEntityCollectionProperty
private List<Employee> employeeList;
@PlanningScore(bendableHardLevelsSize = 1, bendableSoftLevelsSize = 5)
private BendableScore score;
/** Relates to {@link Task#getStartTime()}. */
private int frozenCutoff; // In minutes
public TaskAssigningSolution() {
}
public TaskAssigningSolution(long id) {
super(id);
}
public TaskAssigningSolution(long id, List<Skill> skillList, List<TaskType> taskTypeList,
List<Customer> customerList, List<Employee> employeeList, List<Task> taskList) {
this(id);
this.skillList = skillList;
this.taskTypeList = taskTypeList;
this.customerList = customerList;
this.employeeList = employeeList;
this.taskList = taskList;
}
public List<Skill> getSkillList() {
return skillList;
}
public void setSkillList(List<Skill> skillList) {
this.skillList = skillList;
}
public List<TaskType> getTaskTypeList() {
return taskTypeList;
}
public void setTaskTypeList(List<TaskType> taskTypeList) {
this.taskTypeList = taskTypeList;
}
public List<Customer> getCustomerList() {
return customerList;
}
public void setCustomerList(List<Customer> customerList) {
this.customerList = customerList;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public List<Task> getTaskList() {
return taskList;
}
public void setTaskList(List<Task> taskList) {
this.taskList = taskList;
}
public BendableScore getScore() {
return score;
}
public void setScore(BendableScore score) {
this.score = score;
}
public int getFrozenCutoff() {
return frozenCutoff;
}
public void setFrozenCutoff(int frozenCutoff) {
this.frozenCutoff = frozenCutoff;
}
// ************************************************************************
// Complex methods
// ************************************************************************
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/TaskType.java | package ai.timefold.solver.examples.taskassigning.domain;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class TaskType extends AbstractPersistable implements Labeled {
private String code;
private String title;
private int baseDuration; // In minutes
private List<Skill> requiredSkillList;
public TaskType() {
}
public TaskType(long id, String code, String title, int baseDuration) {
super(id);
this.code = code;
this.title = title;
this.baseDuration = baseDuration;
requiredSkillList = new ArrayList<>();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getBaseDuration() {
return baseDuration;
}
public void setBaseDuration(int baseDuration) {
this.baseDuration = baseDuration;
}
public List<Skill> getRequiredSkillList() {
return requiredSkillList;
}
public void setRequiredSkillList(List<Skill> requiredSkillList) {
this.requiredSkillList = requiredSkillList;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@Override
public String getLabel() {
return title;
}
@Override
public String toString() {
return code;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/solver/StartTimeUpdatingVariableListener.java | package ai.timefold.solver.examples.taskassigning.domain.solver;
import java.util.List;
import java.util.Objects;
import ai.timefold.solver.core.api.domain.variable.ListVariableListener;
import ai.timefold.solver.core.api.score.director.ScoreDirector;
import ai.timefold.solver.examples.taskassigning.domain.Employee;
import ai.timefold.solver.examples.taskassigning.domain.Task;
import ai.timefold.solver.examples.taskassigning.domain.TaskAssigningSolution;
public class StartTimeUpdatingVariableListener implements ListVariableListener<TaskAssigningSolution, Employee, Task> {
@Override
public void beforeEntityAdded(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support adding employees.");
}
@Override
public void afterEntityAdded(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support adding employees.");
}
@Override
public void beforeEntityRemoved(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support removing employees.");
}
@Override
public void afterEntityRemoved(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee) {
throw new UnsupportedOperationException("This example does not support removing employees.");
}
@Override
public void afterListVariableElementUnassigned(ScoreDirector<TaskAssigningSolution> scoreDirector, Task task) {
scoreDirector.beforeVariableChanged(task, "startTime");
task.setStartTime(null);
scoreDirector.afterVariableChanged(task, "startTime");
}
@Override
public void beforeListVariableChanged(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee, int startIndex,
int endIndex) {
// Do nothing
}
@Override
public void afterListVariableChanged(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee, int startIndex,
int endIndex) {
updateStartTime(scoreDirector, employee, startIndex);
}
protected void updateStartTime(ScoreDirector<TaskAssigningSolution> scoreDirector, Employee employee, int index) {
List<Task> tasks = employee.getTasks();
Integer previousEndTime = index == 0 ? Integer.valueOf(0) : tasks.get(index - 1).getEndTime();
for (int i = index; i < tasks.size(); i++) {
Task t = tasks.get(i);
Integer startTime = calculateStartTime(t, previousEndTime);
if (!Objects.equals(t.getStartTime(), startTime)) {
scoreDirector.beforeVariableChanged(t, "startTime");
t.setStartTime(startTime);
scoreDirector.afterVariableChanged(t, "startTime");
}
previousEndTime = t.getEndTime();
}
}
private Integer calculateStartTime(Task task, Integer previousEndTime) {
if (previousEndTime == null) {
return null;
}
return Math.max(task.getMinStartTime(), previousEndTime);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/domain/solver/TaskDifficultyComparator.java | package ai.timefold.solver.examples.taskassigning.domain.solver;
import java.util.Comparator;
import ai.timefold.solver.examples.taskassigning.domain.Task;
/**
* Compares tasks by difficulty.
*/
public class TaskDifficultyComparator implements Comparator<Task> {
// FIXME This class is currently unused until the @PlanningListVariable(comparator = ???) API is stable.
// See https://issues.redhat.com/browse/PLANNER-2542.
static final Comparator<Task> INCREASING_DIFFICULTY_COMPARATOR = Comparator.comparing(Task::getPriority)
.thenComparingInt(task -> task.getTaskType().getRequiredSkillList().size())
.thenComparingInt(task -> task.getTaskType().getBaseDuration())
.thenComparingLong(Task::getId);
static final Comparator<Task> DECREASING_DIFFICULTY_COMPARATOR = INCREASING_DIFFICULTY_COMPARATOR.reversed();
@Override
public int compare(Task a, Task b) {
return DECREASING_DIFFICULTY_COMPARATOR.compare(a, b);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/optional/benchmark/TaskAssigningBenchmarkApp.java | package ai.timefold.solver.examples.taskassigning.optional.benchmark;
import ai.timefold.solver.examples.common.app.CommonBenchmarkApp;
public class TaskAssigningBenchmarkApp extends CommonBenchmarkApp {
public static void main(String[] args) {
new TaskAssigningBenchmarkApp().buildAndBenchmark(args);
}
public TaskAssigningBenchmarkApp() {
super(
new ArgOption("default",
"ai/timefold/solver/examples/taskassigning/optional/benchmark/taskAssigningBenchmarkConfig.xml"),
new ArgOption("scoreDirector",
"ai/timefold/solver/examples/taskassigning/optional/benchmark/taskAssigningScoreDirectorBenchmarkConfig.xml"));
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/persistence/TaskAssigningGenerator.java | package ai.timefold.solver.examples.taskassigning.persistence;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.app.LoggingMain;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.examples.common.persistence.generator.StringDataGenerator;
import ai.timefold.solver.examples.taskassigning.app.TaskAssigningApp;
import ai.timefold.solver.examples.taskassigning.domain.Affinity;
import ai.timefold.solver.examples.taskassigning.domain.Customer;
import ai.timefold.solver.examples.taskassigning.domain.Employee;
import ai.timefold.solver.examples.taskassigning.domain.Priority;
import ai.timefold.solver.examples.taskassigning.domain.Skill;
import ai.timefold.solver.examples.taskassigning.domain.Task;
import ai.timefold.solver.examples.taskassigning.domain.TaskAssigningSolution;
import ai.timefold.solver.examples.taskassigning.domain.TaskType;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
public class TaskAssigningGenerator extends LoggingMain {
public static final int BASE_DURATION_MINIMUM = 30;
public static final int BASE_DURATION_MAXIMUM = 90;
public static final int BASE_DURATION_AVERAGE = BASE_DURATION_MINIMUM + BASE_DURATION_MAXIMUM / 2;
private static final int SKILL_SET_SIZE_MINIMUM = 2;
private static final int SKILL_SET_SIZE_MAXIMUM = 4;
public static void main(String[] args) {
TaskAssigningGenerator generator = new TaskAssigningGenerator();
generator.writeTaskAssigningSolution(24, 8);
generator.writeTaskAssigningSolution(50, 5);
generator.writeTaskAssigningSolution(100, 5);
generator.writeTaskAssigningSolution(500, 20);
// For more tasks, switch to BendableLongScore to avoid overflow in the score.
}
private final StringDataGenerator skillNameGenerator = new StringDataGenerator()
.addPart(true, 0,
"Problem",
"Team",
"Business",
"Risk",
"Creative",
"Strategic",
"Customer",
"Conflict",
"IT",
"Academic")
.addPart(true, 1,
"Solving",
"Building",
"Storytelling",
"Management",
"Thinking",
"Planning",
"Service",
"Resolution",
"Engineering",
"Research");
private final StringDataGenerator taskTypeNameGenerator = new StringDataGenerator()
.addPart(true, 0,
"Improve",
"Expand",
"Shrink",
"Approve",
"Localize",
"Review",
"Clean",
"Merge",
"Double",
"Optimize")
.addPart(true, 1,
"Sales",
"Tax",
"VAT",
"Legal",
"Cloud",
"Marketing",
"IT",
"Contract",
"Financial",
"Advertisement")
.addPart(false, 2,
"Software",
"Development",
"Accounting",
"Management",
"Facilities",
"Writing",
"Productization",
"Lobbying",
"Engineering",
"Research");
private final StringDataGenerator customerNameGenerator = StringDataGenerator.buildCompanyNames();
private final StringDataGenerator employeeNameGenerator = StringDataGenerator.buildFullNames();
protected final SolutionFileIO<TaskAssigningSolution> solutionFileIO;
protected final File outputDir;
protected Random random;
public TaskAssigningGenerator() {
solutionFileIO = new TaskAssigningSolutionFileIO();
outputDir = new File(CommonApp.determineDataDir(TaskAssigningApp.DATA_DIR_NAME), "unsolved");
}
private void writeTaskAssigningSolution(int taskListSize, int employeeListSize) {
int skillListSize = SKILL_SET_SIZE_MAXIMUM + (int) Math.log(employeeListSize);
int taskTypeListSize = taskListSize / 5;
int customerListSize = Math.min(taskTypeListSize, employeeListSize * 3);
String fileName = determineFileName(taskListSize, employeeListSize);
File outputFile = new File(outputDir, fileName + ".json");
TaskAssigningSolution solution = createTaskAssigningSolution(fileName,
taskListSize, skillListSize, employeeListSize, taskTypeListSize, customerListSize);
solutionFileIO.write(solution, outputFile);
logger.info("Saved: {}", outputFile);
}
private String determineFileName(int taskListSize, int employeeListSize) {
return taskListSize + "tasks-" + employeeListSize + "employees";
}
public TaskAssigningSolution createTaskAssigningSolution(String fileName, int taskListSize, int skillListSize,
int employeeListSize, int taskTypeListSize, int customerListSize) {
random = new Random(37);
TaskAssigningSolution solution = new TaskAssigningSolution(0L);
createSkillList(solution, skillListSize);
createCustomerList(solution, customerListSize);
createEmployeeList(solution, employeeListSize);
createTaskTypeList(solution, taskTypeListSize);
createTaskList(solution, taskListSize);
solution.setFrozenCutoff(0);
BigInteger a = AbstractSolutionImporter.factorial(taskListSize + employeeListSize - 1);
BigInteger b = AbstractSolutionImporter.factorial(employeeListSize - 1);
BigInteger possibleSolutionSize = (a == null || b == null) ? null : a.divide(b);
logger.info(
"TaskAssigningSolution {} has {} tasks, {} skills, {} employees, {} task types and {} customers with a search space of {}.",
fileName,
taskListSize,
skillListSize,
employeeListSize,
taskTypeListSize,
customerListSize,
AbstractSolutionImporter.getFlooredPossibleSolutionSize(possibleSolutionSize));
return solution;
}
private void createSkillList(TaskAssigningSolution solution, int skillListSize) {
List<Skill> skillList = new ArrayList<>(skillListSize);
skillNameGenerator.predictMaximumSizeAndReset(skillListSize);
for (int i = 0; i < skillListSize; i++) {
String skillName = skillNameGenerator.generateNextValue();
Skill skill = new Skill(i, skillName);
logger.trace("Created skill with skillName ({}).", skillName);
skillList.add(skill);
}
solution.setSkillList(skillList);
}
private void createCustomerList(TaskAssigningSolution solution, int customerListSize) {
List<Customer> customerList = new ArrayList<>(customerListSize);
customerNameGenerator.predictMaximumSizeAndReset(customerListSize);
for (int i = 0; i < customerListSize; i++) {
String customerName = customerNameGenerator.generateNextValue();
Customer customer = new Customer(i, customerName);
logger.trace("Created skill with customerName ({}).", customerName);
customerList.add(customer);
}
solution.setCustomerList(customerList);
}
private void createEmployeeList(TaskAssigningSolution solution, int employeeListSize) {
List<Skill> skillList = solution.getSkillList();
List<Customer> customerList = solution.getCustomerList();
Affinity[] affinities = Affinity.values();
List<Employee> employeeList = new ArrayList<>(employeeListSize);
int skillListIndex = 0;
employeeNameGenerator.predictMaximumSizeAndReset(employeeListSize);
for (int i = 0; i < employeeListSize; i++) {
String fullName = employeeNameGenerator.generateNextValue();
Employee employee = new Employee(i, fullName);
int skillSetSize = SKILL_SET_SIZE_MINIMUM + random.nextInt(SKILL_SET_SIZE_MAXIMUM - SKILL_SET_SIZE_MINIMUM);
if (skillSetSize > skillList.size()) {
skillSetSize = skillList.size();
}
Set<Skill> skillSet = new LinkedHashSet<>(skillSetSize);
for (int j = 0; j < skillSetSize; j++) {
skillSet.add(skillList.get(skillListIndex));
skillListIndex = (skillListIndex + 1) % skillList.size();
}
employee.setSkillSet(skillSet);
Map<Customer, Affinity> affinityMap = new LinkedHashMap<>(customerList.size());
for (Customer customer : customerList) {
affinityMap.put(customer, affinities[random.nextInt(affinities.length)]);
}
employee.setAffinityMap(affinityMap);
employee.setTasks(new ArrayList<>());
logger.trace("Created employee with fullName ({}).", fullName);
employeeList.add(employee);
}
solution.setEmployeeList(employeeList);
}
private void createTaskTypeList(TaskAssigningSolution solution, int taskTypeListSize) {
List<Employee> employeeList = solution.getEmployeeList();
List<TaskType> taskTypeList = new ArrayList<>(taskTypeListSize);
Set<String> codeSet = new LinkedHashSet<>(taskTypeListSize);
taskTypeNameGenerator.predictMaximumSizeAndReset(taskTypeListSize);
for (int i = 0; i < taskTypeListSize; i++) {
String title = taskTypeNameGenerator.generateNextValue();
String code;
switch (title.replaceAll("[^ ]", "").length() + 1) {
case 3:
code = title.replaceAll("(\\w)\\w* (\\w)\\w* (\\w)\\w*", "$1$2$3");
break;
case 2:
code = title.replaceAll("(\\w)\\w* (\\w)\\w*", "$1$2");
break;
case 1:
code = title.replaceAll("(\\w)\\w*", "$1");
break;
default:
throw new IllegalStateException("Cannot convert title (" + title + ") into a code.");
}
if (codeSet.contains(code)) {
int codeSuffixNumber = 1;
while (codeSet.contains(code + codeSuffixNumber)) {
codeSuffixNumber++;
}
code = code + codeSuffixNumber;
}
codeSet.add(code);
TaskType taskType = new TaskType(i, title, code,
BASE_DURATION_MINIMUM + random.nextInt(BASE_DURATION_MAXIMUM - BASE_DURATION_MINIMUM));
Employee randomEmployee = employeeList.get(random.nextInt(employeeList.size()));
ArrayList<Skill> randomSkillList = new ArrayList<>(randomEmployee.getSkillSet());
Collections.shuffle(randomSkillList, random);
int requiredSkillListSize = 1 + random.nextInt(randomSkillList.size() - 1);
taskType.setRequiredSkillList(new ArrayList<>(randomSkillList.subList(0, requiredSkillListSize)));
logger.trace("Created taskType with title ({}).", title);
taskTypeList.add(taskType);
}
solution.setTaskTypeList(taskTypeList);
}
private void createTaskList(TaskAssigningSolution solution, int taskListSize) {
List<TaskType> taskTypeList = solution.getTaskTypeList();
List<Customer> customerList = solution.getCustomerList();
Priority[] priorities = Priority.values();
List<Task> taskList = new ArrayList<>(taskListSize);
Map<TaskType, Integer> maxIndexInTaskTypeMap = new LinkedHashMap<>(taskTypeList.size());
for (int i = 0; i < taskListSize; i++) {
TaskType taskType = taskTypeList.get(random.nextInt(taskTypeList.size()));
Integer indexInTaskType = maxIndexInTaskTypeMap.get(taskType);
if (indexInTaskType == null) {
indexInTaskType = 1;
} else {
indexInTaskType++;
}
maxIndexInTaskTypeMap.put(taskType, indexInTaskType);
Task task = new Task(i, taskType, indexInTaskType, customerList.get(random.nextInt(customerList.size())), 0,
priorities[random.nextInt(priorities.length)]);
taskList.add(task);
}
solution.setTaskList(taskList);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/persistence/TaskAssigningSolutionFileIO.java | package ai.timefold.solver.examples.taskassigning.persistence;
import java.io.File;
import java.util.function.Function;
import java.util.stream.Collectors;
import ai.timefold.solver.examples.common.persistence.AbstractJsonSolutionFileIO;
import ai.timefold.solver.examples.taskassigning.domain.Customer;
import ai.timefold.solver.examples.taskassigning.domain.Employee;
import ai.timefold.solver.examples.taskassigning.domain.TaskAssigningSolution;
public class TaskAssigningSolutionFileIO extends AbstractJsonSolutionFileIO<TaskAssigningSolution> {
public TaskAssigningSolutionFileIO() {
super(TaskAssigningSolution.class);
}
@Override
public TaskAssigningSolution read(File inputSolutionFile) {
TaskAssigningSolution taskAssigningSolution = super.read(inputSolutionFile);
var customersById = taskAssigningSolution.getCustomerList().stream()
.collect(Collectors.toMap(Customer::getId, Function.identity()));
/*
* Replace the duplicate customer instances in the affinityMap by references to instances from
* the customerList.
*/
for (Employee employee : taskAssigningSolution.getEmployeeList()) {
var newTravelDistanceMap = deduplicateMap(employee.getAffinityMap(),
customersById, Customer::getId);
employee.setAffinityMap(newTravelDistanceMap);
}
return taskAssigningSolution;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/score/TaskAssigningConstraintProvider.java | package ai.timefold.solver.examples.taskassigning.score;
import ai.timefold.solver.core.api.score.buildin.bendable.BendableScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.uni.UniConstraintStream;
import ai.timefold.solver.examples.taskassigning.domain.Employee;
import ai.timefold.solver.examples.taskassigning.domain.Priority;
import ai.timefold.solver.examples.taskassigning.domain.Task;
public class TaskAssigningConstraintProvider implements ConstraintProvider {
private static final int BENDABLE_SCORE_HARD_LEVELS_SIZE = 1;
private static final int BENDABLE_SCORE_SOFT_LEVELS_SIZE = 5;
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
noMissingSkills(constraintFactory),
minimizeUnassignedTasks(constraintFactory),
minimizeMakespan(constraintFactory),
/*
* TODO potential for performance improvements through API enhancements,
* see https://issues.redhat.com/browse/PLANNER-1604.
*/
criticalPriorityBasedTaskEndTime(constraintFactory),
majorPriorityTaskEndTime(constraintFactory),
minorPriorityTaskEndTime(constraintFactory)
};
}
private Constraint noMissingSkills(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Task.class)
.filter(task -> task.getMissingSkillCount() > 0)
.penalize(BendableScore.ofHard(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 0, 1),
Task::getMissingSkillCount)
.asConstraint("No missing skills");
}
private Constraint minimizeUnassignedTasks(ConstraintFactory constraintFactory) {
return constraintFactory.forEachIncludingUnassigned(Task.class)
.filter(task -> task.getEmployee() == null)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 0, 1))
.asConstraint("Minimize unassigned tasks");
}
private Constraint criticalPriorityBasedTaskEndTime(ConstraintFactory constraintFactory) {
return getTaskWithPriority(constraintFactory, Priority.CRITICAL)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 1, 1),
Task::getEndTime)
.asConstraint("Critical priority task end time");
}
private UniConstraintStream<Task> getTaskWithPriority(ConstraintFactory constraintFactory, Priority priority) {
return constraintFactory.forEach(Task.class)
.filter(task -> task.getEmployee() != null && task.getPriority() == priority);
}
private Constraint minimizeMakespan(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Employee.class)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 2, 1),
employee -> employee.getEndTime() * employee.getEndTime())
.asConstraint("Minimize makespan, latest ending employee first");
}
private Constraint majorPriorityTaskEndTime(ConstraintFactory constraintFactory) {
return getTaskWithPriority(constraintFactory, Priority.MAJOR)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 3, 1),
Task::getEndTime)
.asConstraint("Major priority task end time");
}
private Constraint minorPriorityTaskEndTime(ConstraintFactory constraintFactory) {
return getTaskWithPriority(constraintFactory, Priority.MINOR)
.penalize(BendableScore.ofSoft(BENDABLE_SCORE_HARD_LEVELS_SIZE, BENDABLE_SCORE_SOFT_LEVELS_SIZE, 4, 1),
Task::getEndTime)
.asConstraint("Minor priority task end time");
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/swingui/TaskAssigningPanel.java | package ai.timefold.solver.examples.taskassigning.swingui;
import static ai.timefold.solver.examples.taskassigning.persistence.TaskAssigningGenerator.BASE_DURATION_AVERAGE;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.Timer;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
import ai.timefold.solver.examples.taskassigning.domain.Customer;
import ai.timefold.solver.examples.taskassigning.domain.Priority;
import ai.timefold.solver.examples.taskassigning.domain.Task;
import ai.timefold.solver.examples.taskassigning.domain.TaskAssigningSolution;
import ai.timefold.solver.examples.taskassigning.domain.TaskType;
public class TaskAssigningPanel extends SolutionPanel<TaskAssigningSolution> {
public static final String LOGO_PATH = "/ai/timefold/solver/examples/taskassigning/swingui/taskAssigningLogo.png";
private final TaskOverviewPanel taskOverviewPanel;
private JSpinner consumeRateField;
private AbstractAction consumeAction;
private Timer consumeTimer;
private JSpinner produceRateField;
private AbstractAction produceAction;
private Timer produceTimer;
private int consumedTimeInSeconds = 0;
private int previousConsumedTime = 0; // In minutes
private int producedTimeInSeconds = 0;
private int previousProducedTime = 0; // In minutes
private volatile Random producingRandom;
public TaskAssigningPanel() {
setLayout(new BorderLayout());
JPanel headerPanel = createHeaderPanel();
add(headerPanel, BorderLayout.NORTH);
taskOverviewPanel = new TaskOverviewPanel(this);
add(new JScrollPane(taskOverviewPanel), BorderLayout.CENTER);
}
private JPanel createHeaderPanel() {
JPanel headerPanel = new JPanel(new GridLayout(1, 0));
JPanel consumePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
consumePanel.add(new JLabel("Consume rate:"));
consumeRateField = new JSpinner(new SpinnerNumberModel(600, 10, 3600, 10));
consumePanel.add(consumeRateField);
consumeTimer = new Timer(1000, e -> {
consumedTimeInSeconds += (Integer) consumeRateField.getValue();
consumeUpTo(consumedTimeInSeconds / 60);
repaint();
});
consumeAction = new AbstractAction("Consume") {
@Override
public void actionPerformed(ActionEvent e) {
if (!consumeTimer.isRunning()) {
consumeRateField.setEnabled(false);
consumeTimer.start();
} else {
consumeRateField.setEnabled(true);
consumeTimer.stop();
}
}
};
consumePanel.add(new JToggleButton(consumeAction));
// FIXME remove this when https://issues.redhat.com/browse/PLANNER-2633 is done.
Arrays.stream(consumePanel.getComponents()).forEach(component -> {
component.setEnabled(false);
if (component instanceof JComponent jComponent) {
jComponent.setToolTipText("This feature is currently disabled.");
}
});
headerPanel.add(consumePanel);
JPanel producePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
producePanel.add(new JLabel("Produce rate:"));
produceRateField = new JSpinner(new SpinnerNumberModel(600, 10, 3600, 10));
producePanel.add(produceRateField);
produceTimer = new Timer(1000, e -> {
producedTimeInSeconds += (Integer) produceRateField.getValue();
produceUpTo(producedTimeInSeconds / 60);
repaint();
});
produceAction = new AbstractAction("Produce") {
@Override
public void actionPerformed(ActionEvent e) {
if (!produceTimer.isRunning()) {
produceRateField.setEnabled(false);
produceTimer.start();
} else {
produceRateField.setEnabled(true);
produceTimer.stop();
}
}
};
producePanel.add(new JToggleButton(produceAction));
headerPanel.add(producePanel);
return headerPanel;
}
/**
* @param consumedTime in minutes, just like {@link Task#getStartTime()}
*/
public void consumeUpTo(final int consumedTime) {
taskOverviewPanel.setConsumedDuration(consumedTime);
if (consumedTime <= previousConsumedTime) {
// Occurs due to rounding down of consumedTimeInSeconds
return;
}
logger.debug("Scheduling consumption of all tasks up to {} minutes.", consumedTime);
previousConsumedTime = consumedTime;
doProblemChange((taskAssigningSolution, problemChangeDirector) -> {
taskAssigningSolution.setFrozenCutoff(consumedTime);
// TODO update list variable pins: https://issues.redhat.com/browse/PLANNER-2633.
});
}
/**
* @param producedTime in minutes, just like {@link Task#getStartTime()}
*/
public void produceUpTo(final int producedTime) {
if (producedTime <= previousProducedTime) {
// Occurs due to rounding down of producedDurationInSeconds
return;
}
final int baseDurationBudgetPerEmployee = (producedTime - previousProducedTime);
final int newTaskCount = getSolution().getEmployeeList().size() * baseDurationBudgetPerEmployee / BASE_DURATION_AVERAGE;
if (newTaskCount <= 0) {
// Do not change previousProducedDuration
return;
}
logger.debug("Scheduling production of {} new tasks.", newTaskCount);
previousProducedTime = producedTime;
final int minStartTime = previousConsumedTime;
doProblemChange((taskAssigningSolution, problemChangeDirector) -> {
List<TaskType> taskTypeList = taskAssigningSolution.getTaskTypeList();
List<Customer> customerList = taskAssigningSolution.getCustomerList();
Priority[] priorities = Priority.values();
List<Task> taskList = taskAssigningSolution.getTaskList();
for (int i = 0; i < newTaskCount; i++) {
TaskType taskType = taskTypeList.get(producingRandom.nextInt(taskTypeList.size()));
long nextTaskId = 0L;
int nextIndexInTaskType = 0;
for (Task other : taskList) {
if (nextTaskId <= other.getId()) {
nextTaskId = other.getId() + 1L;
}
if (taskType == other.getTaskType()) {
if (nextIndexInTaskType <= other.getIndexInTaskType()) {
nextIndexInTaskType = other.getIndexInTaskType() + 1;
}
}
}
// Prevent the new task from being assigned retroactively
Task task = new Task(nextTaskId, taskType, nextIndexInTaskType,
customerList.get(producingRandom.nextInt(customerList.size())), minStartTime,
priorities[producingRandom.nextInt(priorities.length)]);
problemChangeDirector.addEntity(task, taskList::add);
}
});
}
@Override
public boolean isWrapInScrollPane() {
return false;
}
@Override
public void resetPanel(TaskAssigningSolution solution) {
consumedTimeInSeconds = solution.getFrozenCutoff() * 60;
previousConsumedTime = solution.getFrozenCutoff();
producedTimeInSeconds = 0;
previousProducedTime = 0;
producingRandom = new Random(0); // Random is thread safe
taskOverviewPanel.resetPanel(solution);
taskOverviewPanel.setConsumedDuration(consumedTimeInSeconds / 60);
}
@Override
public void updatePanel(TaskAssigningSolution taskAssigningSolution) {
taskOverviewPanel.resetPanel(taskAssigningSolution);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/taskassigning/swingui/TaskOverviewPanel.java | package ai.timefold.solver.examples.taskassigning.swingui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.Scrollable;
import javax.swing.SwingConstants;
import ai.timefold.solver.examples.common.business.SolutionBusiness;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
import ai.timefold.solver.examples.common.swingui.components.LabeledComboBoxRenderer;
import ai.timefold.solver.examples.taskassigning.domain.Employee;
import ai.timefold.solver.examples.taskassigning.domain.Skill;
import ai.timefold.solver.examples.taskassigning.domain.Task;
import ai.timefold.solver.examples.taskassigning.domain.TaskAssigningSolution;
import ai.timefold.solver.swing.impl.SwingUtils;
import ai.timefold.solver.swing.impl.TangoColorFactory;
public class TaskOverviewPanel extends JPanel implements Scrollable {
public static final int HEADER_ROW_HEIGHT = 50;
public static final int HEADER_COLUMN_WIDTH = 150;
public static final int ROW_HEIGHT = 50;
public static final int TIME_COLUMN_WIDTH = 60;
private final TaskAssigningPanel taskAssigningPanel;
private final ImageIcon[] affinityIcons;
private final ImageIcon[] priorityIcons;
private TangoColorFactory skillColorFactory;
private int consumedDuration = 0;
public TaskOverviewPanel(TaskAssigningPanel taskAssigningPanel) {
this.taskAssigningPanel = taskAssigningPanel;
affinityIcons = new ImageIcon[] {
new ImageIcon(getClass().getResource("affinityNone.png")),
new ImageIcon(getClass().getResource("affinityLow.png")),
new ImageIcon(getClass().getResource("affinityMedium.png")),
new ImageIcon(getClass().getResource("affinityHigh.png"))
};
priorityIcons = new ImageIcon[] {
new ImageIcon(getClass().getResource("priorityMinor.png")),
new ImageIcon(getClass().getResource("priorityMajor.png")),
new ImageIcon(getClass().getResource("priorityCritical.png"))
};
setLayout(null);
setMinimumSize(new Dimension(HEADER_COLUMN_WIDTH * 2, ROW_HEIGHT * 8));
}
public void resetPanel(TaskAssigningSolution taskAssigningSolution) {
removeAll();
skillColorFactory = new TangoColorFactory();
List<Employee> employeeList = taskAssigningSolution.getEmployeeList();
List<Task> unassignedTaskList = new ArrayList<>(taskAssigningSolution.getTaskList());
int rowIndex = 0;
for (Employee employee : employeeList) {
add(createEmployeeLabel(employee, rowIndex));
rowIndex++;
}
rowIndex = 0;
for (Employee employee : employeeList) {
for (Task task : employee.getTasks()) {
add(createTaskButton(task, rowIndex));
unassignedTaskList.remove(task);
}
rowIndex++;
}
for (Task task : unassignedTaskList) {
add(createTaskButton(task, rowIndex));
rowIndex++;
}
int maxUnassignedTaskDuration = unassignedTaskList.stream().mapToInt(Task::getDuration).max().orElse(0);
int maxEmployeeEndTime = employeeList.stream().mapToInt(Employee::getEndTime).max().orElse(0);
int taskTableWidth = Math.max(maxEmployeeEndTime, maxUnassignedTaskDuration + consumedDuration);
for (int timeGrain = 0; timeGrain < taskTableWidth; timeGrain += TIME_COLUMN_WIDTH) {
add(createTimeLabel(timeGrain));
}
if (taskTableWidth % TIME_COLUMN_WIDTH != 0) {
taskTableWidth += TIME_COLUMN_WIDTH - (taskTableWidth % TIME_COLUMN_WIDTH);
}
Dimension size = new Dimension(taskTableWidth + HEADER_COLUMN_WIDTH, HEADER_ROW_HEIGHT + rowIndex * ROW_HEIGHT);
setSize(size);
setPreferredSize(size);
repaint();
}
public void setConsumedDuration(int consumedDuration) {
this.consumedDuration = consumedDuration;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(TangoColorFactory.ALUMINIUM_2);
int lineX = HEADER_COLUMN_WIDTH + consumedDuration;
g.fillRect(HEADER_COLUMN_WIDTH, 0, lineX, getHeight());
g.setColor(Color.WHITE);
g.fillRect(lineX, 0, getWidth(), getHeight());
}
private JLabel createEmployeeLabel(Employee employee, int rowIndex) {
JLabel employeeLabel = new JLabel(employee.getLabel(), new TaskOrEmployeeIcon(employee), SwingConstants.LEFT);
employeeLabel.setOpaque(true);
employeeLabel.setToolTipText(employee.getToolText());
employeeLabel.setLocation(0, HEADER_ROW_HEIGHT + rowIndex * ROW_HEIGHT);
employeeLabel.setSize(HEADER_COLUMN_WIDTH, ROW_HEIGHT);
employeeLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
return employeeLabel;
}
private JButton createTaskButton(Task task, int rowIndex) {
JButton taskButton = SwingUtils.makeSmallButton(new JButton(new TaskAction(task)));
taskButton.setBackground(TangoColorFactory.ALUMINIUM_1);
taskButton.setHorizontalTextPosition(SwingConstants.CENTER);
taskButton.setVerticalTextPosition(SwingConstants.TOP);
taskButton.setSize(task.getDuration(), ROW_HEIGHT);
int x = HEADER_COLUMN_WIDTH + (task.getEmployee() == null ? task.getMinStartTime() : task.getStartTime());
int y = HEADER_ROW_HEIGHT + rowIndex * ROW_HEIGHT;
taskButton.setLocation(x, y);
return taskButton;
}
private JLabel createTimeLabel(int timeGrain) {
// Use 10 hours per day
int minutesInDay = timeGrain % (10 * 60);
// Start at 8:00
int hours = 8 + (minutesInDay / 60);
int minutesInHour = minutesInDay % 60;
JLabel timeLabel = new JLabel(String.format("%02d:%02d", hours, minutesInHour));
timeLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
timeLabel.setLocation(timeGrain + HEADER_COLUMN_WIDTH, 0);
timeLabel.setSize(TIME_COLUMN_WIDTH, ROW_HEIGHT);
return timeLabel;
}
private class TaskAction extends AbstractAction {
private final Task task;
public TaskAction(Task task) {
super(task.getCode(), new TaskOrEmployeeIcon(task));
this.task = task;
// Tooltip
putValue(SHORT_DESCRIPTION, task.getToolText());
}
@Override
public void actionPerformed(ActionEvent e) {
JComboBox<Integer> indexListField = new JComboBox<>();
JComboBox<Employee> employeeListField = new JComboBox<>(
new Vector<>(taskAssigningPanel.getSolution().getEmployeeList()));
employeeListField.addItemListener(itemEvent -> {
if (itemEvent.getStateChange() == ItemEvent.SELECTED) {
// When en employee is selected, populate the index combo with indexes in the selected employee's task list.
indexListField.setModel(new DefaultComboBoxModel<>(availableIndexes((Employee) itemEvent.getItem())));
}
});
LabeledComboBoxRenderer.applyToComboBox(employeeListField);
selectCurrentEmployee(employeeListField);
JCheckBox unassignCheckBox = new JCheckBox("Or unassign.");
unassignCheckBox.addActionListener(checkBoxEvent -> {
employeeListField.setEnabled(!unassignCheckBox.isSelected());
indexListField.setEnabled(!unassignCheckBox.isSelected());
});
unassignCheckBox.setVisible(task.getEmployee() != null);
JPanel listFieldsPanel = new JPanel(new GridLayout(4, 1));
listFieldsPanel.add(new JLabel("Select employee and index:"));
listFieldsPanel.add(employeeListField);
listFieldsPanel.add(indexListField);
listFieldsPanel.add(unassignCheckBox);
int result = JOptionPane.showConfirmDialog(TaskOverviewPanel.this.getRootPane(),
listFieldsPanel, "Move " + task.getCode(),
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
Employee selectedEmployee = (Employee) employeeListField.getSelectedItem();
Integer selectedIndex = (Integer) indexListField.getSelectedItem();
doProblemChange(selectedEmployee, selectedIndex, unassignCheckBox.isSelected());
taskAssigningPanel.getSolverAndPersistenceFrame().resetScreen();
}
}
private Vector<Integer> availableIndexes(Employee selectedEmployee) {
int availableIndexes = selectedEmployee.getTasks().size();
if (selectedEmployee == task.getEmployee()) {
availableIndexes--;
}
return IntStream.rangeClosed(0, availableIndexes)
.boxed()
.collect(Collectors.toCollection(Vector::new));
}
private void selectCurrentEmployee(JComboBox<Employee> employeeListField) {
// Without selecting null first, the next select wouldn't call the item listener if the selected employee
// is the first on the list (and the index combo wouldn't be populated).
employeeListField.setSelectedItem(null);
if (task.getEmployee() == null) {
employeeListField.setSelectedIndex(0);
} else {
employeeListField.setSelectedItem(task.getEmployee());
}
}
private void doProblemChange(Employee selectedEmployee, Integer selectedIndex, boolean unassignTask) {
SolutionBusiness<TaskAssigningSolution, ?> solutionBusiness = taskAssigningPanel.getSolutionBusiness();
if (unassignTask) {
solutionBusiness.doProblemChange(
(workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(selectedEmployee,
"tasks",
e -> e.getTasks().remove((int) selectedIndex)));
} else {
if (task.getEmployee() == null) {
solutionBusiness.doProblemChange(
(workingSolution, problemChangeDirector) -> problemChangeDirector.changeVariable(selectedEmployee,
"tasks",
e -> e.getTasks().add(selectedIndex, task)));
} else {
solutionBusiness.doProblemChange((workingSolution, problemChangeDirector) -> {
Task workingTask = problemChangeDirector.lookUpWorkingObjectOrFail(task);
problemChangeDirector.changeVariable(task.getEmployee(), "tasks",
e -> e.getTasks().remove(workingTask));
problemChangeDirector.changeVariable(selectedEmployee, "tasks",
e -> e.getTasks().add(selectedIndex, workingTask));
});
}
}
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
return SolutionPanel.PREFERRED_SCROLLABLE_VIEWPORT_SIZE;
}
@Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
@Override
public boolean getScrollableTracksViewportWidth() {
if (getParent() instanceof JViewport) {
return (getParent().getWidth() > getPreferredSize().width);
}
return false;
}
@Override
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
return (getParent().getHeight() > getPreferredSize().height);
}
return false;
}
private class TaskOrEmployeeIcon implements Icon {
private static final int SKILL_ICON_WIDTH = 8;
private static final int SKILL_ICON_HEIGHT = 16;
private final ImageIcon priorityIcon;
private final List<Color> skillColorList;
private final ImageIcon affinityIcon;
private TaskOrEmployeeIcon(Task task) {
priorityIcon = priorityIcons[task.getPriority().ordinal()];
skillColorList = task.getTaskType().getRequiredSkillList().stream()
.map(skillColorFactory::pickColor)
.collect(Collectors.toList());
affinityIcon = affinityIcons[task.getAffinity().ordinal()];
}
private TaskOrEmployeeIcon(Employee employee) {
priorityIcon = null;
skillColorList = employee.getSkillSet().stream()
.sorted(Comparator.comparing(Skill::getName))
.map(skillColorFactory::pickColor)
.collect(Collectors.toList());
affinityIcon = null;
}
@Override
public int getIconWidth() {
int width = 0;
if (priorityIcon != null) {
width += priorityIcon.getIconWidth();
}
width += skillColorList.size() * SKILL_ICON_WIDTH;
if (affinityIcon != null) {
width += affinityIcon.getIconWidth();
}
return width;
}
@Override
public int getIconHeight() {
int height = SKILL_ICON_HEIGHT;
if (priorityIcon != null && priorityIcon.getIconHeight() > height) {
height = priorityIcon.getIconHeight();
}
if (affinityIcon != null && affinityIcon.getIconHeight() > height) {
height = affinityIcon.getIconHeight();
}
return height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
int innerX = x;
if (priorityIcon != null) {
priorityIcon.paintIcon(c, g, innerX, y);
innerX += priorityIcon.getIconWidth();
}
for (Color skillColor : skillColorList) {
g.setColor(skillColor);
g.fillRect(innerX + 1, y + 1, SKILL_ICON_WIDTH - 2, SKILL_ICON_HEIGHT - 2);
g.setColor(TangoColorFactory.ALUMINIUM_5);
g.drawRect(innerX + 1, y + 1, SKILL_ICON_WIDTH - 2, SKILL_ICON_HEIGHT - 2);
innerX += SKILL_ICON_WIDTH;
}
if (affinityIcon != null) {
affinityIcon.paintIcon(c, g, innerX, y);
innerX += affinityIcon.getIconWidth();
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/app/TennisApp.java | package ai.timefold.solver.examples.tennis.app;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.tennis.domain.TennisSolution;
import ai.timefold.solver.examples.tennis.persistence.TennisSolutionFileIO;
import ai.timefold.solver.examples.tennis.swingui.TennisPanel;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
public class TennisApp extends CommonApp<TennisSolution> {
public static final String SOLVER_CONFIG = "ai/timefold/solver/examples/tennis/tennisSolverConfig.xml";
public static final String DATA_DIR_NAME = "tennis";
public static void main(String[] args) {
prepareSwingEnvironment();
new TennisApp().init();
}
public TennisApp() {
super("Tennis club scheduling",
"Assign available spots to teams.\n\n" +
"Each team must play an almost equal number of times.\n" +
"Each team must play against each other team an almost equal number of times.",
SOLVER_CONFIG, DATA_DIR_NAME,
TennisPanel.LOGO_PATH);
}
@Override
protected TennisPanel createSolutionPanel() {
return new TennisPanel();
}
@Override
public SolutionFileIO<TennisSolution> createSolutionFileIO() {
return new TennisSolutionFileIO();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/domain/Day.java | package ai.timefold.solver.examples.tennis.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(scope = Day.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Day extends AbstractPersistable implements Labeled {
private int dateIndex;
public Day() {
}
public Day(long id, int dateIndex) {
super(id);
this.dateIndex = dateIndex;
}
public int getDateIndex() {
return dateIndex;
}
public void setDateIndex(int dateIndex) {
this.dateIndex = dateIndex;
}
@Override
public String getLabel() {
return "day " + dateIndex;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/domain/Team.java | package ai.timefold.solver.examples.tennis.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(scope = Team.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Team extends AbstractPersistable implements Labeled {
private String name;
public Team() {
}
public Team(long id, String name) {
super(id);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getLabel() {
return name;
}
@Override
public String toString() {
return name == null ? super.toString() : name;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/domain/TeamAssignment.java | package ai.timefold.solver.examples.tennis.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.entity.PlanningPin;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
@PlanningEntity
public class TeamAssignment extends AbstractPersistable {
private Day day;
private int indexInDay;
private boolean pinned;
// planning variable
private Team team;
public TeamAssignment() {
}
public TeamAssignment(long id, Day day, int indexInDay) {
super(id);
this.day = day;
this.indexInDay = indexInDay;
}
public Day getDay() {
return day;
}
public void setDay(Day day) {
this.day = day;
}
public int getIndexInDay() {
return indexInDay;
}
public void setIndexInDay(int indexInDay) {
this.indexInDay = indexInDay;
}
@PlanningPin
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
@PlanningVariable
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
@Override
public String toString() {
return "Day-" + day.getDateIndex() + "(" + indexInDay + ")";
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/domain/TennisSolution.java | package ai.timefold.solver.examples.tennis.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
@PlanningSolution
public class TennisSolution extends AbstractPersistable {
private List<Team> teamList;
private List<Day> dayList;
private List<UnavailabilityPenalty> unavailabilityPenaltyList;
private List<TeamAssignment> teamAssignmentList;
private HardMediumSoftScore score;
public TennisSolution() {
}
public TennisSolution(long id) {
super(id);
}
@ValueRangeProvider
@ProblemFactCollectionProperty
public List<Team> getTeamList() {
return teamList;
}
public void setTeamList(List<Team> teamList) {
this.teamList = teamList;
}
@ProblemFactCollectionProperty
public List<Day> getDayList() {
return dayList;
}
public void setDayList(List<Day> dayList) {
this.dayList = dayList;
}
@ProblemFactCollectionProperty
public List<UnavailabilityPenalty> getUnavailabilityPenaltyList() {
return unavailabilityPenaltyList;
}
public void setUnavailabilityPenaltyList(List<UnavailabilityPenalty> unavailabilityPenaltyList) {
this.unavailabilityPenaltyList = unavailabilityPenaltyList;
}
@PlanningEntityCollectionProperty
public List<TeamAssignment> getTeamAssignmentList() {
return teamAssignmentList;
}
public void setTeamAssignmentList(List<TeamAssignment> teamAssignmentList) {
this.teamAssignmentList = teamAssignmentList;
}
@PlanningScore
public HardMediumSoftScore getScore() {
return score;
}
public void setScore(HardMediumSoftScore score) {
this.score = score;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/domain/UnavailabilityPenalty.java | package ai.timefold.solver.examples.tennis.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
public class UnavailabilityPenalty extends AbstractPersistable {
private Team team;
private Day day;
public UnavailabilityPenalty() {
}
public UnavailabilityPenalty(long id, Team team, Day day) {
super(id);
this.team = team;
this.day = day;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public Day getDay() {
return day;
}
public void setDay(Day day) {
this.day = day;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/optional | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/optional/benchmark/TennisBenchmarkApp.java | package ai.timefold.solver.examples.tennis.optional.benchmark;
import java.io.File;
import ai.timefold.solver.benchmark.api.PlannerBenchmark;
import ai.timefold.solver.benchmark.api.PlannerBenchmarkFactory;
import ai.timefold.solver.examples.common.app.LoggingMain;
import ai.timefold.solver.examples.tennis.app.TennisApp;
import ai.timefold.solver.examples.tennis.domain.TennisSolution;
import ai.timefold.solver.examples.tennis.persistence.TennisGenerator;
public class TennisBenchmarkApp extends LoggingMain {
public static void main(String[] args) {
new TennisBenchmarkApp().benchmark();
}
private final PlannerBenchmarkFactory benchmarkFactory;
public TennisBenchmarkApp() {
benchmarkFactory = PlannerBenchmarkFactory.createFromSolverConfigXmlResource(
TennisApp.SOLVER_CONFIG, new File("local/data/tennis"));
}
public void benchmark() {
TennisSolution problem = new TennisGenerator().createTennisSolution();
PlannerBenchmark plannerBenchmark = benchmarkFactory.buildPlannerBenchmark(problem);
plannerBenchmark.benchmark();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/persistence/TennisGenerator.java | package ai.timefold.solver.examples.tennis.persistence;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.app.LoggingMain;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.examples.tennis.app.TennisApp;
import ai.timefold.solver.examples.tennis.domain.Day;
import ai.timefold.solver.examples.tennis.domain.Team;
import ai.timefold.solver.examples.tennis.domain.TeamAssignment;
import ai.timefold.solver.examples.tennis.domain.TennisSolution;
import ai.timefold.solver.examples.tennis.domain.UnavailabilityPenalty;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
public class TennisGenerator extends LoggingMain {
public static void main(String[] args) {
new TennisGenerator().generate();
}
protected final SolutionFileIO<TennisSolution> solutionFileIO = new TennisSolutionFileIO();
protected final File outputDir;
public TennisGenerator() {
this.outputDir = new File(CommonApp.determineDataDir(TennisApp.DATA_DIR_NAME), "unsolved");
}
public void generate() {
File outputFile = new File(outputDir, "munich-7teams.json");
TennisSolution tennisSolution = createTennisSolution();
solutionFileIO.write(tennisSolution, outputFile);
logger.info("Saved: {}", outputFile);
}
public TennisSolution createTennisSolution() {
TennisSolution tennisSolution = new TennisSolution(0L);
List<Team> teamList = new ArrayList<>();
teamList.add(new Team(0L, "Micha"));
teamList.add(new Team(1L, "Angelika"));
teamList.add(new Team(2L, "Katrin"));
teamList.add(new Team(3L, "Susi"));
teamList.add(new Team(4L, "Irene"));
teamList.add(new Team(5L, "Kristina"));
teamList.add(new Team(6L, "Tobias"));
tennisSolution.setTeamList(teamList);
List<Day> dayList = new ArrayList<>();
for (int i = 0; i < 18; i++) {
dayList.add(new Day(i, i));
}
tennisSolution.setDayList(dayList);
List<UnavailabilityPenalty> unavailabilityPenaltyList = new ArrayList<>();
unavailabilityPenaltyList.add(new UnavailabilityPenalty(0L, teamList.get(4), dayList.get(0)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(1L, teamList.get(6), dayList.get(1)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(2L, teamList.get(2), dayList.get(2)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(3L, teamList.get(4), dayList.get(3)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(4L, teamList.get(4), dayList.get(5)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(5L, teamList.get(2), dayList.get(6)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(6L, teamList.get(1), dayList.get(8)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(7L, teamList.get(2), dayList.get(9)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(8L, teamList.get(4), dayList.get(10)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(9L, teamList.get(4), dayList.get(11)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(10L, teamList.get(6), dayList.get(12)));
unavailabilityPenaltyList.add(new UnavailabilityPenalty(11L, teamList.get(5), dayList.get(15)));
tennisSolution.setUnavailabilityPenaltyList(unavailabilityPenaltyList);
List<TeamAssignment> teamAssignmentList = new ArrayList<>();
long id = 0L;
for (Day day : dayList) {
for (int i = 0; i < 4; i++) {
teamAssignmentList.add(new TeamAssignment(id, day, i));
id++;
}
}
tennisSolution.setTeamAssignmentList(teamAssignmentList);
BigInteger possibleSolutionSize = BigInteger.valueOf(teamList.size()).pow(
teamAssignmentList.size());
logger.info("Tennis {} has {} teams, {} days, {} unavailabilityPenalties and {} teamAssignments"
+ " with a search space of {}.",
"munich-7teams", teamList.size(), dayList.size(), unavailabilityPenaltyList.size(), teamAssignmentList.size(),
AbstractSolutionImporter.getFlooredPossibleSolutionSize(possibleSolutionSize));
return tennisSolution;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/persistence/TennisSolutionFileIO.java | package ai.timefold.solver.examples.tennis.persistence;
import ai.timefold.solver.examples.common.persistence.AbstractJsonSolutionFileIO;
import ai.timefold.solver.examples.tennis.domain.TennisSolution;
public class TennisSolutionFileIO extends AbstractJsonSolutionFileIO<TennisSolution> {
public TennisSolutionFileIO() {
super(TennisSolution.class);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/score/TennisConstraintProvider.java | package ai.timefold.solver.examples.tennis.score;
import static ai.timefold.solver.core.api.score.stream.Joiners.equal;
import static ai.timefold.solver.core.api.score.stream.Joiners.lessThan;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import ai.timefold.solver.core.api.function.TriFunction;
import ai.timefold.solver.core.api.score.buildin.hardmediumsoft.HardMediumSoftScore;
import ai.timefold.solver.core.api.score.stream.Constraint;
import ai.timefold.solver.core.api.score.stream.ConstraintFactory;
import ai.timefold.solver.core.api.score.stream.ConstraintProvider;
import ai.timefold.solver.core.api.score.stream.bi.BiConstraintCollector;
import ai.timefold.solver.core.api.score.stream.uni.UniConstraintCollector;
import ai.timefold.solver.examples.tennis.domain.TeamAssignment;
import ai.timefold.solver.examples.tennis.domain.UnavailabilityPenalty;
public class TennisConstraintProvider implements ConstraintProvider {
private static <A> UniConstraintCollector<A, ?, LoadBalanceData> loadBalance(Function<A, Object> groupKey) {
return new LoadBalanceUniConstraintCollector<>(groupKey);
}
private static <A, B> BiConstraintCollector<A, B, ?, LoadBalanceData> loadBalance(BiFunction<A, B, Object> groupKey) {
return new LoadBalanceBiConstraintCollector<>(groupKey);
}
@Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
oneAssignmentPerDatePerTeam(constraintFactory),
unavailabilityPenalty(constraintFactory),
fairAssignmentCountPerTeam(constraintFactory),
evenlyConfrontationCount(constraintFactory)
};
}
Constraint oneAssignmentPerDatePerTeam(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(TeamAssignment.class)
.join(TeamAssignment.class,
equal(TeamAssignment::getTeam),
equal(TeamAssignment::getDay),
lessThan(TeamAssignment::getId))
.penalize(HardMediumSoftScore.ONE_HARD)
.asConstraint("oneAssignmentPerDatePerTeam");
}
Constraint unavailabilityPenalty(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(UnavailabilityPenalty.class)
.ifExists(TeamAssignment.class,
equal(UnavailabilityPenalty::getTeam, TeamAssignment::getTeam),
equal(UnavailabilityPenalty::getDay, TeamAssignment::getDay))
.penalize(HardMediumSoftScore.ONE_HARD)
.asConstraint("unavailabilityPenalty");
}
Constraint fairAssignmentCountPerTeam(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(TeamAssignment.class)
.groupBy(loadBalance(TeamAssignment::getTeam))
.penalize(HardMediumSoftScore.ONE_MEDIUM,
result -> (int) result.getZeroDeviationSquaredSumRootMillis())
.asConstraint("fairAssignmentCountPerTeam");
}
Constraint evenlyConfrontationCount(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(TeamAssignment.class)
.join(TeamAssignment.class,
equal(TeamAssignment::getDay),
lessThan(assignment -> assignment.getTeam().getId()))
.groupBy(loadBalance(
(assignment, otherAssignment) -> new Pair<>(assignment.getTeam(), otherAssignment.getTeam())))
.penalize(HardMediumSoftScore.ONE_SOFT,
result -> (int) result.getZeroDeviationSquaredSumRootMillis())
.asConstraint("evenlyConfrontationCount");
}
public static final class LoadBalanceData {
private final Map<Object, Long> groupCountMap = new LinkedHashMap<>(0);
// the sum of squared deviation from zero
private long squaredSum = 0L;
private Runnable apply(Object mapped) {
long count = groupCountMap.compute(mapped,
(key, value) -> (value == null) ? 1L : value + 1L);
// squaredZeroDeviation = squaredZeroDeviation - (count - 1)² + count²
// <=> squaredZeroDeviation = squaredZeroDeviation + (2 * count - 1)
squaredSum += (2 * count - 1);
return () -> {
Long computed = groupCountMap.compute(mapped,
(key, value) -> (value == 1L) ? null : value - 1L);
squaredSum -= (computed == null) ? 1L : (2 * computed + 1);
};
}
public long getZeroDeviationSquaredSumRootMillis() {
return (long) (Math.sqrt(squaredSum) * 1_000);
}
}
public record Pair<A, B>(A key, B value) {
}
public static class LoadBalanceUniConstraintCollector<A>
implements UniConstraintCollector<A, LoadBalanceData, LoadBalanceData> {
private final Function<A, Object> groupKey;
public LoadBalanceUniConstraintCollector(Function<A, Object> groupKey) {
this.groupKey = groupKey;
}
@Override
public Supplier<LoadBalanceData> supplier() {
return LoadBalanceData::new;
}
@Override
public BiFunction<LoadBalanceData, A, Runnable> accumulator() {
return (resultContainer, a) -> {
Object mapped = groupKey.apply(a);
return resultContainer.apply(mapped);
};
}
@Override
public Function<LoadBalanceData, LoadBalanceData> finisher() {
return Function.identity();
}
}
public static class LoadBalanceBiConstraintCollector<A, B>
implements BiConstraintCollector<A, B, LoadBalanceData, LoadBalanceData> {
private final BiFunction<A, B, Object> groupKey;
public LoadBalanceBiConstraintCollector(BiFunction<A, B, Object> groupKey) {
this.groupKey = groupKey;
}
@Override
public Supplier<LoadBalanceData> supplier() {
return LoadBalanceData::new;
}
@Override
public TriFunction<LoadBalanceData, A, B, Runnable> accumulator() {
return (resultContainer, a, b) -> {
Object mapped = groupKey.apply(a, b);
return resultContainer.apply(mapped);
};
}
@Override
public Function<LoadBalanceData, LoadBalanceData> finisher() {
return Function.identity();
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/tennis/swingui/TennisPanel.java | package ai.timefold.solver.examples.tennis.swingui;
import static ai.timefold.solver.examples.common.swingui.timetable.TimeTablePanel.HeaderColumnKey.HEADER_COLUMN;
import static ai.timefold.solver.examples.common.swingui.timetable.TimeTablePanel.HeaderColumnKey.TRAILING_HEADER_COLUMN;
import static ai.timefold.solver.examples.common.swingui.timetable.TimeTablePanel.HeaderRowKey.HEADER_ROW;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import ai.timefold.solver.examples.common.swingui.CommonIcons;
import ai.timefold.solver.examples.common.swingui.SolutionPanel;
import ai.timefold.solver.examples.common.swingui.components.LabeledComboBoxRenderer;
import ai.timefold.solver.examples.common.swingui.timetable.TimeTablePanel;
import ai.timefold.solver.examples.tennis.domain.Day;
import ai.timefold.solver.examples.tennis.domain.Team;
import ai.timefold.solver.examples.tennis.domain.TeamAssignment;
import ai.timefold.solver.examples.tennis.domain.TennisSolution;
import ai.timefold.solver.examples.tennis.domain.UnavailabilityPenalty;
import ai.timefold.solver.swing.impl.SwingUtils;
import ai.timefold.solver.swing.impl.TangoColorFactory;
public class TennisPanel extends SolutionPanel<TennisSolution> {
public static final String LOGO_PATH = "/ai/timefold/solver/examples/tennis/swingui/tennisLogo.png";
private final TimeTablePanel<Day, Team> datesPanel;
private final TimeTablePanel<Team, Team> confrontationsPanel;
public TennisPanel() {
setLayout(new BorderLayout());
JTabbedPane tabbedPane = new JTabbedPane();
datesPanel = new TimeTablePanel<>();
tabbedPane.add("Dates", new JScrollPane(datesPanel));
confrontationsPanel = new TimeTablePanel<>();
tabbedPane.add("Confrontations", new JScrollPane(confrontationsPanel));
add(tabbedPane, BorderLayout.CENTER);
setPreferredSize(PREFERRED_SCROLLABLE_VIEWPORT_SIZE);
}
@Override
public boolean isWrapInScrollPane() {
return false;
}
@Override
public void resetPanel(TennisSolution tennisSolution) {
datesPanel.reset();
confrontationsPanel.reset();
defineGrid(tennisSolution);
fillCells(tennisSolution);
repaint(); // Hack to force a repaint of TimeTableLayout during "refresh screen while solving"
}
private void defineGrid(TennisSolution tennisSolution) {
JButton footprint = SwingUtils.makeSmallButton(new JButton("999999"));
int footprintWidth = footprint.getPreferredSize().width;
datesPanel.defineColumnHeaderByKey(HEADER_COLUMN);
for (Day day : tennisSolution.getDayList()) {
datesPanel.defineColumnHeader(day, footprintWidth);
}
datesPanel.defineColumnHeaderByKey(TRAILING_HEADER_COLUMN); // Assignment count
datesPanel.defineRowHeaderByKey(HEADER_ROW);
for (Team team : tennisSolution.getTeamList()) {
datesPanel.defineRowHeader(team);
}
datesPanel.defineRowHeader(null); // Unassigned
confrontationsPanel.defineColumnHeaderByKey(HEADER_COLUMN);
for (Team team : tennisSolution.getTeamList()) {
confrontationsPanel.defineColumnHeader(team);
}
confrontationsPanel.defineRowHeaderByKey(HEADER_ROW);
for (Team team : tennisSolution.getTeamList()) {
confrontationsPanel.defineRowHeader(team);
}
}
private void fillCells(TennisSolution tennisSolution) {
datesPanel.addCornerHeader(HEADER_COLUMN, HEADER_ROW, createTableHeader(new JLabel("Team")));
fillDayCells(tennisSolution);
fillTeamCells(tennisSolution);
fillUnavailabilityPenaltyCells(tennisSolution);
fillTeamAssignmentCells(tennisSolution);
fillConfrontationCells(tennisSolution);
}
private void fillDayCells(TennisSolution tennisSolution) {
for (Day day : tennisSolution.getDayList()) {
datesPanel.addColumnHeader(day, HEADER_ROW,
createTableHeader(new JLabel(day.getLabel(), SwingConstants.CENTER)));
}
datesPanel.addCornerHeader(TRAILING_HEADER_COLUMN, HEADER_ROW,
createTableHeader(new JLabel("Day count")));
}
private void fillTeamCells(TennisSolution tennisSolution) {
Map<Team, Integer> teamToDayCountMap = extractTeamToDayCountMap(tennisSolution);
for (Team team : tennisSolution.getTeamList()) {
datesPanel.addRowHeader(HEADER_COLUMN, team,
createTableHeader(new JLabel(team.getLabel())));
datesPanel.addRowHeader(TRAILING_HEADER_COLUMN, team,
createTableHeader(new JLabel(teamToDayCountMap.get(team) + " days")));
confrontationsPanel.addColumnHeader(team, HEADER_ROW,
createTableHeader(new JLabel(team.getLabel())));
confrontationsPanel.addRowHeader(HEADER_COLUMN, team,
createTableHeader(new JLabel(team.getLabel())));
}
datesPanel.addRowHeader(HEADER_COLUMN, null,
createTableHeader(new JLabel("Unassigned")));
}
private Map<Team, Integer> extractTeamToDayCountMap(TennisSolution tennisSolution) {
Map<Team, Integer> teamToDayCountMap = new HashMap<>(tennisSolution.getTeamList().size());
for (Team team : tennisSolution.getTeamList()) {
teamToDayCountMap.put(team, 0);
}
for (TeamAssignment teamAssignment : tennisSolution.getTeamAssignmentList()) {
Team team = teamAssignment.getTeam();
if (team != null) {
int count = teamToDayCountMap.get(team);
count++;
teamToDayCountMap.put(team, count);
}
}
return teamToDayCountMap;
}
private void fillUnavailabilityPenaltyCells(TennisSolution tennisSolution) {
for (UnavailabilityPenalty unavailabilityPenalty : tennisSolution.getUnavailabilityPenaltyList()) {
JPanel unavailabilityPanel = new JPanel();
unavailabilityPanel.setBackground(TangoColorFactory.ALUMINIUM_4);
datesPanel.addCell(unavailabilityPenalty.getDay(), unavailabilityPenalty.getTeam(),
unavailabilityPanel);
}
}
private void fillTeamAssignmentCells(TennisSolution tennisSolution) {
TangoColorFactory tangoColorFactory = new TangoColorFactory();
for (Team team : tennisSolution.getTeamList()) {
tangoColorFactory.pickColor(team);
}
for (TeamAssignment teamAssignment : tennisSolution.getTeamAssignmentList()) {
Team team = teamAssignment.getTeam();
Color teamColor = team == null ? TangoColorFactory.SCARLET_1 : tangoColorFactory.pickColor(team);
datesPanel.addCell(teamAssignment.getDay(), team,
createButton(teamAssignment, teamColor));
}
}
private void fillConfrontationCells(TennisSolution tennisSolution) {
List<Team> teamList = tennisSolution.getTeamList();
List<Day> dayList = tennisSolution.getDayList();
Map<Day, List<TeamAssignment>> dayToTeamAssignmentListMap = new HashMap<>(
dayList.size());
for (Day day : dayList) {
dayToTeamAssignmentListMap.put(day, new ArrayList<>());
}
for (TeamAssignment teamAssignment : tennisSolution.getTeamAssignmentList()) {
dayToTeamAssignmentListMap.get(teamAssignment.getDay()).add(teamAssignment);
}
Map<List<Team>, Integer> teamPairToConfrontationCountMap = new HashMap<>();
for (Team left : teamList) {
for (Team right : teamList) {
if (left != right) {
List<Team> teamPair = Arrays.asList(left, right);
teamPairToConfrontationCountMap.put(teamPair, 0);
}
}
}
for (List<TeamAssignment> teamAssignmentSubList : dayToTeamAssignmentListMap.values()) {
for (TeamAssignment left : teamAssignmentSubList) {
if (left.getTeam() != null) {
for (TeamAssignment right : teamAssignmentSubList) {
if (right.getTeam() != null && left.getTeam() != right.getTeam()) {
List<Team> teamPair = Arrays.asList(left.getTeam(), right.getTeam());
int confrontationCount = teamPairToConfrontationCountMap.get(teamPair);
confrontationCount++;
teamPairToConfrontationCountMap.put(teamPair, confrontationCount);
}
}
}
}
}
for (Map.Entry<List<Team>, Integer> teamPairToConfrontationCount : teamPairToConfrontationCountMap.entrySet()) {
List<Team> teamPair = teamPairToConfrontationCount.getKey();
int confrontationCount = teamPairToConfrontationCount.getValue();
confrontationsPanel.addCell(teamPair.get(0), teamPair.get(1),
createTableHeader(new JLabel(Integer.toString(confrontationCount))));
}
}
private JPanel createTableHeader(JLabel label) {
JPanel headerPanel = new JPanel(new BorderLayout());
headerPanel.add(label, BorderLayout.NORTH);
headerPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(TangoColorFactory.ALUMINIUM_5),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
return headerPanel;
}
private JButton createButton(TeamAssignment teamAssignment, Color color) {
JButton button = SwingUtils.makeSmallButton(new JButton(new TeamAssignmentAction(teamAssignment)));
button.setBackground(color);
if (teamAssignment.isPinned()) {
button.setIcon(CommonIcons.PINNED_ICON);
}
return button;
}
private class TeamAssignmentAction extends AbstractAction {
private TeamAssignment teamAssignment;
public TeamAssignmentAction(TeamAssignment teamAssignment) {
super("Play");
this.teamAssignment = teamAssignment;
}
@Override
public void actionPerformed(ActionEvent e) {
JPanel listFieldsPanel = new JPanel(new GridLayout(2, 2));
listFieldsPanel.add(new JLabel("Team:"));
List<Team> teamList = getSolution().getTeamList();
// Add 1 to array size to add null, which makes the entity unassigned
JComboBox teamListField = new JComboBox(
teamList.toArray(new Object[teamList.size() + 1]));
LabeledComboBoxRenderer.applyToComboBox(teamListField);
teamListField.setSelectedItem(teamAssignment.getTeam());
listFieldsPanel.add(teamListField);
listFieldsPanel.add(new JLabel("Pinned:"));
JCheckBox pinnedField = new JCheckBox("cannot move during solving");
pinnedField.setSelected(teamAssignment.isPinned());
listFieldsPanel.add(pinnedField);
int result = JOptionPane.showConfirmDialog(TennisPanel.this.getRootPane(), listFieldsPanel,
"Select team", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
Team toTeam = (Team) teamListField.getSelectedItem();
if (teamAssignment.getTeam() != toTeam) {
doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector
.changeVariable(teamAssignment, "team", ta -> ta.setTeam(toTeam)));
}
boolean toPinned = pinnedField.isSelected();
if (teamAssignment.isPinned() != toPinned) {
doProblemChange((workingSolution, problemChangeDirector) -> problemChangeDirector
.changeProblemProperty(teamAssignment, ta -> ta.setPinned(toPinned)));
}
solverAndPersistenceFrame.resetScreen();
}
}
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament/app/TravelingTournamentApp.java | package ai.timefold.solver.examples.travelingtournament.app;
import java.util.Collections;
import java.util.Set;
import ai.timefold.solver.examples.common.app.CommonApp;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionExporter;
import ai.timefold.solver.examples.common.persistence.AbstractSolutionImporter;
import ai.timefold.solver.examples.travelingtournament.domain.TravelingTournament;
import ai.timefold.solver.examples.travelingtournament.persistence.TravelingTournamentExporter;
import ai.timefold.solver.examples.travelingtournament.persistence.TravelingTournamentImporter;
import ai.timefold.solver.examples.travelingtournament.persistence.TravelingTournamentSolutionFileIO;
import ai.timefold.solver.examples.travelingtournament.swingui.TravelingTournamentPanel;
import ai.timefold.solver.persistence.common.api.domain.solution.SolutionFileIO;
/**
* WARNING: This is an old, complex, tailored example. You're probably better off with one of the other examples.
*/
public class TravelingTournamentApp extends CommonApp<TravelingTournament> {
public static final String SOLVER_CONFIG =
"ai/timefold/solver/examples/travelingtournament/travelingTournamentSolverConfig.xml";
public static final String DATA_DIR_NAME = "travelingtournament";
public static void main(String[] args) {
prepareSwingEnvironment();
new TravelingTournamentApp().init();
}
public TravelingTournamentApp() {
super("Traveling tournament",
"Official competition name: TTP - Traveling tournament problem\n\n" +
"Assign sport matches to days. Minimize the distance travelled.",
SOLVER_CONFIG, DATA_DIR_NAME,
TravelingTournamentPanel.LOGO_PATH);
}
@Override
protected TravelingTournamentPanel createSolutionPanel() {
return new TravelingTournamentPanel();
}
@Override
public SolutionFileIO<TravelingTournament> createSolutionFileIO() {
return new TravelingTournamentSolutionFileIO();
}
@Override
protected Set<AbstractSolutionImporter<TravelingTournament>> createSolutionImporters() {
return Collections.singleton(new TravelingTournamentImporter());
}
@Override
protected Set<AbstractSolutionExporter<TravelingTournament>> createSolutionExporters() {
return Collections.singleton(new TravelingTournamentExporter());
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament/domain/Day.java | package ai.timefold.solver.examples.travelingtournament.domain;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Day extends AbstractPersistable implements Labeled {
private int index;
private Day nextDay;
public Day() {
}
public Day(int id) {
super(id);
this.index = id;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Day getNextDay() {
return nextDay;
}
public void setNextDay(Day nextDay) {
this.nextDay = nextDay;
}
@Override
public String getLabel() {
return Integer.toString(index);
}
@Override
public String toString() {
return "Day-" + index;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament/domain/Match.java | package ai.timefold.solver.examples.travelingtournament.domain;
import ai.timefold.solver.core.api.domain.entity.PlanningEntity;
import ai.timefold.solver.core.api.domain.variable.PlanningVariable;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
@PlanningEntity
public class Match extends AbstractPersistable {
private Team homeTeam;
private Team awayTeam;
private Day day;
public Match() {
}
public Match(long id, Team homeTeam, Team awayTeam) {
super(id);
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
}
public Team getHomeTeam() {
return homeTeam;
}
public void setHomeTeam(Team homeTeam) {
this.homeTeam = homeTeam;
}
public Team getAwayTeam() {
return awayTeam;
}
public void setAwayTeam(Team awayTeam) {
this.awayTeam = awayTeam;
}
@PlanningVariable
public Day getDay() {
return day;
}
public void setDay(Day day) {
this.day = day;
}
@Override
public String toString() {
return homeTeam + "+" + awayTeam;
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament/domain/Team.java | package ai.timefold.solver.examples.travelingtournament.domain;
import java.util.Map;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import ai.timefold.solver.examples.common.persistence.jackson.JacksonUniqueIdGenerator;
import ai.timefold.solver.examples.common.persistence.jackson.KeySerializer;
import ai.timefold.solver.examples.common.swingui.components.Labeled;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonIdentityInfo(generator = JacksonUniqueIdGenerator.class)
public class Team extends AbstractPersistable implements Labeled {
private String name;
private Map<Team, Integer> distanceToTeamMap;
public Team() {
}
public Team(long id) {
super(id);
}
public Team(long id, String name) {
this(id);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonSerialize(keyUsing = KeySerializer.class)
@JsonDeserialize(keyUsing = TeamKeyDeserializer.class)
public Map<Team, Integer> getDistanceToTeamMap() {
return distanceToTeamMap;
}
public void setDistanceToTeamMap(Map<Team, Integer> distanceToTeamMap) {
this.distanceToTeamMap = distanceToTeamMap;
}
@JsonIgnore
public int getDistance(Team other) {
return distanceToTeamMap.get(other);
}
@Override
public String getLabel() {
return name;
}
@Override
public String toString() {
return getName();
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament/domain/TeamKeyDeserializer.java | package ai.timefold.solver.examples.travelingtournament.domain;
import ai.timefold.solver.examples.common.persistence.jackson.AbstractKeyDeserializer;
final class TeamKeyDeserializer extends AbstractKeyDeserializer<Team> {
public TeamKeyDeserializer() {
super(Team.class);
}
@Override
protected Team createInstance(long id) {
return new Team(id);
}
}
|
0 | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament | java-sources/ai/timefold/solver/timefold-solver-examples/1.9.0/ai/timefold/solver/examples/travelingtournament/domain/TravelingTournament.java | package ai.timefold.solver.examples.travelingtournament.domain;
import java.util.List;
import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty;
import ai.timefold.solver.core.api.domain.solution.PlanningScore;
import ai.timefold.solver.core.api.domain.solution.PlanningSolution;
import ai.timefold.solver.core.api.domain.solution.ProblemFactCollectionProperty;
import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider;
import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore;
import ai.timefold.solver.examples.common.domain.AbstractPersistable;
import com.fasterxml.jackson.annotation.JsonIgnore;
@PlanningSolution
public class TravelingTournament extends AbstractPersistable {
private List<Day> dayList;
private List<Team> teamList;
private List<Match> matchList;
private HardSoftScore score;
public TravelingTournament() {
}
public TravelingTournament(long id) {
super(id);
}
@ValueRangeProvider
@ProblemFactCollectionProperty
public List<Day> getDayList() {
return dayList;
}
public void setDayList(List<Day> dayList) {
this.dayList = dayList;
}
@ProblemFactCollectionProperty
public List<Team> getTeamList() {
return teamList;
}
public void setTeamList(List<Team> teamList) {
this.teamList = teamList;
}
@PlanningEntityCollectionProperty
public List<Match> getMatchList() {
return matchList;
}
public void setMatchList(List<Match> matchSets) {
this.matchList = matchSets;
}
@PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
// ************************************************************************
// Complex methods
// ************************************************************************
@JsonIgnore
public int getN() {
return teamList.size();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.