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

The following examples show how to use org.apache.uima.cas.text.AnnotationFS#setStringValue() . 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: 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 2
Source File: CasMergeTest.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleCopyToDiffExistingAnnoWithStackingTest()
    throws Exception
{
    neLayer.setOverlapMode(OverlapMode.ANY_OVERLAP);

    CAS jcas = createJCas().getCas();
    Type type = jcas.getTypeSystem().getType(NamedEntity.class.getTypeName());
    AnnotationFS clickedFs = createNEAnno(jcas, "NN", 0, 0);

    CAS mergeCAs = createJCas().getCas();
    createTokenAnno(mergeCAs, 0, 0);
    AnnotationFS existingFs = mergeCAs.createAnnotation(type, 0, 0);
    Feature posValue = type.getFeatureByBaseName("value");
    existingFs.setStringValue(posValue, "NE");
    mergeCAs.addFsToIndexes(existingFs);

    sut.mergeSpanAnnotation(null, null, neLayer, mergeCAs, clickedFs, true);

    assertEquals(2, selectCovered(mergeCAs, type, 0, 0).size());
}
 
Example 3
Source File: CasMergeTest.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleCopyToDiffExistingAnnoWithNoStackingTest()
    throws Exception
{
    CAS jcas = createJCas().getCas();
    Type type = jcas.getTypeSystem().getType(POS.class.getTypeName());
    AnnotationFS clickedFs = createPOSAnno(jcas, "NN", 0, 0);

    CAS mergeCAs = createJCas().getCas();
    AnnotationFS existingFs = mergeCAs.createAnnotation(type, 0, 0);
    Feature posValue = type.getFeatureByBaseName("PosValue");
    existingFs.setStringValue(posValue, "NE");
    mergeCAs.addFsToIndexes(existingFs);

    sut.mergeSpanAnnotation(null, null, posLayer, mergeCAs, clickedFs, false);

    assertEquals(1, CasUtil.selectCovered(mergeCAs, type, 0, 0).size());
}
 
Example 4
Source File: CasMergeTest.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleCopyToSameExistingAnnoTest()
    throws Exception
{
    CAS jcas = createJCas().getCas();
    Type type = jcas.getTypeSystem().getType(POS.class.getTypeName());
    AnnotationFS clickedFs = createPOSAnno(jcas, "NN", 0, 0);

    CAS mergeCas = createJCas().getCas();
    AnnotationFS existingFs = mergeCas.createAnnotation(type, 0, 0);
    Feature posValue = type.getFeatureByBaseName("PosValue");
    existingFs.setStringValue(posValue, "NN");
    mergeCas.addFsToIndexes(existingFs);

    Assertions.assertThatExceptionOfType(AnnotationException.class)
            .isThrownBy(() -> sut.mergeSpanAnnotation(null, null, posLayer, mergeCas, 
                    clickedFs, false))
            .withMessageContaining("annotation already exists");
}
 
Example 5
Source File: DiffTestUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static AnnotationFS makeLinkHostMultiSPanFeatureFS(JCas aCas, int aBegin, int aEnd,
        Feature aSpanFeature, String aValue, FeatureStructure... aLinks)
{
    Type hostType = aCas.getTypeSystem().getType(HOST_TYPE);
    AnnotationFS hostA1 = aCas.getCas().createAnnotation(hostType, aBegin, aEnd);
    hostA1.setFeatureValue(hostType.getFeatureByBaseName("links"),
            FSCollectionFactory.createFSArray(aCas, asList(aLinks)));
    hostA1.setStringValue(aSpanFeature, aValue);
    aCas.getCas().addFsToIndexes(hostA1);
    return hostA1;
}
 
Example 6
Source File: AgreementTestUtils.java    From webanno with Apache License 2.0 5 votes vote down vote up
public static AnnotationFS makeLinkHostMultiSPanFeatureFS(JCas aCas, int aBegin, int aEnd,
        Feature aSpanFeature, String aValue, FeatureStructure... aLinks)
{
    Type hostType = aCas.getTypeSystem().getType(HOST_TYPE);
    AnnotationFS hostA1 = aCas.getCas().createAnnotation(hostType, aBegin, aEnd);
    hostA1.setFeatureValue(hostType.getFeatureByBaseName("links"),
            FSCollectionFactory.createFSArray(aCas, asList(aLinks)));
    hostA1.setStringValue(aSpanFeature, aValue);
    aCas.getCas().addFsToIndexes(hostA1);
    return hostA1;
}
 
Example 7
Source File: CasMergeTest.java    From webanno with Apache License 2.0 5 votes vote down vote up
private AnnotationFS createNEAnno(CAS aCas, String aValue, int aBegin, int aEnd)
{
    Type type = aCas.getTypeSystem().getType(NamedEntity.class.getTypeName());
    AnnotationFS clickedFs = aCas.createAnnotation(type, aBegin, aEnd);
    Feature value = type.getFeatureByBaseName("value");
    clickedFs.setStringValue(value, aValue);
    aCas.addFsToIndexes(clickedFs);
    return clickedFs;
}
 
Example 8
Source File: DataMajorityNerRecommender.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override
public void predict(RecommenderContext aContext, CAS aCas) throws RecommendationException
{
    DataMajorityModel model = aContext.get(KEY_MODEL).orElseThrow(() ->
            new RecommendationException("Key [" + KEY_MODEL + "] not found in context"));

    // Make the predictions
    Type tokenType = CasUtil.getAnnotationType(aCas, Token.class);
    Collection<AnnotationFS> candidates = CasUtil.select(aCas, tokenType);
    List<Annotation> predictions = predict(candidates, model);

    // Add predictions to the CAS
    Type predictedType = getPredictedType(aCas);
    Feature scoreFeature = getScoreFeature(aCas);
    Feature scoreExplanationFeature = getScoreExplanationFeature(aCas);
    Feature predictedFeature = getPredictedFeature(aCas);
    Feature isPredictionFeature = getIsPredictionFeature(aCas);

    for (Annotation ann : predictions) {
        AnnotationFS annotation = aCas.createAnnotation(predictedType, ann.begin, ann.end);
        annotation.setStringValue(predictedFeature, ann.label);
        annotation.setDoubleValue(scoreFeature, ann.score);
        annotation.setStringValue(scoreExplanationFeature, ann.explanation);
        annotation.setBooleanValue(isPredictionFeature, true);
        aCas.addFsToIndexes(annotation);
    }
}
 
Example 9
Source File: NewPrimitiveTypesTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testClone() throws Exception {
  createExampleFS(cas);
  // get the example FS
  CAS englishView = cas.getView("EnglishDocument");
  FSIterator iter = englishView.getAnnotationIndex().iterator();
  // skip document annotation
  iter.moveToNext();
  // the exampleType fs
  AnnotationFS fs = (AnnotationFS) iter.get();

  // clone it
  AnnotationFS clone = (AnnotationFS) fs.clone();

  // substitute the clone for the original in the index,
  // and validate that it was correctly copied
  englishView.removeFsFromIndexes(fs);
  englishView.addFsToIndexes(clone);
  validateFSData(cas);

  // editing the original FS should not change the clone
  englishView.removeFsFromIndexes(fs);  // does nothing, is not in the index, the clone is
  fs.setStringValue(stringFeature, "foo");
  fs.setFloatValue(floatFeature, -1f);
  fs.setByteValue(byteFeature, (byte) -1);
  fs.setBooleanValue(booleanFeature, false);
  fs.setShortValue(shortFeature, (short) -1);
  fs.setLongValue(longFeature, -1);
  fs.setDoubleValue(doubleFeature, -1);
  fs.setBegin(clone.getBegin() + 1);  // to be sure that fs is beyond the original
  englishView.addFsToIndexes(fs);  // will add, is no longer "equal" to the clone
  validateFSData(cas);
}
 
Example 10
Source File: ExternalRecommenderIntegrationTest.java    From inception with Apache License 2.0 5 votes vote down vote up
private void createNamedEntity(CAS aCas, String aValue)
{
    Type neType = getType(aCas, "de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity");
    Feature valueFeature = neType.getFeatureByBaseName("value");
    AnnotationFS ne = aCas.createAnnotation(neType, 0, 42);
    ne.setStringValue(valueFeature, aValue);
    aCas.addFsToIndexes(ne);
}
 
Example 11
Source File: FilteredIteratorTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testIterator2() {
    try {
      cas.setDocumentText("This is a test with the word \"the\" in it.");

      // create token and sentence annotations
      String type1 = "type1";
      String type2 = "type2";
      AnnotationFS token;
      token = cas.createAnnotation(tokenType, 0, 4);
      token.setStringValue(lemmaFeat, type1);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 5, 7);
      token.setStringValue(lemmaFeat, "the");
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 8, 9);
      token.setStringValue(lemmaFeat, type2);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 10, 14);
      token.setStringValue(lemmaFeat, type1);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 14, 15);
      token.setStringValue(lemmaFeat, type1);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 0, 15);
      token.setStringValue(lemmaFeat, type1);
      cas.getIndexRepository().addFS(token);

      iterAndCount2();
      
//      expandBeyondFlatThreshold(6);  // enables flat iterator
      iterAndCount2();
          
    } catch (Exception e) {
      e.printStackTrace();
      fail();
    }
  }
 
Example 12
Source File: ComplexTypeTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Test
public void testCountryType()
    throws Exception
{

    TypeSystemDescription tsd = TypeSystemDescriptionFactory
            .createTypeSystemDescription("desc.types.TestTypeSystemDescriptor");

    CAS cas = CasCreationUtils.createCas(tsd, null, null);
    cas.setDocumentText("Asia is the largest continent on Earth. Asia is subdivided into 48 "
            + "countries, two of them (Russia and Turkey) having part of their land in "
            + "Europe. The most active place on Earth for tropical cyclone activity lies "
            + "northeast of the Philippines and south of Japan. The Gobi Desert is in "
            + "Mongolia and the Arabian Desert stretches across much of the Middle East. "
            + "The Yangtze River in China is the longest river in the continent. The "
            + "Himalayas between Nepal and China is the tallest mountain range in the "
            + "world. Tropical rainforests stretch across much of southern Asia and "
            + "coniferous and deciduous forests lie farther north.");
    TypeSystem ts = cas.getTypeSystem();
    Type continentType = ts.getType("de.Continent");
    Feature continentName = continentType.getFeatureByBaseName("name");
    AnnotationFS asiaContinent = cas.createAnnotation(continentType, 0, 4);
    asiaContinent.setStringValue(continentName, "Asia");
    cas.addFsToIndexes(asiaContinent);

    Type countryType = ts.getType("de.Country");
    Feature countryName = countryType.getFeatureByBaseName("name");
    AnnotationFS russia = cas.createAnnotation(countryType, 56, 62);
    russia.setStringValue(countryName, "Russian Federation");
    Feature continentFeature = countryType.getFeatureByBaseName("continent");
    russia.setFeatureValue(continentFeature, asiaContinent);
    cas.addFsToIndexes(russia);

    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(russia,
            "regionType", constraints);

    List<PossibleValue> exValues = new LinkedList<>();
    exValues.add(new PossibleValue("cold", true));

    assertEquals(possibleValues, exValues);
}
 
Example 13
Source File: ComplexTypeTest.java    From webanno with Apache License 2.0 4 votes vote down vote up
@Test
public void testProfType()
    throws Exception
{
    TypeSystemDescription tsd = TypeSystemDescriptionFactory
            .createTypeSystemDescription("desc.types.TestTypeSystemDescriptor");

    CAS cas = CasCreationUtils.createCas(tsd, null, null);
    cas.setDocumentText("I listen to lectures by Prof. Gurevych sometimes.");

    TypeSystem ts = cas.getTypeSystem();
    Type profType = ts.getType("de.tud.Prof");
    Feature profNameFeature = profType.getFeatureByBaseName("fullName");
    Feature profBossFeature = profType.getFeatureByBaseName("boss");

    AnnotationFS proemel = cas.createAnnotation(profType, 0, 0);
    proemel.setStringValue(profNameFeature, "Hans Juergen Proeml");
    cas.addFsToIndexes(proemel);

    AnnotationFS gurevych = cas.createAnnotation(profType, 24, 38);
    gurevych.setStringValue(profNameFeature, "Iryna Gurevych");
    gurevych.setFeatureValue(profBossFeature, proemel);
    cas.addFsToIndexes(gurevych);

    /*
     * for (String feature : Arrays.asList("fullName", "boss")) { Feature someFeature =
     * gurevych.getType().getFeatureByBaseName(feature); if
     * (someFeature.getRange().isPrimitive()) { String value =
     * gurevych.getFeatureValueAsString(someFeature); System.out.println(value); } else {
     * FeatureStructure value = gurevych.getFeatureValue(someFeature);
     * System.out.printf("%s (%s)%n", value.getFeatureValueAsString(profNameFeature),
     * value.getType()); } }
     */

    ConstraintsGrammar parser = new ConstraintsGrammar(new FileInputStream(
            "src/test/resources/rules/prof.rules"));
    Parse p = parser.Parse();

    ParsedConstraints constraints = p.accept(new ParserVisitor());

    Evaluator constraintsEvaluator = new ValuesGenerator();

    List<PossibleValue> possibleValues = constraintsEvaluator.generatePossibleValues(gurevych,
            "professorName", constraints);

    List<PossibleValue> exValues = new LinkedList<>();
    exValues.add(new PossibleValue("Iryna Gurevych", false));

    assertEquals(possibleValues, exValues);

}
 
Example 14
Source File: FilteredIteratorTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testIterator2b() {
    try {
      cas.setDocumentText("This is a test with the word \"the\" in it.");

      FeatureStructure wordFS = this.cas.createFS(wordType);
      FeatureStructure sepFS = this.cas.createFS(sepType);
      FeatureStructure eosFS = this.cas.createFS(eosType);

      // create token and sentence annotations
      String type1 = "type1";
      String type2 = "type2";
      AnnotationFS token;
      token = cas.createAnnotation(tokenType, 0, 4);
      token.setStringValue(lemmaFeat, type1);
      token.setFeatureValue(tokenTypeFeat, wordFS);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 5, 7);
      token.setStringValue(lemmaFeat, "the");
      token.setFeatureValue(tokenTypeFeat, sepFS);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 8, 9);
      token.setStringValue(lemmaFeat, type2);
      token.setFeatureValue(tokenTypeFeat, eosFS);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 10, 14);
      token.setStringValue(lemmaFeat, type1);
      token.setFeatureValue(tokenTypeFeat, wordFS);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 14, 15);
      token.setStringValue(lemmaFeat, type1);
      token.setFeatureValue(tokenTypeFeat, sepFS);
      cas.getIndexRepository().addFS(token);
      token = cas.createAnnotation(tokenType, 0, 15);
      token.setStringValue(lemmaFeat, type1);
      token.setFeatureValue(tokenTypeFeat, eosFS);
      cas.getIndexRepository().addFS(token);

      iterAndCount2b();
      
//      expandBeyondFlatThreshold(6);  // enables flat iterator
      iterAndCount2b();
      
    } catch (Exception e) {
      e.printStackTrace();
      assertTrue(false);
    }
  }
 
Example 15
Source File: OpenNlpNerRecommender.java    From inception with Apache License 2.0 4 votes vote down vote up
@Override
public void predict(RecommenderContext aContext, CAS aCas) throws RecommendationException
{
    TokenNameFinderModel model = aContext.get(KEY_MODEL).orElseThrow(() -> 
            new RecommendationException("Key [" + KEY_MODEL + "] not found in context"));
    
    NameFinderME finder = new NameFinderME(model);

    Type sentenceType = getType(aCas, Sentence.class);
    Type tokenType = getType(aCas, Token.class);
    Type predictedType = getPredictedType(aCas);

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

    int predictionCount = 0;
    for (AnnotationFS sentence : select(aCas, sentenceType)) {
        if (predictionCount >= traits.getPredictionLimit()) {
            break;
        }
        predictionCount++;
        
        List<AnnotationFS> tokenAnnotations = selectCovered(tokenType, sentence);
        String[] tokens = tokenAnnotations.stream()
            .map(AnnotationFS::getCoveredText)
            .toArray(String[]::new);

        for (Span prediction : finder.find(tokens)) {
            String label = prediction.getType();
            if (NameSample.DEFAULT_TYPE.equals(label)) {
                continue;
            }
            int begin = tokenAnnotations.get(prediction.getStart()).getBegin();
            int end = tokenAnnotations.get(prediction.getEnd() - 1).getEnd();
            AnnotationFS annotation = aCas.createAnnotation(predictedType, begin, end);
            annotation.setStringValue(predictedFeature, label);
            annotation.setDoubleValue(scoreFeature, prediction.getProb());
            annotation.setBooleanValue(isPredictionFeature, true);

            aCas.addFsToIndexes(annotation);
        }
    }
}
 
Example 16
Source File: OpenNlpPosRecommender.java    From inception with Apache License 2.0 4 votes vote down vote up
@Override
    public void predict(RecommenderContext aContext, CAS aCas)
        throws RecommendationException
    {
        POSModel model = aContext.get(KEY_MODEL).orElseThrow(() -> 
                new RecommendationException("Key [" + KEY_MODEL + "] not found in context"));
        
        POSTaggerME tagger = new POSTaggerME(model);

        Type sentenceType = getType(aCas, Sentence.class);
        Type predictedType = getPredictedType(aCas);
        Type tokenType = getType(aCas, Token.class);

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

        int predictionCount = 0;
        for (AnnotationFS sentence : select(aCas, sentenceType)) {
            if (predictionCount >= traits.getPredictionLimit()) {
                break;
            }
            predictionCount++;
            
            List<AnnotationFS> tokenAnnotations = selectCovered(tokenType, sentence);
            String[] tokens = tokenAnnotations.stream()
                .map(AnnotationFS::getCoveredText)
                .toArray(String[]::new);

            Sequence[] bestSequences = tagger.topKSequences(tokens);

//            LOG.debug("Total number of sequences predicted: {}", bestSequences.length);

            for (int s = 0; s < Math.min(bestSequences.length, maxRecommendations); s++) {
                Sequence sequence = bestSequences[s];
                List<String> outcomes = sequence.getOutcomes();
                double[] probabilities = sequence.getProbs();

//                LOG.debug("Sequence {} score {}", s, sequence.getScore());
//                LOG.debug("Outcomes: {}", outcomes);
//                LOG.debug("Probabilities: {}", asList(probabilities));

                for (int i = 0; i < outcomes.size(); i++) {
                    String label = outcomes.get(i);

                    // Do not return PADded tokens
                    if (PAD.equals(label)) {
                        continue;
                    }

                    AnnotationFS token = tokenAnnotations.get(i);
                    int begin = token.getBegin();
                    int end = token.getEnd();
                    double confidence = probabilities[i];

                    // Create the prediction
                    AnnotationFS annotation = aCas.createAnnotation(predictedType, begin, end);
                    annotation.setStringValue(predictedFeature, label);
                    annotation.setDoubleValue(scoreFeature, confidence);
                    annotation.setBooleanValue(isPredictionFeature, true);
                    aCas.addFsToIndexes(annotation);
                }
            }
        }
    }
 
Example 17
Source File: CasAnnotationViewerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void createExampleFS(CAS cas) throws Exception {
  // Set the document text
  cas.setDocumentText("this beer is good");

  // create an FS of exampleType and index it
  AnnotationFS fs = cas.createAnnotation(exampleType, 1, 5);
  cas.getIndexRepository().addFS(fs);

  // create Array FSs
  StringArrayFS strArrayFS = cas.createStringArrayFS(5);
  strArrayFS.set(0, "zzzzzz");
  strArrayFS.set(1, "yyyyyy");
  strArrayFS.set(2, "xxxxxx");
  strArrayFS.set(3, "wwwwww");
  strArrayFS.set(4, "vvvvvv");

  IntArrayFS intArrayFS = cas.createIntArrayFS(5);
  intArrayFS.set(0, Integer.MAX_VALUE);
  intArrayFS.set(1, Integer.MAX_VALUE - 1);
  intArrayFS.set(2, 42);
  intArrayFS.set(3, Integer.MIN_VALUE + 1);
  intArrayFS.set(4, Integer.MIN_VALUE);

  FloatArrayFS floatArrayFS = cas.createFloatArrayFS(5);
  floatArrayFS.set(0, Float.MAX_VALUE);
  floatArrayFS.set(1, (float) (Float.MAX_VALUE / 1000.0));
  floatArrayFS.set(2, (float) 42);
  floatArrayFS.set(3, (float) (Float.MIN_VALUE * 1000.0));
  floatArrayFS.set(4, Float.MIN_VALUE);

  ByteArrayFS byteArrayFS = cas.createByteArrayFS(5);
  byteArrayFS.set(0, (byte) 8);
  byteArrayFS.set(1, (byte) 16);
  byteArrayFS.set(2, (byte) 64);
  byteArrayFS.set(3, (byte) 128);
  byteArrayFS.set(4, (byte) 255);

  BooleanArrayFS boolArrayFS = cas.createBooleanArrayFS(8);
  boolean val = false;
  for (int i = 0; i < 8; i++) {
    boolArrayFS.set(i, val = !val);
  }

  ShortArrayFS shortArrayFS = cas.createShortArrayFS(5);
  shortArrayFS.set(0, Short.MAX_VALUE);
  shortArrayFS.set(1, (short) (Short.MAX_VALUE - 1));
  shortArrayFS.set(2, (short) (Short.MAX_VALUE - 2));
  shortArrayFS.set(3, (short) (Short.MAX_VALUE - 3));
  shortArrayFS.set(4, (short) (Short.MAX_VALUE - 4));

  LongArrayFS longArrayFS = cas.createLongArrayFS(5);
  longArrayFS.set(0, Long.MAX_VALUE);
  longArrayFS.set(1, Long.MAX_VALUE - 1);
  longArrayFS.set(2, Long.MAX_VALUE - 2);
  longArrayFS.set(3, Long.MAX_VALUE - 3);
  longArrayFS.set(4, Long.MAX_VALUE - 4);

  DoubleArrayFS doubleArrayFS = cas.createDoubleArrayFS(5);
  doubleArrayFS.set(0, Double.MAX_VALUE);
  doubleArrayFS.set(1, Double.MIN_VALUE);
  doubleArrayFS.set(2, Double.parseDouble("1.5555"));
  doubleArrayFS.set(3, Double.parseDouble("99.000000005"));
  doubleArrayFS.set(4, Double.parseDouble("4.44444444444444444"));

  // set features of fs
  fs.setStringValue(stringFeature, "aaaaaaa");
  fs.setFloatValue(floatFeature, (float) 99.99);

  fs.setFeatureValue(intArrayFeature, intArrayFS);
  fs.setFeatureValue(floatArrayFeature, floatArrayFS);
  fs.setFeatureValue(stringArrayFeature, strArrayFS);

  // fs.setByteValue(byteFeature, Byte.MAX_VALUE);
  fs.setByteValue(byteFeature, (byte) 'z');
  fs.setFeatureValue(byteArrayFeature, byteArrayFS);
  fs.setBooleanValue(booleanFeature, true);
  fs.setFeatureValue(booleanArrayFeature, boolArrayFS);
  fs.setShortValue(shortFeature, Short.MIN_VALUE);
  fs.setFeatureValue(shortArrayFeature, shortArrayFS);
  fs.setLongValue(longFeature, Long.MIN_VALUE);
  fs.setFeatureValue(longArrayFeature, longArrayFS);
  fs.setDoubleValue(doubleFeature, Double.MAX_VALUE);
  fs.setFeatureValue(doubleArrayFeature, doubleArrayFS);

  cas.getIndexRepository().addFS(fs);
}
 
Example 18
Source File: CASImpl.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public <T extends Annotation> T createDocumentAnnotationNoRemoveNoIndex(int length) {
  final TypeSystemImpl ts = getTypeSystemImpl();
  AnnotationFS docAnnot = createAnnotation(ts.docType, 0, length);
  docAnnot.setStringValue(ts.langFeat, CAS.DEFAULT_LANGUAGE_NAME);
  return (T) docAnnot;    
}
 
Example 19
Source File: XmiCasDeserializerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void testDeltaCasIgnorePreexistingFS() throws Exception {
 try {
 CAS cas1 = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(),
         indexes);
  TypeSystem ts = cas1.getTypeSystem();
 CAS cas2 = CasCreationUtils.createCas(ts, new TypePriorities_impl(),
         indexes, null);
 cas1.setDocumentText("This is a test document in the initial view");
 AnnotationFS anAnnot1 = cas1.createAnnotation(cas1.getAnnotationType(), 0, 4);
 cas1.getIndexRepository().addFS(anAnnot1);
 AnnotationFS anAnnot2 = cas1.createAnnotation(cas1.getAnnotationType(), 5, 10);
 cas1.getIndexRepository().addFS(anAnnot2);
 FSIndex tIndex = cas1.getAnnotationIndex();
 assertTrue(tIndex.size() == 3); //doc annot plus  annots
 
 //serialize complete  
 XmiSerializationSharedData sharedData = new XmiSerializationSharedData();
 String xml = this.serialize(cas1, sharedData);
 int maxOutgoingXmiId = sharedData.getMaxXmiId();
 //deserialize into cas2
 XmiSerializationSharedData sharedData2 = new XmiSerializationSharedData();      
 //XmiCasDeserializer.deserialize(new StringBufferInputStream(xml), cas2, true, sharedData2);
 this.deserialize(xml, cas2, sharedData2, true, -1);
 CasComparer.assertEquals(cas1, cas2);
 
 //create Marker, add/modify fs and serialize in delta xmi format.
 Marker marker = cas2.createMarker();
 FSIndex<AnnotationFS> cas2tIndex = cas2.getAnnotationIndex();
 
 //create an annotation and add to index
 AnnotationFS cas2newAnnot = cas2.createAnnotation(cas2.getAnnotationType(), 6, 8);
 cas2.getIndexRepository().addFS(cas2newAnnot);
 assertTrue(cas2tIndex.size() == 4); // prev annots and this new one
 
 //modify an existing annotation
 Iterator<AnnotationFS> tIndexIter = cas2tIndex.iterator();
 AnnotationFS docAnnot = (AnnotationFS) tIndexIter.next(); //doc annot
 //delete from index
 AnnotationFS delAnnot = (AnnotationFS) tIndexIter.next(); //annot
 cas2.getIndexRepository().removeFS(delAnnot);
 assertTrue(cas2.getAnnotationIndex().size() == 3);
 
 //modify language feature
 Feature languageF2 = cas2.getDocumentAnnotation().getType().getFeatureByBaseName(CAS.FEATURE_BASE_NAME_LANGUAGE);
 docAnnot.setStringValue(languageF2, "en");
 // serialize cas2 in delta format 
 String deltaxml1 = serialize(cas2, sharedData2, marker);
 //System.out.println("delta cas");
 //System.out.println(deltaxml1);
 
 //deserialize delta xmi into cas1
 this.deserialize(deltaxml1, cas1, sharedData, true, maxOutgoingXmiId, AllowPreexistingFS.ignore);
 
 //check language feature of doc annot is not changed.
 //System.out.println(cas1.getDocumentAnnotation().getStringValue(languageF));
  Feature languageF1 = cas1.getDocumentAnnotation().getType().getFeatureByBaseName(CAS.FEATURE_BASE_NAME_LANGUAGE);

 assertTrue( cas1.getAnnotationIndex().iterator().next().getStringValue(languageF1).equals("x-unspecified"));
 //check new annotation exists and preexisting is not deleted
 assertTrue(cas1.getAnnotationIndex().size()==4);
 } catch (Exception e) {
 JUnitExtension.handleException(e);
 }
}
 
Example 20
Source File: PersonTitleAnnotator.java    From uima-uimaj with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an PersonTitle annotation in the CAS.
 * 
 * @param aCAS
 *          the CAS in which to create the annotation
 * @param aBeginPos
 *          the begin position of the annotation relative to the start of the document
 * @param aEndPos
 *          the end position of the annotation relative to the start of the document. (Note that,
 *          as in the Java string functions, the end position is one past the last character in
 *          the annotation, so that (end - begin) = length.
 * @param aTitleType
 *          the type of person title. This becomes the value of the <code>Kind</code> feature.
 */
protected void createAnnotation(CAS aCAS, int aBeginPos, int aEndPos, String aTitleType) {
  AnnotationFS title = aCAS.createAnnotation(mPersonTitleType, aBeginPos, aEndPos);
  // Set the "kind" feature if it's part of the ResultSpec
  if (getResultSpecification().containsFeature("example.PersonTitle:Kind",aCAS.getDocumentLanguage())) {
    title.setStringValue(mPersonTitleKindFeature, aTitleType);
  }
  // Add the annotation to the index.
  aCAS.getIndexRepository().addFS(title);
}