org.apache.uima.cas.Feature Java Examples

The following examples show how to use org.apache.uima.cas.Feature. 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: FeatureUtilsTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Test
public void testStringArrayToObject() {
  DocumentAnnotation da = (DocumentAnnotation) jCas.getDocumentAnnotationFs();
  StringArray rel = new StringArray(jCas, 3);
  rel.set(0, "true");
  rel.set(1, "2");
  rel.set(2, "0.45");
  da.setDocumentReleasability(rel);

  Feature f = da.getType().getFeatureByBaseName(DOCUMENT_RELEASABILITY);

  Object[] o = FeatureUtils.featureToArray(f, da);
  assertEquals(3, o.length);
  assertTrue(o[0] instanceof Boolean);
  assertTrue((Boolean) o[0]);
  assertTrue(o[1] instanceof Integer);
  assertEquals(new Integer(2), (Integer) o[1]);
  assertTrue(o[2] instanceof Double);
  assertEquals(new Double(0.45), (Double) o[2]);
}
 
Example #2
Source File: CASArtifact.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
CASArtifact(
    @Nullable LabelAdapters labelAdapters, CAS cas
) {
  this.labelAdapters = labelAdapters;
  this.cas = cas;

  TypeSystem typeSystem = cas.getTypeSystem();
  metadataType = typeSystem.getType("ArtifactMetadata");
  keyFeature = metadataType.getFeatureByBaseName("key");
  valueFeature = metadataType.getFeatureByBaseName("value");

  metadataCas = cas.getView("metadata");
  Type idType = typeSystem.getType("ArtifactID");
  Feature idFeat = idType.getFeatureByBaseName("artifactID");
  FSIndexRepository indexRepository = metadataCas.getIndexRepository();
  artifactID = indexRepository.getIndex("artifactID", idType).iterator().get()
      .getStringValue(idFeat);
  metadataIndex = indexRepository.getIndex("metadata", metadataType);

  casMetadata = new CASMetadata();
}
 
Example #3
Source File: RunAE.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Entity process complete.
 *
 * @param aCas the a cas
 * @param aStatus the a status
 * @see org.apache.uima.collection.StatusCallbackListener#entityProcessComplete(org.apache.uima.cas.CAS,
 *      org.apache.uima.collection.EntityProcessStatus)
 */
@Override
public void entityProcessComplete(CAS aCas, EntityProcessStatus aStatus) {
  if (aStatus.isException()) {
    Iterator iter = aStatus.getExceptions().iterator();
    while (iter.hasNext()) {
      ((Throwable) iter.next()).printStackTrace();
    }
  } else if (genProgressMessages) {
    // retrieve the filename of the input file from the CAS
    // (it was put there by the FileSystemCollectionReader)
    if (!(xcasInput || xmiInput)) {
      Type fileLocType = aCas.getTypeSystem().getType(
              "org.apache.uima.examples.SourceDocumentInformation");
      Feature fileNameFeat = fileLocType.getFeatureByBaseName("uri");
      FSIterator it = aCas.getAnnotationIndex(fileLocType).iterator();
      FeatureStructure fileLoc = it.get();
      File inFile = new File(fileLoc.getStringValue(fileNameFeat));
      System.out.println("Processed Document " + inFile.getName());
    } else {
      System.out.println("doc" + docsProcessed++ + " processed successfully");
    }
  }
}
 
Example #4
Source File: CasOutputDestination.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
@Override
public void controlWordEncountered(KeywordAction keywordAction) {
  AnnotationFS annotation;
  int currentTextIndex = sofaBuilder.length();
  String controlWord = keywordAction.getControlWord();

  Type type;
  if (annotationTypeForControlWord.containsKey(controlWord)) {
    type = annotationTypeForControlWord.get(controlWord);
  } else {
    return;
  }
  annotation = destinationView.createAnnotation(type, currentTextIndex,
      currentTextIndex);
  Feature paramFeature = type.getFeatureByBaseName("param");
  if (keywordAction.hasParameter()) {
    annotation.setIntValue(paramFeature, keywordAction.getParameter());
  }
  Feature indexFeature = type.getFeatureByBaseName("index");
  annotation.setIntValue(indexFeature, keywordAction.getBegin());
  Feature knownFeature = type.getFeatureByBaseName("known");
  annotation.setBooleanValue(knownFeature, true);

  destinationView.addFsToIndexes(annotation);
}
 
Example #5
Source File: ConstraintsVerifier.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Override
public boolean verify(FeatureStructure featureStructure, ParsedConstraints parsedConstraints)
{

    boolean isOk = false;
    Type type = featureStructure.getType();
    for (Feature feature : type.getFeatures()) {
        if (feature.getRange().isPrimitive()) {
            String scopeName = featureStructure.getFeatureValueAsString(feature);
            List<Rule> rules = parsedConstraints.getScopeByName(scopeName).getRules();

            // Check if all the feature values are ok according to the
            // rules;
        }
        else {
            // Here some recursion would be in order
        }
    }
    return isOk;
}
 
Example #6
Source File: CasDoctorUtils.java    From webanno with Apache License 2.0 6 votes vote down vote up
/**
 * Recursively collect referenced FSes and also record for each the last indexed FS that refers
 * the them.
 */
public static void collect(Map<FeatureStructure, FeatureStructure> aFSes,
        Set<FeatureStructure> aIndexed, FeatureStructure aFS, FeatureStructure aLastIndexed)
{
    if (aFS != null && !aFSes.containsKey(aFS)) {
        // We might find an annotation indirectly. In that case make sure we consider it as 
        // an indexed annotation instead of wrongly recording it as non-indexed
        if (aIndexed.contains(aFS)) {
            aFSes.put(aFS, aFS);
        }
        else {
            aFSes.put(aFS, aLastIndexed);
        }

        for (Feature f : aFS.getType().getFeatures()) {
            if (!f.getRange().isPrimitive()
                    && !CAS.FEATURE_BASE_NAME_SOFA.equals(f.getShortName())) {
                collect(aFSes, aIndexed, aFS.getFeatureValue(f),
                        aIndexed.contains(aFS) ? aFS : aLastIndexed);
            }
        }
    }
}
 
Example #7
Source File: StringMatchingRecommender.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public void predict(RecommenderContext aContext, CAS aCas) throws RecommendationException
{
    Trie<DictEntry> dict = aContext.get(KEY_MODEL).orElseThrow(() -> 
            new RecommendationException("Key [" + KEY_MODEL + "] not found in context"));

    Type predictedType = getPredictedType(aCas);
    Feature predictedFeature = getPredictedFeature(aCas);
    Feature isPredictionFeature = getIsPredictionFeature(aCas);
    Feature scoreFeature = getScoreFeature(aCas);

    List<Sample> data = predict(0, aCas, dict);
    
    for (Sample sample : data) {
        for (Span span : sample.getSpans()) {
            AnnotationFS annotation = aCas.createAnnotation(predictedType, span.getBegin(),
                    span.getEnd());
            annotation.setStringValue(predictedFeature, span.getLabel());
            annotation.setDoubleValue(scoreFeature, span.getScore());
            annotation.setBooleanValue(isPredictionFeature, true);
            aCas.addFsToIndexes(annotation);
        }
    }
}
 
Example #8
Source File: RelationAdapter.java    From webanno with Apache License 2.0 6 votes vote down vote up
private AnnotationFS createRelationAnnotation(CAS cas, AnnotationFS originFS,
        AnnotationFS targetFS)
    throws AnnotationException
{
    if (targetFS == null || originFS == null) {
        throw new IllegalPlacementException("Relation must have a source and a target!");
    }

    // Set the relation offsets in DKPro Core style - the relation recieves the offsets from
    // the dependent
    // If origin and target spans are multiple tokens, dependentFS.getBegin will be the
    // the begin position of the first token and dependentFS.getEnd will be the End
    // position of the last token.
    final Type type = getType(cas, getLayer().getName());
    final Feature dependentFeature = type.getFeatureByBaseName(targetFeatureName);
    final Feature governorFeature = type.getFeatureByBaseName(sourceFeatureName);

    AnnotationFS newAnnotation = cas.createAnnotation(type, targetFS.getBegin(),
            targetFS.getEnd());
    newAnnotation.setFeatureValue(dependentFeature, targetFS);
    newAnnotation.setFeatureValue(governorFeature, originFS);
    cas.addFsToIndexes(newAnnotation);
    return newAnnotation;
}
 
Example #9
Source File: AutomationUtil.java    From webanno with Apache License 2.0 6 votes vote down vote up
private static List<String> getAnnotation(TypeAdapter aAdapter, AnnotationFS aSentence,
        AnnotationFeature aFeature)
{
    CAS cas = aSentence.getCAS();
    
    Type type = getType(cas, aAdapter.getAnnotationTypeName());
    List<String> annotations = new ArrayList<>();

    for (AnnotationFS token : selectTokensCovered(aSentence)) {
        List<AnnotationFS> tokenLevelAnnotations = selectCovered(type, token);
        if (tokenLevelAnnotations.size() > 0) {
            AnnotationFS anno = tokenLevelAnnotations.get(0);
            Feature labelFeature = anno.getType().getFeatureByBaseName(aFeature.getName());
            annotations.add(anno.getFeatureValueAsString(labelFeature));
        }
        else {
            annotations.add(NILL);
        }
    }
    return annotations;
}
 
Example #10
Source File: DebugFSLogicalStructure.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public static Object integerListToArray(FeatureStructure fs) {
  List<Integer> list = new ArrayList<>();
  TypeSystem ts = fs.getCAS().getTypeSystem();
  Type emptyFSList = ts.getType("uima.cas.EmptyIntegerList");
  Feature headFeature = ts.getFeatureByFullName("uima.cas.NonEmptyIntegerList:head");
  Feature tailFeature = ts.getFeatureByFullName("uima.cas.NonEmptyIntegerList:tail");

  Set<FeatureStructure> alreadySeen = new HashSet<>();
  FeatureStructure nextFs;
  for (FeatureStructure currentFs = fs; currentFs.getType() != emptyFSList; currentFs = nextFs) {
    list.add(currentFs.getIntValue(headFeature));
    nextFs = currentFs.getFeatureValue(tailFeature);
    if (alreadySeen.contains(nextFs)) {
      return loopInList(list);
    }
    alreadySeen.add(nextFs);
  }
  int[] intArray = new int[list.size()];
  for (int i = 0; i < intArray.length; i++) {
    intArray[i] = list.get(i);
  }
  return intArray;
}
 
Example #11
Source File: RunAE.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Entity process complete.
 *
 * @param aCas the a cas
 * @param aStatus the a status
 * @see org.apache.uima.collection.StatusCallbackListener#entityProcessComplete(org.apache.uima.cas.CAS,
 *      org.apache.uima.collection.EntityProcessStatus)
 */
public void entityProcessComplete(CAS aCas, EntityProcessStatus aStatus) {
  if (aStatus.isException()) {
    Iterator iter = aStatus.getExceptions().iterator();
    while (iter.hasNext()) {
      ((Throwable) iter.next()).printStackTrace();
    }
  } else if (genProgressMessages) {
    // retrieve the filename of the input file from the CAS
    // (it was put there by the FileSystemCollectionReader)
    if (!(xcasInput || xmiInput)) {
      Type fileLocType = aCas.getTypeSystem().getType(
              "org.apache.uima.examples.SourceDocumentInformation");
      Feature fileNameFeat = fileLocType.getFeatureByBaseName("uri");
      FSIterator it = aCas.getAnnotationIndex(fileLocType).iterator();
      FeatureStructure fileLoc = it.get();
      File inFile = new File(fileLoc.getStringValue(fileNameFeat));
      System.out.println("Processed Document " + inFile.getName());
    } else {
      System.out.println("doc" + docsProcessed++ + " processed successfully");
    }
  }
}
 
Example #12
Source File: JCasDeserialiser.java    From baleen with Apache License 2.0 6 votes vote down vote up
private void populateFeaturesForAnnotation(
    final JCas jCas,
    final BaleenAnnotation annotation,
    final Map<String, Object> map,
    final List<ReferencedFeatures> featuresToDereference) {
  for (final Feature f : annotation.getType().getFeatures()) {
    try {
      populateFeature(jCas, map, annotation, f, featuresToDereference);
    } catch (final Exception e) {
      getMonitor()
          .warn(
              "Couldn't populate {} to map. Type '{}' isn't supported.",
              f.getName(),
              f.getRange().getShortName(),
              e);
    }
  }
}
 
Example #13
Source File: FeatureUtilsTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullArrayValue() {
  DocumentAnnotation da = (DocumentAnnotation) jCas.getDocumentAnnotationFs();
  da.setDocumentReleasability(null);

  Feature f = da.getType().getFeatureByBaseName(DOCUMENT_RELEASABILITY);

  Object[] o = FeatureUtils.featureToArray(f, da);
  assertEquals(0, o.length);
}
 
Example #14
Source File: CasMergeTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Test
public void multiLinkMultiSpanRoleDiffTest()
    throws Exception
{
    JCas jcasA = createJCas(createMultiLinkWithRoleTestTypeSystem("f1"));
    Type type = jcasA.getTypeSystem().getType(HOST_TYPE);
    Feature feature = type.getFeatureByBaseName("f1");

    makeLinkHostMultiSPanFeatureFS(jcasA, 0, 0, feature, "A",
            makeLinkFS(jcasA, "slot1", 0, 0));

    JCas jcasB = createJCas(createMultiLinkWithRoleTestTypeSystem("f1"));
    makeLinkHostMultiSPanFeatureFS(jcasB, 0, 0, feature, "A",
            makeLinkFS(jcasB, "slot2", 0, 0));

    Map<String, List<CAS>> casByUser = new LinkedHashMap<>();
    casByUser.put("user1", asList(jcasA.getCas()));
    casByUser.put("user2", asList(jcasB.getCas()));

    JCas curatorCas = createJCas(createMultiLinkWithRoleTestTypeSystem("f1"));
    curatorCas.setDocumentText(casByUser.values().stream().flatMap(Collection::stream)
            .findFirst().get().getDocumentText());

    DiffResult result = doDiff(diffAdapters, LINK_TARGET_AS_LABEL, casByUser).toResult();

    // result.print(System.out);

    sut.reMergeCas(result, document, null, curatorCas.getCas(), getSingleCasByUser(casByUser));

    Type hostType = curatorCas.getTypeSystem().getType(HOST_TYPE);

    assertThat(select(curatorCas.getCas(), hostType))
            .hasSize(1);
}
 
Example #15
Source File: FeatureUtilsTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testLong() {
  Entity e = new Entity(jCas);
  e.setInternalId(123456789);
  e.addToIndexes();

  Feature f = e.getType().getFeatureByBaseName("internalId");

  Object o = FeatureUtils.featureToObject(f, e);
  assertTrue(o instanceof Long);
  assertEquals(new Long(123456789), (Long) o);
}
 
Example #16
Source File: FeatureUtilsTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testInteger() {
  Entity e = new Entity(jCas);
  e.setBegin(5);
  e.addToIndexes();

  Feature f = e.getType().getFeatureByBaseName("begin");

  Object o = FeatureUtils.featureToObject(f, e);
  assertTrue(o instanceof Integer);
  assertEquals(new Integer(5), (Integer) o);
}
 
Example #17
Source File: FeatureUtilsTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testString() {
  Entity e = new Entity(jCas);
  e.setValue("Test Value");
  e.addToIndexes();

  Feature f = e.getType().getFeatureByBaseName("value");

  Object o = FeatureUtils.featureToObject(f, e);
  assertTrue(o instanceof String);
  assertEquals("Test Value", (String) o);
}
 
Example #18
Source File: FSCollectionFactory.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static <T extends TOP> FSList<T> createFSList(CAS aCas, Collection<T> aValues) {
  if (aValues == null) {
    return null;
  }
  
  TypeSystem ts = aCas.getTypeSystem();

  if (aValues.size() == 0) {
    return aCas.emptyFSList();
  }
  
  Type nonEmptyType = ts.getType(CAS.TYPE_NAME_NON_EMPTY_FS_LIST);
  Feature headFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_HEAD);
  Feature tailFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_TAIL);

  FeatureStructure head = aCas.createFS(nonEmptyType);
  FeatureStructure list = head;
  Iterator<? extends FeatureStructure> i = aValues.iterator();
  while (i.hasNext()) {
    head.setFeatureValue(headFeature, i.next());
    if (i.hasNext()) {
      FeatureStructure tail = aCas.createFS(nonEmptyType);
      head.setFeatureValue(tailFeature, tail);
      head = tail;
    } else {
      head.setFeatureValue(tailFeature, aCas.emptyFSList());
    }
  }

  return (FSList<T>) list;
}
 
Example #19
Source File: XmiCompare.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
void canonicalizeStringFirstVariant(String t, String f, String v, CASImpl cas) {
  TypeSystem ts = cas.getTypeSystem();
  Type type = ts.getType(t);
  Feature feat = ts.getFeatureByFullName(t + ":" + f);
  Feature featv = ts.getFeatureByFullName(t + ":" + v);  // v is the variant array
  cas.select(type).allViews().forEach(fs ->
    { StringArray sa = (StringArray) fs.getFeatureValue(featv);
      if (sa != null && sa.size() > 2) {
        String item = fs.getStringValue(feat);
        if (sa.contains(item)) {
          fs.setStringValue(feat, sa.get(0));
        }
      }
    });
}
 
Example #20
Source File: FSUtil.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
private static Feature getMandatoryFeature(FeatureStructure aFS, String aFeature)
{
  Feature feat = aFS.getType().getFeatureByBaseName(aFeature);
  
  if (feat == null) {
    throw new IllegalArgumentException("Type [" + aFS.getType() + "] has no feature with name ["
            + aFeature + "]");
  }
  
  return feat;
}
 
Example #21
Source File: CasCompare.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
private void mismatchFs(TOP fs1, TOP fs2, Feature fi, Feature fi2) {
  if (isSkipMismatch) return;

  Pair<TOP, TOP> pair = new Pair<>(fs1, fs2);
  if (prevReport.contains(pair)) {
    if (leafErrorReported == null) {
      leafErrorReported = pair;
    }
    return; // already reported
  }
  prevReport.add(pair);
  
  if (leafErrorReported == null) {

    leafErrorReported = pair;
    String mapmsg = fi.equals(fi2) 
                      ? ""
                      : "which mapped to target feature " + fi2.getShortName() + " ";
    mismatchSb.append(String.format("Mismatched Feature Structures in feature %s %s%n %s%n %s%n", 
        fi.getShortName(), mapmsg, ps(fs1), ps(fs2)));
  } else {
    TOP ofs1 = leafErrorReported.t;
    TOP ofs2 = leafErrorReported.u;
    String s1 = String.format("  from: %s:%d, %s:%d", fs1.getType().getShortName(), fs1._id, fs2.getType().getShortName(), fs2._id);
    s1maxLen = Math.max(s1.length() + 4, s1maxLen);
    mismatchSb.append(String.format("%-"+s1maxLen+"s   original mismatch: %s:%d, %s, %d%n", s1,
        ofs1.getType().getShortName(), ofs1._id, ofs2.getType().getShortName(), ofs2._id));
  }
}
 
Example #22
Source File: Tsv3XCasSchemaAnalyzer.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static boolean isChainLayer(Type aType)
{
    boolean hasTypeFeature = aType.getFeatureByBaseName(COREFERENCE_TYPE_FEATURE) != null;
    boolean hasRelationFeature = aType
            .getFeatureByBaseName(COREFERENCE_RELATION_FEATURE) != null;
    boolean nameEndsInLink = aType.getName().endsWith("Link");

    boolean compatible = true;
    for (Feature feat : aType.getFeatures()) {
        if (
                CAS.FEATURE_BASE_NAME_SOFA.equals(feat.getShortName()) ||
                CHAIN_NEXT_FEAT.equals(feat.getShortName()) || 
                COREFERENCE_TYPE_FEATURE.equals(feat.getShortName()) || 
                COREFERENCE_RELATION_FEATURE.equals(feat.getShortName())
        ) {
            continue;
        }
        
        if (!isPrimitiveFeature(feat)) {
            compatible = false;
            LOG.debug("Incompatible feature in type [" + aType + "]: " + feat);
            break;
        }
    }

    return hasTypeFeature && hasRelationFeature && nameEndsInLink && compatible;
}
 
Example #23
Source File: NewFeatureUtilsTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testLong() {
  Entity e = new Entity(jCas);
  e.setInternalId(12345);
  e.addToIndexes();
  Feature feature = e.getType().getFeatureByBaseName("internalId");
  NewFeatureUtils.setPrimitive(e, feature, 54321);
  assertEquals(54321, e.getLongValue(feature));
}
 
Example #24
Source File: IndexRepositoryTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testRemovalSpeed() throws Exception {
    // create an instance of an annotation type
    Feature beginFeat = this.typeSystem.getFeatureByFullName(CASTestSetup.TOKEN_TYPE + ":begin");
    Type fsType = this.typeSystem.getType(CASTestSetup.TOKEN_TYPE);
    FeatureStructure[] fsa = new FeatureStructure[NBR_ITEMS];
    // create 40000 tokens
    for (int i = 0; i < fsa.length; i++) {
      fsa[i] = this.cas.createFS(fsType);
      fsa[i].setIntValue(beginFeat,  i);
    }
    
    // warmup and jit
    timeAdd2Indexes(fsa, false);
    timeRemoveFromIndexes(fsa);
    
    long a2i = timeAdd2Indexes(fsa, false);
    long rfi = timeRemoveFromIndexes(fsa);
    
    long a2i2 = timeAdd2Indexes(fsa, false);
    long rfir = timeRemoveFromIndexesReverse(fsa);
    
    System.out.format("Timing add/remv from indexes: add1: %,d microsec, add2: %,d microsec, rmv: %,d microsec, rmvReversed: %,d microsec%n", 
        a2i/1000, a2i2/1000, rfi/1000, rfir/1000);
// big loop for doing profiling by hand and checking space recovery by hand   
    
//    for (int i = 0; i < 10000; i++) {
//      timeAdd2Indexes(fsa);
//      timeRemoveFromIndexesReverse(fsa);
//    }
  }
 
Example #25
Source File: CasMerge.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void copyFeatures(SourceDocument aDocument, String aUsername, TypeAdapter aAdapter,
        FeatureStructure aTargetFS, FeatureStructure aSourceFs)
    throws AnnotationException
{
    // Cache the feature list instead of hammering the database
    List<AnnotationFeature> features = featureCache.computeIfAbsent(aAdapter.getLayer(),
        key -> schemaService.listSupportedFeatures(key));
    for (AnnotationFeature feature : features) {
        Type sourceFsType = aAdapter.getAnnotationType(aSourceFs.getCAS());
        Feature sourceFeature = sourceFsType.getFeatureByBaseName(feature.getName());

        if (sourceFeature == null) {
            throw new IllegalStateException("Target CAS type [" + sourceFsType.getName()
                    + "] does not define a feature named [" + feature.getName() + "]");
        }

        if (shouldIgnoreFeatureOnMerge(aSourceFs, sourceFeature)) {
            continue;
        }

        Object value = aAdapter.getFeatureValue(feature, aSourceFs);
        
        try {
            aAdapter.setFeatureValue(aDocument, aUsername, aTargetFS.getCAS(),
                    getAddr(aTargetFS), feature, value);
        }
        catch (IllegalArgumentException e) {
            // This happens e.g. if the value we try to set is not in the tagset and the tagset
            // cannot be extended.
            throw new IllegalFeatureValueException("Cannot set value of feature ["
                    + feature.getUiName() + "] to [" + value + "]: " + e.getMessage(), e);
        }
    }
}
 
Example #26
Source File: CASArtifact.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
CASArtifact(
    @Nullable LabelAdapters labelAdapters,
    Artifact artifact,
    CAS cas
) {
  this.labelAdapters = labelAdapters;
  this.cas = cas;

  TypeSystem typeSystem = cas.getTypeSystem();
  metadataType = typeSystem.getType("ArtifactMetadata");
  keyFeature = metadataType.getFeatureByBaseName("key");
  valueFeature = metadataType.getFeatureByBaseName("value");

  metadataCas = cas.createView("metadata");
  metadataCas.setDocumentText("");

  Type idType = typeSystem.getType("ArtifactID");
  Feature idFeat = idType.getFeatureByBaseName("artifactID");
  this.artifactID = artifact.getArtifactID();
  FeatureStructure documentIdFs = metadataCas.createFS(idType);
  documentIdFs.setStringValue(idFeat, artifactID);
  metadataCas.addFsToIndexes(documentIdFs);
  metadataIndex = metadataCas.getIndexRepository().getIndex("metadata", metadataType);

  casMetadata = new CASMetadata();
  casMetadata.putAll(artifact.getMetadata());

  copyDocuments(artifact);
}
 
Example #27
Source File: FSCollectionFactory.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
public static <T extends FeatureStructure> T createFloatList(CAS aCas, Collection<Float> aValues) {
  if (aValues == null) {
    return null;
  }
  
  TypeSystem ts = aCas.getTypeSystem();

  Type emptyType = ts.getType(CAS.TYPE_NAME_EMPTY_FLOAT_LIST);

  if (aValues.size() == 0) {
    return aCas.createFS(emptyType);
  }
  
  Type nonEmptyType = ts.getType(CAS.TYPE_NAME_NON_EMPTY_FLOAT_LIST);
  Feature headFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_HEAD);
  Feature tailFeature = nonEmptyType.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_TAIL);

  FeatureStructure head = aCas.createFS(nonEmptyType);
  FeatureStructure list = head;
  Iterator<Float> i = aValues.iterator();
  while (i.hasNext()) {
    head.setFloatValue(headFeature, i.next());
    if (i.hasNext()) {
      FeatureStructure tail = aCas.createFS(nonEmptyType);
      head.setFeatureValue(tailFeature, tail);
      head = tail;
    } else {
      head.setFeatureValue(tailFeature, aCas.createFS(emptyType));
    }
  }

  return (T) list;
}
 
Example #28
Source File: FeatureCopiers.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
/**
 * {@code FeatureCopier} used for features which are references to {@code FeatureStructure}s.
 *
 * @param fromFeature the {@link Feature}
 * @param fromFs the {@link FeatureStructure} to copy from
 * @param toFs the {@link FeatureStructure} to copy to
 */
private void defaultFeatureMapper(Feature fromFeature, FeatureStructure fromFs,
    FeatureStructure toFs) {
  TypeSystem typeSystem = fromFs.getCAS().getTypeSystem();
  if (typeSystem.subsumes(typeSystem.getType(CAS.TYPE_NAME_STRING), fromFeature.getRange())) {
    STRING_COPIER.copy(fromFeature, fromFs, toFs);
  } else {
    FeatureStructure fromFeatureValue = fromFs.getFeatureValue(fromFeature);
    if (fromFeatureValue != null) {
      FeatureStructure toFeatureValue = fsEncounteredCallback.apply(fromFeatureValue);
      Feature toFeature = toFs.getType().getFeatureByBaseName(fromFeature.getShortName());
      toFs.setFeatureValue(toFeature, toFeatureValue);
    }
  }
}
 
Example #29
Source File: AutomationUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static void clearAnnotations(CAS aCas, AnnotationFeature aFeature)
    throws IOException
{
    // Check if annotation layer is attached to another layer
    String attachTypeName = aFeature.getLayer().getAttachType() == null ? null : aFeature
            .getLayer().getAttachType().getName();
    Type attachType = null;
    Feature attachFeature = null;
    if (attachTypeName != null) {
        attachType = CasUtil.getType(aCas, attachTypeName);
        attachFeature = attachType
                .getFeatureByBaseName(aFeature.getLayer().getAttachFeature().getName());
    }
    
    List<AnnotationFS> annotationsToRemove = new ArrayList<>();
    Type type = CasUtil.getType(aCas, aFeature.getLayer().getName());
    annotationsToRemove.addAll(select(aCas, type));
    
    for (AnnotationFS annotation : annotationsToRemove) {
        if (attachFeature != null) {
            // Unattach the annotation to be removed
            for (AnnotationFS attach : selectCovered(attachType, annotation)) {
                FeatureStructure existing = attach.getFeatureValue(attachFeature);
                if (annotation.equals(existing)) {
                    attach.setFeatureValue(attachFeature, null);
                }
            }
        }
        aCas.removeFsFromIndexes(annotation);
    }
}
 
Example #30
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());
}