Skip to content

[WIP] Add simple cycles algorithm #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions src/SimpleCycles.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

namespace Graphp\Algorithms;

use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Set\Vertices;
use Fhaculty\Graph\Vertex;

class SimpleCycles
{
/** @var Vertex[] */
protected $blockedSet;

/** @var Vertex[][] */
protected $blockedMap;

/** @var Vertex[] */
protected $stack;

/** @var Vertices[] */
protected $cycles;

/**
* Remove node from blocked set and recursively remove all dependent nodes from blocked set
* @param Vertex $v Node to unblock
*/
protected function unblock(Vertex $v)
{
unset($this->blockedSet[$v->getId()]);
if (isset($this->blockedMap[$v->getId()])) {
foreach ($this->blockedMap[$v->getId()] as $w) {
if (isset($this->blockedSet[$w->getId()])) {
$this->unblock($w);
}
}
unset($this->blockedMap[$v->getId()]);
}
}

/**
* Recursive node visit procedure
* @param Vertex $r Root node
* @param Vertex $v Visited node
* @return bool Found cycle
*/
protected function visit(Vertex $r, Vertex $v)
{
array_push($this->stack, $v);
$this->blockedSet[$v->getId()] = $v;
$found = false;
// Examine adjacent nodes
foreach ($v->getVerticesEdgeTo() as $w) {
if ($w->getId() === $r->getId()) {
// Adjacent node == start node .'. found a cycle
$found = true;
// Cycle is whatever is on the stack
$this->cycles[] = new Vertices($this->stack);
} else if (!isset($this->blockedSet[$w->getId()])) {
// Only visit adjacent node if not blocked
$found = $this->visit($r, $w) || $found;
}
}
if ($found) {
// If cycle found, block node and all nodes mapped to it
$this->unblock($v);
} else {
// Otherwise add node to all adjacent nodes' blocked map
foreach ($v->getVerticesEdgeTo() as $w) {
if (!isset($this->blockedMap[$w->getId()])) {
$this->blockedMap[$w->getId()] = array();
}
$this->blockedMap[$w->getId()][$v->getId()] = $v;
}
}
array_pop($this->stack);
return $found;
}

/**
* @param Graph $g
*/
protected function findCycles(Graph $g)
{
$this->blockedSet = array();
$this->blockedMap = array();
$this->stack = array();
foreach ($g->getVertices() as $v) {
$this->visit($v, $v);
$v->destroy();
}
}

/**
* @param Graph $graph
* @return array|Vertices[]
*/
public function getSimpleCycles(Graph $graph)
{
$this->cycles = array();
$components = new StronglyConnectedComponents();
foreach ($components->stronglyConnectedGraph($graph) as $component) {
$this->findCycles($component);
}
return $this->cycles;
}
}
121 changes: 121 additions & 0 deletions src/StronglyConnectedComponents.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php

namespace Graphp\Algorithms;

use Fhaculty\Graph\Set\Vertices;
use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Vertex;
use SplObjectStorage;

/**
* Tarjan's strongly connected components algorithm
*
* @link https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
*/
class StronglyConnectedComponents
{
/** @var int */
public $minSize = 1;

/**
* Get vertices adjacent to vertex
*
* @param Vertex $v
* @return Vertex[]
*/
protected function vertexAdjacent(Vertex $v)
{
return $v->getVerticesEdgeTo()->getVector();
}

/**
* Find the strongly connected components of the given graph and return a set of Vertices which
* refer to the original Vertexes
*
* @param Graph $graph
* @return Vertices[]
*/
public function stronglyConnectedVertices(Graph $graph)
{
/** @var SplObjectStorage $preorder int[] */
$preorder = new SplObjectStorage();
/** @var SplObjectStorage $lowlink int[] */
$lowlink = new SplObjectStorage();
/** @var SplObjectStorage $scc_found bool[] */
$scc_found = new SplObjectStorage();
/** @var Vertex[] $scc_queue */
$scc_queue = array();
/** @var int $i */
$i = 0; // preorder counter
/** @var Vertices[] $sccs */
$sccs = array();

foreach ($graph->getVertices() as $source) {
if (!$scc_found->contains($source)) {
$queue = array($source);
while ($queue) {
/** @var Vertex $v */
$v = end($queue);
if (!$preorder->contains($v)) {
$i++;
$preorder[$v] = $i;
}
/** @var bool $done */
$done = true;
$v_nbrs = $this->vertexAdjacent($v);
foreach ($v_nbrs as $w) {
if (!$preorder->contains($w)) {
array_push($queue, $w);
$done = false;
break;
}
}
if ($done) {
$lowlink[$v] = $preorder[$v];
foreach ($v_nbrs as $w) {
if (!$scc_found->contains($w)) {
if ($preorder[$w] > $preorder[$v]) {
$lowlink[$v] = min($lowlink[$v], $lowlink[$w]);
} else {
$lowlink[$v] = min($lowlink[$v], $preorder[$w]);
}
}
}
array_pop($queue);
if ($lowlink[$v] === $preorder[$v]) {
$scc_found->attach($v);
/** @var Vertex[] $scc (Dictionary) */
$scc = array($v);
while ($scc_queue && $preorder[end($scc_queue)] > $preorder[$v]) {
/** @var Vertex $k */
$k = array_pop($scc_queue);
$scc_found->attach($k);
array_push($scc, $k);
}
array_push($sccs, new Vertices($scc));
} else {
array_push($scc_queue, $v);
}
}
}
}
}

$minSize = $this->minSize; // PHP < 5.4
return array_filter($sccs, function (Vertices $vertices) use ($minSize) { return $vertices->count() >= $minSize; });
}

/**
* Return a set of new Graphs each representing a discovered strongly connected connected component
*
* @param Graph $graph
* @return Graph[]
*/
public function stronglyConnectedGraph(Graph $graph)
{
$sccs = $this->stronglyConnectedVertices($graph);
return array_map(function(Vertices $vertices) use ($graph) {
return $graph->createGraphCloneVertices($vertices);
}, $sccs);
}
}
90 changes: 90 additions & 0 deletions tests/SimpleCyclesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

use Fhaculty\Graph\Graph;
use Fhaculty\Graph\Set\Vertices;
use Graphp\Algorithms\SimpleCycles;

class SimpleCyclesTest extends TestCase
{
public function providerGetSimpleCycles()
{
return array(
"simple cycle" => array(
"edges" => array(
array(8, 9),
array(9, 8),
),
"cycles" => array(
array(8, 9),
),
),
"strongly connected component (isolated)" => array(
"edges" => array(
array(1, 2),
array(1, 5),
array(2, 3),
array(3, 1),
array(3, 2),
array(3, 4),
array(3, 6),
array(4, 5),
array(5, 2),
array(6, 4),
),
"cycles" => array(
array(1, 2, 3),
array(1, 5, 2, 3),
array(2, 3),
array(2, 3, 4, 5),
array(2, 3, 6, 4, 5),
),
),
"strongly connected component (connected)" => array(
"edges" => array(
array(1, 2),
array(1, 5),
array(1, 8),
array(2, 3),
array(2, 7),
array(2, 9),
array(3, 1),
array(3, 2),
array(3, 4),
array(3, 6),
array(4, 5),
array(5, 2),
array(6, 4),
array(8, 9),
array(9, 8),
),
"cycles" => array(
array(8, 9),
array(1, 2, 3),
array(1, 5, 2, 3),
array(2, 3),
array(2, 3, 4, 5),
array(2, 3, 6, 4, 5),
),
),
);
}



/**
* @dataProvider providerGetSimpleCycles
*/
public function testGetSimpleCycles(array $edges, array $cycles)
{
$graph = new Graph();
foreach ($edges as $edge) {
$graph->createVertex($edge[0], true)->createEdgeTo($graph->createVertex($edge[1], true));
}
$alg = new SimpleCycles();
$actual = array();
foreach ($alg->getSimpleCycles($graph) as $cycle) {
$actual[] = $cycle->getIds();
}
$this->assertSame($cycles, $actual);
}
}
Loading