Example usage for org.apache.commons.collections4.iterators PermutationIterator PermutationIterator

List of usage examples for org.apache.commons.collections4.iterators PermutationIterator PermutationIterator

Introduction

In this page you can find the example usage for org.apache.commons.collections4.iterators PermutationIterator PermutationIterator.

Prototype

public PermutationIterator(final Collection<? extends E> coll) 

Source Link

Document

Standard constructor for this class.

Usage

From source file:me.aatma.languagetologic.CleanAndCombineGraphTest.java

@Test
public void testListPermutation() {
    List<Integer> li = Arrays.asList(1, 2, 3);
    PermutationIterator<Integer> pi = new PermutationIterator<Integer>(li);

    int i = 0;/*from  www  .j av a2 s  .co  m*/
    while (pi.hasNext()) {
        List<Integer> li2 = pi.next();
        System.out.println("Iteration: " + i + " List: " + li2);
        i++;
    }

}

From source file:de.richtercloud.validation.tools.ValidationToolsTest.java

@Property
public void testBuildConstraintVioloationMessage(@ForAll boolean bean2Null, @ForAll int bean2Property0,
        @ForAll boolean bean1Null, @ForAll boolean bean1Bean2sNull, @ForAll boolean bean1bean2sEmpty,
        @ForAll @WithNull(0.5) String bean0Property0, @ForAll boolean bean0Valid, @ForAll boolean bean2Valid)
        throws Exception {
    LOGGER.info("testBuildConstraintVioloationMessage");
    LOGGER.trace("testBuildConstraintVioloationMessage bean2Null: {}", bean2Null);
    LOGGER.trace("testBuildConstraintVioloationMessage bean2Property0: {}", bean2Property0);
    LOGGER.trace("testBuildConstraintVioloationMessage bean1Null: {}", bean1Null);
    LOGGER.trace("testBuildConstraintVioloationMessage bean1Bean2sNull: {}", bean1Bean2sNull);
    LOGGER.trace("testBuildConstraintVioloationMessage bean1bean2sEmpty: {}", bean1bean2sEmpty);
    LOGGER.trace("testBuildConstraintVioloationMessage bean0Property0: {}", bean0Property0);
    LOGGER.trace("testBuildConstraintVioloationMessage bean0Valid: {}", bean0Valid);
    LOGGER.trace("testBuildConstraintVioloationMessage bean2Valid: {}", bean2Valid);
    Bean0Validator.retValue = bean0Valid;
    Bean2Validator.retValue = bean2Valid;
    Bean2 bean2;//  w  w w.jav  a2 s.c  o m
    if (bean2Null) {
        bean2 = null;
    } else {
        bean2 = new Bean2(bean2Property0);
    }
    Bean1 bean1;
    if (bean1Null) {
        bean1 = null;
    } else {
        List<Bean2> bean1Bean2s;
        if (bean1Bean2sNull) {
            bean1Bean2s = null;
        } else {
            //Bean1.bean2s has @Min(1)
            bean1Bean2s = new ArrayList<>();
            if (!bean1bean2sEmpty) {
                bean1Bean2s.add(bean2);
            }
        }
        bean1 = new Bean1(bean1Bean2s);
    }
    Bean0 bean0 = new Bean0(bean1, bean0Property0);
    Set<ConstraintViolation<Object>> violations = Validation.buildDefaultValidatorFactory().getValidator()
            .validate(bean0);
    FieldRetriever fieldRetriever = new CachedFieldRetriever();
    FieldNameLambda fieldNameLambda = field -> "+++" + field.getName() + ",,,";
    Map<Path, String> pathDescriptionMap = new HashMap<>();
    OutputMode outputMode = OutputMode.PLAIN_TEXT;
    LOGGER.debug("validations.size: {}", violations.size());
    if (violations.isEmpty()) {
        Assertions.assertThrows(IllegalArgumentException.class,
                () -> ValidationTools.buildConstraintVioloationMessage(violations, bean0, fieldRetriever,
                        pathDescriptionMap, fieldNameLambda, false, //skipPathes
                        outputMode));
        return;
    }
    Set<String> messages = new HashSet<>();
    if (!bean0Valid) {
        messages.add("invalid Bean0");
    }
    if (bean0Property0 == null) {
        messages.add("+++property0,,,: darf nicht null sein");
    }
    if (bean1Null) {
        messages.add("+++bean1,,,: darf nicht null sein");
    } else {
        if (!bean1Bean2sNull) {
            //bean1bean2sNull is valid
            if (!bean1bean2sEmpty) {
                if (!bean2Null) {
                    if (!bean2Valid) {
                        messages.add("+++bean1,,,: +++bean2s,,,: invalid Bean2");
                    }
                    if (bean2Property0 < 1) {
                        messages.add(
                                "+++bean1,,,: +++bean2s,,,: +++property0,,,: muss grer oder gleich 1 sein");
                    }
                }
            } else {
                messages.add("+++bean1,,,: +++bean2s,,,: Bean1.bean2s mustn't be empty");
            }
        }
    }
    Set<List<String>> permutations = new HashSet<>();
    PermutationIterator<String> textsPermutationIterator = new PermutationIterator<>(messages);
    textsPermutationIterator.forEachRemaining(permutation -> permutations.add(permutation));
    Matcher<String> expResult = anyOf(permutations.stream()
            .map(permutation -> equalTo(
                    StreamEx.of(permutation).joining("\n", "The following constraints are violated:\n",
                            "\nFix the corresponding values in the components.")))
            .collect(Collectors.toSet()));
    String result = ValidationTools.buildConstraintVioloationMessage(violations, bean0, fieldRetriever,
            pathDescriptionMap, fieldNameLambda, false, //skipPathes
            outputMode);
    assertTrue(String.format("result was: %s; expResult was: %s", result, expResult),
            expResult.matches(result));
}

From source file:com.act.biointerpretation.Utils.ReactionProjector.java

/**
 * This function takes as input an array of molecules and a Reactor and outputs the products of the transformation.
 * The results are returned as a map from orderings of the substrates to the products produced by those orderings.
 * In most cases the map will have only one entry, but in some cases different orderings of substrates can lead to
 * different valid predictions.//from   w  w w  .  j  a  v a  2  s . c  o  m
 * <p>
 * Note that, for efficient two substrate expansion, the specialized method
 * fastProjectionOfTwoSubstrateRoOntoTwoMolecules should be used instead of this one.
 *
 * @param mols    An array of molecules representing the chemical reactants.
 * @param reactor A Reactor representing the reaction to apply.
 * @param maxProducts The maximum number of products to compute before exiting.  No limit is imposed for max values
 *                    of null or 0.
 * @return The substrate -> product map.
 */
public Map<Molecule[], List<Molecule[]>> getRoProjectionMap(Molecule[] mols, Reactor reactor,
        Integer maxProducts) throws ReactionException, IOException {

    Map<Molecule[], List<Molecule[]>> resultsMap = new HashMap<>();

    if (mols.length != reactor.getReactantCount()) {
        LOGGER.debug("Tried to project RO with %d substrates on set of %d substrates",
                reactor.getReactantCount(), mols.length);
        return resultsMap;
    }

    // If there is only one reactant, we can do just a simple reaction computation. However, if we have multiple reactants,
    // we have to use the ConcurrentReactorProcessor API since it gives us the ability to combinatorially explore all
    // possible matching combinations of reactants on the substrates of the RO.
    if (mols.length == 1) {
        List<Molecule[]> productSets = getProductsFixedOrder(reactor, mols, maxProducts);
        if (!productSets.isEmpty()) {
            resultsMap.put(mols, productSets);
        }
    } else if (useSubstructureFiltering) {
        Optional<List<Set<Integer>>> viableSubstrateIndexes;
        try {
            viableSubstrateIndexes = matchCandidatesToSubstrateStructures(reactor, mols);
        } catch (SearchException e) {
            throw new ReactionException("Caught exception when performing pre-reaction substructure search", e);
        }

        if (viableSubstrateIndexes.isPresent()) {
            List<Integer> allIndexes = new ArrayList<Integer>(mols.length) {
                {
                    for (int i = 0; i < mols.length; i++) {
                        add(i);
                    }
                }
            };

            int permutationIndex = 0;
            PermutationIterator<Integer> iter = new PermutationIterator<>(allIndexes);
            while (iter.hasNext()) {
                permutationIndex++;
                List<Integer> permutation = iter.next();
                if (permutationFitsSubstructureMatches(permutation, viableSubstrateIndexes.get())) {
                    Molecule[] substrates = indexPermutationToMolecules(mols, permutation);
                    reactor.setReactants(substrates);
                    Molecule[] products;
                    List<Molecule[]> results = new ArrayList<>();
                    while ((products = reactor.react()) != null) {
                        results.add(products);
                        if (maxProducts != null && maxProducts > 0 && results.size() >= maxProducts) {
                            break;
                        }
                    }
                    if (results.size() > 0) {
                        resultsMap.put(substrates, results);
                    }
                }
            }
        } // Otherwise just return the empty map.
    } else {
        // TODO: why not make one of these per ReactionProjector object?
        // TODO: replace this with Apache commons PermutationIterator for clean iteration over distinct permutations.
        ConcurrentReactorProcessor reactorProcessor = new ConcurrentReactorProcessor();
        reactorProcessor.setReactor(reactor);

        // This step is needed by ConcurrentReactorProcessor for the combinatorial exploration.
        // The iterator takes in the same substrates in each iteration step to build a matrix of combinations.
        // For example, if we have A + B -> C, the iterator creates this array: [[A,B], [A,B]]. Based on this,
        // ConcurrentReactorProcessor will cross the elements in the first index with the second, creating the combinations
        // A+A, A+B, B+A, B+B and operates all of those on the RO, which is what is desired.
        MoleculeIterator[] iterator = new MoleculeIterator[mols.length];
        for (int i = 0; i < mols.length; i++) {
            iterator[i] = MoleculeIteratorFactory.createMoleculeIterator(mols);
        }

        reactorProcessor.setReactantIterators(iterator, ConcurrentReactorProcessor.MODE_COMBINATORIAL);

        // Bag is a multi-set class that ships with Apache commons collection, and we already use many commons libs--easy!
        Bag<Molecule> originalReactantsSet = new HashBag<>(Arrays.asList(mols));

        // This set keeps track of substrate combinations we've used, and avoids repeats.  Repeats can occur
        // when several substrates are identical, and can be put in "different" but symmetric orderings.
        Set<String> substrateHashes = new HashSet<>();

        List<Molecule[]> results = null;
        int reactantCombination = 0;
        while ((results = reactorProcessor.reactNext()) != null) {
            reactantCombination++;
            Molecule[] reactants = reactorProcessor.getReactants();

            if (results.isEmpty()) {
                LOGGER.debug("No results found for reactants combination %d, skipping", reactantCombination);
                continue;
            }

            Bag<Molecule> thisReactantSet = new HashBag<>(Arrays.asList(reactants));
            if (!originalReactantsSet.equals(thisReactantSet)) {
                LOGGER.debug("Reactant set %d does not represent original, complete reactant sets, skipping",
                        reactantCombination);
                continue;
            }

            String thisHash = getStringHash(reactants);
            if (substrateHashes.contains(thisHash)) {
                continue;
            }

            substrateHashes.add(thisHash);
            resultsMap.put(reactants, results);
            if (maxProducts != null && maxProducts > 0 && resultsMap.size() >= maxProducts) {
                break;
            }
        }
    }
    return resultsMap;
}

From source file:org.nmrfx.processor.gui.RefManager.java

void setupItems(int dim) {
    ChartProcessor chartProcessor = processorController.chartProcessor;
    NMRData nmrData = getNMRData();/*from www.  ja  va2  s . co m*/
    ObservableList<PropertySheet.Item> newItems = FXCollections.observableArrayList();
    String dimName = "" + (dim + 1);
    if (dim == 0) {
        newItems.add(new TextOperationItem(stringListener, chartProcessor.getDatasetName(), dimName, "dataset",
                "Enter the name of the dataset"));
        ArrayList<String> extensionChoices = new ArrayList<>();
        extensionChoices.add(".nv");
        extensionChoices.add(".ucsf");
        newItems.add(new ChoiceOperationItem(stringListener, chartProcessor.getExtension(), extensionChoices,
                dimName, "extension", "Filename extension (determines dataset type)"));
        if (nmrData != null) {
            ArrayList<String> choices = new ArrayList<>();
            if (nmrData.getNDim() > 1) {
                ArrayList<Integer> dimList = new ArrayList<>();
                for (int i = 1; i <= (nmrData.getNDim() - 1); i++) {
                    dimList.add(i);
                }
                PermutationIterator permIter = new PermutationIterator(dimList);
                StringBuilder sBuilder = new StringBuilder();
                while (permIter.hasNext()) {
                    ArrayList<Integer> permDims = (ArrayList<Integer>) permIter.next();
                    sBuilder.setLength(0);
                    if (nmrData.getVendor().equals("bruker")) {
                        sBuilder.append(nmrData.getNDim());
                    }
                    for (Integer iVal : permDims) {
                        sBuilder.append(iVal);
                    }
                    choices.add(sBuilder.toString());
                }
                newItems.add(new EditableChoiceOperationItem(stringListener, chartProcessor.getAcqOrder(),
                        choices, dimName, "acqOrder", "Enter the acquisiton order of the dataset"));
            }
        } else {
            newItems.add(new TextOperationItem(stringListener, chartProcessor.getAcqOrder(), dimName,
                    "acqOrder", "Enter the acquisiton order of the dataset"));
        }
        if ((nmrData != null) && nmrData.getVendor().equals("bruker")) {
            newItems.add(new BooleanOperationItem(boolListener, chartProcessor.getFixDSP(), dimName, "fixdsp",
                    "Fix DSP buildup before FT"));
        }
    }
    //newItems.add(new IntRangeOperationItem(intListener, 3, 0, 5, "op", "opname", "opDesc"));
    for (String propName : propNames) {
        if (propName.equals("skip")) {
            if (dim > 0) {
                String value = getPropValue(dim, propName, false);
                boolean boolValue = false;
                if (value.equals("1")) {
                    boolValue = true;
                }
                newItems.add(new BooleanOperationItem(boolListener, boolValue, dimName, propName,
                        "Skip this dimension?"));
            }
        } else if (propName.equals("ref")) {
            String value = getPropValue(dim, propName, false);
            String defaultValue = getPropValue(dim, propName, true);
            if (nmrData != null) {
                if (dim == 0) {
                    defaultValue = nmrData.getRef(0) + "";
                }
            }
            String comment = " (default is " + defaultValue + ")";
            newItems.add(new MenuTextOperationItem(stringListener, value, dimName, propName,
                    "Select the " + propName + comment));
        } else if (propName.contains("size")) {
            String value = getPropValue(dim, propName, false);
            int iValue = 0;
            try {
                iValue = Integer.parseInt(value);
            } catch (NumberFormatException nFe) {

            }
            String defaultValue = getPropValue(dim, propName, true);
            String comment = " (default is " + defaultValue + ")";
            newItems.add(new IntOperationItem(intListener, iValue, 0, 1000000, dimName, propName,
                    "Enter the " + propName + comment));
        } else if (propName.equals("acqarray")) {
            int arraySize = 0;
            if (nmrData != null) {
                arraySize = nmrData.getArraySize(dim);
            }
            String comment = " (default is " + 0 + ")";
            newItems.add(new IntOperationItem(intListener, arraySize, 0, 1000000, dimName, propName,
                    "Enter the " + propName + comment));
        } else {
            String value = getPropValue(dim, propName, false);
            String defaultValue = getPropValue(dim, propName, true);
            String comment = " (default is " + defaultValue + ")";
            newItems.add(new TextOperationItem(stringListener, value, dimName, propName,
                    "Enter the " + propName + comment));
        }
    }
    refSheet.getItems().setAll(newItems);
}