Skip to content

Commit da1cf8d

Browse files
committed
Merge Algorithm\Balance into Algorithm\Flow
1 parent 85efcba commit da1cf8d

File tree

4 files changed

+55
-92
lines changed

4 files changed

+55
-92
lines changed

src/Balance.php

Lines changed: 0 additions & 62 deletions
This file was deleted.

src/Flow.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,44 @@ public function getFlowVertex(Vertex $vertex)
7474

7575
return $sumOfFlow;
7676
}
77+
78+
public function getBalance()
79+
{
80+
$balance = 0;
81+
// Sum for all vertices of value
82+
foreach ($this->set->getVertices() as $vertex) {
83+
$balance += $vertex->getBalance();
84+
}
85+
86+
return $balance;
87+
}
88+
89+
/**
90+
* check if the current flow is balanced (aka "balanced flow" or "b-flow")
91+
*
92+
* a flow is considered balanced if each edge's current flow does not exceed its
93+
* maximum capacity (which is always guaranteed due to the implementation
94+
* of Edge::setFlow()) and each vertices' flow (i.e. outflow-inflow) equals
95+
* its balance.
96+
*
97+
* checking whether the FLOW is balanced is not to be confused with checking
98+
* whether the GRAPH is balanced (see Graph::isBalanced() instead)
99+
*
100+
* @return boolean
101+
* @see Algorithm\Degree::isBalanced() if you merely want to check indegree=outdegree
102+
* @uses self::getFlowVertex()
103+
* @uses Vertex::getBalance()
104+
*/
105+
public function isBalancedFlow()
106+
{
107+
// no need to check for each edge: flow <= capacity (setters already check that)
108+
// check for each vertex: outflow-inflow = balance
109+
foreach ($this->set->getVertices() as $vertex) {
110+
if ($this->getFlowVertex($vertex) !== $vertex->getBalance()) {
111+
return false;
112+
}
113+
}
114+
115+
return true;
116+
}
77117
}

tests/BalanceTest.php

Lines changed: 0 additions & 30 deletions
This file was deleted.

tests/FlowTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ public function testGraphEmpty()
1212
$alg = new AlgorithmFlow($graph);
1313

1414
$this->assertFalse($alg->hasFlow());
15+
$this->assertEquals(0, $alg->getBalance());
16+
$this->assertTrue($alg->isBalancedFlow());
1517

1618
return $graph;
1719
}
@@ -59,4 +61,17 @@ public function testGraphWithUnweightedEdges(Graph $graph)
5961

6062
$this->assertTrue($alg->hasFlow());
6163
}
64+
65+
public function testGraphBalance()
66+
{
67+
// source(+100) -> sink(-10)
68+
$graph = new Graph();
69+
$graph->createVertex('source')->setBalance(100);
70+
$graph->createVertex('sink')->setBalance(-10);
71+
72+
$alg = new AlgorithmFlow($graph);
73+
74+
$this->assertEquals(90, $alg->getBalance());
75+
$this->assertFalse($alg->isBalancedFlow());
76+
}
6277
}

0 commit comments

Comments
 (0)