You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by jo...@apache.org on 2011/08/01 16:21:35 UTC

svn commit: r1152792 [8/10] - in /uima/sandbox/trunk/TextMarker: org.apache.uima.tm.textruler.lp2/ org.apache.uima.tm.textruler.lp2/META-INF/ org.apache.uima.tm.textruler.lp2/bin/ org.apache.uima.tm.textruler.lp2/src/ org.apache.uima.tm.textruler.lp2/s...

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerToolkit.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerToolkit.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerToolkit.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerToolkit.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,574 @@
+package org.apache.uima.tm.textruler.core;
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.net.URL;
+import java.text.CharacterIterator;
+import java.text.StringCharacterIterator;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.uima.UIMAFramework;
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.FSIterator;
+import org.apache.uima.cas.Feature;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.impl.XmiCasDeserializer;
+import org.apache.uima.cas.impl.XmiCasSerializer;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceSpecifier;
+import org.apache.uima.tm.dltk.internal.core.builder.TextMarkerProjectUtils;
+import org.apache.uima.tm.textruler.TextRulerPlugin;
+import org.apache.uima.tm.textruler.core.TextRulerTarget.MLTargetType;
+import org.apache.uima.util.XMLInputSource;
+import org.apache.uima.util.XMLSerializer;
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+
+
+/**
+ * 
+ * This static class provides all kinds of helper methods and constants that are useful for all
+ * kinds of stuff in this project.
+ */
+public class TextRulerToolkit {
+
+  public static final boolean LOGGING_ENABLED = true;
+
+  public static final boolean DEBUG = false;
+
+  public static final String TM_ALL_TYPE_NAME = "org.apache.uima.tm.type.ALL";
+
+  public static final String TM_ANY_TYPE_NAME = "org.apache.uima.tm.type.ANY";
+
+  public static final String TM_WORD_TYPE_NAME = "org.apache.uima.tm.type.W";
+
+  public static final String TM_BREAK_TYPE_NAME = "org.apache.uima.tm.type.BREAK";
+
+  public static final String TM_SPACE_TYPE_NAME = "org.apache.uima.tm.type.SPACE";
+
+  public static final String TM_NUM_TYPE_NAME = "org.apache.uima.tm.type.NUM";
+
+  public static final String TM_MARKUP_TYPE_NAME = "org.apache.uima.tm.type.MARKUP";
+
+  public static final String TM_SPECIAL_TYPE_NAME = "org.apache.uima.tm.type.SPECIAL";
+
+  public static final String TM_NBSP_TYPE_NAME = "org.apache.uima.tm.type.NBSP";
+
+  public static final String LEFT_BOUNDARY_EXTENSION = "START";
+
+  public static final String RIGHT_BOUNDARY_EXTENSION = "END";
+
+  public static void log(String str) {
+    if (LOGGING_ENABLED)
+      System.out.println(str);
+  }
+
+  public static void logIfDebug(String str) {
+    if (DEBUG)
+      log(str);
+  }
+
+  public static void logIf(boolean condition, String str) {
+    if (LOGGING_ENABLED && condition)
+      System.out.println(str);
+  }
+
+  public static URL getResourceURL(String name) {
+    return FileLocator.find(TextRulerPlugin.getDefault().getBundle(), new Path(name), null);
+  }
+
+  // public static AnalysisEngine loadAnalysisEngine()
+  // {
+  // URL u = TextRulerToolkit.getResourceURL("desc/MLEngine.xml"); // this was
+  // a predefined engine file in the plugin. got removed now since we load the
+  // // engine file of the given preprocessing file!
+  // return loadAnalysisEngine(u);
+  // }
+
+  public static AnalysisEngine loadAnalysisEngine(String descFile) {
+    AnalysisEngine result = null;
+    try {
+      XMLInputSource in = new XMLInputSource(new File(descFile));
+      ResourceSpecifier specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
+      result = UIMAFramework.produceAnalysisEngine(specifier);
+    } catch (Exception e) {
+      e.printStackTrace();
+      result = null;
+    }
+    return result;
+  }
+
+  public static AnalysisEngine loadAnalysisEngine(URL fileURL) {
+    AnalysisEngine result = null;
+    try {
+      XMLInputSource in = new XMLInputSource(fileURL);
+      ResourceSpecifier specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in);
+      result = UIMAFramework.produceAnalysisEngine(specifier);
+    } catch (Exception e) {
+      e.printStackTrace();
+      result = null;
+    }
+    return result;
+  }
+
+  public static CAS readCASfromXMIFile(String filename, AnalysisEngine ae, CAS reuseCAS) {
+    return readCASfromXMIFile(new File(filename), ae, reuseCAS);
+  }
+
+  public static CAS readCASfromXMIFile(File file, AnalysisEngine ae, CAS reuseCAS) {
+    FileInputStream inputStream = null;
+    try {
+      CAS resultCas;
+      inputStream = new FileInputStream(file);
+      if (reuseCAS != null) {
+        reuseCAS.reset();
+        resultCas = reuseCAS;
+      } else {
+        resultCas = GlobalCASSource.allocCAS(ae); // ae.newCAS();
+      }
+      XmiCasDeserializer.deserialize(inputStream, resultCas, true);
+      return resultCas;
+    } catch (Exception e) {
+      e.printStackTrace();
+    } finally {
+      try {
+        if (inputStream != null)
+          inputStream.close();
+      } catch (Exception e) {
+        e.printStackTrace();
+      }
+    }
+    return null;
+  }
+
+  public static void writeCAStoXMIFile(CAS aCas, String filename)// throws
+  // IOException,
+  // SAXException
+  {
+    File newFile = new File(filename);
+    FileOutputStream out = null;
+
+    try {
+      // write XMI
+      out = new FileOutputStream(newFile);
+      XmiCasSerializer ser = new XmiCasSerializer(aCas.getTypeSystem());
+      XMLSerializer xmlSer = new XMLSerializer(out, false);
+      ser.serialize(aCas, xmlSer.getContentHandler());
+    } catch (Exception e) {
+      e.printStackTrace();
+    } finally {
+      if (out != null) {
+        try {
+          out.close();
+        } catch (Exception e) {
+          e.printStackTrace();
+        }
+
+      }
+    }
+  }
+
+  public static List<AnnotationFS> extractAnnotationsForSlotName(CAS aCas, String slotName) {
+    List<AnnotationFS> result = new ArrayList<AnnotationFS>();
+    TypeSystem ts = aCas.getTypeSystem();
+    Type slotType = ts.getType(slotName);
+    FSIterator<AnnotationFS> it = aCas.getAnnotationIndex(slotType).iterator(true);
+    if (!it.isValid()) {
+      // System.out.println("##### -> iterator not valid for slots!!");
+    }
+    while (it.isValid()) {
+      AnnotationFS fs = it.get();
+
+      // quick hack for quantifier bug in TM:
+      AnnotationFS previous = result.size() > 0 ? result.get(result.size() - 1) : null;
+      if (previous == null || previous.getBegin() != fs.getBegin()
+              || previous.getEnd() != fs.getEnd())
+        result.add(fs);
+      else {
+        logIfDebug("******** TM QUANTIFIER BUG ?? Multiple annotation: " + fs.getType().getName());
+      }
+      it.moveToNext();
+    }
+
+    return result;
+  }
+
+  private static List<AnnotationFS> getAnnotationWithinBounds(CAS aCas, int posStart, int posEnd,
+          Set<String> filterSet, Type rootType) {
+    List<AnnotationFS> result = new ArrayList<AnnotationFS>();
+    TypeSystem ts = aCas.getTypeSystem();
+    try {
+
+      // TODO wie in TMs AnnotationRetrieval evtl nicht den subiterator
+      // nehmen, da der auf
+      // type comparisons basiert, die wir evtl nicht gegeben haben!?
+      AnnotationFS boundaryAnnotation = aCas.createAnnotation(ts.getType("uima.tcas.Annotation"),
+              posStart > 0 ? posStart - 1 : 0, posEnd); // TODO ist das
+      // richtig so??!!
+      FSIterator<AnnotationFS> it = aCas.getAnnotationIndex().subiterator(boundaryAnnotation, true,
+              true);
+      while (it.isValid()) {
+        AnnotationFS fs = it.get();
+        if (fs.getBegin() < posStart || fs.getEnd() > posEnd) {
+          it.moveToNext();
+          continue;
+        }
+        if (rootType != null) {
+          if (!ts.subsumes(rootType, fs.getType())) {
+            it.moveToNext();
+            continue;
+          }
+        }
+        if (filterSet == null || !filterSet.contains(fs.getType().getName())) {
+          result.add(fs);
+        }
+
+        it.moveToNext();
+      }
+
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+    return result;
+  }
+
+  public static List<AnnotationFS> getAnnotationsBeforePosition(CAS aCas, int position,
+          int maxCount, Set<String> filterSet, Type rootType) {
+    List<AnnotationFS> result = getAnnotationWithinBounds(aCas, 0, position, filterSet, rootType);
+    if (maxCount > 0) {
+      while (result.size() > maxCount)
+        result.remove(0); // remove from front of queue !
+    }
+    return result;
+  }
+
+  public static List<AnnotationFS> getAnnotationsAfterPosition(CAS aCas, int position,
+          int maxCount, Set<String> filterSet, Type rootType) {
+    int maxPos = aCas.getDocumentText().length() - 1;
+    List<AnnotationFS> result = getAnnotationWithinBounds(aCas, position, maxPos, filterSet,
+            rootType);
+    if (maxCount > 0) {
+      while (result.size() > maxCount)
+        result.remove(result.size() - 1); // remove from end of queue!
+    }
+    return result;
+  }
+
+  public static List<AnnotationFS> getAnnotationsWithinBounds(CAS aCas, int start, int end,
+          Set<String> filterSet, Type rootType) {
+    return getAnnotationWithinBounds(aCas, start, end, filterSet, rootType);
+  }
+
+  public static List<AnnotationFS> getNonTMAnnoationsOverToken(CAS aCas,
+          AnnotationFS tmTokenAnnotation, Set<String> filterSet) {
+    List<AnnotationFS> result = new ArrayList<AnnotationFS>();
+    // filter out document annotation!!
+    FSIterator<AnnotationFS> it = aCas.getAnnotationIndex().iterator();
+    Type tokenType = tmTokenAnnotation.getType();
+    FSIterator<AnnotationFS> leftIt = null;
+    FSIterator<AnnotationFS> rightIt = null;
+    TypeSystem ts = aCas.getTypeSystem();
+    Type tmRootType = ts.getType(TM_ALL_TYPE_NAME);
+    Set<String> allFilters = new HashSet<String>();
+    allFilters.add("uima.tcas.DocumentAnnotation");
+    if (filterSet != null)
+      allFilters.addAll(filterSet);
+    for (; it.isValid(); it.moveToNext()) {
+      AnnotationFS fs = (AnnotationFS) it.get();
+      // System.out.println(fs.getBegin() + " " + tmTokenAnnotation.getBegin() + " " + fs.getEnd()
+      // + " " + tmTokenAnnotation.getEnd() + " " + fs.getType() + " " + tokenType);
+      if (fs.getBegin() == tmTokenAnnotation.getBegin()
+              && fs.getEnd() == tmTokenAnnotation.getEnd() && fs.getType().equals(tokenType)) {
+        leftIt = it;
+
+        rightIt = it.copy();
+        break;
+      }
+    }
+    if (leftIt == null)
+      return null; // the token annotation was not found !
+    if (leftIt.isValid())
+      leftIt.moveToPrevious(); // leave our token annotation behind us...
+    // search from the token annotation to the left
+    for (; leftIt.isValid(); leftIt.moveToPrevious()) {
+      AnnotationFS fs = (AnnotationFS) leftIt.get();
+      if (fs.getEnd() <= tmTokenAnnotation.getBegin())
+        break; // if that happens we are out of reach and can stop
+      if (fs.getBegin() <= tmTokenAnnotation.getBegin()
+              && fs.getEnd() >= tmTokenAnnotation.getEnd()
+              && !allFilters.contains(fs.getType().getName())
+              && !ts.subsumes(tmRootType, fs.getType()))
+        result.add(fs);
+    }
+
+    // search from the token annotation to the right
+    if (rightIt.isValid())
+      rightIt.moveToNext(); // leave our token annotation behind us...
+    for (; rightIt.isValid(); rightIt.moveToNext()) {
+      AnnotationFS fs = (AnnotationFS) rightIt.get();
+      if (fs.getBegin() >= tmTokenAnnotation.getEnd())
+        break; // if that happens we are out of reach and can stop
+      if (fs.getBegin() <= tmTokenAnnotation.getBegin()
+              && fs.getEnd() >= tmTokenAnnotation.getEnd()
+              && !allFilters.contains(fs.getType().getName())
+              && !ts.subsumes(tmRootType, fs.getType()))
+        result.add(fs);
+    }
+    return result;
+  }
+
+  public static synchronized Set<String> getFilterSetWithSlotNames(String[] slotNames,
+          Set<String> otherFilters) {
+    Set<String> result = new HashSet<String>(otherFilters);
+    if (slotNames != null)
+      for (String s : slotNames)
+        result.add(s);
+    return result;
+  }
+
+  public static synchronized Set<String> getFilterSetWithSlotName(String slotName,
+          Set<String> otherFilters) {
+    String[] sn = { slotName };
+    return getFilterSetWithSlotNames(sn, otherFilters);
+  }
+
+  public static synchronized String getStandardFilterSetString() {
+    String str = "";
+    for (String s : getStandardFilterSet(null))
+      if (str.length() == 0)
+        str += s;
+      else
+        str += ", " + s;
+    return str;
+  }
+
+  public static synchronized Set<String> getStandardFilterSet(String[] slotNames) {
+    Set<String> filterSet = new HashSet<String>();
+    if (slotNames != null) {
+      for (String s : slotNames)
+        filterSet.add(s);
+    }
+    filterSet.add(TM_SPACE_TYPE_NAME);
+    filterSet.add(TM_BREAK_TYPE_NAME);
+    filterSet.add(TM_MARKUP_TYPE_NAME);
+    filterSet.add(TM_NBSP_TYPE_NAME);
+    return filterSet;
+  }
+
+  public static synchronized Set<String> getStandardFeatureFilterSet() {
+    Set<String> filterSet = new HashSet<String>();
+
+    filterSet.add("uima.cas.AnnotationBase:sofa");
+    filterSet.add("uima.tcas.Annotation:begin");
+    filterSet.add("uima.tcas.Annotation:end");
+    filterSet.add("org.apache.uima.tm.textmarker.kernel.type.TextMarkerBasic:Replacement");
+    return filterSet;
+  }
+
+  // return the example of the list if found, null otherwise
+  public static synchronized TextRulerExample exampleListContainsAnnotation(
+          List<TextRulerExample> list, TextRulerAnnotation ann) {
+    TextRulerExample needle = new TextRulerExample(null, ann, true, null);
+    int index = Collections.binarySearch(list, needle, new Comparator<TextRulerExample>() {
+      public int compare(TextRulerExample o1, TextRulerExample o2) {
+        TextRulerAnnotation afs1 = o1.getAnnotation();
+        TextRulerAnnotation afs2 = o2.getAnnotation();
+        if (afs1.getBegin() < afs2.getBegin())
+          return -1;
+        else if (afs1.getBegin() > afs2.getBegin())
+          return 1;
+        else if (afs1.getEnd() > afs2.getEnd())
+          return -1;
+        else if (afs1.getEnd() < afs2.getEnd())
+          return 1;
+        else
+          return 0;
+      }
+    });
+    if (index >= 0)
+      return list.get(index);
+    else
+      return null;
+  }
+
+  public static synchronized String addTrailingSlashToPath(String path) {
+    if (!(path.endsWith("/") || path.endsWith("\\")))
+      path = path + System.getProperty("file.separator");
+    return path;
+  }
+
+  public static synchronized String createTemporaryDirectory() throws IOException {
+
+    final File temp;
+
+    temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
+    if (!(temp.delete()))
+      return null;
+    if (!(temp.mkdir()))
+      return null;
+    temp.deleteOnExit();
+    return addTrailingSlashToPath(temp.getPath());
+  }
+
+  public static synchronized String getTypeShortName(String typeName) {
+    if (typeName.indexOf(".") >= 0) {
+      String components[] = typeName.split("\\.");
+      return components[components.length - 1];
+    } else
+      return typeName;
+  }
+
+  public static synchronized String getEngineDescriptorFromTMSourceFile(IPath scriptFilePath) {
+    IPath folder = scriptFilePath;
+
+    while (!folder.lastSegment().equals(TextMarkerProjectUtils.getDefaultScriptLocation())) {
+      folder = folder.removeLastSegments(1);
+    }
+    IPath relativeTo = scriptFilePath.makeRelativeTo(folder);
+    IPath projectPath = folder.removeLastSegments(1);
+    String elementName = scriptFilePath.lastSegment();
+    int lastIndexOf = elementName.lastIndexOf(".tm");
+    if (lastIndexOf != -1) {
+      elementName = elementName.substring(0, lastIndexOf);
+    }
+    IPath descPath = projectPath.append(TextMarkerProjectUtils.getDefaultDescriptorLocation());
+    IPath descPackagePath = descPath.append(relativeTo.removeLastSegments(1));
+    return descPackagePath.append(elementName + "Engine.xml").toString();
+  }
+
+  public static synchronized String getTypeSystemDescriptorFromTMSourceFile(IPath scriptFilePath) {
+    IPath folder = scriptFilePath;
+
+    while (!folder.lastSegment().equals(TextMarkerProjectUtils.getDefaultScriptLocation())) {
+      folder = folder.removeLastSegments(1);
+    }
+    IPath relativeTo = scriptFilePath.makeRelativeTo(folder);
+    IPath projectPath = folder.removeLastSegments(1);
+    String elementName = scriptFilePath.lastSegment();
+    int lastIndexOf = elementName.lastIndexOf(".tm");
+    if (lastIndexOf != -1) {
+      elementName = elementName.substring(0, lastIndexOf);
+    }
+    IPath descPath = projectPath.append(TextMarkerProjectUtils.getDefaultDescriptorLocation());
+    IPath descPackagePath = descPath.append(relativeTo.removeLastSegments(1));
+    return descPackagePath.append(elementName + "TypeSystem.xml").toString();
+  }
+
+  public static synchronized String escapeForRegExp(String aRegexFragment) {
+    final StringBuilder result = new StringBuilder();
+
+    final StringCharacterIterator iterator = new StringCharacterIterator(aRegexFragment);
+    char character = iterator.current();
+    while (character != CharacterIterator.DONE) {
+      /*
+       * All literals need to have backslashes doubled.
+       */
+      if (character == '.') {
+        result.append("\\.");
+      } else if (character == '\\') {
+        result.append("\\\\");
+      } else if (character == '?') {
+        result.append("\\?");
+      } else if (character == '*') {
+        result.append("\\*");
+      } else if (character == '+') {
+        result.append("\\+");
+      } else if (character == '&') {
+        result.append("\\&");
+      } else if (character == ':') {
+        result.append("\\:");
+      } else if (character == '{') {
+        result.append("\\{");
+      } else if (character == '}') {
+        result.append("\\}");
+      } else if (character == '[') {
+        result.append("\\[");
+      } else if (character == ']') {
+        result.append("\\]");
+      } else if (character == '(') {
+        result.append("\\(");
+      } else if (character == ')') {
+        result.append("\\)");
+      } else if (character == '^') {
+        result.append("\\^");
+      } else if (character == '$') {
+        result.append("\\$");
+      } else {
+        // the char is not a special one
+        // add it to the result as is
+        result.append(character);
+      }
+      character = iterator.next();
+    }
+    return result.toString();
+  }
+
+  public static synchronized String escapeForTMStringParameter(String aTMStringFragment) {
+    final StringBuilder result = new StringBuilder();
+
+    final StringCharacterIterator iterator = new StringCharacterIterator(aTMStringFragment);
+    char character = iterator.current();
+    while (character != CharacterIterator.DONE) {
+      if (character == '"') {
+        result.append("\\\"");
+      } else if (character == '\\') {
+        result.append("\\\\");
+      } else {
+        result.append(character);
+      }
+      character = iterator.next();
+    }
+    return result.toString();
+  }
+
+  public static synchronized void appendStringToFile(String fileName, String str) {
+    try {
+      File f = new File(fileName);
+      BufferedWriter output;
+      if (!f.exists())
+        output = new BufferedWriter(new FileWriter(fileName));
+      else
+        output = new BufferedWriter(new FileWriter(fileName, true));
+      output.append(str);
+      output.close();
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+  }
+
+  public static synchronized TextRulerAnnotation convertToTargetAnnotation(AnnotationFS fs,
+          TextRulerExampleDocument doc, TextRulerTarget target, TypeSystem ts) {
+    AnnotationFS theAnnotation;
+    if (target.type == MLTargetType.SINGLE_LEFT_BOUNDARY)
+      theAnnotation = fs.getCAS().createAnnotation(ts.getType(target.getSingleSlotTypeName()),
+              fs.getBegin(), fs.getBegin());
+    else if (target.type == MLTargetType.SINGLE_RIGHT_BOUNDARY)
+      theAnnotation = fs.getCAS().createAnnotation(ts.getType(target.getSingleSlotTypeName()),
+              fs.getEnd(), fs.getEnd());
+    else
+      theAnnotation = fs;
+    return new TextRulerAnnotation(theAnnotation, doc);
+  }
+
+  public static synchronized List<Feature> getFilteredAnnotationFeatures(AnnotationFS afs) {
+    List<Feature> result = new ArrayList<Feature>();
+    List<Feature> theFeatures = afs.getType().getFeatures();
+    Set<String> filters = getStandardFeatureFilterSet();
+    for (Feature f : theFeatures)
+      if (!filters.contains(f.getName()))
+        result.add(f);
+    return result;
+  }
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerToolkit.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerToolkit.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerWordConstraint.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerWordConstraint.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerWordConstraint.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerWordConstraint.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,89 @@
+package org.apache.uima.tm.textruler.core;
+
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+
+/**
+ * 
+ * This class was moved from one of the algorithms to the core framework since it gets used in
+ * almost every algorithm. It encapsulates the word constraint e.g. of a TextMarker rule item.
+ */
+public class TextRulerWordConstraint {
+
+  protected TextRulerAnnotation tokenAnnotation;
+
+  protected boolean isRegExpType; // indicates wheter this token can have
+
+  // different contens according to its type
+
+  // (PERIOD e.g. is NOT such a token, it is bound to the content '.'; NUM is
+  // such a token, it can be any number!
+
+  public TextRulerWordConstraint(TextRulerWordConstraint copyFrom) {
+    super();
+    tokenAnnotation = copyFrom.tokenAnnotation;
+    isRegExpType = copyFrom.isRegExpType;
+  }
+
+  public TextRulerWordConstraint(TextRulerAnnotation tokenAnnotation) {
+    super();
+    this.tokenAnnotation = tokenAnnotation;
+    TypeSystem ts = tokenAnnotation.getDocument().getCAS().getTypeSystem();
+    Type wType = ts.getType(TextRulerToolkit.TM_WORD_TYPE_NAME);
+    Type numType = ts.getType(TextRulerToolkit.TM_NUM_TYPE_NAME);
+    Type markupType = ts.getType(TextRulerToolkit.TM_MARKUP_TYPE_NAME);
+    // TODO special auch wieder einschalten!? !!!!!
+    // Type specialType = ts.getType(TextRulerToolkit.TM_SPECIAL_TYPE_NAME);
+    isRegExpType = ts.subsumes(wType, tokenAnnotation.getType())
+            || ts.subsumes(markupType, tokenAnnotation.getType())
+            || ts.subsumes(numType, tokenAnnotation.getType())
+    // || ts.subsumes(specialType, tokenAnnotation.getType()
+    ;
+  }
+
+  protected TextRulerWordConstraint(TextRulerAnnotation tokenAnnotation, boolean isRegExpType) {
+    this.tokenAnnotation = tokenAnnotation;
+    this.isRegExpType = isRegExpType;
+  }
+
+  public Type annotationType() {
+    return tokenAnnotation.getType();
+  }
+
+  public String typeShortName() {
+    return tokenAnnotation.getType().getShortName();
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (o == null)
+      return false;
+    return toString().equals(((TextRulerWordConstraint) o).toString());
+  }
+
+  @Override
+  public int hashCode() {
+    return toString().hashCode();
+  }
+
+  public boolean isRegExpConstraint() {
+    return isRegExpType;
+  }
+
+  @Override
+  public String toString() {
+    if (isRegExpConstraint())
+      return TextRulerToolkit.escapeForTMStringParameter(TextRulerToolkit
+              .escapeForRegExp(tokenAnnotation.getCoveredText()));
+    else
+      return tokenAnnotation.getType().getShortName();
+  }
+
+  public TextRulerWordConstraint copy() {
+    return new TextRulerWordConstraint(this);
+  }
+
+  public TextRulerAnnotation getTokenAnnotation() {
+    return tokenAnnotation;
+  }
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerWordConstraint.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/core/TextRulerWordConstraint.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerController.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerController.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerController.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerController.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,228 @@
+package org.apache.uima.tm.textruler.extension;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.uima.tm.textruler.core.TextRulerToolkit;
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtensionRegistry;
+import org.eclipse.core.runtime.Path;
+import org.eclipse.core.runtime.Platform;
+
+
+/**
+ * The static class TextRulerController is the heart of the eclipse plug-in extension. It cares
+ * about the extension point and creates TextRulerLearnerController objects for the found algorithms
+ * and is the link to a UI that can build upon this controller (see .ui package).
+ * 
+ * A UI (or whoever) is notified about e.g. status updates via the TextRulerControllerDelegate
+ * interface.
+ */
+public class TextRulerController {
+
+  protected static ArrayList<TextRulerLearnerController> learners = null;
+
+  protected static String currentTempDir = null;
+
+  protected static String[] currentSlotNames = null;
+
+  protected static Set<String> currentFilters = null;
+
+  protected static TextRulerControllerDelegate currentDelegate = null;
+
+  protected static Thread preprocessorThread = null;
+
+  protected static boolean shouldAbort = false;
+
+  protected static String currentPreprocessorTMFile = null;
+
+  protected static Map<String, Map<String, Object>> currentAlgorithmParams;
+
+  private static boolean anAlgorithmIsRunning() {
+    for (TextRulerLearnerController i : getAvailableControllers()) {
+      if (i.isRunning())
+        return true;
+    }
+
+    return false;
+  }
+
+  public static int enabledAlgorithmsCount() {
+    int cnt = 0;
+    for (TextRulerLearnerController c : learners) {
+      if (c.isEnabled())
+        cnt++;
+    }
+    return cnt;
+  }
+
+  private static void preprocessorDidEnd(String algorithmsInputFolder, String additionalFolder) {
+    if (shouldAbort()) {
+      if (currentDelegate != null)
+        currentDelegate.globalStatusUpdate("Aborted!");
+      cleanUp();
+    } else {
+      if (currentDelegate != null)
+        currentDelegate.globalStatusUpdate("Running...");
+      // start algorithms
+      for (TextRulerLearnerController c : learners) {
+        if (c.isEnabled())
+          c.runInNewThread(algorithmsInputFolder, additionalFolder, currentPreprocessorTMFile,
+                  currentSlotNames, currentFilters, currentTempDir, currentDelegate,
+                  currentAlgorithmParams.get(c.getID()));
+      }
+
+    }
+    preprocessorThread = null;
+  }
+
+  private static void cleanUp() {
+    // cleaning up
+    // TODO delete all temporary files and directories?! this data are good
+    // for debugging...
+    currentTempDir = null;
+    currentPreprocessorTMFile = null;
+    currentSlotNames = null;
+    currentFilters = null;
+    currentDelegate = null;
+    currentAlgorithmParams = null;
+    shouldAbort = false;
+  }
+
+  protected static void saveParametersToTempFolder(String inFolder, boolean skipPreprocessing) {
+    String str = "\nSettings:\n\n";
+
+    str += "inputDir: " + inFolder;
+    str += "\npreprocessTMFile: " + currentPreprocessorTMFile;
+    str += "\nslotnames : ";
+    for (String s : currentSlotNames)
+      str += s + "; ";
+    str += "\nfilters: " + currentFilters;
+    str += "\nskip preproc: " + skipPreprocessing;
+    str += "\n";
+
+    TextRulerToolkit.appendStringToFile(TextRulerToolkit.addTrailingSlashToPath(currentTempDir)
+            + "settings.txt", str);
+  }
+
+  public static boolean start(final String inFolder, final String additionalFolder,
+          final String preprocessorTMFile, final String[] slotNames, Set<String> filters,
+          final TextRulerControllerDelegate delegate, Map<String, Map<String, Object>> algParams,
+          boolean skipPreprocessing) {
+    if (isRunning() || enabledAlgorithmsCount() == 0)
+      return false;
+
+    shouldAbort = false;
+
+    String outFolder = null;
+    try {
+      currentTempDir = TextRulerToolkit.createTemporaryDirectory();
+      outFolder = currentTempDir + "input";
+      File outputFolder = new File(outFolder);
+      outputFolder.mkdir();
+    } catch (IOException e) {
+      e.printStackTrace();
+      return false;
+    }
+
+    if (TextRulerToolkit.getEngineDescriptorFromTMSourceFile(new Path(preprocessorTMFile)).length() == 0)
+      return false;
+
+    currentPreprocessorTMFile = preprocessorTMFile;
+    currentSlotNames = slotNames;
+    currentFilters = filters;
+    currentDelegate = delegate;
+    currentAlgorithmParams = algParams;
+
+    saveParametersToTempFolder(inFolder, skipPreprocessing);
+    for (TextRulerLearnerController c : learners)
+      c.resetStatusString();
+
+    if (skipPreprocessing)
+      preprocessorDidEnd(inFolder, additionalFolder); // just use the original input folder
+    // as real input folder!
+    else {
+      preprocessorThread = new Thread(new Runnable() {
+        public void run() {
+          TextRulerPreprocessor p = new TextRulerPreprocessor();
+          String algorithmsInputFolder = p.run(inFolder, currentPreprocessorTMFile, currentTempDir,
+                  new TextRulerPreprocessorDelegate() {
+
+                    public void preprocessorStatusUpdate(TextRulerPreprocessor p,
+                            String statusString) {
+                      currentDelegate.preprocessorStatusUpdate(p, statusString);
+                    }
+
+                    public boolean shouldAbort() {
+                      return TextRulerController.shouldAbort();
+                    }
+
+                  });
+          preprocessorDidEnd(algorithmsInputFolder, additionalFolder);
+        }
+      });
+      if (currentDelegate != null)
+        currentDelegate.globalStatusUpdate("Preprocessing...");
+
+      preprocessorThread.setPriority(Thread.NORM_PRIORITY);
+      preprocessorThread.start();
+    }
+    return true;
+  }
+
+  public static TextRulerLearnerController getControllerForID(String id) {
+    for (TextRulerLearnerController c : getAvailableControllers())
+      if (c.getID().equals(id))
+        return c;
+    return null;
+  }
+
+  public static ArrayList<TextRulerLearnerController> getAvailableControllers() {
+    if (learners == null) {
+      learners = new ArrayList<TextRulerLearnerController>();
+      IExtensionRegistry reg = Platform.getExtensionRegistry();
+      if (reg == null)
+        return null;
+      IConfigurationElement[] extensions = reg
+              .getConfigurationElementsFor("org.apache.uima.tm.textruler.learners");
+      for (IConfigurationElement element : extensions) {
+        try {
+          TextRulerLearnerFactory factory = (TextRulerLearnerFactory) element
+                  .createExecutableExtension("class");
+          learners.add(new TextRulerLearnerController(element.getAttribute("id"), element
+                  .getAttribute("name"), factory));
+        } catch (CoreException e) {
+          e.printStackTrace();
+        }
+      }
+    }
+    return learners;
+  }
+
+  // gets called from TextRulerLearnerController when the algorithm thread did
+  // end
+  public static void anAlgorithmDidEnd(TextRulerLearnerController algController) {
+    if (!anAlgorithmIsRunning()) // all algorithms have finished
+    {
+      if (currentDelegate != null)
+        currentDelegate.globalStatusUpdate(shouldAbort ? "Aborted!" : "Done.");
+      cleanUp();
+    }
+  }
+
+  public static boolean isRunning() {
+    return preprocessorThread != null || anAlgorithmIsRunning();
+  }
+
+  public static synchronized boolean shouldAbort() {
+    return shouldAbort;
+  }
+
+  public static synchronized void abort() {
+    shouldAbort = true;
+  }
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerController.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerController.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerControllerDelegate.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerControllerDelegate.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerControllerDelegate.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerControllerDelegate.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,20 @@
+package org.apache.uima.tm.textruler.extension;
+
+import org.apache.uima.tm.textruler.extension.TextRulerLearner.TextRulerLearnerState;
+
+/**
+ * TextRulerControllerDelegate provides some useful notificaion methods e.g. a UI class can
+ * implement to get some important information.
+ */
+public interface TextRulerControllerDelegate {
+
+  public void algorithmDidEnd(TextRulerLearnerController algController);
+
+  public void algorithmStatusUpdate(TextRulerLearnerController algController, String statusString,
+          TextRulerLearnerState state, boolean ruleBaseChanged);
+
+  public void preprocessorStatusUpdate(TextRulerPreprocessor p, String statusString);
+
+  public void globalStatusUpdate(String str);
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerControllerDelegate.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerControllerDelegate.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearner.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearner.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearner.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearner.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,60 @@
+package org.apache.uima.tm.textruler.extension;
+
+import java.util.Map;
+
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.cas.CAS;
+
+/**
+ * If you want to add an own algorithm to the TextRuler-System, you can do this by providing two
+ * classes:
+ * 
+ * One algorithm class that implements the interface
+ * 
+ * TextRulerLearner
+ * 
+ * And one factory class that can create an instance of that algorithm. This factory has to
+ * implement the interface
+ * 
+ * MLAlgoriothmFactory
+ * 
+ * which gets created and used by adding an extension point to
+ * 
+ * org.apache.uima.tm.textruler.algorithms
+ * 
+ */
+public interface TextRulerLearner {
+
+  enum TextRulerLearnerState {
+    ML_UNDEFINED, ML_INITIALIZING, ML_RUNNING, ML_ERROR, ML_ABORTED, ML_DONE
+  };
+
+  /**
+   * There the magic has to be placed...
+   */
+  void run();
+
+  /**
+   * this method gets called from the UI and passes a hashMap with key value coded parameters that
+   * your corresponding TextRulerLearnerFactory declared by its getAlgorithmParameters method.
+   */
+  void setParameters(Map<String, Object> params);
+
+  /**
+   * If any TextMarker-Rules result is available (yet), the system asks your algorithm for it by
+   * calling this method.
+   */
+  String getResultString();
+
+  /**
+   * 
+   * @return
+   */
+  AnalysisEngine getAnalysisEngine();
+
+  /**
+   * 
+   * @return
+   */
+  CAS getTestCAS();
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearner.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearner.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerController.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerController.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerController.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerController.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,155 @@
+package org.apache.uima.tm.textruler.extension;
+
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.uima.tm.textruler.core.TextRulerToolkit;
+import org.apache.uima.tm.textruler.extension.TextRulerLearner.TextRulerLearnerState;
+
+
+/**
+ * This class encapsulates the functionality for administrating an algorithm that was added via the
+ * eclipse extension point. It e.g. holds the three extension point parameters name, factory class
+ * and the id, cares about running the algorithm in an own thread, act as the algorithm's delegate,
+ * hold the algorithms results and status string and pass it to a possible UI
+ * (TextRulerControllerDelegate), ...
+ * 
+ */
+public class TextRulerLearnerController implements TextRulerLearnerDelegate {
+
+  // these three are extracted from the extension points:
+  protected String name; // name of the algorithm
+
+  protected TextRulerLearnerFactory algoritmFactory; // the factory that can create an instance of
+
+  // it
+
+  protected String id; // the id of this algorithm
+
+  // other member variables:
+  protected boolean enabled; // flag if this algorithm is enabled for learning
+
+  protected TextRulerLearner algorithm; // the algorithm, null if it is not running currently
+
+  protected Thread thread; // the thread in which we run the algorithm, null if not running
+
+  protected TextRulerControllerDelegate delegate; // the delegate for status notifications, etc.
+
+  protected String currentStatusString; // the current status String that the algorithm reported to
+
+  // us
+
+  protected TextRulerLearnerState algorithmState = TextRulerLearnerState.ML_UNDEFINED; // the
+
+  // current
+  // state
+
+  protected String resultString; // the current rules result string
+
+  public TextRulerLearnerController(String id, String name, TextRulerLearnerFactory factory) {
+    super();
+    this.id = id;
+    this.name = name;
+    this.algoritmFactory = factory;
+  }
+
+  public String getID() {
+    return id;
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public String toString() // give back a status string that the UI can directly print or
+  // whatever...
+  {
+    if (currentStatusString != null)
+      return getName() + " - " + currentStatusString;
+    else
+      return getName();
+  }
+
+  public boolean isEnabled() {
+    return enabled;
+  }
+
+  public void setEnabled(boolean value) {
+    enabled = value;
+  }
+
+  public boolean isRunning() {
+    return thread != null;
+  }
+
+  private void sendUpdateToDelegate(boolean ruleBaseChanged) {
+    if (delegate != null)
+      delegate.algorithmStatusUpdate(this, currentStatusString, algorithmState, ruleBaseChanged);
+  }
+
+  // TextRulerLearnerDelegate Methods
+  public boolean shouldAbort() {
+    return TextRulerController.shouldAbort();
+  }
+
+  public void algorithmStatusUpdate(TextRulerLearner alg, String statusString,
+          TextRulerLearnerState state, boolean ruleBaseChanged) {
+    resultString = alg.getResultString();
+    algorithmState = state;
+    currentStatusString = statusString;
+    sendUpdateToDelegate(ruleBaseChanged);
+  }
+
+  public String getCurrentResultString() {
+    if (algorithm != null)
+      resultString = algorithm.getResultString();
+    return resultString;
+  }
+
+  private void algorithmDidEnd() {
+    thread = null;
+    if (delegate != null)
+      delegate.algorithmDidEnd(this);
+    delegate = null;
+    algorithm = null;
+    TextRulerController.anAlgorithmDidEnd(this);
+  }
+
+  public boolean runInNewThread(final String inputFolderPath, final String additionalFolderPath,
+          final String preprocessorTMfile, final String[] slotNames, final Set<String> filters,
+          final String tempBaseDirectory, TextRulerControllerDelegate delegate,
+          final Map<String, Object> algorithmParams) {
+    if (thread == null) {
+      final TextRulerLearnerDelegate algDelegate = this;
+      this.delegate = delegate;
+      thread = new Thread(new Runnable() {
+        public void run() {
+          String tmpDir = TextRulerToolkit.addTrailingSlashToPath(tempBaseDirectory + getID());
+          algorithm = algoritmFactory.createAlgorithm(inputFolderPath, additionalFolderPath,
+                  preprocessorTMfile, tmpDir, slotNames, filters, algDelegate);
+          algorithm.setParameters(algorithmParams);
+          algorithm.run();
+          algorithmDidEnd();
+          System.gc();
+        }
+      }
+
+      );
+      thread.setPriority(Thread.NORM_PRIORITY);
+      thread.start();
+      return true;
+    } else {
+      return false;
+    }
+  }
+
+  public void resetStatusString() {
+    currentStatusString = null;
+  }
+
+  public TextRulerLearnerFactory getFactory() {
+    return algoritmFactory;
+  }
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerController.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerController.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerDelegate.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerDelegate.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerDelegate.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerDelegate.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,20 @@
+package org.apache.uima.tm.textruler.extension;
+
+import org.apache.uima.tm.textruler.extension.TextRulerLearner.TextRulerLearnerState;
+
+/**
+ * 
+ * An TextRulerLearnerDelegate is used for an TextRulerLearner so that it can e.g. send status
+ * updates to some one that might be interested (in our case the controller and though the UI). In
+ * addition to that, the algorithm can ask the delegate if he should abort his work (e.g. because
+ * the user clicked the abort button).
+ * 
+ */
+public interface TextRulerLearnerDelegate {
+
+  public void algorithmStatusUpdate(TextRulerLearner alg, String statusString,
+          TextRulerLearnerState state, boolean ruleBaseChanged);
+
+  public boolean shouldAbort();
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerDelegate.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerDelegate.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerFactory.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerFactory.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerFactory.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerFactory.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,48 @@
+package org.apache.uima.tm.textruler.extension;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * The TextRuler system uses this interface to create an algorithm you added to it via the extension
+ * point.
+ * 
+ * Please see TextRulerLearner for more detailed information.
+ */
+public interface TextRulerLearnerFactory {
+
+  /**
+   * @param inputFolderPath
+   *          the input folder path where e.g. example XMIs are located
+   * @param additionalFolderPath TODO
+   * @param preprocessorTMfile
+   *          the preprocessing TextMarker file (this is important for finding the type system and
+   *          analysis engine descriptor file)
+   * @param tempFolderPath
+   *          a folder name that you can use as temporary folder (caution: you need to create it if
+   *          you want to use it!)
+   * @param fullSlotTypeNames
+   *          an array with the slot-names to learn (full qualified UIMA type names)
+   * @param delegate
+   *          a delegate that can be notified for status updates and asked for aborting the
+   *          algorithm
+   * @param the
+   *          TextMarker filter set (full qualified UIMA type names)
+   * @return the algorithm of your class that implements TextRulerLearner
+   */
+  public TextRulerLearner createAlgorithm(String inputFolderPath, String additionalFolderPath,
+          String preprocessorTMfile, String tempFolderPath, String[] fullSlotTypeNames,
+          Set<String> filterSet, TextRulerLearnerDelegate delegate);
+
+  /**
+   * @return null or an array with MLAlgorithmParameters your TextRulerLearner wants to get from the
+   *         GUI
+   */
+  public TextRulerLearnerParameter[] getAlgorithmParameters();
+
+  /**
+   * @return null or a key value set for the standard values of your algorithm's parameters
+   */
+  public Map<String, Object> getAlgorithmParameterStandardValues();
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerFactory.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerFactory.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerParameter.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerParameter.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerParameter.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerParameter.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,52 @@
+package org.apache.uima.tm.textruler.extension;
+
+/**
+ * With your TextRulerLearnerFactory-class you can specify some parameters your algorithm has (e.g.
+ * a window size for extracting features around a token or such). This is done with an array of
+ * 
+ * TextRulerLearnerParameter
+ * 
+ * objects. In the TextRuler UI in Eclipse some widgets get automatically created for those
+ * parameters if the algorithm is selected in the algorithm list.
+ */
+public class TextRulerLearnerParameter {
+
+  public enum MLAlgorithmParamType {
+    ML_STRING_PARAM, ML_BOOL_PARAM, ML_INT_PARAM, ML_FLOAT_PARAM, ML_SELECT_PARAM
+  };
+
+  public static class MLParameterSelectValue {
+    public String id;
+
+    public String name;
+
+    public MLParameterSelectValue(String id, String name) {
+      this.id = id;
+      this.name = name;
+    }
+  }
+
+  public String id;
+
+  public String name;
+
+  public MLAlgorithmParamType type;
+
+  public MLParameterSelectValue[] selectValues;
+
+  public TextRulerLearnerParameter(String id, String name, MLAlgorithmParamType type) {
+    this.id = id;
+    this.name = name;
+    this.type = type;
+    selectValues = null;
+  }
+
+  public TextRulerLearnerParameter(String id, String name, MLAlgorithmParamType type,
+          MLParameterSelectValue[] values) {
+    this.id = id;
+    this.name = name;
+    this.type = type;
+    this.selectValues = values;
+  }
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerParameter.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerLearnerParameter.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessor.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessor.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessor.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessor.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,93 @@
+package org.apache.uima.tm.textruler.extension;
+
+import java.io.File;
+import java.io.FilenameFilter;
+
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.tm.textruler.core.GlobalCASSource;
+import org.apache.uima.tm.textruler.core.TextRulerToolkit;
+import org.eclipse.core.runtime.Path;
+
+
+/**
+ * This "algorithm" gets executed right before the real algorithms get started. It preprocesses the
+ * input XMI files with the given TextMarker preprocessing file and stores the results in a
+ * temporary folder. Those new XMI files are then passed as input documents to the MLAlgorithms.
+ * 
+ */
+public class TextRulerPreprocessor {
+
+  public String run(String inFolder, String tmFile, String tmpDir,
+          TextRulerPreprocessorDelegate delegate) {
+    AnalysisEngine ae = TextRulerToolkit.loadAnalysisEngine(TextRulerToolkit
+            .getEngineDescriptorFromTMSourceFile(new Path(tmFile)));
+
+    // preprocess input XMIs
+    File inputFolder = new File(inFolder);
+    File outputFolder = new File(tmpDir + "input");
+    File[] files = inputFolder.listFiles(new FilenameFilter() {
+      public boolean accept(File dir, String name) {
+        return (name.endsWith(".xmi"));
+      }
+    });
+
+    try {
+      outputFolder.mkdir();
+      // FileUtils.saveString2File("PACKAGE de.uniwue.ml;\n\n", new
+      // File(tmpDir+"preprocess.tm"));
+      // ae.setConfigParameterValue(TextMarkerEngine.SCRIPT_LOCATION,
+      // tmpDir+"preprocess.tm");
+      // IPath path = new Path(tmFile);
+      // IPath scriptRoot = new Path(tmFile);
+      // while (!scriptRoot.lastSegment().equals(TextMarkerProjectUtils.getDefaultScriptLocation()))
+      // {
+      // scriptRoot = scriptRoot.removeLastSegments(1);
+      // }
+      // IPath makeRelativeTo = path.makeRelativeTo(scriptRoot);
+      //
+      // String replaceAll =
+      // makeRelativeTo.removeFileExtension().toPortableString().replaceAll("[/]",
+      // ".");
+      // Object configParameterValue = ae.getConfigParameterValue(TextMarkerEngine.MAIN_SCRIPT);
+      // ae.setConfigParameterValue(TextMarkerEngine.MAIN_SCRIPT, replaceAll);
+      // ae.setConfigParameterValue(TextMarkerEngine.SCRIPT_PATHS, new String[] { scriptRoot
+      // .toPortableString() });
+      // ae.setConfigParameterValue(TextMarkerEngine.USE_SCANNER, true);
+      // ae.reconfigure();
+    } catch (Exception e) {
+      e.printStackTrace();
+      return null;
+    }
+
+    CAS cas = null;
+    for (File file : files) {
+      if (delegate != null && delegate.shouldAbort()) {
+        TextRulerToolkit.log("[PREPROCESSOR] ABORT");
+        break;
+      }
+      TextRulerToolkit.log("Load INPUT XMI file: " + file.getName());
+      if (delegate != null)
+        delegate.preprocessorStatusUpdate(this, "Loading input XMI file: " + file.getName());
+      cas = TextRulerToolkit.readCASfromXMIFile(file, ae, cas);
+      System.out.print("Processing...");
+      try {
+        ae.process(cas);
+        TextRulerToolkit.log(" OK");
+        TextRulerToolkit.writeCAStoXMIFile(cas, outputFolder + "/processed_" + file.getName());
+      } catch (Exception e) {
+        e.printStackTrace();
+        TextRulerToolkit.log(" ERROR!");
+      }
+      cas.reset();
+      if (delegate != null)
+        delegate.preprocessorStatusUpdate(this, "Done");
+    }
+    if (cas != null) {
+      cas.reset();
+      GlobalCASSource.releaseCAS(cas);
+    }
+    return tmpDir + "input";
+  }
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessor.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessor.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessorDelegate.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessorDelegate.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessorDelegate.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessorDelegate.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,13 @@
+package org.apache.uima.tm.textruler.extension;
+
+/**
+ * Small helper class for possible UI implementations for the preprocessor (see .ui)
+ * 
+ */
+public interface TextRulerPreprocessorDelegate {
+
+  public void preprocessorStatusUpdate(TextRulerPreprocessor p, String statusString);
+
+  public boolean shouldAbort();
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessorDelegate.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/extension/TextRulerPreprocessorDelegate.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/AlgorithmPreferencePage.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/AlgorithmPreferencePage.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/AlgorithmPreferencePage.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/AlgorithmPreferencePage.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,135 @@
+package org.apache.uima.tm.textruler.preferences;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.uima.tm.textruler.TextRulerPlugin;
+import org.apache.uima.tm.textruler.extension.TextRulerLearnerController;
+import org.apache.uima.tm.textruler.extension.TextRulerLearnerFactory;
+import org.apache.uima.tm.textruler.extension.TextRulerLearnerParameter;
+import org.eclipse.jface.preference.BooleanFieldEditor;
+import org.eclipse.jface.preference.FieldEditor;
+import org.eclipse.jface.preference.FieldEditorPreferencePage;
+import org.eclipse.jface.preference.IPreferencePage;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.preference.StringFieldEditor;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+
+public class AlgorithmPreferencePage extends FieldEditorPreferencePage implements
+        IPreferencePage {
+
+  public static String ID = "org.apache.uima.tm.textruler.algorithmPages";
+
+  private TextRulerLearnerController algorithmController;
+
+  private IPreferenceStore store;
+
+  private ArrayList<FieldEditor> fields = new ArrayList<FieldEditor>();
+
+  public AlgorithmPreferencePage(TextRulerLearnerController algorithmController) {
+    super(FieldEditorPreferencePage.GRID);
+    this.algorithmController = algorithmController;
+    store = TextRulerPlugin.getDefault().getPreferenceStore();
+    setPreferenceStore(store);
+  }
+
+  protected void createFieldEditors() {
+    TextRulerLearnerFactory f = algorithmController.getFactory();
+    TextRulerLearnerParameter[] params = f.getAlgorithmParameters();
+    Map<String, Object> values = f.getAlgorithmParameterStandardValues();
+    if (params != null) {
+      for (int i = 0; i < params.length; i++) {
+        TextRulerLearnerParameter p = params[i];
+        String id = algorithmController.getID() + "." + p.id;
+        FieldEditor l = null;
+        switch (p.type) {
+          case ML_BOOL_PARAM: {
+            l = new BooleanFieldEditor(id, p.name, getFieldEditorParent());
+            fields.add(l);
+            addField(l);
+            store.setDefault(id, (Boolean) values.get(p.id));
+            l.setPreferenceStore(store);
+            break;
+          }
+
+          case ML_FLOAT_PARAM:
+          case ML_INT_PARAM:
+          case ML_STRING_PARAM: {
+            l = new StringFieldEditor(id, p.name, getFieldEditorParent());
+            fields.add(l);
+            addField(l);
+            store.setDefault(id, values.get(p.id).toString());
+            l.setPreferenceStore(store);
+            break;
+          }
+            // case ML_SELECT_PARAM: {
+            // Combo combo = new Combo(top, SWT.READ_ONLY);
+            // if (p.selectValues != null)
+            // for (MLParameterSelectValue v : p.selectValues) {
+            // combo.add(v.name);
+            // }
+            // c = combo;
+            // break;
+            // }
+          case ML_SELECT_PARAM:
+            break;
+        }
+      }
+    }
+  }
+
+//  public Map<String, Object> getCurrentAlgorithmParameters() {
+//    // Map<String, Map<String, Object>> results = new HashMap<String, Map<String, Object>>();
+//    Map<String, Object> result = new HashMap<String, Object>();
+//
+//    TextRulerLearnerFactory f = algorithmController.getFactory();
+//    TextRulerLearnerParameter[] params = f.getAlgorithmParameters();
+//    if (params != null) {
+//      for (int i = 0; i < params.length; i++) {
+//        TextRulerLearnerParameter p = params[i];
+//        String id = algorithmController.getID() + "." + p.id;
+//        switch (p.type) {
+//          case ML_BOOL_PARAM: {
+//            // Map<String, Object> result = new HashMap<String, Object>();
+//            result.put(p.id, store.getBoolean(id));
+//            // results.put(p.id, result);
+//            break;
+//          }
+//
+//          case ML_FLOAT_PARAM:
+//          case ML_INT_PARAM:
+//          case ML_STRING_PARAM: {
+//            // Map<String, Object> result = new HashMap<String, Object>();
+//            result.put(p.id, store.getString(id));
+//            // results.put(p.id, result);
+//            break;
+//          }
+//            // case ML_SELECT_PARAM: {
+//            // break;
+//            // }
+//          case ML_SELECT_PARAM:
+//            break;
+//        }
+//      }
+//    }
+//    return result;
+//  }
+
+  @Override
+  protected void performDefaults() {
+    for (FieldEditor f : fields)
+      f.loadDefault();
+    // super.performDefaults();
+  }
+
+  @Override
+  public boolean performOk() {
+    for (FieldEditor f : fields)
+      f.store();
+    // return super.performOk();
+    return true;
+  }
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/AlgorithmPreferencePage.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/AlgorithmPreferencePage.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/ConfigPreferencePage.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/ConfigPreferencePage.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/ConfigPreferencePage.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/ConfigPreferencePage.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,39 @@
+package org.apache.uima.tm.textruler.preferences;
+
+import org.eclipse.jface.preference.PreferencePage;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.ui.IWorkbench;
+import org.eclipse.ui.IWorkbenchPreferencePage;
+
+public class ConfigPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
+
+  public static String ID = "org.apache.uima.tm.textruler.config";
+
+  private Label evalHeadline;
+
+  public ConfigPreferencePage() {
+
+  }
+
+  @Override
+  protected Control createContents(Composite parent) {
+    Composite top = new Composite(parent, SWT.LEFT);
+    top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
+    top.setLayout(new GridLayout());
+
+    evalHeadline = new Label(top, SWT.NULL);
+    evalHeadline.setText("General settings for the different TextRuler methods.");
+
+    return top;
+  }
+
+  @Override
+  public void init(IWorkbench workbench) {
+    
+  }
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/ConfigPreferencePage.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/preferences/ConfigPreferencePage.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleEvaluator.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleEvaluator.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleEvaluator.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleEvaluator.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,166 @@
+package org.apache.uima.tm.textruler.tools;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.resource.ResourceConfigurationException;
+import org.apache.uima.tm.textmarker.engine.TextMarkerEngine;
+import org.apache.uima.tm.textruler.core.TextRulerToolkit;
+import org.apache.uima.util.FileUtils;
+import org.eclipse.core.runtime.IPath;
+import org.eclipse.core.runtime.Path;
+
+public class BatchRuleEvaluator {
+
+  private static AnalysisEngine ae;
+
+  private static String engineFile;
+
+  // private static String preprocessorTMFile;
+  private static String tempDir;
+
+  private static String foldRootDirectory;
+
+  private static int foldCount = 0;
+
+  private static CAS sharedCAS;
+
+  public static AnalysisEngine getAnalysisEngine() {
+    if (ae == null) {
+      // String descriptorFile =
+      // TextRulerToolkit.getEngineDescriptorFromTMSourceFile(new
+      // Path(preprocessorTMFile));
+      String descriptorFile = engineFile;
+      TextRulerToolkit.log("loading AE...");
+      ae = TextRulerToolkit.loadAnalysisEngine(descriptorFile);
+
+      // set filters to NO filtering so that we can add it manually with
+      // the FILTERTYPE expression!
+      ae.setConfigParameterValue(TextMarkerEngine.DEFAULT_FILTERED_MARKUPS, new String[0]);
+      IPath path = new Path(tempDir + "/results.tm");
+      ae.setConfigParameterValue(TextMarkerEngine.MAIN_SCRIPT, path.removeFileExtension()
+              .lastSegment());
+      ae.setConfigParameterValue(TextMarkerEngine.SCRIPT_PATHS, new String[] { path
+              .removeLastSegments(1).toPortableString() });
+      // ae.setConfigParameterValue(TextMarkerEngine.SEEDERS, new String[] {});
+      try {
+        ae.reconfigure();
+      } catch (ResourceConfigurationException e) {
+        e.printStackTrace();
+        return null;
+      }
+    }
+    return ae;
+  }
+
+  private static File[] getXMIFileFromFolder(String folderName) {
+    File folder = new File(folderName);
+    File[] files = folder.listFiles(new FilenameFilter() {
+      public boolean accept(File dir, String name) {
+        return (name.endsWith(".xmi"));
+      }
+    });
+    return files;
+  }
+
+  /**
+   * @param args
+   */
+  public static void main(String[] args) {
+
+    // preprocessorTMFile =
+    // "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/script/de.uniwue.ml/ML.tm";
+    tempDir = "/testinput/temp/"; // mit / am Ende !!
+    engineFile = "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/Subset100/10fold/desc/lp2ergebnisrandomgiantEngine.xml";
+    // foldRootDirectory =
+    // "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/Subset100/10fold/";//
+    // mit / am Ende !!
+    foldRootDirectory = "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/9010_middle/";// mit
+    // /
+    // am
+    // Ende
+    // !!
+    foldCount = 1;
+    String slotNames[] = { "de.uniwue.ml.types.etime", "de.uniwue.ml.types.stime",
+        "de.uniwue.ml.types.location", "de.uniwue.ml.types.speaker" };
+    String algIDs[] = { "optimizedLP2"// ,
+    // "rapier",
+    // "whisk"
+    };
+
+    // TODO back to 0 !
+    for (int foldNumber = 0; foldNumber < foldCount; foldNumber++) {
+      for (String slotName : slotNames) {
+        for (String algID : algIDs) {
+          runRules(foldNumber, slotName, algID);
+        }
+      }
+    }
+
+  }
+
+  public static void runRules(int foldNumber, String slotName, String algorithmID) {
+    getAnalysisEngine(); // ae erzeugen falls noch nicht geschehen...
+
+    TextRulerToolkit.log("Testing Fold Number " + foldNumber + "\t  Slot: " + slotName
+            + "\t  Algorithm: " + algorithmID);
+
+    // Input: 0/testing/withouttags/*.xmi
+    String inputFolder = foldRootDirectory + foldNumber + "/testing/withouttags/";
+    String rulesFile = foldRootDirectory + foldNumber + "/learnResults/" + slotName + "/"
+            + algorithmID + "/results.tm";
+    String scriptFile = tempDir + "results.tm";
+    File oldScriptFile = new File(scriptFile);
+    if (oldScriptFile.exists()) {
+      if (!oldScriptFile.delete()) {
+        TextRulerToolkit.log("ERROR DELETING OLD SCRIPT FILE: " + scriptFile);
+        return;
+      }
+    }
+
+    if (!new File(rulesFile).exists()) {
+      TextRulerToolkit.log("\tSKIPPED, no rules file not found!");
+      return;
+    }
+
+    try {
+      FileUtils.copyFile(new File(rulesFile), new File(tempDir));
+    } catch (IOException e) {
+      // TODO Auto-generated catch block
+      e.printStackTrace();
+      return;
+    }
+
+    String outputFolder1 = foldRootDirectory + foldNumber + "/testing/markedFromRules";
+    String outputFolder2 = foldRootDirectory + foldNumber + "/testing/markedFromRules/" + slotName;
+    String outputFolder = foldRootDirectory + foldNumber + "/testing/markedFromRules/" + slotName
+            + "/" + algorithmID;
+    new File(outputFolder1).mkdir();
+    new File(outputFolder2).mkdir();
+    new File(outputFolder).mkdir();
+
+    File[] inputFiles = getXMIFileFromFolder(inputFolder);
+
+    for (File inputFile : inputFiles) {
+      // TextRulerToolkit.log("FILE TO TEST: "+inputFile.getAbsolutePath());
+      // TextRulerToolkit.log(" RESULT FILE: "+TextRulerToolkit.addTrailingSlashToPath(outputFolder)+"fromRules_"+inputFile.getName());
+
+      sharedCAS = TextRulerToolkit.readCASfromXMIFile(inputFile, ae, sharedCAS);
+
+      try {
+        ae.process(sharedCAS);
+      } catch (AnalysisEngineProcessException e) {
+        e.printStackTrace();
+        return;
+      }
+      TextRulerToolkit.writeCAStoXMIFile(sharedCAS, TextRulerToolkit
+              .addTrailingSlashToPath(outputFolder)
+              + "fromRules_" + inputFile.getName());
+    }
+  }
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleEvaluator.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleEvaluator.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleScorer.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleScorer.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleScorer.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleScorer.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,87 @@
+package org.apache.uima.tm.textruler.tools;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.tm.textruler.core.TextRulerToolkit;
+import org.apache.uima.tm.textruler.tools.F1Scorer.Score;
+import org.apache.uima.util.FileUtils;
+
+public class BatchRuleScorer {
+
+  private static String engineFile;
+
+  // private static String preprocessorTMFile;
+  private static String foldRootDirectory;
+
+  private static int foldCount = 0;
+
+  private static AnalysisEngine ae = null;
+
+  public static void main(String[] args) {
+    // preprocessorTMFile =
+    // "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/script/de.uniwue.ml/ML.tm";
+    engineFile = "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/Subset100/10fold/desc/lp2ergebnisrandomgiantEngine.xml";
+    // foldRootDirectory =
+    // "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/Subset100/10fold/";//
+    // mit / am Ende !!
+    foldRootDirectory = "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/9010_middle/";// mit
+    // /
+    // am
+    // Ende
+    // !!
+    foldCount = 1;
+    String slotNames[] = { "de.uniwue.ml.types.etime", "de.uniwue.ml.types.stime",
+        "de.uniwue.ml.types.location", "de.uniwue.ml.types.speaker" };
+    String algIDs[] = { "optimizedLP2"// ,
+    // "rapier",
+    // "whisk"
+    };
+
+    ae = TextRulerToolkit.loadAnalysisEngine(engineFile);
+
+    // TODO back to 0 !
+    for (int foldNumber = 0; foldNumber < foldCount; foldNumber++) {
+      for (String slotName : slotNames) {
+        for (String algID : algIDs) {
+          scoreRules(foldNumber, slotName, algID);
+        }
+      }
+    }
+    // F1Scorer scorer = new F1Scorer(
+    // "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/descriptor/de.uniwue.ml/lp2validateEngine.xml",
+    // "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/Subset100/10fold/2/testing/withtags",
+    // "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/output"
+    // );
+    // Score score = scorer.scoreSlot("de.uniwue.ml.types.stime");
+    // if (score != null)
+    // score.logInfo();
+  }
+
+  public static void scoreRules(int foldNumber, String slotName, String algorithmID) {
+    TextRulerToolkit.log("Scoring Fold Number " + foldNumber + "\t  Slot: " + slotName
+            + "\t  Algorithm: " + algorithmID);
+
+    String fromRulesFolder = foldRootDirectory + foldNumber + "/testing/markedFromRules/"
+            + slotName + "/" + algorithmID + "/";
+    String originalsFolder = foldRootDirectory + foldNumber + "/testing/withtags/";
+    String resultsFile = foldRootDirectory + foldNumber + "/testing/score_" + foldNumber + "_"
+            + algorithmID + "." + slotName + ".txt";
+    if (!new File(fromRulesFolder).exists()) {
+      TextRulerToolkit.log("\tSKIPPED, fromRulesFolder not found!");
+      return;
+    }
+    F1Scorer scorer = new F1Scorer(ae, originalsFolder, fromRulesFolder);
+    Score slotScore = scorer.scoreSlot(slotName);
+    String str = "Score Results for Fold " + foldNumber + "\t  Slot: " + slotName
+            + "\t  Algorithm: " + algorithmID + "\n\n";
+    str += slotScore.toString();
+    try {
+      FileUtils.saveString2File(str, new File(resultsFile));
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+  }
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleScorer.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/BatchRuleScorer.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/F1Scorer.java
URL: http://svn.apache.org/viewvc/uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/F1Scorer.java?rev=1152792&view=auto
==============================================================================
--- uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/F1Scorer.java (added)
+++ uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/F1Scorer.java Mon Aug  1 14:21:12 2011
@@ -0,0 +1,206 @@
+package org.apache.uima.tm.textruler.tools;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import org.apache.uima.analysis_engine.AnalysisEngine;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.tm.textruler.core.CasCache;
+import org.apache.uima.tm.textruler.core.CasCacheLoader;
+import org.apache.uima.tm.textruler.core.GlobalCASSource;
+import org.apache.uima.tm.textruler.core.TextRulerExample;
+import org.apache.uima.tm.textruler.core.TextRulerExampleDocument;
+import org.apache.uima.tm.textruler.core.TextRulerTarget;
+import org.apache.uima.tm.textruler.core.TextRulerToolkit;
+
+public class F1Scorer implements CasCacheLoader {
+
+  private AnalysisEngine ae;
+
+  ArrayList<TextRulerExampleDocument> trainingDocuments;
+
+  String[] testFileNames;
+
+  public static class Score {
+    public String slotName;
+
+    public int tp; // true positives: correct extracted slots
+
+    public int fp; // false positives: spurious fillers that do not occur in
+
+    // the original document
+    public int fn; // false negatives: missing slots that occur in the
+
+    // document but not in the result
+
+    public void logInfo() {
+      TextRulerToolkit.log(toString());
+    }
+
+    @Override
+    public String toString() {
+      String str = "Slot: '" + slotName + "';  tp=" + tp + "\tfp=" + fp + "\tfn=" + fn + "\n";
+      str += "\tPrecision: \t" + precision() + "\n";
+      str += "\tRecall:    \t" + recall() + "\n";
+      str += "\tF1 Score:  \t" + f1Score() + "\n";
+      return str;
+    }
+
+    public double f1Score() {
+      return f1Score(precision(), recall());
+    }
+
+    public static double f1Score(double P, double R) {
+      if (P + R == 0)
+        return 0;
+      else
+        return (2 * P * R) / (P + R);
+    }
+
+    public double precision() {
+      double v = tp + fp;
+      if (v == 0)
+        return 0;
+      else
+        return (tp) / v;
+    }
+
+    public double recall() {
+      double v = tp + fn;
+      if (v == 0)
+        return 0;
+      else
+        return (tp) / v;
+    }
+  }
+
+  public static String[] getXMIfileNames(String folderName) {
+    File folder = new File(folderName);
+    File[] files = folder.listFiles(new FilenameFilter() {
+      public boolean accept(File dir, String name) {
+        return (name.endsWith(".xmi"));
+      }
+    });
+    ArrayList<String> resultList = new ArrayList<String>();
+    for (File f : files)
+      resultList.add(f.getAbsolutePath());
+
+    Comparator<String> cmp = new Comparator<String>() {
+
+      public int compare(String o1, String o2) {
+        return o1.compareTo(o2);
+      }
+
+    };
+    Collections.sort(resultList, cmp);
+    return resultList.toArray(new String[0]);
+  }
+
+  public F1Scorer(String descriptorFile, String trainingFolder, String testFolder) {
+    this(TextRulerToolkit.loadAnalysisEngine(descriptorFile), trainingFolder, testFolder);
+  }
+
+  public F1Scorer(AnalysisEngine ae, String trainingFolder, String testFolder) {
+    this.ae = ae;
+
+    trainingDocuments = new ArrayList<TextRulerExampleDocument>();
+    CasCache casCache = new CasCache(5, this);
+
+    for (String fileName : getXMIfileNames(trainingFolder))
+      trainingDocuments.add(new TextRulerExampleDocument(fileName, casCache));
+    testFileNames = getXMIfileNames(testFolder);
+  }
+
+  public Score scoreSlot(String slotName) {
+    Score result = new Score();
+    // TODO set a learner here... or something else...
+    TextRulerTarget target = new TextRulerTarget(slotName, null);
+    result.slotName = slotName;
+    int index = 0;
+    CAS testCAS = null;
+    for (TextRulerExampleDocument doc : trainingDocuments) {
+      CAS exampleCAS = doc.getCAS();
+      if (index >= testFileNames.length) {
+        TextRulerToolkit.log("ABORTING DUE TO NON TEST-EXISTENT FILE! ");
+        break;
+      }
+      testCAS = loadCAS(testFileNames[index], testCAS);
+      if (!testCAS.getDocumentText().equals((exampleCAS.getDocumentText()))) {
+        TextRulerToolkit.log("ERROR, EXAMPLE AND TEST DOCUMENT MISMATCH! WRONG FILE ORDER?");
+        return null;
+      }
+
+      doc.clearCurrentExamples();
+      doc.createExamplesForTarget(target);
+      compareOriginalDocumentWithTestCAS(doc, testCAS, target, result);
+      testCAS.reset();
+      index++;
+    }
+    testCAS.reset();
+    GlobalCASSource.releaseCAS(testCAS); // testCAS.release();
+    return result;
+  }
+
+  // based on TextRulerBasicLearner's method:
+  protected void compareOriginalDocumentWithTestCAS(TextRulerExampleDocument originalDoc,
+          CAS testCas, TextRulerTarget target, Score theScore) {
+    List<TextRulerExample> originalPositives = originalDoc.getPositiveExamples();
+    List<TextRulerExample> testPositives = originalDoc.createSlotInstancesForCAS(testCas, target,
+            true);
+
+    for (TextRulerExample e : testPositives) {
+      TextRulerExample coveredExample = TextRulerToolkit.exampleListContainsAnnotation(
+              originalPositives, e.getAnnotation());
+      if (coveredExample != null) {
+        originalPositives.remove(coveredExample);
+        theScore.tp++;
+      } else
+        theScore.fp++;
+    }
+
+    // all remaining positives are missing positives (false negatives)
+    theScore.fn += originalPositives.size();
+  }
+
+  public static void main(String[] args) {
+    // RAPIER
+    // TextRulerToolkit.log("stime = "+Score.f1Score(93.9, 92.9));
+    // TextRulerToolkit.log("etime = "+Score.f1Score(95.8, 94.6));
+    // TextRulerToolkit.log("loc   = "+Score.f1Score(91.0, 60.5));
+    // TextRulerToolkit.log("speak = "+Score.f1Score(80.9, 39.4));
+
+    // WHISK
+    // TextRulerToolkit.log("stime = "+Score.f1Score(86.2, 100.0));
+    // TextRulerToolkit.log("etime = "+Score.f1Score(85.0, 87.2));
+    // TextRulerToolkit.log("loc   = "+Score.f1Score(83.6, 55.4));
+    // TextRulerToolkit.log("speak = "+Score.f1Score(52.6, 11.1));
+
+    // // SRV
+    // TextRulerToolkit.log("stime = "+Score.f1Score(98.4, 98.3));
+    // TextRulerToolkit.log("etime = "+Score.f1Score(66.7, 92.6));
+    // TextRulerToolkit.log("loc   = "+Score.f1Score(73.8, 69.5));
+    // TextRulerToolkit.log("speak = "+Score.f1Score(54.9, 58.3));
+
+    F1Scorer scorer = new F1Scorer(
+            // "/testinput/f1test2/desc/lp2ergebnisrandomgiantEngine.xml",
+            // "/testinput/f1test2/original",
+            // // "/testinput/f1test/fromSystem"
+            // "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/output"
+            "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/descriptor/de.uniwue.ml/lp2validateEngine.xml",
+            "/Users/tobi/Documents/UniLaptop/Diplomarbeit/TestDataSets/withPosTags/Subset100/5fold/2/testing/withtags",
+            "/Users/tobi/Documents/runtime-EclipseApplication/MLSandBox/output");
+    Score score = scorer.scoreSlot("de.uniwue.ml.types.stime");
+    // Score score = scorer.scoreSlot("de.uniwue.ml.types.location");
+    if (score != null)
+      score.logInfo();
+  }
+
+  public CAS loadCAS(String fileName, CAS reuseCAS) {
+    return TextRulerToolkit.readCASfromXMIFile(fileName, ae, reuseCAS);
+  }
+
+}

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/F1Scorer.java
------------------------------------------------------------------------------
    svn:executable = *

Propchange: uima/sandbox/trunk/TextMarker/org.apache.uima.tm.textruler/src/main/java/org/apache/uima/tm/textruler/tools/F1Scorer.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain