Example usage for com.google.common.graph EndpointPair nodeV

List of usage examples for com.google.common.graph EndpointPair nodeV

Introduction

In this page you can find the example usage for com.google.common.graph EndpointPair nodeV.

Prototype

N nodeV

To view the source code for com.google.common.graph EndpointPair nodeV.

Click Source Link

Usage

From source file:io.acoia.graphs.MinimumSpanningTree.java

/**
 * An implementation of Kruskal's minimum spanning tree algorithm.
 * //from w  w w  .j av a2s. c o  m
 * Description from Wiki: Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an
 * edge of the least possible weight that connects any two trees in the forest. It is a greedy
 * algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph
 * adding increasing cost arcs at each step. This means it finds a subset of the edges that forms
 * a tree that includes every vertex, where the total weight of all the edges in the tree is
 * minimized. If the graph is not connected, then it finds a minimum spanning forest (a minimum
 * spanning tree for each connected component).
 * 
 * This implementation uses io.acoia.sets.UnionFind and expects a sorted list of edges, and thus
 * runs in O(E (V)) time.
 */
public static <E, N> ValueGraph<N, E> kruskals(ValueGraph<N, E> g, List<EndpointPair<N>> sortedEdges) {

    if (g.isDirected())
        throw new IllegalArgumentException("Kruskal's does not support directed graphs");

    // Set up a Graph to store the result. 
    MutableValueGraph<N, E> tree = ValueGraphBuilder.undirected().allowsSelfLoops(false)
            .expectedNodeCount(g.nodes().size()).build();

    for (N n : g.nodes()) {
        tree.addNode(n);
    }

    // Now we start kruskals.. most of the work is done by the UnionFind really...
    UnionFind<N> uf = new UnionFind<>(g.nodes());
    for (EndpointPair<N> e : sortedEdges) {

        N nodeU = e.nodeU();
        N nodeV = e.nodeV();

        if (uf.findRoot(nodeU) != uf.findRoot(nodeV)) {
            tree.putEdgeValue(nodeU, nodeV, g.edgeValue(nodeU, nodeV));
            uf.join(nodeU, nodeV);
        }
    }

    return tree;
}

From source file:edu.uci.ics.jung.algorithms.transformation.NodePartitionCollapser.java

/**
 * Creates a new graph whose nodes correspond to the partitions of the supplied graph. Two nodes u
 * and v in the collapsed graph will be connected if there is an edge between any of the nodes in
 * u and any of the nodes in v, and u and v are distinct. The value of the edge represents the
 * number of such edges./* w ww . j  a  v  a  2  s .  c o m*/
 *
 * @param partitioning a node partition of a graph
 * @return the collapsed graph
 */
public static <N> ValueGraph<Set<N>, Integer> collapseNodePartitions(NodePartition<N> partitioning) {
    Graph<N> original = partitioning.getGraph();
    ValueGraphBuilder<Object, Object> builder = original.isDirected() ? ValueGraphBuilder.directed()
            : ValueGraphBuilder.undirected();
    MutableValueGraph<Set<N>, Integer> collapsed = builder.build();

    // create nodes in new graph corresponding to equivalence sets in the original graph
    for (Set<N> set : partitioning.getNodePartitions()) {
        collapsed.addNode(set);
    }

    // for each pair of endpoints in the original graph, connect the corresponding nodes
    // (representing partitions) in the collapsed graph if the partitions are different
    Map<N, Set<N>> nodeToPartition = partitioning.getNodeToPartitionMap();
    for (EndpointPair<N> endpoints : original.edges()) {
        N nodeU = endpoints.nodeU();
        N nodeV = endpoints.nodeV();
        Set<N> partitionU = nodeToPartition.get(nodeU);
        Set<N> partitionV = nodeToPartition.get(nodeV);
        if (nodeU.equals(nodeV) || partitionU.equals(partitionV)) {
            // we only connect partitions if the partitions are different;
            // check the nodes first as an optimization
            continue;
        }

        int edgeCount = collapsed.edgeValueOrDefault(partitionU, partitionV, 0);
        collapsed.putEdgeValue(partitionU, partitionV, edgeCount + 1);
    }
    return collapsed;
}

From source file:edu.uci.ics.jung.visualization.util.ParallelEdgeIndexFunction.java

public int getIndex(Context<Network<N, E>, E> context) {
    Network<N, E> network = context.graph;
    E edge = context.element;/*ww w.  j a va  2  s  .c  o  m*/
    Integer index = edge_index.get(edge);
    if (index == null) {
        EndpointPair<N> endpoints = network.incidentNodes(edge);
        N u = endpoints.nodeU();
        N v = endpoints.nodeV();
        int count = 0;
        for (E connectingEdge : network.edgesConnecting(u, v)) {
            edge_index.put(connectingEdge, count++);
        }
        return edge_index.get(edge);
    }
    return index;
}

From source file:edu.uci.ics.jung.graph.util.ParallelEdgeIndexFunction.java

public int getIndex(E edge) {
    checkNotNull(edge, "edge");
    Integer index = edgeIndex.get(edge);
    if (index == null) {
        EndpointPair<N> endpoints = graph.incidentNodes(edge);
        N u = endpoints.nodeU();//  w  w  w  .  ja  v  a 2 s  . c  o m
        N v = endpoints.nodeV();
        int count = 0;
        for (E connectingEdge : graph.edgesConnecting(u, v)) {
            edgeIndex.put(connectingEdge, count++);
        }
        return edgeIndex.get(edge);
    }
    return index;
}

From source file:edu.uci.ics.jung.visualization.decorators.GradientEdgePaintFunction.java

public Paint apply(E e) {
    EndpointPair<N> endpoints = graph.incidentNodes(e);
    N b = endpoints.nodeU();//from  w  w  w.  j a  v  a  2 s  .  c o  m
    N f = endpoints.nodeV();
    Point pb = layoutModel.apply(b);
    Point pf = layoutModel.apply(f);
    Point2D p2db = transformer.transform(pb.x, pb.y);
    Point2D p2df = transformer.transform(pf.x, pf.y);
    float xB = (float) p2db.getX();
    float yB = (float) p2db.getY();
    float xF = (float) p2df.getX();
    float yF = (float) p2df.getY();
    if (!graph.isDirected()) {
        xF = (xF + xB) / 2;
        yF = (yF + yB) / 2;
    }
    if (isSelfLoop(endpoints)) {
        yF += 50;
        xF += 50;
    }

    return new GradientPaint(xB, yB, getColor1(e), xF, yF, getColor2(e), true);
}

From source file:org.jgrapht.graph.guava.BaseGraphAdapter.java

@Override
public V getEdgeTarget(EndpointPair<V> e) {
    return e.nodeV();
}

From source file:edu.uci.ics.jung.visualization.renderers.BasicEdgeLabelRenderer.java

@Override
public void labelEdge(RenderContext<N, E> renderContext, VisualizationModel<N, E> visualizationModel, E e,
        String label) {/*from   w  w w . j a va 2s  .  c  o m*/
    if (label == null || label.length() == 0) {
        return;
    }

    // don't draw edge if either incident node is not drawn
    EndpointPair<N> endpoints = visualizationModel.getNetwork().incidentNodes(e);
    N v1 = endpoints.nodeU();
    N v2 = endpoints.nodeV();
    Predicate<N> nodeIncludePredicate = renderContext.getNodeIncludePredicate();
    if (!nodeIncludePredicate.test(v1) || !nodeIncludePredicate.test(v2)) {
        return;
    }

    Point p1 = visualizationModel.getLayoutModel().apply(v1);
    Point p2 = visualizationModel.getLayoutModel().apply(v2);
    Point2D p2d1 = renderContext.getMultiLayerTransformer().transform(Layer.LAYOUT,
            new Point2D.Double(p1.x, p1.y));
    Point2D p2d2 = renderContext.getMultiLayerTransformer().transform(Layer.LAYOUT,
            new Point2D.Double(p2.x, p2.y));
    float x1 = (float) p2d1.getX();
    float y1 = (float) p2d1.getY();
    float x2 = (float) p2d2.getX();
    float y2 = (float) p2d2.getY();

    GraphicsDecorator g = renderContext.getGraphicsContext();
    float distX = x2 - x1;
    float distY = y2 - y1;
    double totalLength = Math.sqrt(distX * distX + distY * distY);

    float closeness = renderContext.getEdgeLabelCloseness();

    int posX = (int) (x1 + (closeness) * distX);
    int posY = (int) (y1 + (closeness) * distY);

    int xDisplacement = (int) (renderContext.getLabelOffset() * (distY / totalLength));
    int yDisplacement = (int) (renderContext.getLabelOffset() * (-distX / totalLength));

    Component component = prepareRenderer(renderContext, visualizationModel.getLayoutModel(),
            renderContext.getEdgeLabelRenderer(), label, renderContext.getPickedEdgeState().isPicked(e), e);

    Dimension d = component.getPreferredSize();

    Shape edgeShape = renderContext.getEdgeShapeFunction()
            .apply(Context.getInstance(visualizationModel.getNetwork(), e));

    double parallelOffset = 1;

    parallelOffset += renderContext.getParallelEdgeIndexFunction()
            .getIndex(Context.getInstance(visualizationModel.getNetwork(), e));

    parallelOffset *= d.height;
    if (edgeShape instanceof Ellipse2D) {
        parallelOffset += edgeShape.getBounds().getHeight();
        parallelOffset = -parallelOffset;
    }

    AffineTransform old = g.getTransform();
    AffineTransform xform = new AffineTransform(old);
    xform.translate(posX + xDisplacement, posY + yDisplacement);
    double dx = x2 - x1;
    double dy = y2 - y1;
    if (renderContext.getEdgeLabelRenderer().isRotateEdgeLabels()) {
        double theta = Math.atan2(dy, dx);
        if (dx < 0) {
            theta += Math.PI;
        }
        xform.rotate(theta);
    }
    if (dx < 0) {
        parallelOffset = -parallelOffset;
    }

    xform.translate(-d.width / 2, -(d.height / 2 - parallelOffset));
    g.setTransform(xform);
    g.draw(component, renderContext.getRendererPane(), 0, 0, d.width, d.height, true);

    g.setTransform(old);
}

From source file:edu.uci.ics.jung.visualization.layout.RadiusNetworkElementAccessor.java

/**
 * Gets the edge nearest to the location of the (x,y) location selected, whose endpoints are &lt;
 * {@code maxDistance}. Iterates through all visible nodes and checks their distance from the
 * location. Override this method to provide a more efficient implementation.
 *
 * <p>// * @param layout the context in which the location is defined
 *
 * @param x the x coordinate of the location
 * @param y the y coordinate of the location // * @param maxDistance the maximum distance at which
 *     any element can be from a specified location and still be returned
 * @return an edge which is associated with the location {@code (x,y)} as given by {@code layout}
 *///from   w  w w  .  j  a  va2 s .  co m
@Override
public E getEdge(LayoutModel<N> layoutModel, double x, double y) {
    double minDistance = maxDistance * maxDistance;
    E closest = null;
    while (true) {
        try {
            for (E edge : network.edges()) {
                EndpointPair<N> endpoints = network.incidentNodes(edge);
                N node1 = endpoints.nodeU();
                N node2 = endpoints.nodeV();
                // Get coords
                Point p1 = layoutModel.apply(node1);
                Point p2 = layoutModel.apply(node2);
                double x1 = p1.x;
                double y1 = p1.y;
                double x2 = p2.x;
                double y2 = p2.y;
                // Calculate location on line closest to (x,y)
                // First, check that v1 and v2 are not coincident.
                if (x1 == x2 && y1 == y2) {
                    continue;
                }
                double b = ((y - y1) * (y2 - y1) + (x - x1) * (x2 - x1))
                        / ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
                //
                double distance2; // square of the distance
                if (b <= 0) {
                    distance2 = (x - x1) * (x - x1) + (y - y1) * (y - y1);
                } else if (b >= 1) {
                    distance2 = (x - x2) * (x - x2) + (y - y2) * (y - y2);
                } else {
                    double x3 = x1 + b * (x2 - x1);
                    double y3 = y1 + b * (y2 - y1);
                    distance2 = (x - x3) * (x - x3) + (y - y3) * (y - y3);
                }

                if (distance2 < minDistance) {
                    minDistance = distance2;
                    closest = edge;
                }
            }
            break;
        } catch (ConcurrentModificationException cme) {
        }
    }
    return closest;
}

From source file:org.jgrapht.graph.guava.ImmutableValueGraphAdapter.java

private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject();/*from  www. j  ava  2 s .  c om*/

    // write type
    oos.writeObject(getType());

    // write vertices
    int n = vertexSet().size();
    oos.writeInt(n);
    for (V v : vertexSet()) {
        oos.writeObject(v);
    }

    // write edges
    int m = edgeSet().size();
    oos.writeInt(m);
    for (EndpointPair<V> e : edgeSet()) {
        V u = e.nodeU();
        V v = e.nodeV();
        oos.writeObject(u);
        oos.writeObject(v);
        oos.writeObject(valueGraph.edgeValue(u, v).get());
    }
}

From source file:org.jgrapht.graph.guava.MutableGraphAdapter.java

private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject();/*from   www .ja  v  a  2 s .co m*/

    // write type
    oos.writeObject(getType());

    // write vertices
    int n = vertexSet().size();
    oos.writeInt(n);
    for (V v : vertexSet()) {
        oos.writeObject(v);
    }

    // write edges
    int m = edgeSet().size();
    oos.writeInt(m);
    for (EndpointPair<V> e : edgeSet()) {
        V u = e.nodeU();
        V v = e.nodeV();
        oos.writeObject(u);
        oos.writeObject(v);
    }
}