Constraints

Define constraints using the fluent Constraint Streams API.

Constraints define the rules that make a solution valid and optimal. SolverForge uses a fluent Constraint Streams API that lets you express constraints declaratively.

Topics

Constraint Types

TypePurposeExample
HardMust be satisfied for feasibilityNo two lessons in the same room at the same time
SoftPreferences to optimizeTeachers prefer consecutive lessons
MediumBetween hard and soft (optional)Important but not mandatory constraints

Example

from solverforge_legacy.solver.score import (
    constraint_provider, ConstraintFactory, Constraint, Joiners, HardSoftScore
)

@constraint_provider
def define_constraints(constraint_factory: ConstraintFactory) -> list[Constraint]:
    return [
        room_conflict(constraint_factory),
        teacher_conflict(constraint_factory),
        teacher_room_stability(constraint_factory),
    ]

def room_conflict(constraint_factory: ConstraintFactory) -> Constraint:
    # Hard constraint: No two lessons in the same room at the same time
    return (
        constraint_factory
        .for_each_unique_pair(
            Lesson,
            Joiners.equal(lambda lesson: lesson.timeslot),
            Joiners.equal(lambda lesson: lesson.room),
        )
        .penalize(HardSoftScore.ONE_HARD)
        .as_constraint("Room conflict")
    )

def teacher_room_stability(constraint_factory: ConstraintFactory) -> Constraint:
    # Soft constraint: Teachers prefer teaching in the same room
    return (
        constraint_factory
        .for_each_unique_pair(
            Lesson,
            Joiners.equal(lambda lesson: lesson.teacher),
        )
        .filter(lambda lesson1, lesson2: lesson1.room != lesson2.room)
        .penalize(HardSoftScore.ONE_SOFT)
        .as_constraint("Teacher room stability")
    )

Constraint Streams

Build constraints using the fluent Constraint Streams API.

Joiners

Efficiently filter and match entities in constraint streams.

Collectors

Aggregate data in constraint streams using collectors.

Score Types

Choose the right score type for your constraints.

Score Analysis

Understand why a solution has its score.

Constraint Performance

Optimize constraint evaluation for faster solving.

Testing Constraints

Test constraints in isolation for correctness.