/*
   * 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<V, E> visitedGraph, VertexData<V> vertexData, Set<V> vertices) {
    Deque<VertexData<V>> stack = new ArrayDeque<VertexData<V>>();
    stack.add(vertexData);

    while (!stack.isEmpty()) {
      VertexData<V> data = stack.removeLast();

      if (!data.isDiscovered()) {
        data.setDiscovered(true);

        if (vertices != null) {
          vertices.add(data.getVertex());
        }

        stack.add(new VertexData1<V>(data, true, true));

        // follow all edges
        for (E edge : visitedGraph.outgoingEdgesOf(data.getVertex())) {
          VertexData<V> 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());
        }
      }
    }
  }
 private static List<String> shortestCycle(DirectedGraph<String, DefaultEdge> graph) {
   FloydWarshallShortestPaths<String, DefaultEdge> floyd = new FloydWarshallShortestPaths<>(graph);
   int minDistance = Integer.MAX_VALUE;
   String minSource = null;
   String minDestination = null;
   for (DefaultEdge edge : graph.edgeSet()) {
     String src = graph.getEdgeSource(edge);
     String dst = graph.getEdgeTarget(edge);
     int dist = (int) Math.round(floyd.shortestDistance(dst, src)); // from dst to src
     if (dist < 0) {
       continue;
     }
     if (dist < minDistance) {
       minDistance = dist;
       minSource = src;
       minDestination = dst;
     }
   }
   if (minSource == null) {
     return null;
   }
   GraphPath<String, DefaultEdge> shortestPath = floyd.getShortestPath(minDestination, minSource);
   List<String> pathVertexList = Graphs.getPathVertexList(shortestPath);
   // note: pathVertexList will be [a, a] instead of [a] when the shortest path is a loop edge
   if (!Objects.equals(shortestPath.getStartVertex(), shortestPath.getEndVertex())) {
     pathVertexList.add(pathVertexList.get(0));
   }
   return pathVertexList;
 }
  @Test
  public void databaseConnectionEstablishedCorrectly() {
    ISqlSchemaFrontend frontend = new H2SchemaFrontend(DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema = frontend.createSqlSchema();
    Set<ISqlElement> tables =
        SqlElementFactory.getSqlElementsOfType(SqlTableVertex.class, schema.vertexSet());
    Set<ISqlElement> columns =
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema.vertexSet());
    ArrayList<ISqlElement> mandatoryColumns = new ArrayList<>();
    int tableCount = tables.size();
    int columnCount = columns.size();

    for (ISqlElement column : columns) {
      if (column.isMandatory() && !isPrimaryKey(schema, column)) {
        mandatoryColumns.add(column);
      }
    }

    assertNotNull(schema);
    assertEquals(7, tableCount);
    assertEquals(29, columnCount);
    assertEquals(
        7,
        TestHelper.getColumnWithConstraint(schema, IColumnConstraint.ConstraintType.PRIMARY_KEY)
            .size());
    assertEquals(1, mandatoryColumns.size());
    assertEquals("[Column] DEPARTMENTS.NAME", mandatoryColumns.get(0).toString());
  }
  /*
   * Creates a VertexData object for every vertex in the graph and stores
   * them
   * in a HashMap.
   */
  private void createVertexData() {
    vertexToVertexData = new HashMap<V, VertexData<V>>(graph.vertexSet().size());

    for (V vertex : graph.vertexSet()) {
      vertexToVertexData.put(vertex, new VertexData2<V>(vertex, false, false));
    }
  }
  @Test
  public void replaceColumnDetectedCorrectly() throws StructureGraphComparisonException {
    ISqlSchemaFrontend frontend1 = new H2SchemaFrontend(DATABASE_FILE_PATH);
    ISqlSchemaFrontend frontend2 = new H2SchemaFrontend(REPLACE_COLUMN_DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema1 = frontend1.createSqlSchema();
    DirectedGraph<IStructureElement, DefaultEdge> schema2 = frontend2.createSqlSchema();
    SqlSchemaComparer comparer = new SqlSchemaComparer(schema1, schema2);
    SqlSchemaComparisonResult result = comparer.comparisonResult;

    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema1.vertexSet()).size());
    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema2.vertexSet()).size());

    Entry<ISqlElement, SchemaModification> renameColumnEntry =
        TestHelper.getModificationOfType(result, SchemaModification.RENAME_COLUMN);
    Entry<ISqlElement, SchemaModification> replaceColumnTypeEntry =
        TestHelper.getModificationOfType(result, SchemaModification.CHANGE_COLUMN_TYPE);

    assertNotNull(renameColumnEntry);
    assertEquals(REPLACE_COLUMN_NAME, renameColumnEntry.getKey().getName());
    assertNotNull(replaceColumnTypeEntry);
    assertEquals(
        REPLACE_COLUMN_TYPE, ((ColumnTypeVertex) replaceColumnTypeEntry.getKey()).getColumnType());
  }
  @Test
  public void replaceLobWithTable() throws StructureGraphComparisonException {
    ISqlSchemaFrontend frontend1 = new H2SchemaFrontend(DATABASE_FILE_PATH);
    ISqlSchemaFrontend frontend2 = new H2SchemaFrontend(REPLACE_LOB_WITH_TABLE_DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema1 = frontend1.createSqlSchema();
    DirectedGraph<IStructureElement, DefaultEdge> schema2 = frontend2.createSqlSchema();
    SqlSchemaComparer comparer = new SqlSchemaComparer(schema1, schema2);
    SqlSchemaComparisonResult result = comparer.comparisonResult;

    assertEquals(
        29,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema1.vertexSet()).size());
    assertEquals(
        33,
        SqlElementFactory.getSqlElementsOfType(SqlColumnVertex.class, schema2.vertexSet()).size());

    for (Entry<ISqlElement, SchemaModification> entry : result.getModifications().entrySet()) {
      if (entry.getValue() == SchemaModification.CREATE_TABLE) {
        assertEquals(REPLACE_LOB_WITH_TABLE, entry.getKey().getName());
      }

      if (entry.getValue() == SchemaModification.DELETE_COLUMN) {
        assertEquals(REPLACE_LOB_WITH_COLUMN, entry.getKey().getName());
      }
    }
  }
Beispiel #7
0
  public void testDirectedAdjacencyList() {
    DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
    g.addVertex(1);
    g.addVertex(2);
    g.addVertex(3);
    g.addVertex(4);
    g.addVertex(5);
    g.addEdge(1, 2);
    g.addEdge(1, 3);
    g.addEdge(3, 1);
    g.addEdge(3, 4);
    g.addEdge(4, 5);
    g.addEdge(5, 1);
    g.addEdge(5, 2);
    g.addEdge(5, 3);
    g.addEdge(5, 4);
    g.addEdge(5, 5);
    g.addEdge(5, 5);

    CSVExporter<Integer, DefaultEdge> exporter =
        new CSVExporter<>(nameProvider, CSVFormat.ADJACENCY_LIST, ';');
    StringWriter w = new StringWriter();
    exporter.exportGraph(g, w);
    assertEquals(DIRECTED_ADJACENCY_LIST, w.toString());
  }
  private void buildFullyConnectedGraph(NodeLists listPairs) {

    for (int i = 0; i < listPairs.getList1().size(); i++) {

      // falls Knoten noch nicht erzeugt wurde
      if (!graph.containsVertex(listPairs.getList1().get(i))) {
        graph.addVertex(listPairs.getList1().get(i));
      }
      if (!parents.contains(listPairs.getList1().get(i))) {
        parents.add(listPairs.getList1().get(i));
      }

      // falls Knoten noch nicht erzeugt wurde
      for (int j = 0; j < listPairs.getList2().size(); j++) {

        if (!graph.containsVertex(listPairs.getList2().get(j))) {
          graph.addVertex(listPairs.getList2().get(j));
        }

        if (!children.contains(listPairs.getList2().get(j))) {
          children.add(listPairs.getList2().get(j));
        }

        // Erstelle eine Kante
        graph.addEdge(listPairs.getList1().get(i), listPairs.getList2().get(j));
        System.out.println(listPairs.getList1().get(i) + " -> " + listPairs.getList2().get(j));
      }
    }
  }
 public void testZeroNodes() {
   GraphGenerator<Integer, DefaultEdge, Integer> gen =
       new GnpRandomBipartiteGraphGenerator<>(0, 0, 0.5);
   DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
   gen.generateGraph(g, new IntegerVertexFactory(), null);
   assertEquals(0, g.vertexSet().size());
   assertEquals(0, g.edgeSet().size());
 }
  private void replaceVertex(JavaClass newClass) {
    List<JavaClass> incomingEdges = getParents(newClass);

    graph.removeVertex(newClass);
    graph.addVertex(newClass);
    for (JavaClass each : incomingEdges) {
      graph.addEdge(each, newClass);
    }
  }
  public void testDirectedGraphGnp2() {
    GraphGenerator<Integer, DefaultEdge, Integer> gen =
        new GnpRandomBipartiteGraphGenerator<>(4, 4, 1.0, SEED);
    DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
    gen.generateGraph(g, new IntegerVertexFactory(), null);

    assertEquals(4 + 4, g.vertexSet().size());
    assertEquals(32, g.edgeSet().size());
  }
 public synchronized void addBuild(JobInvocation build)
     throws ExecutionException, InterruptedException {
   builds.addVertex(build);
   for (JobInvocation up : state.get().getLastCompleted()) {
     String edge = up.toString() + " => " + build.toString();
     LOGGER.fine("added build to execution graph " + edge);
     builds.addEdge(up, build, edge);
   }
   state.get().setLastCompleted(build);
 }
 private void updateParentReferences(JavaClass parentClass) {
   for (String child : parentClass.getImports()) {
     JavaClass childClass = findJavaClass(child);
     if ((childClass != null) && !childClass.equals(parentClass)) {
       if (graph.containsVertex(childClass)) {
         graph.addEdge(parentClass, childClass);
       }
     }
   }
 }
Beispiel #14
0
  public void testDirectedMatrixNoNodeIdZeroMissingEdges() {
    DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
    g.addVertex(1);
    g.addVertex(2);
    g.addVertex(3);
    g.addVertex(4);
    g.addVertex(5);
    g.addEdge(1, 2);
    g.addEdge(1, 3);
    g.addEdge(3, 1);
    g.addEdge(3, 4);
    g.addEdge(4, 5);
    g.addEdge(5, 1);
    g.addEdge(5, 2);
    g.addEdge(5, 3);
    g.addEdge(5, 4);
    g.addEdge(5, 5);

    CSVExporter<Integer, DefaultEdge> exporter =
        new CSVExporter<>(nameProvider, CSVFormat.MATRIX, ';');
    exporter.setParameter(CSVFormat.Parameter.MATRIX_FORMAT_ZERO_WHEN_NO_EDGE, true);
    StringWriter w = new StringWriter();
    exporter.exportGraph(g, w);
    assertEquals(DIRECTED_MATRIX_NO_NODEID_ZERO_NO_EDGE, w.toString());
  }
  @Test
  public void tableHasColumnRelationsEstablishedCorrectly() {
    ISqlSchemaFrontend frontend = new H2SchemaFrontend(DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema = frontend.createSqlSchema();
    int tableHasColumnEdges = 0;

    for (DefaultEdge edge : schema.edgeSet())
      if (edge instanceof TableHasColumnEdge) tableHasColumnEdges++;

    assertEquals(29, tableHasColumnEdges);
  }
  @Test
  public void foreignKeysEstablishedCorrectly() {
    ISqlSchemaFrontend frontend = new H2SchemaFrontend(DATABASE_FILE_PATH);
    DirectedGraph<IStructureElement, DefaultEdge> schema = frontend.createSqlSchema();
    int foreignKeyEdges = 0;

    for (DefaultEdge edge : schema.edgeSet())
      if (edge instanceof ForeignKeyRelationEdge) foreignKeyEdges++;

    assertEquals(7, foreignKeyEdges);
  }
 /** @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */
 public void edgeRemoved(GraphEdgeChangeEvent<V, E> 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);
   }
 }
Beispiel #18
0
  public void testAdjacencyDirected() {
    DirectedGraph<String, DefaultEdge> g =
        new DirectedMultigraph<String, DefaultEdge>(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());
  }
Beispiel #19
0
  /** Dot is a popular graph visualization format. See/Install Graphviz */
  private static String toDot(DirectedGraph<String, DefaultEdge> g) {

    StringBuffer sb = new StringBuffer();
    sb.append("digraph mygraph {\n ");
    Set<DefaultEdge> edges = g.edgeSet();
    for (DefaultEdge e : edges) {
      sb.append(g.getEdgeSource(e)./*remove file extension*/ split("\\.")[0]);
      sb.append("->");
      sb.append(g.getEdgeTarget(e)./*remove file extension*/ split("\\.")[0]);
      sb.append(";\n");
    }
    sb.append("}\n");
    return sb.toString();
  }
  public void testDirectedGraphGnp3() {
    GraphGenerator<Integer, DefaultEdge, Integer> gen =
        new GnpRandomBipartiteGraphGenerator<>(4, 4, 0.1, SEED);
    DirectedGraph<Integer, DefaultEdge> g = new DirectedPseudograph<>(DefaultEdge.class);
    gen.generateGraph(g, new IntegerVertexFactory(), null);

    int[][] edges = {{5, 1}, {7, 3}, {3, 8}, {8, 4}};

    assertEquals(4 + 4, g.vertexSet().size());
    for (int[] e : edges) {
      assertTrue(g.containsEdge(e[0], e[1]));
    }
    assertEquals(edges.length, g.edgeSet().size());
  }
  /** . */
  public void testStronglyConnected2() {
    DirectedGraph<String, DefaultEdge> g =
        new DefaultDirectedGraph<String, DefaultEdge>(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<String, DefaultEdge> inspector =
        new StrongConnectivityInspector<String, DefaultEdge>(g);

    // convert from List to Set because we need to ignore order
    // during comparison
    Set<Set<String>> actualSets = new HashSet<Set<String>>(inspector.stronglyConnectedSets());

    // construct the expected answer
    Set<Set<String>> expectedSets = new HashSet<Set<String>>();
    Set<String> set = new HashSet<String>();
    set.add(V1);
    set.add(V2);
    expectedSets.add(set);
    set = new HashSet<String>();
    set.add(V3);
    expectedSets.add(set);
    set = new HashSet<String>();
    set.add(V4);
    expectedSets.add(set);

    assertEquals(expectedSets, actualSets);

    actualSets.clear();

    List<DirectedSubgraph<String, DefaultEdge>> subgraphs = inspector.stronglyConnectedSubgraphs();
    for (DirectedSubgraph<String, DefaultEdge> sg : subgraphs) {
      actualSets.add(sg.vertexSet());

      StrongConnectivityInspector<String, DefaultEdge> ci =
          new StrongConnectivityInspector<String, DefaultEdge>(sg);
      assertTrue(ci.isStronglyConnected());
    }

    assertEquals(expectedSets, actualSets);
  }
Beispiel #22
0
  /** string graph representations */
  @SuppressWarnings("unused")
  private static String toCustomRepr(DirectedGraph<String, DefaultEdge> g) {

    StringBuffer sb = new StringBuffer();
    sb.append("Vertex set:");
    sb.append(g.vertexSet());

    Set<DefaultEdge> edges = g.edgeSet();
    sb.append("\nEdge set:");
    for (DefaultEdge e : edges) {
      sb.append(e);
    }

    return sb.toString();
  }
Beispiel #23
0
  /**
   * 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<V> findCycles() {
    // ProbeIterator can't be used to handle this case,
    // so use StrongConnectivityInspector instead.
    StrongConnectivityInspector<V, E> inspector = new StrongConnectivityInspector<V, E>(graph);
    List<Set<V>> 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<V> set = new HashSet<V>();
    for (Set<V> 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;
  }
  private void specifyMinimalSignatureValues() {
    vertSet = graph.vertexSet();
    tops = getTopObjects(children, parents);
    bottoms = getBottomObjects(children, parents);
    setTopsAndBottoms();
    completeGraphWithTopAndBottom();
    System.out.println("--------------------------------------------");

    // depth-search
    // results of deph-search save as depthResult
    depthSearch();

    // breadth-search
    // results of breadth-search save as resultTuple
    // results as a node- signatures, in the form of ArrayList<Integer>
    breadthSearch();

    // positions, wich contain only zero-values have to be removed
    // array with max positions- value is saved as max_values_array

    maxValuesArray = new int[length];

    removeMaxZeroPositions();

    System.out.println("Signatures: ");
    for (Object s : signatures.keySet()) {
      System.out.println(s + " :" + signatures.get(s).toString());
    }
    System.out.println("\n ################################################################");

    signatureLength = signatureLength + combinedSignatureLength();
  }
 public Table addTable(Table table) {
   String schemaName = normalizeName(table.schema);
   String tableName = normalizeName(table.name);
   tablesByName.put(qualifiedTableName(schemaName, tableName), table);
   graph.addVertex(table);
   return table;
 }
 private JavaClass findClass(String classname) {
   for (JavaClass jClass : graph.vertexSet()) {
     if (jClass.getName().equals(classname)) {
       return jClass;
     }
   }
   return null;
 }
 public Set<String> getIndexedClasses() {
   Set<String> classes = newHashSet();
   Set<JavaClass> vertexSet = graph.vertexSet();
   for (JavaClass each : vertexSet) {
     classes.add(each.getName());
   }
   return classes;
 }
  private boolean isPrimaryKey(
      DirectedGraph<IStructureElement, DefaultEdge> schema, ISqlElement column) {
    Set<DefaultEdge> outgoingEdges = schema.outgoingEdgesOf(column);

    for (DefaultEdge outgoingEdge : outgoingEdges) {
      IStructureElement element = schema.getEdgeTarget(outgoingEdge);

      if (element instanceof ColumnConstraintVertex
          && ((ColumnConstraintVertex) element)
              .getConstraintType()
              .equals(ConstraintType.PRIMARY_KEY)) {
        return true;
      }
    }

    return false;
  }
Beispiel #29
0
  public DirectedGraph<Node, Edge> convert() {
    DirectedGraph<Node, Edge> graph = new SimpleDirectedGraph<Node, Edge>(Edge.factory);

    // Add vertices

    for (Type t : hierarchy) graph.addVertex(Node.get(t));

    // Add edges

    for (Type t : hierarchy) {
      for (Type i : hierarchy.getInterfaces(t)) {
        graph.addVertex(Node.get(i));
        graph.addEdge(Node.get(t), Node.get(i));
      }

      Type sc = hierarchy.getSuperclass(t);

      if (sc == null) {
        assert t.equals(OBJECT) : t;
        continue;
      }

      graph.addVertex(Node.get(sc));
      graph.addEdge(Node.get(t), Node.get(sc));
    }

    // Check for cycles

    if (new CycleDetector<Node, Edge>(graph).detectCycles())
      throw new CyclicHierarchyException(graph.toString());

    return graph;
  }
Beispiel #30
0
  public static <V, E> void write(DirectedGraph<V, E> g, String fileName, EdgeFilter<E> filter)
      throws FileNotFoundException {
    PrintWriter out = new PrintWriter(fileName);

    // System.out.println("Writing '" + fileName + "'");

    out.print("digraph \"DirectedGraph\" { \n graph [label=\"");
    out.print(g.toString());
    out.print("\", labelloc=t, concentrate=true]; ");
    out.print("center=true;fontsize=12;node [fontsize=12];edge [fontsize=12]; \n");

    for (V node : g.vertexSet()) {
      out.print("   \"");
      out.print(getId(node));
      out.print("\" ");
      out.print("[label=\"");
      out.print(node.toString());
      out.print("\" shape=\"box\" color=\"blue\" ] \n");
    }

    for (V src : g.vertexSet()) {
      for (E e : g.outgoingEdgesOf(src)) {
        if (!filter.accept(e)) {
          continue;
        }

        V tgt = g.getEdgeTarget(e);

        out.print(" \"");
        out.print(getId(src));
        out.print("\" -> \"");
        out.print(getId(tgt));
        out.print("\" ");
        out.print("[label=\"");
        out.print(e.toString());
        out.print("\"]\n");
      }
    }

    out.print("\n}");

    out.flush();
    out.close();
  }