Your First 3D Loading: From Selection to Placement
Work through business input, solving and result extraction with this example. Prepare dependencies and backends using Setup.
1. Business Scenario
Start with one cuboid instead of combining cylinders, support rules and mixed bin types. Kotlin uses a 1 × 1 × 1 m carton and a 3 × 3 × 3 m bin. Rust CSV uses a 2 × 3 × 4 m item and a 10 × 10 × 10 m bin. These teach the same lifecycle, not a numerical cross-language benchmark.
A candidate layer is not a final loading plan. Kotlin supplies an initial layer with an actual placement and one empty bin, with no additional-layer search. Rust loads and converts input through the public CSV loader and connects two real model backends.
2. Construct Input and Call the Framework
Kotlin and Rust Entry Points
The Kotlin example defines material, packaging attributes, orientation and coordinates locally and accepts a real solver. Rust requires the domain crate serde feature and uses synchronous APIs without async. Configure backends for both restricted-master and final-integer phases and retain their solve reports.
The examples include imports and error handling. The application supplies Kotlin ColumnGenerationSolver to runExample; the next section shows the launcher.
package docs.examples.bpp3d
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.*
import fuookami.ospf.kotlin.utils.functional.*
private object Cargo : AbstractCargoAttribute
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}" })
}
fun makeItem(edge: Double = 1.0): ActualItem {
val material = Material(
no = MaterialNo("M1"), type = MaterialType.RawMaterial,
cargo = Cargo, name = "goods", weight = FltX.one * Kilogram
)
return ActualItem(
id = itemIdOf("I1"), name = "carton",
pack = Package.innerPackage(
shape = PackageShape(
width = FltX(edge) * Meter, height = FltX(edge) * Meter, depth = FltX(edge) * Meter,
weight = FltX.one * Kilogram, packageType = PackageType.CartonContainer
),
materials = mapOf(material to UInt64.one)
),
enabledOrientations = listOf(Orientation.Upright), batchNo = BatchNo("batch-1"),
packageAttribute = PackageAttribute(
packageType = PackageType.CartonContainer, weightAttribute = WeightAttribute(),
deformationAttribute = LinearDeformationAttribute(FltX.zero),
hangingPolicy = AbsoluteHangingPolicy(FltX.zero), stackingOnPolicy = FilterStackingOnPolicy()
)
)
}
suspend fun runExample(solver: ColumnGenerationSolver) {
val item = makeItem()
val binType = BinType(
width = FltX(3.0) * Meter, height = FltX(3.0) * Meter, depth = FltX(3.0) * Meter,
capacity = FltX(100.0) * Kilogram, longitudinalBalance = null, lateralBalance = null,
typeCode = binTypeIdOf("BOX")
)
// Supply an actual placement, not just a demand-coverage number.
val layer = BinLayer(
iteration = Int64.zero, from = Cargo::class, bin = binType, shape = binType.asContainer3Shape(),
units = listOf(itemPlacement3Of(item, QuantityPoint3(
FltX.zero * Meter, FltX.zero * Meter, FltX.zero * Meter
)))
)
val response = ColumnGenerationApplicationService(solver).solve(
request = ColumnGenerationApplicationRequest(
itemDemands = listOf(item to UInt64.one), initialColumns = listOf(layer),
finalBins = listOf(layerBinOf(shape = binType, units = emptyList())),
generators = listOf(object : Bpp3dLayerGenerator<FltX> {
override suspend fun generate(request: Bpp3dLayerGenerationRequest<FltX>) =
emptyList<Bpp3dLayerGenerationResult<FltX>>()
})
),
packingAnalyzer = ColumnGenerationPackingAnalyzer()
).getOrThrow()
println("finalSolved=${response.result.finalSolved}")
val packing = response.packingSnapshot ?: error("No deliverable loading plan")
// #region result
val bins = packing.packingResult.aggregation.bins
println("bins=${bins.size}, objective=${response.result.finalObjective}")
for (bin in bins) {
println("bin=${bin.name}, type=${bin.type.typeCode}")
for (packed in bin.items) {
val p = packed.placement
println("${(p.unit as? ActualItem)?.id}: (${p.x}, ${p.y}, ${p.z}), orientation=${p.orientation}, order=${packed.loadingOrder}")
}
}
check(bins.flatMap { it.items }.size == 1) { "Expected exactly one carton" }
// #endregion result
}use ospf_rust_framework::solver::meta_model_backend::MetaModelSolverBackend;
use ospf_rust_framework_bpp3d::application::service::*;
use ospf_rust_framework_bpp3d::application::CsvDatasetLoader;
// Requires the `serde` feature. Backends are real, separately configured dependencies.
pub fn run_example<R: MetaModelSolverBackend, F: MetaModelSolverBackend>(
rmp_backend: R, final_backend: F,
) -> Result<(), String> {
let csv = "# table:items
item_id,name,shape_type,width,height,depth,weight,amount
i1,carton,cuboid,2,3,4,1,1
# table:bins
bin_id,type_code,width,height,depth,capacity
b1,BOX,10,10,10,1000
# table:layers
layer_id,bin_id,depth
l1,b1,4
";
let request = CsvDatasetLoader::load_str(csv).map_err(|e| format!("{e:?}"))?
.materialize().map_err(|e| format!("{e:?}"))?;
let service = ColumnGenerationApplicationService::new(ColumnGenerationConfig::default());
let rmp = SolverBackedMetaModelRmpExecutor::new(MetaModelRmpExecutorConfig::default(), rmp_backend);
let final_executor = SolverBackedMetaModelFinalExecutor::new(MetaModelFinalExecutorConfig::default(), final_backend);
let result = service.run_csv_materialized_with_bins(request, &rmp, &final_executor)
.map_err(|e| format!("{e:?}"))?;
println!("rmp objective={:?}", result.rmp.objective);
// #region result
println!("final={}, objective={:?}", result.final_execution.final_solved, result.final_execution.objective);
for bin in &result.final_execution.packed_bins {
println!("bin={}, type={:?}, weight={:?}, volume={:?}", bin.name, bin.bin_type.type_code, bin.total_weight(), bin.total_actual_volume());
for item in &bin.items {
println!("item={:?}, xyz={:?}, orientation={:?}, order={}", item.item.id, item.position, item.orientation, item.loading_order);
}
}
let count: usize = result.final_execution.packed_bins.iter().map(|b| b.items.len()).sum();
if result.final_execution.final_solved && count != 1 { return Err(format!("Expected one carton, got {count}")); }
// #endregion result
println!("diagnostics={:?}", result.result.info);
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.
import docs.examples.bpp3d.runExample
import kotlinx.coroutines.runBlocking
import fuookami.ospf.kotlin.core.solver.gurobi.GurobiColumnGenerationSolver
fun main() = runBlocking {
runExample(GurobiColumnGenerationSolver())
}Place the Rust example in src/bpp3d.rs and use this launcher in src/main.rs. See Setup for dependencies and toolchain; do not enable async for these synchronous examples.
mod bpp3d;
use ospf_rust_core::solver::solvers::scip::SCIPConfig;
use ospf_rust_framework::solver::{ScipColumnGenerationSolver, meta_model_backend::ColumnGenerationSolverMetaModelBackend};
fn main() -> Result<(), String> {
let config = SCIPConfig::new().with_output(false).with_time_limit(30.0);
let rmp = ColumnGenerationSolverMetaModelBackend::new(
ScipColumnGenerationSolver::with_config(config.clone()),
).with_lp_subproblem_defaults();
let final_backend = ColumnGenerationSolverMetaModelBackend::new(
ScipColumnGenerationSolver::with_config(config),
);
bpp3d::run_example(rmp, final_backend)
}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
| Read | Kotlin | Rust |
|---|---|---|
| Enabled bins | packingSnapshot.packingResult.aggregation.bins → name / type / items | final_execution.packed_bins → name / bin_type / items |
| Position, orientation and loading order | placement.x / y / z / orientation, loadingOrder | item.position / orientation / loading_order |
| Counts and objective | bins.flatMap { it.items }, result.finalObjective | packed_bins.iter().map(|b| b.items.len()), final_execution.objective |
| Diagnostics | result.finalSolved / finalInfo | final_execution.final_solved / diagnostics, result.info |
Result Semantics
This entry exposes neither pool complete nor BPP1D idle intervals. Positions are local 3D coordinates. Unused volume is not a free-space geometry guarantee. Kotlin Item is an interface; obtain business IDs through ActualItem or an application mapping.
Distinguish candidates, selected layers and actual packed bins. Read Kotlin packingSnapshot; for Rust inspect selected layers and diagnostics such as final_final_diagnostics. A layer or rendering data alone does not establish delivery. Verify exact item counts, orientation, boundaries, overlap and load limits. A finite initial candidate pool limits the scope of any proof.
5. Change One Business Condition
When changing demand from one item to two, update empty-bin availability and candidate coverage as well. Add a second bin type next, and objectives last. The empty new-layer generator is not a general loading search algorithm.
Continue to the next business scenario and integration checks. Consult repository verification when checking source behavior.