Skip to content

Sheet Types, Rotation and Spacing ​

After your first 2D layout, separate geometry, material consumption and cost with four items. Replace the first-lesson items and sheet types with this input.

1. Two Sheets and One Rectangle Type ​

ObjectDimensions / amountPrice
R2 × 2 m, four pieces—
S4 × 4 m, at least one available5
L5 × 5 m, at least one available3

Use ample weight capacity, no rotation and zero spacing first. Four items fit an exact 2×2 grid on S and also fit on L. Pure area consumption favors S (16 m²); pure purchase cost favors L (3). Minimum sheet count cannot distinguish them.

Set spacing to 0.2 m: two items need 2 + 0.2 + 2 = 4.2 m per row. S loses the 2×2 layout while L remains feasible. Total item area of 16 m² does not establish fit; four axis-aligned 2×2 squares have no alternative four-piece layout with positive gaps on a 4×4 sheet either.

2. Send Every Sheet Type to Generation ​

Construct This Lesson’s Request ​

makeRequest / make_input builds R×4 and sheet types S/L, explicitly binding geometry to metres. Kotlin binds load to kilograms separately. Change spacing to 0.2 and solve again.

kt
val part = ActualItem(ItemId("R"), "part", rectangleShape2(FltX(2.0) * Meter, FltX(2.0) * Meter).getOrThrow(),
    allowRotate = false, weight = FltX.one * Kilogram)
fun sheet(id: String, side: Double) = SheetType(FltX(side) * Meter, FltX(side) * Meter,
    FltX(100.0) * Kilogram, SheetTypeId(id), isMain = true)
val request = ColumnGenerationApplicationRequest(items = mapOf(part to UInt64(4)), itemCatalog = mapOf(part.id to part),
    sheetTypes = listOf(sheet("S", 4.0), sheet("L", 5.0)), kerf = FltX(spacing) * Meter)
rs
let part = ActualItem::new(ItemId::new("R"), "part", PackingShape2::Rectangle(rectangle_shape2(m(2.0), m(2.0))?), false, m(0.0));
let small = SheetType::new(m(4.0), m(4.0), m(0.0), SheetTypeId::new("S"));
let large = SheetType::new(m(5.0), m(5.0), m(0.0), SheetTypeId::new("L"));
Ok(ColumnGenerationInput { sheet: small.clone(), sheets: vec![small.clone(), large], items: vec![(part, 4)],
    demands: vec![Bpp2dAssignmentDemandEntry::item_amount("R", 4)], kerf: Some(m(spacing)),
    sheet_shape: small.geometry(), item_catalog: [(ItemId::new("R"), false)].into_iter().collect() })

Rust Unit Boundary

The current Rust interface shares a unit type between weight and length. This example is geometry-only with zero weight/load; it does not provide type-safe kilogram modeling. Production load handling needs explicit normalization and independent unit checks.

Put Costs in Objective Configuration ​

kt
return if (!costObjective) request else request.copy(executorConfig = ColumnGenerationStandardExecutorConfig(
    sheetAreaWeight = FltX.zero, sheetAmountWeight = FltX.zero, sheetTypeCostWeight = FltX.one,
    sheetTypeCosts = mapOf(SheetTypeId("S") to FltX(5.0), SheetTypeId("L") to FltX(3.0))))
rs
pub fn cost_config() -> ospf_rust_framework_bpp2d::application::service::ColumnGenerationStandardExecutorConfig {
    ospf_rust_framework_bpp2d::application::service::ColumnGenerationStandardExecutorConfig {
        sheet_area_weight: 0.0, sheet_amount_weight: 0.0, sheet_type_cost_weight: 1.0,
        sheet_type_costs: [(SheetTypeId::new("S"), 5.0), (SheetTypeId::new("L"), 3.0)].into_iter().collect(),
        ..Default::default()
    }
}

Kotlin passes configuration through request.executorConfig. Supply Rust cost_config() to the application’s standard executor adapters; run_business receives those configured restricted-master and final-integer adapters rather than creating a backend.

ResponsibilityKotlinRust
Multiple typesBpp2dLayerGenerationRequest.sheetsSheet collection on Bpp2dLayerGenerationRequest
Candidate identityLayer.sheet retains its typeEach candidate retains its actual sheet type
SpacingRequest kerfRequest with_kerf(...)
ObjectiveArea, count and per-type cost pipelinesCorresponding area, count and type-cost pipelines

The primary/default sheet does not replace the full sheets collection. Identical coordinates on S and L are different columns: do not deduplicate by coordinates alone.

Use the first-lesson item constructors, create S and L sheet types and pass both into the request. Wire cost into the master objective rather than only adding prices to an output table.

3. Check the Spacing Path Separately ​

After changing spacing, regenerate candidates, solve again and independently measure actual edge-to-edge gaps. Fewer candidates do not prove every placement has legal spacing.

Entry and Generation Budget ​

This service already uses column generation. Bound iterations and columns per round; these are neither exhaustive-enumeration evidence nor backend node limits.

kt
val bounded = request.copy(iterationLimit = 12, maxColumnsPerIteration = 24, finalMilpEnabled = true)
rs
let config = ColumnGenerationConfig { iteration_limit: 12, max_columns_per_iteration: 24,
    time_limit_ms: 30_000, final_milp_enabled: true, ..Default::default() };

4. Add Approval Rules, Then Isolate Rotation ​

Minimal Extension: Approved Sheet Types ​

Suppose L is not approved for purchase. Wrap generation to reject L. Kotlin injects the wrapper through algorithmFactory and applies it to both initial candidates and later generation, so initial columns cannot bypass the rule.

kt
class ApprovedSheets(private val delegate: Bpp2dLayerGenerator<FltX>) : Bpp2dLayerGenerator<FltX> {
    override fun generate(request: Bpp2dLayerGenerationRequest<FltX>) =
        delegate.generate(request).filter { it.layer.sheet?.typeCode == SheetTypeId("S") }
}
rs
struct ApprovedSheets;
impl Bpp2dLayerGenerator<f64, Meter> for ApprovedSheets {
    fn name(&self) -> &str { "approved-sheets" }
    fn generate(&self, request: &Bpp2dLayerGenerationRequest<f64, Meter>) -> Vec<Bpp2dLayerGenerationResult<f64, Meter>> {
        LayerGenerationContext::new().generate(request, &LayerGenerationContext::default_generators())
            .into_iter().filter(|c| c.layer.sheet.as_ref().is_some_and(|s| s.type_code == SheetTypeId::new("S"))).collect()
    }
}

Injection point:

kt
val service = if (!restrictSheets) ColumnGenerationApplicationService(solver) else
    ColumnGenerationApplicationService(solver, algorithmFactory = { req, executors ->
        val generator = ApprovedSheets(LayerGenerationContext<FltX>())
        ColumnGenerationAlgorithm(layerGenerator = generator, rmpSolver = executors.rmpSolver(),
            finalMilpSolver = executors.finalSolver(), layerRequestBuilder = executors.requestBuilder(),
            filterByReducedCostWithResult = executors.reducedCostFilter(), initialColumnsWithResult = {
                val seed = executors.requestBuilder().build(ColumnGenerationState(iteration = 0, columns = emptyList()),
                    ColumnGenerationConfig(maxColumnsPerIteration = req.maxColumnsPerIteration))
                Ok(generator.generate(seed).map { it.layer })
            })
    })
val response = service.solve(bounded).getOrThrow()
rs
let algorithm = ColumnGenerationAlgorithm::new(Box::new(ApprovedSheets), input.demands.clone())
    .with_rmp_solver(rmp).with_final_solver(final_solver);
let request = Bpp2dLayerGenerationRequest::new(0, input.items)
    .with_sheets(input.sheets).with_kerf(input.kerf.clone().unwrap()).with_max_candidates(24);
let mut result = algorithm.solve(request, &config)?;
let analyzer = ColumnGenerationPackingAnalyzer::new();
let packing = analyzer.analyze(&result, input.kerf.as_ref())?;
result.render = Some(analyzer.render(&packing));
result.packing = Some(packing);

Rust injects generation into the lower-level algorithm and explicitly runs the packing analyzer. The final adapter must preserve sheet-type identity. A per-candidate approval rule is not a cross-sheet purchase-budget constraint.

Use one 3 × 2 m sheet and one 2 × 3 m rectangle with zero spacing. It fits with 90° rotation and does not fit without rotation. This isolates allowRotate; a square cannot demonstrate the difference.

5. Business Acceptance ​

  • At zero spacing, a pure area objective favors S and pure cost favors L. With weighted objectives, recompute the configured score instead of retaining both single-objective expectations.
  • Regenerate, solve and validate after a spacing change; moving coordinates in a picture does not enforce a rule.
  • Stock/procurement limits require real master-model constraints. A catalog of sheet types is not modeled stock.
  • Report net item area, consumed sheet area, free regions and reusable remnants separately. Reuse needs business rules such as minimum width/height.

Continue to CSP2D process requirements for a guillotine tree, not a renamed BPP2D layout. Complete the integration checks before delivering business results.

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
package docs.examples.bpp2d.business

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.domain.layer_generation.*
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.message)
    is Fatal -> error(errors.joinToString { it.message })
}

fun makeRequest(costObjective: Boolean = false, spacing: Double = 0.0): ColumnGenerationApplicationRequest {
    // #region input
    val part = ActualItem(ItemId("R"), "part", rectangleShape2(FltX(2.0) * Meter, FltX(2.0) * Meter).getOrThrow(),
        allowRotate = false, weight = FltX.one * Kilogram)
    fun sheet(id: String, side: Double) = SheetType(FltX(side) * Meter, FltX(side) * Meter,
        FltX(100.0) * Kilogram, SheetTypeId(id), isMain = true)
    val request = ColumnGenerationApplicationRequest(items = mapOf(part to UInt64(4)), itemCatalog = mapOf(part.id to part),
        sheetTypes = listOf(sheet("S", 4.0), sheet("L", 5.0)), kerf = FltX(spacing) * Meter)
    // #endregion input
    // #region objective
    return if (!costObjective) request else request.copy(executorConfig = ColumnGenerationStandardExecutorConfig(
        sheetAreaWeight = FltX.zero, sheetAmountWeight = FltX.zero, sheetTypeCostWeight = FltX.one,
        sheetTypeCosts = mapOf(SheetTypeId("S") to FltX(5.0), SheetTypeId("L") to FltX(3.0))))
    // #endregion objective
}

// #region rule
class ApprovedSheets(private val delegate: Bpp2dLayerGenerator<FltX>) : Bpp2dLayerGenerator<FltX> {
    override fun generate(request: Bpp2dLayerGenerationRequest<FltX>) =
        delegate.generate(request).filter { it.layer.sheet?.typeCode == SheetTypeId("S") }
}
// #endregion rule

suspend fun runBusiness(solver: ColumnGenerationSolver, restrictSheets: Boolean = false) {
    val request = makeRequest(costObjective = true)
    // #region entry
    val bounded = request.copy(iterationLimit = 12, maxColumnsPerIteration = 24, finalMilpEnabled = true)
    // #endregion entry
    // #region injection
    val service = if (!restrictSheets) ColumnGenerationApplicationService(solver) else
        ColumnGenerationApplicationService(solver, algorithmFactory = { req, executors ->
            val generator = ApprovedSheets(LayerGenerationContext<FltX>())
            ColumnGenerationAlgorithm(layerGenerator = generator, rmpSolver = executors.rmpSolver(),
                finalMilpSolver = executors.finalSolver(), layerRequestBuilder = executors.requestBuilder(),
                filterByReducedCostWithResult = executors.reducedCostFilter(), initialColumnsWithResult = {
                    val seed = executors.requestBuilder().build(ColumnGenerationState(iteration = 0, columns = emptyList()),
                        ColumnGenerationConfig(maxColumnsPerIteration = req.maxColumnsPerIteration))
                    Ok(generator.generate(seed).map { it.layer })
                })
        })
    val response = service.solve(bounded).getOrThrow()
    // #endregion injection
    println("kpi=${response.kpi}, final=${response.result.finalInfo}")
}
rs
use ospf_rust_base::error::Ret;
use ospf_rust_framework_geometry2d::{rectangle_shape2, PackingShape2};
use ospf_rust_quantities::{Quantity, unit::Meter};
use ospf_rust_framework_bpp2d::application::{algorithm::*, config::ColumnGenerationConfig,
    state::{ColumnGenerationInput, ColumnGenerationResult}, service::ColumnGenerationPackingAnalyzer};
use ospf_rust_framework_bpp2d::domain::{item::model::*, layer_generation::*, layer_assignment::Bpp2dAssignmentDemandEntry};

// Pass this configuration to the application's standard executor adapters.
// #region objective
pub fn cost_config() -> ospf_rust_framework_bpp2d::application::service::ColumnGenerationStandardExecutorConfig {
    ospf_rust_framework_bpp2d::application::service::ColumnGenerationStandardExecutorConfig {
        sheet_area_weight: 0.0, sheet_amount_weight: 0.0, sheet_type_cost_weight: 1.0,
        sheet_type_costs: [(SheetTypeId::new("S"), 5.0), (SheetTypeId::new("L"), 3.0)].into_iter().collect(),
        ..Default::default()
    }
}
// #endregion objective

// Geometric input only: the current application seam shares U for weight and length.
pub fn make_input(spacing: f64) -> Ret<ColumnGenerationInput<f64, Meter>> {
    let m = |value| Quantity::<f64, Meter>::new_ct(value);
    // #region input
    let part = ActualItem::new(ItemId::new("R"), "part", PackingShape2::Rectangle(rectangle_shape2(m(2.0), m(2.0))?), false, m(0.0));
    let small = SheetType::new(m(4.0), m(4.0), m(0.0), SheetTypeId::new("S"));
    let large = SheetType::new(m(5.0), m(5.0), m(0.0), SheetTypeId::new("L"));
    Ok(ColumnGenerationInput { sheet: small.clone(), sheets: vec![small.clone(), large], items: vec![(part, 4)],
        demands: vec![Bpp2dAssignmentDemandEntry::item_amount("R", 4)], kerf: Some(m(spacing)),
        sheet_shape: small.geometry(), item_catalog: [(ItemId::new("R"), false)].into_iter().collect() })
    // #endregion input
}

// #region rule
struct ApprovedSheets;
impl Bpp2dLayerGenerator<f64, Meter> for ApprovedSheets {
    fn name(&self) -> &str { "approved-sheets" }
    fn generate(&self, request: &Bpp2dLayerGenerationRequest<f64, Meter>) -> Vec<Bpp2dLayerGenerationResult<f64, Meter>> {
        LayerGenerationContext::new().generate(request, &LayerGenerationContext::default_generators())
            .into_iter().filter(|c| c.layer.sheet.as_ref().is_some_and(|s| s.type_code == SheetTypeId::new("S"))).collect()
    }
}
// #endregion rule

pub fn run_business(rmp: Box<dyn ColumnGenerationRmpSolver>, final_solver: Box<dyn ColumnGenerationFinalSolver>)
    -> Ret<ColumnGenerationResult<f64, Meter>> {
    let input = make_input(0.0)?;
    // #region entry
    let config = ColumnGenerationConfig { iteration_limit: 12, max_columns_per_iteration: 24,
        time_limit_ms: 30_000, final_milp_enabled: true, ..Default::default() };
    // #endregion entry
    // #region injection
    let algorithm = ColumnGenerationAlgorithm::new(Box::new(ApprovedSheets), input.demands.clone())
        .with_rmp_solver(rmp).with_final_solver(final_solver);
    let request = Bpp2dLayerGenerationRequest::new(0, input.items)
        .with_sheets(input.sheets).with_kerf(input.kerf.clone().unwrap()).with_max_candidates(24);
    let mut result = algorithm.solve(request, &config)?;
    let analyzer = ColumnGenerationPackingAnalyzer::new();
    let packing = analyzer.analyze(&result, input.kerf.as_ref())?;
    result.render = Some(analyzer.render(&packing));
    result.packing = Some(packing);
    // #endregion injection
    Ok(result)
}