@Test public void testUnreachable() { Graph<String, MyLink> g = new DirectedOrderedSparseMultigraph<String, MyLink>(); String n1 = new String("S"); // S g.addVertex(n1); String n2 = new String("A"); // A g.addVertex(n2); String n3 = new String("B"); // B -- not connected g.addVertex(n3); g.addEdge(new MyLink(1, "S-A"), n1, n2, EdgeType.DIRECTED); // S - A Transformer<MyLink, Number> weightTrans = new Transformer<MyLink, Number>() { @Override public Number transform(MyLink link) { return link.getWeight(); } }; SuurballeTarjan<String, MyLink> testMain = new SuurballeTarjan<String, MyLink>( g, weightTrans); assertEquals(null, testMain.getDisjointPaths(n1, n3)); }
@Test public void testNoDisjointSolution() { Graph<String, MyLink> g = new DirectedOrderedSparseMultigraph<String, MyLink>(); String n1 = new String("A"); // A g.addVertex(n1); String n2 = new String("B"); // B g.addVertex(n2); g.addEdge(new MyLink(2, "A-B"), n1, n2, EdgeType.DIRECTED); Transformer<MyLink, Number> weightTrans = new Transformer<MyLink, Number>() { @Override public Number transform(MyLink link) { return link.getWeight(); } }; SuurballeTarjan<String, MyLink> testMain = new SuurballeTarjan<String, MyLink>( g, weightTrans); assertEquals("[[A-B]]", testMain.getDisjointPaths(n1, n2).toString()); }
DistanceEntry getDistance(SubstrateNetwork sNetwork, SubstrateNode from, SubstrateNode to, Transformer<SubstrateLink, Double> transformer) { if (from.getId() == to.getId()) { return new DistanceEntry(from, to, new LinkedList<SubstrateLink>(), 0.0); } // we need a new instance here because we use other link weights // every time MyDijkstraShortestPath<SubstrateNode, SubstrateLink> dijkstra = new MyDijkstraShortestPath<SubstrateNode, SubstrateLink>( sNetwork, transformer, true); List<SubstrateLink> path = dijkstra.getPath(from, to); if (path == null) { return null; } Number distance = dijkstra.getDistance(from, to); return new DistanceEntry(from, to, path, distance.doubleValue()); }
public static LinkedList<SubstrateLink> findShortestPath( SubstrateNetwork sNetwork, SubstrateNode n1, SubstrateNode n2, Transformer<SubstrateLink, Double> t) { if (n1.getId() == n2.getId()) { return new LinkedList<SubstrateLink>(); } MyDijkstraShortestPath<SubstrateNode, SubstrateLink> dijkstra = new MyDijkstraShortestPath<SubstrateNode, SubstrateLink>( sNetwork, t, true); LinkedList<SubstrateLink> path = dijkstra.getPath(n1, n2, -1); return path; }
public static Collection<LinkedList<SubstrateLink>> findAllShortestPaths( SubstrateNetwork sNetwork, SubstrateNode n, Transformer<SubstrateLink, Double> t) { Collection<LinkedList<SubstrateLink>> result = new LinkedList<LinkedList<SubstrateLink>>(); for (SubstrateNode n2 : sNetwork.getVertices()) { if (n != n2) { LinkedList<SubstrateLink> current = findShortestPath(sNetwork, n, n2, t); if (current != null) { result.add(current); } } } return result; }
public static Collection<LinkedList<SubstrateLink>> getShortestPathsALinkGoesThrough( SubstrateNetwork sNetwork, SubstrateLink l, Transformer<SubstrateLink, Double> t) { Collection<LinkedList<SubstrateLink>> result = new LinkedList<LinkedList<SubstrateLink>>(); Map<SubstrateNode, Collection<LinkedList<SubstrateLink>>> all = Utils.findAllShortestPaths(sNetwork, t); for (Entry<SubstrateNode, Collection<LinkedList<SubstrateLink>>> e : all.entrySet()) { for (LinkedList<SubstrateLink> path : e.getValue()) { if (path.contains(l)) { result.add(path); break; } } } return result; }
/** * This method takes the GraphPrototype class name as string and creates a graph of the prototype and shows a preview in the visualizationViewer * @param graphPrototype */ private void setPrototypePreview() { String componentName = this.localComponentTypeListElement.getComponentName(); // --- Create the graph of the NetworkComponent ------------- this.localNetworkModel = NetworkComponentFactory.getNetworkModel4NetworkComponent(this.graphController.getNetworkModel().getGeneralGraphSettings4MAS(), componentName, this.getVisualizationViewer().getSize()); this.localGraphElementPrototype = NetworkComponentFactory.getGraphElementPrototypeOfLastNetworkComponent(); if (this.localNetworkModel!=null && this.localGraphElementPrototype!=null) { // --- Set the graph to the layout ---------------------- Layout<GraphNode, GraphEdge> layout = new StaticLayout<GraphNode, GraphEdge>(this.localNetworkModel.getGraph()); layout.setInitializer(new Transformer<GraphNode, Point2D>() { public Point2D transform(GraphNode node) { return node.getPosition(); } }); this.getVisualizationViewer().setGraphLayout(layout); this.getVisualizationViewer().repaint(); // --- Pick first GraphNode -------------------- this.pickFirstGraphNode(); this.setSelectedGraphNode(); } }
public static GraphVisualizationPanel<MarkovVertex, MarkovEdge> getPanel( Graph<MarkovVertex, MarkovEdge> test_graph) { GraphVisualizationPanel<MarkovVertex, MarkovEdge> graph_panel = GraphVisualizationPanel .factory(test_graph); Transformer<MarkovVertex, Paint> transformer = new VertexTransformer<MarkovVertex, Paint>(); graph_panel.getRenderContext().setVertexFillPaintTransformer( transformer); graph_panel.getRenderContext().setEdgeLabelTransformer( new ToStringLabeller<MarkovEdge>()); PluggableGraphMouse gm = new PluggableGraphMouse(); gm.add(new PopupMousePlugin<MarkovVertex, MarkovEdge>()); gm.add(new TranslatingGraphMousePlugin(MouseEvent.BUTTON1_MASK)); graph_panel.setGraphMouse(gm); Transformer<MarkovVertex, String> labelTransform = new VertexLabelTransformer<MarkovVertex, String>(); graph_panel.getRenderContext() .setVertexLabelTransformer(labelTransform); return graph_panel; }
/** * Main. * * @param args * command line arguments */ public static void main(String[] args) { TestExample example = new TestExample(); Term bdd = example.get(); Transformer<String, ReliabilityFunction> exponentialTransformer = new TestExponentialTransformer(); Transformer<String, ReliabilityFunction> weibullTransformer = new TestWeibullTransformer(); BDDProviderFactory bddProviderFactory = new JBDDProviderFactory(); BDDProvider<String> bddProvider = bddProviderFactory.getProvider(); BDDTTRF<String> transformer = new BDDTTRF<>(bddProvider); ReliabilityFunction exponentialDistribution = transformer.convert(bdd, exponentialTransformer); ReliabilityFunction weibullDistribution = transformer.convert(bdd, weibullTransformer); Map<String, ReliabilityFunction> reliabilityFunction = new HashMap<>(); reliabilityFunction.put("Exponential", exponentialDistribution); reliabilityFunction.put("Weibull", weibullDistribution); ReliabilityViewer.view("JReliability Viewer", reliabilityFunction); }
/** * Calculates the top event for the values given by the functionTransformer. * * @param transformer * the transformer from the variables to the values * @return the top event */ public double calculate(Transformer<T, Double> transformer) { for (Entry<T, Var> entry : variables.entrySet()) { T t = entry.getKey(); Var var = entry.getValue(); double value = transformer.transform(t); var.setValue(value); } for (VarNode node : nodes) { double r = node.getVar().getValue(); double low = node.getLo().getValue(); double high = node.getHi().getValue(); // Shannon decomposition double y = r * high + (1 - r) * low; node.setValue(y); } return root.getValue(); }
@Override public double getY(final double x) { final Transformer<T, Double> t = new Transformer<T, Double>() { /** * Default {@link Transformer}. * * @param a * parameter a * @return the double value of a */ @Override public Double transform(T a) { return functionTransformer.transform(a).getY(x); } }; return topEvent.calculate(t); }
/** * Calculates the top event of the {@link BDD} based on a functionTransformer that delivers for each variable * {@code T} a double value. * * @param <T> * the type of variable * @param bdd * the bdd * @param transformer * the transformer that returns a double value for each variable * @return the top event of the bdd */ public static <T> double calculateTop(BDD<T> bdd, Transformer<T, Double> transformer) { if (bdd.isOne()) { return 1.0; } if (bdd.isZero()) { return 0.0; } Set<BDD<T>> upSort = new LinkedHashSet<>(); traverseBDD(bdd, upSort); double top = evaluate(bdd, transformer, upSort); for (BDD<T> ups : upSort) { ups.free(); } return top; }
/** * Performs a single simulation run to gather one time-to-failure. * * @param bdd * the given bdd * @param functionTransformer * the element to reliability function transformer * @return a single time-to-failure */ protected double simulateTimeToFailure(BDD<T> bdd, Transformer<T, ReliabilityFunction> functionTransformer) { double time = 0; BDD<T> myBDD = bdd.copy(); Set<Failure<T>> failures = getFailures(bdd, functionTransformer); for (Failure<T> failure : failures) { BDD<T> objectVariable = provider.get(failure.getObject()); myBDD.restrictWith(objectVariable.not()); if (myBDD.isZero()) { time = failure.getTime(); break; } } return time; }
@Test public void testCalculate() { BDD<String> a = provider.get("a"); BDD<String> b = provider.get("b"); BDD<String> and = a.and(b); BDDTopEvent<String> event = new BDDTopEvent<>(and); double result = event.calculate(new Transformer<String, Double>() { @Override public Double transform(String input) { return 0.5; } }); Assert.assertEquals(0.25, result, 0.000001); }
@Test public void testCalculateSeriesParallel() { BDD<String> a = provider.get("a"); BDD<String> b = provider.get("b"); BDD<String> bdd = a.or(b); BDD<String> c = provider.get("c"); bdd = bdd.and(c); BDDTopEvent<String> event = new BDDTopEvent<>(bdd); double result = event.calculate(new Transformer<String, Double>() { @Override public Double transform(String input) { return 0.9; } }); Assert.assertEquals(0.891, result, 0.000001); }
/** * Tests the {@link BDDs#getNodes(BDD)} method. */ @Test public void testCalculateTop() { BDDProvider<String> provider = factory.getProvider(); String var = "a"; BDD<String> bdd = provider.get(var); Transformer<String, Double> t = new Transformer<String, Double>() { @Override public Double transform(String input) { return 0.7; } }; Assert.assertEquals(0.7, BDDs.calculateTop(bdd, t), 0.00001); }
/** * Tests the {@link BDDs#getNodes(BDD)} method. */ @Test public void testCalculateTopNot() { BDDProvider<String> provider = factory.getProvider(); String var = "a"; BDD<String> bdd = provider.get(var).not(); Transformer<String, Double> t = new Transformer<String, Double>() { @Override public Double transform(String input) { return 0.7; } }; Assert.assertEquals(0.3, BDDs.calculateTop(bdd, t), 0.00001); }
/** * Tests the {@link BDDs#getNodes(BDD)} method with a one terminal. */ @Test public void testCalculate2Top() { BDDProvider<String> provider = factory.getProvider(); String var = "a"; String var2 = "b"; BDD<String> bdd = provider.get(var).and(provider.get(var2)); Transformer<String, Double> t = new Transformer<String, Double>() { @Override public Double transform(String input) { return 0.7; } }; Assert.assertEquals(0.49, BDDs.calculateTop(bdd, t), 0.00001); }
/** * Tests the {@link BDDs#getNodes(BDD)} method with a one terminal. */ @Test public void testCalculate2TopNot() { BDDProvider<String> provider = factory.getProvider(); String var = "a"; String var2 = "b"; BDD<String> bdd = provider.get(var).not().and(provider.get(var2)); Transformer<String, Double> t = new Transformer<String, Double>() { @Override public Double transform(String input) { return 0.7; } }; Assert.assertEquals(0.21, BDDs.calculateTop(bdd, t), 0.00001); }
/** Returns all the loopless shortest paths between two nodes. All these paths have the same total cost. * Links with cost {@code Double.MAX_VALUE} are not considered. * * @param nodes List of nodes * @param links List of links * @param originNode Origin node * @param destinationNode Destination node * @param linkCostMap Cost per link, where the key is the link identifier and the value is the cost of traversing the link. No special iteration-order (i.e. ascending) is required * @return All loopless shortest paths */ public static List<List<Link>> getAllLooplessShortestPaths(List<Node> nodes, List<Link> links, Node originNode, Node destinationNode, Map<Link, Double> linkCostMap) { final List<Link> filteredLinks = linkCostMap == null? links : links.stream().filter(e->linkCostMap.get(e) != Double.MAX_VALUE).collect(Collectors.toList()); Graph<Node, Link> g = JUNGUtils.getGraphFromLinkMap(nodes, filteredLinks); Transformer<Link, Double> nev = JUNGUtils.getEdgeWeightTransformer(linkCostMap); YenAlgorithm<Node, Link> paths = new YenAlgorithm<Node, Link>(g, nev) { @Override public boolean compareCandidateToShortestPath(GraphPath<Link> candidate, GraphPath<Link> shortestPath) { return Math.abs(candidate.getPathWeight() - shortestPath.getPathWeight()) < 1E-10; } }; List<List<Link>> pathList = paths.getPaths(originNode, destinationNode, Integer.MAX_VALUE); return pathList; }
/** @param nodes List of nodes * @param links List of links * @param originNode Origin node * @param destinationNode Destination node * @param linkCostMap Cost per link, where the key is the link identifier and the value is the cost of traversing the link. No special iteration-order (i.e. ascending) is required. If <code>null</code> all the links have a weight of one. * @param linkSpareCapacityMap Current available capacity per link, where the key is the link identifier and the value is the cost of traversing the link. No special iteration-order (i.e. ascending) is required. If <code>null</code> the spare capacity of each link is its capacity minus its carried traffic (summing the regular traffic and the ones in the protection segments), truncated to zero (negative values are not admitted). * @param capacityGoal Minimum capacity required * @return Shortest path fulfilling a minimum capacity requirement */ public static List<Link> getCapacitatedShortestPath(Collection<Node> nodes, Collection<Link> links, Node originNode, Node destinationNode, final Map<Link, Double> linkCostMap, Map<Link, Double> linkSpareCapacityMap, final double capacityGoal) { if (linkSpareCapacityMap == null) { linkSpareCapacityMap = new HashMap<Link, Double>(); for (Link e : links) linkSpareCapacityMap.put(e, Math.max(0, e.getCapacity() - e.getOccupiedCapacity())); } final Map<Link,Double> auxMapLinkCost = linkSpareCapacityMap; final List<Link> validLinks = linkCostMap == null? links.stream().filter(e->auxMapLinkCost.get(e) >= capacityGoal).collect(Collectors.toList()) : links.stream().filter(e->auxMapLinkCost.get(e) >= capacityGoal && linkCostMap.get(e) != Double.MAX_VALUE).collect(Collectors.toList()); final Graph<Node, Link> graph = JUNGUtils.getGraphFromLinkMap(nodes, validLinks); if (!graph.containsVertex(originNode)) return new LinkedList<Link>(); if (!graph.containsVertex(destinationNode)) return new LinkedList<Link>(); Transformer<Link, Double> nev = JUNGUtils.getEdgeWeightTransformer(linkCostMap); return JUNGUtils.getShortestPath(graph, nev, originNode, destinationNode); }
/** Builds an auxiliary graph for the application of edge-disjoint shortest-path pair algorithms to node-disjoint problems. * * @param graph Graph representing the network * @param nev Object responsible for returning weights for edges * @param originNode Origin node * @param destinationNode Destination node * @return Auxiliary graph, and its corresponding object returning edge weights */ public static Pair<Graph<Node, Link>, Transformer<Link, Double>> buildAuxiliaryNodeDisjointGraph(final Graph<Node, Link> graph, final Transformer<Link, Double> nev, Node originNode, Node destinationNode) { final Graph<Node, Link> auxGraph = buildAuxiliaryNodeDisjointGraph(graph, originNode, destinationNode); Transformer<Link, Double> auxNev = new Transformer<Link, Double>() { @Override public Double transform(Link edge) { if (graph.containsEdge(edge)) { if (edge.getId() < 0) throw new RuntimeException("Bad"); return nev.transform(edge); } else if (auxGraph.containsEdge(edge)) { return 1.0; } throw new RuntimeException("Bad"); } }; return Pair.of(auxGraph, auxNev); }
/** <p>Filters a graph removing those edges whose weight is equal to {@code Double.MAX_VALUE}, or whose capacity is below a certain threshold.</p> * * <p><b>Important</b>: Returned graph is not backed in the input one, so changes will not be reflected on it. * * @param <V> Class type for vertices * @param <E> Class type for edges * @param graph Graph representing the network * @param nev Object responsible for returning weights for edges * @param edgeSpareCapacityTransformer Object responsible for returning capacity for edges (if null, it will not applied) * @param requiredCapacity Capacity threshold. Edges whose capacity is below that value it will be removed * @return Filtered graph */ public static <V, E> Graph<V, E> filterGraph(Graph<V, E> graph, final Transformer<E, Double> nev, final Transformer<E, Double> edgeSpareCapacityTransformer, final double requiredCapacity) { EdgePredicateFilter<V, E> linkFilter = new EdgePredicateFilter<V, E>(new Predicate<E>() { @Override public boolean evaluate(E edge) { if (nev != null && nev.transform(edge) == Double.MAX_VALUE) return false; else if (edgeSpareCapacityTransformer != null && edgeSpareCapacityTransformer.transform(edge) < requiredCapacity) return false; return true; } }); return linkFilter.transform(graph); }
/** Returns the shortest pair of node-disjoint paths, where each item represents a path. The number of returned items will be equal to the number of paths found: when empty, no path was found; when {@code size()} = 1, only one path was found; and when {@code size()} = 2, the node-disjoint paths were found. Internally it uses the Suurballe-Tarjan algorithm. * * @param graph Graph representing the network * @param nev Object responsible for returning weights for edges * @param originNode Origin node * @param destinationNode Origin node * @return Shortest pair of node-disjoint paths */ public static List<List<Link>> getTwoNodeDisjointPaths(final Graph<Node, Link> graph, final Transformer<Link, Double> nev, Node originNode, Node destinationNode) { List<List<Link>> nodeDisjointSPs = new LinkedList<List<Link>>(); if (graph.getVertexCount() < 2 || !graph.containsVertex(originNode) || !graph.containsVertex(destinationNode)) return nodeDisjointSPs; Pair<Graph<Node, Link>, Transformer<Link, Double>> aux = buildAuxiliaryNodeDisjointGraph(graph, nev, originNode, destinationNode); Graph<Node, Link> auxGraph = aux.getFirst(); Transformer<Link, Double> auxNev = aux.getSecond(); nodeDisjointSPs = getTwoLinkDisjointPaths(auxGraph, auxNev, originNode, destinationNode); for (List<Link> auxSP : nodeDisjointSPs) { Iterator<Link> it = auxSP.iterator(); while (it.hasNext()) { Link edge = it.next(); if (!graph.containsEdge(edge)) it.remove(); } } return nodeDisjointSPs; }
/** This method does the following length transformation: * * <pre> c'(v,w) = c(v,w) - d (s,w) + d (s,v) </pre> * * @param graph1 the graph * @param slTrans The shortest length transformer * @return the transformed graph * @since 0.3.0 */ private Transformer<E, Double> lengthTransformation(Graph<V, E> graph1, Transformer<V, Number> slTrans) { Map<E, Double> map = new LinkedHashMap<E, Double>(); for (E link : graph1.getEdges()) { double newWeight; if (slTrans.transform(graph1.getSource(link)) == null) { newWeight = Double.MAX_VALUE; } else { newWeight = nev.transform(link) - slTrans.transform(graph1.getDest(link)).doubleValue() + slTrans.transform(graph1.getSource(link)).doubleValue(); if (newWeight < 0 || newWeight > -1e-6) newWeight = 0; /* Numerical errors */ } map.put(link, newWeight); } return MapTransformer.getInstance(map); }
/** * Assigns a probability of 1/<code>roots.size()</code> to each of the * elements of <code>roots</code>. * * @param <V> * the vertex type * @param roots * the vertices to be assigned nonzero prior probabilities * @return */ protected Transformer<Vertex, Double> getRootPrior(Collection<Vertex> roots) { final Collection<Vertex> inner_roots = roots; double sum = 0; for (Vertex v : inner_roots) { sum += v.getOccurrences(); } final double overallOccs = sum; Transformer<Vertex, Double> distribution = new Transformer<Vertex, Double>() { public Double transform(Vertex input) { if (inner_roots.contains(input)) { double d = new Double(input.getOccurrences() / (double) overallOccs); return d; } else { return 0.0; } } }; return distribution; }
@Override public Transformer<String, Paint> getVertexPaintTransformer(VisualizationViewer<String, String> viewer) { return new Transformer<String, Paint>() { @Override public Paint transform(String name) { if (viewer.getPickedVertexState().isPicked(name)) { return GraphViewer.NODE_SELECTED; } else if (sourceFilter.getSelectedIndex() > 0 && ((SourceId) sourceFilter.getSelectedItem()).getId().equals(name)) { return GraphViewer.NODE_ON_PATH; } else { return GraphViewer.NODE_BACKGROUND; } } }; }
/** * Create a new Transformer that calls each transformer in turn, passing the * result into the next transformer. The ordering is that of the iterator() * method on the collection. * * @param transformers a collection of transformers to chain * @return the <code>chained</code> transformer * @throws IllegalArgumentException if the transformers collection is null * @throws IllegalArgumentException if any transformer in the collection is null */ public static <I,O> Transformer<I, O> getInstance(Collection<Transformer> transformers) { if (transformers == null) { throw new IllegalArgumentException("Transformer collection must not be null"); } if (transformers.size() == 0) { return NOPTransformer.INSTANCE; } // convert to array like this to guarantee iterator() ordering Transformer[] cmds = new Transformer[transformers.size()]; int i = 0; for (Iterator<Transformer> it = transformers.iterator(); it.hasNext();) { cmds[i++] = it.next(); } FunctorUtils.validate(cmds); return new ChainedTransformer<I, O>(cmds); }
/** * Gets an instance of this transformer calling a specific method with specific values. * * @param methodName the method name to call * @param paramTypes the parameter types of the method * @param args the arguments to pass to the method * @return an invoker transformer */ public static Transformer getInstance(String methodName, Class[] paramTypes, Object[] args) { if (methodName == null) { throw new IllegalArgumentException("The method to invoke must not be null"); } if (((paramTypes == null) && (args != null)) || ((paramTypes != null) && (args == null)) || ((paramTypes != null) && (args != null) && (paramTypes.length != args.length))) { throw new IllegalArgumentException("The parameter types must match the arguments"); } if (paramTypes == null || paramTypes.length == 0) { return new InvokerTransformer(methodName); } else { paramTypes = (Class[]) paramTypes.clone(); args = (Object[]) args.clone(); return new InvokerTransformer(methodName, paramTypes, args); } }
/** * Instantiates a new default instance viewer. * * @param graph * the graph * @param preferredSize * the preferred size * @param bounds * bounds for the nodes coordinates */ public DefaultInstanceViewer(Graph<INodeVisit, IArc> graph, Dimension preferredSize, double[] bounds) { super(new StaticLayout<INodeVisit, IArc>(graph), preferredSize); mGraph = graph; mTransformer = new NodeVisitTransformer(Math.ceil(Math.max(bounds[1] - bounds[0], bounds[3] - bounds[2])), 14, -bounds[0], -bounds[2]); getGraphLayout().setInitializer(mTransformer); addComponentListener(mTransformer); mVertexSize = UIManager.getFont("Label.font").getSize() + 4; setDefaultVertexShapeTransformer(); setDefaultVertexFillPaintTransformer(); setDefaultVertexLabelTransformer(); getRenderContext().setVertexFontTransformer(new Transformer<INodeVisit, Font>() { @Override public Font transform(INodeVisit arg0) { return UIManager.getFont("Label.font"); } }); addComponentListener(this); }
public static VisualizationFrame showInstance(TRSPLegacyInstance instance, Transformer<INodeVisit, Paint> trans) { DefaultInstanceGraph graph = new DefaultInstanceGraph(instance); DefaultInstanceViewer view = new DefaultInstanceViewer(graph); view.getRenderContext().setVertexFillPaintTransformer(trans); VisualizationFrame frame = new VisualizationFrame(instance.getName(), view); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Logging.awaitLogging(60000); System.exit(0); } }); frame.setPreferredSize(new Dimension(400, 400)); frame.pack(); frame.setVisible(true); return frame; }
public static Map<String, Double> hitsScoring(Graph<String, WeightedEdge> graph) { Transformer<WeightedEdge, Double> edgeTransformer = WeightedEdge.getEdgeTransformer(); HITS<String, WeightedEdge> ranker = new HITS<String, WeightedEdge>(graph, edgeTransformer , aplha); ranker.setTolerance(tolerance) ; ranker.setMaxIterations(maxIterations); ranker.evaluate(); Collection<String> vertices = graph.getVertices(); Map<String, Double> verticesMap = new TreeMap<String, Double>(); for(String vertex : vertices) { Scores hitsScores = ranker.getVertexScore(vertex); Double authorityScore = hitsScores.authority; //Double hubScore = hitsScores.hub; verticesMap.put(vertex, authorityScore); //temp.put(vertex, hubScore); } return verticesMap; }
@Test(expected = IllegalArgumentException.class) public void constructorTest1() { Graph<String, MyLink> g = null; Transformer<MyLink, Number> weightTrans = new Transformer<MyLink, Number>() { @Override public Number transform(MyLink link) { return link.getWeight(); } }; new SuurballeTarjan<String, MyLink>(g, weightTrans); }
@Test(expected = IllegalArgumentException.class) public void constructorTest2() { Graph<String, MyLink> g = new DirectedOrderedSparseMultigraph<String, MyLink>(); Transformer<MyLink, Number> weightTrans = null; new SuurballeTarjan<String, MyLink>(g, weightTrans); }
@Test public void testTargetRemoval() { Graph<String, MyLink> g = new DirectedOrderedSparseMultigraph<String, MyLink>(); String n1 = new String("S"); // S g.addVertex(n1); String n2 = new String("A"); // A g.addVertex(n2); String n3 = new String("B"); // B g.addVertex(n3); String n4 = new String("C"); // C g.addVertex(n4); String n5 = new String("D"); // D g.addVertex(n5); g.addEdge(new MyLink(3, "S-A"), n1, n2, EdgeType.DIRECTED); // S - A g.addEdge(new MyLink(1, "A-C"), n2, n4, EdgeType.DIRECTED); // A - C g.addEdge(new MyLink(3, "S-B"), n1, n3, EdgeType.DIRECTED); // S - B g.addEdge(new MyLink(3, "B-C"), n3, n4, EdgeType.DIRECTED); // B - C g.addEdge(new MyLink(3, "C-D"), n4, n5, EdgeType.DIRECTED); // C - D Transformer<MyLink, Number> weightTrans = new Transformer<MyLink, Number>() { @Override public Number transform(MyLink link) { return link.getWeight(); } }; SuurballeTarjan<String, MyLink> testMain = new SuurballeTarjan<String, MyLink>( g, weightTrans); assertEquals("[[S-A, A-C, C-D]]", testMain.getDisjointPaths(n1, n5) .toString()); }
@Test(expected = IllegalArgumentException.class) public void basics() { Graph<String, MyLink> graph = new DirectedOrderedSparseMultigraph<String, MyLink>(); Transformer<MyLink, Number> weightTrans = null; factory.create(graph, weightTrans); }
@Override protected List<List<E>> getShortestPathsIntern(V source, V target, int k) { PriorityQueue<WeightedPath> prioQ = new PriorityQueue<WeightedPath>(); List<List<E>> found_paths = new LinkedList<List<E>>(); Transformer<E, Double> delta = prepareTransformations(target); // Initialize with start vertex. prioQ.add(new WeightedPath(source)); while (!prioQ.isEmpty() && found_paths.size() < k) { WeightedPath curPath = prioQ.poll(); // get & remove next shortest V curV = curPath.getLast(); if (curV.equals(target)) { found_paths.add(curPath.getPath()); continue; } // Create new paths for every expanded vertex ... for (V nextV : graph.getSuccessors(curV)) { if (curPath.contains(nextV)) continue; // Prevent looping! // ... and every possible edge. for (E e : graph.findEdgeSet(curV, nextV)) { if (Double.isInfinite(delta.transform(e))) continue; // Skip unreachable vertices. WeightedPath tmpPath = new WeightedPath(curPath); // clone tmpPath.addHop(e, delta.transform(e), nextV); prioQ.add(tmpPath); } } } return found_paths; }
public SuurballeTarjan(Graph<V, E> graph, Transformer<E, Number> nev, Comparator<E> comparator) { super(graph, nev); if (comparator == null) this.comparator = defaultComparator; else this.comparator = comparator; }