Skip to content

Calendars and Rolling Recovery ​

After your first activity schedule, add downtime and varying capacity before execution facts and baselines. A fact is not a soft preference with a large penalty.

1. Expose Start-Only Calendar Checks ​

An activity lasts 2 h and consumes capacity 2 throughout. Allowed starts are 0, 2 and 4 h. Equipment capacity is normally 2, unavailable on [1,2), and reduced to 1 on [3,4).

StartOccupancyFeasible?Reason
0 h[0,2)NoOverlaps downtime
2 h[2,4)NoInsufficient capacity in the second half
4 h[4,6)YesEnough capacity throughout

Reuse the first-lesson at/q helpers and resource IDs, passing downtime and capacity overrides explicitly to ActivityResource. With half-open intervals, a start at hour 4 does not occupy [3,4).

2. Attach Calendars to Resources ​

Build the Activity and Its Calendar ​

The full function defines at relative to one time origin and q as dimensionless capacity. Resource availability, reservation quantity and allowed starts are constructed together, matching all three rows in the table.

kt
val resource = ActivityResource(machine, q(2.0),
    unavailableTimes = listOf(TimeRange(at(1), at(2))),
    capacities = listOf(ActivityCapacity(TimeRange(at(3), at(4)), q(1.0))))
val task = Activity(Task("a"), listOf(ActivityMode("normal", 2.hours,
    listOf(at(0), at(2), at(4)), listOf(ActivityResourceUse(machine, q(2.0))), q(0.0))))
rs
let resource = ActivityResource { id: executor_id("machine"), capacity: q(2.0),
    unavailable_times: vec![TimeRange::new(at(1), at(2))],
    capacities: vec![ActivityCapacity { time: TimeRange::new(at(3), at(4)), capacity: q(1.0) }] };
let mode = ActivityMode { id: "normal".into(), duration: Duration::hours(2), starts: vec![at(0), at(2), at(4)],
    resources: vec![ActivityResourceUse { resource: executor_id("machine"), quantity: q(2.0), from: Duration::ZERO, until: None }],
    cost: q(0.0), material_flows: vec![] };
let task = Activity { id: task_id("a"), modes: vec![mode], cancellation_cost: None };
MeaningKotlinRust
DowntimeActivityResource.unavailableTimesActivityResource.unavailable_times
Varying capacityActivityResource.capacitiesActivityResource.capacities
Relative phase occupancyActivityResourceUseActivityResourceUse
Execution factsActivityExecutionActivityExecution
Baseline/frozen choicesActivityBaselineActivityBaseline

Equipment and technicians may occupy only parts of an activity. Do not lock every resource for the entire activity for convenience, or check only availability at the start. Occupancy phases must match the business.

Inside the first-lesson runExample, use this as the machine entry in problem.resources. The at/q helpers and machine ID are defined by that function:

kotlin
val calendarResource = ActivityResource(
    id = machine, capacity = q(2.0),
    unavailableTimes = listOf(TimeRange(at(1), at(2))),
    capacities = listOf(ActivityCapacity(TimeRange(at(3), at(4)), q(1.0)))
)

3. Separate Three Rolling-Horizon Inputs ​

Let now be 0 h. A running activity started at -1 h, finishes at 2 h and occupies future equipment on [0,2). A completed activity ran from -3 to -2 h. Other activities remain decisions.

  • Execution facts: retain original times/status; supply remaining future occupancy instead of rescheduling the whole running activity from 0 h.
  • Frozen choices: committed starts/modes are hard restrictions. New downtime conflicting with them must yield a conflict/infeasibility, not a silent move for lower cost.
  • Adjustable baselines: changes are allowed with configured adjustment costs. A baseline is not an execution fact and does not create new allowed starts.

Pass actual execution records through executions and committed or adjustable choices through baselines, retaining consistent task IDs in dependencies. Do not put completed work back into pending activities or charge full running occupancy again in the future window.

Keep the Entry, Separate Domain from Budget ​

Pass this problem to the activity service from the first lesson. No column-generation switch is involved. starts defines allowed business choices, not search truncation. Configure native time/node limits on the actual backend and retain time limits and feasible solutions.

kt
suspend fun runBusiness(solver: ColumnGenerationSolver) =
    ActivitySchedulingApplicationService(solver, schedulingSolverValueAdapter).solve(makeProblem())
rs
let report = ActivitySchedulingApplicationService::new(solver)
    .solve(|| Ok(context), FrameworkSolveOptions::default()).map_err(|e| format!("{e:?}"))?;
println!("{report:?}");

4. Make Two Controlled Changes ​

Minimal Extension: A Late-Start Surcharge ​

Add a fee of 2 for starts at or after 4 h. Kotlin injects additionalCost into the problem; the Rust closure implements ActivityCostPolicy and is supplied when creating the context. Capacity remains hard; the surcharge only ranks legal choices.

kt
val lateStartFee: (ActivityPlacement<Flt64>) -> fuookami.ospf.kotlin.utils.functional.Ret<Quantity<Flt64>> = { placement ->
    fuookami.ospf.kotlin.utils.functional.Ok(q(if (placement.key.start >= at(4)) 2.0 else 0.0))
}
return ActivitySchedulingProblem(horizon = TimeRange(at(0), at(6)), activities = listOf(task),
    resources = listOf(resource), costUnit = NoneUnit, additionalCost = lateStartFee)
rs
let late_start_fee = |p: &ActivityPlacement<f64>| -> ospf_rust_framework_gantt_scheduling::GanttResult<_> {
    let late = p.key.start >= OffsetDateTime::UNIX_EPOCH + Duration::hours(4);
    Ok(Quantity::new(if late { 2.0 } else { 0.0 }, NoneUnit::INSTANT.clone()))
};
let context = ActivitySchedulingContext::new(make_problem(), &F64SolverValueAdapter,
    Some(&late_start_fee), Default::default()).map_err(|e| format!("{e:?}"))?;
  1. Remove the 4 h start from the calendar example. A mandatory non-cancellable activity has no feasible candidate; do not invent a 6 h start or automatic pause/resume.
  2. Restore starts, add a frozen choice, then overlap it with downtime. Keep normal infeasibility distinct from technical input failure, and establish who may authorize unfreezing.

New starts, alternative resources and cancellation are different business decisions. Configure and validate them separately. Cancellation also requires dependency and material-event checks, not just removing a chart bar.

5. Validate Recovery Before Delivery ​

Retain completed facts, original running times and remaining occupancy. Preserve frozen choices, restrict adjustable activities to allowed candidates, validate resources/dependencies/inventory throughout, and recompute adjustment costs. A feasible solution found before a time limit retains its real status.

Use input revisions/request IDs so old results cannot overwrite newer facts. Continue with rolling optimization and the integration guide.

Repository regression commands live in Verification. Complete the business input, call and result checks before using them.

Complete Application Sources ​

The snippets come from the same source files. Keep imports and helpers, then call runBusiness / run_business from your application. Constructors can also be used independently for input validation. Reuse first-lesson backend dependencies; these functions do not create an implicit backend.

Full Kotlin / Rust sources
kt
@file:OptIn(kotlin.time.ExperimentalTime::class)
package docs.examples.gantt.business

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.*

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

fun makeProblem(): ActivitySchedulingProblem<Flt64> {
    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 machine = Resource("machine")
    // #region input
    val resource = ActivityResource(machine, q(2.0),
        unavailableTimes = listOf(TimeRange(at(1), at(2))),
        capacities = listOf(ActivityCapacity(TimeRange(at(3), at(4)), q(1.0))))
    val task = Activity(Task("a"), listOf(ActivityMode("normal", 2.hours,
        listOf(at(0), at(2), at(4)), listOf(ActivityResourceUse(machine, q(2.0))), q(0.0))))
    // #endregion input
    // #region rule
    val lateStartFee: (ActivityPlacement<Flt64>) -> fuookami.ospf.kotlin.utils.functional.Ret<Quantity<Flt64>> = { placement ->
        fuookami.ospf.kotlin.utils.functional.Ok(q(if (placement.key.start >= at(4)) 2.0 else 0.0))
    }
    return ActivitySchedulingProblem(horizon = TimeRange(at(0), at(6)), activities = listOf(task),
        resources = listOf(resource), costUnit = NoneUnit, additionalCost = lateStartFee)
    // #endregion rule
}

// #region entry
suspend fun runBusiness(solver: ColumnGenerationSolver) =
    ActivitySchedulingApplicationService(solver, schedulingSolverValueAdapter).solve(makeProblem())
// #endregion entry
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 make_problem() -> ActivitySchedulingProblem<f64> {
    let at = |h| OffsetDateTime::UNIX_EPOCH + Duration::hours(h);
    let q = |value| Quantity::new(value, NoneUnit::INSTANT.clone());
    // #region input
    let resource = ActivityResource { id: executor_id("machine"), capacity: q(2.0),
        unavailable_times: vec![TimeRange::new(at(1), at(2))],
        capacities: vec![ActivityCapacity { time: TimeRange::new(at(3), at(4)), capacity: q(1.0) }] };
    let mode = ActivityMode { id: "normal".into(), duration: Duration::hours(2), starts: vec![at(0), at(2), at(4)],
        resources: vec![ActivityResourceUse { resource: executor_id("machine"), quantity: q(2.0), from: Duration::ZERO, until: None }],
        cost: q(0.0), material_flows: vec![] };
    let task = Activity { id: task_id("a"), modes: vec![mode], cancellation_cost: None };
    // #endregion input
    ActivitySchedulingProblem { horizon: TimeRange::new(at(0), at(6)), activities: vec![task], resources: vec![resource],
        dependencies: vec![], baselines: vec![], executions: vec![], rows: vec![], cost_unit: NoneUnit::INSTANT.clone(),
        materials: vec![], material_events: vec![] }
}

pub fn run_business<S: ColumnGenerationSolver>(solver: S) -> Result<(), String> {
    // #region rule
    let late_start_fee = |p: &ActivityPlacement<f64>| -> ospf_rust_framework_gantt_scheduling::GanttResult<_> {
        let late = p.key.start >= OffsetDateTime::UNIX_EPOCH + Duration::hours(4);
        Ok(Quantity::new(if late { 2.0 } else { 0.0 }, NoneUnit::INSTANT.clone()))
    };
    let context = ActivitySchedulingContext::new(make_problem(), &F64SolverValueAdapter,
        Some(&late_start_fee), Default::default()).map_err(|e| format!("{e:?}"))?;
    // #endregion rule
    // #region entry
    let report = ActivitySchedulingApplicationService::new(solver)
        .solve(|| Ok(context), FrameworkSolveOptions::default()).map_err(|e| format!("{e:?}"))?;
    println!("{report:?}");
    // #endregion entry
    Ok(())
}