Shared Resources, Shortage and Embedding
After your first network flow, add a non-arc capacity before deciding whether shortage is allowed. Connectivity and adequate arc capacity do not establish business feasibility.
1. A Shared Handling Resource Can Make Flow Infeasible
Use normalized units of one commodity: source supplies 2, sink demands 2, and the delivery arc has capacity 3. Add shared dock capacity 1, consuming one resource unit per transported commodity unit.
The arc can carry demand but dock cannot. Another arc does not necessarily help if it consumes the same dock. Feasibility requires more resource capacity, different actual consumption or explicitly authorized demand relaxation.
Start from the first-lesson flow problem, retain balances and add only the shared resource row. Solve again and check actual flows and shared-resource consumption.
2. Convert Resource Units Across Commodities
Build Balances and Arcs Before Adding the Dock
The code normalizes one business unit of a single commodity to NoneUnit, with nodes source and sink. Start with makeProblem(2.0) / make_problem(2.0), then reduce dock capacity to 1.0. Arc capacity stays at 3 and balances stay at ±2.
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(q(0.0), q(3.0)).getOrThrow()
val goods = FlowCommodity("goods", listOf(
SupplyDemand(source.id, NodeBalance(q(2.0)).getOrThrow()).getOrThrow(),
SupplyDemand(sink.id, NodeBalance(q(-2.0)).getOrThrow()).getOrThrow())).getOrThrow()let arcs = 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)))];
let goods = FlowCommodity::new("goods").with_balance("source", q(2.0)).with_balance("sink", q(-2.0));
let problem = FlowProblem::new(vec![FlowNode::new("source"), FlowNode::new("sink")], arcs, vec![goods])
.map_err(|e| format!("{e:?}"))?;| Object | Kotlin | Rust |
|---|---|---|
| Shared resource | FlowCapacity | FlowResource |
| Commodity-arc usage | usage keyed by FlowKey | commodity/arc keys in consumptions |
| Allowed services | allowedArcs | allowed_arcs |
| Elastic balances | FlowSlack | FlowBalanceSlack |
Unit Constraints
Commodities measured in kg, m or pieces need resource-unit/commodity-unit conversion coefficients before summation. Normalized integer steps are not physical usage. Distinct parallel-service IDs must remain distinct.
3. Shortage Needs Bounds and Costs
Construct a separate spill/shortage scenario using one normalized unit:
| Condition | Value |
|---|---|
| Supply at source / demand at sink | 3 / 4 |
| Arc capacity / transport price | 2 / 1 |
| Allowed unused supply at source / penalty | At most 1 / 5 |
| Allowed unmet demand at sink / penalty | At most 2 / 7 |
Flow 2, unused supply 1 and shortage 2 cost 2×1 + 1×5 + 2×7 = 21. Shortage does not change the order from 4 to 2; retain original demand in output. Relaxation bounds are finite, not unlimited.
In either language, report transported quantities, unused supply, unmet demand and each cost component separately. Equal costs for different inputs do not establish equivalent business outcomes.
Inject Bounded Relaxation
makeSlackProblem() / make_slack_problem() constructs the separate table scenario without the dock restriction. Solve it through the first lesson’s service, then read spills, shortages and cost components.
val slacks = listOf(
FlowSlack("goods", source, unusedSupply = q(1.0), unmetDemand = q(0.0), penalty = q(5.0)),
FlowSlack("goods", sink, unusedSupply = q(0.0), unmetDemand = q(2.0), penalty = q(7.0)))
return FlowProblem(graph = NetworkGraph(base.graph.nodes, listOf(arc)).getOrThrow(),
arcs = listOf(FlowArc(arc, CapacityBounds(q(0.0), q(2.0)).getOrThrow()).getOrThrow()),
commodities = listOf(CommodityFlow(goods, NoneUnit)), zero = Flt64.zero, slacks = slacks)goods.slacks.insert("source".into(), FlowBalanceSlack { spill_limit: q(1.0), shortage_limit: q(0.0),
spill_cost: NetworkCost::new(q(5.0)), shortage_cost: NetworkCost::new(q(0.0)) });
goods.slacks.insert("sink".into(), FlowBalanceSlack { spill_limit: q(0.0), shortage_limit: q(2.0),
spill_cost: NetworkCost::new(q(0.0)), shortage_cost: NetworkCost::new(q(7.0)) });
FlowProblem::new(vec![FlowNode::new("source"), FlowNode::new("sink")], vec![FlowArc::new("delivery", "source", "sink",
CapacityBounds::try_new(q(0.0), q(2.0)).map_err(|e| format!("{e:?}"))?, NetworkCost::new(q(1.0)))], vec![goods])
.map_err(|e| format!("{e:?}"))Call the Standalone Service
The same service solves the problem with shared capacity. Pure flow has no column-count or pricing-round option. Configure budgets in the actual linear/integer backend and retain its report with the business result.
suspend fun runBusiness(solver: ColumnGenerationSolver, dockCapacity: Double = 2.0) =
NetworkFlowApplicationService(solver, Flt64NetworkSchedulingSolverValueAdapter).solve(makeProblem(dockCapacity))pub fn run_business<S: LinearSolver>(solver: S, dock_capacity: f64) -> Result<(), String> {
let report = FlowApplicationService::new(solver).solve(&make_problem(dock_capacity)?).map_err(|e| format!("{e:?}"))?;
println!("{report:?}");
Ok(())
}4. Wire a Joint Model Correctly
Minimal Business Rule: A Shared Dock Capacity Row
Use the existing domain contract rather than inventing a policy interface. Kotlin injects FlowCapacity through FlowProblem.resources; Rust injects FlowResource with with_resources. Consumption is one resource unit per normalized commodity unit; add more commodity/service keys to the same row for sharing.
val dock = FlowCapacity("dock", CapacityBounds(q(0.0), q(dockCapacity)).getOrThrow(),
usage = mapOf(FlowKey("goods", arc.id) to q(1.0)))
return FlowProblem(graph = NetworkGraph(listOf(source, sink), listOf(arc)).getOrThrow(),
arcs = listOf(FlowArc(arc, bounds).getOrThrow()), commodities = listOf(CommodityFlow(goods, NoneUnit)),
zero = Flt64.zero, resources = listOf(dock))let dock = FlowResource { id: "dock".into(),
capacity: CapacityBounds::try_new(q(0.0), q(dock_capacity)).map_err(|e| format!("{e:?}"))?,
consumptions: [(("goods".into(), "delivery".into()), q(1.0))].into_iter().collect() };
problem.with_resources(vec![dock]).map_err(|e| format!("{e:?}"))Standalone entry points are Kotlin NetworkFlowApplicationService and Rust FlowApplicationService. For joint network construction, scheduling or shared-budget decisions, register FlowContext in the common model and solve at the upper layer.
Shared IDs alone are insufficient: decisions must connect through actual variables, constraints or expressions. Cheapest transport followed by a separate scheduler is generally a decomposed business process, not joint optimality. A decomposition algorithm needs explicit feedback, feasibility repair and termination evidence.
Keep context/variable mappings consistent. Never replay an old vector into a fresh model by stale indices. Isolate request state and do not reuse partially registered state after an error.
5. Acceptance and Exercises
- Increase dock capacity from 1 to 2 to recover hard-demand feasibility; increase to 3 and verify only demand 2 is transported.
- Retain original demand, add explicit bounded shortage, then tighten its limit below the capacity deficit and verify infeasibility returns.
- Check conservation, arc bounds, shared resources and slacks per commodity. Recompute operating, unused-supply and shortage costs separately.
- In a joint model, change the shared budget and verify both domains' decisions respond, rather than returning unrelated outputs.
Whether a shortage plan is deliverable is a business decision, not implied by outer success. Retain shortfalls and true status using the integration guide; continue to Gantt for time and personnel across locations.
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
package docs.examples.network.business
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}" })
}
fun makeProblem(dockCapacity: Double = 2.0): FlowProblem<Flt64> {
fun q(value: Double) = Quantity(Flt64(value), NoneUnit)
// #region input
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(q(0.0), q(3.0)).getOrThrow()
val goods = FlowCommodity("goods", listOf(
SupplyDemand(source.id, NodeBalance(q(2.0)).getOrThrow()).getOrThrow(),
SupplyDemand(sink.id, NodeBalance(q(-2.0)).getOrThrow()).getOrThrow())).getOrThrow()
// #endregion input
// #region rule
val dock = FlowCapacity("dock", CapacityBounds(q(0.0), q(dockCapacity)).getOrThrow(),
usage = mapOf(FlowKey("goods", arc.id) to q(1.0)))
return FlowProblem(graph = NetworkGraph(listOf(source, sink), listOf(arc)).getOrThrow(),
arcs = listOf(FlowArc(arc, bounds).getOrThrow()), commodities = listOf(CommodityFlow(goods, NoneUnit)),
zero = Flt64.zero, resources = listOf(dock))
// #endregion rule
}
fun makeSlackProblem(): FlowProblem<Flt64> {
fun q(value: Double) = Quantity(Flt64(value), NoneUnit)
val base = makeProblem()
val source = NetworkNodeId("source")
val sink = NetworkNodeId("sink")
val arc = NetworkArc(id = NetworkArcId("delivery"), from = source, to = sink, cost = q(1.0)).getOrThrow()
val goods = FlowCommodity("goods", listOf(
SupplyDemand(source, NodeBalance(q(3.0)).getOrThrow()).getOrThrow(),
SupplyDemand(sink, NodeBalance(q(-4.0)).getOrThrow()).getOrThrow())).getOrThrow()
// #region slack
val slacks = listOf(
FlowSlack("goods", source, unusedSupply = q(1.0), unmetDemand = q(0.0), penalty = q(5.0)),
FlowSlack("goods", sink, unusedSupply = q(0.0), unmetDemand = q(2.0), penalty = q(7.0)))
return FlowProblem(graph = NetworkGraph(base.graph.nodes, listOf(arc)).getOrThrow(),
arcs = listOf(FlowArc(arc, CapacityBounds(q(0.0), q(2.0)).getOrThrow()).getOrThrow()),
commodities = listOf(CommodityFlow(goods, NoneUnit)), zero = Flt64.zero, slacks = slacks)
// #endregion slack
}
// #region entry
suspend fun runBusiness(solver: ColumnGenerationSolver, dockCapacity: Double = 2.0) =
NetworkFlowApplicationService(solver, Flt64NetworkSchedulingSolverValueAdapter).solve(makeProblem(dockCapacity))
// #endregion entryuse 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, FlowResource, FlowBalanceSlack};
use ospf_rust_framework_network_scheduling::infrastructure::{CapacityBounds, NetworkCost};
use ospf_rust_quantities::{Quantity, unit::{CTUnit, NoneUnit}};
pub fn make_problem(dock_capacity: f64) -> Result<FlowProblem<f64>, String> {
let q = |value| Quantity::new(value, NoneUnit::INSTANT.clone());
// #region input
let arcs = 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)))];
let goods = FlowCommodity::new("goods").with_balance("source", q(2.0)).with_balance("sink", q(-2.0));
let problem = FlowProblem::new(vec![FlowNode::new("source"), FlowNode::new("sink")], arcs, vec![goods])
.map_err(|e| format!("{e:?}"))?;
// #endregion input
// #region rule
let dock = FlowResource { id: "dock".into(),
capacity: CapacityBounds::try_new(q(0.0), q(dock_capacity)).map_err(|e| format!("{e:?}"))?,
consumptions: [(("goods".into(), "delivery".into()), q(1.0))].into_iter().collect() };
problem.with_resources(vec![dock]).map_err(|e| format!("{e:?}"))
// #endregion rule
}
pub fn make_slack_problem() -> Result<FlowProblem<f64>, String> {
let q = |value| Quantity::new(value, NoneUnit::INSTANT.clone());
let mut goods = FlowCommodity::new("goods").with_balance("source", q(3.0)).with_balance("sink", q(-4.0));
// #region slack
goods.slacks.insert("source".into(), FlowBalanceSlack { spill_limit: q(1.0), shortage_limit: q(0.0),
spill_cost: NetworkCost::new(q(5.0)), shortage_cost: NetworkCost::new(q(0.0)) });
goods.slacks.insert("sink".into(), FlowBalanceSlack { spill_limit: q(0.0), shortage_limit: q(2.0),
spill_cost: NetworkCost::new(q(0.0)), shortage_cost: NetworkCost::new(q(7.0)) });
FlowProblem::new(vec![FlowNode::new("source"), FlowNode::new("sink")], vec![FlowArc::new("delivery", "source", "sink",
CapacityBounds::try_new(q(0.0), q(2.0)).map_err(|e| format!("{e:?}"))?, NetworkCost::new(q(1.0)))], vec![goods])
.map_err(|e| format!("{e:?}"))
// #endregion slack
}
// #region entry
pub fn run_business<S: LinearSolver>(solver: S, dock_capacity: f64) -> Result<(), String> {
let report = FlowApplicationService::new(solver).solve(&make_problem(dock_capacity)?).map_err(|e| format!("{e:?}"))?;
println!("{report:?}");
Ok(())
}
// #endregion entry