Java 类com.google.common.collect.ImmutableMultimap 实例源码

项目:GitHub    文件:ExtraCollection.java   
default void use() {
  ImmutableExtraCollection.of(
      ImmutableList.<String>of(),
      ImmutableMultimap.<Integer, String>of(),
      ImmutableMultimap.<Integer, String>of(),
      ImmutableMultimap.<Integer, String>of(),
      ImmutableBiMap.<Integer, String>of());
  ImmutableExtraCollection.of();
  ImmutableExtraCollection collection = ImmutableExtraCollection.builder()
      .addBag("2", "2")
      .putIndex(1, "2", "3", "4")
      .putAllIndex(1, Arrays.asList("2", "3", "4"))
      .putIndex(2, "5")
      .putIndexList(1, "")
      .putIndexSet(2, "2")
      .putAllIndexSet(2, Arrays.asList("3", "4"))
      .putBiMap(1, "a")
      .putBiMap(2, "b")
      .putAllBiMap(Collections.singletonMap(3, "c"))
      .build();

  collection.bag().count("2");
  collection.index().get(1);
  collection.indexList().get(1);
  collection.indexSet().get(2);
}
项目:de.flapdoodle.solid    文件:Multimaps.java   
public static <K,V> ImmutableList<ImmutableMap<K, V>> flatten(ImmutableMultimap<K, V> src) {
    ImmutableList.Builder<ImmutableMap<K, V>> listBuilder=ImmutableList.builder();

    if (!src.isEmpty()) {
        ImmutableMap<K, Collection<V>> map = src.asMap();
        int entries=map.values().stream().reduce(1, (s,l) -> s*l.size(), (a,b) -> a*b);

        ImmutableList<Line<K,V>> lines = map.entrySet().stream()
                .map(e -> new Line<>(e.getKey(), e.getValue()))
                .collect(ImmutableList.toImmutableList());

        for (int i=0;i<entries;i++) {
            ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder();

            int fact=1;
            for (Line<K,V> line: lines) {
                mapBuilder.put(line.key, line.get((i/fact) % line.values.length));
                fact=fact*line.values.length;
            }

            listBuilder.add(mapBuilder.build());
        }
    }
    return listBuilder.build();
}
项目:GitHub    文件:Gsons.java   
@Override
public Multimap<Character, Map.Entry<String, ValueAttribute>> apply(Iterable<ValueAttribute> attributes) {
  ImmutableMultimap.Builder<Character, Map.Entry<String, ValueAttribute>> builder = ImmutableMultimap.builder();

  for (ValueAttribute attribute : attributes) {
    String serializedName = attribute.getMarshaledName();
    builder.put(serializedName.charAt(0), Maps.immutableEntry(serializedName, attribute));

    for (String alternateName : attribute.getAlternateSerializedNames()) {
      if (!alternateName.isEmpty()) {
        builder.put(alternateName.charAt(0), Maps.immutableEntry(alternateName, attribute));
      }
    }
  }

  return builder.build();
}
项目:mug    文件:BiStreamTest.java   
@Test public void testOf() {
  assertKeyValues(BiStream.of("one", 1))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "two", 2))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "two", 2, "three", 3))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3, "four", 4))
      .containsExactlyEntriesIn(ImmutableMultimap.of(
          "one", 1, "two", 2, "three", 3, "four", 4))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5))
      .containsExactlyEntriesIn(ImmutableMultimap.of(
          "one", 1, "two", 2, "three", 3, "four", 4, "five", 5))
      .inOrder();
}
项目:de.flapdoodle.solid    文件:Blobs.java   
public static ImmutableMultimap<String, Object> pathPropertiesOfAsMultimap(Blob blob, Function<String, Collection<String>> pathPropertyMapping, Path path, PropertyCollectionResolver propertyResolver) {
    ImmutableList<String> pathProperties = path.propertyNamesWithoutPage();

    ImmutableMap<String, ImmutableSet<?>> blopPathPropertyMap = pathProperties.stream()
        .map(p -> Pair.<String, ImmutableSet<?>>of(p, propertyOf(blob, pathPropertyMapping, propertyResolver, p)))
        .filter(pair -> !pair.b().isEmpty())
        .collect(ImmutableMap.toImmutableMap(Pair::a, Pair::b));

    if (blopPathPropertyMap.keySet().size()<pathProperties.size()) {
        return ImmutableMultimap.of();
    }

    Builder<String, Object> multiMapBuilder = ImmutableMultimap.builder();

    blopPathPropertyMap.forEach((key, values) -> {
        multiMapBuilder.putAll(key, values);
    });

    return multiMapBuilder.build();
}
项目:de.flapdoodle.solid    文件:ImmutableGroupedPropertyMap.java   
public ImmutableGroupedPropertyMap build() {
    ImmutableMap.Builder<Key, ImmutableMap<String, Object>> mapOfMapsBuilder=ImmutableMap.builder();
    ImmutableMultimap.Builder<Key, String> groupOfKeyBuilder=ImmutableMultimap.builder();

    maps.forEach((key, map) -> {
        mapOfMapsBuilder.put(key, ImmutableMap.copyOf(map));
    });

    maps.keySet().forEach(key -> {
        Key current=key;
        while (!current.isRoot()) {
            Key parent = current.parent();
            groupOfKeyBuilder.put(parent, current.last());
            current=parent;
        }
    });

    return new ImmutableGroupedPropertyMap(mapOfMapsBuilder.build(), groupOfKeyBuilder.build());
}
项目:tac-kbp-eal    文件:EAScoringObserver.java   
private ImmutableMultimap<String, FMeasureCounts> toFMeasures(
    Collection<BrokenDownSummaryConfusionMatrix<Symbol>> data,
    Map.Entry<String, Collection<Symbol>> FMeasureSymbol) {
  final ImmutableMultimap.Builder<String, FMeasureCounts> ret = ImmutableMultimap.builder();

    /*
     MapUtils.copyWithTransformedEntries(data.asMap(),
                        Functions.toStringFunction(), FmeasureVs(FMeasureSymbol.getValue()));
     */
  final Function<SummaryConfusionMatrix, FMeasureCounts> scoringFunction =
      FmeasureVs(ImmutableSet.copyOf(FMeasureSymbol.getValue()));
  for (final BrokenDownSummaryConfusionMatrix<Symbol> dataPoint : data) {
    for (final Map.Entry<Symbol, SummaryConfusionMatrix> entry : dataPoint.asMap().entrySet()) {
      ret.put(entry.getKey().toString(), scoringFunction.apply(entry.getValue()));
    }
  }

  return ret.build();
}
项目:stroom-stats    文件:StopProcessingTask.java   
@Override
public void execute(final ImmutableMultimap<String, String> parameters, final PrintWriter output) throws Exception {

    LOGGER.info("{} endpoint called", TASK_NAME);

    @SuppressWarnings("FutureReturnValueIgnored")
    Future<Void> future = CompletableFuture
            .runAsync(statisticsIngestService::stop)
            .handle((aVoid, ex) -> {
                if (ex != null) {
                    LOGGER.error("Task {} failed with error {}", TASK_NAME, ex.getMessage(), ex);
                } else {
                    LOGGER.info("Task {} completed successfully", TASK_NAME);
                }
                return aVoid;
            });
}
项目:de.flapdoodle.solid    文件:Menu.java   
public static ImmutableList<Menu> of(ImmutableMultimap<ImmutableMap<String, Object>, Blob> groupedBlobs) {
    ImmutableList<BlobAndMenu> sortedBlobs = groupedBlobs.inverse().asMap()
            .entrySet()
            .stream()
            .filter(e -> !e.getValue().isEmpty())
            .map(e -> BlobAndMenu.of(e.getKey(), e.getValue().iterator().next()))
            .sorted((a,b) -> Long.compare(a.menu().weight(), b.menu().weight()))
            .collect(ImmutableList.toImmutableList());

    ImmutableList<BlobAndMenu> parents = sortedBlobs.stream()
            .filter(blobmenu -> !blobmenu.menu().parent().isPresent())
            .collect(ImmutableList.toImmutableList());

    return parents.stream()
        .map(parent -> asMenu(parent,sortedBlobs))
        .collect(ImmutableList.toImmutableList());
}
项目:ProjectAres    文件:MapUtils.java   
public static <K, V> Multimap<K, V> combine(Iterable<Multimap<K, V>> maps) {
    Multimap<K, V> singleton = null;
    ImmutableMultimap.Builder<K, V> builder = null;
    for(Multimap<K, V> map : maps) {
        if(!map.isEmpty()) {
            if(singleton == null) {
                singleton = map;
            } else {
                if(builder == null) {
                    builder = ImmutableMultimap.builder();
                }
                builder.putAll(singleton);
                builder.putAll(map);
            }
        }
    }

    if(builder != null) {
        return builder.build();
    } else if(singleton != null) {
        return singleton;
    } else {
        return ImmutableMultimap.of();
    }
}
项目:de.flapdoodle.solid    文件:Collectors.java   
public static <T, L, K> Collector<T, ?, ImmutableMultimap<K, T>> groupingByValues(Function<? super T, ? extends Iterable<? extends K>> classifier) {
    return ImmutableGenericCollector.<T, LinkedListMultimap<K, T>, ImmutableMultimap<K, T>>builder()
        .supplier(LinkedListMultimap::create)
        .accumulator((map, t) -> {
            classifier.apply(t).forEach(k -> {
                map.put(k, t);
            });
        })
        .combiner((a,b) -> {
            LinkedListMultimap<K, T> ret = LinkedListMultimap.create(a);
            ret.putAll(b);
            return ret;
        })
        .finisher(map -> ImmutableMultimap.copyOf(map))
        .build();
}
项目:Equella    文件:ItemDaoImpl.java   
@Override
@Transactional(propagation = Propagation.MANDATORY)
public Multimap<Long, String> getCollaboratorsForItemIds(Collection<Long> itemIds)
{
    if( itemIds.isEmpty() )
    {
        return ImmutableMultimap.of();
    }
    List<Object[]> attachments = getHibernateTemplate().findByNamedParam(
        "select c, i.id from Item i join i.collaborators c where i.id in (:items)", "items", itemIds);
    ListMultimap<Long, String> multiMap = ArrayListMultimap.create();
    for( Object[] attachmentRow : attachments )
    {
        multiMap.put((Long) attachmentRow[1], (String) attachmentRow[0]);
    }
    return multiMap;
}
项目:javaide    文件:Actions.java   
public ImmutableMultimap<Integer, Record> getResultingSourceMapping(XmlDocument xmlDocument)
        throws ParserConfigurationException, SAXException, IOException {

    XmlLoader.SourceLocation inMemory = XmlLoader.UNKNOWN;

    XmlDocument loadedWithLineNumbers = XmlLoader.load(
            xmlDocument.getSelectors(),
            xmlDocument.getSystemPropertyResolver(),
            inMemory,
            xmlDocument.prettyPrint(),
            XmlDocument.Type.MAIN,
            Optional.<String>absent() /* mainManifestPackageName */);

    ImmutableMultimap.Builder<Integer, Record> mappingBuilder = ImmutableMultimap.builder();
    for (XmlElement xmlElement : loadedWithLineNumbers.getRootNode().getMergeableElements()) {
        parse(xmlElement, mappingBuilder);
    }
    return mappingBuilder.build();
}
项目:javaide    文件:Actions.java   
private void parse(XmlElement element,
        ImmutableMultimap.Builder<Integer, Record> mappings) {
    DecisionTreeRecord decisionTreeRecord = mRecords.get(element.getId());
    if (decisionTreeRecord != null) {
        NodeRecord nodeRecord = findNodeRecord(decisionTreeRecord);
        if (nodeRecord != null) {
            mappings.put(element.getPosition().getLine(), nodeRecord);
        }
        for (XmlAttribute xmlAttribute : element.getAttributes()) {
            AttributeRecord attributeRecord = findAttributeRecord(decisionTreeRecord,
                    xmlAttribute);
            if (attributeRecord != null) {
                mappings.put(xmlAttribute.getPosition().getLine(), attributeRecord);
            }
        }
    }
    for (XmlElement xmlElement : element.getMergeableElements()) {
        parse(xmlElement, mappings);
    }
}
项目:javaide    文件:Actions.java   
public String blame(XmlDocument xmlDocument)
        throws IOException, SAXException, ParserConfigurationException {

    ImmutableMultimap<Integer, Record> resultingSourceMapping =
            getResultingSourceMapping(xmlDocument);
    LineReader lineReader = new LineReader(
            new StringReader(xmlDocument.prettyPrint()));

    StringBuilder actualMappings = new StringBuilder();
    String line;
    int count = 1;
    while ((line = lineReader.readLine()) != null) {
        actualMappings.append(count).append(line).append("\n");
        if (resultingSourceMapping.containsKey(count)) {
            for (Record record : resultingSourceMapping.get(count)) {
                actualMappings.append(count).append("-->")
                        .append(record.getActionLocation().toString())
                        .append("\n");
            }
        }
        count++;
    }
    return actualMappings.toString();
}
项目:hashsdn-controller    文件:DOMNotificationRouter.java   
@Override
public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
    final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
        @Override
        protected void removeRegistration() {
            final ListenerRegistration<T> me = this;

            synchronized (DOMNotificationRouter.this) {
                replaceListeners(ImmutableMultimap.copyOf(Multimaps.filterValues(listeners, input -> input != me)));
            }
        }
    };

    if (!types.isEmpty()) {
        final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
        b.putAll(listeners);

        for (final SchemaPath t : types) {
            b.put(t, reg);
        }

        replaceListeners(b.build());
    }

    return reg;
}
项目:OperatieBRP    文件:MetaObject.java   
/**
 * Bouwt het MetaObject.
 * @param parentObject het parent meta object
 * @return het MetaObject
 */
MetaObject build(final MetaObject parentObject) {
    final MetaObject gebouwdObject = new MetaObject();
    gebouwdObject.parentObject = parentObject;
    gebouwdObject.objectsleutel = objectsleutel;
    gebouwdObject.objectElement = objectElement;

    final Multimap<ObjectElement, MetaObject> tempObjectenMap = HashMultimap.create();
    for (final Builder builder : objectBuilderList) {
        final MetaObject object = builder.build(gebouwdObject);
        tempObjectenMap.put(object.getObjectElement(), object);
    }
    gebouwdObject.elementObjectMap = ImmutableMultimap.copyOf(tempObjectenMap);
    gebouwdObject.objecten = ImmutableSet.copyOf(tempObjectenMap.values());

    final Map<GroepElement, MetaGroep> tempGroepenMap = Maps.newHashMap();
    for (final MetaGroep.Builder groepBuilder : groepBuilderList) {
        final MetaGroep groep = groepBuilder.build(gebouwdObject);
        tempGroepenMap.put(groep.getGroepElement(), groep);
    }
    gebouwdObject.elementGroepMap = ImmutableMap.copyOf(tempGroepenMap);
    gebouwdObject.groepen = ImmutableSet.copyOf(tempGroepenMap.values());
    return gebouwdObject;
}
项目:de.flapdoodle.solid    文件:Blobs.java   
public static ImmutableMultimap<ImmutableMap<String, Object>, Blob> orderByKey(ImmutableMultimap<ImmutableMap<String, Object>, Blob> src,
        ImmutableList<String> pathOrdering) {
    ImmutableMultimap.Builder<ImmutableMap<String, Object>, Blob> builder=ImmutableMultimap.builder();

    src.asMap().entrySet()
        .stream()
        .sorted(pathOrderingOf(pathOrdering))
        .forEach(e -> {
            builder.putAll(e.getKey(), e.getValue());
        });

    return builder.build();
}
项目:de.flapdoodle.solid    文件:Collectors.java   
public static <T, K> Collector<T, ?, ImmutableMultimap<K, T>> groupingBy(Function<? super T, ? extends K> classifier) {
    return ImmutableGenericCollector.<T, LinkedListMultimap<K, T>, ImmutableMultimap<K, T>>builder()
        .supplier(LinkedListMultimap::create)
        .accumulator((map, t) -> {
            map.put(classifier.apply(t), t);
        })
        .combiner((a,b) -> {
            LinkedListMultimap<K, T> ret = LinkedListMultimap.create(a);
            ret.putAll(b);
            return ret;
        })
        .finisher(map -> ImmutableMultimap.copyOf(map))
        .build();
}
项目:mug    文件:BiStreamTest.java   
@Test public void testMapKeys() {
  assertKeyValues(BiStream.of("one", 1).mapKeys((k, v) -> k + v))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one1", 1))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1).mapKeys(k -> k + k))
      .containsExactlyEntriesIn(ImmutableMultimap.of("oneone", 1))
      .inOrder();
}
项目:mug    文件:BiStreamTest.java   
@Test public void testMapValues() {
  assertKeyValues(BiStream.of("one", 1).mapValues((k, v) -> k + v))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", "one1"))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1).mapValues(v -> v * 10))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 10))
      .inOrder();
}
项目:de.flapdoodle.solid    文件:MultimapsTest.java   
@Test
public void flattenSampleWith3() {
    ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
            .putAll("a", 1,4)
            .putAll("m", 0)
            .putAll("b", 2,3)
            .build());

    assertEquals(4,result.size());
    assertEquals("[{a=1, m=0, b=2}, {a=4, m=0, b=2}, {a=1, m=0, b=3}, {a=4, m=0, b=3}]",result.toString());
}
项目:mug    文件:BiStreamTest.java   
@Test public void testFlatMapValues() {
  assertKeyValues(BiStream.of("one", 1).flatMapValues((k, v) -> Stream.of(k, v)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", "one", "one", 1))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1).flatMapValues(v -> Stream.of(v, v * 10)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "one", 10))
      .inOrder();
}
项目:de.flapdoodle.solid    文件:DefaultSiteGenerator.java   
private ImmutableMultimap<ImmutableMap<String, Object>, Blob> reverse(ImmutableMultimap<ImmutableMap<String, Object>, Blob> src) {
    ImmutableMultimap.Builder<ImmutableMap<String,Object>, Blob> builder=ImmutableMultimap.builder();
    src.keySet().asList().reverse().forEach(key -> {
        builder.putAll(key, src.get(key));
    });
    return builder.build();
}
项目:mug    文件:BiStreamTest.java   
@Test public void testPeek() {
  AtomicInteger sum = new AtomicInteger();
  assertKeyValues(BiStream.of(1, 2, 3, 4).peek((k, v) -> sum.addAndGet(k + v)))
      .containsExactlyEntriesIn(ImmutableMultimap.of(1, 2, 3, 4))
      .inOrder();
  assertThat(sum.get()).isEqualTo(10);
}
项目:mug    文件:BiStreamTest.java   
@Test public void testSorted() {
  assertKeyValues(
          BiStream.of("b", 10, "a", 11, "a", 22)
              .sorted(Comparator.naturalOrder(), Comparator.naturalOrder()))
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 11, "a", 22, "b", 10))
      .inOrder();
}
项目:de.flapdoodle.solid    文件:MultimapsTest.java   
@Test
public void flattenSampleWithOneCollection() {
    ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
            .putAll("a", 1)
            .putAll("b", 2,3)
            .build());

    assertEquals(2,result.size());
    assertEquals("[{a=1, b=2}, {a=1, b=3}]",result.toString());
}
项目:mug    文件:BiStreamTest.java   
@Test public void toBiCollectionWithCollectorStrategy() {
  BiCollection<String, Integer> biCollection = BiStream.of("a", 1)
      .toBiCollection(ImmutableList::toImmutableList);
  assertKeyValues(biCollection.stream())
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1))
      .inOrder();
  assertKeyValues(biCollection.stream())
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1))
      .inOrder();
}
项目:tac-kbp-eal    文件:SelectForDualAnnotation.java   
private static ImmutableMultimap<Symbol, Symbol> makeAnnotatorsToDocumentsMap(
    Table<Symbol, Symbol, Symbol> annotatorsTable, Set<Symbol> targetDocIDs) {
  final ImmutableMultimap.Builder<Symbol, Symbol> ret = ImmutableMultimap.builder();

  for (final Symbol docID : targetDocIDs) {
    for (final Symbol annotator : annotatorsTable.row(docID).values()) {
      ret.put(annotator, docID);
    }
  }

  return ret.build();
}
项目:tac-kbp-eal    文件:SelectForDualAnnotation.java   
private static ImmutableMultimap<Symbol, Symbol> makeEventTypesToDocumentsMap(
    AnnotationStore annotationStore, Set<Symbol> targetDocIDs) throws IOException {
  final ImmutableMultimap.Builder<Symbol, Symbol> ret = ImmutableMultimap.builder();

  for (final Symbol docID : targetDocIDs) {
    for (final Response response : annotationStore.readOrEmpty(docID).allResponses()) {
      ret.put(response.type(), docID);
    }
  }

  return ret.build();
}
项目:tac-kbp-eal    文件:FilterAnswerKeyByTypeAndRole.java   
private static Multimap<Symbol, Symbol> loadTypesToValidRolesMap(final Parameters params)
    throws IOException {
  final Multimap<Symbol, Symbol> typesToValidRolesInitial = FileUtils.loadSymbolMultimap(
      Files.asCharSource(params.getExistingFile("typeAndRoleFile"), Charsets.UTF_8));
  final Set<Symbol> alwaysValidRoles = params.getSymbolSet("alwaysValidRoles");
  final ImmutableMultimap.Builder<Symbol, Symbol> typesToValidRolesB = ImmutableMultimap.builder();
  typesToValidRolesB.putAll(typesToValidRolesInitial);
  for (final Symbol eventType : typesToValidRolesInitial.keySet()) {
    typesToValidRolesB.putAll(eventType, alwaysValidRoles);
  }
  return typesToValidRolesB.build();
}
项目:tac-kbp-eal    文件:_CorpusEventLinking.java   
@Value.Derived
public ImmutableMultimap<DocEventFrameReference, CorpusEventFrame> docEventsToCorpusEvents() {
  final ImmutableMultimap.Builder<DocEventFrameReference, CorpusEventFrame> ret =
      ImmutableMultimap.builder();

  for (final CorpusEventFrame corpusEventFrame : corpusEventFrames()) {
    for (final DocEventFrameReference docEventFrameReference : corpusEventFrame
        .docEventFrames()) {
      ret.put(docEventFrameReference, corpusEventFrame);
    }
  }

  return ret.build();
}
项目:tac-kbp-eal    文件:CorefAnnotation.java   
private CorefAnnotation(final Symbol docId, final Multimap<Integer, KBPString> idToCASes,
    final Map<KBPString, Integer> CASesToIDs, final Set<KBPString> unannotated) {
  this.docId = checkNotNull(docId);
  this.idToCASes = ImmutableMultimap.copyOf(idToCASes);
  this.CASesToIDs = ImmutableMap.copyOf(CASesToIDs);
  this.unannotated = ImmutableSet.copyOf(unannotated);
  checkConsistency();
}
项目:tac-kbp-eal    文件:ExactMatchEventArgumentLinkingAligner.java   
/**
 * Converts a {@link ResponseLinking} to an {@link EventArgumentLinking} using a {@link
 * CorefAnnotation} from an {@link com.bbn.kbp.events2014.AnswerKey} to canonicalize the
 * responses.  If the canonicalization is inconsistent with the response linking, an {@link
 * java.lang.IllegalArgumentException} will be thrown.
 */
public EventArgumentLinking align(ResponseLinking responseLinking,
    AnswerKey answerKey)  {
  checkArgument(answerKey.docId() == responseLinking.docID());

  // assertLinkingSubsetOfAnswerKey(responseLinking, answerKey);
  // the above assertion was too strong - the system response linking could
  // validly include responses which were not included in the answerKey because
  // there was a higher scoring system response in the same equivalence class

  final ImmutableMultimap<TypeRoleFillerRealis, Response> canonicalToResponses =
      Multimaps.index(responseLinking.allResponses(),
          TypeRoleFillerRealis.extractFromSystemResponse(
              answerKey.corefAnnotation().strictCASNormalizerFunction()));

  final Multimap<Response, TypeRoleFillerRealis> responsesToCanonical =
      canonicalToResponses.inverse();

  final ImmutableSet.Builder<TypeRoleFillerRealisSet> coreffedArgs = ImmutableSet.builder();
  for (final ResponseSet responseSet : responseLinking.responseSets()) {
    coreffedArgs.add(TypeRoleFillerRealisSet.from(
        canonicalizeResponseSet(responseSet.asSet(),
            canonicalToResponses, responsesToCanonical)));
  }
  final ImmutableSet<TypeRoleFillerRealis> incompleteResponses = canonicalizeResponseSet(
      responseLinking.incompleteResponses(), canonicalToResponses, responsesToCanonical);

  return EventArgumentLinking.builder().docID(responseLinking.docID())
      .eventFrames(coreffedArgs.build()).incomplete(incompleteResponses).build();
}
项目:tac-kbp-eal    文件:ExactMatchEventArgumentLinkingAligner.java   
@Override
public ResponseLinking alignToResponseLinking(EventArgumentLinking eventArgumentLinking,
    AnswerKey answerKey) {
  // For every Response in answerKey, answerKey.corefAnnotation().strictCASNormalizerFunction() will try to find
  // a canonical coreferent for the Response's CAS (KBPString), by checking CorefAnnotation.CASesToIDs
  // If the KBPString does not exist in CASesToIDs, then an Exception will be thrown
  final ImmutableMultimap<TypeRoleFillerRealis, Response> canonicalToResponses =
      Multimaps.index(answerKey.allResponses(),
          TypeRoleFillerRealis.extractFromSystemResponse(
              answerKey.corefAnnotation().strictCASNormalizerFunction()));

  final ImmutableSet.Builder<Response> incompletes = ImmutableSet.builder();
  for (final TypeRoleFillerRealis incompleteEquivClass : eventArgumentLinking.incomplete()) {
    incompletes.addAll(canonicalToResponses.get(incompleteEquivClass));
  }

  final ImmutableSet.Builder<ResponseSet> responseSets = ImmutableSet.builder();
  for (final TypeRoleFillerRealisSet equivClassSet : eventArgumentLinking.eventFrames()) {
    final ImmutableSet.Builder<Response> setBuilder = ImmutableSet.builder();
    for (final TypeRoleFillerRealis trfr : equivClassSet.asSet()) {
      setBuilder.addAll(canonicalToResponses.get(trfr));
    }
    responseSets.add(ResponseSet.from(setBuilder.build()));
  }

  return ResponseLinking.builder().docID(answerKey.docId()).responseSets(responseSets.build())
      .incompleteResponses(incompletes.build()).build();
}
项目:tac-kbp-eal    文件:SingleFileQueryAssessmentsLoader.java   
public final CorpusQueryAssessments loadFrom(final CharSource source) throws IOException {
  final List<String> lines = source.readLines();
  final List<QueryResponse2016> queries = Lists.newArrayList();
  final Map<QueryResponse2016, String> metadata = Maps.newHashMap();
  final ImmutableMultimap.Builder<QueryResponse2016, Symbol> responsesToSystems =
      ImmutableMultimap.builder();
  final Map<QueryResponse2016, QueryAssessment2016> assessments = Maps.newHashMap();
  Optional<String> lastMetadata = Optional.absent();
  for (final String line : lines) {
    if (line.startsWith("#")) {
      lastMetadata = Optional.of(line.trim().substring(1));
    } else {
      final String[] parts = line.trim().split("\t");
      checkArgument(parts.length == 5, "expected five columns, but got " + parts.length);
      final Symbol queryID = Symbol.from(parts[0]);
      final Symbol docID = Symbol.from(parts[1]);
      final String[] systemIDs = parts[2].split(",");
      final ImmutableSortedSet<CharOffsetSpan> spans = extractPJSpans(parts[3]);
      final QueryAssessment2016 assessment = QueryAssessment2016.valueOf(parts[4]);
      final QueryResponse2016 query =
          QueryResponse2016.builder().queryID(queryID).docID(docID)
              .addAllPredicateJustifications(spans).build();
      queries.add(query);
      for(final String systemID: systemIDs) {
        responsesToSystems.put(query, Symbol.from(systemID));
      }
      if (!assessment.equals(QueryAssessment2016.UNASSESSED)) {
        assessments.put(query, assessment);
      }
      if (lastMetadata.isPresent()) {
        metadata.put(query, lastMetadata.get());
        lastMetadata = Optional.absent();
      }
    }
  }
  return CorpusQueryAssessments.builder().addAllQueryReponses(queries).assessments(assessments)
      .queryResponsesToSystemIDs(responsesToSystems.build())
      .metadata(metadata).build();
}
项目:tac-kbp-eal    文件:AnswerAlignment.java   
private AnswerAlignment(
    final Multimap<Answerable, LeftAnswer> equivalenceClassesToLeftItems,
    final Multimap<Answerable, RightAnswer> equivalenceClassesToRightItems) {
  this.ecToLeft = ImmutableMultimap.copyOf(equivalenceClassesToLeftItems);
  this.ecToRight = ImmutableMultimap.copyOf(equivalenceClassesToRightItems);

  // build set of equivalence classes
  final ImmutableSet.Builder<Answerable> classesBuilder = ImmutableSet.builder();
  classesBuilder.addAll(equivalenceClassesToLeftItems.keySet());
  classesBuilder.addAll(equivalenceClassesToRightItems.keySet());
  this.answerables = classesBuilder.build();
}
项目:de.flapdoodle.solid    文件:MultimapsTest.java   
@Test
public void flattenSampleWithTwoCollections() {
    ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
            .putAll("a", 1,4)
            .putAll("b", 2,3)
            .build());

    assertEquals(4,result.size());
    assertEquals("[{a=1, b=2}, {a=4, b=2}, {a=1, b=3}, {a=4, b=3}]",result.toString());
}
项目:tac-kbp-eal    文件:EAScoringObserver.java   
@MoveToBUECommon
private static <K, V> ImmutableMultimap<K, V> combineMapsToMultimap(
    Iterable<? extends Map<K, V>> maps) {
  final ImmutableMultimap.Builder<K, V> ret = ImmutableMultimap.builder();

  for (final Map<K, V> map : maps) {
    ret.putAll(Multimaps.forMap(map));
  }

  return ret.build();
}
项目:de.flapdoodle.solid    文件:MultimapsTest.java   
@Test
public void flattenSimpleSample() {
    ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
            .putAll("a", 1)
            .putAll("b", 2)
            .build());

    assertEquals(1,result.size());
    assertEquals("[{a=1, b=2}]",result.toString());
}