Skip to content

Bin Types and Objectives ​

After your first 3D loading connects final selection and packing analysis, introduce a second bin type. This exercise uses cubes so orientation complexity does not hide objective configuration.

1. A Scenario That Separates Objectives ​

Load ten 2 × 2 × 2 m cubes, net volume 80 m³, with ample weight capacity and no extra spacing, support or balance rules:

TypeInner dimensionsVolumeAvailable binsCost per bin
S4 × 4 × 4 m64 m³24
L4 × 4 × 6 m96 m³110

S fits at most eight cubes. L fits twelve on a 2×2×3 grid, so one L or two S can carry demand. Consumed volume is 96 versus 128 m³; cost is 10 versus 8. Minimum count and volume favor L; minimum cost favors two S.

The following constructors make this scenario callable. Compare the selected physical bins with this calculation, then verify actual placements and full demand coverage.

2. Connect Three Multi-Type Responsibilities ​

Construct Requests from the Scenario ​

Kotlin reuses the first lesson’s makeItem(edge = 2.0), creates physical bins S/S/L and enumerates actual placements containing the first one, two, and then more items in grid order; see the full function below. Rust uses one record per carton and loads and converts metric geometry, bins and initial layers. Retain recorded quantities and independently count delivered placements.

kt
val item = makeItem(edge = 2.0)
fun bin(id: String, depth: Double) = BinType(width = FltX(4.0) * Meter, height = FltX(4.0) * Meter,
    depth = FltX(depth) * Meter, capacity = FltX(100.0) * Kilogram,
    longitudinalBalance = null, lateralBalance = null, typeCode = binTypeIdOf(id))
val small = bin("S", 4.0)
val large = bin("L", 6.0)
val physicalBins = if (smallOnly) listOf(small, small) else listOf(small, small, large)
rs
let mut csv = String::from("# table:items\nitem_id,name,shape_type,width,height,depth,weight,amount\n");
for i in 0..10 { csv.push_str(&format!("i{i},carton,cuboid,2,2,2,1,1\n")); }
csv.push_str("# table:bins\nbin_id,type_code,width,height,depth,capacity\ns1,S,4,4,4,100\ns2,S,4,4,4,100\nl1,L,4,4,6,100\n");
csv.push_str("# table:layers\nlayer_id,bin_id,depth\ns1-layer,s1,4\ns2-layer,s2,4\nl-layer,l1,6\n");
let mut request = CsvDatasetLoader::load_str(&csv).map_err(|e| format!("{e:?}"))?.materialize().map_err(|e| format!("{e:?}"))?;

Two Input Paths

Kotlin candidates contain real placements. Rust CSV layer rows contain initial-layer metadata; geometry still depends on executor generation and reconstruction. Layer-row counts are not deliverable bins. The metric Rust interface also shares the weight/length unit type, requiring separate weight normalization checks in production.

  1. Include every type in generation: Kotlin Bpp3dLayerGenerationRequest.bins; Rust LayerGenerationRequest.bins.
  2. Retain originating bin type in column identity. Identical coordinates on different types are different layers.
  3. Supply actual available final bins: Kotlin finalBins, and Rust's corresponding final-executor input. A type catalog does not mean unlimited physical bins; array indices should not become cross-request identities.

Set exact demand to ten for the same item ID. Follow the first lesson's request factory to keep demand representations, initial columns and final bins consistent. A small bin's capacity of eight is not the order quantity.

3. Configure Objectives Explicitly ​

MeaningKotlin fieldRust field
Consumed volume weightfinalBinVolumeWeightfinal_bin_volume_weight
Count coefficientfinalBinAmountCoefficientfinal_bin_amount_coefficient
Type-cost weightfinalBinTypeCostWeightfinal_bin_type_cost_weight
Type-cost mapfinalBinTypeCostsfinal_bin_type_costs

See the Kotlin standard executors and Rust executor configuration. Current defaults are volume weight 1, count coefficient 1e-6 and cost weight 0. Filling the cost map alone does not make cost dominate.

First isolate pure volume and pure cost. Then set the count coefficient to zero and explore normalized score = consumed_volume + λ × cost: L scores 96 + 10λ; two S score 128 + 8λ. They tie at λ=16; larger λ reverses the preference. Volume numbers here use m³, so define the weight's conversion convention.

A weighted sum is not strict volume-first, cost-second optimization. Such a requirement needs proven bounded weights or an explicitly evaluated staged optimization that fixes the first optimum. Do not claim default 1e-6 guarantees lexicographic priority at every scale.

Configure a Pure Cost Objective ​

kt
return if (!costObjective) request else request.copy(executorConfig = ColumnGenerationStandardExecutorConfig(
    finalBinVolumeWeight = FltX.zero, finalBinAmountCoefficient = FltX.zero, finalBinTypeCostWeight = FltX.one,
    finalBinTypeCosts = mapOf(small.typeCode to FltX(4.0), large.typeCode to FltX(10.0))))
rs
let final_config = MetaModelFinalExecutorConfig { final_bin_volume_weight: 0.0,
    final_bin_amount_coefficient: 0.0, final_bin_type_cost_weight: 1.0,
    final_bin_type_costs: [("S".into(), 4.0), ("L".into(), 10.0)].into_iter().collect(), ..Default::default() };

Entry and Generation Budget ​

Kotlin configures cgConfig on the request; Rust configures the service and also exposes a total-column cap. Both paths still require real restricted-master and final-integer backends.

kt
suspend fun runBusiness(solver: ColumnGenerationSolver) {
    val request = makeRequest(costObjective = true).copy(cgConfig = ColumnGenerationConfig(iterationLimit = 12, maxColumnsPerIteration = 24))
    val response = ColumnGenerationApplicationService(solver).solve(request, packingAnalyzer = ColumnGenerationPackingAnalyzer())
    println(response)
}
rs
let config = ColumnGenerationConfig::new().with_max_iterations(12)
    .with_max_column_amount(256).with_max_candidates_per_iteration(24);

4. Validate Packing, Not Candidate Volume ​

Minimal Rule: Only S Bins Are Approved ​

Kotlin smallOnly restricts physical bins, initial columns and generators together. The snippet shows the generator signature and request injection. Apply the restriction before optimization and audit delivered bins afterward.

kt
val generator = object : Bpp3dLayerGenerator<FltX> {
    override suspend fun generate(request: Bpp3dLayerGenerationRequest<FltX>) =
        layers.filter { !smallOnly || it.bin?.typeCode == small.typeCode }
            .map { Bpp3dLayerGenerationResult<FltX>(layer = it, source = "approved-grid") }
}
val request = ColumnGenerationApplicationRequest(itemDemands = listOf(item to UInt64(10)),
    initialColumns = layers, generators = listOf(generator),
    finalBins = physicalBins.map { layerBinOf(shape = it, units = emptyList()) })
rs
#[derive(Debug, Clone)]
struct SmallOnly;
impl PackingGeometryContract<f64, Meter> for SmallOnly {
    fn validate(&self, bin: &PackedBin<f64, Meter>) -> Result<(), Vec<String>> {
        PackingGeometryGuard::new().validate(bin)?;
        if bin.bin_type.type_code == "L" { Err(vec!["Only approved S bins may be delivered".into()]) } else { Ok(()) }
    }
}

Rust filters available types and initial candidates before solving, then adds delivery validation through the public geometry validation interface:

rs
let service = ColumnGenerationApplicationService::with_geometry_guard(config, SmallOnly);
let request = make_request(true)?;
let rmp = SolverBackedMetaModelRmpExecutor::new(MetaModelRmpExecutorConfig::default(), rmp_backend);
let final_executor = SolverBackedMetaModelFinalExecutor::new(final_config, final_backend);
let result = service.run_csv_materialized_with_bins(request, &rmp, &final_executor).map_err(|e| format!("{e:?}"))?;

Generation Rules Versus Delivery Guards

The custom geometry validator runs during packing analysis: rejection does not insert a constraint into the restricted master or pricing. The full source also restricts bins and initial candidates before solving. Model new mixing, cross-layer or total-budget rules in their generation/modeling paths, then audit them at delivery.

  • Place exactly ten items without counting one item through multiple selected layers.
  • Validate bounds, overlap, orientations, weight and enabled support rules on actual placements.
  • Recompute actual bin count, 96/128 m³ consumption and cost; unused volume is 16/48 m³ respectively.
  • Check restricted-master and final-integer extensions and backends, finalSolved or corresponding diagnostics, packing snapshots and placements together.

Record objective coefficients separately from solve scope. Correct coefficients do not establish a complete candidate pool or global optimality of the new scenario.

If one item cannot fit, inspect orientation and generation first. If layers exist but final packing fails, inspect physical bins, demand and cross-layer geometry. Preserve original diagnostics using the integration guide, rather than only increasing iterations.

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.bpp3d.business

import docs.examples.bpp3d.makeItem
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.bpp3d.infrastructure.*
import fuookami.ospf.kotlin.framework.bpp3d.domain.item.model.*
import fuookami.ospf.kotlin.framework.bpp3d.domain.layer_generation.*
import fuookami.ospf.kotlin.framework.bpp3d.application.service.*

private object Grid

fun makeRequest(costObjective: Boolean = false, smallOnly: Boolean = false): ColumnGenerationApplicationRequest {
    // #region input
    val item = makeItem(edge = 2.0)
    fun bin(id: String, depth: Double) = BinType(width = FltX(4.0) * Meter, height = FltX(4.0) * Meter,
        depth = FltX(depth) * Meter, capacity = FltX(100.0) * Kilogram,
        longitudinalBalance = null, lateralBalance = null, typeCode = binTypeIdOf(id))
    val small = bin("S", 4.0)
    val large = bin("L", 6.0)
    val physicalBins = if (smallOnly) listOf(small, small) else listOf(small, small, large)
    // #endregion input
    // Enumerate actual prefix placements, not selected bins or solver answers.
    val layers = physicalBins.distinct().flatMap { type ->
        val slots = (0 until if (type.typeCode == small.typeCode) 8 else 10).map { n ->
            itemPlacement3Of(item, QuantityPoint3(FltX((n % 2) * 2.0) * Meter,
                FltX(((n / 2) % 2) * 2.0) * Meter, FltX((n / 4) * 2.0) * Meter))
        }
        (1..slots.size).map { n -> BinLayer(iteration = Int64.zero, from = Grid::class,
            bin = type, shape = type.asContainer3Shape(), units = slots.take(n)) }
    }
    // #region rule
    val generator = object : Bpp3dLayerGenerator<FltX> {
        override suspend fun generate(request: Bpp3dLayerGenerationRequest<FltX>) =
            layers.filter { !smallOnly || it.bin?.typeCode == small.typeCode }
                .map { Bpp3dLayerGenerationResult<FltX>(layer = it, source = "approved-grid") }
    }
    val request = ColumnGenerationApplicationRequest(itemDemands = listOf(item to UInt64(10)),
        initialColumns = layers, generators = listOf(generator),
        finalBins = physicalBins.map { layerBinOf(shape = it, units = emptyList()) })
    // #endregion rule
    // #region objective
    return if (!costObjective) request else request.copy(executorConfig = ColumnGenerationStandardExecutorConfig(
        finalBinVolumeWeight = FltX.zero, finalBinAmountCoefficient = FltX.zero, finalBinTypeCostWeight = FltX.one,
        finalBinTypeCosts = mapOf(small.typeCode to FltX(4.0), large.typeCode to FltX(10.0))))
    // #endregion objective
}

// #region entry
suspend fun runBusiness(solver: ColumnGenerationSolver) {
    val request = makeRequest(costObjective = true).copy(cgConfig = ColumnGenerationConfig(iterationLimit = 12, maxColumnsPerIteration = 24))
    val response = ColumnGenerationApplicationService(solver).solve(request, packingAnalyzer = ColumnGenerationPackingAnalyzer())
    println(response)
}
// #endregion entry
rs
use ospf_rust_framework::solver::meta_model_backend::MetaModelSolverBackend;
use ospf_rust_framework_bpp3d::application::{CsvDatasetLoader, csv::CsvMaterializedApplicationRequest, service::*};
use ospf_rust_framework_bpp3d::domain::packing::{PackedBin, service::{PackingGeometryContract, PackingGeometryGuard}};
use ospf_rust_quantities::unit::Meter;

pub fn make_request(small_only: bool) -> Result<CsvMaterializedApplicationRequest, String> {
    // The CSV adapter fixes geometry to metres; each record below is one physical carton.
    // #region input
    let mut csv = String::from("# table:items\nitem_id,name,shape_type,width,height,depth,weight,amount\n");
    for i in 0..10 { csv.push_str(&format!("i{i},carton,cuboid,2,2,2,1,1\n")); }
    csv.push_str("# table:bins\nbin_id,type_code,width,height,depth,capacity\ns1,S,4,4,4,100\ns2,S,4,4,4,100\nl1,L,4,4,6,100\n");
    csv.push_str("# table:layers\nlayer_id,bin_id,depth\ns1-layer,s1,4\ns2-layer,s2,4\nl-layer,l1,6\n");
    let mut request = CsvDatasetLoader::load_str(&csv).map_err(|e| format!("{e:?}"))?.materialize().map_err(|e| format!("{e:?}"))?;
    // #endregion input
    // Restrict both available bins and seed layers before optimization.
    if small_only {
        request.bins.retain(|b| b.type_code != "L");
        request.initial_layers.retain(|l| l.bin.as_ref().is_some_and(|b| b.type_code != "L"));
    }
    Ok(request)
}

// A delivery guard complements input restrictions; it is not a pricing constraint.
// #region rule
#[derive(Debug, Clone)]
struct SmallOnly;
impl PackingGeometryContract<f64, Meter> for SmallOnly {
    fn validate(&self, bin: &PackedBin<f64, Meter>) -> Result<(), Vec<String>> {
        PackingGeometryGuard::new().validate(bin)?;
        if bin.bin_type.type_code == "L" { Err(vec!["Only approved S bins may be delivered".into()]) } else { Ok(()) }
    }
}
// #endregion rule

pub fn run_business<R: MetaModelSolverBackend, F: MetaModelSolverBackend>(rmp_backend: R, final_backend: F) -> Result<(), String> {
    // #region objective
    let final_config = MetaModelFinalExecutorConfig { final_bin_volume_weight: 0.0,
        final_bin_amount_coefficient: 0.0, final_bin_type_cost_weight: 1.0,
        final_bin_type_costs: [("S".into(), 4.0), ("L".into(), 10.0)].into_iter().collect(), ..Default::default() };
    // #endregion objective
    // #region entry
    let config = ColumnGenerationConfig::new().with_max_iterations(12)
        .with_max_column_amount(256).with_max_candidates_per_iteration(24);
    // #endregion entry
    // #region injection
    let service = ColumnGenerationApplicationService::with_geometry_guard(config, SmallOnly);
    let request = make_request(true)?;
    let rmp = SolverBackedMetaModelRmpExecutor::new(MetaModelRmpExecutorConfig::default(), rmp_backend);
    let final_executor = SolverBackedMetaModelFinalExecutor::new(final_config, final_backend);
    let result = service.run_csv_materialized_with_bins(request, &rmp, &final_executor).map_err(|e| format!("{e:?}"))?;
    // #endregion injection
    println!("final={}, objective={:?}, diagnostics={:?}", result.final_execution.final_solved, result.final_execution.objective, result.result.info);
    Ok(())
}