Skip to content

Your First 2D Layout: Start with Rectangles ​

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

1. Business Scenario ​

Place R1 (4 × 3 m, six pieces) and R2 (2 × 2 m, eight pieces) on 20 × 12 m standard sheets. Rotation is allowed and kerf is zero. Each piece weighs 1 kg and a sheet carries up to 10000 kg.

Net area is 104 m² versus 240 m² per sheet. Sufficient area does not prove geometric feasibility. Keep IDs consistent across the catalogue, demands and sheet types; equal dimensions do not merge separate orders.

2. Construct Input and Call the Framework ​

Kotlin and Rust Entry Points

The Kotlin example constructs items, sheet types and the request before calling the public service. The Rust example is an explicit integration boundary: the caller supplies domain input plus real restricted-master and final-integer adapters; it is not a standalone optimizer. The current Rust service is fixed to f64 + Meter and shares a unit type between weight and length. Handle this unit limitation explicitly in the application adapter. StandardRmpSolver and StandardFinalSolver wrap closures; they do not automatically implement a SCIP backend.

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

kt
package docs.examples.bpp2d

import fuookami.ospf.kotlin.math.algebra.number.*
import fuookami.ospf.kotlin.quantities.quantity.times
import fuookami.ospf.kotlin.quantities.unit.*
import fuookami.ospf.kotlin.framework.solver.ColumnGenerationSolver
import fuookami.ospf.kotlin.framework.geometry2d.*
import fuookami.ospf.kotlin.framework.bpp2d.domain.item.model.*
import fuookami.ospf.kotlin.framework.bpp2d.application.service.*
import fuookami.ospf.kotlin.utils.functional.*

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}" })
}

suspend fun runExample(solver: ColumnGenerationSolver) {
    fun rectangle(id: String, width: Double, height: Double) = ActualItem(
        id = ItemId(id), name = id,
        shape = rectangleShape2(FltX(width) * Meter, FltX(height) * Meter).getOrThrow(),
        allowRotate = true, weight = FltX.one * Kilogram
    )
    val items = listOf(rectangle("R1", 4.0, 3.0) to UInt64(6), rectangle("R2", 2.0, 2.0) to UInt64(8))
    val sheet = SheetType(
        width = FltX(20.0) * Meter, height = FltX(12.0) * Meter,
        maxLoad = FltX(10000.0) * Kilogram, typeCode = SheetTypeId("STD"), isMain = true
    )
    val request = ColumnGenerationApplicationRequest(
        items = items.toMap(), itemCatalog = items.associate { it.first.id to it.first },
        sheetTypes = listOf(sheet), iterationLimit = 12, maxColumnsPerIteration = 12
    )
    val response = ColumnGenerationApplicationService(solver = solver).solve(request).getOrThrow()
    val packing = response.packing ?: error("No deliverable packing; inspect the solve result")
    val bins = packing.aggregation.bins
    val counts = bins.flatMap { it.items }.groupingBy { it.placement.itemId }.eachCount()
    // #region result
    println("final=${response.result.finalSolved}, limited=${response.result.terminatedByIterationLimit}")
    println("kpi=${response.kpi}, placed=$counts")
    for (bin in bins) {
        println("sheet=${bin.name}, type=${bin.type.typeCode}")
        for (item in bin.items) {
            val p = item.placement
            println("${p.itemId}: (${p.x}, ${p.y}) -> (${p.maxX().getOrThrow()}, ${p.maxY().getOrThrow()}), rotated=${p.rotated}")
        }
    }
    packing.remnants.forEach { println("${it.sheetName}: free=${it.rectangle}, area=${it.area}") }
    // #endregion result
    for ((item, demand) in items) {
        check(UInt64(counts[item.id.value] ?: 0) == demand) { "Demand mismatch: ${item.id}" }
    }
}
rs
use ospf_rust_base::error::Ret;
use ospf_rust_framework_bpp2d::application::{
    algorithm::{ColumnGenerationFinalSolver, ColumnGenerationRmpSolver},
    config::ColumnGenerationConfig,
    service::ColumnGenerationApplicationService,
    state::{ColumnGenerationInput, ColumnGenerationResult},
};
use ospf_rust_quantities::unit::Meter;

// The caller supplies normalized domain input and BOTH real solver adapters.
// This is an application boundary, not a standalone optimizer implementation.
pub fn solve_layout(
    input: ColumnGenerationInput<f64, Meter>,
    rmp: Box<dyn ColumnGenerationRmpSolver>,
    final_solver: Box<dyn ColumnGenerationFinalSolver>,
) -> Ret<ColumnGenerationResult<f64, Meter>> {
    let demands: Vec<_> = input.items.iter().map(|(item, count)| (item.id.clone(), *count as u64)).collect();
    let result = ColumnGenerationApplicationService::new().solve(
        input, &ColumnGenerationConfig::default(), Some(rmp), Some(final_solver),
    )?;
    println!("lp solves={}, final solved={}", result.lp_solved_times, result.final_solved);
    // #region result
    println!("limited={}, objective={:?}", result.terminated_by_iteration_limit, result.final_objective);
    if let Some(packing) = &result.packing {
        println!("counts={:?}, occupied={:?}, remnants={:?}", packing.item_amounts(), packing.occupied_area(), packing.remnant_area());
        for sheet in &packing.sheets {
            println!("sheet={}, type={:?}", sheet.name, sheet.sheet_type.type_code);
            for item in &sheet.items {
                let p = &item.placement;
                println!("{:?}: ({:?}, {:?}) -> ({:?}, {:?}), rotated={}", p.item_id, p.x(), p.y(), p.max_x()?, p.max_y()?, p.rotated);
            }
            for free in &sheet.remnants { println!("free={:?}, area={:?}", free.rectangle, free.area); }
        }
        let counts = packing.item_amounts();
        for (id, demand) in demands { assert_eq!(counts.get(&id).copied().unwrap_or(0), demand, "Demand mismatch: {id:?}"); }
    }
    // #endregion result
    Ok(result)
}

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.bpp2d.runExample
import kotlinx.coroutines.runBlocking
import fuookami.ospf.kotlin.core.solver.gurobi.GurobiColumnGenerationSolver

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

Use Rust solve_layout as the application boundary after implementing input normalization and both restricted-master and final-integer adapters. This lesson does not provide a standalone native Rust BPP2D adapter; None, None or hand-filled prices/usages are not substitutes.

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
Enabled sheets and itemspacking.aggregation.bins → name / type / itemspacking.sheets → name / sheet_type / items
Coordinates and rotationplacement.x / y / maxX() / maxY() / rotatedplacement.x() / y() / max_x() / max_y() / rotated
Remnants and KPIspacking.remnants, response.kpisheet.remnants, packing.item_amounts() / occupied_area() / remnant_area()
Termination scoperesponse.result.finalSolved / terminatedByIterationLimit / terminatedByTimeLimitresult.final_solved / terminated_by_iteration_limit / terminated_by_time_limit

Result Semantics

This entry has no complete field. Final execution and budget flags describe the run; validate actual geometry and exact demand separately. Remnants are free rectangles associated with sheet names, not stocked inventory.

Confirm both LP and final integer execution, then count exactly R1=6 and R2=8. Check boundaries, pairwise non-overlap, allowed rotation and spacing. The example count check is only the first delivery gate, not geometric verification or a global optimality proof.

5. Change One Business Condition ​

Disable rotation for R1 only and compare candidates and coordinates. Add positive kerf in a separate iteration so you can explain which condition changed the result.

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