Java Code Examples for org.jgrapht.Graph#addEdge()

The following examples show how to use org.jgrapht.Graph#addEdge() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UpdateOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).put("value", "A").build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"),
            ImmutableMap.<String, Object>builder().put("id", 3l).put("value", "C").build());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation, times(2)).executeQuery(eq(connection), queryCaptor.capture());
    final List<String> queries = queryCaptor.getAllValues();
    assertThat(queries.get(0), containsString("MATCH (n1:A {id:1}) SET n1.value=\"A\""));
    assertThat(queries.get(1), containsString("MATCH (n1:A {id:1}),(n2:A {id:2}) MERGE (n1)-[e1:E]->(n2) SET e1.id=3,e1.value=\"C\""));
}
 
Example 2
Source File: SymmetryTools.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts a self alignment into a directed jGraphT of aligned residues,
 * where each vertex is a residue and each edge means the equivalence
 * between the two residues in the self-alignment.
 *
 * @param selfAlignment
 *            AFPChain
 *
 * @return alignment Graph
 */
public static Graph<Integer, DefaultEdge> buildSymmetryGraph(
		AFPChain selfAlignment) {

	Graph<Integer, DefaultEdge> graph = new SimpleGraph<Integer, DefaultEdge>(
			DefaultEdge.class);

	for (int i = 0; i < selfAlignment.getOptAln().length; i++) {
		for (int j = 0; j < selfAlignment.getOptAln()[i][0].length; j++) {
			Integer res1 = selfAlignment.getOptAln()[i][0][j];
			Integer res2 = selfAlignment.getOptAln()[i][1][j];
			graph.addVertex(res1);
			graph.addVertex(res2);
			graph.addEdge(res1, res2);
		}
	}
	return graph;
}
 
Example 3
Source File: DagChecker.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean tryAdd(Set<? extends T> roots, Graph<T, Pair> graph, Set<T> knownNodes,
                       CycleDetector<T, Pair> cycleDetector, Deque<T> nodePath)
{
    for (T node : roots) {
        nodePath.addLast(node);
        graph.addVertex(node);
        if (knownNodes.add(node)) {
            Set<? extends T> nodesFrom = nodesFrom(node);
            for (T from : nodesFrom) {
                graph.addVertex(from);
                Pair edge = new Pair(from, node);
                graph.addEdge(from, node, edge);
                nodePath.addLast(from);
                if (cycleDetector.detectCycles())
                    return false;
                nodePath.removeLast();
            }
            if (!tryAdd(nodesFrom, graph, knownNodes, cycleDetector, nodePath))
                return false;
        }
        nodePath.removeLast();
    }
    return true;
}
 
Example 4
Source File: RefreshOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).put("value", "A").build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"),
            ImmutableMap.<String, Object>builder().put("id", 3l).put("value", "C").build());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation, times(3)).executeQuery(eq(connection), queryCaptor.capture());
    final List<String> queries = queryCaptor.getAllValues();
    assertThat(queries.get(0), containsString("MERGE (n1:A {id:1}) SET n1.value=\"A\""));
    assertThat(queries.get(1), containsString("MERGE (n2:A {id:2})"));
    assertThat(queries.get(2), containsString("MATCH (n1:A {id:1}),(n2:A {id:2}) MERGE (n1)-[e1:E]->(n2) SET e1.id=3,e1.value=\"C\""));
}
 
Example 5
Source File: InsertOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"),
            ImmutableMap.<String, Object>builder().put("id", 3l).build());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation).executeQuery(eq(connection), queryCaptor.capture());
    final String query = queryCaptor.getValue();
    assertThat(query, containsString("CREATE (n1:A {id:1}),(n2:A {id:2}),(n1)-[e1:E {id:3}]->(n2)"));
}
 
Example 6
Source File: QueryGraphBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Adds a single edge to the graph
 * @param graph
 * @param edefEdge
 */
private void addEdgeToGraph(Graph<IModelEntity, Relationship> graph, DefaultEdge edefEdge){
	if(edefEdge!=null){
		Relationship edge = (Relationship)edefEdge;
		IModelEntity src= edge.getSourceEntity();
		IModelEntity target= edge.getTargetEntity();

		if(!vertexes.contains(src)){
			logger.debug("Add the vertex "+src.getName());
			vertexes.add(src);
			graph.addVertex(src);
		}
		if(!vertexes.contains(target)){
			logger.debug("Add the vertex "+src.getName());
			vertexes.add(target);
			graph.addVertex(target);
		}

		logger.debug("Add the edge "+src.getName()+"--"+target.getName());
		graph.addEdge(src, target, edge);
	}
	logger.debug("OUT");
}
 
Example 7
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderingWithSubgraph() {
    String sp1 = "sp1";
    String sp2 = "sp2";
    String sp3 = "sp3";
    String sp4 = "sp4";
    String sp5 = "sp5";

    Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);

    for (String vertex : shuffledList(sp1, sp2, sp3, sp4, sp5)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);
    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);

    ImmutableList<String> sorted = sorter.sortChanges(graph, Lists.mutable.with(sp1, sp2, sp3));

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(3, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3), sorted);
}
 
Example 8
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCycleDetection() {
    SortableDependency sp1 = newVertex("sp1");
    SortableDependency sp2 = newVertex("sp2");
    SortableDependency sp3 = newVertex("sp3");
    SortableDependency sp4 = newVertex("sp4");
    SortableDependency sp5 = newVertex("sp5");
    SortableDependency sp6 = newVertex("sp6");
    SortableDependency sp7 = newVertex("sp7");
    SortableDependency sp8 = newVertex("sp8");

    Graph<SortableDependency, DefaultEdge> graph = new DefaultDirectedGraph<SortableDependency, DefaultEdge>(DefaultEdge.class);
    for (SortableDependency vertex : shuffledList(sp1, sp2, sp3, sp4, sp5, sp6, sp7, sp8)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);
    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);
    graph.addEdge(sp4, sp5);
    graph.addEdge(sp6, sp5);
    graph.addEdge(sp7, sp6);
    graph.addEdge(sp8, sp7);
    graph.addEdge(sp6, sp8);

    try {
        sorter.sortChanges(graph);
        fail("Expecting exception here: " + GraphCycleException.class);
    } catch (GraphCycleException e) {
        verifyCycleExists(e, Sets.immutable.with("sp4", "sp5"));
        verifyCycleExists(e, Sets.immutable.with("sp6", "sp7", "sp8"));
        Verify.assertSize(2, e.getCycleComponents());
    }
}
 
Example 9
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create an internal DataExpr Graph.
 * 
 * @param arg1
 * @return
 */
private static GraphExpr<ExprEdge> createGraph(final IExpr arg1) {
	if (arg1.head().equals(F.Graph) && arg1 instanceof GraphExpr) {
		return (GraphExpr<ExprEdge>) arg1;
	}
	Graph<IExpr, ExprEdge> g;
	GraphType t = arg1.isListOfEdges();
	if (t != null) {
		if (t.isDirected()) {
			g = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
		} else {
			g = new DefaultUndirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
		}

		IAST list = (IAST) arg1;
		for (int i = 1; i < list.size(); i++) {
			IAST edge = list.getAST(i);
			g.addVertex(edge.arg1());
			g.addVertex(edge.arg2());
			g.addEdge(edge.arg1(), edge.arg2());
		}

		return GraphExpr.newInstance(g);
	}

	return null;
}
 
Example 10
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicOrderingWithComparator() {
    SortableDependency sp1 = newVertex("sp1");
    SortableDependency sp2 = newVertex("sp2");
    SortableDependency sp3 = newVertex("sp3");
    SortableDependency sp4 = newVertex("sp4");
    SortableDependency sp5 = newVertex("sp5");

    Graph<SortableDependency, DefaultEdge> graph = new DefaultDirectedGraph<SortableDependency, DefaultEdge>(DefaultEdge.class);

    for (SortableDependency vertex : shuffledList(sp1, sp2, sp3, sp4, sp5)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);
    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);

    ListIterable<SortableDependency> sorted = sorter.sortChanges(graph, Comparators.fromFunctions(new Function<SortableDependency, String>() {
        @Override
        public String valueOf(SortableDependency sortableDependency) {
            return sortableDependency.getChangeKey().getChangeName();
        }
    }));

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(5, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp1)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp3)));
    assertThat(sorted.indexOf(sp4), greaterThan(sorted.indexOf(sp5)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3, sp5, sp4), sorted);
}
 
Example 11
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
private static GraphExpr createGraph(final IAST vertices, final IAST edges) {

		Graph<IExpr, ExprEdge> g;
		GraphType t = edges.isListOfEdges();
		if (t != null) {
			if (t.isDirected()) {
				g = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
			} else {
				g = new DefaultUndirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
			}
			if (vertices.isList()) {
				// Graph<IExpr, IExprEdge> g = new DefaultDirectedGraph<IExpr, IExprEdge>(IExprEdge.class);
				for (int i = 1; i < vertices.size(); i++) {
					g.addVertex(vertices.get(i));
				}
			}

			for (int i = 1; i < edges.size(); i++) {
				IAST edge = edges.getAST(i);
				g.addVertex(edge.arg1());
				g.addVertex(edge.arg2());
				g.addEdge(edge.arg1(), edge.arg2());
			}

			return GraphExpr.newInstance(g);
		}

		return null;
	}
 
Example 12
Source File: QuatSymmetryDetector.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static  Graph<Integer, DefaultEdge> initContactGraph(List<SubunitCluster> clusters){

		Graph<Integer, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);

		// extract Ca coords from every subunit of every cluster.
		// all subunit coords are used for contact evaluation,
		// not only the aligned equivalent residues
		List <Point3d[]> clusterSubunitCoords =
				clusters.stream().
					flatMap(c -> c.getSubunits().stream()).
						map(r -> Calc.atomsToPoints(r.getRepresentativeAtoms())).
						collect(Collectors.toList());

		for (int i = 0; i < clusterSubunitCoords.size(); i++) {
			graph.addVertex(i);
		}

		// pre-compute bounding boxes
		List<BoundingBox> boundingBoxes = new ArrayList<>();
		clusterSubunitCoords.forEach(c -> boundingBoxes.add(new BoundingBox(c)));

		for (int i = 0; i < clusterSubunitCoords.size() - 1; i++) {
			Point3d[] coords1 = clusterSubunitCoords.get(i);
			BoundingBox bb1 = boundingBoxes.get(i);

			for (int j = i + 1; j < clusterSubunitCoords.size(); j++) {
				Point3d[] coords2 = clusterSubunitCoords.get(j);
				BoundingBox bb2 = boundingBoxes.get(j);
				Grid grid = new Grid(CONTACT_GRAPH_DISTANCE_CUTOFF);
				grid.addCoords(coords1, bb1, coords2, bb2);

				if (grid.getIndicesContacts().size() >= CONTACT_GRAPH_MIN_CONTACTS) {
					graph.addEdge(i, j);
				}
			}
		}
		return graph;
	}
 
Example 13
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicOrdering() {
    String sp1 = "sp1";
    String sp2 = "sp2";
    String sp3 = "sp3";
    String sp4 = "sp4";
    String sp5 = "sp5";

    Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);

    for (String vertex : Lists.mutable.with(sp1, sp2, sp3, sp4, sp5).toReversed()) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);
    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);

    ListIterable<String> sorted = sorter.sortChanges(graph);

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(5, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp1)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp3)));
    assertThat(sorted.indexOf(sp4), greaterThan(sorted.indexOf(sp5)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3, sp5, sp4), sorted);
}
 
Example 14
Source File: SubtourSeparatorDemo.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Example on undirected graph
 */
public static void example1(){
	//Define a new Undirected Graph. For simplicity we'll use a simple, unweighted graph, but in reality this class is mainly used
	//in combination with weighted graphs for TSP problems.
	Graph<Integer, DefaultEdge> undirectedGraph=new SimpleGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(undirectedGraph, Arrays.asList(1,2,3,4,5,6));
	undirectedGraph.addEdge(1, 2);
	undirectedGraph.addEdge(2, 3);
	undirectedGraph.addEdge(3, 4);
	undirectedGraph.addEdge(4, 1);
	undirectedGraph.addEdge(1, 5);
	undirectedGraph.addEdge(4, 5);
	undirectedGraph.addEdge(5, 6);
	undirectedGraph.addEdge(2, 6);
	undirectedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(undirectedGraph.getEdge(1,2), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,3), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,4), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,1), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(1,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(5,6), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,6), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(undirectedGraph);
	separator.separateSubtour(edgeValueMap);
	
	System.out.println("Has found a violated subtour: "+separator.hasSubtour());
	System.out.println("Cut value: "+separator.getCutValue());
	System.out.println("Cut set: "+separator.getCutSet());
	//The returned cut set is: {2,3,6}. This leads to the cut: \sum_{e\in \delta{2,3,6}} x_e >=2
}
 
Example 15
Source File: SubtourSeparatorDemo.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Example on directed graph
 */
public static void example2(){
	//Define a new Directed Graph. For simplicity we'll use a simple, unweighted graph.
	Graph<Integer, DefaultEdge> directedGraph=new SimpleDirectedGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(directedGraph, Arrays.asList(1,2,3,4,5,6));
	directedGraph.addEdge(1, 2);
	directedGraph.addEdge(2, 3);
	directedGraph.addEdge(3, 4);
	directedGraph.addEdge(4, 1);
	directedGraph.addEdge(1, 4);
	directedGraph.addEdge(1, 5);
	directedGraph.addEdge(5, 1);
	directedGraph.addEdge(4, 5);
	directedGraph.addEdge(5, 4);
	directedGraph.addEdge(6, 2);
	directedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(directedGraph.getEdge(1,2), 0.0);
	edgeValueMap.put(directedGraph.getEdge(2,3), 1.0);
	edgeValueMap.put(directedGraph.getEdge(3,4), 0.0);
	edgeValueMap.put(directedGraph.getEdge(4,1), 0.5);
	edgeValueMap.put(directedGraph.getEdge(1,4), 0.5);
	edgeValueMap.put(directedGraph.getEdge(1,5), 0.5);
	edgeValueMap.put(directedGraph.getEdge(5,1), 0.5);
	edgeValueMap.put(directedGraph.getEdge(4,5), 0.5);
	edgeValueMap.put(directedGraph.getEdge(5,4), 0.5);
	edgeValueMap.put(directedGraph.getEdge(6,2), 1.0);
	edgeValueMap.put(directedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(directedGraph);
	separator.separateSubtour(edgeValueMap);
	
	System.out.println("Has found a violated subtour: "+separator.hasSubtour());
	System.out.println("Cut value: "+separator.getCutValue());
	System.out.println("Cut set: "+separator.getCutSet());
	//The returned cut set is: {2,3,6}. This leads to the cut: \sum_{e\in \delta{2,3,6}} x_e >=2
}
 
Example 16
Source File: DIMACSImporter.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void generateGraph(
        Graph<V, E> target,
        VertexFactory<V> vertexFactory,
        Map<String, V> 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 (target instanceof WeightedGraph && (edge != null)) {
                double weight = defaultWeight;
                if (cols.length > 3) {
                    weight = Double.parseDouble(cols[3]);
                }
                ((WeightedGraph<V, E>) target).setEdgeWeight(edge, weight);
            }
        }
        cols = skipComments();
    }
}
 
Example 17
Source File: SubtourSeparatorTest.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test 1 - Undirected, incomplete graph with a subtour.
 */
public void testUndirectedGraphWithSubtour(){
	//Define a new Undirected Graph. For simplicity we'll use a simple, unweighted graph, but in reality this class is mainly used
	//in combination with weighted graphs for TSP problems.
	Graph<Integer, DefaultEdge> undirectedGraph=new SimpleGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(undirectedGraph, Arrays.asList(1,2,3,4,5,6));
	undirectedGraph.addEdge(1, 2);
	undirectedGraph.addEdge(2, 3);
	undirectedGraph.addEdge(3, 4);
	undirectedGraph.addEdge(4, 1);
	undirectedGraph.addEdge(1, 5);
	undirectedGraph.addEdge(4, 5);
	undirectedGraph.addEdge(5, 6);
	undirectedGraph.addEdge(2, 6);
	undirectedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(undirectedGraph.getEdge(1,2), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,3), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,4), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,1), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(1,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(5,6), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,6), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(undirectedGraph);
	separator.separateSubtour(edgeValueMap);
	
	assertTrue(separator.hasSubtour());
	assertEquals(0, separator.getCutValue(), PRECISION);
	assertEquals(new HashSet<Integer>(Arrays.asList(2,3,6)), separator.getCutSet());
}
 
Example 18
Source File: SubtourSeparatorTest.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test 2 - Undirected, incomplete graph without a subtour.
 */
public void testUndirectedGraphWithoutSubtour(){
	//Define a new Undirected Graph. For simplicity we'll use a simple, unweighted graph, but in reality this class is mainly used
	//in combination with weighted graphs for TSP problems.
	Graph<Integer, DefaultEdge> undirectedGraph=new SimpleGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(undirectedGraph, Arrays.asList(1,2,3,4,5,6));
	undirectedGraph.addEdge(1, 2);
	undirectedGraph.addEdge(2, 3);
	undirectedGraph.addEdge(3, 4);
	undirectedGraph.addEdge(4, 1);
	undirectedGraph.addEdge(1, 5);
	undirectedGraph.addEdge(4, 5);
	undirectedGraph.addEdge(5, 6);
	undirectedGraph.addEdge(2, 6);
	undirectedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(undirectedGraph.getEdge(1,2), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,3), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,4), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,1), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(1,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(5,6), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,6), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(undirectedGraph);
	separator.separateSubtour(edgeValueMap);
	
	assertFalse(separator.hasSubtour());
	assertEquals(2, separator.getCutValue(), PRECISION);
}
 
Example 19
Source File: SubtourSeparatorTest.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test 3 - Directed, incomplete graph without a subtour.
 */
public void testDirectedGraphWithSubtour(){
	//Define a new Directed Graph. For simplicity we'll use a simple, unweighted graph.
	Graph<Integer, DefaultEdge> directedGraph=new SimpleDirectedGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(directedGraph, Arrays.asList(1,2,3,4,5,6));
	directedGraph.addEdge(1, 2);
	directedGraph.addEdge(2, 3);
	directedGraph.addEdge(3, 4);
	directedGraph.addEdge(4, 1);
	directedGraph.addEdge(1, 4);
	directedGraph.addEdge(1, 5);
	directedGraph.addEdge(5, 1);
	directedGraph.addEdge(4, 5);
	directedGraph.addEdge(5, 4);
	directedGraph.addEdge(6, 2);
	directedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(directedGraph.getEdge(1,2), 0.0);
	edgeValueMap.put(directedGraph.getEdge(2,3), 1.0);
	edgeValueMap.put(directedGraph.getEdge(3,4), 0.0);
	edgeValueMap.put(directedGraph.getEdge(4,1), 0.5);
	edgeValueMap.put(directedGraph.getEdge(1,4), 0.5);
	edgeValueMap.put(directedGraph.getEdge(1,5), 0.5);
	edgeValueMap.put(directedGraph.getEdge(5,1), 0.5);
	edgeValueMap.put(directedGraph.getEdge(4,5), 0.5);
	edgeValueMap.put(directedGraph.getEdge(5,4), 0.5);
	edgeValueMap.put(directedGraph.getEdge(6,2), 1.0);
	edgeValueMap.put(directedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(directedGraph);
	separator.separateSubtour(edgeValueMap);
	
	assertTrue(separator.hasSubtour());
	assertEquals(0, separator.getCutValue(), PRECISION);
	assertEquals(new HashSet<Integer>(Arrays.asList(2,3,6)), separator.getCutSet());
}
 
Example 20
Source File: BitSetBasedSimpleGraphGenerator.java    From JQF with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void generateGraph(Graph<V, E> graph, VertexFactory<V> vertexFactory, Map<String, V> map) {
    // Calculate number of edges to generate
    boolean isDirected = graph instanceof DirectedGraph;
    int numEdges = numEdges(isDirected);

    // Figure out how many random bytes to generate for this purpose
    int numBytes = (numEdges + 7) / 8;  // Equal to ceil(numEdges/8.0)
    byte[] bytes = new byte[numBytes];

    // Generate random bytes
    rng.nextBytes(bytes);

    // Convert to bitset
    BitSet bitSet = BitSet.valueOf(bytes);

    // Generate nodes
    V[] vertices = (V[]) new Object[n];
    for(int i = 0; i < n; ++i) {
        V v = vertexFactory.createVertex();
        graph.addVertex(v);
        vertices[i] = v;
    }

    // Add edges as necessary
    int k = 0;
    for (int i = 0; i < n; i++) {
        V s = vertices[i];
        for (int j = 0; j < i; j++) {
            V t = vertices[j];
            // Get next boolean to decide s --> t
            if (bitSet.get(k++)) {
                graph.addEdge(s, t);
            }

            if (isDirected) {
                // Get next boolean to decide t --> t
                if (bitSet.get(k++)) {
                    graph.addEdge(t, s);
                }
            }
        }
    }
    // Sanity check
    assert(k == numEdges);




}