Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions crates/solverforge/tests/construction_heuristics.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
//! Each scalar construction heuristic assigns in its documented entity
//! order, value order and forager. Tasks have difficulties 1, 3, 2; workers
//! have strengths 2, 0, 1 plus `load_weight` per task already on them and
//! costs 3, 2, 1; a task only goes to a free worker.

use solverforge::{SolverEvent, SolverManager};

#[path = "construction_heuristics/domain/mod.rs"]
mod domain;

use domain::Plan;

static MANAGER: SolverManager<Plan> = SolverManager::new();

fn construct(heuristic: &'static str, load_weight: i64) -> Vec<Option<usize>> {
construct_plan(Plan::new(heuristic, load_weight))
}

fn construct_plan(plan: Plan) -> Vec<Option<usize>> {
let heuristic = plan.heuristic;
let (job_id, mut receiver) = MANAGER.solve(plan).expect("solve starts");
let solution = loop {
match receiver
.blocking_recv()
.expect("event stream should reach a terminal event")
{
SolverEvent::Completed { solution, .. } => break solution,
SolverEvent::Failed { error, .. } => panic!("{heuristic} failed: {error}"),
SolverEvent::Cancelled { .. } => panic!("{heuristic} was cancelled"),
_ => {}
}
};
MANAGER.delete(job_id).expect("the completed job deletes");
solution.workers_by_task()
}

#[test]
fn first_fit_takes_tasks_in_order_and_the_first_free_worker() {
assert_eq!(construct("first_fit", 0), [Some(0), Some(1), Some(2)]);
}

#[test]
fn first_fit_decreasing_takes_the_hardest_task_first() {
// Tasks 1, 2, 0 in that order, each on the first free worker.
assert_eq!(
construct("first_fit_decreasing", 0),
[Some(2), Some(0), Some(1)]
);
}

#[test]
fn allocate_entity_from_queue_takes_the_easiest_task_first() {
// Tasks 0, 2, 1.
assert_eq!(
construct("allocate_entity_from_queue", 0),
[Some(0), Some(2), Some(1)]
);
}

#[test]
fn allocate_to_value_from_queue_offers_the_weakest_worker_first() {
// Workers in strength order 1, 2, 0.
assert_eq!(
construct("allocate_to_value_from_queue", 0),
[Some(1), Some(2), Some(0)]
);
}

#[test]
fn weakest_fit_picks_the_weakest_free_worker() {
// Loaded workers get stronger, so the weakest is always a free one:
// task 0 → 1, task 1 → 2, task 2 → 0.
assert_eq!(construct("weakest_fit", 10), [Some(1), Some(2), Some(0)]);
}

#[test]
fn weakest_fit_decreasing_picks_the_weakest_worker_for_the_hardest_task() {
// Task 1 → 1, task 2 → 2, task 0 → 0.
assert_eq!(
construct("weakest_fit_decreasing", 10),
[Some(0), Some(1), Some(2)]
);
}

#[test]
fn strongest_fit_picks_the_strongest_free_worker() {
// Loaded workers get weaker: task 0 → 0, task 1 → 2, task 2 → 1.
assert_eq!(construct("strongest_fit", -10), [Some(0), Some(2), Some(1)]);
}

#[test]
fn strongest_fit_decreasing_picks_the_strongest_worker_for_the_hardest_task() {
// Task 1 → 0, task 2 → 2, task 0 → 1.
assert_eq!(
construct("strongest_fit_decreasing", -10),
[Some(1), Some(0), Some(2)]
);
}

#[test]
fn cheapest_insertion_picks_the_best_scoring_worker() {
// The cheapest free worker: task 0 → 2, task 1 → 1, task 2 → 0.
assert_eq!(
construct("cheapest_insertion", 0),
[Some(2), Some(1), Some(0)]
);
}

#[test]
fn allocate_to_value_from_queue_reorders_the_workers_after_each_assignment() {
// Worker 0's key falls by 10 per assigned task: after task 0 takes
// worker 1, worker 0 comes before worker 2 for task 1.
let plan = Plan {
drift: -10,
..Plan::new("allocate_to_value_from_queue", 0)
};
assert_eq!(construct_plan(plan), [Some(1), Some(0), Some(2)]);
}

#[test]
fn first_fit_decreasing_reorders_the_tasks_after_each_assignment() {
// Task 0's difficulty rises by 10 per assigned task: after task 1 takes
// worker 0, task 0 comes before task 2.
let plan = Plan {
difficulty_drift: 10,
..Plan::new("first_fit_decreasing", 0)
};
assert_eq!(construct_plan(plan), [Some(1), Some(0), Some(2)]);
}
11 changes: 11 additions & 0 deletions crates/solverforge/tests/construction_heuristics/domain/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
solverforge::planning_model! {
root = "crates/solverforge/tests/construction_heuristics/domain";

mod plan;
mod task;
mod worker;

pub use plan::Plan;
pub use task::Task;
pub use worker::Worker;
}
103 changes: 103 additions & 0 deletions crates/solverforge/tests/construction_heuristics/domain/plan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
use solverforge::prelude::*;
use solverforge::stream::{joiner::equal, ConstraintFactory};
use solverforge::SolverConfig;

use super::{Task, Worker};

#[planning_solution(constraints = "constraints", config = "solver_config")]
pub struct Plan {
#[problem_fact_collection]
pub workers: Vec<Worker>,

#[planning_entity_collection]
pub tasks: Vec<Task>,

#[planning_score]
pub score: Option<HardSoftScore>,

/// How much each assigned task moves its worker's strength key.
pub load_weight: i64,

/// How much each assigned task moves worker 0's strength key.
pub drift: i64,

/// How much each assigned task moves task 0's difficulty key.
pub difficulty_drift: i64,

pub heuristic: &'static str,
}

impl Plan {
/// Three tasks with difficulties 1, 3, 2 and three workers with
/// strengths 2, 0, 1 and costs 3, 2, 1.
pub fn new(heuristic: &'static str, load_weight: i64) -> Self {
Self {
workers: [2, 0, 1]
.into_iter()
.enumerate()
.map(|(id, strength)| Worker {
id,
strength,
cost: 3 - id as i64,
})
.collect(),
tasks: [1, 3, 2]
.into_iter()
.enumerate()
.map(|(id, difficulty)| Task {
id,
difficulty,
worker: None,
})
.collect(),
score: None,
load_weight,
drift: 0,
difficulty_drift: 0,
heuristic,
}
}

pub fn workers_by_task(&self) -> Vec<Option<usize>> {
self.tasks.iter().map(|task| task.worker).collect()
}
}

fn solver_config(plan: &Plan, _base: SolverConfig) -> SolverConfig {
SolverConfig::from_toml_str(&format!(
"[[phases]]\ntype = \"construction_heuristic\"\nconstruction_heuristic_type = \"{}\"\n",
plan.heuristic
))
.expect("the test config parses")
}

/// An unassigned task costs one hard point and two tasks sharing a worker
/// two, so a task goes only to a free worker; each assigned task costs its
/// worker's soft cost.
fn constraints() -> impl ConstraintSet<Plan, HardSoftScore> {
(
ConstraintFactory::<Plan, HardSoftScore>::new()
.for_each(Plan::tasks())
.filter(|task: &Task| task.worker.is_none())
.penalize(HardSoftScore::ONE_HARD)
.named("unassigned task"),
ConstraintFactory::<Plan, HardSoftScore>::new()
.for_each(Plan::tasks())
.join(equal(|task: &Task| task.worker))
.penalize(|left: &Task, _right: &Task| {
HardSoftScore::of(if left.worker.is_some() { 2 } else { 0 }, 0)
})
.named("shared worker"),
ConstraintFactory::<Plan, HardSoftScore>::new()
.for_each(Plan::tasks())
.join((
Plan::workers(),
solverforge::stream::joiner::equal_bi(
|task: &Task| task.worker,
|worker: &Worker| Some(worker.id),
),
))
.penalize(|_task: &Task, worker: &Worker| HardSoftScore::of_soft(worker.cost))
.named("worker cost"),
)
}
42 changes: 42 additions & 0 deletions crates/solverforge/tests/construction_heuristics/domain/task.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use solverforge::prelude::*;

use super::Plan;

#[planning_entity]
pub struct Task {
#[planning_id]
pub id: usize,

/// Construction difficulty: task 1 is the hardest, task 0 the easiest.
pub difficulty: i64,

#[planning_variable(
value_range_provider = "workers",
allows_unassigned = true,
construction_entity_order_key = "task_difficulty",
construction_value_order_key = "worker_strength"
)]
pub worker: Option<usize>,
}

/// A task's difficulty, moved for task 0 only by `difficulty_drift` for
/// every assigned task.
pub(super) fn task_difficulty(plan: &Plan, task: &Task) -> i64 {
let assigned = plan.tasks.iter().filter(|task| task.worker.is_some()).count() as i64;
let drift = if task.id == 0 { plan.difficulty_drift * assigned } else { 0 };
task.difficulty + drift
}

/// A worker's base strength, moved by `load_weight` for every task already
/// on it and, for worker 0 only, by `drift` for every assigned task, so the
/// key changes as construction assigns.
pub(super) fn worker_strength(plan: &Plan, _task: &Task, worker: usize) -> i64 {
let load = plan
.tasks
.iter()
.filter(|task| task.worker == Some(worker))
.count() as i64;
let assigned = plan.tasks.iter().filter(|task| task.worker.is_some()).count() as i64;
let drift = if worker == 0 { plan.drift * assigned } else { 0 };
plan.workers[worker].strength + plan.load_weight * load + drift
}
13 changes: 13 additions & 0 deletions crates/solverforge/tests/construction_heuristics/domain/worker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use solverforge::prelude::*;

#[problem_fact]
pub struct Worker {
#[planning_id]
pub id: usize,

/// Base strength: worker 1 is the weakest, worker 0 the strongest.
pub strength: i64,

/// Soft cost of each task on this worker: worker 2 is the cheapest.
pub cost: i64,
}
Loading