org.apache.uima.cas.text.AnnotationFS Java Examples

The following examples show how to use org.apache.uima.cas.text.AnnotationFS. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CasUtilTest.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testSelectOnAnnotations() throws Exception {
  String text = "Rot wood cheeses dew?";
  tokenBuilder.buildTokens(jCas, text);

  CAS cas = jCas.getCas();

  assertEquals(asList("Rot", "wood", "cheeses", "dew?"),
          toText(select(cas, getType(cas, Token.class.getName()))));

  assertEquals(
          asList("Rot", "wood", "cheeses", "dew?"),
          toText((Collection<AnnotationFS>) (Collection) selectFS(cas,
                  getType(cas, Token.class.getName()))));
}
 
Example #2
Source File: ComplexTypeTest.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void thatBooleanValueInConditionWorks() throws Exception
{
    TypeSystemDescription tsd = TypeSystemDescriptionFactory
            .createTypeSystemDescription("desc.types.TestTypeSystemDescriptor");

    CAS cas = createCas(tsd, null, null);
    cas.setDocumentText("blah");
    
    AnnotationFS continent = cas.createAnnotation(getType(cas, "de.Continent"), 0, 1);
    FSUtil.setFeature(continent, "discovered", true);
    cas.addFsToIndexes(continent);

    ConstraintsGrammar parser = new ConstraintsGrammar(new FileInputStream(
            "src/test/resources/rules/region.rules"));
    ParsedConstraints constraints = parser.Parse().accept(new ParserVisitor());

    Evaluator constraintsEvaluator = new ValuesGenerator();
    List<PossibleValue> possibleValues = constraintsEvaluator.generatePossibleValues(continent,
            "name", constraints);
    
    assertThat(possibleValues)
            .extracting(PossibleValue::getValue)
            .containsExactlyInAnyOrder("America");
}
 
Example #3
Source File: IndexRepositoryTest.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
private long timeAdd2Indexes (FeatureStructure[] fsa, boolean reverse) {
  long start = System.nanoTime();
  if (reverse) {
    AnnotationIndex<AnnotationFS> annotIndex = cas.getAnnotationIndex();
    for (int i = fsa.length - 1; i >= 0; i--) {
      cas.addFsToIndexes(fsa[i]);
      if ((i % 10000) == 9999) {
        annotIndex.size();  // forces batch add to indexes
      }
    }      
  } else {
    for (int i = 0; i < fsa.length; i++) {
      cas.addFsToIndexes(fsa[i]);
    }
  }
  return System.nanoTime() - start;
}
 
Example #4
Source File: FeatureValue.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
@Override
public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
  if (AnnotationFS.class.equals(adapter)) {
    if (getValue() instanceof AnnotationFS) {
      return getValue();
    }
  }

  if (FeatureStructure.class.equals(adapter)) {
    if (getValue() instanceof FeatureStructure) {
      return getValue();
    }
  }

  return null;
}
 
Example #5
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * Get the single instance of the specified type from the CAS at the given offsets.
 * 
 * @param aCas
 *          the CAS containing the annotations.
 * @param aType
 *          the type of annotations to fetch.
 * @param aBegin
 *          the begin offset.
 * @param aEnd
 *          the end offset.
 * @return the single annotation at the specified offsets.
 */
public static AnnotationFS selectSingleAt(final CAS aCas, final Type aType, int aBegin, int aEnd) {
  List<AnnotationFS> list = selectAt(aCas, aType, aBegin, aEnd);

  if (list.isEmpty()) {
    throw new IllegalArgumentException("CAS does not contain any [" + aType.getName() + "] at ["
            + aBegin + "," + aEnd + "]");
  }
  
  if (list.size() > 1) {
    throw new IllegalArgumentException("CAS contains more than one [" + aType.getName()
            + "] at [" + aBegin + "," + aEnd + "]");
  }

  return list.get(0);
}
 
Example #6
Source File: AbstractJsonConsumer.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Write an annotation to the file.
 *
 * @param generator the generator
 * @param annotation the annotation
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void writeFS(JsonGenerator generator, FeatureStructure annotation) throws IOException {
  generator.writeStartObject();

  Type type = annotation.getType();
  generator.writeStringField("type", type.getName());

  List<Feature> features = type.getFeatures();
  if (annotation instanceof AnnotationFS) {
    AnnotationFS annotationFS = (AnnotationFS) annotation;
    if (!(annotationFS.getEnd() == 0 && annotationFS.getBegin() == 0)) {
      generator.writeStringField("coveredText", annotationFS.getCoveredText());
    }
  }

  if (!features.isEmpty()) {
    writeFS(generator, annotation, features);
  }
  generator.writeEndObject();
}
 
Example #7
Source File: BratRenderer.java    From webanno with Apache License 2.0 6 votes vote down vote up
public static void renderTokens(CAS aCas, GetDocumentResponse aResponse, AnnotatorState aState)
{
    int winBegin = aState.getWindowBeginOffset();
    int winEnd = aState.getWindowEndOffset();
    Type tokenType = CasUtil.getType(aCas, Token.class);

    List<AnnotationFS> tokens = selectCovered(aCas, tokenType, winBegin, winEnd);
    for (AnnotationFS fs : tokens) {
        // attach type such as POS adds non-existing token element for ellipsis annotation
        if (fs.getBegin() == fs.getEnd()) {
            continue;
        }
        
        split(aResponse.getSentenceOffsets(), fs.getCoveredText(), fs.getBegin() - winBegin,
                fs.getEnd() - winBegin)                    
                .forEach(range -> {
                    aResponse.addToken(range.getBegin(), range.getEnd());
                    if (DEBUG) {
                        aResponse.addEntity(new Entity(new VID(fs), "Token",
                                new Offsets(range.getBegin(), range.getEnd()),
                                fs.getCoveredText(), "#d9d9d9",
                                "[" + fs.getBegin() + "-" + fs.getEnd() + "]"));
                    }
                });
    }
}
 
Example #8
Source File: ActiveLearningSidebar.java    From inception with Apache License 2.0 6 votes vote down vote up
/**
 * Select an item from the learning history. When the user clicks on an item from the learning
 * history, the following should happen:
 * <ul>
 * <li>the main editor should jump to the location of the history item</li>
 * <li>if there is an annotation which matches the history item in terms of layer and feature
 *     value, then this annotation should be highlighted.</li>
 * <li>if there is no matching annotation, then the text should be highlighted</li>
 * </ul>
 */
private void actionSelectHistoryItem(AjaxRequestTarget aTarget, LearningRecord aRecord)
    throws IOException
{
    actionShowSelectedDocument(aTarget, aRecord.getSourceDocument(),
            aRecord.getOffsetCharacterBegin(), aRecord.getOffsetCharacterEnd());
    
    // Since we have switched documents above (if it was necessary), the editor CAS should
    // now point to the correct one
    CAS cas = getCasProvider().get();

    // ... if a matching annotation exists, highlight the annotaiton
    Optional<AnnotationFS> annotation = getMatchingAnnotation(cas, aRecord);
    
    if (annotation.isPresent()) {
        setHighlight(aRecord.getSourceDocument(), annotation.get());
    }
    // ... otherwise highlight the text
    else {
        setHighlight(aRecord);
        
        info("No annotation could be highlighted.");
        aTarget.addChildren(getPage(), IFeedback.class);
    }
}
 
Example #9
Source File: ContainingConstraint.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the given FeatureStructure is inside the a containing annotation.
 *
 * @param featureStructure the feature structure
 * @return true, if successful
 */
@Override
public boolean match(FeatureStructure featureStructure) {
  boolean result = false;

  if (featureStructure instanceof AnnotationFS) {
    AnnotationFS annotation = (AnnotationFS) featureStructure;

    for (AnnotationFS containingAnnotation : mContainingAnnotations) {
      if (isContaining(annotation, containingAnnotation)) {
        result = true;
        break;
      }
    }
  }

  return result;
}
 
Example #10
Source File: MtasUimaParser.java    From inception with Apache License 2.0 5 votes vote down vote up
private int indexFeatures(AnnotationFS aAnnotation, String aLayer, String aPrefix, Range aRange,
        int aMtasId, int aFSAddress)
{
    int mtasId = aMtasId;

    // If there are no features on the layer, do not attempt to index them
    List<AnnotationFeature> features = layerFeatures.get(aAnnotation.getType().getName());
    if (features == null) {
        return mtasId;
    }
    
    // Iterate over the features of this layer and index them one-by-one
    for (AnnotationFeature feature : features) {
        Optional<FeatureIndexingSupport> fis = featureIndexingSupportRegistry
                .getIndexingSupport(feature);
        if (fis.isPresent()) {
            MultiValuedMap<String, String> fieldsAndValues = fis.get()
                    .indexFeatureValue(aLayer, aAnnotation, aPrefix, feature);
            for (Entry<String, String> e : fieldsAndValues.entries()) {
                indexFeatureValue(e.getKey(), e.getValue(), mtasId++,
                        aAnnotation.getBegin(), aAnnotation.getEnd(), aRange, aFSAddress);
            }
            
            LOG.trace("FEAT[{}-{}]: {}", aRange.getBegin(), aRange.getEnd(), fieldsAndValues);
        }
    }
    
    return mtasId;
}
 
Example #11
Source File: BratAnnotatorUtility.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static CAS clearAnnotations(CAS aCas)
    throws IOException
{
    CAS target;
    try {
        target = CasFactory.createCas((TypeSystemDescription) null);
    }
    catch (UIMAException e) {
        throw new IOException(e);
    }
    
    // Copy the CAS - basically we do this just to keep the full type system information
    CASCompleteSerializer serializer = serializeCASComplete((CASImpl) getRealCas(aCas));
    deserializeCASComplete(serializer, (CASImpl) getRealCas(target));

    // Remove all annotations from the target CAS but we keep the type system!
    target.reset();
    
    // Copy over essential information
    if (exists(aCas, getType(aCas, DocumentMetaData.class))) {
        copyDocumentMetadata(aCas, target);
    }
    else {
        WebAnnoCasUtil.createDocumentMetadata(aCas);
    }
    target.setDocumentLanguage(aCas.getDocumentLanguage()); // DKPro Core Issue 435
    target.setDocumentText(aCas.getDocumentText());
    
    // Transfer token boundaries
    for (AnnotationFS t : selectTokens(aCas)) {
        target.addFsToIndexes(createToken(target, t.getBegin(), t.getEnd()));
    }

    // Transfer sentence boundaries
    for (AnnotationFS s : selectSentences(aCas)) {
        target.addFsToIndexes(createSentence(target, s.getBegin(), s.getEnd()));
    }

    return target;
}
 
Example #12
Source File: ConstraintsGeneratorTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void testTwoConditions()
    throws Exception
{
    JCas jcas = makeJCasOneSentence();
    CAS cas = jcas.getCas();
    
    List<Token> tokens = new ArrayList<>(select(jcas, Token.class));
    
    Token t1 = tokens.get(0);
    Token t2 = tokens.get(tokens.size() - 1);

    NamedEntity gov = new NamedEntity(jcas, t1.getBegin(), t1.getEnd());
    gov.setValue("Animal");
    gov.addToIndexes();
    NamedEntity dep =  new NamedEntity(jcas, t2.getBegin(), t2.getEnd());
    dep.setValue("NotWeight");
    dep.addToIndexes();

    Type relationType = cas.getTypeSystem().getType("webanno.custom.Relation");
    
    AnnotationFS fs1 = cas.createAnnotation(relationType, dep.getBegin(), dep.getEnd());
    FSUtil.setFeature(fs1, "Governor", gov);
    FSUtil.setFeature(fs1, "Dependent", dep);
    cas.addFsToIndexes(fs1);
    
    ConstraintsGrammar parser = new ConstraintsGrammar(new FileInputStream(
            "src/test/resources/rules/twoConditions.rules"));
    Parse p = parser.Parse();
    ParsedConstraints constraints = p.accept(new ParserVisitor());

    Evaluator constraintsEvaluator = new ValuesGenerator();
    List<PossibleValue> possibleValues = constraintsEvaluator.generatePossibleValues(
            fs1, "label", constraints);
    
    System.out.println(possibleValues);
    
    // "Weight" != "NotWeight", so the rule should not match
    assertEquals(0, possibleValues.size());
}
 
Example #13
Source File: AnnotationDetailEditorPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void createNewChainLinkAnnotation(ChainAdapter aAdapter, CAS aCas)
{
    LOG.trace("createNewChainLinkAnnotation()");

    AnnotatorState state = getModelObject();
    Selection selection = state.getSelection();

    AnnotationFS originFs = selectAnnotationByAddr(aCas, selection.getOrigin());
    AnnotationFS targetFs = selectAnnotationByAddr(aCas, selection.getTarget());

    // Creating a new chain link
    int addr = aAdapter.addArc(state.getDocument(), state.getUser().getUsername(), aCas,
            originFs, targetFs);
    selection.selectArc(new VID(addr), originFs, targetFs);
}
 
Example #14
Source File: WebAnnoTsv3WriterTestBase.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void testZeroLengthSlotFeature2() throws Exception
{
    JCas jcas = makeJCasOneSentence();
    CAS cas = jcas.getCas();
    
    List<Token> tokens = new ArrayList<>(select(jcas, Token.class));
    
    Token t1 = tokens.get(0);
    Token t2 = tokens.get(1);
    Token t3 = tokens.get(2);
    
    Type type = cas.getTypeSystem().getType("webanno.custom.SimpleSpan");
    AnnotationFS s2 = cas.createAnnotation(type, t2.getBegin(), t3.getEnd());
    cas.addFsToIndexes(s2);
    AnnotationFS s3 = cas.createAnnotation(type, t3.getEnd(), t3.getEnd());
    cas.addFsToIndexes(s3);

    FeatureStructure link1 = makeLinkFS(jcas, "p1", s2);
    FeatureStructure link2 = makeLinkFS(jcas, "p2", s3);
    
    makeLinkHostFS(jcas, t1.getBegin(), t1.getEnd(), link1, link2);
    
    writeAndAssertEquals(jcas, 
            WebannoTsv3Writer.PARAM_SLOT_FEATS, asList("webanno.custom.SimpleLinkHost:links"),
            WebannoTsv3Writer.PARAM_SPAN_LAYERS, asList("webanno.custom.SimpleSpan", 
                    "webanno.custom.SimpleLinkHost"),
            WebannoTsv3Writer.PARAM_LINK_TYPES, asList("webanno.custom.LinkType"),
            WebannoTsv3Writer.PARAM_SLOT_TARGETS, asList("webanno.custom.SimpleSpan"));
}
 
Example #15
Source File: SubjectObjectFeatureSupportTest.java    From inception with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapUnwrap() throws Exception
{
    CAS cas = JCasFactory.createJCasFromPath("src/test/resources/desc/type/webannoTestTypes.xml")
            .getCas();
    
    SubjectObjectFeatureSupport sut = new SubjectObjectFeatureSupport();
    
    AnnotationFeature feat1 = new AnnotationFeature("slot", "webanno.custom.SimpleSpan");
    feat1.setLinkTypeName("webanno.custom.LinkType");
    feat1.setLinkMode(LinkMode.WITH_ROLE);
    feat1.setLinkTypeRoleFeatureName("role");
    feat1.setLinkTypeTargetFeatureName("target");
    feat1.setMode(MultiValueMode.ARRAY);
    
    List<LinkWithRoleModel> links = new ArrayList<>();
    links.add(new LinkWithRoleModel("role", "label", 3));
    
    cas.setDocumentText("label");
    Type targetType = cas.getTypeSystem().getType(feat1.getType());
    Type linkType = cas.getTypeSystem().getType(feat1.getLinkTypeName());
    
    AnnotationFS targetFS = cas.createAnnotation(targetType, 0, cas.getDocumentText().length());
    
    ArrayFS array = cas.createArrayFS(1);
    FeatureStructure linkFS = cas.createFS(linkType);
    FSUtil.setFeature(linkFS, feat1.getLinkTypeRoleFeatureName(), "role");
    FSUtil.setFeature(linkFS, feat1.getLinkTypeTargetFeatureName(), targetFS);
    array.set(0, linkFS);
    
    assertThat(sut.wrapFeatureValue(feat1, cas, array)).isEqualTo(links);
    assertThat(sut.wrapFeatureValue(feat1, cas, null)).isEmpty();
    assertThatThrownBy(() -> sut.wrapFeatureValue(feat1, cas, new Object()))
            .isInstanceOf(IllegalArgumentException.class);
    
    assertThat(sut.unwrapFeatureValue(feat1, cas, links)).isSameAs(links);
    assertThat(sut.unwrapFeatureValue(feat1, cas, null)).isNull();
    assertThatThrownBy(() -> sut.unwrapFeatureValue(feat1, cas, new Object()))
            .isInstanceOf(IllegalArgumentException.class);
}
 
Example #16
Source File: CasMergeTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void copySpanWithSlotWithStackingTest()
    throws Exception
{
    AnnotatorState state = new AnnotatorStateImpl(CURATION);
    state.setUser(new User());
    
    slotLayer.setAnchoringMode(TOKENS);
    slotLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);
    
    JCas jcasA = createJCas(CurationTestUtils.createMultiLinkWithRoleTestTypeSystem("f1"));
    Type type = jcasA.getTypeSystem().getType(CurationTestUtils.HOST_TYPE);
    Feature feature = type.getFeatureByBaseName("f1");

    AnnotationFS clickedFs = CurationTestUtils.makeLinkHostMultiSPanFeatureFS(jcasA, 0, 0, feature, "A",
            CurationTestUtils.makeLinkFS(jcasA, "slot1", 0, 0));

    JCas mergeCAs = JCasFactory
            .createJCas(CurationTestUtils.createMultiLinkWithRoleTestTypeSystem("f1"));

    CurationTestUtils.makeLinkHostMultiSPanFeatureFS(mergeCAs, 0, 0, feature, "C",
            CurationTestUtils.makeLinkFS(mergeCAs, "slot1", 0, 0));

    sut.mergeSpanAnnotation(null, null, slotLayer, mergeCAs.getCas(), clickedFs, true);

    assertEquals(2, selectCovered(mergeCAs.getCas(), type, 0, 0).size());
}
 
Example #17
Source File: AutomationUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static Map<Integer, String> getMultipleAnnotation(
        AnnotationSchemaService aAnnotationService, AnnotationFS sentence,
        AnnotationFeature aFeature)
    throws CASException
{
    SpanAdapter adapter = (SpanAdapter) aAnnotationService.getAdapter(aFeature.getLayer());
    Map<Integer, String> multAnno = new HashMap<>();
    Type type = getType(sentence.getCAS(), adapter.getAnnotationTypeName());
    for (AnnotationFS fs : selectCovered(type, sentence)) {
        boolean isBegin = true;
        Feature labelFeature = fs.getType().getFeatureByBaseName(aFeature.getName());
        for (AnnotationFS token : selectTokensCovered(fs)) {
            if (multAnno.get(getAddr(token)) == null) {
                if (isBegin) {
                    multAnno.put(getAddr(token),
                            "B-" + fs.getFeatureValueAsString(labelFeature));
                    isBegin = false;
                }
                else {
                    multAnno.put(getAddr(token),
                            "I-" + fs.getFeatureValueAsString(labelFeature));
                }
            }
        }
    }
    return multAnno;
}
 
Example #18
Source File: CasUtil.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
/**
 * Get a list of annotations of the given annotation type constraint by a certain annotation.
 * Iterates over all annotations of the given type to find the covered annotations. Does not use
 * subiterators and does not respect type prioritites. Was adapted from {@link Subiterator}. Uses
 * the same approach except that type priorities are ignored.
 * <p>
 * <b>Note:</b> this is significantly slower than using
 * {@link #selectCovered(CAS, Type, AnnotationFS)}. It is possible to use
 * {@code  selectCovered(cas, type, new Annotation(jCas, int, int))}, but that will allocate memory
 * in the jCas for the new annotation. If you do that repeatedly many times, memory may fill up.
 * <p>
 * The method only returns properly covered annotations, that is annotations where the begin/end
 * offsets are equal to the given begin/end or where both the begin/end are included in
 * the span of the given span. Partially overlapping annotations are not returned.
 * 
 * @param cas
 *          a CAS.
 * @param type
 *          a UIMA type.
 * @param begin
 *          begin offset.
 * @param end
 *          end offset.
 * @return a return value.
 * @see Subiterator
 * @see <a href="package-summary.html#SortOrder">Order of selected feature structures</a>
 */
public static List<AnnotationFS> selectCovered(CAS cas, Type type, int begin, int end) {

  List<AnnotationFS> list = new ArrayList<AnnotationFS>();
  
  // withSnapshotIterators() not needed here since we copy the FSes to a list anyway    
  FSIterator<AnnotationFS> it = cas.getAnnotationIndex(type).iterator();

  // Skip annotations whose start is before the start parameter.
  while (it.isValid() && (it.get()).getBegin() < begin) {
    it.moveToNext();
  }

  boolean strict = true;
  while (it.isValid()) {
    AnnotationFS a = it.get();
    // If the start of the current annotation is past the end parameter, we're done.
    if (a.getBegin() > end) {
      break;
    }
    it.moveToNext();
    if (strict && a.getEnd() > end) {
      continue;
    }

    assert (a.getBegin() >= begin) : "Illegal begin " + a.getBegin() + " in [" + begin + ".."
            + end + "]";

    assert (a.getEnd() <= end) : "Illegal end " + a.getEnd() + " in [" + begin + ".." + end + "]";

    list.add(a);
  }

  return list;
}
 
Example #19
Source File: WebAnnoTsv3WriterTestBase.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiTokenStackedSlotFeature() throws Exception
{
    JCas jcas = makeJCasOneSentence();
    CAS cas = jcas.getCas();
    
    List<Token> tokens = new ArrayList<>(select(jcas, Token.class));
    
    Token t1 = tokens.get(0);
    Token t2 = tokens.get(1);
    Token t3 = tokens.get(2);
    
    Type type = cas.getTypeSystem().getType("webanno.custom.SimpleSpan");
    AnnotationFS s2 = cas.createAnnotation(type, t2.getBegin(), t3.getEnd());
    cas.addFsToIndexes(s2);
    AnnotationFS s3 = cas.createAnnotation(type, t2.getBegin(), t3.getEnd());
    cas.addFsToIndexes(s3);

    FeatureStructure link1 = makeLinkFS(jcas, "p1", s2);
    FeatureStructure link2 = makeLinkFS(jcas, "p2", s3);
    
    makeLinkHostFS(jcas, t1.getBegin(), t1.getEnd(), link1, link2);
    
    writeAndAssertEquals(jcas, 
            WebannoTsv3Writer.PARAM_SLOT_FEATS, asList("webanno.custom.SimpleLinkHost:links"),
            WebannoTsv3Writer.PARAM_SPAN_LAYERS, asList("webanno.custom.SimpleSpan", 
                    "webanno.custom.SimpleLinkHost"),
            WebannoTsv3Writer.PARAM_LINK_TYPES, asList("webanno.custom.LinkType"),
            WebannoTsv3Writer.PARAM_SLOT_TARGETS, asList("webanno.custom.SimpleSpan"));
}
 
Example #20
Source File: FsIndex_annotation.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
@Override
public FSIterator<T> subiterator(AnnotationFS annot, boolean ambiguous, boolean strict) {
  return new Subiterator<>(iterator(),
      (Annotation) annot,
      ambiguous,
      strict,
      BoundsUse.coveredBy,  // isBounded 
      true,  // uses type priority
      true  // skip returning results equal to annot
  );
}
 
Example #21
Source File: NamedEntityLinker.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void predict(RecommenderContext aContext, CAS aCas) throws RecommendationException
{
    Type predictedType = getPredictedType(aCas);

    for (AnnotationFS sentence : selectSentences(aCas)) {
        for (AnnotationFS annotation : CasUtil.selectCovered(aCas, predictedType, sentence)) {
            int begin = annotation.getBegin();
            int end = annotation.getEnd();
            predictSingle(annotation.getCoveredText(), begin, end, aCas);
        }
    }
}
 
Example #22
Source File: CasMerge.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static boolean existsSameAt(CAS aCas, AnnotationFS aFs)
{
    return CasUtil.selectAt(aCas, aFs.getType(), aFs.getBegin(), aFs.getEnd()).stream()
            .filter(cand -> isEquivalentAnnotation(aFs, cand))
            .findAny()
            .isPresent();
}
 
Example #23
Source File: WebannoTsv3Writer.java    From webanno with Apache License 2.0 5 votes vote down vote up
private boolean isMultiToken(AnnotationFS aFs)
{

    for (AnnotationUnit unit : units) {
        if (unit.begin <= aFs.getBegin() && unit.end > aFs.getBegin()
                && unit.end < aFs.getEnd()) {
            return true;
        }
    }
    return false;
}
 
Example #24
Source File: ConcurrentTokenizer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void postProcessAnnotations(Span[] tokens, AnnotationFS[] tokenAnnotations) {
    // if interest
    if (probabilityFeature != null) {
        double tokenProbabilties[] = tokenizer.getTokenProbabilities();

        for (int i = 0; i < tokenAnnotations.length; i++) {
            tokenAnnotations[i].setDoubleValue(probabilityFeature, tokenProbabilties[i]);
        }
    }
}
 
Example #25
Source File: WideLeftAnnotationSideAction.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Decreases the begin index of an annotation by one.
 */
@Override
public void run() {
  AnnotationSelection annotations = new AnnotationSelection(getStructuredSelection());

  AnnotationFS annotation = annotations.getFirst();
  
  wideLeftAnnotationSide(editor.getDocument(), annotation);
}
 
Example #26
Source File: WebannoTsv3Writer.java    From webanno with Apache License 2.0 5 votes vote down vote up
private AnnotationUnit getFirstUnit(AnnotationFS targetFs)
{
    SubTokenAnno sta = new SubTokenAnno();
    sta.setBegin(targetFs.getBegin());
    sta.setEnd(targetFs.getEnd());
    sta.setText(targetFs.getCoveredText());
    Set<AnnotationUnit> sus = new LinkedHashSet<>();
    AnnotationUnit firstUnit = null;
    for (AnnotationUnit u : getSubUnits(sta, sus)) {
        firstUnit = u;
        break;
    }
    return firstUnit;
}
 
Example #27
Source File: CasMerge.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static List<AnnotationFS> selectCandidateRelationsAt(CAS aTargetCas,
        AnnotationFS aSourceFs, AnnotationFS aSourceOriginFs, AnnotationFS aSourceTargetFs)
{
    Type type = aSourceFs.getType();
    Feature sourceFeat = type.getFeatureByBaseName(WebAnnoConst.FEAT_REL_SOURCE);
    Feature targetFeat = type.getFeatureByBaseName(WebAnnoConst.FEAT_REL_TARGET);
    return selectCovered(aTargetCas, type, aSourceFs.getBegin(), aSourceFs.getEnd()).stream()
            .filter(fs -> fs.getFeatureValue(sourceFeat).equals(aSourceOriginFs)
                    && fs.getFeatureValue(targetFeat).equals(aSourceTargetFs))
            .collect(Collectors.toList());
}
 
Example #28
Source File: ImageSidebar.java    From inception with Apache License 2.0 5 votes vote down vote up
public void actionJumpTo(AjaxRequestTarget aTarget, ImageHandle aHandle)
{
    try {
        AnnotatorState state = getModelObject();
        
        // Get the CAS
        CAS cas = getCasProvider().get();
        
        AnnotationFS fs = WebAnnoCasUtil.selectAnnotationByAddr(cas, aHandle.getVid().getId());

        AnnotationLayer layer = annotationService.findLayer(state.getProject(), fs);
        if (SPAN_TYPE.equals(layer.getType())) {
            state.getSelection().selectSpan(aHandle.getVid(), cas, aHandle.getBegin(),
                    aHandle.getEnd());
        }
        else if (RELATION_TYPE.equals(layer.getType())) {
            RelationAdapter adapter = (RelationAdapter) annotationService.getAdapter(layer);
            AnnotationFS originFS = FSUtil.getFeature(fs, adapter.getSourceFeatureName(),
                    AnnotationFS.class);
            AnnotationFS targetFS = FSUtil.getFeature(fs, adapter.getTargetFeatureName(),
                    AnnotationFS.class);
            state.getSelection().selectArc(aHandle.getVid(), originFS, targetFS);
        }
        else {
            return;
        }
        
        actionShowSelectedDocument(aTarget, aHandle.getDocument(), aHandle.getBegin(),
                aHandle.getEnd());
        aTarget.add((Component) getActionHandler());
    }
    catch (IOException e) {
        error("Unable to select annotation: " + e.getMessage());
        LOG.error("Unable to select annotation", e);
    }
}
 
Example #29
Source File: AbstractAnnotationDocumentListener.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Remove notification.
 *
 * @param structures the structures
 */
@Override
public void removed(Collection<FeatureStructure> structures) {
  Collection<AnnotationFS> annotations = filterAnnotations(structures);

  if (!annotations.isEmpty()) {
    removedAnnotation(annotations);
  }
}
 
Example #30
Source File: DocumentUimaImpl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves annotations of the given type from the {@link CAS}.
 *
 * @param type the type
 * @return the annotations
 */
@Override
public Collection<AnnotationFS> getAnnotations(Type type) {
  FSIndex<AnnotationFS> annotationIndex = mCAS.getAnnotationIndex(type);

  StrictTypeConstraint typeConstrain = new StrictTypeConstraint(type);

  FSIterator<AnnotationFS> strictTypeIterator = mCAS
          .createFilteredIterator(annotationIndex.iterator(), typeConstrain);

  return fsIteratorToCollection(strictTypeIterator);
}