Example #1
0
  /**
   * Creates an SPQRTree.
   *
   * @param g Create the tree for this graph.
   */
  public SPQRTree(Graph g, Pair<Integer, Integer> atEdge) {
    rootNode = null;

    nodeId2NodePointer = new HashMap<Integer, Integer>();
    nodePointer2NodeId = new HashMap<Integer, Integer>();
    treeNode2TreeNodePtr = new HashMap<SPQRTreeNode, Integer>();

    int graphPointer = createGraph();
    for (Integer v : g.getVertices()) {
      int nodePointer = addNode(graphPointer);
      nodeId2NodePointer.put(v, nodePointer);
      nodePointer2NodeId.put(nodePointer, v);
    }
    Integer atEdgePtr = null;
    for (Pair<Integer, Integer> e : g.getEdges()) {
      int eptr =
          addEdge(
              graphPointer,
              nodeId2NodePointer.get(Pair.get1(e)),
              nodeId2NodePointer.get(Pair.get2(e)));
      if (e.equals(atEdge)) {
        atEdgePtr = eptr;
      }
    }
    int spqrTreePointer =
        (atEdgePtr == null)
            ? createSPQRTree(graphPointer)
            : createSPQRTree(graphPointer, atEdgePtr);
    rootNode = new SPQRTreeNode();
    int rootNodePointer = spqrRootNode(spqrTreePointer);
    addSPQRTreeNodeAndChildren(spqrTreePointer, rootNodePointer, rootNode);
    orderSNodes(rootNode);
  }
Example #2
0
  @Override
  protected String describe(Graph graph, boolean create) {
    /* --- create a graph's code word */
    int i, k, n; /* loop variable, buffers */
    StringBuffer s; /* created description */
    TypeMgr nmgr, emgr; /* node and edge type manager */

    if (create) /* construct the graph's code word */ this.makeWord(graph, graph.edgecnt);
    nmgr = graph.getNodeMgr(); /* get the node type manager */
    emgr = graph.getEdgeMgr(); /* and the edge type manager */
    k = this.word[0]; /* get and decode type of root node */
    if (graph.coder != null) k = graph.coder.decode(k);
    s = new StringBuffer(nmgr.getName(k));
    n = graph.edgecnt << 2; /* get the number of characters */
    for (i = 0; i < n; ) {
        /* traverse the characters */
      s.append('|'); /* separator for edges */
      s.append(this.word[++i]); /* source node index */
      s.append(' '); /* separator to edge type */
      s.append(emgr.getName(this.word[++i]));
      s.append(' '); /* separator to node type */
      k = this.word[++i]; /* get and decode the node type */
      if (graph.coder != null) k = graph.coder.decode(k);
      s.append(nmgr.getName(k));
      s.append(' '); /* separator to node index */
      s.append(this.word[++i]); /* destination node index */
    } /* store the edge descriptions */
    return s.toString(); /* return created string description */
  } /* describe() */
Example #3
0
  public GraphIndex(Graph graph) {
    LOG.info("Indexing graph...");

    for (String feedId : graph.getFeedIds()) {
      for (Agency agency : graph.getAgencies(feedId)) {
        Map<String, Agency> agencyForId = agenciesForFeedId.getOrDefault(feedId, new HashMap<>());
        agencyForId.put(agency.getId(), agency);
        this.agenciesForFeedId.put(feedId, agencyForId);
      }
    }

    Collection<Edge> edges = graph.getEdges();
    /* We will keep a separate set of all vertices in case some have the same label.
     * Maybe we should just guarantee unique labels. */
    Set<Vertex> vertices = Sets.newHashSet();
    for (Edge edge : edges) {
      vertices.add(edge.getFromVertex());
      vertices.add(edge.getToVertex());
      if (edge instanceof TablePatternEdge) {
        TablePatternEdge patternEdge = (TablePatternEdge) edge;
        TripPattern pattern = patternEdge.getPattern();
        patternForId.put(pattern.code, pattern);
      }
    }
    for (Vertex vertex : vertices) {
      vertexForId.put(vertex.getLabel(), vertex);
      if (vertex instanceof TransitStop) {
        TransitStop transitStop = (TransitStop) vertex;
        Stop stop = transitStop.getStop();
        stopForId.put(stop.getId(), stop);
        stopVertexForStop.put(stop, transitStop);
        stopsForParentStation.put(stop.getParentStation(), stop);
      }
    }
    for (TransitStop stopVertex : stopVertexForStop.values()) {
      Envelope envelope = new Envelope(stopVertex.getCoordinate());
      stopSpatialIndex.insert(envelope, stopVertex);
    }
    for (TripPattern pattern : patternForId.values()) {
      patternsForFeedId.put(pattern.getFeedId(), pattern);
      patternsForRoute.put(pattern.route, pattern);

      for (Trip trip : pattern.getTrips()) {
        patternForTrip.put(trip, pattern);
        tripForId.put(trip.getId(), trip);
      }
      for (Stop stop : pattern.getStops()) {
        patternsForStop.put(stop, pattern);
      }
    }
    for (Route route : patternsForRoute.asMap().keySet()) {
      routeForId.put(route.getId(), route);
    }

    // Copy these two service indexes from the graph until we have better ones.
    calendarService = graph.getCalendarService();
    serviceCodes = graph.serviceCodes;
    this.graph = graph;
    LOG.info("Done indexing graph.");
  }
Example #4
0
  private Graph changeLatentNames(Graph full, Clusters measurements, List<String> latentVarList) {
    Graph g2 = null;

    try {
      g2 = (Graph) new MarshalledObject(full).get();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    for (int i = 0; i < measurements.getNumClusters(); i++) {
      List<String> d = measurements.getCluster(i);
      String latentName = latentVarList.get(i);

      for (Node node : full.getNodes()) {
        if (!(node.getNodeType() == NodeType.LATENT)) {
          continue;
        }

        List<Node> _children = full.getChildren(node);

        _children.removeAll(ReidentifyVariables.getLatents(full));

        List<String> childNames = getNames(_children);

        if (new HashSet<String>(childNames).equals(new HashSet<String>(d))) {
          g2.getNode(node.getName()).setName(latentName);
        }
      }
    }

    return g2;
  }
Example #5
0
  /**
   * Random graph. Generates randomly k directed edges out of each node. The neighbors (edge
   * targets) are chosen randomly without replacement from the nodes of the graph other than the
   * source node (i.e. no loop edge is added). If k is larger than N-1 (where N is the number of
   * nodes) then k is set to be N-1 and a complete graph is returned.
   *
   * @param g the graph to be wired
   * @param k samples to be drawn for each node
   * @param r source of randomness
   * @return returns g for convenience
   */
  public static Graph wireKOut(Graph g, int k, Random r) {

    final int n = g.size();
    if (n < 2) {
      return g;
    }
    if (n <= k) {
      k = n - 1;
    }
    int[] nodes = new int[n];
    for (int i = 0; i < nodes.length; ++i) {
      nodes[i] = i;
    }
    for (int i = 0; i < n; ++i) {
      int j = 0;
      while (j < k) {
        int newedge = j + r.nextInt(n - j);
        int tmp = nodes[j];
        nodes[j] = nodes[newedge];
        nodes[newedge] = tmp;
        if (nodes[j] != i) {
          g.setEdge(i, nodes[j]);
          j++;
        }
      }
    }
    return g;
  }
Example #6
0
  // ===========================SCORING METHODS===================//
  public double scoreDag(Graph graph) {
    Graph dag = new EdgeListGraphSingleConnections(graph);
    buildIndexing(graph);

    double score = 0.0;

    for (Node y : dag.getNodes()) {
      Set<Node> parents = new HashSet<Node>(dag.getParents(y));
      int nextIndex = -1;
      for (int i = 0; i < getVariables().size(); i++) {
        nextIndex = hashIndices.get(variables.get(i));
      }
      int parentIndices[] = new int[parents.size()];
      Iterator<Node> pi = parents.iterator();
      int count = 0;
      while (pi.hasNext()) {
        Node nextParent = pi.next();
        parentIndices[count++] = hashIndices.get(nextParent);
      }

      if (this.isDiscrete()) {
        score += localDiscreteScore(nextIndex, parentIndices);
      } else {
        score += localSemScore(nextIndex, parentIndices);
      }
    }
    return score;
  }
  /** Get a graph and direct only the unshielded colliders. */
  public static void basicPattern(Graph graph) {
    Set<Edge> undirectedEdges = new HashSet<Edge>();

    NEXT_EDGE:
    for (Edge edge : graph.getEdges()) {
      Node head = null, tail = null;

      if (edge.getEndpoint1() == Endpoint.ARROW && edge.getEndpoint2() == Endpoint.TAIL) {
        head = edge.getNode1();
        tail = edge.getNode2();
      } else if (edge.getEndpoint2() == Endpoint.ARROW && edge.getEndpoint1() == Endpoint.TAIL) {
        head = edge.getNode2();
        tail = edge.getNode1();
      }

      if (head != null) {
        for (Node node : graph.getParents(head)) {
          if (node != tail && !graph.isAdjacentTo(tail, node)) {
            continue NEXT_EDGE;
          }
        }

        undirectedEdges.add(edge);
      }
    }

    for (Edge nextUndirected : undirectedEdges) {
      Node node1 = nextUndirected.getNode1(), node2 = nextUndirected.getNode2();

      graph.removeEdge(nextUndirected);
      graph.addUndirectedEdge(node1, node2);
    }
  }
 static GraphDescription create(Graph graph) {
   if (graph == null) {
     return EMPTY;
   }
   Map<String, NODE> nodes = new HashMap<String, NODE>();
   for (NODE node : graph.nodes()) {
     if (nodes.put(defined(node.name()), node) != null) {
       throw new IllegalArgumentException("Node \"" + node.name() + "\" defined more than once");
     }
   }
   Map<String, REL> rels = new HashMap<String, REL>();
   List<REL> relationships = new ArrayList<REL>();
   for (REL rel : graph.relationships()) {
     createIfAbsent(nodes, rel.start());
     createIfAbsent(nodes, rel.end());
     String name = rel.name();
     if (!name.equals("")) {
       if (rels.put(name, rel) != null) {
         throw new IllegalArgumentException(
             "Relationship \"" + name + "\" defined more than once");
       }
     }
     relationships.add(rel);
   }
   parse(graph.value(), nodes, relationships);
   return new GraphDescription(
       nodes.values().toArray(NO_NODES),
       relationships.toArray(NO_RELS),
       graph.autoIndexNodes(),
       graph.autoIndexRelationships());
 }
Example #9
0
  public static Graph getGraph() {

    Graph g = Factory.createGraphMem();

    g.add(
        new Triple(
            NodeFactory.createURI("http://example.com/subject"),
            NodeFactory.createURI("http://example.com/predicate"),
            NodeFactory.createURI("http://example.com/object")));

    g.add(
        new Triple(
            NodeFactory.createBlankNode(BlankNodeId.create("a")),
            NodeFactory.createURI("http://example.com/p1"),
            NodeFactory.createBlankNode(BlankNodeId.create("b"))));

    g.add(
        new Triple(
            NodeFactory.createBlankNode(BlankNodeId.create("b")),
            NodeFactory.createURI("http://example.com/p2"),
            NodeFactory.createLiteral("foo")));

    g.add(
        new Triple(
            NodeFactory.createURI("http://example.com/ns/e"),
            NodeFactory.createURI("http://example.com/ns/p5"),
            NodeFactory.createLiteral("verify base works")));

    return g;
  }
Example #10
0
  /**
   * Execute Dijkstra's algorithm on the given graph to find the shortest path from {@code
   * sourceNode} to {@code destinationNode}. The length of the path is defined as the sum of the
   * edge weights, which are provided in the edge file. Every time the algorithm pulls a node into
   * the cloud, call {@link Logger#movedCharacter(String, String)} with the name {@link
   * #PATH_CHARACTER} and the location equal to the new cloud node. Every time the algorithm uses an
   * edge to relax the known distances to a node <b>which is not yet in the cloud</b>, call {@link
   * Logger#traversedEdge(String, String, String)} with the tag {@link #DIJKSTRA_TAG}, the node just
   * pulled into the cloud as the second argument, and the node whose known distance may be relaxed
   * as the third argument. Do this even if the known distance to the node doesn't decrease. For
   * testing purposes run the algorithm until all nodes are in the cloud and be sure to relax the
   * edges using alphabetical ordering of the nodes.
   *
   * @return the sequence of node GUIDs of the shortest path found, or null if there is no such path
   */
  public List<Graph.Node> dijkstra(Graph.Node sourceNode, Graph.Node destinationNode) {
    HashMap<Graph.Node, Double> dist = new HashMap<Graph.Node, Double>();
    HashMap<Graph.Node, Graph.Node> previous = new HashMap<Graph.Node, Graph.Node>();

    for (Graph.Node node : g.getNodes()) {
      dist.put(node, Double.POSITIVE_INFINITY);
      previous.put(node, null);
    }
    dist.put(sourceNode, 0.0);
    Set<Graph.Node> nodes = g.getNodes();
    while (!nodes.isEmpty()) {
      Graph.Node current = closest(nodes, dist);
      if (dist.get(current) == Double.POSITIVE_INFINITY) break;
      nodes.remove(current);
      if (current == destinationNode) {
        List<Graph.Node> sequence = new ArrayList<Graph.Node>();
        while (previous.get(current) != null) {
          sequence.add(current);
          current = previous.get(current);
        }
        sequence.add(sourceNode);
        Collections.reverse(sequence);
        return sequence;
      }
      for (Graph.Node neighbor : current.getNeighbors().keySet()) {
        double alt = dist.get(current) + current.getNeighbors().get(neighbor);
        if (alt < dist.get(neighbor)) {
          dist.put(neighbor, alt);
          previous.put(neighbor, current);
        }
      }
    }
    return new ArrayList<Graph.Node>();
  }
  /**
   * Creates a new iterator for the specified graph. Iteration will start at the specified start
   * vertex. If the specified start vertex is <code>
   * null</code>, 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 <code>g==null</code> or does not contain <code>startVertex
   *     </code>
   */
  public CrossComponentIterator(Graph<V, E> 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<V, E>(this, null);
    reusableVertexEvent = new FlyweightVertexEvent<V>(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");
    }
  }
  @SuppressWarnings("serial")
  public static void main(String[] args) throws Exception {

    ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

    DataSet<Vertex<Long, Double>> pages = getPagesDataSet(env);

    DataSet<Edge<Long, Double>> links = getLinksDataSet(env);

    Graph<Long, Double, Double> network = new Graph<Long, Double, Double>(pages, links, env);

    DataSet<Tuple2<Long, Long>> vertexOutDegrees = network.outDegrees();

    // assign the transition probabilities as the edge weights
    Graph<Long, Double, Double> networkWithWeights =
        network.joinWithEdgesOnSource(
            vertexOutDegrees,
            new MapFunction<Tuple2<Double, Long>, Double>() {
              public Double map(Tuple2<Double, Long> value) {
                return value.f0 / value.f1;
              }
            });

    DataSet<Vertex<Long, Double>> pageRanks =
        networkWithWeights
            .run(new PageRank<Long>(numPages, DAMPENING_FACTOR, maxIterations))
            .getVertices();

    pageRanks.print();

    env.execute();
  }
 private static boolean hasContiguousVertices(Graph<?> g) {
   int order = g.order();
   for (int v : g.vertices()) {
     if (v >= order) return false;
   }
   return true;
 }
Example #14
0
 // @brief Print path from s to v with BFS iteration
 // @status finished
 public LinkedList<Integer> HasPathBFS(int s, int v) {
   LinkedList<Integer> ret = new LinkedList<Integer>();
   int[] edgeTo = new int[G.V()];
   boolean[] marked = new boolean[G.V()];
   Queue<Integer> queue = new LinkedList<Integer>();
   queue.add(s);
   marked[s] = true;
   while (!queue.isEmpty()) {
     int node = queue.poll();
     LinkedList<Integer> neighbors = G.adj(node);
     for (int n : neighbors) {
       if (!marked[n]) {
         edgeTo[node] = n;
         marked[n] = true;
         queue.add(n);
       }
     }
   }
   if (marked[v] == false) {
     System.out.println("Can not find a path from " + s + " to " + v + "!\n");
     return ret;
   }
   for (int n = v; n != s; n = edgeTo[n]) ret.addFirst(n);
   printPath(s, v, ret);
   return ret;
 }
Example #15
0
  public static Graph erdosRenyiGraph(int n, int e) {
    List<Node> nodes = new ArrayList<Node>();
    for (int i = 0; i < n; i++) nodes.add(new GraphNode("X" + i));

    Graph graph = new EdgeListGraph(nodes);

    for (int e0 = 0; e0 < e; e0++) {
      int i1 = RandomUtil.getInstance().nextInt(n);
      int i2 = RandomUtil.getInstance().nextInt(n);

      if (i1 == i2) {
        e0--;
        continue;
      }

      Edge edge = Edges.undirectedEdge(nodes.get(i1), nodes.get(i2));

      if (graph.containsEdge(edge)) {
        e0--;
        continue;
      }

      graph.addEdge(edge);
    }

    return graph;
  }
Example #16
0
 public Set<Edge> getNonadjacencies() {
   Graph complete = GraphUtils.completeGraph(graph);
   Set<Edge> nonAdjacencies = complete.getEdges();
   Graph undirected = GraphUtils.undirectedGraph(graph);
   nonAdjacencies.removeAll(undirected.getEdges());
   return new HashSet<Edge>(nonAdjacencies);
 }
Example #17
0
  private boolean existsUnblockedSemiDirectedPath(Node from, Node to, List<Node> cond, Graph G) {
    Queue<Node> Q = new LinkedList<Node>();
    Set<Node> V = new HashSet<Node>();
    Q.offer(from);
    V.add(from);

    while (!Q.isEmpty()) {
      Node t = Q.remove();
      if (t == to) return true;

      for (Node u : G.getAdjacentNodes(t)) {
        Edge edge = G.getEdge(t, u);
        Node c = Edges.traverseSemiDirected(t, edge);
        if (c == null) continue;
        if (cond.contains(c)) continue;
        if (c == to) return true;

        if (!V.contains(c)) {
          V.add(c);
          Q.offer(c);
        }
      }
    }

    return false;
  }
Example #18
0
  public List<Triple> getUnshieldedCollidersFromGraph(Graph graph) {
    List<Triple> colliders = new ArrayList<>();

    List<Node> nodes = graph.getNodes();

    for (Node b : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(b);

      if (adjacentNodes.size() < 2) {
        continue;
      }

      ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
      int[] combination;

      while ((combination = cg.next()) != null) {
        Node a = adjacentNodes.get(combination[0]);
        Node c = adjacentNodes.get(combination[1]);

        // Skip triples that are shielded.
        if (graph.isAdjacentTo(a, c)) {
          continue;
        }

        if (graph.isDefCollider(a, b, c)) {
          colliders.add(new Triple(a, b, c));
        }
      }
    }

    return colliders;
  }
  Graph create(Collection<? extends Deployer> deployers) {
    // S ← Set of all nodes with no incoming edges
    List<Deployer> s = new ArrayList<Deployer>();
    Map<String, Collection<Deployer>> inputCache = new HashMap<String, Collection<Deployer>>();
    // Map<Deployer, Set<Edge>> edgeCache = new IdentityHashMap<Deployer, Set<Edge>>();
    Map edgeCache = new IdentityHashMap<Deployer, Set<?>>();
    Set<String> outputs = new HashSet<String>();
    Map<String, Collection<Deployer>> outputCache = new HashMap<String, Collection<Deployer>>();
    for (Deployer deployer : deployers) {
      process(deployer, s, inputCache, edgeCache, outputs, outputCache);
    }

    processTransientDeployers(s, inputCache, outputCache, edgeCache);

    Graph graph = new Graph();
    for (Deployer d : deployers) {
      graph.addNode(d.toString());
    }

    for (Map.Entry entry : (Set<Map.Entry>) edgeCache.entrySet()) {
      System.out.println(entry);
      Set<Object> edges = (Set<Object>) entry.getValue();
      for (Object edge : edges) {
        String fromNode = fromNode(edge);
        String edgeLabel = edgeLabel(edge);
        String toNode = toNode(edge);
        graph.addEdge(fromNode, toNode, edgeLabel);
      }
    }
    System.out.println(graph.edges.size());
    return graph;
  }
Example #20
0
  /**
   * Returns minimum spanning tree. Method uses Kruskal's algorithm for this purpose. Working only
   * for undirected graph
   *
   * @return map represents branches of minimum-spanning-tree (key - child, value - parent)
   */
  public static Map<Integer, Integer> minTreeKruskal(Graph graph) {
    if (graph.isDirected())
      throw new UnsupportedOperationException(
          "Kruscal's algorithm works only for undirected graphs");
    Map<Integer, Integer> tree = new HashMap<>();
    // get all edges via iterator
    List<Graph.Edge> edges = new ArrayList<>();
    for (Graph.Edge edge : graph.edges()) edges.add(edge);
    // sort edges by weight
    Collections.sort(
        edges,
        new Comparator<Graph.Edge>() {
          @Override
          public int compare(Graph.Edge o1, Graph.Edge o2) {
            return o1.getWeight() - o2.getWeight();
          }
        });

    // for algorithm we use disjoint set forest data structure (a.k.a. union-find, merge-find etc.
    // see wikipedia)
    DisjointSetForest<Integer> set = new DisjointSetForest<>();
    for (Integer number : graph.vertexes()) set.makeSet(number);
    // adding edges to tree, while it can't be possible to add edge that don't creates a cycle
    for (Graph.Edge edge : edges) {
      if (set.find(edge.getIn()) != set.find(edge.getOut())) {
        if (!tree.containsKey(edge.getIn())) tree.put(edge.getIn(), edge.getOut());
        else tree.put(edge.getOut(), edge.getIn());
        set.union(edge.getIn(), edge.getOut());
      }
    }
    return tree;
  }
  private void init(Graph<V, E> g, Set<V> vertexSet, Set<E> edgeSet) {
    // create a map between vertex value to its order(1st,2nd,etc)
    // "CAT"=1 "DOG"=2 "RHINO"=3

    this.mapVertexToOrder = new HashMap<V, Integer>(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<LabelsEdge>(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);
      }
    }
  }
Example #22
0
  /**
   * Builds the gml text into the vGML string
   *
   * @param graph - the graph to convert into GML
   */
  public void mBuildGML(Graph graph) {
    vGML.append("Creator \"ProjectAG\" \n");
    vGML.append("Version 0.5 \n");
    if (graph != null) {
      vGML.append("graph \n [\n");
      if (!graph.mGetTitle().isEmpty()) {
        vGML.append("\tlabel \"");
        vGML.append(graph.mGetTitle() + "\"\n");
      }

      // Build the GML text for each node (at the graph level of the GML)
      ArrayList<Node> nodes = graph.mGetNodeList();
      for (int i = 0; i < nodes.size(); i++) {
        mBuildNodeAttribute(nodes.get(i));
      }

      // Build the GML text for each edge (at the graph level of the GML)
      ArrayList<Edge> edges = graph.mGetEdgeList();
      for (int i = 0; i < edges.size(); i++) {
        mBuildEdgeAttribute(edges.get(i));
      }

      // Don't forget the closing bracket
      vGML.append("] \n");
    }
  }
Example #23
0
  /**
   * Constructs a new JGraph model adapter for the specified JGraphT graph.
   *
   * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to be created. <code>null
   *     </code> is NOT permitted.
   * @param defaultVertexAttributes a default map of JGraph attributes to format vertices. <code>
   *     null</code> is NOT permitted.
   * @param defaultEdgeAttributes a default map of JGraph attributes to format edges. <code>null
   *     </code> is NOT permitted.
   * @param cellFactory a {@link CellFactory} to be used to create the JGraph cells. <code>null
   *     </code> is NOT permitted.
   * @throws IllegalArgumentException
   */
  public JGraphModelAdapter(
      Graph<V, E> jGraphTGraph,
      AttributeMap defaultVertexAttributes,
      AttributeMap defaultEdgeAttributes,
      CellFactory<V, E> 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<V, E> g = (ListenableGraph<V, E>) jGraphTGraph;
      g.addGraphListener(new JGraphTListener());
    }

    for (Iterator<V> i = jGraphTGraph.vertexSet().iterator(); i.hasNext(); ) {
      handleJGraphTAddedVertex(i.next());
    }

    for (Iterator<E> i = jGraphTGraph.edgeSet().iterator(); i.hasNext(); ) {
      handleJGraphTAddedEdge(i.next());
    }

    this.addGraphModelListener(new JGraphListener());
  }
Example #24
0
  ////////////////////////////////////////////////
  // collect in rTupleList all unshielded tuples
  ////////////////////////////////////////////////
  private List<Node[]> getRTuples() {
    List<Node[]> rTuples = new ArrayList<Node[]>();
    List<Node> nodes = graph.getNodes();

    for (Node j : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(j);

      if (adjacentNodes.size() < 2) {
        continue;
      }

      ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
      int[] combination;

      while ((combination = cg.next()) != null) {
        Node i = adjacentNodes.get(combination[0]);
        Node k = adjacentNodes.get(combination[1]);

        // Skip triples that are shielded.
        if (!graph.isAdjacentTo(i, k)) {
          Node[] newTuple = {i, j, k};
          rTuples.add(newTuple);
        }
      }
    }

    return (rTuples);
  }
Example #25
0
  /**
   * Returns a uniformly random tree on <tt>V</tt> vertices. This algorithm uses a Prufer sequence
   * and takes time proportional to <em>V log V</em>.
   *
   * @param V the number of vertices in the tree
   * @return a uniformly random tree on <tt>V</tt> vertices
   */
  public static Graph tree(int V) {
    Graph G = new Graph(V);

    // special case
    if (V == 1) return G;

    // Cayley's theorem: there are V^(V-2) labeled trees on V vertices
    // Prufer sequence: sequence of V-2 values between 0 and V-1
    // Prufer's proof of Cayley's theorem: Prufer sequences are in 1-1
    // with labeled trees on V vertices
    int[] prufer = new int[V - 2];
    for (int i = 0; i < V - 2; i++) prufer[i] = StdRandom.uniform(V);

    // degree of vertex v = 1 + number of times it appers in Prufer sequence
    int[] degree = new int[V];
    for (int v = 0; v < V; v++) degree[v] = 1;
    for (int i = 0; i < V - 2; i++) degree[prufer[i]]++;

    // pq contains all vertices of degree 1
    MinPQ<Integer> pq = new MinPQ<Integer>();
    for (int v = 0; v < V; v++) if (degree[v] == 1) pq.insert(v);

    // repeatedly delMin() degree 1 vertex that has the minimum index
    for (int i = 0; i < V - 2; i++) {
      int v = pq.delMin();
      G.addEdge(v, prufer[i]);
      degree[v]--;
      degree[prufer[i]]--;
      if (degree[prufer[i]] == 1) pq.insert(prufer[i]);
    }
    G.addEdge(pq.delMin(), pq.delMin());
    return G;
  }
Example #26
0
  public Nodes dual() {
    Graph graph = belongsTo();
    Nodes vertices = graph.nodes(Node.Duality.hvert);
    Nodes edges = graph.nodes(Node.Duality.hedge);

    return (this == vertices) ? edges : (this == edges) ? vertices : this;
  }
Example #27
0
 /**
  * Main method to solve the maze. pre: args[0] contains the name of the input file.
  *
  * @param args Command line argument
  */
 public static void main(String[] args) {
   int numV = 0; // The number of vertices.
   Graph theMaze = null;
   // Load the graph data from a file.
   try {
     Scanner scan = new Scanner(new FileReader(args[0]));
     theMaze = AbstractGraph.createGraph(scan, false, "List");
     numV = theMaze.getNumV();
   } catch (IOException ex) {
     System.err.println("IO Error while reading graph");
     System.err.println(ex.toString());
     System.exit(1);
   }
   // Perform breadth-first search.
   int parent[] = BreadthFirstSearch.breadthFirstSearch(theMaze, 0);
   // Construct the path.
   Deque<Integer> thePath = new ArrayDeque<Integer>();
   int v = numV - 1;
   while (parent[v] != -1) {
     thePath.push(new Integer(v));
     v = parent[v];
   }
   // Output the path.
   System.out.println("The Shortest path is:");
   while (!thePath.isEmpty()) {
     System.out.println(thePath.pop());
   }
 }
Example #28
0
  /**
   * @param vertexNumber the number which identifies the vertex v in this order.
   * @return the identifying numbers of all vertices which are connected to v by an edge incoming to
   *     v.
   */
  public int[] getInEdges(int vertexNumber) {
    if (cacheEdges && (incomingEdges[vertexNumber] != null)) {
      return incomingEdges[vertexNumber];
    }

    V v = getVertex(vertexNumber);
    Set<E> edgeSet;

    if (graph instanceof DirectedGraph<?, ?>) {
      edgeSet = ((DirectedGraph<V, E>) graph).incomingEdgesOf(v);
    } else {
      edgeSet = graph.edgesOf(v);
    }

    int[] vertexArray = new int[edgeSet.size()];
    int i = 0;

    for (E edge : edgeSet) {
      V source = graph.getEdgeSource(edge), target = graph.getEdgeTarget(edge);
      vertexArray[i++] = mapVertexToOrder.get(source.equals(v) ? target : source);
    }

    if (cacheEdges) {
      incomingEdges[vertexNumber] = vertexArray;
    }

    return vertexArray;
  }
  private void getNewNodes() {
    Vector levelNodes = new Vector();
    Vector nextLevelNodes = new Vector();
    Vector passedNodes = new Vector();
    levelNodes.add(centerNode.name);
    for (int level = 0; level <= Config.navigationDepth; level++) {
      for (Enumeration e = levelNodes.elements(); e.hasMoreElements(); ) {
        String nodeName = (String) e.nextElement();

        if (!passedNodes.contains(nodeName)) {
          passedNodes.add(nodeName);

          Node node = graph.nodeFromName(nodeName);
          if (node == null) {
            node = xmlReader.getNode(nodeName);
            graph.add(node);
          }
          node.passed = true;

          Set linkSet = node.links.keySet();
          for (Iterator it = linkSet.iterator(); it.hasNext(); ) {
            String neighbourName = (String) it.next();
            if (!passedNodes.contains(neighbourName) && !levelNodes.contains(neighbourName)) {
              nextLevelNodes.add(neighbourName);
            }
          }
        }
      }
      levelNodes = nextLevelNodes;
      nextLevelNodes = new Vector();
    }
  }
  protected Graph<String, DefaultWeightedEdge> createWithBias(boolean negate) {
    Graph<String, DefaultWeightedEdge> g;
    double bias = 1;
    if (negate) {
      // negative-weight edges are being tested, so only a directed graph
      // makes sense
      g = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
      bias = -1;
    } else {
      // by default, use an undirected graph
      g = new SimpleWeightedGraph<String, DefaultWeightedEdge>(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;
  }