Skip to content

Demand Units and Business Rules ​

After your first slitting plan, specify what the customer orders before adding machines and compatibility rules. Demand labels, physical units, per-use contributions and plan usage must form one consistent chain.

1. Start with an Algorithm-Independent Acceptance Case ​

Suppose validated plan P produces two rolls of A per use, each weighing 10 kg. This is a business calculation, not an input protocol where the framework guesses the unit of a bare number:

OrderP contribution per useRequired usesOutput
A, six rollsTwo rolls3Six rolls
A, 60 kg20 kg360 kg
A, 30 kg20 kgNot exactly satisfiableExplicit overproduction or another plan required

Do not silently use an indivisible plan 1.5 times. With modeled overproduction, two uses can deliver 40 kg; with exact production and no other plan, the problem is infeasible. The allowance belongs in the model, not just a changed order label.

2. Express Orders with Actual Demand Types ​

Construct the Roll-Demand Example ​

This implements the six-roll row: product A is 0.8 m wide, stock is up to 1.6 m wide, and M1 has three batches. M2 is quarantined stock. Two A strips fit each batch. The weight rows are separate exercises requiring per-product weight data; changing 6 to 60 is insufficient.

kt
val product = Product(id = productIdOf("A"), name = "strip", width = listOf(m(0.8)))
val stock = Material(id = materialIdOf("M1"), name = "stock",
    widthRange = WidthRange(QuantityRange(m(0.8), m(1.6)), m(0.8)), availableBatches = UInt64(3))
return Csp1dProblem(products = listOf(product), materials = listOf(stock, stock.copy(id = materialIdOf("M2"))),
    machines = emptyList(), demands = listOf(ProductDemand.legacyRoll(product, Flt64(6.0))))
rs
let product = Product { id: "A".into(), name: "strip".into(), width: vec![m(0.8)],
    length: None, unit_weight: None, weight: None, max_over_produce_length: None, dynamic_length: false };
let stock = Material { id: "M1".into(), name: "stock".into(), width_range: WidthRange::new(m(0.8), m(1.6)),
    length: None, unit_weight: None, machine_id: None, available_batches: 3 };
let quarantined = Material { id: "M2".into(), ..stock.clone() };
Csp1dProblem::new(vec![product.clone()], vec![stock, quarantined], vec![], vec![ProductDemand::legacy_roll(product, 6.0)])
DemandKotlin entryRust entry
Legacy roll countProductDemand.legacyRollProductDemand::legacy_roll
Legacy sheet countProductDemand.legacySheetProductDemand::legacy_sheet
Legacy weightProductDemand.legacyWeightProductDemand::legacy_weight

These helpers express demand conventions; they do not invent product weight, length or unit-weight data. For quantity constructors, discrete/continuous behavior also follows the actual unit, not only mode.

Use the first-lesson input and solve entry and read contributions in the actual demand unit. Legacy mode labels do not override quantities or production-density data.

3. Establish Contributions Before Solving ​

  1. Identify demands by stable product IDs, retaining width, optional length and weight sources.
  2. Check CuttingPlanDemandContribution quantities against order units. A roll order still counts rolls when the product also has weight.
  3. Use the language-specific contribution construction/calculation path rather than treating slice counts as kilograms. Verify the dimensions of width, length, areal density or per-piece mass.
  4. Recompute each product's output as Σ contribution × usage, with separate surplus, shortage and allowed bounds.

Whether two measurement requirements for the same product must both hold is a business decision. An adapter must not overwrite an order merely because the product ID matches.

Switch Entry and Bound Plans ​

Keep the problem and policies, then switch from Csp1dMilp to Csp1dColumnGeneration. Bound initial plans, plans per round and iterations in solve configuration, and inspect trace termination and final status.

kt
val bounded = config.copy(columnGeneration = Csp1dConfiguration(
    maxInitialPlans = Int64(64), maxPricingPlans = Int64(16), iterationLimit = Int64(8)))
val cg = Csp1dColumnGeneration<Flt64>(solver, initialGenerator = initialGenerator()).solveWithTrace(problem, bounded)
println("termination=${cg.trace.terminationReason}, final=${cg.trace.finalMilpStatus}")
rs
config.column_generation = Csp1dConfiguration { max_initial_plans: 64, max_pricing_plans: 16, iteration_limit: 8 };
let cg = Csp1dColumnGeneration::with_generators(Box::new(initial.clone()), Box::new(ReducedCostPricingGenerator::new(initial)))
    .solve_with_trace(problem, Some(config));
println!("termination={:?}, final={:?}", cg.trace.termination_reason, cg.trace.final_milp_status);

Rust Execution Semantics

This Rust example uses default heuristic master solving with estimated prices for candidate search. MILP method names and final trace statuses do not establish native optimization. Configure a Csp1dLpSolver adapter for real LP/dual extraction and retain status, shortfalls and trace for delivery.

4. Put Machine Rules in the Right Layer ​

Minimal Extension: Quarantine Material M2 ​

Implement Csp1dDomainPolicy.isFeasible and inject it through extensionSet.domainPolicies / extension_set.domain_policies. The policy excludes M2 while preserving default width feasibility. Reuse the configuration for ordinary and column-generation solving.

This scenario also injects NSameGenerator to produce two A strips per execution. The default simple generator supplies only one strip, insufficient for six rolls from three batches. The complete Kotlin helper resolves quantity arithmetic before creating N-Same.

kt
val quarantine = object : Csp1dDomainPolicy<Flt64> {
    override val name = "quarantine-M2"
    override fun isFeasible(context: Csp1dDomainCalculationContext<Flt64>) = context.material.id != materialIdOf("M2")
}
val config = Csp1dSolveConfig(extensionSet = Csp1dExtensionSet(domainPolicies = listOf(quarantine)))
val milp = Csp1dMilp<Flt64>(solver, initialGenerator = initialGenerator()).solve(problem.copy(solveConfig = config))
rs
struct Quarantine;
impl Csp1dDomainPolicy<f64> for Quarantine {
    fn name(&self) -> &str { "quarantine-M2" }
    fn is_feasible(&self, context: &dyn Csp1dDomainCalculationContext<f64>) -> bool { context.material().id != "M2" }
}

Rust instance injection:

rs
let mut config = Csp1dSolveConfig::default();
config.extension_set.domain_policies.push(Arc::new(Quarantine));
let initial = NSameGenerator::<f64>::default();
let milp = Csp1dMilp::with_initial_generator(Box::new(initial.clone())).solve(problem.clone(), Some(config.clone()));
println!("status={:?}, unmet={:?}", milp.status, milp.produce.unmet_demands);
assert!(milp.produce.cutting_plans.iter().all(|usage| usage.plan.material.id != "M2"));
assert!(milp.produce.unmet_demands.is_empty(), "Expected six rolls from three batches");

“Material M cannot run on machine X” can be checked per plan. “Machine X can process at most 100 m this shift” needs a sum across plans; checking each plan separately against 100 is insufficient.

Cross-plan rules belong in the relevant context/modeling pipelines. With column generation, inspect LP, dual/pricing and final participation too. Removing offending plans after solving does not preserve demand coverage.

5. Retain Three Assertion Groups ​

  • Changing demand mode while retaining the numeric amount changes units and contribution calculations, not just a label on the same output.
  • A prohibited material-machine pair cannot enter selection. Prohibiting all feasible pairs leaves no deliverable output.
  • Tightened aggregate capacity is checked across all plan usages, not independently per selected plan.

Use the integration guide to distinguish normal no-solution outcomes, technical failure and native reports. Feasibility recovery or heuristic fallback retains its real status, not an automatic upgrade to optimality.

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

import fuookami.ospf.kotlin.math.algebra.number.*
import fuookami.ospf.kotlin.quantities.quantity.*
import fuookami.ospf.kotlin.quantities.unit.Meter
import fuookami.ospf.kotlin.framework.solver.ColumnGenerationSolver
import fuookami.ospf.kotlin.framework.csp1d.application.model.*
import fuookami.ospf.kotlin.framework.csp1d.application.service.*
import fuookami.ospf.kotlin.framework.csp1d.domain.material.model.*
import fuookami.ospf.kotlin.framework.csp1d.domain.produce.model.Csp1dExtensionSet
import fuookami.ospf.kotlin.framework.csp1d.domain.cutting_plan_generation.service.NSameGenerator
import fuookami.ospf.kotlin.utils.functional.*

fun initialGenerator(): NSameGenerator<Flt64> {
    val arithmetic = when (val result = DefaultQuantityArithmetic.resolveFor(Flt64.zero)) {
        is Ok -> result.value
        is Failed -> error(result.error.message)
        is Fatal -> error(result.errors.joinToString { it.message })
    }
    return NSameGenerator(arithmetic = arithmetic, allAmount = false)
}

fun makeProblem(): Csp1dProblem<Flt64> {
    fun m(value: Double) = Quantity(Flt64(value), Meter)
    // #region input
    val product = Product(id = productIdOf("A"), name = "strip", width = listOf(m(0.8)))
    val stock = Material(id = materialIdOf("M1"), name = "stock",
        widthRange = WidthRange(QuantityRange(m(0.8), m(1.6)), m(0.8)), availableBatches = UInt64(3))
    return Csp1dProblem(products = listOf(product), materials = listOf(stock, stock.copy(id = materialIdOf("M2"))),
        machines = emptyList(), demands = listOf(ProductDemand.legacyRoll(product, Flt64(6.0))))
    // #endregion input
}

suspend fun runBusiness(solver: ColumnGenerationSolver) {
    val problem = makeProblem()
    // #region rule
    val quarantine = object : Csp1dDomainPolicy<Flt64> {
        override val name = "quarantine-M2"
        override fun isFeasible(context: Csp1dDomainCalculationContext<Flt64>) = context.material.id != materialIdOf("M2")
    }
    val config = Csp1dSolveConfig(extensionSet = Csp1dExtensionSet(domainPolicies = listOf(quarantine)))
    val milp = Csp1dMilp<Flt64>(solver, initialGenerator = initialGenerator()).solve(problem.copy(solveConfig = config))
    // #endregion rule
    println("milp=${milp.status}, unmet=${milp.produce.unmetDemands}")
    // #region entry
    val bounded = config.copy(columnGeneration = Csp1dConfiguration(
        maxInitialPlans = Int64(64), maxPricingPlans = Int64(16), iterationLimit = Int64(8)))
    val cg = Csp1dColumnGeneration<Flt64>(solver, initialGenerator = initialGenerator()).solveWithTrace(problem, bounded)
    println("termination=${cg.trace.terminationReason}, final=${cg.trace.finalMilpStatus}")
    // #endregion entry
}
rs
use std::sync::Arc;
use ospf_rust_framework_csp1d::{Csp1dMilp, Csp1dColumnGeneration, Csp1dProblem};
use ospf_rust_framework_csp1d::application::model::{Csp1dSolveConfig, Csp1dConfiguration};
use ospf_rust_framework_csp1d::domain::material::{Material, Product, ProductDemand, WidthRange};
use ospf_rust_framework_csp1d::domain::produce::{Csp1dDomainPolicy, Csp1dDomainCalculationContext};
use ospf_rust_framework_csp1d::domain::cutting_plan_generation::{NSameGenerator, ReducedCostPricingGenerator};
use ospf_rust_quantities::{Quantity, unit::{CTUnit, Meter, Unit}};

pub fn make_problem() -> Csp1dProblem<f64> {
    let m = |value| Quantity::<f64, Unit>::new(value, Meter::INSTANT.clone());
    // #region input
    let product = Product { id: "A".into(), name: "strip".into(), width: vec![m(0.8)],
        length: None, unit_weight: None, weight: None, max_over_produce_length: None, dynamic_length: false };
    let stock = Material { id: "M1".into(), name: "stock".into(), width_range: WidthRange::new(m(0.8), m(1.6)),
        length: None, unit_weight: None, machine_id: None, available_batches: 3 };
    let quarantined = Material { id: "M2".into(), ..stock.clone() };
    Csp1dProblem::new(vec![product.clone()], vec![stock, quarantined], vec![], vec![ProductDemand::legacy_roll(product, 6.0)])
    // #endregion input
}

// #region rule
struct Quarantine;
impl Csp1dDomainPolicy<f64> for Quarantine {
    fn name(&self) -> &str { "quarantine-M2" }
    fn is_feasible(&self, context: &dyn Csp1dDomainCalculationContext<f64>) -> bool { context.material().id != "M2" }
}
// #endregion rule

pub fn run_business() {
    let problem = make_problem();
    // #region injection
    let mut config = Csp1dSolveConfig::default();
    config.extension_set.domain_policies.push(Arc::new(Quarantine));
    let initial = NSameGenerator::<f64>::default();
    let milp = Csp1dMilp::with_initial_generator(Box::new(initial.clone())).solve(problem.clone(), Some(config.clone()));
    println!("status={:?}, unmet={:?}", milp.status, milp.produce.unmet_demands);
    assert!(milp.produce.cutting_plans.iter().all(|usage| usage.plan.material.id != "M2"));
    assert!(milp.produce.unmet_demands.is_empty(), "Expected six rolls from three batches");
    // #endregion injection
    // #region entry
    config.column_generation = Csp1dConfiguration { max_initial_plans: 64, max_pricing_plans: 16, iteration_limit: 8 };
    let cg = Csp1dColumnGeneration::with_generators(Box::new(initial.clone()), Box::new(ReducedCostPricingGenerator::new(initial)))
        .solve_with_trace(problem, Some(config));
    println!("termination={:?}, final={:?}", cg.trace.termination_reason, cg.trace.final_milp_status);
    // #endregion entry
}