Skip to content

Your First Network Flow: Balances, Capacity and Cost ​

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

1. Business Scenario ​

Source supplies two units and sink demands two. A delivery arc connects them with bounds 0–3 and cost 3 per unit. Use a common dimensionless unit first to learn balances, capacity, a real solve call and result handling.

Write supply as +2 and demand as -2 so total balance is zero. Hand calculation gives flow 2 and cost 6. Node, service and commodity IDs are separate; parallel services must not be identified by endpoints alone.

2. Construct Input and Call the Framework ​

Kotlin and Rust Entry Points

Kotlin constructors for nodes, arcs, bounds and commodities return Ret; the example handles failures before calling NetworkFlowApplicationService. Rust uses FlowProblem::new and FlowApplicationService with an actual LinearSolver. Read the returned report for status before extracting business flows.

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

kt
package docs.examples.network

import fuookami.ospf.kotlin.math.algebra.number.Flt64
import fuookami.ospf.kotlin.quantities.quantity.Quantity
import fuookami.ospf.kotlin.quantities.unit.NoneUnit
import fuookami.ospf.kotlin.framework.solver.ColumnGenerationSolver
import fuookami.ospf.kotlin.framework.network_scheduling.infrastructure.*
import fuookami.ospf.kotlin.framework.network_scheduling.domain.flow.*
import fuookami.ospf.kotlin.framework.network_scheduling.domain.flow.model.*
import fuookami.ospf.kotlin.framework.network_scheduling.application.service.*
import fuookami.ospf.kotlin.utils.functional.*

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}" })
}

suspend fun runExample(solver: ColumnGenerationSolver) {
    fun q(value: Double) = Quantity(Flt64(value), NoneUnit)
    val source = NetworkNode<Flt64>(NetworkNodeId("source")).getOrThrow()
    val sink = NetworkNode<Flt64>(NetworkNodeId("sink")).getOrThrow()
    val arc = NetworkArc(
        id = NetworkArcId("delivery"), from = source.id, to = sink.id, cost = q(3.0)
    ).getOrThrow()
    val bounds = CapacityBounds(lower = q(0.0), upper = q(3.0)).getOrThrow()
    val commodity = FlowCommodity("goods", listOf(
        SupplyDemand(source.id, NodeBalance(q(2.0)).getOrThrow()).getOrThrow(),
        SupplyDemand(sink.id, NodeBalance(q(-2.0)).getOrThrow()).getOrThrow()
    )).getOrThrow()
    val problem = FlowProblem(
        graph = NetworkGraph(listOf(source, sink), listOf(arc)).getOrThrow(),
        arcs = listOf(FlowArc(arc, bounds).getOrThrow()),
        commodities = listOf(CommodityFlow(commodity, NoneUnit)), zero = Flt64.zero
    )
    val outcome = NetworkFlowApplicationService(solver, Flt64NetworkSchedulingSolverValueAdapter)
        .solve(problem).getOrThrow()
    println(outcome.report)
    val solution = outcome.solution
    if (solution == null) {
        println("No flow; inspect infeasibility or the no-incumbent termination")
    } else {
        // #region result
        for ((key, amount) in solution.flows) {
            println("commodity=${key.commodity}, arc=${key.arc}, amount=$amount")
        }
        println("resource usage=${solution.capacityUsage}")
        println("unused supply=${solution.unusedSupply}, unmet demand=${solution.unmetDemand}")
        println("cost=${solution.cost}, commodity costs=${solution.commodityCosts}, penalty=${solution.relaxationCost}")
        check(solution.flows[FlowKey("goods", arc.id)] == q(2.0))
        // #endregion result
    }
}
rs
use ospf_rust_core::solver::LinearSolver;
use ospf_rust_framework_network_scheduling::application::FlowApplicationService;
use ospf_rust_framework_network_scheduling::domain::flow::{FlowArc, FlowCommodity, FlowNode, FlowProblem};
use ospf_rust_framework_network_scheduling::infrastructure::{CapacityBounds, NetworkCost};
use ospf_rust_quantities::{Quantity, unit::{CTUnit, NoneUnit}};

pub fn run_example<S: LinearSolver>(solver: S) -> Result<(), String> {
    let q = |value| Quantity::new(value, NoneUnit::INSTANT.clone());
    let problem = FlowProblem::new(
        vec![FlowNode::new("source"), FlowNode::new("sink")],
        vec![FlowArc::new("delivery", "source", "sink",
            CapacityBounds::try_new(q(0.0), q(3.0)).map_err(|e| format!("{e:?}"))?,
            NetworkCost::new(q(3.0)))],
        vec![FlowCommodity::new("goods")
            .with_balance("source", q(2.0)).with_balance("sink", q(-2.0))],
    ).map_err(|e| format!("{e:?}"))?;
    let report = FlowApplicationService::new(solver).solve(&problem).map_err(|e| format!("{e:?}"))?;
    println!("report={report:?}");
    match report.solution.and_then(|solution| solution.value) {
        Some(flow) => {
            // #region result
            for ((commodity, arc), amount) in &flow.flows { println!("commodity={commodity:?}, arc={arc:?}, amount={amount:?}"); }
            println!("resource usage={:?}", flow.resources);
            println!("unused supply={:?}, unmet demand={:?}", flow.spills, flow.shortages);
            println!("operating={:?}, penalties=({:?}, {:?}), total={:?}", flow.operating_cost, flow.spill_cost, flow.shortage_cost, flow.total_cost);
            assert_eq!(flow.flows.values().next().map(|q| q.value), Some(2.0));
            // #endregion result
        },
        None => println!("No flow; retain the report and its termination reason"),
    }
    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.network.runExample
import kotlinx.coroutines.runBlocking
import fuookami.ospf.kotlin.core.solver.gurobi.GurobiColumnGenerationSolver

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

Place the Rust example in src/network.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 network;
use ospf_rust_core::solver::solvers::scip::SCIPSolver;

fn main() -> Result<(), String> {
    network::run_example(SCIPSolver::new())
}

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
Actual commodity flowssolution.flows: FlowKey(commodity, arc) → Quantityflow.flows: (CommodityId, NetworkArcId) → Quantity
Shared-resource usagecapacityUsageresources
Spills and shortagesunusedSupply / unmetDemandspills / shortages
Cost decomposition and statuscost / commodityCosts / relaxationCost, outcome.reportoperating_cost / spill_cost / shortage_cost / total_cost, report

Result Semantics

The solution may be absent; use the report for infeasibility or termination without a feasible solution. This entry has no candidate-pool complete. Bounded shortages may be valid model output, while delivery acceptance remains a business decision.

Read the report and optional business solution. Verify outflow 2 at source, inflow 2 at sink, arc flow within 0–3, and cost 2 × 3 = 6. Solver steps are not physical quantities, and outer success is not demand fulfillment.

5. Change One Business Condition ​

Reduce capacity from three to one. Hard balances should yield no complete feasible flow, not silently discard an order unit. Restore capacity and add a second service with a distinct ID and cost. Shortage requires an explicit bounded and costed relaxation.

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