/** * chooses the cluster with the highest number of semantic concepts that correspond to different * search keywords * * @param graph the graph * @param correspondingKeywords Mapping of semantic concepts (nodeIDs) to search keywords */ public void filterClusterByInterconnectionLevel( WTPGraph graph, Map<String, String> correspondingKeywords) { Set<Set<String>> clusters = getClusters(graph); printClusters(clusters); Set<Set<String>> resultClusters = new HashSet<Set<String>>(); // get biggest number of corresponding keywords of one cluster int maxNumberOfCorrespondingKeywords = 0; for (Set<String> cluster : clusters) { int numOfDifferentCorrespondingKeywords = getNumberOfCorrespondingKeywords(cluster, correspondingKeywords); System.out.println( "Number of different corresponding keywords: " + numOfDifferentCorrespondingKeywords); if (numOfDifferentCorrespondingKeywords > maxNumberOfCorrespondingKeywords) { maxNumberOfCorrespondingKeywords = numOfDifferentCorrespondingKeywords; resultClusters = new HashSet<Set<String>>(); resultClusters.add(cluster); } else if (numOfDifferentCorrespondingKeywords == maxNumberOfCorrespondingKeywords) { resultClusters.add(cluster); } } Set<String> survivingNodes = new HashSet<String>(); for (Set<String> cluster : resultClusters) { survivingNodes.addAll(cluster); } Set<Node> dyingNodes = new HashSet<Node>(); for (Node n : graph.getGraph().getNodeSet()) { if (!survivingNodes.contains(n.getId())) dyingNodes.add(n); } graph.getGraph().getNodeSet().removeAll(dyingNodes); }
/** * Clone a given graph with same node/edge structure and same attributes. * * @param g the graph to clone * @return a copy of g */ public static Graph clone(Graph g) { Graph copy; try { Class<? extends Graph> cls = g.getClass(); copy = cls.getConstructor(String.class).newInstance(g.getId()); } catch (Exception e) { logger.warning(String.format("Cannot create a graph of %s.", g.getClass().getName())); copy = new AdjacencyListGraph(g.getId()); } copyAttributes(g, copy); for (int i = 0; i < g.getNodeCount(); i++) { Node source = g.getNode(i); Node target = copy.addNode(source.getId()); copyAttributes(source, target); } for (int i = 0; i < g.getEdgeCount(); i++) { Edge source = g.getEdge(i); Edge target = copy.addEdge( source.getId(), source.getSourceNode().getId(), source.getTargetNode().getId(), source.isDirected()); copyAttributes(source, target); } return copy; }
@SuppressWarnings("unchecked") private void pathSetShortestPath_facilitate(Node current, Path path, List<Path> paths) { Node source = graph.getNode(this.source_id); if (current != source) { Node next = null; ArrayList<? extends Edge> predecessors = (ArrayList<? extends Edge>) current.getAttribute(identifier + ".predecessors"); while (current != source && predecessors.size() == 1) { Edge e = predecessors.get(0); next = e.getOpposite(current); path.add(current, e); current = next; predecessors = (ArrayList<? extends Edge>) current.getAttribute(identifier + ".predecessors"); } if (current != source) { for (Edge e : predecessors) { Path p = path.getACopy(); p.add(current, e); pathSetShortestPath_facilitate(e.getOpposite(current), p, paths); } } } if (current == source) { paths.add(path); } }
public BenchPerformance(String fileName, Graph graph) { r = Runtime.getRuntime(); forceGC(); long used1 = r.totalMemory() - r.freeMemory(); g = graph; try { g.read(fileName); } catch (Exception e) { e.printStackTrace(); System.exit(0); } System.out.println( "Graph read: " + g.getNodeCount() + " nodes and " + g.getEdgeCount() + " edges"); for (Node n : g) n.clearAttributes(); for (Edge e : g.getEachEdge()) e.clearAttributes(); forceGC(); long used2 = r.totalMemory() - r.freeMemory(); measureValues = new EnumMap<Measures, Long>(Measures.class); measureValues.put(Measures.MEMORY, used2 - used1); nodeIds = new ArrayList<String>(g.getNodeCount()); for (Node n : g) nodeIds.add(n.getId()); // sort them to be sure that we always work with the same nodes Collections.sort(nodeIds); edgeIds = new ArrayList<String>(g.getEdgeCount()); for (Edge e : g.getEachEdge()) edgeIds.add(e.getId()); Collections.sort(edgeIds); }
public int testBfsDfs() { int foo = 0; // BFS from 1000 nodes start = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { Iterator<Node> bfsIt = g.getNode(nodeIds.get(i)).getBreadthFirstIterator(); while (bfsIt.hasNext()) { Node node = bfsIt.next(); if (node.hasAttribute("foo")) foo++; } } end = System.currentTimeMillis(); measureValues.put(Measures.BFS_IT, end - start); // DFS from 1000 nodes - tested only for new implementations // because of a bug in the old start = System.currentTimeMillis(); if (g instanceof org.graphstream.graph.implementations.AbstractGraph) { for (int i = 0; i < 1000; i++) { Iterator<Node> dfsIt = g.getNode(nodeIds.get(i)).getDepthFirstIterator(); while (dfsIt.hasNext()) { Node node = dfsIt.next(); if (node.hasAttribute("foo")) foo++; } } } end = System.currentTimeMillis(); measureValues.put(Measures.DFS_IT, end - start); return foo; }
public int testGraphIterators() { int foo = 0; // Iterating on all nodes start = System.currentTimeMillis(); Iterator<Node> nodeIt = g.getNodeIterator(); while (nodeIt.hasNext()) { Node n = nodeIt.next(); if (n.hasAttribute("foo")) foo++; } end = System.currentTimeMillis(); measureValues.put(Measures.GRAPH_NODE_IT, end - start); // iterating on all edges start = System.currentTimeMillis(); Iterator<Edge> edgeIt = g.getEdgeIterator(); while (edgeIt.hasNext()) { Edge e = edgeIt.next(); if (e.hasAttribute("foo")) foo++; } end = System.currentTimeMillis(); measureValues.put(Measures.GRAPH_EDGE_IT, end - start); return foo; }
/** * This methods deletes all nodes of the graph that are not part of a path * * @param paths all paths that are interconnecting nodes, which correspond to different keywords * @param graph the graph */ private void filterInterconnectedNodes(List<Path> paths, WTPGraph graph) { // NodeIDs of the nodes that are part of at least one of the path Set<String> interconnectedNodeIDs = new HashSet<String>(); // Write all nodeIDs included in at least one of the path into the interconnectedNodeIDs Set for (Path p : paths) { System.out.println("Path: " + p.toString()); for (Node n : p) { interconnectedNodeIDs.add(n.getId()); } } System.out.println( "Count of Nodes before interconnectionFiltering: " + graph.getGraph().getNodeCount()); // Nodes whose nodeID is not included in interconnectedNodeIDs and which should be deleted, // because they are not interconnected List<Node> notInterconnectedNodes = new LinkedList<Node>(); for (Node n : graph.getGraph().getNodeSet()) { if (!interconnectedNodeIDs.contains(n.getId())) notInterconnectedNodes.add(n); } // remove all of the not interconnected Nodes graph.getGraph().getNodeSet().removeAll(notInterconnectedNodes); System.out.println( "Count of Nodes after interconnectionFiltering:" + graph.getGraph().getNodeCount()); }
public <T extends Node> T getNode(int index) throws IndexOutOfBoundsException { Node n; elementLock.lock(); n = wrappedElement.getNode(index); elementLock.unlock(); return n == null ? null : this.<T>getNode(n.getId()); }
/** * @param graph the graph * @param relevanceThreshold atleast number of including paths to be relevant */ private void removeNodesWithLessThanNOccurrences(WTPGraph graph, int minNumOfOccurrences) { if (countOfNodeOccurrencesInPaths != null) { LinkedList<Node> nodesToDelete = new LinkedList<Node>(); for (Node node : graph.getGraph().getNodeSet()) { Integer occurrenceCount = countOfNodeOccurrencesInPaths.get(node.getId()); if (occurrenceCount == null || occurrenceCount < minNumOfOccurrences) nodesToDelete.add(node); } graph.getGraph().getNodeSet().removeAll(nodesToDelete); // System.out.println("nodes filtered by number of including paths heuristic"); } }
SynchronizedGraph(Graph g) { super(g); elementLock = new ReentrantLock(); synchronizedNodes = new HashMap<String, Node>(); synchronizedEdges = new HashMap<String, Edge>(); for (Node n : g.getEachNode()) synchronizedNodes.put(n.getId(), new SynchronizedNode(this, n)); for (Edge e : g.getEachEdge()) synchronizedEdges.put(e.getId(), new SynchronizedEdge(this, e)); }
private Set<Set<String>> getClusters(WTPGraph graph) { visitedWhileClustering = new HashSet<String>(); Set<Set<String>> clusters = new HashSet<Set<String>>(); // for each node of the graph: if not yet in a cluster, try to generate the cluster starting // with this node for (Node n : graph.getGraph().getNodeSet()) { String id = n.getId(); if (!visitedWhileClustering.contains(id)) { clusters.add(getCluster(graph, id)); } } return clusters; }
// For adding Node To Graph public void AddNodeToGraph(String IP, boolean IsSwitch) { String temp; if (IsSwitch) { temp = "OpenVSwitch"; } else { temp = "EndHost"; } network_graph.addNode(temp + " [" + IP + "]"); Node node = network_graph.getNode(temp + " [" + IP + "]"); node.addAttribute("ui.class", temp); node.addAttribute("ui.label", node.getId()); }
/** * this method counts in how many paths of paths each node is included and generates the * corresponding map * * @param paths all remaining paths of the graph */ private void countOccurrencesInPaths(List<Path> paths) { countOfNodeOccurrencesInPaths = new HashMap<String, Integer>(); for (Path p : paths) { for (Node n : p) { Integer occurrenceCount = countOfNodeOccurrencesInPaths.get(n.getId()); // if already occurred in another path if (occurrenceCount != null) countOfNodeOccurrencesInPaths.put(n.getId(), occurrenceCount + 1); // else first occurrence in a path else countOfNodeOccurrencesInPaths.put(n.getId(), 1); } } }
@Override protected void originateCommunity(Node node) { super.originateCommunity(node); // Correct the original community score for the Leung algorithm node.setAttribute(marker + ".score", 1.0); }
/** * Process each node to check if it is in the actual view port, and mark invisible nodes. This * method allows for fast node, sprite and edge visibility checking when drawing. This must be * called before each rendering (if the view port changed). */ public void checkVisibility(GraphicGraph graph) { double X = metrics.viewport[0]; double Y = metrics.viewport[1]; double W = metrics.viewport[2]; double H = metrics.viewport[3]; nodeInvisible.clear(); for (Node node : graph) { boolean visible = isNodeIn((GraphicNode) node, X, Y, X + W, Y + H) && (!((GraphicNode) node).hidden) && ((GraphicNode) node).positionned; if (!visible) nodeInvisible.add(node.getId()); } }
/** * Like {@link #nodePosition(Graph,String,Point3)} but use an existing node as argument. * * @param node The node to consider. * @param pos A point that will receive the node position. */ public static void nodePosition(Node node, Point3 pos) { if (node.hasAttribute("xyz") || node.hasAttribute("xy")) { Object o = node.getAttribute("xyz"); if (o == null) o = node.getAttribute("xy"); if (o != null) { positionFromObject(o, pos); } } else if (node.hasAttribute("x")) { pos.x = (double) node.getNumber("x"); if (node.hasAttribute("y")) pos.y = (double) node.getNumber("y"); if (node.hasAttribute("z")) pos.z = (double) node.getNumber("z"); } // if (node.hasAttribute("xyz") || node.hasAttribute("xy")) { // Object o = node.getAttribute("xyz"); // // if (o == null) // o = node.getAttribute("xy"); // // if (o != null && o instanceof Object[]) { // Object oo[] = (Object[]) o; // // if (oo.length > 0 && oo[0] instanceof Number) { // pos.x = ((Number) oo[0]).doubleValue(); // // if (oo.length > 1) // pos.y = ((Number) oo[1]).doubleValue(); // if (oo.length > 2) // pos.z = ((Number) oo[2]).doubleValue(); // } // } // } else if (node.hasAttribute("x")) { // pos.x = (double) node.getNumber("x"); // // if (node.hasAttribute("y")) // pos.y = (double) node.getNumber("y"); // // if (node.hasAttribute("z")) // pos.z = (double) node.getNumber("z"); // } }
private void defaultVisit(CFrame frame) { MultiGraph graph = this.view.getGraph(); graph.getNodeSet().clear(); graph.getEdgeSet().clear(); // this.baseIRIList = new HashSet<String>(); // Получение всех элементов и формирование из них визуального части. for (OWLNamedIndividual owlName : frame.getContent().getConcepts()) { String label = this.model.getLabel(owlName); if (label.equals("_EMPTY_")) { label = owlName.getIRI().getFragment().toString(); } Node node = graph.addNode(owlName.getIRI().toString()); node.addAttribute("OWLNamedIndividual", owlName); node.addAttribute("ui.label", label); if (owlName.getIRI().equals(frame.getTrgConcept().getIRI())) { node.setAttribute("ui.class", "concept"); } } // Связывает все элементы линиями. for (Branch br : frame.getContent().getBranches()) { Node nodeSub = null; Node nodeObj = null; for (Node node : graph.getNodeSet()) { if (node.getId().equals(br.getSubject().getIRI().toString())) { nodeSub = node; continue; } else { if (node.getId().equals(br.getObject().getIRI().toString())) { nodeObj = node; continue; } } if (nodeSub != null && nodeObj != null) { break; } } // Создает элемент линия для двух node. Edge edge = graph.addEdge(br.getBrachIndIRI().toString(), nodeSub, nodeObj, true); String labelEdge = this.model.getAnnotationValue(br.getPrp().getIRI()); if (labelEdge.equals("_EMPTY_")) { labelEdge = br.getPrp().getIRI().getFragment().toString(); } edge.addAttribute("ui.label", labelEdge); } }
/** * Like {@link #nodePosition(Graph,String,double[])} but use an existing node as argument. * * @param node The node to consider. * @param xyz An array of at least three cells. */ public static void nodePosition(Node node, double xyz[]) { if (xyz.length < 3) return; if (node.hasAttribute("xyz") || node.hasAttribute("xy")) { Object o = node.getAttribute("xyz"); if (o == null) o = node.getAttribute("xy"); if (o != null) { positionFromObject(o, xyz); } } else if (node.hasAttribute("x")) { xyz[0] = (double) node.getNumber("x"); if (node.hasAttribute("y")) xyz[1] = (double) node.getNumber("y"); if (node.hasAttribute("z")) xyz[2] = (double) node.getNumber("z"); } }
/** * Returns the shortest path between the source node and one given target. If multiple shortest * paths exist, one of them is returned at random. * * @param target the target of the shortest path starting at the source node given in the * constructor. * @return A {@link org.graphstream.graph.Path} object that constrains the list of nodes and edges * that constitute it. */ @SuppressWarnings("unchecked") public Path getShortestPath(Node target) { Path p = new Path(); if (target == source) { return p; } boolean noPath = false; Node v = target; while (v != source && !noPath) { ArrayList<? extends Edge> list = (ArrayList<? extends Edge>) v.getAttribute(identifier + ".predecessors"); if (list == null) { noPath = true; } else { Edge parentEdge = list.get(0); p.add(v, parentEdge); v = parentEdge.getOpposite(v); } } return p; }
public void filterClusterBySize(WTPGraph graph) { Set<Set<String>> clusters = getClusters(graph); printClusters(clusters); Set<String> survivingNodes = new HashSet<String>(); int maxClusterSize = 0; for (Set<String> cluster : clusters) { System.out.println("Size of Cluster: " + cluster.size()); if (cluster.size() > maxClusterSize) { maxClusterSize = cluster.size(); survivingNodes = new HashSet<String>(); survivingNodes.addAll(cluster); } else if (cluster.size() == maxClusterSize) { survivingNodes.addAll(cluster); } } Set<Node> dyingNodes = new HashSet<Node>(); for (Node n : graph.getGraph().getNodeSet()) { if (!survivingNodes.contains(n.getId())) dyingNodes.add(n); } graph.getGraph().getNodeSet().removeAll(dyingNodes); }
public static void main(String[] args) throws PyException, IOException { String[] argss = new String[] {"C:\\Python27\\python.exe", "D:\\pydemo.py", "D:\\large.txt"}; readInputFile(argss[2], 1); createGraph(network); Process process = null; try { process = Runtime.getRuntime().exec(argss); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; int i = -1; try { while ((line = bufferedReader.readLine()) != null) { System.out.println(line); if (line.equals("Community: ")) { i++; } else { Node node = graph.getNode(line); if (node != null) { node.addAttribute("ui.label", i + ""); } } } } catch (IOException e) { e.printStackTrace(); } System.out.println("Num of Nodes:" + network.nNodes); System.out.println("Num of Edges:" + network.nEdges); System.out.println("Num of Communities:" + (i + 1)); }
public int testAccessById() { int foo = 0; // access each node by id start = System.currentTimeMillis(); for (String id : nodeIds) { Node n = g.getNode(id); if (n.hasAttribute("foo")) foo++; } end = System.currentTimeMillis(); measureValues.put(Measures.NODE_BY_ID, end - start); // access each edge by id start = System.currentTimeMillis(); for (String id : edgeIds) { Edge e = g.getEdge(id); if (e.hasAttribute("foo")) foo++; } end = System.currentTimeMillis(); measureValues.put(Measures.EDGE_BY_ID, end - start); return foo; }
@Override protected void makeTree() { if (treeEdges == null) treeEdges = new LinkedList<Edge>(); else treeEdges.clear(); int n = graph.getNodeCount(); Data[] data = new Data[n]; FibonacciHeap<Double, Node> heap = new FibonacciHeap<Double, Node>(); for (int i = 0; i < n; i++) { data[i] = new Data(); data[i].edgeToTree = null; data[i].fn = heap.add(Double.POSITIVE_INFINITY, graph.getNode(i)); } treeWeight = 0; while (!heap.isEmpty()) { Node u = heap.extractMin(); Data dataU = data[u.getIndex()]; data[u.getIndex()] = null; if (dataU.edgeToTree != null) { treeEdges.add(dataU.edgeToTree); edgeOn(dataU.edgeToTree); treeWeight += dataU.fn.getKey(); dataU.edgeToTree = null; } dataU.fn = null; for (Edge e : u) { Node v = e.getOpposite(u); Data dataV = data[v.getIndex()]; if (dataV == null) continue; double w = getWeight(e); if (w < dataV.fn.getKey()) { heap.decreaseKey(dataV.fn, w); dataV.edgeToTree = e; } } } }
/** * This methods deletes all paths of paths that are not interconnection between two nodes, which * correspond to different keywords * * @param paths all possible paths of the graph * @param correspondingKeywords a map which delivers the corresponding search keyword for each * semantic concept (nodeID) */ private static void filterInterconnectingPaths( List<Path> paths, Map<String, String> correspondingKeywords) { // Paths that are not interconnecting two nodes of different search keywords LinkedList<Path> notInterconnectingPaths = new LinkedList<Path>(); // counts for each path how often semantic concepts by the same corresponding keyword occur for (Path path : paths) { // counts the occurrence of the keywords OccurenceCounter<String> occurrenceCounter = new OccurenceCounter<String>(); // counts occurrence of the corresponding keyword for each nodes for (Node n : path) { occurrenceCounter.inc(correspondingKeywords.get(n.getId())); } // to stop if their are at least two nodes that correspond to the same keyword on the same // path boolean alReadyadded = false; for (Entry<String, Integer> e : occurrenceCounter.entrySet()) { // if the occurrence counter is bigger than 1 --> the Path is not interconnecting if (e.getValue() > 1 && !alReadyadded) { notInterconnectingPaths.add(path); alReadyadded = true; } } } System.out.println("Count of all paths: " + paths.size()); System.out.println( "Count of paths that are not interconnecting: " + notInterconnectingPaths.size()); paths.removeAll(notInterconnectingPaths); System.out.println("Count of remaining paths: " + paths.size()); }
public void filterClusterByNodeOccurrencesInPaths(WTPGraph graph, List<Path> paths) { Set<Set<String>> clusters = getClusters(graph); printClusters(clusters); Set<String> survivingNodes = new HashSet<String>(); int maxOccurrance = 0; for (Set<String> cluster : clusters) { int count = getNumberOfClusterOccurrencesInPaths(cluster, paths); System.out.println("Number of cluster occurrences in paths: " + count); if (count > maxOccurrance) { maxOccurrance = count; survivingNodes = new HashSet<String>(); survivingNodes.addAll(cluster); } else if (count == maxOccurrance) { survivingNodes.addAll(cluster); } } Set<Node> dyingNodes = new HashSet<Node>(); for (Node n : graph.getGraph().getNodeSet()) { if (!survivingNodes.contains(n.getId())) dyingNodes.add(n); } graph.getGraph().getNodeSet().removeAll(dyingNodes); }
@Override public MyGraph generate(int nbVertex, int nbChips) { MyGraph graph = new MyGraph(false); if (nbVertex <= 1) { return graph; } int i = 1, j = 1; while (j < nbVertex) { j++; graph.addEdge("" + i + "" + j, "" + i, "" + j, true); i++; } graph.addEdge("" + nbVertex + "1", "" + nbVertex, "1", true); for (Node node : graph.getNodeSet()) { node.addAttribute("label", nbChips); } return graph; }
public int testTriangleCount() { start = System.currentTimeMillis(); int count = 0; for (Node n0 : g) { int d = n0.getDegree(); for (int i = 0; i < d; i++) { Node n1 = n0.getEdge(i).getOpposite(n0); String n1id = n1.getId(); for (int j = i + 1; j < d; j++) { Node n2 = n0.getEdge(j).getOpposite(n0); if (n2.hasEdgeBetween(n1id)) count++; } } } end = System.currentTimeMillis(); measureValues.put(Measures.TRIANGLE, end - start); return count / 3; }
public int testFindEdge() { int foo = 0; // for each pair of nodes (n1, n2) find the edge between n1 and n2 long start = System.currentTimeMillis(); for (String id1 : nodeIds) { Node n1 = g.getNode(id1); for (String id2 : nodeIds) { Edge e = n1.getEdgeBetween(id2); if (e != null && e.hasAttribute("foo")) foo++; } } end = System.currentTimeMillis(); measureValues.put(Measures.EDGE_BETWEEN, end - start); // for each pair of nodes (n1, n2) find the edge from n1 to n2 start = System.currentTimeMillis(); for (String id1 : nodeIds) { Node n1 = g.getNode(id1); for (String id2 : nodeIds) { Edge e = n1.getEdgeToward(id2); if (e != null && e.hasAttribute("foo")) foo++; } } end = System.currentTimeMillis(); measureValues.put(Measures.EDGE_TOWARD, end - start); // for each pair of nodes (n1, n2) find the edge from n2 to n1 start = System.currentTimeMillis(); for (String id1 : nodeIds) { Node n1 = g.getNode(id1); for (String id2 : nodeIds) { Edge e = n1.getEdgeFrom(id2); if (e != null && e.hasAttribute("foo")) foo++; } } end = System.currentTimeMillis(); measureValues.put(Measures.EDGE_FROM, end - start); return foo; }
/* * (non-Javadoc) * * @see org.graphstream.algorithm.Algorithm#compute() */ public void compute() { float min = Float.MAX_VALUE; HashSet<Node> centroid = new HashSet<Node>(); for (Node node : graph.getEachNode()) { float m = 0; APSP.APSPInfo info = node.getAttribute(apspInfoAttribute); if (info == null) System.err.printf("APSPInfo missing. Did you compute APSP before ?\n"); for (Node other : graph.getEachNode()) { if (node != other) { double d = info.getLengthTo(other.getId()); if (d < 0) System.err.printf( "Found a negative length value in centroid algorithm. " + "Is graph connected ?\n"); else m += d; } } if (m < min) { centroid.clear(); centroid.add(node); min = m; } else if (m == min) { centroid.add(node); } } for (Node node : graph.getEachNode()) node.setAttribute( centroidAttribute, centroid.contains(node) ? isInCentroid : isNotInCentroid); centroid.clear(); }
/** * Get the style of a given node. * * @param node The node to search for. * @return The node style. */ public StyleGroup getStyleFor(Node node) { String gid = byNodeIdGroups.get(node.getId()); return groups.get(gid); }