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.eclipse.viatra.query.runtime.localsearch.planner.PConstraintInfoInferrer.java

private void createConstraintInfoConstantValue(List<PConstraintInfo> resultList, ConstantValue pConstraint) {
    // A ConstantValue constraint has a single variable, which is allowed to be unbound 
    // (extending through ConstantValue is considered a cheap operation)
    Set<PVariable> affectedVariables = pConstraint.getAffectedVariables();
    Set<Set<PVariable>> bindings = Sets.powerSet(affectedVariables);
    doCreateConstraintInfos(resultList, pConstraint, affectedVariables, bindings);
}

From source file:dk.dma.nogoservice.service.NoGoResponseMerger.java

/**
 * Calculate the number of ways areas can overlap.
 *
 * @param areas the calculated nogo areas
 * @return the combination of all possible overlaps, identified by the indexes
 *///from  w  w  w.ja va  2 s  .c o  m
private Set<Overlap> calculateOverlapCombinations(List<CalculatedNoGoArea> areas) {

    Set<Integer> indexes = IntStream.range(0, areas.size()).boxed().collect(Collectors.toSet());
    // PowerSet calculates combinations of all sizes, overlaps are combinations of size 2 or more
    Set<Set<Integer>> indexSets = Sets.powerSet(indexes).stream().filter(s -> s.size() > 1)
            .collect(Collectors.toSet());
    Set<Overlap> overlaps = new HashSet<>();
    for (Set<Integer> indexSet : indexSets) {
        Set<CalculatedNoGoArea> included = new HashSet<>();
        List<CalculatedNoGoArea> copy = new ArrayList<>(areas);
        List<CalculatedNoGoArea> toBeRemoved = new ArrayList<>();
        for (Integer index : indexSet) {
            CalculatedNoGoArea area = copy.get(index);
            toBeRemoved.add(area);
            included.add(area);
        }
        copy.removeAll(toBeRemoved);
        overlaps.add(new Overlap(included, copy));
    }
    return overlaps;
}

From source file:de.uni_potsdam.hpi.asg.logictool.srgraph.StateGraphComputer.java

private boolean checkCSC(Set<State> states2) {
    Map<BitSet, State> checkList = new THashMap<BitSet, State>();
    HashMap<BitSet, Set<State>> equallyEncodedStates = new HashMap<BitSet, Set<State>>();
    BitSet binRep = null;/*from w ww .ja v a2  s. c  om*/
    State otherState = null;
    Value v1 = null, v2 = null;
    boolean csc;
    Signal problematicSignal = null;
    for (State state : states2) {
        binRep = state.getBinaryRepresentationNormalised(sortedSignals);
        if (checkList.containsKey(binRep)) {
            otherState = checkList.get(binRep);
            csc = true;
            for (Entry<Signal, Value> entry2 : otherState.getStateValues().entrySet()) {
                if (entry2.getKey().isInternalOrOutput()) {
                    v1 = state.getStateValues().get(entry2.getKey());
                    v2 = entry2.getValue();
                    if (v1 != v2) {
                        csc = false;
                        problematicSignal = entry2.getKey();
                        break;
                    }
                }
            }
            if (csc) {
                if (!equallyEncodedStates.containsKey(binRep)) {
                    equallyEncodedStates.put(binRep, new HashSet<State>());
                }
                if (state.hashCode() == otherState.hashCode()) {
                    logger.fatal("Different state objects have same Hash");
                    System.exit(-1);
                }
                equallyEncodedStates.get(binRep).add(state);
                equallyEncodedStates.get(binRep).add(otherState);
            } else {
                logger.warn("STG has no CSC");
                logger.debug("States: " + state.getId() + " and " + otherState.getId() + ", Signal: "
                        + problematicSignal.getName());
                return false;
            }
        } else {
            checkList.put(binRep, state);
        }
    }

    //      System.out.println("Equally encoded states:");
    //      for(Entry<BitSet, Set<State>> e : equallyEncodedStates.entrySet()) {
    //         for(State s : e.getValue()) {
    //            System.out.print(s.getId() + ", ");
    //         }
    //         System.out.println();
    //      }

    //merge
    Transition t = null;
    State s1 = null, s2 = null;
    Iterator<State> it = null;
    boolean change = false;
    do {
        change = false;
        for (Entry<BitSet, Set<State>> entry : equallyEncodedStates.entrySet()) {
            for (Set<State> set : Sets.powerSet(entry.getValue())) {
                if (set.size() == 2) {
                    it = set.iterator();
                    s1 = it.next();
                    s2 = it.next();
                    //only merge if nextstates are the same
                    boolean merge = true;
                    for (Entry<Transition, State> nextentry : s2.getNextStates().entrySet()) {
                        State repnext = null;
                        for (Entry<Transition, State> repnextentry : s1.getNextStates().entrySet()) {
                            if (repnextentry.getKey().getSignal() == nextentry.getKey().getSignal()) {
                                repnext = repnextentry.getValue();
                            }
                        }
                        if (repnext == null || !repnext.equals(nextentry.getValue())) {
                            merge = false;
                            break;
                        }
                    }

                    if (merge) {
                        for (State prev : s2.getPrevStates()) {
                            t = null;
                            for (Entry<Transition, State> entry2 : prev.getNextStates().entrySet()) {
                                if (entry2.getValue() == s2) {
                                    t = entry2.getKey();
                                    break;
                                }
                            }
                            if (t == null) {
                                logger.error("Transition in map not found (Missing edge?)");
                                return false;
                            }
                            prev.addEdgeNextState(s1, t);
                        }
                        s2.getPrevStates().clear();
                        for (Entry<Transition, State> next : s2.getNextStates().entrySet()) {
                            if (!next.getValue().getPrevStates().contains(s1)) {
                                if (s1.getNextStates().containsKey(next.getKey())) {
                                    next.getValue().getPrevStates().remove(s2);
                                } else {
                                    s1.addEdgeNextState(next.getValue(), next.getKey());
                                }
                            }
                            next.getValue().getPrevStates().remove(s2);
                        }
                        states2.remove(s2);
                        entry.getValue().remove(s2);
                        change = true;
                        break;
                    }
                }
            }
        }
    } while (change);

    for (Entry<BitSet, Set<State>> e : equallyEncodedStates.entrySet()) {
        if (e.getValue().size() <= 1) {
            continue;
        }
        for (State s3 : e.getValue()) {
            for (State s4 : e.getValue()) {
                if (s3 != s4) {
                    s3.addEquallyEncodedState(s4);
                }
            }
        }
    }

    return true;
}

From source file:org.eclipse.viatra.query.runtime.localsearch.planner.PConstraintInfoInferrer.java

private void createConstraintInfoPositivePatternCall(List<PConstraintInfo> resultList,
        PositivePatternCall pCall) {//w  w w  .  j  a  v  a2s  .c om
    // A pattern call can have any of its variables unbound
    Set<PVariable> affectedVariables = pCall.getAffectedVariables();
    // IN parameters cannot be unbound and
    // OUT parameters cannot be bound
    Tuple variables = pCall.getVariablesTuple();
    final Set<PVariable> inVariables = new HashSet<>();
    Set<PVariable> inoutVariables = new HashSet<>();
    List<PParameter> parameters = pCall.getReferredQuery().getParameters();
    for (int i = 0; i < parameters.size(); i++) {
        switch (parameters.get(i).getDirection()) {
        case IN:
            inVariables.add((PVariable) variables.get(i));
            break;
        case INOUT:
            inoutVariables.add((PVariable) variables.get(i));
            break;
        case OUT:
        default:
            break;

        }
    }
    Iterable<Set<PVariable>> bindings = Sets.powerSet(inoutVariables).stream()
            .map(input -> Stream.concat(input.stream(), inVariables.stream()).collect(Collectors.toSet()))
            .collect(Collectors.toSet());

    doCreateConstraintInfos(resultList, pCall, affectedVariables, bindings);
}

From source file:org.deri.iris.queryrewriting.FORewriter.java

/**
 * Checks if the n atoms are sharing the same variables in all the existential positions
 * @param q a conjunctive query//  w w  w .j  a  v a  2  s .c  o m
 * @param r a TGD
 * @param a1 the first atom
 * @param a2 the second atom
 * @return true if they share the same variables in all the existential positions
 */
protected boolean factorisable(IRule q, final IRule r, final Map<IVariable, ITerm> sbstMap) {

    rep.incrementValue(RewMetric.FACTOR_COUNT);

    if (q.getBody().size() > 1) {
        // Get the atoms in body(q) that unify with head(r).

        final IAtom rheadAtom = r.getHead().iterator().next().getAtom();
        final Set<IPosition> headExPos = r.getExistentialPositions();

        final Set<IAtom> potentialUnifiableAtoms = new LinkedHashSet<IAtom>();
        for (final ILiteral l : q.getBody()) {
            final IAtom qbodyAtom = l.getAtom();

            if (qbodyAtom.getPredicate().equals(rheadAtom.getPredicate())) {
                potentialUnifiableAtoms.add(qbodyAtom);
            }
        }
        if (potentialUnifiableAtoms.size() < 2)
            return false;
        else {

            // compute the powerset of atoms that are potentially unifiable in the body in the query.
            final Set<Set<IAtom>> atomsPowSet = Sets.powerSet(potentialUnifiableAtoms);
            // sort the set by size
            final List<Set<IAtom>> sortedPowSet = Lists.newArrayList(atomsPowSet);
            Collections.sort(sortedPowSet, new SetSizeComparator());

            for (final Set<IAtom> candidateSet : sortedPowSet) {
                // check that we have at least two atoms in the candidate set.
                if (candidateSet.size() > 1) {
                    final Map<IVariable, ITerm> unifier = new HashMap<IVariable, ITerm>();
                    if (TermMatchingAndSubstitution.unify(candidateSet, unifier)) {
                        // the atoms have a unifier, check that there is a well-behaved existential variable

                        // get variables in existential positions
                        final Set<IVariable> variables = getVariablesInPositions(candidateSet, headExPos);
                        for (final IVariable var : variables) {
                            // check that the variable does not occur in non-existential positions
                            if (headExPos.containsAll(q.getPositions(var))
                                    && containedInAllAtoms(var, candidateSet)) {
                                q = RewritingUtils.factoriseQuery(q, unifier);
                                return true;
                            }
                        }

                    }
                }
            }

            return false;
        }
    } else
        return false;
}

From source file:org.dllearner.algorithms.qtl.experiments.NegativeExampleSPARQLQueryGenerator.java

private List<Query> generateQueriesByRemoval(Query query) {
    List<Query> queries = new ArrayList<>();

    // extract paths
    Node source = query.getProjectVars().get(0).asNode();
    Set<List<Triple>> paths = getPaths(new ArrayList<>(), query, source);

    // for each path create query which excludes the path by FILTER NOT EXISTS
    Set<Set<List<Triple>>> pathSubsets = Sets.powerSet(paths);

    for (Set<List<Triple>> pathSubset : pathSubsets) {
        if (!pathSubset.isEmpty() && pathSubset.size() < paths.size()) {

            ElementGroup eg = new ElementGroup();

            // keep other paths
            ElementTriplesBlock existsBlock = new ElementTriplesBlock();
            eg.addElement(existsBlock);/*from ww w. j a  v a 2 s.com*/
            SetView<List<Triple>> difference = Sets.difference(paths, pathSubset);
            for (List<Triple> otherPath : difference) {
                for (Triple tp : otherPath) {
                    existsBlock.addTriple(tp);
                }
            }

            // not exists current path
            ElementTriplesBlock notExistsBlock = new ElementTriplesBlock();
            for (List<Triple> path : pathSubset) {
                for (Triple tp : path) {
                    notExistsBlock.addTriple(tp);
                }
            }
            ElementGroup notExistsGroup = new ElementGroup();
            notExistsGroup.addElement(notExistsBlock);
            eg.addElementFilter(getNotExistsFilter(notExistsGroup));

            Query newQuery = QueryFactory.create();
            newQuery.setQuerySelectType();
            newQuery.setQueryPattern(eg);
            newQuery.addProjectVars(query.getProjectVars());
            newQuery.setDistinct(true);
            queries.add(newQuery);
        }
    }

    return queries;
}

From source file:com.eucalyptus.cluster.callback.reporting.AbsoluteMetricQueue.java

private static List<AbsoluteMetricQueueItem> foldMetrics(List<AbsoluteMetricQueueItem> dataBatch) {
    final List<AbsoluteMetricQueueItem> foldedMetrics = Lists.newArrayList();
    if (dataBatch != null) {
        for (AbsoluteMetricQueueItem queueItem : dataBatch) {
            // keep the same metric data unless the namespace is AWS/EC2.  In that case points will exist with dimensions
            // instance-id, image-id, instance-type, and (optionally) autoscaling group name.  These points have 4
            // dimensions, and we are really only supposed to have one dimension (or zero) for aggregation purposes.
            if (queueItem != null && queueItem.getNamespace() != null
                    && "AWS/EC2".equals(queueItem.getNamespace())) {
                MetricDatum metricDatum = queueItem.getMetricDatum();
                if (metricDatum != null && metricDatum.getDimensions() != null
                        && metricDatum.getDimensions().getMember() != null) {
                    Set<Dimension> dimensionSet = Sets
                            .newLinkedHashSet(metricDatum.getDimensions().getMember());
                    for (Set<Dimension> permutation : Sets.powerSet(dimensionSet)) {
                        if (permutation.size() > 1)
                            continue;
                        MetricDatum newMetricDatum = new MetricDatum();
                        newMetricDatum.setValue(metricDatum.getValue());
                        newMetricDatum.setUnit(metricDatum.getUnit());
                        newMetricDatum.setStatisticValues(metricDatum.getStatisticValues());
                        newMetricDatum.setTimestamp(metricDatum.getTimestamp());
                        newMetricDatum.setMetricName(metricDatum.getMetricName());
                        ArrayList<Dimension> newDimensionsList = Lists.newArrayList(permutation);
                        Dimensions newDimensions = new Dimensions();
                        newDimensions.setMember(newDimensionsList);
                        newMetricDatum.setDimensions(newDimensions);
                        AbsoluteMetricQueueItem newQueueItem = new AbsoluteMetricQueueItem();
                        newQueueItem.setAccountId(queueItem.getAccountId());
                        newQueueItem.setNamespace(queueItem.getNamespace());
                        newQueueItem.setMetricDatum(newMetricDatum);
                        foldedMetrics.add(newQueueItem);
                    }//from  www .  j a v a  2  s . com
                } else {
                    foldedMetrics.add(queueItem);
                }
            } else {
                foldedMetrics.add(queueItem);
            }
        }
    }
    return foldedMetrics;
}

From source file:edu.oregonstate.eecs.mcplan.abstraction.WekaUtil.java

public static Instances powerSet(final Instances D, final int n) {
    final Attribute class_attr = D.classAttribute();

    final ImmutableSet.Builder<Integer> b = new ImmutableSet.Builder<Integer>();
    final int Nattr = class_attr != null ? D.numAttributes() - 1 : D.numAttributes();
    for (final int i : Fn.range(1, Nattr)) {
        b.add(i);//w w  w  .  j a v a2 s  .co m
    }
    final Set<Set<Integer>> index = Sets.powerSet(b.build());

    final ArrayList<Attribute> attributes = new ArrayList<Attribute>();
    for (final Set<Integer> subset : index) {
        if (subset.isEmpty() || subset.size() > n) {
            continue;
        }

        final StringBuilder attr_name = new StringBuilder();
        int count = 0;
        for (final Integer i : subset) {
            if (count++ > 0) {
                attr_name.append("_x_");
            }
            attr_name.append(D.attribute(i).name());
        }

        attributes.add(new Attribute(attr_name.toString()));
    }
    if (class_attr != null) {
        assert (class_attr.isNominal());
        attributes.add(WekaUtil.createNominalAttribute(class_attr.name(), class_attr.numValues()));
    }

    final String Pname = "P" + n + "_" + D.relationName();
    final Instances P = new Instances(Pname, attributes, 0);
    if (class_attr != null) {
        P.setClassIndex(attributes.size() - 1);
    }

    for (final Instance inst : D) {
        final double[] xp = new double[attributes.size()];
        int idx = 0;
        for (final Set<Integer> subset : index) {
            if (subset.isEmpty() || subset.size() > n) {
                continue;
            }

            double p = 1.0;
            for (final Integer i : subset) {
                p *= inst.value(i);
            }
            xp[idx++] = p;
        }
        if (class_attr != null) {
            xp[idx++] = inst.classValue();
        }

        WekaUtil.addInstance(P, new DenseInstance(inst.weight(), xp));
    }

    return P;
}

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

private void compileAllShaderPermutations() {
    compileShaders(Collections.<ShaderProgramFeature>emptySet());

    int counter = 1;

    for (Set<ShaderProgramFeature> permutation : Sets.powerSet(availableFeatures)) {
        compileShaders(permutation);/*from   ww w. ja v a 2 s .  c  o  m*/
        counter++;
    }
    logger.debug("Compiled {} permutations for {}.", counter, getURI());
}

From source file:org.eclipse.viatra.query.runtime.localsearch.planner.PConstraintInfoInferrer.java

/**
 * /*from  w  w w. ja v  a2  s  .c om*/
 * @param canBeUnboundVariables Variables which are allowed to be unbound
 * @param affectedVariables All affected variables
 * @return The set of possible bound variable sets
 */
private Set<Set<PVariable>> calculatePossibleBindings(Set<PVariable> canBeUnboundVariables,
        Set<PVariable> affectedVariables) {
    final Set<PVariable> mustBindVariables = affectedVariables.stream()
            .filter(input -> !canBeUnboundVariables.contains(input)).collect(Collectors.toSet());
    return Sets.powerSet(canBeUnboundVariables).stream().map(input -> {
        //some variables have to be bound before executing this constraint
        Set<PVariable> result = new HashSet<>(input);
        result.addAll(mustBindVariables);
        return result;
    }).collect(Collectors.toSet());
}