GithubHelp home page GithubHelp logo

algorithms's Introduction

graphp/graph

CI status development installs on Packagist previous installs on Packagist

GraPHP is the mathematical graph/network library written in PHP.

Development version: This branch contains the code for the upcoming 1.0 release. For the code of the current stable 0.9 release, check out the 0.9.x branch.

The upcoming 1.0 release will be the way forward for this package. However, we will still actively support 0.9.x for those not yet on the latest version. See also installation instructions for more details.

Table of contents

Quickstart examples

Once installed, let's initialize a sample graph:

<?php

require __DIR__ . '/vendor/autoload.php';

$graph = new Graphp\Graph\Graph();

// create some cities
$rome = $graph->createVertex(array('name' => 'Rome'));
$madrid = $graph->createVertex(array('name' => 'Madrid'));
$cologne = $graph->createVertex(array('name' => 'Cologne'));

// build some roads
$graph->createEdgeDirected($cologne, $madrid);
$graph->createEdgeDirected($madrid, $rome);
// create loop
$graph->createEdgeDirected($rome, $rome);

Let's see which city (Vertex) has a road (i.e. an edge pointing) to Rome:

foreach ($rome->getVerticesEdgeFrom() as $vertex) {
    echo $vertex->getAttribute('name') . ' leads to Rome' . PHP_EOL;
    // result: Madrid and Rome itself lead to Rome
}

Features

This library is built around the concept of mathematical graph theory (i.e. it is not a charting library for drawing a graph of a function). In essence, a graph is a set of nodes with any number of connections in between. In graph theory, vertices (plural of vertex) are an abstract representation of these nodes, while connections are represented as edges. Edges may be either undirected ("two-way") or directed ("one-way", aka di-edges, arcs).

Depending on how the edges are constructed, the whole graph can either be undirected, can be a directed graph (aka digraph) or be a mixed graph. Edges are also allowed to form loops (i.e. an edge from vertex A pointing to vertex A again). Also, multiple edges from vertex A to vertex B are supported as well (aka parallel edges), effectively forming a multigraph (aka pseudograph). And of course, any combination thereof is supported as well. While many authors try to differentiate between these core concepts, this library tries hard to not impose any artificial limitations or assumptions on your graphs.

Components

This library provides the core data structures for working with graphs, its vertices, edges and attributes.

There are several official components built on top of these structures to provide commonly needed functionality. This architecture allows these components to be used independently and on demand only.

Following is a list of some highlighted components. A list of all official components can be found in the graphp project.

Graph drawing

This library is built to support visualizing graph images, including them into webpages, opening up images from within CLI applications and exporting them as PNG, JPEG or SVG file formats (among many others). Because graph drawing is a complex area on its own, the actual layouting of the graph is left up to the excellent GraphViz "Graph Visualization Software" and we merely provide some convenient APIs to interface with GraphViz.

See graphp/graphviz for more details.

Common algorithms

Besides graph drawing, one of the most common things to do with graphs is running algorithms to solve common graph problems. Therefore this library is being used as the basis for implementations for a number of commonly used graph algorithms:

  • Search
    • Deep first (DFS)
    • Breadth first search (BFS)
  • Shortest path
    • Dijkstra
    • Moore-Bellman-Ford (MBF)
    • Counting number of hops (simple BFS)
  • Minimum spanning tree (MST)
    • Kruskal
    • Prim
  • Traveling salesman problem (TSP)
    • Bruteforce algorithm
    • Minimum spanning tree heuristic (TSP MST heuristic)
    • Nearest neighbor heuristic (NN heuristic)
  • Maximum flow
  • Minimum cost flow (MCF)
    • Cycle canceling
    • Successive shortest path
  • Maximum matching
    • Flow algorithm

See graphp/algorithms for more details.

Install

The recommended way to install this library is through Composer. New to Composer?

Once released, this project will follow SemVer. At the moment, this will install the latest development version:

composer require graphp/graph:^1@dev

See also the CHANGELOG for details about version upgrades.

This project aims to run on any platform and thus does not require any PHP extensions and supports running on legacy PHP 5.3 through current PHP 8+. It's highly recommended to use the latest supported PHP version for this project.

You may also want to install some of the additional components. A list of all official components can be found in the graphp project.

Tests

This library uses PHPUnit for its extensive test suite. To run the test suite, you first need to clone this repo and then install all dependencies through Composer:

composer install

To run the test suite, go to the project root and run:

vendor/bin/phpunit

Contributing

This library comes with an extensive test suite and is regularly tested and used in the real world. Despite this, this library is still considered beta software and its API is subject to change. The changelog lists all relevant information for updates between releases.

If you encounter any issues, please don't hesitate to drop us a line, file a bug report or even best provide us with a patch / pull request and/or unit test to reproduce your problem.

Besides directly working with the code, any additional documentation, additions to our readme or even fixing simple typos are appreciated just as well.

Any feedback and/or contribution is welcome!

Check out #graphp on irc.freenode.net.

License

This project is released under the permissive MIT license.

Did you know that I offer custom development services and issuing invoices for sponsorships of releases and for contributions? Contact me (@clue) for details.

algorithms's People

Contributors

clue avatar drowe-wayfair avatar flos avatar peter279k avatar phyrwork avatar simonfrings avatar tobiasneumann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algorithms's Issues

Support topological sorting on Disconnected Graphs

When using a disconnected graph the topological sort will not fully sort all nodes.

There is a work-around: use (new ConnectedComponents($graph))->createGraphsComponents() and sort each graph individually. The draw-back here is that finding all connected components is a very time-expensive task (for example, it takes roughly 2-3 minutes when I get 2000~ components form a 6000~ vertex graph).

Is there a Transitive Reduction algorithm available?

Hi,

I'm looking for a way to reduce a dependency graph in order to remove redundant links in it.
I came to the conclusion that Transitive Reduction seems to be the right way to do it, but I cannot find it in the available algorithms in this repo.

Can you confirm it does not exist? (and as a consequence, that if I need it I have to code it, obviously ^^)

Thanks

Mising method call error

Fatal error: Call to undefined method Fhaculty\Graph\Graph::getWeight() in /vendor/graphp/algorithms/src/TravelingSalesmanProblem/Bruteforce.php on line 88

Add dedicated Result interfaces for algorithms

Originally reported by @clue in graphp/graph#94:

A lot of our algorithms would benefit from a dedicated Result interface, which saves the intermediary result for further operations. Also, passing its arguments to the createResult() method instead of the constructor allows for a much cleaner design by interchanging the actual algorithm implementation (via dependency injection).

For example, calling the following code always calculates the whole algorithm and then only returns a subset of its results:

$alg = new EdmondsKarp($va, $vb);
$max1 = $alg->getFlowMax();
$max2 = $alg->getFlowMax();

Instead, I'd like to propose something like this, which makes it clear when the actual algorithm runs:

$alg = new EdmondsKarp();
$result = $alg->createResult($va, $vb);
$max1 = $result->getFlowMax();
$max2 = $result->getFlowMax();

This applies to at least MaxFlow, MaximumMatching, MinimumCostFlow, MinimumSpanningTree, ShortestPath, TravelingSalesmanProblem and perhaps a few others.

I'm opening this one as a way to discuss this concept and also to link the first batch of PRs against. I'd love to get some feedback!

Deprecate Algorithm base classes

Originally reported by @clue in graphp/graph#118:

The abstract algorithm base classes are pretty much useless and make up for an awkward API (see also #4).

We should work towards updating the API of all algorithm implementations currently using the base classes and eventually remove the base classes.

Obviously, this involves quite a big BC break and will likely take some time until all algorithms are updated.

Confusing method DepthFirst::getVertices() - could add explanatory comments

DepthFirst::getVertices() demonstrates how both the iterative and recursive versions of the algorithm should be used - but clearly the second example is not reachable and the primary methods are themselves private.

My guess is that the iterative version should always be used and hence is the one that will be called from getVertices(), since with any sizeable graphs the call depth limit will be reached.

Ideally comments should be added to explain what's going on with the weird double return value example thing.

CI builds for PHP 5.3 are broken

PHP 5.3 is supported only on Precise.
See https://docs.travis-ci.com/user/reference/trusty#PHP-images on how to test PHP 5.3 on Precise.
Terminating.

Algorithm common interface

When looking at the different algorithm providen, I cannot help feeling that they should share a common class interface.

When one look at Flow, one will find a few functions providing various outputs. However, class name does not help to know that one will find getBalance method wihtin. On the contrary, one get MinimumSpanningTree algorithms nicely sorted in a folder, with base class giving a common interface.

I would suggest rewrite algorithms by making them implement common interfaces, like this:

interface GraphToVerticesAlgorithm {
public function compute(Graph $graph): Vertices;
}
interface GraphToBooleanAlgorithm {
public function compute(Graph $graph): Boolean;
}
class StronglyConnectedComponent\Tarjan implements GraphToVerticesAlgorithm {...}
class Eulerian\HasCycle implements GraphToBooleanAlgorithm {...}

I'll emphasize also on reusability of Algorithms. They shall not persist state between calls to compute function. You could reuse an Algorithm object multiple times.

I'm aware that this rewrite would be costly and maybe discouraging to even more contributors to port their pull requests. This is just a suggestion.

Ullman's Subgraph Isomorphism Algorithm?

I need to use Ullman's Subgraph Isomorphism Algorithm in a project I'm working on. I was wondering if this library contains that algorithm. At least I could not find it from looking at the source code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.