jgrapht-0.8.3/0000755000175000017500000000000011752244360013373 5ustar giovannigiovannijgrapht-0.8.3/build.xml0000644000175000017500000005005011706124627015216 0ustar giovannigiovanni project.version=$${${svntag}.name} JAVA_HOME=${java.home} If you get a junit task lookup failure, you need to add the junit.jar to the classpath, possibly by copying it into the ANT_HOME/lib folder. See http://ant.apache.org/manual/OptionalTasks/junit.html for more. replaceme Starting release build at ${checkout.dir}/${build.file.name} Checking out files of SVN tag: ${svntag} Variable $${svntag} must be specified for selected target. jgrapht-0.8.3/README.html0000644000175000017500000005503611706124625015227 0ustar giovannigiovanni JGraphT Release Notes


JGraphT  0.8.3
 

 

Released: January, 2012

Written by Barak Naveh (barak_naveh@users.sourceforge.net) and Contributors.

(C) Copyright 2003-2012, by Barak Naveh and Contributors. All rights reserved.

Please address all contributions, suggestions, and inquiries to the current project administrator, John Sichi.

Introduction

JGraphT is a free Java class library that provides mathematical graph-theory objects and algorithms. It runs on Java 2 Platform (requires JDK 1.6 or later).

JGraphT is licensed under the terms of the GNU Lesser General Public License (LGPL). A copy of the license is included in the download.

Please note that JGraphT is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Please refer to the license for details.

Contents

jgrapht-jdk1.6.jar the compiled JGraphT library for JRE 1.6
README.html this file
licence-LGPL.txt GNU Lesser General Public License
javadoc/ Javadoc documentation
lib/ libraries required for build:
  • junit.jar
  • jgraph.jar
  • TGGraphLayout.jar
src/ source code
testsrc/ source code of unit tests
META-INF/MANIFEST.MF meta information for use as an OSGi plug-in (e.g. within an Eclipse RCP application)
build.properties describes content of OSGi plug-in export
build.xml ant buildfile

Getting Started

The package org.jgrapht.demo includes small demo applications to help you get started. If you spawn your own demo app and think others can use it, please send it to us and we will add it to that package.

Upgrading Versions

To help upgrading, JGraphT maintains a one-version-backwards compatibility. While this compatibility is not a hard promise, it is generally respected. (This policy was not followed for the jump from 0.6.0 to 0.7.0 due to the pervasive changes required for generics.) You can upgrade via:

Reading the change history is always recommended.

Documentation

A local copy of the Javadoc HTML files is included in this distribution. The latest version of these files is also available on-line at http://www.jgrapht.org/javadoc.

Dependencies

Online Resources

The JGraphT website is at: http://www.jgrapht.org. You can use this site to:

There is also a wiki set up for everyone in the JGraphT community to share information about the project.

Your Improvements

If you add improvements to JGraphT please send them to us. We will add them to the next release so that everyone can enjoy them. You might also benefit from it: others may fix bugs in your source files or may continue to enhance them.

History

Changes to JGraphT in each version:

Contributors

JGraphT wouldn't be the library it is today without the source contributions and suggestions made by the authors:

(if we have missed your name on this list, please email us to get it fixed).

Other people have also helped in different ways: reporting bugs, requesting features, commenting, and by merely asking very good questions. Many thanks to all of you.

Regards,
Barak Naveh
JGraphT Project Creator

John Sichi
JGraphT Project Administrator

 


Valid HTML 4.01! © Copyright 2003-2008, by Barak Naveh and Contributors. All rights reserved. Get JGraphT at SourceForge.net. Fast, secure and Free Open Source software downloads

jgrapht-0.8.3/lib/0000755000175000017500000000000011752244360014141 5ustar giovannigiovannijgrapht-0.8.3/lib/lib-readme.txt0000644000175000017500000000377711706124626016722 0ustar giovannigiovanni ================== Library Folder ================== This folder contains jar files of libraries used by JGraphT: ----------------------------------- jgraph.jar (version 5.8.3.2-Munich) ----------------------------------- The runtime library of the JGraph project. The JGraph library is licensed under the terms of the GNU Lesser General Public License (LGPL), as with JGraphT. You can find out more about JGraph and/or download the latest version from http://www.jgraph.com. You will also find there the source code of the JGraph library. Note: the JGraph jar in this folder is the build for Java 1.4. ------------------------- junit.jar (version 3.8.1) ------------------------- The runtime library of the JUnit testing framework. The JUnit library is licensed under the terms of the IBM Common Public License. You can find out more about JUnit and/or download the latest version from http://www.junit.org. You will also find there the source code of the JUnit library. -------------------------------- TGGraphLayout.jar (version 1.22) -------------------------------- The layout library of the Touchgraph project. The Touchgraph library is licensed under an Apache-style license; see TG-APACHE-LICENSE.txt. You can find out more about Touchgraph and/or download the latest version from http://www.touchgraph.com. You can find the source code of the Touchgraph library at http://sourceforge.net/projects/touchgraph. ------------------------ svn*.jar (version 1.0.0) ------------------------ The svn ant task from http://subclipse.tigris.org/svnant/svn.html ---------------------------- xmlunit1.0.jar (version 1.0) ---------------------------- The runtime library for the XMLUnit extension to JUnit. The XMLUnit library is licensed under the terms of the BSD License. You can find out more about XMLUnit and/or download the latest version from http://xmlunit.sourceforge.net. You will also find there the source code of the xmlunit library. jgrapht-0.8.3/testsrc/0000755000175000017500000000000011706124625015062 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/0000755000175000017500000000000011706124625015651 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/0000755000175000017500000000000011752244360017310 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/graph/0000755000175000017500000000000011752244360020411 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/graph/SubgraphTest.java0000644000175000017500000001333211706124627023673 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------ * SubgraphTest.java * ------------------------ * (C) Copyright 2003-2008, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: SubgraphTest.java 722 2010-11-24 06:22:07Z perfecthash $ * * Changes * ------- * 21-Sep-2004 : Initial revision (MB); * */ package org.jgrapht.graph; import java.util.*; import junit.framework.*; import org.jgrapht.*; /** * Unit test for {@link Subgraph} class. * * @author Michael Behrisch * @since Sep 21, 2004 */ public class SubgraphTest extends TestCase { //~ Instance fields -------------------------------------------------------- private String v1 = "v1"; private String v2 = "v2"; private String v3 = "v3"; private String v4 = "v4"; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public SubgraphTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * . */ public void testInducedSubgraphListener() { UndirectedGraph g = init(true); UndirectedSubgraph sub = new UndirectedSubgraph(g, null, null); assertEquals(g.vertexSet(), sub.vertexSet()); assertEquals(g.edgeSet(), sub.edgeSet()); g.addEdge(v3, v4); assertEquals(g.vertexSet(), sub.vertexSet()); assertEquals(g.edgeSet(), sub.edgeSet()); } /** * Tests Subgraph. */ public void testSubgraph() { UndirectedGraph g = init(false); UndirectedSubgraph sub = new UndirectedSubgraph(g, null, null); assertEquals(g.vertexSet(), sub.vertexSet()); assertEquals(g.edgeSet(), sub.edgeSet()); Set vset = new HashSet(g.vertexSet()); g.removeVertex(v1); assertEquals(vset, sub.vertexSet()); // losing track g = init(false); vset = new HashSet(); vset.add(v1); sub = new UndirectedSubgraph(g, vset, null); assertEquals(vset, sub.vertexSet()); assertEquals(0, sub.degreeOf(v1)); assertEquals(Collections.EMPTY_SET, sub.edgeSet()); vset.add(v2); vset.add(v3); sub = new UndirectedSubgraph( g, vset, new HashSet(g.getAllEdges(v1, v2))); assertEquals(vset, sub.vertexSet()); assertEquals(1, sub.edgeSet().size()); } /** * . */ public void testSubgraphListener() { UndirectedGraph g = init(true); UndirectedSubgraph sub = new UndirectedSubgraph(g, null, null); assertEquals(g.vertexSet(), sub.vertexSet()); assertEquals(g.edgeSet(), sub.edgeSet()); Set vset = new HashSet(g.vertexSet()); g.removeVertex(v1); vset.remove(v1); assertEquals(vset, sub.vertexSet()); // not losing track assertEquals(g.edgeSet(), sub.edgeSet()); } private UndirectedGraph init(boolean listenable) { UndirectedGraph g; if (listenable) { g = new ListenableUndirectedGraph( DefaultEdge.class); } else { g = new SimpleGraph( DefaultEdge.class); } g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addVertex(v4); g.addEdge(v1, v2); g.addEdge(v2, v3); g.addEdge(v3, v1); g.addEdge(v1, v4); return g; } public void testInducedSubgraphUnderlyingEdgeAddition() { ListenableGraph baseGraph = new ListenableUndirectedGraph( DefaultEdge.class); baseGraph.addVertex(v1); baseGraph.addVertex(v2); Set initialVertexes = new LinkedHashSet(); initialVertexes.add(v1); Subgraph> subgraph = new Subgraph>( baseGraph, initialVertexes, null); baseGraph.addEdge(v1, v2); assertFalse(subgraph.containsEdge(v1, v2)); } } // End SubgraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/ListenableGraphTest.java0000644000175000017500000001527011706124627025167 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------ * ListenableGraphTest.java * ------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: ListenableGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 03-Aug-2003 : Initial revision (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * */ package org.jgrapht.graph; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.event.*; /** * Unit test for {@link ListenableGraph} class. * * @author Barak Naveh * @since Aug 3, 2003 */ public class ListenableGraphTest extends TestCase { //~ Instance fields -------------------------------------------------------- DefaultEdge lastAddedEdge; DefaultEdge lastRemovedEdge; Object lastAddedVertex; Object lastRemovedVertex; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public ListenableGraphTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * Tests GraphListener listener. */ public void testGraphListener() { init(); ListenableGraph g = new ListenableUndirectedGraph( DefaultEdge.class); GraphListener listener = new MyGraphListner(); g.addGraphListener(listener); String v1 = "v1"; String v2 = "v2"; // test vertex notification g.addVertex(v1); assertEquals(v1, lastAddedVertex); assertEquals(null, lastRemovedVertex); init(); g.removeVertex(v1); assertEquals(v1, lastRemovedVertex); assertEquals(null, lastAddedVertex); // test edge notification g.addVertex(v1); g.addVertex(v2); init(); DefaultEdge e = g.addEdge(v1, v2); assertEquals(e, lastAddedEdge); assertEquals(null, lastRemovedEdge); init(); assertTrue(g.removeEdge(e)); assertEquals(e, lastRemovedEdge); assertEquals(null, lastAddedEdge); g.removeVertex(v1); g.removeVertex(v2); // // test notification stops when removing listener // g.removeGraphListener(listener); init(); g.addVertex(v1); g.addVertex(v2); e = g.addEdge(v1, v2); g.removeEdge(e); assertEquals(null, lastAddedEdge); assertEquals(null, lastAddedVertex); assertEquals(null, lastRemovedEdge); assertEquals(null, lastRemovedVertex); } /** * Tests VertexSetListener listener. */ public void testVertexSetListener() { init(); ListenableGraph g = new ListenableUndirectedGraph( DefaultEdge.class); VertexSetListener listener = new MyGraphListner(); g.addVertexSetListener(listener); String v1 = "v1"; String v2 = "v2"; // test vertex notification g.addVertex(v1); assertEquals(v1, lastAddedVertex); assertEquals(null, lastRemovedVertex); init(); g.removeVertex(v1); assertEquals(v1, lastRemovedVertex); assertEquals(null, lastAddedVertex); // test edge notification g.addVertex(v1); g.addVertex(v2); init(); DefaultEdge e = g.addEdge(v1, v2); assertEquals(null, lastAddedEdge); assertEquals(null, lastRemovedEdge); init(); assertTrue(g.removeEdge(e)); assertEquals(null, lastRemovedEdge); assertEquals(null, lastAddedEdge); g.removeVertex(v1); g.removeVertex(v2); // // test notification stops when removing listener // g.removeVertexSetListener(listener); init(); g.addVertex(v1); g.addVertex(v2); e = g.addEdge(v1, v2); g.removeEdge(e); assertEquals(null, lastAddedEdge); assertEquals(null, lastAddedVertex); assertEquals(null, lastRemovedEdge); assertEquals(null, lastRemovedVertex); } private void init() { lastAddedEdge = null; lastAddedVertex = null; lastRemovedEdge = null; lastRemovedVertex = null; } //~ Inner Classes ---------------------------------------------------------- /** * A listener on the tested graph. * * @author Barak Naveh * @since Aug 3, 2003 */ private class MyGraphListner implements GraphListener { /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded(GraphEdgeChangeEvent e) { lastAddedEdge = e.getEdge(); } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved(GraphEdgeChangeEvent e) { lastRemovedEdge = e.getEdge(); } /** * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded(GraphVertexChangeEvent e) { lastAddedVertex = e.getVertex(); } /** * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved(GraphVertexChangeEvent e) { lastRemovedVertex = e.getVertex(); } } } // End ListenableGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/SerializationTest.java0000644000175000017500000000712211706124627024735 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------- * SerializationTest.java * -------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: SerializationTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Oct-2003 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.io.*; import org.jgrapht.*; /** * SerializationTest tests serialization and deserialization of JGraphT objects. * * @author John V. Sichi */ public class SerializationTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- private String v1 = "v1"; private String v2 = "v2"; private String v3 = "v3"; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public SerializationTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * Tests serialization of DirectedMultigraph. */ @SuppressWarnings("unchecked") public void testDirectedMultigraph() throws Exception { DirectedMultigraph graph = new DirectedMultigraph( DefaultEdge.class); graph.addVertex(v1); graph.addVertex(v2); graph.addVertex(v3); graph.addEdge(v1, v2); graph.addEdge(v2, v3); graph.addEdge(v2, v3); graph = (DirectedMultigraph) serializeAndDeserialize( graph); assertTrue(graph.containsVertex(v1)); assertTrue(graph.containsVertex(v2)); assertTrue(graph.containsVertex(v3)); assertTrue(graph.containsEdge(v1, v2)); assertTrue(graph.containsEdge(v2, v3)); assertEquals(1, graph.edgesOf(v1).size()); assertEquals(3, graph.edgesOf(v2).size()); assertEquals(2, graph.edgesOf(v3).size()); } private Object serializeAndDeserialize(Object obj) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(obj); out.flush(); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream in = new ObjectInputStream(bin); obj = in.readObject(); return obj; } } // End SerializationTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/AsUndirectedGraphTest.java0000644000175000017500000001162111706124627025453 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * AsUndirectedGraphTest.java * -------------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: AsUndirectedGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 14-Aug-2003 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * A unit test for the AsDirectedGraph view. * * @author John V. Sichi */ public class AsUndirectedGraphTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- private DirectedGraph directed; private DefaultEdge loop; private String v1 = "v1"; private String v2 = "v2"; private String v3 = "v3"; private String v4 = "v4"; private UndirectedGraph undirected; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public AsUndirectedGraphTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * . */ public void testAddEdge() { try { undirected.addEdge(v3, v4); assertFalse(); } catch (UnsupportedOperationException e) { assertTrue(); } assertEquals( "([v1, v2, v3, v4], [{v1,v2}, {v2,v3}, {v2,v4}, {v4,v4}])", undirected.toString()); } /** * . */ public void testAddVertex() { String v5 = "v5"; undirected.addVertex(v5); assertEquals(true, undirected.containsVertex(v5)); assertEquals(true, directed.containsVertex(v5)); } /** * . */ public void testDegreeOf() { assertEquals(1, undirected.degreeOf(v1)); assertEquals(3, undirected.degreeOf(v2)); assertEquals(1, undirected.degreeOf(v3)); assertEquals(3, undirected.degreeOf(v4)); } /** * . */ public void testGetAllEdges() { Set edges = undirected.getAllEdges(v3, v2); assertEquals(1, edges.size()); assertEquals(directed.getEdge(v2, v3), edges.iterator().next()); edges = undirected.getAllEdges(v4, v4); assertEquals(1, edges.size()); assertEquals(loop, edges.iterator().next()); } /** * . */ public void testGetEdge() { assertEquals( directed.getEdge(v1, v2), undirected.getEdge(v1, v2)); assertEquals( directed.getEdge(v1, v2), undirected.getEdge(v2, v1)); assertEquals( directed.getEdge(v4, v4), undirected.getEdge(v4, v4)); } /** * . */ public void testRemoveEdge() { undirected.removeEdge(loop); assertEquals(false, undirected.containsEdge(loop)); assertEquals(false, directed.containsEdge(loop)); } /** * . */ public void testRemoveVertex() { undirected.removeVertex(v4); assertEquals(false, undirected.containsVertex(v4)); assertEquals(false, directed.containsVertex(v4)); } /** * . */ protected void setUp() { directed = new DefaultDirectedGraph( DefaultEdge.class); undirected = new AsUndirectedGraph(directed); directed.addVertex(v1); directed.addVertex(v2); directed.addVertex(v3); directed.addVertex(v4); directed.addEdge(v1, v2); directed.addEdge(v2, v3); directed.addEdge(v2, v4); loop = directed.addEdge(v4, v4); } } // End AsUndirectedGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/AllGraphTests.java0000644000175000017500000000516511706124627024002 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * AllGraphTests.java * ----------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: AllGraphTests.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 03-Aug-2003 : Initial revision (BN); * */ package org.jgrapht.graph; import junit.framework.*; /** * A TestSuite for all tests in this package. * * @author Barak Naveh * @since Aug 3, 2003 */ public final class AllGraphTests { //~ Constructors ----------------------------------------------------------- private AllGraphTests() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * Creates a test suite for all tests in this package. * * @return a test suite for all tests in this package. */ public static Test suite() { TestSuite suite = new TestSuite(); // $JUnit-BEGIN$ suite.addTest(new TestSuite(DefaultDirectedGraphTest.class)); suite.addTest(new TestSuite(ListenableGraphTest.class)); suite.addTest(new TestSuite(SimpleDirectedGraphTest.class)); suite.addTest(new TestSuite(AsUndirectedGraphTest.class)); suite.addTest(new TestSuite(AsUnweightedGraphTest.class)); suite.addTest(new TestSuite(CloneTest.class)); suite.addTest(new TestSuite(SerializationTest.class)); suite.addTest(new TestSuite(GenericGraphsTest.class)); // $JUnit-END$ return suite; } } // End AllGraphTests.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/SimpleDirectedGraphTest.java0000644000175000017500000003114011706124627025774 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------------- * SimpleDirectedGraphTest.java * ---------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: SimpleDirectedGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 25-Jul-2003 : Initial revision (BN); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * A unit test for simple directed graph. * * @author Barak Naveh * @since Jul 25, 2003 */ public class SimpleDirectedGraphTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- DirectedGraph gEmpty; private DirectedGraph g1; private DirectedGraph g2; private DirectedGraph g3; private DirectedGraph g4; private DefaultEdge eLoop; private EdgeFactory eFactory; private String v1 = "v1"; private String v2 = "v2"; private String v3 = "v3"; private String v4 = "v4"; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public SimpleDirectedGraphTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * Class to test for boolean addEdge(V, V, E) */ public void testAddEdgeEdge() { init(); try { g1.addEdge(v1, v1, eLoop); // loops not allowed assertFalse(); } catch (IllegalArgumentException e) { assertTrue(); } try { g3.addEdge(v1, v1, null); assertFalse(); // NPE } catch (NullPointerException e) { assertTrue(); } DefaultEdge e = eFactory.createEdge(v2, v1); try { g1.addEdge("ya", "ya", e); // no such vertex in graph assertFalse(); } catch (IllegalArgumentException ile) { assertTrue(); } assertEquals(false, g2.addEdge(v2, v1, e)); assertEquals(false, g3.addEdge(v2, v1, e)); assertEquals(true, g4.addEdge(v2, v1, e)); } /** * Class to test for Edge addEdge(Object, Object) */ public void testAddEdgeObjectObject() { init(); try { g1.addEdge(v1, v1); // loops not allowed assertFalse(); } catch (IllegalArgumentException e) { assertTrue(); } try { g3.addEdge(null, null); assertFalse(); // NPE } catch (NullPointerException e) { assertTrue(); } try { g1.addEdge(v2, v1); // no such vertex in graph assertFalse(); } catch (IllegalArgumentException ile) { assertTrue(); } assertNull(g2.addEdge(v2, v1)); assertNull(g3.addEdge(v2, v1)); assertNotNull(g4.addEdge(v2, v1)); } /** * . */ public void testAddVertex() { init(); assertEquals(1, g1.vertexSet().size()); assertEquals(2, g2.vertexSet().size()); assertEquals(3, g3.vertexSet().size()); assertEquals(4, g4.vertexSet().size()); assertFalse(g1.addVertex(v1)); assertTrue(g1.addVertex(v2)); assertEquals(2, g1.vertexSet().size()); } /** * Class to test for boolean containsEdge(Edge) */ public void testContainsEdgeEdge() { init(); // TODO Implement containsEdge(). } /** * Class to test for boolean containsEdge(Object, Object) */ public void testContainsEdgeObjectObject() { init(); assertFalse(g1.containsEdge(v1, v2)); assertFalse(g1.containsEdge(v1, v1)); assertTrue(g2.containsEdge(v1, v2)); assertTrue(g2.containsEdge(v2, v1)); assertTrue(g3.containsEdge(v1, v2)); assertTrue(g3.containsEdge(v2, v1)); assertTrue(g3.containsEdge(v3, v2)); assertTrue(g3.containsEdge(v2, v3)); assertTrue(g3.containsEdge(v1, v3)); assertTrue(g3.containsEdge(v3, v1)); assertFalse(g4.containsEdge(v1, v4)); g4.addEdge(v1, v4); assertTrue(g4.containsEdge(v1, v4)); assertFalse(g3.containsEdge(v4, v2)); assertFalse(g3.containsEdge(null, null)); } /** * . */ public void testContainsVertex() { init(); // TODO Implement containsVertex(). } /** * . */ public void testEdgeSet() { init(); // TODO Implement edgeSet(). } /** * . */ public void testEdgesOf() { init(); assertEquals(g4.edgesOf(v1).size(), 2); assertEquals(g3.edgesOf(v1).size(), 4); Iterator iter = g3.edgesOf(v1).iterator(); int count = 0; while (iter.hasNext()) { iter.next(); count++; } assertEquals(count, 4); } /** * . */ public void testGetAllEdges() { init(); // TODO Implement getAllEdges(). } /** * . */ public void testGetEdge() { init(); // TODO Implement getEdge(). } /** * . */ public void testGetEdgeFactory() { init(); // TODO Implement getEdgeFactory(). } /** * . */ public void testInDegreeOf() { init(); assertEquals(0, g1.inDegreeOf(v1)); assertEquals(1, g2.inDegreeOf(v1)); assertEquals(1, g2.inDegreeOf(v2)); assertEquals(2, g3.inDegreeOf(v1)); assertEquals(2, g3.inDegreeOf(v2)); assertEquals(2, g3.inDegreeOf(v3)); assertEquals(1, g4.inDegreeOf(v1)); assertEquals(1, g4.inDegreeOf(v2)); assertEquals(1, g4.inDegreeOf(v3)); assertEquals(1, g4.inDegreeOf(v4)); try { g3.inDegreeOf(new String()); assertFalse(); } catch (IllegalArgumentException e) { assertTrue(); } try { g3.inDegreeOf(null); assertFalse(); } catch (NullPointerException e) { assertTrue(); } } /** * . */ public void testIncomingOutgoingEdgesOf() { init(); Set e1to2 = g2.outgoingEdgesOf(v1); Set e2from1 = g2.incomingEdgesOf(v2); assertEquals(e1to2, e2from1); } /** * . */ public void testOutDegreeOf() { init(); // TODO Implement outDegreeOf(). } /** * . */ public void testOutgoingEdgesOf() { init(); // TODO Implement outgoingEdgesOf(). } /** * Class to test for boolean removeEdge(Edge) */ public void testRemoveEdgeEdge() { init(); assertEquals(g4.edgeSet().size(), 4); g4.removeEdge(v1, v2); assertEquals(g4.edgeSet().size(), 3); assertFalse(g4.removeEdge(eLoop)); assertTrue(g4.removeEdge(g4.getEdge(v2, v3))); assertEquals(g4.edgeSet().size(), 2); } /** * Class to test for Edge removeEdge(Object, Object) */ public void testRemoveEdgeObjectObject() { init(); // TODO Implement removeEdge(). } /** * . */ public void testRemoveVertex() { init(); assertEquals(4, g4.vertexSet().size()); assertTrue(g4.removeVertex(v1)); assertEquals(3, g4.vertexSet().size()); assertEquals(2, g4.edgeSet().size()); assertFalse(g4.removeVertex(v1)); assertTrue(g4.removeVertex(v2)); assertEquals(1, g4.edgeSet().size()); assertTrue(g4.removeVertex(v3)); assertEquals(0, g4.edgeSet().size()); assertEquals(1, g4.vertexSet().size()); assertTrue(g4.removeVertex(v4)); assertEquals(0, g4.vertexSet().size()); } /** * . */ public void testVertexSet() { init(); // TODO Implement vertexSet(). } public void testReversedView() { init(); DirectedGraph g = new SimpleDirectedGraph(DefaultEdge.class); DirectedGraph r = new EdgeReversedGraph(g); g.addVertex(v1); g.addVertex(v2); DefaultEdge e = g.addEdge(v1, v2); verifyReversal(g, r, e); // We have implicitly verified that r is backed by g for additive // operations (since we constructed it before adding anything to g). // Now verify for deletion. g.removeEdge(e); assertTrue(r.edgeSet().isEmpty()); assertEquals(0, r.inDegreeOf(v1)); assertEquals(0, r.outDegreeOf(v1)); assertEquals(0, r.inDegreeOf(v2)); assertEquals(0, r.outDegreeOf(v2)); assertTrue(r.incomingEdgesOf(v1).isEmpty()); assertTrue(r.outgoingEdgesOf(v1).isEmpty()); assertTrue(r.incomingEdgesOf(v2).isEmpty()); assertTrue(r.outgoingEdgesOf(v2).isEmpty()); } private void verifyReversal( DirectedGraph g, DirectedGraph r, DefaultEdge e) { assertTrue(r.containsVertex(v1)); assertTrue(r.containsVertex(v2)); assertEquals(g.vertexSet(), r.vertexSet()); assertEquals(g.edgeSet(), r.edgeSet()); assertTrue(r.containsEdge(v2, v1)); assertSame(e, r.getEdge(v2, v1)); assertFalse(r.containsEdge(v1, v2)); assertNull(r.getEdge(v1, v2)); Set s = r.getAllEdges(v1, v2); assertEquals(0, s.size()); s = r.getAllEdges(v2, v1); assertEquals(1, s.size()); assertSame(e, s.iterator().next()); assertEquals(1, r.inDegreeOf(v1)); assertEquals(0, r.inDegreeOf(v2)); assertEquals(0, r.outDegreeOf(v1)); assertEquals(1, r.outDegreeOf(v2)); assertEquals(g.edgeSet(), r.incomingEdgesOf(v1)); assertTrue(r.outgoingEdgesOf(v1).isEmpty()); assertTrue(r.incomingEdgesOf(v2).isEmpty()); assertEquals(g.edgeSet(), r.outgoingEdgesOf(v2)); assertSame(v2, r.getEdgeSource(e)); assertSame(v1, r.getEdgeTarget(e)); assertEquals("([v1, v2], [(v2,v1)])", r.toString()); } private void init() { gEmpty = new SimpleDirectedGraph( DefaultEdge.class); g1 = new SimpleDirectedGraph( DefaultEdge.class); g2 = new SimpleDirectedGraph( DefaultEdge.class); g3 = new SimpleDirectedGraph( DefaultEdge.class); g4 = new SimpleDirectedGraph( DefaultEdge.class); eFactory = g1.getEdgeFactory(); eLoop = eFactory.createEdge(v1, v1); g1.addVertex(v1); g2.addVertex(v1); g2.addVertex(v2); g2.addEdge(v1, v2); g2.addEdge(v2, v1); g3.addVertex(v1); g3.addVertex(v2); g3.addVertex(v3); g3.addEdge(v1, v2); g3.addEdge(v2, v1); g3.addEdge(v2, v3); g3.addEdge(v3, v2); g3.addEdge(v3, v1); g3.addEdge(v1, v3); g4.addVertex(v1); g4.addVertex(v2); g4.addVertex(v3); g4.addVertex(v4); g4.addEdge(v1, v2); g4.addEdge(v2, v3); g4.addEdge(v3, v4); g4.addEdge(v4, v1); } } // End SimpleDirectedGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/CloneTest.java0000644000175000017500000001012111706124627023151 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------- * CloneTest.java * -------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: CloneTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Oct-2003 : Initial revision (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A unit test for a cloning bug, adapted from a forum entry from Linda Buisman. * * @author John V. Sichi * @since Oct 6, 2003 */ public class CloneTest extends EnhancedTestCase { //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public CloneTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * Test graph cloning. */ @SuppressWarnings("unchecked") public void testCloneSpecificsBug() { SimpleGraph g1 = new SimpleGraph(DefaultEdge.class); String one = "1"; String two = "2"; String three = "3"; g1.addVertex(one); g1.addVertex(two); g1.addVertex(three); g1.addEdge(one, two); g1.addEdge(two, three); SimpleGraph g2 = (SimpleGraph) g1.clone(); // Type-safty // warning OK with // clone assertEquals(2, g2.edgeSet().size()); assertNotNull(g2.getEdge(one, two)); assertTrue(g2.removeEdge(g2.getEdge(one, two))); assertNotNull(g2.removeEdge("2", "3")); assertTrue(g2.edgeSet().isEmpty()); } /** * Tests usage of {@link ParanoidGraph} for detecting broken vertex * implementations. */ public void testParanoidGraph() { BrokenVertex v1 = new BrokenVertex(1); BrokenVertex v2 = new BrokenVertex(2); BrokenVertex v3 = new BrokenVertex(1); SimpleGraph g = new SimpleGraph(DefaultEdge.class); ParanoidGraph pg = new ParanoidGraph(g); pg.addVertex(v1); pg.addVertex(v2); try { pg.addVertex(v3); // should not get here assertFalse(); } catch (IllegalArgumentException ex) { // expected, swallow } } //~ Inner Classes ---------------------------------------------------------- private class BrokenVertex { private int x; BrokenVertex(int x) { this.x = x; } public boolean equals(Object other) { if (!(other instanceof BrokenVertex)) { return false; } return x == ((BrokenVertex) other).x; } } } // End CloneTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/AsUnweightedGraphTest.java0000644000175000017500000001054611706124627025475 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * AsUnweightedGraphTest.java * -------------------------- * (C) Copyright 2007-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: AsUnweightedGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 22-Sep-2007 : Initial revision (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A unit test for the AsUnweighted[Directed]Graph views. * * @author John V. Sichi */ public class AsUnweightedGraphTest extends EnhancedTestCase { //~ Static fields/initializers --------------------------------------------- private static final String v1 = "v1"; private static final String v2 = "v2"; private static final String v3 = "v3"; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public AsUnweightedGraphTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * . */ public void testDirected() { DefaultDirectedWeightedGraph directed = new DefaultDirectedWeightedGraph( DefaultWeightedEdge.class); constructWeighted(directed); AsUnweightedDirectedGraph unweighted = new AsUnweightedDirectedGraph( directed); checkView(directed, unweighted); } /** * . */ public void testUndirected() { WeightedGraph undirected = new SimpleWeightedGraph( DefaultWeightedEdge.class); constructWeighted(undirected); AsUnweightedGraph unweighted = new AsUnweightedGraph( undirected); checkView(undirected, unweighted); } private void constructWeighted( WeightedGraph weighted) { weighted.addVertex(v1); weighted.addVertex(v2); weighted.addVertex(v3); Graphs.addEdge(weighted, v1, v2, 3.0); assertEquals( 3.0, weighted.getEdgeWeight( weighted.getEdge(v1, v2))); } private void checkView( WeightedGraph weighted, Graph unweighted) { assertEquals( WeightedGraph.DEFAULT_EDGE_WEIGHT, unweighted.getEdgeWeight( unweighted.getEdge(v1, v2))); Graphs.addEdge(weighted, v2, v3, 5.0); assertEquals( WeightedGraph.DEFAULT_EDGE_WEIGHT, unweighted.getEdgeWeight( unweighted.getEdge(v2, v3))); unweighted.addEdge(v3, v1); assertEquals( WeightedGraph.DEFAULT_EDGE_WEIGHT, unweighted.getEdgeWeight( unweighted.getEdge(v3, v1))); assertEquals( WeightedGraph.DEFAULT_EDGE_WEIGHT, weighted.getEdgeWeight( weighted.getEdge(v3, v1))); } } // End AsUnweightedGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/DefaultDirectedGraphTest.java0000644000175000017500000001315611706124627026136 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * DefaultDirectedGraphTest.java * ----------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: DefaultDirectedGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 09-Aug-2003 : Initial revision (BN); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * A unit test for directed multigraph. * * @author Barak Naveh * @since Aug 9, 2003 */ public class DefaultDirectedGraphTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- private String v1 = "v1"; private String v2 = "v2"; private String v3 = "v3"; //~ Methods ---------------------------------------------------------------- /** * . */ public void testEdgeSetFactory() { DirectedMultigraph g = new DirectedMultigraph( DefaultEdge.class); g.setEdgeSetFactory(new LinkedHashSetFactory()); initMultiTriangleWithMultiLoop(g); } /** * . */ public void testEdgeOrderDeterminism() { DirectedGraph g = new DirectedMultigraph( DefaultEdge.class); g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); DefaultEdge e1 = g.addEdge(v1, v2); DefaultEdge e2 = g.addEdge(v2, v3); DefaultEdge e3 = g.addEdge(v3, v1); Iterator iter = g.edgeSet().iterator(); assertEquals(e1, iter.next()); assertEquals(e2, iter.next()); assertEquals(e3, iter.next()); // some bonus tests assertTrue(Graphs.testIncidence(g, e1, v1)); assertTrue(Graphs.testIncidence(g, e1, v2)); assertFalse(Graphs.testIncidence(g, e1, v3)); assertEquals(v2, Graphs.getOppositeVertex(g, e1, v1)); assertEquals(v1, Graphs.getOppositeVertex(g, e1, v2)); assertEquals( "([v1, v2, v3], [(v1,v2), (v2,v3), (v3,v1)])", g.toString()); } /** * . */ public void testEdgesOf() { DirectedGraph g = createMultiTriangleWithMultiLoop(); assertEquals(3, g.edgesOf(v1).size()); assertEquals(2, g.edgesOf(v2).size()); } /** * . */ public void testGetAllEdges() { DirectedGraph g = createMultiTriangleWithMultiLoop(); Set loops = g.getAllEdges(v1, v1); assertEquals(1, loops.size()); } /** * . */ public void testInDegreeOf() { DirectedGraph g = createMultiTriangleWithMultiLoop(); assertEquals(2, g.inDegreeOf(v1)); assertEquals(1, g.inDegreeOf(v2)); } /** * . */ public void testOutDegreeOf() { DirectedGraph g = createMultiTriangleWithMultiLoop(); assertEquals(2, g.outDegreeOf(v1)); assertEquals(1, g.outDegreeOf(v2)); } /** * . */ public void testVertexOrderDeterminism() { DirectedGraph g = createMultiTriangleWithMultiLoop(); Iterator iter = g.vertexSet().iterator(); assertEquals(v1, iter.next()); assertEquals(v2, iter.next()); assertEquals(v3, iter.next()); } private DirectedGraph createMultiTriangleWithMultiLoop() { DirectedGraph g = new DirectedMultigraph( DefaultEdge.class); initMultiTriangleWithMultiLoop(g); return g; } private void initMultiTriangleWithMultiLoop( DirectedGraph g) { g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addEdge(v1, v1); g.addEdge(v1, v2); g.addEdge(v2, v3); g.addEdge(v3, v1); } //~ Inner Classes ---------------------------------------------------------- private static class LinkedHashSetFactory implements EdgeSetFactory { /** * . * * @param vertex * * @return an empty list. */ public Set createEdgeSet(V vertex) { return new LinkedHashSet(); } } } // End DefaultDirectedGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/GenericGraphsTest.java0000644000175000017500000001525611706124627024650 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * GenericGraphsTest.java * -------------------------- * (C) Copyright 2006-2008, by HartmutBenz and Contributors. * * Original Author: Hartmut Benz * Contributor(s): John V. Sichi * * $Id: GenericGraphsTest.java 701 2010-01-04 08:36:24Z perfecthash $ * * Changes * ------- * ??-???-2006 : Initial revision (HB); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A unit test for graph generic vertex/edge parameters. * * @author Hartmut Benz */ public class GenericGraphsTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- Graph objectGraph; Graph fooFooGraph; Graph barBarGraph; Graph fooBarGraph; //~ Constructors ----------------------------------------------------------- /** * @see junit.framework.TestCase#TestCase(java.lang.String) */ public GenericGraphsTest(String name) { super(name); } //~ Methods ---------------------------------------------------------------- // ~ Methods --------------------------------------------------------------- public void testLegalInsertStringGraph() { String v1 = "Vertex1"; Object v2 = "Vertex2"; objectGraph.addVertex(v1); objectGraph.addVertex(v2); objectGraph.addEdge(v1, v2); } public void testLegalInsertFooGraph() { FooVertex v1 = new FooVertex(); FooVertex v2 = new FooVertex(); BarVertex vb1 = new BarVertex(); BarVertex vb2 = new BarVertex(); fooFooGraph.addVertex(v1); fooFooGraph.addVertex(v2); fooFooGraph.addVertex(vb1); fooFooGraph.addVertex(vb2); fooFooGraph.addEdge(v1, v2); fooFooGraph.addEdge(vb1, vb2); fooFooGraph.addEdge(v1, vb2); fooFooGraph.addEdge(v1, v2, new BarEdge()); fooFooGraph.addEdge(v1, vb2, new BarEdge()); fooFooGraph.addEdge(vb1, vb2, new BarEdge()); } public void testLegalInsertBarGraph() { BarVertex v1 = new BarVertex(); BarVertex v2 = new BarVertex(); barBarGraph.addVertex(v1); barBarGraph.addVertex(v2); barBarGraph.addEdge(v1, v2); } public void testLegalInsertFooBarGraph() { FooVertex v1 = new FooVertex(); FooVertex v2 = new FooVertex(); BarVertex vb1 = new BarVertex(); BarVertex vb2 = new BarVertex(); fooFooGraph.addVertex(v1); fooFooGraph.addVertex(v2); fooFooGraph.addVertex(vb1); fooFooGraph.addVertex(vb2); fooFooGraph.addEdge(v1, v2); fooFooGraph.addEdge(vb1, vb2); fooFooGraph.addEdge(v1, vb2); } public void testAlissaHacker() { DirectedGraph g = new DefaultDirectedGraph(CustomEdge.class); g.addVertex("a"); g.addVertex("b"); g.addEdge("a", "b"); CustomEdge custom = g.getEdge("a", "b"); String s = custom.toString(); assertEquals("Alissa P. Hacker approves the edge from a to b", s); } public void testEqualButNotSameVertex() { EquivVertex v1 = new EquivVertex(); EquivVertex v2 = new EquivVertex(); EquivGraph g = new EquivGraph(); g.addVertex(v1); g.addVertex(v2); g.addEdge(v1, v2, new DefaultEdge()); assertEquals(2, g.degreeOf(v1)); assertEquals(2, g.degreeOf(v2)); } /** * . */ protected void setUp() { objectGraph = new DefaultDirectedGraph( DefaultEdge.class); fooFooGraph = new SimpleGraph(FooEdge.class); barBarGraph = new SimpleGraph(BarEdge.class); } //~ Inner Classes ---------------------------------------------------------- public static class CustomEdge extends DefaultEdge { private static final long serialVersionUID = 1L; public String toString() { return "Alissa P. Hacker approves the edge from " + getSource() + " to " + getTarget(); } } public static class EquivVertex { public boolean equals(Object o) { return true; } public int hashCode() { return 1; } } public static class EquivGraph extends AbstractBaseGraph implements UndirectedGraph { /** */ private static final long serialVersionUID = 8647217182401022498L; public EquivGraph() { super( new ClassBasedEdgeFactory( DefaultEdge.class), true, true); } } public static class FooEdge extends DefaultEdge { private static final long serialVersionUID = 1L; } private class FooVertex { String str; public FooVertex() { super(); str = "empty foo"; } public FooVertex(String s) { str = s; } } public static class BarEdge extends FooEdge { private static final long serialVersionUID = 1L; } private class BarVertex extends FooVertex { public BarVertex() { super("empty bar"); } public BarVertex(String s) { super(s); } } } // End GenericGraphsTest.java jgrapht-0.8.3/testsrc/org/jgrapht/graph/AsWeightedGraphTest.java0000644000175000017500000001141111706124627025122 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * AsWeightedGraphTest.java * -------------------------- * (C) Copyright 2007, by Lucas J. Scharenbroich and Contributors. * * Original Author: Lucas J. Scharenbroich * Contributor(s): John V. Sichi * * $Id: AsWeightedGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 22-Sep-2007 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * A unit test for the AsWeightedGraph view. * * @author Lucas J. Scharenbroich */ public class AsWeightedGraphTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- public SimpleWeightedGraph weightedGraph; public SimpleGraph unweightedGraph; //~ Methods ---------------------------------------------------------------- public void setUp() { weightedGraph = new SimpleWeightedGraph( DefaultWeightedEdge.class); unweightedGraph = new SimpleGraph(DefaultEdge.class); // Create a very simple graph weightedGraph.addVertex("v1"); weightedGraph.addVertex("v2"); weightedGraph.addVertex("v3"); unweightedGraph.addVertex("v1"); unweightedGraph.addVertex("v2"); unweightedGraph.addVertex("v3"); weightedGraph.setEdgeWeight(weightedGraph.addEdge("v1", "v2"), 1.); weightedGraph.setEdgeWeight(weightedGraph.addEdge("v2", "v3"), 2.); weightedGraph.setEdgeWeight(weightedGraph.addEdge("v3", "v1"), 3.); unweightedGraph.addEdge("v1", "v2"); unweightedGraph.addEdge("v2", "v3"); unweightedGraph.addEdge("v3", "v1"); } public void tearDown() { } public void test1() { Map weightMap1 = new HashMap(); Map weightMap2 = new HashMap(); DefaultEdge e1 = unweightedGraph.getEdge("v1", "v2"); DefaultEdge e2 = unweightedGraph.getEdge("v2", "v3"); DefaultEdge e3 = unweightedGraph.getEdge("v3", "v1"); DefaultWeightedEdge e4 = weightedGraph.getEdge("v1", "v2"); DefaultWeightedEdge e5 = weightedGraph.getEdge("v2", "v3"); DefaultWeightedEdge e6 = weightedGraph.getEdge("v3", "v1"); weightMap1.put(e1, 9.0); weightMap2.put(e4, 9.0); weightMap2.put(e6, 8.0); assertEquals( unweightedGraph.getEdgeWeight(e1), WeightedGraph.DEFAULT_EDGE_WEIGHT); WeightedGraph g1 = new AsWeightedGraph( unweightedGraph, weightMap1); WeightedGraph g2 = new AsWeightedGraph( weightedGraph, weightMap2); assertEquals(g1.getEdgeWeight(e1), 9.0); assertEquals(g1.getEdgeWeight(e2), WeightedGraph.DEFAULT_EDGE_WEIGHT); assertEquals(g1.getEdgeWeight(e3), WeightedGraph.DEFAULT_EDGE_WEIGHT); assertEquals(g2.getEdgeWeight(e4), 9.0); assertEquals(g2.getEdgeWeight(e5), 2.0); assertEquals(g2.getEdgeWeight(e6), 8.0); g1.setEdgeWeight(e2, 5.0); g2.setEdgeWeight(e5, 5.0); assertEquals(g1.getEdgeWeight(e2), 5.0); assertEquals( unweightedGraph.getEdgeWeight(e2), WeightedGraph.DEFAULT_EDGE_WEIGHT); assertEquals(g2.getEdgeWeight(e5), 5.0); assertEquals(weightedGraph.getEdgeWeight(e5), 5.0); } } // End AsWeightedGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/ext/0000755000175000017500000000000011752244360020110 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/ext/DOTExporterTest.java0000644000175000017500000001154111706124627023776 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * DOTExporterTest.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; import java.io.*; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author Trevor Harmon */ public class DOTExporterTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String NL = System.getProperty("line.separator"); // TODO jvs 23-Dec-2006: externalized diff-based testing framework private static final String UNDIRECTED = "graph G {" + NL + " 1 [ label=\"a\" ];" + NL + " 2 [ x=\"y\" ];" + NL + " 3;" + NL + " 1 -- 2;" + NL + " 3 -- 1;" + NL + "}" + NL; //~ Methods ---------------------------------------------------------------- public void testUndirected() { UndirectedGraph g = new SimpleGraph(DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); g.addVertex(V3); g.addEdge(V3, V1); StringWriter w = new StringWriter(); ComponentAttributeProvider vertexAttributeProvider = new ComponentAttributeProvider() { public Map getComponentAttributes(String v) { Map map = new LinkedHashMap(); if (v.equals(V1)) { map.put("label", "a"); } else if (v.equals(V2)) { map.put("x", "y"); } else { map = null; } return map; } }; DOTExporter exporter = new DOTExporter( new IntegerNameProvider(), null, null, vertexAttributeProvider, null); exporter.export(w, g); assertEquals(UNDIRECTED, w.toString()); } public void testValidNodeIDs() { DOTExporter exporter = new DOTExporter( new StringNameProvider(), new StringNameProvider(), null); List validVertices = Arrays.asList( "-9.78", "-.5", "12", "a", "12", "abc_78", "\"--34asdf\""); for (String vertex : validVertices) { Graph graph = new DefaultDirectedGraph( DefaultEdge.class); graph.addVertex(vertex); exporter.export(new StringWriter(), graph); } List invalidVertices = Arrays.asList("2test", "--4", "foo-bar", "", "t:32"); for (String vertex : invalidVertices) { Graph graph = new DefaultDirectedGraph( DefaultEdge.class); graph.addVertex(vertex); try { exporter.export(new StringWriter(), graph); Assert.fail(vertex); } catch (RuntimeException re) { // this is a negative test so exception is expected } } } } // End DOTExporterTest.java jgrapht-0.8.3/testsrc/org/jgrapht/ext/MatrixExporterTest.java0000644000175000017500000001066111706124627024616 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * MatrixExporterTest.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Charles Fry * * $Id: MatrixExporterTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 12-Dec-2005 : Initial revision (CF); * */ package org.jgrapht.ext; import java.io.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author Charles Fry */ public class MatrixExporterTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String NL = System.getProperty("line.separator"); // TODO jvs 23-Dec-2006: externalized diff-based testing framework private static final String LAPLACIAN = "1 1 2" + NL + "1 2 -1" + NL + "1 3 -1" + NL + "2 2 1" + NL + "2 1 -1" + NL + "3 3 1" + NL + "3 1 -1" + NL; private static final String NORMALIZED_LAPLACIAN = "1 1 1" + NL + "1 2 -0.7071067811865475" + NL + "1 3 -0.7071067811865475" + NL + "2 2 1" + NL + "2 1 -0.7071067811865475" + NL + "3 3 1" + NL + "3 1 -0.7071067811865475" + NL; private static final String UNDIRECTED_ADJACENCY = "1 2 1" + NL + "1 3 1" + NL + "1 1 2" + NL + "2 1 1" + NL + "3 1 1" + NL; private static final String DIRECTED_ADJACENCY = "1 2 1" + NL + "3 1 2" + NL; private static final MatrixExporter exporter = new MatrixExporter(); //~ Methods ---------------------------------------------------------------- public void testLaplacian() { UndirectedGraph g = new SimpleGraph(DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); g.addVertex(V3); g.addEdge(V3, V1); StringWriter w = new StringWriter(); exporter.exportLaplacianMatrix(w, g); assertEquals(LAPLACIAN, w.toString()); w = new StringWriter(); exporter.exportNormalizedLaplacianMatrix(w, g); assertEquals(NORMALIZED_LAPLACIAN, w.toString()); } public void testAdjacencyUndirected() { UndirectedGraph g = new Pseudograph(DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); g.addVertex(V3); g.addEdge(V3, V1); g.addEdge(V1, V1); StringWriter w = new StringWriter(); exporter.exportAdjacencyMatrix(w, g); assertEquals(UNDIRECTED_ADJACENCY, w.toString()); } public void testAdjacencyDirected() { DirectedGraph g = new DirectedMultigraph(DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); g.addVertex(V3); g.addEdge(V3, V1); g.addEdge(V3, V1); Writer w = new StringWriter(); exporter.exportAdjacencyMatrix(w, g); assertEquals(DIRECTED_ADJACENCY, w.toString()); } } // End MatrixExporterTest.java jgrapht-0.8.3/testsrc/org/jgrapht/ext/GraphMLExporterTest.java0000644000175000017500000000673511706124627024653 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * GraphMLExporterTest.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; import java.io.*; import junit.framework.*; import org.custommonkey.xmlunit.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author Trevor Harmon */ public class GraphMLExporterTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String NL = System.getProperty("line.separator"); // TODO jvs 23-Dec-2006: externalized diff-based testing framework private static final String UNDIRECTED = "" + NL + "" + NL + "" + NL + "" + NL + "" + NL + "" + NL + "" + NL + "" + NL + "" + NL + "" + NL; private static final GraphMLExporter exporter = new GraphMLExporter(); //~ Methods ---------------------------------------------------------------- public void testUndirected() throws Exception { UndirectedGraph g = new SimpleGraph(DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); g.addVertex(V3); g.addEdge(V3, V1); StringWriter w = new StringWriter(); exporter.export(w, g); if (System.getProperty("java.vm.version").startsWith("1.4")) { // NOTE jvs 16-Mar-2007: XML prefix mapping comes out // with missing info on 1.4, so skip the verification part // of the test. return; } XMLAssert.assertXMLEqual(UNDIRECTED, w.toString()); } } // End GraphMLExporterTest.java jgrapht-0.8.3/testsrc/org/jgrapht/ext/GmlExporterTest.java0000644000175000017500000000657711706124627024104 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * GmlExporterTest.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: John V. Sichi * * $Id: GmlExporterTest.java 648 2008-12-19 04:10:28Z vocaro $ * * Changes * ------- * 23-Dec-2006 : Initial revision (JVS); * */ package org.jgrapht.ext; import java.io.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi */ public class GmlExporterTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String NL = System.getProperty("line.separator"); // TODO jvs 23-Dec-2006: externalized diff-based testing framework private static final String UNDIRECTED = "Creator \"JGraphT GML Exporter\"" + NL + "Version 1" + NL + "graph" + NL + "[" + NL + "\tlabel \"\"" + NL + "\tdirected 0" + NL + "\tnode" + NL + "\t[" + NL + "\t\tid 1" + NL + "\t]" + NL + "\tnode" + NL + "\t[" + NL + "\t\tid 2" + NL + "\t]" + NL + "\tnode" + NL + "\t[" + NL + "\t\tid 3" + NL + "\t]" + NL + "\tedge" + NL + "\t[" + NL + "\t\tid 1" + NL + "\t\tsource 1" + NL + "\t\ttarget 2" + NL + "\t]" + NL + "\tedge" + NL + "\t[" + NL + "\t\tid 2" + NL + "\t\tsource 3" + NL + "\t\ttarget 1" + NL + "\t]" + NL + "]" + NL; private static final GmlExporter exporter = new GmlExporter(); //~ Methods ---------------------------------------------------------------- public void testUndirected() { UndirectedGraph g = new SimpleGraph(DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); g.addVertex(V3); g.addEdge(V3, V1); StringWriter w = new StringWriter(); exporter.export(w, g); assertEquals(UNDIRECTED, w.toString()); } } // End GmlExporterTest.java jgrapht-0.8.3/testsrc/org/jgrapht/EnhancedTestCase.java0000644000175000017500000000443311706124626023321 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------- * EnhancedTestCase.java * --------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: EnhancedTestCase.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org.jgrapht; import junit.framework.*; /** * A little extension to JUnit's TestCase. * * @author Barak Naveh * @since Jul 25, 2003 */ public abstract class EnhancedTestCase extends TestCase { //~ Constructors ----------------------------------------------------------- /** * @see TestCase#TestCase() */ public EnhancedTestCase() { super(); } /** * @see TestCase#TestCase(java.lang.String) */ public EnhancedTestCase(String name) { super(name); } //~ Methods ---------------------------------------------------------------- /** * It means: it's wrong that we got here. */ public void assertFalse() { assertTrue(false); } /** * It means: it's right that we got here. */ public void assertTrue() { assertTrue(true); } } // End EnhancedTestCase.java jgrapht-0.8.3/testsrc/org/jgrapht/generate/0000755000175000017500000000000011752244360021102 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/generate/GraphGeneratorTest.java0000644000175000017500000003525611706124627025532 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * GraphGeneratorTest.java * ----------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: GraphGeneratorTest.java 738 2011-01-19 03:55:06Z perfecthash $ * * Changes * ------- * 17-Sep-2003 : Initial revision (JVS); * 07-May-2006 : Changed from List to Set (JVS); * */ package org.jgrapht.generate; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.alg.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi * @since Sep 17, 2003 */ public class GraphGeneratorTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final int SIZE = 10; //~ Instance fields -------------------------------------------------------- private VertexFactory vertexFactory = new VertexFactory() { private int i; public Object createVertex() { return new Integer(++i); } }; //~ Methods ---------------------------------------------------------------- /** * . */ public void testEmptyGraphGenerator() { GraphGenerator gen = new EmptyGraphGenerator(SIZE); DirectedGraph g = new DefaultDirectedGraph(DefaultEdge.class); Map resultMap = new HashMap(); gen.generateGraph(g, vertexFactory, resultMap); assertEquals(SIZE, g.vertexSet().size()); assertEquals(0, g.edgeSet().size()); assertTrue(resultMap.isEmpty()); } /** * . */ public void testLinearGraphGenerator() { GraphGenerator gen = new LinearGraphGenerator(SIZE); DirectedGraph g = new DefaultDirectedGraph(DefaultEdge.class); Map resultMap = new HashMap(); gen.generateGraph(g, vertexFactory, resultMap); assertEquals(SIZE, g.vertexSet().size()); assertEquals(SIZE - 1, g.edgeSet().size()); Object startVertex = resultMap.get(LinearGraphGenerator.START_VERTEX); Object endVertex = resultMap.get(LinearGraphGenerator.END_VERTEX); Iterator vertexIter = g.vertexSet().iterator(); while (vertexIter.hasNext()) { Object vertex = vertexIter.next(); if (vertex == startVertex) { assertEquals(0, g.inDegreeOf(vertex)); assertEquals(1, g.outDegreeOf(vertex)); continue; } if (vertex == endVertex) { assertEquals(1, g.inDegreeOf(vertex)); assertEquals(0, g.outDegreeOf(vertex)); continue; } assertEquals(1, g.inDegreeOf(vertex)); assertEquals(1, g.outDegreeOf(vertex)); } } /** * . */ public void testRingGraphGenerator() { GraphGenerator gen = new RingGraphGenerator(SIZE); DirectedGraph g = new DefaultDirectedGraph(DefaultEdge.class); Map resultMap = new HashMap(); gen.generateGraph(g, vertexFactory, resultMap); assertEquals(SIZE, g.vertexSet().size()); assertEquals(SIZE, g.edgeSet().size()); Object startVertex = g.vertexSet().iterator().next(); assertEquals(1, g.outDegreeOf(startVertex)); Object nextVertex = startVertex; Set seen = new HashSet(); for (int i = 0; i < SIZE; ++i) { DefaultEdge nextEdge = g.outgoingEdgesOf(nextVertex).iterator().next(); nextVertex = g.getEdgeTarget(nextEdge); assertEquals(1, g.inDegreeOf(nextVertex)); assertEquals(1, g.outDegreeOf(nextVertex)); assertTrue(!seen.contains(nextVertex)); seen.add(nextVertex); } // do you ever get the feeling you're going in circles? assertTrue(nextVertex == startVertex); assertTrue(resultMap.isEmpty()); } /** * . */ public void testCompleteGraphGenerator() { Graph completeGraph = new SimpleGraph(DefaultEdge.class); CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(10); completeGenerator.generateGraph( completeGraph, new ClassBasedVertexFactory(Object.class), null); // complete graph with 10 vertices has 10*(10-1)/2 = 45 edges assertEquals(45, completeGraph.edgeSet().size()); } /** * . */ public void testScaleFreeGraphGenerator() { DirectedGraph graph = new DefaultDirectedGraph(DefaultEdge.class); ScaleFreeGraphGenerator generator = new ScaleFreeGraphGenerator(500); generator.generateGraph(graph, vertexFactory, null); ConnectivityInspector inspector = new ConnectivityInspector(graph); assertTrue( "generated graph is not connected", inspector.isGraphConnected()); try { generator = new ScaleFreeGraphGenerator(-50); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } try { generator = new ScaleFreeGraphGenerator(-50, 31337); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { } generator = new ScaleFreeGraphGenerator(0); DirectedGraph empty = new DefaultDirectedGraph(DefaultEdge.class); generator.generateGraph(empty, vertexFactory, null); assertTrue("non-empty graph generated", empty.vertexSet().size() == 0); } /** * . */ public void testCompleteBipartiteGraphGenerator() { Graph completeBipartiteGraph = new SimpleGraph( DefaultEdge.class); CompleteBipartiteGraphGenerator completeBipartiteGenerator = new CompleteBipartiteGraphGenerator( 10, 4); completeBipartiteGenerator.generateGraph( completeBipartiteGraph, new ClassBasedVertexFactory(Object.class), null); // Complete bipartite graph with 10 and 4 vertices should have 14 // total vertices and 4*10=40 total edges assertEquals(14, completeBipartiteGraph.vertexSet().size()); assertEquals(40, completeBipartiteGraph.edgeSet().size()); } /** * . */ public void testHyperCubeGraphGenerator() { Graph hyperCubeGraph = new SimpleGraph( DefaultEdge.class); HyperCubeGraphGenerator hyperCubeGenerator = new HyperCubeGraphGenerator( 4); hyperCubeGenerator.generateGraph( hyperCubeGraph, new ClassBasedVertexFactory(Object.class), null); // Hypercube of 4 dimensions should have 2^4=16 vertices and // 4*2^(4-1)=32 total edges assertEquals(16, hyperCubeGraph.vertexSet().size()); assertEquals(32, hyperCubeGraph.edgeSet().size()); } /** * . */ public void testStarGraphGenerator() { Map map = new HashMap(); Graph starGraph = new SimpleGraph( DefaultEdge.class); StarGraphGenerator starGenerator = new StarGraphGenerator( 10); starGenerator.generateGraph( starGraph, new ClassBasedVertexFactory(Object.class), map); // Star graph of order 10 should have 10 vertices and 9 edges assertEquals(9, starGraph.edgeSet().size()); assertEquals(10, starGraph.vertexSet().size()); assertTrue(map.get(StarGraphGenerator.CENTER_VERTEX) != null); } /** * . */ public void testGridGraphGenerator() { int rows = 3; int cols = 4; //the form of these two classes helps debugging class StringVertexFactory implements VertexFactory { int index = 1; @Override public String createVertex() { return String.valueOf(index++); } } class StringEdgeFactory implements EdgeFactory { @Override public String createEdge( String sourceVertex, String targetVertex) { return new String(sourceVertex + '-' + targetVertex); } } GridGraphGenerator generator = new GridGraphGenerator(rows, cols); Map resultMap = new HashMap(); //validating a directed and undirected graph Graph directedGridGraph = new DefaultDirectedGraph(new StringEdgeFactory()); generator.generateGraph( directedGridGraph, new StringVertexFactory(), resultMap); validateGridGraphGenerator(rows, cols, directedGridGraph, resultMap); resultMap.clear(); Graph undirectedGridGraph = new SimpleGraph(new StringEdgeFactory()); generator.generateGraph( undirectedGridGraph, new StringVertexFactory(), resultMap); validateGridGraphGenerator(rows, cols, undirectedGridGraph, resultMap); } public void validateGridGraphGenerator( int rows, int cols, Graph gridGraph, Map resultMap) { // graph structure validations int expectedVerticeNum = rows * cols; assertEquals( "number of vertices is wrong (" + gridGraph .vertexSet().size() + "), should be " + expectedVerticeNum, expectedVerticeNum, gridGraph.vertexSet().size()); int expectedEdgesNum = (((rows - 1) * cols) + ((cols - 1) * rows)) * ((gridGraph instanceof UndirectedGraph) ? 1 : 2); assertEquals( "number of edges is wrong (" + gridGraph .edgeSet().size() + "), should be " + expectedEdgesNum, expectedEdgesNum, gridGraph.edgeSet().size()); int cornerVertices = 0, borderVertices = 0, innerVertices = 0, neighborsSize; int expCornerVertices = 4; int expBorderVertices = Math.max(((rows - 2) * 2) + ((cols - 2) * 2), 0); int expInnerVertices = Math.max((rows - 2) * (cols - 2), 0); Set neighbors = new HashSet(); for (String v : gridGraph.vertexSet()) { neighbors.clear(); neighbors.addAll(Graphs.neighborListOf(gridGraph, v)); neighborsSize = neighbors.size(); assertTrue( "vertex with illegal number of neighbors (" + neighborsSize + ").", (neighborsSize == 2) || (neighborsSize == 3) || (neighborsSize == 4)); if (neighborsSize == 2) { cornerVertices++; } else if (neighborsSize == 3) { borderVertices++; } else if (neighborsSize == 4) { innerVertices++; } } assertEquals( "there should be exactly " + expCornerVertices + " corner (with two neighbors) vertices. " + " actual number is " + cornerVertices + ".", expCornerVertices, cornerVertices); assertEquals( "there should be exactly " + expBorderVertices + " border (with three neighbors) vertices. " + " actual number is " + borderVertices + ".", expBorderVertices, borderVertices); assertEquals( "there should be exactly " + expInnerVertices + " inner (with four neighbors) vertices. " + " actual number is " + innerVertices + ".", expInnerVertices, innerVertices); // result map validations Set keys = resultMap.keySet(); assertEquals( "result map contains should contains exactly 4 corner verices", 4, keys.size()); for (String key : keys) { neighbors.clear(); neighbors.addAll( Graphs.neighborListOf(gridGraph, resultMap.get(key))); neighborsSize = neighbors.size(); assertEquals( "corner vertex should have exactly 2 neighbors", 2, neighborsSize); } } } // End GraphGeneratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/generate/RandomGraphGeneratorTest.java0000644000175000017500000001156711706124627026672 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * RandomGraphGeneratorTest.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: RandomGraphGeneratorTest.java 704 2010-02-28 02:29:09Z perfecthash $ * * Changes * ------- */ package org.jgrapht.generate; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.experimental.isomorphism.*; import org.jgrapht.graph.*; /** * @author Assaf * @since Aug 6, 2005 */ public class RandomGraphGeneratorTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testGenerateDirectedGraph() { List> graphArray = new ArrayList>(); for (int i = 0; i < 3; ++i) { graphArray.add( new SimpleDirectedGraph( DefaultEdge.class)); } generateGraphs(graphArray, 11, 100); assertTrue( EdgeTopologyCompare.compare(graphArray.get(0), graphArray.get(1))); // cannot assert false , cause it may be true once in a while (random) // but it generally should work. // assertFalse(EdgeTopologyCompare.compare(graphArray.get(1),graphArray.get(2))); } public void testGenerateListenableUndirectedGraph() { List> graphArray = new ArrayList>(); for (int i = 0; i < 3; ++i) { graphArray.add( new ListenableUndirectedGraph( DefaultEdge.class)); } generateGraphs(graphArray, 11, 50); assertTrue( EdgeTopologyCompare.compare(graphArray.get(0), graphArray.get(1))); } public void testBadVertexFactory() { RandomGraphGenerator randomGen = new RandomGraphGenerator( 10, 3); Graph graph = new SimpleDirectedGraph(DefaultEdge.class); try { randomGen.generateGraph( graph, new ClassBasedVertexFactory(String.class), null); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { // expected } } /** * Generates 3 graphs with the same numOfVertex and numOfEdges. The first * two are generated using the same RandomGraphGenerator; the third is * generated using a new instance. * * @param graphs array of graphs to generate * @param numOfVertex number of vertices to generate per graph * @param numOfEdges number of edges to generate per graph */ private static void generateGraphs( List> graphs, int numOfVertex, int numOfEdges) { RandomGraphGenerator randomGen = new RandomGraphGenerator( numOfVertex, numOfEdges); randomGen.generateGraph( graphs.get(0), new IntegerVertexFactory(), null); // use the same randomGen randomGen.generateGraph( graphs.get(1), new IntegerVertexFactory(), null); // use new randomGen here RandomGraphGenerator newRandomGen = new RandomGraphGenerator( numOfVertex, numOfEdges); newRandomGen.generateGraph( graphs.get(2), new IntegerVertexFactory(), null); } } // End RandomGraphGeneratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/generate/AllGenerateTests.java0000644000175000017500000000435611706124627025165 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------- * AllGenerateTests.java * --------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: AllGenerateTests.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org.jgrapht.generate; import junit.framework.*; /** * A TestSuite for all tests in this package. * * @author Barak Naveh */ public final class AllGenerateTests { //~ Constructors ----------------------------------------------------------- private AllGenerateTests() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * Creates a test suite for all tests in this package. * * @return a test suite for all tests in this package. */ public static Test suite() { TestSuite suite = new TestSuite(); // $JUnit-BEGIN$ suite.addTest(new TestSuite(GraphGeneratorTest.class)); suite.addTestSuite(RandomGraphGeneratorTest.class); // $JUnit-END$ return suite; } } // End AllGenerateTests.java jgrapht-0.8.3/testsrc/org/jgrapht/util/0000755000175000017500000000000011752244360020265 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/util/AllUtilTests.java0000644000175000017500000000401611706124627023524 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * AllUtilTests.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: AllUtilTests.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.util; import junit.framework.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.experimental.permutation.*; public class AllUtilTests { //~ Methods ---------------------------------------------------------------- public static Test suite() { TestSuite suite = new TestSuite("Test for org.jgrapht.util"); // $JUnit-BEGIN$ suite.addTestSuite(FibonacciHeapTest.class); suite.addTestSuite(PrefetchIteratorTest.class); suite.addTestSuite(CompoundPermutationIterTest.class); suite.addTestSuite(EquivalenceGroupCreatorTest.class); // $JUnit-END$ return suite; } } // End AllUtilTests.java jgrapht-0.8.3/testsrc/org/jgrapht/util/FibonacciHeapTest.java0000644000175000017500000000601611706124627024450 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * FibonacciHeapTest.java * ----------------- * (C) Copyright 2008-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: FibonacciHeapTest.java 701 2010-01-04 08:36:24Z perfecthash $ * * Changes * ------- * 20-Apr-2008 : Initial revision (JVS); */ package org.jgrapht.util; import java.util.*; import junit.framework.*; public class FibonacciHeapTest extends TestCase { //~ Methods ---------------------------------------------------------------- // in honor of sf.net bug #1845376 public void testAddRemoveOne() { String s = "A"; FibonacciHeapNode n = new FibonacciHeapNode(s); FibonacciHeap h = new FibonacciHeap(); assertTrue(h.isEmpty()); h.insert(n, 1.0); assertFalse(h.isEmpty()); FibonacciHeapNode n2 = h.removeMin(); assertEquals(s, n2.getData()); assertTrue(h.isEmpty()); } public void testGrowReplaceShrink() { Random r = new Random(); int k = 10000; String s = "A"; double t = 0; FibonacciHeap h = new FibonacciHeap(); for (int i = 0; i < (k * 3); ++i) { // during first two-thirds, insert if (i < (k * 2)) { double d = r.nextDouble(); t += d; FibonacciHeapNode n = new FibonacciHeapNode(s); h.insert(n, d); } // during last two-thirds, delete (so during middle // third, we'll do both insert and delete, interleaved) if (i >= k) { FibonacciHeapNode n2 = h.removeMin(); t -= n2.getKey(); } } assertTrue(h.isEmpty()); // tally should come back down to zero, or thereabouts (due to roundoff) assertEquals(0.0, t, 0.00001); } } // End FibonacciHeapTest.java jgrapht-0.8.3/testsrc/org/jgrapht/util/StopWatch.java0000644000175000017500000000443211706124627023051 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * StopWatch.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: StopWatch.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.util; /** * @author Assaf * @since May 30, 2005 */ public class StopWatch { //~ Instance fields -------------------------------------------------------- long beforeTime; //~ Methods ---------------------------------------------------------------- public void start() { this.beforeTime = System.currentTimeMillis(); } public void stopAndReport() { long deltaTime = System.currentTimeMillis() - beforeTime; if (deltaTime > 9999) { double deltaTimeSec = deltaTime / 1000.0; System.out.println( "# Performence: " + deltaTimeSec + " full Seconds"); } else { String timeDesc; timeDesc = (deltaTime <= 10) ? "<10ms [less than minumun measurement time]" : String.valueOf(deltaTime); System.out.println("# Performence: in MiliSeconds:" + timeDesc); } } } // End StopWatch.java jgrapht-0.8.3/testsrc/org/jgrapht/util/PrefetchIteratorTest.java0000644000175000017500000001045311706124627025247 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * PrefetchIteratorTest.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: PrefetchIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.util; import java.util.*; import junit.framework.*; public class PrefetchIteratorTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testIteratorInterface() { Iterator iterator = new IterateFrom1To99(); for (int i = 1; i < 100; i++) { assertEquals(true, iterator.hasNext()); assertEquals(i, iterator.next()); } assertEquals(false, iterator.hasNext()); Exception exceptionThrown = null; try { iterator.next(); } catch (Exception e) { exceptionThrown = e; } assertTrue(exceptionThrown instanceof NoSuchElementException); } public void testEnumInterface() { Enumeration enumuration = new IterateFrom1To99(); for (int i = 1; i < 100; i++) { assertEquals(true, enumuration.hasMoreElements()); assertEquals(i, enumuration.nextElement()); } assertEquals(false, enumuration.hasMoreElements()); Exception exceptionThrown = null; try { enumuration.nextElement(); } catch (Exception e) { exceptionThrown = e; } assertTrue(exceptionThrown instanceof NoSuchElementException); } //~ Inner Classes ---------------------------------------------------------- // This test class supplies enumeration of integer from 1 till 100. public static class IterateFrom1To99 implements Enumeration, Iterator { private int counter = 0; private PrefetchIterator nextSupplier; public IterateFrom1To99() { nextSupplier = new PrefetchIterator( new PrefetchIterator.NextElementFunctor() { public Integer nextElement() throws NoSuchElementException { counter++; if (counter >= 100) { throw new NoSuchElementException(); } else { return new Integer(counter); } } }); } // forwarding to nextSupplier and return its returned value public boolean hasMoreElements() { return this.nextSupplier.hasMoreElements(); } // forwarding to nextSupplier and return its returned value public Object nextElement() { return this.nextSupplier.nextElement(); } public Object next() { return this.nextSupplier.next(); } public boolean hasNext() { return this.nextSupplier.hasNext(); } public void remove() { this.nextSupplier.remove(); } } } // End PrefetchIteratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/0000755000175000017500000000000011752244360020053 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/alg/AllAlgTests.java0000644000175000017500000000703211706124626023100 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * AllAlgTests.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: AllAlgTests.java 746 2011-11-07 06:15:21Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org.jgrapht.alg; import junit.framework.*; import org.jgrapht.experimental.isomorphism.*; /** * A TestSuite for all tests in this package. * * @author Barak Naveh */ public final class AllAlgTests { //~ Constructors ----------------------------------------------------------- private AllAlgTests() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * Creates a test suite for all tests in this package. * * @return a test suite for all tests in this package. */ public static Test suite() { TestSuite suite = new TestSuite(); // $JUnit-BEGIN$ suite.addTest(new TestSuite(ConnectivityInspectorTest.class)); suite.addTest(new TestSuite(DijkstraShortestPathTest.class)); suite.addTest(new TestSuite(BellmanFordShortestPathTest.class)); suite.addTest(new TestSuite(FloydWarshallShortestPathsTest.class)); suite.addTest(new TestSuite(VertexCoversTest.class)); suite.addTest(new TestSuite(CycleDetectorTest.class)); suite.addTest(new TestSuite(BronKerboschCliqueFinderTest.class)); suite.addTest(new TestSuite(TransitiveClosureTest.class)); suite.addTest(new TestSuite(BiconnectivityInspectorTest.class)); suite.addTest(new TestSuite(BlockCutpointGraphTest.class)); suite.addTest(new TestSuite(KShortestPathCostTest.class)); suite.addTest(new TestSuite(KShortestPathKValuesTest.class)); suite.addTest(new TestSuite(KSPExampleTest.class)); suite.addTest(new TestSuite(KSPDiscardsValidPathsTest.class)); suite.addTestSuite(IsomorphismInspectorTest.class); suite.addTest(new TestSuite(EdmondsKarpMaximumFlowTest.class)); suite.addTest(new TestSuite(ChromaticNumberTest.class)); suite.addTest(new TestSuite(EulerianCircuitTest.class)); suite.addTest(new TestSuite(HamiltonianCycleTest.class)); suite.addTest(new TestSuite(KruskalMinimumSpanningTreeTest.class)); suite.addTest(new TestSuite(StoerWagnerMinimumCutTest.class)); // $JUnit-END$ return suite; } } // End AllAlgTests.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/NeighborIndexTest.java0000644000175000017500000001007311706124626024305 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * NeighborIndexTest.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Charles Fry * * $Id: NeighborIndexTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 12-Dec-2005 : Initial revision (CF); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.graph.*; /** * . * * @author Charles Fry */ public class NeighborIndexTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; //~ Methods ---------------------------------------------------------------- public void testNeighborSet() { ListenableUndirectedGraph g = new ListenableUndirectedGraph( DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); NeighborIndex index = new NeighborIndex(g); g.addGraphListener(index); Set neighbors1 = index.neighborsOf(V1); assertEquals(1, neighbors1.size()); assertEquals(true, neighbors1.contains(V2)); g.addVertex(V3); g.addEdge(V3, V1); Set neighbors3 = index.neighborsOf(V3); assertEquals(2, neighbors1.size()); assertEquals(true, neighbors1.contains(V3)); assertEquals(1, neighbors3.size()); assertEquals(true, neighbors3.contains(V1)); g.removeEdge(V3, V1); assertEquals(1, neighbors1.size()); assertEquals(false, neighbors1.contains(V3)); assertEquals(0, neighbors3.size()); g.removeVertex(V2); assertEquals(0, neighbors1.size()); } public void testDirectedNeighborSet() { ListenableDirectedGraph g = new ListenableDirectedGraph( DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addEdge(V1, V2); DirectedNeighborIndex index = new DirectedNeighborIndex(g); g.addGraphListener(index); Set p = index.predecessorsOf(V1); Set s = index.successorsOf(V1); assertEquals(0, p.size()); assertEquals(1, s.size()); assertEquals(true, s.contains(V2)); g.addVertex(V3); g.addEdge(V3, V1); Set q = index.successorsOf(V3); assertEquals(1, p.size()); assertEquals(1, s.size()); assertEquals(true, p.contains(V3)); assertEquals(1, q.size()); assertEquals(true, q.contains(V1)); g.removeEdge(V3, V1); assertEquals(0, q.size()); assertEquals(0, p.size()); g.removeVertex(V2); assertEquals(0, s.size()); } } // End NeighborIndexTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/ConnectivityInspectorTest.java0000644000175000017500000002613711706124626026135 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * ConnectivityInspectorTest.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): John V. Sichi * * $Id: ConnectivityInspectorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 07-Aug-2003 : Initial revision (BN); * 20-Apr-2005 : Added StrongConnectivityInspector test (JVS); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * . * * @author Barak Naveh */ public class ConnectivityInspectorTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String V4 = "v4"; //~ Instance fields -------------------------------------------------------- // DefaultEdge e1; DefaultEdge e2; DefaultEdge e3; DefaultEdge e3_b; DefaultEdge u; //~ Methods ---------------------------------------------------------------- /** * . * * @return a graph */ public Pseudograph create() { Pseudograph g = new Pseudograph(DefaultEdge.class); assertEquals(0, g.vertexSet().size()); g.addVertex(V1); assertEquals(1, g.vertexSet().size()); g.addVertex(V2); assertEquals(2, g.vertexSet().size()); g.addVertex(V3); assertEquals(3, g.vertexSet().size()); g.addVertex(V4); assertEquals(4, g.vertexSet().size()); assertEquals(0, g.edgeSet().size()); e1 = g.addEdge(V1, V2); assertEquals(1, g.edgeSet().size()); e2 = g.addEdge(V2, V3); assertEquals(2, g.edgeSet().size()); e3 = g.addEdge(V3, V1); assertEquals(3, g.edgeSet().size()); e3_b = g.addEdge(V3, V1); assertEquals(4, g.edgeSet().size()); assertNotNull(e3_b); u = g.addEdge(V1, V1); assertEquals(5, g.edgeSet().size()); u = g.addEdge(V1, V1); assertEquals(6, g.edgeSet().size()); return g; } /** * . */ public void testDirectedGraph() { ListenableDirectedGraph g = new ListenableDirectedGraph( DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addEdge(V1, V2); ConnectivityInspector inspector = new ConnectivityInspector(g); g.addGraphListener(inspector); assertEquals(false, inspector.isGraphConnected()); g.addEdge(V1, V3); assertEquals(true, inspector.isGraphConnected()); } /** * . */ public void testIsGraphConnected() { Pseudograph g = create(); ConnectivityInspector inspector = new ConnectivityInspector(g); assertEquals(false, inspector.isGraphConnected()); g.removeVertex(V4); inspector = new ConnectivityInspector(g); assertEquals(true, inspector.isGraphConnected()); g.removeVertex(V1); assertEquals(1, g.edgeSet().size()); g.removeEdge(e2); g.addEdge(V2, V2); assertEquals(1, g.edgeSet().size()); inspector = new ConnectivityInspector(g); assertEquals(false, inspector.isGraphConnected()); } /** * . */ public void testStronglyConnected1() { DirectedGraph g = new DefaultDirectedGraph( DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addEdge(V1, V2); g.addEdge(V2, V1); // strongly connected g.addEdge(V3, V4); // only weakly connected StrongConnectivityInspector inspector = new StrongConnectivityInspector(g); // convert from List to Set because we need to ignore order // during comparison Set> actualSets = new HashSet>(inspector.stronglyConnectedSets()); // construct the expected answer Set> expectedSets = new HashSet>(); Set set = new HashSet(); set.add(V1); set.add(V2); expectedSets.add(set); set = new HashSet(); set.add(V3); expectedSets.add(set); set = new HashSet(); set.add(V4); expectedSets.add(set); assertEquals(expectedSets, actualSets); actualSets.clear(); List> subgraphs = inspector.stronglyConnectedSubgraphs(); for (DirectedSubgraph sg : subgraphs) { actualSets.add(sg.vertexSet()); StrongConnectivityInspector ci = new StrongConnectivityInspector(sg); assertTrue(ci.isStronglyConnected()); } assertEquals(expectedSets, actualSets); } /** * . */ public void testStronglyConnected2() { DirectedGraph g = new DefaultDirectedGraph( DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addEdge(V1, V2); g.addEdge(V2, V1); // strongly connected g.addEdge(V4, V3); // only weakly connected g.addEdge(V3, V2); // only weakly connected StrongConnectivityInspector inspector = new StrongConnectivityInspector(g); // convert from List to Set because we need to ignore order // during comparison Set> actualSets = new HashSet>(inspector.stronglyConnectedSets()); // construct the expected answer Set> expectedSets = new HashSet>(); Set set = new HashSet(); set.add(V1); set.add(V2); expectedSets.add(set); set = new HashSet(); set.add(V3); expectedSets.add(set); set = new HashSet(); set.add(V4); expectedSets.add(set); assertEquals(expectedSets, actualSets); actualSets.clear(); List> subgraphs = inspector.stronglyConnectedSubgraphs(); for (DirectedSubgraph sg : subgraphs) { actualSets.add(sg.vertexSet()); StrongConnectivityInspector ci = new StrongConnectivityInspector(sg); assertTrue(ci.isStronglyConnected()); } assertEquals(expectedSets, actualSets); } /** * . */ public void testStronglyConnected3() { DirectedGraph g = new DefaultDirectedGraph( DefaultEdge.class); g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addEdge(V1, V2); g.addEdge(V2, V3); g.addEdge(V3, V1); // strongly connected g.addEdge(V1, V4); g.addEdge(V2, V4); g.addEdge(V3, V4); // weakly connected StrongConnectivityInspector inspector = new StrongConnectivityInspector(g); // convert from List to Set because we need to ignore order // during comparison Set> actualSets = new HashSet>(inspector.stronglyConnectedSets()); // construct the expected answer Set> expectedSets = new HashSet>(); Set set = new HashSet(); set.add(V1); set.add(V2); set.add(V3); expectedSets.add(set); set = new HashSet(); set.add(V4); expectedSets.add(set); assertEquals(expectedSets, actualSets); actualSets.clear(); List> subgraphs = inspector.stronglyConnectedSubgraphs(); for (DirectedSubgraph sg : subgraphs) { actualSets.add(sg.vertexSet()); StrongConnectivityInspector ci = new StrongConnectivityInspector(sg); assertTrue(ci.isStronglyConnected()); } assertEquals(expectedSets, actualSets); } public void testStronglyConnected4() { DefaultDirectedGraph graph = new DefaultDirectedGraph( new EdgeFactory() { public String createEdge(Integer from, Integer to) { return (from + "->" + to).intern(); } }); new RingGraphGenerator(3).generateGraph( graph, new VertexFactory() { private int i = 0; public Integer createVertex() { return i++; } }, null); StrongConnectivityInspector sc = new StrongConnectivityInspector( graph); Set> expected = new HashSet>(); expected.add(graph.vertexSet()); assertEquals( expected, new HashSet>(sc.stronglyConnectedSets())); } } // End ConnectivityInspectorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/Picture1.jpg0000644000175000017500000011616111706124626022260 0ustar giovannigiovanni����JFIF``��C    $.' ",#(7),01444'9=82<.342��C  2!!22222222222222222222222222222222222222222222222222�� �"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������� ?��(�� (�� (�� (�� (�� (�� (��ڮ�u�i^ ���v��K%���=��c.r UX�20$2��� =fM��u߈���d��c�w*�6RP7`�a��x$��5�R�> ��4R��H�i##��Bk���4��~-3L�m�!��B7H��v�,qנ�.i�֕�<��vW�e��d1��n�N3����s�|I��zV� �#6�~�yh� r�gc�ca9�q���~4мk�5�w��[D𺔒a�O�22���pk��?�ׄ�"�>6��Ķ1,J��R�FL2"�̀��q�d� +/Ú�|?g�i�!��B��.�R VR=C8��G5�@Q@Q@N�U���������-e�$�ä¹ 6 RFr25r�9������ZO�y����@ӥ�Ic�0T9��[9�$0��7h�O�sX�~�w��[jw��G����8Q�EO@$�k��xn�⸷�9���$l]H� �#������:6������{����Ѐ�)e�'"0Cg$q�����Kw� )�-�VÔ®N�”n% ���'� �8�c�� ��n��A$�W�/�_��-Ô§$�I�I���O$�H?��CY�����zo��(����G�<�N�)+� É«�?4Ôšx���si������T�m`á��?�ZG���u�V���4G JW018Ô’îµ½W�G�Q�������6g��W#8�O�5���/4��\���2k]_�gD�Iu�(Ûl �� �(�(����[�u���]��O4ϴ����8�zP��'�'�|��_U�zv�y ����˶��N~b�x��b���]�?�a��+��7R|"�f�A�n��v��T�����H� ���� ���8"�����]�?�a��+��7G�.���\�����Zl��g��߷�lc?t�q}5ͽ��ZZ��`$>`�1$X������gh������e���#�.<��ɻn��� ����1� O��/���������H^9��?�g[�h�uxt��ҭ|���Y\`�Ǵ�#� )$q�= |��kÄ¿j�͖�������Awk�9��H\�eIL�p�d���*x��~ �6����_�zU�}Gk������d�W;A���FI5�z�›x�m�7]D� �ӡm�����;�[v�W.��'M��Η�i�Q��$*�l��NF9É  ��W��[y$��[�D̾R���q�'���V������<�i�� ����z�k��S�Ma����bx���1<~y��n�h�B@�6��T�\�]��u�i�Y�jSŴ�XX+�,cx j�BXg$�5��(�5��:Z�cO𖵦[�����`,1��%9;��:�j�<��o�w�����:?�-��D��+���U�us� G�t/���Cw�����k)Ș!��/��0CH�?�����������C��a����@��<��R�n�,R�?,�$��[�j���S�t�Ç&���_����v�kp$׭�d�K��H�?x���x�L��<�����}�ս��]6� ��s:��,Ë‚0�&a���>����m�_�2G�j[#IO�k�,�ÒF�*s� �s����/U��m.�2h༑6E;��I���b�� xb$���7����!�\��KSL7�.�6�NcO��e�<���r�_�o�q⯇s�Zo�r�]%n�HWcƬ�yw�T+ �ܣ�+��(�ƛ���+9�B��/�d�V�N@^z�\��y��[�qo,sA*�H�2���AG9��Ϋ⛟�^7��zn�.�����Tw���|�;X�p+�<��zMSL���Z�fX�������t=p� c�> �&�� C�^ ��"mQT_Y�H�&u��S��x�'×��Z�A�T��{�ֵi�[�bM��Eڈ��g�@Uy�?����P��;� ,�� d[����`�('�8�^�^w�ÄŸ|O�� ���G��7lT,�FXϳiá�s���(��(��(��(��(��(��(��(��(��(��(��(��(��+��]��Æ¿d��\j�ʗmՌ���#a"�'#%Ma�t�Þw��w�.�+�t�($i�̭�mXIÂŒ(�M��$;S� �|>2�隶�"I���]D��P~��?0�"1�A��{^���H��ÿa��ՓzG�8 c|)Þ²�6H���z��g��v�gd�H$F� ��Tz����6�o�i���+�X�YT6� � �5���c���ij��c#�a�Ƞ��\�;PQ��E�忟�ꖖ(Q�Ò…i�����dp��G�y�MS��&���H�,;%0N<��W�e����Nz�O1��o�iV���4�Fr��B.8��q���_S]eQEW�7��C` k���9!# ��23�=J�} S��^��i�]����_��&�4���cbxQ��xc��h�K�^�|C!�:;F�������8�F�[*!נ�8筢���jpiV�=�wn�����᳂yXÕˆu�:z��;��G�q���6�=����Ä��X3���qֻ��@���徑���mx��Q:U��8�1i�-B��=za����Z5��5C%׋5}N'�� -��dhO�ao-��c��M��2���m*�Ox�G�1i��hc�S��H�� �Øï¿½~��Ԛ��>Ô­e����4�V�O1��o' |��l���𯇭�)�};C�m��D��������X��M�{�OGv�&�i�q<�Mγ�$�������\Юo"ӵ�[� �O�!�!0�d6�6��nm��<@��gC��C�=��a�d�3��F�=U�N`��hB��8���7��Æž\�ѵ���� s�\��X|���f�Ri��� �|{���JL*\?�,�l&J�2/�2U@�4�TpO Õ¼W��4�xäƒ+��s��� (��#�n�巸�9�� I�]H�#�W������[�t�����5��<�+��n�H�KcØ–+�g��(��>*xW�~��k�n�[l�8ÇšwN���*���i�r]M�)�LdAr�9��BX��8�ҵ5/ h:���j�&�}:�E���%`�'�'$��Ѧ�kAÑ®�K�4�� 4����8%@8�€<�X��S�oN�Ӽ+�O�_Î�{�*��@4@7,l��ʃ�Ѷ���XƖ� ��$�޵go��H�b�+0g��&@J�$�NX��f�D�o�~ �ñ––O$�����Xjq-��2�A�@��� �@IEyÞ��_A�*�G�3F�w.N��,b8��?q��%�J��J(��(��(��(��(��(��(��(��(��(��(��+���|����%����6|�u)� �q�2pq��$O��7��s��N�k��mG����y'#lc�#8<�������w��kskx��s��2B�x � ��d|�v������G�����)�#^bÓ¢9�Q �� sÔ€NY����í·ï¿½o�B�@.�-!�b!��rX�S�4`��d�p1�EQEQEQEQYz��� im�kW��Z ��b�zU��p��Ô¯3���S� ���Q������Siar$s�=��N|\�=Ö¯�O��S46�n�|�),d���LҴ�K��4�h���dQ'EÌ’rI<�I9&�0��]/��y�}�V�s^j��g�v �,rB�۞�99'���(��(��(��*�����g%��v�c|3�$F�eO�U�(���Y}�����'�Є�����mY���BJr�9��`��MÔ¼1p,�"hRi��X�ki�����BB /��9!EzeG<�[�oqsA*�92���<G��o��;8�,.໵�;&�A"6  88 �¬W���!�!�����߆5m��&-�Պ�LpS��U�@����/e��ͱS�{IH��T�)��.O ��z����h^+�7Z��k��<��8e�ӌ��dq[QEe�ڜ�m�-�i6�t� H�;ZB �c��f�S��Ee�kR�Y𮑪\,k=�7,`� ���N2}McZx�R��V�5��w<ż�;�u��ˇ��;��˩���sH�N��n�cÝ¡p��*áVR �� �  �;��5O�r�#_K�S�#o�~�^cØ¡`�U�?�w ע�����Cuo-��Q��RH�P��F �Ab�'���+�yc� P�m��ْH���^/� ��4O23e���Nx�b�1� b�&��LÔµ)�V�I�Q�ݠ��vY^<�PW*�n'$4x�����}�I�m��M��z���$�m�`��g�2���m�z�E�Zj�.�� ��r��!<�2 ��A�p���x#���}�Vծ���M��������m�` `g����G�#�iÕµk��?j?5������c�����PEPEPEPE�z�� K�:���m�K�����r��[O����r� ��@��qP��>=���إ�ޫ�]����b��p��*�\g� ���>���6~)���wÚ¤Z�M�0-��f-� �m�B�_j���g��#������b�S�b��1b�y'h,s�� ����� ��&�y���M�Y驩��KXZ����m���w;.PrA�{X2xV�M@Noo~�.E����f �?����lnۻ�P|o-?u[�;Q�����k�xR6�R6!XH�6������ ��3.��˽�Z�X3MM� �!�x��Up���c�ر����8&���E�g� w�'����N���X��(��(��(��(��(��(��/�� \�mV����ѹ�R���6K���.K��e���:�[�E���k9X�=��y� � � ����(��<9�;p�6����%��$���H��2��Z���5����Z�l��Ik{5��w ��v�\���9�犮���KMR7W�R�&�J�� @@`p:c�s�t|k�.>2�-�ނ�E��/�4vϿ��h 燬�M. �;M����0��͘�8ݸ��%�w`nPa!�5)u��SV��,��b��\�!Bdm��<(Q�p*��>#xs�Weks%���I�ߧ�p���6�� !$)8qҺ�(��+����x;To��0B��WdW�/�F�aeQ�`s�%�OL��9� x�K�Ķ|��n���˞��#�8�9�GP@�+��g��5a|K�}S�ı��5��)�*�M��.�Ko�'�B���w# ��Q@Q@Q@Q@Q@Q@Q@p~3��z�xC��u⋔��71i�fYN�!y� *�x��w���G׊.Ss��ŧDq�e8#8 ��$��ǃ<c��-��I.��_ο�'�[�NIf$�������I$� ��<>���/o���A�97z�фf\���!8��/YEQEQEy���/� ���6K���=v�]�c�º����A{�����$��s�gg��+���×ґ�k�/��s��ܱ�p���r#� *8'���+�yc� P�d����Fp� ��bpO%�UubOQ@(��#W�W�vH'���S�� ��C`��~VR$G5��/u�CK{ �Y�97Lc+4n�*�lv8&&႞�P�Q@y������Kui>y�*xW�~��k�n�[l�8ÇšwN���*�Ã��օ��9�e�9�$����`c �0y����-[ò¿µ´ï¿½�'>_���]��q�g��� �>,�ާy���4���3�/c����'�V�r��<�Y�k7��������aӱ�J���%���������W��¬����?�8��(��#�V��O�S�Z_���L3��+`�$�#��ڀ=���ìŠ:_�yx�C�<Ͽ�`��N:l� ݜ���c���G⮙���Ú�m� }2�Ki��Za�������Q^� �������)��>i��X�iX�`��A��G�-?�s���΀=����]^��w���WK�ַ3�!q���B�pO#�ji���۴��'�Q�u0�l�M��z�} u�V^��]Y�k}/[�o�T.���$� d�$�$ �Ԡ�3-��orN��G(����3����� �/u�j6�h,��nc�S*��$��X���H�u����o+[���&4��+68�$ ��ǡ�_J�uI�/�hz�6PG|�ed��y�.d��Ѧ6��pO(�����j+a�ikaq5��� q�@T0o�v��L���pM.��_C�����q����\n�����~V������H�g���'�N�U��&����Fd�V�Ŝ�M��(�����Rx�÷���=���0MÌ—s�$`��R>&N�c3������ KN���b�\“FH�U�#�5b�iz|:N�e�ےa�� �w]��FV���(��(��(��(�����g%��v�c|3�$F�eO�W����R�����w�ɦ��o٦����Y r�3��P���bmEo�� jZ��O{F{&o/pċ��C ����q�7�z��w�p]�É�A ���G�RO7V���E�J�$�E ��`��+���_�ד���'�ޥ&Y����s��9��8*�|���}ag���giݬ�� ��AS����~0��? �o�|5�we<j�)g�VtTQ"�܃s�����T���?_xjmSiT��X��n^�"6�o8���J�F� w��?��[t���=̠�m%Ҭ�t��rE��U ��I+�g>��_h�]�r^ʉ�9�s �q!rx��g�x��g�5w��\Ô¬.�����D���C���y2q��<���w�{����6(���ɰ���8�xFUP�0ev��َ>����3â§ï¿½7��&����ﵱ��s�y�wt�q����'���+�yc� P_���]��q�g���?�������v���PA�x�6sM��PE4qy�h�)�PN���NH���ZV���#��ޕ��f��K��U<\N:��_�&N�J�� -��Új=��g�d�[v�|���� ���t�V�D�K�р#<�T��]%a�� �\Kqq�i�r�I%�L���J�y�hi����۵Ɨ�Z_@�Q���eP��#8 ��U���/���n{� Z#�՞�q�yX�A<��zz �� s¶����U�n� u�j2���З,6��Ӫ�h�(�?��aq�l��$�O���Dч�xʀ�eI�qG�"_������h�(�?����R7�M�� Ä«�k�X�'޼���d�#jJ7����8"�=����X"ӿ�?��\���S�$z�q���+���=y���Öo��[�^+�,W�e���� ^���<�(�<�@�Ey��.߇��0������y������h�6�muK4�]�Z�(��G��Ä�+��088O�_ |A���G�pi�e���v6��8a� db��Ò1�p ����%Ó¾^G�mW�����9���͢y�DP�/ve?)��)5�|>�ۤx���uu�K�$u�$�LW,W�!, Ǻ�X�4�i:? ��`'�e�Q�99�r�j_�y?�w^������5���c�>6������g˶�m~%|<�{F���d�k��%��g�&���f2Z�Q�'� ����c�}��n���,�G�������ϟ����4W�����y�C�I\�?�v�<����$�?��z���~����W�n��]�?�a��+��7@�Ey��.߇��0������o����J�����Q^� ���� ?�%q�������������t�W�����y�C�I\�?�v�<����$�?��z���~����W�n��]�?�a��+��7@�Ey��.߇��0������o����J�����Q^� ���� ?�%q�������������t�W�����y�C�I\�?�v�<����$�?��z���~����W�n��]�?�a��+��7@�^�O h�g��C�F�w�ϋ{$�K������eUW�%�. ��o����J����� ���� ?�%q����;�3Y�G����n��-��'������ �ʀ�?�UA�*/���?f���֗(�K�]���O6&��*���l( �Hj���]����Þ���A��R�v3�!S�>�К�|�;io<�kl�M��?��2 � d �� t�QEq�7��#�f�t�_�?j?-������9c'9��̠!������G�xgO�u�7ke$�tqbh��]p짃�q�ؚ+�� �U�����y�����֡p�{��|�d`p'�I(��\ˢ�H��H�=��V�X�t�eQ1 ������d�㼿7k�\���DLm�bDfL�����8�\ߎS�q��:*+>����6%ak�D�*].�n# �QU�1�^jz)����Q��[;A�ÊžH�,�d 8��@QEQEQEQEQEQEQEQEQEQEQEQEQEQEQEW?� ߃��k���c�\��.߇��0�����@����������w��m[�n���c��t%�*F���o�+��'���/����l�8�W�q����@�Ey���,_��i~���gq4�G���9##� ��?�^x�J�d_�[�`���]�;�����Mz��ð®µC����O�t>Um1��0�@1� �I����G�)���~�\���?ں���g�lÙ·�\�?tP_�K[�u4�����zM���B�"�e8�x2��B�'� c�{L�?��� B�^�u]@:�v� �G�l�Q���d�l3���4Ï…~�<ß³xf�O7�֦��1��׶3�z ��|5��� q��m��K[T����d�a@.|D���X�W�MgM��1B�g1�Ƞ�����#=�ÿ��*YI)�ɛ��sdä§so�8 I� ��|=?��_�iZ�v������@�9� ����@�����㼰����L� ��$0���? �@oo�;���u��iV�Z�g�O��g�3y2+�rnP���ʓ��EuZ��{u�5���-��[ [���v����k�w�97 �:��<)�iu��y�ô� R� �n�b1� ��W.�|W�O�C�ov�D�*��⋈�#}��f$�q�Px�8��Yi��h������t�-�#�7�R��� ���������3��Z-���ix�\Kp� 6��K+���G���09�\z|P��E�σ5--E�jX��]͵��O���ar����Zx��ľ�/�{i��En���7 #Y��e�-���h���n.%�"B�I#TP2I'��5���Z_�41`|���V��{w=���7|v ��ㆾ�W���e&�i=�j���$��#FÝ‹6wdc�2�;��Z�u��� ����o&�wp�$'�Œ4���y � �Ikx���dq�P=Ulr3�>��� =2�;; H--c��`�F��IÂŽI'�Ox�F���6����ni$��' ����}�@���i���~!�o���,Z�Nډ�>Ã’�ۂy8������,^��JÖ­�L�M��*��L�3�zá½[��&�i�i��kt�а���=A�s�>�ck���Z4�Y�KF�N��hg ��#d�����,�����X|a�; z y-���\�Q��0��7)��#��@Q@Q@��ko-�ı�H^I$`��I$���� �6��Y��Z1Hл�cv �Ic�'�t�W�����y�C�I\�?�i�ԅ����t�W���e��{g��w���� �B��/�cRxo�I�Sww�� *F{[!&� 8�^S�� ��$��OO�rx�͸�➿�ީ����pB��(�� ����M��Kĺ�p�����c��H��H� A�A�5�X|1����y�]������Wy�v�1���pFrMi��ᶉy�����3GkxRy�`䨔����p�ր,j< �y_i�5��nv��1��� ��|g�t5�� �÷����\r2{Q� �koX�s?ݼ���xc�'rD7������x�����|X��F��<)���z���i���/�rFzH� ?� ������;ڿ�2���C!C��Q��0k�(�?��Qo'��� � �ӿ��Ӵ�{�o�d�����x�V̀���l�z�gX��ŗ��a�Y<��y�t�J�y��?*��k6~��u{��kiJ� �E\� �y$ �x���|O�G��6�� �[o�: x� D�0 ��� |��]G�,j?��s�O����Ւ=?�7��ѳ��z�υ�U����g�?�5+���Ĝ3K#��� @�(�9�Ҁ<��s�v��?iZ,��OS1��,#pc�rx�=ȣ�;⮧��{Ú,k�2�K���Vc�)�9��נQ@�G��?��o�w�ؿ�İӡ��㑶U�^@�##��t��j�%�^�b��,o�Vhe��)��� � (������k��O�^7�K��I<�9 =� ����V��+� h����H�"VF � ��kr�(��(����Ki�u.�bI ���e`ۇ�3����,|am�j�����nmt�+k���D�*���*�Nyb�Q@%���mÇ«i�D�N���/� �Ѵh� �UI�^�=9�~/�t}3���U���=A�t��#+��@�–!s�'k��n�巸�9�� I�]H�#�T�QEQEQEQEQEQEQQ�<6���\K0D��F ��d�O�k��%^k���/ý> j�}�Q��Y�~�/'�&@c��+��_���m-�-j�;K@�7�,Y�@���=N<z^w�wň?必�q�w�F�������Z+q��߆�^���@z�4� ik��1�Z/�Ib�z�f$��2I�� Ԣ�(��(��(��(��(��(��(��*�����g%��v�c|3�$F�eO�V���ֻn�o�Z\�s\�*��-�b�؄"����+"��P���/�x�. �Ԥ�;�����2­jØŒ$D�w`���t� �/ \χz�`.M&�k)y@zå�-�1�QRi��� �|{���JL*\?�,�l&J�2/�2U@�5�k��˦;�_�ci �f��*���x �9�q�}=k��~��zM��h5f�[��w��n �Iܠ� �:���?�4�hsi�m���/���� �̂$Ox��{�>k~m����:�2C�->ANX`eryg=+CJ�t����}\d�:��̀�l+�}�p��.��z�ç�G��rO��xmb�\��]�\as� �S����YLʯs#D���"�d���ɭ�(���M�4۵���o��]�/,�+ËÑ•8 !��H�ii�e��n�[�v�ϼ���n8�����L��PY�·��N{ ^� �V��2gi ��z�`�0��օ��x�> �q��[�lF���Չ��h؉� r�+��9�Z�� �f=�:u߇u�dv��1�w2�*P`v�$�wWyYz��4��m��V1����R�:e ��2��КԢ��? ����?���!ѣڿ���f�G���n�6Úª?��lxk▅�^.�~��z�گ��hb}� �l�G z��;�(�� (�� (�� +�������5��1����M7V�u�v��� K��4��,���$g{��EPEPEPEPEPE^���L����� KX�i���2Ç�@�h����� YN�3O�\�Ee�F��; �xJ�rWq�pqNx~*x�K�7��|�Q�r}��'��N�=AF\q���5�h�����R�� ;��P� Q�ؽ\�����_�w� y��ዽtF��;}��_j�| �(J2@<� j�mj K�:��; �iu9Z4���(�͌��&[�x�A I:�#d`�*�>�;�����R�=���ɩ���l������0�+ `��h����9,4�,�Wd)��71�̀2�$�@��㯠\�� st` x�0\��Xq��b�(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��WB�]���4�/c_�\��v��.v�����آ�<�? ����?���!ѣڿ���f�G���n�6Úª?��t��vÓ®!�G�b�%Òµ�͒����<� ��+��_��9�;r�Î����$���ÎH��r��@%SÒµ[sK���˘�l�|R�F�r<�8"��Q��? ,��?���G���:jS�/ R\��$����p��^q�S�w�#z����}���;�2��?�?,m�z��?(,h��K���6����[�ª���;���$H��|!�?�����5 �?I���|7j�XX�!Qp�'nJ��NAC�x��,�M4�K�2�7 ��f �.0w��IX �I>�@��mo �]�hL�Q�9f��$�޳�����-�?ijꎱ�`�Ý���&�F��zrsw�Z�Þ���:�!��r������� ��[�|G��IÕµk��_O�y��TݶgQ€s�!�~k�/���-�dV h�~T�@�98� I=I$n��B�����:�~��n�h���Ë@`pA�\���V�R�D0j�2\km���NYe�� Xp�!O����iEg�zî¢y_�ڭ����/�w �c8�Fq���W?��T�6��}���2y���F78�3�(6޽�q��aEy��ɠ^�o@��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(����/�4?��o��Iu^8�ı��1��'��'Ms����r������?��_�%��{M�#i-�E��)�26���1c��J��w���C����+Ksc����I�%��\� 9 @��P��J�lu�.�S�.c���M�J�0A� � ���U��:����_�c+�[����b�S�S� ��7�{�Fo���:_��`��KÏ´+�tҗ�)���^��B��MN������� �\[���bÇ–$�I<�Я�g�toK�}SY{��2^=��ݺY�7 \ B77.��#������A��Eѣ���:�4zu�;K! �9�����b���>ð†ƒÄ— h� �.����t��s��OZ��>�H�~��<�n�Z��c8Çš[o^���+��4-D��t�;g�-�-��3� �'��� (��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(�7��}�xkXmW����J�u�� ���(�Pe��*�i�(���7��T0^|=���7e76��P�(�pÊ��s�: .o�(�:sgh���;�o� 溓�6�yI�`���d�F:���;�V>{�绻�u��E���|���I�S+�d����c���(��(��(��(��(��(��(��(��(��(��(��(��(��(��(���� jgrapht-0.8.3/testsrc/org/jgrapht/alg/BlockCutpointGraphTest.java0000644000175000017500000001113711706124626025324 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BlockCutpointGraphTest.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: BlockCutpointGraphTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class BlockCutpointGraphTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testBiconnected() { BiconnectedGraph graph = new BiconnectedGraph(); BlockCutpointGraph blockCutpointGraph = new BlockCutpointGraph(graph); testGetBlock(blockCutpointGraph); assertEquals(0, blockCutpointGraph.getCutpoints().size()); int nbBiconnectedComponents = blockCutpointGraph.vertexSet().size() - blockCutpointGraph.getCutpoints().size(); assertEquals(1, nbBiconnectedComponents); } public void testGetBlock(BlockCutpointGraph blockCutpointGraph) { for ( Iterator iter = blockCutpointGraph.vertexSet().iterator(); iter.hasNext();) { UndirectedGraph component = (UndirectedGraph) iter.next(); if (!component.edgeSet().isEmpty()) { for ( Iterator iterator = component.vertexSet().iterator(); iterator.hasNext();) { Object vertex = iterator.next(); if (!blockCutpointGraph.getCutpoints().contains(vertex)) { assertEquals( component, blockCutpointGraph.getBlock(vertex)); } } } else { assertTrue( blockCutpointGraph.getCutpoints().contains( component.vertexSet().iterator().next())); } } } public void testLinearGraph() { testLinearGraph(3); testLinearGraph(5); } public void testLinearGraph(int nbVertices) { UndirectedGraph graph = new SimpleGraph(DefaultEdge.class); LinearGraphGenerator generator = new LinearGraphGenerator(nbVertices); generator.generateGraph( graph, new ClassBasedVertexFactory( Object.class), null); BlockCutpointGraph blockCutpointGraph = new BlockCutpointGraph(graph); testGetBlock(blockCutpointGraph); assertEquals(nbVertices - 2, blockCutpointGraph.getCutpoints().size()); int nbBiconnectedComponents = blockCutpointGraph.vertexSet().size() - blockCutpointGraph.getCutpoints().size(); assertEquals(nbVertices - 1, nbBiconnectedComponents); } public void testNotBiconnected() { UndirectedGraph graph = new NotBiconnectedGraph(); BlockCutpointGraph blockCutpointGraph = new BlockCutpointGraph(graph); testGetBlock(blockCutpointGraph); assertEquals(2, blockCutpointGraph.getCutpoints().size()); int nbBiconnectedComponents = blockCutpointGraph.vertexSet().size() - blockCutpointGraph.getCutpoints().size(); assertEquals(3, nbBiconnectedComponents); } } // End BlockCutpointGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/Picture1Graph.java0000644000175000017500000000756511706124626023412 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * Picture1Graph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: Picture1Graph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * * * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class Picture1Graph extends SimpleDirectedWeightedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 5587737522611531029L; //~ Instance fields -------------------------------------------------------- public Object e15; public Object e25; public Object e27; public Object e37; public Object e47; public Object e56; public Object e57; public Object e67; public Object eS1; public Object eS2; public Object eS3; public Object eS4; public Object eS7; //~ Constructors ----------------------------------------------------------- /** * */ public Picture1Graph() { super(DefaultWeightedEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { this.eS1 = this.addEdge("vS", "v1"); this.eS2 = this.addEdge("vS", "v2"); this.eS3 = this.addEdge("vS", "v3"); this.eS4 = this.addEdge("vS", "v4"); this.eS7 = this.addEdge("vS", "v7"); this.e15 = this.addEdge("v1", "v5"); this.e25 = this.addEdge("v2", "v5"); this.e27 = this.addEdge("v2", "v7"); this.e37 = this.addEdge("v3", "v7"); this.e47 = this.addEdge("v4", "v7"); this.e56 = this.addEdge("v5", "v6"); this.e57 = this.addEdge("v5", "v7"); this.e67 = this.addEdge("v6", "v7"); setEdgeWeight(this.eS1, 3.0); setEdgeWeight(this.eS2, 2.0); setEdgeWeight(this.eS3, 10.0); setEdgeWeight(this.eS4, 15.0); setEdgeWeight(this.eS7, 15.0); setEdgeWeight(this.e15, 3.0); setEdgeWeight(this.e25, 6.0); setEdgeWeight(this.e27, 10.0); setEdgeWeight(this.e37, 20.0); setEdgeWeight(this.e47, 5.0); setEdgeWeight(this.e56, -3.0); setEdgeWeight(this.e57, 4.0); setEdgeWeight(this.e67, 5.0); } private void addVertices() { addVertex("vS"); addVertex("v1"); addVertex("v2"); addVertex("v3"); addVertex("v4"); addVertex("v5"); addVertex("v6"); addVertex("v7"); } } // End Picture1Graph.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KSPDiscardsValidPathsTest.java0000644000175000017500000001242711706124626025657 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KSPDiscardsValidPathsTest.java * ------------------------- * (C) Copyright 2010-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: MaskFunctor.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Dec-2010 : Initial revision (GB); * */ package org.jgrapht.alg; import junit.framework.*; import org.jgrapht.graph.*; @SuppressWarnings("unchecked") public class KSPDiscardsValidPathsTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * Example with a biconnected graph but not 3-connected. With a graph not * 3-connected, the start vertex and the end vertex can be disconnected by 2 * paths. */ public void testNot3connectedGraph() { WeightedMultigraph graph; KShortestPaths paths; graph = new WeightedMultigraph( DefaultWeightedEdge.class); graph.addVertex("S"); graph.addVertex("T"); graph.addVertex("A"); graph.addVertex("B"); graph.addVertex("C"); graph.addVertex("D"); graph.addVertex("E"); graph.addVertex("F"); graph.addVertex("G"); graph.addVertex("H"); graph.addVertex("I"); graph.addVertex("J"); graph.addVertex("K"); graph.addVertex("L"); this.addGraphEdge(graph, "S", "A", 1.0); this.addGraphEdge(graph, "A", "T", 1.0); this.addGraphEdge(graph, "A", "B", 1.0); this.addGraphEdge(graph, "B", "T", 1.0); this.addGraphEdge(graph, "B", "C", 1.0); this.addGraphEdge(graph, "C", "D", 1.0); this.addGraphEdge(graph, "C", "E", 1.0); this.addGraphEdge(graph, "C", "F", 1.0); this.addGraphEdge(graph, "D", "G", 1.0); this.addGraphEdge(graph, "E", "G", 1.0); this.addGraphEdge(graph, "F", "G", 1.0); this.addGraphEdge(graph, "G", "H", 1.0); this.addGraphEdge(graph, "H", "I", 1.0); this.addGraphEdge(graph, "I", "J", 1.0); this.addGraphEdge(graph, "J", "K", 1.0); this.addGraphEdge(graph, "K", "L", 1.0); this.addGraphEdge(graph, "L", "S", 1.0); paths = new KShortestPaths(graph, "S", 3); Assert.assertTrue(paths.getPaths("T").size() == 3); } /** * JUnit test for the bug reported by Bruno Maoili. Example with a connected * graph but not 2-connected. With a graph not 2-connected, the start vertex * and the end vertex can be disconnected by 1 path. */ public void testBrunoMaoili() { WeightedMultigraph graph; KShortestPaths paths; graph = new WeightedMultigraph( DefaultWeightedEdge.class); graph.addVertex("A"); graph.addVertex("B"); graph.addVertex("C"); graph.addVertex("D"); graph.addVertex("E"); this.addGraphEdge(graph, "A", "B", 1.0); this.addGraphEdge(graph, "A", "C", 2.0); this.addGraphEdge(graph, "B", "D", 1.0); this.addGraphEdge(graph, "B", "D", 1.0); this.addGraphEdge(graph, "B", "D", 1.0); this.addGraphEdge(graph, "B", "E", 1.0); this.addGraphEdge(graph, "C", "D", 1.0); paths = new KShortestPaths(graph, "A", 2); Assert.assertTrue(paths.getPaths("E").size() == 2); paths = new KShortestPaths(graph, "A", 3); Assert.assertTrue(paths.getPaths("E").size() == 3); paths = new KShortestPaths(graph, "A", 4); Assert.assertTrue(paths.getPaths("E").size() == 4); } private void addGraphEdge( WeightedMultigraph graph, String sourceVertex, String targetVertex, double weight) { DefaultWeightedEdge edge = new DefaultWeightedEdge(); graph.addEdge(sourceVertex, targetVertex, edge); graph.setEdgeWeight(edge, weight); } } // End KSPDiscardsValidPathsTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KShortestPathKValuesTest.java0000644000175000017500000001123111706124626025613 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPathKValuesTest.java * ------------------------- * (C) Copyright 2007-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KShortestPathKValuesTest.java 742 2011-03-12 23:06:31Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 06-Dec-2010 : Bugfixes (GB); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class KShortestPathKValuesTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * @param k * @param n * * @return A(n,k). */ public static long permutation(int n, int k) { if (k <= n) { return MathUtil.factorial(n) / MathUtil.factorial(n - k); } else { return 0; } } public void testMaxSizeValueCompleteGraph6() { KShortestPathCompleteGraph6 graph = new KShortestPathCompleteGraph6(); for ( int maxSize = 1; maxSize <= calculateNbElementaryPathsForCompleteGraph(6); maxSize++) { KShortestPaths finder = new KShortestPaths(graph, "vS", maxSize); assertEquals(finder.getPaths("v1").size(), maxSize); assertEquals(finder.getPaths("v2").size(), maxSize); assertEquals(finder.getPaths("v3").size(), maxSize); assertEquals(finder.getPaths("v4").size(), maxSize); assertEquals(finder.getPaths("v5").size(), maxSize); } } public void testNbReturnedPaths() { KShortestPathCompleteGraph4 kSPCompleteGraph4 = new KShortestPathCompleteGraph4(); verifyNbPathsForAllPairsOfVertices(kSPCompleteGraph4); KShortestPathCompleteGraph5 kSPCompleteGraph5 = new KShortestPathCompleteGraph5(); verifyNbPathsForAllPairsOfVertices(kSPCompleteGraph5); KShortestPathCompleteGraph6 kSPCompleteGraph6 = new KShortestPathCompleteGraph6(); verifyNbPathsForAllPairsOfVertices(kSPCompleteGraph6); } /** * Compute the total number of paths between every pair of vertices in a * complete graph with n vertices. * * @param n * * @return */ private long calculateNbElementaryPathsForCompleteGraph(int n) { long nbPaths = 0; for (int k = 1; k <= (n - 1); k++) { nbPaths = nbPaths + permutation(n - 2, k - 1); } return nbPaths; } private void verifyNbPathsForAllPairsOfVertices(Graph graph) { long nbPaths = calculateNbElementaryPathsForCompleteGraph( graph.vertexSet().size()); int maxSize = Integer.MAX_VALUE; for ( Iterator sourceIterator = graph.vertexSet().iterator(); sourceIterator.hasNext();) { Object sourceVertex = sourceIterator.next(); KShortestPaths finder = new KShortestPaths(graph, sourceVertex, maxSize); for ( Iterator targetIterator = graph.vertexSet().iterator(); targetIterator.hasNext();) { Object targetVertex = targetIterator.next(); if (targetVertex != sourceVertex) { assertEquals(finder.getPaths(targetVertex).size(), nbPaths); } } } } } // End KShortestPathKValuesTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/EulerianCircuitTest.java0000644000175000017500000000645411706124626024657 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * EulerianCircuitTest.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: EulerianCircuitTest.java 652 2008-12-24 21:26:17Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.alg; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * . * * @author Andrew Newell */ public class EulerianCircuitTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testEulerianCircuit() { UndirectedGraph completeGraph1 = new SimpleGraph( DefaultEdge.class); CompleteGraphGenerator completeGenerator1 = new CompleteGraphGenerator( 6); completeGenerator1.generateGraph( completeGraph1, new ClassBasedVertexFactory(Object.class), null); // A complete graph of order 6 will have all vertices with degree 5 // which is odd, therefore this graph is not Eulerian assertFalse(EulerianCircuit.isEulerian(completeGraph1)); assertTrue( EulerianCircuit.getEulerianCircuitVertices(completeGraph1) == null); UndirectedGraph completeGraph2 = new SimpleGraph( DefaultEdge.class); CompleteGraphGenerator completeGenerator2 = new CompleteGraphGenerator( 5); completeGenerator2.generateGraph( completeGraph2, new ClassBasedVertexFactory(Object.class), null); assertTrue(EulerianCircuit.isEulerian(completeGraph2)); // There are 10 edges total in this graph, so an Eulerian circuit // labeled by vertices should have 11 vertices assertEquals( 11, EulerianCircuit.getEulerianCircuitVertices(completeGraph2).size()); } } // End EulerianCircuitTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/util/0000755000175000017500000000000011752244360021030 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/alg/util/AllAlgUtilTests.java0000644000175000017500000000411611706124627024714 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * AllAlgTests.java * ---------------- * (C) Copyright 2010-2010, by Tom Conerly and Contributors. * * Original Author: Tom Conerly * Contributor(s): * * Changes * ------- * 2-Feb-2010 : Initial revision (TC); * */ package org.jgrapht.alg.util; import junit.framework.*; /** * A TestSuite for all tests in this package. * * @author Tom Conerly */ public final class AllAlgUtilTests { //~ Constructors ----------------------------------------------------------- private AllAlgUtilTests() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * Creates a test suite for all tests in this package. * * @return a test suite for all tests in this package. */ public static Test suite() { TestSuite suite = new TestSuite(); // $JUnit-BEGIN$ suite.addTest(new TestSuite(UnionFindTest.class)); // $JUnit-END$ return suite; } } // End AllAlgUtilTests.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/util/UnionFindTest.java0000644000175000017500000000765511706124627024443 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * UnionFindTest.java * ------------------------------ * (C) Copyright 2010-2010, by Tom Conerly and Contributors. * * Original Author: Tom Conerly * Contributor(s): - * * Changes * ------- * 02-Feb-2010 : Initial revision (TC); * */ package org.jgrapht.alg.util; import java.util.*; import junit.framework.*; /** * . * * @author Tom Conerly */ public class UnionFindTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testUnionFind() { TreeSet set = new TreeSet(); String [] strs = { "aaa", "bbb", "ccc", "ddd", "eee" }; ArrayList> sets = new ArrayList>(); for (String str : strs) { set.add(str); sets.add(new ArrayList()); sets.get(sets.size() - 1).add(str); } UnionFind uf = new UnionFind(set); testIdentical(strs, sets, uf); uf.union(strs[0], strs[1]); union(sets, strs[0], strs[1]); testIdentical(strs, sets, uf); uf.union(strs[2], strs[3]); union(sets, strs[2], strs[3]); testIdentical(strs, sets, uf); uf.union(strs[2], strs[4]); union(sets, strs[2], strs[4]); testIdentical(strs, sets, uf); uf.union(strs[2], strs[4]); union(sets, strs[2], strs[4]); testIdentical(strs, sets, uf); uf.union(strs[0], strs[4]); union(sets, strs[0], strs[4]); testIdentical(strs, sets, uf); } private void union(ArrayList> sets, String a, String b) { ArrayList toAdd = new ArrayList(); for (int i = 0; i < sets.size(); i++) { if (sets.get(i).contains(a)) { toAdd.addAll(sets.get(i)); sets.remove(i); break; } } for (int i = 0; i < sets.size(); i++) { if (sets.get(i).contains(b)) { toAdd.addAll(sets.get(i)); sets.remove(i); break; } } sets.add(toAdd); } private boolean same(ArrayList> sets, String a, String b) { for (ArrayList set : sets) { if (set.contains(a) && set.contains(b)) { return true; } } return false; } private void testIdentical( String [] universe, ArrayList> sets, UnionFind uf) { for (String a : universe) { for (String b : universe) { boolean same1 = uf.find(a).equals(uf.find(b)); boolean same2 = same(sets, a, b); assertEquals(same1, same2); } } } } // End UnionFindTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/BiconnectivityInspectorTest.java0000644000175000017500000000631211706124626026441 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BiconnectivityInspectorTest.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: BiconnectivityInspectorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class BiconnectivityInspectorTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testBiconnected() { BiconnectedGraph graph = new BiconnectedGraph(); BiconnectivityInspector inspector = new BiconnectivityInspector(graph); assertTrue(inspector.isBiconnected()); assertEquals(0, inspector.getCutpoints().size()); assertEquals(1, inspector.getBiconnectedVertexComponents().size()); } public void testLinearGraph() { testLinearGraph(3); testLinearGraph(5); } public void testLinearGraph(int nbVertices) { UndirectedGraph graph = new SimpleGraph(DefaultEdge.class); LinearGraphGenerator generator = new LinearGraphGenerator(nbVertices); generator.generateGraph( graph, new ClassBasedVertexFactory( Object.class), null); BiconnectivityInspector inspector = new BiconnectivityInspector(graph); assertEquals(nbVertices - 2, inspector.getCutpoints().size()); assertEquals( nbVertices - 1, inspector.getBiconnectedVertexComponents().size()); } public void testNotBiconnected() { NotBiconnectedGraph graph = new NotBiconnectedGraph(); BiconnectivityInspector inspector = new BiconnectivityInspector(graph); assertEquals(2, inspector.getCutpoints().size()); assertEquals(3, inspector.getBiconnectedVertexComponents().size()); } } // End BiconnectivityInspectorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/ShortestPathTestCase.java0000644000175000017500000001072511706124626025010 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * ShortestPathTestCase.java * ------------------------------ * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: ShortestPathTestCase.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 14-Jan-2006 : Factored out of DijkstraShortestPathTest (JVS); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi */ public abstract class ShortestPathTestCase extends TestCase { //~ Static fields/initializers --------------------------------------------- static final String V1 = "v1"; static final String V2 = "v2"; static final String V3 = "v3"; static final String V4 = "v4"; static final String V5 = "v5"; //~ Instance fields -------------------------------------------------------- DefaultWeightedEdge e12; DefaultWeightedEdge e13; DefaultWeightedEdge e15; DefaultWeightedEdge e24; DefaultWeightedEdge e34; DefaultWeightedEdge e45; //~ Methods ---------------------------------------------------------------- /** * . */ public void testPathBetween() { List path; Graph g = create(); path = findPathBetween(g, V1, V2); assertEquals(Arrays.asList(new DefaultEdge[] { e12 }), path); path = findPathBetween(g, V1, V4); assertEquals(Arrays.asList( new DefaultEdge[] { e12, e24 }), path); path = findPathBetween(g, V1, V5); assertEquals(Arrays.asList( new DefaultEdge[] { e12, e24, e45 }), path); path = findPathBetween(g, V3, V4); assertEquals(Arrays.asList( new DefaultEdge[] { e13, e12, e24 }), path); } protected abstract List findPathBetween( Graph g, String src, String dest); protected Graph create() { return createWithBias(false); } protected Graph createWithBias( boolean negate) { Graph g; double bias = 1; if (negate) { // negative-weight edges are being tested, so only a directed graph // makes sense g = new SimpleDirectedWeightedGraph( DefaultWeightedEdge.class); bias = -1; } else { // by default, use an undirected graph g = new SimpleWeightedGraph( DefaultWeightedEdge.class); } g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addVertex(V5); e12 = Graphs.addEdge(g, V1, V2, bias * 2); e13 = Graphs.addEdge(g, V1, V3, bias * 3); e24 = Graphs.addEdge(g, V2, V4, bias * 5); e34 = Graphs.addEdge(g, V3, V4, bias * 20); e45 = Graphs.addEdge(g, V4, V5, bias * 5); e15 = Graphs.addEdge(g, V1, V5, bias * 100); return g; } } // End ShortestPathTestCase.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/VertexCoversTest.java0000644000175000017500000001100611706124627024215 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------- * VertexCoversTest.java * --------------------- * (C) Copyright 2003-2008, by Linda Buisman and Contributors. * * Original Author: Linda Buisman * Contributor(s): Barak Naveh * * $Id: VertexCoversTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Nov-2003 : Initial revision (LB); * 10-Nov-2003 : Adapted to VertexCovers (BN); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests the vertex cover algorithms. * * @author Linda Buisman * @since Nov 6, 2003 */ public class VertexCoversTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final int TEST_GRAPH_SIZE = 200; private static final int TEST_REPEATS = 20; //~ Methods ---------------------------------------------------------------- /** * . */ public void testFind2ApproximationCover() { for (int i = 0; i < TEST_REPEATS; i++) { Graph g = createRandomGraph(); assertTrue( isCover(VertexCovers.find2ApproximationCover(g), g)); } } /** * . */ public void testFindGreedyCover() { for (int i = 0; i < TEST_REPEATS; i++) { Graph g = createRandomGraph(); Set c = VertexCovers.findGreedyCover( Graphs.undirectedGraph(g)); assertTrue(isCover(c, g)); } } /** * Checks if the specified vertex set covers every edge of the graph. Uses * the definition of Vertex Cover - removes every edge that is incident on a * vertex in vertexSet. If no edges are left, vertexSet is a vertex cover * for the specified graph. * * @param vertexSet the vertices to be tested for covering the graph. * @param g the graph to be covered. * * @return */ private boolean isCover( Set vertexSet, Graph g) { Set uncoveredEdges = new HashSet(g.edgeSet()); for (Iterator i = vertexSet.iterator(); i.hasNext();) { uncoveredEdges.removeAll(g.edgesOf(i.next())); } return uncoveredEdges.size() == 0; } /** * Create a random graph of TEST_GRAPH_SIZE nodes. * * @return */ private Graph createRandomGraph() { // TODO: move random graph generator to be under GraphGenerator // framework. Pseudograph g = new Pseudograph(DefaultEdge.class); for (int i = 0; i < TEST_GRAPH_SIZE; i++) { g.addVertex(new Integer(i)); } List vertices = new ArrayList(g.vertexSet()); // join every vertex with a random number of other vertices for (int source = 0; source < TEST_GRAPH_SIZE; source++) { int numEdgesToCreate = ((int) Math.random() * TEST_GRAPH_SIZE / 2) + 1; for (int j = 0; j < numEdgesToCreate; j++) { // find a random vertex to join to int target = (int) Math.floor(Math.random() * TEST_GRAPH_SIZE); g.addEdge(vertices.get(source), vertices.get(target)); } } return g; } } // End VertexCoversTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KShortestPathCostTest.java0000644000175000017500000002504611706124626025162 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPathCostTest.java * ------------------------- * (C) Copyright 2007-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KShortestPathCostTest.java 742 2011-03-12 23:06:31Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 06-Dec-2010 : Bugfixes (GB); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class KShortestPathCostTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testKShortestPathCompleteGraph4() { int nbPaths = 5; KShortestPathCompleteGraph4 graph = new KShortestPathCompleteGraph4(); KShortestPaths pathFinder = new KShortestPaths(graph, "vS", nbPaths); List pathElements = pathFinder.getPaths("v3"); assertEquals( "[[(vS : v1), (v1 : v3)], [(vS : v2), (v2 : v3)]," + " [(vS : v2), (v1 : v2), (v1 : v3)], " + "[(vS : v1), (v1 : v2), (v2 : v3)], " + "[(vS : v3)]]", pathElements.toString()); assertEquals(5, pathElements.size(), 0); GraphPath pathElement = (GraphPath) pathElements.get(0); assertEquals(2, pathElement.getWeight(), 0); assertEquals( Arrays.asList(new Object[] { graph.eS1, graph.e13 }), pathElement.getEdgeList()); } public void testPicture1Graph() { Picture1Graph picture1Graph = new Picture1Graph(); int maxSize = 10; KShortestPaths pathFinder = new KShortestPaths(picture1Graph, "vS", maxSize); // assertEquals(2, pathFinder.getPaths("v5").size()); List pathElements = pathFinder.getPaths("v5"); GraphPath pathElement = (GraphPath) pathElements.get(0); assertEquals( Arrays.asList( new Object[] { picture1Graph.eS1, picture1Graph.e15 }), pathElement.getEdgeList()); List vertices = Graphs.getPathVertexList(pathElement); assertEquals( Arrays.asList(new Object[] { "vS", "v1", "v5" }), vertices); pathElement = (GraphPath) pathElements.get(1); assertEquals( Arrays.asList( new Object[] { picture1Graph.eS2, picture1Graph.e25 }), pathElement.getEdgeList()); vertices = Graphs.getPathVertexList(pathElement); assertEquals( Arrays.asList(new Object[] { "vS", "v2", "v5" }), vertices); pathElements = pathFinder.getPaths("v7"); pathElement = (GraphPath) pathElements.get(0); double lastCost = pathElement.getWeight(); for (int i = 0; i < pathElements.size(); i++) { pathElement = (GraphPath) pathElements.get(i); double cost = pathElement.getWeight(); assertTrue(lastCost <= cost); lastCost = cost; } } public void testShortestPathsInIncreasingOrder() { BiconnectedGraph biconnectedGraph = new BiconnectedGraph(); verifyShortestPathsInIncreasingOrderOfWeight(biconnectedGraph); KShortestPathCompleteGraph4 kSPCompleteGraph4 = new KShortestPathCompleteGraph4(); verifyShortestPathsInIncreasingOrderOfWeight(kSPCompleteGraph4); KShortestPathCompleteGraph5 kSPCompleteGraph5 = new KShortestPathCompleteGraph5(); verifyShortestPathsInIncreasingOrderOfWeight(kSPCompleteGraph5); KShortestPathCompleteGraph6 kSPCompleteGraph6 = new KShortestPathCompleteGraph6(); verifyShortestPathsInIncreasingOrderOfWeight(kSPCompleteGraph6); KSPExampleGraph kSPExampleGraph = new KSPExampleGraph(); verifyShortestPathsInIncreasingOrderOfWeight(kSPExampleGraph); NotBiconnectedGraph notBiconnectedGraph = new NotBiconnectedGraph(); verifyShortestPathsInIncreasingOrderOfWeight(notBiconnectedGraph); Picture1Graph picture1Graph = new Picture1Graph(); verifyShortestPathsInIncreasingOrderOfWeight(picture1Graph); } public void testShortestPathsWeightsWithMaxSizeIncreases() { BiconnectedGraph biconnectedGraph = new BiconnectedGraph(); verifyShortestPathsWeightsWithMaxSizeIncreases(biconnectedGraph); KShortestPathCompleteGraph4 kSPCompleteGraph4 = new KShortestPathCompleteGraph4(); verifyShortestPathsWeightsWithMaxSizeIncreases(kSPCompleteGraph4); KShortestPathCompleteGraph5 kSPCompleteGraph5 = new KShortestPathCompleteGraph5(); verifyShortestPathsWeightsWithMaxSizeIncreases(kSPCompleteGraph5); KShortestPathCompleteGraph6 kSPCompleteGraph6 = new KShortestPathCompleteGraph6(); verifyShortestPathsWeightsWithMaxSizeIncreases(kSPCompleteGraph6); KSPExampleGraph kSPExampleGraph = new KSPExampleGraph(); verifyShortestPathsWeightsWithMaxSizeIncreases(kSPExampleGraph); NotBiconnectedGraph notBiconnectedGraph = new NotBiconnectedGraph(); verifyShortestPathsWeightsWithMaxSizeIncreases(notBiconnectedGraph); Picture1Graph picture1Graph = new Picture1Graph(); verifyShortestPathsWeightsWithMaxSizeIncreases(picture1Graph); } private void verifyShortestPathsInIncreasingOrderOfWeight(Graph graph) { int maxSize = 20; for ( Iterator sourceIterator = graph.vertexSet().iterator(); sourceIterator.hasNext();) { Object sourceVertex = sourceIterator.next(); for ( Iterator targetIterator = graph.vertexSet().iterator(); targetIterator.hasNext();) { Object targetVertex = targetIterator.next(); if (targetVertex != sourceVertex) { KShortestPaths pathFinder = new KShortestPaths(graph, sourceVertex, maxSize); List pathElements = pathFinder.getPaths(targetVertex); if (pathElements == null) { // no path exists between the start vertex and the end // vertex continue; } GraphPath pathElement = (GraphPath) pathElements.get(0); double lastWeight = pathElement.getWeight(); for (int i = 0; i < pathElements.size(); i++) { pathElement = (GraphPath) pathElements.get(i); double weight = pathElement.getWeight(); assertTrue(lastWeight <= weight); lastWeight = weight; } assertTrue(pathElements.size() <= maxSize); } } } } private void verifyShortestPathsWeightsWithMaxSizeIncreases(Graph graph) { int maxSizeLimit = 10; for ( Iterator sourceIterator = graph.vertexSet().iterator(); sourceIterator.hasNext();) { Object sourceVertex = sourceIterator.next(); for ( Iterator targetIterator = graph.vertexSet().iterator(); targetIterator.hasNext();) { Object targetVertex = targetIterator.next(); if (targetVertex != sourceVertex) { KShortestPaths pathFinder = new KShortestPaths(graph, sourceVertex, 1); List prevPathElementsResults = pathFinder.getPaths(targetVertex); if (prevPathElementsResults == null) { // no path exists between the start vertex and the // end vertex continue; } for (int maxSize = 2; maxSize < maxSizeLimit; maxSize++) { pathFinder = new KShortestPaths(graph, sourceVertex, maxSize); List pathElementsResults = pathFinder.getPaths(targetVertex); verifyWeightsConsistency( prevPathElementsResults, pathElementsResults); } } } } } /** * Verify weights consistency between the results when the max-size argument * increases. * * @param prevPathElementsResults results obtained with a max-size argument * equal to k * @param pathElementsResults results obtained with a max-size argument * equal to k+1 */ private void verifyWeightsConsistency( List prevPathElementsResults, List pathElementsResults) { for (int i = 0; i < prevPathElementsResults.size(); i++) { GraphPath pathElementResult = (GraphPath) pathElementsResults.get(i); GraphPath prevPathElementResult = (GraphPath) prevPathElementsResults.get(i); assertTrue( pathElementResult.getWeight() == prevPathElementResult.getWeight()); } } } // End KShortestPathCostTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/DijkstraShortestPathTest.java0000644000175000017500000000564011706124626025710 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * DijkstraShortestPathTest.java * ------------------------------ * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: DijkstraShortestPathTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 03-Sept-2003 : Initial revision (JVS); * 14-Jan-2006 : Factored out ShortestPathTestCase (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi */ public class DijkstraShortestPathTest extends ShortestPathTestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testConstructor() { DijkstraShortestPath path; Graph g = create(); path = new DijkstraShortestPath( g, V3, V4, Double.POSITIVE_INFINITY); assertEquals( Arrays.asList( new DefaultEdge[] { e13, e12, e24 }), path.getPathEdgeList()); assertEquals(10.0, path.getPathLength(), 0); path = new DijkstraShortestPath( g, V3, V4, 7); assertNull(path.getPathEdgeList()); assertEquals(Double.POSITIVE_INFINITY, path.getPathLength(), 0); } protected List findPathBetween( Graph g, String src, String dest) { return DijkstraShortestPath.findPathBetween(g, src, dest); } } // End DijkstraShortestPathTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KShortestPathCompleteGraph4.java0000644000175000017500000000575611706124626026236 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPathCompleteGraph4.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KShortestPathCompleteGraph4.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class KShortestPathCompleteGraph4 extends SimpleWeightedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = -4091707260999013100L; //~ Instance fields -------------------------------------------------------- public Object e12; public Object e13; public Object e23; public Object eS1; public Object eS2; public Object eS3; //~ Constructors ----------------------------------------------------------- public KShortestPathCompleteGraph4() { super(DefaultWeightedEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { this.eS1 = addEdge("vS", "v1"); this.eS2 = addEdge("vS", "v2"); this.eS3 = addEdge("vS", "v3"); this.e12 = addEdge("v1", "v2"); this.e13 = addEdge("v1", "v3"); this.e23 = addEdge("v2", "v3"); setEdgeWeight(this.eS1, 1.0); setEdgeWeight(this.eS2, 1.0); setEdgeWeight(this.eS3, 1000.0); setEdgeWeight(this.e12, 1.0); setEdgeWeight(this.e13, 1.0); setEdgeWeight(this.e23, 1.0); } private void addVertices() { addVertex("vS"); addVertex("v1"); addVertex("v2"); addVertex("v3"); } } // End KShortestPathCompleteGraph4.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/TransitiveClosureTest.java0000644000175000017500000000733111706124627025251 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * TransitiveClosureTest.java * ------------------------------ * (C) Copyright 2007, by Vinayak R. Borkar. * * Original Author: Vinayak R. Borkar * Contributor(s): * * Changes * ------- * 5-May-2007: Initial revision (VRB); * */ package org.jgrapht.alg; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** */ public class TransitiveClosureTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testLinearGraph() { SimpleDirectedGraph graph = new SimpleDirectedGraph(DefaultEdge.class); int N = 10; LinearGraphGenerator gen = new LinearGraphGenerator(N); VertexFactory vf = new VertexFactory() { private int m_index = 0; public Integer createVertex() { return Integer.valueOf(m_index++); } }; gen.generateGraph(graph, vf, null); TransitiveClosure.INSTANCE.closeSimpleDirectedGraph(graph); assertEquals(true, graph.edgeSet().size() == ((N * (N - 1)) / 2)); for (int i = 0; i < N; ++i) { for (int j = i + 1; j < N; ++j) { assertEquals( true, graph.getEdge(Integer.valueOf(i), Integer.valueOf(j)) != null); } } } public void testRingGraph() { SimpleDirectedGraph graph = new SimpleDirectedGraph(DefaultEdge.class); int N = 10; RingGraphGenerator gen = new RingGraphGenerator(N); VertexFactory vf = new VertexFactory() { private int m_index = 0; public Integer createVertex() { return Integer.valueOf(m_index++); } }; gen.generateGraph(graph, vf, null); TransitiveClosure.INSTANCE.closeSimpleDirectedGraph(graph); assertEquals(true, graph.edgeSet().size() == (N * (N - 1))); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { assertEquals( true, (i == j) || (graph.getEdge(Integer.valueOf(i), Integer.valueOf(j)) != null)); } } } } // End TransitiveClosureTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/FloydWarshallShortestPathsTest.java0000644000175000017500000001277411706124626027101 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * FloydWarshallShortestPathsTest.java * ------------------------- * (C) Copyright 2009-2009, by Tom Larkworthy and Contributors * * Original Author: Tom Larkworthy * Contributors: Andrea Pagani * * $Id: FloydWarshallShortestPathsTest.java 715 2010-06-13 01:25:00Z perfecthash $ * * Changes * ------- * 29-Jun-2009 : Initial revision (TL); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * @author Tom Larkworthy * @version $Id: FloydWarshallShortestPathsTest.java 715 2010-06-13 01:25:00Z perfecthash $ */ public class FloydWarshallShortestPathsTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testCompareWithDijkstra() { RandomGraphGenerator gen = new RandomGraphGenerator( 10, 15); VertexFactory f = new VertexFactory() { int gid; public Integer createVertex() { return gid++; } }; for (int i = 0; i < 10; i++) { SimpleDirectedGraph directed = new SimpleDirectedGraph( DefaultWeightedEdge.class); gen.generateGraph(directed, f, new HashMap()); // setup our shortest path measurer FloydWarshallShortestPaths fw = new FloydWarshallShortestPaths( directed); for (Integer v1 : directed.vertexSet()) { for (Integer v2 : directed.vertexSet()) { double fwSp = fw.shortestDistance(v1, v2); double dijSp = new DijkstraShortestPath( directed, v1, v2).getPathLength(); assertTrue( (Math.abs(dijSp - fwSp) < .01) || (Double.isInfinite(fwSp) && Double.isInfinite(dijSp))); } } SimpleGraph undirected = new SimpleGraph( DefaultWeightedEdge.class); gen.generateGraph(undirected, f, new HashMap()); // setup our shortest path measurer fw = new FloydWarshallShortestPaths( undirected); for (Integer v1 : undirected.vertexSet()) { for (Integer v2 : undirected.vertexSet()) { double fwSp = fw.shortestDistance(v1, v2); double dijSp = new DijkstraShortestPath( undirected, v1, v2).getPathLength(); assertTrue( (Math.abs(dijSp - fwSp) < .01) || (Double.isInfinite(fwSp) && Double.isInfinite(dijSp))); } } } } private static UndirectedGraph createStringGraph() { UndirectedGraph g = new SimpleGraph(DefaultEdge.class); String v1 = "v1"; String v2 = "v2"; String v3 = "v3"; String v4 = "v4"; // add the vertices g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addVertex(v4); // add edges to create a circuit g.addEdge(v1, v2); g.addEdge(v2, v3); g.addEdge(v3, v1); g.addEdge(v3, v4); return g; } public void testDiameter() { UndirectedGraph stringGraph = createStringGraph(); FloydWarshallShortestPaths testFWPath = new FloydWarshallShortestPaths(stringGraph); double diameter = testFWPath.getDiameter(); assertEquals(2.0, diameter); } } // End FloydWarshallShortestPathsTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/BronKerboschCliqueFinderTest.java0000644000175000017500000001161111706124626026433 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * BronKerboschCliqueFinderTest.java * ------------------------------ * (C) Copyright 2005-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: BronKerboschCliqueFinderTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 26-July-2005 : Initial revision (JVS); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi */ public class BronKerboschCliqueFinderTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String V4 = "v4"; private static final String V5 = "v5"; private static final String V6 = "v6"; private static final String V7 = "v7"; private static final String V8 = "v8"; //~ Methods ---------------------------------------------------------------- /** * . * * @param g */ public void createGraph(Graph g) { g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addVertex(V5); g.addVertex(V6); g.addVertex(V7); g.addVertex(V8); // biggest clique: { V1, V2, V3, V4 } g.addEdge(V1, V2); g.addEdge(V1, V3); g.addEdge(V1, V4); g.addEdge(V2, V3); g.addEdge(V2, V4); g.addEdge(V3, V4); // smaller clique: { V5, V6, V7 } g.addEdge(V5, V6); g.addEdge(V5, V7); g.addEdge(V6, V7); // for fun, add an overlapping clique { V3, V4, V5 } g.addEdge(V3, V5); g.addEdge(V4, V5); // make V8 less lonely g.addEdge(V7, V8); } public void testFindBiggest() { SimpleGraph g = new SimpleGraph(DefaultEdge.class); createGraph(g); BronKerboschCliqueFinder finder = new BronKerboschCliqueFinder(g); Collection> cliques = finder.getBiggestMaximalCliques(); assertEquals(1, cliques.size()); Set expected = new HashSet(); expected.add(V1); expected.add(V2); expected.add(V3); expected.add(V4); Set actual = cliques.iterator().next(); assertEquals(expected, actual); } public void testFindAll() { SimpleGraph g = new SimpleGraph(DefaultEdge.class); createGraph(g); BronKerboschCliqueFinder finder = new BronKerboschCliqueFinder(g); Collection> cliques = finder.getAllMaximalCliques(); assertEquals(4, cliques.size()); Set> expected = new HashSet>(); Set set = new HashSet(); set.add(V1); set.add(V2); set.add(V3); set.add(V4); expected.add(set); set = new HashSet(); set.add(V5); set.add(V6); set.add(V7); expected.add(set); set = new HashSet(); set.add(V3); set.add(V4); set.add(V5); expected.add(set); set = new HashSet(); set.add(V7); set.add(V8); expected.add(set); // convert result from Collection to Set because we don't want // order to be significant Set> actual = new HashSet>(cliques); assertEquals(expected, actual); } } // End BronKerboschCliqueFinderTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KShortestPathCompleteGraph5.java0000644000175000017500000000664011706124626026230 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPathCompleteGraph5.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KShortestPathCompleteGraph5.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class KShortestPathCompleteGraph5 extends SimpleWeightedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = -3289497257289559394L; //~ Instance fields -------------------------------------------------------- public Object e12; public Object e13; public Object e14; public Object e23; public Object e24; public Object e34; public Object eS1; public Object eS2; public Object eS3; public Object eS4; //~ Constructors ----------------------------------------------------------- public KShortestPathCompleteGraph5() { super(DefaultWeightedEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { this.eS1 = addEdge("vS", "v1"); this.eS2 = addEdge("vS", "v2"); this.eS3 = addEdge("vS", "v3"); this.eS4 = addEdge("vS", "v4"); this.e12 = addEdge("v1", "v2"); this.e13 = addEdge("v1", "v3"); this.e14 = addEdge("v1", "v4"); this.e23 = addEdge("v2", "v3"); this.e24 = addEdge("v2", "v4"); this.e34 = addEdge("v3", "v4"); setEdgeWeight(this.eS1, 1.0); setEdgeWeight(this.eS2, 1.0); setEdgeWeight(this.eS3, 1.0); setEdgeWeight(this.eS4, 1000.0); setEdgeWeight(this.e12, 1.0); setEdgeWeight(this.e13, 1.0); setEdgeWeight(this.e14, 1.0); setEdgeWeight(this.e23, 1.0); setEdgeWeight(this.e24, 1.0); setEdgeWeight(this.e34, 1.0); } private void addVertices() { addVertex("vS"); addVertex("v1"); addVertex("v2"); addVertex("v3"); addVertex("v4"); } } // End KShortestPathCompleteGraph5.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/StoerWagnerMinimumCutTest.java0000644000175000017500000000732411706124626026035 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2011, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * StoerWagnerMinimumCutTest.java * ---------------- * (C) Copyright 2011-2011, by Robby McKilliam and Contributors. * * Original Author: Robby McKilliam * Contributor(s): - * * $Id: StoerWagnerMinimumCut.java $ * * Changes * ------- * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.graph.*; /** * @author Robby McKilliam */ public class StoerWagnerMinimumCutTest extends TestCase { //~ Instance fields -------------------------------------------------------- private String v1 = "v1"; private String v2 = "v2"; private String v3 = "v3"; private String v4 = "v4"; //~ Constructors ----------------------------------------------------------- public StoerWagnerMinimumCutTest() { } //~ Methods ---------------------------------------------------------------- /** * Test of mergeVertices method, of class StoerWagnerMinimumCut. */ public void testMinCut14() { SimpleWeightedGraph g = new SimpleWeightedGraph( DefaultWeightedEdge.class); g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addVertex(v4); DefaultWeightedEdge e; e = g.addEdge(v1, v2); g.setEdgeWeight(e, 3.0); e = g.addEdge(v1, v3); g.setEdgeWeight(e, 2.0); e = g.addEdge(v1, v4); g.setEdgeWeight(e, 4.0); e = g.addEdge(v2, v3); g.setEdgeWeight(e, 1.0); e = g.addEdge(v3, v4); g.setEdgeWeight(e, 1.0); StoerWagnerMinimumCut mincut = new StoerWagnerMinimumCut(g); assertEquals(4.0, mincut.bestcutweight, 0.000001); } /** * Test of mergeVertices method, of class StoerWagnerMinimumCut. */ public void testMinCutDisconnected() { SimpleWeightedGraph g = new SimpleWeightedGraph( DefaultWeightedEdge.class); g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addVertex(v4); DefaultWeightedEdge e; e = g.addEdge(v1, v2); g.setEdgeWeight(e, 3.0); e = g.addEdge(v1, v3); g.setEdgeWeight(e, 2.0); e = g.addEdge(v2, v3); g.setEdgeWeight(e, 1.0); StoerWagnerMinimumCut mincut = new StoerWagnerMinimumCut(g); assertEquals(0.0, mincut.bestcutweight, 0.000001); } } // End StoerWagnerMinimumCutTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KruskalMinimumSpanningTreeTest.java0000644000175000017500000000672111706124626027053 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * KruskalMinimumSpanningTreeTest.java * ------------------------------ * (C) Copyright 2010-2010, by Tom Conerly and Contributors. * * Original Author: Tom Conerly * Contributor(s): - * * Changes * ------- * 02-Feb-2010 : Initial revision (TC); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; public class KruskalMinimumSpanningTreeTest extends TestCase { //~ Static fields/initializers --------------------------------------------- static final String V1 = "v1"; static final String V2 = "v2"; static final String V3 = "v3"; static final String V4 = "v4"; static final String V5 = "v5"; //~ Instance fields -------------------------------------------------------- DefaultWeightedEdge e12; DefaultWeightedEdge e13; DefaultWeightedEdge e15; DefaultWeightedEdge e24; DefaultWeightedEdge e34; DefaultWeightedEdge e45; //~ Methods ---------------------------------------------------------------- /** * . */ public void testMinimumSpanningTree() { Graph graph = createWeighted(); KruskalMinimumSpanningTree mst = new KruskalMinimumSpanningTree(graph); assertEquals(15.0, mst.getSpanningTreeCost()); Set edges = mst.getEdgeSet(); for (DefaultWeightedEdge edge : edges) { assertTrue( edge.equals(e12) || edge.equals(e13) || edge.equals(e24) || edge.equals(e45)); } } protected Graph createWeighted() { Graph g; double bias = 1; g = new SimpleWeightedGraph( DefaultWeightedEdge.class); g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addVertex(V5); e12 = Graphs.addEdge(g, V1, V2, bias * 2); e13 = Graphs.addEdge(g, V1, V3, bias * 3); e24 = Graphs.addEdge(g, V2, V4, bias * 5); e34 = Graphs.addEdge(g, V3, V4, bias * 20); e45 = Graphs.addEdge(g, V4, V5, bias * 5); e15 = Graphs.addEdge(g, V1, V5, bias * 100); return g; } } // End KruskalMinimumSpanningTreeTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/CycleDetectorTest.java0000644000175000017500000001545711706124626024324 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * CycleDetectorTest.java * ------------------------------ * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Khanh Vu * * $Id: CycleDetectorTest.java 745 2011-06-07 05:50:57Z perfecthash $ * * Changes * ------- * 16-Sept-2004 : Initial revision (JVS); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi */ public class CycleDetectorTest extends TestCase { //~ Static fields/initializers --------------------------------------------- private static final String V1 = "v1"; private static final String V2 = "v2"; private static final String V3 = "v3"; private static final String V4 = "v4"; private static final String V5 = "v5"; private static final String V6 = "v6"; private static final String V7 = "v7"; //~ Methods ---------------------------------------------------------------- /** * . * * @param g */ public void createGraph(Graph g) { g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addVertex(V5); g.addVertex(V6); g.addVertex(V7); g.addEdge(V1, V2); g.addEdge(V2, V3); g.addEdge(V3, V4); g.addEdge(V4, V1); g.addEdge(V4, V5); g.addEdge(V5, V6); g.addEdge(V1, V6); // test an edge which leads into a cycle, but where the source // is not itself part of a cycle g.addEdge(V7, V1); } /** * . */ public void testDirectedWithCycle() { DirectedGraph g = new DefaultDirectedGraph( DefaultEdge.class); createGraph(g); Set cyclicSet = new HashSet(); cyclicSet.add(V1); cyclicSet.add(V2); cyclicSet.add(V3); cyclicSet.add(V4); Set acyclicSet = new HashSet(); acyclicSet.add(V5); acyclicSet.add(V6); acyclicSet.add(V7); runTest(g, cyclicSet, acyclicSet); } /** * . */ public void testDirectedWithDoubledCycle() { DirectedGraph g = new DefaultDirectedGraph( DefaultEdge.class); // build the graph: vertex order is chosen specifically // to exercise old bug-cases in CycleDetector g.addVertex(V2); g.addVertex(V1); g.addVertex(V3); g.addEdge(V1, V2); g.addEdge(V2, V3); g.addEdge(V3, V1); g.addEdge(V2, V1); Set cyclicSet = new HashSet(); cyclicSet.add(V1); cyclicSet.add(V2); cyclicSet.add(V3); Set acyclicSet = new HashSet(); runTest(g, cyclicSet, acyclicSet); } /** * . */ @SuppressWarnings("unchecked") public void testDirectedWithoutCycle() { DirectedGraph g = new DefaultDirectedGraph( DefaultEdge.class); createGraph(g); g.removeVertex(V2); Set cyclicSet = Collections.EMPTY_SET; // hb: I would like // EMPTY_SET to be typed // as well... Set acyclicSet = g.vertexSet(); runTest(g, cyclicSet, acyclicSet); } private void runTest( DirectedGraph g, Set cyclicSet, Set acyclicSet) { CycleDetector detector = new CycleDetector(g); Set emptySet = Collections.EMPTY_SET; assertEquals(!cyclicSet.isEmpty(), detector.detectCycles()); assertEquals(cyclicSet, detector.findCycles()); for (String v : cyclicSet) { assertEquals(true, detector.detectCyclesContainingVertex(v)); assertEquals(cyclicSet, detector.findCyclesContainingVertex(v)); } for (String v : acyclicSet) { assertEquals(false, detector.detectCyclesContainingVertex(v)); assertEquals(emptySet, detector.findCyclesContainingVertex(v)); } } public void testVertexEquals() { DefaultDirectedGraph graph = new DefaultDirectedGraph(DefaultEdge.class); assertEquals(0, graph.edgeSet().size()); String vertexA = "A"; String vertexB = "B"; String vertexC = new StringBuffer("A").toString(); assertNotSame(vertexA, vertexC); graph.addVertex(vertexA); graph.addVertex(vertexB); graph.addEdge(vertexA, vertexB); graph.addEdge(vertexB, vertexC); assertEquals(2, graph.edgeSet().size()); assertEquals(2, graph.vertexSet().size()); CycleDetector cycleDetector = new CycleDetector(graph); Set cycleVertices = cycleDetector.findCycles(); boolean foundCycle = cycleDetector.detectCyclesContainingVertex(vertexA); boolean foundVertex = graph.containsVertex(vertexA); Set subCycle = cycleDetector.findCyclesContainingVertex(vertexA); assertEquals(2, cycleVertices.size()); assertEquals(2, subCycle.size()); // fails with zero items assertTrue(foundCycle); // fails with no cycle found which includes // vertexA assertTrue(foundVertex); } } // End CycleDetectorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/EdmondsKarpMaximumFlowTest.java0000644000175000017500000002211511706124626026155 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EdmondsKarpMaximumFlowTest.java * ----------------- * (C) Copyright 2008-2008, by Ilya Razenshteyn and Contributors. * * Original Author: Ilya Razenshteyn * Contributor(s): - * * $Id: EdmondsKarpMaximumFlowTest.java 628 2008-08-17 12:00:59Z ilyaraz $ * * Changes * ------- */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.graph.*; public final class EdmondsKarpMaximumFlowTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testCornerCases() { DirectedWeightedMultigraph simple = new DirectedWeightedMultigraph( DefaultWeightedEdge.class); simple.addVertex(0); simple.addVertex(1); DefaultWeightedEdge e = simple.addEdge(0, 1); try { new EdmondsKarpMaximumFlow(null); fail(); } catch (NullPointerException ex) { } try { new EdmondsKarpMaximumFlow( simple, -0.1); fail(); } catch (IllegalArgumentException ex) { } try { simple.setEdgeWeight(e, -1.0); new EdmondsKarpMaximumFlow(simple); fail(); } catch (IllegalArgumentException ex) { } try { simple.setEdgeWeight(e, 1.0); EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow( simple); solver.calculateMaximumFlow(0, 1); Map flow = solver.getMaximumFlow(); flow.put(e, 25.0); fail(); } catch (UnsupportedOperationException ex) { } try { EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow( simple); solver.calculateMaximumFlow(2, 0); fail(); } catch (IllegalArgumentException ex) { } try { EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow( simple); solver.calculateMaximumFlow(1, 2); fail(); } catch (IllegalArgumentException ex) { } try { EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow( simple); solver.calculateMaximumFlow(0, 0); fail(); } catch (IllegalArgumentException ex) { } try { EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow( simple); solver.calculateMaximumFlow(null, 0); fail(); } catch (IllegalArgumentException ex) { } try { EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow( simple); solver.calculateMaximumFlow(0, null); fail(); } catch (IllegalArgumentException ex) { } } /** * . */ public void testLogic() { runTest( new int[] {}, new int[] {}, new double[] {}, new int[] { 1 }, new int[] { 4057218 }, new double[] { 0.0 }); runTest( new int[] { 3, 1, 4, 3, 2, 8, 2, 5, 7 }, new int[] { 1, 4, 8, 2, 8, 6, 5, 7, 6 }, new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 }, new int[] { 3 }, new int[] { 6 }, new double[] { 2 }); runTest( new int[] { 5, 5, 5, 1, 1, 4, 2, 7, 8, 3 }, new int[] { 1, 4, 2, 7, 8, 3, 8, 6, 6, 6 }, new double[] { 7, 8, 573146, 31337, 1, 1, 1, 1, 2391717, 170239 }, new int[] { 5 }, new int[] { 6 }, new double[] { 4.0 }); runTest( new int[] { 1, 1, 2, 2, 3 }, new int[] { 2, 3, 3, 4, 4 }, new double[] { 1000000000.0, 1000000000.0, 1.0, 1000000000.0, 1000000000.0 }, new int[] { 1 }, new int[] { 4 }, new double[] { 2000000000.0 }); } private void runTest( int [] tails, int [] heads, double [] capacities, int [] sources, int [] sinks, double [] expectedResults) { assertTrue(tails.length == heads.length); assertTrue(tails.length == capacities.length); DirectedWeightedMultigraph network = new DirectedWeightedMultigraph( DefaultWeightedEdge.class); int m = tails.length; for (int i = 0; i < m; i++) { network.addVertex(tails[i]); network.addVertex(heads[i]); DefaultWeightedEdge e = network.addEdge(tails[i], heads[i]); network.setEdgeWeight(e, capacities[i]); } assertTrue(sources.length == sinks.length); int q = sources.length; for (int i = 0; i < q; i++) { network.addVertex(sources[i]); network.addVertex(sinks[i]); } EdmondsKarpMaximumFlow solver = new EdmondsKarpMaximumFlow(network); assertTrue(solver.getCurrentSource() == null); assertTrue(solver.getCurrentSink() == null); assertTrue(solver.getMaximumFlowValue() == null); assertTrue(solver.getMaximumFlow() == null); for (int i = 0; i < q; i++) { solver.calculateMaximumFlow(sources[i], sinks[i]); assertTrue(solver.getCurrentSource().equals(sources[i])); assertTrue(solver.getCurrentSink().equals(sinks[i])); double flowValue = solver.getMaximumFlowValue(); Map flow = solver.getMaximumFlow(); assertEquals( expectedResults[i], flowValue, EdmondsKarpMaximumFlow.DEFAULT_EPSILON); for (DefaultWeightedEdge e : network.edgeSet()) { assertTrue(flow.containsKey(e)); } for (DefaultWeightedEdge e : flow.keySet()) { assertTrue(network.containsEdge(e)); assertTrue( flow.get(e) >= -EdmondsKarpMaximumFlow.DEFAULT_EPSILON); assertTrue( flow.get(e) <= (network.getEdgeWeight(e) + EdmondsKarpMaximumFlow.DEFAULT_EPSILON)); } for (Integer v : network.vertexSet()) { double balance = 0.0; for (DefaultWeightedEdge e : network.outgoingEdgesOf(v)) { balance -= flow.get(e); } for (DefaultWeightedEdge e : network.incomingEdgesOf(v)) { balance += flow.get(e); } if (v.equals(sources[i])) { assertEquals( -flowValue, balance, EdmondsKarpMaximumFlow.DEFAULT_EPSILON); } else if (v.equals(sinks[i])) { assertEquals( flowValue, balance, EdmondsKarpMaximumFlow.DEFAULT_EPSILON); } else { assertEquals( 0.0, balance, EdmondsKarpMaximumFlow.DEFAULT_EPSILON); } } } } } // End EdmondsKarpMaximumFlowTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KSPExampleTest.java0000644000175000017500000000524011706124626023531 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KSPExampleTest.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KSPExampleTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 23-Sep-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import junit.framework.*; import org.jgrapht.graph.*; @SuppressWarnings("unchecked") public class KSPExampleTest extends TestCase { //~ Methods ---------------------------------------------------------------- public void testFourReturnedPathsJGraphT() { SimpleWeightedGraph graph = new KSPExampleGraph(); Object sourceVertex = "S"; KShortestPaths ksp = new KShortestPaths(graph, sourceVertex, 4); Object targetVertex = "T"; assertEquals(3, ksp.getPaths(targetVertex).size()); } public void testThreeReturnedPathsJGraphT() { SimpleWeightedGraph graph = new KSPExampleGraph(); Object sourceVertex = "S"; int nbPaths = 3; KShortestPaths ksp = new KShortestPaths(graph, sourceVertex, nbPaths); Object targetVertex = "T"; assertEquals(nbPaths, ksp.getPaths(targetVertex).size()); } public void testTwoReturnedPathsJGraphT() { SimpleWeightedGraph graph = new KSPExampleGraph(); Object sourceVertex = "S"; int nbPaths = 2; KShortestPaths ksp = new KShortestPaths(graph, sourceVertex, nbPaths); Object targetVertex = "T"; assertEquals(nbPaths, ksp.getPaths(targetVertex).size()); } } // End $file.name$ jgrapht-0.8.3/testsrc/org/jgrapht/alg/BiconnectedGraph.java0000644000175000017500000000467311706124626024130 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BiconnectedGraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: BiconnectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class BiconnectedGraph extends SimpleGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 6007460525580983710L; //~ Constructors ----------------------------------------------------------- public BiconnectedGraph() { super(DefaultEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { addEdge("0", "1"); addEdge("1", "2"); addEdge("2", "3"); addEdge("3", "4"); addEdge("4", "5"); addEdge("5", "0"); } private void addVertices() { addVertex("0"); addVertex("1"); addVertex("2"); addVertex("3"); addVertex("4"); addVertex("5"); } } // End BiconnectedGraph.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/BellmanFordShortestPathTest.java0000644000175000017500000000740711706124626026325 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * BellmanFordShortestPathTest.java * ------------------------------ * (C) Copyright 2006-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: BellmanFordShortestPathTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 14-Jan-2006 : Initial revision (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author John V. Sichi */ public class BellmanFordShortestPathTest extends ShortestPathTestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testConstructor() { BellmanFordShortestPath path; Graph g = create(); path = new BellmanFordShortestPath(g, V3); // find best path with no constraint on number of hops assertEquals( Arrays.asList( new DefaultEdge[] { e13, e12, e24, e45 }), path.getPathEdgeList(V5)); assertEquals(15.0, path.getCost(V5), 0); // find best path within 2 hops (less than optimal) path = new BellmanFordShortestPath( g, V3, 2); assertEquals( Arrays.asList( new DefaultEdge[] { e34, e45 }), path.getPathEdgeList(V5)); assertEquals(25.0, path.getCost(V5), 0); // find best path within 1 hop (doesn't exist!) path = new BellmanFordShortestPath( g, V3, 1); assertNull(path.getPathEdgeList(V5)); assertEquals(Double.POSITIVE_INFINITY, path.getCost(V5)); } protected List findPathBetween( Graph g, String src, String dest) { return BellmanFordShortestPath.findPathBetween(g, src, dest); } public void testWithNegativeEdges() { Graph g = createWithBias(true); List path; path = findPathBetween(g, V1, V4); assertEquals(Arrays.asList( new DefaultEdge[] { e13, e34 }), path); path = findPathBetween(g, V1, V5); assertEquals(Arrays.asList(new DefaultEdge[] { e15 }), path); } } // End BellmanFordShortestPathTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KSPExampleGraph.java0000644000175000017500000000645711706124626023666 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KSPExampleGraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KSPExampleGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 23-Sep-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * */ @SuppressWarnings("unchecked") public class KSPExampleGraph extends SimpleWeightedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = -1850978181764235655L; //~ Instance fields -------------------------------------------------------- public Object edgeAD; public Object edgeBT; public Object edgeCB; public Object edgeCT; public Object edgeDE; public Object edgeEC; public Object edgeSA; public Object edgeST; //~ Constructors ----------------------------------------------------------- /** * */ public KSPExampleGraph() { super(DefaultWeightedEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { this.edgeST = this.addEdge("S", "T"); this.edgeSA = this.addEdge("S", "A"); this.edgeAD = this.addEdge("A", "D"); this.edgeDE = this.addEdge("D", "E"); this.edgeEC = this.addEdge("E", "C"); this.edgeCB = this.addEdge("C", "B"); this.edgeCT = this.addEdge("C", "T"); this.edgeBT = this.addEdge("B", "T"); setEdgeWeight(this.edgeST, 1); setEdgeWeight(this.edgeSA, 100); setEdgeWeight(this.edgeAD, 1); setEdgeWeight(this.edgeDE, 1); setEdgeWeight(this.edgeEC, 1); setEdgeWeight(this.edgeCB, 1); setEdgeWeight(this.edgeCT, 1); setEdgeWeight(this.edgeBT, 1); } private void addVertices() { addVertex("S"); addVertex("T"); addVertex("A"); addVertex("B"); addVertex("C"); addVertex("D"); addVertex("E"); } } // End KSPExampleGraph.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KSPExample.png0000644000175000017500000005115011706124626022535 0ustar giovannigiovanni�PNG  IHDR�U Jb pHYsKJ�k{.$IDATx���P�×�qP�޸41vv�� L���e�d�#H��.PeE�3�ժECèµ±�Ш ����0E���+8:�S��"�2L����D����NoCD~�{��<���#� � ��{>�{������Ԕ4`���74gBs�!4gBs�!4gBs�!4gBs�!4gBs�!4gBs�!4g��O������� �������)�Up�W�Ã͙�����σ�l6����p<�h�&��Мh���Мh���Мh���Мh���8��{��?���33�_�~��c��ŋ=<��rrrr^�d�OOÕ•pu�?�__�p&���۷o�~�v����������}�o|����F������������~�����͛7��oÞ¼y�ʕ�{����/~ñ‹ššï¿½ï¿½ï¿½ï¿½ï¿½|�^������v�ؗ����z�g�y��7߬���<|���uuuu�������?��o���޾m�?qjjj�!�+�%��A����/���S����.�i�����������>�5؇�392�7���o�w�޽�qi�Μ9s�ȑ�����h�5؇������Ç��׿���������V�\�rÉ’7nܰZ�z뭷��?U�`��_%{8�u�� Éž3����:X9p4g�����������Z��� .mddddd$>>>>>������_uEWGs�f6��fszzzzz��Zps�9���v�ڵk×¶oß¾}�vյ��Fs�����㣺 ��� @Ch�4�� @C~C��/p>8q�5��X����p��ٔ"k×®]�vmYYYYY��>��o �����DZ�篪����JHHHHH�y�ÆškÖ¬Y�fMccccc��Z`��lÙ²e˖�����������J�p�8� �#�޽{��ݥK�.]�Tu]\���������������ؖ������˗/_�\�W�Q �r������)A@MMMMM��`��-[�l�2��b�XrsssssUW�� ؜�W^y�W^immmmmU] ,Trrrrr��M� �cM166666������{�Î;w�xyyyyy�� �k��������pDDDDD��j�Z�D���v�L���\�r�ʕ �+��������������'��ʰ͙HJJJJJbr��deeeee=x�����������+`O��5�&�w��D������á����D��1|�L�M��$�`$q�gjjjjj����� �B�96lذa�&㑈�d2�L������r�X(�ǚbrrrrrR�͞�����M��;[d����������/�X9�ה�������+{�V��0�h���͛7o�|�ܹs�Ω��/'''''G�"N@�\"�������������nr�&GsN�iK��)N"N@�\h�L^MJ���&���8 �8=r��Llݺu�֭���-#####��������5������D`````��7nܸ!g�� �19?ִ������M� �˭�yzzzzzÊ�/^�x���Q�������������8�p��L0� �u������qz�r���;7�������޽{��]YQS]�QkÚ’)N9���8-sÑ•39D#.....��M�@�8������8-s��L$%%%%%�?����kg��j�-#��I���Nn~��|��&��N�i��.�������������upss�3i�V�^�z�j�M�Cv�|��a�pss�XSH�)��nr�&{�f�i������/*****�j�Z�V9Mu]��b��p��M�) `��ݻw�޶mÛ¶m�TW�:��/���k���Zkkkkk��Z����ٳg���d2��8�4���L������>>>>>>CCCCCC�R]}�~�i�v���P���/H+F� ���''����Y�fÍš5kU�j�۷oß¾}���ѣG�U]�Zt������K_��-�8CCCCCC�������8�`���n����b�X,9���8�9� �� d�Sڲ�����R�Ƨ��vG#�`/�5m�A��wq�������� 0&Vξ�&ؒ�j%�������&����7�VNNNNN���'�8�_lw�p�Î;w����Mse�X����������������'`_��=�&L�lÙ²e˖������������q�Es�n�����֪��"+++++K��Ç?~\uE�qj��7,��bM[q���)���ô•³ï¿½ ��G��3?????_��$���lV7�Qd�S^�rP-�p�]l�/�M�c�XӖ��)���)@�� �V�f�pf&�XaaaaaaJJJJJ '0?4gs@� 3�����È��8��q��v{!�0W�kڒ�8������;;;;;;�8��c�l$܌�����$��G���333333SuE���YRRRRR�&�L���9��=�[l_������1??????�M3s�XÓ–Lq������߸q�ÆD���X9�3i�7`6l�8�.N�ZGs6O��0{D����b�Bn� bM[�wq�������� �V���6ܬ�����Q]h��ř�������������"@�h�d������������>���۷o�~�����'�x�'�x��_|��+W�\�re~ @;f�0�����������ӧO�V]�-4g �v�ڵk�vwwwww�r��������H||||||��>������Hg�~�駟~�iÓ¦M�6Mß·1�����e�N�:u�TAAAAA�Lt�� ÐŒ),�ܹYVVVVV6��%����3/���o}�[���O>��y�G}��G}�������=���3�t��9`T%%%%%%+W�\�r�g�}��g���P�m�v ��gΜ9s�lq����ˠf�2�dÉ’%K�ܿ����3�� �9f���s���r������D�(��������.@%�{8�Ln������������ȫ����Ê�U�U&��\?�s̾�r��L �Nq�P���`Ï™��,�777777���?��O>����˾��}$h������w~~~~~�Lqʊ��5h���q��~����7�)�\òž‰‰ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½s��H�ÛƒjÏž={��Y�j��B&7g�bÅŠ+V�8q�ĉ�cÇŽ;v,*****j~ �TQQQQQ!S�w��p:� F3��͙�×®]�v�Lb.^�x��Å������nݺu���>�s��I�3ٖ�8 ������UW|Í™bLn���Nqr'���v�8�06bM-#�6�r��?/^�x���U�F�۶mÛ¶m��77�3�`rT���d2�L&"Nh��`;�y��ݻw�zyyyyy�� �Bk��A�mmmmmmAAAAAA��+b�Ll'7kjjjjjTW�e�A��� Uh�4��MPK"N������J���خ!������~~~~~~w�ܹs��&�wÄšz$[M$�d���ʙ�H+�z��իW744444��\�l5�X,��)N8͙�lذaÆ �ϟ?���Z�ueeeeeeMNNNNN2� gb�]s������|}}}}} 7�#�Ի�����������������."N8+g�#ןK�ɱ��V@@@@@�Lqq�9h�4�p�C"N��$℣�خQn�Nnʊ��� ��� �''��3��V,&&&&&�p�@Z1"N8͙�I�Y[[[[[������G�r'��vM#��XÓ¨z{{{{{�������8a_��i�&h�\�^XXXXXH� �9� 7Ï;w��9յ�&#####C�&ℽ�خn������H������?.�G�� �.������p"N,+g: �f\\\\\\}}}}}��#wq������qb�h�t��M�����8�p,���&�G��v��j�Z�VP]�3� ��V��j�4g:C� �1>>>>>������?��+ÕšL&��t���Ç��j�',�� �&�/Äšz422222�~�����_�z��ի������������Nĉ�`�Lg7���f��lNOOOOO_��)���<"N�Í™.I������ب�0�k×®]�vm���۷o_�g�)Ny����b�.I�������+ᦗ������|�����;������'gggggg''��3]�ps��իW�nhhhhhP]`&��b�qbf4g:&�����ϟ?�����ܹs�Î�����b�&Ȳ��*惿?0~�(��%⌊�����ZLGs� �����ݭ���l6��F�� �q��=z��QI?d��ZA� �#9��ݳgÏž={�m"NØ¢9@������������b��SuEP�� ed�s��ݻw�f��� ���۷o�>OOOOOO"NМ� D��9@�/_�|�r"NМ�!�����"8�����I��������A����34G"N��333333����Xu-0������������Ii�TW{�93����� Ö¯_���ק��u�ֽ��|��J���;���_����FE��F �d������G�9r�H_____��`4g!����ׯwt|�{��ކ �?f��ի7m����W]5`L��9kmmm��>p���ӧUW�X�lÙ²e��������.N�8��� �`��.��~ ?������W^y�W^��kUW��c� ݓ�8%�P]�� tL�,�A��,,,,,,LIIIII!��/�3����P9;~pppppPuEP######C��.N�9;u�ԩS�nݺu��-9X!88888877777�F�5�]�������D�zDs�'w/J�v�Æ7nLLLLLLШ�&Û»8333333UW���9CyT��5�!���T�/4g`X��Ú;w�ܹ������A�� d���������S/h��%x{{{{{�������6j~}���ܪ+��ќ�˙ި-]�t�ҥ�������Q3"N}�tiM���UW1��1�3(������e����ӧO�NNNNNN�����˓˂TŘ?i�e�������=(((((Hu]�2V�4aJ󚚚���BBBBBB>���?� F��'l�����vEM��0�L&�IV�8p��������1��1̇���jË©x�+�W�9ì$$$$$$�������&b�p��ڽ{��ݻ'�Ҩ�WNNNNN�����������_F��9���/��� /��������>kjjjjj�oß¾}�v�'_� T׈Ǔ�3*****�j�Z�VP]��X9�<�����������������׫���خ�uuuuuuٮ�1L�q�޽{��ݩ������ũ4g�3Y ������޵k×®]�8' pMÓ§>�}��g�}V��Өi��wzzzzzz�={��ٳ�+����M�,)))))IIIIII�{�T�@ 9�C��Mo���߿�~��i��ؖc��Z^lk�d�Æ7n|��^{�5i�TW@���׿�����L}j����������'�Z4g�y�����KuE�¶Q��>��4jZc{P-�ZLk�n$Ö”�����������.Z$ Ù¡C�:d;��s�Î;wJK��FW$�oFGGGGG�������˵�r���*/\�p��������V]-���v�@�������!'�Z�Bs;��@� �U]í’¶L�M��>������iÔœO"N�y�A��G� �Gjkkkkk�r(�A���r��~��_��W IIIIIID��!�T+'��:+gp i�d�� ҫ����ӣ�����������S�O��qZ,��"w�0��4gp������������fy?"�c;�9�f5DZ�8��tbM8��۷oß¾-@mmmmmmf��l6�� ��MLLLLL=z��ѣgΜ9s��֭[�n�J�i_��lS���U�eL���IBBBBBBdMx� `�d����O>��O>aE;l#N�8�� N������ � lÚ´iÓ¦M�``/�N&{�$����?��c��ًD�rpReeeee�ꊌ�X HC�jÕªU�VEFFFFF�YG��`LÒ��x��� jȺ�꺌��3( j4555555�P]c�������& dEm�l#NÙ¦Bb_4gPF���������ÍM���zi���D�sE��8�Y9Û»w�޽{�qI����.�#G�9r��>g��8��3h�Zu����dEM�Q��������63Û»8SRRRRRTWd4g����F��%ErG��1��[n �%��'./////W]��ќAC��������������Ө�%����I����ÇJ�������+/)UW�^EEEEEÅ¡C�:$����H�hΠ9��… .\�]h����$�Ϟ�����g�}��g�������صk×®]�\9�S��0Ź4g������cÇŽ;vL�1�: �v���)���O?���O�G------M���Ç?~\uE�ô&t@���������E��U�_& Yiiiii�+��)/�eMQ,$Q]�>�r()))))�ë³ï¿½ï¿½ï¿½ï¿½ï¿½UW_�vEM�������VJWØ£&jH�� �\ÑœAdy\v���3��Eu]0����s�=��s��z�+ H�)oq��&t������WO��8�X��������y��͛7oÚ´iÓ¦M{���>�iq��+� �3о}�������������g?�����;�)S�r)_yyyyy��ԣ9�a������ɠ@}}}}}���l�[�nݺuKޯ�a�S�N�:uJ6��a�+R�� �%����'Y�������V]8��S�Z8�{�A���)��  ��RSSSSS9���is`~�7j�/^�x�4jZØ£&��TYYYYY�����@a�޽{��C7� ��zÓ§>e��b�X,��! ��5tuuuuui�ԾX9� ���p i�TW�M&��������`��Q�VLZC����"N�3��������f�+��FM�~I�y�޽{�����J�6:::::��J�XZ���"NbM��������U�V�Z�J"N��Su]�E24P\\\\\,�I�i�o�_�_�|8���9�K���߿�~9�Z&�T����Fm��ݻw��)�Ҝuwww�'1��f��A� �&���`6�E���s���"���%�P]�^Ñœ_�( �r��@l5&�g��ZJ���+���� �BUUUUU��p����FM���ԧ�Q� �3� 2:.7 dgggggs�Ì4j%%%%%%2�)��6j�+�"�3��ÈÇŽ;v��B�� t�/�7�Lo�233333Uר-4g�W�A�-[�lٲ�A��FM� x�N�Q�c�[�nݺur���������4l�r������OL<�c��S]�Lh���FFFFFF��������������y�.�;v�ر#%%%%%�3���V�X���W/_�|��n������͛�������JgBs�f6��fszzzzz��?Û›o���o��r���\Ë–-[���}�ĉo���?��.��z{�ӟ��_�5%%%e�NՕ΄��������!َ��`��{}��eo����?��!Óš?���kWjjj�= �S7@s|�^͙�����íˆï¿½ï¿½ï¿½ï¿½ï¿½ï¿½bbbbbbT��EÜ­i�Xp������ �(]v�Ɋ��ZGs8���������(� �3��JJJJJJ�.]�t�ҽ{��ݻWuE�9����������������ӧO�V]@�h΀/8z8fÙ²eË–-��������6������U�m�9�JNV������JMMMMMU]@+h�Ö®]�v�Ú7nܸQ.}R]@+h�e�Z��d2��3@Ù…&�gÏž={���*qC� ������r�@{{{{{�c��.p�!@u�� �a�,���������Ƞ�15 YYYYYY�[w6������98p����ׯ_�~�… .H��.PC�������P�������T��(4g�FÉ���VTTTTT��"PCΆ��e����� �����������p�@=!!!!!Au]�<Ò������uuuuuu��������˱h�M�����ë‹ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½ï¿½Ø‹ï¿½`K��$Ö”g�ꊜ�� Ð�������������N�F]u]�(Ò�so�/M������%y��_���E�W37Lk: �IIIIIIIr���>>>>������_��1��:�nݺu��0(�xl����������Wf�322222���М:311111!���M����}fr�cuuuuu�������Ð������l��>G�E�}���۷�������������f��lV]��B��MGs@�������4]��_�����ٲf����h�(#�YooooooSSSSS��`nq��233333_x�^xaÏž={��Q]Ì–#��9���!��,��b������S]��qwМ��V�Z�jժ�����9tCu]��\���ќ�����ѱ������� ��d2�T�c��L#���bbbbbb6lذa����������W��`p���������w����2(@ r�+�9 Nn�]hyyyyyyrS������� h�ÒI%�U��%�qx2h���8Vwww�~gf�٬�6}�ɠe h���Мh���Мh���Мh���Мh7x�G�������������K/��R\��J8�lN���=�As`V�?d�^�z��Ž{��]������wh�WC���IZ1i�~������W]������>�Lu-`Äš4�����q{Yh��;�=�� ��LMMM�@þ/~h��X���X�Ln����� �<]�r���~'Ӛ���� �+# �0+�w�p���9����� `:� �C� �!4g�9������W] `44g�9������������W]`44g�90��f�9=====]u-�1Ñœ��ڵk×®]Û¾}����U��`||||||TW���Мh����OMMMq�/`D���î¾VE�x.����/<��* !���3 �9��3 �9��3 �9��3 �9��3 �9��3 �9��3 �9��3 �9��3 �9Ð�g�Ž7�<�IEND�B`� jgrapht-0.8.3/testsrc/org/jgrapht/alg/NotBiconnectedGraph.java0000644000175000017500000000471211706124626024603 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * NotBiconnectedGraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: NotBiconnectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class NotBiconnectedGraph extends SimpleGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 6518961051694377584L; //~ Constructors ----------------------------------------------------------- public NotBiconnectedGraph() { super(DefaultEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { addEdge("0", "2"); addEdge("0", "3"); addEdge("3", "1"); addEdge("1", "4"); addEdge("4", "5"); addEdge("5", "3"); } private void addVertices() { addVertex("0"); addVertex("1"); addVertex("2"); addVertex("3"); addVertex("4"); addVertex("5"); } } // End NotBiconnectedGraph.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/ChromaticNumberTest.java0000644000175000017500000000640011706124626024641 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * ChromaticNumberTest.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: ChromaticNumberTest.java 740 2011-02-26 06:30:14Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * . * * @author Andrew Newell */ public class ChromaticNumberTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testChromaticNumber() { UndirectedGraph completeGraph = new SimpleGraph( DefaultEdge.class); CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator( 7); completeGenerator.generateGraph( completeGraph, new ClassBasedVertexFactory(Object.class), null); // A complete graph has a chromatic number equal to its order assertEquals( 7, ChromaticNumber.findGreedyChromaticNumber(completeGraph)); Map> coloring = ChromaticNumber.findGreedyColoredGroups(completeGraph); assertEquals( 7, coloring.keySet().size()); UndirectedGraph linearGraph = new SimpleGraph( DefaultEdge.class); LinearGraphGenerator linearGenerator = new LinearGraphGenerator( 50); linearGenerator.generateGraph( linearGraph, new ClassBasedVertexFactory(Object.class), null); // A linear graph is a tree, and a greedy algorithm for chromatic number // can always find a 2-coloring assertEquals(2, ChromaticNumber.findGreedyChromaticNumber(linearGraph)); } } // End ChromaticNumberTest.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/KShortestPathCompleteGraph6.java0000644000175000017500000001001611706124626026221 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPathCompleteGraph6.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: KShortestPathCompleteGraph6.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.alg; import org.jgrapht.graph.*; /** * @author Guillaume Boulmier * @since July 5, 2007 */ @SuppressWarnings("unchecked") public class KShortestPathCompleteGraph6 extends SimpleWeightedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 6310990195071210970L; //~ Instance fields -------------------------------------------------------- public Object e12; public Object e13; public Object e14; public Object e23; public Object e24; public Object e34; public Object eS1; public Object eS2; public Object eS3; public Object eS4; private Object e15; private Object e25; private Object e35; private Object e45; private Object eS5; //~ Constructors ----------------------------------------------------------- public KShortestPathCompleteGraph6() { super(DefaultWeightedEdge.class); addVertices(); addEdges(); } //~ Methods ---------------------------------------------------------------- private void addEdges() { this.eS1 = this.addEdge("vS", "v1"); this.eS2 = this.addEdge("vS", "v2"); this.eS3 = this.addEdge("vS", "v3"); this.eS4 = this.addEdge("vS", "v4"); this.eS5 = this.addEdge("vS", "v5"); this.e12 = this.addEdge("v1", "v2"); this.e13 = this.addEdge("v1", "v3"); this.e14 = this.addEdge("v1", "v4"); this.e15 = this.addEdge("v1", "v5"); this.e23 = this.addEdge("v2", "v3"); this.e24 = this.addEdge("v2", "v4"); this.e25 = this.addEdge("v2", "v5"); this.e34 = this.addEdge("v3", "v4"); this.e35 = this.addEdge("v3", "v5"); this.e45 = this.addEdge("v4", "v5"); setEdgeWeight(this.eS1, 1.0); setEdgeWeight(this.eS2, 1.0); setEdgeWeight(this.eS3, 1.0); setEdgeWeight(this.eS4, 1.0); setEdgeWeight(this.eS5, 1000.0); setEdgeWeight(this.e12, 1.0); setEdgeWeight(this.e13, 1.0); setEdgeWeight(this.e14, 1.0); setEdgeWeight(this.e15, 1.0); setEdgeWeight(this.e23, 1.0); setEdgeWeight(this.e24, 1.0); setEdgeWeight(this.e25, 1.0); setEdgeWeight(this.e34, 1.0); setEdgeWeight(this.e35, 1.0); setEdgeWeight(this.e45, 1.0); } private void addVertices() { addVertex("vS"); addVertex("v1"); addVertex("v2"); addVertex("v3"); addVertex("v4"); addVertex("v5"); } } // End KShortestPathCompleteGraph6.java jgrapht-0.8.3/testsrc/org/jgrapht/alg/HamiltonianCycleTest.java0000644000175000017500000000555411706124626025013 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * HamiltonianCycleTest.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: HamiltonianCycleTest.java 722 2010-11-24 06:22:07Z perfecthash $ * * Changes * ------- * 17-Feb-2008 : Initial revision (AN); * */ package org.jgrapht.alg; import java.util.*; import junit.framework.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * . * * @author Andrew Newell */ public class HamiltonianCycleTest extends TestCase { //~ Methods ---------------------------------------------------------------- // ~ Methods // ---------------------------------------------------------------- /** * . */ public void testHamiltonianCycle() { SimpleWeightedGraph completeGraph = new SimpleWeightedGraph( DefaultWeightedEdge.class); CompleteGraphGenerator completeGraphGenerator = new CompleteGraphGenerator( 6); completeGraphGenerator.generateGraph( completeGraph, new ClassBasedVertexFactory(Object.class), null); assertTrue( HamiltonianCycle.getApproximateOptimalForCompleteGraph( completeGraph).size() == 6); List vertices = new LinkedList(completeGraph.vertexSet()); completeGraph.removeEdge( completeGraph.getEdge(vertices.get(0), vertices.get(1))); assertTrue( HamiltonianCycle.getApproximateOptimalForCompleteGraph( completeGraph) == null); } } // End HamiltonianCycleTest.java jgrapht-0.8.3/testsrc/org/jgrapht/AllTests.java0000644000175000017500000000670711706124626021721 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------- * AllTests.java * ------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: AllTests.java 706 2010-02-28 05:09:24Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org.jgrapht; import java.util.*; import junit.framework.*; import org.jgrapht.alg.*; import org.jgrapht.alg.util.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; import org.jgrapht.util.*; /** * Runs all unit tests of the JGraphT library. * * @author Barak Naveh */ public final class AllTests { //~ Constructors ----------------------------------------------------------- private AllTests() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * Creates a test suite that includes all JGraphT tests. * * @return a test suite that includes all JGraphT tests. */ public static Test suite() { ExpandableTestSuite suite = new ExpandableTestSuite("All tests of JGraphT"); suite.addTestSuit((TestSuite) AllAlgTests.suite()); suite.addTestSuit((TestSuite) AllAlgUtilTests.suite()); suite.addTestSuit((TestSuite) AllGenerateTests.suite()); suite.addTestSuit((TestSuite) AllGraphTests.suite()); suite.addTestSuit((TestSuite) AllTraverseTests.suite()); suite.addTestSuit((TestSuite) AllUtilTests.suite()); return suite; } //~ Inner Classes ---------------------------------------------------------- private static class ExpandableTestSuite extends TestSuite { /** * @see TestSuite#TestSuite() */ public ExpandableTestSuite() { super(); } /** * @see TestSuite#TestSuite(java.lang.String) */ public ExpandableTestSuite(String name) { super(name); } /** * Adds all the test from the specified suite into this suite. * * @param suite */ public void addTestSuit(TestSuite suite) { for (Enumeration e = suite.tests(); e.hasMoreElements();) { Test t = (Test) e.nextElement(); this.addTest(t); } } } } // End AllTests.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/0000755000175000017500000000000011752244360022005 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/experimental/GraphReaderTest.java0000644000175000017500000001012311706124627025673 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * GraphReaderTest.java * ------------------- * (C) Copyright 2010-2010, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: GraphReaderTest.java 714 2010-06-13 01:19:56Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.experimental; import java.io.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * . * * @author Michael Behrisch */ public class GraphReaderTest extends TestCase { //~ Instance fields -------------------------------------------------------- String _unweighted = "p 3\ne 1 2\ne 1 3\n"; String _weighted = "p 3\ne 1 2 .5\ne 1 3 7\n"; //~ Methods ---------------------------------------------------------------- /** * . */ public void testGraphReader() { GraphReader reader; try { reader = new GraphReader( new StringReader(_unweighted)); Graph g = new SimpleGraph( DefaultEdge.class); VertexFactory vf = new IntVertexFactory(); reader.generateGraph(g, vf, null); Graph g2 = new SimpleGraph( DefaultEdge.class); g2.addVertex(0); g2.addVertex(1); g2.addVertex(2); g2.addEdge(0, 1); g2.addEdge(0, 2); assertEquals(g2.toString(), g.toString()); } catch (IOException e) { } } /** * . */ public void testGraphReaderWeighted() { try { GraphReader reader = new GraphReader( new StringReader(_weighted), 1); Graph g = new SimpleWeightedGraph( DefaultWeightedEdge.class); VertexFactory vf = new IntVertexFactory(); reader.generateGraph(g, vf, null); WeightedGraph g2 = new SimpleWeightedGraph( DefaultWeightedEdge.class); g2.addVertex(0); g2.addVertex(1); g2.addVertex(2); g2.setEdgeWeight(g2.addEdge(0, 1), .5); g2.setEdgeWeight(g2.addEdge(0, 2), 7); assertEquals(g2.toString(), g.toString()); } catch (IOException e) { } } //~ Inner Classes ---------------------------------------------------------- private static final class IntVertexFactory implements VertexFactory { int last = 0; public Integer createVertex() { return last++; } } } // End GraphReaderTest.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/permutation/0000755000175000017500000000000011752244360024354 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/experimental/permutation/CompoundPermutationIterTest.java0000644000175000017500000000774011706124627032731 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * CompoundPermutationIterTest.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: CompoundPermutationIterTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.permutation; import java.util.*; import junit.framework.*; /** * @author Assaf * @since May 30, 2005 */ public class CompoundPermutationIterTest extends TestCase { //~ Instance fields -------------------------------------------------------- private CompoundPermutationIter complexPerm; //~ Methods ---------------------------------------------------------------- /** * Asserts that the number of permutations is the same as getMax. It also * verifies that the number is the same when using different internal order * of the permutation components. Note: The prints and timer can be unmarked * to see performance results and the permutations array themselves. */ public void testGetNext() { // System.out.println("testing complex perm {1,1,1,2,2,3,4,5} "); // StopperTimer timer = new StopperTimer(); // timer.start(); this.complexPerm = new CompoundPermutationIter( new int[] { 1, 1, 1, 2, 2, 3, 4, 5 }); int maxPermNum = this.complexPerm.getMax(); // System.out.println(Arrays.toString(this.complexPerm.getPermAsArray())); int counter = 0; while (this.complexPerm.hasNext()) { int [] resultArray = this.complexPerm.getNext(); if (false) { System.out.println(Arrays.toString(resultArray)); } counter++; } // System.out.println(counter); assertEquals(maxPermNum, counter); // timer.stopAndReport(); // timer.start(); this.complexPerm = new CompoundPermutationIter( new int[] { 5, 4, 3, 2, 2, 1, 1, 1 }); // System.out.println("testing complex perm {5,4,3,2,2,1,1,1} "); // System.out.println(Arrays.toString(this.complexPerm.getPermAsArray())); counter = 0; while (this.complexPerm.hasNext()) { int [] resultArray = this.complexPerm.getNext(); if (false) { System.out.println(Arrays.toString(resultArray)); } counter++; } // System.out.println(counter); assertEquals(maxPermNum, counter); // timer.stopAndReport(); } } // End CompoundPermutationIterTest.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/equivalence/0000755000175000017500000000000011752244360024306 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/experimental/equivalence/EquivalenceGroupCreatorTest.java0000644000175000017500000001276211706124627032621 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceGroupCreatorTest.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceGroupCreatorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; import java.util.*; import junit.framework.*; import org.jgrapht.experimental.isomorphism.comparators.*; /** * @author Assaf * @since Jul 22, 2005 */ public class EquivalenceGroupCreatorTest extends TestCase { //~ Instance fields -------------------------------------------------------- // create the groups array as 0 to X (it) final int INTEGER_ARRAY_SIZE = 25; //~ Methods ---------------------------------------------------------------- /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } public void testUniformGroup() { // expecting two seperate groups , one with odd , one with even nubmers" testOneComparator(new UniformEquivalenceComparator(), 1); // " expecting 3 seperate groups , one for each mod3 testOneComparator( new org.jgrapht.experimental.isomorphism.comparators.Mod3GroupComparator(), 3); } public void testOddEvenGroup() { // " expecting two seperate groups , one with odd , one with even // nubmers"); testOneComparator( new org.jgrapht.experimental.isomorphism.comparators.OddEvenGroupComparator(), 2); // " expecting 3 seperate groups , one for each mod3"); testOneComparator( new org.jgrapht.experimental.isomorphism.comparators.Mod3GroupComparator(), 3); } /** * Using a chain of evenOdd(mod2) and mod3 comparator , should yield the 6 * groups , which are infact mod6 , examples: *
  • mod2 = 0 , mod3 = 0 --> mod6=0 , like : 6 , 12 *
  • mod2 = 1 , mod3 = 0 --> mod6=1 , like : 7 , 13 *
  • */ public void testComparatorChain() { EquivalenceComparatorChain comparatorChain = new EquivalenceComparatorChainBase( new OddEvenGroupComparator()); comparatorChain.appendComparator(new Mod3GroupComparator()); // for (int i=0 ; i integerArray = new ArrayList(INTEGER_ARRAY_SIZE); for (int i = 0; i < INTEGER_ARRAY_SIZE; i++) { integerArray.add(i); } EquivalenceSet [] eqGroupArray = EquivalenceSetCreator.createEqualityGroupOrderedArray( integerArray, comparator, null); assertEquals(expectedNumOfGroups, eqGroupArray.length); // assert the group order size is sorted. for (int i = 1; i < eqGroupArray.length; i++) { EquivalenceSet set = eqGroupArray[i]; assertTrue(set.size() >= eqGroupArray[i - 1].size()); } // System.out.println("\nTesting the EquivalenceSet[] returned from // Integer[" // +INTEGER_ARRAY_SIZE+"] filled with the integers as the indexes. \n" // + expectedResult); // System.out.println("result size="+eqGroupArray.length); // for (int i = 0; i < eqGroupArray.length; i++) { // System.out.println(eqGroupArray[i]); // } } } // End EquivalenceGroupCreatorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/0000755000175000017500000000000011752244360024356 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/IsomorphismInspectorTest.java0000644000175000017500000005105711706124627032273 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * IsomorphismInspectorTest.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: IsomorphismInspectorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.experimental.isomorphism.comparators.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * @author Assaf * @since May 27, 2005 */ public class IsomorphismInspectorTest extends TestCase { //~ Constructors ----------------------------------------------------------- /** * Constructor for IsomorphismInspectorTest. * * @param arg0 */ public IsomorphismInspectorTest(String arg0) { super(arg0); } //~ Methods ---------------------------------------------------------------- /* * @see TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } /** * Calls the same method with different (default) parameters * EqualityGroupChecker vertexChecker = null EqualityGroupChecker * edgeChecker = null */ private void assertIsomorphic( Graph [] graphs, boolean shouldTheyBeIsomorphic) { assertIsomorphic(graphs, shouldTheyBeIsomorphic, null, null); } @SuppressWarnings("unchecked") private void assertIsomorphic( Graph [] graphs, boolean shouldTheyBeIsomorphic, EquivalenceComparator vertexChecker, EquivalenceComparator edgeChecker) { // System.out.println("\nassertIsomorphic:"+shouldTheyBeIsomorphic); Graph g1 = graphs[0]; Graph g2 = graphs[1]; // System.out.println("g1:"+g1); // System.out.println("g2:"+g2); // long beforeTime=System.currentTimeMillis(); GraphIsomorphismInspector iso = AdaptiveIsomorphismInspectorFactory.createIsomorphismInspector( g1, g2, vertexChecker, edgeChecker); int counter = 0; while (iso.hasNext()) { IsomorphismRelation isioResult = (IsomorphismRelation) iso.next(); if (false) { if (counter == 0) { System.out.println( "Graphs are isomorphic. Iterating over all options:"); } System.out.println(counter + " : " + isioResult); } counter++; } // if (counter==0) // { // System.out.println("Graphs are NOT isomorphic."); // } // long deltaTime=System.currentTimeMillis()-beforeTime; // String timeDesc; // timeDesc= deltaTime<=10 ? "<10ms [less than minimum measurement // time]": String.valueOf(deltaTime); // System.out.println("# Performence: Isomorphism check in // MiliSeconds:"+timeDesc); if (shouldTheyBeIsomorphic) { assertTrue(counter != 0); } else { assertTrue(counter == 0); } } @SuppressWarnings("unchecked") private void checkRelation( Graph [] graphs, EquivalenceComparator vertexChecker, EquivalenceComparator edgeChecker) { Graph g1 = graphs[0]; Graph g2 = graphs[1]; GraphIsomorphismInspector iso = AdaptiveIsomorphismInspectorFactory.createIsomorphismInspector( g1, g2, vertexChecker, edgeChecker); IsomorphismRelation isoResult; if (iso.hasNext()) { isoResult = (IsomorphismRelation) iso.next(); Set vertexSet = g1.vertexSet(); for ( Iterator iter = vertexSet.iterator(); iter.hasNext();) { Integer v1 = iter.next(); Integer v2 = isoResult.getVertexCorrespondence(v1, true); if (false) { System.out.println("Vertex relation " + v1 + " to " + v2); } } Set edgeSet = g1.edgeSet(); for ( Iterator iter = edgeSet.iterator(); iter.hasNext();) { DefaultEdge e1 = iter.next(); DefaultEdge e2 = isoResult.getEdgeCorrespondence(e1, true); if (false) { System.out.println("Vertex relation " + e1 + " to " + e2); } } // if (counter==0) // { // System.out.println("Graphs are isomorphic. Iterating over all // options:"); // } // System.out.println(counter+" : "+isioResult); } } @SuppressWarnings("unchecked") public void testWheelGraphAddRemoveParts() { final int NUM_OF_VERTEXES_IN_WHEEL = 6; final int FIRST_INTEGER_FOR_G2 = 13; Graph g1 = new DefaultDirectedGraph( DefaultEdge.class); Graph g2 = new DefaultDirectedGraph( DefaultEdge.class); WheelGraphGenerator gen1 = new WheelGraphGenerator( NUM_OF_VERTEXES_IN_WHEEL); gen1.generateGraph(g1, new IntegerVertexFactory(), null); // FIRST_INTEGER_FOR_G2-1 , cause first integer is always the next one. gen1.generateGraph( g2, new IntegerVertexFactory(FIRST_INTEGER_FOR_G2), null); assertIsomorphic( new Graph[] { g1, g2 }, true); // In a wheel , the last vertex is the wheel center! g1.removeVertex(new Integer(NUM_OF_VERTEXES_IN_WHEEL)); // delete one vertex from g1 assertIsomorphic( new Graph[] { g1, g2 }, false); // for example: 10+4 g2.removeVertex( new Integer(FIRST_INTEGER_FOR_G2 + NUM_OF_VERTEXES_IN_WHEEL)); assertIsomorphic( new Graph[] { g1, g2 }, true); g1.removeEdge(new Integer(1), new Integer(2)); assertIsomorphic( new Graph[] { g1, g2 }, false); } @SuppressWarnings("unchecked") public void testLinear4vertexIsomorphicGraph() { Graph g1 = new DefaultDirectedGraph( DefaultEdge.class); LinearGraphGenerator gen1 = new LinearGraphGenerator(4); gen1.generateGraph(g1, new IntegerVertexFactory(), null); Graph g2 = new DefaultDirectedGraph( DefaultEdge.class); LinearGraphGenerator gen2 = new LinearGraphGenerator(4); gen2.generateGraph(g2, new IntegerVertexFactory(5), null); // start vertex from number 6 assertIsomorphic( new Graph[] { g1, g2 }, true); checkRelation( new Graph[] { g1, g2 }, null, null); } /** * Create two graphs which are topologically the same (same number of * vertexes and same edges connection), but the contents of the vertexes * belong to different eq. set. g1: 1-->2-->3-->4 g2: 2-->3-->4-->5 g3: * 3-->4-->5-->6 The eq-group-check is if the number is even or odd. So, g1 * and g3 are isomorphic. g2 is not isomorphic to either of them. */ @SuppressWarnings("unchecked") public void testLinear4vertexNonIsomorphicCauseOfVertexEqGroup() { LinearGraphGenerator gen4 = new LinearGraphGenerator(4); Graph g1 = new DefaultDirectedGraph( DefaultEdge.class); gen4.generateGraph(g1, new IntegerVertexFactory(), null); Graph g2 = new DefaultDirectedGraph( DefaultEdge.class); gen4.generateGraph(g2, new IntegerVertexFactory(1), null); // start vertex from number 2 Graph g3 = new DefaultDirectedGraph( DefaultEdge.class); gen4.generateGraph(g3, new IntegerVertexFactory(2), null); // start vertex from number 3 // first assert all are isomorphic (if vertexChecker is not used) assertIsomorphic( new Graph[] { g1, g2 }, true); assertIsomorphic( new Graph[] { g2, g3 }, true); assertIsomorphic( new Graph[] { g1, g3 }, true); // create a functor according to odd even EquivalenceComparator vertexEqChecker = new OddEvenGroupComparator(); assertIsomorphic( new Graph[] { g1, g2 }, false, vertexEqChecker, null); assertIsomorphic( new Graph[] { g2, g3 }, false, vertexEqChecker, null); assertIsomorphic( new Graph[] { g1, g3 }, true, vertexEqChecker, null); } /** * Passes an EdgeComparator, which compares according to odd-even edge * weight. The generated graphs are: A-(12)->B-(10)->C-(5)->D * A-(10)->B-(18)->C-(3)->D A-(11)->B-(10)->C-(5)->D (the first here is odd) * * @author Assaf * @since Aug 12, 2005 */ @SuppressWarnings("unchecked") public void testEdgeComparator() { int LINEAR_GRAPH_VERTEX_NUM = 4; Graph [] graphsArray = new DirectedGraph[3]; Character [] charArray = new Character[] { new Character('A'), new Character('B'), new Character('C'), new Character('D') }; int [][] weigthsArray = new int[][] { { 12, 10, 5 }, { 10, 18, 3 }, { 11, 10, 5 } }; for (int i = 0; i < graphsArray.length; i++) { Graph currGraph = graphsArray[i] = new DefaultDirectedWeightedGraph( DefaultWeightedEdge.class); for (int j = 0; j < LINEAR_GRAPH_VERTEX_NUM; j++) { currGraph.addVertex(charArray[j]); } // create the 3 edges with weights for (int j = 0; j < 3; j++) { Graphs.addEdge( currGraph, charArray[j], charArray[j + 1], weigthsArray[i][j]); } } // first assert all are isomorphic (if vertexChecker is not used) assertIsomorphic(new Graph[] { graphsArray[0], graphsArray[1] }, true); assertIsomorphic(new Graph[] { graphsArray[0], graphsArray[2] }, true); assertIsomorphic(new Graph[] { graphsArray[1], graphsArray[2] }, true); // create a functor according to odd even EquivalenceComparator edgeEqChecker = new DirectedEdgeWeightOddEvenComparator(graphsArray[0]); assertIsomorphic( new Graph[] { graphsArray[0], graphsArray[1] }, true, null, edgeEqChecker); assertIsomorphic( new Graph[] { graphsArray[0], graphsArray[2] }, false, null, edgeEqChecker); assertIsomorphic( new Graph[] { graphsArray[1], graphsArray[2] }, false, null, edgeEqChecker); } @SuppressWarnings("unchecked") private void assertIsomorphicStopAfterFirstMatch( Graph [] graphs, boolean assertActive, boolean shouldTheyBeIsomorphic, EquivalenceComparator vertexChecker, EquivalenceComparator edgeChecker) { if (assertActive) { System.out.println("\nassertIsomorphic:" + shouldTheyBeIsomorphic); } Graph g1 = graphs[0]; Graph g2 = graphs[1]; System.out.println("g1:" + g1); System.out.println("g2:" + g2); long beforeTime = System.currentTimeMillis(); GraphIsomorphismInspector iso = AdaptiveIsomorphismInspectorFactory.createIsomorphismInspector( g1, g2, vertexChecker, edgeChecker); boolean isoResult = iso.isIsomorphic(); if (isoResult) { System.out.println("Graphs are isomorphic. "); } else { System.out.println("Graphs are NOT isomorphic."); } long deltaTime = System.currentTimeMillis() - beforeTime; String timeDesc; timeDesc = (deltaTime <= 10) ? "<10ms [less than minumun measurement time]" : String.valueOf(deltaTime); System.out.println( "# Performence: Isomorphism check in MiliSeconds:" + timeDesc); if (assertActive) { assertEquals(shouldTheyBeIsomorphic, isoResult); } } /** * Performance test with different number of vertex, edges. For each number * pair, 3 graphs are generated. The first two, using the same generator, * the third using a different generator. Note: the 1st and 2nd must be * isomorphic. The 3rd will most likely not be isomorphic , but on special * occasaions may be, so do not assert it. (example: empty graph, full mesh * , rare case that they are not real random). NOTE: RENAME TO testXXX to * make it work. It shows output and not assertions, so it cannot be used by * automatic tests. */ @SuppressWarnings("unchecked") public void performanceTestOnRandomGraphs() throws Exception { final int [] numOfVertexesArray = new int[] { 6, 6, 6, 8, 8, 8, 10, 10, 10, 12, 14, 20, 30, 99 }; final int [] numOfEdgesArray = new int[] { 0, 4, 12, 1, 15, 54, 0, 40, 90, 130, 50, 79, 30, 234 }; // there will be two different generators. The first will be used for // 1st,2nd graph // the other for the3rd graph final int NUM_OF_GENERATORS = 2; RandomGraphGenerator [] genArray = new RandomGraphGenerator[NUM_OF_GENERATORS]; String [] graphConctereClassesFullName = new String[] { // "org.jgrapht.graph.SimpleGraph" , "org.jgrapht.graph.SimpleDirectedGraph", "org.jgrapht.graph.DefaultDirectedGraph", // "org.jgrapht.graph.Multigraph", // "org.jgrapht.graph.Pseudograph" }; // 3 graphs. 1st,2nd must be isomorphic .3rd probably not iso. final int SIZE_OF_GENERATED_GRAPH_ARRAY = 3; // graphsArray rows are different graph types. Columns are few // instances of that type Graph [][] graphsArray = new Graph[graphConctereClassesFullName.length][SIZE_OF_GENERATED_GRAPH_ARRAY]; Graph [] currIsoTestArray = new Graph[2]; for (int testNum = 0; testNum < numOfVertexesArray.length; testNum++) { // recreate the graphs (empty) try { for (int i = 0; i < graphConctereClassesFullName.length; i++) { for (int j = 0; j < SIZE_OF_GENERATED_GRAPH_ARRAY; j++) { graphsArray[i][j] = (Graph) Class.forName( graphConctereClassesFullName[i]).newInstance(); } } } catch (Exception e) { throw new Exception("failed to initilized the graphs", e); } // create generators for the new vertex/edges number for (int i = 0; i < genArray.length; i++) { genArray[i] = new RandomGraphGenerator( numOfVertexesArray[testNum], numOfEdgesArray[testNum]); } for ( int graphType = 0; graphType < graphConctereClassesFullName.length; graphType++) { System.out.println( "### numOfVertexes= " + numOfVertexesArray[testNum]); System.out.println( "### numOfEdges= " + numOfEdgesArray[testNum]); System.out.println( "######### Graph Type:" + graphConctereClassesFullName[graphType]); System.out.println( "# # # # # # # # # # # # # # # # # # # # # # # # # # # #"); // 1st and 2nd from genArray[0] genArray[0].generateGraph( graphsArray[graphType][0], new IntegerVertexFactory(), null); genArray[0].generateGraph( graphsArray[graphType][1], new IntegerVertexFactory(), null); // 3rd from genArray[1] genArray[1].generateGraph( graphsArray[graphType][2], new IntegerVertexFactory(), null); // now start testing currIsoTestArray[0] = graphsArray[graphType][0]; currIsoTestArray[1] = graphsArray[graphType][1]; assertIsomorphicStopAfterFirstMatch( currIsoTestArray, true, true, null, null); // remember it is not a MUST - it can be true . DEGUG REASON // ONLY , and with care currIsoTestArray[1] = graphsArray[graphType][2]; assertIsomorphicStopAfterFirstMatch( currIsoTestArray, false, false, null, null); } } } } // End IsomorphismInspectorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/EdgeTopologyCompare.java0000644000175000017500000000414211706124627031134 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EdgeTopologyCompare.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EdgeTopologyCompare.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import org.jgrapht.*; /** * @author Assaf * @since Aug 6, 2005 */ public class EdgeTopologyCompare { //~ Methods ---------------------------------------------------------------- /** * Compare topology of the two graphs. It does not compare the contents of * the vertexes/edges, but only the relationships between them. * * @param g1 * @param g2 */ @SuppressWarnings("unchecked") public static boolean compare(Graph g1, Graph g2) { boolean result = false; GraphOrdering lg1 = new GraphOrdering(g1); GraphOrdering lg2 = new GraphOrdering(g2); result = lg1.equalsByEdgeOrder(lg2); return result; } } // End EdgeTopologyCompare.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/IntegerVertexFactory.java0000644000175000017500000000472111706124627031352 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * IntegerVertexFactory.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: IntegerVertexFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import org.jgrapht.*; /** * Implements createVertex() by producing a sequence of Integers; their values * start with the successor to the constructor value. * *

    for example : IntegerVertexFactory(10); the first createVertex() will * return Integer=11 * * @author Assaf * @since May 25, 2005 */ public class IntegerVertexFactory implements VertexFactory { //~ Instance fields -------------------------------------------------------- private int counter; //~ Constructors ----------------------------------------------------------- /** * Equivalent to IntegerVertexFactory(0); * * @author Assaf * @since Aug 6, 2005 */ public IntegerVertexFactory() { this(0); } public IntegerVertexFactory(int oneBeforeFirstValue) { this.counter = oneBeforeFirstValue; } //~ Methods ---------------------------------------------------------------- public Integer createVertex() { this.counter++; return new Integer(this.counter); } } // End IntegerVertexFactory.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/comparators/0000755000175000017500000000000011752244360026710 5ustar giovannigiovanni././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootjgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/comparators/DirectedEdgeWeightOddEvenComparator.javajgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/comparators/DirectedEdgeWeightOddEvenComp0000644000175000017500000000622111706124627034402 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * DirectedEdgeWeightOddEvenComparator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: DirectedEdgeWeightOddEvenComparator.java 489 2006-07-02 02:05:47Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism.comparators; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; /** * eq.set according to the weights of the edges. Uses Graph.getEdgeWeight(Edge) * (cast to integer) and checks odd/even. * * @author Assaf * @since Aug 12, 2005 */ public class DirectedEdgeWeightOddEvenComparator implements EquivalenceComparator { //~ Instance fields -------------------------------------------------------- private final Graph graph; //~ Constructors ----------------------------------------------------------- public DirectedEdgeWeightOddEvenComparator(Graph graph) { this.graph = graph; } //~ Methods ---------------------------------------------------------------- /* (non-Javadoc) * @see * * * * * * org.jgrapht.experimental.equivalence.EquivalenceComparator#equivalenceCompare(java.lang.Object, * java.lang.Object, java.lang.Object, java.lang.Object) */ @SuppressWarnings("unchecked") public boolean equivalenceCompare( Object arg1, Object arg2, Object context1, Object context2) { int int1 = (int) graph.getEdgeWeight(arg1); int int2 = (int) graph.getEdgeWeight(arg2); boolean result = ((int1 % 2) == (int2 % 2)); return result; } /* (non-Javadoc) * @see * * * * * * org.jgrapht.experimental.equivalence.EquivalenceComparator#equivalenceHashcode(java.lang.Object, * java.lang.Object) */ @SuppressWarnings("unchecked") public int equivalenceHashcode(Object arg1, Object context) { int int1 = (int) graph.getEdgeWeight(arg1); return int1 % 2; } } // End DirectedEdgeWeightOddEvenComparator.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/comparators/Mod3GroupComparator.java0000644000175000017500000000472311706124627033432 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * Mod3GroupComparator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: Mod3GroupComparator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism.comparators; import org.jgrapht.experimental.equivalence.*; /** * Comparator which defines three groups of integers, according to mod3 result *

  • mod3=0 , *
  • mod3=1 *
  • mod3=2 Works only on Integers. * * @author Assaf * @since Jul 22, 2005 */ public class Mod3GroupComparator implements EquivalenceComparator { //~ Methods ---------------------------------------------------------------- public boolean equivalenceCompare( Integer arg1, Integer arg2, Object context1, Object context2) { int int1 = arg1.intValue(); int int2 = arg2.intValue(); boolean result = ((int1 % 3) == (int2 % 3)); return result; } /* Each group must have unique values. * @see * * * * * * org.jgrapht.experimental.equivalence.EquivalenceComparator#equivalenceHashcode(java.lang.Object) */ public int equivalenceHashcode(Integer arg1, Object context) { int int1 = arg1.intValue(); return int1 % 3; } } // End Mod3GroupComparator.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/isomorphism/comparators/OddEvenGroupComparator.java0000644000175000017500000000467711706124627034164 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * OddEvenGroupComparator.java * ----------------- * (C) Copyright 2005-2008, by Barak Naveh and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: OddEvenGroupComparator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism.comparators; import org.jgrapht.experimental.equivalence.*; /** * Comparator which defines two groups of integers. Odds (mod2=1) and * Evens(mod2=0). Works only on Integers. * * @author Assaf * @since Jul 22, 2005 */ public class OddEvenGroupComparator implements EquivalenceComparator { //~ Methods ---------------------------------------------------------------- public boolean equivalenceCompare( Integer arg1, Integer arg2, Object context1, Object context2) { int int1 = arg1.intValue(); int int2 = arg2.intValue(); boolean result = ((int1 % 2) == (int2 % 2)); return result; } /* Odd and even must have unique values. * @see * * * * * * org.jgrapht.experimental.equivalence.EquivalenceComparator#equivalenceHashcode(java.lang.Object) */ public int equivalenceHashcode(Integer arg1, Object context) { int int1 = arg1.intValue(); return int1 % 2; } } // End OddEvenGroupComparator.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/alg/0000755000175000017500000000000011752244360022550 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/experimental/alg/ColoringTest.java0000644000175000017500000000625111706124627026035 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * ColoringTest.java * ---------------- * (C) Copyright 2010, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: ColoringTest.java 714 2010-06-13 01:19:56Z perfecthash $ * * Changes * ------- * 17-Feb-2008 : Initial revision (MB); * */ package org.jgrapht.experimental.alg; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.experimental.alg.color.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; /** * . * * @author Michael Behrisch */ public class ColoringTest extends TestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testGreedyColoring() { Graph completeGraph = new SimpleGraph( DefaultEdge.class); CompleteGraphGenerator completeGraphGenerator = new CompleteGraphGenerator( 6); completeGraphGenerator.generateGraph( completeGraph, new ClassBasedVertexFactory(Object.class), null); GreedyColoring colorer = new GreedyColoring(completeGraph); assertEquals(new Integer(6), colorer.getUpperBound(null)); } /** * . */ public void testBacktrackColoring() { Graph completeGraph = new SimpleGraph( DefaultEdge.class); CompleteGraphGenerator completeGraphGenerator = new CompleteGraphGenerator( 6); completeGraphGenerator.generateGraph( completeGraph, new ClassBasedVertexFactory(Object.class), null); BrownBacktrackColoring colorer = new BrownBacktrackColoring(completeGraph); assertEquals(new Integer(6), colorer.getResult(null)); } } // End ColoringTest.java jgrapht-0.8.3/testsrc/org/jgrapht/experimental/dag/0000755000175000017500000000000011752244360022540 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/experimental/dag/DirectedAcyclicGraphTest.java0000644000175000017500000005365711706124627030262 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * DirectedAcyclicGraphTest.java * ------------------- * (C) Copyright 2008-2008, by Peter Giles and Contributors. * * Original Author: Peter Giles * Contributor(s): - * * $Id: DirectedAcyclicGraphTest.java 637 2008-09-28 22:23:11Z perfecthash $ * * Changes * ------- * 17-Mar-2008 : Initial revision (PG); * */ package org.jgrapht.experimental.dag; import java.util.*; import junit.framework.*; import org.jgrapht.*; import org.jgrapht.alg.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; /** * Unit tests for the DirectedAcyclicGraph, a dynamic DAG implementation. * * @author gilesp@u.washington.edu */ public class DirectedAcyclicGraphTest extends TestCase { //~ Instance fields -------------------------------------------------------- private RandomGraphGenerator randomGraphGenerator = null; private Graph sourceGraph = null; //~ Methods ---------------------------------------------------------------- @Override protected void setUp() throws Exception { super.setUp(); setUpWithSeed(100, 5000, 2); } private void setUpWithSeed(int vertices, int edges, long seed) { randomGraphGenerator = new RepeatableRandomGraphGenerator( vertices, edges, seed); sourceGraph = new SimpleDirectedGraph(DefaultEdge.class); randomGraphGenerator.generateGraph( sourceGraph, new LongVertexFactory(), null); } /** * Tests the cycle detection capabilities of DirectedAcyclicGraph by * building a parallel SimpleDirectedGraph and using a CycleDetector to * check for cycles, and comparing the results. */ public void testCycleDetectionInRandomGraphBuild() { for (int i = 0; i < 50; i++) { // test with 50 random graph // configurations setUpWithSeed(20, 200, i); DirectedAcyclicGraph dag = new DirectedAcyclicGraph(DefaultEdge.class); SimpleDirectedGraph compareGraph = new SimpleDirectedGraph(DefaultEdge.class); for (Long vertex : sourceGraph.vertexSet()) { dag.addVertex(vertex); compareGraph.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); boolean dagRejectedEdge = false; try { dag.addDagEdge(edgeSource, edgeTarget); } catch (DirectedAcyclicGraph.CycleFoundException e) { // okay, it did't add that edge dagRejectedEdge = true; } DefaultEdge compareEdge = compareGraph.addEdge(edgeSource, edgeTarget); CycleDetector cycleDetector = new CycleDetector(compareGraph); boolean cycleDetected = cycleDetector.detectCycles(); assertTrue(dagRejectedEdge == cycleDetected); if (cycleDetected) { // remove the edge from the compareGraph so the graphs // remain in sync compareGraph.removeEdge(compareEdge); } } // after all this, our graphs must be equal assertEquals(compareGraph.vertexSet(), dag.vertexSet()); // for some reason comparing vertex sets doesn't work, so doing it // the hard way: for (Long sourceVertex : compareGraph.vertexSet()) { for ( DefaultEdge outgoingEdge : compareGraph.outgoingEdgesOf(sourceVertex)) { Long targetVertex = compareGraph.getEdgeTarget(outgoingEdge); assertTrue(dag.containsEdge(sourceVertex, targetVertex)); } } } } /** * trivial test of topological order using a linear graph */ public void testTopoIterationOrderLinearGraph() { DirectedAcyclicGraph dag = new DirectedAcyclicGraph(DefaultEdge.class); LinearGraphGenerator graphGen = new LinearGraphGenerator(100); graphGen.generateGraph(dag, new LongVertexFactory(), null); Iterator internalTopoIter = dag.iterator(); TopologicalOrderIterator comparTopoIter = new TopologicalOrderIterator(dag); while (comparTopoIter.hasNext()) { Long compareNext = comparTopoIter.next(); Long myNext = null; if (internalTopoIter.hasNext()) { myNext = internalTopoIter.next(); } assertSame(compareNext, myNext); assertEquals(comparTopoIter.hasNext(), internalTopoIter.hasNext()); } } /** * more rigorous test of topological iteration order, by assuring that each * visited vertex adheres to the definition of topological order, that is * that it doesn't have a path leading to any of its predecessors. */ public void testTopoIterationOrderComplexGraph() { for (int seed = 0; seed < 20; seed++) { DirectedAcyclicGraph dag = new DirectedAcyclicGraph(DefaultEdge.class); RepeatableRandomGraphGenerator graphGen = new RepeatableRandomGraphGenerator( 100, 500, seed); graphGen.generateGraph(dag, new LongVertexFactory(), null); ConnectivityInspector connectivityInspector = new ConnectivityInspector(dag); Iterator internalTopoIter = dag.iterator(); List previousVertices = new ArrayList(); while (internalTopoIter.hasNext()) { Long vertex = internalTopoIter.next(); for (Long previousVertex : previousVertices) { connectivityInspector.pathExists(vertex, previousVertex); } previousVertices.add(vertex); } } } public void testIterationBehaviors() { int vertexCount = 100; DirectedAcyclicGraph dag = new DirectedAcyclicGraph(DefaultEdge.class); RepeatableRandomGraphGenerator graphGen = new RepeatableRandomGraphGenerator( vertexCount, 500, 2); graphGen.generateGraph(dag, new LongVertexFactory(), null); Iterator dagIter = dag.iterator(); // Scroll through all the elements, then make sure things happen as // should when an iterator is all used up for (int i = 0; i < vertexCount; i++) { assertTrue(dagIter.hasNext()); dagIter.next(); } assertFalse(dagIter.hasNext()); try { dagIter.next(); fail(); } catch (NoSuchElementException e) { // good, we already looked at all of the elements } assertFalse(dagIter.hasNext()); dagIter = dag.iterator(); // replace dagIter; assertNotNull(dagIter.next()); // make sure it works on first element // even if hasNext() wasn't called // Test that ConcurrentModificationExceptionS happen as they should when // the topology is modified during iteration // remove a random vertex dag.removeVertex(dag.vertexSet().iterator().next()); // now we expect exceptions since the topological order has been // modified (albeit trivially) try { dagIter.next(); fail(); // fail, no exception was thrown } catch (ConcurrentModificationException e) { // good, this is expected } try { dagIter.hasNext(); fail(); // fail, no exception was thrown } catch (ConcurrentModificationException e) { // good, this is expected } try { dagIter.remove(); fail(); // fail, no exception was thrown } catch (ConcurrentModificationException e) { // good, this is expected } // TODO: further iterator tests } // Performance tests have underscores in the names so that they // they are only run explicitly (not automatically as part of // default JUnit runs). /** * A somewhat frivolous test of the performance difference between doing a * full cycle detection (non-dynamic algorithm) for each edge added versus * the dynamic algorithm used by DirectedAcyclicGraph. */ public void _testPerformanceVersusStaticChecking() { int trialsPerConfiguration = 10; int maxVertices = 1024; int maxConnectednessFactor = 4; for ( int numVertices = 1024; numVertices <= maxVertices; numVertices *= 2) { for ( int connectednessFactor = 1; (connectednessFactor <= maxConnectednessFactor) && (connectednessFactor < (numVertices - 1)); connectednessFactor *= 2) { long dynamicDagTime = 0; long staticDagTime = 0; for (int seed = 0; seed < trialsPerConfiguration; seed++) { // test with random graph configurations setUpWithSeed( numVertices, numVertices * connectednessFactor, seed); DirectedAcyclicGraph dag = new DirectedAcyclicGraph( DefaultEdge.class); long dynamicOpStart = System.nanoTime(); for (Long vertex : sourceGraph.vertexSet()) { dag.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); dag.addEdge(edgeSource, edgeTarget); } dynamicDagTime += System.nanoTime() - dynamicOpStart; SimpleDirectedGraph compareGraph = new SimpleDirectedGraph( DefaultEdge.class); long staticOpStart = System.nanoTime(); for (Long vertex : sourceGraph.vertexSet()) { compareGraph.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); DefaultEdge compareEdge = compareGraph.addEdge(edgeSource, edgeTarget); CycleDetector cycleDetector = new CycleDetector(compareGraph); boolean cycleDetected = cycleDetector.detectCycles(); if (cycleDetected) { // remove the edge from the compareGraph compareGraph.removeEdge(compareEdge); } } staticDagTime += System.nanoTime() - staticOpStart; } System.out.println( "vertices = " + numVertices + " connectednessFactor = " + connectednessFactor + " trialsPerConfiguration = " + trialsPerConfiguration); System.out.println( "total static DAG time = " + staticDagTime + " ns"); System.out.println( "total dynamic DAG time = " + dynamicDagTime + " ns"); System.out.println(); } } } /** * A somewhat frivolous test of the performance difference between doing a * full cycle detection (non-dynamic algorithm) for each edge added versus * the dynamic algorithm used by DirectedAcyclicGraph. */ public void _testVisitedImplementationPerformance() { int trialsPerConfiguration = 10; int maxVertices = 1024; int maxConnectednessFactor = 4; for ( int numVertices = 64; numVertices <= maxVertices; numVertices *= 2) { for ( int connectednessFactor = 1; (connectednessFactor <= maxConnectednessFactor) && (connectednessFactor < (numVertices - 1)); connectednessFactor *= 2) { long arrayDagTime = 0; long arrayListDagTime = 0; long hashSetDagTime = 0; long bitSetDagTime = 0; for (int seed = 0; seed < trialsPerConfiguration; seed++) { // test with random graph configurations setUpWithSeed( numVertices, numVertices * connectednessFactor, seed); DirectedAcyclicGraph arrayDag = new DirectedAcyclicGraph( DefaultEdge.class, new DirectedAcyclicGraph.VisitedArrayImpl(), null); DirectedAcyclicGraph arrayListDag = new DirectedAcyclicGraph( DefaultEdge.class, new DirectedAcyclicGraph.VisitedArrayListImpl(), null); DirectedAcyclicGraph hashSetDag = new DirectedAcyclicGraph( DefaultEdge.class, new DirectedAcyclicGraph.VisitedHashSetImpl(), null); DirectedAcyclicGraph bitSetDag = new DirectedAcyclicGraph( DefaultEdge.class, new DirectedAcyclicGraph.VisitedBitSetImpl(), null); long arrayStart = System.nanoTime(); for (Long vertex : sourceGraph.vertexSet()) { arrayDag.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); try { arrayDag.addDagEdge(edgeSource, edgeTarget); } catch (DirectedAcyclicGraph.CycleFoundException e) { // okay } } arrayDagTime += System.nanoTime() - arrayStart; long arrayListStart = System.nanoTime(); for (Long vertex : sourceGraph.vertexSet()) { arrayListDag.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); try { arrayListDag.addDagEdge(edgeSource, edgeTarget); } catch (DirectedAcyclicGraph.CycleFoundException e) { // okay } } arrayListDagTime += System.nanoTime() - arrayListStart; long hashSetStart = System.nanoTime(); for (Long vertex : sourceGraph.vertexSet()) { hashSetDag.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); try { hashSetDag.addDagEdge(edgeSource, edgeTarget); } catch (DirectedAcyclicGraph.CycleFoundException e) { // okay } } hashSetDagTime += System.nanoTime() - hashSetStart; long bitSetStart = System.nanoTime(); for (Long vertex : sourceGraph.vertexSet()) { bitSetDag.addVertex(vertex); } for (DefaultEdge edge : sourceGraph.edgeSet()) { Long edgeSource = sourceGraph.getEdgeSource(edge); Long edgeTarget = sourceGraph.getEdgeTarget(edge); try { bitSetDag.addDagEdge(edgeSource, edgeTarget); } catch (DirectedAcyclicGraph.CycleFoundException e) { // okay } } bitSetDagTime += System.nanoTime() - bitSetStart; } System.out.println( "vertices = " + numVertices + " connectednessFactor = " + connectednessFactor + " trialsPerConfiguration = " + trialsPerConfiguration); System.out.println( "total array time = " + arrayDagTime + " ns"); System.out.println( "total ArrayList time = " + arrayListDagTime + " ns"); System.out.println( "total HashSet time = " + hashSetDagTime + " ns"); System.out.println( "total BitSet time = " + bitSetDagTime + " ns"); System.out.println(); } } } //~ Inner Classes ---------------------------------------------------------- private static class LongVertexFactory implements VertexFactory { private long nextVertex = 0; public Long createVertex() { return nextVertex++; } } // it is nice for tests to be easily repeatable, so we use a graph generator // that we can seed for specific configurations private static class RepeatableRandomGraphGenerator extends RandomGraphGenerator { public RepeatableRandomGraphGenerator( int vertices, int edges, long seed) { super(vertices, edges); randomizer = new Random(seed); } @Override public void generateGraph( Graph graph, VertexFactory vertexFactory, Map namedVerticesMap) { List vertices = new ArrayList(numOfVertexes); Set edgeGeneratorIds = new HashSet(); for (int i = 0; i < numOfVertexes; i++) { V vertex = vertexFactory.createVertex(); vertices.add(vertex); graph.addVertex(vertex); } for (int i = 0; i < numOfEdges; i++) { Integer edgeGeneratorId; do { edgeGeneratorId = randomizer.nextInt(numOfVertexes * (numOfVertexes - 1)); } while (edgeGeneratorIds.contains(edgeGeneratorId)); int fromVertexId = edgeGeneratorId / numOfVertexes; int toVertexId = edgeGeneratorId % (numOfVertexes - 1); if (toVertexId >= fromVertexId) { ++toVertexId; } try { graph.addEdge( vertices.get(fromVertexId), vertices.get(toVertexId)); } catch (IllegalArgumentException e) { // okay, that's fine; omit cycle } } } } } // End DirectedAcyclicGraphTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/0000755000175000017500000000000011752244360021143 5ustar giovannigiovannijgrapht-0.8.3/testsrc/org/jgrapht/traverse/IgnoreDirectionTest.java0000644000175000017500000000550711706124627025743 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * IgnoreDirectionTest.java * --------------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: IgnoreDirectionTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 08-Aug-2003 : Initial revision (JVS); * */ package org.jgrapht.traverse; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests for the ignoreDirection parameter to XXFirstIterator. * *

    NOTE: This test uses hard-coded expected ordering which isn't really * guaranteed by the specification of the algorithm. This could cause spurious * failures if the traversal implementation changes.

    * * @author John V. Sichi * @since Aug 8, 2003 */ public class IgnoreDirectionTest extends AbstractGraphIteratorTest { //~ Methods ---------------------------------------------------------------- String getExpectedStr1() { return "4,9,7,8,2,1,3,6,5"; } String getExpectedStr2() { return "4,9,7,8,2,1,3,6,5,orphan"; } String getExpectedFinishString() { return "5:6:3:1:2:8:7:9:4:orphan:"; } AbstractGraphIterator createIterator( DirectedGraph g, String vertex) { // ignore the passed in vertex and always start from v4, since that's // the only vertex without out-edges UndirectedGraph undirectedView = new AsUndirectedGraph(g); AbstractGraphIterator i = new DepthFirstIterator(undirectedView, "4"); i.setCrossComponentTraversal(true); return i; } } // End IgnoreDirectionTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/BreadthFirstIteratorTest.java0000644000175000017500000000507511706124627026752 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * BreadthFirstIteratorTest.java * ----------------------------- * (C) Copyright 2003-2008, by Liviu Rau and Contributors. * * Original Author: Liviu Rau * Contributor(s): Barak Naveh * * $Id: BreadthFirstIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 30-Jul-2003 : Initial revision (LR); * 06-Aug-2003 : Test traversal listener & extract a shared superclass (BN); * */ package org.jgrapht.traverse; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests for the {@link BreadthFirstIterator} class. * *

    NOTE: This test uses hard-coded expected ordering isn't really guaranteed * by the specification of the algorithm. This could cause false failures if the * traversal implementation changes.

    * * @author Liviu Rau * @since Jul 30, 2003 */ public class BreadthFirstIteratorTest extends AbstractGraphIteratorTest { //~ Methods ---------------------------------------------------------------- String getExpectedStr1() { return "1,2,3,4,5,6,7,8,9"; } String getExpectedStr2() { return "1,2,3,4,5,6,7,8,9,orphan"; } AbstractGraphIterator createIterator( DirectedGraph g, String vertex) { AbstractGraphIterator i = new BreadthFirstIterator(g, vertex); i.setCrossComponentTraversal(true); return i; } } // End BreadthFirstIteratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/ClosestFirstIteratorTest.java0000644000175000017500000000707511706124627027017 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * ClosestFirstIteratorTest.java * ----------------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: ClosestFirstIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 03-Sep-2003 : Initial revision (JVS); * 29-May-2005 : Test radius support (JVS); * */ package org.jgrapht.traverse; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests for ClosestFirstIterator. * * @author John V. Sichi * @since Sep 3, 2003 */ public class ClosestFirstIteratorTest extends AbstractGraphIteratorTest { //~ Methods ---------------------------------------------------------------- /** * . */ public void testRadius() { result = new StringBuffer(); DirectedGraph graph = createDirectedGraph(); // NOTE: pick 301 as the radius because it discriminates // the boundary case edge between v7 and v9 AbstractGraphIterator iterator = new ClosestFirstIterator(graph, "1", 301); while (iterator.hasNext()) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(','); } } assertEquals("1,2,3,5,6,7", result.toString()); } /** * . */ public void testNoStart() { result = new StringBuffer(); DirectedGraph graph = createDirectedGraph(); AbstractGraphIterator iterator = new ClosestFirstIterator(graph); while (iterator.hasNext()) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(','); } } assertEquals("1,2,3,5,6,7,9,4,8,orphan", result.toString()); } // NOTE: the edge weights make the result deterministic String getExpectedStr1() { return "1,2,3,5,6,7,9,4,8"; } String getExpectedStr2() { return getExpectedStr1() + ",orphan"; } AbstractGraphIterator createIterator( DirectedGraph g, String vertex) { AbstractGraphIterator i = new ClosestFirstIterator(g, vertex); i.setCrossComponentTraversal(true); return i; } } // End ClosestFirstIteratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/AbstractGraphIteratorTest.java0000644000175000017500000001523111706124627027111 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * AbstractGraphIteratorTest.java * ------------------------------ * (C) Copyright 2003-2008, by Liviu Rau and Contributors. * * Original Author: Liviu Rau * Contributor(s): Barak Naveh * * $Id: AbstractGraphIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 30-Jul-2003 : Initial revision (LR); * 06-Aug-2003 : Test traversal listener & extract a shared superclass (BN); * */ package org.jgrapht.traverse; import org.jgrapht.*; import org.jgrapht.event.*; import org.jgrapht.graph.*; /** * A basis for testing {@link org.jgrapht.traverse.BreadthFirstIterator} and * {@link org.jgrapht.traverse.DepthFirstIterator} classes. * * @author Liviu Rau * @since Jul 30, 2003 */ public abstract class AbstractGraphIteratorTest extends EnhancedTestCase { //~ Instance fields -------------------------------------------------------- StringBuffer result; //~ Methods ---------------------------------------------------------------- /** * . */ public void testDirectedGraph() { result = new StringBuffer(); DirectedGraph graph = createDirectedGraph(); AbstractGraphIterator iterator = createIterator(graph, "1"); MyTraversalListener listener = new MyTraversalListener(); iterator.addTraversalListener(listener); while (iterator.hasNext()) { result.append(iterator.next()); if (iterator.hasNext()) { result.append(','); } } assertEquals(getExpectedStr2(), result.toString()); assertEquals(getExpectedFinishString(), listener.getFinishString()); } abstract String getExpectedStr1(); abstract String getExpectedStr2(); String getExpectedFinishString() { return ""; } DirectedGraph createDirectedGraph() { DirectedGraph graph = new DefaultDirectedWeightedGraph( DefaultWeightedEdge.class); // String v1 = "1"; String v2 = "2"; String v3 = "3"; String v4 = "4"; String v5 = "5"; String v6 = "6"; String v7 = "7"; String v8 = "8"; String v9 = "9"; graph.addVertex(v1); graph.addVertex(v2); graph.addVertex("3"); graph.addVertex("4"); graph.addVertex("5"); graph.addVertex("6"); graph.addVertex("7"); graph.addVertex("8"); graph.addVertex("9"); graph.addVertex("orphan"); // NOTE: set weights on some of the edges to test traversals like // ClosestFirstIterator where it matters. For other traversals, it // will be ignored. Rely on the default edge weight being 1. graph.addEdge(v1, v2); Graphs.addEdge(graph, v1, v3, 100); Graphs.addEdge(graph, v2, v4, 1000); graph.addEdge(v3, v5); Graphs.addEdge(graph, v3, v6, 100); graph.addEdge(v5, v6); Graphs.addEdge(graph, v5, v7, 200); graph.addEdge(v6, v1); Graphs.addEdge(graph, v7, v8, 100); graph.addEdge(v7, v9); graph.addEdge(v8, v2); graph.addEdge(v9, v4); return graph; } abstract AbstractGraphIterator createIterator( DirectedGraph g, String startVertex); //~ Inner Classes ---------------------------------------------------------- /** * Internal traversal listener. * * @author Barak Naveh */ private class MyTraversalListener implements TraversalListener { private int componentNumber = 0; private int numComponentVertices = 0; private String finishString = ""; /** * @see TraversalListener#connectedComponentFinished(ConnectedComponentTraversalEvent) */ public void connectedComponentFinished( ConnectedComponentTraversalEvent e) { switch (componentNumber) { case 1: assertEquals(getExpectedStr1(), result.toString()); assertEquals(9, numComponentVertices); break; case 2: assertEquals(getExpectedStr2(), result.toString()); assertEquals(1, numComponentVertices); break; default: assertFalse(); break; } numComponentVertices = 0; } /** * @see TraversalListener#connectedComponentStarted(ConnectedComponentTraversalEvent) */ public void connectedComponentStarted( ConnectedComponentTraversalEvent e) { componentNumber++; } /** * @see TraversalListener#edgeTraversed(EdgeTraversalEvent) */ public void edgeTraversed(EdgeTraversalEvent e) { // to be tested... } /** * @see TraversalListener#vertexTraversed(VertexTraversalEvent) */ public void vertexTraversed(VertexTraversalEvent e) { numComponentVertices++; } /** * @see TraversalListener#vertexTraversed(VertexTraversalEvent) */ public void vertexFinished(VertexTraversalEvent e) { finishString += e.getVertex() + ":"; } public String getFinishString() { return finishString; } } } // End AbstractGraphIteratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/TopologicalOrderIteratorTest.java0000644000175000017500000001001211706124627027624 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * TopologicalOrderIteratorTest.java * --------------------------- * (C) Copyright 2005-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: TopologicalOrderIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 25-Apr-2005 : Initial revision (JVS); * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests for TopologicalOrderIterator. * * @author John V. Sichi * @since Apr 25, 2005 */ public class TopologicalOrderIteratorTest extends EnhancedTestCase { //~ Methods ---------------------------------------------------------------- /** * . */ public void testRecipe() { DirectedGraph graph = new DefaultDirectedGraph( DefaultEdge.class); String [] v = new String[9]; v[0] = "preheat oven"; v[1] = "sift dry ingredients"; v[2] = "stir wet ingredients"; v[3] = "mix wet and dry ingredients"; v[4] = "spoon onto pan"; v[5] = "bake"; v[6] = "cool"; v[7] = "frost"; v[8] = "eat"; // add in mixed up order graph.addVertex(v[4]); graph.addVertex(v[8]); graph.addVertex(v[1]); graph.addVertex(v[3]); graph.addVertex(v[7]); graph.addVertex(v[6]); graph.addVertex(v[0]); graph.addVertex(v[2]); graph.addVertex(v[5]); // specify enough edges to guarantee deterministic total order graph.addEdge(v[0], v[1]); graph.addEdge(v[1], v[2]); graph.addEdge(v[0], v[2]); graph.addEdge(v[1], v[3]); graph.addEdge(v[2], v[3]); graph.addEdge(v[3], v[4]); graph.addEdge(v[4], v[5]); graph.addEdge(v[5], v[6]); graph.addEdge(v[6], v[7]); graph.addEdge(v[7], v[8]); graph.addEdge(v[6], v[8]); Iterator iter = new TopologicalOrderIterator(graph); int i = 0; while (iter.hasNext()) { assertEquals(v[i], iter.next()); ++i; } // Test with a reversed view DirectedGraph reversed = new EdgeReversedGraph(graph); iter = new TopologicalOrderIterator(reversed); i = v.length - 1; while (iter.hasNext()) { assertEquals(v[i], iter.next()); --i; } } /** * . */ public void testEmptyGraph() { DirectedGraph graph = new DefaultDirectedGraph( DefaultEdge.class); Iterator iter = new TopologicalOrderIterator(graph); assertFalse(iter.hasNext()); } } // End TopologicalOrderIteratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/DepthFirstIteratorTest.java0000644000175000017500000001027711706124627026445 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * DepthFirstIteratorTest.java * --------------------------- * (C) Copyright 2003-2008, by Liviu Rau and Contributors. * * Original Author: Liviu Rau * Contributor(s): Barak Naveh * * $Id: DepthFirstIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 30-Jul-2003 : Initial revision (LR); * 06-Aug-2003 : Test traversal listener & extract a shared superclass (BN); * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Tests for the {@link DepthFirstIteratorTest} class. * *

    NOTE: This test uses hard-coded expected ordering isn't really guaranteed * by the specification of the algorithm. This could cause false failures if the * traversal implementation changes.

    * * @author Liviu Rau * @since Jul 30, 2003 */ public class DepthFirstIteratorTest extends AbstractGraphIteratorTest { //~ Methods ---------------------------------------------------------------- String getExpectedStr1() { return "1,3,6,5,7,9,4,8,2"; } String getExpectedStr2() { return "1,3,6,5,7,9,4,8,2,orphan"; } String getExpectedFinishString() { return "6:4:9:2:8:7:5:3:1:orphan:"; } AbstractGraphIterator createIterator( DirectedGraph g, String vertex) { AbstractGraphIterator i = new DepthFirstIterator(g, vertex); i.setCrossComponentTraversal(true); return i; } /** * See Sourceforge bug 1169182 * for details. */ public void testBug1169182() { DirectedGraph dg = new DefaultDirectedGraph(DefaultEdge.class); String a = "A"; String b = "B"; String c = "C"; String d = "D"; String e = "E"; String f = "F"; String g = "G"; String h = "H"; String i = "I"; String j = "J"; String k = "K"; String l = "L"; dg.addVertex(a); dg.addVertex(b); dg.addVertex(c); dg.addVertex(d); dg.addVertex(e); dg.addVertex(f); dg.addVertex(g); dg.addVertex(h); dg.addVertex(i); dg.addVertex(j); dg.addVertex(k); dg.addVertex(l); dg.addEdge(a, b); dg.addEdge(b, c); dg.addEdge(c, j); dg.addEdge(c, d); dg.addEdge(c, e); dg.addEdge(c, f); dg.addEdge(c, g); dg.addEdge(d, h); dg.addEdge(e, h); dg.addEdge(f, i); dg.addEdge(g, i); dg.addEdge(h, j); dg.addEdge(i, c); dg.addEdge(j, k); dg.addEdge(k, l); Iterator dfs = new DepthFirstIterator(dg); String actual = ""; while (dfs.hasNext()) { String v = dfs.next(); actual += v; } String expected = "ABCGIFEHJKLD"; assertEquals(expected, actual); } } // End DepthFirstIteratorTest.java jgrapht-0.8.3/testsrc/org/jgrapht/traverse/AllTraverseTests.java0000644000175000017500000000470311706124627025263 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * AllTraverseTests.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: AllTraverseTests.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org.jgrapht.traverse; import junit.framework.*; /** * A TestSuite for all tests in this package. * * @author Barak Naveh */ public final class AllTraverseTests { //~ Constructors ----------------------------------------------------------- private AllTraverseTests() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * Creates a test suite for all tests in this package. * * @return a test suite for all tests in this package. */ public static Test suite() { TestSuite suite = new TestSuite(); // $JUnit-BEGIN$ suite.addTest(new TestSuite(BreadthFirstIteratorTest.class)); suite.addTest(new TestSuite(DepthFirstIteratorTest.class)); suite.addTest(new TestSuite(ClosestFirstIteratorTest.class)); suite.addTest(new TestSuite(IgnoreDirectionTest.class)); suite.addTest(new TestSuite(TopologicalOrderIteratorTest.class)); // $JUnit-END$ return suite; } } // End AllTraverseTests.java jgrapht-0.8.3/license-LGPL.txt0000644000175000017500000006347611706124627016334 0ustar giovannigiovanni GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! jgrapht-0.8.3/etc/0000755000175000017500000000000011752244356014153 5ustar giovannigiovannijgrapht-0.8.3/etc/build.properties.template0000644000175000017500000000372611706124627021207 0ustar giovannigiovanni# ========================================== # JGraphT : a free Java graph-theory library # ========================================== # # Project Info: http://jgrapht.sourceforge.net/ # Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) # # (C) Copyright 2003-2006, by Barak Naveh and Contributors. # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # ~~~~~~~~~ # etc/build.properties # ~~~~~~~~~ # # Original Author: John V. Sichi # Contributor(s): - # # $Id: build.properties.template 570 2007-09-30 01:06:39Z perfecthash $ # # Changes # ~~~~~~~ # 31-July-2005 : Initial revision (JVS); # 01-July-2006 : Update for version 0.7 (JVS); # ~~~~~~~ # # etc/build.properties is used to customize the JGraphT build. # To use it, uncomment the settings below for the attributes you want # to customize, then change the values to your site-specifics. # The ant buildfile will override its own defaults with any # uncommented values it sees here. # NOTE: If you are building JGraphT directly from Subversion rather than from # a distribution, create etc/build.properties by making a copy of # etc/build.properties.template. (The template file should only be # changed by developers who are enhancing the build process # with customizability.) # ~~~~~~~~~~~~~~~~~ # End build.properties # ~~~~~~~~~~~~~~~~~ jgrapht-0.8.3/etc/build.properties0000644000175000017500000000372611706124627017375 0ustar giovannigiovanni# ========================================== # JGraphT : a free Java graph-theory library # ========================================== # # Project Info: http://jgrapht.sourceforge.net/ # Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) # # (C) Copyright 2003-2006, by Barak Naveh and Contributors. # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # ~~~~~~~~~ # etc/build.properties # ~~~~~~~~~ # # Original Author: John V. Sichi # Contributor(s): - # # $Id: build.properties.template 570 2007-09-30 01:06:39Z perfecthash $ # # Changes # ~~~~~~~ # 31-July-2005 : Initial revision (JVS); # 01-July-2006 : Update for version 0.7 (JVS); # ~~~~~~~ # # etc/build.properties is used to customize the JGraphT build. # To use it, uncomment the settings below for the attributes you want # to customize, then change the values to your site-specifics. # The ant buildfile will override its own defaults with any # uncommented values it sees here. # NOTE: If you are building JGraphT directly from Subversion rather than from # a distribution, create etc/build.properties by making a copy of # etc/build.properties.template. (The template file should only be # changed by developers who are enhancing the build process # with customizability.) # ~~~~~~~~~~~~~~~~~ # End build.properties # ~~~~~~~~~~~~~~~~~ jgrapht-0.8.3/src/0000755000175000017500000000000011752244360014162 5ustar giovannigiovannijgrapht-0.8.3/src/org/0000755000175000017500000000000011706124625014751 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/0000755000175000017500000000000011752244360016410 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/graph/0000755000175000017500000000000011752244357017517 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/graph/MaskFunctor.java0000644000175000017500000000412311706124626022611 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * MaskFunctor.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: MaskFunctor.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; /** * A functor interface for masking out vertices and edges of a graph. * * @author Guillaume Boulmier * @since July 5, 2007 */ public interface MaskFunctor { //~ Methods ---------------------------------------------------------------- /** * Returns true if the edge is masked, false * otherwise. * * @param edge edge. * * @return . */ public boolean isEdgeMasked(E edge); /** * Returns true if the vertex is masked, false * otherwise. * * @param vertex vertex. * * @return . */ public boolean isVertexMasked(V vertex); } // End MaskFunctor.java jgrapht-0.8.3/src/org/jgrapht/graph/AbstractGraph.java0000644000175000017500000001512011706124626023101 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * AbstractGraph.java * ------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: AbstractGraph.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * A skeletal implementation of the Graph interface, to minimize the * effort required to implement graph interfaces. This implementation is * applicable to both: directed graphs and undirected graphs. * * @author Barak Naveh * @see Graph * @see DirectedGraph * @see UndirectedGraph */ public abstract class AbstractGraph implements Graph { //~ Constructors ----------------------------------------------------------- /** * Construct a new empty graph object. */ public AbstractGraph() { } //~ Methods ---------------------------------------------------------------- /** * @see Graph#containsEdge(Object, Object) */ public boolean containsEdge(V sourceVertex, V targetVertex) { return getEdge(sourceVertex, targetVertex) != null; } /** * @see Graph#removeAllEdges(Collection) */ public boolean removeAllEdges(Collection edges) { boolean modified = false; for (E e : edges) { modified |= removeEdge(e); } return modified; } /** * @see Graph#removeAllEdges(Object, Object) */ public Set removeAllEdges(V sourceVertex, V targetVertex) { Set removed = getAllEdges(sourceVertex, targetVertex); removeAllEdges(removed); return removed; } /** * @see Graph#removeAllVertices(Collection) */ public boolean removeAllVertices(Collection vertices) { boolean modified = false; for (V v : vertices) { modified |= removeVertex(v); } return modified; } /** * Returns a string of the parenthesized pair (V, E) representing this * G=(V,E) graph. 'V' is the string representation of the vertex set, and * 'E' is the string representation of the edge set. * * @return a string representation of this graph. */ public String toString() { return toStringFromSets( vertexSet(), edgeSet(), (this instanceof DirectedGraph)); } /** * Ensures that the specified vertex exists in this graph, or else throws * exception. * * @param v vertex * * @return true if this assertion holds. * * @throws NullPointerException if specified vertex is null. * @throws IllegalArgumentException if specified vertex does not exist in * this graph. */ protected boolean assertVertexExist(V v) { if (containsVertex(v)) { return true; } else if (v == null) { throw new NullPointerException(); } else { throw new IllegalArgumentException("no such vertex in graph"); } } /** * Removes all the edges in this graph that are also contained in the * specified edge array. After this call returns, this graph will contain no * edges in common with the specified edges. This method will invoke the * {@link Graph#removeEdge(Object)} method. * * @param edges edges to be removed from this graph. * * @return true if this graph changed as a result of the call. * * @see Graph#removeEdge(Object) * @see Graph#containsEdge(Object) */ protected boolean removeAllEdges(E [] edges) { boolean modified = false; for (int i = 0; i < edges.length; i++) { modified |= removeEdge(edges[i]); } return modified; } /** * Helper for subclass implementations of toString( ). * * @param vertexSet the vertex set V to be printed * @param edgeSet the edge set E to be printed * @param directed true to use parens for each edge (representing directed); * false to use curly braces (representing undirected) * * @return a string representation of (V,E) */ protected String toStringFromSets( Collection vertexSet, Collection edgeSet, boolean directed) { List renderedEdges = new ArrayList(); StringBuffer sb = new StringBuffer(); for (E e : edgeSet) { if ((e.getClass() != DefaultEdge.class) && (e.getClass() != DefaultWeightedEdge.class)) { sb.append(e.toString()); sb.append("="); } if (directed) { sb.append("("); } else { sb.append("{"); } sb.append(getEdgeSource(e)); sb.append(","); sb.append(getEdgeTarget(e)); if (directed) { sb.append(")"); } else { sb.append("}"); } // REVIEW jvs 29-May-2006: dump weight somewhere? renderedEdges.add(sb.toString()); sb.setLength(0); } return "(" + vertexSet + ", " + renderedEdges + ")"; } } // End AbstractGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/EdgeReversedGraph.java0000644000175000017500000001153411706124626023707 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------- * EdgeReversedGraph.java * ------------- * (C) Copyright 2006-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: EdgeReversedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sept-2006 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * Provides an edge-reversed view g' of a directed graph g. The vertex sets for * the two graphs are the same, but g' contains an edge (v2, v1) iff g contains * an edge (v1, v2). g' is backed by g, so changes to g are reflected in g', and * vice versa. * *

    This class allows you to use a directed graph algorithm in reverse. For * example, suppose you have a directed graph representing a tree, with edges * from parent to child, and you want to find all of the parents of a node. To * do this, simply create an edge-reversed graph and pass that as input to * {@link org.jgrapht.traverse.DepthFirstIterator}. * * @author John V. Sichi * @see AsUndirectedGraph */ public class EdgeReversedGraph extends GraphDelegator implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 9091361782455418631L; //~ Constructors ----------------------------------------------------------- /** * Creates a new EdgeReversedGraph. * * @param g the base (backing) graph on which the edge-reversed view will be * based. */ public EdgeReversedGraph(DirectedGraph g) { super(g); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { return super.getEdge(targetVertex, sourceVertex); } /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { return super.getAllEdges(targetVertex, sourceVertex); } /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { return super.addEdge(targetVertex, sourceVertex); } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { return super.addEdge(targetVertex, sourceVertex, e); } /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { return super.outDegreeOf(vertex); } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { return super.inDegreeOf(vertex); } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { return super.outgoingEdgesOf(vertex); } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { return super.incomingEdgesOf(vertex); } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { return super.removeEdge(targetVertex, sourceVertex); } /** * @see Graph#getEdgeSource(Object) */ public V getEdgeSource(E e) { return super.getEdgeTarget(e); } /** * @see Graph#getEdgeTarget(Object) */ public V getEdgeTarget(E e) { return super.getEdgeSource(e); } /** * @see java.lang.Object#toString() */ public String toString() { return toStringFromSets( vertexSet(), edgeSet(), true); } } // End EdgeReversedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/AsUnweightedGraph.java0000644000175000017500000000625011706124626023731 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * AsUnweightedGraph.java * ---------------------- * (C) Copyright 2007-2008, by Lucas J. Scharenbroich and Contributors. * * Original Author: Lucas J. Scharenbroich * Contributor(s): John V. Sichi * * $Id: AsUnweightedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 7-Sep-2007 : Initial revision (LJS); * */ package org.jgrapht.graph; import java.io.*; import org.jgrapht.*; /** * An unweighted view of the backing weighted graph specified in the * constructor. This graph allows modules to apply algorithms designed for * unweighted graphs to a weighted graph by simply ignoring edge weights. Query * operations on this graph "read through" to the backing graph. Vertex * addition/removal and edge addition/removal are all supported (and immediately * reflected in the backing graph). * *

    Note that edges returned by this graph's accessors are really just the * edges of the underlying directed graph.

    * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods. This graph will be serializable if the backing * graph is serializable.

    * * @author Lucas J. Scharenbroich * @since Sep 7, 2007 */ public class AsUnweightedGraph extends GraphDelegator implements Serializable { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 7175505077601824663L; //~ Constructors ----------------------------------------------------------- /** * Constructor for AsUnweightedGraph. * * @param g the backing graph over which an unweighted view is to be * created. */ public AsUnweightedGraph(Graph g) { super(g); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getEdgeWeight */ public double getEdgeWeight(E e) { return WeightedGraph.DEFAULT_EDGE_WEIGHT; } } // End AsUnweightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/UndirectedMaskSubgraph.java0000644000175000017500000000370011706124626024753 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * UndirectedMaskSubgraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: UndirectedMaskSubgraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * An undirected graph that is a {@link MaskSubgraph} on another graph. * * @author Guillaume Boulmier * @since July 5, 2007 */ public class UndirectedMaskSubgraph extends MaskSubgraph implements UndirectedGraph { //~ Constructors ----------------------------------------------------------- public UndirectedMaskSubgraph( UndirectedGraph base, MaskFunctor mask) { super(base, mask); } } // End UndirectedMaskSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/AsWeightedGraph.java0000644000175000017500000001172011706124626023364 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * AsWeightedGraph.java * ---------------------- * (C) Copyright 2007, by Lucas J. Scharenbroich and Contributors. * * Original Author: Lucas J. Scharenbroich * Contributor(s): John V. Sichi * * $Id: AsWeightedGraph.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 10-Sep-2007 : Initial revision (LJS); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; /** *

    A weighted view of the backing graph specified in the constructor. This * graph allows modules to apply algorithms designed for weighted graphs to an * unweighted graph by providing an explicit edge weight mapping. The * implementation also allows for "masking" weights for a subset of the edges in * an existing weighted graph.

    * *

    Query operations on this graph "read through" to the backing graph. Vertex * addition/removal and edge addition/removal are all supported (and immediately * reflected in the backing graph). Setting an edge weight will pass the * operation to the backing graph as well if the backing graph implements the * WeightedGraph interface. Setting an edge weight will modify the weight map in * order to maintain a consistent graph.

    * *

    Note that edges returned by this graph's accessors are really just the * edges of the underlying directed graph.

    * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods. This graph will be serializable if the backing * graph is serializable.

    * * @author Lucas J. Scharenbroich * @since Sep 10, 2007 */ public class AsWeightedGraph extends GraphDelegator implements Serializable, WeightedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = -716810639338971372L; //~ Instance fields -------------------------------------------------------- protected final Map weightMap; private final boolean isWeightedGraph; //~ Constructors ----------------------------------------------------------- /** * Constructor for AsWeightedGraph. * * @param g the backing graph over which a weighted view is to be created. * @param weightMap A mapping of edges to weights. If an edge is not present * in the weight map, the edge weight for the underlying graph is returned. * Note that a live reference to this map is retained, so if the caller * changes the map after construction, the changes will affect the * AsWeightedGraph instance as well. */ public AsWeightedGraph(Graph g, Map weightMap) { super(g); assert (weightMap != null); this.weightMap = weightMap; // Remember whether the backing graph implements the WeightedGraph // interface this.isWeightedGraph = (g instanceof WeightedGraph); } //~ Methods ---------------------------------------------------------------- /** * @see WeightedGraph#setEdgeWeight */ public void setEdgeWeight(E e, double weight) { if (isWeightedGraph) { super.setEdgeWeight(e, weight); } // Always modify the weight map. It would be a terrible violation // of the use contract to silently ignore changes to the weights. weightMap.put(e, weight); } /** * @see Graph#getEdgeWeight */ public double getEdgeWeight(E e) { double weight; // Always return the value from the weight map first and // only pass the call through as a backup if (weightMap.containsKey(e)) { weight = weightMap.get(e); } else { weight = super.getEdgeWeight(e); } return weight; } } // End AsWeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DefaultListenableGraph.java0000644000175000017500000003415411706124626024735 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * DefaultListenableGraph.java * --------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DefaultListenableGraph.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 04-Aug-2003 : Strong refs to listeners instead of weak refs (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 07-Mar-2004 : Fixed unnecessary clone bug #819075 (BN); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; import org.jgrapht.event.*; import org.jgrapht.util.*; /** * A graph backed by the the graph specified at the constructor, which can be * listened by GraphListener s and by * VertexSetListener s. Operations on this graph "pass through" to the to * the backing graph. Any modification made to this graph or the backing graph * is reflected by the other. * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods.

    * * @author Barak Naveh * @see GraphListener * @see VertexSetListener * @since Jul 20, 2003 */ public class DefaultListenableGraph extends GraphDelegator implements ListenableGraph, Cloneable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3977575900898471984L; //~ Instance fields -------------------------------------------------------- private ArrayList> graphListeners = new ArrayList>(); private ArrayList> vertexSetListeners = new ArrayList>(); private FlyweightEdgeEvent reuseableEdgeEvent; private FlyweightVertexEvent reuseableVertexEvent; private boolean reuseEvents; //~ Constructors ----------------------------------------------------------- /** * Creates a new listenable graph. * * @param g the backing graph. */ public DefaultListenableGraph(Graph g) { this(g, false); } /** * Creates a new listenable graph. If the reuseEvents flag is * set to true this class will reuse previously fired events * and will not create a new object for each event. This option increases * performance but should be used with care, especially in multithreaded * environment. * * @param g the backing graph. * @param reuseEvents whether to reuse previously fired event objects * instead of creating a new event object for each event. * * @throws IllegalArgumentException if the backing graph is already a * listenable graph. */ public DefaultListenableGraph(Graph g, boolean reuseEvents) { super(g); this.reuseEvents = reuseEvents; reuseableEdgeEvent = new FlyweightEdgeEvent(this, -1, null); reuseableVertexEvent = new FlyweightVertexEvent(this, -1, null); // the following restriction could be probably relaxed in the future. if (g instanceof ListenableGraph) { throw new IllegalArgumentException( "base graph cannot be listenable"); } } //~ Methods ---------------------------------------------------------------- /** * If the reuseEvents flag is set to true this * class will reuse previously fired events and will not create a new object * for each event. This option increases performance but should be used with * care, especially in multithreaded environment. * * @param reuseEvents whether to reuse previously fired event objects * instead of creating a new event object for each event. */ public void setReuseEvents(boolean reuseEvents) { this.reuseEvents = reuseEvents; } /** * Tests whether the reuseEvents flag is set. If the flag is * set to true this class will reuse previously fired events * and will not create a new object for each event. This option increases * performance but should be used with care, especially in multithreaded * environment. * * @return the value of the reuseEvents flag. */ public boolean isReuseEvents() { return reuseEvents; } /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { E e = super.addEdge(sourceVertex, targetVertex); if (e != null) { fireEdgeAdded(e); } return e; } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { boolean added = super.addEdge(sourceVertex, targetVertex, e); if (added) { fireEdgeAdded(e); } return added; } /** * @see ListenableGraph#addGraphListener(GraphListener) */ public void addGraphListener(GraphListener l) { addToListenerList(graphListeners, l); } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { boolean modified = super.addVertex(v); if (modified) { fireVertexAdded(v); } return modified; } /** * @see ListenableGraph#addVertexSetListener(VertexSetListener) */ public void addVertexSetListener(VertexSetListener l) { addToListenerList(vertexSetListeners, l); } /** * @see java.lang.Object#clone() */ public Object clone() { try { TypeUtil> typeDecl = null; DefaultListenableGraph g = TypeUtil.uncheckedCast(super.clone(), typeDecl); g.graphListeners = new ArrayList>(); g.vertexSetListeners = new ArrayList>(); return g; } catch (CloneNotSupportedException e) { // should never get here since we're Cloneable e.printStackTrace(); throw new RuntimeException("internal error"); } } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { E e = super.removeEdge(sourceVertex, targetVertex); if (e != null) { fireEdgeRemoved(e); } return e; } /** * @see Graph#removeEdge(Object) */ public boolean removeEdge(E e) { boolean modified = super.removeEdge(e); if (modified) { fireEdgeRemoved(e); } return modified; } /** * @see ListenableGraph#removeGraphListener(GraphListener) */ public void removeGraphListener(GraphListener l) { graphListeners.remove(l); } /** * @see Graph#removeVertex(Object) */ public boolean removeVertex(V v) { if (containsVertex(v)) { Set touchingEdgesList = edgesOf(v); // copy set to avoid ConcurrentModificationException removeAllEdges(new ArrayList(touchingEdgesList)); super.removeVertex(v); // remove the vertex itself fireVertexRemoved(v); return true; } else { return false; } } /** * @see ListenableGraph#removeVertexSetListener(VertexSetListener) */ public void removeVertexSetListener(VertexSetListener l) { vertexSetListeners.remove(l); } /** * Notify listeners that the specified edge was added. * * @param edge the edge that was added. */ protected void fireEdgeAdded(E edge) { GraphEdgeChangeEvent e = createGraphEdgeChangeEvent(GraphEdgeChangeEvent.EDGE_ADDED, edge); for (int i = 0; i < graphListeners.size(); i++) { GraphListener l = graphListeners.get(i); l.edgeAdded(e); } } /** * Notify listeners that the specified edge was removed. * * @param edge the edge that was removed. */ protected void fireEdgeRemoved(E edge) { GraphEdgeChangeEvent e = createGraphEdgeChangeEvent( GraphEdgeChangeEvent.EDGE_REMOVED, edge); for (int i = 0; i < graphListeners.size(); i++) { GraphListener l = graphListeners.get(i); l.edgeRemoved(e); } } /** * Notify listeners that the specified vertex was added. * * @param vertex the vertex that was added. */ protected void fireVertexAdded(V vertex) { GraphVertexChangeEvent e = createGraphVertexChangeEvent( GraphVertexChangeEvent.VERTEX_ADDED, vertex); for (int i = 0; i < vertexSetListeners.size(); i++) { VertexSetListener l = vertexSetListeners.get(i); l.vertexAdded(e); } for (int i = 0; i < graphListeners.size(); i++) { GraphListener l = graphListeners.get(i); l.vertexAdded(e); } } /** * Notify listeners that the specified vertex was removed. * * @param vertex the vertex that was removed. */ protected void fireVertexRemoved(V vertex) { GraphVertexChangeEvent e = createGraphVertexChangeEvent( GraphVertexChangeEvent.VERTEX_REMOVED, vertex); for (int i = 0; i < vertexSetListeners.size(); i++) { VertexSetListener l = vertexSetListeners.get(i); l.vertexRemoved(e); } for (int i = 0; i < graphListeners.size(); i++) { GraphListener l = graphListeners.get(i); l.vertexRemoved(e); } } private static void addToListenerList( List list, L l) { if (!list.contains(l)) { list.add(l); } } private GraphEdgeChangeEvent createGraphEdgeChangeEvent( int eventType, E edge) { if (reuseEvents) { reuseableEdgeEvent.setType(eventType); reuseableEdgeEvent.setEdge(edge); return reuseableEdgeEvent; } else { return new GraphEdgeChangeEvent(this, eventType, edge); } } private GraphVertexChangeEvent createGraphVertexChangeEvent( int eventType, V vertex) { if (reuseEvents) { reuseableVertexEvent.setType(eventType); reuseableVertexEvent.setVertex(vertex); return reuseableVertexEvent; } else { return new GraphVertexChangeEvent(this, eventType, vertex); } } //~ Inner Classes ---------------------------------------------------------- /** * A reuseable edge event. * * @author Barak Naveh * @since Aug 10, 2003 */ private static class FlyweightEdgeEvent extends GraphEdgeChangeEvent { private static final long serialVersionUID = 3907207152526636089L; /** * @see GraphEdgeChangeEvent#GraphEdgeChangeEvent(Object, int, Edge) */ public FlyweightEdgeEvent(Object eventSource, int type, EE e) { super(eventSource, type, e); } /** * Sets the edge of this event. * * @param e the edge to be set. */ protected void setEdge(EE e) { this.edge = e; } /** * Set the event type of this event. * * @param type the type to be set. */ protected void setType(int type) { this.type = type; } } /** * A reuseable vertex event. * * @author Barak Naveh * @since Aug 10, 2003 */ private static class FlyweightVertexEvent extends GraphVertexChangeEvent { private static final long serialVersionUID = 3257848787857585716L; /** * @see GraphVertexChangeEvent#GraphVertexChangeEvent(Object, int, * Object) */ public FlyweightVertexEvent(Object eventSource, int type, VV vertex) { super(eventSource, type, vertex); } /** * Set the event type of this event. * * @param type type to be set. */ protected void setType(int type) { this.type = type; } /** * Sets the vertex of this event. * * @param vertex the vertex to be set. */ protected void setVertex(VV vertex) { this.vertex = vertex; } } } // End DefaultListenableGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/UnmodifiableUndirectedGraph.java0000644000175000017500000000445611706124626025755 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------------- * UnmodifiableUndirectedGraph.java * -------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: UnmodifiableUndirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH) * */ package org.jgrapht.graph; import org.jgrapht.*; /** * An undirected graph that cannot be modified. * * @see UnmodifiableGraph */ public class UnmodifiableUndirectedGraph extends UnmodifiableGraph implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3258134639355704624L; //~ Constructors ----------------------------------------------------------- /** * Creates a new unmodifiable undirected graph based on the specified * backing graph. * * @param g the backing graph on which an unmodifiable graph is to be * created. */ public UnmodifiableUndirectedGraph(UndirectedGraph g) { super(g); } } // End UnmodifiableUndirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/UnmodifiableGraph.java0000644000175000017500000001135111706124626023736 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * UnmodifiableGraph.java * ---------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: UnmodifiableGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; /** * An unmodifiable view of the backing graph specified in the constructor. This * graph allows modules to provide users with "read-only" access to internal * graphs. Query operations on this graph "read through" to the backing graph, * and attempts to modify this graph result in an * UnsupportedOperationException. * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods. This graph will be serializable if the backing * graph is serializable.

    * * @author Barak Naveh * @since Jul 24, 2003 */ public class UnmodifiableGraph extends GraphDelegator implements Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3544957670722713913L; private static final String UNMODIFIABLE = "this graph is unmodifiable"; //~ Constructors ----------------------------------------------------------- /** * Creates a new unmodifiable graph based on the specified backing graph. * * @param g the backing graph on which an unmodifiable graph is to be * created. */ public UnmodifiableGraph(Graph g) { super(g); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllEdges(Collection) */ public boolean removeAllEdges(Collection edges) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllEdges(Object, Object) */ public Set removeAllEdges(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllVertices(Collection) */ public boolean removeAllVertices(Collection vertices) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeEdge(Object) */ public boolean removeEdge(E e) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeVertex(Object) */ public boolean removeVertex(V v) { throw new UnsupportedOperationException(UNMODIFIABLE); } } // End UnmodifiableGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedWeightedMultigraph.java0000644000175000017500000000531611706124626025623 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------- * DirectedWeightedMultigraph.java * ------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DirectedWeightedMultigraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Jun-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed weighted multigraph. A directed weighted multigraph is a * non-simple directed graph in which loops and multiple edges between any two * vertices are permitted, and edges have weights. */ public class DirectedWeightedMultigraph extends DirectedMultigraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 4049071636005206066L; //~ Constructors ----------------------------------------------------------- /** * Creates a new directed weighted multigraph. * * @param edgeClass class on which to base factory for edges */ public DirectedWeightedMultigraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new directed weighted multigraph with the specified edge * factory. * * @param ef the edge factory of the new graph. */ public DirectedWeightedMultigraph(EdgeFactory ef) { super(ef); } } // End DirectedWeightedMultigraph.java jgrapht-0.8.3/src/org/jgrapht/graph/SimpleDirectedWeightedGraph.java0000644000175000017500000000523411706124626025721 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------------- * SimpleDirectedWeightedGraph.java * -------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: SimpleDirectedWeightedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A simple directed weighted graph. A simple directed weighted graph is a * simple directed graph for which edges are assigned weights. */ public class SimpleDirectedWeightedGraph extends SimpleDirectedGraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3904960841681220919L; //~ Constructors ----------------------------------------------------------- /** * Creates a new simple directed weighted graph with the specified edge * factory. * * @param ef the edge factory of the new graph. */ public SimpleDirectedWeightedGraph(EdgeFactory ef) { super(ef); } /** * Creates a new simple directed weighted graph. * * @param edgeClass class on which to base factory for edges */ public SimpleDirectedWeightedGraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } } // End SimpleDirectedWeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/AsUnweightedDirectedGraph.java0000644000175000017500000000635611706124626025404 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * AsUnweightedGraph.java * ---------------------- * (C) Copyright 2007-2008, by Lucas J. Scharenbroich and Contributors. * * Original Author: Lucas J. Scharenbroich * Contributor(s): John V. Sichi * * $Id: AsUnweightedDirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 7-Sep-2007 : Initial revision (LJS); * */ package org.jgrapht.graph; import java.io.*; import org.jgrapht.*; /** * An unweighted view of the backing weighted graph specified in the * constructor. This graph allows modules to apply algorithms designed for * unweighted graphs to a weighted graph by simply ignoring edge weights. Query * operations on this graph "read through" to the backing graph. Vertex * addition/removal and edge addition/removal are all supported (and immediately * reflected in the backing graph). * *

    Note that edges returned by this graph's accessors are really just the * edges of the underlying directed graph.

    * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods. This graph will be serializable if the backing * graph is serializable.

    * * @author Lucas J. Scharenbroich * @since Sep 7, 2007 */ public class AsUnweightedDirectedGraph extends GraphDelegator implements Serializable, DirectedGraph { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = -4320818446777715312L; //~ Constructors ----------------------------------------------------------- /** * Constructor for AsUnweightedGraph. * * @param g the backing graph over which an unweighted view is to be * created. */ public AsUnweightedDirectedGraph(DirectedGraph g) { super(g); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getEdgeWeight */ public double getEdgeWeight(E e) { return WeightedGraph.DEFAULT_EDGE_WEIGHT; } } // End AsUnweightedDirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DefaultGraphMapping.java0000644000175000017500000000765011706124626024247 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * DefaultGraphMapping.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: DefaultGraphMapping.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * Implementation of the GraphMapping interface. The performance of * getVertex/EdgeCorrespondence is based on the performance of the * concrete Map class which is passed in the constructor. For example, using * hashmaps will provide O(1) performence. * * @author Assaf * @since Jul 30, 2005 */ public class DefaultGraphMapping implements GraphMapping { //~ Instance fields -------------------------------------------------------- private Map graphMappingForward; private Map graphMappingReverse; private Graph graph1; private Graph graph2; //~ Constructors ----------------------------------------------------------- /** * The maps themselves are used. There is no defensive-copy. Assumption: The * key and value in the mappings are of valid graph objects. It is not * checked. * * @param g1ToG2 * @param g2ToG1 * @param g1 * @param g2 */ public DefaultGraphMapping( Map g1ToG2, Map g2ToG1, Graph g1, Graph g2) { this.graph1 = g1; this.graph2 = g2; this.graphMappingForward = g1ToG2; this.graphMappingReverse = g2ToG1; } //~ Methods ---------------------------------------------------------------- public E getEdgeCorrespondence(E currEdge, boolean forward) { Graph sourceGraph, targetGraph; if (forward) { sourceGraph = this.graph1; targetGraph = this.graph2; } else { sourceGraph = this.graph2; targetGraph = this.graph1; } V mappedSourceVertex = getVertexCorrespondence( sourceGraph.getEdgeSource(currEdge), forward); V mappedTargetVertex = getVertexCorrespondence( sourceGraph.getEdgeTarget(currEdge), forward); if ((mappedSourceVertex == null) || (mappedTargetVertex == null)) { return null; } else { return targetGraph.getEdge( mappedSourceVertex, mappedTargetVertex); } } public V getVertexCorrespondence( V keyVertex, boolean forward) { Map graphMapping; if (forward) { graphMapping = graphMappingForward; } else { graphMapping = graphMappingReverse; } return graphMapping.get(keyVertex); } } // End DefaultGraphMapping.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedMultigraph.java0000644000175000017500000000512311706124626024136 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * DirectedMultigraph.java * ----------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DirectedMultigraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed multigraph. A directed multigraph is a non-simple directed graph * in which loops and multiple edges between any two vertices are permitted. */ public class DirectedMultigraph extends AbstractBaseGraph implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3258408413590599219L; //~ Constructors ----------------------------------------------------------- /** * Creates a new directed multigraph. * * @param edgeClass class on which to base factory for edges */ public DirectedMultigraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new directed multigraph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public DirectedMultigraph(EdgeFactory ef) { super(ef, true, true); } } // End DirectedMultigraph.java jgrapht-0.8.3/src/org/jgrapht/graph/GraphPathImpl.java0000644000175000017500000000571511706124626023065 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * GraphPathImpl.java * ---------------- * (C) Copyright 2009-2009, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * * $Id: GraphPathImpl.java 689 2009-07-04 06:40:29Z perfecthash $ * * Changes * ------- * 03-Jul-2009 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * GraphPathImpl is a default implementation of {@link GraphPath}. * * @author John Sichi * @version $Id: GraphPathImpl.java 689 2009-07-04 06:40:29Z perfecthash $ */ public class GraphPathImpl implements GraphPath { //~ Instance fields -------------------------------------------------------- private Graph graph; private List edgeList; private V startVertex; private V endVertex; private double weight; //~ Constructors ----------------------------------------------------------- public GraphPathImpl( Graph graph, V startVertex, V endVertex, List edgeList, double weight) { this.graph = graph; this.startVertex = startVertex; this.endVertex = endVertex; this.edgeList = edgeList; this.weight = weight; } //~ Methods ---------------------------------------------------------------- // implement GraphPath public Graph getGraph() { return graph; } // implement GraphPath public V getStartVertex() { return startVertex; } // implement GraphPath public V getEndVertex() { return endVertex; } // implement GraphPath public List getEdgeList() { return edgeList; } // implement GraphPath public double getWeight() { return weight; } // override Object public String toString() { return edgeList.toString(); } } // End GraphPathImpl.java jgrapht-0.8.3/src/org/jgrapht/graph/IntrusiveEdge.java0000644000175000017500000000456311706124626023142 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * IntrusiveEdge.java * ------------------- * (C) Copyright 2006-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: IntrusiveEdge.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 28-May-2006 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.io.*; /** * IntrusiveEdge encapsulates the internals for the default edge implementation. * It is not intended to be referenced directly (which is why it's not public); * use DefaultEdge for that. * * @author John V. Sichi */ class IntrusiveEdge implements Cloneable, Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3258408452177932855L; //~ Instance fields -------------------------------------------------------- Object source; Object target; //~ Methods ---------------------------------------------------------------- /** * @see Object#clone() */ public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { // shouldn't happen as we are Cloneable throw new InternalError(); } } } // End IntrusiveEdge.java jgrapht-0.8.3/src/org/jgrapht/graph/DefaultDirectedWeightedGraph.java0000644000175000017500000000540111706124626026050 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------------- * DefaultDirectedWeightedGraph.java * --------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DefaultDirectedWeightedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Jun-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed weighted graph. A directed weighted graph is a non-simple directed * graph in which multiple edges between any two vertices are not * permitted, but loops are. The graph has weights on its edges. * * @see DefaultDirectedGraph */ public class DefaultDirectedWeightedGraph extends DefaultDirectedGraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3761405317841171513L; //~ Constructors ----------------------------------------------------------- /** * Creates a new directed weighted graph. * * @param edgeClass class on which to base factory for edges */ public DefaultDirectedWeightedGraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new directed weighted graph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public DefaultDirectedWeightedGraph(EdgeFactory ef) { super(ef); } } // End DefaultDirectedWeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ClassBasedEdgeFactory.java0000644000175000017500000000545511706124626024507 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * ClassBasedEdgeFactory.java * ------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: ClassBasedEdgeFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 04-Aug-2003 : Renamed from EdgeFactoryFactory & made utility class (BN); * 03-Nov-2003 : Made edge factories serializable (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.io.*; import org.jgrapht.*; /** * An {@link EdgeFactory} for producing edges by using a class as a factory. * * @author Barak Naveh * @since Jul 14, 2003 */ public class ClassBasedEdgeFactory implements EdgeFactory, Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3618135658586388792L; //~ Instance fields -------------------------------------------------------- private final Class edgeClass; //~ Constructors ----------------------------------------------------------- public ClassBasedEdgeFactory(Class edgeClass) { this.edgeClass = edgeClass; } //~ Methods ---------------------------------------------------------------- /** * @see EdgeFactory#createEdge(Object, Object) */ public E createEdge(V source, V target) { try { return edgeClass.newInstance(); } catch (Exception ex) { throw new RuntimeException("Edge factory failed", ex); } } } // End ClassBasedEdgeFactory.java jgrapht-0.8.3/src/org/jgrapht/graph/package.html0000644000175000017500000000017211706124626021773 0ustar giovannigiovanni Implementations of various graphs. jgrapht-0.8.3/src/org/jgrapht/graph/DefaultDirectedGraph.java0000644000175000017500000000531011706124626024366 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * DefaultDirectedGraph.java * ------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DefaultDirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed graph. A default directed graph is a non-simple directed graph in * which multiple edges between any two vertices are not permitted, but * loops are. * *

    prefixed 'Default' to avoid name collision with the DirectedGraph * interface.

    */ public class DefaultDirectedGraph extends AbstractBaseGraph implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3544953246956466230L; //~ Constructors ----------------------------------------------------------- /** * Creates a new directed graph. * * @param edgeClass class on which to base factory for edges */ public DefaultDirectedGraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new directed graph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public DefaultDirectedGraph(EdgeFactory ef) { super(ef, false, true); } } // End DefaultDirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/Multigraph.java0000644000175000017500000000523011706124626022471 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------- * Multigraph.java * --------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: Multigraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A multigraph. A multigraph is a non-simple undirected graph in which no loops * are permitted, but multiple edges between any two vertices are. If you're * unsure about multigraphs, see: * http://mathworld.wolfram.com/Multigraph.html. */ public class Multigraph extends AbstractBaseGraph implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3257001055819871795L; //~ Constructors ----------------------------------------------------------- /** * Creates a new multigraph. * * @param edgeClass class on which to base factory for edges */ public Multigraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new multigraph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public Multigraph(EdgeFactory ef) { super(ef, true, false); } } // End Multigraph.java jgrapht-0.8.3/src/org/jgrapht/graph/WeightedPseudograph.java0000644000175000017500000000542211706124626024322 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------ * WeightedPseudograph.java * ------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: WeightedPseudograph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A weighted pseudograph. A weighted pseudograph is a non-simple undirected * graph in which both graph loops and multiple edges are permitted. The edges * of a weighted pseudograph have weights. If you're unsure about pseudographs, * see: * http://mathworld.wolfram.com/Pseudograph.html. */ public class WeightedPseudograph extends Pseudograph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3257290244524356152L; //~ Constructors ----------------------------------------------------------- /** * Creates a new weighted pseudograph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public WeightedPseudograph(EdgeFactory ef) { super(ef); } /** * Creates a new weighted pseudograph. * * @param edgeClass class on which to base factory for edges */ public WeightedPseudograph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } } // End WeightedPseudograph.java jgrapht-0.8.3/src/org/jgrapht/graph/EdgeSetFactory.java0000644000175000017500000000472311706124626023233 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * EdgeSetFactory.java * ---------------- * (C) Copyright 2005-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Christian Hammer * * $Id: EdgeSetFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 01-Jun-2005 : Initial revision (JVS); * 06-Aug-2005 : Made generic (CH); * 07-May-2006 : Renamed and changed from List to Set (JVS); * */ package org.jgrapht.graph; import java.util.*; /** * A factory for edge sets. This interface allows the creator of a graph to * choose the {@link java.util.Set} implementation used internally by the graph * to maintain sets of edges. This provides control over performance tradeoffs * between memory and CPU usage. * * @author John V. Sichi */ public interface EdgeSetFactory { //~ Methods ---------------------------------------------------------------- /** * Create a new edge set for a particular vertex. * * @param vertex the vertex for which the edge set is being created; * sophisticated factories may be able to use this information to choose an * optimal set representation (e.g. ArrayUnenforcedSet for a vertex expected * to have low degree, and LinkedHashSet for a vertex expected to have high * degree) * * @return new set */ public Set createEdgeSet(V vertex); } // End EdgeSetFactory.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedWeightedSubgraph.java0000644000175000017500000000532511706124626025262 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * DirectedWeightedSubgraph.java * ----------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DirectedWeightedSubgraph.java 755 2012-01-18 23:50:37Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * A directed weighted graph that is a subgraph on other graph. * * @see Subgraph */ public class DirectedWeightedSubgraph extends DirectedSubgraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3905799799168250680L; //~ Constructors ----------------------------------------------------------- /** * Creates a new weighted directed subgraph. * * @param base the base (backing) graph on which the subgraph will be based. * @param vertexSubset vertices to include in the subgraph. If * null then all vertices are included. * @param edgeSubset edges to in include in the subgraph. If * null then all the edges whose vertices found in the graph * are included. */ public DirectedWeightedSubgraph( WeightedGraph base, Set vertexSubset, Set edgeSubset) { super((DirectedGraph) base, vertexSubset, edgeSubset); } } // End DirectedWeightedSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/SimpleDirectedGraph.java0000644000175000017500000000514211706124626024236 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------ * SimpleDirectedGraph.java * ------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: SimpleDirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A simple directed graph. A simple directed graph is a directed graph in which * neither multiple edges between any two vertices nor loops are permitted. */ public class SimpleDirectedGraph extends AbstractBaseGraph implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 4049358608472879671L; //~ Constructors ----------------------------------------------------------- /** * Creates a new simple directed graph. * * @param edgeClass class on which to base factory for edges */ public SimpleDirectedGraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new simple directed graph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public SimpleDirectedGraph(EdgeFactory ef) { super(ef, false, false); } } // End SimpleDirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ListenableDirectedGraph.java0000644000175000017500000000504411706124626025070 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------------- * ListenableDirectedGraph.java * ---------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: ListenableDirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed graph which is also {@link org.jgrapht.ListenableGraph}. * * @see DefaultListenableGraph */ public class ListenableDirectedGraph extends DefaultListenableGraph implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3257571698126368824L; //~ Constructors ----------------------------------------------------------- /** * Creates a new listenable directed graph. * * @param edgeClass class on which to base factory for edges */ public ListenableDirectedGraph(Class edgeClass) { this(new DefaultDirectedGraph(edgeClass)); } /** * Creates a new listenable directed graph. * * @param base the backing graph. */ public ListenableDirectedGraph(DirectedGraph base) { super(base); } } // End ListenableDirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ListenableDirectedWeightedGraph.java0000644000175000017500000000524111706124626026550 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------------ * ListenableDirectedWeightedGraph.java * ------------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: ListenableDirectedWeightedGraph.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Jun-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed weighted graph which is also {@link org.jgrapht.ListenableGraph}. * * @see DefaultListenableGraph */ public class ListenableDirectedWeightedGraph extends ListenableDirectedGraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3977582476627621938L; //~ Constructors ----------------------------------------------------------- /** * Creates a new listenable directed weighted graph. * * @param edgeClass class on which to base factory for edges */ public ListenableDirectedWeightedGraph(Class edgeClass) { this(new DefaultDirectedWeightedGraph(edgeClass)); } /** * Creates a new listenable directed weighted graph. * * @param base the backing graph. */ public ListenableDirectedWeightedGraph(WeightedGraph base) { super((DirectedGraph) base); } } // End ListenableDirectedWeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DefaultEdge.java0000644000175000017500000000513111706124626022526 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * DefaultEdge.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DefaultEdge.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 10-Aug-2003 : General edge refactoring (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A default implementation for edges in a {@link Graph}. * * @author Barak Naveh * @since Jul 14, 2003 */ public class DefaultEdge extends IntrusiveEdge { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3258408452177932855L; //~ Methods ---------------------------------------------------------------- /** * Retrieves the source of this edge. This is protected, for use by * subclasses only (e.g. for implementing toString). * * @return source of this edge */ protected Object getSource() { return source; } /** * Retrieves the target of this edge. This is protected, for use by * subclasses only (e.g. for implementing toString). * * @return target of this edge */ protected Object getTarget() { return target; } public String toString() { return "(" + source + " : " + target + ")"; } } // End DefaultEdge.java jgrapht-0.8.3/src/org/jgrapht/graph/UndirectedWeightedSubgraph.java0000644000175000017500000000525111706124626025623 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------- * UndirectedWeightedSubgraph.java * ------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: UndirectedWeightedSubgraph.java 755 2012-01-18 23:50:37Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * An undirected weighted graph that is a subgraph on other graph. * * @see Subgraph */ public class UndirectedWeightedSubgraph extends UndirectedSubgraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3689346615735236409L; //~ Constructors ----------------------------------------------------------- /** * Creates a new undirected weighted subgraph. * * @param base the base (backing) graph on which the subgraph will be based. * @param vertexSubset vertices to include in the subgraph. If * null then all vertices are included. * @param edgeSubset edges to in include in the subgraph. If * null then all the edges whose vertices found in the graph * are included. */ public UndirectedWeightedSubgraph( WeightedGraph base, Set vertexSubset, Set edgeSubset) { super((UndirectedGraph) base, vertexSubset, edgeSubset); } } // End UndirectedWeightedSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/GraphDelegator.java0000644000175000017500000001614511706124626023254 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * GraphDelegator.java * ------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphDelegator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; /** * A graph backed by the the graph specified at the constructor, which delegates * all its methods to the backing graph. Operations on this graph "pass through" * to the to the backing graph. Any modification made to this graph or the * backing graph is reflected by the other. * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods.

    * *

    This class is mostly used as a base for extending subclasses.

    * * @author Barak Naveh * @since Jul 20, 2003 */ public class GraphDelegator extends AbstractGraph implements Graph, Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3257005445226181425L; //~ Instance fields -------------------------------------------------------- /** * The graph to which operations are delegated. */ private Graph delegate; //~ Constructors ----------------------------------------------------------- /** * Constructor for GraphDelegator. * * @param g the backing graph (the delegate). * * @throws IllegalArgumentException iff g==null */ public GraphDelegator(Graph g) { super(); if (g == null) { throw new IllegalArgumentException("g must not be null."); } delegate = g; } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { return delegate.getAllEdges(sourceVertex, targetVertex); } /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { return delegate.getEdge(sourceVertex, targetVertex); } /** * @see Graph#getEdgeFactory() */ public EdgeFactory getEdgeFactory() { return delegate.getEdgeFactory(); } /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { return delegate.addEdge(sourceVertex, targetVertex); } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { return delegate.addEdge(sourceVertex, targetVertex, e); } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { return delegate.addVertex(v); } /** * @see Graph#containsEdge(Object) */ public boolean containsEdge(E e) { return delegate.containsEdge(e); } /** * @see Graph#containsVertex(Object) */ public boolean containsVertex(V v) { return delegate.containsVertex(v); } /** * @see UndirectedGraph#degreeOf(Object) */ public int degreeOf(V vertex) { return ((UndirectedGraph) delegate).degreeOf(vertex); } /** * @see Graph#edgeSet() */ public Set edgeSet() { return delegate.edgeSet(); } /** * @see Graph#edgesOf(Object) */ public Set edgesOf(V vertex) { return delegate.edgesOf(vertex); } /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { return ((DirectedGraph) delegate).inDegreeOf(vertex); } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { return ((DirectedGraph) delegate).incomingEdgesOf(vertex); } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { return ((DirectedGraph) delegate).outDegreeOf(vertex); } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { return ((DirectedGraph) delegate).outgoingEdgesOf(vertex); } /** * @see Graph#removeEdge(Object) */ public boolean removeEdge(E e) { return delegate.removeEdge(e); } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { return delegate.removeEdge(sourceVertex, targetVertex); } /** * @see Graph#removeVertex(Object) */ public boolean removeVertex(V v) { return delegate.removeVertex(v); } /** * @see java.lang.Object#toString() */ public String toString() { return delegate.toString(); } /** * @see Graph#vertexSet() */ public Set vertexSet() { return delegate.vertexSet(); } /** * @see Graph#getEdgeSource(Object) */ public V getEdgeSource(E e) { return delegate.getEdgeSource(e); } /** * @see Graph#getEdgeTarget(Object) */ public V getEdgeTarget(E e) { return delegate.getEdgeTarget(e); } /** * @see Graph#getEdgeWeight(Object) */ public double getEdgeWeight(E e) { return delegate.getEdgeWeight(e); } /** * @see WeightedGraph#setEdgeWeight(Object, double) */ public void setEdgeWeight(E e, double weight) { ((WeightedGraph) delegate).setEdgeWeight(e, weight); } } // End GraphDelegator.java jgrapht-0.8.3/src/org/jgrapht/graph/UnmodifiableDirectedGraph.java0000644000175000017500000000443011706124626025402 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * UnmodifiableDirectedGraph.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: UnmodifiableDirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed graph that cannot be modified. * * @see UnmodifiableGraph */ public class UnmodifiableDirectedGraph extends UnmodifiableGraph implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3978701783725913906L; //~ Constructors ----------------------------------------------------------- /** * Creates a new unmodifiable directed graph based on the specified backing * graph. * * @param g the backing graph on which an unmodifiable graph is to be * created. */ public UnmodifiableDirectedGraph(DirectedGraph g) { super(g); } } // End UnmodifiableDirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedMaskSubgraph.java0000644000175000017500000000365711706124626024423 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * DirectedMaskSubgraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: DirectedMaskSubgraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed graph that is a {@link MaskSubgraph} on another graph. * * @author Guillaume Boulmier * @since July 5, 2007 */ public class DirectedMaskSubgraph extends MaskSubgraph implements DirectedGraph { //~ Constructors ----------------------------------------------------------- public DirectedMaskSubgraph( DirectedGraph base, MaskFunctor mask) { super(base, mask); } } // End DirectedMaskSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/WeightedMultigraph.java0000644000175000017500000000542711706124626024162 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * WeightedMultigraph.java * ----------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: WeightedMultigraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A weighted multigraph. A weighted multigraph is a non-simple undirected graph * in which no loops are permitted, but multiple edges between any two vertices * are. The edges of a weighted multigraph have weights. If you're unsure about * multigraphs, see: * http://mathworld.wolfram.com/Multigraph.html. */ public class WeightedMultigraph extends Multigraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3544671793370640696L; //~ Constructors ----------------------------------------------------------- /** * Creates a new weighted multigraph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public WeightedMultigraph(EdgeFactory ef) { super(ef); } /** * Creates a new weighted multigraph. * * @param edgeClass class on which to base factory for edges */ public WeightedMultigraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } } // End WeightedMultigraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DefaultWeightedEdge.java0000644000175000017500000000457611706124626024223 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * DefaultWeightedEdge.java * ---------------- * (C) Copyright 2006-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: DefaultWeightedEdge.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 29-May-2006 : Initial revision (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A default implementation for edges in a {@link WeightedGraph}. All access to * the weight of an edge must go through the graph interface, which is why this * class doesn't expose any public methods. * * @author John V. Sichi */ public class DefaultWeightedEdge extends DefaultEdge { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 229708706467350994L; //~ Instance fields -------------------------------------------------------- double weight = WeightedGraph.DEFAULT_EDGE_WEIGHT; //~ Methods ---------------------------------------------------------------- /** * Retrieves the weight of this edge. This is protected, for use by * subclasses only (e.g. for implementing toString). * * @return weight of this edge */ protected double getWeight() { return weight; } } // End DefaultWeightedEdge.java jgrapht-0.8.3/src/org/jgrapht/graph/Pseudograph.java0000644000175000017500000000521511706124626022641 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * Pseudograph.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: Pseudograph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A pseudograph. A pseudograph is a non-simple undirected graph in which both * graph loops and multiple edges are permitted. If you're unsure about * pseudographs, see: * http://mathworld.wolfram.com/Pseudograph.html. */ public class Pseudograph extends AbstractBaseGraph implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3833183614484755253L; //~ Constructors ----------------------------------------------------------- /** * Creates a new pseudograph. * * @param edgeClass class on which to base factory for edges */ public Pseudograph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * Creates a new pseudograph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public Pseudograph(EdgeFactory ef) { super(ef, true, true); } } // End Pseudograph.java jgrapht-0.8.3/src/org/jgrapht/graph/SimpleWeightedGraph.java0000644000175000017500000000504011706124626024250 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------ * SimpleWeightedGraph.java * ------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: SimpleWeightedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A simple weighted graph. A simple weighted graph is a simple graph for which * edges are assigned weights. */ public class SimpleWeightedGraph extends SimpleGraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3906088949100655922L; //~ Constructors ----------------------------------------------------------- /** * Creates a new simple weighted graph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public SimpleWeightedGraph(EdgeFactory ef) { super(ef); } /** * Creates a new simple weighted graph. * * @param edgeClass class on which to base factory for edges */ public SimpleWeightedGraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } } // End SimpleWeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ParanoidGraph.java0000644000175000017500000000643511706124626023104 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * ParanoidGraph.java * ------------------- * (C) Copyright 2007-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: ParanoidGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 8-Nov-2007 : Initial revision (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * ParanoidGraph provides a way to verify that objects added to a graph obey the * standard equals/hashCode contract. It can be used to wrap an underlying graph * to be verified. Note that the verification is very expensive, so * ParanoidGraph should only be used during debugging. * * @author John Sichi * @version $Id: ParanoidGraph.java 645 2008-09-30 19:44:48Z perfecthash $ */ public class ParanoidGraph extends GraphDelegator { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = 5075284167422166539L; //~ Constructors ----------------------------------------------------------- public ParanoidGraph(Graph g) { super(g); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { verifyAdd(edgeSet(), e); return super.addEdge(sourceVertex, targetVertex, e); } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { verifyAdd(vertexSet(), v); return super.addVertex(v); } private static void verifyAdd(Set set, T t) { for (T o : set) { if (o == t) { continue; } if (o.equals(t) && (o.hashCode() != t.hashCode())) { throw new IllegalArgumentException( "ParanoidGraph detected objects " + "o1 (hashCode=" + o.hashCode() + ") and o2 (hashCode=" + t.hashCode() + ") where o1.equals(o2) " + "but o1.hashCode() != o2.hashCode()"); } } } } // End ParanoidGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/AsUndirectedGraph.java0000644000175000017500000001445711706124626023724 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * AsUndirectedGraph.java * ---------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Christian Hammer * * $Id: AsUndirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 14-Aug-2003 : Initial revision (JVS); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * An undirected view of the backing directed graph specified in the * constructor. This graph allows modules to apply algorithms designed for * undirected graphs to a directed graph by simply ignoring edge direction. If * the backing directed graph is an oriented graph, * then the view will be a simple graph; otherwise, it will be a multigraph. * Query operations on this graph "read through" to the backing graph. Attempts * to add edges will result in an UnsupportedOperationException, * but vertex addition/removal and edge removal are all supported (and * immediately reflected in the backing graph). * *

    Note that edges returned by this graph's accessors are really just the * edges of the underlying directed graph. Since there is no interface * distinction between directed and undirected edges, this detail should be * irrelevant to algorithms.

    * *

    This graph does not pass the hashCode and equals operations through * to the backing graph, but relies on Object's equals and * hashCode methods. This graph will be serializable if the backing * graph is serializable.

    * * @author John V. Sichi * @since Aug 14, 2003 */ public class AsUndirectedGraph extends GraphDelegator implements Serializable, UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3257845485078065462L; // @todo renew private static final String NO_EDGE_ADD = "this graph does not support edge addition"; private static final String UNDIRECTED = "this graph only supports undirected operations"; //~ Constructors ----------------------------------------------------------- /** * Constructor for AsUndirectedGraph. * * @param g the backing directed graph over which an undirected view is to * be created. */ public AsUndirectedGraph(DirectedGraph g) { super(g); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { Set forwardList = super.getAllEdges(sourceVertex, targetVertex); if (sourceVertex.equals(targetVertex)) { // avoid duplicating loops return forwardList; } Set reverseList = super.getAllEdges(targetVertex, sourceVertex); Set list = new ArrayUnenforcedSet( forwardList.size() + reverseList.size()); list.addAll(forwardList); list.addAll(reverseList); return list; } /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { E edge = super.getEdge(sourceVertex, targetVertex); if (edge != null) { return edge; } // try the other direction return super.getEdge(targetVertex, sourceVertex); } /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(NO_EDGE_ADD); } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { throw new UnsupportedOperationException(NO_EDGE_ADD); } /** * @see UndirectedGraph#degreeOf(Object) */ public int degreeOf(V vertex) { // this counts loops twice, which is consistent with AbstractBaseGraph return super.inDegreeOf(vertex) + super.outDegreeOf(vertex); } /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { throw new UnsupportedOperationException(UNDIRECTED); } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { throw new UnsupportedOperationException(UNDIRECTED); } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { throw new UnsupportedOperationException(UNDIRECTED); } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { throw new UnsupportedOperationException(UNDIRECTED); } /** * @see AbstractBaseGraph#toString() */ public String toString() { return super.toStringFromSets(vertexSet(), edgeSet(), false); } } // End AsUndirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/MaskVertexSet.java0000644000175000017500000000713711706124626023132 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * MaskVertexSet.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: MaskVertexSet.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.util.*; import org.jgrapht.util.PrefetchIterator.*; /** * Helper for {@link MaskSubgraph}. * * @author Guillaume Boulmier * @since July 5, 2007 */ class MaskVertexSet extends AbstractSet { //~ Instance fields -------------------------------------------------------- private MaskFunctor mask; private int size; private Set vertexSet; private transient TypeUtil vertexTypeDecl = null; //~ Constructors ----------------------------------------------------------- public MaskVertexSet(Set vertexSet, MaskFunctor mask) { this.vertexSet = vertexSet; this.mask = mask; this.size = -1; } //~ Methods ---------------------------------------------------------------- /** * @see java.util.Collection#contains(java.lang.Object) */ public boolean contains(Object o) { return !this.mask.isVertexMasked(TypeUtil.uncheckedCast(o, vertexTypeDecl)) && this.vertexSet.contains(o); } /** * @see java.util.Set#iterator() */ public Iterator iterator() { return new PrefetchIterator(new MaskVertexSetNextElementFunctor()); } /** * @see java.util.Set#size() */ public int size() { if (this.size == -1) { this.size = 0; for (Iterator iter = iterator(); iter.hasNext();) { iter.next(); this.size++; } } return this.size; } //~ Inner Classes ---------------------------------------------------------- private class MaskVertexSetNextElementFunctor implements NextElementFunctor { private Iterator iter; public MaskVertexSetNextElementFunctor() { this.iter = MaskVertexSet.this.vertexSet.iterator(); } public V nextElement() throws NoSuchElementException { V element = this.iter.next(); while (MaskVertexSet.this.mask.isVertexMasked(element)) { element = this.iter.next(); } return element; } } } // End MaskVertexSet.java jgrapht-0.8.3/src/org/jgrapht/graph/Subgraph.java0000644000175000017500000003745111706124626022142 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------- * Subgraph.java * ------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: Subgraph.java 755 2012-01-18 23:50:37Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 26-Jul-2003 : Accurate constructors to avoid casting problems (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 23-Oct-2003 : Allowed non-listenable graph as base (BN); * 07-Feb-2004 : Enabled serialization (BN); * 11-Mar-2004 : Made generic (CH); * 15-Mar-2004 : Integrity is now checked using Maps (CH); * 20-Mar-2004 : Cancelled verification of element identity to base graph (BN); * 21-Sep-2004 : Added induced subgraph (who?) * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.event.*; import org.jgrapht.util.*; /** * A subgraph is a graph that has a subset of vertices and a subset of edges * with respect to some base graph. More formally, a subgraph G(V,E) that is * based on a base graph Gb(Vb,Eb) satisfies the following subgraph * property: V is a subset of Vb and E is a subset of Eb. Other than * this property, a subgraph is a graph with any respect and fully complies with * the Graph interface. * *

    If the base graph is a {@link org.jgrapht.ListenableGraph}, the subgraph * listens on the base graph and guarantees the subgraph property. If an edge or * a vertex is removed from the base graph, it is automatically removed from the * subgraph. Subgraph listeners are informed on such removal only if it results * in a cascaded removal from the subgraph. If the subgraph has been created as * an induced subgraph it also keeps track of edges being added to its vertices. * If vertices are added to the base graph, the subgraph remains unaffected.

    * *

    If the base graph is not a ListenableGraph, then the subgraph * property cannot be guaranteed. If edges or vertices are removed from the base * graph, they are not removed from the subgraph.

    * *

    Modifications to Subgraph are allowed as long as the subgraph property is * maintained. Addition of vertices or edges are allowed as long as they also * exist in the base graph. Removal of vertices or edges is always allowed. The * base graph is never affected by any modification made to the * subgraph.

    * *

    A subgraph may provide a "live-window" on a base graph, so that changes * made to its vertices or edges are immediately reflected in the base graph, * and vice versa. For that to happen, vertices and edges added to the subgraph * must be identical (that is, reference-equal and not only value-equal) * to their respective ones in the base graph. Previous versions of this class * enforced such identity, at a severe performance cost. Currently it is no * longer enforced. If you want to achieve a "live-window"functionality, your * safest tactics would be to NOT override the equals() methods of * your vertices and edges. If you use a class that has already overridden the * equals() method, such as String, than you can use a * wrapper around it, or else use it directly but exercise a great care to avoid * having different-but-equal instances in the subgraph and the base graph.

    * *

    This graph implementation guarantees deterministic vertex and edge set * ordering (via {@link LinkedHashSet}).

    * * @author Barak Naveh * @see Graph * @see Set * @since Jul 18, 2003 */ public class Subgraph> extends AbstractGraph implements Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3208313055169665387L; private static final String NO_SUCH_EDGE_IN_BASE = "no such edge in base graph"; private static final String NO_SUCH_VERTEX_IN_BASE = "no such vertex in base graph"; //~ Instance fields -------------------------------------------------------- // Set edgeSet = new LinkedHashSet(); // friendly to improve performance Set vertexSet = new LinkedHashSet(); // friendly to improve // performance // private transient Set unmodifiableEdgeSet = null; private transient Set unmodifiableVertexSet = null; private G base; private boolean isInduced = false; //~ Constructors ----------------------------------------------------------- /** * Creates a new Subgraph. * * @param base the base (backing) graph on which the subgraph will be based. * @param vertexSubset vertices to include in the subgraph. If * null then all vertices are included. * @param edgeSubset edges to in include in the subgraph. If * null then all the edges whose vertices found in the graph * are included. */ public Subgraph(G base, Set vertexSubset, Set edgeSubset) { super(); this.base = base; if (edgeSubset == null) { isInduced = true; } if (base instanceof ListenableGraph) { ((ListenableGraph) base).addGraphListener( new BaseGraphListener()); } addVerticesUsingFilter(base.vertexSet(), vertexSubset); addEdgesUsingFilter(base.edgeSet(), edgeSubset); } /** * Creates a new induced Subgraph. The subgraph will keep track of edges * being added to its vertex subset as well as deletion of edges and * vertices. If base it not listenable, this is identical to the call * Subgraph(base, vertexSubset, null) . * * @param base the base (backing) graph on which the subgraph will be based. * @param vertexSubset vertices to include in the subgraph. If * null then all vertices are included. */ public Subgraph(G base, Set vertexSubset) { this(base, vertexSubset, null); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { Set edges = null; if (containsVertex(sourceVertex) && containsVertex(targetVertex)) { edges = new ArrayUnenforcedSet(); Set baseEdges = base.getAllEdges(sourceVertex, targetVertex); for (Iterator iter = baseEdges.iterator(); iter.hasNext();) { E e = iter.next(); if (edgeSet.contains(e)) { // add if subgraph also contains // it edges.add(e); } } } return edges; } /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { Set edges = getAllEdges(sourceVertex, targetVertex); if ((edges == null) || edges.isEmpty()) { return null; } else { return edges.iterator().next(); } } /** * @see Graph#getEdgeFactory() */ public EdgeFactory getEdgeFactory() { return base.getEdgeFactory(); } /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { assertVertexExist(sourceVertex); assertVertexExist(targetVertex); if (!base.containsEdge(sourceVertex, targetVertex)) { throw new IllegalArgumentException(NO_SUCH_EDGE_IN_BASE); } Set edges = base.getAllEdges(sourceVertex, targetVertex); for (Iterator iter = edges.iterator(); iter.hasNext();) { E e = iter.next(); if (!containsEdge(e)) { edgeSet.add(e); return e; } } return null; } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { if (e == null) { throw new NullPointerException(); } if (!base.containsEdge(e)) { throw new IllegalArgumentException(NO_SUCH_EDGE_IN_BASE); } assertVertexExist(sourceVertex); assertVertexExist(targetVertex); assert (base.getEdgeSource(e) == sourceVertex); assert (base.getEdgeTarget(e) == targetVertex); if (containsEdge(e)) { return false; } else { edgeSet.add(e); return true; } } /** * Adds the specified vertex to this subgraph. * * @param v the vertex to be added. * * @return true if the vertex was added, otherwise * false. * * @throws NullPointerException * @throws IllegalArgumentException * * @see Subgraph * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { if (v == null) { throw new NullPointerException(); } if (!base.containsVertex(v)) { throw new IllegalArgumentException(NO_SUCH_VERTEX_IN_BASE); } if (containsVertex(v)) { return false; } else { vertexSet.add(v); return true; } } /** * @see Graph#containsEdge(Object) */ public boolean containsEdge(E e) { return edgeSet.contains(e); } /** * @see Graph#containsVertex(Object) */ public boolean containsVertex(V v) { return vertexSet.contains(v); } /** * @see Graph#edgeSet() */ public Set edgeSet() { if (unmodifiableEdgeSet == null) { unmodifiableEdgeSet = Collections.unmodifiableSet(edgeSet); } return unmodifiableEdgeSet; } /** * @see Graph#edgesOf(Object) */ public Set edgesOf(V vertex) { assertVertexExist(vertex); Set edges = new ArrayUnenforcedSet(); Set baseEdges = base.edgesOf(vertex); for (E e : baseEdges) { if (containsEdge(e)) { edges.add(e); } } return edges; } /** * @see Graph#removeEdge(Object) */ public boolean removeEdge(E e) { return edgeSet.remove(e); } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { E e = getEdge(sourceVertex, targetVertex); return edgeSet.remove(e) ? e : null; } /** * @see Graph#removeVertex(Object) */ public boolean removeVertex(V v) { // If the base graph does NOT contain v it means we are here in // response to removal of v from the base. In such case we don't need // to remove all the edges of v as they were already removed. if (containsVertex(v) && base.containsVertex(v)) { removeAllEdges(edgesOf(v)); } return vertexSet.remove(v); } /** * @see Graph#vertexSet() */ public Set vertexSet() { if (unmodifiableVertexSet == null) { unmodifiableVertexSet = Collections.unmodifiableSet(vertexSet); } return unmodifiableVertexSet; } /** * @see Graph#getEdgeSource(Object) */ public V getEdgeSource(E e) { return base.getEdgeSource(e); } /** * @see Graph#getEdgeTarget(Object) */ public V getEdgeTarget(E e) { return base.getEdgeTarget(e); } private void addEdgesUsingFilter(Set edgeSet, Set filter) { E e; boolean containsVertices; boolean edgeIncluded; for (Iterator iter = edgeSet.iterator(); iter.hasNext();) { e = iter.next(); V sourceVertex = base.getEdgeSource(e); V targetVertex = base.getEdgeTarget(e); containsVertices = containsVertex(sourceVertex) && containsVertex(targetVertex); // note the use of short circuit evaluation edgeIncluded = (filter == null) || filter.contains(e); if (containsVertices && edgeIncluded) { addEdge(sourceVertex, targetVertex, e); } } } private void addVerticesUsingFilter(Set vertexSet, Set filter) { V v; for (Iterator iter = vertexSet.iterator(); iter.hasNext();) { v = iter.next(); // note the use of short circuit evaluation if ((filter == null) || filter.contains(v)) { addVertex(v); } } } public G getBase() { return base; } /** * @see Graph#getEdgeWeight(Object) */ public double getEdgeWeight(E e) { return base.getEdgeWeight(e); } /** * @see WeightedGraph#setEdgeWeight(Object, double) */ public void setEdgeWeight(E e, double weight) { ((WeightedGraph) base).setEdgeWeight(e, weight); } //~ Inner Classes ---------------------------------------------------------- /** * An internal listener on the base graph. * * @author Barak Naveh * @since Jul 20, 2003 */ private class BaseGraphListener implements GraphListener, Serializable { private static final long serialVersionUID = 4343535244243546391L; /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded(GraphEdgeChangeEvent e) { if (isInduced) { E edge = e.getEdge(); V source = base.getEdgeSource(edge); V target = base.getEdgeTarget(edge); if (containsVertex(source) && containsVertex(target)) { addEdge( source, target, edge); } } } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved(GraphEdgeChangeEvent e) { E edge = e.getEdge(); removeEdge(edge); } /** * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded(GraphVertexChangeEvent e) { // we don't care } /** * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved(GraphVertexChangeEvent e) { V vertex = e.getVertex(); removeVertex(vertex); } } } // End Subgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/UndirectedGraphUnion.java0000644000175000017500000000457311706124626024447 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * UndirectedGraphUnion.java * ------------------------- * (C) Copyright 2009-2009, by Ilya Razenshteyn * * Original Author: Ilya Razenshteyn and Contributors. * * $Id: UndirectedGraphUnion.java 695 2009-07-06 02:18:35Z perfecthash $ * * Changes * ------- * 02-Feb-2009 : Initial revision (IR); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; public class UndirectedGraphUnion extends GraphUnion> implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -740199233080172450L; //~ Constructors ----------------------------------------------------------- UndirectedGraphUnion( UndirectedGraph g1, UndirectedGraphUnion g2, WeightCombiner operator) { super(g1, g2, operator); } UndirectedGraphUnion( UndirectedGraph g1, UndirectedGraphUnion g2) { super(g1, g2); } //~ Methods ---------------------------------------------------------------- public int degreeOf(V vertex) { Set res = edgesOf(vertex); return res.size(); } } // End UndirectedGraphUnion.java jgrapht-0.8.3/src/org/jgrapht/graph/AbstractBaseGraph.java0000644000175000017500000007755511706124626023720 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * AbstractBaseGraph.java * ---------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): John V. Sichi * Christian Hammer * * $Id: AbstractBaseGraph.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 10-Aug-2003 : General edge refactoring (BN); * 06-Nov-2003 : Change edge sharing semantics (JVS); * 07-Feb-2004 : Enabled serialization (BN); * 11-Mar-2004 : Made generic (CH); * 01-Jun-2005 : Added EdgeListFactory (JVS); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * The most general implementation of the {@link org.jgrapht.Graph} interface. * Its subclasses add various restrictions to get more specific graphs. The * decision whether it is directed or undirected is decided at construction time * and cannot be later modified (see constructor for details). * *

    This graph implementation guarantees deterministic vertex and edge set * ordering (via {@link LinkedHashMap} and {@link LinkedHashSet}).

    * * @author Barak Naveh * @since Jul 24, 2003 */ public abstract class AbstractBaseGraph extends AbstractGraph implements Graph, Cloneable, Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -1263088497616142427L; private static final String LOOPS_NOT_ALLOWED = "loops not allowed"; //~ Instance fields -------------------------------------------------------- boolean allowingLoops; private EdgeFactory edgeFactory; private EdgeSetFactory edgeSetFactory; private Map edgeMap; private transient Set unmodifiableEdgeSet = null; private transient Set unmodifiableVertexSet = null; private Specifics specifics; private boolean allowingMultipleEdges; private transient TypeUtil vertexTypeDecl = null; //~ Constructors ----------------------------------------------------------- /** * Construct a new pseudograph. The pseudograph can either be directed or * undirected, depending on the specified edge factory. * * @param ef the edge factory of the new graph. * @param allowMultipleEdges whether to allow multiple edges or not. * @param allowLoops whether to allow edges that are self-loops or not. * * @throws NullPointerException if the specified edge factory is * null. */ public AbstractBaseGraph( EdgeFactory ef, boolean allowMultipleEdges, boolean allowLoops) { if (ef == null) { throw new NullPointerException(); } edgeMap = new LinkedHashMap(); edgeFactory = ef; allowingLoops = allowLoops; allowingMultipleEdges = allowMultipleEdges; specifics = createSpecifics(); this.edgeSetFactory = new ArrayListFactory(); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { return specifics.getAllEdges(sourceVertex, targetVertex); } /** * Returns true if and only if self-loops are allowed in this * graph. A self loop is an edge that its source and target vertices are the * same. * * @return true if and only if graph loops are allowed. */ public boolean isAllowingLoops() { return allowingLoops; } /** * Returns true if and only if multiple edges are allowed in * this graph. The meaning of multiple edges is that there can be many edges * going from vertex v1 to vertex v2. * * @return true if and only if multiple edges are allowed. */ public boolean isAllowingMultipleEdges() { return allowingMultipleEdges; } /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { return specifics.getEdge(sourceVertex, targetVertex); } /** * @see Graph#getEdgeFactory() */ public EdgeFactory getEdgeFactory() { return edgeFactory; } /** * Set the {@link EdgeSetFactory} to use for this graph. Initially, a graph * is created with a default implementation which always supplies an {@link * java.util.ArrayList} with capacity 1. * * @param edgeSetFactory factory to use for subsequently created edge sets * (this call has no effect on existing edge sets) */ public void setEdgeSetFactory(EdgeSetFactory edgeSetFactory) { this.edgeSetFactory = edgeSetFactory; } /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { assertVertexExist(sourceVertex); assertVertexExist(targetVertex); if (!allowingMultipleEdges && containsEdge(sourceVertex, targetVertex)) { return null; } if (!allowingLoops && sourceVertex.equals(targetVertex)) { throw new IllegalArgumentException(LOOPS_NOT_ALLOWED); } E e = edgeFactory.createEdge(sourceVertex, targetVertex); if (containsEdge(e)) { // this restriction should stay! return null; } else { IntrusiveEdge intrusiveEdge = createIntrusiveEdge(e, sourceVertex, targetVertex); edgeMap.put(e, intrusiveEdge); specifics.addEdgeToTouchingVertices(e); return e; } } /** * @see Graph#addEdge(Object, Object, Object) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { if (e == null) { throw new NullPointerException(); } else if (containsEdge(e)) { return false; } assertVertexExist(sourceVertex); assertVertexExist(targetVertex); if (!allowingMultipleEdges && containsEdge(sourceVertex, targetVertex)) { return false; } if (!allowingLoops && sourceVertex.equals(targetVertex)) { throw new IllegalArgumentException(LOOPS_NOT_ALLOWED); } IntrusiveEdge intrusiveEdge = createIntrusiveEdge(e, sourceVertex, targetVertex); edgeMap.put(e, intrusiveEdge); specifics.addEdgeToTouchingVertices(e); return true; } private IntrusiveEdge createIntrusiveEdge( E e, V sourceVertex, V targetVertex) { IntrusiveEdge intrusiveEdge; if (e instanceof IntrusiveEdge) { intrusiveEdge = (IntrusiveEdge) e; } else { intrusiveEdge = new IntrusiveEdge(); } intrusiveEdge.source = sourceVertex; intrusiveEdge.target = targetVertex; return intrusiveEdge; } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { if (v == null) { throw new NullPointerException(); } else if (containsVertex(v)) { return false; } else { specifics.addVertex(v); return true; } } /** * @see Graph#getEdgeSource(Object) */ public V getEdgeSource(E e) { return TypeUtil.uncheckedCast( getIntrusiveEdge(e).source, vertexTypeDecl); } /** * @see Graph#getEdgeTarget(Object) */ public V getEdgeTarget(E e) { return TypeUtil.uncheckedCast( getIntrusiveEdge(e).target, vertexTypeDecl); } private IntrusiveEdge getIntrusiveEdge(E e) { if (e instanceof IntrusiveEdge) { return (IntrusiveEdge) e; } return edgeMap.get(e); } /** * Returns a shallow copy of this graph instance. Neither edges nor vertices * are cloned. * * @return a shallow copy of this set. * * @throws RuntimeException * * @see java.lang.Object#clone() */ public Object clone() { try { TypeUtil> typeDecl = null; AbstractBaseGraph newGraph = TypeUtil.uncheckedCast(super.clone(), typeDecl); newGraph.edgeMap = new LinkedHashMap(); newGraph.edgeFactory = this.edgeFactory; newGraph.unmodifiableEdgeSet = null; newGraph.unmodifiableVertexSet = null; // NOTE: it's important for this to happen in an object // method so that the new inner class instance gets associated with // the right outer class instance newGraph.specifics = newGraph.createSpecifics(); Graphs.addGraph(newGraph, this); return newGraph; } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new RuntimeException(); } } /** * @see Graph#containsEdge(Object) */ public boolean containsEdge(E e) { return edgeMap.containsKey(e); } /** * @see Graph#containsVertex(Object) */ public boolean containsVertex(V v) { return specifics.getVertexSet().contains(v); } /** * @see UndirectedGraph#degreeOf(Object) */ public int degreeOf(V vertex) { return specifics.degreeOf(vertex); } /** * @see Graph#edgeSet() */ public Set edgeSet() { if (unmodifiableEdgeSet == null) { unmodifiableEdgeSet = Collections.unmodifiableSet(edgeMap.keySet()); } return unmodifiableEdgeSet; } /** * @see Graph#edgesOf(Object) */ public Set edgesOf(V vertex) { return specifics.edgesOf(vertex); } /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { return specifics.inDegreeOf(vertex); } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { return specifics.incomingEdgesOf(vertex); } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { return specifics.outDegreeOf(vertex); } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { return specifics.outgoingEdgesOf(vertex); } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { E e = getEdge(sourceVertex, targetVertex); if (e != null) { specifics.removeEdgeFromTouchingVertices(e); edgeMap.remove(e); } return e; } /** * @see Graph#removeEdge(Object) */ public boolean removeEdge(E e) { if (containsEdge(e)) { specifics.removeEdgeFromTouchingVertices(e); edgeMap.remove(e); return true; } else { return false; } } /** * @see Graph#removeVertex(Object) */ public boolean removeVertex(V v) { if (containsVertex(v)) { Set touchingEdgesList = edgesOf(v); // cannot iterate over list - will cause // ConcurrentModificationException removeAllEdges(new ArrayList(touchingEdgesList)); specifics.getVertexSet().remove(v); // remove the vertex itself return true; } else { return false; } } /** * @see Graph#vertexSet() */ public Set vertexSet() { if (unmodifiableVertexSet == null) { unmodifiableVertexSet = Collections.unmodifiableSet(specifics.getVertexSet()); } return unmodifiableVertexSet; } /** * @see Graph#getEdgeWeight(Object) */ public double getEdgeWeight(E e) { if (e instanceof DefaultWeightedEdge) { return ((DefaultWeightedEdge) e).getWeight(); } else { return WeightedGraph.DEFAULT_EDGE_WEIGHT; } } /** * @see WeightedGraph#setEdgeWeight(Object, double) */ public void setEdgeWeight(E e, double weight) { assert (e instanceof DefaultWeightedEdge) : e.getClass(); ((DefaultWeightedEdge) e).weight = weight; } private Specifics createSpecifics() { if (this instanceof DirectedGraph) { return new DirectedSpecifics(); } else if (this instanceof UndirectedGraph) { return new UndirectedSpecifics(); } else { throw new IllegalArgumentException( "must be instance of either DirectedGraph or UndirectedGraph"); } } //~ Inner Classes ---------------------------------------------------------- /** * . * * @author Barak Naveh */ private abstract class Specifics implements Serializable { private static final long serialVersionUID = 785196247314761183L; public abstract void addVertex(V vertex); public abstract Set getVertexSet(); /** * . * * @param sourceVertex * @param targetVertex * * @return */ public abstract Set getAllEdges(V sourceVertex, V targetVertex); /** * . * * @param sourceVertex * @param targetVertex * * @return */ public abstract E getEdge(V sourceVertex, V targetVertex); /** * Adds the specified edge to the edge containers of its source and * target vertices. * * @param e */ public abstract void addEdgeToTouchingVertices(E e); /** * . * * @param vertex * * @return */ public abstract int degreeOf(V vertex); /** * . * * @param vertex * * @return */ public abstract Set edgesOf(V vertex); /** * . * * @param vertex * * @return */ public abstract int inDegreeOf(V vertex); /** * . * * @param vertex * * @return */ public abstract Set incomingEdgesOf(V vertex); /** * . * * @param vertex * * @return */ public abstract int outDegreeOf(V vertex); /** * . * * @param vertex * * @return */ public abstract Set outgoingEdgesOf(V vertex); /** * Removes the specified edge from the edge containers of its source and * target vertices. * * @param e */ public abstract void removeEdgeFromTouchingVertices(E e); } private static class ArrayListFactory implements EdgeSetFactory, Serializable { private static final long serialVersionUID = 5936902837403445985L; /** * @see EdgeSetFactory.createEdgeSet */ public Set createEdgeSet(VV vertex) { // NOTE: use size 1 to keep memory usage under control // for the common case of vertices with low degree return new ArrayUnenforcedSet(1); } } /** * A container for vertex edges. * *

    In this edge container we use array lists to minimize memory toll. * However, for high-degree vertices we replace the entire edge container * with a direct access subclass (to be implemented).

    * * @author Barak Naveh */ private static class DirectedEdgeContainer implements Serializable { private static final long serialVersionUID = 7494242245729767106L; Set incoming; Set outgoing; private transient Set unmodifiableIncoming = null; private transient Set unmodifiableOutgoing = null; DirectedEdgeContainer(EdgeSetFactory edgeSetFactory, VV vertex) { incoming = edgeSetFactory.createEdgeSet(vertex); outgoing = edgeSetFactory.createEdgeSet(vertex); } /** * A lazy build of unmodifiable incoming edge set. * * @return */ public Set getUnmodifiableIncomingEdges() { if (unmodifiableIncoming == null) { unmodifiableIncoming = Collections.unmodifiableSet(incoming); } return unmodifiableIncoming; } /** * A lazy build of unmodifiable outgoing edge set. * * @return */ public Set getUnmodifiableOutgoingEdges() { if (unmodifiableOutgoing == null) { unmodifiableOutgoing = Collections.unmodifiableSet(outgoing); } return unmodifiableOutgoing; } /** * . * * @param e */ public void addIncomingEdge(EE e) { incoming.add(e); } /** * . * * @param e */ public void addOutgoingEdge(EE e) { outgoing.add(e); } /** * . * * @param e */ public void removeIncomingEdge(EE e) { incoming.remove(e); } /** * . * * @param e */ public void removeOutgoingEdge(EE e) { outgoing.remove(e); } } /** * . * * @author Barak Naveh */ private class DirectedSpecifics extends Specifics implements Serializable { private static final long serialVersionUID = 8971725103718958232L; private static final String NOT_IN_DIRECTED_GRAPH = "no such operation in a directed graph"; private Map> vertexMapDirected = new LinkedHashMap>(); public void addVertex(V v) { // add with a lazy edge container entry vertexMapDirected.put(v, null); } public Set getVertexSet() { return vertexMapDirected.keySet(); } /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { Set edges = null; if (containsVertex(sourceVertex) && containsVertex(targetVertex)) { edges = new ArrayUnenforcedSet(); DirectedEdgeContainer ec = getEdgeContainer(sourceVertex); Iterator iter = ec.outgoing.iterator(); while (iter.hasNext()) { E e = iter.next(); if (getEdgeTarget(e).equals(targetVertex)) { edges.add(e); } } } return edges; } /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { if (containsVertex(sourceVertex) && containsVertex(targetVertex)) { DirectedEdgeContainer ec = getEdgeContainer(sourceVertex); Iterator iter = ec.outgoing.iterator(); while (iter.hasNext()) { E e = iter.next(); if (getEdgeTarget(e).equals(targetVertex)) { return e; } } } return null; } /** * @see AbstractBaseGraph#addEdgeToTouchingVertices(Edge) */ public void addEdgeToTouchingVertices(E e) { V source = getEdgeSource(e); V target = getEdgeTarget(e); getEdgeContainer(source).addOutgoingEdge(e); getEdgeContainer(target).addIncomingEdge(e); } /** * @see UndirectedGraph#degreeOf(Object) */ public int degreeOf(V vertex) { throw new UnsupportedOperationException(NOT_IN_DIRECTED_GRAPH); } /** * @see Graph#edgesOf(Object) */ public Set edgesOf(V vertex) { ArrayUnenforcedSet inAndOut = new ArrayUnenforcedSet(getEdgeContainer(vertex).incoming); inAndOut.addAll(getEdgeContainer(vertex).outgoing); // we have two copies for each self-loop - remove one of them. if (allowingLoops) { Set loops = getAllEdges(vertex, vertex); for (int i = 0; i < inAndOut.size();) { Object e = inAndOut.get(i); if (loops.contains(e)) { inAndOut.remove(i); loops.remove(e); // so we remove it only once } else { i++; } } } return Collections.unmodifiableSet(inAndOut); } /** * @see DirectedGraph#inDegree(Object) */ public int inDegreeOf(V vertex) { return getEdgeContainer(vertex).incoming.size(); } /** * @see DirectedGraph#incomingEdges(Object) */ public Set incomingEdgesOf(V vertex) { return getEdgeContainer(vertex).getUnmodifiableIncomingEdges(); } /** * @see DirectedGraph#outDegree(Object) */ public int outDegreeOf(V vertex) { return getEdgeContainer(vertex).outgoing.size(); } /** * @see DirectedGraph#outgoingEdges(Object) */ public Set outgoingEdgesOf(V vertex) { return getEdgeContainer(vertex).getUnmodifiableOutgoingEdges(); } /** * @see AbstractBaseGraph#removeEdgeFromTouchingVertices(Edge) */ public void removeEdgeFromTouchingVertices(E e) { V source = getEdgeSource(e); V target = getEdgeTarget(e); getEdgeContainer(source).removeOutgoingEdge(e); getEdgeContainer(target).removeIncomingEdge(e); } /** * A lazy build of edge container for specified vertex. * * @param vertex a vertex in this graph. * * @return EdgeContainer */ private DirectedEdgeContainer getEdgeContainer(V vertex) { assertVertexExist(vertex); DirectedEdgeContainer ec = vertexMapDirected.get(vertex); if (ec == null) { ec = new DirectedEdgeContainer(edgeSetFactory, vertex); vertexMapDirected.put(vertex, ec); } return ec; } } /** * A container of for vertex edges. * *

    In this edge container we use array lists to minimize memory toll. * However, for high-degree vertices we replace the entire edge container * with a direct access subclass (to be implemented).

    * * @author Barak Naveh */ private static class UndirectedEdgeContainer implements Serializable { private static final long serialVersionUID = -6623207588411170010L; Set vertexEdges; private transient Set unmodifiableVertexEdges = null; UndirectedEdgeContainer( EdgeSetFactory edgeSetFactory, VV vertex) { vertexEdges = edgeSetFactory.createEdgeSet(vertex); } /** * A lazy build of unmodifiable list of vertex edges * * @return */ public Set getUnmodifiableVertexEdges() { if (unmodifiableVertexEdges == null) { unmodifiableVertexEdges = Collections.unmodifiableSet(vertexEdges); } return unmodifiableVertexEdges; } /** * . * * @param e */ public void addEdge(EE e) { vertexEdges.add(e); } /** * . * * @return */ public int edgeCount() { return vertexEdges.size(); } /** * . * * @param e */ public void removeEdge(EE e) { vertexEdges.remove(e); } } /** * . * * @author Barak Naveh */ private class UndirectedSpecifics extends Specifics implements Serializable { private static final long serialVersionUID = 6494588405178655873L; private static final String NOT_IN_UNDIRECTED_GRAPH = "no such operation in an undirected graph"; private Map> vertexMapUndirected = new LinkedHashMap>(); public void addVertex(V v) { // add with a lazy edge container entry vertexMapUndirected.put(v, null); } public Set getVertexSet() { return vertexMapUndirected.keySet(); } /** * @see Graph#getAllEdges(Object, Object) */ public Set getAllEdges(V sourceVertex, V targetVertex) { Set edges = null; if (containsVertex(sourceVertex) && containsVertex(targetVertex)) { edges = new ArrayUnenforcedSet(); Iterator iter = getEdgeContainer(sourceVertex).vertexEdges.iterator(); while (iter.hasNext()) { E e = iter.next(); boolean equalStraight = sourceVertex.equals(getEdgeSource(e)) && targetVertex.equals(getEdgeTarget(e)); boolean equalInverted = sourceVertex.equals(getEdgeTarget(e)) && targetVertex.equals(getEdgeSource(e)); if (equalStraight || equalInverted) { edges.add(e); } } } return edges; } /** * @see Graph#getEdge(Object, Object) */ public E getEdge(V sourceVertex, V targetVertex) { if (containsVertex(sourceVertex) && containsVertex(targetVertex)) { Iterator iter = getEdgeContainer(sourceVertex).vertexEdges.iterator(); while (iter.hasNext()) { E e = iter.next(); boolean equalStraight = sourceVertex.equals(getEdgeSource(e)) && targetVertex.equals(getEdgeTarget(e)); boolean equalInverted = sourceVertex.equals(getEdgeTarget(e)) && targetVertex.equals(getEdgeSource(e)); if (equalStraight || equalInverted) { return e; } } } return null; } /** * @see AbstractBaseGraph#addEdgeToTouchingVertices(Edge) */ public void addEdgeToTouchingVertices(E e) { V source = getEdgeSource(e); V target = getEdgeTarget(e); getEdgeContainer(source).addEdge(e); if (!source.equals(target)) { getEdgeContainer(target).addEdge(e); } } /** * @see UndirectedGraph#degreeOf(V) */ public int degreeOf(V vertex) { if (allowingLoops) { // then we must count, and add loops twice int degree = 0; Set edges = getEdgeContainer(vertex).vertexEdges; for (E e : edges) { if (getEdgeSource(e).equals(getEdgeTarget(e))) { degree += 2; } else { degree += 1; } } return degree; } else { return getEdgeContainer(vertex).edgeCount(); } } /** * @see Graph#edgesOf(V) */ public Set edgesOf(V vertex) { return getEdgeContainer(vertex).getUnmodifiableVertexEdges(); } /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { throw new UnsupportedOperationException(NOT_IN_UNDIRECTED_GRAPH); } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { throw new UnsupportedOperationException(NOT_IN_UNDIRECTED_GRAPH); } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { throw new UnsupportedOperationException(NOT_IN_UNDIRECTED_GRAPH); } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { throw new UnsupportedOperationException(NOT_IN_UNDIRECTED_GRAPH); } /** * @see AbstractBaseGraph#removeEdgeFromTouchingVertices(Edge) */ public void removeEdgeFromTouchingVertices(E e) { V source = getEdgeSource(e); V target = getEdgeTarget(e); getEdgeContainer(source).removeEdge(e); if (!source.equals(target)) { getEdgeContainer(target).removeEdge(e); } } /** * A lazy build of edge container for specified vertex. * * @param vertex a vertex in this graph. * * @return EdgeContainer */ private UndirectedEdgeContainer getEdgeContainer(V vertex) { assertVertexExist(vertex); UndirectedEdgeContainer ec = vertexMapUndirected.get(vertex); if (ec == null) { ec = new UndirectedEdgeContainer( edgeSetFactory, vertex); vertexMapUndirected.put(vertex, ec); } return ec; } } } // End AbstractBaseGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ListenableUndirectedWeightedGraph.java0000644000175000017500000000526611706124626027122 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------------------- * ListenableUndirectedWeightedGraph.java * -------------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: ListenableUndirectedWeightedGraph.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Jun-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * An undirected weighted graph which is also {@link * org.jgrapht.ListenableGraph}. * * @see DefaultListenableGraph */ public class ListenableUndirectedWeightedGraph extends ListenableUndirectedGraph implements WeightedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3690762799613949747L; //~ Constructors ----------------------------------------------------------- /** * Creates a new listenable undirected weighted graph. * * @param edgeClass class on which to base factory for edges */ public ListenableUndirectedWeightedGraph(Class edgeClass) { this(new SimpleWeightedGraph(edgeClass)); } /** * Creates a new listenable undirected weighted graph. * * @param base the backing graph. */ public ListenableUndirectedWeightedGraph(WeightedGraph base) { super((UndirectedGraph) base); } } // End ListenableUndirectedWeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/GraphUnion.java0000644000175000017500000001744111706124626022436 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * GraphUnion.java * ------------------------- * (C) Copyright 2009-2009, by Ilya Razenshteyn * * Original Author: Ilya Razenshteyn and Contributors. * * $Id: GraphUnion.java 695 2009-07-06 02:18:35Z perfecthash $ * * Changes * ------- * 02-Feb-2009 : Initial revision (IR); * */ package org.jgrapht.graph; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** *

    Read-only union of two graphs: G1 and G2. If * G1 = (V1, E1) and G2 = * (V2, E2) then their union G = (V, E), where V is the * union of V1 and V2, and E is the union of E1 * and E1.

    * *

    GraphUnion implements Graph interface. * GraphUnion uses WeightCombiner to choose policy for calculating * edge weight.

    */ public class GraphUnion> extends AbstractGraph implements Serializable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -740199233080172450L; private static final String READ_ONLY = "union of graphs is read-only"; //~ Instance fields -------------------------------------------------------- private G g1; private G g2; private WeightCombiner operator; //~ Constructors ----------------------------------------------------------- public GraphUnion(G g1, G g2, WeightCombiner operator) { if (g1 == null) { throw new NullPointerException("g1 is null"); } if (g2 == null) { throw new NullPointerException("g2 is null"); } if (g1 == g2) { throw new IllegalArgumentException("g1 is equal to g2"); } this.g1 = g1; this.g2 = g2; this.operator = operator; } public GraphUnion(G g1, G g2) { this(g1, g2, WeightCombiner.SUM); } //~ Methods ---------------------------------------------------------------- public Set getAllEdges(V sourceVertex, V targetVertex) { Set res = new HashSet(); if (g1.containsVertex(sourceVertex) && g1.containsVertex(targetVertex)) { res.addAll(g1.getAllEdges(sourceVertex, targetVertex)); } if (g2.containsVertex(sourceVertex) && g2.containsVertex(targetVertex)) { res.addAll(g2.getAllEdges(sourceVertex, targetVertex)); } return Collections.unmodifiableSet(res); } public E getEdge(V sourceVertex, V targetVertex) { E res = null; if (g1.containsVertex(sourceVertex) && g1.containsVertex(targetVertex)) { res = g1.getEdge(sourceVertex, targetVertex); } if ((res == null) && g2.containsVertex(sourceVertex) && g2.containsVertex(targetVertex)) { res = g2.getEdge(sourceVertex, targetVertex); } return res; } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public EdgeFactory getEdgeFactory() { throw new UnsupportedOperationException(READ_ONLY); } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public E addEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(READ_ONLY); } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { throw new UnsupportedOperationException(READ_ONLY); } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public boolean addVertex(V v) { throw new UnsupportedOperationException(READ_ONLY); } public boolean containsEdge(E e) { return g1.containsEdge(e) || g2.containsEdge(e); } public boolean containsVertex(V v) { return g1.containsVertex(v) || g2.containsVertex(v); } public Set edgeSet() { Set res = new HashSet(); res.addAll(g1.edgeSet()); res.addAll(g2.edgeSet()); return Collections.unmodifiableSet(res); } public Set edgesOf(V vertex) { Set res = new HashSet(); if (g1.containsVertex(vertex)) { res.addAll(g1.edgesOf(vertex)); } if (g2.containsVertex(vertex)) { res.addAll(g2.edgesOf(vertex)); } return Collections.unmodifiableSet(res); } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public E removeEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(READ_ONLY); } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public boolean removeEdge(E e) { throw new UnsupportedOperationException(READ_ONLY); } /** * Throws UnsupportedOperationException, because * GraphUnion is read-only. */ public boolean removeVertex(V v) { throw new UnsupportedOperationException(READ_ONLY); } public Set vertexSet() { Set res = new HashSet(); res.addAll(g1.vertexSet()); res.addAll(g2.vertexSet()); return Collections.unmodifiableSet(res); } public V getEdgeSource(E e) { if (g1.containsEdge(e)) { return g1.getEdgeSource(e); } if (g2.containsEdge(e)) { return g2.getEdgeSource(e); } return null; } public V getEdgeTarget(E e) { if (g1.containsEdge(e)) { return g1.getEdgeTarget(e); } if (g2.containsEdge(e)) { return g2.getEdgeTarget(e); } return null; } public double getEdgeWeight(E e) { if (g1.containsEdge(e) && g2.containsEdge(e)) { return operator.combine(g1.getEdgeWeight(e), g2.getEdgeWeight(e)); } if (g1.containsEdge(e)) { return g1.getEdgeWeight(e); } if (g2.containsEdge(e)) { return g2.getEdgeWeight(e); } throw new IllegalArgumentException("no such edge in the union"); } /** * @return G1 */ public G getG1() { return g1; } /** * @return G2 */ public G getG2() { return g2; } } // End GraphUnion.java jgrapht-0.8.3/src/org/jgrapht/graph/UndirectedSubgraph.java0000644000175000017500000000614211706124626024142 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * UndirectedSubgraph.java * ----------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: UndirectedSubgraph.java 755 2012-01-18 23:50:37Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * An undirected graph that is a subgraph on other graph. * * @see Subgraph */ public class UndirectedSubgraph extends Subgraph> implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3256728359772631350L; //~ Constructors ----------------------------------------------------------- /** * Creates a new undirected subgraph. * * @param base the base (backing) graph on which the subgraph will be based. * @param vertexSubset vertices to include in the subgraph. If * null then all vertices are included. * @param edgeSubset edges to in include in the subgraph. If * null then all the edges whose vertices found in the graph * are included. */ public UndirectedSubgraph( UndirectedGraph base, Set vertexSubset, Set edgeSubset) { super(base, vertexSubset, edgeSubset); } //~ Methods ---------------------------------------------------------------- /** * @see UndirectedGraph#degreeOf(Object) */ public int degreeOf(V vertex) { assertVertexExist(vertex); int degree = 0; for (E e : getBase().edgesOf(vertex)) { if (containsEdge(e)) { degree++; if (getEdgeSource(e).equals(getEdgeTarget(e))) { degree++; } } } return degree; } } // End UndirectedSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedPseudograph.java0000644000175000017500000000477511706124626024317 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (barak_naveh@users.sourceforge.net) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * DirectedPseudograph.java * ---------------- * (C) Copyright 2004-2008, by Christian Hammer and Contributors. * * Original Author: Christian Hammer * Contributor(s): - * * $Id: DirectedPseudograph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 11-Mar-2004 : Initial revision: generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A directed pseudograph. A directed pseudograph is a non-simple directed graph * in which both graph loops and multiple edges are permitted. If you're unsure * about pseudographs, see: * http://mathworld.wolfram.com/Pseudograph.html. */ public class DirectedPseudograph extends AbstractBaseGraph implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -8300409752893486415L; //~ Constructors ----------------------------------------------------------- /** * @see AbstractBaseGraph */ public DirectedPseudograph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } /** * @see AbstractBaseGraph */ public DirectedPseudograph(EdgeFactory ef) { super(ef, true, true); } } // End DirectedPseudograph.java jgrapht-0.8.3/src/org/jgrapht/graph/MaskSubgraph.java0000644000175000017500000001677511706124626022764 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * MaskSubgraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: MaskSubgraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; /** * An unmodifiable subgraph induced by a vertex/edge masking function. The * subgraph will keep track of edges being added to its vertex subset as well as * deletion of edges and vertices. When iterating over the vertices/edges, it * will iterate over the vertices/edges of the base graph and discard * vertices/edges that are masked (an edge with a masked extremity vertex is * discarded as well). * * @author Guillaume Boulmier * @since July 5, 2007 */ public class MaskSubgraph extends AbstractGraph { //~ Static fields/initializers --------------------------------------------- private static final String UNMODIFIABLE = "this graph is unmodifiable"; //~ Instance fields -------------------------------------------------------- private Graph base; private Set edges; private MaskFunctor mask; private Set vertices; //~ Constructors ----------------------------------------------------------- /** * Creates a new induced subgraph. Running-time = O(1). * * @param base the base (backing) graph on which the subgraph will be based. * @param mask vertices and edges to exclude in the subgraph. If a * vertex/edge is masked, it is as if it is not in the subgraph. */ public MaskSubgraph(Graph base, MaskFunctor mask) { super(); this.base = base; this.mask = mask; this.vertices = new MaskVertexSet(base.vertexSet(), mask); this.edges = new MaskEdgeSet(base, base.edgeSet(), mask); } //~ Methods ---------------------------------------------------------------- /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } public boolean addEdge(V sourceVertex, V targetVertex, E edge) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { throw new UnsupportedOperationException(UNMODIFIABLE); } public boolean containsEdge(E e) { return edgeSet().contains(e); } public boolean containsVertex(V v) { return !this.mask.isVertexMasked(v) && this.base.containsVertex(v); } /** * @see UndirectedGraph#degreeOf(Object) */ public int degreeOf(V vertex) { return edgesOf(vertex).size(); } public Set edgeSet() { return this.edges; } public Set edgesOf(V vertex) { assertVertexExist(vertex); return new MaskEdgeSet( this.base, this.base.edgesOf(vertex), this.mask); } public Set getAllEdges(V sourceVertex, V targetVertex) { Set edges = null; if (containsVertex(sourceVertex) && containsVertex(targetVertex)) { return new MaskEdgeSet( this.base, this.base.getAllEdges( sourceVertex, targetVertex), this.mask); } return edges; } public E getEdge(V sourceVertex, V targetVertex) { Set edges = getAllEdges(sourceVertex, targetVertex); if ((edges == null) || edges.isEmpty()) { return null; } else { return edges.iterator().next(); } } public EdgeFactory getEdgeFactory() { return this.base.getEdgeFactory(); } public V getEdgeSource(E edge) { assert (edgeSet().contains(edge)); return this.base.getEdgeSource(edge); } public V getEdgeTarget(E edge) { assert (edgeSet().contains(edge)); return this.base.getEdgeTarget(edge); } public double getEdgeWeight(E edge) { assert (edgeSet().contains(edge)); return this.base.getEdgeWeight(edge); } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { assertVertexExist(vertex); return new MaskEdgeSet( this.base, ((DirectedGraph) this.base).incomingEdgesOf(vertex), this.mask); } /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { return incomingEdgesOf(vertex).size(); } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { return outgoingEdgesOf(vertex).size(); } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { assertVertexExist(vertex); return new MaskEdgeSet( this.base, ((DirectedGraph) this.base).outgoingEdgesOf(vertex), this.mask); } /** * @see Graph#removeAllEdges(Collection) */ public boolean removeAllEdges(Collection edges) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllEdges(Object, Object) */ public Set removeAllEdges(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllVertices(Collection) */ public boolean removeAllVertices(Collection vertices) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeEdge(Object) */ public boolean removeEdge(E e) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeEdge(Object, Object) */ public E removeEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeVertex(Object) */ public boolean removeVertex(V v) { throw new UnsupportedOperationException(UNMODIFIABLE); } public Set vertexSet() { return this.vertices; } } // End MaskSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/MaskEdgeSet.java0000644000175000017500000000776011706124626022523 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * MaskEdgeSet.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: MaskEdgeSet.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; import org.jgrapht.util.PrefetchIterator.*; /** * Helper for {@link MaskSubgraph}. * * @author Guillaume Boulmier * @since July 5, 2007 */ class MaskEdgeSet extends AbstractSet { //~ Instance fields -------------------------------------------------------- private Set edgeSet; private Graph graph; private MaskFunctor mask; private transient TypeUtil edgeTypeDecl = null; private int size; //~ Constructors ----------------------------------------------------------- public MaskEdgeSet( Graph graph, Set edgeSet, MaskFunctor mask) { this.graph = graph; this.edgeSet = edgeSet; this.mask = mask; this.size = -1; } //~ Methods ---------------------------------------------------------------- /** * @see java.util.Collection#contains(java.lang.Object) */ public boolean contains(Object o) { return this.edgeSet.contains(o) && !this.mask.isEdgeMasked(TypeUtil.uncheckedCast(o, edgeTypeDecl)); } /** * @see java.util.Set#iterator() */ public Iterator iterator() { return new PrefetchIterator(new MaskEdgeSetNextElementFunctor()); } /** * @see java.util.Set#size() */ public int size() { if (this.size == -1) { this.size = 0; for (Iterator iter = iterator(); iter.hasNext();) { iter.next(); this.size++; } } return this.size; } //~ Inner Classes ---------------------------------------------------------- private class MaskEdgeSetNextElementFunctor implements NextElementFunctor { private Iterator iter; public MaskEdgeSetNextElementFunctor() { this.iter = MaskEdgeSet.this.edgeSet.iterator(); } public E nextElement() throws NoSuchElementException { E edge = this.iter.next(); while (isMasked(edge)) { edge = this.iter.next(); } return edge; } private boolean isMasked(E edge) { return MaskEdgeSet.this.mask.isEdgeMasked(edge) || MaskEdgeSet.this.mask.isVertexMasked( MaskEdgeSet.this.graph.getEdgeSource(edge)) || MaskEdgeSet.this.mask.isVertexMasked( MaskEdgeSet.this.graph.getEdgeTarget(edge)); } } } // End MaskEdgeSet.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedGraphUnion.java0000644000175000017500000000626311706124626024102 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * DirectedGraphUnion.java * ------------------------- * (C) Copyright 2009-2009, by Ilya Razenshteyn * * Original Author: Ilya Razenshteyn and Contributors. * * $Id: DirectedGraphUnion.java 695 2009-07-06 02:18:35Z perfecthash $ * * Changes * ------- * 02-Feb-2009 : Initial revision (IR); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; public class DirectedGraphUnion extends GraphUnion> implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -740199233080172450L; //~ Constructors ----------------------------------------------------------- DirectedGraphUnion( DirectedGraph g1, DirectedGraph g2, WeightCombiner operator) { super(g1, g2, operator); } DirectedGraphUnion(DirectedGraph g1, DirectedGraph g2) { super(g1, g2); } //~ Methods ---------------------------------------------------------------- public int inDegreeOf(V vertex) { Set res = incomingEdgesOf(vertex); return res.size(); } public Set incomingEdgesOf(V vertex) { Set res = new HashSet(); if (getG1().containsVertex(vertex)) { res.addAll(getG1().incomingEdgesOf(vertex)); } if (getG2().containsVertex(vertex)) { res.addAll(getG2().incomingEdgesOf(vertex)); } return Collections.unmodifiableSet(res); } public int outDegreeOf(V vertex) { Set res = outgoingEdgesOf(vertex); return res.size(); } public Set outgoingEdgesOf(V vertex) { Set res = new HashSet(); if (getG1().containsVertex(vertex)) { res.addAll(getG1().outgoingEdgesOf(vertex)); } if (getG2().containsVertex(vertex)) { res.addAll(getG2().outgoingEdgesOf(vertex)); } return Collections.unmodifiableSet(res); } } // End DirectedGraphUnion.java jgrapht-0.8.3/src/org/jgrapht/graph/DirectedSubgraph.java0000644000175000017500000001021111706124626023567 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------- * DirectedSubgraph.java * --------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DirectedSubgraph.java 755 2012-01-18 23:50:37Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * A directed graph that is a subgraph on other graph. * * @see Subgraph */ public class DirectedSubgraph extends Subgraph> implements DirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3616445700507054133L; //~ Constructors ----------------------------------------------------------- /** * Creates a new directed subgraph. * * @param base the base (backing) graph on which the subgraph will be based. * @param vertexSubset vertices to include in the subgraph. If * null then all vertices are included. * @param edgeSubset edges to in include in the subgraph. If * null then all the edges whose vertices found in the graph * are included. */ public DirectedSubgraph( DirectedGraph base, Set vertexSubset, Set edgeSubset) { super(base, vertexSubset, edgeSubset); } //~ Methods ---------------------------------------------------------------- /** * @see DirectedGraph#inDegreeOf(Object) */ public int inDegreeOf(V vertex) { assertVertexExist(vertex); int degree = 0; for (E e : getBase().incomingEdgesOf(vertex)) { if (containsEdge(e)) { degree++; } } return degree; } /** * @see DirectedGraph#incomingEdgesOf(Object) */ public Set incomingEdgesOf(V vertex) { assertVertexExist(vertex); Set edges = new ArrayUnenforcedSet(); for (E e : getBase().incomingEdgesOf(vertex)) { if (containsEdge(e)) { edges.add(e); } } return edges; } /** * @see DirectedGraph#outDegreeOf(Object) */ public int outDegreeOf(V vertex) { assertVertexExist(vertex); int degree = 0; for (E e : getBase().outgoingEdgesOf(vertex)) { if (containsEdge(e)) { degree++; } } return degree; } /** * @see DirectedGraph#outgoingEdgesOf(Object) */ public Set outgoingEdgesOf(V vertex) { assertVertexExist(vertex); Set edges = new ArrayUnenforcedSet(); for (E e : getBase().outgoingEdgesOf(vertex)) { if (containsEdge(e)) { edges.add(e); } } return edges; } } // End DirectedSubgraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ListenableUndirectedGraph.java0000644000175000017500000000507511706124626025437 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------ * ListenableUndirectedGraph.java * ------------------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: ListenableUndirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * An undirected graph which is also {@link org.jgrapht.ListenableGraph}. * * @see DefaultListenableGraph */ public class ListenableUndirectedGraph extends DefaultListenableGraph implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3256999969193145905L; //~ Constructors ----------------------------------------------------------- /** * Creates a new listenable undirected simple graph. * * @param edgeClass class on which to base factory for edges */ public ListenableUndirectedGraph(Class edgeClass) { this(new SimpleGraph(edgeClass)); } /** * Creates a new listenable undirected graph. * * @param base the backing graph. */ public ListenableUndirectedGraph(UndirectedGraph base) { super(base); } } // End ListenableUndirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/SimpleGraph.java0000644000175000017500000000524411706124626022575 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * SimpleGraph.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): CHristian Hammer * * $Id: SimpleGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Aug-2003 : Initial revision (BN); * 06-Aug-2005 : Made generic (CH); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A simple graph. A simple graph is an undirected graph for which at most one * edge connects any two vertices, and loops are not permitted. If you're unsure * about simple graphs, see: * http://mathworld.wolfram.com/SimpleGraph.html. */ public class SimpleGraph extends AbstractBaseGraph implements UndirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3545796589454112304L; //~ Constructors ----------------------------------------------------------- /** * Creates a new simple graph with the specified edge factory. * * @param ef the edge factory of the new graph. */ public SimpleGraph(EdgeFactory ef) { super(ef, false, false); } /** * Creates a new simple graph. * * @param edgeClass class on which to base factory for edges */ public SimpleGraph(Class edgeClass) { this(new ClassBasedEdgeFactory(edgeClass)); } } // End SimpleGraph.java jgrapht-0.8.3/src/org/jgrapht/graph/ClassBasedVertexFactory.java0000644000175000017500000000456711706124626025123 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * ClassBasedVertexFactory.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * * $Id: ClassBasedVertexFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * */ package org.jgrapht.graph; import org.jgrapht.*; /** * A {@link VertexFactory} for producing vertices by using a class as a factory. * * @author Guillaume Boulmier * @since July 5, 2007 */ public class ClassBasedVertexFactory implements VertexFactory { //~ Instance fields -------------------------------------------------------- private final Class vertexClass; //~ Constructors ----------------------------------------------------------- public ClassBasedVertexFactory(Class vertexClass) { this.vertexClass = vertexClass; } //~ Methods ---------------------------------------------------------------- /** * @see VertexFactory#createVertex() */ public V createVertex() { try { return this.vertexClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Vertex factory failed", e); } } } // End ClassBasedVertexFactory.java jgrapht-0.8.3/src/org/jgrapht/ext/0000755000175000017500000000000011752244357017216 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/ext/MatrixExporter.java0000644000175000017500000002155111706124626023055 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * MatrixExporter.java * ------------------ * (C) Copyright 2005-2008, by Charles Fry and Contributors. * * Original Author: Charles Fry * * $Id: MatrixExporter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Dec-2005 : Initial Version (CF); * */ package org.jgrapht.ext; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * Exports a graph to a plain text matrix format, which can be processed by * matrix manipulation software, such as * MTJ or MATLAB. * * @author Charles Fry */ public class MatrixExporter { //~ Instance fields -------------------------------------------------------- private String delimiter = " "; private String prefix = ""; private String suffix = ""; //~ Constructors ----------------------------------------------------------- /** * Creates a new MatrixExporter object. */ public MatrixExporter() { } //~ Methods ---------------------------------------------------------------- private void println( PrintWriter out, String fromName, String toName, String value) { out.println( prefix + fromName + suffix + delimiter + prefix + toName + suffix + delimiter + prefix + value + suffix); } /** * Exports the specified graph into a plain text file format containing a * sparse representation of the graph's adjacency matrix. The value stored * in each position of the matrix indicates the number of edges between two * vertices. With an undirected graph, the adjacency matrix is symetric. * * @param output the writer to which the graph to be exported. * @param g the graph to be exported. */ public void exportAdjacencyMatrix(Writer output, UndirectedGraph g) { PrintWriter out = new PrintWriter(output); VertexNameProvider nameProvider = new IntegerNameProvider(); for (V from : g.vertexSet()) { // assign ids in vertex set iteration order nameProvider.getVertexName(from); } for (V from : g.vertexSet()) { exportAdjacencyMatrixVertex( out, nameProvider, from, Graphs.neighborListOf(g, from)); } out.flush(); } /** * Exports the specified graph into a plain text file format containing a * sparse representation of the graph's adjacency matrix. The value stored * in each position of the matrix indicates the number of directed edges * going from one vertex to another. * * @param output the writer to which the graph to be exported. * @param g the graph to be exported. */ public void exportAdjacencyMatrix(Writer output, DirectedGraph g) { PrintWriter out = new PrintWriter(output); VertexNameProvider nameProvider = new IntegerNameProvider(); for (V from : g.vertexSet()) { // assign ids in vertex set iteration order nameProvider.getVertexName(from); } for (V from : g.vertexSet()) { exportAdjacencyMatrixVertex( out, nameProvider, from, Graphs.successorListOf(g, from)); } out.flush(); } private void exportAdjacencyMatrixVertex( PrintWriter out, VertexNameProvider nameProvider, V from, List neighbors) { String fromName = nameProvider.getVertexName(from); Map counts = new LinkedHashMap(); for (V to : neighbors) { String toName = nameProvider.getVertexName(to); ModifiableInteger count = counts.get(toName); if (count == null) { count = new ModifiableInteger(0); counts.put(toName, count); } count.increment(); if (from.equals(to)) { // count loops twice, once for each end count.increment(); } } for (Map.Entry entry : counts.entrySet()) { String toName = entry.getKey(); ModifiableInteger count = entry.getValue(); println(out, fromName, toName, count.toString()); } } /** * Exports the specified graph into a plain text file format containing a * sparse representation of the graph's Laplacian matrix. Laplacian matrices * are only defined for simple graphs, so edge direction, multiple edges, * loops, and weights are all ignored when creating the Laplacian matrix. If * you're unsure about Laplacian matrices, see: * http://mathworld.wolfram.com/LaplacianMatrix.html. * * @param output the writer to which the graph is to be exported. * @param g the graph to be exported. */ public void exportLaplacianMatrix(Writer output, UndirectedGraph g) { PrintWriter out = new PrintWriter(output); VertexNameProvider nameProvider = new IntegerNameProvider(); for (V from : g.vertexSet()) { // assign ids in vertex set iteration order nameProvider.getVertexName(from); } for (V from : g.vertexSet()) { String fromName = nameProvider.getVertexName(from); // TODO modify Graphs to return neighbor sets List neighbors = Graphs.neighborListOf(g, from); println( out, fromName, fromName, Integer.toString(neighbors.size())); for (V to : neighbors) { String toName = nameProvider.getVertexName(to); println(out, fromName, toName, "-1"); } } out.flush(); } /** * Exports the specified graph into a plain text file format containing a * sparse representation of the graph's normalized Laplacian matrix. * Laplacian matrices are only defined for simple graphs, so edge direction, * multiple edges, loops, and weights are all ignored when creating the * Laplacian matrix. If you're unsure about normalized Laplacian matrices, * see: * http://mathworld.wolfram.com/LaplacianMatrix.html. * * @param output the writer to which the graph is to be exported. * @param g the graph to be exported. */ public void exportNormalizedLaplacianMatrix( Writer output, UndirectedGraph g) { PrintWriter out = new PrintWriter(output); VertexNameProvider nameProvider = new IntegerNameProvider(); for (V from : g.vertexSet()) { // assign ids in vertex set iteration order nameProvider.getVertexName(from); } for (V from : g.vertexSet()) { String fromName = nameProvider.getVertexName(from); Set neighbors = new LinkedHashSet(Graphs.neighborListOf(g, from)); if (neighbors.isEmpty()) { println(out, fromName, fromName, "0"); } else { println(out, fromName, fromName, "1"); for (V to : neighbors) { String toName = nameProvider.getVertexName(to); double value = -1 / Math.sqrt(g.degreeOf(from) * g.degreeOf(to)); println(out, fromName, toName, Double.toString(value)); } } } out.flush(); } } // End MatrixExporter.java jgrapht-0.8.3/src/org/jgrapht/ext/IntegerEdgeNameProvider.java0000644000175000017500000000471511706124626024561 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * IntegerNameProvider.java * ------------------ * (C) Copyright 2005-2008, by Trevor Harmon. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; import java.util.*; /** * Assigns a unique integer to represent each edge. Each instance of * IntegerEdgeNameProvider maintains an internal map between every edge it has * ever seen and the unique integer representing that edge. As a result it is * probably desirable to have a separate instance for each distinct graph. * * @author Trevor Harmon */ public class IntegerEdgeNameProvider implements EdgeNameProvider { //~ Instance fields -------------------------------------------------------- private int nextID = 1; private final Map idMap = new HashMap(); //~ Methods ---------------------------------------------------------------- /** * Clears all cached identifiers, and resets the unique identifier counter. */ public void clear() { nextID = 1; idMap.clear(); } /** * Returns the String representation of an edge. * * @param edge the edge to be named */ public String getEdgeName(E edge) { Integer id = idMap.get(edge); if (id == null) { id = nextID++; idMap.put(edge, id); } return id.toString(); } } // End IntegerEdgeNameProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/VisioExporter.java0000644000175000017500000001023611706124626022700 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * VisioExporter.java * ------------------ * (C) Copyright 2003-2008, by Avner Linder and Contributors. * * Original Author: Avner Linder * Contributor(s): Barak Naveh * * $Id: VisioExporter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 27-May-2004 : Initial Version (AL); * */ package org.jgrapht.ext; import java.io.*; import java.util.*; import org.jgrapht.*; /** * Exports a graph to a csv format that can be imported into MS Visio. * *

    Tip: By default, the exported graph doesn't show link directions. * To show link directions:
    * *

      *
    1. Select All (Ctrl-A)
    2. *
    3. Right Click the selected items
    4. *
    5. Format/Line...
    6. *
    7. Line ends: End: (choose an arrow)
    8. *
    *

    * * @author Avner Linder */ public class VisioExporter { //~ Instance fields -------------------------------------------------------- private VertexNameProvider vertexNameProvider; //~ Constructors ----------------------------------------------------------- /** * Creates a new VisioExporter object with the specified naming policy. * * @param vertexNameProvider the vertex name provider to be used for naming * the Visio shapes. */ public VisioExporter(VertexNameProvider vertexNameProvider) { this.vertexNameProvider = vertexNameProvider; } /** * Creates a new VisioExporter object. */ public VisioExporter() { this(new StringNameProvider()); } //~ Methods ---------------------------------------------------------------- /** * Exports the specified graph into a Visio csv file format. * * @param output the print stream to which the graph to be exported. * @param g the graph to be exported. */ public void export(OutputStream output, Graph g) { PrintStream out = new PrintStream(output); for (Iterator i = g.vertexSet().iterator(); i.hasNext();) { exportVertex(out, i.next()); } for (Iterator i = g.edgeSet().iterator(); i.hasNext();) { exportEdge(out, i.next(), g); } out.flush(); } private void exportEdge(PrintStream out, E edge, Graph g) { String sourceName = vertexNameProvider.getVertexName(g.getEdgeSource(edge)); String targetName = vertexNameProvider.getVertexName(g.getEdgeTarget(edge)); out.print("Link,"); // create unique ShapeId for link out.print(sourceName); out.print("-->"); out.print(targetName); // MasterName and Text fields left blank out.print(",,,"); out.print(sourceName); out.print(","); out.print(targetName); out.print("\n"); } private void exportVertex(PrintStream out, V vertex) { String name = vertexNameProvider.getVertexName(vertex); out.print("Shape,"); out.print(name); out.print(",,"); // MasterName field left empty out.print(name); out.print("\n"); } } // End VisioExporter.java jgrapht-0.8.3/src/org/jgrapht/ext/package.html0000644000175000017500000000022411706124626021470 0ustar giovannigiovanni

    Extensions and integration means to other products.

    jgrapht-0.8.3/src/org/jgrapht/ext/ComponentAttributeProvider.java0000644000175000017500000000431111706124626025414 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * ComponentAttributeProvider.java * ------------------ * (C) Copyright 2010-2010, by John Sichi and Contributors. * * Original Author: John Sichi * * $Id: ComponentAttributeProvider.java 714 2010-06-13 01:19:56Z perfecthash $ * * Changes * ------- * 12-Jun-2010 : Initial Version (JVS); * */ package org.jgrapht.ext; import java.util.*; /** * Provides display attributes for vertices and/or edges in a graph. * * @author John Sichi * @version $Id: ComponentAttributeProvider.java 714 2010-06-13 01:19:56Z perfecthash $ */ public interface ComponentAttributeProvider { //~ Methods ---------------------------------------------------------------- /** * Returns a set of attribute key/value pairs for a vertex or edge. If order * is important in the output, be sure to use an order-deterministic map * implementation. * * @param component vertex or edge for which attributes are to be obtained * * @return key/value pairs, or null if no attributes should be supplied */ public Map getComponentAttributes(T component); } // End ComponentAttributeProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/StringEdgeNameProvider.java0000644000175000017500000000372311706124626024430 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * StringNameProvider.java * ------------------ * (C) Copyright 2005-2008, by Trevor Harmon. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; /** * Generates edge names by invoking {@link #toString()} on them. This assumes * that the edge's {@link #toString()} method returns a unique String * representation for each edge. * * @author Trevor Harmon */ public class StringEdgeNameProvider implements EdgeNameProvider { //~ Constructors ----------------------------------------------------------- public StringEdgeNameProvider() { } //~ Methods ---------------------------------------------------------------- /** * Returns the String representation an edge. * * @param edge the edge to be named */ public String getEdgeName(E edge) { return edge.toString(); } } // End StringEdgeNameProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/EdgeNameProvider.java0000644000175000017500000000336411706124626023242 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * VertexNameProvider.java * ------------------ * (C) Copyright 2005-2008, by Trevor Harmon. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; /** * Assigns a display name for each of the graph edes. */ public interface EdgeNameProvider { //~ Methods ---------------------------------------------------------------- /** * Returns a unique name for an edge. This is useful when exporting a graph, * as it ensures that all edges are assigned simple, consistent names. * * @param edge the edge to be named * * @return the name of the edge */ public String getEdgeName(E edge); } // End EdgeNameProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/GmlExporter.java0000644000175000017500000002222511706124626022327 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * GmlExporter.java * ------------------ * (C) Copyright 2006, by Dimitrios Michail. * * Original Author: Dimitrios Michail * * $Id: GmlExporter.java 650 2008-12-24 20:44:06Z perfecthash $ * * Changes * ------- * 15-Dec-2006 : Initial Version (DM); * */ package org.jgrapht.ext; import java.io.*; import org.jgrapht.*; /** * Exports a graph into a GML file (Graph Modelling Language). * *

    For a description of the format see * http://www.infosun.fmi.uni-passau.de/Graphlet/GML/.

    * *

    The objects associated with vertices and edges are exported as labels * using their toString() implementation. See the {@link * #setPrintLabels(Integer)} method. The default behavior is to export no label * information.

    * * @author Dimitrios Michail */ public class GmlExporter { //~ Static fields/initializers --------------------------------------------- private static final String creator = "JGraphT GML Exporter"; private static final String version = "1"; private static final String delim = " "; private static final String tab1 = "\t"; private static final String tab2 = "\t\t"; // TODO jvs 27-Jan-2008: convert these to enum /** * Option to export no vertex or edge labels. */ public static final Integer PRINT_NO_LABELS = 1; /** * Option to export only the edge labels. */ public static final Integer PRINT_EDGE_LABELS = 2; /** * Option to export both edge and vertex labels. */ public static final Integer PRINT_EDGE_VERTEX_LABELS = 3; /** * Option to export only the vertex labels. */ public static final Integer PRINT_VERTEX_LABELS = 4; //~ Instance fields -------------------------------------------------------- private Integer printLabels = PRINT_NO_LABELS; private VertexNameProvider vertexIDProvider; private VertexNameProvider vertexLabelProvider; private EdgeNameProvider edgeIDProvider; private EdgeNameProvider edgeLabelProvider; //~ Constructors ----------------------------------------------------------- /** * Creates a new GmlExporter object with integer name providers for the * vertex and edge IDs and null providers for the vertex and edge labels. */ public GmlExporter() { this( new IntegerNameProvider(), null, new IntegerEdgeNameProvider(), null); } /** * Constructs a new GmlExporter object with the given ID and label * providers. * * @param vertexIDProvider for generating vertex IDs. Must not be null. * @param vertexLabelProvider for generating vertex labels. If null, vertex * labels will be generated using the toString() method of the vertex * object. * @param edgeIDProvider for generating vertex IDs. Must not be null. * @param edgeLabelProvider for generating edge labels. If null, edge labels * will be generated using the toString() method of the edge object. */ public GmlExporter( VertexNameProvider vertexIDProvider, VertexNameProvider vertexLabelProvider, EdgeNameProvider edgeIDProvider, EdgeNameProvider edgeLabelProvider) { this.vertexIDProvider = vertexIDProvider; this.vertexLabelProvider = vertexLabelProvider; this.edgeIDProvider = edgeIDProvider; this.edgeLabelProvider = edgeLabelProvider; } //~ Methods ---------------------------------------------------------------- private String quoted(final String s) { return "\"" + s + "\""; } private void exportHeader(PrintWriter out) { out.println("Creator" + delim + quoted(creator)); out.println("Version" + delim + version); } private void exportVertices( PrintWriter out, Graph g) { for (V from : g.vertexSet()) { out.println(tab1 + "node"); out.println(tab1 + "["); out.println( tab2 + "id" + delim + vertexIDProvider.getVertexName(from)); if ((printLabels == PRINT_VERTEX_LABELS) || (printLabels == PRINT_EDGE_VERTEX_LABELS)) { String label = (vertexLabelProvider == null) ? from.toString() : vertexLabelProvider.getVertexName(from); out.println(tab2 + "label" + delim + quoted(label)); } out.println(tab1 + "]"); } } private void exportEdges( PrintWriter out, Graph g) { for (E edge : g.edgeSet()) { out.println(tab1 + "edge"); out.println(tab1 + "["); String id = edgeIDProvider.getEdgeName(edge); out.println(tab2 + "id" + delim + id); String s = vertexIDProvider.getVertexName(g.getEdgeSource(edge)); out.println(tab2 + "source" + delim + s); String t = vertexIDProvider.getVertexName(g.getEdgeTarget(edge)); out.println(tab2 + "target" + delim + t); if ((printLabels == PRINT_EDGE_LABELS) || (printLabels == PRINT_EDGE_VERTEX_LABELS)) { String label = (edgeLabelProvider == null) ? edge.toString() : edgeLabelProvider.getEdgeName(edge); out.println(tab2 + "label" + delim + quoted(label)); } out.println(tab1 + "]"); } } private void export(Writer output, Graph g, boolean directed) { PrintWriter out = new PrintWriter(output); for (V from : g.vertexSet()) { // assign ids in vertex set iteration order vertexIDProvider.getVertexName(from); } exportHeader(out); out.println("graph"); out.println("["); out.println(tab1 + "label" + delim + quoted("")); if (directed) { out.println(tab1 + "directed" + delim + "1"); } else { out.println(tab1 + "directed" + delim + "0"); } exportVertices(out, g); exportEdges(out, g); out.println("]"); out.flush(); } /** * Exports an undirected graph into a plain text file in GML format. * * @param output the writer to which the graph to be exported * @param g the undirected graph to be exported */ public void export(Writer output, UndirectedGraph g) { export(output, g, false); } /** * Exports a directed graph into a plain text file in GML format. * * @param output the writer to which the graph to be exported * @param g the directed graph to be exported */ public void export(Writer output, DirectedGraph g) { export(output, g, true); } /** * Set whether to export the vertex and edge labels. The default behavior is * to export no vertex or edge labels. * * @param i What labels to export. Valid options are {@link * #PRINT_NO_LABELS}, {@link #PRINT_EDGE_LABELS}, {@link * #PRINT_EDGE_VERTEX_LABELS}, and {@link #PRINT_VERTEX_LABELS}. * * @throws IllegalArgumentException if a non-supported value is used * * @see #PRINT_NO_LABELS * @see #PRINT_EDGE_LABELS * @see #PRINT_EDGE_VERTEX_LABELS * @see #PRINT_VERTEX_LABELS */ public void setPrintLabels(final Integer i) { if ((i != PRINT_NO_LABELS) && (i != PRINT_EDGE_LABELS) && (i != PRINT_EDGE_VERTEX_LABELS) && (i != PRINT_VERTEX_LABELS)) { throw new IllegalArgumentException( "Non-supported parameter value: " + Integer.toString(i)); } printLabels = i; } /** * Get whether to export the vertex and edge labels. * * @return One of the {@link #PRINT_NO_LABELS}, {@link #PRINT_EDGE_LABELS}, * {@link #PRINT_EDGE_VERTEX_LABELS}, or {@link #PRINT_VERTEX_LABELS}. */ public Integer getPrintLabels() { return printLabels; } } // End GmlExporter.java jgrapht-0.8.3/src/org/jgrapht/ext/IntegerNameProvider.java0000644000175000017500000000542311706124626023771 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * IntegerNameProvider.java * ------------------ * (C) Copyright 2005-2008, by Charles Fry and Contributors. * * Original Author: Charles Fry * * $Id: IntegerNameProvider.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Dec-2005 : Initial Version (CF); * */ package org.jgrapht.ext; import java.util.*; import org.jgrapht.event.*; /** * Assigns a unique integer to represent each vertex. Each instance of * IntegerNameProvider maintains an internal map between every vertex it has * ever seen and the unique integer representing that vertex. As a result it is * probably desirable to have a separate instance for each distinct graph. * * @author Charles Fry */ public class IntegerNameProvider implements VertexNameProvider { //~ Instance fields -------------------------------------------------------- private int nextID = 1; private final Map idMap = new HashMap(); //~ Methods ---------------------------------------------------------------- /** * Clears all cached identifiers, and resets the unique identifier counter. */ public void clear() { nextID = 1; idMap.clear(); } /** * Returns the String representation of the unique integer representing a * vertex. * * @param vertex the vertex to be named * * @return the name of * * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public String getVertexName(V vertex) { Integer id = idMap.get(vertex); if (id == null) { id = nextID++; idMap.put(vertex, id); } return id.toString(); } } // End IntegerNameProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/StringNameProvider.java0000644000175000017500000000443211706124626023641 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * StringNameProvider.java * ------------------ * (C) Copyright 2005-2008, by Charles Fry and Contributors. * * Original Author: Charles Fry * * $Id: StringNameProvider.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Dec-2005 : Initial Version (CF); * */ package org.jgrapht.ext; import org.jgrapht.event.*; /** * Generates vertex names by invoking {@link #toString()} on them. This assumes * that the vertex's {@link #toString()} method returns a unique String * representation for each vertex. * * @author Charles Fry */ public class StringNameProvider implements VertexNameProvider { //~ Constructors ----------------------------------------------------------- public StringNameProvider() { } //~ Methods ---------------------------------------------------------------- /** * Returns the String representation of the unique integer representing a * vertex. * * @param vertex the vertex to be named * * @return the name of * * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public String getVertexName(V vertex) { return vertex.toString(); } } // End StringNameProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/JGraphModelAdapter.java0000644000175000017500000011652411706124626023522 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * JGraphModelAdapter.java * ----------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Erik Postma * * $Id: JGraphModelAdapter.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 02-Aug-2003 : Initial revision (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 06-Nov-2003 : Allowed non-listenable underlying JGraphT graph (BN); * 12-Dec-2003 : Added CellFactory support (BN); * 27-Jan-2004 : Added support for JGraph->JGraphT change propagation (EP); * 29-Jan-2005 : Added support for JGraph dangling edges (BN); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht.ext; import java.awt.Color; import java.awt.Font; import java.awt.geom.*; import java.io.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.*; import org.jgraph.event.*; import org.jgraph.event.GraphModelEvent.*; import org.jgraph.graph.*; import org.jgrapht.*; import org.jgrapht.event.*; /** * An adapter that reflects a JGraphT graph as a JGraph graph. This adapter is * useful when using JGraph in order to visualize JGraphT graphs. For more about * JGraph see * http://jgraph.sourceforge.net * *

    Modifications made to the underlying JGraphT graph are reflected to this * JGraph model if and only if the underlying JGraphT graph is a {@link * org.jgrapht.ListenableGraph}. If the underlying JGraphT graph is not * ListenableGraph, then this JGraph model represent a snapshot if the graph at * the time of its creation.

    * *

    Changes made to this JGraph model are also reflected back to the * underlying JGraphT graph. To avoid confusion, variables are prefixed * according to the JGraph/JGraphT object(s) they are referring to.

    * *

    KNOWN BUGS: There is a small issue to be aware of. JGraph allows * 'dangling edges' incident with just one vertex; JGraphT doesn't. Such a * configuration can arise when adding an edge or removing a vertex. The code * handles this by removing the newly-added dangling edge or removing all edges * incident with the vertex before actually removing the vertex, respectively. * This works very well, only it doesn't play all that nicely with the * undo-manager in the JGraph: for the second situation where you remove a * vertex incident with some edges, if you undo the removal, the vertex is * 'unremoved' but the edges aren't.

    * * @author Barak Naveh * @since Aug 2, 2003 */ /* * FUTURE WORK: Now that the adapter supports JGraph dangling edges, it is * possible, with a little effort, to eliminate the "known bugs" above. Some * todo and fixme marks in the code indicate where the possible improvements * could be made to realize that. */ public class JGraphModelAdapter extends DefaultGraphModel { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3256722883706302515L; //~ Instance fields -------------------------------------------------------- /** * The following (jCells|jtElement)Being(Added|Removed) sets are used to * prevent bouncing of events between the JGraph and JGraphT listeners. They * ensure that their respective add/remove operations are done exactly once. * Here is an example of how jCellsBeingAdded is used when an edge is added * to a JGraph graph: * *
            1. First, we add the desired edge to jCellsBeingAdded to indicate
            that the edge is being inserted internally.
            2.    Then we invoke the JGraph 'insert' operation.
            3.    The JGraph listener will detect the newly inserted edge.
            4.    It checks if the edge is contained in jCellsBeingAdded.
            5.    If yes,
            it just removes it and does nothing else.
            if no,
            it knows that the edge was inserted externally and performs
            the insertion.
            6. Lastly, we remove the edge from the jCellsBeingAdded.
         * 
    * *

    Step 6 is not always required but we do it anyway as a safeguard * against the rare case where the edge to be added is already contained in * the graph and thus NO event will be fired. If 6 is not done, a junk edge * will remain in the jCellsBeingAdded set.

    * *

    The other sets are used in a similar manner to the above. Apparently, * All that complication could be eliminated if JGraph and JGraphT had both * allowed operations that do not inform listeners...

    */ final Set jCellsBeingAdded = new HashSet(); final Set jCellsBeingRemoved = new HashSet(); final Set jtElementsBeingAdded = new HashSet(); final Set jtElementsBeingRemoved = new HashSet(); private final CellFactory cellFactory; /** * Maps JGraph edges to JGraphT edges */ private final Map cellToEdge = new HashMap(); /** * Maps JGraph vertices to JGraphT vertices */ private final Map cellToVertex = new HashMap(); private AttributeMap defaultEdgeAttributes; private AttributeMap defaultVertexAttributes; /** * Maps JGraphT edges to JGraph edges */ private final Map edgeToCell = new HashMap(); /** * Maps JGraphT vertices to JGraph vertices */ private final Map vertexToCell = new HashMap(); private final ShieldedGraph jtGraph; //~ Constructors ----------------------------------------------------------- /** * Constructs a new JGraph model adapter for the specified JGraphT graph. * * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to * be created. null is NOT permitted. */ public JGraphModelAdapter(Graph jGraphTGraph) { this( jGraphTGraph, createDefaultVertexAttributes(), createDefaultEdgeAttributes(jGraphTGraph)); } /** * Constructs a new JGraph model adapter for the specified JGraphT graph. * * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to * be created. null is NOT permitted. * @param defaultVertexAttributes a default map of JGraph attributes to * format vertices. null is NOT permitted. * @param defaultEdgeAttributes a default map of JGraph attributes to format * edges. null is NOT permitted. */ public JGraphModelAdapter( Graph jGraphTGraph, AttributeMap defaultVertexAttributes, AttributeMap defaultEdgeAttributes) { this( jGraphTGraph, defaultVertexAttributes, defaultEdgeAttributes, new DefaultCellFactory()); } /** * Constructs a new JGraph model adapter for the specified JGraphT graph. * * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to * be created. null is NOT permitted. * @param defaultVertexAttributes a default map of JGraph attributes to * format vertices. null is NOT permitted. * @param defaultEdgeAttributes a default map of JGraph attributes to format * edges. null is NOT permitted. * @param cellFactory a {@link CellFactory} to be used to create the JGraph * cells. null is NOT permitted. * * @throws IllegalArgumentException */ public JGraphModelAdapter( Graph jGraphTGraph, AttributeMap defaultVertexAttributes, AttributeMap defaultEdgeAttributes, CellFactory cellFactory) { super(); if ((jGraphTGraph == null) || (defaultVertexAttributes == null) || (defaultEdgeAttributes == null) || (cellFactory == null)) { throw new IllegalArgumentException("null is NOT permitted"); } jtGraph = new ShieldedGraph(jGraphTGraph); setDefaultVertexAttributes(defaultVertexAttributes); setDefaultEdgeAttributes(defaultEdgeAttributes); this.cellFactory = cellFactory; if (jGraphTGraph instanceof ListenableGraph) { ListenableGraph g = (ListenableGraph) jGraphTGraph; g.addGraphListener(new JGraphTListener()); } for ( Iterator i = jGraphTGraph.vertexSet().iterator(); i.hasNext();) { handleJGraphTAddedVertex(i.next()); } for (Iterator i = jGraphTGraph.edgeSet().iterator(); i.hasNext();) { handleJGraphTAddedEdge(i.next()); } this.addGraphModelListener(new JGraphListener()); } //~ Methods ---------------------------------------------------------------- /** * Creates and returns a map of attributes to be used as defaults for edge * attributes, depending on the specified graph. * * @param jGraphTGraph the graph for which default edge attributes to be * created. * * @return a map of attributes to be used as default for edge attributes. */ public static AttributeMap createDefaultEdgeAttributes( Graph jGraphTGraph) { AttributeMap map = new AttributeMap(); if (jGraphTGraph instanceof DirectedGraph) { GraphConstants.setLineEnd(map, GraphConstants.ARROW_TECHNICAL); GraphConstants.setEndFill(map, true); GraphConstants.setEndSize(map, 10); } GraphConstants.setForeground(map, Color.decode("#25507C")); GraphConstants.setFont( map, GraphConstants.DEFAULTFONT.deriveFont(Font.BOLD, 12)); GraphConstants.setLineColor(map, Color.decode("#7AA1E6")); return map; } /** * Creates and returns a map of attributes to be used as defaults for vertex * attributes. * * @return a map of attributes to be used as defaults for vertex attributes. */ public static AttributeMap createDefaultVertexAttributes() { AttributeMap map = new AttributeMap(); Color c = Color.decode("#FF9900"); GraphConstants.setBounds(map, new Rectangle2D.Double(50, 50, 90, 30)); GraphConstants.setBorder(map, BorderFactory.createRaisedBevelBorder()); GraphConstants.setBackground(map, c); GraphConstants.setForeground(map, Color.white); GraphConstants.setFont( map, GraphConstants.DEFAULTFONT.deriveFont(Font.BOLD, 12)); GraphConstants.setOpaque(map, true); return map; } /** * Returns the cell factory used to create the JGraph cells. * * @return the cell factory used to create the JGraph cells. */ public CellFactory getCellFactory() { return cellFactory; } /** * Sets the default edge attributes used for creating new JGraph edges. * * @param defaultEdgeAttributes the default edge attributes to set. */ public void setDefaultEdgeAttributes(AttributeMap defaultEdgeAttributes) { this.defaultEdgeAttributes = defaultEdgeAttributes; } /** * Returns the default edge attributes used for creating new JGraph edges. * * @return the default edge attributes used for creating new JGraph edges. */ public AttributeMap getDefaultEdgeAttributes() { return defaultEdgeAttributes; } /** * Sets the default vertex attributes used for creating new JGraph vertices. * * @param defaultVertexAttributes the default vertex attributes to set. */ public void setDefaultVertexAttributes( AttributeMap defaultVertexAttributes) { this.defaultVertexAttributes = defaultVertexAttributes; } /** * Returns the default vertex attributes used for creating new JGraph * vertices. * * @return the default vertex attributes used for creating new JGraph * vertices. */ public AttributeMap getDefaultVertexAttributes() { return defaultVertexAttributes; } /** * Returns the JGraph edge cell that corresponds to the specified JGraphT * edge. If no corresponding cell found, returns null. * * @param jGraphTEdge a JGraphT edge of the JGraphT graph. * * @return the JGraph edge cell that corresponds to the specified JGraphT * edge, or null if no corresponding cell found. */ public DefaultEdge getEdgeCell(E jGraphTEdge) { return (DefaultEdge) edgeToCell.get(jGraphTEdge); } /** * Returns the JGraph vertex cell that corresponds to the specified JGraphT * vertex. If no corresponding cell found, returns null. * * @param jGraphTVertex a JGraphT vertex of the JGraphT graph. * * @return the JGraph vertex cell that corresponds to the specified JGraphT * vertex, or null if no corresponding cell found. */ public DefaultGraphCell getVertexCell(Object jGraphTVertex) { return (DefaultGraphCell) vertexToCell.get(jGraphTVertex); } /** * Returns the JGraph port cell that corresponds to the specified JGraphT * vertex. If no corresponding port found, returns null. * * @param jGraphTVertex a JGraphT vertex of the JGraphT graph. * * @return the JGraph port cell that corresponds to the specified JGraphT * vertex, or null if no corresponding cell found. */ public DefaultPort getVertexPort(Object jGraphTVertex) { DefaultGraphCell vertexCell = getVertexCell(jGraphTVertex); if (vertexCell == null) { return null; } else { return (DefaultPort) vertexCell.getChildAt(0); } } /** * Adds/removes an edge to/from the underlying JGraphT graph according to * the change in the specified JGraph edge. If both vertices are connected, * we ensure to have a corresponding JGraphT edge. Otherwise, we ensure NOT * to have a corresponding JGraphT edge. * *

    This method is to be called only for edges that have already been * changed in the JGraph graph.

    * * @param jEdge the JGraph edge that has changed. */ void handleJGraphChangedEdge(org.jgraph.graph.Edge jEdge) { if (isDangling(jEdge)) { if (cellToEdge.containsKey(jEdge)) { // a non-dangling edge became dangling -- remove the JGraphT // edge by faking as if the edge is removed from the JGraph. // TODO: Consider keeping the JGraphT edges outside the graph // to avoid loosing user data, such as weights. handleJGraphRemovedEdge(jEdge); } else { // a dangling edge is still dangling -- just ignore. } } else { // edge is not dangling if (cellToEdge.containsKey(jEdge)) { // edge already has a corresponding JGraphT edge. // check if any change to its endpoints. E jtEdge = cellToEdge.get(jEdge); Object jSource = getSourceVertex(this, jEdge); Object jTarget = getTargetVertex(this, jEdge); Object jtSource = cellToVertex.get(jSource); Object jtTarget = cellToVertex.get(jTarget); if ((jtGraph.getEdgeSource(jtEdge) == jtSource) && (jtGraph.getEdgeTarget(jtEdge) == jtTarget)) { // no change in edge's endpoints -- nothing to do. } else { // edge's end-points have changed -- need to refresh the // JGraphT edge. Refresh by faking as if the edge has been // removed from JGraph and then added again. // ALSO HERE: consider an alternative that maintains user // data handleJGraphRemovedEdge(jEdge); handleJGraphInsertedEdge(jEdge); } } else { // a new edge handleJGraphInsertedEdge(jEdge); } } } /** * Adds to the underlying JGraphT graph an edge that corresponds to the * specified JGraph edge. If the specified JGraph edge is a dangling edge, * it is NOT added to the underlying JGraphT graph. * *

    This method is to be called only for edges that have already been * added to the JGraph graph.

    * * @param jEdge the JGraph edge that has been added. */ void handleJGraphInsertedEdge(org.jgraph.graph.Edge jEdge) { if (isDangling(jEdge)) { // JGraphT forbid dangling edges so we cannot add the edge yet. If // later the edge becomes connected, we will add it. } else { // FIXME hb 28-nov-05: waiting for jgraph to go generic Object jSource = getSourceVertex(this, jEdge); Object jTarget = getTargetVertex(this, jEdge); V jtSource = cellToVertex.get(jSource); V jtTarget = cellToVertex.get(jTarget); E jtEdge = jtGraph.addEdge(jtSource, jtTarget); if (jtEdge != null) { cellToEdge.put(jEdge, jtEdge); edgeToCell.put(jtEdge, jEdge); } else { // Adding failed because user is using a JGraphT graph the // forbids parallel edges. // For consistency, we remove the edge from the JGraph too. internalRemoveCell(jEdge); System.err.println( "Warning: an edge was deleted because the underlying " + "JGraphT graph refused to create it. " + "This situation can happen when a constraint of the " + "underlying graph is violated, e.g., an attempt to add " + "a parallel edge or a self-loop to a graph that forbids " + "them. To avoid this message, make sure to use a " + "suitable underlying JGraphT graph."); } } } /** * Adds to the underlying JGraphT graph a vertex corresponding to the * specified JGraph vertex. In JGraph, two vertices with the same user * object are in principle allowed; in JGraphT, this would lead to duplicate * vertices, which is not allowed. So if such vertex already exists, the * specified vertex is REMOVED from the JGraph graph and a a warning is * printed. * *

    This method is to be called only for vertices that have already been * added to the JGraph graph.

    * * @param jVertex the JGraph vertex that has been added. */ @SuppressWarnings("unchecked") void handleJGraphInsertedVertex(GraphCell jVertex) { V jtVertex; if (jVertex instanceof DefaultGraphCell) { // FIXME hb 28-nov-05: waiting for jgraph to go generic jtVertex = (V) ((DefaultGraphCell) jVertex).getUserObject(); } else { // FIXME: Why toString? Explain if for a good reason otherwise fix. jtVertex = (V) jVertex.toString(); } if (vertexToCell.containsKey(jtVertex)) { // We have to remove the new vertex, because it would lead to // duplicate vertices. We can't use ShieldedGraph.removeVertex for // that, because it would remove the wrong (existing) vertex. System.err.println( "Warning: detected two JGraph vertices with " + "the same JGraphT vertex as user object. It is an " + "indication for a faulty situation that should NOT happen." + "Removing vertex: " + jVertex); internalRemoveCell(jVertex); } else { jtGraph.addVertex(jtVertex); cellToVertex.put(jVertex, jtVertex); vertexToCell.put(jtVertex, jVertex); } } /** * Removes the edge corresponding to the specified JGraph edge from the * JGraphT graph. If the specified edge is not contained in {@link * #cellToEdge}, it is silently ignored. * *

    This method is to be called only for edges that have already been * removed from the JGraph graph.

    * * @param jEdge the JGraph edge that has been removed. */ void handleJGraphRemovedEdge(org.jgraph.graph.Edge jEdge) { if (cellToEdge.containsKey(jEdge)) { E jtEdge = cellToEdge.get(jEdge); jtGraph.removeEdge(jtEdge); cellToEdge.remove(jEdge); edgeToCell.remove(jtEdge); } } /** * Removes the vertex corresponding to the specified JGraph vertex from the * JGraphT graph. If the specified vertex is not contained in {@link * #cellToVertex}, it is silently ignored. * *

    If any edges are incident with this vertex, we first remove them from * the both graphs, because otherwise the JGraph graph would leave them * intact and the JGraphT graph would throw them out. TODO: Revise this * behavior now that we gracefully tolerate dangling edges. It might be * possible to remove just the JGraphT edges. The JGraph edges will be left * dangling, as a result.

    * *

    This method is to be called only for vertices that have already been * removed from the JGraph graph.

    * * @param jVertex the JGraph vertex that has been removed. */ void handleJGraphRemovedVertex(GraphCell jVertex) { if (cellToVertex.containsKey(jVertex)) { V jtVertex = cellToVertex.get(jVertex); Set jtIncidentEdges = jtGraph.edgesOf(jtVertex); if (!jtIncidentEdges.isEmpty()) { // We can't just call removeAllEdges with this list: that // would throw a ConcurrentModificationException. So we create // a shallow copy. // This also triggers removal of the corresponding JGraph // edges. jtGraph.removeAllEdges(new ArrayList(jtIncidentEdges)); } jtGraph.removeVertex(jtVertex); cellToVertex.remove(jVertex); vertexToCell.remove(jtVertex); } } /** * Adds the specified JGraphT edge to be reflected by this graph model. To * be called only for edges that already exist in the JGraphT graph. * * @param jtEdge a JGraphT edge to be reflected by this graph model. */ void handleJGraphTAddedEdge(E jtEdge) { DefaultEdge edgeCell = cellFactory.createEdgeCell(jtEdge); edgeToCell.put(jtEdge, edgeCell); cellToEdge.put(edgeCell, jtEdge); ConnectionSet cs = new ConnectionSet(); cs.connect( edgeCell, getVertexPort(jtGraph.getEdgeSource(jtEdge)), getVertexPort(jtGraph.getEdgeTarget(jtEdge))); internalInsertCell(edgeCell, createEdgeAttributeMap(edgeCell), cs); } /** * Adds the specified JGraphT vertex to be reflected by this graph model. To * be called only for edges that already exist in the JGraphT graph. * * @param jtVertex a JGraphT vertex to be reflected by this graph model. */ void handleJGraphTAddedVertex(V jtVertex) { DefaultGraphCell vertexCell = cellFactory.createVertexCell(jtVertex); vertexCell.add(new DefaultPort()); vertexToCell.put(jtVertex, vertexCell); cellToVertex.put(vertexCell, jtVertex); internalInsertCell( vertexCell, createVertexAttributeMap(vertexCell), null); } /** * Removes the specified JGraphT vertex from being reflected by this graph * model. To be called only for vertices that have already been removed from * the JGraphT graph. * * @param jtVertex a JGraphT vertex to be removed from being reflected by * this graph model. */ void handleJGraphTRemoveVertex(Object jtVertex) { DefaultGraphCell vertexCell = (DefaultGraphCell) vertexToCell.remove(jtVertex); cellToVertex.remove(vertexCell); List ports = new ArrayList(); for (Object child : vertexCell.getChildren()) { if (this.isPort(child)) { ports.add(child); } } this.remove(ports.toArray()); internalRemoveCell(vertexCell); } /** * Removes the specified JGraphT edge from being reflected by this graph * model. To be called only for edges that have already been removed from * the JGraphT graph. * * @param jtEdge a JGraphT edge to be removed from being reflected by this * graph model. */ void handleJGraphTRemovedEdge(E jtEdge) { DefaultEdge edgeCell = (DefaultEdge) edgeToCell.remove(jtEdge); cellToEdge.remove(edgeCell); internalRemoveCell(edgeCell); } /** * Tests if the specified JGraph edge is 'dangling', that is having at least * one endpoint which is not connected to a vertex. * * @param jEdge the JGraph edge to be tested for being dangling. * * @return true if the specified edge is dangling, otherwise * false. */ private boolean isDangling(org.jgraph.graph.Edge jEdge) { Object jSource = getSourceVertex(this, jEdge); Object jTarget = getTargetVertex(this, jEdge); return !cellToVertex.containsKey(jSource) || !cellToVertex.containsKey(jTarget); } @SuppressWarnings("unchecked") private AttributeMap createEdgeAttributeMap(DefaultEdge edgeCell) { AttributeMap attrs = new AttributeMap(); // FIXME hb 28-nov-05: waiting for graph to go generic attrs.put(edgeCell, getDefaultEdgeAttributes().clone()); return attrs; } @SuppressWarnings("unchecked") private AttributeMap createVertexAttributeMap(GraphCell vertexCell) { AttributeMap attrs = new AttributeMap(); // FIXME hb 28-nov-05: waiting for graph to go generic attrs.put(vertexCell, getDefaultVertexAttributes().clone()); return attrs; } /** * Inserts the specified cell into the JGraph graph model. * * @param cell * @param attrs * @param cs */ // FIXME hb 28-nov-05: waiting for graph to go generic private void internalInsertCell( GraphCell cell, AttributeMap attrs, ConnectionSet cs) { jCellsBeingAdded.add(cell); insert(new Object[] { cell }, attrs, cs, null, null); jCellsBeingAdded.remove(cell); } /** * Removed the specified cell from the JGraph graph model. * * @param cell */ private void internalRemoveCell(GraphCell cell) { jCellsBeingRemoved.add(cell); remove(new Object[] { cell }); jCellsBeingRemoved.remove(cell); } //~ Inner Interfaces ------------------------------------------------------- /** * Creates the JGraph cells that reflect the respective JGraphT elements. * * @author Barak Naveh * @since Dec 12, 2003 */ public static interface CellFactory { /** * Creates an edge cell that contains its respective JGraphT edge. * * @param jGraphTEdge a JGraphT edge to be contained. * * @return an edge cell that contains its respective JGraphT edge. */ public DefaultEdge createEdgeCell(EE jGraphTEdge); /** * Creates a vertex cell that contains its respective JGraphT vertex. * * @param jGraphTVertex a JGraphT vertex to be contained. * * @return a vertex cell that contains its respective JGraphT vertex. */ public DefaultGraphCell createVertexCell(VV jGraphTVertex); } //~ Inner Classes ---------------------------------------------------------- /** * A simple default cell factory. * * @author Barak Naveh * @since Dec 12, 2003 */ public static class DefaultCellFactory implements CellFactory, Serializable { private static final long serialVersionUID = 3690194343461861173L; /** * @see JGraphModelAdapter.CellFactory#createEdgeCell(Object) */ public DefaultEdge createEdgeCell(EE jGraphTEdge) { return new DefaultEdge(jGraphTEdge); } /** * @see JGraphModelAdapter.CellFactory#createVertexCell(Object) */ public DefaultGraphCell createVertexCell(VV jGraphTVertex) { return new DefaultGraphCell(jGraphTVertex); } } /** *

    Inner class listening to the GraphModel. If something is changed in * the GraphModel, this Listener gets notified and propagates the change * back to the JGraphT graph, if it didn't originate there.

    * *

    If this change contains changes that would make this an illegal * JGraphT graph, like adding an edge that is incident with only one vertex, * the illegal parts of the change are undone.

    */ private class JGraphListener implements GraphModelListener, Serializable { private static final long serialVersionUID = 3544673988098865209L; /** * This method is called for all JGraph changes. * * @param e */ public void graphChanged(GraphModelEvent e) { // We first remove edges that have to be removed, then we // remove vertices, then we add vertices and finally we add // edges. Otherwise, things might go wrong: for example, if we // would first remove vertices and then edges, removal of the // vertices might induce 'automatic' removal of edges. If we // later attempt to re-remove these edges, we get confused. GraphModelChange change = e.getChange(); Object [] removedCells = change.getRemoved(); if (removedCells != null) { handleRemovedEdges(filterEdges(removedCells)); handleRemovedVertices(filterVertices(removedCells)); } Object [] insertedCells = change.getInserted(); if (insertedCells != null) { handleInsertedVertices(filterVertices(insertedCells)); handleInsertedEdges(filterEdges(insertedCells)); } // Now handle edges that became 'dangling' or became connected. Object [] changedCells = change.getChanged(); if (changedCells != null) { handleChangedEdges(filterEdges(changedCells)); } } /** * Filters a list of edges out of an array of JGraph GraphCell objects. * Other objects are thrown away. * * @param cells Array of cells to be filtered. * * @return a list of edges. */ private List filterEdges(Object [] cells) { List jEdges = new ArrayList(); for (int i = 0; i < cells.length; i++) { if (cells[i] instanceof org.jgraph.graph.Edge) { jEdges.add(cells[i]); } } return jEdges; } /** * Filters a list of vertices out of an array of JGraph GraphCell * objects. Other objects are thrown away. * * @param cells Array of cells to be filtered. * * @return a list of vertices. */ private List filterVertices(Object [] cells) { List jVertices = new ArrayList(); for (int i = 0; i < cells.length; i++) { Object cell = cells[i]; if (cell instanceof org.jgraph.graph.Edge) { // ignore -- we don't care about edges. } else if (cell instanceof Port) { // ignore -- we don't care about ports. } else if (cell instanceof DefaultGraphCell) { DefaultGraphCell graphCell = (DefaultGraphCell) cell; // If a DefaultGraphCell has a Port as a child, it is a // vertex. // Note: do not change the order of following conditions; // the code uses the short-circuit evaluation of ||. if (graphCell.isLeaf() || (graphCell.getFirstChild() instanceof Port)) { jVertices.add(cell); } } else if (cell instanceof GraphCell) { // If it is not a DefaultGraphCell, it doesn't have // children. jVertices.add(cell); } } return jVertices; } private void handleChangedEdges(List jEdges) { for (Iterator i = jEdges.iterator(); i.hasNext();) { org.jgraph.graph.Edge jEdge = (org.jgraph.graph.Edge) i.next(); handleJGraphChangedEdge(jEdge); } } private void handleInsertedEdges(List jEdges) { for (Iterator i = jEdges.iterator(); i.hasNext();) { org.jgraph.graph.Edge jEdge = (org.jgraph.graph.Edge) i.next(); if (!jCellsBeingAdded.remove(jEdge)) { handleJGraphInsertedEdge(jEdge); } } } private void handleInsertedVertices(List jVertices) { for (Iterator i = jVertices.iterator(); i.hasNext();) { GraphCell jVertex = (GraphCell) i.next(); if (!jCellsBeingAdded.remove(jVertex)) { handleJGraphInsertedVertex(jVertex); } } } private void handleRemovedEdges(List jEdges) { for (Iterator i = jEdges.iterator(); i.hasNext();) { org.jgraph.graph.Edge jEdge = (org.jgraph.graph.Edge) i.next(); if (!jCellsBeingRemoved.remove(jEdge)) { handleJGraphRemovedEdge(jEdge); } } } private void handleRemovedVertices(List jVertices) { for (Iterator i = jVertices.iterator(); i.hasNext();) { GraphCell jVertex = (GraphCell) i.next(); if (!jCellsBeingRemoved.remove(jVertex)) { handleJGraphRemovedVertex(jVertex); } } } } /** * A listener on the underlying JGraphT graph. This listener is used to keep * the JGraph model in sync. Whenever one of the event handlers is called, * it first checks whether the change is due to a previous change in the * JGraph model. If it is, then no action is taken. * * @author Barak Naveh * @since Aug 2, 2003 */ private class JGraphTListener implements GraphListener, Serializable { private static final long serialVersionUID = 3616724963609360440L; /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded(GraphEdgeChangeEvent e) { E jtEdge = e.getEdge(); if (!jtElementsBeingAdded.remove(jtEdge)) { handleJGraphTAddedEdge(jtEdge); } } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved(GraphEdgeChangeEvent e) { E jtEdge = e.getEdge(); if (!jtElementsBeingRemoved.remove(jtEdge)) { handleJGraphTRemovedEdge(jtEdge); } } /** * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded(GraphVertexChangeEvent e) { V jtVertex = e.getVertex(); if (!jtElementsBeingAdded.remove(jtVertex)) { handleJGraphTAddedVertex(jtVertex); } } /** * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved(GraphVertexChangeEvent e) { V jtVertex = e.getVertex(); if (!jtElementsBeingRemoved.remove(jtVertex)) { handleJGraphTRemoveVertex(jtVertex); } } } /** * A wrapper around a JGraphT graph that ensures a few atomic operations. */ private class ShieldedGraph { private final Graph graph; ShieldedGraph(Graph graph) { this.graph = graph; } E addEdge(V jtSource, V jtTarget) { E jtEdge = graph.getEdgeFactory().createEdge(jtSource, jtTarget); jtElementsBeingAdded.add(jtEdge); boolean added = graph.addEdge(jtSource, jtTarget, jtEdge); jtElementsBeingAdded.remove(jtEdge); return added ? jtEdge : null; } V getEdgeSource(E e) { return graph.getEdgeSource(e); } V getEdgeTarget(E e) { return graph.getEdgeTarget(e); } void addVertex(V jtVertex) { jtElementsBeingAdded.add(jtVertex); graph.addVertex(jtVertex); jtElementsBeingAdded.remove(jtVertex); } Set edgesOf(V vertex) { return graph.edgesOf(vertex); } boolean removeAllEdges(Collection edges) { return graph.removeAllEdges(edges); } void removeEdge(E jtEdge) { jtElementsBeingRemoved.add(jtEdge); graph.removeEdge(jtEdge); jtElementsBeingRemoved.remove(jtEdge); } void removeVertex(V jtVertex) { jtElementsBeingRemoved.add(jtVertex); graph.removeVertex(jtVertex); jtElementsBeingRemoved.remove(jtVertex); } } } // End JGraphModelAdapter.java jgrapht-0.8.3/src/org/jgrapht/ext/VertexNameProvider.java0000644000175000017500000000373611706124626023656 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * VertexNameProvider.java * ------------------ * (C) Copyright 2005-2008, by Avner Linder and Contributors. * * Original Author: Avner Linder * * $Id: VertexNameProvider.java 713 2010-06-13 01:07:50Z perfecthash $ * * Changes * ------- * 27-May-2004 : Initial Version (AL); * 13-Dec-2005 : Split out of VisioExporter (CF); * */ package org.jgrapht.ext; /** * Assigns a display name for each of the graph vertices. */ public interface VertexNameProvider { //~ Methods ---------------------------------------------------------------- /** * Returns a unique name for a vertex. This is useful when exporting a a * graph, as it ensures that all vertices are assigned simple, consistent * names. * * @param vertex the vertex to be named * * @return the name of the vertex */ public String getVertexName(V vertex); } // End VertexNameProvider.java jgrapht-0.8.3/src/org/jgrapht/ext/GraphMLExporter.java0000644000175000017500000002131511706124626023101 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * GraphMLExporter.java * ------------------ * (C) Copyright 2006, by Trevor Harmon. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; import java.io.*; import javax.xml.transform.*; import javax.xml.transform.sax.*; import javax.xml.transform.stream.*; import org.jgrapht.*; import org.xml.sax.*; import org.xml.sax.helpers.*; /** * Exports a graph into a GraphML file. * *

    For a description of the format see * http://en.wikipedia.org/wiki/GraphML.

    * * @author Trevor Harmon */ public class GraphMLExporter { //~ Instance fields -------------------------------------------------------- private VertexNameProvider vertexIDProvider; private VertexNameProvider vertexLabelProvider; private EdgeNameProvider edgeIDProvider; private EdgeNameProvider edgeLabelProvider; //~ Constructors ----------------------------------------------------------- /** * Constructs a new GraphMLExporter object with integer name providers for * the vertex and edge IDs and null providers for the vertex and edge * labels. */ public GraphMLExporter() { this( new IntegerNameProvider(), null, new IntegerEdgeNameProvider(), null); } /** * Constructs a new GraphMLExporter object with the given ID and label * providers. * * @param vertexIDProvider for generating vertex IDs. Must not be null. * @param vertexLabelProvider for generating vertex labels. If null, vertex * labels will not be written to the file. * @param edgeIDProvider for generating vertex IDs. Must not be null. * @param edgeLabelProvider for generating edge labels. If null, edge labels * will not be written to the file. */ public GraphMLExporter( VertexNameProvider vertexIDProvider, VertexNameProvider vertexLabelProvider, EdgeNameProvider edgeIDProvider, EdgeNameProvider edgeLabelProvider) { this.vertexIDProvider = vertexIDProvider; this.vertexLabelProvider = vertexLabelProvider; this.edgeIDProvider = edgeIDProvider; this.edgeLabelProvider = edgeLabelProvider; } //~ Methods ---------------------------------------------------------------- /** * Exports a graph into a plain text file in GraphML format. * * @param writer the writer to which the graph to be exported * @param g the graph to be exported */ public void export(Writer writer, Graph g) throws SAXException, TransformerConfigurationException { // Prepare an XML file to receive the GraphML data PrintWriter out = new PrintWriter(writer); StreamResult streamResult = new StreamResult(out); SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = factory.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(streamResult); handler.startDocument(); AttributesImpl attr = new AttributesImpl(); // handler.startPrefixMapping( "xsi", "http://www.w3.org/2001/XMLSchema-instance"); // FIXME: Is this the proper way to add this attribute? attr.addAttribute( "", "", "xsi:schemaLocation", "CDATA", "http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"); handler.startElement( "http://graphml.graphdrawing.org/xmlns", "", "graphml", attr); handler.endPrefixMapping("xsi"); if (vertexLabelProvider != null) { // for vertex label attribute attr.clear(); attr.addAttribute("", "", "id", "CDATA", "vertex_label"); attr.addAttribute("", "", "for", "CDATA", "node"); attr.addAttribute("", "", "attr.name", "CDATA", "Vertex Label"); attr.addAttribute("", "", "attr.type", "CDATA", "string"); handler.startElement("", "", "key", attr); handler.endElement("", "", "key"); } if (edgeLabelProvider != null) { // for edge label attribute attr.clear(); attr.addAttribute("", "", "id", "CDATA", "edge_label"); attr.addAttribute("", "", "for", "CDATA", "edge"); attr.addAttribute("", "", "attr.name", "CDATA", "Edge Label"); attr.addAttribute("", "", "attr.type", "CDATA", "string"); handler.startElement("", "", "key", attr); handler.endElement("", "", "key"); } // attr.clear(); attr.addAttribute( "", "", "edgedefault", "CDATA", (g instanceof DirectedGraph) ? "directed" : "undirected"); handler.startElement("", "", "graph", attr); // Add all the vertices as elements... for (V v : g.vertexSet()) { // attr.clear(); attr.addAttribute( "", "", "id", "CDATA", vertexIDProvider.getVertexName(v)); handler.startElement("", "", "node", attr); if (vertexLabelProvider != null) { // attr.clear(); attr.addAttribute("", "", "key", "CDATA", "vertex_label"); handler.startElement("", "", "data", attr); // Content for String vertexLabel = vertexLabelProvider.getVertexName(v); handler.characters( vertexLabel.toCharArray(), 0, vertexLabel.length()); handler.endElement("", "", "data"); } handler.endElement("", "", "node"); } // Add all the edges as elements... for (E e : g.edgeSet()) { // attr.clear(); attr.addAttribute( "", "", "id", "CDATA", edgeIDProvider.getEdgeName(e)); attr.addAttribute( "", "", "source", "CDATA", vertexIDProvider.getVertexName(g.getEdgeSource(e))); attr.addAttribute( "", "", "target", "CDATA", vertexIDProvider.getVertexName(g.getEdgeTarget(e))); handler.startElement("", "", "edge", attr); if (edgeLabelProvider != null) { // attr.clear(); attr.addAttribute("", "", "key", "CDATA", "edge_label"); handler.startElement("", "", "data", attr); // Content for String edgeLabel = edgeLabelProvider.getEdgeName(e); handler.characters( edgeLabel.toCharArray(), 0, edgeLabel.length()); handler.endElement("", "", "data"); } handler.endElement("", "", "edge"); } handler.endElement("", "", "graph"); handler.endElement("", "", "graphml"); handler.endDocument(); out.flush(); } } // End GraphMLExporter.java jgrapht-0.8.3/src/org/jgrapht/ext/DOTExporter.java0000644000175000017500000002162711706124626022243 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * DOTExporter.java * ------------------ * (C) Copyright 2006, by Trevor Harmon. * * Original Author: Trevor Harmon * */ package org.jgrapht.ext; import java.io.*; import java.util.*; import org.jgrapht.*; /** * Exports a graph into a DOT file. * *

    For a description of the format see * http://en.wikipedia.org/wiki/DOT_language.

    * * @author Trevor Harmon */ public class DOTExporter { //~ Instance fields -------------------------------------------------------- private VertexNameProvider vertexIDProvider; private VertexNameProvider vertexLabelProvider; private EdgeNameProvider edgeLabelProvider; private ComponentAttributeProvider vertexAttributeProvider; private ComponentAttributeProvider edgeAttributeProvider; //~ Constructors ----------------------------------------------------------- /** * Constructs a new DOTExporter object with an integer name provider for the * vertex IDs and null providers for the vertex and edge labels. */ public DOTExporter() { this(new IntegerNameProvider(), null, null); } /** * Constructs a new DOTExporter object with the given ID and label * providers. * * @param vertexIDProvider for generating vertex IDs. Must not be null. * @param vertexLabelProvider for generating vertex labels. If null, vertex * labels will not be written to the file. * @param edgeLabelProvider for generating edge labels. If null, edge labels * will not be written to the file. */ public DOTExporter( VertexNameProvider vertexIDProvider, VertexNameProvider vertexLabelProvider, EdgeNameProvider edgeLabelProvider) { this( vertexIDProvider, vertexLabelProvider, edgeLabelProvider, null, null); } /** * Constructs a new DOTExporter object with the given ID, label, and * attribute providers. Note that if a label provider conflicts with a * label-supplying attribute provider, the label provider is given * precedence. * * @param vertexIDProvider for generating vertex IDs. Must not be null. * @param vertexLabelProvider for generating vertex labels. If null, vertex * labels will not be written to the file (unless an attribute provider is * supplied which also supplies labels). * @param edgeLabelProvider for generating edge labels. If null, edge labels * will not be written to the file. * @param vertexAttributeProvider for generating vertex attributes. If null, * vertex attributes will not be written to the file. * @param edgeAttributeProvider for generating edge attributes. If null, * edge attributes will not be written to the file. */ public DOTExporter( VertexNameProvider vertexIDProvider, VertexNameProvider vertexLabelProvider, EdgeNameProvider edgeLabelProvider, ComponentAttributeProvider vertexAttributeProvider, ComponentAttributeProvider edgeAttributeProvider) { this.vertexIDProvider = vertexIDProvider; this.vertexLabelProvider = vertexLabelProvider; this.edgeLabelProvider = edgeLabelProvider; this.vertexAttributeProvider = vertexAttributeProvider; this.edgeAttributeProvider = edgeAttributeProvider; } //~ Methods ---------------------------------------------------------------- /** * Exports a graph into a plain text file in DOT format. * * @param writer the writer to which the graph to be exported * @param g the graph to be exported */ public void export(Writer writer, Graph g) { PrintWriter out = new PrintWriter(writer); String indent = " "; String connector; if (g instanceof DirectedGraph) { out.println("digraph G {"); connector = " -> "; } else { out.println("graph G {"); connector = " -- "; } for (V v : g.vertexSet()) { out.print(indent + getVertexID(v)); String labelName = null; if (vertexLabelProvider != null) { labelName = vertexLabelProvider.getVertexName(v); } Map attributes = null; if (vertexAttributeProvider != null) { attributes = vertexAttributeProvider.getComponentAttributes(v); } renderAttributes(out, labelName, attributes); out.println(";"); } for (E e : g.edgeSet()) { String source = getVertexID(g.getEdgeSource(e)); String target = getVertexID(g.getEdgeTarget(e)); out.print(indent + source + connector + target); String labelName = null; if (edgeLabelProvider != null) { labelName = edgeLabelProvider.getEdgeName(e); } Map attributes = null; if (edgeAttributeProvider != null) { attributes = edgeAttributeProvider.getComponentAttributes(e); } renderAttributes(out, labelName, attributes); out.println(";"); } out.println("}"); out.flush(); } private void renderAttributes( PrintWriter out, String labelName, Map attributes) { if ((labelName == null) && (attributes == null)) { return; } out.print(" [ "); if ((labelName == null) && (attributes != null)) { labelName = attributes.get("label"); } if (labelName != null) { out.print("label=\"" + labelName + "\" "); } if (attributes != null) { for (Map.Entry entry : attributes.entrySet()) { String name = entry.getKey(); if (name.equals("label")) { // already handled by special case above continue; } out.print(name + "=\"" + entry.getValue() + "\" "); } } out.print("]"); } /** * Return a valid vertex ID (with respect to the .dot language definition as * described in http://www.graphviz.org/doc/info/lang.html Quoted from above * mentioned source: An ID is valid if it meets one of the following * criteria: * *
      *
    • any string of alphabetic characters, underscores or digits, not * beginning with a digit; *
    • a number [-]?(.[0-9]+ | [0-9]+(.[0-9]*)? ); *
    • any double-quoted string ("...") possibly containing escaped quotes * (\"); *
    • an HTML string (<...>). *
    * * @throws RuntimeException if the given vertexIDProvider * didn't generate a valid vertex ID. */ private String getVertexID(V v) { // TODO jvs 28-Jun-2008: possible optimizations here are // (a) only validate once per vertex // (b) compile regex patterns // use the associated id provider for an ID of the given vertex String idCandidate = vertexIDProvider.getVertexName(v); // now test that this is a valid ID boolean isAlphaDig = idCandidate.matches("[a-zA-Z]+([\\w_]*)?"); boolean isDoubleQuoted = idCandidate.matches("\".*\""); boolean isDotNumber = idCandidate.matches("[-]?([.][0-9]+|[0-9]+([.][0-9]*)?)"); boolean isHTML = idCandidate.matches("<.*>"); if (isAlphaDig || isDotNumber || isDoubleQuoted || isHTML) { return idCandidate; } throw new RuntimeException( "Generated id '" + idCandidate + "'for vertex '" + v + "' is not valid with respect to the .dot language"); } } // End DOTExporter.java jgrapht-0.8.3/src/org/jgrapht/GraphPath.java0000644000175000017500000000643511706124626021142 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------- * Graph.java * ---------- * (C) Copyright 2008-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: GraphPath.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 1-Jan-2008 : Initial revision (JVS); * */ package org.jgrapht; import java.util.*; /** * A GraphPath represents a * path in a {@link Graph}. Note that a path is defined primarily in terms * of edges (rather than vertices) so that multiple edges between the same pair * of vertices can be discriminated. * * @author John Sichi * @since Jan 1, 2008 */ public interface GraphPath { //~ Methods ---------------------------------------------------------------- /** * Returns the graph over which this path is defined. The path may also be * valid with respect to other graphs. * * @return the containing graph */ public Graph getGraph(); /** * Returns the start vertex in the path. * * @return the start vertex */ public V getStartVertex(); /** * Returns the end vertex in the path. * * @return the end vertex */ public V getEndVertex(); /** * Returns the edges making up the path. The first edge in this path is * incident to the start vertex. The last edge is incident to the end * vertex. The vertices along the path can be obtained by traversing from * the start vertex, finding its opposite across the first edge, and then * doing the same successively across subsequent edges; {@link * Graphs#getPathVertexList} provides a convenience method for this. * *

    Whether or not the returned edge list is modifiable depends on the * path implementation. * * @return list of edges traversed by the path */ public List getEdgeList(); /** * Returns the weight assigned to the path. Typically, this will be the sum * of the weights of the edge list entries (as defined by the containing * graph), but some path implementations may use other definitions. * * @return the weight of the path */ public double getWeight(); } // End GraphPath.java jgrapht-0.8.3/src/org/jgrapht/WeightedGraph.java0000644000175000017500000000425711706124626022006 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * WeightedGraph.java * ------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: WeightedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 13-Aug-2003 : Included weight methods in Edge interface (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht; /** * An interface for a graph whose edges have non-uniform weights. * * @author Barak Naveh * @since Jul 23, 2003 */ public interface WeightedGraph extends Graph { //~ Static fields/initializers --------------------------------------------- /** * The default weight for an edge. */ public static double DEFAULT_EDGE_WEIGHT = 1.0; //~ Methods ---------------------------------------------------------------- /** * Assigns a weight to an edge. * * @param e edge on which to set weight * @param weight new weight for edge */ public void setEdgeWeight(E e, double weight); } // End WeightedGraph.java jgrapht-0.8.3/src/org/jgrapht/Graphs.java0000644000175000017500000003510511706124626020504 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * Graphs.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * Mikael Hansen * * $Id: Graphs.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 10-Jul-2003 : Initial revision (BN); * 06-Nov-2003 : Change edge sharing semantics (JVS); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht; import java.util.*; import org.jgrapht.graph.*; /** * A collection of utilities to assist with graph manipulation. * * @author Barak Naveh * @since Jul 31, 2003 */ public abstract class Graphs { //~ Methods ---------------------------------------------------------------- /** * Creates a new edge and adds it to the specified graph similarly to the * {@link Graph#addEdge(Object, Object)} method. * * @param g the graph for which the edge to be added. * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * @param weight weight of the edge. * * @return The newly created edge if added to the graph, otherwise * null. * * @see Graph#addEdge(Object, Object) */ public static E addEdge( Graph g, V sourceVertex, V targetVertex, double weight) { EdgeFactory ef = g.getEdgeFactory(); E e = ef.createEdge(sourceVertex, targetVertex); // we first create the edge and set the weight to make sure that // listeners will see the correct weight upon addEdge. assert (g instanceof WeightedGraph) : g.getClass(); ((WeightedGraph) g).setEdgeWeight(e, weight); return g.addEdge(sourceVertex, targetVertex, e) ? e : null; } /** * Adds the specified source and target vertices to the graph, if not * already included, and creates a new edge and adds it to the specified * graph similarly to the {@link Graph#addEdge(Object, Object)} method. * * @param g the graph for which the specified edge to be added. * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return The newly created edge if added to the graph, otherwise * null. */ public static E addEdgeWithVertices( Graph g, V sourceVertex, V targetVertex) { g.addVertex(sourceVertex); g.addVertex(targetVertex); return g.addEdge(sourceVertex, targetVertex); } /** * Adds the specified edge to the graph, including its vertices if not * already included. * * @param targetGraph the graph for which the specified edge to be added. * @param sourceGraph the graph in which the specified edge is already * present * @param edge edge to add * * @return true if the target graph did not already contain the * specified edge. */ public static boolean addEdgeWithVertices( Graph targetGraph, Graph sourceGraph, E edge) { V sourceVertex = sourceGraph.getEdgeSource(edge); V targetVertex = sourceGraph.getEdgeTarget(edge); targetGraph.addVertex(sourceVertex); targetGraph.addVertex(targetVertex); return targetGraph.addEdge(sourceVertex, targetVertex, edge); } /** * Adds the specified source and target vertices to the graph, if not * already included, and creates a new weighted edge and adds it to the * specified graph similarly to the {@link Graph#addEdge(Object, Object)} * method. * * @param g the graph for which the specified edge to be added. * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * @param weight weight of the edge. * * @return The newly created edge if added to the graph, otherwise * null. */ public static E addEdgeWithVertices( Graph g, V sourceVertex, V targetVertex, double weight) { g.addVertex(sourceVertex); g.addVertex(targetVertex); return addEdge(g, sourceVertex, targetVertex, weight); } /** * Adds all the vertices and all the edges of the specified source graph to * the specified destination graph. First all vertices of the source graph * are added to the destination graph. Then every edge of the source graph * is added to the destination graph. This method returns true * if the destination graph has been modified as a result of this operation, * otherwise it returns false. * *

    The behavior of this operation is undefined if any of the specified * graphs is modified while operation is in progress.

    * * @param destination the graph to which vertices and edges are added. * @param source the graph used as source for vertices and edges to add. * * @return true if and only if the destination graph has been * changed as a result of this operation. */ public static boolean addGraph( Graph destination, Graph source) { boolean modified = addAllVertices(destination, source.vertexSet()); modified |= addAllEdges(destination, source, source.edgeSet()); return modified; } /** * Adds all the vertices and all the edges of the specified source digraph * to the specified destination digraph, reversing all of the edges. If you * want to do this as a linked view of the source graph (rather than by * copying to a destination graph), use {@link EdgeReversedGraph} instead. * *

    The behavior of this operation is undefined if any of the specified * graphs is modified while operation is in progress.

    * * @param destination the graph to which vertices and edges are added. * @param source the graph used as source for vertices and edges to add. * * @see EdgeReversedGraph */ public static void addGraphReversed( DirectedGraph destination, DirectedGraph source) { addAllVertices(destination, source.vertexSet()); for (E edge : source.edgeSet()) { destination.addEdge( source.getEdgeTarget(edge), source.getEdgeSource(edge)); } } /** * Adds a subset of the edges of the specified source graph to the specified * destination graph. The behavior of this operation is undefined if either * of the graphs is modified while the operation is in progress. {@link * #addEdgeWithVertices} is used for the transfer, so source vertexes will * be added automatically to the target graph. * * @param destination the graph to which edges are to be added * @param source the graph used as a source for edges to add * @param edges the edges to be added * * @return true if this graph changed as a result of the call */ public static boolean addAllEdges( Graph destination, Graph source, Collection edges) { boolean modified = false; for (E e : edges) { V s = source.getEdgeSource(e); V t = source.getEdgeTarget(e); destination.addVertex(s); destination.addVertex(t); modified |= destination.addEdge(s, t, e); } return modified; } /** * Adds all of the specified vertices to the destination graph. The behavior * of this operation is undefined if the specified vertex collection is * modified while the operation is in progress. This method will invoke the * {@link Graph#addVertex(Object)} method. * * @param destination the graph to which edges are to be added * @param vertices the vertices to be added to the graph. * * @return true if graph changed as a result of the call * * @throws NullPointerException if the specified vertices contains one or * more null vertices, or if the specified vertex collection is * null. * * @see Graph#addVertex(Object) */ public static boolean addAllVertices( Graph destination, Collection vertices) { boolean modified = false; for (V v : vertices) { modified |= destination.addVertex(v); } return modified; } /** * Returns a list of vertices that are the neighbors of a specified vertex. * If the graph is a multigraph vertices may appear more than once in the * returned list. * * @param g the graph to look for neighbors in. * @param vertex the vertex to get the neighbors of. * * @return a list of the vertices that are the neighbors of the specified * vertex. */ public static List neighborListOf(Graph g, V vertex) { List neighbors = new ArrayList(); for (E e : g.edgesOf(vertex)) { neighbors.add(getOppositeVertex(g, e, vertex)); } return neighbors; } /** * Returns a list of vertices that are the direct predecessors of a * specified vertex. If the graph is a multigraph, vertices may appear more * than once in the returned list. * * @param g the graph to look for predecessors in. * @param vertex the vertex to get the predecessors of. * * @return a list of the vertices that are the direct predecessors of the * specified vertex. */ public static List predecessorListOf( DirectedGraph g, V vertex) { List predecessors = new ArrayList(); Set edges = g.incomingEdgesOf(vertex); for (E e : edges) { predecessors.add(getOppositeVertex(g, e, vertex)); } return predecessors; } /** * Returns a list of vertices that are the direct successors of a specified * vertex. If the graph is a multigraph vertices may appear more than once * in the returned list. * * @param g the graph to look for successors in. * @param vertex the vertex to get the successors of. * * @return a list of the vertices that are the direct successors of the * specified vertex. */ public static List successorListOf( DirectedGraph g, V vertex) { List successors = new ArrayList(); Set edges = g.outgoingEdgesOf(vertex); for (E e : edges) { successors.add(getOppositeVertex(g, e, vertex)); } return successors; } /** * Returns an undirected view of the specified graph. If the specified graph * is directed, returns an undirected view of it. If the specified graph is * already undirected, just returns it. * * @param g the graph for which an undirected view is to be returned. * * @return an undirected view of the specified graph, if it is directed, or * or the specified graph itself if it is already undirected. * * @throws IllegalArgumentException if the graph is neither DirectedGraph * nor UndirectedGraph. * * @see AsUndirectedGraph */ public static UndirectedGraph undirectedGraph(Graph g) { if (g instanceof DirectedGraph) { return new AsUndirectedGraph((DirectedGraph) g); } else if (g instanceof UndirectedGraph) { return (UndirectedGraph) g; } else { throw new IllegalArgumentException( "Graph must be either DirectedGraph or UndirectedGraph"); } } /** * Tests whether an edge is incident to a vertex. * * @param g graph containing e and v * @param e edge in g * @param v vertex in g * * @return true iff e is incident on v */ public static boolean testIncidence(Graph g, E e, V v) { return (g.getEdgeSource(e).equals(v)) || (g.getEdgeTarget(e).equals(v)); } /** * Gets the vertex opposite another vertex across an edge. * * @param g graph containing e and v * @param e edge in g * @param v vertex in g * * @return vertex opposite to v across e */ public static V getOppositeVertex(Graph g, E e, V v) { V source = g.getEdgeSource(e); V target = g.getEdgeTarget(e); if (v.equals(source)) { return target; } else if (v.equals(target)) { return source; } else { throw new IllegalArgumentException("no such vertex"); } } /** * Gets the list of vertices visited by a path. * * @param path path of interest * * @return corresponding vertex list */ public static List getPathVertexList(GraphPath path) { Graph g = path.getGraph(); List list = new ArrayList(); V v = path.getStartVertex(); list.add(v); for (E e : path.getEdgeList()) { v = getOppositeVertex(g, e, v); list.add(v); } return list; } } // End Graphs.java jgrapht-0.8.3/src/org/jgrapht/package.html0000644000175000017500000000036311706124626020674 0ustar giovannigiovanni The front-end API's interfaces and classes, including {@link org.jgrapht.Graph}, {@link org.jgrapht.DirectedGraph} and {@link org.jgrapht.UndirectedGraph}. jgrapht-0.8.3/src/org/jgrapht/generate/0000755000175000017500000000000011752244357020210 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/generate/RandomGraphGenerator.java0000644000175000017500000003177111706124626025130 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * RandomGraphGenerator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: RandomGraphGenerator.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * This Generator creates a random-topology graph of a specified number of * vertexes and edges. An instance of this generator will always return the same * graph-topology in calls to generateGraph(). The vertexes can be different * (depends on the VertexFactory implementation) * *

    However, two instances which use the same constructor parameters will * produce two different random graphs (note: as with any random generator, * there is always a small possibility that two instances will create the same * results). * * @author Assaf Lehr * @since Aug 6, 2005 */ public class RandomGraphGenerator implements GraphGenerator { //~ Static fields/initializers --------------------------------------------- private static long seedUniquifier = 8682522807148012L; //~ Instance fields -------------------------------------------------------- protected int numOfVertexes; protected int numOfEdges; protected Random randomizer; private long randomizerSeed; //~ Constructors ----------------------------------------------------------- public RandomGraphGenerator(int aNumOfVertexes, int aNumOfEdges) { if ((aNumOfVertexes < 0) || (aNumOfEdges < 0)) { throw new IllegalArgumentException("must be non-negative"); } this.numOfVertexes = aNumOfVertexes; this.numOfEdges = aNumOfEdges; this.randomizerSeed = chooseRandomSeedOnce(); this.randomizer = new Random(this.randomizerSeed); } //~ Methods ---------------------------------------------------------------- /** * Should be called only once on creation. Chooses a seed which can be used * later to reset the randomizer before each method call. This * implementation copies the java.util.Random constructor because there is * no getSeed() there, and seed is protected. * * @author Assaf * @since Aug 6, 2005 */ private synchronized static long chooseRandomSeedOnce() { return (++seedUniquifier + System.nanoTime()); } /** * Resets seed to generate the same random stream. */ private void resetRandomSeed() { this.randomizer.setSeed(this.randomizerSeed); } /** * (non-Javadoc) * * @throws IllegalArgumentException if the aNumOfEdges passed in the * constructor, cannot be created on a graph of the concrete type with * aNumOfVertexes. * org.jgrapht.generate.RandomGraphGenerator.DefaultEdgeTopologyFactory#isNumberOfEdgesValid(org.jgrapht.Graph, * int) * * @see GraphGenerator#generateGraph(Graph, VertexFactory, Map) */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { resetRandomSeed(); // key = generation order (1st,2nd,3rd,...) value=vertex Object // will be used later Map orderToVertexMap = new HashMap(this.numOfVertexes); for (int i = 0; i < this.numOfVertexes; i++) { V currVertex = vertexFactory.createVertex(); target.addVertex(currVertex); orderToVertexMap.put(Integer.valueOf(i), currVertex); } if (target.vertexSet().size() != numOfVertexes) { throw new IllegalArgumentException( "Vertex factory did not produce " + numOfVertexes + " distinct vertices."); } // use specific type of edge factory, depending of the graph type // and edge density EdgeTopologyFactory edgesFactory = edgeTopologyFactoryChooser(target, numOfEdges); if (!edgesFactory.isNumberOfEdgesValid(target, numOfEdges)) { throw new IllegalArgumentException( "numOfEdges is not valid for the graph type " + "\n-> Invalid number Of Edges=" + numOfEdges + " for:" + " graph type=" + target.getClass() + " ,number Of Vertexes=" + this.numOfVertexes + "\n-> Advice: For the Max value , check the javadoc for" + " org.jgrapht.generate.RandomGraphGenerator.DefaultEdgeTopologyFactory"); } edgesFactory.createEdges( target, orderToVertexMap, this.numOfEdges, this.randomizer); } /** * Returns a concrete EdgeTopologyFactory, depending on graph type and * numOfEdges * * @param target * * @return */ private EdgeTopologyFactory edgeTopologyFactoryChooser( Graph target, int numOfEdges) { return new DefaultEdgeTopologyFactory(); } //~ Inner Interfaces ------------------------------------------------------- /** * This class is used to generate the edge topology for a graph. * * @author Assaf * @since Aug 6, 2005 */ public interface EdgeTopologyFactory { /** * Two different calls to the createEdges() with the same parameters * must result in the generation of the same. But if the randomizer is * different, it should, usually, create different edge topology. * * @param targetGraph - guranteed to start with zero edges. * @param orderToVertexMap - key=Integer of vertex order . between zero * to numOfVertexes (exclusive). value = vertex from the graph. unique. * @param numberOfEdges - to create in the graph * @param randomizer */ public void createEdges( Graph targetGraph, Map orderToVertexMap, int numberOfEdges, Random randomizer); /** * Checks if the graph can contain the givven numberOfEdges according to * the graph type restrictions. For example: #V means number of * vertexes in graph *

  • a Simple Graph, can have max of #V*(#V-1)/2 edges. etc * * @param targetGraph guranteed to start with zero edges. * @param numberOfEdges */ public boolean isNumberOfEdgesValid( Graph targetGraph, int numberOfEdges); } //~ Inner Classes ---------------------------------------------------------- /** * Default implementation of the EdgeTopologyFactory interface. randomly * chooses an edge and tries to add it. If the add fails from any reason * (like: self edge / multiple edges in unpermitted graph type) it will just * choose another and try again. Performance: *
  • when the number of possible edges becomes slim , this class will have * a very poor performance , cause it will not use gready methods to choose * them. for example : In simple graph , if #V = N (#x = number Of x) and we * want full mesh #edges= N*(N-1)/2 , the first added edges will do so * quickly (O(1) , the last will take O(N^2). So , do not use it in this * kind of graphs. *
  • If the numberOfEdges is bigger than what the graph can add, there * will be an infinite loop here. It is not tested. * * @author Assaf * @since Aug 6, 2005 */ public class DefaultEdgeTopologyFactory implements EdgeTopologyFactory { public void createEdges( Graph targetGraph, Map orderToVertexMap, int numberOfEdges, Random randomizer) { int iterationsCounter = 0; int edgesCounter = 0; while (edgesCounter < numberOfEdges) { // randomizer.nextInt(int n) return a number between zero // (inclusive) and n(exclusive) VV startVertex = orderToVertexMap.get( Integer.valueOf(randomizer.nextInt(numOfVertexes))); VV endVertex = orderToVertexMap.get( Integer.valueOf(randomizer.nextInt(numOfVertexes))); try { EE resultEdge = targetGraph.addEdge(startVertex, endVertex); if (resultEdge != null) { edgesCounter++; } } catch (Exception e) { // do nothing.just ignore the edge } iterationsCounter++; } } /** * checks if the numOfEdges is smaller than the Max edges according to * the following table: * *

    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Graph TypeDirected / UnDirectedmultiple edgesloopsMax Edges
    SimpleGraphUnDirected--N(N-1)/2
    MultigraphUnDirected+-Infinite
    PseudographUnDirected++Infinite
    SimpleDirectedGraphDirected--N (N-1)
    DefaultDirectedGraphDirected-+N*(N-1)+ N = N^2
    DirectedMultigraphDirected++Infinite
    * * @see RandomGraphGenerator.EdgeTopologyFactory#isNumberOfEdgesValid(Graph, * int) */ public boolean isNumberOfEdgesValid( Graph targetGraph, int numberOfEdges) { boolean result; boolean infinite = false; int maxAllowedEdges = getMaxEdgesForVertexNum(targetGraph); if (maxAllowedEdges == -1) { infinite = true; } if (true == infinite) { result = true; } else if (numberOfEdges <= maxAllowedEdges) { result = true; } else { result = false; } return result; } /** * Return max edges for that graph. If it is infinite return -1 instead. */ public int getMaxEdgesForVertexNum(Graph targetGraph) { int maxAllowedEdges = 0; if (targetGraph instanceof SimpleGraph) { maxAllowedEdges = numOfVertexes * (numOfVertexes - 1) / 2; } else if (targetGraph instanceof SimpleDirectedGraph) { maxAllowedEdges = numOfVertexes * (numOfVertexes - 1); } else if (targetGraph instanceof DefaultDirectedGraph) { maxAllowedEdges = numOfVertexes * numOfVertexes; } else { // This may be overly liberal in the case of something // like a simple graph which has been wrapped with // a graph adapter or view. maxAllowedEdges = -1; // infinite } return maxAllowedEdges; } } } // End RandomGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/CompleteBipartiteGraphGenerator.java0000644000175000017500000000745511706124626027326 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * CompleteBipartiteGraphGenerator.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: CompleteBipartiteGraphGenerator.java 680 2009-05-25 05:55:31Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a complete * bipartite graph of any size. This is a graph with two partitions; two * vertices will contain an edge if and only if they belong to different * partitions. * * @author Andrew Newell * @since Dec 21, 2008 */ public class CompleteBipartiteGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private int sizeA, sizeB; //~ Constructors ----------------------------------------------------------- /** * Creates a new CompleteBipartiteGraphGenerator object. * * @param partitionOne This is the number of vertices in the first partition * @param partitionTwo This is the number of vertices in the second parition */ public CompleteBipartiteGraphGenerator(int partitionOne, int partitionTwo) { if ((partitionOne < 0) || (partitionTwo < 0)) { throw new IllegalArgumentException("must be non-negative"); } this.sizeA = partitionOne; this.sizeB = partitionTwo; } //~ Methods ---------------------------------------------------------------- /** * Construct a complete bipartite graph */ public void generateGraph( Graph target, final VertexFactory vertexFactory, Map resultMap) { if ((sizeA < 1) && (sizeB < 1)) { return; } //Create vertices in each of the partitions Set a = new HashSet(); Set b = new HashSet(); for (int i = 0; i < sizeA; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); a.add(newVertex); } for (int i = 0; i < sizeB; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); b.add(newVertex); } //Add an edge for each pair of vertices in different partitions for (Iterator iterA = a.iterator(); iterA.hasNext();) { V v = iterA.next(); for (Iterator iterB = b.iterator(); iterB.hasNext();) { target.addEdge(v, iterB.next()); } } } } // End CompleteBipartiteGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/ScaleFreeGraphGenerator.java0000644000175000017500000001235211706124626025533 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * ScaleFreeGraphGenerator.java * ----------------- * (C) Copyright 2008-2008, by Ilya Razenshteyn and Contributors. * * Original Author: Ilya Razenshteyn * Contributor(s): - * * $Id: ScaleFreeGraphGenerator.java 627 2008-08-17 08:17:03Z perfecthash $ * * Changes * ------- */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates directed or undirected scale-free network * of any size. Scale-free network is a connected graph, where degrees of * vertices are distributed in unusual way. There are many vertices with small * degrees and only small amount of vertices with big degrees. * * @author Ilya Razenshteyn */ public class ScaleFreeGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private int size; // size of graphs, generated by this instance of generator private long seed; // initial seed private Random random; // the source of randomness //~ Constructors ----------------------------------------------------------- /** * Constructs a new ScaleFreeGraphGenerator. * * @param size number of vertices to be generated */ public ScaleFreeGraphGenerator( int size) { if (size < 0) { throw new IllegalArgumentException( "invalid size: " + size + " (must be non-negative)"); } this.size = size; random = new Random(); seed = random.nextLong(); } /** * Constructs a new ScaleFreeGraphGenerator using fixed * seed for the random generator. * * @param size number of vertices to be generated * @param seed initial seed for the random generator */ public ScaleFreeGraphGenerator( int size, long seed) { if (size < 0) { throw new IllegalArgumentException( "invalid size: " + size + " (must be non-negative)"); } this.size = size; random = new Random(); this.seed = seed; } //~ Methods ---------------------------------------------------------------- /** * Generates scale-free network with size passed to the * constructor. Each call of this method produces identical output (but if * target is an undirected graph, the directions of edges will be * lost). * * @param target receives the generated edges and vertices; if this is * non-empty on entry, the result will be a disconnected graph since * generated elements will not be connected to existing elements * @param vertexFactory called to produce new vertices * @param resultMap unused parameter */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { random.setSeed(seed); List vertexList = new ArrayList(); List degrees = new ArrayList(); int degreeSum = 0; for (int i = 0; i < size; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); int newDegree = 0; while ((newDegree == 0) && (i != 0)) // we want our graph to be // connected { for (int j = 0; j < vertexList.size(); j++) { if ((degreeSum == 0) || (random.nextInt(degreeSum) < degrees.get(j))) { degrees.set(j, degrees.get(j) + 1); newDegree++; degreeSum += 2; if (random.nextInt(2) == 0) { target.addEdge(vertexList.get(j), newVertex); } else { target.addEdge(newVertex, vertexList.get(j)); } } } } vertexList.add(newVertex); degrees.add(newDegree); } } } // End ScaleFreeGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/EmptyGraphGenerator.java0000644000175000017500000000532411706124626025001 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * EmptyGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: EmptyGraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (JVS); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates an empty * graph of any size. An empty graph is a graph that has no edges. * * @author John V. Sichi * @since Sep 16, 2003 */ public class EmptyGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private int size; //~ Constructors ----------------------------------------------------------- /** * Construct a new EmptyGraphGenerator. * * @param size number of vertices to be generated * * @throws IllegalArgumentException if the specified size is negative. */ public EmptyGraphGenerator(int size) { if (size < 0) { throw new IllegalArgumentException("must be non-negative"); } this.size = size; } //~ Methods ---------------------------------------------------------------- /** * {@inheritDoc} */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { for (int i = 0; i < size; ++i) { target.addVertex(vertexFactory.createVertex()); } } } // End EmptyGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/GraphGenerator.java0000644000175000017500000000556311706124626023767 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * GraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: GraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (JVS); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * GraphGenerator defines an interface for generating new graph structures. * * @author John V. Sichi * @since Sep 16, 2003 */ public interface GraphGenerator { //~ Methods ---------------------------------------------------------------- /** * Generate a graph structure. The topology of the generated graph is * dependent on the implementation. For graphs in which not all vertices * share the same automorphism equivalence class, the generator may produce * a labeling indicating the roles played by generated elements. This is the * purpose of the resultMap parameter. For example, a generator for a wheel * graph would designate a hub vertex. Role names used as keys in resultMap * should be declared as public static final Strings by implementation * classes. * * @param target receives the generated edges and vertices; if this is * non-empty on entry, the result will be a disconnected graph since * generated elements will not be connected to existing elements * @param vertexFactory called to produce new vertices * @param resultMap if non-null, receives implementation-specific mappings * from String roles to graph elements (or collections of graph elements) */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap); } // End GraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/package.html0000644000175000017500000000020311706124626022457 0ustar giovannigiovanni Generators for graphs of various topologies. jgrapht-0.8.3/src/org/jgrapht/generate/GridGraphGenerator.java0000644000175000017500000001140311706124626024563 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2011, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * StarGraphGenerator.java * ------------------- * (C) Copyright 2011-2011, by Assaf Mizrachi and Contributors. * * Original Author: Assaf Mizrachi * Contributor(s): - * * $Id: StarGraphGenerator.java 651 2008-12-24 21:13:41Z perfecthash $ * * Changes * ------- * 3-Jan-2011 : Initial revision (AM); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a bidirectional grid graph of any * size. A grid graph is a two dimensional graph whose vertices correspond to * the points in the plane with integer coordinates, x-coordinates being in the * range 0,..., n, y-coordinates being in the range 1,...m, and two vertices are * connected by an edge whenever the corresponding points are at distance 1. * Vertices are created from left to right and from top to bottom. * * @author Assaf Mizrachi * @since Dec 29, 2010 */ public class GridGraphGenerator implements GraphGenerator { //~ Static fields/initializers --------------------------------------------- /** * Role for the vertices at the corners. */ public static final String CORNER_VERTEX = "Corner Vertex"; //~ Instance fields -------------------------------------------------------- private int rows; private int cols; //~ Constructors ----------------------------------------------------------- /** * Creates a new GridGraphGenerator object with rows x cols dimension. * * @param rows the number of rows * @param cols the number of columns */ public GridGraphGenerator(int rows, int cols) { if (rows < 2) { throw new IllegalArgumentException( "illegal number of rows (" + rows + "). there must be at least two."); } if (cols < 2) { throw new IllegalArgumentException( "illegal number of columns (" + cols + "). there must be at least two."); } this.rows = rows; this.cols = cols; } //~ Methods ---------------------------------------------------------------- /** * {@inheritDoc} */ @Override public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { Map map = new TreeMap(); // Adding all vertices to the set int cornerCtr = 0; for (int i = 0; i < (rows * cols); i++) { V vertex = vertexFactory.createVertex(); target.addVertex(vertex); map.put(i + 1, vertex); boolean isCorner = (i == 0) || (i == (cols - 1)) || (i == (cols * (rows - 1))) || (i == ((rows * cols) - 1)); if (isCorner && (resultMap != null)) { resultMap.put(CORNER_VERTEX + ' ' + ++cornerCtr, vertex); } } // Iterating twice over the key set, for undirected graph edges are // added from upper vertices to lower, and from left to right. The // second addEdge call will return nothing; it will not add a the edge // at the opposite direction. For directed graph, edges in opposite // direction are also added. for (int i : map.keySet()) { for (int j : map.keySet()) { if ((((i % cols) > 0) && ((i + 1) == Integer.valueOf(j))) || ((i + cols) == j)) { target.addEdge(map.get(i), map.get(j)); target.addEdge(map.get(j), map.get(i)); } } } } } // End GridGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/WheelGraphGenerator.java0000644000175000017500000001135211706124626024745 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * WheelGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: WheelGraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (JVS); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a wheel * graph of any size. Reminding a bicycle wheel, a wheel graph has a hub * vertex in the center and a rim of vertices around it that are connected to * each other (as a ring). The rim vertices are also connected to the hub with * edges that are called "spokes". * * @author John V. Sichi * @since Sep 16, 2003 */ public class WheelGraphGenerator implements GraphGenerator { //~ Static fields/initializers --------------------------------------------- /** * Role for the hub vertex. */ public static final String HUB_VERTEX = "Hub Vertex"; //~ Instance fields -------------------------------------------------------- private boolean inwardSpokes; private int size; //~ Constructors ----------------------------------------------------------- /** * Creates a new WheelGraphGenerator object. This constructor is more * suitable for undirected graphs, where spokes' direction is meaningless. * In the directed case, spokes will be oriented from rim to hub. * * @param size number of vertices to be generated. */ public WheelGraphGenerator(int size) { this(size, true); } /** * Construct a new WheelGraphGenerator. * * @param size number of vertices to be generated. * @param inwardSpokes if true and graph is directed, spokes * are oriented from rim to hub; else from hub to rim. * * @throws IllegalArgumentException */ public WheelGraphGenerator(int size, boolean inwardSpokes) { if (size < 0) { throw new IllegalArgumentException("must be non-negative"); } this.size = size; this.inwardSpokes = inwardSpokes; } //~ Methods ---------------------------------------------------------------- /** * {@inheritDoc} */ public void generateGraph( Graph target, final VertexFactory vertexFactory, Map resultMap) { if (size < 1) { return; } // A little trickery to intercept the rim generation. This is // necessary since target may be initially non-empty, meaning we can't // rely on its vertex set after the rim is generated. final Collection rim = new ArrayList(); VertexFactory rimVertexFactory = new VertexFactory() { public V createVertex() { V vertex = vertexFactory.createVertex(); rim.add(vertex); return vertex; } }; RingGraphGenerator ringGenerator = new RingGraphGenerator(size - 1); ringGenerator.generateGraph(target, rimVertexFactory, resultMap); V hubVertex = vertexFactory.createVertex(); target.addVertex(hubVertex); if (resultMap != null) { resultMap.put(HUB_VERTEX, hubVertex); } for (V rimVertex : rim) { if (inwardSpokes) { target.addEdge(rimVertex, hubVertex); } else { target.addEdge(hubVertex, rimVertex); } } } } // End WheelGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/HyperCubeGraphGenerator.java0000644000175000017500000000736611706124626025601 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * HyperCubeGraphGenerator.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: HyperCubeGraphGenerator.java 650 2008-12-24 20:44:06Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a hyper * cube graph of any size. This is a graph that can be represented by bit * strings, so for an n-dimensial hypercube each vertex resembles an n-length * bit string. Then, two vertices are adjacent if and only if their bitstring * differ by exactly one element. * * @author Andrew Newell * @since Dec 21, 2008 */ public class HyperCubeGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private int dim; //~ Constructors ----------------------------------------------------------- /** * Creates a new HyperCubeGraphGenerator object. * * @param dim This is the dimension of the hypercube. */ public HyperCubeGraphGenerator(int dim) { this.dim = dim; } //~ Methods ---------------------------------------------------------------- /** * This will generate the hypercube graph */ public void generateGraph( Graph target, final VertexFactory vertexFactory, Map resultMap) { //Vertices are created, and they are included in the resultmap as their //bitstring representation int order = (int) Math.pow(2, dim); LinkedList vertices = new LinkedList(); for (int i = 0; i < order; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); vertices.add(newVertex); if (resultMap != null) { String s = Integer.toBinaryString(i); while (s.length() < dim) { s = "0" + s; } resultMap.put(s, newVertex); } } //Two vertices will have an edge if their bitstrings differ by exactly //1 element for (int i = 0; i < order; i++) { for (int j = i + 1; j < order; j++) { for (int z = 0; z < dim; z++) { if ((j ^ i) == (1 << z)) { target.addEdge(vertices.get(i), vertices.get(j)); break; } } } } } } // End HyberCubeGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/LinearGraphGenerator.java0000644000175000017500000000673411706124626025123 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * LinearGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: LinearGraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (JVS); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a linear graph of any size. For a directed graph, the edges are * oriented from START_VERTEX to END_VERTEX. * * @author John V. Sichi * @since Sep 16, 2003 */ public class LinearGraphGenerator implements GraphGenerator { //~ Static fields/initializers --------------------------------------------- /** * Role for the first vertex generated. */ public static final String START_VERTEX = "Start Vertex"; /** * Role for the last vertex generated. */ public static final String END_VERTEX = "End Vertex"; //~ Instance fields -------------------------------------------------------- private int size; //~ Constructors ----------------------------------------------------------- /** * Construct a new LinearGraphGenerator. * * @param size number of vertices to be generated * * @throws IllegalArgumentException if the specified size is negative. */ public LinearGraphGenerator(int size) { if (size < 0) { throw new IllegalArgumentException("must be non-negative"); } this.size = size; } //~ Methods ---------------------------------------------------------------- /** * {@inheritDoc} */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { V lastVertex = null; for (int i = 0; i < size; ++i) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); if (lastVertex == null) { if (resultMap != null) { resultMap.put(START_VERTEX, newVertex); } } else { target.addEdge(lastVertex, newVertex); } lastVertex = newVertex; } if ((resultMap != null) && (lastVertex != null)) { resultMap.put(END_VERTEX, lastVertex); } } } // End LinearGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/RingGraphGenerator.java0000644000175000017500000000624111706124626024601 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * RingGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: RingGraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (JVS); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a ring graph of any size. A ring graph is a graph that contains a * single cycle that passes through all its vertices exactly once. For a * directed graph, the generated edges are oriented consistently around the * ring. * * @author John V. Sichi * @since Sep 16, 2003 */ public class RingGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private int size; //~ Constructors ----------------------------------------------------------- /** * Construct a new RingGraphGenerator. * * @param size number of vertices to be generated * * @throws IllegalArgumentException if the specified size is negative. */ public RingGraphGenerator(int size) { if (size < 0) { throw new IllegalArgumentException("must be non-negative"); } this.size = size; } //~ Methods ---------------------------------------------------------------- /** * {@inheritDoc} */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { if (size < 1) { return; } LinearGraphGenerator linearGenerator = new LinearGraphGenerator(size); Map privateMap = new HashMap(); linearGenerator.generateGraph(target, vertexFactory, privateMap); V startVertex = privateMap.get(LinearGraphGenerator.START_VERTEX); V endVertex = privateMap.get(LinearGraphGenerator.END_VERTEX); target.addEdge(endVertex, startVertex); } } // End RingGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/CompleteGraphGenerator.java0000644000175000017500000001067111706124626025454 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * CompleteGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by Tim Shearouse and Contributors. * * Original Author: Tim Shearouse * Contributor(s): - * * $Id: CompleteGraphGenerator.java 598 2008-04-13 02:50:13Z perfecthash $ * * Changes * ------- * 10-Feb-2008 : Initial revision (TS); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a complete graph of any size. A complete graph is a graph where * every vertex shares an edge with every other vertex. If it is a directed * graph, then edges must always exist in both directions. On a side note, a * complete graph is the least efficient possible graph in terms of memory and * cpu usage. Note: This contructor was designed for a simple undirected or * directed graph. It will act strangely when used with certain graph types, * such as undirected multigraphs. Note, though, that a complete undirected * multigraph is rather senseless -- you can keep adding edges and the graph is * never truly complete. * * @author Tim Shearouse * @since Nov 02, 2008 */ public class CompleteGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private int size; //~ Constructors ----------------------------------------------------------- /** * Construct a new CompleteGraphGenerator. * * @param size number of vertices to be generated * * @throws IllegalArgumentException if the specified size is negative. */ public CompleteGraphGenerator(int size) { if (size < 0) { throw new IllegalArgumentException("must be non-negative"); } this.size = size; } //~ Methods ---------------------------------------------------------------- /** * {@inheritDoc} */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { if (size < 1) { return; } //Add all the vertices to the set for (int i = 0; i < size; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); } /* * We want two iterators over the vertex set, one fast and one slow. * The slow one will move through the set once. For each vertex, * the fast iterator moves through the set, adding an edge to all * vertices we haven't connected to yet. * * If we have an undirected graph, the second addEdge call will return * nothing; it will not add a second edge. */ Iterator slowI = target.vertexSet().iterator(); Iterator fastI; while (slowI.hasNext()) { //While there are more vertices in the set V latestVertex = slowI.next(); fastI = target.vertexSet().iterator(); //Jump to the first vertex *past* latestVertex while (fastI.next() != latestVertex) { ; } //And, add edges to all remaining vertices V temp; while (fastI.hasNext()) { temp = fastI.next(); target.addEdge(latestVertex, temp); target.addEdge(temp, latestVertex); } } } } // End CompleteGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/generate/StarGraphGenerator.java0000644000175000017500000000666511706124626024625 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * StarGraphGenerator.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: StarGraphGenerator.java 651 2008-12-24 21:13:41Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates a star * graph of any size. This is a graph where every vertex has exactly one * edge with a center vertex. * * @author Andrew Newell * @since Dec 21, 2008 */ public class StarGraphGenerator implements GraphGenerator { //~ Static fields/initializers --------------------------------------------- public static final String CENTER_VERTEX = "Center Vertex"; //~ Instance fields -------------------------------------------------------- private int order; //~ Constructors ----------------------------------------------------------- /** * Creates a new StarGraphGenerator object. * * @param order number of total vertices including the center vertex */ public StarGraphGenerator(int order) { this.order = order; } //~ Methods ---------------------------------------------------------------- /** * Generates a star graph with the designated order from the constructor */ public void generateGraph( Graph target, final VertexFactory vertexFactory, Map resultMap) { if (order < 1) { return; } //Create center vertex V centerVertex = vertexFactory.createVertex(); target.addVertex(centerVertex); if (resultMap != null) { resultMap.put(CENTER_VERTEX, centerVertex); } //Create other vertices for (int i = 0; i < (order - 1); i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); } //Add one edge between the center vertex and every other vertex Iterator iter = target.vertexSet().iterator(); while (iter.hasNext()) { V v = iter.next(); if (v != centerVertex) { target.addEdge(v, centerVertex); } } } } // End StarGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/EdgeFactory.java0000644000175000017500000000406211706124626021452 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * EdgeFactory.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: EdgeFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht; /** * An edge factory used by graphs for creating new edges. * * @author Barak Naveh * @since Jul 14, 2003 */ public interface EdgeFactory { //~ Methods ---------------------------------------------------------------- /** * Creates a new edge whose endpoints are the specified source and target * vertices. * * @param sourceVertex the source vertex. * @param targetVertex the target vertex. * * @return a new edge whose endpoints are the specified source and target * vertices. */ public E createEdge(V sourceVertex, V targetVertex); } // End EdgeFactory.java jgrapht-0.8.3/src/org/jgrapht/util/0000755000175000017500000000000011752244360017365 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/util/ArrayUnenforcedSet.java0000644000175000017500000000616411706124626024003 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * ArrayUnenforcedSet.java * ----------------- * (C) Copyright 2006-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: ArrayUnenforcedSet.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 07-May-2006 : Initial version (JVS); */ package org.jgrapht.util; import java.util.*; /** * Helper for efficiently representing small sets whose elements are known to be * unique by construction, implying we don't need to enforce the uniqueness * property in the data structure itself. Use with caution. * *

    Note that for equals/hashCode, the class implements the Set behavior * (unordered), not the list behavior (ordered); the fact that it subclasses * ArrayList should be considered an implementation detail. * * @author John V. Sichi */ public class ArrayUnenforcedSet extends ArrayList implements Set { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -7413250161201811238L; //~ Constructors ----------------------------------------------------------- public ArrayUnenforcedSet() { super(); } public ArrayUnenforcedSet(Collection c) { super(c); } public ArrayUnenforcedSet(int n) { super(n); } //~ Methods ---------------------------------------------------------------- public boolean equals(Object o) { return new SetForEquality().equals(o); } public int hashCode() { return new SetForEquality().hashCode(); } //~ Inner Classes ---------------------------------------------------------- /** * Multiple inheritance helper. */ private class SetForEquality extends AbstractSet { public Iterator iterator() { return ArrayUnenforcedSet.this.iterator(); } public int size() { return ArrayUnenforcedSet.this.size(); } } } // End ArrayUnenforcedSet.java jgrapht-0.8.3/src/org/jgrapht/util/MathUtil.java0000644000175000017500000000347111706124626021765 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * MathUtil.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: MathUtil.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.util; /** * Math Utilities. Currently contains the following: *

  • factorial(int N) - caclulate the factorial of N (aka N!) * * @author Assaf * @since May 30, 2005 */ public class MathUtil { //~ Methods ---------------------------------------------------------------- public static long factorial(int N) { long multi = 1; for (int i = 1; i <= N; i++) { multi = multi * i; } return multi; } } // End MathUtil.java jgrapht-0.8.3/src/org/jgrapht/util/PrefetchIterator.java0000644000175000017500000001574611706124626023520 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * PrefetchIterator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: PrefetchIterator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.util; import java.util.*; /** * Utility class to help implement an iterator/enumerator in which the hasNext() * method needs to calculate the next elements ahead of time. * *

    Many classes which implement an iterator face a common problem: if there * is no easy way to calculate hasNext() other than to call getNext(), then they * save the result for fetching in the next call to getNext(). This utility * helps in doing just that. * *

    Usage: The new iterator class will hold this class as a member * variable and forward the hasNext() and next() to it. When creating an * instance of this class, you supply it with a functor that is doing the real * job of calculating the next element. * *

    
        //This class supllies enumeration of integer till 100.
        public class IteratorExample implements Enumeration{
        private int counter=0;
        private PrefetchIterator nextSupplier;
    
            IteratorExample()
            {
                nextSupplier = new PrefetchIterator(new PrefetchIterator.NextElementFunctor(){
    
                    public Object nextElement() throws NoSuchElementException {
                        counter++;
                        if (counter>=100)
                            throw new NoSuchElementException();
                        else
                            return new Integer(counter);
                    }
    
                });
            }
            //forwarding to nextSupplier and return its returned value
            public boolean hasMoreElements() {
                return this.nextSupplier.hasMoreElements();
            }
        //  forwarding to nextSupplier and return its returned value
            public Object nextElement() {
                return this.nextSupplier.nextElement();
            }
      }
    * * * @author Assaf_Lehr */ public class PrefetchIterator implements Iterator, Enumeration { //~ Instance fields -------------------------------------------------------- private NextElementFunctor innerEnum; private E getNextLastResult; private boolean isGetNextLastResultUpToDate = false; private boolean endOfEnumerationReached = false; private boolean flagIsEnumerationStartedEmpty = true; private int innerFunctorUsageCounter = 0; //~ Constructors ----------------------------------------------------------- public PrefetchIterator(NextElementFunctor aEnum) { innerEnum = aEnum; } //~ Methods ---------------------------------------------------------------- /** * Serves as one contact place to the functor; all must use it and not * directly the NextElementFunctor. */ private E getNextElementFromInnerFunctor() { innerFunctorUsageCounter++; E result = this.innerEnum.nextElement(); // if we got here , an exception was not thrown, so at least // one time a good value returned flagIsEnumerationStartedEmpty = false; return result; } /** * 1. Retrieves the saved value or calculates it if it does not exist 2. * Changes isGetNextLastResultUpToDate to false. (Because it does not save * the NEXT element now; it saves the current one!) */ public E nextElement() { E result = null; if (this.isGetNextLastResultUpToDate) { result = this.getNextLastResult; } else { result = getNextElementFromInnerFunctor(); } this.isGetNextLastResultUpToDate = false; return result; } /** * If (isGetNextLastResultUpToDate==true) returns true else 1. calculates * getNext() and saves it 2. sets isGetNextLastResultUpToDate to true. */ public boolean hasMoreElements() { if (endOfEnumerationReached) { return false; } if (isGetNextLastResultUpToDate) { return true; } else { try { this.getNextLastResult = getNextElementFromInnerFunctor(); this.isGetNextLastResultUpToDate = true; return true; } catch (NoSuchElementException noSuchE) { endOfEnumerationReached = true; return false; } } // else } // method /** * Tests whether the enumeration started as an empty one. It does not matter * if it hasMoreElements() now, only at initialization time. Efficiency: if * nextElements(), hasMoreElements() were never used, it activates the * hasMoreElements() once. Else it is immediately(O(1)) */ public boolean isEnumerationStartedEmpty() { if (this.innerFunctorUsageCounter == 0) { if (hasMoreElements()) { return false; } else { return true; } } else // it is not the first time , so use the saved value // which was initilaizeed during a call to // getNextElementFromInnerFunctor { return flagIsEnumerationStartedEmpty; } } public boolean hasNext() { return this.hasMoreElements(); } public E next() { return this.nextElement(); } /** * Always throws UnsupportedOperationException. */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } //~ Inner Interfaces ------------------------------------------------------- public interface NextElementFunctor { /** * You must implement that NoSuchElementException is thrown on * nextElement() if it is out of bound. */ public EE nextElement() throws NoSuchElementException; } } // End PrefetchIterator.java jgrapht-0.8.3/src/org/jgrapht/util/package.html0000644000175000017500000000025611706124626021652 0ustar giovannigiovanni Non-graph-specific data structures, algorithms, and utilities used by JGraphT. jgrapht-0.8.3/src/org/jgrapht/util/FibonacciHeap.java0000644000175000017500000004060311706124626022707 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (barak_naveh@users.sourceforge.net) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * FibonnaciHeap.java * -------------------------- * (C) Copyright 1999-2003, by Nathan Fiedler and Contributors. * * Original Author: Nathan Fiedler * Contributor(s): John V. Sichi * * $Id: FibonacciHeap.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 03-Sept-2003 : Adapted from Nathan Fiedler (JVS); * * Name Date Description * ---- ---- ----------- * nf 08/31/97 Initial version * nf 09/07/97 Removed FibHeapData interface * nf 01/20/01 Added synchronization * nf 01/21/01 Made Node an inner class * nf 01/05/02 Added clear(), renamed empty() to * isEmpty(), and renamed printHeap() * to toString() * nf 01/06/02 Removed all synchronization * */ package org.jgrapht.util; import java.util.*; /** * This class implements a Fibonacci heap data structure. Much of the code in * this class is based on the algorithms in the "Introduction to Algorithms"by * Cormen, Leiserson, and Rivest in Chapter 21. The amortized running time of * most of these methods is O(1), making it a very fast data structure. Several * have an actual running time of O(1). removeMin() and delete() have O(log n) * amortized running times because they do the heap consolidation. If you * attempt to store nodes in this heap with key values of -Infinity * (Double.NEGATIVE_INFINITY) the delete() operation may fail to * remove the correct element. * *

    Note that this implementation is not synchronized. If multiple * threads access a set concurrently, and at least one of the threads modifies * the set, it must be synchronized externally. This is typically * accomplished by synchronizing on some object that naturally encapsulates the * set.

    * *

    This class was originally developed by Nathan Fiedler for the GraphMaker * project. It was imported to JGraphT with permission, courtesy of Nathan * Fiedler.

    * * @author Nathan Fiedler */ public class FibonacciHeap { //~ Static fields/initializers --------------------------------------------- private static final double oneOverLogPhi = 1.0 / Math.log((1.0 + Math.sqrt(5.0)) / 2.0); //~ Instance fields -------------------------------------------------------- /** * Points to the minimum node in the heap. */ private FibonacciHeapNode minNode; /** * Number of nodes in the heap. */ private int nNodes; //~ Constructors ----------------------------------------------------------- /** * Constructs a FibonacciHeap object that contains no elements. */ public FibonacciHeap() { } // FibonacciHeap //~ Methods ---------------------------------------------------------------- /** * Tests if the Fibonacci heap is empty or not. Returns true if the heap is * empty, false otherwise. * *

    Running time: O(1) actual

    * * @return true if the heap is empty, false otherwise */ public boolean isEmpty() { return minNode == null; } // isEmpty /** * Removes all elements from this heap. */ public void clear() { minNode = null; nNodes = 0; } // clear /** * Decreases the key value for a heap node, given the new value to take on. * The structure of the heap may be changed and will not be consolidated. * *

    Running time: O(1) amortized

    * * @param x node to decrease the key of * @param k new key value for node x * * @exception IllegalArgumentException Thrown if k is larger than x.key * value. */ public void decreaseKey(FibonacciHeapNode x, double k) { if (k > x.key) { throw new IllegalArgumentException( "decreaseKey() got larger key value"); } x.key = k; FibonacciHeapNode y = x.parent; if ((y != null) && (x.key < y.key)) { cut(x, y); cascadingCut(y); } if (x.key < minNode.key) { minNode = x; } } // decreaseKey /** * Deletes a node from the heap given the reference to the node. The trees * in the heap will be consolidated, if necessary. This operation may fail * to remove the correct element if there are nodes with key value * -Infinity. * *

    Running time: O(log n) amortized

    * * @param x node to remove from heap */ public void delete(FibonacciHeapNode x) { // make x as small as possible decreaseKey(x, Double.NEGATIVE_INFINITY); // remove the smallest, which decreases n also removeMin(); } // delete /** * Inserts a new data element into the heap. No heap consolidation is * performed at this time, the new node is simply inserted into the root * list of this heap. * *

    Running time: O(1) actual

    * * @param node new node to insert into heap * @param key key value associated with data object */ public void insert(FibonacciHeapNode node, double key) { node.key = key; // concatenate node into min list if (minNode != null) { node.left = minNode; node.right = minNode.right; minNode.right = node; node.right.left = node; if (key < minNode.key) { minNode = node; } } else { minNode = node; } nNodes++; } // insert /** * Returns the smallest element in the heap. This smallest element is the * one with the minimum key value. * *

    Running time: O(1) actual

    * * @return heap node with the smallest key */ public FibonacciHeapNode min() { return minNode; } // min /** * Removes the smallest element from the heap. This will cause the trees in * the heap to be consolidated, if necessary. * *

    Running time: O(log n) amortized

    * * @return node with the smallest key */ public FibonacciHeapNode removeMin() { FibonacciHeapNode z = minNode; if (z != null) { int numKids = z.degree; FibonacciHeapNode x = z.child; FibonacciHeapNode tempRight; // for each child of z do... while (numKids > 0) { tempRight = x.right; // remove x from child list x.left.right = x.right; x.right.left = x.left; // add x to root list of heap x.left = minNode; x.right = minNode.right; minNode.right = x; x.right.left = x; // set parent[x] to null x.parent = null; x = tempRight; numKids--; } // remove z from root list of heap z.left.right = z.right; z.right.left = z.left; if (z == z.right) { minNode = null; } else { minNode = z.right; consolidate(); } // decrement size of heap nNodes--; } return z; } // removeMin /** * Returns the size of the heap which is measured in the number of elements * contained in the heap. * *

    Running time: O(1) actual

    * * @return number of elements in the heap */ public int size() { return nNodes; } // size /** * Joins two Fibonacci heaps into a new one. No heap consolidation is * performed at this time. The two root lists are simply joined together. * *

    Running time: O(1) actual

    * * @param h1 first heap * @param h2 second heap * * @return new heap containing h1 and h2 */ public static FibonacciHeap union( FibonacciHeap h1, FibonacciHeap h2) { FibonacciHeap h = new FibonacciHeap(); if ((h1 != null) && (h2 != null)) { h.minNode = h1.minNode; if (h.minNode != null) { if (h2.minNode != null) { h.minNode.right.left = h2.minNode.left; h2.minNode.left.right = h.minNode.right; h.minNode.right = h2.minNode; h2.minNode.left = h.minNode; if (h2.minNode.key < h1.minNode.key) { h.minNode = h2.minNode; } } } else { h.minNode = h2.minNode; } h.nNodes = h1.nNodes + h2.nNodes; } return h; } // union /** * Creates a String representation of this Fibonacci heap. * * @return String of this. */ public String toString() { if (minNode == null) { return "FibonacciHeap=[]"; } // create a new stack and put root on it Stack> stack = new Stack>(); stack.push(minNode); StringBuffer buf = new StringBuffer(512); buf.append("FibonacciHeap=["); // do a simple breadth-first traversal on the tree while (!stack.empty()) { FibonacciHeapNode curr = stack.pop(); buf.append(curr); buf.append(", "); if (curr.child != null) { stack.push(curr.child); } FibonacciHeapNode start = curr; curr = curr.right; while (curr != start) { buf.append(curr); buf.append(", "); if (curr.child != null) { stack.push(curr.child); } curr = curr.right; } } buf.append(']'); return buf.toString(); } // toString /** * Performs a cascading cut operation. This cuts y from its parent and then * does the same for its parent, and so on up the tree. * *

    Running time: O(log n); O(1) excluding the recursion

    * * @param y node to perform cascading cut on */ protected void cascadingCut(FibonacciHeapNode y) { FibonacciHeapNode z = y.parent; // if there's a parent... if (z != null) { // if y is unmarked, set it marked if (!y.mark) { y.mark = true; } else { // it's marked, cut it from parent cut(y, z); // cut its parent as well cascadingCut(z); } } } // cascadingCut protected void consolidate() { int arraySize = ((int) Math.floor(Math.log(nNodes) * oneOverLogPhi)) + 1; List> array = new ArrayList>(arraySize); // Initialize degree array for (int i = 0; i < arraySize; i++) { array.add(null); } // Find the number of root nodes. int numRoots = 0; FibonacciHeapNode x = minNode; if (x != null) { numRoots++; x = x.right; while (x != minNode) { numRoots++; x = x.right; } } // For each node in root list do... while (numRoots > 0) { // Access this node's degree.. int d = x.degree; FibonacciHeapNode next = x.right; // ..and see if there's another of the same degree. for (;;) { FibonacciHeapNode y = array.get(d); if (y == null) { // Nope. break; } // There is, make one of the nodes a child of the other. // Do this based on the key value. if (x.key > y.key) { FibonacciHeapNode temp = y; y = x; x = temp; } // FibonacciHeapNode y disappears from root list. link(y, x); // We've handled this degree, go to next one. array.set(d, null); d++; } // Save this node for later when we might encounter another // of the same degree. array.set(d, x); // Move forward through list. x = next; numRoots--; } // Set min to null (effectively losing the root list) and // reconstruct the root list from the array entries in array[]. minNode = null; for (int i = 0; i < arraySize; i++) { FibonacciHeapNode y = array.get(i); if (y == null) { continue; } // We've got a live one, add it to root list. if (minNode != null) { // First remove node from root list. y.left.right = y.right; y.right.left = y.left; // Now add to root list, again. y.left = minNode; y.right = minNode.right; minNode.right = y; y.right.left = y; // Check if this is a new min. if (y.key < minNode.key) { minNode = y; } } else { minNode = y; } } } // consolidate /** * The reverse of the link operation: removes x from the child list of y. * This method assumes that min is non-null. * *

    Running time: O(1)

    * * @param x child of y to be removed from y's child list * @param y parent of x about to lose a child */ protected void cut(FibonacciHeapNode x, FibonacciHeapNode y) { // remove x from childlist of y and decrement degree[y] x.left.right = x.right; x.right.left = x.left; y.degree--; // reset y.child if necessary if (y.child == x) { y.child = x.right; } if (y.degree == 0) { y.child = null; } // add x to root list of heap x.left = minNode; x.right = minNode.right; minNode.right = x; x.right.left = x; // set parent[x] to nil x.parent = null; // set mark[x] to false x.mark = false; } // cut /** * Make node y a child of node x. * *

    Running time: O(1) actual

    * * @param y node to become child * @param x node to become parent */ protected void link(FibonacciHeapNode y, FibonacciHeapNode x) { // remove y from root list of heap y.left.right = y.right; y.right.left = y.left; // make y a child of x y.parent = x; if (x.child == null) { x.child = y; y.right = y; y.left = y; } else { y.left = x.child; y.right = x.child.right; x.child.right = y; y.right.left = y; } // increase degree[x] x.degree++; // set mark[y] false y.mark = false; } // link } // FibonacciHeap jgrapht-0.8.3/src/org/jgrapht/util/ModifiableInteger.java0000644000175000017500000001740011706124626023604 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * ModifiableInteger.java * ---------------------- * * (C) Copyright 2002-2004, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: ModifiableInteger.java 723 2010-11-25 05:20:29Z perfecthash $ * * Changes * ------- * 2004-05-27 : Initial version (BN); * */ package org.jgrapht.util; /** * The ModifiableInteger class wraps a value of the primitive type * int in an object, similarly to {@link java.lang.Integer}. An * object of type ModifiableInteger contains a single field whose * type is int. * *

    Unlike java.lang.Integer, the int value which the * ModifiableInteger represents can be modified. It becomes useful when used * together with the collection framework. For example, if you want to have a * {@link java.util.List} of counters. You could use Integer but * that would have became wasteful and inefficient if you frequently had to * update the counters.

    * *

    WARNING: Because instances of this class are mutable, great care must be * exercised if used as keys of a {@link java.util.Map} or as values in a {@link * java.util.Set} in a manner that affects equals comparisons while the * instances are keys in the map (or values in the set). For more see * documentation of Map and Set.

    * * @author Barak Naveh * @since May 27, 2004 */ public class ModifiableInteger extends Number implements Comparable { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3618698612851422261L; //~ Instance fields -------------------------------------------------------- /** * The int value represented by this ModifiableInteger. */ public int value; //~ Constructors ----------------------------------------------------------- /** * !!! DON'T USE - Use the {@link #ModifiableInteger(int)} constructor * instead !!! * *

    This constructor is for the use of java.beans.XMLDecoder * deserialization. The constructor is marked as 'deprecated' to indicate to * the programmer against using it by mistake.

    * * @deprecated not really deprecated, just marked so to avoid mistaken use. */ @Deprecated public ModifiableInteger() { } /** * Constructs a newly allocated ModifiableInteger object that * represents the specified int value. * * @param value the value to be represented by the * ModifiableInteger object. */ public ModifiableInteger(int value) { this.value = value; } //~ Methods ---------------------------------------------------------------- /** * Sets a new value for this modifiable integer. * * @param value the new value to set. */ public void setValue(int value) { this.value = value; } /** * Returns the value of this object, similarly to {@link #intValue()}. This * getter is NOT redundant. It is used for serialization by * java.beans.XMLEncoder. * * @return the value. */ public int getValue() { return this.value; } /** * Adds one to the value of this modifiable integer. */ public void increment() { this.value++; } /** * Subtracts one from the value of this modifiable integer. */ public void decrement() { this.value--; } /** * Compares two ModifiableInteger objects numerically. * * @param anotherInteger the ModifiableInteger to be compared. * * @return the value 0 if this ModifiableInteger * is equal to the argument ModifiableInteger; a value less * than 0 if this ModifiableInteger is numerically * less than the argument ModifiableInteger; and a value * greater than 0 if this ModifiableInteger is * numerically greater than the argument ModifiableInteger * (signed comparison). */ public int compareTo(ModifiableInteger anotherInteger) { int thisVal = this.value; int anotherVal = anotherInteger.value; return (thisVal < anotherVal) ? -1 : ((thisVal == anotherVal) ? 0 : 1); } /** * @see Number#doubleValue() */ public double doubleValue() { return this.value; } /** * Compares this object to the specified object. The result is * true if and only if the argument is not null and is * an ModifiableInteger object that contains the same * int value as this object. * * @param o the object to compare with. * * @return true if the objects are the same; false * otherwise. */ public boolean equals(Object o) { if (o instanceof ModifiableInteger) { return this.value == ((ModifiableInteger) o).value; } return false; } /** * @see Number#floatValue() */ public float floatValue() { return this.value; } /** * Returns a hash code for this ModifiableInteger. * * @return a hash code value for this object, equal to the primitive * int value represented by this ModifiableInteger * object. */ public int hashCode() { return this.value; } /** * @see Number#intValue() */ public int intValue() { return this.value; } /** * @see Number#longValue() */ public long longValue() { return this.value; } /** * Returns an Integer object representing this * ModifiableInteger's value. * * @return an Integer representation of the value of this * object. */ public Integer toInteger() { return Integer.valueOf(this.value); } /** * Returns a String object representing this * ModifiableInteger's value. The value is converted to signed * decimal representation and returned as a string, exactly as if the * integer value were given as an argument to the {@link * java.lang.Integer#toString(int)} method. * * @return a string representation of the value of this object in * base 10. */ public String toString() { return String.valueOf(this.value); } } // End ModifiableInteger.java jgrapht-0.8.3/src/org/jgrapht/util/VertexPair.java0000644000175000017500000000653211706124626022330 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * VertexPair.java * ------------------------- * (C) Copyright 2009-2009, by Soren Davidsen and Contributors * * Original Author: Soren Davidsen * * $Id: VertexPair.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 03-Dec-2009 : Initial revision (SD); * */ package org.jgrapht.util; /** * Representation of a pair of vertices; to be replaced by Pair if Sun ever * gets around to adding Pair to java.util. * * @author Soren */ public class VertexPair { //~ Instance fields -------------------------------------------------------- private V n1; private V n2; //~ Constructors ----------------------------------------------------------- public VertexPair(V n1, V n2) { this.n1 = n1; this.n2 = n2; } //~ Methods ---------------------------------------------------------------- public V getFirst() { return n1; } public V getSecond() { return n2; } /** * Assess if this pair contains the vertex. * * @param v The vertex in question * * @return true if contains, false otherwise */ public boolean hasVertex(V v) { return v.equals(n1) || v.equals(n2); } public V getOther(V one) { if (one.equals(n1)) { return n2; } else if (one.equals(n2)) { return n1; } else { return null; } } @Override public String toString() { return n1 + "," + n2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } @SuppressWarnings("unchecked") VertexPair that = (VertexPair) o; if ((n1 != null) ? (!n1.equals(that.n1)) : (that.n1 != null)) { return false; } if ((n2 != null) ? (!n2.equals(that.n2)) : (that.n2 != null)) { return false; } return true; } @Override public int hashCode() { int result = (n1 != null) ? n1.hashCode() : 0; result = (31 * result) + ((n2 != null) ? n2.hashCode() : 0); return result; } } // End VertexPair.java jgrapht-0.8.3/src/org/jgrapht/util/WeightCombiner.java0000644000175000017500000000601111706124626023135 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * WeightCombiner.java * ------------------------- * (C) Copyright 2009-2009, by Ilya Razenshteyn * * Original Author: Ilya Razenshteyn and Contributors. * * $Id: WeightCombiner.java 695 2009-07-06 02:18:35Z perfecthash $ * * Changes * ------- * 02-Feb-2009 : Initial revision (IR); * */ package org.jgrapht.util; /** * Binary operator for edge weights. There are some prewritten operators. */ public interface WeightCombiner { //~ Instance fields -------------------------------------------------------- /** * Sum of weights. */ public WeightCombiner SUM = new WeightCombiner() { public double combine(double a, double b) { return a + b; } }; /** * Minimum weight. */ public WeightCombiner MIN = new WeightCombiner() { public double combine(double a, double b) { return Math.min(a, b); } }; /** * Maximum weight. */ public WeightCombiner MAX = new WeightCombiner() { public double combine(double a, double b) { return Math.max(a, b); } }; /** * First weight. */ public WeightCombiner FIRST = new WeightCombiner() { public double combine(double a, double b) { return a; } }; /** * Second weight. */ public WeightCombiner SECOND = new WeightCombiner() { public double combine(double a, double b) { return b; } }; //~ Methods ---------------------------------------------------------------- /** * Combines two weights. * * @param a first weight * @param b second weight * * @return result of the operator */ double combine(double a, double b); } // End WeightCombiner.java jgrapht-0.8.3/src/org/jgrapht/util/TypeUtil.java0000644000175000017500000000412211706124626022007 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * TypeUtil.java * ----------------- * (C) Copyright 2006-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): - * * $Id: TypeUtil.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 07-May-2006 : Initial version (JVS); */ package org.jgrapht.util; /** * TypeUtil isolates type-unsafety so that code which uses it for legitimate * reasons can stay warning-free. * * @author John V. Sichi */ public class TypeUtil { //~ Methods ---------------------------------------------------------------- /** * Casts an object to a type. * * @param o object to be cast * @param typeDecl conveys the target type information; the actual value is * unused and can be null since this is all just stupid compiler tricks * * @return the result of the cast */ @SuppressWarnings("unchecked") public static T uncheckedCast(Object o, TypeUtil typeDecl) { return (T) o; } } // End TypeUtil.java jgrapht-0.8.3/src/org/jgrapht/util/FibonacciHeapNode.java0000644000175000017500000000774111706124626023523 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (barak_naveh@users.sourceforge.net) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * FibonnaciHeapNode.java * -------------------------- * (C) Copyright 1999-2008, by Nathan Fiedler and Contributors. * * Original Author: Nathan Fiedler * Contributor(s): John V. Sichi * * $Id: FibonacciHeapNode.java 723 2010-11-25 05:20:29Z perfecthash $ * * Changes * ------- * 03-Sept-2003 : Adapted from Nathan Fiedler (JVS); * * Name Date Description * ---- ---- ----------- * nf 08/31/97 Initial version * nf 09/07/97 Removed FibHeapData interface * nf 01/20/01 Added synchronization * nf 01/21/01 Made Node an inner class * nf 01/05/02 Added clear(), renamed empty() to * isEmpty(), and renamed printHeap() * to toString() * nf 01/06/02 Removed all synchronization * JVS 06/24/06 Generics * */ package org.jgrapht.util; /** * Implements a node of the Fibonacci heap. It holds the information necessary * for maintaining the structure of the heap. It also holds the reference to the * key value (which is used to determine the heap structure). * * @author Nathan Fiedler */ public class FibonacciHeapNode { //~ Instance fields -------------------------------------------------------- /** * Node data. */ T data; /** * first child node */ FibonacciHeapNode child; /** * left sibling node */ FibonacciHeapNode left; /** * parent node */ FibonacciHeapNode parent; /** * right sibling node */ FibonacciHeapNode right; /** * true if this node has had a child removed since this node was added to * its parent */ boolean mark; /** * key value for this node */ double key; /** * number of children of this node (does not count grandchildren) */ int degree; //~ Constructors ----------------------------------------------------------- /** * Default constructor. Initializes the right and left pointers, making this * a circular doubly-linked list. * * @param data data for this node */ public FibonacciHeapNode(T data) { right = this; left = this; this.data = data; } //~ Methods ---------------------------------------------------------------- /** * Obtain the key for this node. * * @return the key */ public final double getKey() { return key; } /** * Obtain the data for this node. */ public final T getData() { return data; } /** * Return the string representation of this object. * * @return string representing this object */ public String toString() { return Double.toString(key); } // toString } // End FibonacciHeapNode.java jgrapht-0.8.3/src/org/jgrapht/demo/0000755000175000017500000000000011752244357017342 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/demo/CompleteGraphDemo.java0000644000175000017500000001054611706124626023545 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------- * CompleteGraphDemo.java * -------------------- * (C) Copyright 2003-2008, by Tim Shearouse and Contributors. * * Original Author: Tim Shearouse * Contributor(s): - * * $Id: CompleteGraphDemo.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * */ package org.jgrapht.demo; import java.util.*; import org.jgrapht.*; import org.jgrapht.generate.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; public final class CompleteGraphDemo { //~ Static fields/initializers --------------------------------------------- static Graph completeGraph; //Number of vertices static int size = 10; //~ Methods ---------------------------------------------------------------- public static void main(String [] args) { //Create the graph object; it is null at this point completeGraph = new SimpleGraph(DefaultEdge.class); //Create the CompleteGraphGenerator object CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); //Create the VertexFactory so the generator can create vertices VertexFactory vFactory = new ClassBasedVertexFactory(Object.class); //Use the CompleteGraphGenerator object to make completeGraph a //complete graph with [size] number of vertices completeGenerator.generateGraph(completeGraph, vFactory, null); //Now, replace all the vertices with sequential numbers so we can ID //them Set vertices = new HashSet(); vertices.addAll(completeGraph.vertexSet()); Integer counter = 0; for (Object vertex : vertices) { replaceVertex(vertex, (Object) counter++); } //Print out the graph to be sure it's really complete Iterator iter = new DepthFirstIterator(completeGraph); Object vertex; while (iter.hasNext()) { vertex = iter.next(); System.out.println( "Vertex " + vertex.toString() + " is connected to: " + completeGraph.edgesOf(vertex).toString()); } } public static boolean replaceVertex(Object oldVertex, Object newVertex) { if ((oldVertex == null) || (newVertex == null)) { return false; } Set relatedEdges = completeGraph.edgesOf(oldVertex); completeGraph.addVertex(newVertex); Object sourceVertex; Object targetVertex; for (DefaultEdge e : relatedEdges) { sourceVertex = completeGraph.getEdgeSource(e); targetVertex = completeGraph.getEdgeTarget(e); if (sourceVertex.equals(oldVertex) && targetVertex.equals(oldVertex)) { completeGraph.addEdge(newVertex, newVertex); } else { if (sourceVertex.equals(oldVertex)) { completeGraph.addEdge(newVertex, targetVertex); } else { completeGraph.addEdge(sourceVertex, newVertex); } } } completeGraph.removeVertex(oldVertex); return true; } } // End CompleteGraphDemo.java jgrapht-0.8.3/src/org/jgrapht/demo/JGraphAdapterDemo.java0000644000175000017500000001344511706124626023470 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * JGraphAdapterDemo.java * ---------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: JGraphAdapterDemo.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 03-Aug-2003 : Initial revision (BN); * 07-Nov-2003 : Adaptation to JGraph 3.0 (BN); * */ package org.jgrapht.demo; import java.awt.*; import java.awt.geom.*; import javax.swing.*; import org.jgraph.*; import org.jgraph.graph.*; import org.jgrapht.*; import org.jgrapht.ext.*; import org.jgrapht.graph.*; // resolve ambiguity import org.jgrapht.graph.DefaultEdge; /** * A demo applet that shows how to use JGraph to visualize JGraphT graphs. * * @author Barak Naveh * @since Aug 3, 2003 */ public class JGraphAdapterDemo extends JApplet { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3256444702936019250L; private static final Color DEFAULT_BG_COLOR = Color.decode("#FAFBFF"); private static final Dimension DEFAULT_SIZE = new Dimension(530, 320); //~ Instance fields -------------------------------------------------------- // private JGraphModelAdapter jgAdapter; //~ Methods ---------------------------------------------------------------- /** * An alternative starting point for this demo, to also allow running this * applet as an application. * * @param args ignored. */ public static void main(String [] args) { JGraphAdapterDemo applet = new JGraphAdapterDemo(); applet.init(); JFrame frame = new JFrame(); frame.getContentPane().add(applet); frame.setTitle("JGraphT Adapter to JGraph Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } /** * {@inheritDoc} */ public void init() { // create a JGraphT graph ListenableGraph g = new ListenableDirectedMultigraph( DefaultEdge.class); // create a visualization using JGraph, via an adapter jgAdapter = new JGraphModelAdapter(g); JGraph jgraph = new JGraph(jgAdapter); adjustDisplaySettings(jgraph); getContentPane().add(jgraph); resize(DEFAULT_SIZE); String v1 = "v1"; String v2 = "v2"; String v3 = "v3"; String v4 = "v4"; // add some sample data (graph manipulated via JGraphT) g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addVertex(v4); g.addEdge(v1, v2); g.addEdge(v2, v3); g.addEdge(v3, v1); g.addEdge(v4, v3); // position vertices nicely within JGraph component positionVertexAt(v1, 130, 40); positionVertexAt(v2, 60, 200); positionVertexAt(v3, 310, 230); positionVertexAt(v4, 380, 70); // that's all there is to it!... } private void adjustDisplaySettings(JGraph jg) { jg.setPreferredSize(DEFAULT_SIZE); Color c = DEFAULT_BG_COLOR; String colorStr = null; try { colorStr = getParameter("bgcolor"); } catch (Exception e) { } if (colorStr != null) { c = Color.decode(colorStr); } jg.setBackground(c); } @SuppressWarnings("unchecked") // FIXME hb 28-nov-05: See FIXME below private void positionVertexAt(Object vertex, int x, int y) { DefaultGraphCell cell = jgAdapter.getVertexCell(vertex); AttributeMap attr = cell.getAttributes(); Rectangle2D bounds = GraphConstants.getBounds(attr); Rectangle2D newBounds = new Rectangle2D.Double( x, y, bounds.getWidth(), bounds.getHeight()); GraphConstants.setBounds(attr, newBounds); // TODO: Clean up generics once JGraph goes generic AttributeMap cellAttr = new AttributeMap(); cellAttr.put(cell, attr); jgAdapter.edit(cellAttr, null, null, null); } //~ Inner Classes ---------------------------------------------------------- /** * a listenable directed multigraph that allows loops and parallel edges. */ private static class ListenableDirectedMultigraph extends DefaultListenableGraph implements DirectedGraph { private static final long serialVersionUID = 1L; ListenableDirectedMultigraph(Class edgeClass) { super(new DirectedMultigraph(edgeClass)); } } } // End JGraphAdapterDemo.java jgrapht-0.8.3/src/org/jgrapht/demo/package.html0000644000175000017500000000022311706124626021613 0ustar giovannigiovanni Demo programs that help to get started with JGraphT. jgrapht-0.8.3/src/org/jgrapht/demo/HelloJGraphT.java0000644000175000017500000001001711706124626022462 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * HelloJGraphT.java * ----------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: HelloJGraphT.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 27-Jul-2003 : Initial revision (BN); * */ package org.jgrapht.demo; import java.net.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * A simple introduction to using JGraphT. * * @author Barak Naveh * @since Jul 27, 2003 */ public final class HelloJGraphT { //~ Constructors ----------------------------------------------------------- private HelloJGraphT() { } // ensure non-instantiability. //~ Methods ---------------------------------------------------------------- /** * The starting point for the demo. * * @param args ignored. */ public static void main(String [] args) { UndirectedGraph stringGraph = createStringGraph(); // note undirected edges are printed as: {,} System.out.println(stringGraph.toString()); // create a graph based on URL objects DirectedGraph hrefGraph = createHrefGraph(); // note directed edges are printed as: (,) System.out.println(hrefGraph.toString()); } /** * Creates a toy directed graph based on URL objects that represents link * structure. * * @return a graph based on URL objects. */ private static DirectedGraph createHrefGraph() { DirectedGraph g = new DefaultDirectedGraph(DefaultEdge.class); try { URL amazon = new URL("http://www.amazon.com"); URL yahoo = new URL("http://www.yahoo.com"); URL ebay = new URL("http://www.ebay.com"); // add the vertices g.addVertex(amazon); g.addVertex(yahoo); g.addVertex(ebay); // add edges to create linking structure g.addEdge(yahoo, amazon); g.addEdge(yahoo, ebay); } catch (MalformedURLException e) { e.printStackTrace(); } return g; } /** * Craete a toy graph based on String objects. * * @return a graph based on String objects. */ private static UndirectedGraph createStringGraph() { UndirectedGraph g = new SimpleGraph(DefaultEdge.class); String v1 = "v1"; String v2 = "v2"; String v3 = "v3"; String v4 = "v4"; // add the vertices g.addVertex(v1); g.addVertex(v2); g.addVertex(v3); g.addVertex(v4); // add edges to create a circuit g.addEdge(v1, v2); g.addEdge(v2, v3); g.addEdge(v3, v4); g.addEdge(v4, v1); return g; } } // End HelloJGraphT.java jgrapht-0.8.3/src/org/jgrapht/demo/PerformanceDemo.java0000644000175000017500000001121011706124626023241 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------- * PerformanceDemo.java * -------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: PerformanceDemo.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 10-Aug-2003 : Initial revision (BN); * */ package org.jgrapht.demo; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; /** * A simple demo to test memory and CPU consumption on a graph with 3 million * elements. * *

    NOTE: To run this demo you may need to increase the JVM max mem size. In * Sun's JVM it is done using the "-Xmx" switch. Specify "-Xmx300M" to set it to * 300MB.

    * *

    WARNING: Don't run this demo as-is on machines with less than 512MB * memory. Your machine will start paging severely. You need to first modify it * to have fewer graph elements. This is easily done by changing the loop * counters below.

    * * @author Barak Naveh * @since Aug 10, 2003 */ public final class PerformanceDemo { //~ Methods ---------------------------------------------------------------- /** * The starting point for the demo. * * @param args ignored. */ public static void main(String [] args) { long time = System.currentTimeMillis(); reportPerformanceFor("starting at", time); Graph g = new Pseudograph(DefaultEdge.class); Object prev; Object curr; curr = prev = new Object(); g.addVertex(prev); int numVertices = 10000; int numEdgesPerVertex = 200; int numElements = numVertices * (1 + numEdgesPerVertex); System.out.println( "\n" + "allocating graph with " + numElements + " elements (may take a few tens of seconds)..."); for (int i = 0; i < numVertices; i++) { curr = new Object(); g.addVertex(curr); for (int j = 0; j < numEdgesPerVertex; j++) { g.addEdge(prev, curr); } prev = curr; } reportPerformanceFor("graph allocation", time); time = System.currentTimeMillis(); for ( Iterator i = new BreadthFirstIterator(g); i.hasNext();) { i.next(); } reportPerformanceFor("breadth traversal", time); time = System.currentTimeMillis(); for ( Iterator i = new DepthFirstIterator(g); i.hasNext();) { i.next(); } reportPerformanceFor("depth traversal", time); System.out.println( "\n" + "Paused: graph is still in memory (to check mem consumption)."); System.out.print("press enter to free memory and finish..."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } System.out.println("done."); } private static void reportPerformanceFor(String msg, long refTime) { double time = (System.currentTimeMillis() - refTime) / 1000.0; double mem = usedMemory() / (1024.0 * 1024.0); mem = Math.round(mem * 100) / 100.0; System.out.println(msg + " (" + time + " sec, " + mem + "MB)"); } private static long usedMemory() { Runtime rt = Runtime.getRuntime(); return rt.totalMemory() - rt.freeMemory(); } } // End PerformanceDemo.java jgrapht-0.8.3/src/org/jgrapht/alg/0000755000175000017500000000000011752244357017161 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/alg/NeighborIndex.java0000644000175000017500000002036111706124626022546 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * NeighborIndex.java * -------------------------- * (C) Copyright 2005-2008, by Charles Fry and Contributors. * * Original Author: Charles Fry * * $Id: NeighborIndex.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Dec-2005 : Initial revision (CF); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.event.*; import org.jgrapht.util.*; /** * Maintains a cache of each vertex's neighbors. While lists of neighbors can be * obtained from {@link Graphs}, they are re-calculated at each invocation by * walking a vertex's incident edges, which becomes inordinately expensive when * performed often. * *

    Edge direction is ignored when evaluating neighbors; to take edge * direction into account when indexing neighbors, use {@link * DirectedNeighborIndex}. * *

    A vertex's neighbors are cached the first time they are asked for (i.e. * the index is built on demand). The index will only be updated automatically * if it is added to the associated graph as a listener. If it is added as a * listener to a graph other than the one it indexes, results are undefined.

    * * @author Charles Fry * @since Dec 13, 2005 */ public class NeighborIndex implements GraphListener { //~ Instance fields -------------------------------------------------------- Map> neighborMap = new HashMap>(); private Graph graph; //~ Constructors ----------------------------------------------------------- /** * Creates a neighbor index for the specified undirected graph. * * @param g the graph for which a neighbor index is to be created. */ public NeighborIndex(Graph g) { // no need to distinguish directedgraphs as we don't do traversals graph = g; } //~ Methods ---------------------------------------------------------------- /** * Returns the set of vertices which are adjacent to a specified vertex. The * returned set is backed by the index, and will be updated when the graph * changes as long as the index has been added as a listener to the graph. * * @param v the vertex whose neighbors are desired * * @return all unique neighbors of the specified vertex */ public Set neighborsOf(V v) { return getNeighbors(v).getNeighbors(); } /** * Returns a list of vertices which are adjacent to a specified vertex. If * the graph is a multigraph, vertices may appear more than once in the * returned list. Because a list of neighbors can not be efficiently * maintained, it is reconstructed on every invocation, by duplicating * entries in the neighbor set. It is thus more efficient to use {@link * #neighborsOf(Object)} unless duplicate neighbors are important. * * @param v the vertex whose neighbors are desired * * @return all neighbors of the specified vertex */ public List neighborListOf(V v) { return getNeighbors(v).getNeighborList(); } /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded(GraphEdgeChangeEvent e) { E edge = e.getEdge(); V source = graph.getEdgeSource(edge); V target = graph.getEdgeTarget(edge); // if a map does not already contain an entry, // then skip addNeighbor, since instantiating the map // will take care of processing the edge (which has already // been added) if (neighborMap.containsKey(source)) { getNeighbors(source).addNeighbor(target); } else { getNeighbors(source); } if (neighborMap.containsKey(target)) { getNeighbors(target).addNeighbor(source); } else { getNeighbors(target); } } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved(GraphEdgeChangeEvent e) { E edge = e.getEdge(); V source = graph.getEdgeSource(edge); V target = graph.getEdgeTarget(edge); if (neighborMap.containsKey(source)) { neighborMap.get(source).removeNeighbor(target); } if (neighborMap.containsKey(target)) { neighborMap.get(target).removeNeighbor(source); } } /** * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded(GraphVertexChangeEvent e) { // nothing to cache until there are edges } /** * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved(GraphVertexChangeEvent e) { neighborMap.remove(e.getVertex()); } private Neighbors getNeighbors(V v) { Neighbors neighbors = neighborMap.get(v); if (neighbors == null) { neighbors = new Neighbors(v, Graphs.neighborListOf(graph, v)); neighborMap.put(v, neighbors); } return neighbors; } //~ Inner Classes ---------------------------------------------------------- /** * Stores cached neighbors for a single vertex. Includes support for live * neighbor sets and duplicate neighbors. */ static class Neighbors { private Map neighborCounts = new LinkedHashMap(); // TODO could eventually make neighborSet modifiable, resulting // in edge removals from the graph private Set neighborSet = Collections.unmodifiableSet( neighborCounts.keySet()); public Neighbors(V v, Collection neighbors) { // add all current neighbors for (V neighbor : neighbors) { addNeighbor(neighbor); } } public void addNeighbor(V v) { ModifiableInteger count = neighborCounts.get(v); if (count == null) { count = new ModifiableInteger(1); neighborCounts.put(v, count); } else { count.increment(); } } public void removeNeighbor(V v) { ModifiableInteger count = neighborCounts.get(v); if (count == null) { throw new IllegalArgumentException( "Attempting to remove a neighbor that wasn't present"); } count.decrement(); if (count.getValue() == 0) { neighborCounts.remove(v); } } public Set getNeighbors() { return neighborSet; } public List getNeighborList() { List neighbors = new ArrayList(); for ( Map.Entry entry : neighborCounts.entrySet()) { V v = entry.getKey(); int count = entry.getValue().intValue(); for (int i = 0; i < count; i++) { neighbors.add(v); } } return neighbors; } } } // End NeighborIndex.java jgrapht-0.8.3/src/org/jgrapht/alg/BlockCutpointGraph.java0000644000175000017500000002660611706124626023573 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BlockCutpointGraph.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: BlockCutpointGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Definition of a block of a * graph in MathWorld.
    *
    Definition and lemma taken from the article * Structure-Based Resilience Metrics for Service-Oriented Networks: * *
      *
    • Definition 4.5 Let G(V; E) be a connected undirected graph. The * block-cut point graph (BC graph) of G, denoted by GB(VB; EB), is the * bipartite graph defined as follows. (a) VB has one node corresponding to each * block and one node corresponding to each cut point of G. (b) Each edge fx; yg * in EB joins a block node x to a cut point y if the block corresponding to x * contains the cut point node corresponding to y.
    • *
    • Lemma 4.4 Let G(V; E) be a connected undirected graph. (a) Each * pair of blocks of G share at most one node, and that node is a cutpoint. (b) * The BC graph of G is a tree in which each leaf node corresponds to a block of * G.
    • *
    * * @author Guillaume Boulmier * @since July 5, 2007 */ public class BlockCutpointGraph extends SimpleGraph, DefaultEdge> { //~ Static fields/initializers --------------------------------------------- /** */ private static final long serialVersionUID = -9101341117013163934L; //~ Instance fields -------------------------------------------------------- private Set cutpoints = new HashSet(); /** * DFS (Depth-First-Search) tree. */ private DirectedGraph dfsTree; private UndirectedGraph graph; private int numOrder; private Deque stack = new ArrayDeque(); private Map>> vertex2biconnectedSubgraphs = new HashMap>>(); private Map> vertex2block = new HashMap>(); private Map vertex2numOrder = new HashMap(); //~ Constructors ----------------------------------------------------------- /** * Running time = O(m) where m is the number of edges. */ public BlockCutpointGraph(UndirectedGraph graph) { super(DefaultEdge.class); this.graph = graph; this.dfsTree = new SimpleDirectedGraph( DefaultEdge.class); V s = graph.vertexSet().iterator().next(); this.dfsTree.addVertex(s); dfsVisit(s, s); if (this.dfsTree.edgesOf(s).size() > 1) { this.cutpoints.add(s); } else { this.cutpoints.remove(s); } for (Iterator iter = this.cutpoints.iterator(); iter.hasNext();) { V cutpoint = iter.next(); UndirectedGraph subgraph = new SimpleGraph(this.graph.getEdgeFactory()); subgraph.addVertex(cutpoint); this.vertex2block.put(cutpoint, subgraph); addVertex(subgraph); Set> biconnectedSubgraphs = getBiconnectedSubgraphs(cutpoint); for ( Iterator> iterator = biconnectedSubgraphs.iterator(); iterator.hasNext();) { UndirectedGraph biconnectedSubgraph = iterator.next(); assert (vertexSet().contains(biconnectedSubgraph)); addEdge(subgraph, biconnectedSubgraph); } } } //~ Methods ---------------------------------------------------------------- /** * Returns the vertex if vertex is a cutpoint, and otherwise returns the * block (biconnected component) containing the vertex. * * @param vertex vertex in the initial graph. */ public UndirectedGraph getBlock(V vertex) { if (!this.graph.vertexSet().contains(vertex)) { throw new IllegalArgumentException("No such vertex in the graph!"); } return this.vertex2block.get(vertex); } /** * Returns the cutpoints of the initial graph. */ public Set getCutpoints() { return this.cutpoints; } /** * Returns true if the vertex is a cutpoint, false * otherwise. * * @param vertex vertex in the initial graph. */ public boolean isCutpoint(V vertex) { if (!this.graph.vertexSet().contains(vertex)) { throw new IllegalArgumentException("No such vertex in the graph!"); } return this.cutpoints.contains(vertex); } private void biconnectedComponentFinished(V s, V n) { this.cutpoints.add(s); Set vertexComponent = new HashSet(); Set edgeComponent = new HashSet(); BCGEdge edge = this.stack.removeLast(); while ( (getNumOrder(edge.getSource()) >= getNumOrder(n)) && !this.stack.isEmpty()) { edgeComponent.add(edge); vertexComponent.add(edge.getSource()); vertexComponent.add(edge.getTarget()); edge = this.stack.removeLast(); } edgeComponent.add(edge); // edgeComponent is an equivalence class. vertexComponent.add(edge.getSource()); vertexComponent.add(edge.getTarget()); VertexComponentForbiddenFunction mask = new VertexComponentForbiddenFunction( vertexComponent); UndirectedGraph biconnectedSubgraph = new UndirectedMaskSubgraph( this.graph, mask); for (Iterator iter = vertexComponent.iterator(); iter.hasNext();) { V vertex = iter.next(); this.vertex2block.put(vertex, biconnectedSubgraph); getBiconnectedSubgraphs(vertex).add(biconnectedSubgraph); } addVertex(biconnectedSubgraph); } private int dfsVisit(V s, V father) { this.numOrder++; int minS = this.numOrder; setNumOrder(s, this.numOrder); for ( Iterator iter = this.graph.edgesOf(s).iterator(); iter.hasNext();) { E edge = iter.next(); V n = Graphs.getOppositeVertex(this.graph, edge, s); if (getNumOrder(n) == 0) { this.dfsTree.addVertex(n); BCGEdge dfsEdge = new BCGEdge(s, n); this.dfsTree.addEdge(s, n, dfsEdge); this.stack.add(dfsEdge); // minimum of the traverse orders of the "attach points" of // the vertex n. int minN = dfsVisit(n, s); minS = Math.min(minN, minS); if (minN >= getNumOrder(s)) { // s is a cutpoint. // it has a son whose "attach depth" is greater or equal. biconnectedComponentFinished(s, n); } } else if ((getNumOrder(n) < getNumOrder(s)) && !n.equals(father)) { BCGEdge backwardEdge = new BCGEdge(s, n); this.stack.add(backwardEdge); // n is an "attach point" of s. {s->n} is a backward edge. minS = Math.min(getNumOrder(n), minS); } } // minimum of the traverse orders of the "attach points" of // the vertex s. return minS; } /** * Returns the biconnected components containing the vertex. A vertex which * is not a cutpoint is contained in exactly one component. A cutpoint is * contained is at least 2 components. * * @param vertex vertex in the initial graph. */ private Set> getBiconnectedSubgraphs(V vertex) { Set> biconnectedSubgraphs = this.vertex2biconnectedSubgraphs.get(vertex); if (biconnectedSubgraphs == null) { biconnectedSubgraphs = new HashSet>(); this.vertex2biconnectedSubgraphs.put(vertex, biconnectedSubgraphs); } return biconnectedSubgraphs; } /** * Returns the traverse order of the vertex in the DFS. */ private int getNumOrder(V vertex) { assert (vertex != null); Integer numOrder = this.vertex2numOrder.get(vertex); if (numOrder == null) { return 0; } else { return numOrder.intValue(); } } private void setNumOrder(V vertex, int numOrder) { this.vertex2numOrder.put(vertex, Integer.valueOf(numOrder)); } //~ Inner Classes ---------------------------------------------------------- private class BCGEdge extends DefaultEdge { /** */ private static final long serialVersionUID = -5115006161815760059L; private V source; private V target; public BCGEdge(V source, V target) { super(); this.source = source; this.target = target; } public V getSource() { return this.source; } public V getTarget() { return this.target; } } private class VertexComponentForbiddenFunction implements MaskFunctor { private Set vertexComponent; public VertexComponentForbiddenFunction(Set vertexComponent) { this.vertexComponent = vertexComponent; } public boolean isEdgeMasked(E edge) { return false; } public boolean isVertexMasked(V vertex) { if (this.vertexComponent.contains(vertex)) { // vertex belongs to component then we do not mask it. return false; } else { return true; } } } } // End BlockCutpointGraph.java jgrapht-0.8.3/src/org/jgrapht/alg/RankingPathElementList.java0000644000175000017500000003442611706124626024404 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * RankingPathElementList.java * ------------------------- * (C) Copyright 2007-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: RankingPathElementList.java 743 2011-03-12 23:07:14Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * 06-Dec-2010 : Bugfixes (GB); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * List of simple paths in increasing order of weight. * * @author Guillaume Boulmier * @since July 5, 2007 */ final class RankingPathElementList extends AbstractPathElementList> { //~ Instance fields -------------------------------------------------------- /** * Vertex that paths of the list must not disconnect. */ private V guardVertexToNotDisconnect = null; private Map, Boolean> path2disconnect = new HashMap, Boolean>(); //~ Constructors ----------------------------------------------------------- /** * Creates a list with an empty path. The list size is 1. * * @param maxSize max number of paths the list is able to store. */ RankingPathElementList( Graph graph, int maxSize, RankingPathElement pathElement) { super(graph, maxSize, pathElement); } /** * Creates paths obtained by concatenating the specified edge to the * specified paths. * * @param prevPathElementList paths, list of * RankingPathElement. * @param edge edge reaching the end vertex of the created paths. * @param maxSize maximum number of paths the list is able to store. */ RankingPathElementList( Graph graph, int maxSize, RankingPathElementList elementList, E edge) { this(graph, maxSize, elementList, edge, null); assert (!this.pathElements.isEmpty()); } /** * Creates paths obtained by concatenating the specified edge to the * specified paths. * * @param prevPathElementList paths, list of * RankingPathElement. * @param edge edge reaching the end vertex of the created paths. * @param maxSize maximum number of paths the list is able to store. */ RankingPathElementList( Graph graph, int maxSize, RankingPathElementList elementList, E edge, V guardVertexToNotDisconnect) { super(graph, maxSize, elementList, edge); this.guardVertexToNotDisconnect = guardVertexToNotDisconnect; // loop over the path elements in increasing order of weight. for (int i = 0; i < elementList.size(); i++) { RankingPathElement prevPathElement = elementList.get(i); if (isNotValidPath(prevPathElement, edge)) { continue; } if (size() < this.maxSize) { double weight = calculatePathWeight(prevPathElement, edge); RankingPathElement newPathElement = new RankingPathElement( this.graph, prevPathElement, edge, weight); // the new path is inserted at the end of the list. this.pathElements.add(newPathElement); } } } /** * Creates an empty list. The list size is 0. * * @param maxSize max number of paths the list is able to store. */ RankingPathElementList(Graph graph, int maxSize, V vertex) { super(graph, maxSize, vertex); } //~ Methods ---------------------------------------------------------------- /** *

    Adds paths in the list at vertex y. Candidate paths are obtained by * concatenating the specified edge (v->y) to the paths * elementList at vertex v.

    * * Complexity = * *
      *
    • w/o guard-vertex: O(k*np) where k is the * max size limit of the list and np is the maximum number of * vertices in the paths stored in the list
    • *
    • with guard-vertex: O(k*(m+n)) where k is * the max size limit of the list, m is the number of edges of * the graph and n is the number of vertices of the graph, * O(m+n) being the complexity of the * ConnectivityInspector to check whether a path exists towards the * guard-vertex
    • *
    * * @param elementList list of paths at vertex v. * @param edge edge (v->y). * * @return true if at least one path has been added in the * list, false otherwise. */ public boolean addPathElements( RankingPathElementList elementList, E edge) { assert (this.vertex.equals( Graphs.getOppositeVertex( this.graph, edge, elementList.getVertex()))); boolean pathAdded = false; // loop over the paths elements of the list at vertex v. for ( int vIndex = 0, yIndex = 0; vIndex < elementList.size(); vIndex++) { RankingPathElement prevPathElement = elementList.get(vIndex); if (isNotValidPath(prevPathElement, edge)) { // checks if path is simple and if guard-vertex is not // disconnected. continue; } double newPathWeight = calculatePathWeight(prevPathElement, edge); RankingPathElement newPathElement = new RankingPathElement( this.graph, prevPathElement, edge, newPathWeight); // loop over the paths of the list at vertex y from yIndex to the // end. RankingPathElement yPathElement = null; for (; yIndex < size(); yIndex++) { yPathElement = get(yIndex); // case when the new path is shorter than the path Py stored at // index y if (newPathWeight < yPathElement.getWeight()) { this.pathElements.add(yIndex, newPathElement); pathAdded = true; // ensures max size limit is not exceeded. if (size() > this.maxSize) { this.pathElements.remove(this.maxSize); } break; } // case when the new path is of the same length as the path Py // stored at index y if (newPathWeight == yPathElement.getWeight()) { this.pathElements.add(yIndex + 1, newPathElement); pathAdded = true; // ensures max size limit is not exceeded. if (size() > this.maxSize) { this.pathElements.remove(this.maxSize); } break; } } // case when the new path is longer than the longest path in the // list (Py stored at the last index y) if (newPathWeight > yPathElement.getWeight()) { // ensures max size limit is not exceeded. if (size() < this.maxSize) { // the new path is inserted at the end of the list. this.pathElements.add(newPathElement); pathAdded = true; } else { // max size limit is reached -> end of the loop over the // paths elements of the list at vertex v. break; } } } return pathAdded; } /** * @return list of RankingPathElement. */ List> getPathElements() { return this.pathElements; } /** * Costs taken into account are the weights stored in Edge * objects. * * @param pathElement * @param edge the edge via which the vertex was encountered. * * @return the cost obtained by concatenation. * * @see Graph#getEdgeWeight(E) */ private double calculatePathWeight( RankingPathElement pathElement, E edge) { double pathWeight = this.graph.getEdgeWeight(edge); // otherwise it's the start vertex. if ((pathElement.getPrevEdge() != null)) { pathWeight += pathElement.getWeight(); } return pathWeight; } /** * Ensures that paths of the list do not disconnect the guard-vertex. * * @return true if the specified path element disconnects the * guard-vertex, false otherwise. */ private boolean isGuardVertexDisconnected( RankingPathElement prevPathElement) { if (this.guardVertexToNotDisconnect == null) { return false; } if (this.path2disconnect.containsKey(prevPathElement)) { return this.path2disconnect.get(prevPathElement); } ConnectivityInspector connectivityInspector; MaskFunctor connectivityMask; if (this.graph instanceof DirectedGraph) { connectivityMask = new PathMask(prevPathElement); DirectedMaskSubgraph connectivityGraph = new DirectedMaskSubgraph( (DirectedGraph) this.graph, connectivityMask); connectivityInspector = new ConnectivityInspector( connectivityGraph); } else { connectivityMask = new PathMask(prevPathElement); UndirectedMaskSubgraph connectivityGraph = new UndirectedMaskSubgraph( (UndirectedGraph) this.graph, connectivityMask); connectivityInspector = new ConnectivityInspector( connectivityGraph); } if (connectivityMask.isVertexMasked(this.guardVertexToNotDisconnect)) { // the guard-vertex was already in the path element -> invalid path this.path2disconnect.put(prevPathElement, true); return true; } if (!connectivityInspector.pathExists( this.vertex, this.guardVertexToNotDisconnect)) { this.path2disconnect.put(prevPathElement, true); return true; } this.path2disconnect.put(prevPathElement, false); return false; } private boolean isNotValidPath( RankingPathElement prevPathElement, E edge) { return !isSimplePath(prevPathElement, edge) || isGuardVertexDisconnected(prevPathElement); } /** * Ensures that paths of the list are simple (check that the vertex was not * already in the path element). * * @param prevPathElement * @param edge * * @return true if the resulting path (obtained by * concatenating the specified edge to the specified path) is simple, * false otherwise. */ private boolean isSimplePath( RankingPathElement prevPathElement, E edge) { RankingPathElement pathElementToTest = prevPathElement; while (pathElementToTest.getPrevEdge() != null) { if (pathElementToTest.getVertex() == this.vertex) { return false; } else { pathElementToTest = pathElementToTest.getPrevPathElement(); } } return true; } //~ Inner Classes ---------------------------------------------------------- private static class PathMask implements MaskFunctor { private Set maskedEdges; private Set maskedVertices; /** * Creates a mask for all the edges and the vertices of the path * (including the 2 extremity vertices). * * @param pathElement */ PathMask(RankingPathElement pathElement) { this.maskedEdges = new HashSet(); this.maskedVertices = new HashSet(); while (pathElement.getPrevEdge() != null) { this.maskedEdges.add(pathElement.getPrevEdge()); this.maskedVertices.add(pathElement.getVertex()); pathElement = pathElement.getPrevPathElement(); } this.maskedVertices.add(pathElement.getVertex()); } // implement MaskFunctor public boolean isEdgeMasked(E edge) { return this.maskedEdges.contains(edge); } // implement MaskFunctor public boolean isVertexMasked(V vertex) { return this.maskedVertices.contains(vertex); } } } // End RankingPathElementList.java jgrapht-0.8.3/src/org/jgrapht/alg/RankingPathElement.java0000644000175000017500000000616311706124626023545 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * RankingPathElement.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: RankingPathElement.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * */ package org.jgrapht.alg; import org.jgrapht.*; /** * Helper class for {@link KShortestPaths}. * * @author Guillaume Boulmier * @since July 5, 2007 */ final class RankingPathElement extends AbstractPathElement { //~ Instance fields -------------------------------------------------------- /** * Weight of the path. */ private double weight; //~ Constructors ----------------------------------------------------------- /** * Creates a path element by concatenation of an edge to a path element. * * @param pathElement * @param edge edge reaching the end vertex of the path element created. * @param weight total cost of the created path element. */ RankingPathElement( Graph graph, RankingPathElement pathElement, E edge, double weight) { super(graph, pathElement, edge); this.weight = weight; } /** * Creates an empty path element. * * @param vertex end vertex of the path element. */ RankingPathElement(V vertex) { super(vertex); this.weight = 0; } //~ Methods ---------------------------------------------------------------- /** * Returns the weight of the path. * * @return . */ public double getWeight() { return this.weight; } /** * Returns the previous path element. * * @return null is the path is empty. */ public RankingPathElement getPrevPathElement() { return (RankingPathElement) super.getPrevPathElement(); } } // End RankingPathElement.java jgrapht-0.8.3/src/org/jgrapht/alg/ChromaticNumber.java0000644000175000017500000001234611706124626023107 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * ChromaticNumber.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): gpaschos@netscape.net, harshalv@telenav.com * * $Id: ChromaticNumber.java 741 2011-02-26 06:30:49Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.alg.util.*; import org.jgrapht.graph.*; /** * Allows the * chromatic number of a graph to be calculated. This is the minimal number * of colors needed to color each vertex such that no two adjacent vertices * share the same color. This algorithm will not find the true chromatic number, * since this is an NP-complete problem. So, a greedy algorithm will find an * approximate chromatic number. * * @author Andrew Newell * @since Dec 21, 2008 */ public abstract class ChromaticNumber { //~ Methods ---------------------------------------------------------------- /** * Finds the number of colors required for a greedy coloring of the graph. * * @param g an undirected graph to find the chromatic number of * * @return integer the approximate chromatic number from the greedy * algorithm */ public static int findGreedyChromaticNumber(UndirectedGraph g) { Map> coloredGroups = findGreedyColoredGroups(g); return coloredGroups.keySet().size(); } /** * Finds a greedy coloring of the graph. * * @param g an undirected graph for which to find the coloring */ public static Map> findGreedyColoredGroups( UndirectedGraph g) { // A copy of the graph is made, so that elements of the graph may be // removed to carry out the algorithm UndirectedGraph sg = new UndirectedSubgraph(g, null, null); // The Vertices will be sorted in decreasing order by degree, so that // higher degree vertices have priority to be colored first VertexDegreeComparator comp = new VertexDegreeComparator(sg); List sortedVertices = new LinkedList(sg.vertexSet()); Collections.sort(sortedVertices, comp); Collections.reverse(sortedVertices); int color; // create a map which will hold color as key and Set as value Map> coloredGroups = new HashMap>(); // We'll attempt to color each vertex with a single color each // iteration, and these vertices will be removed from the graph at the // end of each iteration for (color = 0; sg.vertexSet().size() > 0; color++) { // This set will contain vertices that are colored with the // current color of this iteration Set currentColor = new HashSet(); for ( Iterator iter = sortedVertices.iterator(); iter.hasNext();) { V v = iter.next(); // Add new vertices to be colored as long as they are not // adjacent with any other vertex that has already been colored // with the current color boolean flag = true; for ( Iterator innerIter = currentColor.iterator(); innerIter.hasNext();) { V temp = innerIter.next(); if (sg.containsEdge(temp, v)) { flag = false; break; } } if (flag) { currentColor.add(v); iter.remove(); } } // Add all these vertices as a group for this color coloredGroups.put(color, currentColor); // Remove vertices from the graph and then repeat the process for // the next iteration sg.removeAllVertices(currentColor); } return coloredGroups; } } // End ChromaticNumber.java jgrapht-0.8.3/src/org/jgrapht/alg/BiconnectivityInspector.java0000644000175000017500000001044411706124626024702 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BiconnectivityInspector.java * ------------------------- * (C) Copyright 2007-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: BiconnectivityInspector.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * Inspects a graph for the biconnectivity property. See {@link * BlockCutpointGraph} for more information. A biconnected graph has only one * block (i.e. no cutpoints). * * @author Guillaume Boulmier * @since July 5, 2007 */ public class BiconnectivityInspector { //~ Instance fields -------------------------------------------------------- private BlockCutpointGraph blockCutpointGraph; //~ Constructors ----------------------------------------------------------- /** * Running time = O(m) where m is the number of edges. */ public BiconnectivityInspector(UndirectedGraph graph) { super(); this.blockCutpointGraph = new BlockCutpointGraph(graph); } //~ Methods ---------------------------------------------------------------- /** * Returns the biconnected vertex-components of the graph. */ public Set> getBiconnectedVertexComponents() { Set> biconnectedVertexComponents = new HashSet>(); for ( Iterator> iter = this.blockCutpointGraph.vertexSet().iterator(); iter.hasNext();) { UndirectedGraph subgraph = iter.next(); if (!subgraph.edgeSet().isEmpty()) { biconnectedVertexComponents.add(subgraph.vertexSet()); } } return biconnectedVertexComponents; } /** * Returns the biconnected vertex-components containing the vertex. A * biconnected vertex-component contains all the vertices in the component. * A vertex which is not a cutpoint is contained in exactly one component. A * cutpoint is contained is at least 2 components. * * @param vertex * * @return set of all biconnected vertex-components containing the vertex. */ public Set> getBiconnectedVertexComponents(V vertex) { Set> vertexComponents = new HashSet>(); for ( Iterator> iter = getBiconnectedVertexComponents().iterator(); iter.hasNext();) { Set vertexComponent = iter.next(); if (vertexComponent.contains(vertex)) { vertexComponents.add(vertexComponent); } } return vertexComponents; } /** * Returns the cutpoints of the graph. */ public Set getCutpoints() { return this.blockCutpointGraph.getCutpoints(); } /** * Returns true if the graph is biconnected (no cutpoint), * false otherwise. */ public boolean isBiconnected() { return this.blockCutpointGraph.vertexSet().size() == 1; } } // End BiconnectivityInspector.java jgrapht-0.8.3/src/org/jgrapht/alg/StoerWagnerMinimumCut.java0000644000175000017500000002165011706124626024273 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2011, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * StoerWagnerMinimumCut.java * ---------------- * (C) Copyright 2011-2011, by Robby McKilliam and Contributors. * * Original Author: Robby McKilliam * Contributor(s): - * * $Id: StoerWagnerMinimumCut.java $ * * Changes * ------- * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; import org.jgrapht.util.*; /** * Implements the Stoer and * Wagner minimum cut algorithm. Deterministically computes the minimum cut * in O(|V||E| + |V|log|V|) time. This implementation uses Java's PriorityQueue * and requires O(|V||E|log|E|) time. M. Stoer and F. Wagner, "A Simple Min-Cut * Algorithm", Journal of the ACM, volume 44, number 4. pp 585-591, 1997. * * @author Robby McKilliam */ public class StoerWagnerMinimumCut { //~ Instance fields -------------------------------------------------------- final WeightedGraph, DefaultWeightedEdge> workingGraph; double bestcutweight = Double.POSITIVE_INFINITY; Set bestCut; boolean firstRun = true; //~ Constructors ----------------------------------------------------------- /** * Will compute the minimum cut in graph. * * @param graph graph over which to run algorithm */ public StoerWagnerMinimumCut(WeightedGraph graph) { //get a version of this graph where each vertex is wrapped with a list workingGraph = new SimpleWeightedGraph, DefaultWeightedEdge>( DefaultWeightedEdge.class); Map> vertexMap = new HashMap>(); for (V v : graph.vertexSet()) { Set list = new HashSet(); list.add(v); vertexMap.put(v, list); workingGraph.addVertex(list); } for (E e : graph.edgeSet()) { V s = graph.getEdgeSource(e); Set sNew = vertexMap.get(s); V t = graph.getEdgeTarget(e); Set tNew = vertexMap.get(t); DefaultWeightedEdge eNew = workingGraph.addEdge(sNew, tNew); workingGraph.setEdgeWeight(eNew, graph.getEdgeWeight(e)); } //arbitrary vertex used to seed the algorithm. Set a = workingGraph.vertexSet().iterator().next(); while (workingGraph.vertexSet().size() > 2) { minimumCutPhase(a); } } //~ Methods ---------------------------------------------------------------- /** * Implements the MinimumCutPhase function of Stoer and Wagner */ protected void minimumCutPhase(Set a) { //construct sorted queue with vertices connected to vertex a PriorityQueue queue = new PriorityQueue(); Map, VertexAndWeight> dmap = new HashMap, VertexAndWeight>(); for (Set v : workingGraph.vertexSet()) { if (v != a) { Double w = -workingGraph.getEdgeWeight(workingGraph.getEdge(v, a)); VertexAndWeight vandw = new VertexAndWeight(v, w); queue.add(vandw); dmap.put(v, vandw); } } //now iteratatively update the queue to get the required vertex ordering List> list = new ArrayList>(workingGraph.vertexSet().size()); list.add(a); while (!queue.isEmpty()) { Set v = queue.poll().vertex; dmap.remove(v); list.add(v); for (DefaultWeightedEdge e : workingGraph.edgesOf(v)) { Set vc; if (v != workingGraph.getEdgeSource(e)) { vc = workingGraph.getEdgeSource(e); } else { vc = workingGraph.getEdgeTarget(e); } if (dmap.get(vc) != null) { Double neww = -workingGraph.getEdgeWeight(workingGraph.getEdge(v, vc)) + dmap.get(vc).weight; queue.remove(dmap.get(vc)); //this is O(logn) but could be //O(1)? dmap.get(vc).weight = neww; queue.add(dmap.get(vc)); //this is O(logn) but could be //O(1)? } } } //if this is the first run we compute the weight of last vertex in the //list if (firstRun) { Set v = list.get(list.size() - 1); double w = vertexWeight(v); if (w < bestcutweight) { bestcutweight = w; bestCut = v; } firstRun = false; } //the last two elements in list are the vertices we want to merge. Set s = list.get(list.size() - 2); Set t = list.get(list.size() - 1); //merge these vertices and get the weight. VertexAndWeight vw = mergeVertices(s, t); //If this is the best cut so far store it. if (vw.weight < bestcutweight) { bestcutweight = vw.weight; bestCut = vw.vertex; } } /** * Return the weight of the minimum cut */ public double minCutWeight() { return bestcutweight; } /** * Return a set of vertices on one side of the cut */ public Set minCut() { return bestCut; } /** * Merges vertex t into vertex s, summing the weights as required. Returns * the merged vertex and the sum of its weights */ protected VertexAndWeight mergeVertices(Set s, Set t) { //construct the new combinedvertex Set set = new HashSet(); for (V v : s) { set.add(v); } for (V v : t) { set.add(v); } workingGraph.addVertex(set); //add edges and weights to the combined vertex double wsum = 0.0; for (Set v : workingGraph.vertexSet()) { if ((s != v) && (t != v)) { DefaultWeightedEdge etv = workingGraph.getEdge(t, v); DefaultWeightedEdge esv = workingGraph.getEdge(s, v); double wtv = 0.0, wsv = 0.0; if (etv != null) { wtv = workingGraph.getEdgeWeight(etv); } if (esv != null) { wsv = workingGraph.getEdgeWeight(esv); } double neww = wtv + wsv; wsum += neww; if (neww != 0.0) { workingGraph.setEdgeWeight( workingGraph.addEdge(set, v), neww); } } } //remove original vertices workingGraph.removeVertex(t); workingGraph.removeVertex(s); return new VertexAndWeight(set, wsum); } /** * Compute the sum of the weights entering a vertex */ public double vertexWeight(Set v) { double wsum = 0.0; for (DefaultWeightedEdge e : workingGraph.edgesOf(v)) { wsum += workingGraph.getEdgeWeight(e); } return wsum; } //~ Inner Classes ---------------------------------------------------------- /** * Class for weighted vertices */ protected class VertexAndWeight implements Comparable { public Set vertex; public Double weight; public VertexAndWeight(Set v, double w) { this.vertex = v; this.weight = w; } @Override public int compareTo(VertexAndWeight that) { return Double.compare(weight, that.weight); } @Override public String toString() { return "(" + vertex + ", " + weight + ")"; } } } // End StoerWagnerMinimumCut.java jgrapht-0.8.3/src/org/jgrapht/alg/package.html0000644000175000017500000000017711706124626021442 0ustar giovannigiovanni Algorithms provided with JGraphT. jgrapht-0.8.3/src/org/jgrapht/alg/KShortestPaths.java0000644000175000017500000001677111706124626022761 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPaths.java * ------------------------- * (C) Copyright 2007-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: KShortestPaths.java 743 2011-03-12 23:07:14Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * 06-Dec-2010 : Bugfixes (GB); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * The algorithm determines the k shortest simple paths in increasing order of * weight. Weights can be negative (but no negative cycle is allowed), and paths * can be constrained by a maximum number of edges. Multigraphs are allowed. * *

    The algorithm is a variant of the Bellman-Ford algorithm but instead of * only storing the best path it stores the "k" best paths at each pass, * yielding a complexity of O(k*n*(m^2)) where m is the number of edges and n is * the number of vertices. * * @author Guillaume Boulmier * @since July 5, 2007 */ public class KShortestPaths { //~ Instance fields -------------------------------------------------------- /** * Graph on which shortest paths are searched. */ private Graph graph; private int nMaxHops; private int nPaths; private V startVertex; //~ Constructors ----------------------------------------------------------- /** * Creates an object to compute ranking shortest paths between the start * vertex and others vertices. * * @param graph * @param startVertex * @param k number of paths to be computed. */ public KShortestPaths(Graph graph, V startVertex, int k) { this(graph, startVertex, k, graph.vertexSet().size() - 1); } /** * Creates an object to calculate ranking shortest paths between the start * vertex and others vertices. * * @param graph graph on which shortest paths are searched. * @param startVertex start vertex of the calculated paths. * @param nPaths number of ranking paths between the start vertex and an end * vertex. * @param nMaxHops maximum number of edges of the calculated paths. * * @throws NullPointerException if the specified graph or startVertex is * null. * @throws IllegalArgumentException if nPaths is negative or 0. * @throws IllegalArgumentException if nMaxHops is negative or 0. */ public KShortestPaths( Graph graph, V startVertex, int nPaths, int nMaxHops) { assertKShortestPathsFinder(graph, startVertex, nPaths, nMaxHops); this.graph = graph; this.startVertex = startVertex; this.nPaths = nPaths; this.nMaxHops = nMaxHops; } //~ Methods ---------------------------------------------------------------- /** * Returns the k shortest simple paths in increasing order of weight. * * @param endVertex target vertex of the calculated paths. * * @return list of paths, or null if no path exists between the * start vertex and the end vertex. */ public List> getPaths(V endVertex) { assertGetPaths(endVertex); KShortestPathsIterator iter = new KShortestPathsIterator( this.graph, this.startVertex, endVertex, this.nPaths); // at the i-th pass the shortest paths with less (or equal) than i edges // are calculated. for ( int passNumber = 1; (passNumber <= this.nMaxHops) && iter.hasNext(); passNumber++) { iter.next(); } List> list = iter.getPathElements(endVertex); if (list == null) { return null; } List> pathList = new ArrayList>(); for (RankingPathElement element : list) { pathList.add(new PathWrapper(element)); } return pathList; } private void assertGetPaths(V endVertex) { if (endVertex == null) { throw new NullPointerException("endVertex is null"); } if (endVertex.equals(this.startVertex)) { throw new IllegalArgumentException( "The end vertex is the same as the start vertex!"); } if (!this.graph.vertexSet().contains(endVertex)) { throw new IllegalArgumentException( "Graph must contain the end vertex!"); } } private void assertKShortestPathsFinder( Graph graph, V startVertex, int nPaths, int nMaxHops) { if (graph == null) { throw new NullPointerException("graph is null"); } if (startVertex == null) { throw new NullPointerException("startVertex is null"); } if (nPaths <= 0) { throw new NullPointerException("nPaths is negative or 0"); } if (nMaxHops <= 0) { throw new NullPointerException("nMaxHops is negative or 0"); } } //~ Inner Classes ---------------------------------------------------------- private class PathWrapper implements GraphPath { private RankingPathElement rankingPathElement; private List edgeList; PathWrapper(RankingPathElement rankingPathElement) { this.rankingPathElement = rankingPathElement; } // implement GraphPath public Graph getGraph() { return graph; } // implement GraphPath public V getStartVertex() { return startVertex; } // implement GraphPath public V getEndVertex() { return rankingPathElement.getVertex(); } // implement GraphPath public List getEdgeList() { if (edgeList == null) { edgeList = rankingPathElement.createEdgeListPath(); } return edgeList; } // implement GraphPath public double getWeight() { return rankingPathElement.getWeight(); } // override Object public String toString() { return getEdgeList().toString(); } } } // End KShortestPaths.java jgrapht-0.8.3/src/org/jgrapht/alg/EdmondsKarpMaximumFlow.java0000644000175000017500000003102711706124626024417 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EdmondsKarpMaximumFlow.java * ----------------- * (C) Copyright 2008-2008, by Ilya Razenshteyn and Contributors. * * Original Author: Ilya Razenshteyn * Contributor(s): - * * $Id: EdmondsKarpMaximumFlow.java 628 2008-08-17 12:00:59Z ilyaraz $ * * Changes * ------- */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * A flow network is a * directed graph where each edge has a capacity and each edge receives a flow. * The amount of flow on an edge can not exceed the capacity of the edge (note, * that all capacities must be non-negative). A flow must satisfy the * restriction that the amount of flow into a vertex equals the amount of flow * out of it, except when it is a source, which "produces" flow, or sink, which * "consumes" flow. * *

    This class computes maximum flow in a network using Edmonds-Karp * algorithm. Be careful: for large networks this algorithm may consume * significant amount of time (its upper-bound complexity is O(VE^2), where V - * amount of vertices, E - amount of edges in the network). * *

    For more details see Andrew V. Goldberg's Combinatorial Optimization * (Lecture Notes). */ public final class EdmondsKarpMaximumFlow { //~ Static fields/initializers --------------------------------------------- /** * Default tolerance. */ public static final double DEFAULT_EPSILON = 0.000000001; //~ Instance fields -------------------------------------------------------- private DirectedGraph network; // our network private double epsilon; // tolerance (DEFAULT_EPSILON or user-defined) private int currentSource; // current source vertex private int currentSink; // current sink vertex private Map maximumFlow; // current maximum flow private Double maximumFlowValue; // current maximum flow value private int numNodes; // number of nodes in the network private Map indexer; // mapping from vertices to their indexes // in the internal representation private List nodes; // internal representation of the network //~ Constructors ----------------------------------------------------------- /** * Constructs MaximumFlow instance to work with a copy of * network. Current source and sink are set to null. If * network is weighted, then capacities are weights, otherwise all * capacities are equal to one. Doubles are compared using * DEFAULT_EPSILON tolerance. * * @param network network, where maximum flow will be calculated */ public EdmondsKarpMaximumFlow(DirectedGraph network) { this(network, DEFAULT_EPSILON); } /** * Constructs MaximumFlow instance to work with a copy of * network. Current source and sink are set to null. If * network is weighted, then capacities are weights, otherwise all * capacities are equal to one. * * @param network network, where maximum flow will be calculated * @param epsilon tolerance for comparing doubles */ public EdmondsKarpMaximumFlow(DirectedGraph network, double epsilon) { if (network == null) { throw new NullPointerException("network is null"); } if (epsilon <= 0) { throw new IllegalArgumentException( "invalid epsilon (must be positive)"); } for (E e : network.edgeSet()) { if (network.getEdgeWeight(e) < -epsilon) { throw new IllegalArgumentException( "invalid capacity (must be non-negative)"); } } this.network = network; this.epsilon = epsilon; currentSource = -1; currentSink = -1; maximumFlow = null; maximumFlowValue = null; buildInternalNetwork(); } //~ Methods ---------------------------------------------------------------- // converting the original network into internal more convenient format private void buildInternalNetwork() { numNodes = network.vertexSet().size(); nodes = new ArrayList(); Iterator it = network.vertexSet().iterator(); indexer = new HashMap(); for (int i = 0; i < numNodes; i++) { V currentNode = it.next(); nodes.add(new Node(currentNode)); indexer.put(currentNode, i); } for (int i = 0; i < numNodes; i++) { V we = nodes.get(i).prototype; for (E e : network.outgoingEdgesOf(we)) { V he = network.getEdgeTarget(e); int j = indexer.get(he); Arc e1 = new Arc(i, j, network.getEdgeWeight(e), e); Arc e2 = new Arc(j, i, 0.0, null); e1.reversed = e2; e2.reversed = e1; nodes.get(i).outgoingArcs.add(e1); nodes.get(j).outgoingArcs.add(e2); } } } /** * Sets current source to source, current sink to sink, * then calculates maximum flow from source to sink. Note, * that source and sink must be vertices of the * network passed to the constructor, and they must be different. * * @param source source vertex * @param sink sink vertex */ public void calculateMaximumFlow( V source, V sink) { if (!network.containsVertex(source)) { throw new IllegalArgumentException( "invalid source (null or not from this network)"); } if (!network.containsVertex(sink)) { throw new IllegalArgumentException( "invalid sink (null or not from this network)"); } if (source.equals(sink)) { throw new IllegalArgumentException("source is equal to sink"); } currentSource = indexer.get(source); currentSink = indexer.get(sink); for (int i = 0; i < numNodes; i++) { for (Arc currentArc : nodes.get(i).outgoingArcs) { currentArc.flow = 0.0; } } maximumFlowValue = 0.0; for (;;) { breadthFirstSearch(); if (!nodes.get(currentSink).visited) { maximumFlow = new HashMap(); for (int i = 0; i < numNodes; i++) { for (Arc currentArc : nodes.get(i).outgoingArcs) { if (currentArc.prototype != null) { maximumFlow.put( currentArc.prototype, currentArc.flow); } } } return; } augmentFlow(); } } private void breadthFirstSearch() { for (int i = 0; i < numNodes; i++) { nodes.get(i).visited = false; } Queue queue = new LinkedList(); queue.offer(currentSource); nodes.get(currentSource).visited = true; nodes.get(currentSource).flowAmount = Double.POSITIVE_INFINITY; while (queue.size() != 0) { int currentNode = queue.poll(); for (Arc currentArc : nodes.get(currentNode).outgoingArcs) { if ((currentArc.flow + epsilon) < currentArc.capacity) { if (!nodes.get(currentArc.head).visited) { nodes.get(currentArc.head).visited = true; nodes.get(currentArc.head).flowAmount = Math.min( nodes.get(currentNode).flowAmount, currentArc.capacity - currentArc.flow); nodes.get(currentArc.head).lastArc = currentArc; queue.add(currentArc.head); } } } } } private void augmentFlow() { double deltaFlow = nodes.get(currentSink).flowAmount; maximumFlowValue += deltaFlow; int currentNode = currentSink; while (currentNode != currentSource) { nodes.get(currentNode).lastArc.flow += deltaFlow; nodes.get(currentNode).lastArc.reversed.flow -= deltaFlow; currentNode = nodes.get(currentNode).lastArc.tail; } } /** * Returns maximum flow value, that was calculated during last * calculateMaximumFlow call, or null, if there was no * calculateMaximumFlow calls. * * @return maximum flow value */ public Double getMaximumFlowValue() { return maximumFlowValue; } /** * Returns maximum flow, that was calculated during last * calculateMaximumFlow call, or null, if there was no * calculateMaximumFlow calls. * * @return read-only mapping from edges to doubles - flow values */ public Map getMaximumFlow() { if (maximumFlow == null) { return null; } return Collections.unmodifiableMap(maximumFlow); } /** * Returns current source vertex, or null if there was no * calculateMaximumFlow calls. * * @return current source */ public V getCurrentSource() { if (currentSource == -1) { return null; } return nodes.get(currentSource).prototype; } /** * Returns current sink vertex, or null if there was no * calculateMaximumFlow calls. * * @return current sink */ public V getCurrentSink() { if (currentSink == -1) { return null; } return nodes.get(currentSink).prototype; } //~ Inner Classes ---------------------------------------------------------- // class used for internal representation of network class Node { V prototype; // corresponding node in the original network List outgoingArcs = new ArrayList(); // list of outgoing arcs // in the residual // network boolean visited; // this mark is used during BFS to mark visited nodes Arc lastArc; // last arc in the shortest path double flowAmount; // amount of flow, we are able to push here Node( V prototype) { this.prototype = prototype; } } // class used for internal representation of network class Arc { int tail; // "from" int head; // "to" double capacity; // capacity (can be zero) double flow; // current flow (can be negative) Arc reversed; // for each arc in the original network we are to create // reversed arc E prototype; // corresponding edge in the original network, can be null, // if it is reversed arc Arc( int tail, int head, double capacity, E prototype) { this.tail = tail; this.head = head; this.capacity = capacity; this.prototype = prototype; } } } // End EdmondsKarpMaximumFlow.java jgrapht-0.8.3/src/org/jgrapht/alg/BellmanFordShortestPath.java0000644000175000017500000001530711706124626024563 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BellmanFordShortestPath.java * ------------------------- * (C) Copyright 2006-2008, by France Telecom and Contributors. * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: BellmanFordShortestPath.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jan-2006 : Initial revision (GB); * 14-Jan-2006 : Added support for generics (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * Bellman-Ford * algorithm: weights could be negative, paths could be constrained by a * maximum number of edges. */ public class BellmanFordShortestPath { //~ Static fields/initializers --------------------------------------------- private static final double DEFAULT_EPSILON = 0.000000001; //~ Instance fields -------------------------------------------------------- /** * Graph on which shortest paths are searched. */ protected Graph graph; /** * Start vertex. */ protected V startVertex; private BellmanFordIterator iter; /** * Maximum number of edges of the calculated paths. */ private int nMaxHops; private int passNumber; private double epsilon; //~ Constructors ----------------------------------------------------------- /** * Creates an object to calculate shortest paths between the start vertex * and others vertices using the Bellman-Ford algorithm. * * @param graph * @param startVertex */ public BellmanFordShortestPath(Graph graph, V startVertex) { this(graph, startVertex, graph.vertexSet().size() - 1); } /** * Creates an object to calculate shortest paths between the start vertex * and others vertices using the Bellman-Ford algorithm. * * @param graph * @param startVertex * @param nMaxHops maximum number of edges of the calculated paths. */ public BellmanFordShortestPath( Graph graph, V startVertex, int nMaxHops) { this(graph, startVertex, nMaxHops, DEFAULT_EPSILON); } /** * Creates an object to calculate shortest paths between the start vertex * and others vertices using the Bellman-Ford algorithm. * * @param graph * @param startVertex * @param nMaxHops maximum number of edges of the calculated paths. * @param epsilon tolerance factor. */ public BellmanFordShortestPath( Graph graph, V startVertex, int nMaxHops, double epsilon) { this.startVertex = startVertex; this.nMaxHops = nMaxHops; this.graph = graph; this.passNumber = 1; this.epsilon = epsilon; } //~ Methods ---------------------------------------------------------------- /** * @param endVertex end vertex. * * @return the cost of the shortest path between the start vertex and the * end vertex. */ public double getCost(V endVertex) { assertGetPath(endVertex); lazyCalculate(); BellmanFordPathElement pathElement = this.iter.getPathElement(endVertex); if (pathElement == null) { return Double.POSITIVE_INFINITY; } return pathElement.getCost(); } /** * @param endVertex end vertex. * * @return list of Edge, or null if no path exists between the * start vertex and the end vertex. */ public List getPathEdgeList(V endVertex) { assertGetPath(endVertex); lazyCalculate(); BellmanFordPathElement pathElement = this.iter.getPathElement(endVertex); if (pathElement == null) { return null; } return pathElement.createEdgeListPath(); } private void assertGetPath(V endVertex) { if (endVertex.equals(this.startVertex)) { throw new IllegalArgumentException( "The end vertex is the same as the start vertex!"); } if (!this.graph.containsVertex(endVertex)) { throw new IllegalArgumentException( "Graph must contain the end vertex!"); } } private void lazyCalculate() { if (this.iter == null) { this.iter = new BellmanFordIterator( this.graph, this.startVertex, epsilon); } // at the i-th pass the shortest paths with less (or equal) than i edges // are calculated. for ( ; (this.passNumber <= this.nMaxHops) && this.iter.hasNext(); this.passNumber++) { this.iter.next(); } } /** * Convenience method to find the shortest path via a single static method * call. If you need a more advanced search (e.g. limited by hops, or * computation of the path length), use the constructor instead. * * @param graph the graph to be searched * @param startVertex the vertex at which the path should start * @param endVertex the vertex at which the path should end * * @return List of Edges, or null if no path exists */ public static List findPathBetween( Graph graph, V startVertex, V endVertex) { BellmanFordShortestPath alg = new BellmanFordShortestPath( graph, startVertex); return alg.getPathEdgeList(endVertex); } } // End BellmanFordShortestPath.java jgrapht-0.8.3/src/org/jgrapht/alg/KruskalMinimumSpanningTree.java0000644000175000017500000000761111706124626025312 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KruskalMinimumSpanningTree.java * ------------------------- * (C) Copyright 2010-2010, by Tom Conerly and Contributors. * * Original Author: Tom Conerly * Contributor(s): * * Changes * ------- * 02-Feb-2010 : Initial revision (TC); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.alg.util.*; /** * An implementation of Kruskal's minimum * spanning tree algorithm. If the given graph is connected it computes the * minimum spanning tree, otherwise it computes the minimum spanning forest. The * algorithm runs in time O(E log E). This implementation uses the hashCode and * equals method of the vertices. * * @author Tom Conerly * @since Feb 10, 2010 */ public class KruskalMinimumSpanningTree { //~ Instance fields -------------------------------------------------------- private double spanningTreeCost; private Set edgeList; //~ Constructors ----------------------------------------------------------- /** * Creates and executes a new KruskalMinimumSpanningTree algorithm instance. * An instance is only good for a single spanning tree; after construction, * it can be accessed to retrieve information about the spanning tree found. * * @param graph the graph to be searched */ public KruskalMinimumSpanningTree(final Graph graph) { UnionFind forest = new UnionFind(graph.vertexSet()); ArrayList allEdges = new ArrayList(graph.edgeSet()); Collections.sort( allEdges, new Comparator() { public int compare(E edge1, E edge2) { return Double.valueOf(graph.getEdgeWeight(edge1)).compareTo( graph.getEdgeWeight(edge2)); } }); spanningTreeCost = 0; edgeList = new HashSet(); for (E edge : allEdges) { V source = graph.getEdgeSource(edge); V target = graph.getEdgeTarget(edge); if (forest.find(source).equals(forest.find(target))) { continue; } forest.union(source, target); edgeList.add(edge); spanningTreeCost += graph.getEdgeWeight(edge); } } //~ Methods ---------------------------------------------------------------- /** * Returns the edges making up the tree found. * * @return Set of Edges */ public Set getEdgeSet() { return edgeList; } /** * Returns the cost of the minimum spanning tree or forest. * * @return Cost of the spanning tree */ public double getSpanningTreeCost() { return spanningTreeCost; } } // End KruskalMinimumSpanningTree.java jgrapht-0.8.3/src/org/jgrapht/alg/DirectedNeighborIndex.java0000644000175000017500000001731311706124626024215 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * DirectedNeighborIndex.java * -------------------------- * (C) Copyright 2005-2008, by Charles Fry and Contributors. * * Original Author: Charles Fry * * $Id: DirectedNeighborIndex.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Dec-2005 : Initial revision (CF); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.alg.NeighborIndex.*; import org.jgrapht.event.*; /** * Maintains a cache of each vertex's neighbors. While lists of neighbors can be * obtained from {@link Graphs}, they are re-calculated at each invocation by * walking a vertex's incident edges, which becomes inordinately expensive when * performed often. * *

    A vertex's neighbors are cached the first time they are asked for (i.e. * the index is built on demand). The index will only be updated automatically * if it is added to the associated graph as a listener. If it is added as a * listener to a graph other than the one it indexes, results are undefined.

    * * @author Charles Fry * @since Dec 13, 2005 */ public class DirectedNeighborIndex implements GraphListener { //~ Instance fields -------------------------------------------------------- Map> predecessorMap = new HashMap>(); Map> successorMap = new HashMap>(); private DirectedGraph graph; //~ Constructors ----------------------------------------------------------- /** * Creates a neighbor index for the specified directed graph. * * @param g the graph for which a neighbor index is to be created. */ public DirectedNeighborIndex(DirectedGraph g) { graph = g; } //~ Methods ---------------------------------------------------------------- /** * Returns the set of vertices which are the predecessors of a specified * vertex. The returned set is backed by the index, and will be updated when * the graph changes as long as the index has been added as a listener to * the graph. * * @param v the vertex whose predecessors are desired * * @return all unique predecessors of the specified vertex */ public Set predecessorsOf(V v) { return getPredecessors(v).getNeighbors(); } /** * Returns the set of vertices which are the predecessors of a specified * vertex. If the graph is a multigraph, vertices may appear more than once * in the returned list. Because a list of predecessors can not be * efficiently maintained, it is reconstructed on every invocation by * duplicating entries in the neighbor set. It is thus more efficient to use * {@link #predecessorsOf(Object)} unless duplicate neighbors are required. * * @param v the vertex whose predecessors are desired * * @return all predecessors of the specified vertex */ public List predecessorListOf(V v) { return getPredecessors(v).getNeighborList(); } /** * Returns the set of vertices which are the successors of a specified * vertex. The returned set is backed by the index, and will be updated when * the graph changes as long as the index has been added as a listener to * the graph. * * @param v the vertex whose successors are desired * * @return all unique successors of the specified vertex */ public Set successorsOf(V v) { return getSuccessors(v).getNeighbors(); } /** * Returns the set of vertices which are the successors of a specified * vertex. If the graph is a multigraph, vertices may appear more than once * in the returned list. Because a list of successors can not be efficiently * maintained, it is reconstructed on every invocation by duplicating * entries in the neighbor set. It is thus more efficient to use {@link * #successorsOf(Object)} unless duplicate neighbors are required. * * @param v the vertex whose successors are desired * * @return all successors of the specified vertex */ public List successorListOf(V v) { return getSuccessors(v).getNeighborList(); } /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded(GraphEdgeChangeEvent e) { E edge = e.getEdge(); V source = graph.getEdgeSource(edge); V target = graph.getEdgeTarget(edge); // if a map does not already contain an entry, // then skip addNeighbor, since instantiating the map // will take care of processing the edge (which has already // been added) if (successorMap.containsKey(source)) { getSuccessors(source).addNeighbor(target); } else { getSuccessors(source); } if (predecessorMap.containsKey(target)) { getPredecessors(target).addNeighbor(source); } else { getPredecessors(target); } } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved(GraphEdgeChangeEvent e) { E edge = e.getEdge(); V source = graph.getEdgeSource(edge); V target = graph.getEdgeTarget(edge); if (successorMap.containsKey(source)) { successorMap.get(source).removeNeighbor(target); } if (predecessorMap.containsKey(target)) { predecessorMap.get(target).removeNeighbor(source); } } /** * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded(GraphVertexChangeEvent e) { // nothing to cache until there are edges } /** * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved(GraphVertexChangeEvent e) { predecessorMap.remove(e.getVertex()); successorMap.remove(e.getVertex()); } private Neighbors getPredecessors(V v) { Neighbors neighbors = predecessorMap.get(v); if (neighbors == null) { neighbors = new Neighbors(v, Graphs.predecessorListOf(graph, v)); predecessorMap.put(v, neighbors); } return neighbors; } private Neighbors getSuccessors(V v) { Neighbors neighbors = successorMap.get(v); if (neighbors == null) { neighbors = new Neighbors(v, Graphs.successorListOf(graph, v)); successorMap.put(v, neighbors); } return neighbors; } } // End DirectedNeighborIndex.java jgrapht-0.8.3/src/org/jgrapht/alg/HamiltonianCycle.java0000644000175000017500000001034211706124626023242 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * HamiltonianCycle.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: HamiltonianCycle.java 681 2009-05-25 06:17:31Z perfecthash $ * * Changes * ------- * 17-Feb-2008 : Initial revision (AN); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.graph.*; /** * This class will deal with finding the optimal or approximately optimal * minimum tour (hamiltonian cycle) or commonly known as the Traveling * Salesman Problem. * * @author Andrew Newell */ public class HamiltonianCycle { //~ Methods ---------------------------------------------------------------- /** * This method will return an approximate minimal traveling salesman tour * (hamiltonian cycle). This algorithm requires that the graph be complete * and the triangle inequality exists (if x,y,z are vertices then * d(x,y)+d(y,z) * @param * @param g is the graph to find the optimal tour for. * * @return The optimal tour as a list of vertices. */ public static List getApproximateOptimalForCompleteGraph( SimpleWeightedGraph g) { List vertices = new LinkedList(g.vertexSet()); // If the graph is not complete then return null since this algorithm // requires the graph be complete if ((vertices.size() * (vertices.size() - 1) / 2) != g.edgeSet().size()) { return null; } List tour = new LinkedList(); // Each iteration a new vertex will be added to the tour until all // vertices have been added while (tour.size() != g.vertexSet().size()) { boolean firstEdge = true; double minEdgeValue = 0; int minVertexFound = 0; int vertexConnectedTo = 0; // A check will be made for the shortest edge to a vertex not within // the tour and that new vertex will be added to the vertex for (int i = 0; i < tour.size(); i++) { V v = tour.get(i); for (int j = 0; j < vertices.size(); j++) { double weight = g.getEdgeWeight(g.getEdge(v, vertices.get(j))); if (firstEdge || (weight < minEdgeValue)) { firstEdge = false; minEdgeValue = weight; minVertexFound = j; vertexConnectedTo = i; } } } tour.add(vertexConnectedTo, vertices.get(minVertexFound)); vertices.remove(minVertexFound); } return tour; } } // End HamiltonianCycle.java jgrapht-0.8.3/src/org/jgrapht/alg/CycleDetector.java0000644000175000017500000001712011706124626022551 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * CycleDetector.java * ------------------ * (C) Copyright 2004-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Christian Hammer * * $Id: CycleDetector.java 744 2011-06-07 05:49:07Z perfecthash $ * * Changes * ------- * 16-Sept-2004 : Initial revision (JVS); * 07-Jun-2005 : Made generic (CH); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.traverse.*; /** * Performs cycle detection on a graph. The inspected graph is specified * at construction time and cannot be modified. Currently, the detector supports * only directed graphs. * * @author John V. Sichi * @since Sept 16, 2004 */ public class CycleDetector { //~ Instance fields -------------------------------------------------------- /** * Graph on which cycle detection is being performed. */ DirectedGraph graph; //~ Constructors ----------------------------------------------------------- /** * Creates a cycle detector for the specified graph. Currently only directed * graphs are supported. * * @param graph the DirectedGraph in which to detect cycles */ public CycleDetector(DirectedGraph graph) { this.graph = graph; } //~ Methods ---------------------------------------------------------------- /** * Performs yes/no cycle detection on the entire graph. * * @return true iff the graph contains at least one cycle */ public boolean detectCycles() { try { execute(null, null); } catch (CycleDetectedException ex) { return true; } return false; } /** * Performs yes/no cycle detection on an individual vertex. * * @param v the vertex to test * * @return true if v is on at least one cycle */ public boolean detectCyclesContainingVertex(V v) { try { execute(null, v); } catch (CycleDetectedException ex) { return true; } return false; } /** * Finds the vertex set for the subgraph of all cycles. * * @return set of all vertices which participate in at least one cycle in * this graph */ public Set findCycles() { // ProbeIterator can't be used to handle this case, // so use StrongConnectivityInspector instead. StrongConnectivityInspector inspector = new StrongConnectivityInspector(graph); List> components = inspector.stronglyConnectedSets(); // A vertex participates in a cycle if either of the following is // true: (a) it is in a component whose size is greater than 1 // or (b) it is a self-loop Set set = new HashSet(); for (Set component : components) { if (component.size() > 1) { // cycle set.addAll(component); } else { V v = component.iterator().next(); if (graph.containsEdge(v, v)) { // self-loop set.add(v); } } } return set; } /** * Finds the vertex set for the subgraph of all cycles which contain a * particular vertex. * *

    REVIEW jvs 25-Aug-2006: This implementation is not guaranteed to cover * all cases. If you want to be absolutely certain that you report vertices * from all cycles containing v, it's safer (but less efficient) to use * StrongConnectivityInspector instead and return the strongly connected * component containing v. * * @param v the vertex to test * * @return set of all vertices reachable from v via at least one cycle */ public Set findCyclesContainingVertex(V v) { Set set = new HashSet(); execute(set, v); return set; } private void execute(Set s, V v) { ProbeIterator iter = new ProbeIterator(s, v); while (iter.hasNext()) { iter.next(); } } //~ Inner Classes ---------------------------------------------------------- /** * Exception thrown internally when a cycle is detected during a yes/no * cycle test. Must be caught by top-level detection method. */ private static class CycleDetectedException extends RuntimeException { private static final long serialVersionUID = 3834305137802950712L; } /** * Version of DFS which maintains a backtracking path used to probe for * cycles. */ private class ProbeIterator extends DepthFirstIterator { private List path; private Set cycleSet; private V root; ProbeIterator(Set cycleSet, V startVertex) { super(graph, startVertex); root = startVertex; this.cycleSet = cycleSet; path = new ArrayList(); } /** * {@inheritDoc} */ protected void encounterVertexAgain(V vertex, E edge) { super.encounterVertexAgain(vertex, edge); int i; if (root != null) { // For rooted detection, the path must either // double back to the root, or to a node of a cycle // which has already been detected. if (vertex.equals(root)) { i = 0; } else if ((cycleSet != null) && cycleSet.contains(vertex)) { i = 0; } else { return; } } else { i = path.indexOf(vertex); } if (i > -1) { if (cycleSet == null) { // we're doing yes/no cycle detection throw new CycleDetectedException(); } else { for (; i < path.size(); ++i) { cycleSet.add(path.get(i)); } } } } /** * {@inheritDoc} */ protected V provideNextVertex() { V v = super.provideNextVertex(); // backtrack for (int i = path.size() - 1; i >= 0; --i) { if (graph.containsEdge(path.get(i), v)) { break; } path.remove(i); } path.add(v); return v; } } } // End CycleDetector.java jgrapht-0.8.3/src/org/jgrapht/alg/util/0000755000175000017500000000000011752244357020136 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/alg/util/package.html0000644000175000017500000000017411706124626022414 0ustar giovannigiovanni Utilities used by JGraphT algorithms. jgrapht-0.8.3/src/org/jgrapht/alg/util/VertexDegreeComparator.java0000644000175000017500000001030011706124626025407 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * VertexDegreeComparator.java * --------------------------- * (C) Copyright 2003-2008, by Linda Buisman and Contributors. * * Original Author: Linda Buisman * Contributor(s): Christian Hammer * * $Id: VertexDegreeComparator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Nov-2003 : Initial revision (LB); * 07-Jun-2005 : Made generic (CH); * */ package org.jgrapht.alg.util; import org.jgrapht.*; /** * Compares two vertices based on their degree. * *

    Used by greedy algorithms that need to sort vertices by their degree. Two * vertices are considered equal if their degrees are equal.

    * * @author Linda Buisman * @since Nov 6, 2003 */ public class VertexDegreeComparator implements java.util.Comparator { //~ Instance fields -------------------------------------------------------- /** * The graph that contains the vertices to be compared. */ private UndirectedGraph graph; /** * The sort order for vertex degree. true for ascending degree * order (smaller degrees first), false for descending. */ private boolean ascendingOrder; //~ Constructors ----------------------------------------------------------- /** * Creates a comparator for comparing the degrees of vertices in the * specified graph. The comparator compares in ascending order of degrees * (lowest first). * * @param g graph with respect to which the degree is calculated. */ public VertexDegreeComparator(UndirectedGraph g) { this(g, true); } /** * Creates a comparator for comparing the degrees of vertices in the * specified graph. * * @param g graph with respect to which the degree is calculated. * @param ascendingOrder true - compares in ascending order of degrees * (lowest first), false - compares in descending order of degrees (highest * first). */ public VertexDegreeComparator( UndirectedGraph g, boolean ascendingOrder) { graph = g; this.ascendingOrder = ascendingOrder; } //~ Methods ---------------------------------------------------------------- /** * Compare the degrees of v1 and v2, taking into * account whether ascending or descending order is used. * * @param v1 the first vertex to be compared. * @param v2 the second vertex to be compared. * * @return -1 if v1 comes before v2, +1 if * v1 comes after v2, 0 if equal. */ public int compare(V v1, V v2) { int degree1 = graph.degreeOf(v1); int degree2 = graph.degreeOf(v2); if (((degree1 < degree2) && ascendingOrder) || ((degree1 > degree2) && !ascendingOrder)) { return -1; } else if ( ((degree1 > degree2) && ascendingOrder) || ((degree1 < degree2) && !ascendingOrder)) { return 1; } else { return 0; } } } // End VertexDegreeComparator.java jgrapht-0.8.3/src/org/jgrapht/alg/util/UnionFind.java0000644000175000017500000001147011706124626022670 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * UnionFind.java * ------------------------- * (C) Copyright 2010-2010, by Tom Conerly and Contributors. * * Original Author: Tom Conerly * Contributor(s): * * Changes * ------- * 02-Feb-2010 : Initial revision (TC); * */ package org.jgrapht.alg.util; import java.util.*; /** * An implementation of Union * Find data structure. Union Find is a disjoint-set data structure. It * supports two operations: finding the set a specific element is in, and * merging two sets. The implementation uses union by rank and path compression * to achieve an amortized cost of O(a(n)) per operation where a is the inverse * Ackermann function. UnionFind uses the hashCode and equals method of the * elements it operates on. * * @author Tom Conerly * @since Feb 10, 2010 */ public class UnionFind { //~ Instance fields -------------------------------------------------------- private Map parentMap; private Map rankMap; //~ Constructors ----------------------------------------------------------- /** * Creates a UnionFind instance with all of the elements of elements in * seperate sets. */ public UnionFind(Set elements) { parentMap = new HashMap(); rankMap = new HashMap(); for (T element : elements) { parentMap.put(element, element); rankMap.put(element, 0); } } //~ Methods ---------------------------------------------------------------- /** * Adds a new element to the data structure in its own set. * * @param element The element to add. */ public void addElement(T element) { parentMap.put(element, element); rankMap.put(element, 0); } /** * @return map from element to parent element */ protected Map getParentMap() { return parentMap; } /** * @return map from element to rank */ protected Map getRankMap() { return rankMap; } /** * Returns the representative element of the set that element is in. * * @param element The element to find. * * @return The element representing the set the element is in. */ public T find(T element) { if (!parentMap.containsKey(element)) { throw new IllegalArgumentException( "elements must be contained in given set"); } T parent = parentMap.get(element); if (parent.equals(element)) { return element; } T newParent = find(parent); parentMap.put(element, newParent); return newParent; } /** * Merges the sets which contain element1 and element2. * * @param element1 The first element to union. * @param element2 The second element to union. */ public void union(T element1, T element2) { if (!parentMap.containsKey(element1) || !parentMap.containsKey(element2)) { throw new IllegalArgumentException( "elements must be contained in given set"); } T parent1 = find(element1); T parent2 = find(element2); //check if the elements are already in the same set if (parent1.equals(parent2)) { return; } int rank1 = rankMap.get(parent1); int rank2 = rankMap.get(parent2); if (rank1 > rank2) { parentMap.put(parent2, parent1); } else if (rank1 < rank2) { parentMap.put(parent1, parent2); } else { parentMap.put(parent2, parent1); rankMap.put(parent1, rank1 + 1); } } } // End UnionFind.java jgrapht-0.8.3/src/org/jgrapht/alg/BellmanFordIterator.java0000644000175000017500000003203111706124626023715 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BellmanFordIterator.java * ------------------------- * (C) Copyright 2006-2008, by France Telecom and Contributors. * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: BellmanFordIterator.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 05-Jan-2006 : Initial revision (GB); * 14-Jan-2006 : Added support for generics (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * Helper class for {@link BellmanFordShortestPath}; not intended for general * use. */ class BellmanFordIterator implements Iterator> { //~ Static fields/initializers --------------------------------------------- /** * Error message. */ protected final static String NEGATIVE_UNDIRECTED_EDGE = "Negative" + "edge-weights are not allowed in an unidrected graph!"; //~ Instance fields -------------------------------------------------------- /** * Graph on which shortest paths are searched. */ protected Graph graph; /** * Start vertex. */ protected V startVertex; /** * Vertices whose shortest path cost have been improved during the previous * pass. */ private List prevImprovedVertices = new ArrayList(); private Map> prevVertexData; private boolean startVertexEncountered = false; /** * Stores the vertices that have been seen during iteration and (optionally) * some additional traversal info regarding each vertex. */ private Map> vertexData; private double epsilon; //~ Constructors ----------------------------------------------------------- /** * @param graph * @param startVertex start vertex. * @param epsilon tolerance factor. */ protected BellmanFordIterator( Graph graph, V startVertex, double epsilon) { assertBellmanFordIterator(graph, startVertex); this.graph = graph; this.startVertex = startVertex; this.epsilon = epsilon; } //~ Methods ---------------------------------------------------------------- /** * Returns the path element of the shortest path with less than * nMaxHops edges between the start vertex and the end vertex. * * @param endVertex end vertex. * * @return . */ public BellmanFordPathElement getPathElement(V endVertex) { return getSeenData(endVertex); } /** * @return true if at least one path has been improved during * the previous pass, false otherwise. */ public boolean hasNext() { if (!this.startVertexEncountered) { encounterStartVertex(); } return !(this.prevImprovedVertices.isEmpty()); } /** * Returns the list Collection of vertices whose path has been * improved during the current pass. * * @see java.util.Iterator#next() */ public List next() { if (!this.startVertexEncountered) { encounterStartVertex(); } if (hasNext()) { List improvedVertices = new ArrayList(); for (int i = this.prevImprovedVertices.size() - 1; i >= 0; i--) { V vertex = this.prevImprovedVertices.get(i); for ( Iterator iter = edgesOfIterator(vertex); iter.hasNext();) { E edge = iter.next(); V oppositeVertex = Graphs.getOppositeVertex( graph, edge, vertex); if (getPathElement(oppositeVertex) != null) { boolean relaxed = relaxVertexAgain(oppositeVertex, edge); if (relaxed) { improvedVertices.add(oppositeVertex); } } else { relaxVertex(oppositeVertex, edge); improvedVertices.add(oppositeVertex); } } } savePassData(improvedVertices); return improvedVertices; } throw new NoSuchElementException(); } /** * Unsupported * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } /** * @param edge * * @throws IllegalArgumentException if the graph is undirected and the * edge-weight is negative. */ protected void assertValidEdge(E edge) { if (this.graph instanceof UndirectedGraph) { if (graph.getEdgeWeight(edge) < 0) { throw new IllegalArgumentException(NEGATIVE_UNDIRECTED_EDGE); } } } /** * Costs taken into account are the weights stored in Edge * objects. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. * * @return the cost obtained by concatenation. * * @see Graph#getEdgeWeight(E) */ protected double calculatePathCost(V vertex, E edge) { V oppositeVertex = Graphs.getOppositeVertex(graph, edge, vertex); // we get the data of the previous pass. BellmanFordPathElement oppositePrevData = getPrevSeenData(oppositeVertex); double pathCost = graph.getEdgeWeight(edge); if (!oppositePrevData.getVertex().equals(this.startVertex)) { // if it's not the start vertex, we add the cost of the previous // pass. pathCost += oppositePrevData.getCost(); } return pathCost; } /** * Returns an iterator to loop over outgoing edges Edge of the * vertex. * * @param vertex * * @return . */ protected Iterator edgesOfIterator(V vertex) { if (this.graph instanceof DirectedGraph) { return ((DirectedGraph) this.graph).outgoingEdgesOf(vertex) .iterator(); } else { return this.graph.edgesOf(vertex).iterator(); } } /** * Access the data stored for a seen vertex in the previous pass. * * @param vertex a vertex which has already been seen. * * @return data associated with the seen vertex or null if no * data was associated with the vertex. */ protected BellmanFordPathElement getPrevSeenData(V vertex) { return this.prevVertexData.get(vertex); } /** * Access the data stored for a seen vertex in the current pass. * * @param vertex a vertex which has already been seen. * * @return data associated with the seen vertex or null if no * data was associated with the vertex. */ protected BellmanFordPathElement getSeenData(V vertex) { return this.vertexData.get(vertex); } /** * Determines whether a vertex has been seen yet by this traversal. * * @param vertex vertex in question. * * @return true if vertex has already been seen. */ protected boolean isSeenVertex(V vertex) { return this.vertexData.containsKey(vertex); } /** * @param vertex * @param data * * @return . */ protected BellmanFordPathElement putPrevSeenData( V vertex, BellmanFordPathElement data) { if (this.prevVertexData == null) { this.prevVertexData = new HashMap>(); } return this.prevVertexData.put(vertex, data); } /** * Stores iterator-dependent data for a vertex that has been seen during the * current pass. * * @param vertex a vertex which has been seen. * @param data data to be associated with the seen vertex. * * @return previous value associated with specified vertex or * null if no data was associated with the vertex. */ protected BellmanFordPathElement putSeenData( V vertex, BellmanFordPathElement data) { if (this.vertexData == null) { this.vertexData = new HashMap>(); } return this.vertexData.put(vertex, data); } private void assertBellmanFordIterator(Graph graph, V startVertex) { if (!(graph.containsVertex(startVertex))) { throw new IllegalArgumentException( "Graph must contain the start vertex!"); } } /** * The first time we see a vertex, make up a new entry for it. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. * @param cost cost of the created path element. * * @return the new entry. */ private BellmanFordPathElement createSeenData( V vertex, E edge, double cost) { BellmanFordPathElement prevPathElement = getPrevSeenData( Graphs.getOppositeVertex(graph, edge, vertex)); BellmanFordPathElement data = new BellmanFordPathElement( graph, prevPathElement, edge, cost, epsilon); return data; } private void encounterStartVertex() { BellmanFordPathElement data = new BellmanFordPathElement( this.startVertex, epsilon); // first the only vertex considered as improved is the start vertex. this.prevImprovedVertices.add(this.startVertex); putSeenData(this.startVertex, data); putPrevSeenData(this.startVertex, data); this.startVertexEncountered = true; } /** * Upates data first time a vertex is reached by a path. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. */ private void relaxVertex(V vertex, E edge) { assertValidEdge(edge); double shortestPathCost = calculatePathCost(vertex, edge); BellmanFordPathElement data = createSeenData(vertex, edge, shortestPathCost); putSeenData(vertex, data); } /** * Check if the cost of the best path so far reaching the specified vertex * could be improved if the vertex is reached through the specified edge. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. * * @return true if the cost has been improved, * false otherwise. */ private boolean relaxVertexAgain(V vertex, E edge) { assertValidEdge(edge); double candidateCost = calculatePathCost(vertex, edge); // we get the data of the previous pass. BellmanFordPathElement oppositePrevData = getPrevSeenData( Graphs.getOppositeVertex(graph, edge, vertex)); BellmanFordPathElement pathElement = getSeenData(vertex); return pathElement.improve(oppositePrevData, edge, candidateCost); } private void savePassData(List improvedVertices) { for (V vertex : improvedVertices) { BellmanFordPathElement orig = getSeenData(vertex); BellmanFordPathElement clonedData = new BellmanFordPathElement(orig); putPrevSeenData(vertex, clonedData); } this.prevImprovedVertices = improvedVertices; } } // End BellmanFordIterator.java jgrapht-0.8.3/src/org/jgrapht/alg/DijkstraShortestPath.java0000644000175000017500000001450111706124626024144 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * DijkstraShortestPath.java * ------------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Christian Hammer * * $Id: DijkstraShortestPath.java 689 2009-07-04 06:40:29Z perfecthash $ * * Changes * ------- * 02-Sep-2003 : Initial revision (JVS); * 29-May-2005 : Make non-static and add radius support (JVS); * 07-Jun-2005 : Made generic (CH); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; /** * An implementation of Dijkstra's * shortest path algorithm using ClosestFirstIterator. * * @author John V. Sichi * @since Sep 2, 2003 */ public final class DijkstraShortestPath { //~ Instance fields -------------------------------------------------------- private GraphPath path; //~ Constructors ----------------------------------------------------------- /** * Creates and executes a new DijkstraShortestPath algorithm instance. An * instance is only good for a single search; after construction, it can be * accessed to retrieve information about the path found. * * @param graph the graph to be searched * @param startVertex the vertex at which the path should start * @param endVertex the vertex at which the path should end */ public DijkstraShortestPath(Graph graph, V startVertex, V endVertex) { this(graph, startVertex, endVertex, Double.POSITIVE_INFINITY); } /** * Creates and executes a new DijkstraShortestPath algorithm instance. An * instance is only good for a single search; after construction, it can be * accessed to retrieve information about the path found. * * @param graph the graph to be searched * @param startVertex the vertex at which the path should start * @param endVertex the vertex at which the path should end * @param radius limit on path length, or Double.POSITIVE_INFINITY for * unbounded search */ public DijkstraShortestPath( Graph graph, V startVertex, V endVertex, double radius) { if (!graph.containsVertex(endVertex)) { throw new IllegalArgumentException( "graph must contain the end vertex"); } ClosestFirstIterator iter = new ClosestFirstIterator(graph, startVertex, radius); while (iter.hasNext()) { V vertex = iter.next(); if (vertex.equals(endVertex)) { createEdgeList(graph, iter, startVertex, endVertex); return; } } path = null; } //~ Methods ---------------------------------------------------------------- /** * Return the edges making up the path found. * * @return List of Edges, or null if no path exists */ public List getPathEdgeList() { if (path == null) { return null; } else { return path.getEdgeList(); } } /** * Return the path found. * * @return path representation, or null if no path exists */ public GraphPath getPath() { return path; } /** * Return the length of the path found. * * @return path length, or Double.POSITIVE_INFINITY if no path exists */ public double getPathLength() { if (path == null) { return Double.POSITIVE_INFINITY; } else { return path.getWeight(); } } /** * Convenience method to find the shortest path via a single static method * call. If you need a more advanced search (e.g. limited by radius, or * computation of the path length), use the constructor instead. * * @param graph the graph to be searched * @param startVertex the vertex at which the path should start * @param endVertex the vertex at which the path should end * * @return List of Edges, or null if no path exists */ public static List findPathBetween( Graph graph, V startVertex, V endVertex) { DijkstraShortestPath alg = new DijkstraShortestPath( graph, startVertex, endVertex); return alg.getPathEdgeList(); } private void createEdgeList( Graph graph, ClosestFirstIterator iter, V startVertex, V endVertex) { List edgeList = new ArrayList(); V v = endVertex; while (true) { E edge = iter.getSpanningTreeEdge(v); if (edge == null) { break; } edgeList.add(edge); v = Graphs.getOppositeVertex(graph, edge, v); } Collections.reverse(edgeList); double pathLength = iter.getShortestPathLength(endVertex); path = new GraphPathImpl( graph, startVertex, endVertex, edgeList, pathLength); } } // End DijkstraShortestPath.java jgrapht-0.8.3/src/org/jgrapht/alg/EulerianCircuit.java0000644000175000017500000001166011706124626023112 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * EulerianCircuit.java * ------------------- * (C) Copyright 2008-2008, by Andrew Newell and Contributors. * * Original Author: Andrew Newell * Contributor(s): - * * $Id: EulerianCircuit.java 651 2008-12-24 21:13:41Z perfecthash $ * * Changes * ------- * 24-Dec-2008 : Initial revision (AN); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * This algorithm will check whether a graph is Eulerian (hence it contains an * Eulerian * circuit). Also, if a graph is Eulerian, the caller can obtain a list of * vertices making up the Eulerian circuit. An Eulerian circuit is a circuit * which traverses each edge exactly once. * * @author Andrew Newell * @since Dec 21, 2008 */ public abstract class EulerianCircuit { //~ Methods ---------------------------------------------------------------- /** * This method will check whether the graph passed in is Eulerian or not. * * @param g The graph to be checked * * @return true for Eulerian and false for non-Eulerian */ public static boolean isEulerian(UndirectedGraph g) { // If the graph is not connected, then no Eulerian circuit exists if (!(new ConnectivityInspector(g)).isGraphConnected()) { return false; } // A graph is Eulerian if and only if all vertices have even degree // So, this code will check for that Iterator iter = g.vertexSet().iterator(); while (iter.hasNext()) { V v = iter.next(); if ((g.degreeOf(v) % 2) == 1) { return false; } } return true; } /** * This method will return a list of vertices which represents the Eulerian * circuit of the graph. * * @param g The graph to find an Eulerian circuit * * @return null if no Eulerian circuit exists, or a list of vertices * representing the Eulerian circuit if one does exist */ public static List getEulerianCircuitVertices( UndirectedGraph g) { // If the graph is not Eulerian then just return a null since no // Eulerian circuit exists if (!isEulerian(g)) { return null; } // The circuit will be represented by a linked list List path = new LinkedList(); UndirectedGraph sg = new UndirectedSubgraph(g, null, null); path.add(sg.vertexSet().iterator().next()); // Algorithm for finding an Eulerian circuit Basically this will find an // arbitrary circuit, then it will find another arbitrary circuit until // every edge has been traversed while (sg.edgeSet().size() > 0) { V v = null; // Find a vertex which has an edge that hasn't been traversed yet, // and keep its index position in the circuit list int index = 0; for (Iterator iter = path.iterator(); iter.hasNext(); index++) { v = iter.next(); if (sg.degreeOf(v) > 0) { break; } } // Finds an arbitrary circuit of the current vertex and // appends this into the circuit list while (sg.degreeOf(v) > 0) { for ( Iterator iter = sg.vertexSet().iterator(); iter.hasNext();) { V temp = iter.next(); if (sg.containsEdge(v, temp)) { path.add(index, temp); sg.removeEdge(v, temp); v = temp; break; } } } } return path; } } // End EulerianCircuit.java jgrapht-0.8.3/src/org/jgrapht/alg/TransitiveClosure.java0000644000175000017500000000774411706124626023520 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * TransitiveClosure.java * ---------------------- * (C) Copyright 2007, by Vinayak R. Borkar. * * Original Author: Vinayak R. Borkar * Contributor(s): * * Changes * ------- * 5-May-2007: Initial revision (VRB); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.graph.*; /** * Constructs the transitive closure of the input graph. * * @author Vinayak R. Borkar * @since May 5, 2007 */ public class TransitiveClosure { //~ Static fields/initializers --------------------------------------------- /** * Singleton instance. */ public static final TransitiveClosure INSTANCE = new TransitiveClosure(); //~ Constructors ----------------------------------------------------------- /** * Private Constructor. */ private TransitiveClosure() { } //~ Methods ---------------------------------------------------------------- /** * Computes the transitive closure of the given graph. * * @param graph - Graph to compute transitive closure for. */ public void closeSimpleDirectedGraph(SimpleDirectedGraph graph) { Set vertexSet = graph.vertexSet(); Set newEdgeTargets = new HashSet(); // At every iteration of the outer loop, we add a path of length 1 // between nodes that originally had a path of length 2. In the worst // case, we need to make floor(log |V|) + 1 iterations. We stop earlier // if there is no change to the output graph. int bound = computeBinaryLog(vertexSet.size()); boolean done = false; for (int i = 0; !done && (i < bound); ++i) { done = true; for (V v1 : vertexSet) { newEdgeTargets.clear(); for (E v1OutEdge : graph.outgoingEdgesOf(v1)) { V v2 = graph.getEdgeTarget(v1OutEdge); for (E v2OutEdge : graph.outgoingEdgesOf(v2)) { V v3 = graph.getEdgeTarget(v2OutEdge); if (v1.equals(v3)) { // Its a simple graph, so no self loops. continue; } if (graph.getEdge(v1, v3) != null) { // There is already an edge from v1 ---> v3, skip; continue; } newEdgeTargets.add(v3); done = false; } } for (V v3 : newEdgeTargets) { graph.addEdge(v1, v3); } } } } /** * Computes floor(log_2(n)) + 1 */ private int computeBinaryLog(int n) { assert n >= 0; int result = 0; while (n > 0) { n >>= 1; ++result; } return result; } } // End TransitiveClosure.java jgrapht-0.8.3/src/org/jgrapht/alg/FloydWarshallShortestPaths.java0000644000175000017500000002011611706124626025326 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2009, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * FloydWarshallShortestPaths.java * ------------------------- * (C) Copyright 2009-2009, by Tom Larkworthy and Contributors * * Original Author: Tom Larkworthy * Contributor(s): Soren Davidsen * * $Id: FloydWarshallShortestPaths.java 755 2012-01-18 23:50:37Z perfecthash $ * * Changes * ------- * 29-Jun-2009 : Initial revision (TL); * 03-Dec-2009 : Optimized and enhanced version (SD); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; import org.jgrapht.util.*; /** * The * Floyd-Warshall algorithm finds all shortest paths (all n^2 of them) in * O(n^3) time. This also works out the graph diameter during the process. * * @author Tom Larkworthy * @author Soren Davidsen */ public class FloydWarshallShortestPaths { //~ Instance fields -------------------------------------------------------- private Graph graph; private List vertices; private int nShortestPaths = 0; private double diameter = 0.0; private double [][] d = null; private int [][] backtrace = null; private Map, GraphPath> paths = null; //~ Constructors ----------------------------------------------------------- public FloydWarshallShortestPaths(Graph graph) { this.graph = graph; this.vertices = new ArrayList(graph.vertexSet()); } //~ Methods ---------------------------------------------------------------- /** * @return the graph on which this algorithm operates */ public Graph getGraph() { return graph; } /** * @return total number of shortest paths */ public int getShortestPathsCount() { lazyCalculatePaths(); return nShortestPaths; } /** * Calculates the matrix of all shortest paths, along with the diameter, but * does not populate the paths map. */ private void lazyCalculateMatrix() { if (d != null) { // already done return; } int n = vertices.size(); // init the backtrace matrix backtrace = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(backtrace[i], -1); } // initialize matrix, 0 d = new double[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(d[i], Double.POSITIVE_INFINITY); } // initialize matrix, 1 for (int i = 0; i < n; i++) { d[i][i] = 0.0; } // initialize matrix, 2 Set edges = graph.edgeSet(); for (E edge : edges) { V v1 = graph.getEdgeSource(edge); V v2 = graph.getEdgeTarget(edge); int v_1 = vertices.indexOf(v1); int v_2 = vertices.indexOf(v2); d[v_1][v_2] = graph.getEdgeWeight(edge); if (!(graph instanceof DirectedGraph)) { d[v_2][v_1] = graph.getEdgeWeight(edge); } } // run fw alg for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double ik_kj = d[i][k] + d[k][j]; if (ik_kj < d[i][j]) { d[i][j] = ik_kj; backtrace[i][j] = k; diameter = (diameter > d[i][j]) ? diameter : d[i][j]; } } } } } /** * Get the length of a shortest path. * * @param a first vertex * @param b second vertex * * @return shortest distance between a and b */ public double shortestDistance(V a, V b) { lazyCalculateMatrix(); return d[vertices.indexOf(a)][vertices.indexOf(b)]; } /** * @return the diameter (longest of all the shortest paths) computed for the * graph */ public double getDiameter() { lazyCalculateMatrix(); return diameter; } private void shortestPathRecur(List edges, int v_a, int v_b) { int k = backtrace[v_a][v_b]; if (k == -1) { E edge = graph.getEdge(vertices.get(v_a), vertices.get(v_b)); if (edge != null) { edges.add(edge); } } else { shortestPathRecur(edges, v_a, k); shortestPathRecur(edges, k, v_b); } } /** * Get the shortest path between two vertices. Note: The paths are * calculated using a recursive algorithm. It *will* give problems on paths * longer than the stack allows. * * @param a From vertice * @param b To vertice * * @return the path, or null if none found */ public GraphPath getShortestPath(V a, V b) { lazyCalculatePaths(); return getShortestPathImpl(a, b); } private GraphPath getShortestPathImpl(V a, V b) { int v_a = vertices.indexOf(a); int v_b = vertices.indexOf(b); List edges = new ArrayList(); shortestPathRecur(edges, v_a, v_b); // no path, return null if (edges.size() < 1) { return null; } GraphPathImpl path = new GraphPathImpl(graph, a, b, edges, edges.size()); return path; } /** * Calculate the shortest paths (not done per default) */ private void lazyCalculatePaths() { // already we have calculated it once. if (paths != null) { return; } lazyCalculateMatrix(); Map, GraphPath> sps = new HashMap, GraphPath>(); int n = vertices.size(); nShortestPaths = 0; for (int i = 0; i < n; i++) { V v_i = vertices.get(i); for (int j = 0; j < n; j++) { // don't count this. if (i == j) { continue; } V v_j = vertices.get(j); GraphPath path = getShortestPathImpl(v_i, v_j); // we got a path if (path != null) { sps.put(new VertexPair(v_i, v_j), path); nShortestPaths++; } } } this.paths = sps; } /** * Get shortest paths from a vertex to all other vertices in the graph. * * @param v the originating vertex * * @return List of paths */ public List> getShortestPaths(V v) { lazyCalculatePaths(); List> found = new ArrayList>(); // TODO: two-level map for paths so that we don't have to // iterate over all paths here! for (VertexPair pair : paths.keySet()) { if (pair.getFirst().equals(v)) { found.add(paths.get(pair)); } } return found; } } // End FloydWarshallShortestPaths.java jgrapht-0.8.3/src/org/jgrapht/alg/BellmanFordPathElement.java0000644000175000017500000001047611706124626024343 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BellmanFordPathElement.java * ------------------------- * (C) Copyright 2006-2008, by France Telecom and Contributors. * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: BellmanFordPathElement.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jan-2006 : Initial revision (GB); * 14-Jan-2006 : Added support for generics (JVS); * */ package org.jgrapht.alg; import org.jgrapht.*; /** * Helper class for {@link BellmanFordShortestPath}; not intended for general * use. */ final class BellmanFordPathElement extends AbstractPathElement { //~ Instance fields -------------------------------------------------------- private double cost = 0; private double epsilon; //~ Constructors ----------------------------------------------------------- /** * Creates a path element by concatenation of an edge to a path element. * * @param pathElement * @param edge edge reaching the end vertex of the path element created. * @param cost total cost of the created path element. * @param epsilon tolerance factor. */ protected BellmanFordPathElement( Graph graph, BellmanFordPathElement pathElement, E edge, double cost, double epsilon) { super(graph, pathElement, edge); this.cost = cost; this.epsilon = epsilon; } /** * Copy constructor. * * @param original source to copy from */ BellmanFordPathElement(BellmanFordPathElement original) { super(original); this.cost = original.cost; this.epsilon = original.epsilon; } /** * Creates an empty path element. * * @param vertex end vertex of the path element. * @param epsilon tolerance factor. */ protected BellmanFordPathElement(V vertex, double epsilon) { super(vertex); this.cost = 0; this.epsilon = epsilon; } //~ Methods ---------------------------------------------------------------- /** * Returns the total cost of the path element. * * @return . */ public double getCost() { return this.cost; } /** * Returns true if the path has been improved, * false otherwise. We use an "epsilon" precision to check whether * the cost has been improved (because of many roundings, a formula equal to * 0 could unfortunately be evaluated to 10^-14). * * @param candidatePrevPathElement * @param candidateEdge * @param candidateCost * * @return . */ protected boolean improve( BellmanFordPathElement candidatePrevPathElement, E candidateEdge, double candidateCost) { // to avoid improvement only due to rounding errors. if (candidateCost < (getCost() - epsilon)) { this.prevPathElement = candidatePrevPathElement; this.prevEdge = candidateEdge; this.cost = candidateCost; this.nHops = candidatePrevPathElement.getHopCount() + 1; return true; } else { return false; } } } // End BellmanFordPathElement.java jgrapht-0.8.3/src/org/jgrapht/alg/StrongConnectivityInspector.java0000644000175000017500000002733111706124626025567 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * StrongConnectivityInspector.java * -------------------------- * (C) Copyright 2005-2008, by Christian Soltenborn and Contributors. * * Original Author: Christian Soltenborn * * $Id: StrongConnectivityInspector.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 2-Feb-2005 : Initial revision (CS); * 5-Feb-2007 : fixed NullPointerException (CS); * 1-Apr-2008 : Reduced memory consumption (CS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** *

    Complements the {@link org.jgrapht.alg.ConnectivityInspector} class with * the capability to compute the strongly connected components of a directed * graph. The algorithm is implemented after "Cormen et al: Introduction to * agorithms", Chapter 22.5. It has a running time of O(V + E).

    * *

    Unlike {@link org.jgrapht.alg.ConnectivityInspector}, this class does not * implement incremental inspection. The full algorithm is executed at the first * call of {@link StrongConnectivityInspector#stronglyConnectedSets()} or {@link * StrongConnectivityInspector#isStronglyConnected()}.

    * * @author Christian Soltenborn * @author Christian Hammer * @since Feb 2, 2005 */ public class StrongConnectivityInspector { //~ Instance fields -------------------------------------------------------- // the graph to compute the strongly connected sets for private final DirectedGraph graph; // stores the vertices, ordered by their finishing time in first dfs private LinkedList> orderedVertices; // the result of the computation, cached for future calls private List> stronglyConnectedSets; // the result of the computation, cached for future calls private List> stronglyConnectedSubgraphs; // maps vertices to their VertexData object private Map> vertexToVertexData; //~ Constructors ----------------------------------------------------------- /** * The constructor of the StrongConnectivityInspector class. * * @param directedGraph the graph to inspect * * @throws IllegalArgumentException */ public StrongConnectivityInspector(DirectedGraph directedGraph) { if (directedGraph == null) { throw new IllegalArgumentException("null not allowed for graph!"); } graph = directedGraph; vertexToVertexData = null; orderedVertices = null; stronglyConnectedSets = null; stronglyConnectedSubgraphs = null; } //~ Methods ---------------------------------------------------------------- /** * Returns the graph inspected by the StrongConnectivityInspector. * * @return the graph inspected by this StrongConnectivityInspector */ public DirectedGraph getGraph() { return graph; } /** * Returns true if the graph of this * StronglyConnectivityInspector instance is strongly connected. * * @return true if the graph is strongly connected, false otherwise */ public boolean isStronglyConnected() { return stronglyConnectedSets().size() == 1; } /** * Computes a {@link List} of {@link Set}s, where each set contains vertices * which together form a strongly connected component within the given * graph. * * @return List of Set s containing the strongly * connected components */ public List> stronglyConnectedSets() { if (stronglyConnectedSets == null) { orderedVertices = new LinkedList>(); stronglyConnectedSets = new Vector>(); // create VertexData objects for all vertices, store them createVertexData(); // perform the first round of DFS, result is an ordering // of the vertices by decreasing finishing time for (VertexData data : vertexToVertexData.values()) { if (!data.isDiscovered()) { dfsVisit(graph, data, null); } } // 'create' inverse graph (i.e. every edge is reversed) DirectedGraph inverseGraph = new EdgeReversedGraph(graph); // get ready for next dfs round resetVertexData(); // second dfs round: vertices are considered in decreasing // finishing time order; every tree found is a strongly // connected set for (VertexData data : orderedVertices) { if (!data.isDiscovered()) { // new strongly connected set Set set = new HashSet(); stronglyConnectedSets.add(set); dfsVisit(inverseGraph, data, set); } } // clean up for garbage collection orderedVertices = null; vertexToVertexData = null; } return stronglyConnectedSets; } /** *

    Computes a list of {@link DirectedSubgraph}s of the given graph. Each * subgraph will represent a strongly connected component and will contain * all vertices of that component. The subgraph will have an edge (u,v) iff * u and v are contained in the strongly connected component.

    * *

    NOTE: Calling this method will first execute {@link * StrongConnectivityInspector#stronglyConnectedSets()}. If you don't need * subgraphs, use that method.

    * * @return a list of subgraphs representing the strongly connected * components */ public List> stronglyConnectedSubgraphs() { if (stronglyConnectedSubgraphs == null) { List> sets = stronglyConnectedSets(); stronglyConnectedSubgraphs = new Vector>(sets.size()); for (Set set : sets) { stronglyConnectedSubgraphs.add( new DirectedSubgraph( graph, set, null)); } } return stronglyConnectedSubgraphs; } /* * Creates a VertexData object for every vertex in the graph and stores * them * in a HashMap. */ private void createVertexData() { vertexToVertexData = new HashMap>(graph.vertexSet().size()); for (V vertex : graph.vertexSet()) { vertexToVertexData.put( vertex, new VertexData2(vertex, false, false)); } } /* * The subroutine of DFS. NOTE: the set is used to distinguish between 1st * and 2nd round of DFS. set == null: finished vertices are stored (1st * round). set != null: all vertices found will be saved in the set (2nd * round) */ private void dfsVisit( DirectedGraph visitedGraph, VertexData vertexData, Set vertices) { Deque> stack = new ArrayDeque>(); stack.add(vertexData); while (!stack.isEmpty()) { VertexData data = stack.removeLast(); if (!data.isDiscovered()) { data.setDiscovered(true); if (vertices != null) { vertices.add(data.getVertex()); } stack.add(new VertexData1(data, true, true)); // follow all edges for (E edge : visitedGraph.outgoingEdgesOf(data.getVertex())) { VertexData targetData = vertexToVertexData.get( visitedGraph.getEdgeTarget(edge)); if (!targetData.isDiscovered()) { // the "recursion" stack.add(targetData); } } } else if (data.isFinished()) { if (vertices == null) { orderedVertices.addFirst(data.getFinishedData()); } } } } /* * Resets all VertexData objects. */ private void resetVertexData() { for (VertexData data : vertexToVertexData.values()) { data.setDiscovered(false); data.setFinished(false); } } //~ Inner Classes ---------------------------------------------------------- /* * Lightweight class storing some data for every vertex. */ private static abstract class VertexData { private byte bitfield; private VertexData( boolean discovered, boolean finished) { this.bitfield = 0; setDiscovered(discovered); setFinished(finished); } private boolean isDiscovered() { if ((bitfield & 1) == 1) { return true; } return false; } private boolean isFinished() { if ((bitfield & 2) == 2) { return true; } return false; } private void setDiscovered(boolean discovered) { if (discovered) { bitfield |= 1; } else { bitfield &= ~1; } } private void setFinished(boolean finished) { if (finished) { bitfield |= 2; } else { bitfield &= ~2; } } abstract VertexData getFinishedData(); abstract V getVertex(); } private static final class VertexData1 extends VertexData { private final VertexData finishedData; private VertexData1( VertexData finishedData, boolean discovered, boolean finished) { super(discovered, finished); this.finishedData = finishedData; } VertexData getFinishedData() { return finishedData; } V getVertex() { return null; } } private static final class VertexData2 extends VertexData { private final V vertex; private VertexData2( V vertex, boolean discovered, boolean finished) { super(discovered, finished); this.vertex = vertex; } VertexData getFinishedData() { return null; } V getVertex() { return vertex; } } } // End StrongConnectivityInspector.java jgrapht-0.8.3/src/org/jgrapht/alg/BronKerboschCliqueFinder.java0000644000175000017500000001523311706124626024677 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * BronKerboschCliqueFinder.java * ------------------- * (C) Copyright 2005-2008, by Ewgenij Proschak and Contributors. * * Original Author: Ewgenij Proschak * Contributor(s): John V. Sichi * * $Id: BronKerboschCliqueFinder.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 21-Jul-2005 : Initial revision (EP); * 26-Jul-2005 : Cleaned up and checked in (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * This class implements Bron-Kerbosch clique detection algorithm as it is * described in [Samudrala R.,Moult J.:A Graph-theoretic Algorithm for * comparative Modeling of Protein Structure; J.Mol. Biol. (1998); vol 279; pp. * 287-302] * * @author Ewgenij Proschak */ public class BronKerboschCliqueFinder { //~ Instance fields -------------------------------------------------------- private final Graph graph; private Collection> cliques; //~ Constructors ----------------------------------------------------------- /** * Creates a new clique finder. * * @param graph the graph in which cliques are to be found; graph must be * simple */ public BronKerboschCliqueFinder(Graph graph) { this.graph = graph; } //~ Methods ---------------------------------------------------------------- /** * Finds all maximal cliques of the graph. A clique is maximal if it is * impossible to enlarge it by adding another vertex from the graph. Note * that a maximal clique is not necessarily the biggest clique in the graph. * * @return Collection of cliques (each of which is represented as a Set of * vertices) */ public Collection> getAllMaximalCliques() { // TODO jvs 26-July-2005: assert that graph is simple cliques = new ArrayList>(); List potential_clique = new ArrayList(); List candidates = new ArrayList(); List already_found = new ArrayList(); candidates.addAll(graph.vertexSet()); findCliques(potential_clique, candidates, already_found); return cliques; } /** * Finds the biggest maximal cliques of the graph. * * @return Collection of cliques (each of which is represented as a Set of * vertices) */ public Collection> getBiggestMaximalCliques() { // first, find all cliques getAllMaximalCliques(); int maximum = 0; Collection> biggest_cliques = new ArrayList>(); for (Set clique : cliques) { if (maximum < clique.size()) { maximum = clique.size(); } } for (Set clique : cliques) { if (maximum == clique.size()) { biggest_cliques.add(clique); } } return biggest_cliques; } private void findCliques( List potential_clique, List candidates, List already_found) { List candidates_array = new ArrayList(candidates); if (!end(candidates, already_found)) { // for each candidate_node in candidates do for (V candidate : candidates_array) { List new_candidates = new ArrayList(); List new_already_found = new ArrayList(); // move candidate node to potential_clique potential_clique.add(candidate); candidates.remove(candidate); // create new_candidates by removing nodes in candidates not // connected to candidate node for (V new_candidate : candidates) { if (graph.containsEdge(candidate, new_candidate)) { new_candidates.add(new_candidate); } // of if } // of for // create new_already_found by removing nodes in already_found // not connected to candidate node for (V new_found : already_found) { if (graph.containsEdge(candidate, new_found)) { new_already_found.add(new_found); } // of if } // of for // if new_candidates and new_already_found are empty if (new_candidates.isEmpty() && new_already_found.isEmpty()) { // potential_clique is maximal_clique cliques.add(new HashSet(potential_clique)); } // of if else { // recursive call findCliques( potential_clique, new_candidates, new_already_found); } // of else // move candidate_node from potential_clique to already_found; already_found.add(candidate); potential_clique.remove(candidate); } // of for } // of if } private boolean end(List candidates, List already_found) { // if a node in already_found is connected to all nodes in candidates boolean end = false; int edgecounter; for (V found : already_found) { edgecounter = 0; for (V candidate : candidates) { if (graph.containsEdge(found, candidate)) { edgecounter++; } // of if } // of for if (edgecounter == candidates.size()) { end = true; } } // of for return end; } } // End BronKerboschCliqueFinder.java jgrapht-0.8.3/src/org/jgrapht/alg/ConnectivityInspector.java0000644000175000017500000002333211706124626024367 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * ConnectivityInspector.java * -------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): John V. Sichi * Christian Hammer * * $Id: ConnectivityInspector.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Aug-2003 : Initial revision (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 07-Jun-2005 : Made generic (CH); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.event.*; import org.jgrapht.graph.*; import org.jgrapht.traverse.*; /** * Allows obtaining various connectivity aspects of a graph. The inspected * graph is specified at construction time and cannot be modified. * Currently, the inspector supports connected components for an undirected * graph and weakly connected components for a directed graph. To find strongly * connected components, use {@link StrongConnectivityInspector} instead. * *

    The inspector methods work in a lazy fashion: no computation is performed * unless immediately necessary. Computation are done once and results and * cached within this class for future need.

    * *

    The inspector is also a {@link org.jgrapht.event.GraphListener}. If added * as a listener to the inspected graph, the inspector will amend internal * cached results instead of recomputing them. It is efficient when a few * modifications are applied to a large graph. If many modifications are * expected it will not be efficient due to added overhead on graph update * operations. If inspector is added as listener to a graph other than the one * it inspects, results are undefined.

    * * @author Barak Naveh * @author John V. Sichi * @since Aug 6, 2003 */ public class ConnectivityInspector implements GraphListener { //~ Instance fields -------------------------------------------------------- List> connectedSets; Map> vertexToConnectedSet; private Graph graph; //~ Constructors ----------------------------------------------------------- /** * Creates a connectivity inspector for the specified undirected graph. * * @param g the graph for which a connectivity inspector to be created. */ public ConnectivityInspector(UndirectedGraph g) { init(); this.graph = g; } /** * Creates a connectivity inspector for the specified directed graph. * * @param g the graph for which a connectivity inspector to be created. */ public ConnectivityInspector(DirectedGraph g) { init(); this.graph = new AsUndirectedGraph(g); } //~ Methods ---------------------------------------------------------------- /** * Test if the inspected graph is connected. An empty graph is not * considered connected. * * @return true if and only if inspected graph is connected. */ public boolean isGraphConnected() { return lazyFindConnectedSets().size() == 1; } /** * Returns a set of all vertices that are in the maximally connected * component together with the specified vertex. For more on maximally * connected component, see * http://www.nist.gov/dads/HTML/maximallyConnectedComponent.html. * * @param vertex the vertex for which the connected set to be returned. * * @return a set of all vertices that are in the maximally connected * component together with the specified vertex. */ public Set connectedSetOf(V vertex) { Set connectedSet = vertexToConnectedSet.get(vertex); if (connectedSet == null) { connectedSet = new HashSet(); BreadthFirstIterator i = new BreadthFirstIterator(graph, vertex); while (i.hasNext()) { connectedSet.add(i.next()); } vertexToConnectedSet.put(vertex, connectedSet); } return connectedSet; } /** * Returns a list of Set s, where each set contains all * vertices that are in the same maximally connected component. All graph * vertices occur in exactly one set. For more on maximally connected * component, see * http://www.nist.gov/dads/HTML/maximallyConnectedComponent.html. * * @return Returns a list of Set s, where each set contains all * vertices that are in the same maximally connected component. */ public List> connectedSets() { return lazyFindConnectedSets(); } /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded(GraphEdgeChangeEvent e) { init(); // for now invalidate cached results, in the future need to // amend them. } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved(GraphEdgeChangeEvent e) { init(); // for now invalidate cached results, in the future need to // amend them. } /** * Tests if there is a path from the specified source vertex to the * specified target vertices. For a directed graph, direction is ignored for * this interpretation of path. * *

    Note: Future versions of this method might not ignore edge directions * for directed graphs.

    * * @param sourceVertex one end of the path. * @param targetVertex another end of the path. * * @return true if and only if there is a path from the source * vertex to the target vertex. */ public boolean pathExists(V sourceVertex, V targetVertex) { /* * TODO: Ignoring edge direction for directed graph may be * confusing. For directed graphs, consider Dijkstra's algorithm. */ Set sourceSet = connectedSetOf(sourceVertex); return sourceSet.contains(targetVertex); } /** * @see VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded(GraphVertexChangeEvent e) { init(); // for now invalidate cached results, in the future need to // amend them. } /** * @see VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved(GraphVertexChangeEvent e) { init(); // for now invalidate cached results, in the future need to // amend them. } private void init() { connectedSets = null; vertexToConnectedSet = new HashMap>(); } private List> lazyFindConnectedSets() { if (connectedSets == null) { connectedSets = new ArrayList>(); Set vertexSet = graph.vertexSet(); if (vertexSet.size() > 0) { BreadthFirstIterator i = new BreadthFirstIterator(graph, null); i.addTraversalListener(new MyTraversalListener()); while (i.hasNext()) { i.next(); } } } return connectedSets; } //~ Inner Classes ---------------------------------------------------------- /** * A traversal listener that groups all vertices according to to their * containing connected set. * * @author Barak Naveh * @since Aug 6, 2003 */ private class MyTraversalListener extends TraversalListenerAdapter { private Set currentConnectedSet; /** * @see TraversalListenerAdapter#connectedComponentFinished(ConnectedComponentTraversalEvent) */ public void connectedComponentFinished( ConnectedComponentTraversalEvent e) { connectedSets.add(currentConnectedSet); } /** * @see TraversalListenerAdapter#connectedComponentStarted(ConnectedComponentTraversalEvent) */ public void connectedComponentStarted( ConnectedComponentTraversalEvent e) { currentConnectedSet = new HashSet(); } /** * @see TraversalListenerAdapter#vertexTraversed(VertexTraversalEvent) */ public void vertexTraversed(VertexTraversalEvent e) { V v = e.getVertex(); currentConnectedSet.add(v); vertexToConnectedSet.put(v, currentConnectedSet); } } } // End ConnectivityInspector.java jgrapht-0.8.3/src/org/jgrapht/alg/AbstractPathElementList.java0000644000175000017500000001315611706124626024553 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * AbstractPathElementList.java * ------------------------- * (C) Copyright 2007-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: AbstractPathElementList.java 742 2011-03-12 23:06:31Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * 06-Dec-2010 : Bugfixes (GB); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * List of paths AbstractPathElement with same target vertex. * * @author Guillaume Boulmier * @since July 5, 2007 */ abstract class AbstractPathElementList> extends AbstractList { //~ Instance fields -------------------------------------------------------- protected Graph graph; /** * Max number of stored paths. */ protected int maxSize; /** * Stored paths, list of AbstractPathElement. */ protected ArrayList pathElements = new ArrayList(); /** * Target vertex of the paths. */ protected V vertex; //~ Constructors ----------------------------------------------------------- /** * Creates paths obtained by concatenating the specified edge to the * specified paths. * * @param maxSize maximum number of paths the list is able to store. * @param elementList paths, list of AbstractPathElement. * @param edge edge reaching the end vertex of the created paths. * * @throws NullPointerException if the specified prevPathElementList or edge * is null. * @throws IllegalArgumentException if maxSize is negative or * 0. */ protected AbstractPathElementList( Graph graph, int maxSize, AbstractPathElementList elementList, E edge) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize is negative or 0"); } if (elementList == null) { throw new NullPointerException("elementList is null"); } if (edge == null) { throw new NullPointerException("edge is null"); } this.graph = graph; this.maxSize = maxSize; this.vertex = Graphs.getOppositeVertex(graph, edge, elementList.getVertex()); } /** * Creates a list with an empty path. The list size is 1. * * @param maxSize maximum number of paths the list is able to store. * * @throws NullPointerException if the specified path-element is * null. * @throws IllegalArgumentException if maxSize is negative or * 0. * @throws IllegalArgumentException if pathElement is not * empty. */ protected AbstractPathElementList( Graph graph, int maxSize, T pathElement) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize is negative or 0"); } if (pathElement == null) { throw new NullPointerException("pathElement is null"); } if (pathElement.getPrevEdge() != null) { throw new IllegalArgumentException("path must be empty"); } this.graph = graph; this.maxSize = maxSize; this.vertex = pathElement.getVertex(); this.pathElements.add(pathElement); } /** * Creates an empty list. The list size is 0. * * @param maxSize maximum number of paths the list is able to store. * * @throws IllegalArgumentException if maxSize is negative or * 0. */ protected AbstractPathElementList(Graph graph, int maxSize, V vertex) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize is negative or 0"); } this.graph = graph; this.maxSize = maxSize; this.vertex = vertex; } //~ Methods ---------------------------------------------------------------- /** * Returns path AbstractPathElement stored at the specified * index. */ public T get(int index) { return this.pathElements.get(index); } /** * Returns target vertex. */ public V getVertex() { return this.vertex; } /** * Returns the number of paths stored in the list. */ public int size() { return this.pathElements.size(); } } // End AbstractPathElementList.java jgrapht-0.8.3/src/org/jgrapht/alg/KShortestPathsIterator.java0000644000175000017500000003212211706124626024457 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2010, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * KShortestPathsIterator.java * ------------------------- * (C) Copyright 2007-2010, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: KShortestPathsIterator.java 742 2011-03-12 23:06:31Z perfecthash $ * * Changes * ------- * 05-Jun-2007 : Initial revision (GB); * 05-Jul-2007 : Added support for generics (JVS); * 06-Dec-2010 : Bugfixes (GB); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * Helper class for {@link KShortestPaths}. * * @author Guillaume Boulmier * @since July 5, 2007 */ class KShortestPathsIterator implements Iterator> { //~ Instance fields -------------------------------------------------------- /** * End vertex. */ private V endVertex; /** * Graph on which shortest paths are searched. */ private Graph graph; /** * Number of paths stored at each end vertex. */ private int k; /** * Vertices whose ranking shortest paths have been modified during the * previous pass. */ private Set prevImprovedVertices; /** * Stores the paths that improved the vertex in the previous pass. */ private Map> prevSeenDataContainer; /** * Stores the vertices that have been seen during iteration and (optionally) * some additional traversal info regarding each vertex. Key = vertex, value * = RankingPathElementList list of calculated paths. */ private Map> seenDataContainer; /** * Start vertex. */ private V startVertex; private boolean startVertexEncountered; /** * Stores the number of the path. */ private int passNumber = 1; //~ Constructors ----------------------------------------------------------- /** * @param graph graph on which shortest paths are searched. * @param startVertex start vertex of the calculated paths. * @param endVertex end vertex of the calculated paths. * @param maxSize number of paths stored at end vertex of the graph. */ public KShortestPathsIterator( Graph graph, V startVertex, V endVertex, int maxSize) { assertKShortestPathsIterator(graph, startVertex); this.graph = graph; this.startVertex = startVertex; this.endVertex = endVertex; this.k = maxSize; this.seenDataContainer = new HashMap>(); this.prevSeenDataContainer = new HashMap>(); this.prevImprovedVertices = new HashSet(); } //~ Methods ---------------------------------------------------------------- /** * @return true if at least one path has been improved during * the previous pass, false otherwise. */ public boolean hasNext() { if (!this.startVertexEncountered) { encounterStartVertex(); } return !(this.prevImprovedVertices.isEmpty()); } /** * Returns the list of vertices whose path has been improved during the * current pass. Complexity = * *
      *
    • O(m*k*(m+n)) where k is the maximum number * of shortest paths to compute, m is the number of edges of * the graph and n is the number of vertices of the graph
    • *
    * * @see java.util.Iterator#next() */ public Set next() { if (!this.startVertexEncountered) { encounterStartVertex(); } // at the i-th pass the shortest paths with i edges are calculated. if (hasNext()) { Set improvedVertices = new HashSet(); for ( Iterator iter = this.prevImprovedVertices.iterator(); iter.hasNext();) { V vertex = iter.next(); if (!vertex.equals(this.endVertex)) { updateOutgoingVertices(vertex, improvedVertices); } } savePassData(improvedVertices); this.passNumber++; return improvedVertices; } throw new NoSuchElementException(); } /** * Unsupported. * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } /** * Returns the path elements of the ranking shortest paths with less than * nMaxHops edges between the start vertex and the end vertex. * * @param endVertex end vertex. * * @return list of RankingPathElement, or null of * no path exists between the start vertex and the end vertex. */ RankingPathElementList getPathElements(V endVertex) { return this.seenDataContainer.get(endVertex); } private void assertKShortestPathsIterator(Graph graph, V startVertex) { if (graph == null) { throw new NullPointerException("graph is null"); } if (startVertex == null) { throw new NullPointerException("startVertex is null"); } } /** * The first time we see a vertex, make up a new entry for it. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. * * @return the new entry. */ private RankingPathElementList createSeenData(V vertex, E edge) { V oppositeVertex = Graphs.getOppositeVertex(this.graph, edge, vertex); RankingPathElementList oppositeData = this.prevSeenDataContainer.get(oppositeVertex); // endVertex in argument to ensure that stored paths do not disconnect // the end-vertex RankingPathElementList data = new RankingPathElementList( this.graph, this.k, oppositeData, edge, this.endVertex); return data; } /** * Returns an iterator to loop over outgoing edges Edge of the * vertex. * * @param vertex * * @return . */ private Iterator edgesOfIterator(V vertex) { if (this.graph instanceof DirectedGraph) { return ((DirectedGraph) this.graph).outgoingEdgesOf(vertex) .iterator(); } else { return this.graph.edgesOf(vertex).iterator(); } } /** * Initializes the list of paths at the start vertex and adds an empty path. */ private void encounterStartVertex() { RankingPathElementList data = new RankingPathElementList( this.graph, this.k, new RankingPathElement( this.startVertex)); this.seenDataContainer.put(this.startVertex, data); this.prevSeenDataContainer.put(this.startVertex, data); // initially the only vertex whose value is considered to have changed // is the start vertex this.prevImprovedVertices.add(this.startVertex); this.startVertexEncountered = true; } private void savePassData(Set improvedVertices) { for (Iterator iter = improvedVertices.iterator(); iter.hasNext();) { V vertex = iter.next(); RankingPathElementList pathElementList = this.seenDataContainer.get(vertex); RankingPathElementList improvedPaths = new RankingPathElementList( this.graph, pathElementList.maxSize, vertex); for ( Iterator> pathIter = pathElementList.iterator(); pathIter.hasNext();) { RankingPathElement path = pathIter.next(); if (path.getHopCount() == this.passNumber) { // the path has just been computed. improvedPaths.pathElements.add(path); } } this.prevSeenDataContainer.put(vertex, improvedPaths); } this.prevImprovedVertices = improvedVertices; } /** * Try to add the first paths to the specified vertex. These paths reached * the specified vertex and ended with the specified edge. A new * intermediary path is stored in the paths list of the specified vertex * provided that the path can be extended to the end-vertex. * * @param vertex vertex reached by a path. * @param edge edge reaching the vertex. */ private boolean tryToAddFirstPaths(V vertex, E edge) { // the vertex has not been reached yet RankingPathElementList data = createSeenData(vertex, edge); if (!data.isEmpty()) { this.seenDataContainer.put(vertex, data); return true; } return false; } /** * Try to add new paths for the vertex. These new paths reached the * specified vertex and ended with the specified edge. A new intermediary * path is stored in the paths list of the specified vertex provided that * the path can be extended to the end-vertex. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. */ private boolean tryToAddNewPaths(V vertex, E edge) { RankingPathElementList data = this.seenDataContainer.get(vertex); V oppositeVertex = Graphs.getOppositeVertex(this.graph, edge, vertex); RankingPathElementList oppositeData = this.prevSeenDataContainer.get(oppositeVertex); return data.addPathElements(oppositeData, edge); } /** *

    Updates outgoing vertices of the vertex. For each outgoing vertex, the * new paths are obtained by concatenating the specified edge to the * calculated paths of the specified vertex. If the weight of a new path is * greater than the weight of any path stored so far at the outgoing vertex * then the path is not added, otherwise it is added to the list of paths in * increasing order of weight.

    * * Complexity = * *
      *
    • O(d(v)*k*(m+n)) where d(v) is the outgoing * degree of the specified vertex, k is the maximum number of * shortest paths to compute, m is the number of edges of the * graph and n is the number of vertices of the graph
    • *
    * * @param vertex * @param improvedVertices */ private void updateOutgoingVertices(V vertex, Set improvedVertices) { // try to add new paths for the target vertices of the outgoing edges // of the vertex in argument. for (Iterator iter = edgesOfIterator(vertex); iter.hasNext();) { E edge = iter.next(); V vertexReachedByEdge = Graphs.getOppositeVertex(this.graph, edge, vertex); // check if the path does not loop over the start vertex. if (vertexReachedByEdge != this.startVertex) { if (this.seenDataContainer.containsKey(vertexReachedByEdge)) { boolean relaxed = tryToAddNewPaths(vertexReachedByEdge, edge); if (relaxed) { improvedVertices.add(vertexReachedByEdge); } } else { boolean relaxed = tryToAddFirstPaths(vertexReachedByEdge, edge); if (relaxed) { improvedVertices.add(vertexReachedByEdge); } } } } } } // End KShortestPathsIterator.java jgrapht-0.8.3/src/org/jgrapht/alg/VertexCovers.java0000644000175000017500000001241611706124626022462 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * VertexCovers.java * ----------------- * (C) Copyright 2003-2008, by Linda Buisman and Contributors. * * Original Author: Linda Buisman * Contributor(s): Barak Naveh * Christian Hammer * * $Id: VertexCovers.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Nov-2003 : Initial revision (LB); * 07-Jun-2005 : Made generic (CH); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; import org.jgrapht.alg.util.*; import org.jgrapht.graph.*; /** * Algorithms to find a vertex cover for a graph. A vertex cover is a set of * vertices that touches all the edges in the graph. The graph's vertex set is a * trivial cover. However, a minimal vertex set (or at least an * approximation for it) is usually desired. Finding a true minimal vertex cover * is an NP-Complete problem. For more on the vertex cover problem, see * http://mathworld.wolfram.com/VertexCover.html * * @author Linda Buisman * @since Nov 6, 2003 */ public abstract class VertexCovers { //~ Methods ---------------------------------------------------------------- /** * Finds a 2-approximation for a minimal vertex cover of the specified * graph. The algorithm promises a cover that is at most double the size of * a minimal cover. The algorithm takes O(|E|) time. * *

    For more details see Jenny Walter, CMPU-240: Lecture notes for * Language Theory and Computation, Fall 2002, Vassar College, * http://www.cs.vassar.edu/~walter/cs241index/lectures/PDF/approx.pdf. *

    * * @param g the graph for which vertex cover approximation is to be found. * * @return a set of vertices which is a vertex cover for the specified * graph. */ public static Set find2ApproximationCover(Graph g) { // C <-- {} Set cover = new HashSet(); // G'=(V',E') <-- G(V,E) Subgraph> sg = new Subgraph>( g, null, null); // while E' is non-empty while (sg.edgeSet().size() > 0) { // let (u,v) be an arbitrary edge of E' E e = sg.edgeSet().iterator().next(); // C <-- C U {u,v} V u = g.getEdgeSource(e); V v = g.getEdgeTarget(e); cover.add(u); cover.add(v); // remove from E' every edge incident on either u or v sg.removeVertex(u); sg.removeVertex(v); } return cover; // return C } /** * Finds a greedy approximation for a minimal vertex cover of a specified * graph. At each iteration, the algorithm picks the vertex with the highest * degree and adds it to the cover, until all edges are covered. * *

    The algorithm works on undirected graphs, but can also work on * directed graphs when their edge-directions are ignored. To ignore edge * directions you can use {@link org.jgrapht.Graphs#undirectedGraph(Graph)} * or {@link org.jgrapht.graph.AsUndirectedGraph}.

    * * @param g the graph for which vertex cover approximation is to be found. * * @return a set of vertices which is a vertex cover for the specified * graph. */ public static Set findGreedyCover(UndirectedGraph g) { // C <-- {} Set cover = new HashSet(); // G' <-- G UndirectedGraph sg = new UndirectedSubgraph(g, null, null); // compare vertices in descending order of degree VertexDegreeComparator comp = new VertexDegreeComparator(sg); // while G' != {} while (sg.edgeSet().size() > 0) { // v <-- vertex with maximum degree in G' V v = Collections.max(sg.vertexSet(), comp); // C <-- C U {v} cover.add(v); // remove from G' every edge incident on v, and v itself sg.removeVertex(v); } return cover; } } // End VertexCovers.java jgrapht-0.8.3/src/org/jgrapht/alg/AbstractPathElement.java0000644000175000017500000001220211706124626023706 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * AbstractPathElement.java * ------------------------- * (C) Copyright 2006-2008, by France Telecom * * Original Author: Guillaume Boulmier and Contributors. * Contributor(s): John V. Sichi * * $Id: AbstractPathElement.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 05-Jan-2006 : Initial revision (GB); * 14-Jan-2006 : Added support for generics (JVS); * */ package org.jgrapht.alg; import java.util.*; import org.jgrapht.*; /** * A new path is created from a path concatenated to an edge. It's like a linked * list.
    * The empty path is composed only of one vertex.
    * In this case the path has no previous path element.
    * . * *

    NOTE jvs 1-Jan-2008: This is an internal data structure for use in * algorithms. For returning paths to callers, use the public {@link GraphPath} * interface instead. * * @author Guillaume Boulmier * @since July 5, 2007 */ abstract class AbstractPathElement { //~ Instance fields -------------------------------------------------------- /** * Number of hops of the path. */ protected int nHops; /** * Edge reaching the target vertex of the path. */ protected E prevEdge; /** * Previous path element. */ protected AbstractPathElement prevPathElement; /** * Target vertex. */ private V vertex; //~ Constructors ----------------------------------------------------------- /** * Creates a path element by concatenation of an edge to a path element. * * @param pathElement * @param edge edge reaching the end vertex of the path element created. */ protected AbstractPathElement( Graph graph, AbstractPathElement pathElement, E edge) { this.vertex = Graphs.getOppositeVertex( graph, edge, pathElement.getVertex()); this.prevEdge = edge; this.prevPathElement = pathElement; this.nHops = pathElement.getHopCount() + 1; } /** * Copy constructor. * * @param original source to copy from */ protected AbstractPathElement(AbstractPathElement original) { this.nHops = original.nHops; this.prevEdge = original.prevEdge; this.prevPathElement = original.prevPathElement; this.vertex = original.vertex; } /** * Creates an empty path element. * * @param vertex end vertex of the path element. */ protected AbstractPathElement(V vertex) { this.vertex = vertex; this.prevEdge = null; this.prevPathElement = null; this.nHops = 0; } //~ Methods ---------------------------------------------------------------- /** * Returns the path as a list of edges. * * @return list of Edge. */ public List createEdgeListPath() { List path = new ArrayList(); AbstractPathElement pathElement = this; // while start vertex is not reached. while (pathElement.getPrevEdge() != null) { path.add(pathElement.getPrevEdge()); pathElement = pathElement.getPrevPathElement(); } Collections.reverse(path); return path; } /** * Returns the number of hops (or number of edges) of the path. * * @return . */ public int getHopCount() { return this.nHops; } /** * Returns the edge reaching the target vertex of the path. * * @return null if the path is empty. */ public E getPrevEdge() { return this.prevEdge; } /** * Returns the previous path element. * * @return null is the path is empty. */ public AbstractPathElement getPrevPathElement() { return this.prevPathElement; } /** * Returns the target vertex of the path. * * @return . */ public V getVertex() { return this.vertex; } } // End AbstractPathElement.java jgrapht-0.8.3/src/org/jgrapht/event/0000755000175000017500000000000011752244357017537 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/event/ConnectedComponentTraversalEvent.java0000644000175000017500000000561211706124626027054 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------------------- * ConnectedComponentTraversalEvent.java * ------------------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: ConnectedComponentTraversalEvent.java 487 2006-07-02 00:53:17Z * perfecthash $ * * Changes * ------- * 11-Aug-2003 : Initial revision (BN); * */ package org.jgrapht.event; import java.util.*; /** * A traversal event with respect to a connected component. * * @author Barak Naveh * @since Aug 11, 2003 */ public class ConnectedComponentTraversalEvent extends EventObject { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3834311717709822262L; /** * Connected component traversal started event. */ public static final int CONNECTED_COMPONENT_STARTED = 31; /** * Connected component traversal finished event. */ public static final int CONNECTED_COMPONENT_FINISHED = 32; //~ Instance fields -------------------------------------------------------- /** * The type of this event. */ private int type; //~ Constructors ----------------------------------------------------------- /** * Creates a new ConnectedComponentTraversalEvent. * * @param eventSource the source of the event. * @param type the type of event. */ public ConnectedComponentTraversalEvent(Object eventSource, int type) { super(eventSource); this.type = type; } //~ Methods ---------------------------------------------------------------- /** * Returns the event type. * * @return the event type. */ public int getType() { return type; } } // End ConnectedComponentTraversalEvent.java jgrapht-0.8.3/src/org/jgrapht/event/package.html0000644000175000017500000000031311706124626022010 0ustar giovannigiovanni Event classes and listener interfaces, used to provide a change notification mechanism on graph modification events. jgrapht-0.8.3/src/org/jgrapht/event/GraphVertexChangeEvent.java0000644000175000017500000000723711706124626024755 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * GraphVertexChangeEvent.java * --------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphVertexChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 10-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; /** * An event which indicates that a graph vertex has changed, or is about to * change. The event can be used either as an indication after the vertex * has been added or removed, or before it is added. The type of the * event can be tested using the {@link * org.jgrapht.event.GraphChangeEvent#getType()} method. * * @author Barak Naveh * @since Aug 10, 2003 */ public class GraphVertexChangeEvent extends GraphChangeEvent { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3690189962679104053L; /** * Before vertex added event. This event is fired before a vertex is added * to a graph. */ public static final int BEFORE_VERTEX_ADDED = 11; /** * Before vertex removed event. This event is fired before a vertex is * removed from a graph. */ public static final int BEFORE_VERTEX_REMOVED = 12; /** * Vertex added event. This event is fired after a vertex is added to a * graph. */ public static final int VERTEX_ADDED = 13; /** * Vertex removed event. This event is fired after a vertex is removed from * a graph. */ public static final int VERTEX_REMOVED = 14; //~ Instance fields -------------------------------------------------------- /** * The vertex that this event is related to. */ protected V vertex; //~ Constructors ----------------------------------------------------------- /** * Creates a new GraphVertexChangeEvent object. * * @param eventSource the source of the event. * @param type the type of the event. * @param vertex the vertex that the event is related to. */ public GraphVertexChangeEvent(Object eventSource, int type, V vertex) { super(eventSource, type); this.vertex = vertex; } //~ Methods ---------------------------------------------------------------- /** * Returns the vertex that this event is related to. * * @return the vertex that this event is related to. */ public V getVertex() { return vertex; } } // End GraphVertexChangeEvent.java jgrapht-0.8.3/src/org/jgrapht/event/TraversalListenerAdapter.java0000644000175000017500000000537411706124626025360 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * TraversalListenerAdapter.java * ----------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: TraversalListenerAdapter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 06-Aug-2003 : Initial revision (BN); * 11-Aug-2003 : Adaptation to new event model (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; /** * An empty do-nothing implementation of the {@link TraversalListener} interface * used for subclasses. * * @author Barak Naveh * @since Aug 6, 2003 */ public class TraversalListenerAdapter implements TraversalListener { //~ Methods ---------------------------------------------------------------- /** * @see TraversalListener#connectedComponentFinished(ConnectedComponentTraversalEvent) */ public void connectedComponentFinished( ConnectedComponentTraversalEvent e) { } /** * @see TraversalListener#connectedComponentStarted(ConnectedComponentTraversalEvent) */ public void connectedComponentStarted(ConnectedComponentTraversalEvent e) { } /** * @see TraversalListener#edgeTraversed(EdgeTraversalEvent) */ public void edgeTraversed(EdgeTraversalEvent e) { } /** * @see TraversalListener#vertexTraversed(VertexTraversalEvent) */ public void vertexTraversed(VertexTraversalEvent e) { } /** * @see TraversalListener#vertexFinished(VertexTraversalEvent) */ public void vertexFinished(VertexTraversalEvent e) { } } // End TraversalListenerAdapter.java jgrapht-0.8.3/src/org/jgrapht/event/GraphListener.java0000644000175000017500000000442711706124626023153 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * GraphListener.java * ------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphListener.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; /** * A listener that is notified when the graph changes. * *

    If only notifications on vertex set changes are required it is more * efficient to use the VertexSetListener.

    * * @author Barak Naveh * @see VertexSetListener * @since Jul 18, 2003 */ public interface GraphListener extends VertexSetListener { //~ Methods ---------------------------------------------------------------- /** * Notifies that an edge has been added to the graph. * * @param e the edge event. */ public void edgeAdded(GraphEdgeChangeEvent e); /** * Notifies that an edge has been removed from the graph. * * @param e the edge event. */ public void edgeRemoved(GraphEdgeChangeEvent e); } // End GraphListener.java jgrapht-0.8.3/src/org/jgrapht/event/GraphChangeEvent.java0000644000175000017500000000510511706124626023547 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------- * GraphChangeEvent.java * --------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: GraphChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 10-Aug-2003 : Initial revision (BN); * */ package org.jgrapht.event; import java.util.*; /** * An event which indicates that a graph has changed. This class is a root for * graph change events. * * @author Barak Naveh * @since Aug 10, 2003 */ public class GraphChangeEvent extends EventObject { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3834592106026382391L; //~ Instance fields -------------------------------------------------------- /** * The type of graph change this event indicates. */ protected int type; //~ Constructors ----------------------------------------------------------- /** * Creates a new graph change event. * * @param eventSource the source of the event. * @param type the type of event. */ public GraphChangeEvent(Object eventSource, int type) { super(eventSource); this.type = type; } //~ Methods ---------------------------------------------------------------- /** * Returns the event type. * * @return the event type. */ public int getType() { return type; } } // End GraphChangeEvent.java jgrapht-0.8.3/src/org/jgrapht/event/EdgeTraversalEvent.java0000644000175000017500000000506411706124626024134 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * EdgeTraversalEvent.java * ----------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: EdgeTraversalEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 11-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; import java.util.*; /** * A traversal event for a graph edge. * * @author Barak Naveh * @since Aug 11, 2003 */ public class EdgeTraversalEvent extends EventObject { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 4050768173789820979L; //~ Instance fields -------------------------------------------------------- /** * The traversed edge. */ protected E edge; //~ Constructors ----------------------------------------------------------- /** * Creates a new EdgeTraversalEvent. * * @param eventSource the source of the event. * @param edge the traversed edge. */ public EdgeTraversalEvent(Object eventSource, E edge) { super(eventSource); this.edge = edge; } //~ Methods ---------------------------------------------------------------- /** * Returns the traversed edge. * * @return the traversed edge. */ public E getEdge() { return edge; } } // End EdgeTraversalEvent.java jgrapht-0.8.3/src/org/jgrapht/event/GraphEdgeChangeEvent.java0000644000175000017500000000712311706124626024336 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * GraphEdgeChangeEvent.java * ------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphEdgeChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 10-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; /** * An event which indicates that a graph edge has changed, or is about to * change. The event can be used either as an indication after the edge * has been added or removed, or before it is added. The type of the * event can be tested using the {@link * org.jgrapht.event.GraphChangeEvent#getType()} method. * * @author Barak Naveh * @since Aug 10, 2003 */ public class GraphEdgeChangeEvent extends GraphChangeEvent { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3618134563335844662L; /** * Before edge added event. This event is fired before an edge is added to a * graph. */ public static final int BEFORE_EDGE_ADDED = 21; /** * Before edge removed event. This event is fired before an edge is removed * from a graph. */ public static final int BEFORE_EDGE_REMOVED = 22; /** * Edge added event. This event is fired after an edge is added to a graph. */ public static final int EDGE_ADDED = 23; /** * Edge removed event. This event is fired after an edge is removed from a * graph. */ public static final int EDGE_REMOVED = 24; //~ Instance fields -------------------------------------------------------- /** * The edge that this event is related to. */ protected E edge; //~ Constructors ----------------------------------------------------------- /** * Constructor for GraphEdgeChangeEvent. * * @param eventSource the source of this event. * @param type the event type of this event. * @param e the edge that this event is related to. */ public GraphEdgeChangeEvent(Object eventSource, int type, E e) { super(eventSource, type); edge = e; } //~ Methods ---------------------------------------------------------------- /** * Returns the edge that this event is related to. * * @return the edge that this event is related to. */ public E getEdge() { return edge; } } // End GraphEdgeChangeEvent.java jgrapht-0.8.3/src/org/jgrapht/event/TraversalListener.java0000644000175000017500000000645511706124626024060 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * TraversalListener.java * ---------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: TraversalListener.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Aug-2003 : Adaptation to new event model (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; /** * A listener on graph iterator or on a graph traverser. * * @author Barak Naveh * @since Jul 19, 2003 */ public interface TraversalListener { //~ Methods ---------------------------------------------------------------- /** * Called to inform listeners that the traversal of the current connected * component has finished. * * @param e the traversal event. */ public void connectedComponentFinished( ConnectedComponentTraversalEvent e); /** * Called to inform listeners that a traversal of a new connected component * has started. * * @param e the traversal event. */ public void connectedComponentStarted(ConnectedComponentTraversalEvent e); /** * Called to inform the listener that the specified edge have been visited * during the graph traversal. Depending on the traversal algorithm, edge * might be visited more than once. * * @param e the edge traversal event. */ public void edgeTraversed(EdgeTraversalEvent e); /** * Called to inform the listener that the specified vertex have been visited * during the graph traversal. Depending on the traversal algorithm, vertex * might be visited more than once. * * @param e the vertex traversal event. */ public void vertexTraversed(VertexTraversalEvent e); /** * Called to inform the listener that the specified vertex have been * finished during the graph traversal. Exact meaning of "finish" is * algorithm-dependent; e.g. for DFS, it means that all vertices reachable * via the vertex have been visited as well. * * @param e the vertex traversal event. */ public void vertexFinished(VertexTraversalEvent e); } // End TraversalListener.java jgrapht-0.8.3/src/org/jgrapht/event/VertexTraversalEvent.java0000644000175000017500000000513111706124626024540 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * VertexTraversalEvent.java * ------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: VertexTraversalEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 11-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; import java.util.*; /** * A traversal event for a graph vertex. * * @author Barak Naveh * @since Aug 11, 2003 */ public class VertexTraversalEvent extends EventObject { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3688790267213918768L; //~ Instance fields -------------------------------------------------------- /** * The traversed vertex. */ protected V vertex; //~ Constructors ----------------------------------------------------------- /** * Creates a new VertexTraversalEvent. * * @param eventSource the source of the event. * @param vertex the traversed vertex. */ public VertexTraversalEvent(Object eventSource, V vertex) { super(eventSource); this.vertex = vertex; } //~ Methods ---------------------------------------------------------------- /** * Returns the traversed vertex. * * @return the traversed vertex. */ public V getVertex() { return vertex; } } // End VertexTraversalEvent.java jgrapht-0.8.3/src/org/jgrapht/event/VertexSetListener.java0000644000175000017500000000460411706124626024040 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * VertexSetListener.java * ---------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: VertexSetListener.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht.event; import java.util.*; /** * A listener that is notified when the graph's vertex set changes. It should be * used when only notifications on vertex-set changes are of interest. If * all graph notifications are of interest better use * GraphListener. * * @author Barak Naveh * @see GraphListener * @since Jul 18, 2003 */ public interface VertexSetListener extends EventListener { //~ Methods ---------------------------------------------------------------- /** * Notifies that a vertex has been added to the graph. * * @param e the vertex event. */ public void vertexAdded(GraphVertexChangeEvent e); /** * Notifies that a vertex has been removed from the graph. * * @param e the vertex event. */ public void vertexRemoved(GraphVertexChangeEvent e); } // End VertexSetListener.java jgrapht-0.8.3/src/org/jgrapht/Graph.java0000644000175000017500000004314411706124626020323 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------- * Graph.java * ---------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): John V. Sichi * Christian Hammer * * $Id: Graph.java 721 2010-11-20 06:11:44Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 06-Nov-2003 : Change edge sharing semantics (JVS); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht; import java.util.*; /** * The root interface in the graph hierarchy. A mathematical graph-theory graph * object G(V,E) contains a set V of vertices and a set * E of edges. Each edge e=(v1,v2) in E connects vertex v1 to vertex v2. * for more information about graphs and their related definitions see * http://mathworld.wolfram.com/Graph.html. * *

    This library generally follows the terminology found at: * http://mathworld.wolfram.com/topics/GraphTheory.html. Implementation of * this interface can provide simple-graphs, multigraphs, pseudographs etc. The * package org.jgrapht.graph provides a gallery of abstract and * concrete graph implementations.

    * *

    This library works best when vertices represent arbitrary objects and * edges represent the relationships between them. Vertex and edge instances may * be shared by more than one graph.

    * *

    Through generics, a graph can be typed to specific classes for vertices * V and edges E<T>. Such a graph can contain * vertices of type V and all sub-types and Edges of type * E and all sub-types.

    * *

    For guidelines on vertex and edge classes, see this wiki * page. * * @author Barak Naveh * @since Jul 14, 2003 */ public interface Graph { //~ Methods ---------------------------------------------------------------- /** * Returns a set of all edges connecting source vertex to target vertex if * such vertices exist in this graph. If any of the vertices does not exist * or is null, returns null. If both vertices * exist but no edges found, returns an empty set. * *

    In undirected graphs, some of the returned edges may have their source * and target vertices in the opposite order. In simple graphs the returned * set is either singleton set or empty set.

    * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return a set of all edges connecting source vertex to target vertex. */ public Set getAllEdges(V sourceVertex, V targetVertex); /** * Returns an edge connecting source vertex to target vertex if such * vertices and such edge exist in this graph. Otherwise returns * null. If any of the specified vertices is null * returns null * *

    In undirected graphs, the returned edge may have its source and target * vertices in the opposite order.

    * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return an edge connecting source vertex to target vertex. */ public E getEdge(V sourceVertex, V targetVertex); /** * Returns the edge factory using which this graph creates new edges. The * edge factory is defined when the graph is constructed and must not be * modified. * * @return the edge factory using which this graph creates new edges. */ public EdgeFactory getEdgeFactory(); /** * Creates a new edge in this graph, going from the source vertex to the * target vertex, and returns the created edge. Some graphs do not allow * edge-multiplicity. In such cases, if the graph already contains an edge * from the specified source to the specified target, than this method does * not change the graph and returns null. * *

    The source and target vertices must already be contained in this * graph. If they are not found in graph IllegalArgumentException is * thrown.

    * *

    This method creates the new edge e using this graph's * EdgeFactory. For the new edge to be added e * must not be equal to any other edge the graph (even if the graph * allows edge-multiplicity). More formally, the graph must not contain any * edge e2 such that e2.equals(e). If such * e2 is found then the newly created edge e is * abandoned, the method leaves this graph unchanged returns * null.

    * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return The newly created edge if added to the graph, otherwise * null. * * @throws IllegalArgumentException if source or target vertices are not * found in the graph. * @throws NullPointerException if any of the specified vertices is * null. * * @see #getEdgeFactory() */ public E addEdge(V sourceVertex, V targetVertex); /** * Adds the specified edge to this graph, going from the source vertex to * the target vertex. More formally, adds the specified edge, * e, to this graph if this graph contains no edge e2 * such that e2.equals(e). If this graph already contains such * an edge, the call leaves this graph unchanged and returns false. * Some graphs do not allow edge-multiplicity. In such cases, if the graph * already contains an edge from the specified source to the specified * target, than this method does not change the graph and returns * false. If the edge was added to the graph, returns * true. * *

    The source and target vertices must already be contained in this * graph. If they are not found in graph IllegalArgumentException is * thrown.

    * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * @param e edge to be added to this graph. * * @return true if this graph did not already contain the specified * edge. * * @throws IllegalArgumentException if source or target vertices are not * found in the graph. * @throws ClassCastException if the specified edge is not assignment * compatible with the class of edges produced by the edge factory of this * graph. * @throws NullPointerException if any of the specified vertices is * null. * * @see #addEdge(Object, Object) * @see #getEdgeFactory() */ public boolean addEdge(V sourceVertex, V targetVertex, E e); /** * Adds the specified vertex to this graph if not already present. More * formally, adds the specified vertex, v, to this graph if * this graph contains no vertex u such that * u.equals(v). If this graph already contains such vertex, the call * leaves this graph unchanged and returns false. In combination * with the restriction on constructors, this ensures that graphs never * contain duplicate vertices. * * @param v vertex to be added to this graph. * * @return true if this graph did not already contain the specified * vertex. * * @throws NullPointerException if the specified vertex is * null. */ public boolean addVertex(V v); /** * Returns true if and only if this graph contains an edge going * from the source vertex to the target vertex. In undirected graphs the * same result is obtained when source and target are inverted. If any of * the specified vertices does not exist in the graph, or if is * null, returns false. * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return true if this graph contains the specified edge. */ public boolean containsEdge(V sourceVertex, V targetVertex); /** * Returns true if this graph contains the specified edge. More * formally, returns true if and only if this graph contains an * edge e2 such that e.equals(e2). If the * specified edge is null returns false. * * @param e edge whose presence in this graph is to be tested. * * @return true if this graph contains the specified edge. */ public boolean containsEdge(E e); /** * Returns true if this graph contains the specified vertex. More * formally, returns true if and only if this graph contains a * vertex u such that u.equals(v). If the * specified vertex is null returns false. * * @param v vertex whose presence in this graph is to be tested. * * @return true if this graph contains the specified vertex. */ public boolean containsVertex(V v); /** * Returns a set of the edges contained in this graph. The set is backed by * the graph, so changes to the graph are reflected in the set. If the graph * is modified while an iteration over the set is in progress, the results * of the iteration are undefined. * *

    The graph implementation may maintain a particular set ordering (e.g. * via {@link java.util.LinkedHashSet}) for deterministic iteration, but * this is not required. It is the responsibility of callers who rely on * this behavior to only use graph implementations which support it.

    * * @return a set of the edges contained in this graph. */ public Set edgeSet(); /** * Returns a set of all edges touching the specified vertex. If no edges are * touching the specified vertex returns an empty set. * * @param vertex the vertex for which a set of touching edges is to be * returned. * * @return a set of all edges touching the specified vertex. * * @throws IllegalArgumentException if vertex is not found in the graph. * @throws NullPointerException if vertex is null. */ public Set edgesOf(V vertex); /** * Removes all the edges in this graph that are also contained in the * specified edge collection. After this call returns, this graph will * contain no edges in common with the specified edges. This method will * invoke the {@link #removeEdge(Object)} method. * * @param edges edges to be removed from this graph. * * @return true if this graph changed as a result of the call * * @throws NullPointerException if the specified edge collection is * null. * * @see #removeEdge(Object) * @see #containsEdge(Object) */ public boolean removeAllEdges(Collection edges); /** * Removes all the edges going from the specified source vertex to the * specified target vertex, and returns a set of all removed edges. Returns * null if any of the specified vertices does not exist in the * graph. If both vertices exist but no edge is found, returns an empty set. * This method will either invoke the {@link #removeEdge(Object)} method, or * the {@link #removeEdge(Object, Object)} method. * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return the removed edges, or null if no either vertex not * part of graph */ public Set removeAllEdges(V sourceVertex, V targetVertex); /** * Removes all the vertices in this graph that are also contained in the * specified vertex collection. After this call returns, this graph will * contain no vertices in common with the specified vertices. This method * will invoke the {@link #removeVertex(Object)} method. * * @param vertices vertices to be removed from this graph. * * @return true if this graph changed as a result of the call * * @throws NullPointerException if the specified vertex collection is * null. * * @see #removeVertex(Object) * @see #containsVertex(Object) */ public boolean removeAllVertices(Collection vertices); /** * Removes an edge going from source vertex to target vertex, if such * vertices and such edge exist in this graph. Returns the edge if removed * or null otherwise. * * @param sourceVertex source vertex of the edge. * @param targetVertex target vertex of the edge. * * @return The removed edge, or null if no edge removed. */ public E removeEdge(V sourceVertex, V targetVertex); /** * Removes the specified edge from the graph. Removes the specified edge * from this graph if it is present. More formally, removes an edge * e2 such that e2.equals(e), if the graph contains such * edge. Returns true if the graph contained the specified edge. * (The graph will not contain the specified edge once the call returns). * *

    If the specified edge is null returns * false.

    * * @param e edge to be removed from this graph, if present. * * @return true if and only if the graph contained the * specified edge. */ public boolean removeEdge(E e); /** * Removes the specified vertex from this graph including all its touching * edges if present. More formally, if the graph contains a vertex * u such that u.equals(v), the call removes all edges * that touch u and then removes u itself. If no * such u is found, the call leaves the graph unchanged. * Returns true if the graph contained the specified vertex. (The * graph will not contain the specified vertex once the call returns). * *

    If the specified vertex is null returns * false.

    * * @param v vertex to be removed from this graph, if present. * * @return true if the graph contained the specified vertex; * false otherwise. */ public boolean removeVertex(V v); /** * Returns a set of the vertices contained in this graph. The set is backed * by the graph, so changes to the graph are reflected in the set. If the * graph is modified while an iteration over the set is in progress, the * results of the iteration are undefined. * *

    The graph implementation may maintain a particular set ordering (e.g. * via {@link java.util.LinkedHashSet}) for deterministic iteration, but * this is not required. It is the responsibility of callers who rely on * this behavior to only use graph implementations which support it.

    * * @return a set view of the vertices contained in this graph. */ public Set vertexSet(); /** * Returns the source vertex of an edge. For an undirected graph, source and * target are distinguishable designations (but without any mathematical * meaning). * * @param e edge of interest * * @return source vertex */ public V getEdgeSource(E e); /** * Returns the target vertex of an edge. For an undirected graph, source and * target are distinguishable designations (but without any mathematical * meaning). * * @param e edge of interest * * @return target vertex */ public V getEdgeTarget(E e); /** * Returns the weight assigned to a given edge. Unweighted graphs return 1.0 * (as defined by {@link WeightedGraph#DEFAULT_EDGE_WEIGHT}), allowing * weighted-graph algorithms to apply to them where meaningful. * * @param e edge of interest * * @return edge weight * * @see WeightedGraph */ public double getEdgeWeight(E e); } // End Graph.java jgrapht-0.8.3/src/org/jgrapht/GraphMapping.java0000644000175000017500000000513311706124626021633 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * GraphMapping.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): John V. Sichi * * Changes * ------- */ package org.jgrapht; /** * GraphMapping represents a bidirectional mapping between two graphs (called * graph1 and graph2), which allows the caller to obtain the matching vertex or * edge in either direction, from graph1 to graph2, or from graph2 to graph1. It * does not have to always be a complete bidirectional mapping (it could return * null for some lookups). * * @author Assaf Lehr * @since Jul 30, 2005 */ public interface GraphMapping { //~ Methods ---------------------------------------------------------------- /** * Gets the mapped value where the key is vertex * * @param vertex vertex in one of the graphs * @param forward if true, uses mapping from graph1 to graph2; if false, use * mapping from graph2 to graph1 * * @return corresponding vertex in other graph, or null if none */ public V getVertexCorrespondence(V vertex, boolean forward); /** * Gets the mapped value where the key is edge * * @param edge edge in one of the graphs * @param forward if true, uses mapping from graph1 to graph2; if false, use * mapping from graph2 to graph1 * * @return corresponding edge in other graph, or null if none */ public E getEdgeCorrespondence(E edge, boolean forward); } // End GraphMapping.java jgrapht-0.8.3/src/org/jgrapht/UndirectedGraph.java0000644000175000017500000000440411706124626022326 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------- * UndirectedGraph.java * -------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: UndirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht; /** * A graph whose all edges are undirected. This is the root interface of all * undirected graphs. * *

    See * http://mathworld.wolfram.com/Graph.html for more on undirected and on * directed graphs.

    * * @author Barak Naveh * @since Jul 14, 2003 */ public interface UndirectedGraph extends Graph { //~ Methods ---------------------------------------------------------------- /** * Returns the degree of the specified vertex. A degree of a vertex in an * undirected graph is the number of edges touching that vertex. * * @param vertex vertex whose degree is to be calculated. * * @return the degree of the specified vertex. */ public int degreeOf(V vertex); } // End UndirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/experimental/0000755000175000017500000000000011752244360021105 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/permutation/0000755000175000017500000000000011752244357023462 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/permutation/CompoundPermutationIter.java0000644000175000017500000002112511706124626031161 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * CompoundPermutationIter.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: CompoundPermutationIter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.permutation; import java.util.*; import org.jgrapht.util.*; /** * For permutation like this: *
  • 1,2 are the same eq.group (numbers) *
  • a,b are og the same eq.group (letters) *
  • '$' is of its own eq. group (signs) Let the order of the group be * (arbitrary): signs,numbers,letters (note that for performance reasons, this * arbitrary order is the worst! see Performance section below) * *

    These are the possible compound perm: [$,1,2,a,b,c] * *

    [$,1,2,a,c,b] * *

    [$,1,2,b,a,c] * *

    [$,1,2,b,c,a] * *

    [$,1,2,c,a,b] * *

    [$,1,2,c,b,a] * *

    [$,2,1,a,b,c] * *

    [$,2,1,a,c,b] * *

    [$,2,1,b,a,c] * *

    [$,2,1,b,c,a] * *

    [$,2,1,c,a,b] * *

    [$,2,1,c,b,a] * *

    The overall number is the product of the factorials of each eq. group * size; in our example : (1!)x(2!)x(3!)=1x2x6=12. Using the constructor with * eq.group sizes and initial order [1,2,3], the result permutations are * retrieved as numbers in an array, where [0,1,2,3,4,5] means [$,1,2,a,b,c]: * *

    [0,1,2,3,5,4] * *

    [0,1,2,4,3,5] * *

    etc. etc., till: * *

    [0,2,1,5,4,3] means [$,2,1,c,b,a] * *

    *

    Performance: The implementation tries to advance each time the * group zero, if it does not succeed, it tries the next group (1,2 and so on), * so: try to put the largest group as the first groups, UNLIKE the example. * Performance-wise it is better to do [a,b,c,1,2,$] .The effect is improvement * by constant (for example, by 2) * * @author Assaf * @since May 30, 2005 */ public class CompoundPermutationIter implements ArrayPermutationsIter, Iterator { //~ Instance fields -------------------------------------------------------- IntegerPermutationIter [] permArray; /** * on the example 1+2+3=6 */ private int totalPermArraySize; /** * The overall number is the product of the factorial of each eq. group * size. */ private int max; private int iterCounter = 0; //~ Constructors ----------------------------------------------------------- /** * For the class example, use [1,2,2]. order matters! (performance-wise too) * * @param equalityGroupsSizesArray */ public CompoundPermutationIter(int [] equalityGroupsSizesArray) { init(equalityGroupsSizesArray); } //~ Methods ---------------------------------------------------------------- /** * Creates an IntegerPermutationIter class per equalityGroup with different * integers. * * @param equalityGroupsSizesArray */ private void init(int [] equalityGroupsSizesArray) { this.permArray = new IntegerPermutationIter[equalityGroupsSizesArray.length]; int counter = 0; this.max = 1; // each time , multiply by factorail(eqGroupSize) for ( int eqGroup = 0; eqGroup < equalityGroupsSizesArray.length; eqGroup++) { // create an array of eq.group size filled with values // of counter, counter+1, ... counter+size-1 int currGroupSize = equalityGroupsSizesArray[eqGroup]; int [] currArray = new int[currGroupSize]; for (int i = 0; i < currGroupSize; i++) { currArray[i] = counter; counter++; } this.permArray[eqGroup] = new IntegerPermutationIter(currArray); this.permArray[eqGroup].getNext(); // first iteration return the // source // each time , multiply by factorail(eqGroupSize) this.max *= MathUtil.factorial(currGroupSize); } this.totalPermArraySize = counter; // calc max } public Object next() { return getNext(); } /** * Iteration may be one of these two: 1. the last group advances by one * iter, all else stay. 2. the last group cannot advance , so it restarts * but telling the group after it to advance (done recursively till some * group can advance) */ public int [] getNext() { if (this.iterCounter == 0) { // just return it , without change this.iterCounter++; return getPermAsArray(); } int firstGroupCapableOfAdvancing = -1; int currGroupIndex = 0; // while (firstGroupCapableOfAdvancing == -1) { IntegerPermutationIter currGroup = this.permArray[currGroupIndex]; if (currGroup.hasNext()) { currGroup.getNext(); // restart all that we passed on for (int i = 0; i < currGroupIndex; i++) { restartPermutationGroup(i); } firstGroupCapableOfAdvancing = currGroupIndex; } currGroupIndex++; if (currGroupIndex >= this.permArray.length) { break; } } this.iterCounter++; if (firstGroupCapableOfAdvancing == -1) { // nothing found. we finished all iterations return null; } else { int [] tempArray = getPermAsArray(); return tempArray; } } /** * Creates and returns a new array which consists of the eq. group current * permutation arrays. For example, in the 10th iter ([$,2,1,b,c,a]) The * permutations current statuses is [0] [2,1] [4,5,3] so retrieve * [0,2,1,4,5,3] */ public int [] getPermAsArray() { int [] resultArray = new int[this.totalPermArraySize]; int counter = 0; for ( int groupIndex = 0; groupIndex < this.permArray.length; groupIndex++) { int [] currPermArray = this.permArray[groupIndex].getCurrent(); System.arraycopy( currPermArray, 0, resultArray, counter, currPermArray.length); counter += currPermArray.length; } return resultArray; } /** * Restarts by creating a new one instead. * * @param groupIndex */ private void restartPermutationGroup(int groupIndex) { int [] oldPermArray = this.permArray[groupIndex].getCurrent(); Arrays.sort(oldPermArray); this.permArray[groupIndex] = new IntegerPermutationIter(oldPermArray); this.permArray[groupIndex].getNext(); } public boolean hasNext() { boolean result; if (this.iterCounter < this.max) { result = true; } else { result = false; } return result; } public int getMax() { return max; } /* (non-Javadoc) * @see ArrayPermutationsIter#nextPermutation() */ public int [] nextPermutation() { return (int []) next(); } /* (non-Javadoc) * @see ArrayPermutationsIter#hasNextPermutaions() */ public boolean hasNextPermutaions() { return hasNext(); } /** * UNIMPLEMENTED. always throws new UnsupportedOperationException * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } // End CompoundPermutationIter.java jgrapht-0.8.3/src/org/jgrapht/experimental/permutation/CollectionPermutationIter.java0000644000175000017500000001317411706124626031475 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * CollectionPermutationIter.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: CollectionPermutationIter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.permutation; import java.util.*; /** * Given a container with elements (Collection,Enumeration,array) defines a * permutation iterator which returns, on each iteration, a differnt permutation * of the source container. You may choose a different container * type(Collection/Array/etc) for each next call. It will continue as if they * were the same iterator. * * @author Assaf * @since May 20, 2005 */ public class CollectionPermutationIter { //~ Instance fields -------------------------------------------------------- private ArrayPermutationsIter permOrder; private List sourceArray; /** * change everry calculation.can be retrieved publicly */ private int [] currPermutationArray; //~ Constructors ----------------------------------------------------------- /** * Note: the Set interface does not guarantee iteration order. This method * iterates on the set to get the initial order and after that the data will * be saved internally in another (ordered) container. So, remeber that the * Initial order can be different from the objectSet.toString() method. If * you want it to be the same, use a LinkedHashSet , or use the array * constructor. * * @param objectsSet */ public CollectionPermutationIter(Set objectsSet) { this( new ArrayList(objectsSet), new IntegerPermutationIter(objectsSet.size())); } /** * Uses a permArray like [1,1,1,2] where some of the permutations are not * relevant. Here there will be 4 permutations (only the '2' position is * important) * * @param objectsArray * @param permuter */ public CollectionPermutationIter(List objectsArray) { this( objectsArray, new IntegerPermutationIter(objectsArray.size())); } public CollectionPermutationIter( List objectsArray, ArrayPermutationsIter permuter) { this.permOrder = permuter; this.sourceArray = objectsArray; } //~ Methods ---------------------------------------------------------------- public boolean hasNext() { return this.permOrder.hasNextPermutaions(); } /** * On first call, returns the source as an array; on any other call * thereafter, a new permutation * * @return null if we overflowed! the array otherwise */ public List getNextArray() { List permutationResult; // will hold the array result if (this.permOrder.hasNextPermutaions()) { this.currPermutationArray = this.permOrder.nextPermutation(); permutationResult = applyPermutation(); } else { permutationResult = null; } return permutationResult; } private List applyPermutation() { ArrayList output = new ArrayList(sourceArray); // Example : this.sourceArray = ["A","B","C","D"] // perOrder: = [ 1 , 0 , 3 , 2 ] // result : = ["B","A","D","C"] for (int i = 0; i < output.size(); i++) { output.set( i, this.sourceArray.get(this.currPermutationArray[i])); } return output; } /** * Wrap result to a Set. * * @return null if we overflowed! the set otherwise */ public Set getNextSet() { List result = getNextArray(); if (result == null) { return null; } else // wrap in a SET { Set resultSet = new LinkedHashSet(result); return resultSet; } } public int [] getCurrentPermutationArray() { return this.currPermutationArray; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Permutation int[]="); sb.append(Arrays.toString(getCurrentPermutationArray())); List permutationResult = applyPermutation(); sb.append("\nPermutationSet Source Object[]="); sb.append(this.sourceArray.toString()); sb.append("\nPermutationSet Result Object[]="); sb.append(permutationResult.toString()); return sb.toString(); } } // End CollectionPermutationIter.java jgrapht-0.8.3/src/org/jgrapht/experimental/permutation/ArrayPermutationsIter.java0000644000175000017500000000347211706124626030643 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * ArrayPermutationsIter.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: ArrayPermutationsIter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.permutation; /** * An interface to iterate over array permutations. Similiar to Iterator, but * with specific return types and without the remove() method. * * @author Assaf * @since Jul 29, 2005 */ public interface ArrayPermutationsIter { //~ Methods ---------------------------------------------------------------- public int [] nextPermutation(); public boolean hasNextPermutaions(); } // End ArrayPermutationsIter.java jgrapht-0.8.3/src/org/jgrapht/experimental/permutation/package.html0000644000175000017500000000023311706124626025734 0ustar giovannigiovanni Classes to provide all the possible permutations of arrays or sets. jgrapht-0.8.3/src/org/jgrapht/experimental/permutation/PermutationFactory.java0000644000175000017500000000625411706124626030166 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * PermutationFactory.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: PermutationFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.permutation; /** * Factory to create Permutations of several types and use them as Enumerations. * Note that callers may use them directly if they need to use special concrete * methods. * *

    These types are: * *

    *

  • All elements are different. There are N! possible permutations. * *

    example: source=[1,2,3] * result=[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2][3,2,1] * *

    *

  • Some of the elements are the same. * *

    example: source=[1,1,2] result=[1,1,2][1,2,1][2,1,1] * *

    *

  • There are separate permutations groups, which are connected to one * sequence. Permutations are allowed only inside the group. Possible sequences: * product of factorial of each group. see example. * *

    example: assume source=the groups are sizes are : 1,2,2,5 elements * will be created: (1),(2,3),(4,5). * *

    result=[1,(2,3),(4,5)] [1,(2,3),(5,4)] [1,(3,2),(5,4)] [1,(3,2),(4,5)]. In * this example the number of possiblities is 1! x 2! x 2! = 4 * * @author Assaf Lehr * @since Jun 3, 2005 */ public class PermutationFactory { //~ Methods ---------------------------------------------------------------- public static ArrayPermutationsIter createRegular(int [] permSourceArray) { IntegerPermutationIter regularPerm = new IntegerPermutationIter(permSourceArray); return regularPerm; } /** * For efficiency, try putting the biggest groups at the beggining of the * array. * * @param groupSizesArray . example [3,2] will create an array (0,1,2)(3,4) */ public static ArrayPermutationsIter createByGroups( int [] groupSizesArray) { CompoundPermutationIter complexPerm = new CompoundPermutationIter(groupSizesArray); return complexPerm; } } // End PermutationFactory.java jgrapht-0.8.3/src/org/jgrapht/experimental/permutation/IntegerPermutationIter.java0000644000175000017500000002103111706124626030766 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * IntegerPermutationIter.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: IntegerPermutationIter.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.permutation; import java.util.*; /** * Iterates through permutations of N elements. *

  • use getNext() to get the next permutation order, for example(N=4): * perm0=[1,2,3,4] perm1=[1,2,4,3] perm2=[1,3,2,4] . *
  • use hasNext() or verify by counter[1,1,1,2,3]; * note that there are much less than 5! premutations here, because of the * repetitive 1s. * * @param array creates a copy of it (so sort / later changes will not * matter) */ public IntegerPermutationIter(int [] array) { int [] newArray = new int[array.length]; System.arraycopy(array, 0, newArray, 0, array.length); Arrays.sort(newArray); init(newArray); } //~ Methods ---------------------------------------------------------------- private void init(int [] array) { this.N = array.length; this.Value = array; this.currentValueBackup = this.Value; permutationCounter = 0; } /** * Swaps by array indexes * * @param i * @param j */ private void swap(int i, int j) { int temp = this.Value[i]; this.Value[i] = this.Value[j]; this.Value[j] = temp; } private int [] arrayClone(int [] sourceArray) { int [] destArray = new int[sourceArray.length]; System.arraycopy(sourceArray, 0, destArray, 0, sourceArray.length); return destArray; } private int [] getNextStartingWith2() { permutationCounter++; int i = N - 1; if (i <= 0) // may happen only on N<=1 { this.endWasReached = true; return null; } /** while (Value[i-1] >= Value[i]) { i = i-1; }*/ while (Value[i - 1] >= Value[i]) { i = i - 1; if (i == 0) { this.endWasReached = true; return null; } } int j = N; while (Value[j - 1] <= Value[i - 1]) { j = j - 1; } swap(i - 1, j - 1); // swap values at positions (i-1) and (j-1) i++; j = N; while (i < j) { swap(i - 1, j - 1); i++; j--; } return this.Value; } /** * Efficiency: O(N) implementation, try to take the next! */ public boolean hasNext() { if ((this.permutationCounter == 0) || (this.wasNextValueCalculatedAlready)) { return true; } else if (this.endWasReached) { return false; } boolean result = true; // calculate the next value into this.value save the current result. in // the end swap the arrays there is no way to know when to stop , but // the out-of-bound /* try * { * this.wasNextValueCalculatedAlready=true; * getNextStartingWith2(); * } * catch (ArrayIndexOutOfBoundsException outOfBoundException) * { * endWasReached=true; * result=false; * }*/ getNextStartingWith2(); this.wasNextValueCalculatedAlready = true; if (endWasReached) { return false; } ////////////////////////////// return result; } public Object next() { return getNext(); } /** * Facade. use it with getNext. efficency: O(N) * * @return a new Array with the permutatation order. for example: * perm0=[1,2,3,4] perm1=[1,2,4,3] perm2=[1,3,2,4] */ public int [] getNext() { if (!hasNext()) { throw new RuntimeException( "IntegerPermutationIter exceeds the total number of permutaions." + " Suggestion: do a check with hasNext() , or count till getTotalNumberOfPermutations" + " before using getNext()"); } // if it is the first one , return original int [] internalArray; if (this.permutationCounter == 0) { this.permutationCounter++; internalArray = this.Value; } else { // if hasNext() has precaclulated it , take this value. if (this.wasNextValueCalculatedAlready) { internalArray = this.Value; this.wasNextValueCalculatedAlready = false; } else { internalArray = getNextStartingWith2(); if (this.endWasReached) { return null; } } } this.currentValueBackup = arrayClone(internalArray); return arrayClone(internalArray); } public int [] getCurrent() { return arrayClone(this.currentValueBackup); } /** * Utility method to convert the array into a string examples: [] [0] * [0,1][1,0] * * @param array */ public String toString(int [] array) { if (array.length <= 0) { return "[]"; } StringBuffer stBuffer = new StringBuffer("["); for (int i = 0; i < (array.length - 1); i++) { stBuffer.append(array[i]).append(","); } stBuffer.append(array[array.length - 1]).append("]"); return stBuffer.toString(); } /** * UNIMPLEMENTED. always throws new UnsupportedOperationException * * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see ArrayPermutationsIter#nextPermutation() */ public int [] nextPermutation() { return (int []) next(); } /* (non-Javadoc) * @see ArrayPermutationsIter#hasNextPermutaions() */ public boolean hasNextPermutaions() { return hasNext(); } } // End IntegerPermutationIter.java jgrapht-0.8.3/src/org/jgrapht/experimental/PartiteRandomGraphGenerator.java0000644000175000017500000001242411706124626027356 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * PartiteRandomGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: PartiteRandomGraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Sep-2004 : Initial revision (MB); * */ // package org.jgrapht.generate; package org.jgrapht.experimental; import java.util.*; import org.jgrapht.*; import org.jgrapht.generate.*; /** * PartiteRandomGraphGenerator generates a partite uniform random * graph of any size. A partite uniform random graph contains edges chosen * independently uniformly at random from the set of possible edges between * partition classes. * * @author Michael Behrisch * @since Sep 13, 2004 */ public class PartiteRandomGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private final int [] numVertices; private final int numEdges; //~ Constructors ----------------------------------------------------------- /** * Construct a new PartiteRandomGraphGenerator for a bipartite graph. * * @param numVertices1 number of vertices in the first partition * @param numVertices2 number of vertices in the second partition * @param numEdges number of edges to be generated * * @throws IllegalArgumentException */ public PartiteRandomGraphGenerator( int numVertices1, int numVertices2, int numEdges) { if ((numVertices1 < 0) || (numVertices2 < 0)) { throw new IllegalArgumentException("must be non-negative"); } if ((numEdges < 0) || (numEdges > (numVertices1 * numVertices2))) { throw new IllegalArgumentException("illegal number of edges"); } final int [] numVertices = { numVertices1, numVertices2 }; this.numVertices = numVertices; this.numEdges = numEdges; } /** * Construct a new PartiteRandomGraphGenerator for a k-partite graph. * * @param numVertices number of vertices in the k partitions * @param numEdges number of edges to be generated between any two * partitions * * @throws IllegalArgumentException */ public PartiteRandomGraphGenerator(int [] numVertices, int numEdges) { if (numEdges < 0) { throw new IllegalArgumentException("illegal number of edges"); } for (int i = 0; i < numVertices.length; i++) { if (numVertices[i] < 0) { throw new IllegalArgumentException("must be non-negative"); } for (int j = 0; j < i; j++) { if (numEdges > (numVertices[i] * numVertices[j])) { throw new IllegalArgumentException( "illegal number of edges"); } } } this.numVertices = numVertices; this.numEdges = numEdges; } //~ Methods ---------------------------------------------------------------- /** * TODO hb 30-nov-05: document me * * @param target * @param vertexFactory * @param resultMap some array of vertices * * @see GraphGenerator#generateGraph */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { Object [][] vertices = new Object[numVertices.length][]; for (int i = 0; i < numVertices.length; i++) { vertices[i] = RandomGraphHelper.addVertices( target, vertexFactory, numVertices[i]); if (resultMap != null) { resultMap.put(Integer.toString(i), vertices[i]); } for (int j = 0; j < i; j++) { RandomGraphHelper.addEdges( target, Arrays.asList(vertices[i]), Arrays.asList(vertices[j]), numEdges); } } } } // End PartiteRandomGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/experimental/package.html0000644000175000017500000000061011706124626023364 0ustar giovannigiovanni

    A package that contains experimental work or work-in-progress that is not yet ready to be included in a release. It may contain classes that are: incomplete, not yet documented, have not yet reached a satisfying form, etc.

    The only requirement for classes included here is to compile.

    jgrapht-0.8.3/src/org/jgrapht/experimental/RandomGraphHelper.java0000644000175000017500000000671511706124626025324 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * RandomGraphHelper.java * ------------------- * (C) Copyright 2003-2008, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: RandomGraphHelper.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Sep-2004 : Initial revision (MB); * */ // package org.jgrapht.generate; package org.jgrapht.experimental; import java.util.*; import org.jgrapht.*; /** * UniformRandomGraphGenerator generates a uniform random graph * of any size. A uniform random graph contains edges chosen independently * uniformly at random from the set of all possible edges. * * @author Michael Behrisch * @since Sep 13, 2004 */ public final class RandomGraphHelper { //~ Static fields/initializers --------------------------------------------- private static final Random randSingleton = new Random(); //~ Constructors ----------------------------------------------------------- /** * . */ private RandomGraphHelper() { } //~ Methods ---------------------------------------------------------------- /** * @see GraphGenerator#generateGraph */ @SuppressWarnings("unchecked") public static void addEdges( Graph target, List sourceVertices, List destVertices, int numEdges) { int sourceSize = sourceVertices.size(); int destSize = destVertices.size(); for (int i = 0; i < numEdges; ++i) { while ( target.addEdge( sourceVertices.get(randSingleton.nextInt( sourceSize)), destVertices.get(randSingleton.nextInt(destSize))) == null) { ; } } } /** * . * * @param target * @param vertexFactory * @param numVertices * * @return */ @SuppressWarnings("unchecked") public static Object [] addVertices( Graph target, VertexFactory vertexFactory, int numVertices) { Object [] vertices = new Object[numVertices]; for (int i = 0; i < numVertices; ++i) { vertices[i] = vertexFactory.createVertex(); target.addVertex(vertices[i]); } return vertices; } } // End RandomGraphHelper.java jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/0000755000175000017500000000000011752244357023414 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/package.html0000644000175000017500000000021311706124626025664 0ustar giovannigiovanni Classes which enable working with Equivalence Sets. jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/EquivalenceSetCreator.java0000644000175000017500000002360311706124626030513 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceSetCreator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceSetCreator.java 722 2010-11-24 06:22:07Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; import java.util.*; /** * FIXME Document me. * * @param the type of the elements in the set * @param the type of the context the element is compared against, e.g. a * Graph TODO hb 060208: REVIEW: Using an array for aElementsArray causes * problems with generics elsewhere - changed to List? * * @author Assaf * @since Jul 21, 2005 */ public class EquivalenceSetCreator { //~ Static fields/initializers --------------------------------------------- private static final EqGroupSizeComparator groupSizeComparator = new EqGroupSizeComparator(); //~ Methods ---------------------------------------------------------------- /** * Checks for equivalance groups in the aElementsArray. Returns an ordered * array of them, where the smallest one is the first in the array. * * @param aElementsArray * @param aEqComparator * * @deprecated To improve type-safety when using generics, use {@link * #createEqualityGroupOrderedArray(Collection, EquivalenceComparator, * Object)} */ @Deprecated public static EquivalenceSet [] createEqualityGroupOrderedArray( EE [] aElementsArray, EquivalenceComparator aEqComparator, CC aContext) { return (createEqualityGroupOrderedArray( Arrays.asList(aElementsArray), aEqComparator, aContext)); // ArrayList> arrayList = new // ArrayList>(); // // HashMap>> map // = createEqualityGroupMap(aElementsArray, aEqComparator, // aContext); // each of the map values is a list with one or // more groups in it. // Object[] array = map.values().toArray(); // // for (int i = 0; i < array.length; i++) // { // List list = // (List)array[i]; // // for (List> list : // map.values() ) { for (EquivalenceSet // eSet : list ) { arrayList.add( eSet ); } } // // // now we got all the eq. groups in an array list. we need to sort // // them EquivalenceSet [] resultArray = new EquivalenceSet // [arrayList.size()]; arrayList.toArray(resultArray); // Arrays.sort(resultArray, groupSizeComparator); return // resultArray; } /** * Checks for equivalance groups in the aElementsArray. Returns an ordered * array of them, where the smallest one is the first in the array. * * @param elements * @param aEqComparator TODO hb 060208: Using an array for aElementsArray * causes problems with generics elsewhere - change to List? */ public static EquivalenceSet [] createEqualityGroupOrderedArray( Collection elements, EquivalenceComparator aEqComparator, CC aContext) { ArrayList> arrayList = new ArrayList>(); HashMap>> map = createEqualityGroupMap(elements, aEqComparator, aContext); // each of the map values is a list with one or more groups in it. // Object[] array = map.values().toArray(); // for (int i = 0; i < array.length; i++) // { // List list = (List)array[i]; for (List> list : map.values()) { for (EquivalenceSet eSet : list) { arrayList.add(eSet); } } // now we got all the eq. groups in an array list. we need to sort // them EquivalenceSet [] resultArray = new EquivalenceSet[arrayList.size()]; arrayList.toArray(resultArray); Arrays.sort(resultArray, groupSizeComparator); return resultArray; } /** * The data structure we use to store groups is a map, where the key is * eqGroupHashCode, and the value is list, containing one or more eqGroup * which match this hash. * * @param elements * @param aEqComparator * * @return a hashmap with key=group hashcode , value = list of eq.groups * which match that hash. TODO hb 060208: Using an array for aElementsArray * causes problems with generics elsewhere - change to List? */ private static HashMap>> createEqualityGroupMap( Collection elements, EquivalenceComparator aEqComparator, CC aComparatorContext) { HashMap>> equalityGroupMap = new HashMap>>( elements.size()); for (EE curentElement : elements) { int hashcode = aEqComparator.equivalenceHashcode( curentElement, aComparatorContext); List> list = equalityGroupMap.get(Integer.valueOf(hashcode)); // determine the type of value. It can be null(no value yet) , // or a list of EquivalenceSet if (list == null) { // create list with one element in it list = new LinkedList>(); list.add( new EquivalenceSet( curentElement, aEqComparator, aComparatorContext)); // This is the first one .add it to the map , in an eqGroup equalityGroupMap.put(Integer.valueOf(hashcode), list); } else { boolean eqWasFound = false; // we need to check the groups in the list. If none are good, // create a new one for (EquivalenceSet eqGroup : list) { if (eqGroup.equivalentTo( curentElement, aComparatorContext)) { // add it to the list and break eqGroup.add(curentElement); eqWasFound = true; break; } } // if no match was found add it to the list as a new group if (!eqWasFound) { list.add( new EquivalenceSet( curentElement, aEqComparator, aComparatorContext)); } } } return equalityGroupMap; } //~ Inner Classes ---------------------------------------------------------- /** * Functor used to order groups by size (number of elements in the group) * from the smallest to the biggest. If they have the same size, uses the * hashcode of the group to compare from the smallest to the biggest. Note * that it is inconsistent with equals(). See Object.equals() javadoc. * * @author Assaf * @since Jul 22, 2005 */ private static class EqGroupSizeComparator implements Comparator { /** * compare by size , then (if size equal) by hashcode * * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @SuppressWarnings("unchecked") public int compare(EquivalenceSet arg1, EquivalenceSet arg2) { int eqGroupSize1 = arg1.size(); int eqGroupSize2 = arg2.size(); if (eqGroupSize1 > eqGroupSize2) { return 1; } else if (eqGroupSize1 < eqGroupSize2) { return -1; } else { // size equal , compare hashcodes int eqGroupHash1 = arg1.hashCode(); int eqGroupHash2 = arg2.hashCode(); if (eqGroupHash1 > eqGroupHash2) { return 1; } else if (eqGroupHash1 < eqGroupHash2) { return -1; } else { return 0; } } } } } // End EquivalenceSetCreator.java jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/EquivalenceComparatorChainBase.java0000644000175000017500000001237411706124626032310 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceComparatorChainBase.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceComparatorChainBase.java 485 2006-06-26 09:12:14Z perfecthash * $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; import java.util.*; /** * This class implements comparator chaining. * *

    Usage examples: *

  • graph-theory, node equivalence: You can create a comparator for * the inDegree of a node, another for the total weight of outDegree edges, and * a third which checks the business content of the node. You know that the * first topological comparators has dozens of different groups, but the * buisness comparator has only two, and they are hard to check . The best * performance will be gained by: * *
    *

    EquivalenceComparatorChainBase eqChain = new * EquivalenceComparatorChainBase(fastNodesDegreeComparator); * *

    eqChain.addComparatorAfter(ABitSlowerEdgeWeightComparator); * *

    eqChain.addComparatorAfter(slowestBuisnessContentsComparator); *

    * * @param the type of the elements in the set * @param the type of the context the element is compared against, e.g. a * Graph * * @author Assaf * @since Jul 22, 2005 */ public class EquivalenceComparatorChainBase implements EquivalenceComparatorChain { //~ Instance fields -------------------------------------------------------- private List> chain; //~ Constructors ----------------------------------------------------------- /** */ public EquivalenceComparatorChainBase( EquivalenceComparator firstComaparator) { this.chain = new LinkedList>(); this.chain.add(firstComaparator); } //~ Methods ---------------------------------------------------------------- /* (non-Javadoc) * @see * * * * * * org.jgrapht.experimental.equivalence.EquivalenceComparatorChain#addComparatorAfter(org.jgrapht.experimental.equivalence.EquivalenceComparator) */ @SuppressWarnings("unchecked") public void appendComparator(EquivalenceComparator comparatorAfter) { if (comparatorAfter != null) { this.chain.add(comparatorAfter); } } /** * Implements logical AND between the comparators results. Iterates through * the comparators chain until one of them returns false. If none returns * false, this method returns true. * * @see EquivalenceComparator#equivalenceCompare(Object, Object, Object, * Object) */ public boolean equivalenceCompare( E arg1, E arg2, C context1, C context2) { for ( EquivalenceComparator currentComparator : this.chain) { if (!currentComparator.equivalenceCompare( arg1, arg2, context1, context2)) { return false; } } return true; } /** * Rehashes the concatenation of the results of all single hashcodes. * * @see EquivalenceComparator#equivalenceHashcode(Object, Object) */ public int equivalenceHashcode(E arg1, C context) { StringBuffer hashStringBuffer = new StringBuffer(); for ( ListIterator> iter = this.chain.listIterator(); iter.hasNext();) { EquivalenceComparator currentComparator = iter.next(); int currentHashCode = currentComparator.equivalenceHashcode(arg1, context); hashStringBuffer.append(currentHashCode); // add a delimeter only if needed for next if (iter.hasNext()) { hashStringBuffer.append('+'); } } return hashStringBuffer.toString().hashCode(); } } // End EquivalenceComparatorChainBase.java jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/EquivalenceComparator.java0000644000175000017500000000663711706124626030557 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceComparator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceComparator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; /** * This interface distinguishes between Equivalence sets. * *

    It is similar, in concept, to the Object.hashcode() and Object.equals() * methods, but instead of checking whether two objects are equal, it is used to * check whether they are part of the same Equivalence group, where the * definition of an "equivalence" is defined by the implementation of this * interface. * *

    A specific usage of it is shown below, but it may be used outside of the * graph-theory class library. * *

    In Isomorphism, edges/vertexes matching may relay on none/some/all of the * vertex/edge properties. For example, if a vertex representing a person * contains two properties: gender(male/female) and person name(string), we can * decide that to check isomorphism in vertex groups of gender only. Meaning if * this is the graph: * *

    (male,"Don")---->(female,"Dana")--->(male,"John") * *

    if there is no equivalence set at all , this graph can be described as: * (1)---->(2)---->(3) * *

    if the equivalence set is determined only by the gender property : * (male)---->(female)---->(male) * *

    and if it is determined by both properties: (the original figure) The * isomorphism inspection may return different result according to this choice. * If the other graph is: (male,"Don")--->(male,"Sunny")---->(male,"Jo") In no * eq.set they are Isomorphic, but for the two other cases they are not. Other * examples: Nodes with the same degree, Edges with the same weight, Graphs with * the same number of nodes and edges. * * @param the type of the elements in the set * @param the type of the context the element is compared against, e.g. a * Graph * * @author Assaf * @since Jul 15, 2005 */ public interface EquivalenceComparator { //~ Methods ---------------------------------------------------------------- public boolean equivalenceCompare( E arg1, E arg2, C context1, C context2); public int equivalenceHashcode(E arg1, C context); } // End EquivalenceComparator.java jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/EquivalenceComparatorChain.java0000644000175000017500000000532711706124626031515 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceComparatorChain.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceComparatorChain.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; /** * A container of comparators, which are tested in a chain until the first * result can be supplied. It implements the EquivalenceComparator, so chains * can include other chains. The first check will use the current comparator and * not the next one. So, make sure to use the one which has better performance * first. (This class follows the "Composite" design-pattern). * * @param the type of the elements in the set * @param the type of the context the element is compared against, e.g. a * Graph * * @author Assaf * @since Jul 22, 2005 */ public interface EquivalenceComparatorChain extends EquivalenceComparator { //~ Methods ---------------------------------------------------------------- /** * Adds a comparator which will also test equivalence. For * equivalenceCompare(), the return value is a logical AND of the two * comparators. The first check will use the first comparator before the * next one. Make sure to put the one which has better performance first. * For equivalenceHashcode(), the resulting hashes will be rehashed * together. This method may be used multiple times to create a long "chain" * of comparators. */ public void appendComparator(EquivalenceComparator comparatorAfter); } // End EquivalenceComparatorChain.java jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/EquivalenceSet.java0000644000175000017500000001443411706124626027175 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceSet.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceSet.java 723 2010-11-25 05:20:29Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; import java.util.*; /** * EquivalenceSet is a Set of elements which have been determined to be * equivalent using EquivalenceComparator. The class makes sure the set size * will be one or more. *

  • The group can only be created using the factory method * createGroupWithElement(). *
  • The equals and hashcode of a group uses the EquivalenceComparator on one * of the group members, thus it is actually checking whether the "other" is in * the same group. * * @param the type of the elements in the set * @param the type of the context the element is compared against, e.g. a * Graph * * @author Assaf * @since Jul 21, 2005 */ public class EquivalenceSet { //~ Instance fields -------------------------------------------------------- /** * The comparator used to define the group */ protected EquivalenceComparator eqComparator; protected C comparatorContext; /** * Contains the current elements of the group */ protected Set elementsSet; //~ Constructors ----------------------------------------------------------- /** * Constructs a new EquivalenceSet, filled with the aElement parameter and a * reference to the comparator which is used. */ public EquivalenceSet( E aElement, EquivalenceComparator aEqComparator, C aComparatorContext) { this.eqComparator = aEqComparator; this.comparatorContext = aComparatorContext; this.elementsSet = new HashSet(); this.elementsSet.add(aElement); } //~ Methods ---------------------------------------------------------------- /** * Returns an arbitrary object from the group. There is no guarantee as to * which will be returned, and whether the same will be returned on the next * call. */ public E getRepresentative() { return elementsSet.iterator().next(); } public C getContext() { return this.comparatorContext; } public int size() { return elementsSet.size(); } /** * Adds an element to the group. It does not check it for equivalance . You * must make sure it does, using equals(). */ public void add(E element) { this.elementsSet.add(element); } public boolean equivalentTo(E aOther, C aOtherContext) { boolean result = this.eqComparator.equivalenceCompare( this.getRepresentative(), aOther, this.comparatorContext, aOtherContext); return result; } /** * Uses the equivalenceCompare() of the comparator to compare a * representation of this group, taken using this.getRepresentative(), and a * representation of the other object, which may be the object itself, or, * if it is an equivalence group too, other.getRepresentative() */ // FIXME REVIEW hb 26-Jan-2006: I think throwing the exception is kind of // odd, // - it feels like violating the contract of Object.equals() // From what I understand, comparing any object to any other object should // be // possible at all times and simply return false if they are not equal. // Uncomparable objects beeing unequal. // Suggestion: remove the exception, at best, test on this specific class // and // write a warning or some such. @SuppressWarnings("unchecked") public boolean equals(Object other) { E otherRepresentative = null; C otherContext = null; if (other instanceof EquivalenceSet) { otherRepresentative = ((EquivalenceSet) other).getRepresentative(); otherContext = ((EquivalenceSet) other).getContext(); } else { throw new ClassCastException( "can check equal() only of EqualityGroup"); } boolean result = this.eqComparator.equivalenceCompare( this.getRepresentative(), otherRepresentative, this.comparatorContext, otherContext); return result; } /** * Uses a representative to calculate the group hashcode using * equivalenceHashcode(). * * @see java.lang.Object#hashCode() */ public int hashCode() { int result = this.eqComparator.equivalenceHashcode( this.getRepresentative(), this.comparatorContext); return result; } public String toString() { return "Eq.Group=" + this.elementsSet.toString(); } /** * Returns the elements of the group. The order of the elements in the * returned array is not guaranteed. In other words, two calls to the same * object may return different order. */ public Object [] toArray() { return this.elementsSet.toArray(); } } // End EquivalenceSet.java jgrapht-0.8.3/src/org/jgrapht/experimental/equivalence/UniformEquivalenceComparator.java0000644000175000017500000000465211706124626032112 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * UniformEquivalenceComparator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: UniformEquivalenceComparator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.equivalence; /** * This Equivalence comparator acts as if all elements are in one big global * equivalence class. Useful when a comparator is needed, but there is no * important difference between the elements. equivalenceCompare() always return * true; equivalenceHashcode() always returns 0. * * @author Assaf * @since Jul 21, 2005 */ public class UniformEquivalenceComparator implements EquivalenceComparator { //~ Methods ---------------------------------------------------------------- /** * Always returns true. * * @see EquivalenceComparator#equivalenceCompare(Object, Object, Object, * Object) */ public boolean equivalenceCompare( E arg1, E arg2, C context1, C context2) { return true; } /** * Always returns 0. * * @see EquivalenceComparator#equivalenceHashcode(Object, Object) */ public int equivalenceHashcode(E arg1, C context) { return 0; } } // End UniformEquivalenceComparator.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/0000755000175000017500000000000011752244357023464 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/PermutationIsomorphismInspector.java0000644000175000017500000001114111706124626032750 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * PermutationIsomorphismInspector.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: PermutationIsomorphismInspector.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.experimental.permutation.*; /** * Checks every possible permutation. * *

    It does not uses the graph topology to enhance the performance. It is * recommended to use only if there cannot be a useful division into equivalence * sets. * * @author Assaf * @since Jul 29, 2005 */ class PermutationIsomorphismInspector extends AbstractExhaustiveIsomorphismInspector { //~ Constructors ----------------------------------------------------------- /** * @param graph1 * @param graph2 * @param vertexChecker eq. group checker for vertexes. If null, * UniformEquivalenceComparator will be used as default (always return true) * @param edgeChecker eq. group checker for edges. If null, * UniformEquivalenceComparator will be used as default (always return true) */ public PermutationIsomorphismInspector( Graph graph1, Graph graph2, // XXX hb 060128: FOllowing parameter may need Graph EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { super(graph1, graph2, vertexChecker, edgeChecker); } /** * Constructor which uses the default comparators. * * @see AbstractExhaustiveIsomorphismInspector#AbstractExhaustiveIsomorphismInspector(Graph, * Graph) */ public PermutationIsomorphismInspector( Graph graph1, Graph graph2) { super(graph1, graph2); } //~ Methods ---------------------------------------------------------------- /** * Creates the permutation iterator, not dependant on equality group, or the * other vertexset. * * @param vertexSet1 FIXME Document me * @param vertexSet2 FIXME Document me * * @return the permutation iterator */ protected CollectionPermutationIter createPermutationIterator( Set vertexSet1, Set vertexSet2) { return new CollectionPermutationIter(vertexSet2); } /** * FIXME Document me FIXME Document me * * @param vertexSet1 FIXME Document me * @param vertexSet2 FIXME Document me * * @return FIXME Document me */ protected boolean areVertexSetsOfTheSameEqualityGroup( Set vertexSet1, Set vertexSet2) { if (vertexSet1.size() != vertexSet2.size()) { return false; } Iterator iter2 = vertexSet2.iterator(); // only check hasNext() of one , cause they are of the same size for (Iterator iter1 = vertexSet1.iterator(); iter1.hasNext();) { V vertex1 = iter1.next(); V vertex2 = iter2.next(); if (!this.vertexComparator.equivalenceCompare( vertex1, vertex2, this.graph1, this.graph2)) { return false; } } return true; } } // End PermutationIsomorphismInspector.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/IsomorphismRelation.java0000644000175000017500000001062711706124626030337 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * IsomorphismRelation.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: IsomorphismRelation.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** * Holds an isomorphism relation for two graphs. It contains a mapping between * the two graphs. * *

    Usage: * *

      *
    1. use getVertexCorrespondence() or * getEdgeCorrespondence() to get the mapped object in the other graph. *
    * *

    *

    It consists of two vertexes array , the i-th vertex in the 1st array is * the isomorphic eqv. of the i-th in 2nd array. Note that the getters are * unsafe (they return the array and not a copy of it). * * @author Assaf * @since May 27, 2005 */ public class IsomorphismRelation implements GraphMapping { //~ Instance fields -------------------------------------------------------- private List vertexList1; private List vertexList2; private GraphMapping graphMapping = null; private Graph graph1; private Graph graph2; //~ Constructors ----------------------------------------------------------- /** */ public IsomorphismRelation( List aGraph1vertexArray, List aGraph2vertexArray, Graph g1, Graph g2) { this.vertexList1 = aGraph1vertexArray; this.vertexList2 = aGraph2vertexArray; this.graph1 = g1; this.graph2 = g2; } //~ Methods ---------------------------------------------------------------- public String toString() { StringBuffer sb = new StringBuffer(); sb.append("vertexList1: ").append( this.vertexList1.toString()); sb.append("\tvertexList2: ").append( this.vertexList2.toString()); return sb.toString(); } public V getVertexCorrespondence(V vertex, boolean forward) { // lazy initializer for graphMapping if (graphMapping == null) { initGraphMapping(); } return graphMapping.getVertexCorrespondence(vertex, forward); } public E getEdgeCorrespondence(E edge, boolean forward) { // lazy initializer for graphMapping if (graphMapping == null) { initGraphMapping(); } return graphMapping.getEdgeCorrespondence(edge, forward); } /** * We currently have the vertexes array. From them we will construct two * maps: g1ToG2 and g2ToG1, using the array elements with the same index. */ private void initGraphMapping() { int mapSize = vertexList1.size(); Map g1ToG2 = new HashMap(mapSize); Map g2ToG1 = new HashMap(mapSize); for (int i = 0; i < mapSize; i++) { V source = this.vertexList1.get(i); V target = this.vertexList2.get(i); g1ToG2.put(source, target); g2ToG1.put(target, source); } this.graphMapping = new DefaultGraphMapping( g1ToG2, g2ToG1, this.graph1, this.graph2); } } // End IsomorphismRelation.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/package.html0000644000175000017500000000022611706124626025740 0ustar giovannigiovanni Algorithms which provide isomorphism check between two graphs. jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/EquivalenceIsomorphismInspector.java0000644000175000017500000002767411706124626032724 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * EquivalenceIsomorphismInspector.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: EquivalenceIsomorphismInspector.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.experimental.permutation.*; /** * The current implementation uses the vertexComparator to greatly increase the * test speed by dividing the vertexes into equivalent groups and permuting * inside them only. The EdgeComparator is used to test edges, but not to make a * finer division, thus it adds overhead. Use it only when needed. * * @author Assaf * @since Jul 29, 2005 */ class EquivalenceIsomorphismInspector extends AbstractExhaustiveIsomorphismInspector { //~ Constructors ----------------------------------------------------------- /** * @param graph1 * @param graph2 * @param vertexChecker eq. group checker for vertexes. If null, * UniformEquivalenceComparator will be used as default (always return true) * @param edgeChecker eq. group checker for edges. If null, * UniformEquivalenceComparator will be used as default (always return true) */ public EquivalenceIsomorphismInspector( Graph graph1, Graph graph2, // XXX hb 060128: FOllowing parameter may need Graph EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { super(graph1, graph2, vertexChecker, edgeChecker); } /** * Constructor which uses the default comparators. * * @see ExhaustiveIsomorphismInspector(Graph,Graph,EquivalenceComparator,EquivalenceComparator) */ public EquivalenceIsomorphismInspector( Graph graph1, Graph graph2) { super(graph1, graph2); } //~ Methods ---------------------------------------------------------------- /** * Creates the permutation iterator according to equivalance class. * *

    1. Get the eq.group (ordered by size) array of the source vertex set * (vertexSet1) * *

    2. Get the eq.group ordered array of vertexSet2. * *

    3. Reorder the second array to match the group order of the first * array sets. 4. Use CompoundPermutationIter (and not regular * IntegerPermutationIter) to permute only inside groups. * *

    *

    That's it. If the eq.group comaparator is strong enough to provide * small groups, this algortihm will produce a small possible permutations * numbers. example: G1: [A,B,F,X,Y] [A->B,B->X,X->Y] * *

    G2: [D,Z,C,U,F] [D->C,Z->C,U->Z] * *

    vertexEq: three groups , one all letters A-E , second all letters S-Z * , third the letter 'f'. 1. [(f)size=1, (X,Y)size=2 , (A,B)size=2] 2. * [(f)size=1 ,(C,D)size=2 , (Z,U)size=2] 3. the match is done by reordering * the second array to have the equiviavlant order :##[(f)size=1 , * (Z,U)size=2 , (C,D)size=2]## 4.for example G2 will not do all 5!=120 * permutations , but 2!x2!x1!=4 permutations only which are: (of the 3rd * array) [ F, Z , U , C , D ] [ F, Z , U , D , C ] [ F, U , Z, C , D ] [ F, * U , Z , D , C ] * * @return null, if the eq.group do not match (there cannot be any * permutation for eq.groups) or the sets do not match in size; otherwise, * the permutationiterator otherwise * * @see AbstractExhaustiveIsomorphismInspector#createPermutationIterator(Set, * Set) */ @SuppressWarnings("unchecked") protected CollectionPermutationIter createPermutationIterator( Set vertexSet1, Set vertexSet2) { if (vertexSet1.size() != vertexSet2.size()) { // throw new IllegalArgumentException("the two vertx-sets // parameters must be of" // +"the same size. The first size was:"+vertexSet1.size() // +" the other size was:" +vertexSet2.size() ); return null; // only instead of exception } // 1// EquivalenceSet [] eqGroupArray1 = EquivalenceSetCreator.createEqualityGroupOrderedArray( vertexSet1, this.vertexComparator, this.graph1); // 2// EquivalenceSet [] eqGroupArray2 = EquivalenceSetCreator.createEqualityGroupOrderedArray( vertexSet2, this.vertexComparator, this.graph2); // 3// boolean reorderSuccess = reorderTargetArrayToMatchSourceOrder(eqGroupArray1, eqGroupArray2); // 2 is the target if (!reorderSuccess) { // if reordering fail , no match can be done return null; } // reorder set1 (source), so when we work with the flat array of the // second array, // the permutations will be relevant. // note that it does not start in any way related to eqGroup sizes. V [] reorderingVertexSet1Temp = (V []) new Object[vertexSet1.size()]; fillElementsflatArray(eqGroupArray1, reorderingVertexSet1Temp); vertexSet1.clear(); vertexSet1.addAll(Arrays.asList(reorderingVertexSet1Temp)); // 4//use CompoundPermutationIter to permute only inside groups. // the CollectionPermutationIter needs a array/set of objects and a // permuter which will // work on that set/array order. lets make these two: // 1. create array of the vertexes , by flattening the eq.group array // contents V [] flatVertexArray = (V []) new Object[vertexSet2.size()]; fillElementsflatArray(eqGroupArray2, flatVertexArray); // 2. make the permuter according to the groups size int [] groupSizesArray = new int[eqGroupArray1.length]; // iterate over the EqualityGroup array for ( int eqGroupCounter = 0; eqGroupCounter < eqGroupArray2.length; eqGroupCounter++) { // now for (.2.) size count groupSizesArray[eqGroupCounter] = eqGroupArray2[eqGroupCounter].size(); } ArrayPermutationsIter arrayPermIter = PermutationFactory.createByGroups(groupSizesArray); CollectionPermutationIter vertexPermIter = new CollectionPermutationIter( Arrays.asList(flatVertexArray), arrayPermIter); return vertexPermIter; } /** * Reorders inplace targetArray * *

    rules: *

  • try to match only group of the same size and then hashcode *
  • it is enough to choose one from each group to see if a match exist. * *

    Algorithm: hold counters in the two arrays. [a,b,c,d,e] assume groups * are:a,(b,c,d),e [a,c,d,b,e] c1=0 , c2=0 check if eqvivalent . if not , * advance , as long as both size and hashcode are the same. if found a * match , swap the group positions in array2. if not , throws * IllegalArgumentExcpetion. Assumption: array size is the same. not * checked. * * @param sourceArray * @param targetArray * * @return true if the array was reordered successfully. false if not(It * will happen if there is no complete match between the groups) */ private boolean reorderTargetArrayToMatchSourceOrder( EquivalenceSet [] sourceArray, EquivalenceSet [] targetArray) { boolean result = true; for ( int sourceIndex = 0; sourceIndex < sourceArray.length; sourceIndex++) { int currTargetIndex = sourceIndex; // if they are already equivalent do nothing. EquivalenceSet sourceEqGroup = sourceArray[sourceIndex]; EquivalenceSet targetEqGroup = targetArray[currTargetIndex]; if (!sourceEqGroup.equals(targetEqGroup)) { // iterate through the next group in the targetArray until // a new size or hashcode is seen boolean foundMatch = false; int sourceSize = sourceEqGroup.size(); int sourceHashCode = sourceEqGroup.hashCode(); while ( (targetEqGroup.size() == sourceSize) && (targetEqGroup.hashCode() == sourceHashCode) && (currTargetIndex < (targetArray.length - 1))) { currTargetIndex++; targetEqGroup = targetArray[currTargetIndex]; if (targetEqGroup.equals(sourceEqGroup)) { foundMatch = true; // swap . targetEqGroup will serve as the temp // variable. targetArray[currTargetIndex] = targetArray[sourceIndex]; targetArray[sourceIndex] = targetEqGroup; } } if (!foundMatch) { // a match was not found // throw new IllegalArgumentException("could not reorder // the array , because the groups don`t match"); result = false; break; } } } return result; } /** * @param eqGroupArray * @param flatArray an empy array with the proper size */ protected void fillElementsflatArray( EquivalenceSet [] eqGroupArray, Object [] flatVertexArray) { int flatVertexArrayNextFree = 0; // the next free place in the array // iterate over the EqualityGroup array for ( int eqGroupCounter = 0; eqGroupCounter < eqGroupArray.length; eqGroupCounter++) { Object [] currGroupArray = eqGroupArray[eqGroupCounter].toArray(); // copy this small array to the free place in the big // flatVertexArray System.arraycopy( currGroupArray, // src 0, // srcPos flatVertexArray, // dest flatVertexArrayNextFree, // destPos currGroupArray.length // length ); flatVertexArrayNextFree += currGroupArray.length; } } /** * We know for sure, that the sets are alreay checked for equivalence , so * it will return true without any further checks. * * @see AbstractExhaustiveIsomorphismInspector#areVertexSetsOfTheSameEqualityGroup( * Set, Set) */ protected boolean areVertexSetsOfTheSameEqualityGroup( Set vertexSet1, Set vertexSet2) { return true; } } // End EquivalenceIsomorphismInspector.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/VertexDegreeEquivalenceComparator.java0000644000175000017500000001341011706124626033124 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * VertexDegreeEquivalenceComparator.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: VertexDegreeEquivalenceComparator.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; /** * Two vertexes are equivalent under this comparator if and only if: * *

      *
    1. they have the same IN degree * *

      AND *

    2. they have the same OUT degree *
    * * @author Assaf * @since Jul 21, 2005 */ public class VertexDegreeEquivalenceComparator implements EquivalenceComparator> { //~ Constructors ----------------------------------------------------------- /** */ public VertexDegreeEquivalenceComparator() { } //~ Methods ---------------------------------------------------------------- /** * Compares the in degrees and the out degrees of the two vertexes. * *

    One may reside in an Undirected Graph and the other in a Directed * graph, or both on the same graph type. * * @see EquivalenceComparator#equivalenceCompare(Object, Object, Object, * Object) */ public boolean equivalenceCompare( V vertex1, V vertex2, Graph context1, Graph context2) { // note that VertexDegreeComparator cannot be used. It supports only // directed graphs. InOutDegrees inOut1 = getInOutDegrees(context1, vertex1); InOutDegrees inOut2 = getInOutDegrees(context2, vertex2); boolean result = inOut1.equals(inOut2); return result; } /** * Hashes using the in & out degree of a vertex * * @see EquivalenceComparator#equivalenceHashcode(Object, Object) */ public int equivalenceHashcode(V vertex, Graph context) { InOutDegrees inOut = getInOutDegrees(context, vertex); // hash it using the string hash. use the format N '-' N StringBuffer sb = new StringBuffer(); sb.append(String.valueOf(inOut.inDegree)); sb.append("-"); // to diffrentiate inner and outer sb.append(String.valueOf(inOut.outDegree)); return sb.toString().hashCode(); } /** * Calculates the In and Out degrees of vertexes. Supported graph types: * UnDirectedGraph, DirectedGraph. In UnDirected graph, the in = out (as if * it was undirected and every edge is both an in and out edge) * * @param aContextGraph * @param vertex */ protected InOutDegrees getInOutDegrees(Graph aContextGraph, V vertex) { int inVertexDegree = 0; int outVertexDegree = 0; if (aContextGraph instanceof UndirectedGraph) { UndirectedGraph undirectedGraph = (UndirectedGraph) aContextGraph; inVertexDegree = undirectedGraph.degreeOf(vertex); outVertexDegree = inVertexDegree; // it is UNdirected } else if (aContextGraph instanceof DirectedGraph) { DirectedGraph directedGraph = (DirectedGraph) aContextGraph; inVertexDegree = directedGraph.inDegreeOf(vertex); outVertexDegree = directedGraph.outDegreeOf(vertex); } else { throw new RuntimeException( "contextGraph is of unsupported type . It must be one of these two :" + " UndirectedGraph or DirectedGraph"); } return new InOutDegrees(inVertexDegree, outVertexDegree); } //~ Inner Classes ---------------------------------------------------------- /** * Simple structure used to hold the two ints: vertex in degree and vertex * out degree. Useful as returned value for methods which calculate both at * the same time. * * @author Assaf * @since Jul 21, 2005 */ protected class InOutDegrees { public int inDegree; public int outDegree; public InOutDegrees(int aInDegree, int aOutDegree) { this.inDegree = aInDegree; this.outDegree = aOutDegree; } /** * Checks both inDegree and outDegree. Does not check class type to save * time. If should be used with caution. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { InOutDegrees other = (InOutDegrees) obj; return ((this.inDegree == other.inDegree) && (this.outDegree == other.outDegree)); } } } // End VertexDegreeEquivalenceComparator.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/AbstractExhaustiveIsomorphismInspector.java0000644000175000017500000003563511706124626034270 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * AbstractExhaustiveIsomorphismInspector.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: AbstractExhaustiveIsomorphismInspector.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.experimental.permutation.*; import org.jgrapht.util.*; /** * Abstract base for isomorphism inspectors which exhaustively test the possible * mappings between graphs. The current algorithms do not support graphs with * multiple edges (Multigraph / Pseudograph). For the maintainer: The reason is * the use of GraphOrdering which currently does not support all graph types. * * @author Assaf Lehr * @since May 20, 2005 ver5.3 */ abstract class AbstractExhaustiveIsomorphismInspector implements GraphIsomorphismInspector { //~ Static fields/initializers --------------------------------------------- public static EquivalenceComparator edgeDefaultIsomorphismComparator = new UniformEquivalenceComparator(); public static EquivalenceComparator vertexDefaultIsomorphismComparator = new UniformEquivalenceComparator(); //~ Instance fields -------------------------------------------------------- protected EquivalenceComparator> edgeComparator; protected EquivalenceComparator> vertexComparator; protected Graph graph1; protected Graph graph2; private PrefetchIterator nextSupplier; // kept as member, to ease computations private GraphOrdering lableGraph1; private LinkedHashSet graph1VertexSet; private LinkedHashSet graph2EdgeSet; private CollectionPermutationIter vertexPermuteIter; private Set currVertexPermutation; // filled every iteration, used in the //~ Constructors ----------------------------------------------------------- // result relation. /** * @param graph1 * @param graph2 * @param vertexChecker eq. group checker for vertexes. If null, * UniformEquivalenceComparator will be used as default (always return true) * @param edgeChecker eq. group checker for edges. If null, * UniformEquivalenceComparator will be used as default (always return true) */ public AbstractExhaustiveIsomorphismInspector( Graph graph1, Graph graph2, // XXX hb 060128: FOllowing parameter may need Graph EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { this.graph1 = graph1; this.graph2 = graph2; if (vertexChecker != null) { this.vertexComparator = vertexChecker; } else { this.vertexComparator = vertexDefaultIsomorphismComparator; } // Unlike vertexes, edges have better performance, when not tested for // Equivalence, so if the user did not supply one, use null // instead of edgeDefaultIsomorphismComparator. if (edgeChecker != null) { this.edgeComparator = edgeChecker; } init(); } /** * Constructor which uses the default comparators. * * @param graph1 * @param graph2 * * @see #AbstractExhaustiveIsomorphismInspector(Graph,Graph,EquivalenceComparator,EquivalenceComparator) */ public AbstractExhaustiveIsomorphismInspector( Graph graph1, Graph graph2) { this( graph1, graph2, edgeDefaultIsomorphismComparator, vertexDefaultIsomorphismComparator); } //~ Methods ---------------------------------------------------------------- /** * Inits needed data-structures , among them: *

  • LabelsGraph which is a created in the image of graph1 *
  • vertexPermuteIter which is created after the vertexes were divided to * equivalence groups. This saves order-of-magnitude in performance, because * the number of possible permutations dramatically decreases. * *

    for example: if the eq.group are even/odd - only two groups. A graph * with consist of 10 nodes of which 5 are even , 5 are odd , will need to * test 5!*5! (14,400) instead of 10! (3,628,800). * *

    besides the EquivalenceComparator`s supplied by the user, we also use * predefined topological comparators. */ private void init() { this.nextSupplier = new PrefetchIterator( // XXX hb 280106: I don't understand this warning, yet :-) new NextFunctor()); this.graph1VertexSet = new LinkedHashSet(this.graph1.vertexSet()); // vertexPermuteIter will be null, if there is no match this.vertexPermuteIter = createPermutationIterator( this.graph1VertexSet, this.graph2.vertexSet()); this.lableGraph1 = new GraphOrdering( this.graph1, this.graph1VertexSet, this.graph1.edgeSet()); this.graph2EdgeSet = new LinkedHashSet(this.graph2.edgeSet()); } /** * Creates the permutation iterator for vertexSet2 . The subclasses may make * either cause it to depend on equality groups or use vertexSet1 for it. * * @param vertexSet1 [i] may be reordered * @param vertexSet2 [i] may not. * * @return permutation iterator */ protected abstract CollectionPermutationIter createPermutationIterator( Set vertexSet1, Set vertexSet2); /** *

    1. Creates a LabelsGraph of graph1 which will serve as a source to all * the comparisons which will follow. * *

    2. extract the edge array of graph2; it will be permanent too. * *

    3. for each permutation of the vertexes of graph2, test : * *

    3.1. vertices * *

    3.2. edges (in labelsgraph) * *

    Implementation Notes and considerations: Let's consider a trivial * example: graph of strings "A","B","C" with two edges A->B,B->C. Let's * assume for this example that the vertex comparator always returns true, * meaning String value does not matter, only the graph structure does. So * "D" "E" "A" with D->E->A will be isomorphic , but "A","B,"C"with * A->B,A->C will not. * *

    First let's extract the important info for isomorphism from the graph. * We don't care what the vertexes are, we care that there are 3 of them * with edges from first to second and from second to third. So the source * LabelsGraph will be: vertexes:[1,2,3] edges:[[1->2],[2->3]] Now we will * do several permutations of D,E,A. A few examples: D->E , E->A * [1,2,3]=[A,D,E] so edges are: 2->3 , 3->1 . does it match the source? NO. * [1,2,3]=[D,A,E] so edges are: 1->3 , 3->2 . no match either. * [1,2,3]=[D,E,A] so edges are: 1->2 , 2->3 . MATCH FOUND ! Trivial * algorithm: We will iterate on all permutations * [abc][acb][bac][bca][cab][cba]. (n! of them,3!=6) For each, first compare * vertexes using the VertexComparator(always true). Then see that the edges * are in the exact order 1st->2nd , 2nd->3rd. If we found a match stop and * return true, otherwise return false; we will compare vetices and edges by * their order (1st,2nd,3rd,etc) only. Two graphs are the same, by this * order, if: 1. for each i, sourceVertexArray[i] is equivalent to * targetVertexArray[i] 2. for each vertex, the edges which start in it (it * is the source) goes to the same ordered vertex. For multiple ones, count * them too. * * @return IsomorphismRelation for a permutation found, or null if no * permutation was isomorphic */ private IsomorphismRelation findNextIsomorphicGraph() { boolean result = false; IsomorphismRelation resultRelation = null; if (this.vertexPermuteIter != null) { // System.out.println("Souce LabelsGraph="+this.lableGraph1); while (this.vertexPermuteIter.hasNext()) { currVertexPermutation = this.vertexPermuteIter.getNextSet(); // compare vertexes if (!areVertexSetsOfTheSameEqualityGroup( this.graph1VertexSet, currVertexPermutation)) { continue; // this one is not iso, so try the next one } // compare edges GraphOrdering currPermuteGraph = new GraphOrdering( this.graph2, currVertexPermutation, this.graph2EdgeSet); // System.out.println("target LablesGraph="+currPermuteGraph); if (this.lableGraph1.equalsByEdgeOrder(currPermuteGraph)) { // create result object. resultRelation = new IsomorphismRelation( new ArrayList(graph1VertexSet), new ArrayList(currVertexPermutation), graph1, graph2); // if the edge comparator exists, check equivalence by it boolean edgeEq = areAllEdgesEquivalent( resultRelation, this.edgeComparator); if (edgeEq) // only if equivalent { result = true; break; } } } } if (result == true) { return resultRelation; } else { return null; } } /** * Will be called on every two sets of vertexes returned by the permutation * iterator. From findNextIsomorphicGraph(). Should make sure that the two * sets are euqivalent. Subclasses may decide to implements it as an always * true methods only if they make sure that the permutationIterator will * always be already equivalent. * * @param vertexSet1 FIXME Document me * @param vertexSet2 FIXME Document me */ protected abstract boolean areVertexSetsOfTheSameEqualityGroup( Set vertexSet1, Set vertexSet2); /** * For each edge in g1, get the Correspondence edge and test the pair. * * @param resultRelation * @param edgeComparator if null, always return true. */ protected boolean areAllEdgesEquivalent( IsomorphismRelation resultRelation, EquivalenceComparator> edgeComparator) { boolean checkResult = true; if (edgeComparator == null) { // nothing to check return true; } try { Set edgeSet = this.graph1.edgeSet(); for (E currEdge : edgeSet) { E correspondingEdge = resultRelation.getEdgeCorrespondence(currEdge, true); // if one edge test fail , fail the whole method if (!edgeComparator.equivalenceCompare( currEdge, correspondingEdge, this.graph1, this.graph2)) { checkResult = false; break; } } } catch (IllegalArgumentException illegal) { checkResult = false; } return checkResult; } /** * return nextElement() casted as IsomorphismRelation */ public IsomorphismRelation nextIsoRelation() { return next(); } /** * Efficiency: The value is known after the first check for isomorphism * activated on this class and returned there after in O(1). If called on a * new ("virgin") class, it activates 1 iso-check. * * @return true iff the two graphs are isomorphic */ public boolean isIsomorphic() { return !(this.nextSupplier.isEnumerationStartedEmpty()); } /* (non-Javadoc) * @see java.util.Enumeration#hasMoreElements() */ public boolean hasNext() { boolean result = this.nextSupplier.hasMoreElements(); return result; } /** * @see java.util.Iterator#next() */ public IsomorphismRelation next() { return this.nextSupplier.nextElement(); } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException( "remove() method is not supported in AdaptiveIsomorphismInspectorFactory." + " There is no meaning to removing an isomorphism result."); } //~ Inner Classes ---------------------------------------------------------- private class NextFunctor implements PrefetchIterator.NextElementFunctor { public IsomorphismRelation nextElement() throws NoSuchElementException { IsomorphismRelation resultRelation = findNextIsomorphicGraph(); if (resultRelation != null) { return resultRelation; } else { throw new NoSuchElementException( "IsomorphismInspector does not have any more elements"); } } } } // End AbstractExhaustiveIsomorphismInspector.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/AdaptiveIsomorphismInspectorFactory.java0000644000175000017500000002123211706124626033530 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * AdaptiveIsomorphismInspectorFactory.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: AdaptiveIsomorphismInspectorFactory.java 485 2006-06-26 09:12:14Z * perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import org.jgrapht.*; import org.jgrapht.experimental.equivalence.*; import org.jgrapht.graph.*; /** * This class serves as a factory for GraphIsomorphismInspector concrete * implementations. It can be used in two ways: *

  • You can can let this class to determine what is the most efficient * algorithm for your graph. *
  • You can specify the type of your graph (planar / tree / other) and save * this class the graph-checking time. * *

    Note that the concrete implementations are package-private and should not * be created directly. If you are the maintainer of the package, you can add * new implementation classes, and add them to the "check-list". The current * algorithms do not support graphs with multiple edges (Multigraph / * Pseudograph) * * @author Assaf * @see GraphIsomorphismInspector * @since Jul 17, 2005 */ public class AdaptiveIsomorphismInspectorFactory { //~ Static fields/initializers --------------------------------------------- public static final int GRAPH_TYPE_ARBITRARY = 0; public static final int GRAPH_TYPE_PLANAR = 1; public static final int GRAPH_TYPE_TREE = 2; public static final int GRAPH_TYPE_MULTIGRAPH = 3; //~ Methods ---------------------------------------------------------------- /** * Creates a new inspector, letting this class determine what is the most * efficient algorithm. * * @param graph1 * @param graph2 * @param vertexChecker may be null * @param edgeChecker may be null */ public static GraphIsomorphismInspector createIsomorphismInspector( Graph graph1, Graph graph2, EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { int graphType = checkGraphsType(graph1, graph2); return createAppropriateConcreteInspector( graphType, graph1, graph2, vertexChecker, edgeChecker); } /** * Creates a new inspector, letting this class determine what is the most * efficient algorithm and using default equivalence comparators. * *

    same as calling createIsomorphismInspector(graph1,graph2,null,null); * * @param graph1 * @param graph2 */ public static GraphIsomorphismInspector createIsomorphismInspector( Graph graph1, Graph graph2) { return createIsomorphismInspector(graph1, graph2, null, null); } /** * Creates a new inspector for a particular graph type (planar / tree / * other). * * @param type - AdaptiveIsomorphismInspectorFactory.GRAPH_TYPE_XXX * @param graph1 * @param graph2 * @param vertexChecker - can be null * @param edgeChecker - can be null */ public static GraphIsomorphismInspector createIsomorphismInspectorByType( int type, Graph graph1, Graph graph2, EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { return createAppropriateConcreteInspector( type, graph1, graph2, vertexChecker, edgeChecker); } /** * Creates a new inspector for a particular graph type (planar / tree / * other) using default equivalence comparators. * *

    same as calling * createAppropriateConcreteInspector(graph1,graph2,null,null); * * @param type - AdaptiveIsomorphismInspectorFactory.GRAPH_TYPE_XXX * @param graph1 * @param graph2 */ public static GraphIsomorphismInspector createIsomorphismInspectorByType( int type, Graph graph1, Graph graph2) { return createAppropriateConcreteInspector( type, graph1, graph2, null, null); } /** * Checks the graph type, and accordingly decides which type of concrete * inspector class to create. This implementation creates an exhaustive * inspector without further tests, because no other implementations are * available yet. * * @param graph1 * @param graph2 * @param vertexChecker * @param edgeChecker */ protected static GraphIsomorphismInspector createAppropriateConcreteInspector( int graphType, Graph graph1, Graph graph2, EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { assertUnsupportedGraphTypes(graph1); assertUnsupportedGraphTypes(graph2); GraphIsomorphismInspector currentInspector = null; switch (graphType) { case GRAPH_TYPE_PLANAR: case GRAPH_TYPE_TREE: case GRAPH_TYPE_ARBITRARY: currentInspector = createTopologicalExhaustiveInspector( graph1, graph2, vertexChecker, edgeChecker); break; default: throw new IllegalArgumentException( "The type was not one of the supported types."); } return currentInspector; } /** * Checks if one of the graphs is from unsupported graph type and throws * IllegalArgumentException if it is. The current unsupported types are * graphs with multiple-edges. * * @param graph1 * @param graph2 * * @throws IllegalArgumentException */ protected static void assertUnsupportedGraphTypes(Graph g) throws IllegalArgumentException { if ((g instanceof Multigraph) || (g instanceof DirectedMultigraph) || (g instanceof Pseudograph)) { throw new IllegalArgumentException( "graph type not supported for the graph" + g); } } protected static int checkGraphsType(Graph graph1, Graph graph2) { return GRAPH_TYPE_ARBITRARY; } /** * @return ExhaustiveInspector, where the equivalence comparator is chained * with a topological comparator. This implementation uses: *

  • vertex degree size comparator */ @SuppressWarnings("unchecked") protected static GraphIsomorphismInspector createTopologicalExhaustiveInspector( Graph graph1, Graph graph2, EquivalenceComparator> vertexChecker, EquivalenceComparator> edgeChecker) { VertexDegreeEquivalenceComparator degreeComparator = new VertexDegreeEquivalenceComparator(); EquivalenceComparatorChain> vertexChainedChecker = new EquivalenceComparatorChainBase>( degreeComparator); vertexChainedChecker.appendComparator(vertexChecker); GraphIsomorphismInspector inspector = // FIXME hb060208 I don't understand how to generify this, yet new EquivalenceIsomorphismInspector( graph1, graph2, vertexChainedChecker, edgeChecker); return inspector; } } // End AdaptiveIsomorphismInspectorFactory.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/GraphOrdering.java0000644000175000017500000001622111706124626027057 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * GraphOrdering.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: GraphOrdering.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; import org.jgrapht.*; /** * Holds graph information as int labels only. vertexes: 1,2,3,4 edges:1->2 , * 3->4 ,1->1. Implementation as imutable graph by int[] for vetexes and * LabelsEdge[] for edges. The current algorithms do not support graph with * multiple edges (Multigraph / Pseudograph). For the maintaner: The reason for * it is the use of edges sets of LabelsEdge in which the equals checks for * source and target vertexes. Thus there cannot be two LabelsEdge with the same * source and target in the same Set. * * @author Assaf * @since May 20, 2005 */ public class GraphOrdering { //~ Instance fields -------------------------------------------------------- /** * Holds a mapping between key=V(vertex) and value=Integer(vertex order). It * can be used for identifying the order of regular vertex/edge. */ private Map mapVertexToOrder; /** * Holds a HashSet of all LabelsGraph of the graph. */ private Set labelsEdgesSet; //~ Constructors ----------------------------------------------------------- /** * Creates a new labels graph according to the regular graph. After its * creation they will no longer be linked, thus changes to one will not * affect the other. * * @param regularGraph */ public GraphOrdering(Graph regularGraph) { this(regularGraph, regularGraph.vertexSet(), regularGraph.edgeSet()); } /** * Creates a new labels graph according to the regular graph. After its * creation they will no longer be linked, thus changes to one will not * affect the other. * * @param regularGraph * @param vertexSet * @param edgeSet */ public GraphOrdering( Graph regularGraph, Set vertexSet, Set edgeSet) { init(regularGraph, vertexSet, edgeSet); } //~ Methods ---------------------------------------------------------------- private void init(Graph g, Set vertexSet, Set edgeSet) { // create a map between vertex value to its order(1st,2nd,etc) // "CAT"=1 "DOG"=2 "RHINO"=3 this.mapVertexToOrder = new HashMap(vertexSet.size()); int counter = 0; for (V vertex : vertexSet) { mapVertexToOrder.put(vertex, new Integer(counter)); counter++; } // create a friendlier representation of an edge // by order, like 2nd->3rd instead of B->A // use the map to convert vertex to order // on directed graph, edge A->B must be (A,B) // on undirected graph, edge A-B can be (A,B) or (B,A) this.labelsEdgesSet = new HashSet(edgeSet.size()); for (E edge : edgeSet) { V sourceVertex = g.getEdgeSource(edge); Integer sourceOrder = mapVertexToOrder.get(sourceVertex); int sourceLabel = sourceOrder.intValue(); int targetLabel = (mapVertexToOrder.get(g.getEdgeTarget(edge))).intValue(); LabelsEdge lablesEdge = new LabelsEdge(sourceLabel, targetLabel); this.labelsEdgesSet.add(lablesEdge); if (g instanceof UndirectedGraph) { LabelsEdge oppositeEdge = new LabelsEdge(targetLabel, sourceLabel); this.labelsEdgesSet.add(oppositeEdge); } } } /** * Tests equality by order of edges */ public boolean equalsByEdgeOrder(GraphOrdering otherGraph) { boolean result = this.getLabelsEdgesSet().equals(otherGraph.getLabelsEdgesSet()); return result; } public Set getLabelsEdgesSet() { return labelsEdgesSet; } /** * This is the format example: * *
           mapVertexToOrder=        labelsOrder=
         * 
    */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("mapVertexToOrder="); // vertex will be printed in their order Object [] vertexArray = new Object[this.mapVertexToOrder.size()]; Set keySet = this.mapVertexToOrder.keySet(); for (V currVertex : keySet) { Integer index = this.mapVertexToOrder.get(currVertex); vertexArray[index.intValue()] = currVertex; } sb.append(Arrays.toString(vertexArray)); sb.append("labelsOrder=").append(this.labelsEdgesSet.toString()); return sb.toString(); } //~ Inner Classes ---------------------------------------------------------- private class LabelsEdge { private int source; private int target; private int hashCode; public LabelsEdge(int aSource, int aTarget) { this.source = aSource; this.target = aTarget; this.hashCode = new String(this.source + "" + this.target).hashCode(); } /** * Checks both source and target. Does not check class type to be fast, * so it may throw ClassCastException. Careful! * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { LabelsEdge otherEdge = (LabelsEdge) obj; if ((this.source == otherEdge.source) && (this.target == otherEdge.target)) { return true; } else { return false; } } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return this.hashCode; // filled on constructor } public String toString() { return this.source + "->" + this.target; } } } // End GraphOrdering.java jgrapht-0.8.3/src/org/jgrapht/experimental/isomorphism/GraphIsomorphismInspector.java0000644000175000017500000000727311706124626031515 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------- * GraphIsomorphismInspector.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id: GraphIsomorphismInspector.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- */ package org.jgrapht.experimental.isomorphism; import java.util.*; /** * Isomorphism Overview * *

    Isomorphism is the problem of testing whether two graphs are topologically * the same. Suppose we are given a collection of graphs and must perform some * operation on each of them. If we can identify which of the graphs are * duplicates, they can be discarded so as to avoid redundant work. * *

    In Formal Math: Input description: Two graphs, G and H. Problem * description: Find a (or all) mappings f of the vertices of G to the * vertices of H such that G and H are identical; i.e. (x,y) is an edge of G iff * (f(x),f(y)) is an edge of H. * http://www2.toki.or.id/book/AlgDesignManual/BOOK/BOOK4/NODE180.HTM. * *

    Efficiency: The general algorithm is not polynomial, however * polynomial algorithms are known for special cases, like acyclic graphs, * planar graphs etc. There are several heuristic algorithms which gives quite * good results (polynomial) in general graphs, for most but not all cases. * *

    Usage: * *

      *
    1. Choose comparators for the vertexes and edges. You may use the default * comparator by sending null parameters for them to the constructor. Example: * Assume Your graphs are of human relations. Each vertex is either a man or a * woman and also has the person name. You may decide that isomorphism is * checked according to gender, but not according to the specific name. So you * will create a comparator that distinguishes vertexes only according to * gender. *
    2. Use the isIsomorphic() method as a boolean test for isomorphism *
    3. Use the Iterator interface to iterate through all the possible * isomorphism ordering. *
    * * @author Assaf Lehr * @since Jul 15, 2005 */ // REVIEW jvs 5-Sept-2005: Since we're using JDK1.5 now, we should be // able to declare this as Iterator, correct? Otherwise // the caller doesn't even know what they're getting back. public interface GraphIsomorphismInspector extends Iterator { //~ Methods ---------------------------------------------------------------- /** * @return true iff the two graphs are isomorphic */ public boolean isIsomorphic(); } // End GraphIsomorphismInspector.java jgrapht-0.8.3/src/org/jgrapht/experimental/UniformRandomGraphGenerator.java0000644000175000017500000000671311706124626027371 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * UniformRandomGraphGenerator.java * ------------------- * (C) Copyright 2003-2008, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: UniformRandomGraphGenerator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 13-Sep-2004 : Initial revision (MB); * */ // package org.jgrapht.generate; package org.jgrapht.experimental; import java.util.*; import org.jgrapht.*; import org.jgrapht.generate.*; /** * UniformRandomGraphGenerator generates a uniform random graph * of any size. A uniform random graph contains edges chosen independently * uniformly at random from the set of all possible edges. * * @author Michael Behrisch * @since Sep 13, 2004 */ public class UniformRandomGraphGenerator implements GraphGenerator { //~ Instance fields -------------------------------------------------------- private final int numEdges; private final int numVertices; //~ Constructors ----------------------------------------------------------- /** * Construct a new UniformRandomGraphGenerator. * * @param numVertices number of vertices to be generated * @param numEdges number of edges to be generated * * @throws IllegalArgumentException */ public UniformRandomGraphGenerator(int numVertices, int numEdges) { if (numVertices < 0) { throw new IllegalArgumentException("must be non-negative"); } if ((numEdges < 0) || (numEdges > (numVertices * (numVertices - 1) / 2))) { throw new IllegalArgumentException("illegal number of edges"); } this.numVertices = numVertices; this.numEdges = numEdges; } //~ Methods ---------------------------------------------------------------- /** * @see GraphGenerator#generateGraph */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { Object [] vertices = RandomGraphHelper.addVertices( target, vertexFactory, numVertices); RandomGraphHelper.addEdges( target, Arrays.asList(vertices), Arrays.asList(vertices), numEdges); } } // End UniformRandomGraphGenerator.java jgrapht-0.8.3/src/org/jgrapht/experimental/GraphSquare.java0000644000175000017500000001426011706124626024176 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------------- * GraphSquare.java * ---------------------- * (C) Copyright 2004-2008, by Michael Behrisch and Contributors. * * Original Author: Michael Behrisch * Contributor(s): - * * $Id: GraphSquare.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 14-Sep-2004 : Initial revision (MB); * */ package org.jgrapht.experimental; import java.util.*; import org.jgrapht.*; import org.jgrapht.event.*; import org.jgrapht.graph.*; /** * DOCUMENT ME! * * @author Michael Behrisch * @since Sep 14, 2004 */ public class GraphSquare extends AbstractBaseGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = -2642034600395594304L; private static final String UNMODIFIABLE = "this graph is unmodifiable"; //~ Constructors ----------------------------------------------------------- /** * Constructor for GraphSquare. * * @param g the graph of which a square is to be created. * @param createLoops */ public GraphSquare(final Graph g, final boolean createLoops) { super(g.getEdgeFactory(), false, createLoops); Graphs.addAllVertices(this, g.vertexSet()); addSquareEdges(g, createLoops); if (g instanceof ListenableGraph) { ((ListenableGraph) g).addGraphListener( new GraphListener() { public void edgeAdded(GraphEdgeChangeEvent e) { E edge = e.getEdge(); addEdgesStartingAt( g, g.getEdgeSource(edge), g.getEdgeTarget(edge), createLoops); addEdgesStartingAt( g, g.getEdgeTarget(edge), g.getEdgeSource(edge), createLoops); } public void edgeRemoved(GraphEdgeChangeEvent e) { // this is not a very performant implementation GraphSquare.super.removeAllEdges(edgeSet()); addSquareEdges(g, createLoops); } public void vertexAdded(GraphVertexChangeEvent e) { } public void vertexRemoved(GraphVertexChangeEvent e) { } }); } } //~ Methods ---------------------------------------------------------------- /** * @see Graph#addEdge(Object, Object) */ public E addEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#addEdge(Object, Object, E) */ public boolean addEdge(V sourceVertex, V targetVertex, E e) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#addVertex(Object) */ public boolean addVertex(V v) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllEdges(Collection) */ public boolean removeAllEdges(Collection edges) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllEdges(V, V) */ public Set removeAllEdges(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeAllVertices(Collection) */ public boolean removeAllVertices(Collection vertices) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeEdge(E) */ public boolean removeEdge(E e) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeEdge(V, V) */ public E removeEdge(V sourceVertex, V targetVertex) { throw new UnsupportedOperationException(UNMODIFIABLE); } /** * @see Graph#removeVertex(V) */ public boolean removeVertex(V v) { throw new UnsupportedOperationException(UNMODIFIABLE); } private void addEdgesStartingAt( final Graph g, final V v, final V u, boolean createLoops) { if (!g.containsEdge(v, u)) { return; } final List adjVertices = Graphs.neighborListOf(g, u); for (int i = 0; i < adjVertices.size(); i++) { final V w = adjVertices.get(i); if (g.containsEdge(u, w) && ((v != w) || createLoops)) { super.addEdge(v, w); } } } private void addSquareEdges(Graph g, boolean createLoops) { for (V v : g.vertexSet()) { List adjVertices = Graphs.neighborListOf(g, v); for (int i = 0; i < adjVertices.size(); i++) { addEdgesStartingAt(g, v, adjVertices.get(i), createLoops); } } } } // End GraphSquare.java jgrapht-0.8.3/src/org/jgrapht/experimental/GraphTests.java0000644000175000017500000000574211706124626024045 0ustar giovannigiovannipackage org.jgrapht.experimental; import java.util.*; import org.jgrapht.*; public final class GraphTests { //~ Constructors ----------------------------------------------------------- private GraphTests() { } //~ Methods ---------------------------------------------------------------- public static boolean isEmpty(Graph g) { return g.edgeSet().isEmpty(); } public static boolean isComplete(Graph g) { int n = g.vertexSet().size(); return g.edgeSet().size() == (n * (n - 1) / 2); } public static boolean isConnected(Graph g) { int numVertices = g.vertexSet().size(); int numEdges = g.edgeSet().size(); if (numEdges < (numVertices - 1)) { return false; } if ((numVertices < 2) || (numEdges > ((numVertices - 1) * (numVertices - 2) / 2))) { return true; } Set known = new HashSet(); LinkedList queue = new LinkedList(); V v = g.vertexSet().iterator().next(); queue.add(v); // start with node 1 known.add(v); while (!queue.isEmpty()) { v = queue.removeFirst(); for ( Iterator it = Graphs.neighborListOf(g, v).iterator(); it.hasNext();) { v = it.next(); if (!known.contains(v)) { known.add(v); queue.add(v); } } } return known.size() == numVertices; } public static boolean isTree(Graph g) { return isConnected(g) && (g.edgeSet().size() == (g.vertexSet().size() - 1)); } public static boolean isBipartite(Graph g) { if ((4 * g.edgeSet().size()) > (g.vertexSet().size() * g.vertexSet().size())) { return false; } if (isEmpty(g)) { return true; } Set unknown = new HashSet(g.vertexSet()); LinkedList queue = new LinkedList(); V v = unknown.iterator().next(); Set odd = new HashSet(); queue.add(v); while (!unknown.isEmpty()) { if (queue.isEmpty()) { queue.add(unknown.iterator().next()); } v = queue.removeFirst(); unknown.remove(v); for ( Iterator it = Graphs.neighborListOf(g, v).iterator(); it.hasNext();) { V n = it.next(); if (unknown.contains(n)) { queue.add(n); if (!odd.contains(v)) { odd.add(n); } } else if (!(odd.contains(v) ^ odd.contains(n))) { return false; } } } return true; } } // End GraphTests.java jgrapht-0.8.3/src/org/jgrapht/experimental/alg/0000755000175000017500000000000011752244357021656 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/alg/color/0000755000175000017500000000000011752244357022774 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/alg/color/BrownBacktrackColoring.java0000644000175000017500000000517711706124626030236 0ustar giovannigiovanni/** * */ package org.jgrapht.experimental.alg.color; import java.util.*; import org.jgrapht.*; import org.jgrapht.experimental.alg.*; /** * @author micha */ public class BrownBacktrackColoring extends IntArrayGraphAlgorithm implements ExactAlgorithm { //~ Instance fields -------------------------------------------------------- private int [] _color; private int [] _colorCount; private BitSet [] _allowedColors; private int _chi; //~ Constructors ----------------------------------------------------------- /** * @param g */ public BrownBacktrackColoring(final Graph g) { super(g); } //~ Methods ---------------------------------------------------------------- void recursiveColor(int pos) { _colorCount[pos] = _colorCount[pos - 1]; _allowedColors[pos].set(0, _colorCount[pos] + 1); for (int i = 0; i < _neighbors[pos].length; i++) { final int nb = _neighbors[pos][i]; if (_color[nb] > 0) { _allowedColors[pos].clear(_color[nb]); } } for ( int i = 1; (i <= _colorCount[pos]) && (_colorCount[pos] < _chi); i++) { if (_allowedColors[pos].get(i)) { _color[pos] = i; if (pos < (_neighbors.length - 1)) { recursiveColor(pos + 1); } else { _chi = _colorCount[pos]; } } } if ((_colorCount[pos] + 1) < _chi) { _colorCount[pos]++; _color[pos] = _colorCount[pos]; if (pos < (_neighbors.length - 1)) { recursiveColor(pos + 1); } else { _chi = _colorCount[pos]; } } _color[pos] = 0; } /* (non-Javadoc) * @see org.jgrapht.experimental.alg.ExactAlgorithm#getResult() */ public Integer getResult(Map additionalData) { _chi = _neighbors.length; _color = new int[_neighbors.length]; _color[0] = 1; _colorCount = new int[_neighbors.length]; _colorCount[0] = 1; _allowedColors = new BitSet[_neighbors.length]; for (int i = 0; i < _neighbors.length; i++) { _allowedColors[i] = new BitSet(1); } recursiveColor(1); if (additionalData != null) { for (int i = 0; i < _vertices.size(); i++) { additionalData.put(_vertices.get(i), _color[i]); } } return _chi; } } // End BrownBacktrackColoring.java jgrapht-0.8.3/src/org/jgrapht/experimental/alg/color/GreedyColoring.java0000644000175000017500000001363711706124626026560 0ustar giovannigiovannipackage org.jgrapht.experimental.alg.color; import java.util.*; import org.jgrapht.*; import org.jgrapht.experimental.alg.*; public class GreedyColoring extends IntArrayGraphAlgorithm implements ApproximationAlgorithm { //~ Static fields/initializers --------------------------------------------- public static final int BEST_ORDER = 0; public static final int NATURAL_ORDER = 1; public static final int SMALLEST_DEGREE_LAST_ORDER = 2; public static final int LARGEST_SATURATION_FIRST_ORDER = 3; //~ Instance fields -------------------------------------------------------- private int _order = BEST_ORDER; //~ Constructors ----------------------------------------------------------- /** * @param g */ public GreedyColoring(final Graph g) { this(g, BEST_ORDER); } /** * @param g */ public GreedyColoring(final Graph g, final int method) { super(g); _order = method; } //~ Methods ---------------------------------------------------------------- int color(int [] order) { final int [] color = new int[_neighbors.length]; int maxColor = 1; BitSet usedColors = new BitSet(_neighbors.length); for (int i = 0; i < _neighbors.length; i++) { final int v = (order == null) ? i : order[i]; usedColors.clear(); for (int j = 0; j < _neighbors[v].length; j++) { final int nb = _neighbors[v][j]; if (color[nb] > 0) { usedColors.set(color[nb]); } } color[v] = usedColors.nextClearBit(1); if (color[v] > maxColor) { maxColor = color[v]; } } return maxColor; } int [] smallestDegreeLastOrder() { final int [] order = new int[_neighbors.length]; final int [] degree = new int[_neighbors.length]; final List> buckets = new ArrayList>(_neighbors.length); int index = _neighbors.length - 1; for (int i = 0; i < _neighbors.length; i++) { buckets.add(new ArrayList()); degree[i] = _neighbors[i].length; } for (int i = 0; i < _neighbors.length; i++) { buckets.get(degree[i]).add(i); } for (int i = 0; i < _neighbors.length; i++) { while (buckets.get(i).size() > 0) { final int s = buckets.get(i).size() - 1; final int vertex = (Integer) buckets.get(i).get(s); buckets.get(i).remove(s); degree[vertex] = -1; order[index--] = vertex; for (int j = 0; j < _neighbors[vertex].length; j++) { final int nb = _neighbors[vertex][j]; if (degree[nb] >= 0) { buckets.get(degree[nb]).remove(new Integer(nb)); degree[nb]--; buckets.get(degree[nb]).add(nb); if (degree[nb] < i) { i = degree[nb]; } } } } } return order; } int [] largestSaturationFirstOrder() { final int [] satur = new int[_neighbors.length]; final int [] buckets = new int[_neighbors.length]; final int [] cumBucketSize = new int[_neighbors.length]; final int [] bucketIndex = new int[_neighbors.length]; int index = 0; int maxSat = 0; for (int i = 0; i < _neighbors.length; i++) { buckets[i] = i; bucketIndex[i] = i; } cumBucketSize[0] = _neighbors.length; while (index < _neighbors.length) { while ( (maxSat > 0) && (cumBucketSize[maxSat] == cumBucketSize[maxSat - 1])) { cumBucketSize[maxSat--] = 0; } final int v = buckets[cumBucketSize[maxSat] - 1]; cumBucketSize[maxSat]--; satur[v] = -1; index++; for (int j = 0; j < _neighbors[v].length; j++) { final int nb = (int) _neighbors[v][j]; final int bi = bucketIndex[nb]; if (satur[nb] >= 0) { if (bi != (cumBucketSize[satur[nb]] - 1)) { buckets[bi] = buckets[cumBucketSize[satur[nb]] - 1]; buckets[cumBucketSize[satur[nb]] - 1] = nb; bucketIndex[nb] = cumBucketSize[satur[nb]] - 1; bucketIndex[buckets[bi]] = bi; } cumBucketSize[satur[nb]]--; satur[nb]++; if (cumBucketSize[satur[nb]] == 0) { cumBucketSize[satur[nb]] = cumBucketSize[satur[nb] - 1] + 1; } if (satur[nb] > maxSat) { maxSat = satur[nb]; } } } } Collections.reverse(Arrays.asList(buckets)); return buckets; } public Integer getLowerBound(Map optionalData) { return 0; } public Integer getUpperBound(Map optionalData) { switch (_order) { case BEST_ORDER: return Math.min( Math.min(color(null), color(smallestDegreeLastOrder())), color(largestSaturationFirstOrder())); case NATURAL_ORDER: return color(null); case SMALLEST_DEGREE_LAST_ORDER: return color(smallestDegreeLastOrder()); case LARGEST_SATURATION_FIRST_ORDER: return color(largestSaturationFirstOrder()); } return _neighbors.length; } public boolean isExact() { return false; } } // End GreedyColoring.java jgrapht-0.8.3/src/org/jgrapht/experimental/alg/IntArrayGraphAlgorithm.java0000644000175000017500000000250511706124626027100 0ustar giovannigiovanni/** * */ package org.jgrapht.experimental.alg; import java.util.*; import org.jgrapht.*; /** * @author micha */ public abstract class IntArrayGraphAlgorithm { //~ Instance fields -------------------------------------------------------- protected final List _vertices; protected final int [][] _neighbors; protected final Map _vertexToPos; //~ Constructors ----------------------------------------------------------- /** * @param g */ public IntArrayGraphAlgorithm(final Graph g) { final int numVertices = g.vertexSet().size(); _vertices = new ArrayList(numVertices); _neighbors = new int[numVertices][]; _vertexToPos = new HashMap(numVertices); for (V vertex : g.vertexSet()) { _neighbors[_vertices.size()] = new int[g.edgesOf(vertex).size()]; _vertexToPos.put(vertex, _vertices.size()); _vertices.add(vertex); } for (int i = 0; i < numVertices; i++) { int nbIndex = 0; final V vertex = _vertices.get(i); for (E e : g.edgesOf(vertex)) { _neighbors[i][nbIndex++] = _vertexToPos.get(Graphs.getOppositeVertex(g, e, vertex)); } } } } // End IntArrayGraphAlgorithm.java jgrapht-0.8.3/src/org/jgrapht/experimental/alg/ApproximationAlgorithm.java0000644000175000017500000000057511706124626027224 0ustar giovannigiovannipackage org.jgrapht.experimental.alg; import java.util.*; public interface ApproximationAlgorithm { //~ Methods ---------------------------------------------------------------- ResultType getUpperBound(Map optionalData); ResultType getLowerBound(Map optionalData); boolean isExact(); } // End ApproximationAlgorithm.java jgrapht-0.8.3/src/org/jgrapht/experimental/alg/ExactAlgorithm.java0000644000175000017500000000042511706124626025430 0ustar giovannigiovannipackage org.jgrapht.experimental.alg; import java.util.*; public interface ExactAlgorithm { //~ Methods ---------------------------------------------------------------- ResultType getResult(Map optionalData); } // End ExactAlgorithm.java jgrapht-0.8.3/src/org/jgrapht/experimental/dag/0000755000175000017500000000000011752244357021646 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/experimental/dag/DirectedAcyclicGraph.java0000644000175000017500000010653011706124626026506 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * DirectedAcyclicGraph.java * ------------------- * (C) Copyright 2008-2008, by Peter Giles and Contributors. * * Original Author: Peter Giles * Contributor(s): John V. Sichi * * $Id: DirectedAcyclicGraph.java 637 2008-09-28 22:23:11Z perfecthash $ * * Changes * ------- * 17-Mar-2008 : Initial revision (PG); * 23-Aug-2008 : Added VisitedBitSetImpl and made it the default (JVS); * */ package org.jgrapht.experimental.dag; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.graph.*; /** *

    DirectedAcyclicGraph implements a DAG that can be modified (vertices & * edges added and removed), is guaranteed to remain acyclic, and provides fast * topological order iteration.

    * *

    This is done using a dynamic topological sort which is based on the * algorithm PK described in "D. Pearce & P. Kelly, 2007: A Dynamic * Topological Sort Algorithm for Directed Acyclic Graphs", (see Paper or ACM link for details). *

    * *

    The implementation differs from the algorithm specified in the above paper * in some ways, perhaps most notably in that the topological ordering is stored * by default using two HashMaps, which will have some effects on runtime, but * also allows for vertex addition and removal, and other operations which are * helpful for manipulating or combining DAGs. This storage mechanism is * pluggable for subclassers.

    * *

    This class makes no claims to thread safety, and concurrent usage from * multiple threads will produce undefined results.

    * * @author Peter Giles, gilesp@u.washington.edu */ public class DirectedAcyclicGraph extends SimpleDirectedGraph { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 4522128427004938150L; //~ Instance fields -------------------------------------------------------- private TopoComparator topoComparator; private TopoOrderMapping topoOrderMap; private int maxTopoIndex = 0; private int minTopoIndex = 0; // this update count is used to keep internal topological iterators honest private long topologyUpdateCount = 0; /** * Pluggable VisitedFactory implementation */ private VisitedFactory visitedFactory = new VisitedBitSetImpl(); /** * Pluggable TopoOrderMappingFactory implementation */ private TopoOrderMappingFactory topoOrderFactory = new TopoVertexBiMap(); //~ Constructors ----------------------------------------------------------- public DirectedAcyclicGraph(Class arg0) { super(arg0); initialize(); } DirectedAcyclicGraph( Class arg0, VisitedFactory visitedFactory, TopoOrderMappingFactory topoOrderFactory) { super(arg0); if (visitedFactory != null) { this.visitedFactory = visitedFactory; } if (topoOrderFactory != null) { this.topoOrderFactory = topoOrderFactory; } initialize(); } //~ Methods ---------------------------------------------------------------- /** * set the topoOrderMap based on the current factory, and create the * comparator; */ private void initialize() { topoOrderMap = topoOrderFactory.getTopoOrderMapping(); topoComparator = new TopoComparator(topoOrderMap); } /** * iterator will traverse the vertices in topological order, meaning that * for a directed graph G = (V,E), if there exists a path from vertex va to * vertex vb then va is guaranteed to come before vertex vb in the iteration * order. * * @return an iterator that will traverse the graph in topological order */ public Iterator iterator() { return new TopoIterator(); } /** * adds the vertex if it wasn't already in the graph, and puts it at the top * of the internal topological vertex ordering */ @Override public boolean addVertex(V v) { boolean added = super.addVertex(v); if (added) { // add to the top ++maxTopoIndex; topoOrderMap.putVertex(maxTopoIndex, v); ++topologyUpdateCount; } return added; } /** * adds the vertex if it wasn't already in the graph, and puts it either at * the top or the bottom of the topological ordering, depending on the value * of addToTop. This may provide useful optimizations for merging * DirectedAcyclicGraphS that become connected. * * @param v * @param addToTop * * @return */ public boolean addVertex(V v, boolean addToTop) { boolean added = super.addVertex(v); if (added) { int insertIndex; // add to the top if (addToTop) { insertIndex = ++maxTopoIndex; } else { insertIndex = --minTopoIndex; } topoOrderMap.putVertex(insertIndex, v); ++topologyUpdateCount; } return added; } /** *

    Adds the given edge and updates the internal topological order for * consistency IFF * *

      *
    • there is not already an edge (fromVertex, toVertex) in the graph *
    • the edge does not induce a cycle in the graph *
    *

    * * @return null if the edge is already in the graph, else the created edge * is returned * * @throws IllegalArgumentException If either fromVertex or toVertex is not * a member of the graph * @throws CycleFoundException if the edge would induce a cycle in the graph * * @see Graph#addEdge(Object, Object, Object) */ public E addDagEdge(V fromVertex, V toVertex) throws CycleFoundException { Integer lb = topoOrderMap.getTopologicalIndex(toVertex); Integer ub = topoOrderMap.getTopologicalIndex(fromVertex); if ((lb == null) || (ub == null)) { throw new IllegalArgumentException( "vertices must be in the graph already!"); } if (lb < ub) { Set df = new HashSet(); Set db = new HashSet(); // Discovery Region affectedRegion = new Region(lb, ub); Visited visited = visitedFactory.getInstance(affectedRegion); // throws CycleFoundException if there is a cycle dfsF(toVertex, df, visited, affectedRegion); dfsB(fromVertex, db, visited, affectedRegion); reorder(df, db, visited); ++topologyUpdateCount; // if we do a reorder, than the topology has // been updated } return super.addEdge(fromVertex, toVertex); } /** * identical to {@link #addDagEdge(Object, Object)}, except an unchecked * {@link IllegalArgumentException} is thrown if a cycle would have been * induced by this edge */ @Override public E addEdge(V sourceVertex, V targetVertex) { E result = null; try { result = addDagEdge(sourceVertex, targetVertex); } catch (CycleFoundException e) { throw new IllegalArgumentException(e); } return result; } /** *

    Adds the given edge and updates the internal topological order for * consistency IFF * *

      *
    • the given edge is not already a member of the graph *
    • there is not already an edge (fromVertex, toVertex) in the graph *
    • the edge does not induce a cycle in the graph *
    *

    * * @return true if the edge was added to the graph * * @throws CycleFoundException if adding an edge (fromVertex, toVertex) to * the graph would induce a cycle. * * @see Graph#addEdge(Object, Object, Object) */ public boolean addDagEdge(V fromVertex, V toVertex, E e) throws CycleFoundException { if (e == null) { throw new NullPointerException(); } else if (containsEdge(e)) { return false; } Integer lb = topoOrderMap.getTopologicalIndex(toVertex); Integer ub = topoOrderMap.getTopologicalIndex(fromVertex); if ((lb == null) || (ub == null)) { throw new IllegalArgumentException( "vertices must be in the graph already!"); } if (lb < ub) { Set df = new HashSet(); Set db = new HashSet(); // Discovery Region affectedRegion = new Region(lb, ub); Visited visited = visitedFactory.getInstance(affectedRegion); // throws CycleFoundException if there is a cycle dfsF(toVertex, df, visited, affectedRegion); dfsB(fromVertex, db, visited, affectedRegion); reorder(df, db, visited); ++topologyUpdateCount; // if we do a reorder, than the topology has // been updated } return super.addEdge(fromVertex, toVertex, e); } /** * identical to {@link #addDagEdge(Object, Object, Object)}, except an * unchecked {@link IllegalArgumentException} is thrown if a cycle would * have been induced by this edge */ @Override public boolean addEdge(V sourceVertex, V targetVertex, E edge) { boolean result; try { result = addDagEdge(sourceVertex, targetVertex, edge); } catch (CycleFoundException e) { throw new IllegalArgumentException(e); } return result; } // note that this can leave holes in the topological ordering, which // (depending on the TopoOrderMap implementation) can degrade performance // for certain operations over time @Override public boolean removeVertex(V v) { boolean removed = super.removeVertex(v); if (removed) { Integer topoIndex = topoOrderMap.removeVertex(v); // contract minTopoIndex as we are able if (topoIndex == minTopoIndex) { while ( (minTopoIndex < 0) && (null == topoOrderMap.getVertex(minTopoIndex))) { ++minTopoIndex; } } // contract maxTopoIndex as we are able if (topoIndex == maxTopoIndex) { while ( (maxTopoIndex > 0) && (null == topoOrderMap.getVertex(maxTopoIndex))) { --maxTopoIndex; } } ++topologyUpdateCount; } return removed; } @Override public boolean removeAllVertices(Collection arg0) { boolean removed = super.removeAllVertices(arg0); topoOrderMap.removeAllVertices(); maxTopoIndex = 0; minTopoIndex = 0; ++topologyUpdateCount; return removed; } /** * Depth first search forward, building up the set (df) of forward-connected * vertices in the Affected Region * * @param vertex the vertex being visited * @param df the set we are populating with forward connected vertices in * the Affected Region * @param visited a simple data structure that lets us know if we already * visited a node with a given topo index * @param topoIndexMap for quick lookups, a map from vertex to topo index in * the AR * @param ub the topo index of the original fromVertex -- used for cycle * detection * * @throws CycleFoundException if a cycle is discovered */ private void dfsF( V vertex, Set df, Visited visited, Region affectedRegion) throws CycleFoundException { int topoIndex = topoOrderMap.getTopologicalIndex(vertex); // Assumption: vertex is in the AR and so it will be in visited visited.setVisited(topoIndex); df.add(vertex); for (E outEdge : outgoingEdgesOf(vertex)) { V nextVertex = getEdgeTarget(outEdge); Integer nextVertexTopoIndex = topoOrderMap.getTopologicalIndex(nextVertex); if (nextVertexTopoIndex.intValue() == affectedRegion.finish) { // reset visited try { for (V visitedVertex : df) { visited.clearVisited( topoOrderMap.getTopologicalIndex(visitedVertex)); } } catch (UnsupportedOperationException e) { // okay, fine, some implementations (ones that automatically // clear themselves out) don't work this way } throw new CycleFoundException(); } // note, order of checks is important as we need to make sure the // vertex is in the affected region before we check its visited // status (otherwise we will be causing an // ArrayIndexOutOfBoundsException). if (affectedRegion.isIn(nextVertexTopoIndex) && !visited.getVisited(nextVertexTopoIndex)) { dfsF(nextVertex, df, visited, affectedRegion); // recurse } } } /** * Depth first search backward, building up the set (db) of back-connected * vertices in the Affected Region * * @param vertex the vertex being visited * @param db the set we are populating with back-connected vertices in the * AR * @param visited * @param topoIndexMap */ private void dfsB( V vertex, Set db, Visited visited, Region affectedRegion) { // Assumption: vertex is in the AR and so we will get a topoIndex from // the map int topoIndex = topoOrderMap.getTopologicalIndex(vertex); visited.setVisited(topoIndex); db.add(vertex); for (E inEdge : incomingEdgesOf(vertex)) { V previousVertex = getEdgeSource(inEdge); Integer previousVertexTopoIndex = topoOrderMap.getTopologicalIndex(previousVertex); // note, order of checks is important as we need to make sure the // vertex is in the affected region before we check its visited // status (otherwise we will be causing an // ArrayIndexOutOfBoundsException). if (affectedRegion.isIn(previousVertexTopoIndex) && !visited.getVisited(previousVertexTopoIndex)) { // if prevousVertexTopoIndex != null, the vertex is in the // Affected Region according to our topoIndexMap dfsB(previousVertex, db, visited, affectedRegion); } } } @SuppressWarnings("unchecked") private void reorder(Set df, Set db, Visited visited) { List topoDf = new ArrayList(df); List topoDb = new ArrayList(db); Collections.sort(topoDf, topoComparator); Collections.sort(topoDb, topoComparator); // merge these suckers together in topo order SortedSet availableTopoIndices = new TreeSet(); // we have to cast to the generic type, can't do "new V[size]" in java // 5; V [] bigL = (V []) new Object[df.size() + db.size()]; int lIndex = 0; // this index is used for the sole purpose of pushing // into // the correct index of bigL // assume (for now) that we are resetting visited boolean clearVisited = true; for (V vertex : topoDb) { Integer topoIndex = topoOrderMap.getTopologicalIndex(vertex); // add the available indices to the set availableTopoIndices.add(topoIndex); bigL[lIndex++] = vertex; if (clearVisited) { // reset visited status if supported try { visited.clearVisited(topoIndex); } catch (UnsupportedOperationException e) { clearVisited = false; } } } for (V vertex : topoDf) { Integer topoIndex = topoOrderMap.getTopologicalIndex(vertex); // add the available indices to the set availableTopoIndices.add(topoIndex); bigL[lIndex++] = vertex; if (clearVisited) { // reset visited status if supported try { visited.clearVisited(topoIndex); } catch (UnsupportedOperationException e) { clearVisited = false; } } } lIndex = 0; // reusing lIndex for (Integer topoIndex : availableTopoIndices) { // assign the indexes to the elements of bigL in order V vertex = bigL[lIndex++]; // note the post-increment topoOrderMap.putVertex(topoIndex, vertex); } } //~ Inner Interfaces ------------------------------------------------------- /** * For performance tuning, an interface for storing the topological ordering * * @author gilesp */ public interface TopoOrderMapping extends Serializable { /** * add a vertex at the given topological index. * * @param index * @param vertex */ public void putVertex(Integer index, V vertex); /** * get the vertex at the given topological index. * * @param index * * @return */ public V getVertex(Integer index); /** * get the topological index of the given vertex. * * @param vertex * * @return the index that the vertex is at, or null if the vertex isn't * in the topological ordering */ public Integer getTopologicalIndex(V vertex); /** * remove the given vertex from the topological ordering * * @param vertex * * @return the index that the vertex was at, or null if the vertex * wasn't in the topological ordering */ public Integer removeVertex(V vertex); /** * remove all vertices from the topological ordering */ public void removeAllVertices(); } public interface TopoOrderMappingFactory { public TopoOrderMapping getTopoOrderMapping(); } /** * this interface allows specification of a strategy for marking vertices as * visited (based on their topological index, so the vertex type isn't part * of the interface). */ public interface Visited { /** * mark the given topological index as visited * * @param index the topological index */ public void setVisited(int index); /** * has the given topological index been visited? * * @param index the topological index */ public boolean getVisited(int index); /** * Clear the visited state of the given topological index * * @param index * * @throws UnsupportedOperationException if the implementation doesn't * support (or doesn't need) clearance. For example, if the factory * vends a new instance every time, it is a waste of cycles to clear the * state after the search of the Affected Region is done, so an * UnsupportedOperationException *should* be thrown. */ public void clearVisited(int index) throws UnsupportedOperationException; } /** * interface for a factory that vends Visited implementations * * @author gilesp */ public interface VisitedFactory extends Serializable { public Visited getInstance(Region affectedRegion); } //~ Inner Classes ---------------------------------------------------------- /** * Note, this is a lazy and incomplete implementation, with assumptions that * inputs are in the given topoIndexMap * * @param * * @author gilesp */ private static class TopoComparator implements Comparator, Serializable { /** */ private static final long serialVersionUID = 1L; private TopoOrderMapping topoOrderMap; public TopoComparator(TopoOrderMapping topoOrderMap) { this.topoOrderMap = topoOrderMap; } public int compare(V o1, V o2) { return topoOrderMap.getTopologicalIndex(o1).compareTo( topoOrderMap.getTopologicalIndex(o2)); } } /** * a dual HashMap implementation * * @author gilesp */ private class TopoVertexBiMap implements TopoOrderMapping, TopoOrderMappingFactory { /** */ private static final long serialVersionUID = 1L; private final Map topoToVertex = new HashMap(); private final Map vertexToTopo = new HashMap(); public void putVertex(Integer index, V vertex) { topoToVertex.put(index, vertex); vertexToTopo.put(vertex, index); } public V getVertex(Integer index) { return topoToVertex.get(index); } public Integer getTopologicalIndex(V vertex) { Integer topoIndex = vertexToTopo.get(vertex); return topoIndex; } public Integer removeVertex(V vertex) { Integer topoIndex = vertexToTopo.remove(vertex); if (topoIndex != null) { topoToVertex.remove(topoIndex); } return topoIndex; } public void removeAllVertices() { vertexToTopo.clear(); topoToVertex.clear(); } public TopoOrderMapping getTopoOrderMapping() { return this; } } /** * For performance and flexibility uses an ArrayList for topological index * to vertex mapping, and a HashMap for vertex to topological index mapping. * * @author gilesp */ public class TopoVertexMap implements TopoOrderMapping, TopoOrderMappingFactory { /** */ private static final long serialVersionUID = 1L; private final List topoToVertex = new ArrayList(); private final Map vertexToTopo = new HashMap(); public void putVertex(Integer index, V vertex) { int translatedIndex = translateIndex(index); // grow topoToVertex as needed to accommodate elements while ((translatedIndex + 1) > topoToVertex.size()) { topoToVertex.add(null); } topoToVertex.set(translatedIndex, vertex); vertexToTopo.put(vertex, index); } public V getVertex(Integer index) { return topoToVertex.get(translateIndex(index)); } public Integer getTopologicalIndex(V vertex) { return vertexToTopo.get(vertex); } public Integer removeVertex(V vertex) { Integer topoIndex = vertexToTopo.remove(vertex); if (topoIndex != null) { topoToVertex.set(translateIndex(topoIndex), null); } return topoIndex; } public void removeAllVertices() { vertexToTopo.clear(); topoToVertex.clear(); } public TopoOrderMapping getTopoOrderMapping() { return this; } /** * We translate the topological index to an ArrayList index. We have to * do this because topological indices can be negative, and we want to * do it because we can make better use of space by only needing an * ArrayList of size |AR|. * * @param unscaledIndex * * @return the ArrayList index */ private final int translateIndex(int index) { if (index >= 0) { return 2 * index; } return -1 * ((index * 2) - 1); } } /** * Region is an *inclusive* range of indices. Esthetically displeasing, but * convenient for our purposes. * * @author gilesp */ public static class Region implements Serializable { /** */ private static final long serialVersionUID = 1L; public final int start; public final int finish; public Region(int start, int finish) { if (start > finish) { throw new IllegalArgumentException( "(start > finish): invariant broken"); } this.start = start; this.finish = finish; } public int getSize() { return (finish - start) + 1; } public boolean isIn(int index) { return (index >= start) && (index <= finish); } } /** * This implementation is close to the performance of VisitedArrayListImpl, * with 1/8 the memory usage. * * @author perfecthash */ public static class VisitedBitSetImpl implements Visited, VisitedFactory { /** */ private static final long serialVersionUID = 1L; private final BitSet visited = new BitSet(); private Region affectedRegion; public Visited getInstance(Region affectedRegion) { this.affectedRegion = affectedRegion; return this; } public void setVisited(int index) { visited.set(translateIndex(index), true); } public boolean getVisited(int index) { return visited.get(translateIndex(index)); } public void clearVisited(int index) throws UnsupportedOperationException { visited.clear(translateIndex(index)); } /** * We translate the topological index to an ArrayList index. We have to * do this because topological indices can be negative, and we want to * do it because we can make better use of space by only needing an * ArrayList of size |AR|. * * @param unscaledIndex * * @return the ArrayList index */ private int translateIndex(int index) { return index - affectedRegion.start; } } /** * This implementation seems to offer the best performance in most cases. It * grows the internal ArrayList as needed to be as large as |AR|, so it will * be more memory intensive than the HashSet implementation, and unlike the * Array implementation, it will hold on to that memory (it expands, but * never contracts). * * @author gilesp */ public static class VisitedArrayListImpl implements Visited, VisitedFactory { /** */ private static final long serialVersionUID = 1L; private final List visited = new ArrayList(); private Region affectedRegion; public Visited getInstance(Region affectedRegion) { // Make sure visited is big enough int minSize = (affectedRegion.finish - affectedRegion.start) + 1; /* plus one because the region range is inclusive of both indices */ while (visited.size() < minSize) { visited.add(Boolean.FALSE); } this.affectedRegion = affectedRegion; return this; } public void setVisited(int index) { visited.set(translateIndex(index), Boolean.TRUE); } public boolean getVisited(int index) { Boolean result = null; result = visited.get(translateIndex(index)); return result; } public void clearVisited(int index) throws UnsupportedOperationException { visited.set(translateIndex(index), Boolean.FALSE); } /** * We translate the topological index to an ArrayList index. We have to * do this because topological indices can be negative, and we want to * do it because we can make better use of space by only needing an * ArrayList of size |AR|. * * @param unscaledIndex * * @return the ArrayList index */ private int translateIndex(int index) { return index - affectedRegion.start; } } /** * This implementation doesn't seem to perform as well, though I can imagine * circumstances where it should shine (lots and lots of vertices). It also * should have the lowest memory footprint as it only uses storage for * indices that have been visited. * * @author gilesp */ public static class VisitedHashSetImpl implements Visited, VisitedFactory { /** */ private static final long serialVersionUID = 1L; private final Set visited = new HashSet(); public Visited getInstance(Region affectedRegion) { visited.clear(); return this; } public void setVisited(int index) { visited.add(index); } public boolean getVisited(int index) { return visited.contains(index); } public void clearVisited(int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } /** * This implementation, somewhat to my surprise, is slower than the * ArrayList version, probably due to its reallocation of the underlying * array for every topology reorder that is required. * * @author gilesp */ public static class VisitedArrayImpl implements Visited, VisitedFactory { /** */ private static final long serialVersionUID = 1L; private final boolean [] visited; private final Region region; /** * Constructs empty factory instance */ public VisitedArrayImpl() { this(null); } public VisitedArrayImpl(Region region) { if (region == null) { // make empty instance this.visited = null; this.region = null; } else { // fill in the needed pieces this.region = region; // initialized to all false by default visited = new boolean[region.getSize()]; } } public Visited getInstance(Region affectedRegion) { return new VisitedArrayImpl(affectedRegion); } public void setVisited(int index) { try { visited[index - region.start] = true; } catch (ArrayIndexOutOfBoundsException e) { /* log.error("Visited set operation out of region boundaries", e); */ throw e; } } public boolean getVisited(int index) { try { return visited[index - region.start]; } catch (ArrayIndexOutOfBoundsException e) { /* log.error("Visited set operation out of region boundaries", e); */ throw e; } } public void clearVisited(int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } } /** * Exception used in dfsF when a cycle is found * * @author gilesp */ public static class CycleFoundException extends Exception { private static final long serialVersionUID = 5583471522212552754L; } /** * iterator which follows topological order * * @author gilesp */ private class TopoIterator implements Iterator { private int currentTopoIndex; private final long updateCountAtCreation; private Integer nextIndex = null; public TopoIterator() { updateCountAtCreation = topologyUpdateCount; currentTopoIndex = minTopoIndex - 1; } public boolean hasNext() { if (updateCountAtCreation != topologyUpdateCount) { throw new ConcurrentModificationException(); } nextIndex = getNextIndex(); return nextIndex != null; } public V next() { if (updateCountAtCreation != topologyUpdateCount) { throw new ConcurrentModificationException(); } if (nextIndex == null) { // find nextIndex nextIndex = getNextIndex(); } if (nextIndex == null) { throw new NoSuchElementException(); } currentTopoIndex = nextIndex; nextIndex = null; return topoOrderMap.getVertex(currentTopoIndex); //topoToVertex.get(currentTopoIndex); } public void remove() { if (updateCountAtCreation != topologyUpdateCount) { throw new ConcurrentModificationException(); } V vertexToRemove = null; if (null != (vertexToRemove = topoOrderMap.getVertex( currentTopoIndex))) { topoOrderMap.removeVertex(vertexToRemove); } else { // should only happen if next() hasn't been called throw new IllegalStateException(); } } private Integer getNextIndex() { for (int i = currentTopoIndex + 1; i <= maxTopoIndex; i++) { if (null != topoOrderMap.getVertex(i)) { return i; } } return null; } } } // End DirectedAcyclicGraph.java jgrapht-0.8.3/src/org/jgrapht/experimental/GraphReader.java0000644000175000017500000001220111706124626024131 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------- * GraphReader.java * ------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: GraphReader.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (BN); * */ package org.jgrapht.experimental; import java.io.*; import java.util.*; import org.jgrapht.*; import org.jgrapht.generate.*; public class GraphReader implements GraphGenerator { //~ Instance fields -------------------------------------------------------- // ~ Static fields/initializers -------------------------------------------- // ~ Instance fields ------------------------------------------------------- // ~ Static fields/initializers -------------------------------------------- // ~ Instance fields ------------------------------------------------------- private final BufferedReader _in; private final boolean _isWeighted; private final double _defaultWeight; // ~ Constructors ---------------------------------------------------------- //~ Constructors ----------------------------------------------------------- /** * Construct a new GraphReader. */ private GraphReader(Reader input, boolean isWeighted, double defaultWeight) throws IOException { if (input instanceof BufferedReader) { _in = (BufferedReader) input; } else { _in = new BufferedReader(input); } _isWeighted = isWeighted; _defaultWeight = defaultWeight; } /** * Construct a new GraphReader. */ public GraphReader(Reader input) throws IOException { this(input, false, 1); } /** * Construct a new GraphReader. */ public GraphReader(Reader input, double defaultWeight) throws IOException { this(input, true, defaultWeight); } //~ Methods ---------------------------------------------------------------- // ~ Methods --------------------------------------------------------------- private String [] split(final String src) { if (src == null) { return null; } return src.split("\\s+"); } private String [] skipComments() { String [] cols = null; try { cols = split(_in.readLine()); while ( (cols != null) && ((cols.length == 0) || cols[0].equals("c") || cols[0].startsWith("%"))) { cols = split(_in.readLine()); } } catch (IOException e) { } return cols; } private int readNodeCount() { final String [] cols = skipComments(); if (cols[0].equals("p")) { return Integer.parseInt(cols[1]); } return -1; } /** * {@inheritDoc} */ public void generateGraph( Graph target, VertexFactory vertexFactory, Map resultMap) { final int size = readNodeCount(); if (resultMap == null) { resultMap = new HashMap(); } for (int i = 0; i < size; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); resultMap.put(Integer.toString(i + 1), newVertex); } String [] cols = skipComments(); while (cols != null) { if (cols[0].equals("e")) { E edge = target.addEdge( resultMap.get(cols[1]), resultMap.get(cols[2])); if (_isWeighted && (edge != null)) { double weight = _defaultWeight; if (cols.length > 3) { weight = Double.parseDouble(cols[3]); } ((WeightedGraph) target).setEdgeWeight(edge, weight); } } cols = skipComments(); } } } // End GraphReader.java jgrapht-0.8.3/src/org/jgrapht/DirectedGraph.java0000644000175000017500000000702111706124626021761 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * DirectedGraph.java * ------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: DirectedGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * */ package org.jgrapht; import java.util.*; /** * A graph whose all edges are directed. This is the root interface of all * directed graphs. * *

    See * http://mathworld.wolfram.com/DirectedGraph.html for more on directed * graphs.

    * * @author Barak Naveh * @since Jul 14, 2003 */ public interface DirectedGraph extends Graph { //~ Methods ---------------------------------------------------------------- /** * Returns the "in degree" of the specified vertex. An in degree of a vertex * in a directed graph is the number of inward directed edges from that * vertex. See * http://mathworld.wolfram.com/Indegree.html. * * @param vertex vertex whose degree is to be calculated. * * @return the degree of the specified vertex. */ public int inDegreeOf(V vertex); /** * Returns a set of all edges incoming into the specified vertex. * * @param vertex the vertex for which the list of incoming edges to be * returned. * * @return a set of all edges incoming into the specified vertex. */ public Set incomingEdgesOf(V vertex); /** * Returns the "out degree" of the specified vertex. An out degree of a * vertex in a directed graph is the number of outward directed edges from * that vertex. See * http://mathworld.wolfram.com/Outdegree.html. * * @param vertex vertex whose degree is to be calculated. * * @return the degree of the specified vertex. */ public int outDegreeOf(V vertex); /** * Returns a set of all edges outgoing from the specified vertex. * * @param vertex the vertex for which the list of outgoing edges to be * returned. * * @return a set of all edges outgoing from the specified vertex. */ public Set outgoingEdgesOf(V vertex); } // End DirectedGraph.java jgrapht-0.8.3/src/org/jgrapht/GraphHelper.java0000644000175000017500000000362711706124626021465 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ---------------- * GraphHelper.java * ---------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * Mikael Hansen * * $Id: GraphHelper.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 10-Jul-2003 : Initial revision (BN); * 06-Nov-2003 : Change edge sharing semantics (JVS); * 11-Mar-2004 : Made generic (CH); * 07-May-2006 : Changed from List to Set (JVS); * 28-May-2006 : Moved connectivity info from edge to graph (JVS); * */ package org.jgrapht; /** * A collection of utilities to assist the working with graphs. * * @author Barak Naveh * @since Jul 31, 2003 * @deprecated Use {@link Graphs} instead. */ @Deprecated public abstract class GraphHelper extends Graphs { } // End GraphHelper.java jgrapht-0.8.3/src/org/jgrapht/VertexFactory.java0000644000175000017500000000374311706124626022070 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * VertexFactory.java * ------------------ * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Christian Hammer * * $Id: VertexFactory.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 16-Sep-2003 : Initial revision (JVS); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht; /** * A vertex factory used by graph algorithms for creating new vertices. * Normally, vertices are constructed by user code and added to a graph * explicitly, but algorithms which generate new vertices require a factory. * * @author John V. Sichi * @since Sep 16, 2003 */ public interface VertexFactory { //~ Methods ---------------------------------------------------------------- /** * Creates a new vertex. * * @return the new vertex */ public V createVertex(); } // End VertexFactory.java jgrapht-0.8.3/src/org/jgrapht/ListenableGraph.java0000644000175000017500000000527411706124626022330 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------- * ListenableGraph.java * -------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: ListenableGraph.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 10-Aug-2003 : Adaptation to new event model (BN); * 11-Mar-2004 : Made generic (CH); * */ package org.jgrapht; import org.jgrapht.event.*; /** * A graph that supports listeners on structural change events. * * @author Barak Naveh * @see GraphListener * @see VertexSetListener * @since Jul 20, 2003 */ public interface ListenableGraph extends Graph { //~ Methods ---------------------------------------------------------------- /** * Adds the specified graph listener to this graph, if not already present. * * @param l the listener to be added. */ public void addGraphListener(GraphListener l); /** * Adds the specified vertex set listener to this graph, if not already * present. * * @param l the listener to be added. */ public void addVertexSetListener(VertexSetListener l); /** * Removes the specified graph listener from this graph, if present. * * @param l the listener to be removed. */ public void removeGraphListener(GraphListener l); /** * Removes the specified vertex set listener from this graph, if present. * * @param l the listener to be removed. */ public void removeVertexSetListener(VertexSetListener l); } // End ListenableGraph.java jgrapht-0.8.3/src/org/jgrapht/traverse/0000755000175000017500000000000011752244360020243 5ustar giovannigiovannijgrapht-0.8.3/src/org/jgrapht/traverse/package.html0000644000175000017500000000015511706124626022526 0ustar giovannigiovanni Graph traversal means. jgrapht-0.8.3/src/org/jgrapht/traverse/AbstractGraphIterator.java0000644000175000017500000001440011706124626025345 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (barak_naveh@users.sourceforge.net) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* -------------------------- * AbstractGraphIterator.java * -------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: AbstractGraphIterator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 11-Aug-2003 : Adaptation to new event model (BN); * 04-May-2004 : Made generic (CH) * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.event.*; /** * An empty implementation of a graph iterator to minimize the effort required * to implement graph iterators. * * @author Barak Naveh * @since Jul 19, 2003 */ public abstract class AbstractGraphIterator implements GraphIterator { //~ Instance fields -------------------------------------------------------- private List> traversalListeners = new ArrayList>(); private boolean crossComponentTraversal = true; private boolean reuseEvents = false; // We keep this cached redundantly with traversalListeners.size() // so that subclasses can use it as a fast check to see if // event firing calls can be skipped. protected int nListeners = 0; //~ Methods ---------------------------------------------------------------- /** * Sets the cross component traversal flag - indicates whether to traverse * the graph across connected components. * * @param crossComponentTraversal if true traverses across * connected components. */ public void setCrossComponentTraversal(boolean crossComponentTraversal) { this.crossComponentTraversal = crossComponentTraversal; } /** * Test whether this iterator is set to traverse the graph across connected * components. * * @return true if traverses across connected components, * otherwise false. */ public boolean isCrossComponentTraversal() { return crossComponentTraversal; } /** * @see GraphIterator#setReuseEvents(boolean) */ public void setReuseEvents(boolean reuseEvents) { this.reuseEvents = reuseEvents; } /** * @see GraphIterator#isReuseEvents() */ public boolean isReuseEvents() { return reuseEvents; } /** * Adds the specified traversal listener to this iterator. * * @param l the traversal listener to be added. */ public void addTraversalListener(TraversalListener l) { if (!traversalListeners.contains(l)) { traversalListeners.add(l); nListeners = traversalListeners.size(); } } /** * Unsupported. * * @throws UnsupportedOperationException */ public void remove() { throw new UnsupportedOperationException(); } /** * Removes the specified traversal listener from this iterator. * * @param l the traversal listener to be removed. */ public void removeTraversalListener(TraversalListener l) { traversalListeners.remove(l); nListeners = traversalListeners.size(); } /** * Informs all listeners that the traversal of the current connected * component finished. * * @param e the connected component finished event. */ protected void fireConnectedComponentFinished( ConnectedComponentTraversalEvent e) { for (int i = 0; i < nListeners; i++) { TraversalListener l = traversalListeners.get(i); l.connectedComponentFinished(e); } } /** * Informs all listeners that a traversal of a new connected component has * started. * * @param e the connected component started event. */ protected void fireConnectedComponentStarted( ConnectedComponentTraversalEvent e) { for (int i = 0; i < nListeners; i++) { TraversalListener l = traversalListeners.get(i); l.connectedComponentStarted(e); } } /** * Informs all listeners that a the specified edge was visited. * * @param e the edge traversal event. */ protected void fireEdgeTraversed(EdgeTraversalEvent e) { for (int i = 0; i < nListeners; i++) { TraversalListener l = traversalListeners.get(i); l.edgeTraversed(e); } } /** * Informs all listeners that a the specified vertex was visited. * * @param e the vertex traversal event. */ protected void fireVertexTraversed(VertexTraversalEvent e) { for (int i = 0; i < nListeners; i++) { TraversalListener l = traversalListeners.get(i); l.vertexTraversed(e); } } /** * Informs all listeners that a the specified vertex was finished. * * @param e the vertex traversal event. */ protected void fireVertexFinished(VertexTraversalEvent e) { for (int i = 0; i < nListeners; i++) { TraversalListener l = traversalListeners.get(i); l.vertexFinished(e); } } } // End AbstractGraphIterator.java jgrapht-0.8.3/src/org/jgrapht/traverse/ClosestFirstIterator.java0000644000175000017500000002505611706124626025255 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * ClosestFirstIterator.java * ------------------------- * (C) Copyright 2003-2008, by John V. Sichi and Contributors. * * Original Author: John V. Sichi * Contributor(s): Barak Naveh * * $Id: ClosestFirstIterator.java 697 2009-09-08 22:21:13Z perfecthash $ * * Changes * ------- * 02-Sep-2003 : Initial revision (JVS); * 31-Jan-2004 : Reparented and changed interface to parent class (BN); * 29-May-2005 : Added radius support (JVS); * 06-Jun-2005 : Made generic (CH); * */ package org.jgrapht.traverse; import org.jgrapht.*; import org.jgrapht.util.*; /** * A closest-first iterator for a directed or undirected graph. For this * iterator to work correctly the graph must not be modified during iteration. * Currently there are no means to ensure that, nor to fail-fast. The results of * such modifications are undefined. * *

    The metric for closest here is the path length from a start vertex. * Graph.getEdgeWeight(Edge) is summed to calculate path length. Negative edge * weights will result in an IllegalArgumentException. Optionally, path length * may be bounded by a finite radius.

    * * @author John V. Sichi * @since Sep 2, 2003 */ public class ClosestFirstIterator extends CrossComponentIterator>> { //~ Instance fields -------------------------------------------------------- /** * Priority queue of fringe vertices. */ private FibonacciHeap> heap = new FibonacciHeap>(); /** * Maximum distance to search. */ private double radius = Double.POSITIVE_INFINITY; private boolean initialized = false; //~ Constructors ----------------------------------------------------------- /** * Creates a new closest-first iterator for the specified graph. * * @param g the graph to be iterated. */ public ClosestFirstIterator(Graph g) { this(g, null); } /** * Creates a new closest-first iterator for the specified graph. Iteration * will start at the specified start vertex and will be limited to the * connected component that includes that vertex. If the specified start * vertex is null, iteration will start at an arbitrary vertex * and will not be limited, that is, will be able to traverse all the graph. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. */ public ClosestFirstIterator(Graph g, V startVertex) { this(g, startVertex, Double.POSITIVE_INFINITY); } /** * Creates a new radius-bounded closest-first iterator for the specified * graph. Iteration will start at the specified start vertex and will be * limited to the subset of the connected component which includes that * vertex and is reachable via paths of length less than or equal to the * specified radius. The specified start vertex may not be * null. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. * @param radius limit on path length, or Double.POSITIVE_INFINITY for * unbounded search. */ public ClosestFirstIterator(Graph g, V startVertex, double radius) { super(g, startVertex); this.radius = radius; checkRadiusTraversal(isCrossComponentTraversal()); initialized = true; } //~ Methods ---------------------------------------------------------------- // override AbstractGraphIterator public void setCrossComponentTraversal(boolean crossComponentTraversal) { if (initialized) { checkRadiusTraversal(crossComponentTraversal); } super.setCrossComponentTraversal(crossComponentTraversal); } /** * Get the length of the shortest path known to the given vertex. If the * vertex has already been visited, then it is truly the shortest path * length; otherwise, it is the best known upper bound. * * @param vertex vertex being sought from start vertex * * @return length of shortest path known, or Double.POSITIVE_INFINITY if no * path found yet */ public double getShortestPathLength(V vertex) { FibonacciHeapNode> node = getSeenData(vertex); if (node == null) { return Double.POSITIVE_INFINITY; } return node.getKey(); } /** * Get the spanning tree edge reaching a vertex which has been seen already * in this traversal. This edge is the last link in the shortest known path * between the start vertex and the requested vertex. If the vertex has * already been visited, then it is truly the minimum spanning tree edge; * otherwise, it is the best candidate seen so far. * * @param vertex the spanned vertex. * * @return the spanning tree edge, or null if the vertex either has not been * seen yet or is the start vertex. */ public E getSpanningTreeEdge(V vertex) { FibonacciHeapNode> node = getSeenData(vertex); if (node == null) { return null; } return node.getData().spanningTreeEdge; } /** * @see CrossComponentIterator#isConnectedComponentExhausted() */ protected boolean isConnectedComponentExhausted() { if (heap.size() == 0) { return true; } else { if (heap.min().getKey() > radius) { heap.clear(); return true; } else { return false; } } } /** * @see CrossComponentIterator#encounterVertex(Object, Object) */ protected void encounterVertex(V vertex, E edge) { double shortestPathLength; if (edge == null) { shortestPathLength = 0; } else { shortestPathLength = calculatePathLength(vertex, edge); } FibonacciHeapNode> node = createSeenData(vertex, edge); putSeenData(vertex, node); heap.insert(node, shortestPathLength); } /** * Override superclass. When we see a vertex again, we need to see if the * new edge provides a shorter path than the old edge. * * @param vertex the vertex re-encountered * @param edge the edge via which the vertex was re-encountered */ protected void encounterVertexAgain(V vertex, E edge) { FibonacciHeapNode> node = getSeenData(vertex); if (node.getData().frozen) { // no improvement for this vertex possible return; } double candidatePathLength = calculatePathLength(vertex, edge); if (candidatePathLength < node.getKey()) { node.getData().spanningTreeEdge = edge; heap.decreaseKey(node, candidatePathLength); } } /** * @see CrossComponentIterator#provideNextVertex() */ protected V provideNextVertex() { FibonacciHeapNode> node = heap.removeMin(); node.getData().frozen = true; return node.getData().vertex; } private void assertNonNegativeEdge(E edge) { if (getGraph().getEdgeWeight(edge) < 0) { throw new IllegalArgumentException( "negative edge weights not allowed"); } } /** * Determine path length to a vertex via an edge, using the path length for * the opposite vertex. * * @param vertex the vertex for which to calculate the path length. * @param edge the edge via which the path is being extended. * * @return calculated path length. */ private double calculatePathLength(V vertex, E edge) { assertNonNegativeEdge(edge); V otherVertex = Graphs.getOppositeVertex(getGraph(), edge, vertex); FibonacciHeapNode> otherEntry = getSeenData(otherVertex); return otherEntry.getKey() + getGraph().getEdgeWeight(edge); } private void checkRadiusTraversal(boolean crossComponentTraversal) { if (crossComponentTraversal && (radius != Double.POSITIVE_INFINITY)) { throw new IllegalArgumentException( "radius may not be specified for cross-component traversal"); } } /** * The first time we see a vertex, make up a new heap node for it. * * @param vertex a vertex which has just been encountered. * @param edge the edge via which the vertex was encountered. * * @return the new heap node. */ private FibonacciHeapNode> createSeenData( V vertex, E edge) { QueueEntry entry = new QueueEntry(); entry.vertex = vertex; entry.spanningTreeEdge = edge; return new FibonacciHeapNode>(entry); } //~ Inner Classes ---------------------------------------------------------- /** * Private data to associate with each entry in the priority queue. */ static class QueueEntry { /** * Best spanning tree edge to vertex seen so far. */ E spanningTreeEdge; /** * The vertex reached. */ V vertex; /** * True once spanningTreeEdge is guaranteed to be the true minimum. */ boolean frozen; QueueEntry() { } } } // End ClosestFirstIterator.java jgrapht-0.8.3/src/org/jgrapht/traverse/DepthFirstIterator.java0000644000175000017500000001641511706124626024704 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------- * DepthFirstIterator.java * ----------------------- * (C) Copyright 2003-2008, by Liviu Rau and Contributors. * * Original Author: Liviu Rau * Contributor(s): Barak Naveh * Christian Hammer * Welson Sun * Ross Judson * * $Id: DepthFirstIterator.java 686 2009-07-01 18:27:21Z perfecthash $ * * Changes * ------- * 29-Jul-2003 : Initial revision (LR); * 31-Jul-2003 : Fixed traversal across connected components (BN); * 06-Aug-2003 : Extracted common logic to TraverseUtils.XXFirstIterator (BN); * 31-Jan-2004 : Reparented and changed interface to parent class (BN); * 04-May-2004 : Made generic (CH) * 27-Aug-2006 : Added WHITE/GRAY/BLACK to fix bug reported by Welson Sun (JVS) * 28-Sep-2008 : Optimized using ArrayDeque per suggestion from Ross (JVS) * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * A depth-first iterator for a directed and an undirected graph. For this * iterator to work correctly the graph must not be modified during iteration. * Currently there are no means to ensure that, nor to fail-fast. The results of * such modifications are undefined. * * @author Liviu Rau * @author Barak Naveh * @since Jul 29, 2003 */ public class DepthFirstIterator extends CrossComponentIterator { //~ Static fields/initializers --------------------------------------------- /** * Sentinel object. Unfortunately, we can't use null, because ArrayDeque * won't accept those. And we don't want to rely on the caller to provide a * sentinel object for us. So we have to play typecasting games. */ public static final Object SENTINEL = new Object(); //~ Instance fields -------------------------------------------------------- /** * @see #getStack */ private Deque stack = new ArrayDeque(); private transient TypeUtil vertexTypeDecl = null; //~ Constructors ----------------------------------------------------------- /** * Creates a new depth-first iterator for the specified graph. * * @param g the graph to be iterated. */ public DepthFirstIterator(Graph g) { this(g, null); } /** * Creates a new depth-first iterator for the specified graph. Iteration * will start at the specified start vertex and will be limited to the * connected component that includes that vertex. If the specified start * vertex is null, iteration will start at an arbitrary vertex * and will not be limited, that is, will be able to traverse all the graph. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. */ public DepthFirstIterator(Graph g, V startVertex) { super(g, startVertex); } //~ Methods ---------------------------------------------------------------- /** * @see CrossComponentIterator#isConnectedComponentExhausted() */ protected boolean isConnectedComponentExhausted() { for (;;) { if (stack.isEmpty()) { return true; } if (stack.getLast() != SENTINEL) { // Found a non-sentinel. return false; } // Found a sentinel: pop it, record the finish time, // and then loop to check the rest of the stack. // Pop null we peeked at above. stack.removeLast(); // This will pop corresponding vertex to be recorded as finished. recordFinish(); } } /** * @see CrossComponentIterator#encounterVertex(Object, Object) */ protected void encounterVertex(V vertex, E edge) { putSeenData(vertex, VisitColor.WHITE); stack.addLast(vertex); } /** * @see CrossComponentIterator#encounterVertexAgain(Object, Object) */ protected void encounterVertexAgain(V vertex, E edge) { VisitColor color = getSeenData(vertex); if (color != VisitColor.WHITE) { // We've already visited this vertex; no need to mess with the // stack (either it's BLACK and not there at all, or it's GRAY // and therefore just a sentinel). return; } // Since we've encountered it before, and it's still WHITE, it // *must* be on the stack. Use removeLastOccurrence on the // assumption that for typical topologies and traversals, // it's likely to be nearer the top of the stack than // the bottom of the stack. boolean found = stack.removeLastOccurrence(vertex); assert (found); stack.addLast(vertex); } /** * @see CrossComponentIterator#provideNextVertex() */ protected V provideNextVertex() { V v; for (;;) { Object o = stack.removeLast(); if (o == SENTINEL) { // This is a finish-time sentinel we previously pushed. recordFinish(); // Now carry on with another pop until we find a non-sentinel } else { // Got a real vertex to start working on v = TypeUtil.uncheckedCast(o, vertexTypeDecl); break; } } // Push a sentinel for v onto the stack so that we'll know // when we're done with it. stack.addLast(v); stack.addLast(SENTINEL); putSeenData(v, VisitColor.GRAY); return v; } private void recordFinish() { V v = TypeUtil.uncheckedCast(stack.removeLast(), vertexTypeDecl); putSeenData(v, VisitColor.BLACK); finishVertex(v); } /** * Retrieves the LIFO stack of vertices which have been encountered but not * yet visited (WHITE). This stack also contains sentinel entries * representing vertices which have been visited but are still GRAY. A * sentinel entry is a sequence (v, SENTINEL), whereas a non-sentinel entry * is just (v). * * @return stack */ public Deque getStack() { return stack; } } // End DepthFirstIterator.java jgrapht-0.8.3/src/org/jgrapht/traverse/CrossComponentIterator.java0000644000175000017500000004052611706124626025604 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* --------------------------- * CrossComponentIterator.java * --------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): John V. Sichi * Christian Hammer * * $Id: CrossComponentIterator.java 725 2010-11-26 01:24:28Z perfecthash $ * * Changes * ------- * 31-Jul-2003 : Initial revision (BN); * 11-Aug-2003 : Adaptation to new event model (BN); * 31-Jan-2004 : Extracted cross-component traversal functionality (BN); * 04-May-2004 : Made generic (CH) * 07-May-2006 : Changed from List to Set (JVS); * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.*; import org.jgrapht.event.*; /** * Provides a cross-connected-component traversal functionality for iterator * subclasses. * * @param vertex type * @param edge type * @param type of data associated to seen vertices * * @author Barak Naveh * @since Jan 31, 2004 */ public abstract class CrossComponentIterator extends AbstractGraphIterator { //~ Static fields/initializers --------------------------------------------- private static final int CCS_BEFORE_COMPONENT = 1; private static final int CCS_WITHIN_COMPONENT = 2; private static final int CCS_AFTER_COMPONENT = 3; //~ Enums ------------------------------------------------------------------ /** * Standard vertex visit state enumeration. */ protected static enum VisitColor { /** * Vertex has not been returned via iterator yet. */ WHITE, /** * Vertex has been returned via iterator, but we're not done with all of * its out-edges yet. */ GRAY, /** * Vertex has been returned via iterator, and we're done with all of its * out-edges. */ BLACK } //~ Instance fields -------------------------------------------------------- // private final ConnectedComponentTraversalEvent ccFinishedEvent = new ConnectedComponentTraversalEvent( this, ConnectedComponentTraversalEvent.CONNECTED_COMPONENT_FINISHED); private final ConnectedComponentTraversalEvent ccStartedEvent = new ConnectedComponentTraversalEvent( this, ConnectedComponentTraversalEvent.CONNECTED_COMPONENT_STARTED); // TODO: support ConcurrentModificationException if graph modified // during iteration. private FlyweightEdgeEvent reusableEdgeEvent; private FlyweightVertexEvent reusableVertexEvent; private Iterator vertexIterator = null; /** * Stores the vertices that have been seen during iteration and (optionally) * some additional traversal info regarding each vertex. */ private Map seen = new HashMap(); private V startVertex; private Specifics specifics; private final Graph graph; /** * The connected component state */ private int state = CCS_BEFORE_COMPONENT; //~ Constructors ----------------------------------------------------------- /** * Creates a new iterator for the specified graph. Iteration will start at * the specified start vertex. If the specified start vertex is * null, Iteration will start at an arbitrary graph vertex. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. * * @throws IllegalArgumentException if g==null or does not * contain startVertex */ public CrossComponentIterator(Graph g, V startVertex) { super(); if (g == null) { throw new IllegalArgumentException("graph must not be null"); } graph = g; specifics = createGraphSpecifics(g); vertexIterator = g.vertexSet().iterator(); setCrossComponentTraversal(startVertex == null); reusableEdgeEvent = new FlyweightEdgeEvent(this, null); reusableVertexEvent = new FlyweightVertexEvent(this, null); if (startVertex == null) { // pick a start vertex if graph not empty if (vertexIterator.hasNext()) { this.startVertex = vertexIterator.next(); } else { this.startVertex = null; } } else if (g.containsVertex(startVertex)) { this.startVertex = startVertex; } else { throw new IllegalArgumentException( "graph must contain the start vertex"); } } //~ Methods ---------------------------------------------------------------- /** * @return the graph being traversed */ public Graph getGraph() { return graph; } /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { if (startVertex != null) { encounterStartVertex(); } if (isConnectedComponentExhausted()) { if (state == CCS_WITHIN_COMPONENT) { state = CCS_AFTER_COMPONENT; if (nListeners != 0) { fireConnectedComponentFinished(ccFinishedEvent); } } if (isCrossComponentTraversal()) { while (vertexIterator.hasNext()) { V v = vertexIterator.next(); if (!isSeenVertex(v)) { encounterVertex(v, null); state = CCS_BEFORE_COMPONENT; return true; } } return false; } else { return false; } } else { return true; } } /** * @see java.util.Iterator#next() */ public V next() { if (startVertex != null) { encounterStartVertex(); } if (hasNext()) { if (state == CCS_BEFORE_COMPONENT) { state = CCS_WITHIN_COMPONENT; if (nListeners != 0) { fireConnectedComponentStarted(ccStartedEvent); } } V nextVertex = provideNextVertex(); if (nListeners != 0) { fireVertexTraversed(createVertexTraversalEvent(nextVertex)); } addUnseenChildrenOf(nextVertex); return nextVertex; } else { throw new NoSuchElementException(); } } /** * Returns true if there are no more uniterated vertices in the * currently iterated connected component; false otherwise. * * @return true if there are no more uniterated vertices in the * currently iterated connected component; false otherwise. */ protected abstract boolean isConnectedComponentExhausted(); /** * Update data structures the first time we see a vertex. * * @param vertex the vertex encountered * @param edge the edge via which the vertex was encountered, or null if the * vertex is a starting point */ protected abstract void encounterVertex(V vertex, E edge); /** * Returns the vertex to be returned in the following call to the iterator * next method. * * @return the next vertex to be returned by this iterator. */ protected abstract V provideNextVertex(); /** * Access the data stored for a seen vertex. * * @param vertex a vertex which has already been seen. * * @return data associated with the seen vertex or null if no * data was associated with the vertex. A null return can also * indicate that the vertex was explicitly associated with * null. */ protected D getSeenData(V vertex) { return seen.get(vertex); } /** * Determines whether a vertex has been seen yet by this traversal. * * @param vertex vertex in question * * @return true if vertex has already been seen */ protected boolean isSeenVertex(Object vertex) { return seen.containsKey(vertex); } /** * Called whenever we re-encounter a vertex. The default implementation does * nothing. * * @param vertex the vertex re-encountered * @param edge the edge via which the vertex was re-encountered */ protected abstract void encounterVertexAgain(V vertex, E edge); /** * Stores iterator-dependent data for a vertex that has been seen. * * @param vertex a vertex which has been seen. * @param data data to be associated with the seen vertex. * * @return previous value associated with specified vertex or * null if no data was associated with the vertex. A * null return can also indicate that the vertex was explicitly * associated with null. */ protected D putSeenData(V vertex, D data) { return seen.put(vertex, data); } /** * Called when a vertex has been finished (meaning is dependent on traversal * represented by subclass). * * @param vertex vertex which has been finished */ protected void finishVertex(V vertex) { if (nListeners != 0) { fireVertexFinished(createVertexTraversalEvent(vertex)); } } // ------------------------------------------------------------------------- /** * @param * @param * @param g * * @return TODO Document me */ static Specifics createGraphSpecifics(Graph g) { if (g instanceof DirectedGraph) { return new DirectedSpecifics((DirectedGraph) g); } else { return new UndirectedSpecifics(g); } } private void addUnseenChildrenOf(V vertex) { for (E edge : specifics.edgesOf(vertex)) { if (nListeners != 0) { fireEdgeTraversed(createEdgeTraversalEvent(edge)); } V oppositeV = Graphs.getOppositeVertex(graph, edge, vertex); if (isSeenVertex(oppositeV)) { encounterVertexAgain(oppositeV, edge); } else { encounterVertex(oppositeV, edge); } } } private EdgeTraversalEvent createEdgeTraversalEvent(E edge) { if (isReuseEvents()) { reusableEdgeEvent.setEdge(edge); return reusableEdgeEvent; } else { return new EdgeTraversalEvent(this, edge); } } private VertexTraversalEvent createVertexTraversalEvent(V vertex) { if (isReuseEvents()) { reusableVertexEvent.setVertex(vertex); return reusableVertexEvent; } else { return new VertexTraversalEvent(this, vertex); } } private void encounterStartVertex() { encounterVertex(startVertex, null); startVertex = null; } //~ Inner Interfaces ------------------------------------------------------- static interface SimpleContainer { /** * Tests if this container is empty. * * @return true if empty, otherwise false. */ public boolean isEmpty(); /** * Adds the specified object to this container. * * @param o the object to be added. */ public void add(T o); /** * Remove an object from this container and return it. * * @return the object removed from this container. */ public T remove(); } //~ Inner Classes ---------------------------------------------------------- /** * Provides unified interface for operations that are different in directed * graphs and in undirected graphs. */ abstract static class Specifics { /** * Returns the edges outgoing from the specified vertex in case of * directed graph, and the edge touching the specified vertex in case of * undirected graph. * * @param vertex the vertex whose outgoing edges are to be returned. * * @return the edges outgoing from the specified vertex in case of * directed graph, and the edge touching the specified vertex in case of * undirected graph. */ public abstract Set edgesOf(VV vertex); } /** * A reusable edge event. * * @author Barak Naveh * @since Aug 11, 2003 */ static class FlyweightEdgeEvent extends EdgeTraversalEvent { private static final long serialVersionUID = 4051327833765000755L; /** * @see EdgeTraversalEvent#EdgeTraversalEvent(Object, Edge) */ public FlyweightEdgeEvent(Object eventSource, localE edge) { super(eventSource, edge); } /** * Sets the edge of this event. * * @param edge the edge to be set. */ protected void setEdge(localE edge) { this.edge = edge; } } /** * A reusable vertex event. * * @author Barak Naveh * @since Aug 11, 2003 */ static class FlyweightVertexEvent extends VertexTraversalEvent { private static final long serialVersionUID = 3834024753848399924L; /** * @see VertexTraversalEvent#VertexTraversalEvent(Object, Object) */ public FlyweightVertexEvent(Object eventSource, VV vertex) { super(eventSource, vertex); } /** * Sets the vertex of this event. * * @param vertex the vertex to be set. */ protected void setVertex(VV vertex) { this.vertex = vertex; } } /** * An implementation of {@link Specifics} for a directed graph. */ private static class DirectedSpecifics extends Specifics { private DirectedGraph graph; /** * Creates a new DirectedSpecifics object. * * @param g the graph for which this specifics object to be created. */ public DirectedSpecifics(DirectedGraph g) { graph = g; } /** * @see CrossComponentIterator.Specifics#edgesOf(Object) */ public Set edgesOf(VV vertex) { return graph.outgoingEdgesOf(vertex); } } /** * An implementation of {@link Specifics} in which edge direction (if any) * is ignored. */ private static class UndirectedSpecifics extends Specifics { private Graph graph; /** * Creates a new UndirectedSpecifics object. * * @param g the graph for which this specifics object to be created. */ public UndirectedSpecifics(Graph g) { graph = g; } /** * @see CrossComponentIterator.Specifics#edgesOf(Object) */ public Set edgesOf(VV vertex) { return graph.edgesOf(vertex); } } } // End CrossComponentIterator.java jgrapht-0.8.3/src/org/jgrapht/traverse/TopologicalOrderIterator.java0000644000175000017500000002160211706124626026072 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ----------------------------- * TopologicalOrderIterator.java * ----------------------------- * (C) Copyright 2004-2008, by Marden Neubert and Contributors. * * Original Author: Marden Neubert * Contributor(s): Barak Naveh, John V. Sichi * * $Id: TopologicalOrderIterator.java 716 2010-07-13 04:48:20Z perfecthash $ * * Changes * ------- * 17-Dec-2004 : Initial revision (MN); * 25-Apr-2005 : Fixes for start vertex order (JVS); * 06-Jun-2005 : Made generic (CH); * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.*; import org.jgrapht.util.*; /** * Implements topological order traversal for a directed acyclic graph. A * topological sort is a permutation p of the vertices of a graph such * that an edge (i,j) implies that i appears before j * in p (Skiena 1990, p. 208). See also * http://mathworld.wolfram.com/TopologicalSort.html. * *

    See "Algorithms in Java, Third Edition, Part 5: Graph Algorithms" by * Robert Sedgewick and "Data Structures and Algorithms with Object-Oriented * Design Patterns in Java" by Bruno R. Preiss for implementation alternatives. * The latter can be found online at * http://www.brpreiss.com/books/opus5/

    * *

    For this iterator to work correctly the graph must be acyclic, and must * not be modified during iteration. Currently there are no means to ensure * that, nor to fail-fast; the results with cyclic input (including self-loops) * or concurrent modifications are undefined. To precheck a graph for cycles, * consider using {@link org.jgrapht.alg.CycleDetector} or {@link * org.jgrapht.alg.StrongConnectivityInspector}.

    * * @author Marden Neubert * @since Dec 18, 2004 */ public class TopologicalOrderIterator extends CrossComponentIterator { //~ Instance fields -------------------------------------------------------- private Queue queue; private Map inDegreeMap; //~ Constructors ----------------------------------------------------------- /** * Creates a new topological order iterator over the directed graph * specified, with arbitrary tie-breaking in case of partial order. * Traversal will start at one of the graph's sources. See the * definition of source at * http://mathworld.wolfram.com/Source.html. * * @param dg the directed graph to be iterated. */ public TopologicalOrderIterator(DirectedGraph dg) { this(dg, new LinkedListQueue()); } /** * Creates a new topological order iterator over the directed graph * specified, with a user-supplied queue implementation to allow customized * control over tie-breaking in case of partial order. Traversal will start * at one of the graph's sources. See the definition of source at * http://mathworld.wolfram.com/Source.html. * * @param dg the directed graph to be iterated. * @param queue queue to use for tie-break in case of partial order (e.g. a * PriorityQueue can be used to break ties according to vertex priority); * must be initially empty */ public TopologicalOrderIterator(DirectedGraph dg, Queue queue) { this(dg, queue, new HashMap()); } // NOTE: This is a hack to deal with the fact that CrossComponentIterator // needs to know the start vertex in its constructor private TopologicalOrderIterator( DirectedGraph dg, Queue queue, Map inDegreeMap) { this(dg, initialize(dg, queue, inDegreeMap)); this.queue = queue; this.inDegreeMap = inDegreeMap; // empty queue for non-empty graph would indicate presence of // cycles (no roots found) assert dg.vertexSet().isEmpty() || !queue.isEmpty(); } // NOTE: This is intentionally private, because starting the sort "in the // middle" doesn't make sense. private TopologicalOrderIterator(DirectedGraph dg, V start) { super(dg, start); } //~ Methods ---------------------------------------------------------------- /** * @see CrossComponentIterator#isConnectedComponentExhausted() */ protected boolean isConnectedComponentExhausted() { // FIXME jvs 25-Apr-2005: This isn't correct for a graph with more than // one component. We will actually exhaust a connected component // before the queue is empty, because initialize adds roots from all // components to the queue. return queue.isEmpty(); } /** * @see CrossComponentIterator#encounterVertex(Object, Object) */ protected void encounterVertex(V vertex, E edge) { putSeenData(vertex, null); decrementInDegree(vertex); } /** * @see CrossComponentIterator#encounterVertexAgain(Object, Object) */ protected void encounterVertexAgain(V vertex, E edge) { decrementInDegree(vertex); } /** * @see CrossComponentIterator#provideNextVertex() */ protected V provideNextVertex() { return queue.remove(); } /** * Decrements the in-degree of a vertex. * * @param vertex the vertex whose in-degree will be decremented. */ private void decrementInDegree(V vertex) { ModifiableInteger inDegree = inDegreeMap.get(vertex); if (inDegree.value > 0) { inDegree.value--; if (inDegree.value == 0) { queue.offer(vertex); } } } /** * Initializes the internal traversal object structure. Sets up the internal * queue with the directed graph vertices and creates the control structure * for the in-degrees. * * @param dg the directed graph to be iterated. * @param queue initializer for queue * @param inDegreeMap initializer for inDegreeMap * * @return start vertex */ private static V initialize( DirectedGraph dg, Queue queue, Map inDegreeMap) { for (Iterator i = dg.vertexSet().iterator(); i.hasNext();) { V vertex = i.next(); int inDegree = dg.inDegreeOf(vertex); inDegreeMap.put(vertex, new ModifiableInteger(inDegree)); if (inDegree == 0) { queue.offer(vertex); } } if (queue.isEmpty()) { return null; } else { return queue.peek(); } } //~ Inner Classes ---------------------------------------------------------- // NOTE jvs 22-Dec-2006: For JDK1.4-compatibility, we can't assume // that LinkedList implements Queue, since that wasn't introduced // until JDK1.5, so use an adapter here. Move this to // top-level in org.jgrapht.util if anyone else needs it. private static class LinkedListQueue extends LinkedList implements Queue { private static final long serialVersionUID = 4217659843476891334L; public T element() { return getFirst(); } public boolean offer(T o) { return add(o); } public T peek() { if (isEmpty()) { return null; } return getFirst(); } public T poll() { if (isEmpty()) { return null; } return removeFirst(); } public T remove() { return removeFirst(); } } } // End TopologicalOrderIterator.java jgrapht-0.8.3/src/org/jgrapht/traverse/BreadthFirstIterator.java0000644000175000017500000001002411706124626025177 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * BreadthFirstIterator.java * ------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Liviu Rau * Christian Hammer * Ross Judson * * $Id: BreadthFirstIterator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * 06-Aug-2003 : Extracted common logic to TraverseUtils.XXFirstIterator (BN); * 31-Jan-2004 : Reparented and changed interface to parent class (BN); * 28-Sep-2008 : Optimized using ArrayDeque per suggestion from Ross (JVS) * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.*; /** * A breadth-first iterator for a directed and an undirected graph. For this * iterator to work correctly the graph must not be modified during iteration. * Currently there are no means to ensure that, nor to fail-fast. The results of * such modifications are undefined. * * @author Barak Naveh * @since Jul 19, 2003 */ public class BreadthFirstIterator extends CrossComponentIterator { //~ Instance fields -------------------------------------------------------- private Deque queue = new ArrayDeque(); //~ Constructors ----------------------------------------------------------- /** * Creates a new breadth-first iterator for the specified graph. * * @param g the graph to be iterated. */ public BreadthFirstIterator(Graph g) { this(g, null); } /** * Creates a new breadth-first iterator for the specified graph. Iteration * will start at the specified start vertex and will be limited to the * connected component that includes that vertex. If the specified start * vertex is null, iteration will start at an arbitrary vertex * and will not be limited, that is, will be able to traverse all the graph. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. */ public BreadthFirstIterator(Graph g, V startVertex) { super(g, startVertex); } //~ Methods ---------------------------------------------------------------- /** * @see CrossComponentIterator#isConnectedComponentExhausted() */ protected boolean isConnectedComponentExhausted() { return queue.isEmpty(); } /** * @see CrossComponentIterator#encounterVertex(Object, Object) */ protected void encounterVertex(V vertex, E edge) { putSeenData(vertex, null); queue.add(vertex); } /** * @see CrossComponentIterator#encounterVertexAgain(Object, Object) */ protected void encounterVertexAgain(V vertex, E edge) { } /** * @see CrossComponentIterator#provideNextVertex() */ protected V provideNextVertex() { return queue.removeFirst(); } } // End BreadthFirstIterator.java jgrapht-0.8.3/src/org/jgrapht/traverse/GraphIterator.java0000644000175000017500000000712011706124626023662 0ustar giovannigiovanni/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (barak_naveh@users.sourceforge.net) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * GraphIterator.java * ------------------ * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphIterator.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 31-Jul-2003 : Initial revision (BN); * 11-Aug-2003 : Adaptation to new event model (BN); * 04-May-2004 : Made generic (CH) * */ package org.jgrapht.traverse; import java.util.*; import org.jgrapht.event.*; /** * A graph iterator. * * @author Barak Naveh * @since Jul 31, 2003 */ public interface GraphIterator extends Iterator { //~ Methods ---------------------------------------------------------------- /** * Test whether this iterator is set to traverse the grpah across connected * components. * * @return true if traverses across connected components, * otherwise false. */ public boolean isCrossComponentTraversal(); /** * Sets a value the reuseEvents flag. If the * reuseEvents flag is set to true this class will reuse * previously fired events and will not create a new object for each event. * This option increases performance but should be used with care, * especially in multithreaded environment. * * @param reuseEvents whether to reuse previously fired event objects * instead of creating a new event object for each event. */ public void setReuseEvents(boolean reuseEvents); /** * Tests whether the reuseEvents flag is set. If the flag is * set to true this class will reuse previously fired events * and will not create a new object for each event. This option increases * performance but should be used with care, especially in multithreaded * environment. * * @return the value of the reuseEvents flag. */ public boolean isReuseEvents(); /** * Adds the specified traversal listener to this iterator. * * @param l the traversal listener to be added. */ public void addTraversalListener(TraversalListener l); /** * Unsupported. * * @throws UnsupportedOperationException */ public void remove(); /** * Removes the specified traversal listener from this iterator. * * @param l the traversal listener to be removed. */ public void removeTraversalListener(TraversalListener l); } // End GraphIterator.java jgrapht-0.8.3/src/overview.html0000644000175000017500000000077011706124626016723 0ustar giovannigiovanni JGraphT is a free Java class library that provides mathematical graph-theory objects and algorithms. This is an open-source java graph library that supports a rich gallery of graphs and is designed to be powerful, extensible and easy to use.

    Visit http://jgrapht.sourceforge.net to download and to get the latest info on JGraphT.