Skip to content

Your First Activity Schedule: Modes, Dependencies and Resources ​

Work through business input, solving and result extraction with this example. Prepare dependencies and backends using Setup.

1. Business Scenario ​

Schedule activities a and b with a finishing before b starts. Activity a offers fast (2 h, machine, cost 3) or slow (3 h, alternate, cost 1). Activity b needs 2 h on machine at cost 0. Modes may start only at hour 0 or 2; both resources have capacity one and activities are mandatory.

Slow finishes no earlier than hour 3, but b has no start at or after 3. A feasible choice is a/fast at 0 and b at 2, costing 3. Both examples use the same relative times; Kotlin has a fixed business date and Rust uses UNIX_EPOCH as a teaching origin.

2. Construct Input and Call the Framework ​

Kotlin and Rust Entry Points

Use the finite-choice single-MILP service without implementing task-bunch column generation. Resource capacities/usages and costs are dimensionless teaching values here; declare business units for production. Kotlin returns an outer Ret and a scheduling report; Rust retains a report with an optional business solution.

The examples include imports and error handling. The application supplies Kotlin ColumnGenerationSolver to runExample; the next section shows the launcher.

kt
@file:OptIn(kotlin.time.ExperimentalTime::class)
package docs.examples.gantt

import kotlin.time.Instant
import kotlin.time.Duration.Companion.hours
import fuookami.ospf.kotlin.math.algebra.number.Flt64
import fuookami.ospf.kotlin.quantities.quantity.Quantity
import fuookami.ospf.kotlin.quantities.unit.NoneUnit
import fuookami.ospf.kotlin.framework.solver.ColumnGenerationSolver
import fuookami.ospf.kotlin.framework.gantt_scheduling.infrastructure.TimeRange
import fuookami.ospf.kotlin.framework.gantt_scheduling.domain.task.model.*
import fuookami.ospf.kotlin.framework.gantt_scheduling.domain.activity.model.*
import fuookami.ospf.kotlin.framework.gantt_scheduling.application.service.*
import fuookami.ospf.kotlin.utils.functional.*

private data class Task(val value: String) : TaskId
private data class Resource(val value: String) : ExecutorId

suspend fun runExample(solver: ColumnGenerationSolver) {
    val origin = Instant.parse("2026-10-22T00:00:00Z")
    fun at(hour: Int) = origin + hour.hours
    fun q(value: Double) = Quantity(Flt64(value), NoneUnit)
    val a = Task("a")
    val b = Task("b")
    val machine = Resource("machine")
    val alternate = Resource("alternate")
    val problem = ActivitySchedulingProblem(
        horizon = TimeRange(at(0), at(6)), costUnit = NoneUnit,
        activities = listOf(
            Activity(a, listOf(
                ActivityMode("fast", 2.hours, listOf(at(0), at(2)), listOf(ActivityResourceUse(machine, q(1.0))), q(3.0)),
                ActivityMode("slow", 3.hours, listOf(at(0), at(2)), listOf(ActivityResourceUse(alternate, q(1.0))), q(1.0))
            )),
            Activity(b, listOf(ActivityMode("next", 2.hours, listOf(at(0), at(2)), listOf(ActivityResourceUse(machine, q(1.0))), q(0.0))))
        ),
        resources = listOf(ActivityResource(machine, q(1.0)), ActivityResource(alternate, q(1.0))),
        dependencies = listOf(ActivityDependency(a, b))
    )
    when (val result = ActivitySchedulingApplicationService(solver, schedulingSolverValueAdapter).solve(problem)) {
        is Ok -> {
            val outcome = result.value
            println(outcome.report)
            val schedule = outcome.schedule
            if (schedule == null) {
                println("No schedule; retain the report instead of inventing a plan")
            } else {
                // #region result
                println("cost=${schedule.cost}, cancelled=${schedule.cancelled}, candidates=${schedule.candidateScope.size}")
                for (p in schedule.placements) {
                    println("task=${p.key.task}, mode=${p.key.mode}, start=${p.time.start}, end=${p.time.end}")
                    p.reservations.forEach { println("resource=${it.resource}, time=${it.time}, quantity=${it.quantity}") }
                }
                println("executions=${schedule.executions}, inventory=${schedule.materialInventory}")
                check(schedule.placements.size == 2 && schedule.cancelled.isEmpty())
                // #endregion result
            }
        }
        is Failed -> error("${result.error.code}: ${result.error.message}")
        is Fatal -> error(result.errors.joinToString { "${it.code}: ${it.message}" })
    }
}
rs
use time::{Duration, OffsetDateTime};
use ospf_rust_framework::solver::{ColumnGenerationSolver, FrameworkSolveOptions};
use ospf_rust_framework_gantt_scheduling::application::service::ActivitySchedulingApplicationService;
use ospf_rust_framework_gantt_scheduling::domain::activity::*;
use ospf_rust_framework_gantt_scheduling::domain::common::{task_id, executor_id};
use ospf_rust_framework_gantt_scheduling::domain::task::F64SolverValueAdapter;
use ospf_rust_framework_gantt_scheduling::infrastructure::TimeRange;
use ospf_rust_quantities::{Quantity, unit::{CTUnit, NoneUnit}};

pub fn run_example<S: ColumnGenerationSolver>(solver: S) -> Result<(), String> {
    let q = |value| Quantity::new(value, NoneUnit::INSTANT.clone());
    let at = |hour| OffsetDateTime::UNIX_EPOCH + Duration::hours(hour);
    let mode = |id: &str, hours: i64, resource: &str, cost: f64| ActivityMode {
        id: id.into(), duration: Duration::hours(hours), starts: vec![at(0), at(2)],
        resources: vec![ActivityResourceUse {
            resource: executor_id(resource), quantity: q(1.0), from: Duration::ZERO, until: None,
        }],
        cost: q(cost), material_flows: vec![],
    };
    let resource = |id: &str| ActivityResource {
        id: executor_id(id), capacity: q(1.0), unavailable_times: vec![], capacities: vec![],
    };
    let problem = ActivitySchedulingProblem {
        horizon: TimeRange::new(at(0), at(6)),
        activities: vec![
            Activity { id: task_id("a"), modes: vec![mode("fast", 2, "machine", 3.0), mode("slow", 3, "alternate", 1.0)], cancellation_cost: None },
            Activity { id: task_id("b"), modes: vec![mode("next", 2, "machine", 0.0)], cancellation_cost: None },
        ],
        resources: vec![resource("machine"), resource("alternate")],
        dependencies: vec![ActivityDependency {
            predecessor: task_id("a"), successor: task_id("b"),
            from: ActivityEndpoint::Finish, to: ActivityEndpoint::Start,
            minimum: Duration::ZERO, maximum: None, presence: ActivityDependencyPresence::RequireBoth,
        }],
        baselines: vec![], executions: vec![], rows: vec![],
        cost_unit: NoneUnit::INSTANT.clone(), materials: vec![], material_events: vec![],
    };
    let report = ActivitySchedulingApplicationService::new(solver).solve(
        || ActivitySchedulingContext::new(problem, &F64SolverValueAdapter, None, Default::default()),
        FrameworkSolveOptions::default(),
    ).map_err(|e| format!("{e:?}"))?;
    println!("report={report:?}");
    match report.solution.and_then(|solution| solution.value) {
        Some(schedule) => {
            // #region result
            println!("cost={:?}, cancelled={:?}, candidates={}", schedule.cost, schedule.cancelled, schedule.candidate_scope.len());
            for p in &schedule.placements {
                println!("task={:?}, mode={}, start={}, end={}", p.key.task, p.key.mode, p.time.start, p.time.end);
                for r in &p.reservations { println!("resource={:?}, time={:?}, quantity={:?}", r.resource, r.time, r.quantity); }
            }
            println!("executions={:?}, inventory={:?}", schedule.executions, schedule.material_inventory);
            assert!(schedule.placements.len() == 2 && schedule.cancelled.is_empty());
            // #endregion result
        },
        None => println!("No schedule; inspect the report before returning a business result"),
    }
    Ok(())
}

3. Launch from Your Application ​

Place the Kotlin example in application sources, retaining its package. This standalone launcher calls the lesson function. Add the domain starter, Gurobi plugin and coroutines, and configure matching native libraries and a license.

kotlin
import docs.examples.gantt.runExample
import kotlinx.coroutines.runBlocking
import fuookami.ospf.kotlin.core.solver.gurobi.GurobiColumnGenerationSolver

fun main() = runBlocking {
    runExample(GurobiColumnGenerationSolver())
}

Place the Rust example in src/gantt.rs and use this launcher in src/main.rs. See Setup for dependencies and toolchain; do not enable async for these synchronous examples.

rust
mod gantt;
use ospf_rust_framework::solver::ScipColumnGenerationSolver;

fn main() -> Result<(), String> {
    gantt::run_example(ScipColumnGenerationSolver::new())
}

At the CLI boundary these examples throw or return errors. A server should translate them at its request boundary and retain diagnostics. Preserve reports when no feasible solution was found rather than inventing a technical failure or an empty successful plan.

4. Read and Validate the Result ​

ReadKotlinRust
Task, mode and timeschedule.placements → key.task / key.mode / time.start / time.endschedule.placements → key.task / key.mode / time.start / time.end
Actual reservationsplacement.reservations → resource / time / quantityplacement.reservations → resource / time / quantity
Cost and retained factscost / cancelled / executions / materialInventorycost / cancelled / executions / material_inventory
Solve status and candidate scopeoutcome.report, schedule.candidateScopereport, schedule.candidate_scope

Result Semantics

Candidate scope records declared allowed choices; it is not complete or an optimality flag. Retain the solve report when no schedule exists. A returned schedule still needs cancellation, dependency and whole-interval resource checks.

Outer success does not ensure a schedule. Read the report before the optional business solution. Verify a mode, start/end times, precedence, resource usage and recomputed cost. Allowed starts define feasibility; a longer solve budget does not create a start at hour 3.

5. Change One Business Condition ​

Add hour 3 to b allowed starts only. You can now examine a/slow at 0 and b at 3, costing 1. Add machine downtime next, leaving freezing and rolling recovery for a later step.

Continue to the next business scenario and integration checks. Consult repository verification when checking source behavior.