Пример #1
0
  /**
   * Method to parse a naf (Negation as Failure)
   *
   * @param naf Element The XOM element that represents the naf atom to be parsed.
   * @return Returns the data structure that represents the naf in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the naf.
   */
  private Term parseNaf(Element naf) throws ParseException {
    Elements children = naf.getChildElements();
    Element el = skipRoleTag(children.get(0));

    Vector<Term> subterms = new Vector<Term>();
    if (el.getLocalName().equals(tagNames.ATOM)) {
      subterms.add(parseAtom(el, false, false));
    } else if (el.getLocalName().equals(tagNames.AND)) {
      children = el.getChildElements();
      for (int i = 0; i < children.size(); i++) {
        Element el2 = children.get(i);
        if (!el2.getLocalName().equals(tagNames.ATOM)) {
          throw new ParseException("And child of Naf element should only contain Atom elements.");
        }

        subterms.add(parseAtom(el2, false, false));
      }
    } else {
      throw new ParseException("Naf element should only contain Atom or And child element.");
    }

    Term t = new Term(SymbolTable.INAF, SymbolTable.INOROLE, Types.IOBJECT, subterms);

    t.setAtom(true);
    return t;
  }
Пример #2
0
  /**
   * Method to parse a Slot
   *
   * @param slot Element The XOM element that represents the slot to be parsed.
   * @return Returns the data structure that represents the slot in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the slot.
   */
  private Term parseSlot(Element slot) throws ParseException {
    Elements children = slot.getChildElements();

    Element firstChildName = children.get(0);
    boolean dataSlot = false;
    if (firstChildName.getLocalName().equals(tagNames.DATA)) {
      dataSlot = true;
    }

    if (!firstChildName.getLocalName().equals(tagNames.IND)
        && !firstChildName.getLocalName().equals(tagNames.DATA)) {
      throw new ParseException("In a <slot> only <Ind> and <Data> are allowed.");
    }
    // Getting the Role from the symbol Table, it will assign one if it
    // doesnt already exist
    int role = SymbolTable.internRole(firstChildName.getValue().trim());

    Element element = children.get(1);
    Term term = parseDefaultElement(element);

    term.setRole(role);

    if (dataSlot) {
      term.setDataSlot(true);
    }

    return term;
  }
Пример #3
0
  /**
   * This method is used to parse an Assertion in the RuleML Document.
   *
   * @param ass Element The XOM Element object that represents the assertion.
   * @return A term object that represents the assertion in a way that can be used by the reasoning
   *     engine.
   * @throws ParseException Thrown if there is a serious error parsing the assertion.
   */
  private Term parseAssert(Element ass) throws ParseException {
    Elements children = ass.getChildElements();

    Element firstChild = skipRoleTag(children.get(0));

    if (firstChild.getLocalName().equals(tagNames.ATOM)) {
      DefiniteClause dc = parseFact(firstChild);
      Vector<Term> v = new Vector<Term>();
      for (int i = 0; i < dc.atoms.length; i++) {
        v.add(dc.atoms[i]);
      }
      Term t = new Term(SymbolTable.IASSERT, SymbolTable.INOROLE, Types.IOBJECT, v);
      t.setAtom(true);
      return t;
    } else if (firstChild.getLocalName().equals(tagNames.IMPLIES)) {
      Vector<DefiniteClause> v2 = parseImplies(firstChild);
      DefiniteClause dc = (DefiniteClause) v2.get(0);
      Vector<Term> v = new Vector<Term>();
      for (int i = 0; i < dc.atoms.length; i++) {
        v.add(dc.atoms[i]);
      }
      Term t = new Term(SymbolTable.IASSERT, SymbolTable.INOROLE, Types.IOBJECT, v);
      t.setAtom(true);
      return t;
    } else {
      throw new ParseException("Assert element can only contain Atom (fact) or Implies elements.");
    }
  }
Пример #4
0
 private static Element createResults0(Element element) {
   Element newElement = null;
   String tag = element.getLocalName();
   if (ResultsElement.TAG.equals(tag)) {
     newElement = new ResultsElement();
   } else if (ResultElement.TAG.equals(tag)) {
     newElement = new ResultElement();
   } else {
     LOG.error("Unknown element: " + tag);
   }
   XMLUtil.copyAttributes(element, newElement);
   for (int i = 0; i < element.getChildCount(); i++) {
     Node child = element.getChild(i);
     if (child instanceof Text) {
       child = child.copy();
     } else {
       child = ResultsElement.createResults0((Element) child);
     }
     if (newElement != null && child != null) {
       newElement.appendChild(child);
     }
   }
   LOG.trace("XML :" + newElement.toXML());
   return newElement;
 }
Пример #5
0
  /**
   * Parses the given element and adds parsed data to sub terms
   *
   * <p>Known elements are: Plex, Expr, Ind, Data, sko, Var, slot, repo, resl
   *
   * @param element The element which has to be parsed
   * @return Returns the data structure that represents the Element in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if this method is not able to handle element.
   */
  private Term parseDefaultElement(Element element) throws ParseException {
    String elementName = element.getLocalName();
    Term result = null;

    if (elementName.equals(tagNames.PLEX)) {
      result = parsePlex(element);
    } else if (elementName.equals(tagNames.EXPR)) {
      result = parseExpression(element);
    } else if (elementName.equals(tagNames.IND)) {
      result = parseInd(element);
    } else if (elementName.equals(tagNames.DATA)) {
      result = parseData(element);
    } else if (elementName.equals(tagNames.SKOLEM)) {
      result = parseSkolem(element);
    } else if (elementName.equals(tagNames.VAR)) {
      result = parseVar(element);
    } else if (elementName.equals(tagNames.SLOT)) {
      result = parseSlot(element);
    } else if (elementName.equals(tagNames.RESL)) {
      result = parseResl(element);
    } else if (elementName.equals(tagNames.REPO)) {
      result = parseRepo(element);
    } else {
      throw new ParseException(String.format("Element (%s) not supported!", elementName));
    }

    return result;
  }
 /** Copy constructor from non-subclassed elements */
 public static AbstractEditorElement createEditorElement(Element element) {
   AbstractEditorElement newElement = null;
   String tag = element.getLocalName();
   if (tag == null || tag.equals("")) {
     throw new RuntimeException("no tag");
   } else if (tag.equals(CombineElement.TAG)) {
     newElement = new CombineElement();
   } else if (tag.equals(ConstantElement.TAG)) {
     newElement = new ConstantElement();
   } else if (tag.equals(EditorElement.TAG)) {
     newElement = new EditorElement();
   } else if (tag.equals(FieldElement.TAG)) {
     newElement = new FieldElement();
   } else if (tag.equals(PatternElement.TAG)) {
     newElement = new PatternElement();
   } else if (tag.equals(PatternListElement.TAG)) {
     newElement = new PatternListElement();
   } else if (tag.equals(SpaceElement.TAG)) {
     newElement = new SpaceElement();
   } else if (tag.equals(SubstitutionElement.TAG)) {
     newElement = new SubstitutionElement();
   } else {
     throw new RuntimeException("unsupported editor element: " + tag);
   }
   if (newElement != null) {
     XMLUtil.copyAttributes(element, newElement);
     createSubclassedChildren(element, newElement);
   }
   return newElement;
 }
Пример #7
0
 public String getType(PseudoPath path) {
   Element element = getElement(path);
   if (element != null) {
     return element.getLocalName();
   } else {
     return null;
   }
 }
Пример #8
0
 /**
  * Get the first element with the given name
  *
  * @param elements Element to search for the child
  * @param childName Name of the element to look for
  * @return The first Element which is labeled with childName
  */
 private Element getFirstChildElement(Element element, String childName) {
   Elements children = element.getChildElements();
   for (int i = 0; i < children.size(); i++) {
     Element child = children.get(i);
     if (child.getLocalName().equals(childName)) {
       return child;
     }
   }
   return null;
 }
Пример #9
0
  /**
   * Get the first element which is not labeled with OID
   *
   * @param elements Elements to search for child
   * @param startIndex Start index to start search at
   * @return Index of the first element which is not labeled with OID. If not exist, returns -1.
   */
  private int getFirstChildElementIndex(Elements elements, int startIndex) {
    for (int i = startIndex; i < elements.size(); i++) {
      Element child = skipRoleTag(elements.get(i));

      if (!child.getLocalName().equals(tagNames.OID)) {
        return i;
      }
    }
    return -1;
  }
Пример #10
0
 /**
  * Removes <Reify> elements recursively from a given element
  *
  * @param element Element to skip <Reify> elements in
  */
 private void removeReifyElements(Element element) {
   Elements children = element.getChildElements();
   for (int i = 0; i < children.size(); i++) {
     Element child = children.get(i);
     if (child.getLocalName().equals(tagNames.REIFY)) {
       element.removeChild(child);
     } else {
       removeReifyElements(child);
     }
   }
 }
Пример #11
0
 /**
  * Retrieve the nearest ancestor element that has the given name, or null if no such ancestor
  * exists.
  */
 public Element getAncestor(Element element, String localName, String namespaceURI) {
   ParentNode parent = element.getParent();
   if (parent != null && parent instanceof Element) {
     Element eparent = (Element) parent;
     if (eparent.getLocalName().equals(localName)
         && eparent.getNamespaceURI().equals(namespaceURI)) {
       return eparent;
     }
     return getAncestor(eparent, localName, namespaceURI);
   }
   return null;
 }
Пример #12
0
  /**
   * Method to parse a Expr (Expresion)
   *
   * @param expr Element The XOM element that represents the Expr to be parsed.
   * @return Returns the data structure that represents the Expr in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the Expr.
   */
  private Term parseExpression(Element expr) throws ParseException {
    Elements children = expr.getChildElements();
    Element op = children.get(0);

    boolean foundOp = false;

    if (op.getLocalName().equals(tagNames.OP)) {
      foundOp = true;
    }

    Element fun = null;
    if (foundOp) {
      Elements funTag = op.getChildElements();
      fun = funTag.get(0);

      // Remove <op> element including its child element <Fun>, so
      // it will not be parsed twice
      expr.removeChild(op);
    }

    if (!foundOp) {
      fun = children.get(0);

      // Remove <Fun> element so that it will not be parsed twice
      expr.removeChild(fun);
    }

    if (!fun.getLocalName().equals(tagNames.FUN)) {
      throw new ParseException("First child of op in an Expr must be a Fun element.");
    }

    int symbol = SymbolTable.internSymbol(fun.getValue().trim());
    int typeid = parseTypeAttribute(expr);

    Vector<Term> subterms = parseDefaultElements(expr);
    Term t = new Term(symbol, SymbolTable.INOROLE, typeid, subterms);
    return t;
  }
Пример #13
0
  /**
   * Gets the root element used to begin RuleML parsing at
   *
   * <p>possible elements are: <RuleML>, <Assert>, <Rulebase> or <Query> if document is a RuleML
   * query
   *
   * @param documentRoot Document's root element
   * @return The RuleML root element on which the parser should start at
   * @throws ParseException
   */
  private Element getRuleMLRootElement(Element documentRoot) throws ParseException {
    String rootName = documentRoot.getLocalName();
    Element ruleMLRoot = null;

    // If <RuleML> is root element
    if (rootName.equals(tagNames.RULEML)) {
      Element assertElement = getFirstChildElement(documentRoot, tagNames.ASSERT);
      if (assertElement == null) {
        throw new ParseException("<Assert> has to be the first child of the <RuleML>.");
      }
      documentRoot = assertElement;
      rootName = assertElement.getLocalName();
    }

    // Now, <Assert> has to be the root element, check for optional children
    if (rootName.equals(tagNames.ASSERT)) {
      ruleMLRoot = documentRoot;

      // <Rulebase> is a optional child of <Assert>
      Element ruleBaseElement = getFirstChildElement(documentRoot, tagNames.RULEBASE);

      // <And> is a optional child of either <Rulebase> or <Assert>
      // (0.88+)
      if (ruleBaseElement != null) {
        ruleMLRoot = ruleBaseElement;
      }
    } else if (rootName.equals(tagNames.QUERY)) {
      ruleMLRoot = documentRoot;
    }

    if (ruleMLRoot == null) {
      throw new ParseException(String.format("Undefined RuleML root element (%s)", rootName));
    }

    return ruleMLRoot;
  }
Пример #14
0
 /**
  * Parses the RuleML root element (<RuleML>, <Assert> or <Rulebase>) or if document is query
  * parses <Query> element
  *
  * @param rmlRoot The RuleML root element on which we start parsing at
  * @throws ParseException
  */
 private void parseRuleMLRoot(Element rmlRoot) throws ParseException {
   Elements children = rmlRoot.getChildElements();
   for (int i = 0; i < children.size(); i++) {
     Element child = skipRoleTag(children.get(i));
     String childName = child.getLocalName();
     if (childName.equals(tagNames.ATOM)) {
       resetVariables();
       clauses.add(parseFact(child));
     } else if (childName.equals(tagNames.NEG)) {
       clauses.addAll(parseNegFact(child));
     } else if (childName.equals(tagNames.IMPLIES)) {
       resetVariables();
       clauses.addAll(parseImplies(child));
     } else if (childName.equals(tagNames.AND)) {
       parseRuleMLRoot(child);
     }
   }
 }
Пример #15
0
  /**
   * Get the inner element with role tag skipped
   *
   * <p>(e.g. <arg><Atom>...</Atom></arg> returns Atom element including all children of the Atom
   * element)
   *
   * @param element Element for which role tags should be skipped
   * @return The inner element without role tag encapsulation
   */
  private Element skipRoleTag(Element element) {
    Element result = element;
    String elementName = element.getLocalName();

    boolean hasRoleTag = false;
    if (elementName.equals(tagNames.ARG)) {
      hasRoleTag = true;
      logger.warn("arg element skipped.");
    } else if (elementName.equals(tagNames.FORMULA)) {
      hasRoleTag = true;
      logger.warn("formula element skipped.");
    } else if (elementName.equals(tagNames.ACT)) {
      hasRoleTag = true;
      logger.warn("act element skipped.");
    } else if (elementName.equals(tagNames.DECLARE)) {
      hasRoleTag = true;
      logger.warn("declare element skipped.");
    } else if (elementName.equals(tagNames.STRONG)) {
      hasRoleTag = true;
      logger.warn("strong element skipped.");
    } else if (elementName.equals(tagNames.WEAK)) {
      hasRoleTag = true;
      logger.warn("weak element skipped.");
    } else if (elementName.equals(tagNames.TORSO)) {
      hasRoleTag = true;
      logger.warn("torso element skipped.");
    } else if (elementName.equals(tagNames.DEGREE)) {
      hasRoleTag = true;
      logger.warn("degree element skipped.");
    }

    if (hasRoleTag) {
      result = element.getChildElements().get(0);
    }

    return result;
  }
Пример #16
0
  @Test
  public void testGeneration() throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // new XmlInstanceGenerator(SampleA.class).generateXmlSchema(System.out, false);
    new XmlInstanceGenerator(SampleA.class).generateXmlSchema(bos, false);

    Builder domBuilder = new Builder();
    Document doc = domBuilder.build(new ByteArrayInputStream(bos.toByteArray()));

    String namespace = XmlInstanceGenerator.getNamespace(SampleA.class);

    Element config = doc.getRootElement();
    Assert.assertEquals("config", config.getLocalName());

    Elements i = config.getChildElements("i", namespace);
    Assert.assertEquals(1, i.size());
    Assert.assertEquals("0", i.get(0).getValue());

    Elements s = config.getChildElements("s", namespace);
    Assert.assertEquals(1, s.size());
    Assert.assertEquals("abc", s.get(0).getValue());

    Elements r = config.getChildElements("r1", namespace);
    Assert.assertEquals(1, r.size());
    Assert.assertEquals("TODO", r.get(0).getValue());

    r = config.getChildElements("r2", namespace);
    Assert.assertEquals(1, r.size());
    Assert.assertEquals("TODO", r.get(0).getValue());

    r = config.getChildElements("r3", namespace);
    Assert.assertEquals(1, r.size());
    Assert.assertEquals("SampleC", r.get(0).getValue());

    Elements l = config.getChildElements("l", namespace);
    Assert.assertEquals(1, l.size());
    Elements values = l.get(0).getChildElements("value", namespace);
    Assert.assertEquals(2, values.size());
    Assert.assertEquals("abc", values.get(0).getValue());
    Assert.assertEquals("xyz", values.get(1).getValue());

    Elements m = config.getChildElements("m", namespace);
    Assert.assertEquals(1, m.size());
    Elements entries = m.get(0).getChildElements("entry", namespace);
    Assert.assertEquals(2, entries.size());
    Assert.assertEquals("ABC", entries.get(0).getValue());
    Assert.assertEquals("1", entries.get(0).getAttribute("key").getValue());
    Assert.assertEquals("XYZ", entries.get(1).getValue());
    Assert.assertEquals("2", entries.get(1).getAttribute("key").getValue());

    Elements lr = config.getChildElements("lr", namespace);
    Assert.assertEquals(1, lr.size());
    values = lr.get(0).getChildElements("value", namespace);
    Assert.assertEquals(1, values.size());
    Assert.assertEquals("", values.get(0).getValue());

    Elements mr = config.getChildElements("mr", namespace);
    Assert.assertEquals(1, mr.size());
    entries = mr.get(0).getChildElements("entry", namespace);
    Assert.assertEquals(1, entries.size());
    Assert.assertEquals("", entries.get(0).getValue());
    Assert.assertEquals("", entries.get(0).getAttribute("key").getValue());
  }
Пример #17
0
  /**
   * This method is used to parse a implication element, creating a new variable name list if
   * indicated. Typically a new variable list is wanted; but in certain cases (such as parsing an
   * inner clause in an assert) the same variable list must be used.
   *
   * @param implies Element The XOM Element object that represents the implication to be parsed.
   * @return A vector of DefiniteClause data structures that represents the implication in a way
   *     that can be used by the reasoning engine.
   * @throws ParseException Thrown if there is a serious error parsing the implication.
   */
  private Vector<DefiniteClause> parseImplies(Element implies) throws ParseException {

    Vector<DefiniteClause> newclauses = new Vector<DefiniteClause>();

    // Implies must have two children (excluding OID elements)
    Elements children = implies.getChildElements();

    // Set first and second child and skip OID element if exists.
    Element firstChild = skipRoleTag(children.get(0));
    Element secondChild = skipRoleTag(children.get(1));
    if (firstChild.getLocalName().equals(tagNames.OID)) {
      firstChild = skipRoleTag(children.get(1));
      secondChild = skipRoleTag(children.get(2));
    }

    String firstChildName = firstChild.getLocalName();
    Element premise, conclusion;
    // Check if implies starts with premise element
    if (firstChildName.equals(tagNames.PREMISE)) {
      premise = firstChild.getChildElements().get(0);
      conclusion = secondChild.getChildElements().get(0);
    }
    // If implies starts with conclusion element
    else if (firstChildName.equals(tagNames.CONCLUSION)) {
      premise = secondChild.getChildElements().get(0);
      conclusion = firstChild.getChildElements().get(0);
    }
    // No premise or conclusion tag available
    else {
      // Use canonical order for stripe-skipped syntax
      premise = firstChild;
      conclusion = secondChild;
    }

    premise = skipRoleTag(premise);
    conclusion = skipRoleTag(conclusion);

    Vector<Term> subterms = new Vector<Term>();
    if (conclusion.getLocalName().equals(tagNames.ATOM)) {
      subterms.add(parseAtom(conclusion, true, false));
    } else if (conclusion.getLocalName().equals(tagNames.NEG)) {
      Elements headatms = conclusion.getChildElements(tagNames.ATOM);
      if (headatms.size() != 1) throw new ParseException("Neg should have one ATOM element");

      Term atom = parseAtom(headatms.get(0), true, true);
      subterms.add(atom);

      String atomstr = atom.toPOSLString(true);

      String clause = "$Sinconsistent() :-";
      clause += atomstr + ", \"" + atomstr.substring(6) + ".";

      System.err.println(clause);

      POSLParser pp = new POSLParser();
      try {
        DefiniteClause dc2 = pp.parseDefiniteClause(clause);
        if (dc2 != null) newclauses.add(dc2);
      } catch (Exception e) {
        throw new ParseException("Error creating inconsistency check rule.");
      }
    } else {
      throw new ParseException(
          "Second element of Implies should always be an Atom or Neg element.");
    }

    String premiseName = premise.getLocalName();

    if (premiseName.equals(tagNames.ATOM)) {
      subterms.add(parseAtom(premise, false, false));
    } else if (premiseName.equals(tagNames.NAF)) {
      subterms.add(parseNaf(premise));
    } else if (premiseName.equals(tagNames.ASSERT)) {
      subterms.add(parseAssert(premise));
    } else if (premiseName.equals(tagNames.NEG)) {
      subterms.add(parseAtom(premise, false, true));
    } else if (premiseName.equals(tagNames.AND)) {
      children = premise.getChildElements();
      for (int i = 0; i < children.size(); i++) {
        Element el = skipRoleTag(children.get(i));
        if (el.getLocalName().equals(tagNames.ATOM)) {
          subterms.add(parseAtom(el, false, false));
        } else if (el.getLocalName().equals(tagNames.NAF)) {
          subterms.add(parseNaf(el));
        } else if (el.getLocalName().equals(tagNames.ASSERT)) {
          subterms.add(parseAssert(el));
        } else if (el.getLocalName().equals(tagNames.NEG)) {
          subterms.add(parseAtom(el, false, true));
        } else {
          throw new ParseException(
              "Implies And element should only contain Atom and Naf elements.");
        }
      }
    } else {
      throw new ParseException("First element of Implies should be an Atom, Naf or And element.");
    }

    logger.debug("Building Types");
    Hashtable<Integer, Integer> types = this.buildTypeTable();
    logger.debug("Built Types");
    Iterator<Term> it = subterms.iterator();
    int i = 0;
    while (it.hasNext()) {
      Term t = (Term) it.next();
      this.fixVarTypes(t, types);
      logger.debug("Fixed atom : " + i++);
    }

    DefiniteClause dc = new DefiniteClause(subterms, variableNames);
    newclauses.add(0, dc);
    return newclauses;
  }
Пример #18
0
  /**
   * Method to parse an Atom
   *
   * @param Atom Element The XOM element that represents the Atom to be parsed.
   * @param head boolean This tells the engine if the atom is a head of a rule.
   * @param neg boolean This tells the engine if the atom is a negative atom (Neg)
   * @return Returns the data structure that represents the Atom in a way that can be used by the
   *     reasoning engine.
   * @throws ParseException Thrown if there is an error parsing the Atom.
   */
  private Term parseAtom(Element atom, boolean head, boolean neg) throws ParseException {

    boolean foundoid = false;

    Elements children = atom.getChildElements();

    // checking for op tag before the rel
    Element op = getFirstChildElement(atom, tagNames.OP);

    Element rel = null;

    if (op != null) {
      Elements relTag = op.getChildElements();
      rel = relTag.get(0);
    } else {
      rel = getFirstChildElement(atom, tagNames.REL);
    }

    if (rel == null) {
      throw new ParseException("In an <Atom>, first child of <op> must be a <Rel>.");
    }

    String relname = rel.getValue().trim();
    if (neg) {
      relname = "$neg-" + relname;
    }

    int symbol = SymbolTable.internSymbol(relname);

    Vector<Term> subterms = new Vector<Term>();
    int startIndex = getFirstChildElementIndex(children, 0) + 1;
    for (int i = startIndex; i < children.size(); i++) {
      Element element = children.get(i);
      Term term = null;
      if (element.getLocalName().equals(tagNames.OID)) {
        if (foundoid) {
          throw new ParseException("<Atom> must contain a most one <oid>.");
        }
        term = parseOid(element);
        foundoid = true;
      } else {
        term = parseDefaultElement(element);
      }
      subterms.add(term);
    }

    // Generate a fake OID if the atom does not have one.
    // This is a requirement put in place by the reasoner.
    if (!foundoid) {
      if (head) {
        String symname = "$gensym" + SymbolTable.genid++;
        int symid = SymbolTable.internSymbol(symname);
        Term t2 = new Term(symid, SymbolTable.IOID, Types.IOBJECT);
        subterms.add(t2);
      } else {
        String varname = generateAnonymousIdentifier();
        int symid = this.internVariable(varname);
        Vector<Integer> types = new Vector<Integer>();
        types.add(Types.IOBJECT);
        this.varClasses.put(symid, types);
        Term t2 = new Term(symid, SymbolTable.IOID, Types.IOBJECT);
        subterms.add(t2);
      }
    }

    Term t = new Term(symbol, SymbolTable.INOROLE, Types.IOBJECT, subterms);
    t.setAtom(true);
    return t;
  }
Пример #19
0
 private static List<CoreMap> toTimexCoreMaps(Element docElem, CoreMap originalDocument) {
   // --Collect Token Offsets
   HashMap<Integer, Integer> beginMap = new HashMap<Integer, Integer>();
   HashMap<Integer, Integer> endMap = new HashMap<Integer, Integer>();
   boolean haveTokenOffsets = true;
   for (CoreMap sent : originalDocument.get(CoreAnnotations.SentencesAnnotation.class)) {
     for (CoreLabel token : sent.get(CoreAnnotations.TokensAnnotation.class)) {
       Integer tokBegin = token.get(CoreAnnotations.TokenBeginAnnotation.class);
       Integer tokEnd = token.get(CoreAnnotations.TokenEndAnnotation.class);
       if (tokBegin == null || tokEnd == null) {
         haveTokenOffsets = false;
       }
       int charBegin = token.get(CoreAnnotations.CharacterOffsetBeginAnnotation.class);
       int charEnd = token.get(CoreAnnotations.CharacterOffsetEndAnnotation.class);
       beginMap.put(charBegin, tokBegin);
       endMap.put(charEnd, tokEnd);
     }
   }
   // --Set Timexes
   List<CoreMap> timexMaps = new ArrayList<CoreMap>();
   int offset = 0;
   Element textElem = docElem.getFirstChildElement("text");
   for (int i = 0; i < textElem.getChildCount(); i++) {
     Node content = textElem.getChild(i);
     if (content instanceof Text) {
       Text text = (Text) content;
       offset += text.getValue().length();
     } else if (content instanceof Element) {
       Element child = (Element) content;
       if (child.getLocalName().equals("TIMEX3")) {
         Timex timex = new Timex(child);
         if (child.getChildCount() != 1) {
           throw new RuntimeException("TIMEX3 should only contain text " + child);
         }
         String timexText = child.getValue();
         CoreMap timexMap = new ArrayCoreMap();
         // (timex)
         timexMap.set(TimexAnnotation.class, timex);
         // (text)
         timexMap.set(CoreAnnotations.TextAnnotation.class, timexText);
         // (characters)
         int charBegin = offset;
         timexMap.set(CoreAnnotations.CharacterOffsetBeginAnnotation.class, charBegin);
         offset += timexText.length();
         int charEnd = offset;
         timexMap.set(CoreAnnotations.CharacterOffsetEndAnnotation.class, charEnd);
         // (tokens)
         if (haveTokenOffsets) {
           Integer tokBegin = beginMap.get(charBegin);
           int searchStep = 1; // if no exact match, search around the character offset
           while (tokBegin == null) {
             tokBegin = beginMap.get(charBegin - searchStep);
             if (tokBegin == null) {
               tokBegin = beginMap.get(charBegin + searchStep);
             }
             searchStep += 1;
           }
           searchStep = 1;
           Integer tokEnd = endMap.get(charEnd);
           while (tokEnd == null) {
             tokEnd = endMap.get(charEnd - searchStep);
             if (tokEnd == null) {
               tokEnd = endMap.get(charEnd + searchStep);
             }
             searchStep += 1;
           }
           timexMap.set(CoreAnnotations.TokenBeginAnnotation.class, tokBegin);
           timexMap.set(CoreAnnotations.TokenEndAnnotation.class, tokEnd);
         }
         // (add)
         timexMaps.add(timexMap);
       } else {
         throw new RuntimeException("unexpected element " + child);
       }
     } else {
       throw new RuntimeException("unexpected content " + content);
     }
   }
   return timexMaps;
 }