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

📄 fbruleinfgraph.java

📁 jena2.5.4推理机系统的一种最基本实现 HP实验室出品
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
                            needReset = true; break;
                        }
                    }
                } else {
                    needReset = ((RulePreprocessHook)preprocessorHooks.get(0)).needsRerun(this, t);
                }
            }
            if (needReset) {
                isPrepared = false;
            } else {
                engine.add(t);
            }
        }
        bEngine.reset();
    }

    /** 
     * Removes the triple t (if possible) from the set belonging to this graph. 
     */   
    public void performDelete(Triple t) {
        version++;
        boolean removeIsFromBase = fdata.getGraph().contains(t);
        fdata.getGraph().delete(t);
        if (useTGCCaching) {
            if (transitiveEngine.delete(t)) {
                if (isPrepared) {
                    bEngine.deleteAllRules();
                }
                isPrepared = false;
            }
        } 
        // Full incremental remove processing requires reference counting
        // of all deductions. It's not clear the cost of maintaining the
        // reference counts is worth it so the current implementation
        // forces a recompute if any external deletes are performed.
        if (isPrepared) {
            bEngine.deleteAllRules();
            isPrepared = false;
            // Re-enable the code below when/if ref counting is added and remove above
            // if (removeIsFromBase) engine.delete(t);
        }
        bEngine.reset();
    }
    
    /**
     * Return a new inference graph which is a clone of the current graph
     * together with an additional set of data premises. Attempts to the replace
     * the default brute force implementation by one that can reuse some of the
     * existing deductions.
     */
    public InfGraph cloneWithPremises(Graph premises) {
        prepare();
        FBRuleInfGraph graph = new FBRuleInfGraph(getReasoner(), rawRules, this);
        if (useTGCCaching) graph.setUseTGCCache();
        graph.setDerivationLogging(recordDerivations);
        graph.setTraceOn(traceOn);
        // Implementation note:  whilst current tests pass its not clear that 
        // the nested passing of FBRuleInfGraph's will correctly handle all
        // cases of indirectly bound schema data. If we do uncover a problem here
        // then either include the raw schema in a Union with the premises or
        // revert of a more brute force version. 
        graph.rebind(premises);
        return graph;
    }
    
    /** 
     * Free all resources, any further use of this Graph is an error.
     */
    public void close() {
        if (!closed) {
            bEngine.halt();        
            bEngine = null;
            transitiveEngine = null;
            super.close();
        }
    }
    
//  =======================================================================
//  Generalized validation machinery. Assumes rule set has special validation
//  rules that can be turned on.
   
    /**
     * Test the consistency of the bound data. This normally tests
     * the validity of the bound instance data against the bound
     * schema data. 
     * @return a ValidityReport structure
     */
    public ValidityReport validate() {
        checkOpen();
        StandardValidityReport report = new StandardValidityReport();
        // Switch on validation
        Triple validateOn = new Triple(Node.createAnon(), 
                                ReasonerVocabulary.RB_VALIDATION.asNode(),
                                Functor.makeFunctorNode("on", new Node[] {}));
        // We sneak this switch directly into the engine to avoid contaminating the
        // real data - this is only possible only the forward engine has been prepared
//      add(validateOn);
        if (!isPrepared) {
            prepare();
        }
        engine.add(validateOn); 
        // Look for all reports
        TriplePattern pattern = new TriplePattern(null, ReasonerVocabulary.RB_VALIDATION_REPORT.asNode(), null);
        for (Iterator i = findFull(pattern); i.hasNext(); ) {
            Triple t = (Triple)i.next();
            Node rNode = t.getObject();
            boolean foundReport = false;
            if (rNode.isLiteral()) {
                Object rVal = rNode.getLiteralValue();
                if (rVal instanceof Functor) {
                    Functor rFunc = (Functor)rVal;
                    foundReport = true;
                    StringBuffer description = new StringBuffer();
                    String nature = rFunc.getName();
                    String type = rFunc.getArgs()[0].toString();
                    String text = rFunc.getArgs()[1].toString();
                    description.append( text + "\n");
                    description.append( "Culprit = " + PrintUtil.print(t.getSubject()) +"\n");
                    for (int j = 2; j < rFunc.getArgLength(); j++) {
                        description.append( "Implicated node: " + PrintUtil.print(rFunc.getArgs()[j]) + "\n");
                    }
                    Node culpritN = t.getSubject();
                    RDFNode culprit = null;
                    if (culpritN.isURI()) {
                        culprit = ResourceFactory.createResource(culpritN.getURI());
                    }
                    report.add(nature.equalsIgnoreCase("error"), type, description.toString(), culprit);
                }
            }
        }
//        // Debug
//        Node ia = Node.createURI("http://jena.hpl.hp.com/testing/reasoners/owl#ia");
//        System.out.println("Types of ia");
//        PrintUtil.printOut(findFull(new TriplePattern(ia, RDF.Nodes.type, null)));
//        System.out.println("different froms");
//        PrintUtil.printOut(findFull(new TriplePattern(null, OWL.differentFrom.asNode(), null)));
//        System.out.println("ia same as");
//        PrintUtil.printOut(findFull(new TriplePattern(ia, OWL.sameIndividualAs.asNode(), null)));
//        // end
        return report;
    }

//  =======================================================================
//  Helper methods

    /**
     * Scan the initial rule set and pick out all the backward-only rules with non-null bodies,
     * and transfer these rules to the backward engine. 
     */
    private static List extractPureBackwardRules(List rules) {
        List bRules = new ArrayList();
        for (Iterator i = rules.iterator(); i.hasNext(); ) {
            Rule r = (Rule)i.next();
            if (r.isBackward() && r.bodyLength() > 0) {
                bRules.add(r);
            }
        }
        return bRules;
    }

    /**
     * Adds a set of precomputed triples to the deductions store. These do not, themselves,
     * fire any rules but provide additional axioms that might enable future rule
     * firing when real data is added. Used to implement bindSchema processing
     * in the parent Reasoner.
     * @return true if the preload was able to load rules as well
     */
    protected boolean preloadDeductions(Graph preloadIn) {
        Graph d = fdeductions.getGraph();
        FBRuleInfGraph preload = (FBRuleInfGraph)preloadIn;
        // If the rule set is the same we can reuse those as well
        if (preload.rules == rules) {
            // Load raw deductions
            for (Iterator i = preload.getDeductionsGraph().find(null, null, null); i.hasNext(); ) {
                d.add((Triple)i.next());
            }
            // Load backward rules
            addBRules(preload.getBRules());
            // Load forward rules
            engine.setRuleStore(preload.getForwardRuleStore());
            // Add access to raw data
            return true;
        } else {
            return false;
        }
    }
   
    /**
     * Called to flag that a node should be hidden from external queries.
     */
    public void hideNode(Node n) {
        if (! JenaParameters.enableFilteringOfHiddenInfNodes) return;
        if (hiddenNodes == null) {
            hiddenNodes = new HashSet();
        }
        synchronized (hiddenNodes) {
            hiddenNodes.add(n);
        }
    }
    
//  =======================================================================
//  Support for LP engine profiling
    
    /**
     * Reset the LP engine profile.
     * @param enable it true then profiling will continue with a new empty profile table,
     * if false profiling will stop all current data lost.
     */
    public void resetLPProfile(boolean enable) {
        bEngine.resetProfile(enable);
    }
    
    /**
     * Print a profile of LP rules used since the last reset.
     */
    public void printLPProfile() {
        bEngine.printProfile();
    }
    
//  =======================================================================
//  Implement Filter signature
 
    /**
     * Post-filter query results to hide unwanted
     * triples from the glare of publicity. Unwanted triples
     * are triples with Functor literals and triples with hidden nodes
     * as subject or object.
     */
    public boolean accept(Object tin) {
        Triple t = (Triple)tin;
        
        if (((Triple)t).getSubject().isLiteral()) return true;
        
        if (JenaParameters.enableFilteringOfHiddenInfNodes && hiddenNodes != null) {
            if (hiddenNodes.contains(t.getSubject()) || hiddenNodes.contains(t.getObject()) || hiddenNodes.contains(t.getPredicate())) {
                return true;
            }
        }
        
        if (filterFunctors) {
            if (Functor.isFunctor(t.getObject())) {
                return true;
            }
        }
        
        return false;

     }
     
//  =======================================================================
//   Inner classes

    /**
     * Structure used to wrap up pre-processed/compiled rule sets.
     */
    public static class RuleStore {
        
        /** The raw rules */
        protected List rawRules;
        
        /** The indexed store used by the forward chainer */
        protected Object fRuleStore;
        
        /** The separated backward rules */
        protected List bRules;
        
        /** 
         * Constructor.
         */
        public RuleStore(List rawRules, Object fRuleStore, List bRules) {
            this.rawRules = rawRules;
            this.fRuleStore = fRuleStore;
            this.bRules = bRules;
        }
        
    }
   
    
}


/*
    (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 + -