Example usage for java.util Collection retainAll

List of usage examples for java.util Collection retainAll

Introduction

In this page you can find the example usage for java.util Collection retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this collection that are contained in the specified collection (optional operation).

Usage

From source file:gov.llnl.lc.infiniband.opensm.plugin.gui.graph.CollapsableGraphView.java

public CollapsableGraphView(Graph graph, boolean val) throws HeadlessException {
    super();/*from   w ww  .  j  av a  2 s.  c  o m*/
    setGraph(graph);

    layout = new FRLayout(graph);
    Dimension preferredSize = new Dimension(400, 400);
    final VisualizationModel visualizationModel = new DefaultVisualizationModel(layout, preferredSize);
    VisualizationViewer vv = new VisualizationViewer(visualizationModel, preferredSize);

    vv.addGraphMouseListener(new CollapsableGraphMouseListener<Number>());

    vv.getRenderContext().setVertexShapeTransformer(new ClusterVertexShapeTransformer());

    PickedState<Integer> picked_state = vv.getPickedVertexState();

    // create decorators
    vv.getRenderContext().setVertexFillPaintTransformer(IB_TransformerFactory.getDefaultPaintTransformer(vv));

    setVisViewer(vv);

    final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance();
    final Set exclusions = new HashSet();
    eif.setPredicate(new Predicate() {

        public boolean evaluate(Object e) {

            return exclusions.contains(e);
        }
    });

    vv.getRenderContext().setParallelEdgeIndexFunction(eif);

    vv.setBackground(Color.white);

    // add a listener for ToolTips

    vv.setVertexToolTipTransformer(new ToStringLabeller() {

        /*
         * (non-Javadoc)
         * 
         * @see edu.uci.ics.jung.visualization.decorators.DefaultToolTipFunction#
         * getToolTipText(java.lang.Object)
         */
        @Override
        public String transform(Object v) {
            if (v instanceof Graph) {
                return ((Graph) v).getVertices().toString();
            }
            return super.transform(v);
        }
    });

    /**
     * the regular graph mouse for the normal view
     */
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();

    vv.setGraphMouse(graphMouse);

    Container content = getContentPane();
    GraphZoomScrollPane gzsp = new GraphZoomScrollPane(vv);
    content.add(gzsp);

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(graphMouse.getModeListener());
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton collapse = new JButton("Collapse");
    collapse.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            System.out.println("Collapsing the graph");

            // Pick all port zeros, and their IMMEDIATE links
            //        PickManager.getInstance().pickAllSwitches(vv);

            VisualizationViewer vv = getVisViewer();
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            if (picked.size() > 1) {
                System.out.println("CGV: The number picked is: " + picked.size());
                Graph inGraph = layout.getGraph();
                Graph clusterGraph = collapser.getClusterGraph(inGraph, picked);

                Graph g = collapser.collapse(layout.getGraph(), clusterGraph);
                collapsedGraph = g;
                double sumx = 0;
                double sumy = 0;
                for (Object v : picked) {
                    Point2D p = (Point2D) layout.transform(v);
                    sumx += p.getX();
                    sumy += p.getY();
                }
                Point2D cp = new Point2D.Double(sumx / picked.size(), sumy / picked.size());
                vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                layout.setGraph(g);
                layout.setLocation(clusterGraph, cp);
                vv.getPickedVertexState().clear();
                vv.repaint();
            }

            // Collection picked = new
            // HashSet(vv.getPickedVertexState().getPicked());
            // if (picked.size() > 1)
            // {
            // Graph inGraph = layout.getGraph();
            // Graph clusterGraph = collapser.getClusterGraph(inGraph, picked);
            //
            // Graph g = collapser.collapse(layout.getGraph(), clusterGraph);
            // collapsedGraph = g;
            // double sumx = 0;
            // double sumy = 0;
            // for (Object v : picked)
            // {
            // Point2D p = (Point2D) layout.transform(v);
            // sumx += p.getX();
            // sumy += p.getY();
            // }
            // Point2D cp = new Point2D.Double(sumx / picked.size(), sumy /
            // picked.size());
            // vv.getRenderContext().getParallelEdgeIndexFunction().reset();
            // layout.setGraph(g);
            // layout.setLocation(clusterGraph, cp);
            // vv.getPickedVertexState().clear();
            // vv.repaint();
            // }

        }

    });

    JButton compressEdges = new JButton("Compress Edges");
    compressEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                getExclusions().addAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expandEdges = new JButton("Expand Edges");
    expandEdges.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Collection picked = vv.getPickedVertexState().getPicked();
            if (picked.size() == 2) {
                Pair pair = new Pair(picked);
                Graph graph = layout.getGraph();
                Collection edges = new HashSet(graph.getIncidentEdges(pair.getFirst()));
                edges.retainAll(graph.getIncidentEdges(pair.getSecond()));
                getExclusions().removeAll(edges);
                vv.repaint();
            }

        }
    });

    JButton expand = new JButton("Expand");
    expand.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Collection picked = new HashSet(vv.getPickedVertexState().getPicked());
            for (Object v : picked) {
                if (v instanceof Graph) {

                    Graph g = collapser.expand(layout.getGraph(), (Graph) v);
                    vv.getRenderContext().getParallelEdgeIndexFunction().reset();
                    layout.setGraph(g);
                }
                vv.getPickedVertexState().clear();
                vv.repaint();
            }
        }
    });

    JButton reset = new JButton("Reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            VisualizationViewer vv = getVisViewer();
            Graph g = getGraph();
            layout.setGraph(g);
            getExclusions().clear();
            vv.repaint();
        }
    });

    JButton help = new JButton("Help");
    help.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog((JComponent) e.getSource(), getInstructions(), "Help",
                    JOptionPane.PLAIN_MESSAGE);
        }
    });
    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    // use a renderer to shorten the layout name presentation
    jcb.setRenderer(new DefaultListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });
    jcb.addActionListener(new LayoutChooser(jcb, vv, this));
    jcb.setSelectedItem(FRLayout.class);

    JPanel controls = new JPanel();
    JPanel zoomControls = new JPanel(new GridLayout(2, 1));
    zoomControls.setBorder(BorderFactory.createTitledBorder("Zoom"));
    zoomControls.add(plus);
    zoomControls.add(minus);
    controls.add(zoomControls);
    JPanel collapseControls = new JPanel(new GridLayout(3, 1));
    collapseControls.setBorder(BorderFactory.createTitledBorder("Picked"));
    collapseControls.add(collapse);
    collapseControls.add(expand);
    collapseControls.add(compressEdges);
    collapseControls.add(expandEdges);
    collapseControls.add(reset);
    controls.add(collapseControls);
    controls.add(modeBox);
    controls.add(help);
    controls.add(jcb);
    content.add(controls, BorderLayout.SOUTH);
}

From source file:org.codehaus.mojo.truezip.internal.TrueZipFileSetManager.java

private Set findDeletableFiles(TrueZipFileSet fileSet, Set deletableDirectories) {
    TrueZipDirectoryScanner scanner = scan(fileSet);

    if (scanner == null) {
        return deletableDirectories;
    }//from  w  ww.  j a  va2 s.  co m

    Set includes = deletableDirectories;
    includes.addAll(Arrays.asList(scanner.getIncludedFiles()));
    Collection excludes = new ArrayList(Arrays.asList(scanner.getExcludedFiles()));
    Collection linksForDeletion = new ArrayList();

    if (!fileSet.isFollowSymlinks()) {
        // we need to see which entries were only excluded because they're symlinks...
        scanner.setFollowSymlinks(true);
        scanner.scan();

        List includedFilesAndSymlinks = Arrays.asList(scanner.getIncludedFiles());

        linksForDeletion.addAll(excludes);
        linksForDeletion.retainAll(includedFilesAndSymlinks);

        excludes.removeAll(includedFilesAndSymlinks);
    }

    excludeParentDirectoriesOfExcludedPaths(excludes, includes);

    includes.addAll(linksForDeletion);

    return includes;
}

From source file:org.codehaus.mojo.truezip.internal.TrueZipFileSetManager.java

private Set findDeletableDirectories(TrueZipFileSet fileSet) {
    TrueZipDirectoryScanner scanner = scan(fileSet);

    if (scanner == null) {
        return Collections.EMPTY_SET;
    }/*  w w  w  . j a v  a2  s  . c o m*/

    Set includes = new HashSet(Arrays.asList(scanner.getIncludedDirectories()));
    Collection excludes = new ArrayList(Arrays.asList(scanner.getExcludedDirectories()));
    Collection linksForDeletion = new ArrayList();

    if (!fileSet.isFollowSymlinks()) {

        // we need to see which entries were only excluded because they're symlinks...
        scanner.setFollowSymlinks(true);
        scanner.scan();

        List includedDirsAndSymlinks = Arrays.asList(scanner.getIncludedDirectories());

        linksForDeletion.addAll(excludes);
        linksForDeletion.retainAll(includedDirsAndSymlinks);

        excludes.removeAll(includedDirsAndSymlinks);
    }

    excludeParentDirectoriesOfExcludedPaths(excludes, includes);

    includes.addAll(linksForDeletion);

    return includes;
}

From source file:ubic.gemma.core.analysis.sequence.BlatAssociationScorer.java

/**
 * Compute scores and find the best one, for each gene product, removing all other hits (so there is just one per
 * gene product//from   www  .  j a  v a  2s.com
 *
 * @param blatAssociations             blat assocs.
 * @param geneProduct2BlatAssociations gene prods 2 blat assocs
 * @return blat accoc
 */
private static BlatAssociation removeExtraHitsPerGeneProduct(Collection<BlatAssociation> blatAssociations,
        Map<GeneProduct, Collection<BlatAssociation>> geneProduct2BlatAssociations) {

    double globalMaxScore = 0.0;
    BlatAssociation globalBest = null;
    Collection<BlatAssociation> keepers = new HashSet<>();

    for (GeneProduct geneProduct : geneProduct2BlatAssociations.keySet()) {
        Collection<BlatAssociation> geneProductBlatAssociations = geneProduct2BlatAssociations.get(geneProduct);

        if (geneProductBlatAssociations.isEmpty())
            continue;

        BlatAssociation ba = geneProductBlatAssociations.iterator().next();

        // Find the best one. If there are ties it's arbitrary which one we pick.
        double maxScore = ba.getScore();
        BlatAssociation best = ba;
        for (BlatAssociation blatAssociation : geneProductBlatAssociations) {
            double score = blatAssociation.getScore();
            if (score >= maxScore) {
                maxScore = score;
                best = blatAssociation;
            }
        }

        // Remove the lower-scoring ones for this gene product
        Collection<BlatAssociation> toKeep = new HashSet<>();
        toKeep.add(best);
        keepers.add(best);
        geneProduct2BlatAssociations.put(geneProduct, toKeep);

        if (best.getScore() > globalMaxScore) {
            globalMaxScore = best.getScore();
            globalBest = best;
        }

    }
    blatAssociations.retainAll(keepers);
    return globalBest;
}

From source file:ubic.gemma.analysis.sequence.BlatAssociationScorer.java

/**
 * Compute scores and find the best one, for each gene product, removing all other hits (so there is just one per
 * gene product//w w w  .j a  v a  2  s  .  c  om
 * 
 * @param blatAssociations
 * @param geneProduct2BlatAssociations
 * @return
 */
private static BlatAssociation removeExtraHitsPerGeneProduct(Collection<BlatAssociation> blatAssociations,
        Map<GeneProduct, Collection<BlatAssociation>> geneProduct2BlatAssociations) {

    double globalMaxScore = 0.0;
    BlatAssociation globalBest = null;
    Collection<BlatAssociation> keepers = new HashSet<BlatAssociation>();
    for (GeneProduct geneProduct : geneProduct2BlatAssociations.keySet()) {
        Collection<BlatAssociation> geneProductBlatAssociations = geneProduct2BlatAssociations.get(geneProduct);

        if (geneProductBlatAssociations.isEmpty())
            continue;

        BlatAssociation ba = geneProductBlatAssociations.iterator().next();

        // Find the best one. If there are ties it's arbitrary which one we pick.
        double maxScore = ba.getScore();
        BlatAssociation best = ba;
        for (BlatAssociation blatAssociation : geneProductBlatAssociations) {
            double score = blatAssociation.getScore();
            if (score >= maxScore) {
                maxScore = score;
                best = blatAssociation;
            }
        }

        // Remove the lower-scoring ones for this gene product
        Collection<BlatAssociation> toKeep = new HashSet<BlatAssociation>();
        toKeep.add(best);
        keepers.add(best);
        geneProduct2BlatAssociations.put(geneProduct, toKeep);

        if (best.getScore() > globalMaxScore) {
            globalMaxScore = best.getScore();
            globalBest = best;
        }

    }
    blatAssociations.retainAll(keepers);
    return globalBest;
}

From source file:io.seldon.clustering.recommender.CountRecommender.java

private void updateTagCounts(String tag, Float tagWeight, int tagAttrId, Set<Integer> dimensions,
        Integer dimension2, boolean checkDimension, int limit, Set<Long> exclusions, Map<Long, Double> counts,
        double decay) {
    Map<Long, Double> itemCounts = null;
    boolean localDimensionCheckNeeded = false;
    if (checkDimension) {
        try {/*  w ww  . j a  v a2 s . c o  m*/
            itemCounts = getClusterTopCountsForTagAndDimensions(tag, tagAttrId, dimensions, dimension2, limit,
                    decay);
        } catch (ClusterCountNoImplementationException e) {
            localDimensionCheckNeeded = true;
        }
    }

    if (itemCounts == null) {
        try {
            itemCounts = getClusterTopCountsForTag(tag, tagAttrId, limit, decay);
        } catch (ClusterCountNoImplementationException e) {
            logger.error("Failed to get cluster counts as method not implemented", e);
            itemCounts = new HashMap<>();
        }
    }
    double maxCount = 0;
    for (Map.Entry<Long, Double> itemCount : itemCounts.entrySet())
        if (itemCount.getValue() > maxCount)
            maxCount = itemCount.getValue();
    if (maxCount > 0) {
        for (Map.Entry<Long, Double> itemCount : itemCounts.entrySet()) {
            Long item = itemCount.getKey();
            if (checkDimension && localDimensionCheckNeeded) {
                Collection<Integer> dims = ItemService.getItemDimensions(new ConsumerBean(client), item);
                dims.retainAll(dimensions);
                if (dims.isEmpty())
                    continue;
            }
            if (!exclusions.contains(item)) {
                Double count = (itemCount.getValue() / maxCount) * tagWeight;
                Double existing = counts.get(item);
                if (existing != null)
                    count = count + existing;
                counts.put(item, count);
            }
        }
    }
}

From source file:io.seldon.clustering.recommender.CountRecommender.java

public Map<Long, Double> recommendGlobal(Set<Integer> dimensions, int numRecommendations, Set<Long> exclusions,
        double decay, Integer dimension2) {
    boolean checkDimension = !(dimensions.isEmpty()
            || (dimensions.size() == 1 && dimensions.iterator().next() == Constants.DEFAULT_DIMENSION));
    int numTopCounts = numRecommendations * 5;
    Map<Long, Double> itemCounts = null;
    boolean localDimensionCheckNeeded = false;
    if (checkDimension) {
        try {//from   w  w w.  j av  a 2s. co  m
            itemCounts = getClusterTopCountsForDimension(dimensions, numTopCounts, decay, dimension2);
        } catch (ClusterCountNoImplementationException e) {
            localDimensionCheckNeeded = true;
        }
    }

    if (itemCounts == null) {
        try {
            itemCounts = getClusterTopCounts(numTopCounts, decay);
            if (itemCounts == null) {
                logger.warn("Got null itemcounts");
                itemCounts = new HashMap<>();
            }
        } catch (ClusterCountNoImplementationException e) {
            logger.error("Failed to get cluster counts as method not implemented", e);
            itemCounts = new HashMap<>();
        }
    }
    int excluded = 0;
    for (Iterator<Map.Entry<Long, Double>> i = itemCounts.entrySet().iterator(); i.hasNext();) {
        Map.Entry<Long, Double> e = i.next();
        Long item = e.getKey();
        if (checkDimension && localDimensionCheckNeeded) {
            Collection<Integer> dims = ItemService.getItemDimensions(new ConsumerBean(client), item);
            dims.retainAll(dimensions);
            if (dims.isEmpty()) {
                i.remove();
                excluded++;
            }
        } else if (exclusions.contains(item)) {
            i.remove();
            excluded++;
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Recommend global for dimension " + StringUtils.join(dimensions, ",") + " numRecs "
                + numRecommendations + " decay " + decay + " #in map " + itemCounts.size() + " excluded "
                + excluded + " client " + client);
    return RecommendationUtils.rescaleScoresToOne(itemCounts, numRecommendations);
}

From source file:ubic.gemma.core.genome.gene.service.GeneSetServiceImpl.java

@Override
@Transactional(readOnly = true)//from  w  ww . ja  v  a  2  s  .  c o  m
public Collection<GeneSet> getUsersGeneGroups(boolean privateOnly, Long taxonId, boolean sharedPublicOnly) {

    Taxon tax = null;
    if (taxonId != null) {
        tax = taxonService.load(taxonId);
        if (tax == null) {
            throw new IllegalArgumentException("No such taxon with id=" + taxonId);
        }
    }

    Collection<GeneSet> geneSets;

    if (privateOnly) {
        // gets all groups user can see (includes: owned by user, shared with user & public)
        geneSets = this.loadAll(tax);

        // this filtering is to filter out public sets
        try {
            if (!geneSets.isEmpty()) {
                geneSets.retainAll(securityService.choosePrivate(geneSets));
            }
        } catch (AccessDeniedException e) {
            // okay, they just aren't allowed to see those.
        }
    } else if (sharedPublicOnly) {
        // gets all groups shared with the user and all groups owned by the user, except public ones
        geneSets = this.loadMySharedGeneSets(tax);
    } else {
        geneSets = this.loadAll(tax);
    }

    return geneSets;
}

From source file:io.seldon.clustering.recommender.CountRecommender.java

private void updateCounts(String recommenderType, long userId, UserCluster cluster, Set<Integer> dimensions,
        boolean checkDimension, int numTopCounts, Set<Long> exclusions, Map<Long, Double> counts,
        double clusterWeight, double decay, Integer dim2) {
    Map<Long, Double> itemCounts = null;
    boolean localDimensionCheckNeeded = false;
    if (checkDimension) {
        try {/*from   w  w w . ja v  a  2 s  .  c  o m*/
            itemCounts = getClusterTopCountsForDimension(recommenderType, cluster.getCluster(), dimensions,
                    cluster.getTimeStamp(), numTopCounts, decay, dim2);
        } catch (ClusterCountNoImplementationException e) {
            localDimensionCheckNeeded = true;
        }
    }

    if (itemCounts == null) {
        try {
            itemCounts = getClusterTopCounts(cluster.getCluster(), cluster.getTimeStamp(), numTopCounts, decay);
        } catch (ClusterCountNoImplementationException e) {
            logger.error("Failed to get cluster counts as method not implemented", e);
            itemCounts = new HashMap<>();
        }
    }
    double maxCount = 0;
    for (Map.Entry<Long, Double> itemCount : itemCounts.entrySet())
        if (itemCount.getValue() > maxCount)
            maxCount = itemCount.getValue();
    if (maxCount > 0) {
        ItemPeer iPeer = null;
        if (localDimensionCheckNeeded)
            iPeer = Util.getItemPeer(client);
        for (Map.Entry<Long, Double> itemCount : itemCounts.entrySet()) {
            Long item = itemCount.getKey();
            if (checkDimension && localDimensionCheckNeeded) {
                Collection<Integer> dims = ItemService.getItemDimensions(new ConsumerBean(client), item);
                dims.retainAll(dimensions);
                if (dims.isEmpty())
                    continue;
            }
            if (!exclusions.contains(item)) {
                Double count = (itemCount.getValue() / maxCount) * cluster.getWeight() * clusterWeight; // weight cluster count by user weight for cluster and long term weight
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Adding long term count " + count + " for item " + item + " for user " + userId);
                Double existing = counts.get(item);
                if (existing != null)
                    count = count + existing;
                counts.put(item, count);
            } else if (logger.isDebugEnabled())
                logger.debug("Ignoring excluded long term item in cluster recommendation " + item + " for user "
                        + userId);
        }
    }
}

From source file:ubic.gemma.core.ontology.providers.GeneOntologyServiceImpl.java

@Override
public Collection<OntologyTerm> computeOverlap(Collection<OntologyTerm> masterTerms,
        Collection<OntologyTerm> comparisonTerms) {
    Collection<OntologyTerm> overlapTerms = new HashSet<>(masterTerms);
    overlapTerms.retainAll(comparisonTerms);

    return overlapTerms;
}