Skip to content

Your First 1D Packing: Items, Gaps and Stock ​

Start with a small batch of bars and work through input, solving and business result extraction. Prepare dependencies and backends using Setup.

1. Business Scenario ​

Pack three bars, each 40 cm long and 2 kg. One small container is 1 m long with a 5 kg limit and cost 1; one large container is 2 m long with a 10 kg limit and cost 3. Leave 20 cm between adjacent items and minimize container count.

All three together require 3×40 cm+2×20 cm=160 cm=1.6 m and weigh 6 kg. Both length and weight exceed small's limits; large can carry them in one container.

Counts, Units and Zero Stock

Item amount is exact demand. Kotlin keeps mixed cm/m inputs and converts through its adapter; Rust normalizes to m/kg. Null stock (null / None) means unlimited; zero means unavailable.

2. Construct Input and Call the Framework ​

Kotlin calls Bpp1dMilp.solve. Rust creates a validated PackingContext and forwards the actual model, remaining time and cancellation handle to an injected LinearSolver.

The examples include imports and error handling. The application supplies a solver to runExample / run_example; the next section shows launchers.

kt
package docs.examples.bpp1d

import fuookami.ospf.kotlin.math.algebra.number.*
import fuookami.ospf.kotlin.quantities.quantity.*
import fuookami.ospf.kotlin.quantities.unit.*
import fuookami.ospf.kotlin.framework.solver.ColumnGenerationSolver
import fuookami.ospf.kotlin.framework.bpp.infrastructure.*
import fuookami.ospf.kotlin.framework.bpp1d.domain.item.model.*
import fuookami.ospf.kotlin.framework.bpp1d.application.*
import fuookami.ospf.kotlin.framework.bpp1d.domain.packing.*
import fuookami.ospf.kotlin.utils.functional.*

suspend fun runExample(solver: ColumnGenerationSolver) {
    val problem = PackingProblem(
        items = listOf(Item(
            id = "a", length = Quantity(Flt64(40), Centimeter),
            weight = Quantity(Flt64(2), Kilogram), amount = UInt64(3)
        )),
        binTypes = listOf(
            BinType("small", Quantity(Flt64(1), Meter), Quantity(Flt64(5), Kilogram), Flt64.one, UInt64.one),
            BinType("large", Quantity(Flt64(2), Meter), Quantity(Flt64(10), Kilogram), Flt64(3), UInt64.one)
        ),
        spacing = Quantity(Flt64(20), Centimeter),
        objective = PackingObjective.BinCount
    )
    when (val result = Bpp1dMilp(solver, Flt64PackingValueAdapter).solve(problem)) {
        is Ok -> {
            val solution = result.value
            // #region result
            println("status=${solution.status}, candidateComplete=${solution.candidateComplete}, objective=${solution.objective}")
            val packing = solution.packing
            packing.plans.forEach { plan ->
                println("bin=${plan.bin.id}, type=${plan.bin.type.id}")
                plan.placements.forEach { println("${it.itemId}: [${it.start}, ${it.start + it.length})") }
            }
            packing.remnants.forEach { println("tail ${it.binId}: [${it.start}, ${it.start + it.length})") }
            val kpi = packing.kpi(Meter).getOrThrow()
            println("bins=${kpi.binCount}, items=${kpi.itemCount}, cost=${kpi.cost}, utilization=${kpi.utilization}")
            println("consumed=${kpi.consumedLength}, tail=${kpi.remnantLength}")
            // #endregion result
            packing.plans.forEach { plan ->
                plan.placements.zipWithNext().forEach { (left, right) ->
                    println("spacing ${plan.bin.id}: [${left.start + left.length}, ${right.start})")
                }
            }
            val counts = packing.plans.flatMap { it.placements }.groupingBy { it.itemId }.eachCount()
            check(problem.items.all { UInt64((counts[it.id] ?: 0).toULong()) == it.amount })
        }
        is Failed -> error("${result.error.code}: ${result.error.message}")
        is Fatal -> error(result.errors.joinToString { "${it.code}: ${it.message}" })
    }
}

private fun <T> Ret<T>.getOrThrow(): T = when (this) {
    is Ok -> value
    is Failed -> error("${error.code}: ${error.message}")
    is Fatal -> error(errors.joinToString { "${it.code}: ${it.message}" })
}
rs
use std::collections::BTreeMap;
use std::time::Duration;
use ospf_rust_core::model::intermediate::LinearTriadModel;
use ospf_rust_core::solver::{LinearSolver, SolveHandle, SolveOptions};
use ospf_rust_framework_bpp::infrastructure::SameUnitPackingValueAdapter;
use ospf_rust_framework_bpp1d::application::Bpp1dMilp;
use ospf_rust_framework_bpp1d::domain::*;
use ospf_rust_quantities::{Quantity, unit::{Meter, Kilogram}};

pub fn run_example(solver: &dyn LinearSolver) -> Result<(), String> {
    let problem = PackingProblem {
        items: vec![Item {
            id: "a".into(), length: Quantity::<f64, Meter>::new_ct(0.4),
            weight: Quantity::<f64, Kilogram>::new_ct(2.0), amount: 3, materials: BTreeMap::new(),
        }],
        bin_types: vec![
            BinType { id: "small".into(), length: Quantity::new_ct(1.0), max_weight: Quantity::new_ct(5.0), cost: 1.0, inventory: Some(1) },
            BinType { id: "large".into(), length: Quantity::new_ct(2.0), max_weight: Quantity::new_ct(10.0), cost: 3.0, inventory: Some(1) },
        ],
        spacing: Quantity::new_ct(0.2), length_unit: Meter, weight_unit: Kilogram,
        objective: PackingObjective::BinCount,
    };
    let context = PackingContext::new(problem, &SameUnitPackingValueAdapter, &SameUnitPackingValueAdapter)
        .map_err(|e| format!("{e:?}"))?;
    let solve = |model: &LinearTriadModel, remaining: Duration, handle: &SolveHandle| {
        solver.solve_linear_report_with_options(model, &SolveOptions {
            time_limit: Some(remaining), cancellation_handle: Some(handle), ..Default::default()
        })
    };
    let result = Bpp1dMilp::solve(context.clone(), Default::default(), &SolveHandle::new(), solve)
        .map_err(|e| format!("{e:?}"))?;
    println!("report={:?}, globally_optimal={}", result.report, result.globally_optimal);
    if let Some(packing) = &result.packing {
        // #region result
        println!("candidate_complete={}", result.candidate_complete);
        for plan in &packing.plans {
            let bin_type = context.problem().bin_types.iter().find(|b| b.id == plan.bin_type_id).ok_or("Unknown bin type")?;
            println!("bin={}, type={}", plan.bin_id, bin_type.id);
            for p in &plan.placements { println!("{}: [{}, {}) m", p.item_id, p.start.value, p.start.value + p.length.value); }
        }
        for f in &packing.free_intervals { println!("free {}: [{}, {}) m", f.bin_id, f.start.value, f.start.value + f.length.value); }
        let kpi = context.kpi(packing).map_err(|e| format!("{e:?}"))?;
        println!("bins={}, items={}, cost={}, utilization={}", kpi.bin_count, kpi.item_count, kpi.cost, kpi.utilization);
        println!("consumed={} m, tail={} m", kpi.consumed_length.value, kpi.remnant_length.value);
        // #endregion result
        let mut counts = BTreeMap::<&str, u64>::new();
        for p in packing.plans.iter().flat_map(|plan| &plan.placements) {
            *counts.entry(p.item_id.as_str()).or_default() += 1;
        }
        if !context.problem().items.iter().all(|item| counts.get(item.id.as_str()).copied().unwrap_or(0) == item.amount) {
            return Err("Packed item counts differ from demand".into());
        }
    } else {
        println!("No packing; inspect the solve report");
    }
    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.bpp1d.runExample
import kotlinx.coroutines.runBlocking
import fuookami.ospf.kotlin.core.solver.gurobi.GurobiColumnGenerationSolver

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

Place the Rust example in src/bpp1d.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 bpp1d;
use ospf_rust_core::solver::solvers::scip::SCIPSolver;

fn main() -> Result<(), String> {
    bpp1d::run_example(&SCIPSolver::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 ​

The key extraction below is already included in section 2. Kotlin runs it in the Ok branch; Rust runs it in Some(packing) and retains the original context for type lookup and KPIs.

kt
println("status=${solution.status}, candidateComplete=${solution.candidateComplete}, objective=${solution.objective}")
val packing = solution.packing
packing.plans.forEach { plan ->
    println("bin=${plan.bin.id}, type=${plan.bin.type.id}")
    plan.placements.forEach { println("${it.itemId}: [${it.start}, ${it.start + it.length})") }
}
packing.remnants.forEach { println("tail ${it.binId}: [${it.start}, ${it.start + it.length})") }
val kpi = packing.kpi(Meter).getOrThrow()
println("bins=${kpi.binCount}, items=${kpi.itemCount}, cost=${kpi.cost}, utilization=${kpi.utilization}")
println("consumed=${kpi.consumedLength}, tail=${kpi.remnantLength}")
rs
println!("candidate_complete={}", result.candidate_complete);
for plan in &packing.plans {
    let bin_type = context.problem().bin_types.iter().find(|b| b.id == plan.bin_type_id).ok_or("Unknown bin type")?;
    println!("bin={}, type={}", plan.bin_id, bin_type.id);
    for p in &plan.placements { println!("{}: [{}, {}) m", p.item_id, p.start.value, p.start.value + p.length.value); }
}
for f in &packing.free_intervals { println!("free {}: [{}, {}) m", f.bin_id, f.start.value, f.start.value + f.length.value); }
let kpi = context.kpi(packing).map_err(|e| format!("{e:?}"))?;
println!("bins={}, items={}, cost={}, utilization={}", kpi.bin_count, kpi.item_count, kpi.cost, kpi.utilization);
println!("consumed={} m, tail={} m", kpi.consumed_length.value, kpi.remnant_length.value);

A one-container plan uses large. With coordinates normalized to meters, inspect:

FieldExpected value
Item intervalsa: [0, 0.4), [0.6, 1.0), [1.2, 1.6)
Internal gaps[0.4, 0.6), [1.0, 1.2)
Tail[1.6, 2.0), length 0.4 m
KPIs1 container, 3 items, consumed container length 2 m, cost 3, utilization 0.6

Free Intervals and Completeness

Kotlin's remnants contains tails only; the full example derives internal gaps with placements.zipWithNext(). Rust's free_intervals includes both. Required gaps are reserved space, not freely reusable capacity. candidateComplete / candidate_complete describes enumeration; combine it with status/report to interpret optimality.

The full example also groups placements by item ID and compares every count with input amount. Preserve container type IDs, item intervals, KPIs and solve status in your application DTO for execution and traceability.

5. Change One Business Condition ​

Set large inventory to zero. The remaining small container cannot cover three items; report no complete feasible packing rather than reuse the previous result. Restore stock, switch to Cost, and compare cost with container count.

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