org.apache.uima.cas.CASException Java Examples

The following examples show how to use org.apache.uima.cas.CASException. 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: UimaSupport.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Remove an annotation to the JCas index, notifying UimaMonitor of the fact we have done so.
 *
 * <p>Relations that refer to the given annotation will also be removed.
 *
 * @param annotations Annotation(s) to remove
 */
public void remove(Collection<? extends Annotation> annotations) {
  for (Annotation annot : annotations) {

    if (annot instanceof Recordable) {
      try {
        addToHistory(
            annot.getCAS().getJCas(), HistoryEvents.createAdded((Recordable) annot, referrer));
      } catch (CASException e) {
        monitor.error("Unable to add to history on remove", e);
      }
    }

    if (annot instanceof Entity) {
      for (Relation r : getRelations((Entity) annot)) {
        monitor.entityRemoved(r.getType().getName());
        r.removeFromIndexes();
      }
    }

    monitor.entityRemoved(annot.getType().getName());

    annot.removeFromIndexes();
  }
}
 
Example #2
Source File: FSClassRegistry.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
private static void reportErrors() {
    boolean throwWhenDone = false;
    List<ErrorReport> es = errorSet.get();
    if (es != null) {
      StringBuilder msg = new StringBuilder(100);
//      msg.append('\n');  // makes a break in the message at the beginning, unneeded
      for (ErrorReport f : es) {
        msg.append(f.e.getMessage());
        throwWhenDone = throwWhenDone || f.doThrow;
        msg.append('\n');
      }
      errorSet.set(null); // reset after reporting
      if (throwWhenDone) {
        throw new CASRuntimeException(CASException.JCAS_INIT_ERROR, "\n" + msg);
      } else {
        Logger logger = UIMAFramework.getLogger();
        if (null == logger) {
          throw new CASRuntimeException(CASException.JCAS_INIT_ERROR, "\n" + msg);
        } else {
          logger.log(Level.WARNING, msg.toString());
        }          
      }
    }
  }
 
Example #3
Source File: CooccurrencesEvaluationAnnotator.java    From bluima with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
    String pmId = BlueCasUtil.getHeaderDocId(jCas);
    print("pmId " + pmId);

    JCas goldView, systemView;
    try {
        goldView = jCas.getView(VIEW_GOLD);
        systemView = jCas.getView(VIEW_SYSTEM);
    } catch (CASException e) {
        throw new AnalysisEngineProcessException(e);
    }

    Collection goldAnnot = select(goldView, Cooccurrence.class);
    Collection systAnnot = select(systemView, Cooccurrence.class);
    print("comparing #gold:" + goldAnnot.size() + " #sys:"
            + systAnnot.size());

    print(/* "pmId:"+pmId + "\t" + */evaluator.add(goldAnnot, systAnnot,
            pmId));
}
 
Example #4
Source File: EvaluationAnnotator.java    From bluima with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {

    JCas goldView, systemView;
    try {
        goldView = jCas.getView(VIEW_GOLD);
        systemView = jCas.getView(VIEW_SYSTEM);
    } catch (CASException e) {
        throw new AnalysisEngineProcessException(e);
    }

    Collection goldAnnot = select(goldView, goldAnnotation);
    Collection systAnnot = select(systemView, systemAnnotation);
    if (verbose)
        System.out
                .println("comparing #gold:" + goldAnnot.size() + " #sys:"
                        + systAnnot.size() + " [pmid "
                        + getHeaderDocId(jCas) + "]");

    String log = evaluator.add(goldAnnot, systAnnot, "");
    if (verbose)
        System.out.println(log);
    // System.out.println(evaluator.compare());
}
 
Example #5
Source File: TypePriorityTest.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
private CASMgr initCAS() {
  // Create a CASMgr. Ensures existence of AnnotationFS type.

  CASMgr localCas = CASFactory.createCAS(200);
  // Create a writable type system.
  TypeSystemMgr tsa = localCas.getTypeSystemMgr();
  // Add new types and features.

  addTypesForLevel(tsa, 4);

  // Commit the type system.
  ((CASImpl) localCas).commitTypeSystem();
  try {
    localCas.initCASIndexes();
  } catch (CASException e2) {
    e2.printStackTrace();
    assertTrue(false);
  }

  localCas.getIndexRepositoryMgr().commit();
  // assert(cas.getIndexRepositoryMgr().isCommitted());
  return localCas;
}
 
Example #6
Source File: CasManager_impl.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a specified interface to a CAS.
 * 
 * @param cas
 *          The CAS
 * @param requiredInterface
 *          interface to get. Currently must be one of CAS or JCas.
 * @param <T> the particular interface
 * @return -         
 */
@SuppressWarnings("unchecked")
public static <T extends AbstractCas> T getCasInterfaceStatic(CAS cas, Class<T> requiredInterface) {
  if (requiredInterface == CAS.class) {
    return (T) cas;
  } else if (requiredInterface == JCas.class) {
    try {
      return (T) cas.getJCas();
    } catch (CASException e) {
      throw new UIMARuntimeException(e);
    }
  } else if (requiredInterface.isInstance(cas)) // covers AbstractCas
  {
    return (T) cas;
  }
  {
    throw new UIMARuntimeException(UIMARuntimeException.UNSUPPORTED_CAS_INTERFACE,
            new Object[] { requiredInterface });
  }
}
 
Example #7
Source File: AbstractTermSuiteCollectionReader.java    From termsuite-core with Apache License 2.0 6 votes vote down vote up
protected void fillCas(CAS cas, File file) throws IOException, CollectionException {
	String uri = file.toURI().toString();
	SourceDocumentInformation sdi;
	try {
		sdi = new SourceDocumentInformation(cas.getJCas());
		sdi.setUri(uri);
		String text = getDocumentText(file.getAbsolutePath(), this.mEncoding);
		cas.setDocumentLanguage(mLanguage.getCode());
		cas.setDocumentText(preparator.prepare(text));
		sdi.setDocumentSize((int)file.length());
		sdi.setCumulatedDocumentSize(this.currentFileByteSize);
		sdi.setCorpusSize(this.totalFileByteSize);
		sdi.setBegin(0);
		sdi.setEnd(text.length());
		sdi.setOffsetInSource(0);
		sdi.setDocumentIndex(mCurrentIndex);
		sdi.setNbDocuments(this.mFiles.size());
		
		sdi.setLastSegment(mCurrentIndex == mFiles.size() - 1);
		sdi.addToIndexes();
	} catch (CASException e) {
		throw new CollectionException(e);
	}
}
 
Example #8
Source File: JCasPoolIterable.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
public JCasPoolIterable(int casPoolSize, CollectionReaderDescription aReader, AnalysisEngineDescription... aEngines)
    throws CASException, ResourceInitializationException {
  this.selfComplete = false;
  this.selfDestroy = false;
  this.destroyed = false;
  this.casPoolSize = casPoolSize;
  this.collectionReader = CollectionReaderFactory.createReader(aReader);
  analysisEngines = new AnalysisEngine[aEngines.length];
  for (int i = 0; i < aEngines.length; i++) {
    analysisEngines[i] = createEngine(aEngines[i]);
  }
  ResourceManager rm = ResourceManagerFactory.newResourceManager();
  rm.getCasManager().addMetaData(collectionReader.getProcessingResourceMetaData());
  AnalysisEngine[] resMgr = analysisEngines;
  int var5 = aEngines.length;
  for (int var6 = 0; var6 < var5; ++var6) {
    AnalysisEngine ae = resMgr[var6];
    rm.getCasManager().addMetaData(ae.getProcessingResourceMetaData());
  }
  casManager = rm.getCasManager();
  casManager.defineCasPool("iterableJcas", casPoolSize, null);
}
 
Example #9
Source File: OpenIEFactRankingByGlobalEntityPrior.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
private double computeScore(List<de.mpg.mpi_inf.ambiversenlu.nlu.entitylinking.service.web.model.Entity> entities) throws EntityLinkingDataAccessException, CASException {
  double score = 0.0;
  
  // Avoid counting mentions twice if theire entities are the same
  Set<String> wikidataIds = new HashSet<>();
  
  for (de.mpg.mpi_inf.ambiversenlu.nlu.entitylinking.service.web.model.Entity e : entities) {
    // If an entity was spotted as a mention, but not linked to the knowledge graph,
    // this could result in no Wikidata ID being present.
    if (e.getId() != null && !wikidataIds.contains(e.getId())) {
      Entity entity = getEntityFromWikidataID(e.getId());
    
      // Mind that 0.0 is the best score!
      double mePrior = da.getGlobalEntityPrior(entity);
    
      score += mePrior;
      
      wikidataIds.add(e.getId());
    }
  }
  
  return score;
}
 
Example #10
Source File: IteratorTestSorted.java    From uima-uimaj with Apache License 2.0 6 votes vote down vote up
public void setUp() {
  CASImpl casMgr = (CASImpl) CASFactory.createCAS();
  TypeSystemImpl tsi = (TypeSystemImpl) casMgr.getTypeSystemMgr();
  TypeImpl level_1_type = tsi.addType("org.apache.uima.cas.test.Level_1", tsi.annotType);
  tsi.addFeature("id", level_1_type, tsi.floatType);
  TypeImpl level_2_type = tsi.addType("org.apache.uima.cas.test.Level_2",  level_1_type);
  TypeImpl level_3_type = tsi.addType("org.apache.uima.cas.test.Level_3",  level_2_type);
  TypeImpl level_4_type = tsi.addType("org.apache.uima.cas.test.Level_4",  level_3_type);
  TypeImpl level_5_type = tsi.addType("org.apache.uima.cas.test.Level_5",  level_4_type);
  TypeImpl level_6_type = tsi.addType("org.apache.uima.cas.test.Level_6",  level_5_type);
  
  casMgr.commitTypeSystem();
  try {
    FSIndexRepositoryMgr irm = casMgr.getIndexRepositoryMgr();
    casMgr.initCASIndexes();
    irm.commit();
    
    jcas = casMgr.getCurrentView().getJCas();
  } catch (CASException e) {
    e.printStackTrace();
    fail();
  }
}
 
Example #11
Source File: BmeowTypeAnnotator.java    From ambiverse-nlu with Apache License 2.0 6 votes vote down vote up
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
	BmeowTypeDictionary dict = null;
	try {
		if (gold) {
			JCas goldView = jCas.getView("gold");
			dict = constructBmeowTypeDictionaryFromGoldStandard(goldView);
		} else {
			dict = constructBmeowTypeDictionaryFromAida(jCas);
		}
		Collection<Token> tokens = JCasUtil.select(jCas, Token.class);

		for(Token token : tokens){
			annotateBmeowType(jCas, dict, token);
		}
	} catch (EntityLinkingDataAccessException | CASException e) {
		throw new AnalysisEngineProcessException(e);
	}
}
 
Example #12
Source File: I2b2JdbcWriter.java    From ctakes-docker with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 * Like process for AEs
 */
@Override
protected void writeJCasInformation( final JCas jcas, 
                                     final String instance,
                                     final int encounterNum,
                                     final long patientNum, final String providerId,
                                     final Timestamp startDate ) throws SQLException {
 
   JCas deidView = null;
   try {
 	  deidView = jcas.getView("DeidView");
   } catch(CASException e) {
 	  throw new RuntimeException(e);
   }

   logger.log(Level.INFO,"view = " + deidView.getViewName());
   writeConceptRows( deidView, instance, Long.toString(patientNum), Integer.toString(encounterNum), providerId );

}
 
Example #13
Source File: I2b2ReadyFileWriter.java    From ctakes-docker with Apache License 2.0 6 votes vote down vote up
@Override
   public void process( final JCas jcas ) throws AnalysisEngineProcessException {

      final String patient = Long.toString( SourceMetadataUtil.getPatientNum( jcas ) );
      final SourceData sourceData = SourceMetadataUtil.getSourceData( jcas );
      final String encounter = sourceData==null?"null":sourceData.getSourceEncounterId();
      final String providerId = sourceData==null?"null":SourceMetadataUtil.getProviderId( sourceData );
      // source date not used ???
//      final String sourceDate = sourceData.getSourceOriginalDate();
      JCas deidView = null;
      try{
        deidView = jcas.getView(DEID_VIEW);
      }catch(CASException e){
        throw new AnalysisEngineProcessException(e);
      }
      final Collection<String> conceptLines = createConceptLines( deidView, patient, encounter, providerId );

      final File outputFile = new File( _outputRootDir, encounter );
      saveAnnotations( outputFile, conceptLines );

   }
 
Example #14
Source File: NewsleakCsvStreamReader.java    From newsleak with GNU Affero General Public License v3.0 6 votes vote down vote up
public void getNext(CAS cas) throws IOException, CollectionException {
	currentRecord++;
	JCas jcas;
	try {
		jcas = cas.getJCas();
	} catch (CASException e) {
		throw new CollectionException(e);
	}

	// Set document data
	CSVRecord record = recordsIterator.next();
	String docId = record.get(0); // external document id from CSV file

	jcas.setDocumentText(cleanBodyText(record.get(1)));
	jcas.setDocumentLanguage(record.size() > 3 ? record.get(3) : defaultLanguage);

	// Set metadata
	Metadata metaCas = new Metadata(jcas);
	metaCas.setDocId(docId);
	metaCas.setTimestamp(record.get(2));
	metaCas.addToIndexes();

	// metadata
	// is assumed to be provided from external prcessing in a separate file

}
 
Example #15
Source File: SentenceAndTokenCopier.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
@Override
public void process(JCas jCas) throws AnalysisEngineProcessException {
  try {
    JCas view1 = jCas.getView(VIEW1);
    JCas view2 = jCas.getView(VIEW2);

    for (Token token1 : select(view1, Token.class)) {
      new Token(view2, token1.getBegin(), token1.getEnd()).addToIndexes();
    }

    for (Sentence sentence1 : select(view1, Sentence.class)) {
      new Sentence(view2, sentence1.getBegin(), sentence1.getEnd()).addToIndexes();
    }
  } catch (CASException ce) {
    throw new AnalysisEngineProcessException(ce);
  }
}
 
Example #16
Source File: TypePriorityTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Test driver.
 */
public void testMain() throws Exception {    
  LinearTypeOrderBuilder order = irm.createTypeSortOrder();
  order = irm.createTypeSortOrder();
  LinearTypeOrder lo;
  try {
    order.add(new String[] { "aaa", "bbb" });
    lo = order.getOrder();
    check(lo, "aaa", "bbb");
  } catch (CASException e) {
    assertTrue(false);
  }
}
 
Example #17
Source File: ViewTextCopierAnnotatorTest.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
@Test
public void testViewTextCopier() throws ResourceInitializationException,
        AnalysisEngineProcessException, CASException {

  String text = "sample text";
  String sourceViewName = "SourceView";
  String destinationViewName = "DestinationView";

  jCas.setDocumentText(text);
  AnalysisEngine viewCreator = AnalysisEngineFactory.createEngine(
          ViewTextCopierAnnotator.class, typeSystemDescription,
          ViewTextCopierAnnotator.PARAM_SOURCE_VIEW_NAME, CAS.NAME_DEFAULT_SOFA,
          ViewTextCopierAnnotator.PARAM_DESTINATION_VIEW_NAME, destinationViewName);
  viewCreator.process(jCas);
  JCas destinationView = jCas.getView(destinationViewName);
  assertNotNull(destinationView);
  assertEquals(text, destinationView.getDocumentText());

  jCas.reset();
  jCas.setDocumentText(text);
  jCas.createView(destinationViewName);
  viewCreator.process(jCas);
  destinationView = jCas.getView(destinationViewName);
  assertNotNull(destinationView);
  assertEquals(text, destinationView.getDocumentText());

  viewCreator = AnalysisEngineFactory.createEngine(ViewTextCopierAnnotator.class,
          typeSystemDescription, ViewTextCopierAnnotator.PARAM_SOURCE_VIEW_NAME, sourceViewName,
          ViewTextCopierAnnotator.PARAM_DESTINATION_VIEW_NAME, destinationViewName);
  jCas.reset();
  JCas sourceView = jCas.createView(sourceViewName);
  sourceView.setDocumentText(text);
  viewCreator.process(jCas);
  destinationView = jCas.getView(destinationViewName);
  assertNotNull(destinationView);
  assertEquals(text, destinationView.getDocumentText());
  assertNull(jCas.getDocumentText());
}
 
Example #18
Source File: JCasIterator.java    From uima-uimafit with Apache License 2.0 5 votes vote down vote up
private JCas createCas(final ResourceManager aResMgr, final CollectionReader aReader,
        final AnalysisEngine... aEngines) throws CASException, ResourceInitializationException
{
  Collection<MetaDataObject> metaData = new ArrayList<MetaDataObject>();
  metaData.add(aReader.getProcessingResourceMetaData());
  for (AnalysisEngine ae : aEngines) {
    metaData.add(ae.getProcessingResourceMetaData());
  }

  return CasCreationUtils.createCas(metaData, null, aResMgr).getJCas();
}
 
Example #19
Source File: AutomationUtil.java    From webanno with Apache License 2.0 5 votes vote down vote up
private static StringBuffer getMiraLineForTabSep(String aToken, String aFeature)
    throws CASException
{
    StringBuffer sb = new StringBuffer();
    char[] words = aToken.toCharArray();
    String prefix1 = Character.toString(words[0]) + " ";
    String prefix2 = (words.length > 1 ? prefix1.trim()
            + (Character.toString(words[1]).trim().equals("") ? "__nil__" : Character
                    .toString(words[1])) : "__nil__")
            + " ";
    String prefix3 = (words.length > 2 ? prefix2.trim()
            + (Character.toString(words[2]).trim().equals("") ? "__nil__" : Character
                    .toString(words[2])) : "__nil__")
            + " ";
    String prefix4 = (words.length > 3 ? prefix3.trim()
            + (Character.toString(words[3]).trim().equals("") ? "__nil__" : Character
                    .toString(words[3])) : "__nil__")
            + " ";
    String suffix1 = Character.toString(words[words.length - 1]) + " ";
    String suffix2 = (words.length > 1 ? (Character.toString(words[words.length - 2]).trim()
            .equals("") ? "__nil__" : Character.toString(words[words.length - 2]))
            + suffix1.trim() : "__nil__")
            + " ";
    String suffix3 = (words.length > 2 ? (Character.toString(words[words.length - 3]).trim()
            .equals("") ? "__nil__" : Character.toString(words[words.length - 3]))
            + suffix2.trim() : "__nil__")
            + " ";
    String suffix4 = (words.length > 3 ? (Character.toString(words[words.length - 4]).trim()
            .equals("") ? "__nil__" : Character.toString(words[words.length - 4]))
            + suffix3.trim() : "__nil__")
            + " ";

    String nl = "\n";
    sb.append(aToken).append(" ").append(prefix1).append(prefix2).append(prefix3)
        .append(prefix4).append(suffix1).append(suffix2).append(suffix3).append(suffix4)
        .append(aFeature).append(nl);
    return sb;

}
 
Example #20
Source File: JsonCasDeserializer.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
private static void FillTermOccAnnotations(JsonParser parser , JsonToken token, TermOccAnnotation toa, CAS cas) throws IOException, CASException {
    if (token.equals(JsonToken.FIELD_NAME)){
        switch (parser.getCurrentName()){
            case F_PATTERN :
                String[] patternTable = parser.nextTextValue().split(" ");
                StringArray stringArray = new StringArray(cas.getJCas(), patternTable.length);

                for (int i = 0; i < patternTable.length; i++){
                    stringArray.set(i,patternTable[i]);
                }
                toa.setPattern(stringArray);
                break;

            case F_SPOTTING_RULE_NAME :
                toa.setSpottingRuleName(parser.nextTextValue());
                break;
            case F_TERM_KEY :
                toa.setTermKey(parser.nextTextValue());
                break;
            case F_WORDS :
                fillWords(toa,cas);
                break;
            case F_BEGIN :
                toa.setBegin(parser.nextIntValue(0));
                break;
            case F_END :
                toa.setEnd(parser.nextIntValue(0));
                break;
        }
    }
}
 
Example #21
Source File: StreamingCollectionReader.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
@Override
public void getNext(CAS cas) throws IOException, CollectionException {
	this.cumulatedLength += currentDoc.getText().length();
	logger.info("[Stream {}] Processing document {}: {} (total length processed: {})", 
			this.streamName,
			this.mCurrentIndex,
			this.currentDoc.getUri(),
			this.cumulatedLength);

	SourceDocumentInformation sdi;
	try {
		
		sdi = new SourceDocumentInformation(cas.getJCas());
		sdi.setUri(currentDoc.getUri());
		cas.setDocumentLanguage(mLanguage.getCode());
		cas.setDocumentText(currentDoc.getText());
		sdi.setDocumentSize(currentDoc.getText().length());
		sdi.setCumulatedDocumentSize(this.cumulatedLength);
		sdi.setBegin(0);
		sdi.setEnd(currentDoc.getText().length());
		sdi.setOffsetInSource(0);
		sdi.setDocumentIndex(mCurrentIndex);
		
		/*
		 * Cannot be known in case of streaming
		 */
		sdi.setCorpusSize(-1);
		sdi.setNbDocuments(-1);
		
		// Cannot know if this is the last
		sdi.setLastSegment(false);
		
		sdi.addToIndexes();
		this.mCurrentIndex++;
	} catch (CASException e) {
		throw new CollectionException(e);
	}
}
 
Example #22
Source File: IndexRepositoryMergingTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    cas = (CASImpl) CASFactory.createCAS();
    
    TypeSystemImpl ts = this.typeSystem = cas.getTypeSystemImpl();
    annotSubtype = ts.addType("annotSubtype", ts.annotType);
    ts.addFeature("x", annotSubtype, ts.intType);
    cas.commitTypeSystem();  // also creates the initial indexrepository
    // handle type system reuse
    ts = this.typeSystem = cas.getTypeSystemImpl();
    annotSubtype = ts.getType("annotSubtype");
    
    cas.initCASIndexes();  // requires committed type system
    
    
    ir = (FSIndexRepositoryImpl) this.cas.getIndexRepositoryMgr(); 
    FSIndexComparator comp = ir.createComparator();
    Type annotation = ts.getType(CAS.TYPE_NAME_ANNOTATION);
    comp.setType(annotation);
    comp.addKey(annotation.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_BEGIN),
            FSIndexComparator.STANDARD_COMPARE);
    comp.addKey(annotation.getFeatureByBaseName(CAS.FEATURE_BASE_NAME_END),
            FSIndexComparator.REVERSE_STANDARD_COMPARE);
    LinearTypeOrderBuilder tob = ir.createTypeSortOrder();
    try {
//      tob.add(new String[] { CAS.TYPE_NAME_ANNOTATION, "annotSubtype",   });  // is equal to annotationIndex
      tob.add(new String[] { "annotSubtype", CAS.TYPE_NAME_ANNOTATION  });  // is !equal AnnotationIndex
      comp.addKey(tob.getOrder(), FSIndexComparator.STANDARD_COMPARE);
    } catch (CASException e) {
      TestCase.assertTrue(false);
    }
    ir.createIndex(comp, "Annot Index");  // should not be the same as the built-in one due to different type order
    ir.createIndex(comp, "Annot Index2");  // should not be the same as the built-in one due to different type order
    FSIndexComparatorImpl comp2 = ((FSIndexComparatorImpl)comp).copy();
    comp2.setType(annotSubtype);
    ir.createIndex(comp2, "Annot Index Subtype");  // should not be the same as the built-in one due to different type order
    ir.commit();
  }
 
Example #23
Source File: CASTestSetup.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void initIndexes(FSIndexRepositoryMgr irm, TypeSystem ts) {
  FSIndexComparator compNoTypeOrder = makeComp(irm, ts);
  FSIndexComparator comp = makeComp(irm, ts);
  LinearTypeOrderBuilder tob = irm.createTypeSortOrder();
  try {
    tob.add(new String[] { CAS.TYPE_NAME_ANNOTATION, SENT_TYPE, TOKEN_TYPE });
    comp.addKey(tob.getOrder(), FSIndexComparator.STANDARD_COMPARE);
  } catch (CASException e) {
    TestCase.assertTrue(false);
  }
  irm.createIndex(comp, ANNOT_BAG_INDEX, FSIndex.BAG_INDEX);
  irm.createIndex(comp, ANNOT_SET_INDEX, FSIndex.SET_INDEX);
  irm.createIndex(comp, ANNOT_SORT_INDEX, FSIndex.SORTED_INDEX);
  irm.createIndex(compNoTypeOrder, ANNOT_SET_INDEX_NO_TYPEORDER, FSIndex.SET_INDEX);
}
 
Example #24
Source File: FSIndexRepositoryImpl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public LinearTypeOrder getDefaultTypeOrder() {
  if (this.sii.defaultTypeOrder == null) {
    if (this.sii.defaultOrderBuilder == null) {
      this.sii.defaultOrderBuilder = new LinearTypeOrderBuilderImpl(this.sii.tsi);
    }
    try {
      this.sii.defaultTypeOrder = this.sii.defaultOrderBuilder.getOrder();
    } catch (final CASException e) {
      // Since we're doing this on an existing type names, we can't
      // get here.
      throw new UIMARuntimeException(UIMARuntimeException.INTERNAL_ERROR, new Object[0], e);
    }
  }
  return this.sii.defaultTypeOrder;
}
 
Example #25
Source File: SWN3.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public double score(CAS cas) throws CASException {
    double totalScore = 0.0;
    for (Sentence sentence : JCasUtil.select(cas.getJCas(), Sentence.class)) {
        totalScore += scoreTokens(JCasUtil.selectCovered(Token.class, sentence));
    }

    return totalScore;
}
 
Example #26
Source File: ProtectIndexTest.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public void testProtectIndex() throws CASException, ResourceInitializationException {
  JCas jcas = CasCreationUtils.createCas((TypeSystemDescription)null, null, null).getJCas();
  
  Annotation a = new Annotation(jcas, 0, 2);
  
  jcas.protectIndexes(() ->
    { a.setBegin(a.getBegin() + 1);
    });
    
  assertEquals(a.getBegin(),  1);  
}
 
Example #27
Source File: UimaSupport.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a event to the history for this CAS document.
 *
 * @param cas the target document for the event
 * @param event the event to add
 */
public void addToHistory(CAS cas, HistoryEvent event) {
  try {
    getDocumentHistory(cas.getJCas()).add(event);
  } catch (CASException e) {
    monitor.error("Unable to add to history on add", e);
  }
}
 
Example #28
Source File: UimaSupport.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void addMergeToHistory(Annotation keep, Annotation removed) {
  if (keep instanceof Recordable && removed instanceof Base) {
    Recordable r = (Recordable) keep;
    Base b = (Base) removed;
    try {
      addToHistory(
          keep.getCAS().getJCas(), HistoryEvents.createMerged(r, referrer, b.getInternalId()));
    } catch (CASException e) {
      monitor.error("Unable to add merge to history", e);
    }
  }
}
 
Example #29
Source File: FlowContainer.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
public FlowContainer newCasProduced(final CAS newCAS, String producedBy)
        throws AnalysisEngineProcessException {
  mTimer.startIt();
  CAS view = null;
  try {
    view = Util.getStartingView(   
        newCAS, 
        mSofaAware, 
        mFlowControllerContainer.getUimaContextAdmin().getComponentInfo());
    // now get the right interface(e.g. CAS or JCAS)
    // must be done before call to switchClassLoader
    Class<? extends AbstractCas> requiredInterface = mFlowControllerContainer.getRequiredCasInterface();
    AbstractCas casToPass = getCasManager().getCasInterface(view, requiredInterface);

    ((CASImpl)view).switchClassLoaderLockCasCL(getFlowClassLoader());
    Flow flow = mFlow.newCasProduced(casToPass, producedBy);
    if (flow instanceof CasFlow_ImplBase) {
      ((CasFlow_ImplBase)flow).setCas(view);
    }
    if (flow instanceof JCasFlow_ImplBase) {
      ((JCasFlow_ImplBase)flow).setJCas(view.getJCas());
    }
    return new FlowContainer(flow, mFlowControllerContainer, newCAS);
  } catch (CASException e) {
    throw new AnalysisEngineProcessException(e);
  } finally {
    newCAS.setCurrentComponentInfo(null);
    if (null != view) {
      ((CASImpl)view).restoreClassLoaderUnlockCas();
    }
    mTimer.stopIt();
    getMBean().reportAnalysisTime(mTimer.getDuration());
    getMBean().incrementCASesProcessed();
  }
}
 
Example #30
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;
}