Example usage for com.google.common.collect BiMap put

List of usage examples for com.google.common.collect BiMap put

Introduction

In this page you can find the example usage for com.google.common.collect BiMap put.

Prototype

@Override
@Nullable
V put(@Nullable K key, @Nullable V value);

Source Link

Usage

From source file:edu.rit.flick.genetics.ByteConverterBiMapFactory.java

/**
 *
 * @param permutation// ww  w .  j av  a  2 s.  c o m
 * @param permutationId
 * @param permutationLength
 * @param byteConverter
 */
void fillConverterMap(final String permutation, final AtomicInteger permutationId, final int permutationLength,
        final BiMap<String, Byte> byteConverter) {
    if (permutation.length() >= permutationLength)
        return;

    // nucleotideIndex
    for (final char element : NUCLEOTIDES) {
        byteConverter.put(permutation + element, (byte) permutationId.getAndAdd(0x0000_0001));

        fillConverterMap(permutation + element, permutationId, permutationLength, byteConverter);
    }
}

From source file:de.xaniox.heavyspleef.addon.java.SharedClassContext.java

public void registerClass(AddOn addOn, Class<?> clazz) {
    BiMap<String, Class<?>> classMap = classes.get(addOn);
    if (classMap == null) {
        //Lazy initialization here
        classMap = HashBiMap.create();// ww w . j a  va 2  s.  co  m
        classes.put(addOn, classMap);
    }

    classMap.put(clazz.getName(), clazz);
}

From source file:mtsar.processors.answer.KOSAggregator.java

@Override
@Nonnull//from w  ww.j  av  a  2s.c o  m
public Map<Integer, AnswerAggregation> aggregate(@Nonnull Collection<Task> tasks) {
    requireNonNull(stage, "the stage provider should not provide null");
    checkArgument(tasks.stream().allMatch(SINGLE_BINARY_TYPE),
            "tasks should be of the type single and have only two possible answers");
    if (tasks.isEmpty())
        return Collections.emptyMap();

    final List<Answer> answers = answerDAO.listForStage(stage.getId());
    if (answers.isEmpty())
        return Collections.emptyMap();

    final Map<Integer, Task> taskMap = taskDAO.listForStage(stage.getId()).stream().filter(SINGLE_BINARY_TYPE)
            .collect(Collectors.toMap(Task::getId, Function.identity()));

    final Map<Integer, BiMap<String, Short>> answerIndex = taskMap.values().stream()
            .collect(Collectors.toMap(Task::getId, task -> {
                final BiMap<String, Short> map = HashBiMap.create(2);
                map.put(task.getAnswers().get(0), (short) -1);
                map.put(task.getAnswers().get(1), (short) +1);
                return map;
            }));

    /* rows are tasks IDs, columns are worker IDs, values are answers */
    final Table<Integer, Integer, Short> graph = HashBasedTable.create();

    for (final Answer answer : answers) {
        if (!answer.getType().equalsIgnoreCase(AnswerDAO.ANSWER_TYPE_ANSWER))
            continue;
        graph.put(answer.getTaskId(), answer.getWorkerId(),
                answerIndex.get(answer.getTaskId()).get(answer.getAnswers().get(0)));
    }

    final Map<Integer, Double> estimations = converge(graph, getKMax());
    return estimations.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, estimation -> {
        final String answer = answerIndex.get(estimation.getKey()).inverse()
                .get(estimation.getValue() < 0 ? (short) -1 : (short) +1);
        return new AnswerAggregation.Builder().setTask(taskMap.get(estimation.getKey())).addAnswers(answer)
                .build();
    }));
}

From source file:org.carrot2.workbench.editors.impl.ImplementingClassesEditor.java

@Override
protected AttributeEditorInfo init(Map<String, Object> defaultValues) {
    for (Annotation ann : descriptor.constraints) {
        if (ann instanceof ImplementingClasses) {
            constraint = (ImplementingClasses) ann;
        }/*from   w ww.  j  a  v  a  2 s  .  com*/
    }

    if (constraint == null) {
        throw new RuntimeException("Missing constraint: " + ImplementingClasses.class);
    }

    valueRequired = (descriptor.getAnnotation(Required.class) != null);

    final BiMap<Object, String> valueToName = HashBiMap.create();
    final List<Object> valueOrder = Lists.newArrayList();
    for (Class<?> clazz : constraint.classes()) {
        valueOrder.add(clazz);
        valueToName.put(clazz, StringUtils.splitCamelCase(ClassUtils.getShortClassName(clazz)));
    }
    setMappedValues(valueToName, valueOrder);

    return new AttributeEditorInfo(1, false);
}

From source file:uk.ac.ebi.mdk.apps.tool.SuggestExchangeMetabolites.java

@Override
public void process() {

    System.out.print("Reading reconstructions...");
    Reconstruction input = read(getFile("input"));
    Reconstruction reference = read(getFile("reference"));
    System.out.println("done");

    // find compounds which are exchange in the 'reference' and list
    // - those which are exchanged and present the input
    // - those which are terminal in the input
    Multimap<Metabolite, MetabolicReaction> exchanged = exchanged(reference);
    Multimap<Long, Metabolite> index = index(exchanged.keySet());

    BiMap<UUID, Integer> metaboliteIdx = HashBiMap.create(input.metabolome().size());
    int i = 0;//from   w w  w .  j  a  va  2s  .  c o m
    for (Metabolite m : input.metabolome())
        metaboliteIdx.put(m.uuid(), i++);
    int[] occurences = new int[input.metabolome().size()];

    for (MetabolicReaction rxn : input.reactome()) {
        for (MetabolicParticipant p : rxn.getParticipants()) {
            occurences[metaboliteIdx.get(p.getMolecule().uuid())]++;
        }
    }

    CSVWriter csv = new CSVWriter(new OutputStreamWriter(System.out), ',', '"');

    for (final Metabolite metabolite : input.metabolome()) {
        for (ChemicalStructure structure : metabolite.getStructures()) {
            long hashCode = generator.generate(structure.getStructure());
            if (index.containsKey(hashCode)) {
                for (Metabolite refMetabolite : index.get(hashCode)) {
                    for (MetabolicReaction rxn : exchanged.get(refMetabolite)) {
                        csv.writeNext(new String[] { metabolite.toString(),
                                Integer.toString(occurences[metaboliteIdx.get(metabolite.uuid())]),
                                rxn.toString() });

                    }
                }
            }
        }
    }

    try {
        csv.flush();
        csv.close();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.addthis.codec.jackson.CodecTypeIdResolver.java

public CodecTypeIdResolver(PluginMap pluginMap, JavaType baseType, TypeFactory typeFactory,
        Collection<NamedType> subtypes, PluginRegistry pluginRegistry) {
    super(baseType, typeFactory);
    this.pluginRegistry = pluginRegistry;
    if (!subtypes.isEmpty()) {
        BiMap<String, Class<?>> mutableExtraSubTypes = HashBiMap.create(subtypes.size());
        for (NamedType namedType : subtypes) {
            if (namedType.hasName()) {
                mutableExtraSubTypes.put(namedType.getName(), namedType.getType());
            }// w  w  w  .j a  v a 2s .c  o  m
        }
        this.extraSubTypes = Maps.unmodifiableBiMap(mutableExtraSubTypes);
    } else {
        this.extraSubTypes = ImmutableBiMap.of();
    }
    this.pluginMap = pluginMap;
}

From source file:additionalpipes.utils.FrequencyMap.java

@SuppressWarnings("unchecked")
public void readFromNBT(NBTTagCompound nbt) {
    for (NBTTagCompound usernameNBT : (Collection<NBTTagCompound>) nbt.getTags()) {
        BiMap<Integer, String> freqMap = HashBiMap.create();
        for (NBTTagInt freqNBT : (Collection<NBTTagInt>) usernameNBT.getTags()) {
            freqMap.put(freqNBT.data, freqNBT.getName());
        }/*from  w  w w .  j a  v  a 2  s  . co m*/
        userMap.put(usernameNBT.getName(), freqMap);
    }
}

From source file:net.automatalib.serialization.etf.writer.Mealy2ETFWriterAlternating.java

private <S, T> void writeETFInternal(PrintWriter pw, MealyMachine<S, I, T, O> mealy, Alphabet<I> inputs) {

    // create a bi-mapping from states to integers
    final BiMap<S, Integer> oldStates = HashBiMap.create();
    mealy.getStates().forEach(s -> oldStates.put(s, oldStates.size()));

    // write the initial state, using the bi-map
    pw.println("begin init");
    pw.printf("%d%n", oldStates.get(mealy.getInitialState()));
    pw.println("end init");

    // create a bi-map for transitions containing output
    final BiMap<Pair<O, S>, Integer> outputTransitions = HashBiMap.create();

    // create a bi-map that maps output to integers
    final BiMap<O, Integer> outputIndices = HashBiMap.create();

    /*/*from ww w.j  a v a 2  s .c  o  m*/
     Write the transitions (here is where the horror begins).
     The key to writing transitions with alternating semantics is that one have of see if appropriate
     intermediate states, and output transitions have already been created. If this is the case, that state, and
     output transitions has to be reused.
     */
    pw.println("begin trans");
    for (S s : mealy.getStates()) {
        for (I i : inputs) {
            T t = mealy.getTransition(s, i);
            if (t != null) {
                final S n = mealy.getSuccessor(t);
                final O o = mealy.getTransitionOutput(t);

                // construct a triple that serves as a key in the outputTransitions bi-map
                final Pair<O, S> outputTransition = Pair.of(o, n);

                // compute the integer value of the intermediate state (this may be a new state)
                final Integer intermediateState = outputTransitions.computeIfAbsent(outputTransition, ii -> {

                    // the output may also be a new letter in the alphabet.
                    final Integer outputIndex = outputIndices.computeIfAbsent(o,
                            iii -> inputs.size() + outputIndices.size());

                    /*
                    Write the output transition. Note that this will only be done if the output
                    transition was not written before.
                    */
                    final Integer res = oldStates.size() + outputTransitions.size();
                    pw.printf("%d/%d %d%n", res, oldStates.get(n), outputIndex);
                    return res;
                });

                // always write the input transition to the output transition
                pw.printf("%d/%d %d%n", oldStates.get(s), intermediateState, inputs.getSymbolIndex(i));
            }
        }
    }
    pw.println("end trans");

    // write all state ids, including the newly created intermediate states
    pw.println("begin sort id");
    for (int i = 0; i < oldStates.size(); i++) {
        pw.printf("\"%s\"%n", oldStates.inverse().get(i));
    }

    final Map<Integer, Pair<O, S>> inverseTransitions = outputTransitions.inverse();
    for (int i = 0; i < outputTransitions.size(); i++) {
        final Pair<O, S> t = inverseTransitions.get(oldStates.size() + i);
        pw.printf("\"(%s,%s)\"%n", t.getFirst(), t.getSecond());
    }
    pw.println("end sort");

    // write all the letters in the new alphabet
    pw.println("begin sort letter");
    inputs.forEach(i -> pw.printf("\"%s\"%n", i));
    for (int i = 0; i < outputIndices.size(); i++) {
        pw.printf("\"%s\"%n", outputIndices.inverse().get(inputs.size() + i));
    }
    pw.println("end sort");
}

From source file:cuchaz.enigma.convert.ClassMatching.java

public BiMap<ClassEntry, ClassEntry> uniqueMatches() {
    BiMap<ClassEntry, ClassEntry> uniqueMatches = HashBiMap.create();
    for (ClassMatch match : matches()) {
        if (match.isMatched() && !match.isAmbiguous()) {
            uniqueMatches.put(match.getUniqueSource(), match.getUniqueDest());
        }//from  ww  w  .j a  va  2 s.  c  om
    }
    return uniqueMatches;
}

From source file:edu.rit.flick.genetics.ByteConverterBiMapFactory.java

/**
 *
 * @param permutation//from   w w  w .j a  v a2 s  .  c o m
 * @param permutationId
 * @param permutationLength
 * @param byteConverter
 */
void fillConverterMapFullSize(final String permutation, final AtomicInteger permutationId,
        final int permutationLength, final BiMap<String, Byte> byteConverter) {
    if (permutation.length() >= permutationLength)
        return;

    // nucleotideIndex
    for (final char element : NUCLEOTIDES) {
        if ((permutation + element).length() == permutationLength)
            byteConverter.put(permutation + element, (byte) permutationId.getAndAdd(0x0000_0001));

        fillConverterMapFullSize(permutation + element, permutationId, permutationLength, byteConverter);
    }
}