Container Types, Stock and Cost
After your first 1D packing, offer two container types for the same items. Load CSV, compare objectives, then add a mixing policy and generation budgets.
1. Start with Hand-Checkable Data
Items:
id,length,weight,amount
a,6,1,2
b,4,1,2Containers:
id,length,max_weight,cost,inventory
small,10,100,3,2
large,20,100,10,1Use meters and kilograms, initially with zero spacing. Net item length is 20 m. One large or two small containers can carry everything without exceeding weight capacity.
| Objective | An optimal choice | Containers | Cost |
|---|---|---|---|
| Minimum count | One large | 1 | 10 |
| Minimum cost | Two small, each carrying a+b | 2 | 6 |
| Minimum consumed length | Total enabled container capacity is 20 m in both cases: | Not unique | Not decided by this objective |
Use these hand calculations as a small-instance business reference. Interpret program evidence using candidate completeness and the solve report together.
2. Load CSV and Change Objectives
Assign the CSV texts above to itemsCsv / binsCsv (Rust: ITEMS_CSV / BINS_CSV). The full source at the end includes imports and numeric parsers parseNumber / parse_number.
val problem = Bpp1dCsvDatasetLoader(::parseNumber).load(
itemsCsv, binsCsv, Meter, Kilogram, Quantity(Flt64.zero, Meter)
).getOrThrow()
val costProblem = problem.copy(objective = PackingObjective.Cost)let options = PackingCsvOptions { length_unit: Meter, weight_unit: Kilogram,
spacing: Quantity::new_ct(0.0), objective: PackingObjective::Cost };
let context = load_packing_csv(ITEMS_CSV, BINS_CSV, options, parse_number,
&SameUnitPackingValueAdapter, &SameUnitPackingValueAdapter)?;Explicit Units and Null Stock
CSV carries no units: bind Meter and Kilogram and supply spacing when loading. This example parses Flt64 / f64; higher-precision domains should parse directly into their numeric type. An empty inventory cell means unlimited stock; 0 means unavailable.
Different Loader Results
Kotlin returns Ret<PackingProblem<Flt64>>; the example's getOrThrow() handles CLI errors before copy(objective = ...) switches objectives. Rust returns a validated PackingContext. To switch objectives, clone context.problem(), modify objective, then validate and rebuild with PackingContext::new. The complete source solves each objective in turn.
Reuse the first lesson's backend for BinCount, Cost and ConsumedLength, and extract physical results in the same way.
3. Change One Condition at a Time
Use minimum cost throughout; step 4 restores original stock.
| Step | Change | Result and interpretation |
|---|---|---|
| 1 | Reduce small stock from 2 to 1, keeping zero spacing | One large, minimum cost 10 |
| 2 | Restore two small; set large stock to zero | Two small carrying a+b each, minimum cost 6 |
| 3 | From step 2, reduce small stock to one | Insufficient capacity; no complete feasible packing |
| 4 | Restore original stock; set spacing to 1 m | large carries a+a+b and small carries b, costing |
For step 4: all four items require
4. Validate Results and Add a Mixing Rule
Independently check the actual placements:
- Exact item counts: group
placementsby ID; both a and b must occur twice. - Container stock: count
plansby container type and compare with non-null inventory limits. - Per-container physics: check intervals, length, weight and adjacent spacing.
- Recomputed total cost: add each used container type's
costonce; compare with KPIs and the selected objective.
Per-Container Policy: PatternPolicy
Restore zero spacing and original stock. Add the rule that a and b cannot share a container. Kotlin supplies the policy to the generator, then injects that generator into the solver entry:
val noMix = PatternPolicy<Flt64> { p -> !("a" in p.amounts && "b" in p.amounts) }
val generator = PatternGenerationContext(noMix)
val result = Bpp1dMilp(solver, Flt64PackingValueAdapter, generator).solve(problem)pub struct NoMixedItems;
impl PatternPolicy for NoMixedItems {
fn accept(&self, p: &PackingPattern) -> CoreResult<bool> {
Ok(!(p.amounts.contains_key("a") && p.amounts.contains_key("b")))
}
}Rust passes the policy explicitly, alongside the no-op model extension:
let result = Bpp1dMilp::solve_with_extension(context, NoPatternExtension, &NoMixedItems,
Bpp1dSolveConfig::default(), &SolveHandle::new(), backend(solver))?;problem / context comes from section 2. backend(solver) forwards the model, remaining time and cancellation handle to the backend from the first lesson. With this policy, large can carry a+a and small can carry b+b, giving minimum cost 13. Keep the count and stock checks, and also verify that no container contains both IDs.
Custom-Rule Report Scope
The policy applies to candidate enumeration and initial-candidate generation. Completeness is relative to its accepted compositions. Rust's solve_with_extension conservatively leaves globally_optimal false for custom rules; interpret the current-model report, completeness and business checks together.
Cross-Container Rules: PatternModelingExtension
For example, limiting total enabled containers to two constrains the sum of pattern usages. This ordinary-MILP example is independent of the mixing exercise:
class BinLimit(private val limit: Flt64) : PatternModelingExtension<Flt64> {
override fun register(context: PatternAssignmentContext<Flt64>): Try {
if (context.stage != PackingModelStage.MILP) {
return Failed(ErrorCode.IllegalArgument, "This BinLimit example supports ordinary MILP only")
}
val bins = sum(context.aggregation.variables.values.toList())
return context.model.addConstraint(bins leq limit, name = "business_bin_limit")
}
}#[derive(Clone)]
pub struct BinLimit(pub f64);
impl PatternModelingExtension<f64, Meter, Kilogram> for BinLimit {
fn register(&self, model: &mut MetaModel<f64>, _: &PackingContext<f64, Meter, Kilogram>,
a: &PatternAggregation<f64>, _: PackingModelStage) -> CoreResult<()> {
let terms = a.inventories.values().flat_map(|expr| expr.monomials())
.map(|term| (term.var_index(), *term.coefficient())).collect::<Vec<_>>();
model.add_le_constraint(&terms, self.0, "business_bin_limit")?;
Ok(())
}
}val config = Bpp1dSolveConfig(extensions = listOf(BinLimit(Flt64(2))))
val result = Bpp1dMilp(solver, Flt64PackingValueAdapter).solve(problem, config)let result = Bpp1dMilp::solve_with_extension(context, BinLimit(2.0), &AcceptAllPatterns,
Bpp1dSolveConfig::default(), &SolveHandle::new(), backend(solver))?;Before Using Model Extensions with Column Generation
Kotlin's lifecycle includes register(context): Try, refresh(context): Try, reducedCost(pattern, context, dual): Flt64 and extractSolution(context, values): Ret<Map<String, String>>. Update additional expressions as columns change and include extra rows' dual contributions in pricing. This Kotlin BinLimit supports ordinary MILP only and explicitly checks the stage.
Rust rebuilds the complete model when the pool changes. register(model, packing, aggregation, stage) receives the current model and columns; optional extract_solution(values) extracts business indicators. Pricing uses the complete matrix. These lifecycles differ; consult the overview's API references for full signatures and constraint identity handling.
5. Switch to Column Generation and Set Budgets
Keep the section 2 input and backend; change the entry and configure its budgets:
val config = Bpp1dSolveConfig<Flt64>(
generation = PatternGenerationConfig(maxPatterns = 10_000, maxNodes = 100_000),
iterationLimit = 32, columnsPerIteration = 32
)
val result = Bpp1dColumnGeneration(solver, Flt64PackingValueAdapter).solve(problem, config)let config = Bpp1dSolveConfig {
generation: PatternGenerationConfig { max_patterns: 10_000, max_nodes: 100_000 },
iteration_limit: 32, columns_per_iteration: 32, ..Default::default()
};
let result = Bpp1dColumnGeneration::solve(context, config, &SolveHandle::new(), backend(solver))?;maxPatterns / max_patterns bounds generated candidates; maxNodes / max_nodes bounds enumeration nodes. iterationLimit / iteration_limit bounds pricing rounds; columnsPerIteration / columns_per_iteration bounds columns activated per round. Read completeness, columnCount / column_count and pricingIterations / pricing_iterations from the solution. These differ from backend time limits; when generation is truncated, retain the finite-pool scope of any optimality claim.
6. Run in Your Application
Kotlin: add the complete source and call runBusinessExample(solver). Rust: place it in src/bpp1d_business.rs and call bpp1d_business::run_business_example(&solver). Reuse the first lesson's launcher, replacing its import or module name. The example runs objective comparisons, the mixing policy, column generation and the container limit in turn.
Complete source: CSV, parsers, imports and backend forwarding
package docs.examples.bpp1d.business
import fuookami.ospf.kotlin.math.algebra.number.*
import fuookami.ospf.kotlin.math.symbol.inequality.*
import fuookami.ospf.kotlin.math.symbol.operation.*
import fuookami.ospf.kotlin.quantities.quantity.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.application.*
import fuookami.ospf.kotlin.framework.bpp1d.domain.item.model.*
import fuookami.ospf.kotlin.framework.bpp1d.domain.pattern_generation.*
import fuookami.ospf.kotlin.framework.bpp1d.domain.pattern_assignment.*
import fuookami.ospf.kotlin.utils.error.ErrorCode
import fuookami.ospf.kotlin.utils.functional.*
private val itemsCsv = """
id,length,weight,amount
a,6,1,2
b,4,1,2
""".trimIndent()
private val binsCsv = """
id,length,max_weight,cost,inventory
small,10,100,3,2
large,20,100,10,1
""".trimIndent()
private fun parseNumber(text: String): Ret<Flt64> =
text.toDoubleOrNull()?.takeIf { it.isFinite() }?.let { Ok(Flt64(it)) }
?: Failed(ErrorCode.IllegalArgument, "Invalid number: $text")
fun loadScenario(): PackingProblem<Flt64> {
// #region csv
val problem = Bpp1dCsvDatasetLoader(::parseNumber).load(
itemsCsv, binsCsv, Meter, Kilogram, Quantity(Flt64.zero, Meter)
).getOrThrow()
val costProblem = problem.copy(objective = PackingObjective.Cost)
// #endregion csv
return costProblem
}
suspend fun solveNoMixed(solver: ColumnGenerationSolver, problem: PackingProblem<Flt64>): Ret<Bpp1dSolution<Flt64>> {
// #region policy
val noMix = PatternPolicy<Flt64> { p -> !("a" in p.amounts && "b" in p.amounts) }
val generator = PatternGenerationContext(noMix)
val result = Bpp1dMilp(solver, Flt64PackingValueAdapter, generator).solve(problem)
// #endregion policy
return result
}
suspend fun solveColumnGeneration(solver: ColumnGenerationSolver, problem: PackingProblem<Flt64>): Ret<Bpp1dSolution<Flt64>> {
// #region cg
val config = Bpp1dSolveConfig<Flt64>(
generation = PatternGenerationConfig(maxPatterns = 10_000, maxNodes = 100_000),
iterationLimit = 32, columnsPerIteration = 32
)
val result = Bpp1dColumnGeneration(solver, Flt64PackingValueAdapter).solve(problem, config)
// #endregion cg
return result
}
// #region extension
class BinLimit(private val limit: Flt64) : PatternModelingExtension<Flt64> {
override fun register(context: PatternAssignmentContext<Flt64>): Try {
if (context.stage != PackingModelStage.MILP) {
return Failed(ErrorCode.IllegalArgument, "This BinLimit example supports ordinary MILP only")
}
val bins = sum(context.aggregation.variables.values.toList())
return context.model.addConstraint(bins leq limit, name = "business_bin_limit")
}
}
// #endregion extension
suspend fun solveWithBinLimit(solver: ColumnGenerationSolver, problem: PackingProblem<Flt64>): Ret<Bpp1dSolution<Flt64>> {
// #region extension-injection
val config = Bpp1dSolveConfig(extensions = listOf(BinLimit(Flt64(2))))
val result = Bpp1dMilp(solver, Flt64PackingValueAdapter).solve(problem, config)
// #endregion extension-injection
return result
}
suspend fun runBusinessExample(solver: ColumnGenerationSolver) {
val problem = loadScenario()
for (objective in listOf(PackingObjective.BinCount, PackingObjective.ConsumedLength, PackingObjective.Cost)) {
val solution = Bpp1dMilp(solver, Flt64PackingValueAdapter)
.solve(problem.copy(objective = objective)).getOrThrow()
println("$objective: ${solution.status}, complete=${solution.candidateComplete}, plans=${solution.packing.plans}")
}
println("noMix=${solveNoMixed(solver, problem).getOrThrow().packing.plans}")
println("cg=${solveColumnGeneration(solver, problem).getOrThrow().status}")
println("binLimit=${solveWithBinLimit(solver, problem).getOrThrow().packing.plans}")
}
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}" })
}use std::time::Duration;
use ospf_rust_core::error::{ModelError, Result as CoreResult};
use ospf_rust_core::model::{MetaModel, intermediate::LinearTriadModel};
use ospf_rust_core::solver::{LinearSolver, SolveHandle, SolveOptions, SolveReport};
use ospf_rust_framework_bpp::infrastructure::SameUnitPackingValueAdapter;
use ospf_rust_framework_bpp1d::{application::*, domain::*, infrastructure::*};
use ospf_rust_quantities::{Quantity, unit::{Meter, Kilogram}};
const ITEMS_CSV: &str = "id,length,weight,amount\na,6,1,2\nb,4,1,2\n";
const BINS_CSV: &str = "id,length,max_weight,cost,inventory\nsmall,10,100,3,2\nlarge,20,100,10,1\n";
fn parse_number(text: &str) -> CoreResult<f64> {
text.parse::<f64>().map_err(|e| ModelError::InvalidConstraint(format!("Invalid number {text}: {e}")).into())
}
pub fn load_scenario() -> CoreResult<PackingContext<f64, Meter, Kilogram>> {
// #region csv
let options = PackingCsvOptions { length_unit: Meter, weight_unit: Kilogram,
spacing: Quantity::new_ct(0.0), objective: PackingObjective::Cost };
let context = load_packing_csv(ITEMS_CSV, BINS_CSV, options, parse_number,
&SameUnitPackingValueAdapter, &SameUnitPackingValueAdapter)?;
// #endregion csv
Ok(context)
}
fn backend(solver: &dyn LinearSolver) -> impl FnMut(&LinearTriadModel, Duration, &SolveHandle) -> CoreResult<SolveReport<f64>> + '_ {
move |model, remaining, handle| solver.solve_linear_report_with_options(model, &SolveOptions {
time_limit: Some(remaining), cancellation_handle: Some(handle), ..Default::default()
})
}
// #region policy
pub struct NoMixedItems;
impl PatternPolicy for NoMixedItems {
fn accept(&self, p: &PackingPattern) -> CoreResult<bool> {
Ok(!(p.amounts.contains_key("a") && p.amounts.contains_key("b")))
}
}
// #endregion policy
pub fn solve_no_mixed(solver: &dyn LinearSolver, context: PackingContext<f64, Meter, Kilogram>) -> CoreResult<Bpp1dSolution<Meter>> {
// #region policy-injection
let result = Bpp1dMilp::solve_with_extension(context, NoPatternExtension, &NoMixedItems,
Bpp1dSolveConfig::default(), &SolveHandle::new(), backend(solver))?;
// #endregion policy-injection
Ok(result)
}
pub fn solve_column_generation(solver: &dyn LinearSolver, context: PackingContext<f64, Meter, Kilogram>) -> CoreResult<Bpp1dSolution<Meter>> {
// #region cg
let config = Bpp1dSolveConfig {
generation: PatternGenerationConfig { max_patterns: 10_000, max_nodes: 100_000 },
iteration_limit: 32, columns_per_iteration: 32, ..Default::default()
};
let result = Bpp1dColumnGeneration::solve(context, config, &SolveHandle::new(), backend(solver))?;
// #endregion cg
Ok(result)
}
// #region extension
#[derive(Clone)]
pub struct BinLimit(pub f64);
impl PatternModelingExtension<f64, Meter, Kilogram> for BinLimit {
fn register(&self, model: &mut MetaModel<f64>, _: &PackingContext<f64, Meter, Kilogram>,
a: &PatternAggregation<f64>, _: PackingModelStage) -> CoreResult<()> {
let terms = a.inventories.values().flat_map(|expr| expr.monomials())
.map(|term| (term.var_index(), *term.coefficient())).collect::<Vec<_>>();
model.add_le_constraint(&terms, self.0, "business_bin_limit")?;
Ok(())
}
}
// #endregion extension
pub fn solve_with_bin_limit(solver: &dyn LinearSolver, context: PackingContext<f64, Meter, Kilogram>) -> CoreResult<Bpp1dSolution<Meter>> {
// #region extension-injection
let result = Bpp1dMilp::solve_with_extension(context, BinLimit(2.0), &AcceptAllPatterns,
Bpp1dSolveConfig::default(), &SolveHandle::new(), backend(solver))?;
// #endregion extension-injection
Ok(result)
}
pub fn run_business_example(solver: &dyn LinearSolver) -> Result<(), String> {
let run = || -> CoreResult<()> {
let context = load_scenario()?;
for objective in [PackingObjective::BinCount, PackingObjective::ConsumedLength, PackingObjective::Cost] {
let mut problem = context.problem().clone();
problem.objective = objective;
let input = PackingContext::new(problem, &SameUnitPackingValueAdapter, &SameUnitPackingValueAdapter)?;
let result = Bpp1dMilp::solve(input, Default::default(), &SolveHandle::new(), backend(solver))?;
println!("{objective:?}: complete={}, report={:?}, packing={:?}", result.candidate_complete, result.report, result.packing);
}
println!("no_mix={:?}", solve_no_mixed(solver, context.clone())?.packing);
println!("cg={:?}", solve_column_generation(solver, context.clone())?.report);
println!("bin_limit={:?}", solve_with_bin_limit(solver, context)?.packing);
Ok(())
};
run().map_err(|e| format!("{e:?}"))
}Use integration guidance to migrate your data, result invariants and failure handling. Consult repository verification for source regressions.