List of usage examples for org.apache.commons.collections15 Transformer Transformer
Transformer
From source file:de.bitocean.dspm.examples.Vertex.java
public static void main(String[] args) throws GraphIOException, FileNotFoundException, IOException { Reader reader = new FileReader(GRAPHML_ACTIVITY_DEPENDENCY_FILE); BufferedReader br = new BufferedReader(reader); while (br.ready()) { System.out.println(br.readLine()); }/*from ww w . ja va 2 s. c om*/ Transformer<NodeMetadata, Vertex> vtrans = new Transformer<NodeMetadata, Vertex>() { public Vertex transform(NodeMetadata nmd) { Vertex v = new Vertex(); v.id = nmd.getId(); v.name = nmd.getProperty("name"); v.expression = nmd.getProperty("expression"); return v; } }; Transformer<EdgeMetadata, Edge> etrans = new Transformer<EdgeMetadata, Edge>() { public Edge transform(EdgeMetadata emd) { System.out.println(emd.toString()); Edge e = new Edge(); try { e.source = emd.getSource(); } catch (Exception ex) { } e.target = emd.getTarget(); e.weight = Double.parseDouble(emd.getProperty("weight")); return e; } }; Transformer<HyperEdgeMetadata, Edge> hetrans = new Transformer<HyperEdgeMetadata, Edge>() { public Edge transform(HyperEdgeMetadata emd) { Edge e = new Edge(); try { e.source = emd.getProperty("source"); } catch (Exception ex) { } e.target = emd.getProperty("target"); e.weight = Double.parseDouble(emd.getProperty("weight")); return e; } }; Transformer<GraphMetadata, DirectedSparseGraph<Vertex, Edge>> gtrans = new Transformer<GraphMetadata, DirectedSparseGraph<Vertex, Edge>>() { public DirectedSparseGraph<Vertex, Edge> transform(GraphMetadata gmd) { return new DirectedSparseGraph<Vertex, Edge>(); } }; GraphMLReader2<DirectedSparseGraph<Vertex, Edge>, Vertex, Edge> gmlr = //new GraphMLReader2<UndirectedSparseGraph<Vertex,Edge>, Vertex, Edge>(fileReader, graphTransformer, vertexTransformer, edgeTransformer, hyperEdgeTransformer) new GraphMLReader2<DirectedSparseGraph<Vertex, Edge>, Vertex, Edge>(reader, gtrans, vtrans, etrans, hetrans); DirectedSparseGraph<Vertex, Edge> g = gmlr.readGraph(); System.out.println("Number of vetex: " + g.getVertexCount()); System.out.println("Number of edges: " + g.getEdgeCount()); System.out.println("=========================="); System.out.println("Vertices"); System.out.println("=========================="); for (Vertex v : g.getVertices()) { System.out.println(v); } System.out.println("=========================="); System.out.println("Edges"); System.out.println("=========================="); for (Edge e : g.getEdges()) { System.out.println(e); } }
From source file:ega.projekt.graphDraw.DrawGraph.java
/** * @param args the command line arguments *///from w w w .java 2 s .co m public static void main(String[] args) { ega.projekt.graph.Graph dataGraph = new ega.projekt.graph.Graph(5, 100, 295, 295); if (dataGraph.getEdges().isEmpty()) System.out.println("Error initializing graph"); DrawGraph graphView = new DrawGraph(dataGraph); // This builds the graph // Layout<V, E>, VisualizationComponent<V,E> Layout<Node, Edge> layout = new StaticLayout(graphView.drawGraph); for (Node n : graphView.drawGraph.getVertices()) { layout.setLocation(n, new java.awt.geom.Point2D.Double(n.getX(), n.getY())); } layout.setSize(new Dimension(300, 300)); BasicVisualizationServer<Node, Edge> vv = new BasicVisualizationServer<>(layout); vv.setPreferredSize(new Dimension(350, 350)); // Setup up a new vertex to paint transformer... Transformer<Node, Paint> vertexPaint = new Transformer<Node, Paint>() { public Paint transform(Node i) { return Color.GREEN; } }; // Set up a new stroke Transformer for the edges //float dash[] = {10.0f}; final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); Transformer<Edge, Stroke> edgeStrokeTransformer = new Transformer<Edge, Stroke>() { public Stroke transform(Edge e) { if (e.isMarked()) { final Stroke modStroke = new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); return modStroke; } return edgeStroke; } }; Transformer<Edge, Paint> edgePaint = new Transformer<Edge, Paint>() { public Paint transform(Edge e) { if (e.isMarked()) { return Color.RED; } return Color.BLACK; } }; vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint); vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.QuadCurve<Node, Edge>()); vv.getRenderContext().setEdgeLabelTransformer(new Transformer<Edge, String>() { public String transform(Edge e) { return (e.getFlowString() + "/" + Integer.toString(e.getCapacity())); } }); vv.getRenderContext().setVertexLabelTransformer(new Transformer<Node, String>() { public String transform(Node n) { return (Integer.toString(n.getID())); } }); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR); JFrame frame = new JFrame("Simple Graph View 2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(vv); frame.pack(); frame.setVisible(true); }
From source file:it.iit.genomics.cru.igb.bundles.mi.view.TestJung.java
public static void main(String[] args) { Graph<MoleculeEntry, EdgeInteraction> graph = new SparseMultigraph<>(); MoleculeEntry v1 = new MoleculeEntry("A"); v1.addGeneName("A"); v1.setTaxid("9606"); MoleculeEntry v2 = new MoleculeEntry("B"); v2.addGeneName("b"); v2.setTaxid("9606"); MoleculeEntry v3 = new MoleculeEntry("DNA"); v3.addGeneName("DNA"); v3.setTaxid(MoleculeEntry.TAXID_DNA); EdgeInteraction edge = new EdgeInteraction(true, true, true, "e1"); graph.addEdge(edge, v1, v2, EdgeType.UNDIRECTED); EdgeInteraction edge2 = new EdgeInteraction(false, false, true, "e2"); graph.addEdge(edge2, v1, v3, EdgeType.UNDIRECTED); EdgeInteraction edge3 = new EdgeInteraction(false, false, false, "e3"); graph.addEdge(edge3, v2, v3, EdgeType.UNDIRECTED); // The Layout<V, E> is parameterized by the vertex and edge types Layout<MoleculeEntry, EdgeInteraction> layout = new ISOMLayout(graph); layout.setSize(new Dimension(500, 600)); // sets the initial size of the space // The BasicVisualizationServer<V,E> is parameterized by the edge types VisualizationViewer<MoleculeEntry, EdgeInteraction> vv = new VisualizationViewer<>(layout); vv.setPreferredSize(new Dimension(550, 650)); //Sets the viewing area size vv.setBackground(Color.WHITE); Transformer<MoleculeEntry, Paint> vertexPaint = new Transformer<MoleculeEntry, Paint>() { @Override/*from w ww . j a v a 2 s .c o m*/ public Paint transform(MoleculeEntry molecule) { switch (molecule.getTaxid()) { case MoleculeEntry.TAXID_DNA: ; case MoleculeEntry.TAXID_RNA: return Color.GREEN; case MoleculeEntry.TAXID_LIGAND: return Color.MAGENTA; default: return Color.GREEN; } } }; Transformer<EdgeInteraction, Paint> edgePaint = new Transformer<EdgeInteraction, Paint>() { @Override public Paint transform(EdgeInteraction interaction) { return interaction.hasStructure ? Color.BLACK : Color.GRAY; } }; final Stroke edgeStroke01 = new BasicStroke(); final float nodeSize = 20; final Stroke edgeStrokeBothContacts = new ShapeStroke(new Shape[] { new Ellipse2D.Float(0, 0, 10, 10) }, nodeSize, true, true); final Stroke edgeStrokeStartContacts = new ShapeStroke(new Shape[] { new Ellipse2D.Float(0, 0, 10, 10) }, nodeSize, true, false); final Stroke edgeStrokeEndContacts = new ShapeStroke(new Shape[] { new Ellipse2D.Float(0, 0, 10, 10) }, nodeSize, false, true); final Stroke edgeStrokeBothContact = new CompoundStroke(edgeStroke01, edgeStrokeBothContacts, CompoundStroke.ADD); final Stroke edgeStrokeStartContact = new CompoundStroke(edgeStroke01, edgeStrokeStartContacts, CompoundStroke.ADD); final Stroke edgeStrokeEndContact = new CompoundStroke(edgeStroke01, edgeStrokeEndContacts, CompoundStroke.ADD); Transformer<EdgeInteraction, Stroke> edgeStrokeTransformer = new Transformer<EdgeInteraction, Stroke>() { @Override public Stroke transform(EdgeInteraction s) { if (s.hasContactsA && s.hasContactsB) { return edgeStrokeBothContact; } if (s.hasContactsA) { return edgeStrokeStartContact; } if (s.hasContactsB) { return edgeStrokeEndContact; } return edgeStroke01; } }; Transformer<MoleculeEntry, String> moleculeLabeller = new Transformer<MoleculeEntry, String>() { @Override public String transform(MoleculeEntry s) { return s.getGeneName(); } }; vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint); vv.getRenderContext().setEdgeDrawPaintTransformer(edgePaint); vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); vv.getRenderContext().setVertexLabelTransformer(moleculeLabeller); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR); DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse(); graphMouse.setMode(ModalGraphMouse.Mode.PICKING); vv.setGraphMouse(graphMouse); JFrame frame = new JFrame("Network " + "A"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(vv); frame.pack(); frame.setVisible(true); }
From source file:com.googlecode.sarasvati.visual.jung.JungVisualizer.java
@SuppressWarnings("serial") public static void main(String[] args) throws Exception { TestSetup.init();/*from www . ja v a 2 s . c om*/ Session session = TestSetup.openSession(); HibEngine engine = new HibEngine(session); JFrame frame = new JFrame("Workflow Visualizer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(800, 600)); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); frame.getContentPane().add(splitPane); DefaultListModel listModel = new DefaultListModel(); for (Graph g : engine.getRepository().getGraphs()) { listModel.addElement(g); } ListCellRenderer cellRenderer = new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); Graph g = (Graph) value; setText(g.getName() + "." + g.getVersion() + " "); return this; } }; final JList graphList = new JList(listModel); graphList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); graphList.setCellRenderer(cellRenderer); JScrollPane listScrollPane = new JScrollPane(graphList); listScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); listScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); splitPane.add(listScrollPane); //TreeLayout<NodeRef, Arc> layout = new TreeLayout<NodeRef, Arc>(); DirectedSparseMultigraph<Node, Arc> graph = new DirectedSparseMultigraph<Node, Arc>(); //final SpringLayout2<HibNodeRef, HibArc> layout = new SpringLayout2<HibNodeRef, HibArc>(graph); //final KKLayout<HibNodeRef, HibArc> layout = new KKLayout<HibNodeRef, HibArc>(graph); final TreeLayout layout = new TreeLayout(graph); final BasicVisualizationServer<Node, Arc> vs = new BasicVisualizationServer<Node, Arc>(layout); //vs.getRenderContext().setVertexLabelTransformer( new NodeLabeller() ); //vs.getRenderContext().setEdgeLabelTransformer( new ArcLabeller() ); vs.getRenderContext().setVertexShapeTransformer(new NodeShapeTransformer()); vs.getRenderContext().setVertexFillPaintTransformer(new NodeColorTransformer()); vs.getRenderContext().setLabelOffset(5); vs.getRenderContext().setVertexIconTransformer(new Transformer<Node, Icon>() { @Override public Icon transform(Node node) { return "task".equals(node.getType()) ? new TaskIcon(node) : null; } }); Transformer<Arc, Paint> edgeColorTrans = new Transformer<Arc, Paint>() { private Color darkRed = new Color(128, 0, 0); @Override public Paint transform(Arc arc) { return "reject".equals(arc.getName()) ? darkRed : Color.black; } }; vs.getRenderContext().setEdgeDrawPaintTransformer(edgeColorTrans); vs.getRenderContext().setArrowDrawPaintTransformer(edgeColorTrans); final JScrollPane scrollPane = new JScrollPane(vs); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); splitPane.add(scrollPane); scrollPane.setBackground(Color.white); graphList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } final Graph g = (Graph) graphList.getSelectedValue(); if ((g == null && currentGraph == null) || (g != null && g.equals(currentGraph))) { return; } currentGraph = g; DirectedSparseMultigraph<Node, Arc> jungGraph = new DirectedSparseMultigraph<Node, Arc>(); for (Node ref : currentGraph.getNodes()) { jungGraph.addVertex(ref); } for (Arc arc : currentGraph.getArcs()) { jungGraph.addEdge(arc, arc.getStartNode(), arc.getEndNode()); } GraphTree graphTree = new GraphTree(g); layout.setGraph(jungGraph); layout.setInitializer(new NodeLocationTransformer(graphTree)); scrollPane.repaint(); } }); frame.setVisible(true); }
From source file:com.diversityarrays.kdxplore.trials.TrialSelectionDialog.java
static public void main(String[] args) { Transformer<BackgroundRunner, TrialSearchOptionsPanel> factory = new Transformer<BackgroundRunner, TrialSearchOptionsPanel>() { @Override//from w w w .j a v a2s .c o m public TrialSearchOptionsPanel transform(BackgroundRunner backgroundRunner) { return TrialSelectionSearchOptionsPanel.create(backgroundRunner); } }; boolean test = false; if (test) { @SuppressWarnings("unchecked") TrialSelectionDialog tsd = new TrialSelectionDialog(null, "Test Tree", null, Collections.EMPTY_LIST, //$NON-NLS-1$ factory); // tsd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); tsd.setVisible(true); } else { File propertiesFile = new File(System.getProperty("user.home"), //$NON-NLS-1$ "LoginDialog.properties"); //$NON-NLS-1$ //.getBundle("LoginDialog"); //, Locale.getDefault()); ResourceBundle bundle = null; if (propertiesFile.exists()) { try { bundle = new PropertyResourceBundle(new FileReader(propertiesFile)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } Preferences loginPreferences = KdxplorePreferences.getInstance().getPreferences(); // Preferences loginPreferences = Preferences.userNodeForPackage(KdxConstants.class); LoginDialog ld = new LoginDialog(null, "Login Please", loginPreferences, bundle); //$NON-NLS-1$ ld.setVisible(true); DALClient client = ld.getDALClient(); if (client != null) { @SuppressWarnings("unchecked") TrialSelectionDialog tsd = new TrialSelectionDialog(null, "Test Tree", client, //$NON-NLS-1$ Collections.EMPTY_LIST, factory); // tsd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); tsd.setVisible(true); if (tsd.trialRecords == null) { System.out.println("Cancelled !"); //$NON-NLS-1$ } else { System.out.println(tsd.trialRecords.length + " chosen: "); //$NON-NLS-1$ for (TrialPlus tr : tsd.trialRecords) { System.out.println("\t" + tr.getTrialId() + ": " + tr.getTrialName()); //$NON-NLS-1$ //$NON-NLS-2$ } System.out.println("- - -"); //$NON-NLS-1$ } } } System.exit(0); }
From source file:SequentialPersonalizedPageRank.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); options.addOption(/*w w w . j av a 2s . c o m*/ OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP)); options.addOption(OptionBuilder.withArgName("node").hasArg() .withDescription("source node (i.e., destination of the random jump)").create(SOURCE)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String infile = cmdline.getOptionValue(INPUT); final String source = cmdline.getOptionValue(SOURCE); float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f; int edgeCnt = 0; DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>(); BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile))); String line; while ((line = data.readLine()) != null) { line.trim(); String[] arr = line.split("\\t"); for (int i = 1; i < arr.length; i++) { graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]); } } data.close(); if (!graph.containsVertex(source)) { System.err.println("Error: source node not found in the graph!"); System.exit(-1); } WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>(); Set<Set<String>> components = clusterer.transform(graph); int numComponents = components.size(); System.out.println("Number of components: " + numComponents); System.out.println("Number of edges: " + graph.getEdgeCount()); System.out.println("Number of nodes: " + graph.getVertexCount()); System.out.println("Random jump factor: " + alpha); // Compute personalized PageRank. PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph, new Transformer<String, Double>() { @Override public Double transform(String vertex) { return vertex.equals(source) ? 1.0 : 0; } }, alpha); ranker.evaluate(); // Use priority queue to sort vertices by PageRank values. PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>(); int i = 0; for (String pmid : graph.getVertices()) { q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid)); } // Print PageRank values. System.out.println("\nPageRank of nodes, in descending order:"); Ranking<String> r = null; while ((r = q.poll()) != null) { System.out.println(r.rankScore + "\t" + r.getRanked()); } }
From source file:edu.umd.shrawanraina.SequentialPersonalizedPageRank.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); options.addOption(//from w w w . jav a2 s. c om OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP)); options.addOption(OptionBuilder.withArgName("node").hasArg() .withDescription("source node (i.e., destination of the random jump)").create(SOURCE)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String infile = cmdline.getOptionValue(INPUT); final String source = cmdline.getOptionValue(SOURCE); float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f; int edgeCnt = 0; DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>(); BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile))); String line; while ((line = data.readLine()) != null) { line.trim(); String[] arr = line.split("\\t"); for (int i = 1; i < arr.length; i++) { graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]); } } data.close(); if (!graph.containsVertex(source)) { System.err.println("Error: source node not found in the graph!"); System.exit(-1); } WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>(); Set<Set<String>> components = clusterer.transform(graph); int numComponents = components.size(); System.out.println("Number of components: " + numComponents); System.out.println("Number of edges: " + graph.getEdgeCount()); System.out.println("Number of nodes: " + graph.getVertexCount()); System.out.println("Random jump factor: " + alpha); // Compute personalized PageRank. PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph, new Transformer<String, Double>() { public Double transform(String vertex) { return vertex.equals(source) ? 1.0 : 0; } }, alpha); ranker.evaluate(); // Use priority queue to sort vertices by PageRank values. PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>(); int i = 0; for (String pmid : graph.getVertices()) { q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid)); } // Print PageRank values. System.out.println("\nPageRank of nodes, in descending order:"); Ranking<String> r = null; while ((r = q.poll()) != null) { System.out.println(r.rankScore + "\t" + r.getRanked()); } }
From source file:de.unisb.cs.st.javaslicer.jung.ShowJungGraph.java
public static void main(String[] args) throws InterruptedException { Options options = createOptions();//from ww w .j ava2 s.co m CommandLineParser parser = new GnuParser(); CommandLine cmdLine; try { cmdLine = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing the command line arguments: " + e.getMessage()); return; } if (cmdLine.hasOption('h')) { printHelp(options, System.out); System.exit(0); } String[] additionalArgs = cmdLine.getArgs(); if (additionalArgs.length != 2) { printHelp(options, System.err); System.exit(-1); } File traceFile = new File(additionalArgs[0]); String slicingCriterionString = additionalArgs[1]; Long threadId = null; if (cmdLine.hasOption('t')) { try { threadId = Long.parseLong(cmdLine.getOptionValue('t')); } catch (NumberFormatException e) { System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t')); System.exit(-1); } } TraceResult trace; try { trace = TraceResult.readFrom(traceFile); } catch (IOException e) { System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e); System.exit(-1); return; } List<SlicingCriterion> sc = null; try { sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses()); } catch (IllegalArgumentException e) { System.err.println("Error parsing slicing criterion: " + e.getMessage()); System.exit(-1); return; } List<ThreadId> threads = trace.getThreads(); if (threads.size() == 0) { System.err.println("The trace file contains no tracing information."); System.exit(-1); } ThreadId tracing = null; for (ThreadId t : threads) { if (threadId == null) { if ("main".equals(t.getThreadName()) && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId())) tracing = t; } else if (t.getJavaThreadId() == threadId.longValue()) { tracing = t; } } if (tracing == null) { System.err.println(threadId == null ? "Couldn't find the main thread." : "The thread you specified was not found."); System.exit(-1); return; } Transformer<InstructionInstance, Object> transformer; Transformer<Object, String> vertexLabelTransformer; Transformer<Object, String> vertexTooltipTransformer; String granularity = cmdLine.getOptionValue("granularity"); if (granularity == null || "instance".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public InstructionInstance transform(InstructionInstance inst) { return inst; } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getShortInstructionText(((InstructionInstance) inst).getInstruction()); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getInstructionTooltip(((InstructionInstance) inst).getInstruction()); } }; } else if ("instruction".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public Instruction transform(InstructionInstance inst) { return inst.getInstruction(); } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getShortInstructionText(((Instruction) inst)); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getInstructionTooltip(((Instruction) inst)); } }; } else if ("line".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public Line transform(InstructionInstance inst) { return new Line(inst.getInstruction().getMethod(), inst.getInstruction().getLineNumber()); } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { Line line = (Line) inst; return line.getMethod().getName() + ":" + line.getLineNr(); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { Line line = (Line) inst; return "Line " + line.getLineNr() + " in method " + line.getMethod().getReadClass().getName() + "." + line.getMethod(); } }; } else { System.err.println("Illegal granularity specification: " + granularity); System.exit(-1); return; } int maxLevel = Integer.MAX_VALUE; if (cmdLine.hasOption("maxlevel")) { try { maxLevel = Integer.parseInt(cmdLine.getOptionValue("maxlevel")); } catch (NumberFormatException e) { System.err.println("Argument to \"maxlevel\" must be an integer."); System.exit(-1); return; } } long startTime = System.nanoTime(); ShowJungGraph<Object> showGraph = new ShowJungGraph<Object>(trace, transformer); showGraph.setMaxLevel(maxLevel); showGraph.setVertexLabelTransformer(vertexLabelTransformer); showGraph.setVertexTooltipTransformer(vertexTooltipTransformer); if (cmdLine.hasOption("progress")) showGraph.addProgressMonitor(new ConsoleProgressMonitor()); boolean multithreaded; if (cmdLine.hasOption("multithreaded")) { String multithreadedStr = cmdLine.getOptionValue("multithreaded"); multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr)); } else { multithreaded = Runtime.getRuntime().availableProcessors() > 1; } DirectedGraph<Object, SliceEdge<Object>> graph = showGraph.getGraph(tracing, sc, multithreaded); long endTime = System.nanoTime(); System.out.format((Locale) null, "%nSlice graph consists of %d nodes.%n", graph.getVertexCount()); System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime)); showGraph.displayGraph(graph); }
From source file:edu.uci.ics.jung.algorithms.scoring.util.ScoringUtils.java
/** * Assigns a probability of 1/<code>roots.size()</code> to each of the elements of <code>roots</code>. * @param <V> the vertex type/*from w ww . j av a 2 s.c o m*/ * @param roots the vertices to be assigned nonzero prior probabilities * @return */ public static <V> Transformer<V, Double> getUniformRootPrior(Collection<V> roots) { final Collection<V> inner_roots = roots; Transformer<V, Double> distribution = new Transformer<V, Double>() { public Double transform(V input) { if (inner_roots.contains(input)) return new Double(1.0 / inner_roots.size()); else return 0.0; } }; return distribution; }
From source file:JGraphLoader.GraphSaver.java
public static void saveG(String filename, Graph g) { final AbstractLayout layout = new StaticLayout(g); GraphMLWriter<node, edge> graphWriter = new GraphMLWriter<node, edge>(); try {//from ww w .java 2 s . c o m PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename))); graphWriter.addEdgeData("id", null, "0", new Transformer<edge, String>() { @Override public String transform(edge i) { return i.getValue(); } }); /* graphWriter.addVertexData("y", null, "0", new Transformer<node, String>() { public String transform(node v) { return Double.toString(layout.getY(v)); } } );*/ graphWriter.save(g, out); } catch (IOException ex) { Logger.getLogger(GraphSaver.class.getName()).log(Level.SEVERE, null, ex); } }