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.ml.liblinear.LibLinearStringOutcomeDataWriter;
 import  org.cleartk.eval.AnnotationStatistics;
 import  org.cleartk.ml.jar.JarClassifierBuilder;
 import  org.cleartk.ml.libsvm.LibSvmStringOutcomeDataWriter;
 import  org.cleartk.util.ViewUriUtil;
 
 
 public class EvaluationOfEventProperties extends
 Evaluation_ImplBase<Map<String, AnnotationStatistics<String>>> {
 	static interface TempRelOptions extends Evaluation_ImplBase.Options{
 		public boolean getPrintFormattedRelations();
 
 		public boolean getBaseline();
 
 		public boolean getClosure();
 
 		public boolean getUseTmp();
 
 		public boolean getUseGoldAttributes();
 
 		public boolean getSkipTrain();
 	}
 	private static final String DOC_TIME_REL = "docTimeRel";
 	private static final String CONTEXTUAL_MODALITY = "contextualModality";
 
 	private static final List<StringPROPERTY_NAMES = Arrays.asList();
 
 	public static void main(String[] argsthrows Exception {
 		TempRelOptions options = CliFactory.parseArguments(TempRelOptions.classargs);
 		List<IntegerpatientSets = options.getPatients().getList();
 		List<IntegertrainItems = getTrainItems(options);
 		List<IntegertestItems = getTestItems(options);
 
 		try{
 			File workingDir = new File("target/eval/event-properties");
 			if(!workingDir.exists()) workingDir.mkdirs();
			if(options.getUseTmp()){
				File tempModelDir = File.createTempFile("temporal"nullworkingDir);
				tempModelDir.delete();
				tempModelDir.mkdir();
				workingDir = tempModelDir;
			}
					workingDir,//new File("target/eval/event-properties"),
					options.getXMLDirectory(),
					options.getXMLFormat(),
					options.getXMIDirectory());
			evaluation.skipTrain = options.getSkipTrain();
			if(evaluation.skipTrain && options.getTest()){
				evaluation.prepareXMIsFor(testItems);
			}else{
				evaluation.prepareXMIsFor(patientSets);
			}
			evaluation.logClassificationErrors(workingDir"ctakes-event-property-errors");
			Map<String, AnnotationStatistics<String>> stats = evaluation.trainAndTest(trainItemstestItems);
			for (String name : ) {
				..println("====================");
				..println("--------------------");
				..println(stats.get(name));
			}
			if(options.getUseTmp()){
				// won't work because it's not empty. should we be concerned with this or is it responsibility of 
				// person invoking the tmp flag?
				FileUtils.deleteRecursive(workingDir);
			}
			..println("Error with Initialization");
		}
	}
	private Map<StringLoggerloggers = Maps.newHashMap();
	protected boolean skipTrain=false;
			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 {
		//	  if(this.baseline) return;
		if(this.return;
		aggregateBuilder.add(CopyFromGold.getDescription(EventMention.class));
		aggregateBuilder.add(CopyFromGold.getDescription(TimeMention.class));
		aggregateBuilder.add(DocTimeRelAnnotator.createDataWriterDescription(
				LibSvmStringOutcomeDataWriter.class,
				new File(directory)));
		aggregateBuilder.add(ContextualModalityAnnotator.createDataWriterDescription(
				LibSvmStringOutcomeDataWriter.class
				new File(directory)));
		SimplePipeline.runPipeline(collectionReaderaggregateBuilder.createAggregate());
		for(String propertyName : ){
			JarClassifierBuilder.trainAndPackage(new File(directorypropertyName), "-h","0","-c""1000");
		}
	}
	@SuppressWarnings("deprecation")
	protected Map<String, AnnotationStatistics<String>> test(
			CollectionReader collectionReader,
			File directorythrows Exception {
		aggregateBuilder.add(CopyFromGold.getDescription(EventMention.class));
		aggregateBuilder.add(CopyFromGold.getDescription(TimeMention.class));
		aggregateBuilder.add(AnalysisEngineFactory.createEngineDescription(ClearEventProperties.class));
		aggregateBuilder.add(DocTimeRelAnnotator.createAnnotatorDescription(new File(directory)));
		aggregateBuilder.add(ContextualModalityAnnotator.createAnnotatorDescription(new File(directory)));
		Function<EventMention, ?> eventMentionToSpan = AnnotationStatistics.annotationToSpan();
		Map<StringFunction<EventMentionString>> propertyGetters;
		propertyGetters = new HashMap<>();
		for (String name : ) {
			propertyGetters.put(namegetPropertyGetter(name));
		}
		Map<String, AnnotationStatistics<String>> statsMap = new HashMap<>();
		for(String propertyName : ){
			statsMap.put(propertyNamenew 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)) {
					List<EventMentiongoldEvents = selectExact(goldViewEventMention.classsegment);
					List<EventMentionsystemEvents = selectExact(systemViewEventMention.classsegment);
					for (String name : ) {
						this..get(name).fine("Errors in : " + ViewUriUtil.getURI(jCas).toString());
						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));
							String systemOutcome = getProperty.apply(systemEvents.get(i));
							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);
							if (!goldOutcome.equals(systemOutcome)) {
								this..get(name).fine(String.format(
										"%s was %s but should be %s, in  ...%s[!%s!:%d-%d]%s...",
										name,
										systemOutcome,
										goldOutcome,
										text.substring(windowBeginbegin).replaceAll("[\r\n]"" "),
										text.substring(beginend),
										begin,
										end,
										text.substring(endwindowEnd).replaceAll("[\r\n]"" ")));
							}else{//if gold outcome equals system outcome
								this..get(name).fine(String.format(
										"%s was correctly labeled as %s, in  ...%s[!%s!:%d-%d]%s...",
										name,
										goldOutcome,
										text.substring(windowBeginbegin).replaceAll("[\r\n]"" "),
										text.substring(beginend),
										begin,
										end,
										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);
			File outputFile = new File(outputDir, String.format("%s.%s.log"outputFilePrefixname));
			FileHandler handler = new FileHandler(outputFile.getPath());
			handler.setFormatter(new Formatter() {
				public String format(LogRecord record) {
					return record.getMessage() + '\n';
				}
			});
			logger.addHandler(handler);
		}
	}
	private static Function<EventMentionStringgetPropertyGetter(final String propertyName) {
		return new Function<EventMentionString>() {
			public String apply(EventMention eventMention) {
				EventProperties eventProperties = eventMention.getEvent().getProperties();
				Feature feature = eventProperties.getType().getFeatureByBaseName(propertyName);
				return eventProperties.getFeatureValueAsString(feature);
			}
		};
	}
		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