Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.apache.ctakes.temporal.eval;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
 import  org.cleartk.eval.AnnotationStatistics;
 import  org.cleartk.opennlp.tools.ParserAnnotator;
 import  org.cleartk.opennlp.tools.PosTaggerAnnotator;
 import  org.cleartk.opennlp.tools.SentenceAnnotator;
 import  org.cleartk.snowball.DefaultSnowballStemmer;
 import  org.cleartk.timeml.event.EventAspectAnnotator;
 import  org.cleartk.timeml.event.EventClassAnnotator;
 import  org.cleartk.timeml.event.EventModalityAnnotator;
 import  org.cleartk.timeml.event.EventPolarityAnnotator;
 import  org.cleartk.timeml.event.EventTenseAnnotator;
 import  org.cleartk.timeml.tlink.TemporalLinkEventToDocumentCreationTimeAnnotator;
 import  org.cleartk.token.tokenizer.TokenAnnotator;
 
 
 public class EvaluationOfClearTKEventProperties extends
     Evaluation_ImplBase<Map<String, AnnotationStatistics<String>>> {
 
   private static final String DOC_TIME_REL = "docTimeRel";
 
   private static final List<StringPROPERTY_NAMES = Arrays.asList();
 
   public static void main(String[] argsthrows Exception {
     Options options = CliFactory.parseArguments(Options.classargs);
     List<IntegerpatientSets = options.getPatients().getList();
     List<IntegertrainItems = getTrainItems(options);
     List<IntegertestItems = getTestItems(options);
     
         new File("target/eval/event-properties"),
         options.getRawTextDirectory(),
         options.getXMLDirectory(),
         options.getXMLFormat(),
         options.getXMIDirectory());
     evaluation.prepareXMIsFor(patientSets);
     evaluation.logClassificationErrors(new File("target/eval"), "ctakes-event-property-errors");
     Map<String, AnnotationStatistics<String>> stats = evaluation.trainAndTest(trainItemstestItems);
     for (String name : ) {
       ..println("====================");
       ..println(name);
       ..println("--------------------");
       ..println(stats.get(name));
     }
   }
 
   private Map<StringLoggerloggers = Maps.newHashMap();
  
      File baseDirectory,
      File rawTextDirectory,
      File xmlDirectory,
      XMLFormat xmlFormat,
      File xmiDirectory) {
    super(baseDirectoryrawTextDirectoryxmlDirectoryxmlFormatxmiDirectorynull);
    for (String name : ) {
      this..put(name, Logger.getLogger(String.format("%s.%s"this.getClass().getName(), name)));
    }
  }
  protected void train(CollectionReader collectionReaderFile directorythrows Exception {
	  AggregateBuilder aggregateBuilder = this.getPreprocessorAggregateBuilder();
	  aggregateBuilder.add(CopyFromGold.getDescription(EventMention.class));
	  aggregateBuilder.add(CopyFromGold.getDescription(EventProperties.class));
	  SimplePipeline.runPipeline(collectionReaderaggregateBuilder.createAggregate());
  }
  protected Map<String, AnnotationStatistics<String>> test(
		  CollectionReader collectionReader,
		  File directorythrows Exception {
	  AggregateBuilder aggregateBuilder = this.getPreprocessorAggregateBuilder();
	  aggregateBuilder.add(CopyFromGold.getDescription(EventMention.class));
	  aggregateBuilder.add(CopyFromGold.getDescription(TimeMention.class));
	  aggregateBuilder.add(SentenceAnnotator.getDescription());
	  aggregateBuilder.add(TokenAnnotator.getDescription());
	  aggregateBuilder.add(PosTaggerAnnotator.getDescription());
	  aggregateBuilder.add(DefaultSnowballStemmer.getDescription("English"));
	  aggregateBuilder.add(ParserAnnotator.getDescription());
	  aggregateBuilder.add(EventToClearTKEventAnnotator.getAnnotatorDescription());//for every cTakes eventMention, create a cleartk event
	  aggregateBuilder.add(ClearTKDocumentCreationTimeAnnotator.getAnnotatorDescription());//for every jCAS create an empty DCT, and add it to index
	  aggregateBuilder.add(EventTenseAnnotator.FACTORY.getAnnotatorDescription("/org/cleartk/timeml/event/eventtenseannotator/model.jar"));
	  aggregateBuilder.add(EventAspectAnnotator.FACTORY.getAnnotatorDescription("/org/cleartk/timeml/event/eventaspectannotator/model.jar"));
	  aggregateBuilder.add(EventClassAnnotator.FACTORY.getAnnotatorDescription("/org/cleartk/timeml/event/eventclassannotator/model.jar"));
	  aggregateBuilder.add(EventPolarityAnnotator.FACTORY.getAnnotatorDescription("/org/cleartk/timeml/event/eventpolarityannotator/model.jar"));
	  aggregateBuilder.add(EventModalityAnnotator.FACTORY.getAnnotatorDescription("/org/cleartk/timeml/event/eventmodalityannotator/model.jar"));
	  aggregateBuilder.add(TemporalLinkEventToDocumentCreationTimeAnnotator.FACTORY.getAnnotatorDescription("/org/cleartk/timeml/tlink/temporallinkeventtodocumentcreationtimeannotator/model.jar"));
	  aggregateBuilder.add(ClearTKDocTimeRelAnnotator.getAnnotatorDescription());// for every tlink, check if it cover and event, add the tlink type to the event's docTimeRel attribute
    Function<EventMention, ?> eventMentionToSpan = AnnotationStatistics.annotationToSpan();
    Map<StringFunction<EventMentionString>> propertyGetters;
    propertyGetters = new HashMap<StringFunction<EventMentionString>>();
    for (String name : ) {
      propertyGetters.put(namegetPropertyGetter(name));
    }
    Map<String, AnnotationStatistics<String>> statsMap = new HashMap<String, AnnotationStatistics<String>>();
    statsMap.put(new AnnotationStatistics<String>());
    for (Iterator<JCascasIter = new JCasIterator(collectionReaderaggregateBuilder.createAggregate()); casIter.hasNext();) {
      JCas jCas = casIter.next();
      JCas goldView = jCas.getView();
      JCas systemView = jCas.getView(.);
      String text = goldView.getDocumentText();
      for (Segment segment : JCasUtil.select(jCasSegment.class)) {
        if (!..contains(segment.getId())) {
          List<EventMentiongoldEvents = selectExact(goldViewEventMention.classsegment);
          List<EventMentionsystemEvents = selectExact(systemViewEventMention.classsegment);
          for (String name : ) {
            Function<EventMentionStringgetProperty = propertyGetters.get(name);
            statsMap.get(name).add(
                goldEvents,
                systemEvents,
                eventMentionToSpan,
                getProperty);
            for (int i = 0; i < goldEvents.size(); ++i) {
              String goldOutcome = getProperty.apply(goldEvents.get(i));
              if ( i == systemEvents.size()){
            	  break;
              }
              String systemOutcome = getProperty.apply(systemEvents.get(i));
              if (!goldOutcome.equals(systemOutcome)) {
                EventMention event = goldEvents.get(i);
                int begin = event.getBegin();
                int end = event.getEnd();
                int windowBegin = Math.max(0, begin - 50);
                int windowEnd = Math.min(text.length(), end + 50);
                this..get(name).fine(String.format(
                    "%s was %s but should be %s, in  ...%s[!%s!]%s...",
                    name,
                    systemOutcome,
                    goldOutcome,
                    text.substring(windowBeginbegin).replaceAll("[\r\n]"" "),
                    text.substring(beginend),
                    text.substring(endwindowEnd).replaceAll("[\r\n]"" ")));
              }
            }
          }
        }
      }
    }
    return statsMap;
  }
  
  public void logClassificationErrors(File outputDirString outputFilePrefixthrows IOException {
    if (!outputDir.exists()) {
      outputDir.mkdirs();
    }
    for (String name : ) {
      Logger logger = this..get(name);
      logger.setLevel(.);
      File outputFile = new File(outputDir, String.format("%s.%s.log"outputFilePrefixname));
      FileHandler handler = new FileHandler(outputFile.getPath());
      handler.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
          return record.getMessage() + '\n';
        }
      });
      logger.addHandler(handler);
    }
  }
  private static Function<EventMentionStringgetPropertyGetter(final String propertyName) {
    return new Function<EventMentionString>() {
      @Override
      public String apply(EventMention eventMention) {
        EventProperties eventProperties = eventMention.getEvent().getProperties();
        Feature feature = eventProperties.getType().getFeatureByBaseName(propertyName);
        return eventProperties.getFeatureValueAsString(feature);
      }
    };
  }
  public static class ClearEventProperties extends JCasAnnotator_ImplBase {
    @Override
    public void process(JCas jCasthrows AnalysisEngineProcessException {
      for (EventProperties eventProperties : JCasUtil.select(jCasEventProperties.class)) {
        eventProperties.setAspect(null);
        eventProperties.setCategory(null);
        eventProperties.setContextualAspect(null);
        eventProperties.setContextualModality(null);
        eventProperties.setDegree(null);
        eventProperties.setDocTimeRel(null);
        eventProperties.setPermanence(null);
        eventProperties.setPolarity(0);
      }
    }
  }
New to GrepCode? Check out our FAQ X