⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ruleclausecode.java

📁 jena2.5.4推理机系统的一种最基本实现 HP实验室出品
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
                }
                code[p++] = MAKE_FUNCTOR;
                args.add(f);
            } else {
                code[p++] = PUT_CONSTANT;
                code[p++] = (byte)argi;
                args.add(node);
            }
        }
        
        /**
         * Emit code for a call to a built-in predicate (functor).
         * @param functor the built-in to be invoked.
         */
        void emitBody(Functor functor) {
            Node[] fargs = functor.getArgs();
            Builtin builtin = functor.getImplementor();
            if (builtin == null) {
                throw new LPRuleSyntaxException("Unknown builtin operation " + functor.getName(), rule);
            }
            if (builtin.getArgLength() != 0 && builtin.getArgLength() != fargs.length) {
                throw new LPRuleSyntaxException("Wrong number of arguments to functor " + functor.getName() 
                                                  + " expected " + functor.getArgLength(), rule);
            }
            for (int i = 0; i < fargs.length; i++) {
                Node node = fargs[i];
                // We optionally force an eager dereference of variables here.
                // We used to force this but the current builtin implementations
                // now robust against it (the do a deref themselves anyway).
                 emitBodyPut(node, i, true);
            }
            code[p++] = CALL_BUILTIN;
            code[p++] = (byte)fargs.length;
            args.add(builtin);
        }
         
        /**
         * Complete the byte stream with a PROCEED and return the packed version of the code.
         * @return the byte code array
         */
        byte[] getFinalCode() {
            code[p++] = PROCEED;
            byte[] finalCode = new byte[p];
            System.arraycopy(code, 0, finalCode, 0, p);
            return finalCode;
        }
        
        /**
         * Fetch the packed array of argument objects for the byte code.
         * @return arg array
         */
        Object[] getFinalArgs() {
            return args.toArray();
        }
        
        /**
         * Classifies the variables now and side effects the
         * index number of the variables so they lie in two sequences - temp
         * and permanent separately. 
         */
        void classifyVariables(Rule rule) {
            // Build index data structure into var use in each term in the rule
            termVarTable = new List[rule.bodyLength() + 1];
            termVarTable[0] = termVars(rule.getHeadElement(0));
            totalOccurrences += termVarTable[0].size();
            for (int i = 0; i < rule.bodyLength(); i++) {
                termVarTable[i+1] = termVars(rule.getBodyElement(i));
                totalOccurrences += termVarTable[i+1].size();
            }
            
            // Build the inverted data structure
            for (int i = 0; i < rule.bodyLength() + 1; i++ ) {
                List varEnts = termVarTable[i];
                for (int j = 0; j < varEnts.size(); j++) {
                    Node n = (Node)varEnts.get(j);
                    if (n.isVariable()) {
                        Node_RuleVariable var = (Node_RuleVariable)n; 
                        List occurrences = (List)varOccurrence.get(var);
                        if (occurrences == null) {
                            occurrences = new ArrayList();
                            varOccurrence.put(var, occurrences);
                        }
                        occurrences.add(new TermIndex(var, i, j));
                    }
                }
            }
            
            // Classify vars as permanent unless they are just dummies (only used once at all)
            // or only used head+first body goal (but not if used in a builtin)
            for (Iterator enti = varOccurrence.values().iterator(); enti.hasNext(); ) {
                List occurrences = (List)enti.next();
                Node_RuleVariable var = null;
                boolean inFirst = false;
                boolean inLaterBody = false;
                boolean inBuiltin = false;
                for (Iterator oi = occurrences.iterator(); oi.hasNext(); ) {
                    TermIndex occurence = (TermIndex)oi.next();
                    var = occurence.var;
                    int termNumber = occurence.termNumber;
                    if (termNumber == 0) {
                        inFirst = true;
                    } else if (termNumber > 1) {
                        inLaterBody = true;
                    }
                    if (termNumber > 0 && rule.getBodyElement(termNumber-1) instanceof Functor) {
                        inBuiltin = true;
                    }
                }
                // Don't think we need to protected builtin's any more, so ignore that test
//                if (inBuiltin) {
//                    permanentVars.add(var);
//                } else {
                    if (!isDummy(var)) {
                        if (inLaterBody || !inFirst) {
                            permanentVars.add(var);
                        } else {
                            tempVars.add(var);
                        }
                    }
//                }
                 
            }
            
            if (permanentVars.size() > MAX_PERMANENT_VARS) {
                throw new LPRuleSyntaxException("Rule too complex for current implementation\n" 
                            + "Rule clauses are limited to " + MAX_PERMANENT_VARS + " permanent variables\n", rule); 
            }
            
            if (tempVars.size() > MAX_TEMPORARY_VARS) {
                throw new LPRuleSyntaxException("Rule too complex for current implementation\n" 
                            + "Rule clauses are limited to " + MAX_TEMPORARY_VARS + " temporary variables\n", rule); 
            }
            
            // Builtins in the forward system use the var index to modify variable bindings.
            // At one time I though the LP system might need to emulate this but (a) it doesn't and
            // (b) renumber vars to make that possible wreaks rule equality which wreaks add/remove in
            // hybrid rule sets. This code left in but commented out as a reminder to not go down
            // that path again.
            
            // Renumber the vars
//            for (int i = 0; i < permanentVars.size(); i++ ) {
//                Node_RuleVariable var = (Node_RuleVariable)permanentVars.get(i);
//                var.setIndex(i);
//            }
//            for (int i = 0; i < tempVars.size(); i++ ) {
//                Node_RuleVariable var = (Node_RuleVariable)tempVars.get(i);
//                var.setIndex(i);
//            }
            
        }
       
        /** Return true if the given rule variable is a temp */
        boolean isTemp(Node_RuleVariable var) {
            return !isDummy(var) && !permanentVars.contains(var);
        }
        
        /** Return true if the given rule variable is a dummy */
        boolean isDummy(Node_RuleVariable var) {
            List occurances = (List)varOccurrence.get(var);
            if (occurances == null || occurances.size() <= 1) return true;
            return false;
        }
                
        /** Return an list of variables or nodes in a ClauseEntry, in flattened order */
        private List termVars(ClauseEntry term) {
            List result = new ArrayList();
            if (term instanceof TriplePattern) {
                TriplePattern goal = (TriplePattern)term;
                result.add(goal.getSubject());
                result.add(goal.getPredicate());
                Node obj = goal.getObject();
                if (Functor.isFunctor(obj)) {
                    result.add(obj);
                    result.addAll(termVars((Functor)obj.getLiteralValue()));
                } else {
                    result.add(obj);
                }
            } else if (term instanceof Functor) {
                Node[] args = (Node[]) ((Functor)term).getArgs();
                for (int i = 0; i < args.length; i++) {
                    result.add(args[i]);
                }
            }
            return result;
        }
    }
                
    
    /**
     * Inner class used to represent the occurance of a variable in a term.
     * Not an abstract data type, just a structure directly accessed.
     */
    static class TermIndex {
        /** The term number in the rule - 0 for head, body starting from 1 */
        int termNumber;
        
        /** The variable position within the term */
        int index;
        
        /** The variable being indexed */
        Node_RuleVariable var;
        
        /** Constructor */
        TermIndex(Node_RuleVariable var, int termNumber, int index) {
            this.var = var;
            this.termNumber = termNumber;
            this.index = index;
        }
    }
      
    /**
     * Debug support - not unit testing.
     */
    public static void main(String[] args) {
        try {
            LPRuleStore store = new LPRuleStore();
            String test1 = "(?a p ?y) <- (?a p2 ?z).";
            String test2 = "(?a p ?y) <- (?a q2 ?z) (?z q2 ?w).";
            String test3 =  "(?a p ?a) <- (?z r2 ?w) (?z r2 ?w).";
            String test4 =  "(?a p ?a) <- (?z r2 ?w) (?a r2 ?w).";
            String test5 = "(?a p ?y) <- (?a p ?z), (?z p ?y).";
            String test6 = "(?x p C3) <- (C1 r ?x).";
            String test7 = "(?x p ?y) <- (?x r ?y) (?x q ?y).";
            String test8 = "(?x p ?y) <- (?x p ?z) addOne(?z, ?y).";
            String test9 = "(?x p ?y) <- (?x p ?z) sum(?z, 2, ?y).";
            String test10 = "(?x p ?y) <- (?x p ?v), sum(?v 2 ?y).";
            String test11 = "(b p ?y) <- (a ?y ?v).";
            String test12 = "(?x p ?y) <- (?x p foo(?z, ?y)).";
            String test13 = "(?x p foo(?y,?z)) <- (?x q ?y), (?x q ?z).";
            String test14 = "(?x p ?z) <- (?x e ?z), (?z q ?z).";
            String test15 = "(?x p ?y ) <- bound(?x), (?x p ?y).";
            String test16 = "(a p b ) <- unbound(?x).";
            String test17 = "(?a p ?a) <- (?a q class).";
            String test18 = "(?a p ?a) <- (?a s ?a).";
            String test19 = "(?X p ?T) <- (?X rdf:type c), noValue(?X, p), makeInstance(?X, p, ?T).";
            String test20 = "(a p b ) <- unbound(?x).";
            String testLong = "(?P p ?C) <- (?P q ?D), (?D r xsd(?B, ?S1, ?L1)),(?P p ?E), notEqual(?D, ?E) " +
                    "(?E e xsd(?B, ?S2, ?L2)),min(?S1, ?S2, ?S3),min(?L1, ?L2, ?L3), (?C r xsd(?B, ?S3, ?L3)).";
            String test21 = "(?a p ?y) <- (?x s ?y) (?a p ?x).";
            String test22 = "(?C p ?D) <- (?C rb:xsdBase ?BC), (?D rb:xsdBase ?BD), notEqual(?BC, ?BD).";
            store.addRule(Rule.parseRule(test22));
            System.out.println("Code for p:");
            List codeList = store.codeFor(Node.createURI("p"));
            RuleClauseCode code = (RuleClauseCode)codeList.get(0);
            code.print(System.out);
        } catch (Exception e) {
            System.out.println("Problem: " + e);
            e.printStackTrace();
        }
    }
}


/*
    (c) Copyright 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -