/** @return the largest connected component of the graph. */ public ArrayList<Cell> getLargestConnectedComponent() { ArrayList<ArrayList<Cell>> components = new ArrayList<>(); boolean visited[][] = new boolean[rowCount][colCount]; for (int row = 0; row < rowCount; ++row) for (int col = 0; col < colCount; ++col) visited[row][col] = false; Queue<Cell> q; Cell t = null, u = null; for (Cell c : g.vertexSet()) { if (!visited[c.getRow()][c.getCol()]) { q = new LinkedList<Cell>(); ArrayList<Cell> component = new ArrayList<>(); visited[c.getRow()][c.getCol()] = true; // Find all connected nodes q.add(c); component.add(c); while (!q.isEmpty()) { t = q.remove(); for (WeightedEdge e : g.edgesOf(t)) { u = t.equals(g.getEdgeSource(e)) ? g.getEdgeTarget(e) : g.getEdgeSource(e); if (!visited[u.getRow()][u.getCol()]) { visited[u.getRow()][u.getCol()] = true; q.add(u); component.add(u); } } } components.add(component); } } int largestSize = 0, largestIndex = 0; for (int i = 0; i < components.size(); ++i) { if (components.get(i).size() > largestSize) { largestSize = components.get(i).size(); largestIndex = i; } } filterGraph(components.get(largestIndex)); return components.get(largestIndex); }
public Queue<Vector2> getPathToPoint(Vector2 origin, Vector2 destination) { LinkedList<Vector2> steps = new LinkedList<Vector2>(); Vector2 originRounded = getClosestNode(Math.round(origin.x), Math.round(origin.y)); Vector2 destinationRounded = getClosestNode(Math.round(destination.x), Math.round(destination.y)); try { List<DefaultWeightedEdge> list = DijkstraShortestPath.findPathBetween(movementGraph, originRounded, destinationRounded); for (DefaultWeightedEdge edge : list) steps.add(movementGraph.getEdgeSource(edge)); steps.add(movementGraph.getEdgeTarget(list.get(list.size() - 1))); } catch (Exception e) { logger.warning( "Error pathfinding for origin=" + originRounded + " destination=" + destinationRounded + " with message: " + e.getMessage()); } return steps; }
/** * Links all the spots in the selection, in time-forward order. * * @param model the model to modify. * @param selectionModel the selection that contains the spots to link. */ public static void linkSpots(final Model model, final SelectionModel selectionModel) { /* * Configure tracker */ final TrackableObjectCollection<Spot> spots = new DefaultTOCollection<Spot>(selectionModel.getSpotSelection()); final Map<String, Object> settings = new HashMap<String, Object>(1); settings.put(KEY_LINKING_MAX_DISTANCE, Double.POSITIVE_INFINITY); final NearestNeighborTracker<Spot> tracker = new NearestNeighborTracker<Spot>(spots, settings); tracker.setNumThreads(1); /* * Execute tracking */ if (!tracker.checkInput() || !tracker.process()) { System.err.println("Problem while computing spot links: " + tracker.getErrorMessage()); return; } final SimpleWeightedGraph<Spot, DefaultWeightedEdge> graph = tracker.getResult(); /* * Copy found links in source model */ model.beginUpdate(); try { for (final DefaultWeightedEdge edge : graph.edgeSet()) { final Spot source = graph.getEdgeSource(edge); final Spot target = graph.getEdgeTarget(edge); model.addEdge(source, target, graph.getEdgeWeight(edge)); } } finally { model.endUpdate(); } }
private void createGraphVisible() { if (graphVisibleBodies == null) graphVisibleBodies = new ArrayList<Body>(); for (int i = 0; i < graphVisibleBodies.size(); i++) world.destroyBody(graphVisibleBodies.get(i)); graphVisibleBodies.clear(); if (nodesVisible) for (Vector2 node : movementGraph.vertexSet()) PhysicsHelper.createCircle(world, BodyType.StaticBody, .1f, 1, FactionType.NEUTRAL) .setTransform(node, 0); if (edgesVisible) for (DefaultWeightedEdge edge : movementGraph.edgeSet()) { Vector2 source = movementGraph.getEdgeSource(edge), target = movementGraph.getEdgeTarget(edge); PhysicsHelper.createEdge( world, BodyType.StaticBody, source.x, source.y, target.x, target.y, 1, FactionType.NEUTRAL); } }
/** * Simulate next step for the given particle. * * @param nextPts * @param particleNum */ public void simulateForwardStep(ArrayList<Point> nextPts, Particle thisParticle) { HashMap<Vertex, Point> thisObservedPosMap = new HashMap<Vertex, Point>(); HashMap<Vertex, AntPath> thisAntPathMap = new HashMap<Vertex, AntPath>(); thisParticle.currentFalsePositives = new ArrayList<Point>(); for (Point pt : nextPts) { Vertex vx = new ObsVertex(); thisObservedPosMap.put(vx, pt); } for (AntPath ap : thisParticle.getPaths()) { Vertex vx = new PathVertex(); thisAntPathMap.put(vx, ap); } /* * Compute probability graph for this particle. */ SimpleWeightedGraph<Vertex, DefaultWeightedComparableEdge> probabilityGraph = new SimpleWeightedGraph<Vertex, DefaultWeightedComparableEdge>( DefaultWeightedComparableEdge.class); ValueSortedMap<DefaultWeightedComparableEdge, Double> edgeMap = new ValueSortedMap<DefaultWeightedComparableEdge, Double>(true); computeLogProbabilityGraph(probabilityGraph, edgeMap, thisObservedPosMap, thisAntPathMap); // displayLogProbabilityGraph(probabilityGraph,thisObservedPosMap,thisAntPathMap,vertexSums); /* * Generate new ant locations based on probability graph. We do this by sampling the most likely event, * removing this event from the probability graph, updating the prob. graph, then repeating until all * observations/causes are accounted for. * * To do this (relatively) efficiently, we maintain a sorted hash-map of possible observation/cause pairs. * To avoid having to rescale the entire hash-map every step, we maintain the current sum of weights. * * We're also keeping track of the posterior log-probability of the simulated step. */ double logprob = 0; int nfp = 0; int nfn = 0; int doOutput = 0; while (edgeMap.size() > 0) { /* * Sample an event from the probability graph. */ DefaultWeightedComparableEdge event = sampleEdge(probabilityGraph, edgeMap); edgeMap.remove(event); double edgeWeight = probabilityGraph.getEdgeWeight(event); double thisLogProb = edgeWeight; logprob = logprob + thisLogProb; Vertex v1 = probabilityGraph.getEdgeSource(event); Vertex v2 = probabilityGraph.getEdgeTarget(event); if (doOutput > 0) { System.err.println("edgeWeight: " + edgeWeight); doOutput = outputInterestingStuff(v1, v2, probabilityGraph); } if (v1.getClass().equals(ObsVertex.class)) { assert (v2.getClass().equals(PathVertex.class)); Vertex tv = v1; v1 = v2; v2 = tv; } /* * Update the probability graph. */ if (!v1.equals(falsePositive)) { Set<DefaultWeightedComparableEdge> es = probabilityGraph.edgesOf(v1); for (DefaultWeightedComparableEdge ed : es) edgeMap.remove(ed); boolean tt = probabilityGraph.removeVertex(v1); assert (tt); } else { nfp += 1; thisParticle.currentFalsePositives.add(thisObservedPosMap.get(v2)); } if (!v2.equals(falseNegative)) { Set<DefaultWeightedComparableEdge> es = probabilityGraph.edgesOf(v2); for (DefaultWeightedComparableEdge ed : es) edgeMap.remove(ed); boolean tt = probabilityGraph.removeVertex(v2); assert (tt); } else nfn += 1; // Utils.computeVertexSums(probabilityGraph,vertexSums); /* * Update AntPath trajectory. */ if (!v1.equals(falsePositive)) { AntPath ap = thisAntPathMap.get(v1); assert (ap != null); Point obs = thisObservedPosMap.get(v2); Point newPos = new Point(); double thislp = sampleConditionalPos(ap, obs, newPos) + thisLogProb; ap.updatePosition(newPos, obs, thislp); } /* * Compute likelihoods. */ } }
public EdgeBetweennessGraph(WeightedMultigraph<String, DefaultWeightedEdge> originalGraph) { super(DefaultWeightedEdge.class); // Constructor inherented from parent class // 1. Initialize the edge betweenness digraph // 1.1. Add vertices for (String thisVertex : originalGraph.vertexSet()) this.addVertex(thisVertex); // 1.2. Add edges for (DefaultWeightedEdge thisEdge : originalGraph.edgeSet()) { DefaultWeightedEdge newEdge = new DefaultWeightedEdge(); String sendingName = originalGraph.getEdgeSource(thisEdge); String receivingName = originalGraph.getEdgeTarget(thisEdge); this.addEdge(sendingName, receivingName, newEdge); this.setEdgeWeight(newEdge, 0.0); } // 1.3. Create corresponding unweighted graph // 1.3.1. Add vertices WeightedMultigraph<String, DefaultWeightedEdge> originalUnweightedGraph = new WeightedMultigraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); for (String thisVertex : originalGraph.vertexSet()) originalUnweightedGraph.addVertex(thisVertex); // 1.3.2. Add edges for (DefaultWeightedEdge thisEdge : originalGraph.edgeSet()) { DefaultWeightedEdge newEdge = new DefaultWeightedEdge(); String sendingName = originalGraph.getEdgeSource(thisEdge); String receivingName = originalGraph.getEdgeTarget(thisEdge); originalUnweightedGraph.addEdge(sendingName, receivingName, newEdge); originalUnweightedGraph.setEdgeWeight(newEdge, 1.0); } for (String thisVertex : this.vertexSet()) { // 2. Create shortest-path graph for every vertex by Dijkstra algorithm Multigraph<String, DefaultEdge> shortestPathDigraph = DijkstraAlgorithm(originalUnweightedGraph, thisVertex); // 3. Calculate the contribution of current vertex's shortest-path graph to final edge // betweenness (Newman algorithm) SimpleWeightedGraph<String, DefaultWeightedEdge> edgeBetweennessDigraph = NewmanAlgorithm(shortestPathDigraph, thisVertex); // 4. Update final edge betweenness digraph with current vertex's shortest-path graph if (edgeBetweennessDigraph != null) for (DefaultWeightedEdge thisEdge : edgeBetweennessDigraph.edgeSet()) { String sourceVertex = edgeBetweennessDigraph.getEdgeSource(thisEdge); String targetVertex = edgeBetweennessDigraph.getEdgeTarget(thisEdge); double betweennessWeight = edgeBetweennessDigraph.getEdgeWeight(thisEdge); DefaultWeightedEdge edgeInWholeGraph = this.getEdge(sourceVertex, targetVertex); double newWeight = this.getEdgeWeight(edgeInWholeGraph) + betweennessWeight; this.setEdgeWeight(edgeInWholeGraph, newWeight); } } // 5. Revise the edge betweenness digraph with the original active power digraph for (DefaultWeightedEdge thisEdge : this.edgeSet()) { String sourceVertex = this.getEdgeSource(thisEdge); String targetVertex = this.getEdgeTarget(thisEdge); double betweennessWeight = this.getEdgeWeight(thisEdge); DefaultWeightedEdge edgeInWholeGraph = originalGraph.getEdge(sourceVertex, targetVertex); double newWeight = betweennessWeight / originalGraph.getEdgeWeight(edgeInWholeGraph); this.setEdgeWeight(thisEdge, newWeight); // System.out.println("Final edge betweenness between " + sourceVertex + " and " + // targetVertex + ": " + newWeight); } }
// Create shortest-path graph for every vertex by depth-first traversal algorithm private Multigraph<String, DefaultEdge> DijkstraAlgorithm( WeightedMultigraph<String, DefaultWeightedEdge> originalGraph, String thisVertex) { // 1. Simplify the multi-graph of the active power flow into a simple graph SimpleWeightedGraph<String, DefaultWeightedEdge> originalSimpleGraph = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); for (String curVertex : originalGraph.vertexSet()) originalSimpleGraph.addVertex(curVertex); for (DefaultWeightedEdge curEdge : originalGraph.edgeSet()) { String sourceVertex = originalGraph.getEdgeSource(curEdge); String targetVertex = originalGraph.getEdgeTarget(curEdge); if (originalSimpleGraph.containsEdge(sourceVertex, targetVertex)) { DefaultWeightedEdge modifiedEdge = originalSimpleGraph.getEdge(sourceVertex, targetVertex); double newEdgeWeight = originalSimpleGraph.getEdgeWeight(modifiedEdge) + originalGraph.getEdgeWeight(curEdge); originalSimpleGraph.setEdgeWeight(modifiedEdge, newEdgeWeight); } else { DefaultWeightedEdge newEdge = new DefaultWeightedEdge(); originalSimpleGraph.addEdge(sourceVertex, targetVertex, newEdge); originalSimpleGraph.setEdgeWeight(newEdge, originalGraph.getEdgeWeight(curEdge)); } } // Issue (2010/10/25): Maybe larger amount of active power transfer still means weaker // relationship between the two terminal buses of a certain branch, // thus originalSimpleGraph other than inverseGraph should be used here. // Use the inverse of active power to build a new weighted directed graph (the larger the active // power is, the close the two buses will be) // SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> inverseGraph = // new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); // for (String curVertex : originalSimpleGraph.vertexSet()) // inverseGraph.addVertex(curVertex); // for (DefaultWeightedEdge curEdge : originalSimpleGraph.edgeSet()) { // String sourceVertex = originalSimpleGraph.getEdgeSource(curEdge); // String targetVertex = originalSimpleGraph.getEdgeTarget(curEdge); // DefaultWeightedEdge newEdge = new DefaultWeightedEdge(); // inverseGraph.addEdge(sourceVertex, targetVertex, newEdge); // inverseGraph.setEdgeWeight(newEdge, 1 / originalSimpleGraph.getEdgeWeight(curEdge)); // } // 2. Initialize the map of vertices and the corresponding weights (distance from current vertex // to the first vertex) HashMap<String, Double> mapVertexShortestDistance = new HashMap<String, Double>(); // for (String thisOriginalVertex : inverseGraph.vertexSet()) for (String thisOriginalVertex : originalSimpleGraph.vertexSet()) mapVertexShortestDistance.put(thisOriginalVertex, 10E10); // The weight of the first vertex is zero mapVertexShortestDistance.put(thisVertex, 0.0); // 3. Depth-first traversing, update the shortest-path values Stack<String> bfiVertices = new Stack<String>(); // Stack to store passed vertices in a breadth-first traversing // The map of a weighted edge and the flag of having been visited // HashMap<DefaultWeightedEdge, Boolean> mapEdgeVisited = new HashMap<DefaultWeightedEdge, // Boolean>(); // for (DefaultWeightedEdge thisEdge : inverseGraph.edgeSet()) // mapEdgeVisited.put(thisEdge, false); String currentVertex = thisVertex; bfiVertices.push(currentVertex); // System.out.println(bfiVertices.toString()); while (!bfiVertices.isEmpty()) { // Operate the following codes for those edges started with current vertex boolean hasNewEdge = false; // for (DefaultWeightedEdge curEdge : inverseGraph.outgoingEdgesOf(currentVertex)) { for (DefaultWeightedEdge curEdge : originalSimpleGraph.edgesOf(currentVertex)) { // if (!mapEdgeVisited.get(curEdge)) { // Used for those edges that have not been treated // yet // 3.1. Mark current edge as already been visited // mapEdgeVisited.put(curEdge, true); // String nextVertex = inverseGraph.getEdgeTarget(curEdge); String nextVertex = originalSimpleGraph.getEdgeTarget(curEdge); // 3.2. Update shortest-path values double curSD = mapVertexShortestDistance.get(currentVertex); // double edgeWeight = inverseGraph.getEdgeWeight(curEdge); double edgeWeight = originalSimpleGraph.getEdgeWeight(curEdge); double newSD = curSD + edgeWeight; if (mapVertexShortestDistance.get(nextVertex) > newSD) { hasNewEdge = true; mapVertexShortestDistance.put(nextVertex, newSD); // 3.3. Push the target vertex of current edge into the stack bfiVertices.push(nextVertex); // System.out.println(bfiVertices.toString()); break; // System.out.println("New shortest path [" + nextVertex + "]: " + newSD); } // } } if (!hasNewEdge) { bfiVertices.pop(); } if (!bfiVertices.isEmpty()) currentVertex = bfiVertices.peek(); } // 4. Create shortest-path digraph of current vertex // 4.1. Initialize the shortest-path digraph Multigraph<String, DefaultEdge> shortestPathGraph = new Multigraph<String, DefaultEdge>(DefaultEdge.class); // 4.2. Add all qualified edges // for (DefaultWeightedEdge curEdge : inverseGraph.edgeSet()) { for (DefaultWeightedEdge curEdge : originalSimpleGraph.edgeSet()) { // 4.2.1. Evaluate if current edge is suitable // String sourceVertex = inverseGraph.getEdgeSource(curEdge); // String targetVertex = inverseGraph.getEdgeTarget(curEdge); String sourceVertex = originalSimpleGraph.getEdgeSource(curEdge); String targetVertex = originalSimpleGraph.getEdgeTarget(curEdge); // if (Math.abs(inverseGraph.getEdgeWeight(curEdge) - if (originalSimpleGraph.getEdgeWeight(curEdge) > 1.0E-5) { if (Math.abs( originalSimpleGraph.getEdgeWeight(curEdge) - (mapVertexShortestDistance.get(targetVertex) - mapVertexShortestDistance.get(sourceVertex))) < 1.0E-5) { // 4.2.2. Add suitable edge that found just now DefaultEdge newEdge = new DefaultEdge(); if (!shortestPathGraph.containsVertex(sourceVertex)) shortestPathGraph.addVertex(sourceVertex); if (!shortestPathGraph.containsVertex(targetVertex)) shortestPathGraph.addVertex(targetVertex); shortestPathGraph.addEdge(sourceVertex, targetVertex, newEdge); } } } return shortestPathGraph; }