Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_multicommodity.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
105# ifndef TPL_MULTICOMMODITY_H
106# define TPL_MULTICOMMODITY_H
107
108# include <vector>
109# include <limits>
110# include <chrono>
111# include <tpl_agraph.H>
112# include <tpl_dynMapTree.H>
113# include <Simplex.H>
114# include <ah-errors.H>
115
116namespace Aleph
117{
118
129 template <typename Node, typename Flow_Type = double>
131 {
132 size_t id;
136 std::string name;
137
139 Commodity() : id(0), source(nullptr), sink(nullptr), demand(0) {}
140
142 Commodity(size_t _id, Node *_src, Node *_sink, Flow_Type _demand,
143 const std::string& _name = "")
144 : id(_id), source(_src), sink(_sink), demand(_demand), name(_name) {}
145 };
146
147
157 template <typename Arc_Info = Empty_Class, typename FT = double>
158 struct MCF_Arc : public Graph_Aarc<Arc_Info>
159 {
161 using Flow_Type = FT;
162
165 std::vector<Flow_Type> commodity_flow;
166 std::vector<Flow_Type> commodity_cost;
167
169 MCF_Arc() = default;
170
172 MCF_Arc(const Arc_Info&) : MCF_Arc() {}
173
176
180
183 {
184 Flow_Type sum = 0;
185 for (auto f : commodity_flow)
186 sum += f;
187 return sum;
188 }
189
191 Flow_Type residual() const { return capacity - total_flow(); }
192
194 Flow_Type flow(size_t k) const
195 {
196 return k < commodity_flow.size() ? commodity_flow[k] : Flow_Type{0};
197 }
198
200 Flow_Type cost(size_t k) const
201 {
202 if (k < commodity_cost.size() and commodity_cost[k] != 0)
203 return commodity_cost[k];
204 return base_cost;
205 }
206
208 void set_flow(size_t k, Flow_Type f)
209 {
210 if (k >= commodity_flow.size())
211 commodity_flow.resize(k + 1, Flow_Type{0});
212 commodity_flow[k] = f;
213 }
214
216 void set_cost(size_t k, Flow_Type c)
217 {
218 if (k >= commodity_cost.size())
219 commodity_cost.resize(k + 1, Flow_Type{0});
220 commodity_cost[k] = c;
221 }
222
224 void init_commodities(size_t K)
225 {
226 commodity_flow.assign(K, Flow_Type{0});
227 commodity_cost.assign(K, Flow_Type{0});
228 }
229 };
230
231
245 template <class NodeT = Graph_Anode<Empty_Class>,
246 class ArcT = MCF_Arc<Empty_Class, double>>
247 class MCF_Graph : public Array_Digraph<NodeT, ArcT>
248 {
249 public:
251 using Node = NodeT;
252 using Arc = ArcT;
253 using Flow_Type = typename Arc::Flow_Type;
255
256 private:
257 std::vector<CommodityType> commodities;
259
260 public:
262 MCF_Graph() = default;
263
265 size_t num_commodities() const { return commodities.size(); }
266
268 const CommodityType& get_commodity(size_t k) const
269 {
271 << "Commodity index " << k << " out of range";
272 return commodities[k];
273 }
274
276 const std::vector<CommodityType>& get_commodities() const
277 {
278 return commodities;
279 }
280
289 size_t add_commodity(Node *source, Node *sink, Flow_Type demand,
290 const std::string& name = "")
291 {
292 size_t id = commodities.size();
293 commodities.emplace_back(id, source, sink, demand, name);
294
295 // Initialize commodity flow in all arcs
296 for (typename Base::Arc_Iterator it(*this); it.has_curr(); it.next_ne())
297 it.get_curr()->init_commodities(id + 1);
298
299 return id;
300 }
301
312 Arc* insert_arc(Node *src, Node *tgt, Flow_Type capacity, Flow_Type cost = 0)
313 {
314 auto arc = Base::insert_arc(src, tgt);
315 arc->capacity = capacity;
316 arc->base_cost = cost;
317 arc->init_commodities(commodities.size());
318 return arc;
319 }
320
323 {
325 size_t idx = 0;
326 for (typename Base::Node_Iterator it(*this); it.has_curr(); it.next_ne())
327 node_to_idx.insert(it.get_curr(), idx++);
328 }
329
331 size_t get_node_index(Node *p) const
332 {
333 return node_to_idx.find(p);
334 }
335
338 {
339 Flow_Type sum = 0;
340 for (typename Base::Arc_Iterator it(*this); it.has_curr(); it.next_ne())
341 {
342 auto arc = it.get_curr();
343 for (size_t k = 0; k < commodities.size(); ++k)
344 sum += arc->flow(k) * arc->cost(k);
345 }
346 return sum;
347 }
348
361 bool demands_satisfied() const
362 {
363 if (commodities.empty())
364 return true;
365
367 for (const auto& comm : commodities)
368 {
369 Flow_Type out_flow = 0;
370 for (Out_Iterator<MCF_Graph> it(comm.source); it.has_curr(); it.next_ne())
371 out_flow += it.get_curr()->flow(comm.id);
372
373 Flow_Type in_flow = 0;
374 for (auto it = in_arcs.get_it(comm.source); it.has_curr(); it.next_ne())
375 in_flow += it.get_curr_ne()->flow(comm.id);
376
377 if (std::abs((out_flow - in_flow) - comm.demand) > 1e-6)
378 return false;
379 }
380 return true;
381 }
382
385 {
386 for (typename Base::Arc_Iterator it(*this); it.has_curr(); it.next_ne())
387 {
388 auto arc = it.get_curr();
389 if (arc->total_flow() > arc->capacity + 1e-6)
390 return false;
391 }
392 return true;
393 }
394
396 void print_summary() const
397 {
398 std::cout << "=== Multi-commodity Network ===\n"
399 << "Nodes: " << this->vsize() << "\n"
400 << "Arcs: " << this->esize() << "\n"
401 << "Commodities: " << commodities.size() << "\n";
402
403 for (const auto& c : commodities)
404 std::cout << " [" << c.id << "] " << c.name
405 << ": demand=" << c.demand << "\n";
406
407 std::cout << "Total cost: " << total_cost() << "\n";
408 }
409 };
410
411
420 template <typename Flow_Type = double>
422 {
424
427 std::vector<Flow_Type> commodity_costs;
428 double solve_time_ms = 0;
429 size_t iterations = 0;
430
431 bool is_optimal() const { return status == Optimal; }
432 };
433
434
456 template <class Net>
458 {
459 public:
460 using Node = typename Net::Node;
461 using Arc = typename Net::Arc;
462 using Flow_Type = typename Net::Flow_Type;
464
465 private:
468
469 // Get variable index for commodity k on arc a
470 size_t var_index(size_t k, size_t arc_idx) const
471 {
472 return k * net.esize() + arc_idx;
473 }
474
475 public:
480 explicit MCF_LP_Solver(Net& network) : net(network)
481 {
482 // Build arc index
483 size_t idx = 0;
484 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
485 arc_to_idx.insert(it.get_curr(), idx++);
486 }
487
497 {
498 Result result;
499 auto start_time = std::chrono::high_resolution_clock::now();
500
501 const size_t K = net.num_commodities();
502 const size_t E = net.esize();
503
504 if (K == 0 || E == 0)
505 {
506 result.status = Result::Optimal;
507 result.total_cost = 0;
508 return result;
509 }
510
511 // Build node index
512 net.build_node_index();
513
514 // LP dimensions
515 const size_t num_vars = K * E; // x_{ij}^k for each arc and commodity
516
517 // Create LP solver for minimization
518 Simplex<Flow_Type> lp(num_vars);
519 lp.set_minimize();
520
521 // Set objective: minimize Σ c_ij^k * x_ij^k
522 size_t var_idx = 0;
523 for (size_t k = 0; k < K; ++k)
524 {
525 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne(), ++var_idx)
526 {
527 auto arc = it.get_curr();
528 lp.put_objetive_function_coef(var_idx, arc->cost(k));
529 }
530 }
531
532 // Build incoming arcs map: for each node, list of arcs entering it
533 // (In Array_Digraph, nodes only store outgoing arcs, so we build this manually)
534 DynMapTree<Node*, DynList<Arc*>> incoming_arcs;
535 for (typename Net::Arc_Iterator ait(net); ait.has_curr(); ait.next_ne())
536 {
537 auto arc = ait.get_curr();
538 auto tgt = static_cast<Node*>(arc->tgt_node);
539 incoming_arcs[tgt].append(arc);
540 }
541
542 // Flow conservation constraints: Σ_j x_ij^k - Σ_j x_ji^k = b_i^k
543 // Use equality constraints
544 // Row format: n coefficients + RHS at the end
545 // NOTE: We skip the sink node because the constraints are linearly
546 // dependent (sum of all = 0). Only N-1 constraints are needed.
547 size_t eq_count = 0;
548 for (size_t k = 0; k < K; ++k)
549 {
550 const auto& comm = net.get_commodity(k);
551
552 for (typename Net::Node_Iterator nit(net); nit.has_curr(); nit.next_ne())
553 {
554 auto node = nit.get_curr();
555
556 // Skip sink node - constraint is redundant
557 if (node == comm.sink)
558 continue;
559
560 // Determine b_i^k
561 Flow_Type b = 0;
562 if (node == comm.source)
563 b = comm.demand;
564 // else: intermediate node, b = 0
565
566 // Build constraint row: [coefficients, RHS]
567 std::vector<Flow_Type> row(num_vars + 1, Flow_Type{0});
568
569 // Outgoing arcs (+1 coefficient) - use Node_Arc_Iterator
570 for (typename Net::Node_Arc_Iterator ait(node); ait.has_curr(); ait.next_ne())
571 {
572 auto arc = ait.get_curr();
573 size_t a_idx = arc_to_idx.find(arc);
574 row[var_index(k, a_idx)] = Flow_Type{1};
575 }
576
577 // Incoming arcs (-1 coefficient) - use our pre-built map
578 if (incoming_arcs.has(node))
579 {
580 auto& in_list = incoming_arcs[node];
581 for (auto it = in_list.get_it(); it.has_curr(); it.next_ne())
582 {
583 auto arc = it.get_curr();
584 size_t a_idx = arc_to_idx.find(arc);
585 row[var_index(k, a_idx)] = Flow_Type{-1};
586 }
587 }
588
589 // RHS at the end
590 row[num_vars] = b;
591
592 // Add equality constraint (now works correctly with mixed LE constraints)
593 lp.put_eq_restriction(row.data());
594 ++eq_count;
595 }
596 }
597
598 // Capacity constraints: Σ_k x_ij^k ≤ u_ij
599 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne())
600 {
601 auto arc = it.get_curr();
602 size_t a_idx = arc_to_idx.find(arc);
603
604 // Row format: [coefficients, RHS]
605 std::vector<Flow_Type> row(num_vars + 1, Flow_Type{0});
606 for (size_t k = 0; k < K; ++k)
607 row[var_index(k, a_idx)] = Flow_Type{1};
608
609 row[num_vars] = arc->capacity; // RHS
610
611 lp.put_restriction(row.data());
612 }
613
614 // Prepare and solve LP
616 auto lp_state = lp.solve();
617
618 if (lp_state != Simplex<Flow_Type>::Solved)
619 {
620 result.status = (lp_state == Simplex<Flow_Type>::Unbounded)
622 return result;
623 }
624
625 // Load solution
626 lp.load_solution();
627
628 // Extract solution
629 result.status = Result::Optimal;
630 result.commodity_costs.resize(K, Flow_Type{0});
631
632 var_idx = 0;
633 for (size_t k = 0; k < K; ++k)
634 {
635 for (typename Net::Arc_Iterator it(net); it.has_curr(); it.next_ne(), ++var_idx)
636 {
637 auto arc = it.get_curr();
638 Flow_Type flow = lp.get_solution(var_idx);
639 if (flow < 0) flow = 0; // Numerical cleanup
640
641 arc->set_flow(k, flow);
642 result.commodity_costs[k] += flow * arc->cost(k);
643 }
644 }
645
646 result.total_cost = lp.objetive_value();
647
648 auto end_time = std::chrono::high_resolution_clock::now();
649 result.solve_time_ms = std::chrono::duration<double, std::milli>(
650 end_time - start_time).count();
651 result.iterations = lp.get_stats().iterations;
652
653 return result;
654 }
655
660 void print_formulation(size_t max_constraints = 10) const
661 {
662 const size_t K = net.num_commodities();
663 const size_t E = net.esize();
664 const size_t V = net.vsize();
665
666 std::cout << "=== MCF LP Formulation ===\n"
667 << "Variables: " << (K * E) << " (K=" << K << " × E=" << E << ")\n"
668 << "Constraints: " << (K * V + E)
669 << " (flow: " << (K * V) << ", capacity: " << E << ")\n\n";
670
671 std::cout << "Objective: minimize Σ c_ij^k * x_ij^k\n\n";
672
673 std::cout << "Commodities:\n";
674 for (size_t k = 0; k < K; ++k)
675 {
676 const auto& c = net.get_commodity(k);
677 std::cout << " k=" << k << ": demand=" << c.demand << "\n";
678 }
679 }
680 };
681
682
694 template <class Net>
696 {
697 MCF_LP_Solver<Net> solver(net);
698 return solver.solve();
699 }
700
701} // end namespace Aleph
702
703# endif // TPL_MULTICOMMODITY_H
Simplex algorithm for linear programming.
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
WeightedDigraph::Node Node
size_t row
Definition ca-c-api.h:115
Iterator over the arcs of a node.
Definition tpl_agraph.H:354
bool has_curr() const noexcept
Return true if the iterator is on an arc.
Definition tpl_agraph.H:387
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Generic key-value map implemented on top of a binary search tree.
Pair * append(const Key &key, const Data &data)
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Data & find(const Key &key)
Find the value associated with key.
bool has(const Key &key) const noexcept(nothrow_search)
Return whether key is in the map.
void empty()
Remove all the elements of the set.
Index of the arcs that go into each node of a graph.
Definition tpl_graph.H:2224
Multi-commodity flow network (directed graph).
const std::vector< CommodityType > & get_commodities() const
Get all commodities.
MCF_Graph()=default
Default constructor.
void print_summary() const
Print network summary.
DynMapTree< Node *, size_t > node_to_idx
Flow_Type total_cost() const
Total flow cost across all commodities.
size_t add_commodity(Node *source, Node *sink, Flow_Type demand, const std::string &name="")
Add a commodity to the network.
void build_node_index()
Build node index mapping (call after all nodes inserted)
std::vector< CommodityType > commodities
Arc * insert_arc(Node *src, Node *tgt, Flow_Type capacity, Flow_Type cost=0)
Insert arc with capacity and cost.
const CommodityType & get_commodity(size_t k) const
Get commodity by index.
bool capacities_respected() const
Check capacity constraints.
size_t num_commodities() const
Get number of commodities.
size_t get_node_index(Node *p) const
Get node index.
bool demands_satisfied() const
Check if all demands are satisfied.
typename Arc::Flow_Type Flow_Type
Multi-commodity flow solver using LP formulation.
typename Net::Flow_Type Flow_Type
size_t var_index(size_t k, size_t arc_idx) const
typename Net::Node Node
Result solve()
Solve the multi-commodity flow problem.
void print_formulation(size_t max_constraints=10) const
Print LP formulation (for debugging).
MCF_LP_Solver(Net &network)
Construct solver for a network.
DynMapTree< Arc *, size_t > arc_to_idx
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Linear program solver using the Simplex method.
Definition Simplex.H:279
const SimplexStats & get_stats() const noexcept
Gets execution statistics.
Definition Simplex.H:1618
void set_minimize() noexcept
Sets minimization mode.
Definition Simplex.H:1001
T objetive_value() const noexcept
Computes and returns the objective function value.
Definition Simplex.H:1374
T * put_restriction(const T *coefs=nullptr, ConstraintType type=ConstraintType::LE)
Adds a constraint to the linear program.
Definition Simplex.H:1132
void prepare_linear_program()
Prepares the linear program for solving.
Definition Simplex.H:1287
const T & get_solution(size_t i) const noexcept
Gets the solution value for a specific variable.
Definition Simplex.H:1360
void put_objetive_function_coef(size_t i, const T &coef)
Sets a coefficient in the objective function.
Definition Simplex.H:1072
void load_solution() noexcept
Loads the solution values into the solution array.
Definition Simplex.H:1337
T * put_eq_restriction(const T *coefs)
Adds an = constraint.
Definition Simplex.H:1173
State solve()
Solves the linear program.
Definition Simplex.H:1310
constexpr size_t vsize() const noexcept
See get_num_nodes().
Definition graph-dry.H:984
size_t esize() const noexcept
Return the total of arcs of graph.
Definition graph-dry.H:1078
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
DynList< typename GT::Arc * > in_arcs(typename GT::Node *p, SA sa=SA())
Return the filtered incoming arcs of p.
Definition tpl_graph.H:2671
double Flow_Type
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
MCF_Result< typename Net::Flow_Type > solve_multicommodity_flow(Net &net)
Solve multi-commodity flow problem.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Iterator over arcs of a graph.
Definition tpl_agraph.H:334
Commodity definition for multi-commodity flow.
Node * source
Source node for this commodity.
Commodity(size_t _id, Node *_src, Node *_sink, Flow_Type _demand, const std::string &_name="")
Full constructor.
size_t id
Unique commodity identifier.
Flow_Type demand
Required flow amount.
std::string name
Optional descriptive name.
Node * sink
Sink node for this commodity.
Commodity()
Default constructor.
Arc information for multi-commodity flow.
Flow_Type cost(size_t k) const
Get cost for commodity k.
Flow_Type capacity
Arc capacity (shared)
MCF_Arc(Flow_Type cap, Flow_Type cost=0)
Constructor with capacity and cost.
Flow_Type flow(size_t k) const
Get flow for commodity k.
Flow_Type base_cost
Default cost per unit flow.
Flow_Type residual() const
Residual capacity.
MCF_Arc()=default
Default constructor.
Flow_Type total_flow() const
Total flow on this arc (sum of all commodities)
void set_flow(size_t k, Flow_Type f)
Set flow for commodity k.
MCF_Arc(const Arc_Info &)
Constructor from Arc_Info (required by graph framework)
void set_cost(size_t k, Flow_Type c)
Set cost for commodity k.
FT Flow_Type
Type for flow values.
std::vector< Flow_Type > commodity_cost
Cost per commodity (optional)
MCF_Arc(Arc_Info &&)
Constructor from Arc_Info rvalue (required by graph framework)
void init_commodities(size_t K)
Initialize for K commodities.
std::vector< Flow_Type > commodity_flow
Flow per commodity.
Multi-commodity flow result.
std::vector< Flow_Type > commodity_costs
Cost per commodity.
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
ArcT Arc
Arc type.
Definition tpl_net.H:322
typename Arc::Flow_Type Flow_Type
Capacity/flow numeric type.
Definition tpl_net.H:328
NodeT Node
Node type.
Definition tpl_net.H:325
size_t iterations
Total simplex iterations.
Definition Simplex.H:99
size_t V
static int * k
Array-based graph implementation.
Dynamic key-value map based on balanced binary search trees.