Skip to content

Your First Cutting Plan: Demand, Patterns and Process ​

Work through business input, solving and result extraction with this example. Prepare dependencies and backends using Setup.

1. Business Scenario ​

Cut rectangular products from fixed sheets. Kotlin uses a 100 × 60 m sheet, 40 × 30 m products and demand of three. Rust uses 10 × 8 m sheets, 2 × 2 m products, demand of twenty and stock of one hundred sheets. Start with Freeform and zero kerf. These are hand-checkable teaching dimensions, not production specifications.

Both inputs admit a manually constructed one-sheet layout. Kotlin explicitly declares product demand and process; Rust uses Csp2dProblem::single. They are different numerical instances.

2. Construct Input and Call the Framework ​

Kotlin and Rust Entry Points

Kotlin Csp2dMilp uses a real injected solver. Default Rust Csp2dSolvers::new().solve_milp uses a heuristic master and needs no native backend. Its name establishes neither native execution nor optimality. Use Csp2dMasterSolver for a real optimizer integration.

The examples include imports and error handling. The application supplies Kotlin ColumnGenerationSolver to runExample; the next section shows the launcher.

kt
package docs.examples.csp2d

import fuookami.ospf.kotlin.math.algebra.number.*
import fuookami.ospf.kotlin.quantities.quantity.times
import fuookami.ospf.kotlin.quantities.unit.Meter
import fuookami.ospf.kotlin.framework.solver.ColumnGenerationSolver
import fuookami.ospf.kotlin.framework.csp2d.application.model.*
import fuookami.ospf.kotlin.framework.csp2d.application.service.*
import fuookami.ospf.kotlin.framework.csp2d.domain.material.model.*
import fuookami.ospf.kotlin.framework.csp2d.infrastructure.CuttingProcess2
import fuookami.ospf.kotlin.utils.functional.*

suspend fun runExample(solver: ColumnGenerationSolver) {
    val sheet = Material2(
        id = materialId2Of("SHEET"), name = "sheet",
        width = FltX(100.0) * Meter, height = FltX(60.0) * Meter
    )
    val product = Product2(
        id = productId2Of("P1"), name = "P1",
        width = FltX(40.0) * Meter, height = FltX(30.0) * Meter
    )
    val problem = Csp2dProblem(
        materials = listOf(sheet), products = listOf(product),
        demands = listOf(ProductDemand2(product = product, demand = DemandValue2.Amount(UInt64(3)))),
        kerf = FltX.zero * Meter, process = CuttingProcess2.Freeform,
        config = Csp2dConfiguration(maxCandidatesPerIteration = 12, iterationLimit = 4)
    )
    when (val result = Csp2dMilp(solver).solve(problem)) {
        is Ok -> {
            val solution = result.value
            // #region result
            println("covered=${solution.covers(problem)}, sheets=${solution.sheetCount}, length=${solution.consumedLength}")
            println("coverage=${solution.coverage}, used=${solution.usedArea}, waste=${solution.wasteArea}, utilization=${solution.utilization}")
            for (usage in solution.usages) {
                check(usage.plan.validate(problem.kerf) is Ok) { "Invalid cutting pattern" }
                println("plan=${usage.plan.id}, material=${usage.plan.pattern.material.id}, usages=${usage.usage}")
                usage.plan.pattern.placements.forEach { println("${it.itemId}: (${it.x}, ${it.y}), width=${it.width}, height=${it.height}") }
                println("cut tree=${usage.plan.pattern.cutTree}")
            }
            check(solution.covers(problem)) { "Demand is not fully covered" }
            // #endregion result
        }
        is Failed -> error("${result.error.code}: ${result.error.message}")
        is Fatal -> error(result.errors.joinToString { "${it.code}: ${it.message}" })
    }
}
rs
use ospf_rust_base::error::Ret;
use ospf_rust_framework_csp2d::application::{Csp2dProblem, Csp2dSolvers};
use ospf_rust_framework_csp2d::domain::material::{
    Material2, Product2, material_id2, product_id2,
};
use ospf_rust_quantities::quantity::Quantity;
use ospf_rust_quantities::unit::derived::Meter;

fn meters(value: f64) -> Quantity<f64, Meter> {
    Quantity::new_ct(value)
}

pub fn run_example() -> Ret<()> {
    let material = Material2::sheet(
        material_id2("m1"), "sheet", meters(10.0), meters(8.0), 100,
    );
    let product = Product2::new(product_id2("a"), "a", meters(2.0), meters(2.0));
    let problem = Csp2dProblem::single(material, product, 20, meters(0.0));
    // The default service uses a heuristic master solver, not a native optimizer.
    let solution = Csp2dSolvers::new().solve_milp(problem)?;
    // #region result
    println!("covered={}, coverage={:?}, termination={:?}", solution.fully_covered, solution.coverage, solution.termination);
    for (plan, count) in &solution.usage {
        plan.validate(&meters(0.0))?;
        println!("plan={}, material={}, usages={}, per usage={:?}", plan.id, plan.pattern.material.id, count, plan.product_amounts());
        for p in &plan.pattern.placements { println!("{:?}: ({:?}, {:?}), size=({:?}, {:?})", p.item_id, p.x(), p.y(), p.width(), p.height()); }
        println!("cut tree={:?}", plan.pattern.cut_tree);
    }
    println!("material usage: {}", solution.total_material_usage());
    println!("waste area: {}", solution.total_waste_area());
    assert!(solution.fully_covered, "Demand is not fully covered");
    // #endregion result
    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.

kotlin
import docs.examples.csp2d.runExample
import kotlinx.coroutines.runBlocking
import fuookami.ospf.kotlin.core.solver.gurobi.GurobiColumnGenerationSolver

fun main() = runBlocking {
    runExample(GurobiColumnGenerationSolver())
}

Place the Rust example in src/csp2d.rs and use this launcher in src/main.rs. See Setup for dependencies and toolchain; do not enable async for these synchronous examples.

rust
mod csp2d;

fn main() -> ospf_rust_base::error::Ret<()> {
    csp2d::run_example()
}

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 ​

ReadKotlinRust
Pattern, material and usagesolution.usages → plan.pattern / plan.material / usagesolution.usage → (plan.pattern, count)
Placements and cut treepattern.placements, pattern.cutTreepattern.placements, pattern.cut_tree
Production and material consumptioncoverage / sheetCount / consumedLength / wasteAreacoverage / material_usage / sheet_assignment / total_waste_area()
Coverage and terminationsolution.covers(problem), iterationsfully_covered / termination / failure_message

Result Semantics

covers(problem) / fully_covered means demand coverage, not an exhaustive pattern pool or global optimality. Coordinates describe one execution; multiply contributions, waste and coil segment lengths by usage. Freeform may have no cut tree.

Check demand coverage, stock consumption, geometry and manufacturing process separately. Pattern count is not sheet usage. Freeform needs no cut tree; guillotine requires a valid tree with consistent stages, regions and kerf. The Rust hand-check baseline covers twenty products on one sheet with zero net-area waste; independently verify actual output.

5. Change One Business Condition ​

Add positive kerf first: an exactly filled layout can become infeasible. Then select two-stage guillotine and regenerate patterns instead of relabelling old coordinates. Switch to coils last and interpret consumption as length rather than sheet count.

Continue to the next business scenario and integration checks. Consult repository verification when checking source behavior.