Example usage for org.apache.commons.collections15 Transformer transform

List of usage examples for org.apache.commons.collections15 Transformer transform

Introduction

In this page you can find the example usage for org.apache.commons.collections15 Transformer transform.

Prototype

public O transform(I input);

Source Link

Document

Transforms the input object (leaving it unchanged) into some output object.

Usage

From source file:net.itransformers.utils.MyGraphMLWriter.java

protected void writeVertexData(Hypergraph<V, E> graph, BufferedWriter w) throws IOException {
    for (V v : graph.getVertices()) {
        String v_string = String.format("<node id=\"%s\"", vertex_ids.transform(v));
        boolean closed = false;
        // write description out if any
        String desc = vertex_desc.transform(v);
        if (desc != null) {
            w.write(v_string + ">\n");
            closed = true;/* ww w .  j  ava  2  s .co m*/
            w.write("<desc>" + desc + "</desc>\n");
        }
        // write data out if any
        for (String key : vertex_data.keySet()) {
            Transformer<V, ?> t = vertex_data.get(key).transformer;
            if (t != null) {
                Object value = t.transform(v);
                if (value != null) {
                    if (!closed) {
                        w.write(v_string + ">\n");
                        closed = true;
                    }
                    w.write(format("data", "key", key, StringEscapeUtils.escapeXml(value.toString())) + "\n");
                }
            }
        }
        if (!closed)
            w.write(v_string + "/>\n"); // no contents; close the node with "/>"
        else
            w.write("</node>\n");
    }
}

From source file:mulavito.algorithms.shortestpath.disjoint.SuurballeTarjan.java

/**
 * This method does the following length transformation:
 * //from   w  w  w  . j  a v a2s . c o  m
 * <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
 */
private Transformer<E, Double> lengthTransformation(Graph<V, E> graph1, Transformer<V, Number> slTrans) {
    Map<E, Double> map = new HashMap<E, Double>();

    for (E link : graph1.getEdges()) {
        double newWeight = nev.transform(link).doubleValue()
                - slTrans.transform(graph1.getDest(link)).doubleValue()
                + slTrans.transform(graph1.getSource(link)).doubleValue();
        newWeight = MiscelFunctions.roundToDecimals(newWeight, 3); //because it exists -1.....E-18

        map.put(link, newWeight);
    }
    return MapTransformer.getInstance(map);
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.wsi.algorithm.SimpleGraphClusteringInductionAlgorithm.java

/**
 * Clusters a set of terms given a similarity function.
 *
 * @param term//from   w  w w . ja va  2s .  c o  m
 *            TODO
 * @param similars
 *
 *
 * @return
 */
public List<List<String>> cluster(String term, Set<Entity> similarEntities) {
    /*
     * Graph creation step. Different strategies can apply.
     */

    Graph<String, Integer> localGraph = null;
    localGraph = new UndirectedSparseGraph<String, Integer>();
    Collection<String> similars = new LinkedList<String>();
    for (final Entity entity : similarEntities) {
        localGraph.addVertex(entity.getFirstLexeme());
        similars.add(entity.getFirstLexeme());
    }
    double mod_sim_thres = this.sim_thres;
    System.out.println("simthres " + this.sim_thres);
    this.sim_thres = 0.20;
    mod_sim_thres = 0.20;
    final double min_thres = 0.01;
    final WeakComponentClusterer<String, Integer> weakComponentClusterer = new WeakComponentClusterer<String, Integer>();
    Collection<Graph<String, Integer>> connectedComponents;
    /*
     * Current implementation adds edges until the number of connected components falls below a
     * threshold
     */
    // final GraphMLWriter<String, Integer> writer = new GraphMLWriter<String, Integer>();
    int iteration = 0;
    do {

        createGraph(similars, localGraph, mod_sim_thres);

        connectedComponents = FilterUtils
                .createAllInducedSubgraphs(weakComponentClusterer.transform(localGraph), localGraph);
        mod_sim_thres = (mod_sim_thres) - (mod_sim_thres / 10);
        System.out.println(
                "got " + connectedComponents.size() + " components reducing sim_thres to " + mod_sim_thres);

        // HEURISTICS WARNING
    } while (connectedComponents.size() > 70 && mod_sim_thres > min_thres);

    System.out.println("final connected components " + connectedComponents.size());

    /*
     * We assume that each connected component represents one sense If the components are too
     * large (needs to be defined), then an more sophisticated clustering is being run.
     */
    int maxSize = 0;
    final List<List<String>> result = new LinkedList<List<String>>();
    final Graph<String, Integer> outliersGraph = new UndirectedSparseGraph<String, Integer>();
    for (final Graph<String, Integer> subGraph : connectedComponents) {
        if (subGraph.getVertexCount() > 1) {
            System.out.println("found connected component !:");

            for (final String i1 : subGraph.getVertices()) {
                System.out.print(i1 + ",");
            }
            System.out.println();

            if (subGraph.getVertexCount() > 20) {
                System.out.println("large cluster found, running community detection");
                final Transformer<Graph<String, Integer>, Set<Set<String>>> fc = new EdgeBetweennessClusterer<String, Integer>(
                        subGraph.getEdgeCount() / 10);

                final Collection<Graph<String, Integer>> subSubGraph = FilterUtils
                        .createAllInducedSubgraphs(fc.transform(subGraph), subGraph);
                System.out.println("done, found " + subSubGraph.size() + " clusters");
                iteration = 0;
                for (final Graph<String, Integer> g2 : subSubGraph) {
                    final List<String> list = new LinkedList<String>();
                    for (final String vertex : g2.getVertices()) {
                        list.add(vertex);
                    }
                    if (list.size() > 1) {
                        result.add(list);

                    } else {
                        outliersGraph.addVertex(list.get(0));
                    }
                }
            } else {
                final List<String> list = new LinkedList<String>();
                for (final String vertex : subGraph.getVertices()) {
                    list.add(vertex);
                }
                result.add(list);
            }

        } else {
            outliersGraph.addVertex(subGraph.getVertices().iterator().next());
        }
        if (subGraph.getVertexCount() >= maxSize) {
            maxSize = subGraph.getVertexCount();
            localGraph = subGraph;
        }

    }
    createGraph(outliersGraph.getVertices(), outliersGraph, 0.000001);
    System.out.println("size of outliersgraph " + outliersGraph.getVertexCount());

    connectedComponents = FilterUtils.createAllInducedSubgraphs(weakComponentClusterer.transform(outliersGraph),
            outliersGraph);
    System.out.println("connected components in outliersgraph " + connectedComponents.size());
    for (final Graph<String, Integer> subGraph : connectedComponents) {
        // System.out.println("component with "+g.getVertexCount()+" verticex");
        if (subGraph.getVertexCount() > 1) {
            System.out.println("found connected component !:");

            for (final String i1 : subGraph.getVertices()) {
                System.out.print(i1 + ",");
            }
            System.out.println();
            final List<String> list = new LinkedList<String>();
            for (final String vertex : subGraph.getVertices()) {
                list.add(vertex);
            }
            result.add(list);
        }
    }
    return result;

}

From source file:edu.uci.ics.jung.visualization.control.LabelEditingGraphMousePlugin.java

/**
 * For primary modifiers (default, MouseButton1):
 * pick a single Vertex or Edge that/*from   www  .j  a  va 2  s.c  om*/
  * is under the mouse pointer. If no Vertex or edge is under
  * the pointer, unselect all picked Vertices and edges, and
  * set up to draw a rectangle for multiple selection
  * of contained Vertices.
  * For additional selection (default Shift+MouseButton1):
  * Add to the selection, a single Vertex or Edge that is
  * under the mouse pointer. If a previously picked Vertex
  * or Edge is under the pointer, it is un-picked.
  * If no vertex or Edge is under the pointer, set up
  * to draw a multiple selection rectangle (as above)
  * but do not unpick previously picked elements.
 * 
 * @param e the event
 */
@SuppressWarnings("unchecked")
public void mouseClicked(MouseEvent e) {
    if (e.getModifiers() == modifiers && e.getClickCount() == 2) {
        VisualizationViewer<V, E> vv = (VisualizationViewer) e.getSource();
        GraphElementAccessor<V, E> pickSupport = vv.getPickSupport();
        if (pickSupport != null) {
            Transformer<V, String> vs = vv.getRenderContext().getVertexLabelTransformer();
            if (vs instanceof MapTransformer) {
                Map<V, String> map = ((MapTransformer) vs).getMap();
                Layout<V, E> layout = vv.getGraphLayout();
                // p is the screen point for the mouse event
                Point2D p = e.getPoint();

                V vertex = pickSupport.getVertex(layout, p.getX(), p.getY());
                if (vertex != null) {
                    String newLabel = vs.transform(vertex);
                    newLabel = JOptionPane.showInputDialog("New Vertex Label for " + vertex);
                    if (newLabel != null) {
                        map.put(vertex, newLabel);
                        vv.repaint();
                    }
                    return;
                }
            }
            Transformer<E, String> es = vv.getRenderContext().getEdgeLabelTransformer();
            if (es instanceof MapTransformer) {
                Map<E, String> map = ((MapTransformer) es).getMap();
                Layout<V, E> layout = vv.getGraphLayout();
                // p is the screen point for the mouse event
                Point2D p = e.getPoint();
                // take away the view transform
                Point2D ip = vv.getRenderContext().getMultiLayerTransformer().inverseTransform(Layer.VIEW, p);
                E edge = pickSupport.getEdge(layout, ip.getX(), ip.getY());
                if (edge != null) {
                    String newLabel = JOptionPane.showInputDialog("New Edge Label for " + edge);
                    if (newLabel != null) {
                        map.put(edge, newLabel);
                        vv.repaint();
                    }
                    return;
                }
            }
        }
        e.consume();
    }
}

From source file:com.diversityarrays.kdxplore.trials.TrialSelectionDialog.java

public TrialSelectionDialog(Window owner, String title, DALClient c, List<Trial> kdxTrials,
        Transformer<BackgroundRunner, TrialSearchOptionsPanel> searchOptionsPanelFactory) {
    super(owner, title, USE_TRIALS);

    setGlassPane(backgroundRunner.getBlockingPane());

    searchOptionsPanel = searchOptionsPanelFactory.transform(backgroundRunner);
    helpInstructions = new JLabel(searchOptionsPanel.getHtmlHelp(GET_TRIALS));

    kdxTrialByIdDownloaded = kdxTrials.stream().filter(t -> t.getIdDownloaded() != null)
            .collect(Collectors.toMap(Trial::getIdDownloaded, java.util.function.Function.identity()));

    trialRecordTable.setName(this.getClass().getName() + ".trialRecordTable"); //$NON-NLS-1$

    TableColumnModel tcm = trialRecordTable.getColumnModel();
    TableCellRenderer cellRenderer = new OptionalCheckboxRenderer("Already downloaded");
    tcm.getColumn(trialRecordTableModel.getChosenColumnIndex()).setCellRenderer(cellRenderer);

    for (int col = tcm.getColumnCount(); --col >= 0;) {
        if ("TrialName".equals(trialRecordTable.getColumnName(col))) {
            TableColumn tc = tcm.getColumn(col);
            tc.setCellRenderer(new TrialNameCellRenderer());
            break;
        }//from ww w .ja va  2 s  . com
    }

    findTrialRecords.setEnabled(false);

    searchOptionsPanel.addSearchOptionsChangeListener(searchOptionsListener);
    wantTrialUnits.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filteringClauseUsed = null;
            handleSearchOptionsChoiceChanged();
        }
    });

    setDALClient(c);

    initialiseGui();

    if (owner != null) {
        Dimension ownerSize = owner.getSize();
        Dimension mySize = getSize();
        int w = (ownerSize.width * 3) / 4;
        int h = (ownerSize.height * 3) / 4;
        if (w > mySize.width || h > mySize.height) {
            if (w > mySize.width) {
                mySize.width = w;
            }
            if (h > mySize.height) {
                mySize.height = h;
            }
            setSize(mySize);
        }
    }

    // TODO consider using setSize to increase to parent's width
    getOkAction().setEnabled(false);
    trialRecordTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            getOkAction().setEnabled(trialRecordTableModel.getAnyChosen());
        }
    });
}

From source file:edu.uci.ics.jung.io.PajekNetIOTest.java

public void testMixedSaveLoadSave() throws IOException {
    Graph<Number, Number> graph1 = new SparseMultigraph<Number, Number>();
    for (int i = 0; i < 5; i++) {
        graph1.addVertex(i);/*from   w w  w.  j  a  va  2 s . c  om*/
    }
    int j = 0;

    List<Number> id = new ArrayList<Number>(graph1.getVertices());//Indexer.getIndexer(graph1);
    GreekLabels<Number> gl = new GreekLabels<Number>(id);
    Number[] edges = { 0, 1, 2, 3, 4, 5 };

    graph1.addEdge(j++, 0, 1, EdgeType.DIRECTED);
    graph1.addEdge(j++, 0, 2, EdgeType.DIRECTED);
    graph1.addEdge(j++, 1, 2, EdgeType.DIRECTED);
    graph1.addEdge(j++, 1, 3);
    graph1.addEdge(j++, 1, 4);
    graph1.addEdge(j++, 4, 3);

    Map<Number, Number> nr = new HashMap<Number, Number>();
    for (int i = 0; i < edges.length; i++) {
        nr.put(edges[i], new Float(Math.random()));
    }

    assertEquals(graph1.getEdgeCount(), 6);

    //        System.err.println(" mixed graph1 = "+graph1);
    //        for(Number edge : graph1.getEdges()) {
    //           System.err.println("edge "+edge+" is directed? "+graph1.getEdgeType(edge));
    //        }
    //        for(Number v : graph1.getVertices()) {
    //           System.err.println(v+" outedges are "+graph1.getOutEdges(v));
    //           System.err.println(v+" inedges are "+graph1.getInEdges(v));
    //           System.err.println(v+" incidentedges are "+graph1.getIncidentEdges(v));
    //        }

    String testFilename = "mtest.net";
    String testFilename2 = testFilename + "2";

    // lay out network
    Dimension d = new Dimension(100, 200);
    Transformer<Number, Point2D> vld = TransformerUtils.mapTransformer(
            LazyMap.decorate(new HashMap<Number, Point2D>(), new RandomLocationTransformer<Number>(d)));

    PajekNetWriter<Number, Number> pnw = new PajekNetWriter<Number, Number>();
    pnw.save(graph1, testFilename, gl, MapTransformer.getInstance(nr), vld);

    Graph<Number, Number> graph2 = pnr.load(testFilename, graphFactory);
    Transformer<Number, String> pl = pnr.getVertexLabeller();
    List<Number> id2 = new ArrayList<Number>(graph2.getVertices());
    Transformer<Number, Point2D> vld2 = pnr.getVertexLocationTransformer();

    assertEquals(graph1.getVertexCount(), graph2.getVertexCount());
    assertEquals(graph1.getEdgeCount(), graph2.getEdgeCount());

    // test vertex labels and locations
    for (int i = 0; i < graph1.getVertexCount(); i++) {
        Number v1 = id.get(i);
        Number v2 = id2.get(i);
        assertEquals(gl.transform(v1), pl.transform(v2));
        assertEquals(vld.transform(v1), vld2.transform(v2));
    }

    // test edge weights
    Transformer<Number, Number> nr2 = pnr.getEdgeWeightTransformer();
    for (Number e2 : graph2.getEdges()) {
        Pair<Number> endpoints = graph2.getEndpoints(e2);
        Number v1_2 = endpoints.getFirst();
        Number v2_2 = endpoints.getSecond();
        Number v1_1 = id.get(id2.indexOf(v1_2));
        Number v2_1 = id.get(id2.indexOf(v2_2));
        Number e1 = graph1.findEdge(v1_1, v2_1);
        assertNotNull(e1);
        assertEquals(nr.get(e1).floatValue(), nr2.transform(e2).floatValue(), 0.0001);
    }

    pnw.save(graph2, testFilename2, pl, nr2, vld2);

    compareIndexedGraphs(graph1, graph2);

    pnr.setVertexLabeller(null);
    Graph<Number, Number> graph3 = pnr.load(testFilename2, graphFactory);

    compareIndexedGraphs(graph2, graph3);

    File file1 = new File(testFilename);
    File file2 = new File(testFilename2);

    Assert.assertTrue(file1.length() == file2.length());
    file1.delete();
    file2.delete();

}

From source file:edu.uci.ics.jung.algorithms.scoring.TestBetweennessCentrality.java

public void testWeighted() {
    Graph<Integer, Character> graph = new DirectedSparseGraph<Integer, Character>();

    for (int i = 0; i < 5; i++)
        graph.addVertex(i);//from ww  w  .j a v a 2 s . c om

    char edge = 'a';
    graph.addEdge(edge++, 0, 1);
    graph.addEdge(edge++, 0, 2);
    graph.addEdge(edge++, 2, 3);
    graph.addEdge(edge++, 3, 1);
    graph.addEdge(edge++, 1, 4);

    final int weights[] = { 1, 1, 1, 1, 1 };

    Transformer<Character, Integer> edge_weights = new Transformer<Character, Integer>() {
        public Integer transform(Character arg0) {
            return weights[arg0 - 'a'];
        }
    };

    BetweennessCentrality<Integer, Character> bc = new BetweennessCentrality<Integer, Character>(graph,
            edge_weights);
    //          new BetweennessCentrality<Integer,Integer>(graph);

    System.out.println("scoring");
    System.out.println("(weighted)");
    System.out.println("vertices:");
    for (int i = 0; i < graph.getVertexCount(); i++)
        System.out.println(String.format("%d: %f", i, bc.getVertexScore(i)));
    System.out.println("edges:");
    for (int i = 0; i < graph.getEdgeCount(); i++) {
        char e = (char) (i + 'a');
        System.out.println(
                String.format("%c: (weight: %d), %f", e, edge_weights.transform(e), bc.getEdgeScore(e)));
    }
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.AutomatonToDot.java

public String convertToDot(Automaton<T> automaton, Transformer<Step<T>, String> edgeLabelTransformer) {
    StringBuilder sb = new StringBuilder();
    sb.append("digraph finite_state_machine {\n" + "\trankdir=LR;\n" + "\tnode [shape = circle];\n");
    List<State<T>> finiteStates = new LinkedList<State<T>>();
    Deque<State<T>> queue = new ArrayDeque<State<T>>();
    Set<State<T>> visited = new HashSet<State<T>>();
    queue.addLast(automaton.getInitialState());
    visited.add(automaton.getInitialState());
    while (!queue.isEmpty()) {
        State<T> actual = queue.removeFirst();
        if (actual.getFinalCount() > 0) {
            finiteStates.add(actual);/*from   ww  w  . j  a v a 2 s  .  c  om*/
        }
        for (Step<T> step : automaton.getDelta().get(actual)) {
            sb.append("\t");
            sb.append(step.getSource().getName());
            sb.append(" -> ");
            sb.append(step.getDestination().getName());
            sb.append(" [ label = \"");
            sb.append(edgeLabelTransformer.transform(step));
            sb.append("|");
            sb.append(step.getUseCount());
            sb.append("\" ];\n");
            if (!visited.contains(step.getDestination())) {
                queue.addLast(step.getDestination());
                visited.add(step.getDestination());
            }
        }
    }
    sb.append("\n}");
    return sb.toString();
}

From source file:mulavito.algorithms.shortestpath.ksp.Eppstein.java

@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();/*  www  . j  a v  a  2s  .c  o m*/

        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;
}

From source file:edu.uci.ics.jung.io.PajekNetWriter.java

/**
 * Writes <code>graph</code> to <code>w</code>.  Labels for vertices may
 * be supplied by <code>vs</code> (defaults to no labels if null), 
 * edge weights may be specified by <code>nev</code>
 * (defaults to weights of 1.0 if null), 
 * and vertex locations may be specified by <code>vld</code> (defaults
 * to no locations if null). /*from   w w  w.j  a  va 2s.c  om*/
 */
public void save(Graph<V, E> graph, Writer w, Transformer<V, String> vs, Transformer<E, Number> nev,
        Transformer<V, Point2D> vld) throws IOException {
    /*
     * TODO: Changes we might want to make:
     * - optionally writing out in list form
     */

    BufferedWriter writer = new BufferedWriter(w);
    if (nev == null)
        nev = new Transformer<E, Number>() {
            public Number transform(E e) {
                return 1;
            }
        };
    writer.write("*Vertices " + graph.getVertexCount());
    writer.newLine();

    List<V> id = new ArrayList<V>(graph.getVertices());//Indexer.getIndexer(graph);
    for (V currentVertex : graph.getVertices()) {
        // convert from 0-based to 1-based index
        int v_id = id.indexOf(currentVertex) + 1;
        writer.write("" + v_id);
        if (vs != null) {
            String label = vs.transform(currentVertex);
            if (label != null)
                writer.write(" \"" + label + "\"");
        }
        if (vld != null) {
            Point2D location = vld.transform(currentVertex);
            if (location != null)
                writer.write(" " + location.getX() + " " + location.getY() + " 0.0");
        }
        writer.newLine();
    }

    Collection<E> d_set = new HashSet<E>();
    Collection<E> u_set = new HashSet<E>();

    boolean directed = graph instanceof DirectedGraph;

    boolean undirected = graph instanceof UndirectedGraph;

    // if it's strictly one or the other, no need to create extra sets
    if (directed)
        d_set.addAll(graph.getEdges());
    if (undirected)
        u_set.addAll(graph.getEdges());
    if (!directed && !undirected) // mixed-mode graph
    {
        u_set.addAll(graph.getEdges());
        d_set.addAll(graph.getEdges());
        for (E e : graph.getEdges()) {
            if (graph.getEdgeType(e) == EdgeType.UNDIRECTED) {
                d_set.remove(e);
            } else {
                u_set.remove(e);
            }
        }
    }

    // write out directed edges
    if (!d_set.isEmpty()) {
        writer.write("*Arcs");
        writer.newLine();
    }
    for (E e : d_set) {
        int source_id = id.indexOf(graph.getEndpoints(e).getFirst()) + 1;
        int target_id = id.indexOf(graph.getEndpoints(e).getSecond()) + 1;
        float weight = nev.transform(e).floatValue();
        writer.write(source_id + " " + target_id + " " + weight);
        writer.newLine();
    }

    // write out undirected edges
    if (!u_set.isEmpty()) {
        writer.write("*Edges");
        writer.newLine();
    }
    for (E e : u_set) {
        Pair<V> endpoints = graph.getEndpoints(e);
        int v1_id = id.indexOf(endpoints.getFirst()) + 1;
        int v2_id = id.indexOf(endpoints.getSecond()) + 1;
        float weight = nev.transform(e).floatValue();
        writer.write(v1_id + " " + v2_id + " " + weight);
        writer.newLine();
    }
    writer.close();
}