List of usage examples for com.google.common.graph Graph nodes
Set<N> nodes();
From source file:dagger.internal.codegen.DaggerGraphs.java
/** Returns the nodes in a graph that are not reachable from a node. */ public static <N> ImmutableSet<N> unreachableNodes(Graph<N> graph, N node) { return ImmutableSet.copyOf(difference(graph.nodes(), reachableNodes(graph, node))); }
From source file:edu.uci.ics.jung.algorithms.metrics.Metrics.java
/** * Returns a <code>Map</code> of nodes to their clustering coefficients. The clustering * coefficient cc(v) of a node v is defined as follows: * * <ul>//from ww w .ja va2 s.c o m * <li><code>degree(v) == {0,1}</code>: 0 * <li><code>degree(v) == n, n >= 2</code>: given S, the set of neighbors of <code>v</code>: * cc(v) = (the sum over all w in S of the number of other elements of w that are neighbors * of w) / ((|S| * (|S| - 1) / 2). Less formally, the fraction of <code>v</code>'s neighbors * that are also neighbors of each other. * </ul> * * <p><b>Note</b>: This algorithm treats its argument as an undirected graph; edge direction is * ignored. * * @param graph the graph whose clustering coefficients are to be calculated * @param <N> the node type * @param <E> the edge type * @return the clustering coefficient for each node * @see "The structure and function of complex networks, M.E.J. Newman, * aps.arxiv.org/abs/cond-mat/0303516" */ public static <N> ImmutableMap<N, Double> clusteringCoefficients(Graph<N> graph) { ImmutableMap.Builder<N, Double> coefficients = ImmutableMap.builder(); for (N v : graph.nodes()) { int n = graph.degree(v); if (n < 2) { coefficients.put(v, new Double(0)); } else { int edgeCount = 0; for (N w : graph.adjacentNodes(v)) { if (!w.equals(v)) { for (N x : graph.adjacentNodes(v)) { // TODO: replace with hasEdge() once it's ready if (!w.equals(x) && graph.adjacentNodes(w).contains(x)) { edgeCount++; } } } } double possible_edges = (n * (n - 1)) / 2.0; coefficients.put(v, new Double(edgeCount / possible_edges)); } } return coefficients.build(); }
From source file:edu.uci.ics.jung.graph.util.TreeUtils.java
public static <N> ImmutableSet<N> roots(Graph<N> graph) { checkNotNull(graph, "graph"); return graph.nodes().stream().filter(node -> graph.predecessors(node).isEmpty()).collect(toImmutableSet()); }
From source file:edu.uci.ics.jung.algorithms.filters.KNeighborhoodFilter.java
public static <N> MutableGraph<N> filterGraph(Graph<N> graph, Set<N> rootNodes, int radius) { checkNotNull(graph);/*from w w w. j a v a 2s.c o m*/ checkNotNull(rootNodes); checkArgument(graph.nodes().containsAll(rootNodes), "graph must contain all of rootNodes"); checkArgument(radius > 0, "radius must be > 0"); MutableGraph<N> filtered = GraphBuilder.from(graph).build(); for (N root : rootNodes) { filtered.addNode(root); } Queue<N> currentNodes = new ArrayDeque<>(rootNodes); Queue<N> nextNodes = new ArrayDeque<>(); for (int depth = 1; depth <= radius && !currentNodes.isEmpty(); depth++) { while (!currentNodes.isEmpty()) { N currentNode = currentNodes.remove(); for (N nextNode : graph.successors(currentNode)) { // the addNode needs to happen before putEdge() because we need to know whether // the node was present in the graph // (and putEdge() will always add the node if not present) if (filtered.addNode(nextNode)) { nextNodes.add(nextNode); } filtered.putEdge(currentNode, nextNode); } } Queue<N> emptyQueue = currentNodes; currentNodes = nextNodes; nextNodes = emptyQueue; } // put in in-edges from nodes in the filtered graph for (N node : filtered.nodes()) { for (N predecessor : graph.predecessors(node)) { if (filtered.nodes().contains(predecessor)) { filtered.putEdge(predecessor, node); } } } return filtered; }
From source file:edu.uci.ics.jung.graph.util.TreeUtils.java
/** * A graph is "forest-shaped" if it is directed, acyclic, and each node has at most one * predecessor./* w w w . j a v a2 s .c o m*/ */ public static <N> boolean isForestShaped(Graph<N> graph) { checkNotNull(graph, "graph"); return graph.isDirected() && !Graphs.hasCycle(graph) && graph.nodes().stream().allMatch(node -> graph.predecessors(node).size() <= 1); }
From source file:edu.uci.ics.jung.algorithms.metrics.TriadicCensus.java
/** * Returns an array whose ith element (for i in [1,16]) is the number of occurrences of the * corresponding triad type in <code>g</code>. (The 0th element is not meaningful; this array is * effectively 1-based.)// ww w .j a va 2s. co m * * @param g the graph whose properties are being measured * @param <N> the node type * @return an array encoding the number of occurrences of each triad type */ public static <N> long[] getCounts(Graph<N> g) { Preconditions.checkArgument(g.isDirected(), "input graph must be directed"); long[] count = new long[MAX_TRIADS]; // TODO: can we make this more efficient and not require the extra list? List<N> id = new ArrayList<N>(g.nodes()); // apply algorithm to each edge, one at at time for (int i_v = 0; i_v < id.size(); i_v++) { N v = id.get(i_v); for (N u : g.adjacentNodes(v)) { int triType = -1; if (id.indexOf(u) <= i_v) { continue; } Set<N> neighbors = new HashSet<N>(g.adjacentNodes(u)); neighbors.addAll(g.adjacentNodes(v)); neighbors.remove(u); neighbors.remove(v); // TODO: use hasEdge() when available if (g.successors(v).contains(u) && g.successors(u).contains(v)) { triType = 3; } else { triType = 2; } count[triType] += id.size() - neighbors.size() - 2; for (N w : neighbors) { if (shouldCount(g, id, u, v, w)) { count[triType(triCode(g, u, v, w))]++; } } } } long sum = 0; for (int i = 2; i <= 16; i++) { sum += count[i]; } int n = id.size(); count[1] = n * (n - 1) * (n - 2) / 6 - sum; return count; }
From source file:no.ssb.vtl.script.operations.hierarchy.HierarchyOperation.java
/** * Try to find a path in the graph between from and to. * * @return a list (possibly empty) of paths *//* w ww. j a va2 s .c o m*/ @VisibleForTesting static <T> List<List<T>> findPaths(Graph<T> graph, T from, T to) { List<List<T>> paths = Lists.newArrayList(); if (graph.nodes().contains(from) && graph.nodes().contains(to)) { // DAG means no loop. // Each time we add nodes, check if there is a path // already. We don't check if we never saw one of them. //LinkedHashSet<String> path = Sets.newLinkedHashSet(); Deque<T> stack = Lists.newLinkedList(); stack.push(from); while (!stack.isEmpty()) { T current = stack.pop(); if (current.equals(to)) { // return false; ArrayList<T> path = Lists.newArrayList(); path.add(from); path.addAll(stack); path.add(to); paths.add(path); continue; } for (T t : graph.successors(current)) { if (!stack.contains(t)) { stack.push(t); } } } } return paths; }
From source file:edu.uci.ics.jung.layout.algorithms.SpringBHIteratorLayoutAlgorithm.java
protected void calculateRepulsion() { Graph<N> graph = layoutModel.getGraph(); try {//ww w . j a v a 2 s .c o m for (N node : graph.nodes()) { if (layoutModel.isLocked(node)) { continue; } SpringNodeData svd = springNodeData.getUnchecked(node); if (svd == null) { continue; } double dx = 0, dy = 0; ForceObject<N> nodeForceObject = new ForceObject<>(node, layoutModel.apply(node)); Iterator<ForceObject<N>> forceObjectIterator = new ForceObjectIterator<>(tree, nodeForceObject); while (forceObjectIterator.hasNext()) { ForceObject<N> nextForceObject = forceObjectIterator.next(); if (nextForceObject == null || node == nextForceObject.getElement()) { continue; } Point p = nodeForceObject.p; Point p2 = nextForceObject.p; if (p == null || p2 == null) { continue; } double vx = p.x - p2.x; double vy = p.y - p2.y; double distanceSq = p.distanceSquared(p2); if (distanceSq == 0) { dx += random.nextDouble(); dy += random.nextDouble(); } else if (distanceSq < repulsion_range_sq) { double factor = 1; dx += factor * vx / distanceSq; dy += factor * vy / distanceSq; } } double dlen = dx * dx + dy * dy; if (dlen > 0) { dlen = Math.sqrt(dlen) / 2; svd.repulsiondx += dx / dlen; svd.repulsiondy += dy / dlen; } } } catch (ConcurrentModificationException cme) { calculateRepulsion(); } }
From source file:edu.uci.ics.jung.algorithms.shortestpath.BFSDistanceLabeler.java
/** * Given a node, returns the shortest distance from any node in the root set to v * * @param g the graph in which the distances are to be measured * @param v the node whose distance is to be retrieved * @return the shortest distance from any node in the root set to v *///from www. j a va 2 s . co m public int getDistance(Graph<N> g, N v) { Preconditions.checkArgument(g.nodes().contains(v), "Node %s is not contained in the graph %s", v, g); return distanceDecorator.get(v); }
From source file:edu.uci.ics.jung.layout.algorithms.SpringBHVisitorLayoutAlgorithm.java
/** * Instead of visiting every other Node (n), visit the QuadTree (log(n)) to gather the forces * applied to each Node./*from w w w .ja v a2s .c o m*/ */ @Override protected void calculateRepulsion() { Graph<N> graph = layoutModel.getGraph(); try { for (N node : graph.nodes()) { if (layoutModel.isLocked(node)) { continue; } SpringNodeData svd = springNodeData.getUnchecked(node); if (svd == null) { continue; } ForceObject<N> nodeForceObject = new ForceObject(node, layoutModel.apply(node)) { @Override protected void addForceFrom(ForceObject other) { if (other == null || node == other.getElement()) { return; } Point p = this.p; Point p2 = other.p; if (p == null || p2 == null) { return; } double vx = p.x - p2.x; double vy = p.y - p2.y; double distanceSq = p.distanceSquared(p2); if (distanceSq == 0) { f = f.add(random.nextDouble(), random.nextDouble()); } else if (distanceSq < repulsion_range_sq) { double factor = 1; f = f.add(factor * vx / distanceSq, factor * vy / distanceSq); } } }; tree.applyForcesTo(nodeForceObject); Point f = nodeForceObject.f; double dlen = f.x * f.x + f.y * f.y; if (dlen > 0) { dlen = Math.sqrt(dlen) / 2; svd.repulsiondx += f.x / dlen; svd.repulsiondy += f.y / dlen; } } } catch (ConcurrentModificationException cme) { calculateRepulsion(); } }