View Javadoc

1   /*
2    wsmo4j - a WSMO API and Reference Implementation
3    Copyright (c) 2004, University of Innsbruck, Institute of Computer Science
4    This library is free software; you can redistribute it and/or modify it under
5    the terms of the GNU Lesser General Public License as published by the Free
6    Software Foundation; either version 2.1 of the License, or (at your option)
7    any later version.
8    This library is distributed in the hope that it will be useful, but WITHOUT
9    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
10   FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
11   details.
12   You should have received a copy of the GNU Lesser General Public License along
13   with this library; if not, write to the Free Software Foundation, Inc.,
14   59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15   */
16  package org.deri.wsmo4j.io.parser.wsml;
17  
18  import java.util.*;
19  
20  import org.deri.wsmo4j.io.parser.*;
21  import org.omwg.logicalexpression.*;
22  import org.omwg.logicalexpression.terms.*;
23  import org.omwg.ontology.*;
24  import org.wsmo.common.*;
25  import org.wsmo.factory.*;
26  import org.wsmo.wsml.*;
27  import org.wsmo.wsml.compiler.node.*;
28  
29  import com.ontotext.wsmo4j.common.*;
30  import com.ontotext.wsmo4j.parser.wsml.*;
31  
32  
33  
34  /**
35   * 
36   * <pre>
37   * Created on 21.11.2005
38   * Committed by $Author$
39   * $Source$,
40   * </pre>
41   *
42   * @author Holger Lausen
43   * @version $Revision$ $Date$
44   */
45  public class AtomicExpressionAnalysis extends ASTAnalysis {
46      private LogicalExpressionFactory lFactory;
47      private WsmoFactory factory;
48      private ASTAnalysisContainer container;
49      
50      private Stack logexps; // handle to logexp stack
51      private Stack terms; // handle to terms stack
52      private Stack termLists; // handle to term lists stack
53      private Stack molecules;
54      
55      private int tempVarCounter=0;
56      private Stack mathAtomsToRewrite=new Stack();
57      
58      
59      public AtomicExpressionAnalysis(ASTAnalysisContainer container, 
60              WsmoFactory factory,
61              LogicalExpressionFactory lFactory) {
62          
63          if (container == null || lFactory == null || factory == null) {
64              throw new IllegalArgumentException();
65          }
66          this.container = container;
67          this.lFactory = lFactory;
68          this.factory = factory;
69          
70          // register the handled nodes
71          container.registerNodeHandler(AAtomSimple.class, this);
72          container.registerNodeHandler(AComparison.class, this);
73          container.registerNodeHandler(AAttrDefAttrRelation.class, this);
74          container.registerNodeHandler(AAttrValAttrRelation.class, this);
75          container.registerNodeHandler(AAttributeMoleculeMolecule.class, this);
76          container.registerNodeHandler(AConceptMoleculeNonpreferredMolecule.class, this);
77          container.registerNodeHandler(AConceptMoleculePreferredMolecule.class, this);
78          container.registerNodeHandler(AMoleculeSimple.class, this);
79  
80          container.registerNodeHandler(AMultVal.class, this);
81          container.registerNodeHandler(AMultiplicationMultVal.class, this);
82          container.registerNodeHandler(ASimpleAdditionArithVal.class, this);
83          container.registerNodeHandler(ASemisimple2AdditionArithVal.class, this);
84          container.registerNodeHandler(ASemisimple1AdditionArithVal.class, this);
85          container.registerNodeHandler(AAdditionArithVal.class, this);
86  
87          //shortcuts
88          logexps = container.getStack(LogicalExpression.class);
89          terms = container.getStack(Term.class);
90          termLists = container.getStack(Term[].class);
91          molecules = container.getStack(Molecule.class);
92  
93      }
94      
95  
96      public void outAAtomSimple(AAtomSimple node) {
97          Term term =null;
98          if (!terms.isEmpty()){
99              term = (Term)terms.pop();
100         }
101         if (term instanceof ConstructedTerm){
102             ConstructedTerm t = (ConstructedTerm)term;
103             Vector v = new Vector();
104             for(int i=0; i<t.getArity(); i++){
105                 v.add(t.getParameter(i));
106             }
107             logexps.add(lFactory.createAtom(
108                     (IRI) t.getFunctionSymbol(),v));
109             rewriteMathAtoms();
110             return;
111         }
112         if (term instanceof IRIImpl){
113             logexps.add(lFactory.createAtom(
114                     (IRI) term,
115                     new Vector()));
116             rewriteMathAtoms();
117             return;
118         }
119         ParserException e = new ParserException("Found Invalid Atom: "+node, null);
120         Token t = null;
121         if (node.getTerm() instanceof AVarTerm){
122             t=((AVarTerm)node.getTerm()).getVariable();
123         }
124         if (node.getTerm() instanceof ANbAnonymousTerm){
125             t=((ANbAnonymousTerm)node.getTerm()).getNbAnonymous();
126         }
127         if (node.getTerm() instanceof ADataTerm){
128             PValue pv =((ADataTerm)node.getTerm()).getValue();
129             if (pv instanceof AStringValue){
130                 t=((AStringValue)pv).getString();
131             }
132             if (pv instanceof ANumericValue){
133                 PNumber pn = ((ANumericValue)pv).getNumber();
134                 if (pn instanceof ADecimalNumber){
135                     t=((ADecimal)((ADecimalNumber)pn).getDecimal()).getPosDecimal();
136                 }
137                 if (pn instanceof AIntegerNumber){
138                     t=((AInteger)((AIntegerNumber)pn).getInteger()).getPosInteger();
139                 }
140             }
141             if (pv instanceof ADatatypeValue){
142                 PFunctionsymbol pf = ((ADatatypeValue)pv).getFunctionsymbol();
143                 if (pf instanceof AMathFunctionsymbol){
144                     t = ((AMathFunctionsymbol)pf).getLpar();
145                 }
146                 if (pf instanceof AParametrizedFunctionsymbol){
147                     t = ((AParametrizedFunctionsymbol)pf).getLpar();
148                 }
149             }
150         }
151         if (t!=null){
152             e.setErrorLine(t.getLine());
153             e.setErrorPos(t.getPos());
154         }
155         e.setFoundToken(node.toString());
156         e.setExpectedToken("IRI or sQName");
157         throw new WrappedParsingException(e);
158     }
159     
160     public void outAComparison(AComparison node) {
161         Vector v = new Vector();
162         Term te2 = (Term)terms.pop();
163         Term te1 = (Term)terms.pop();
164         v.add(te1);
165         v.add(te2);
166         Identifier op = determineCompOp(node.getCompOp(),te1,te2);
167         logexps.add(lFactory.createAtom(op, v));
168         rewriteMathAtoms();
169     }
170     
171     public void outAAttrDefAttrRelation(AAttrDefAttrRelation node) {
172         Term attid = (Term) terms.pop();
173         Term mId = (Term) terms.peek();
174         Term[] values = (Term[]) termLists.pop();
175 
176         if (node.getAttrDefOp() instanceof AImpliestypeAttrDefOp){
177             for (int i=0; i<values.length; i++){
178                 molecules.add(lFactory.createAttributeInference(
179                         mId, attid,values[i]));
180             }
181         }
182         else{
183             for (int i=0; i<values.length; i++){
184                 molecules.add(lFactory.createAttributeConstraint(
185                         mId, attid,values[i]));
186             }
187         }
188     }
189 
190     public void outAAttrValAttrRelation(AAttrValAttrRelation node) {
191         Term attid = (Term) terms.pop();
192         Term mId = (Term) terms.peek();
193         Term[] values = (Term[]) termLists.pop();
194         for (int i=0; i<values.length; i++){
195             molecules.add(lFactory.createAttributeValue(
196                     mId, attid,values[i]));
197         }
198     }
199 
200     public void outAAttributeMoleculeMolecule(AAttributeMoleculeMolecule node) {
201         //clean termstack from id
202         terms.pop();
203     }
204 
205 
206     public void outAConceptMoleculeNonpreferredMolecule(AConceptMoleculeNonpreferredMolecule node) {
207         moleculeCptHelper(node.getCptOp());
208     }
209     
210     public void outAConceptMoleculePreferredMolecule(AConceptMoleculePreferredMolecule node) {
211         moleculeCptHelper(node.getCptOp());
212     }
213 
214     private void moleculeCptHelper(PCptOp node){
215         Term [] conceptOrMemberOfTerms = (Term[])termLists.pop();
216         Term molId = (Term) terms.pop();
217         if (node instanceof AMemberofCptOp){
218             for (int i=0; i<conceptOrMemberOfTerms.length; i++){
219                 molecules.add(lFactory.createMemberShipMolecule(
220                         molId, conceptOrMemberOfTerms[i]));
221             }
222         }
223         else{
224             for (int i=0; i<conceptOrMemberOfTerms.length; i++){
225                 molecules.add(lFactory.createSubConceptMolecule(
226                         molId, conceptOrMemberOfTerms[i]));
227             }
228         }
229     }
230 
231     public void outAMoleculeSimple(AMoleculeSimple node) {
232         if (molecules.size()==1){
233             logexps.add(molecules.pop());
234         }
235         else{
236             logexps.add(lFactory.createCompoundMolecule(new Vector(molecules)));
237             molecules.clear();
238         }
239         rewriteMathAtoms();
240     }
241     
242     //[arith] +- [mul]
243     public void outAAdditionArithVal(AAdditionArithVal node) {
244         Term t2 = (Term)terms.pop(); 
245         createPredicate(getFSIRI(node.getArithOp()),
246                 (Term)terms.pop(),t2);
247     }
248 
249     //term +- [mul]
250     public void outASemisimple1AdditionArithVal(ASemisimple1AdditionArithVal node) {
251         Term t2 = (Term)terms.pop(); 
252         createPredicate(getFSIRI(node.getArithOp()),
253                 (Term)terms.pop(),t2);
254     }
255 
256     //[arith] +- term
257     public void outASemisimple2AdditionArithVal(ASemisimple2AdditionArithVal node) {
258         Term t2 = (Term)terms.pop(); 
259         createPredicate(getFSIRI(node.getArithOp()),
260                 (Term)terms.pop(),t2);
261     }
262     //term +- term
263     public void outASimpleAdditionArithVal(ASimpleAdditionArithVal node) {
264         Term t2 = (Term)terms.pop(); 
265         createPredicate(getFSIRI(node.getArithOp()),
266                 (Term)terms.pop(),t2);
267     }
268 
269     //[mul] */ term
270    public void outAMultiplicationMultVal(AMultiplicationMultVal node) {
271        Term t2 = (Term)terms.pop(); 
272        createPredicate(getFSIRI(node.getMulOp()),
273                (Term)terms.pop(),t2);
274    }
275 
276     //term */ term
277    public void outAMultVal(AMultVal node) {
278        Term t2 = (Term)terms.pop(); 
279        createPredicate(getFSIRI(node.getMulOp()),
280                (Term)terms.pop(),t2);
281    }
282    
283    private void createPredicate(IRI iri, Term left, Term right){
284        Variable v = new TempVariable(tempVarCounter++);
285        List params = new Vector();
286        params.add(v);
287        params.add(left);
288        params.add(right);
289        mathAtomsToRewrite.push(lFactory.createAtom(iri,params));
290        terms.add(v);
291    }
292    
293    private void rewriteMathAtoms() {
294        while (!mathAtomsToRewrite.isEmpty()){
295            LogicalExpression left = (LogicalExpression) logexps.pop();
296            Atom right = (Atom) mathAtomsToRewrite.pop();
297            logexps.push(lFactory.createConjunction(left, right));
298        }
299    }
300 
301     private IRI getFSIRI(PArithOp op) {
302         if (op instanceof AAddArithOp) {
303             //add
304             return factory.createIRI(Constants.NUMERIC_ADD);
305         }
306         //sub
307         return factory.createIRI(Constants.NUMERIC_SUB);
308     }
309 
310     private IRI getFSIRI(PMulOp op) {
311         if (op instanceof AMulMulOp) {
312             //mult
313             return factory.createIRI(Constants.NUMERIC_MUL);
314         }
315         //div
316         return factory.createIRI(Constants.NUMERIC_DIV);
317     }
318     
319     
320     private Identifier determineCompOp(PCompOp cOp, Term te1, Term te2) {
321         Identifier op;
322         if (cOp instanceof AEqualCompOp) {
323             //equal, stringEqual, numericEqual
324             if(isNumeric(te1) && isNumeric(te2)) {
325                 op = factory.createIRI(Constants.NUMERIC_EQUAL);
326             } else if (isString(te1) && isString(te2)){
327                 op = factory.createIRI(Constants.STRING_EQUAL);
328             } else {
329                 op = factory.createIRI(Constants.EQUAL);
330             }
331         }
332         else if (cOp instanceof AGtCompOp) {
333             op = factory.createIRI(Constants.GREATER_THAN);
334         }
335         else if (cOp instanceof AGteCompOp) {
336             op = factory.createIRI(Constants.GREATER_EQUAL);
337         }
338         else if (cOp instanceof ALtCompOp) {
339             op = factory.createIRI(Constants.LESS_THAN);
340         }
341         else if (cOp instanceof ALteCompOp) {
342             op = factory.createIRI(Constants.LESS_EQUAL);
343         }
344         else if (cOp instanceof AStrongEqualCompOp) {
345             op = factory.createIRI(Constants.STRONG_EQUAL);
346         }
347         else {
348             //inequal, stringInequal, numericInequal
349             if(isNumeric(te1) && isNumeric(te2)) {
350                 op = factory.createIRI(Constants.NUMERIC_INEQUAL);
351             } else if (isString(te1) && isString(te2)){
352                 op = factory.createIRI(Constants.STRING_INEQUAL);
353             } else {
354                 op = factory.createIRI(Constants.INEQUAL);
355             }
356         }
357         return op;
358     }
359     
360     //TODO more clever analysis (e.g. for variable)
361     private boolean isNumeric(Term t) {
362         if(t instanceof DataValue ) { 
363             String s = ((DataValue)t).getType().getIRI().toString();
364             if( s.equals(WsmlDataType.WSML_DOUBLE) 
365                     || s.equals(WsmlDataType.WSML_FLOAT)
366                     || s.equals(WsmlDataType.WSML_DECIMAL)
367                     || s.equals(WsmlDataType.WSML_INTEGER) ) {
368                     return true;
369             } else {
370                 return false;
371             }
372         } else {
373             return false;
374         }
375     }
376     
377     private boolean isString(Term t) {
378         if(t instanceof DataValue ) { 
379             String s = ((DataValue)t).getType().getIRI().toString();
380             if( s.equals(WsmlDataType.WSML_STRING)) {
381                 return true;
382             } else {
383                 return false;
384             }
385         } else {
386             return false;
387         }
388     }
389 }