Java Code Examples for org.apache.uima.cas.text.AnnotationFS#getEnd()

The following examples show how to use org.apache.uima.cas.text.AnnotationFS#getEnd() . 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: WebAnnoCasUtil.java    From webanno with Apache License 2.0 6 votes vote down vote up
/**
 * Return true if these two annotations agree on every non slot features
 */
public static boolean isEquivalentAnnotation(AnnotationFS aFs1, AnnotationFS aFs2)
{
    // Check offsets (because they are excluded by shouldIgnoreFeatureOnMerge())
    if (aFs1.getBegin() != aFs2.getBegin() || aFs1.getEnd() != aFs2.getEnd()) {
        return false;
    }
    
    // Check the features (basically limiting to the primitive features)
    for (Feature f : aFs1.getType().getFeatures()) {
        if (shouldIgnoreFeatureOnMerge(aFs1, f)) {
            continue;
        }

        Object value1 = getFeatureValue(aFs1, f);
        Object value2 = getFeatureValue(aFs2, f);
        
        if (!Objects.equals(value1, value2)) {
            return false;
        }
    }
    return true;
}
 
Example 2
Source File: Subiterator.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
static Comparator<AnnotationFS> getAnnotationBeginEndComparator(final int boundingBegin, final int boundingEnd) {
  return new Comparator<AnnotationFS>() {

    @Override
    public int compare(AnnotationFS o1, AnnotationFS o2) {
      AnnotationFS a = (o1 == null) ? o2 : o1;
      boolean isReverse = o1 == null;
      final int b;
      if ((b = a.getBegin()) < boundingBegin) {
        return isReverse? 1 : -1;
      }
      if (b > boundingBegin) {
        return isReverse? -1 : 1;
      }
      
      final int e;
      if ((e = a.getEnd()) < boundingEnd) {
        return isReverse? -1 : 1;
      }
      if (e > boundingEnd) {
        return isReverse? 1 : -1;
      }
      return 0;
    }
  };
}
 
Example 3
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 4
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 5
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 6 votes vote down vote up
/**
 * Get overlapping annotations where selection overlaps with annotations.<br>
 * Example: if annotation is (5, 13) and selection covered was from (7, 12); the annotation (5,
 * 13) is returned as overlapped selection <br>
 * If multiple annotations are [(3, 8), (9, 15), (16, 21)] and selection covered was from (10,
 * 18), overlapped annotation [(9, 15), (16, 21)] should be returned
 *
 * @param aCas
 *            a CAS containing the annotation.
 * @param aType
 *            a UIMA type.
 * @param aBegin
 *            begin offset.
 * @param aEnd
 *            end offset.
 * @return a return value.
 */
public static List<AnnotationFS> selectOverlapping(CAS aCas,
        Type aType, int aBegin, int aEnd)
{

    List<AnnotationFS> annotations = new ArrayList<>();
    for (AnnotationFS t : select(aCas, aType)) {
        if (t.getBegin() >= aEnd) {
            break;
        }
        // not yet there
        if (t.getEnd() <= aBegin) {
            continue;
        }
        annotations.add(t);
    }

    return annotations;
}
 
Example 6
Source File: ParagraphAnnotator.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
@Override
public void process(CAS aCAS) {
  LOGGER.trace("Annotating rtf paragraphs.");
  CAS systemView = aCAS.getView(documentName);

  Type newParagraphType = systemView.getTypeSystem()
      .getType("biomedicus.v2.rtf.NewParagraph");

  Type paragraphType = systemView.getTypeSystem()
      .getType("biomedicus.v2.Paragraph");

  AnnotationIndex<AnnotationFS> newParagraphIndex = systemView
      .getAnnotationIndex(newParagraphType);
  int start = 0;

  for (AnnotationFS newParagraph : newParagraphIndex) {
    int end = newParagraph.getEnd();
    systemView.addFsToIndexes(
        systemView.createAnnotation(paragraphType, start, end));

    start = end;
  }
}
 
Example 7
Source File: RelationOffsetsRepair.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public void repair(Project aProject, CAS aCas, List<LogMessage> aMessages)
{
    List<AnnotationFS> fixedRels = new ArrayList<>();
    for (AnnotationLayer layer : annotationService.listAnnotationLayer(aProject)) {
        if (!WebAnnoConst.RELATION_TYPE.equals(layer.getType())) {
            continue;
        }

        Type type;
        try {
            type = getType(aCas, layer.getName());
        }
        catch (IllegalArgumentException e) {
            // If the type does not exist, the CAS has not been upgraded. In this case, we
            // can skip checking the layer because there will be no annotations anyway.
            continue;
        }
        
        for (AnnotationFS rel : select(aCas, type)) {
            AnnotationFS target = getFeature(rel, WebAnnoConst.FEAT_REL_TARGET,
                    AnnotationFS.class);
            if ((rel.getBegin() != target.getBegin()) || (rel.getEnd() != target.getEnd())) {
                fixedRels.add(rel);
                setFeature(rel, CAS.FEATURE_BASE_NAME_BEGIN, target.getBegin());
                setFeature(rel, CAS.FEATURE_BASE_NAME_END, target.getEnd());
            }
        }
        
        // Delete those relations that pointed to deleted spans
        if (!fixedRels.isEmpty()) {
            aMessages.add(new LogMessage(this, LogLevel.INFO,
                    "Fixed the offsets of [%d] relations in layer [" + layer.getName() + "].",
                    fixedRels.size()));
        }
    }
}
 
Example 8
Source File: WideRightAnnotationSideAction.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Wide right annotation side.
 *
 * @param document the document
 * @param annotation the annotation
 */
public static void wideRightAnnotationSide(ICasDocument document, AnnotationFS annotation) {
  Type annotationType = annotation.getType();
  Feature endFeature = annotationType.getFeatureByBaseName("end");
  
  if (annotation.getEnd() < document.getCAS().getDocumentText().length()) {
    annotation.setIntValue(endFeature, annotation.getEnd() + 1);
  }
  
  document.update(annotation);
}
 
Example 9
Source File: SuggestionBuilder.java    From webanno with Apache License 2.0 5 votes vote down vote up
/**
 * Get a sentence at the end of an annotation
 */
private static AnnotationFS getSentenceByAnnoEnd(List<AnnotationFS> aSentences, int aEnd)
{
    int prevEnd = 0;
    AnnotationFS sent = null;
    for (AnnotationFS sentence : aSentences) {
        if (prevEnd >= aEnd) {
            return sent;
        }
        sent = sentence;
        prevEnd = sent.getEnd();
    }
    return sent;
}
 
Example 10
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 11
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
/**
 * Get the current sentence based on the annotation begin/end offset
 *
 * @param aCas
 *            the CAS.
 * @param aBegin
 *            the begin offset.
 * @param aEnd
 *            the end offset.
 * @return the sentence.
 */
public static AnnotationFS getCurrentSentence(CAS aCas, int aBegin, int aEnd)
{
    AnnotationFS currentSentence = null;
    for (AnnotationFS sentence : selectSentences(aCas)) {
        if (sentence.getBegin() <= aBegin && sentence.getEnd() > aBegin
                && sentence.getEnd() <= aEnd) {
            currentSentence = sentence;
            break;
        }
    }
    return currentSentence;
}
 
Example 12
Source File: WebAnnoCasUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
/**
 * Get the  sentence based on the annotation begin offset
 *
 * @param aCas
 *            the CAS.
 * @param aBegin
 *            the begin offset.
 * @return the sentence.
 */
public static AnnotationFS selectSentenceCovering(CAS aCas, int aBegin)
{
    AnnotationFS currentSentence = null;
    for (AnnotationFS sentence : select(aCas, getType(aCas, Sentence.class))) {
        if (sentence.getBegin() <= aBegin && sentence.getEnd() > aBegin) {
            currentSentence = sentence;
            break;
        }
    }
    return currentSentence;
}
 
Example 13
Source File: RelationDiffAdapter.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public Position getPosition(int aCasId, FeatureStructure aFS, String aFeature, String aRole,
        int aLinkTargetBegin, int aLinkTargetEnd, LinkCompareBehavior aLinkCompareBehavior)
{
    Type type = aFS.getType();
    AnnotationFS sourceFS = (AnnotationFS) aFS.getFeatureValue(type
            .getFeatureByBaseName(sourceFeature));
    AnnotationFS targetFS = (AnnotationFS) aFS.getFeatureValue(type
            .getFeatureByBaseName(targetFeature));
    
    String collectionId = null;
    String documentId = null;
    try {
        FeatureStructure dmd = WebAnnoCasUtil.getDocumentMetadata(aFS.getCAS());
        collectionId = FSUtil.getFeature(dmd, "collectionId", String.class);
        documentId = FSUtil.getFeature(dmd, "documentId", String.class);
    }
    catch (IllegalArgumentException e) {
        // We use this information only for debugging - so we can ignore if the information
        // is missing.
    }
    
    String linkTargetText = null;
    if (aLinkTargetBegin != -1 && aFS.getCAS().getDocumentText() != null) {
        linkTargetText = aFS.getCAS().getDocumentText()
                .substring(aLinkTargetBegin, aLinkTargetEnd);
    }
    
    return new RelationPosition(collectionId, documentId, aCasId, getType(), 
            sourceFS != null ? sourceFS.getBegin() : -1,
            sourceFS != null ? sourceFS.getEnd() : -1,
            sourceFS != null ? sourceFS.getCoveredText() : null,
            targetFS != null ? targetFS.getBegin() : -1,
            targetFS != null ? targetFS.getEnd() : -1,
            targetFS != null ? targetFS.getCoveredText() : null,
            aFeature, aRole, aLinkTargetBegin, aLinkTargetEnd, linkTargetText,
            aLinkCompareBehavior);
}
 
Example 14
Source File: RelationOffsetsCheck.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
public boolean check(Project aProject, CAS aCas, List<LogMessage> aMessages)
{
    boolean ok = true;
    
    for (AnnotationLayer layer : annotationService.listAnnotationLayer(aProject)) {
        if (!WebAnnoConst.RELATION_TYPE.equals(layer.getType())) {
            continue;
        }

        Type type;
        try {
            type = getType(aCas, layer.getName());
        }
        catch (IllegalArgumentException e) {
            // If the type does not exist, the CAS has not been upgraded. In this case, we
            // can skip checking the layer because there will be no annotations anyway.
            continue;
        }
        
        for (AnnotationFS rel : select(aCas, type)) {
            AnnotationFS target = getFeature(rel, WebAnnoConst.FEAT_REL_TARGET,
                    AnnotationFS.class);
            if ((rel.getBegin() != target.getBegin()) || (rel.getEnd() != target.getEnd())) {
                aMessages.add(new LogMessage(this, LogLevel.ERROR,
                        "Relation offsets [%d,%d] to not match target offsets [%d,%d]",
                        rel.getBegin(), rel.getEnd(), target.getBegin(), target.getEnd()));
                ok = false;
            }
        }
    }

    return ok;
}
 
Example 15
Source File: LowerLeftAnnotationSideAction.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Lower left annotation side.
 *
 * @param document the document
 * @param annotation the annotation
 */
public static void lowerLeftAnnotationSide(ICasDocument document, AnnotationFS annotation) {
  Type annotationType = annotation.getType();
  Feature beginFeature = annotationType.getFeatureByBaseName("begin");

  if (annotation.getBegin() < annotation.getEnd()) {
    annotation.setIntValue(beginFeature, annotation.getBegin() + 1);
  }

  document.update(annotation);
}
 
Example 16
Source File: SentenceOrientedPagingStrategy.java    From webanno with Apache License 2.0 5 votes vote down vote up
private Unit toUnit(int aIndex, AnnotationFS aSentence)
{
    // If there is a sentence ID, then make it accessible to the user via a sentence-level
    // comment.
    String sentId = FSUtil.getFeature(aSentence, "id", String.class);
    return new Unit(sentId, aIndex, aSentence.getBegin(), aSentence.getEnd());
}
 
Example 17
Source File: SymbolIndexedDocument.java    From biomedicus with Apache License 2.0 4 votes vote down vote up
/**
 * Indexes all the symbols from an original document.
 *
 * @param originalDocumentView jCas original document view.
 * @return The newly created symbol indexed document.
 */
public static SymbolIndexedDocument fromView(CAS originalDocumentView) {
  Type viewIndexType = originalDocumentView.getTypeSystem()
      .getType("edu.umn.biomedicus.rtfuima.type.ViewIndex");

  Feature destinationNameFeature = viewIndexType
      .getFeatureByBaseName("destinationName");
  Feature destinationIndexFeature = viewIndexType
      .getFeatureByBaseName("destinationIndex");

  AnnotationIndex<AnnotationFS> viewIndexAI = originalDocumentView
      .getAnnotationIndex(viewIndexType);

  List<SymbolLocation> symbolLocations = new ArrayList<>();

  Map<String, Map<Integer, Integer>> destinationMap = new HashMap<>();

  int index = 0;
  int lastEnd = 0;
  for (AnnotationFS annotation : viewIndexAI) {
    int begin = annotation.getBegin();
    int end = annotation.getEnd();

    String destinationName
        = annotation.getStringValue(destinationNameFeature);

    SymbolLocation symbolLocation = new SymbolLocation(
        destinationName,
        begin - lastEnd,
        end - begin,
        index++
    );

    symbolLocations.add(symbolLocation);

    int destinationIndex
        = annotation.getIntValue(destinationIndexFeature);

    destinationMap.compute(destinationName,
        (String key, @Nullable Map<Integer, Integer> value) -> {
          if (value == null) {
            value = new HashMap<>();
          }
          value.put(destinationIndex, symbolLocations.size() - 1);

          return value;
        });
    lastEnd = end;
  }
  return new SymbolIndexedDocument(symbolLocations, destinationMap,
      originalDocumentView.getDocumentText());
}
 
Example 18
Source File: TokenDrawingStrategy.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
@Override
public void draw(Annotation annotation, GC gc, StyledText textWidget, int offset, int length,
        Color color) {
  if (length > 0) {
    if (annotation instanceof EclipseAnnotationPeer) {
      AnnotationFS annotationFS = ((EclipseAnnotationPeer) annotation).getAnnotationFS();
      if (gc != null) {
        Rectangle bounds = textWidget.getTextBounds(offset, offset + length - 1);

        gc.setForeground(color);

        boolean isDrawOpenBracket = annotationFS.getBegin() == offset;
        // and no space before offset
        if (isDrawOpenBracket && offset > 1 && !isWhitespace(annotationFS.getCAS().getDocumentText(), offset - 1)) {
          gc.drawLine(bounds.x, bounds.y + bounds.height - 1, bounds.x + BRACKET_WIDTH, bounds.y
                  + bounds.height - 1);

          gc.drawLine(bounds.x, bounds.y, bounds.x, bounds.y + bounds.height - 1);

          gc.drawLine(bounds.x, bounds.y, bounds.x + BRACKET_WIDTH, bounds.y);
        }

        boolean isDrawCloseBracket = annotationFS.getEnd() == offset + length;
        // and no space after offset
        if (isDrawCloseBracket && offset + length < textWidget.getText().length()
                && !isWhitespace(annotationFS.getCAS().getDocumentText(), offset + length)) {
          gc.drawLine(bounds.x + bounds.width, bounds.y + bounds.height - 1, bounds.x
                  + bounds.width - BRACKET_WIDTH, bounds.y + bounds.height - 1);

          gc.drawLine(bounds.x + bounds.width - 1, bounds.y, bounds.x + bounds.width - 1,
                  bounds.y + bounds.height - 1);

          gc.drawLine(bounds.x + bounds.width, bounds.y, bounds.x + bounds.width - BRACKET_WIDTH,
                  bounds.y);
        }
      } else {
        textWidget.redrawRange(offset, length, true);
      }
    }
  }
}
 
Example 19
Source File: BlueCasUtil.java    From bluima with Apache License 2.0 4 votes vote down vote up
/**
 * REM: modified from CasUtils..
 * 
 * Get a list of annotations constraint by a certain annotation. Iterates
 * over all annotations 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.
 * 
 * @param cas
 *            a CAS.
 * @param coveringAnnotation
 *            the covering annotation.
 * @see Subiterator
 */
public static List<Annotation> selectCovered(CAS cas,
        AnnotationFS coveringAnnotation) {
    final int begin = coveringAnnotation.getBegin();
    final int end = coveringAnnotation.getEnd();

    final List<Annotation> list = new ArrayList<Annotation>();
    final FSIterator<AnnotationFS> it = cas.getAnnotationIndex().iterator();

    // Try to seek the insertion point.
    it.moveTo(coveringAnnotation);

    // If the insertion point is beyond the index, move back to the last.
    if (!it.isValid()) {
        it.moveToLast();
        if (!it.isValid()) {
            return list;
        }
    }

    // Ignore type priorities by seeking to the first that has the same
    // begin
    boolean moved = false;
    while (it.isValid() && (it.get()).getBegin() >= begin) {
        it.moveToPrevious();
        moved = true;
    }

    // If we moved, then we are now on one starting before the requested
    // begin, so we have to
    // move one ahead.
    if (moved) {
        it.moveToNext();
    }

    // If we managed to move outside the index, start at first.
    if (!it.isValid()) {
        it.moveToFirst();
    }

    // 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 (!(a instanceof Annotation))
            continue;

        // 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;
        }

        checkArgument(a.getBegin() >= coveringAnnotation.getBegin(),
                "Illegal begin " + a.getBegin() + " in ["
                        + coveringAnnotation.getBegin() + ".."
                        + coveringAnnotation.getEnd() + "]");
        checkArgument(
                a.getEnd() <= coveringAnnotation.getEnd(),
                "Illegal end " + a.getEnd() + " in ["
                        + coveringAnnotation.getBegin() + ".."
                        + coveringAnnotation.getEnd() + "]");

        if (!a.equals(coveringAnnotation) && !BlueCasUtil.isDocAnnot(a)) {
            list.add((Annotation) a);
        }
    }
    return unmodifiableList(list);
}
 
Example 20
Source File: ContainingConstraint.java    From uima-uimaj with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if is containing.
 *
 * @param annotation the annotation
 * @param containing the containing
 * @return true, if is containing
 */
private boolean isContaining(AnnotationFS annotation, AnnotationFS containing) {
  return containing.getBegin() <= annotation.getBegin()
      && containing.getEnd() >= annotation.getEnd();
}