Example usage for com.google.common.collect Sets powerSet

List of usage examples for com.google.common.collect Sets powerSet

Introduction

In this page you can find the example usage for com.google.common.collect Sets powerSet.

Prototype

@GwtCompatible(serializable = false)
public static <E> Set<Set<E>> powerSet(Set<E> set) 

Source Link

Document

Returns the set of all possible subsets of set .

Usage

From source file:org.icgc.dcc.portal.model.UnionAnalysisRequest.java

public List<UnionUnit> toUnionSets() {

    val setSize = lists.size();
    val subsets = Sets.powerSet(this.lists);

    /*//from  w w  w.  j a  v a2  s. co  m
     * Used to remove the empty set and itself from the subsets.
     */
    val predicate = new Predicate<Collection<?>>() {

        @Override
        public boolean apply(Collection<?> s) {
            val size = s.size();
            return (size > 0) && (size < setSize);
        }
    };
    val filteredSubsets = Sets.filter(subsets, predicate);
    val resultSize = filteredSubsets.size();

    val result = new ArrayList<UnionUnit>(resultSize + 1);

    for (val subset : filteredSubsets) {
        val unionUnit = new UnionUnit(Sets.difference(this.lists, subset), subset);
        result.add(unionUnit);
    }
    result.add(UnionUnit.noExclusionInstance(this.lists));

    return result;
}

From source file:com.eucalyptus.cloudwatch.domain.listmetrics.ListMetricManager.java

private static List<ListMetric> foldMetric(String accountId, String metricName, String namespace,
        Map<String, String> dimensionMap, MetricType metricType) {
    List<ListMetric> metrics = Lists.newArrayList();
    if (dimensionMap == null) {
        dimensionMap = new HashMap<String, String>();
    } else if (dimensionMap.size() > ListMetric.MAX_DIM_NUM) {
        throw new IllegalArgumentException("Too many dimensions for metric, " + dimensionMap.size());
    }/*from  w w w  . j  a v  a2  s.com*/
    TreeSet<DimensionEntity> dimensions = new TreeSet<DimensionEntity>();
    for (Map.Entry<String, String> entry : dimensionMap.entrySet()) {
        DimensionEntity d = new DimensionEntity();
        d.setName(entry.getKey());
        d.setValue(entry.getValue());
        dimensions.add(d);
    }
    Set<Set<DimensionEntity>> permutations = null;
    if (metricType == MetricType.System) {
        // do dimension folding (i.e. insert 2^n metrics.  
        // All with the same metric name and namespace, but one for each subset of the dimension set passed in, including all, and none)
        if (!namespace.equals("AWS/EC2")) {
            permutations = Sets.powerSet(dimensions);
        } else {
            // Hack: no values in AWS/EC2 have more than one dimension, so fold, but only choose dimension subsets of size at most 1.
            // See EUCA-do dimension folding (i.e. insert 2^n metrics.  
            // All with the same metric name and namespace, but one for each subset of the dimension set passed in, including all, and none)
            permutations = Sets.filter(Sets.powerSet(dimensions), new Predicate<Set<DimensionEntity>>() {
                public boolean apply(@Nullable Set<DimensionEntity> candidate) {
                    return (candidate != null && candidate.size() < 2);
                }
            });
        }
    } else { // no folding on custom metrics
        permutations = Sets.newHashSet();
        permutations.add(dimensions);
    }
    for (Set<DimensionEntity> dimensionsPermutation : permutations) {
        ListMetric metric = new ListMetric();
        metric.setAccountId(accountId);
        metric.setMetricName(metricName);
        metric.setNamespace(namespace);
        metric.setDimensions(dimensionsPermutation);
        metric.setMetricType(metricType);
        metrics.add(metric);
    }
    return metrics;
}

From source file:com.eucalyptus.cloudwatch.domain.metricdata.MetricManager.java

private static List<MetricEntity> foldAndHash(SimpleMetricEntity simpleMetricEntity) {
    if (simpleMetricEntity == null)
        return new ArrayList<MetricEntity>();
    TreeSet<DimensionEntity> dimensions = new TreeSet<DimensionEntity>();
    for (Map.Entry<String, String> entry : simpleMetricEntity.getDimensionMap().entrySet()) {
        DimensionEntity d = new DimensionEntity();
        d.setName(entry.getKey());//from   w w  w .ja  va 2 s.co m
        d.setValue(entry.getValue());
        dimensions.add(d);
    }
    Set<Set<DimensionEntity>> permutations = null;
    if (simpleMetricEntity.getMetricType() == MetricType.System) {
        permutations = Sets.powerSet(dimensions);
    } else {
        permutations = Sets.newHashSet();
        permutations.add(dimensions);
    }
    ArrayList<MetricEntity> returnValue = new ArrayList<MetricEntity>();
    for (Set<DimensionEntity> dimensionsPermutation : permutations) {
        String dimensionHash = hash(dimensionsPermutation);
        MetricEntity metric = MetricEntityFactory.getNewMetricEntity(simpleMetricEntity.getMetricType(),
                dimensionHash);
        metric.setAccountId(simpleMetricEntity.getAccountId());
        metric.setMetricName(simpleMetricEntity.getMetricName());
        metric.setNamespace(simpleMetricEntity.getNamespace());
        metric.setDimensions(dimensions);// arguable, but has complete list
        metric.setDimensionHash(dimensionHash);
        metric.setMetricType(simpleMetricEntity.getMetricType());
        metric.setUnits(simpleMetricEntity.getUnits());
        metric.setTimestamp(simpleMetricEntity.getTimestamp());
        metric.setSampleMax(simpleMetricEntity.getSampleMax());
        metric.setSampleMin(simpleMetricEntity.getSampleMin());
        metric.setSampleSum(simpleMetricEntity.getSampleSum());
        metric.setSampleSize(simpleMetricEntity.getSampleSize());
        returnValue.add(metric);
    }
    return returnValue;
}

From source file:org.dishevelled.venn.tools.Venn.java

/** {@inheritDoc} */
public void run() {
    int n = inputFiles.size();
    List<String> labels = new ArrayList<String>(n);
    List<Set<String>> sets = new ArrayList<Set<String>>(n);
    for (File inputFile : inputFiles) {
        labels.add(inputFile.getName());
        sets.add(read(inputFile));//from w  w w  .ja  v  a  2  s .c  o  m
    }
    VennModel<String> model = VennModels.createVennModel(sets);

    ImmutableMap.Builder<ImmutableBitSet, Set<String>> builder = ImmutableMap.builder();
    Set<Set<Integer>> powerSet = Sets.powerSet(range(n));
    for (Set<Integer> set : powerSet) {
        if (!set.isEmpty()) {
            ImmutableBitSet key = toImmutableBitSet(set);
            builder.put(key, model.exclusiveTo(first(key), additional(key)));
        }
    }
    Map<ImmutableBitSet, Set<String>> views = builder.build();

    PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    if (header()) {
        for (Map.Entry<ImmutableBitSet, Set<String>> entry : views.entrySet()) {
            write(true, buildLabel(labels, entry.getKey()), writer);
        }
        // todo trim extra \t
        writer.print("\n");
    }

    if (count()) {
        for (Map.Entry<ImmutableBitSet, Set<String>> entry : views.entrySet()) {
            write(true, entry.getValue().size(), writer);
        }
        // todo trim extra \t
        writer.print("\n");
    } else {
        List<Iterator<String>> iterators = new ArrayList<Iterator<String>>();

        for (Map.Entry<ImmutableBitSet, Set<String>> entry : views.entrySet()) {
            iterators.add(entry.getValue().iterator());
        }

        boolean done = false;
        while (!done) {
            boolean left = false;
            for (Iterator<String> iterator : iterators) {
                if (iterator.hasNext()) {
                    writer.write(iterator.next());
                    left = true;
                }
                writer.write("\t");
            }
            // todo trim extra \t
            writer.print("\n");
            done = !left;
        }
    }
    try {
        writer.close();
    } catch (Exception e) {
        // ignore
    }
}

From source file:gg.uhc.uhc.modules.team.TeamModule.java

protected void setupTeams(Predicate<Prefix> allowedPrefixes) {
    ImmutableMap.Builder<String, Team> teamBuilder = ImmutableMap.builder();

    // separate colours + formatting codes
    Set<ChatColor> colours = Sets.newHashSet();
    Set<ChatColor> formatting = Sets.newHashSet();

    for (ChatColor colour : ChatColor.values()) {
        if (colour.isColor()) {
            colours.add(colour);//  w w  w  . j  a  v  a2 s . c o  m
        } else {
            formatting.add(colour);
        }
    }

    Set<Set<ChatColor>> formattingCombinations = Sets.powerSet(formatting);

    int teamId = 1;
    int totalId = formattingCombinations.size() * colours.size();
    Joiner joiner = Joiner.on("");
    String reset = ChatColor.RESET.toString();

    for (Set<ChatColor> combination : formattingCombinations) {
        for (ChatColor color : colours) {
            if (!allowedPrefixes.apply(new Prefix(color, combination)))
                continue;

            String prefix = color + joiner.join(combination);
            String teamName = "UHC-" + teamId;

            Team team = scoreboard.getTeam(teamName);

            if (team == null) {
                team = scoreboard.registerNewTeam(teamName);
            }

            team.setDisplayName("UHC Team " + teamId);
            team.setPrefix(prefix);
            team.setSuffix(reset);

            teamBuilder.put(teamName, team);
            teamId++;
        }
    }

    // unregister extra ids
    for (int i = teamId; i <= totalId; i++) {
        Team team = scoreboard.getTeam("UHC-" + i);

        if (team != null) {
            team.unregister();
        }
    }

    teams = teamBuilder.build();
}

From source file:org.dishevelled.venn.model.VennModelImpl.java

/**
 * Create and return the map of exclusive set views keyed by bit set.
 *
 * @return the map of exclusive set views keyed by bit set
 *///from w  w  w . j  a  v a2  s .com
private Map<ImmutableBitSet, Set<E>> createExclusives() {
    Map<ImmutableBitSet, Set<E>> map = Maps.newHashMapWithExpectedSize((int) Math.pow(2, this.sets.size()) - 1);

    // construct a set containing 0...n integers
    Set<Integer> input = Sets.newHashSet();
    for (int i = 0, size = size(); i < size; i++) {
        input.add(Integer.valueOf(i));
    }

    // calculate the power set (note n > 30 will overflow int)
    Set<Set<Integer>> powerSet = Sets.powerSet(ImmutableSet.copyOf(input));
    for (Set<Integer> set : powerSet) {
        if (!set.isEmpty()) {
            // intersect all in set
            Iterator<Integer> indices = set.iterator();
            Set<E> view = sets.get(indices.next());
            while (indices.hasNext()) {
                view = Sets.intersection(view, sets.get(indices.next()));
            }

            // subtract all in input not in set
            for (Integer index : input) {
                if (!set.contains(index)) {
                    view = Sets.difference(view, sets.get(index));
                }
            }

            // add to exclusives map
            map.put(toImmutableBitSet(set), view);
        }
    }

    // make an immutable copy?
    return map;
}

From source file:org.terasology.rendering.opengl.GLSLMaterial.java

@Override
public void recompile() {
    TIntIntIterator it = shaderPrograms.iterator();
    while (it.hasNext()) {
        it.advance();//from   w  ww . j  a  va2  s  . c o  m
        GL20.glDeleteProgram(it.value());
    }
    shaderPrograms.clear();
    uniformLocationMap.clear();

    shaderPrograms.put(0, shader.linkShaderProgram(0));
    for (Set<ShaderProgramFeature> permutation : Sets.powerSet(shader.getAvailableFeatures())) {
        int featureMask = ShaderProgramFeature.getBitset(permutation);
        shaderPrograms.put(featureMask, shader.linkShaderProgram(featureMask));
    }
    if (shaderParameters != null) {
        shaderParameters.initialParameters(this);
    }
}

From source file:de.uni_potsdam.hpi.asg.logictool.mapping.GateMerger.java

public boolean merge() {

    //      new NetlistGraph(netlist, null, true);

    Queue<MergeSimulationStep> steps = new LinkedList<>();
    for (NetlistTerm t : netlist.getTerms()) {
        if (t.mergingAllowed()) {
            steps.add(new MergeSimulationStep(null, new HashSet<NetlistTerm>(), t.getLoopVar(), t.getDrivee(),
                    null, t, t.buildingLoopbackAllowed()));
        }/*from ww w  .  j  a  v  a 2s  .c om*/
    }

    Map<NetlistTerm, Set<Mapping>> matches = new HashMap<>();

    MergeSimulationStep step = null;
    while (!steps.isEmpty()) {
        step = steps.poll();
        evaluateStep(step, steps, matches);
    }

    //      for(Entry<NetlistTerm, Set<GateMapping>> entry : matches.entrySet()) {
    //         System.out.println(entry.getKey().getDrivee());
    //         for(GateMapping g : entry.getValue()) {
    //            System.out.println("\t" + g.toString());
    //         }
    //      }

    Map<Integer, Set<NetlistTerm>> cluster = new HashMap<>();
    Map<NetlistTerm, Integer> idmap = new HashMap<>();
    int id = 0;
    for (NetlistTerm t : netlist.getTerms()) {
        Set<NetlistTerm> tmp = new HashSet<>();
        tmp.add(t);
        cluster.put(id, tmp);
        idmap.put(t, id);
        id++;
    }

    //      for(Entry<NetlistTerm, Integer> entry : idmap.entrySet()) {
    //         System.out.println(entry.getKey().getDrivee() + " -> " + entry.getValue());
    //      }
    //      System.out.println("---");
    for (Entry<NetlistTerm, Set<Mapping>> entry : matches.entrySet()) {
        int entryid = idmap.get(entry.getKey());
        for (Mapping m : entry.getValue()) {
            for (NetlistTerm t : m.getTerms()) {
                int termid = idmap.get(t);
                if (termid != entryid) {
                    for (NetlistTerm t2 : cluster.get(termid)) {
                        idmap.put(t2, entryid);
                    }
                    cluster.get(entryid).addAll(cluster.get(termid));
                    cluster.remove(termid);
                }
            }
        }
    }

    //      for(Entry<Integer, Set<NetlistTerm>> entry : cluster.entrySet()) {
    //         System.out.print(entry.getKey() + ": ");
    //         for(NetlistTerm t : entry.getValue()) {
    //            System.out.print(t.getDrivee() + ", ");
    //         }
    //         System.out.println();
    //      }

    for (Set<NetlistTerm> terms : cluster.values()) {
        if (terms.size() == 1) {
            continue;
        }
        Set<Mapping> gms = new HashSet<>();
        for (NetlistTerm t : terms) {
            gms.addAll(matches.get(t));
        }
        SortedMap<Float, List<Set<Mapping>>> possibleResults = new TreeMap<>();
        for (Set<Mapping> x : Sets.powerSet(gms)) {
            Set<NetlistTerm> tmpterms = new HashSet<>(terms);
            float size = 0;
            boolean validSol = true;
            for (Mapping g : x) {
                for (NetlistTerm t : g.getTerms()) {
                    if (tmpterms.contains(t)) {
                        tmpterms.remove(t);
                    } else {
                        validSol = false;
                        break;
                    }
                }
                if (!validSol) {
                    break;
                }
                if (g instanceof GateMapping) {
                    size += ((GateMapping) g).getGate().getSize();
                } else if (g instanceof WireMapping) {
                    size += 0;
                } else {
                    validSol = false;
                    break;
                }
            }
            if (validSol && tmpterms.isEmpty()) {
                if (!possibleResults.containsKey(size)) {
                    possibleResults.put(size, new ArrayList<Set<Mapping>>());
                }
                possibleResults.get(size).add(x);
            }
        }

        //         System.out.println(terms);
        //         System.out.println(possibleResults);
        //         System.out.println("---");

        Set<Mapping> result = possibleResults.get(possibleResults.firstKey()).get(0);
        for (Mapping m : result) {
            if (m instanceof GateMapping) {
                GateMapping g = (GateMapping) m;
                if (BDDHelper.isBuffer(g.getGate().getExpression())) {
                    if (g.getMapping().values().size() != 1) {
                        logger.error("Buffer vars != 1");
                        return false;
                    }
                    NetlistVariable driver = g.getMapping().values().iterator().next();
                    if (driver == null) {
                        logger.error("Buffer driver null");
                        return false;
                    }
                    WireMapping nm = new WireMapping(driver, g.getDrivee(), netlist, g.getTerms());
                    netlist.replaceMapping(nm);
                    continue;
                }
                netlist.replaceMapping(g);
            }
        }
    }

    return true;
}

From source file:org.dishevelled.piccolo.venn.VennNode.java

/**
 * Create nodes.// w ww.jav a2  s. c om
 */
private void createNodes() {
    for (int i = 0, size = size(); i < size; i++) {
        PPath pathNode = new PPath.Double();
        pathNode.setPaint(PAINTS[i]);
        pathNode.setStroke(STROKE);
        pathNode.setStrokePaint(STROKE_PAINT);
        pathNodes.add(pathNode);

        labelTexts.add(DEFAULT_LABEL_TEXT[i]);

        PText label = new PText();
        labels.add(label);
    }

    // calculate the power set (note n > 30 will overflow int)
    Set<Set<Integer>> powerSet = Sets.powerSet(range(size()));
    for (Set<Integer> set : powerSet) {
        if (!set.isEmpty()) {
            ImmutableBitSet key = toImmutableBitSet(set);

            PArea areaNode = new PArea();
            areaNode.setPaint(AREA_PAINT);
            areaNode.setStroke(AREA_STROKE);
            areaNode.setStrokePaint(AREA_STROKE_PAINT);
            areaNodes.put(key, areaNode);

            PText sizeLabel = new PText();
            sizeLabels.put(key, sizeLabel);
        }
    }

    for (PText label : labels) {
        addChild(label);
    }
    for (PPath pathNode : pathNodes) {
        addChild(pathNode);
    }
    for (PText sizeLabel : sizeLabels.values()) {
        addChild(sizeLabel);
    }
    for (PArea areaNode : areaNodes.values()) {
        addChild(areaNode);
    }
}

From source file:se.uu.it.cs.recsys.ruleminer.impl.FPGrowthImpl.java

/**
 *
 * @param singlePrefixPath, ordered single prefix path from a FP Tree
 * @return pairs of (frequent pattern, its support); returns empty map if
 * input is null or empty/*from www  .  j a  v  a 2 s  .  c o m*/
 */
public static Map<Set<Integer>, Integer> getFrequentPatternFromSinglePrefixPath(List<Item> singlePrefixPath) {
    if (singlePrefixPath == null || singlePrefixPath.isEmpty()) {
        LOGGER.warn("Nonsence to give null or empty input. Do you agree?");
        return Collections.EMPTY_MAP;
    }

    Set<Item> itemSetFromPath = new HashSet<>(singlePrefixPath);

    Set<Set<Item>> powerSet = Sets.powerSet(itemSetFromPath);

    Map<Set<Integer>, Integer> r = new HashMap<>();

    Util.removeEmptySet(powerSet).forEach(itemSet -> {
        int localMinSupport = FPTreeUtil.getMinSupport(itemSet);

        r.put(itemSet.stream().map(item -> item.getId()).collect(Collectors.toSet()), localMinSupport);
    });

    return r;
}