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

📄 bruleengine.java

📁 jena2.5.4推理机系统的一种最基本实现 HP实验室出品
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/******************************************************************
 * File:        Agenda.java
 * Created by:  Dave Reynolds
 * Created on:  11-May-2003
 * 
 * (c) Copyright 2003, 2004, 2005, 2006, 2007 Hewlett-Packard Development Company, LP
 * [See end of file]
 * $Id: BRuleEngine.java,v 1.7 2007/01/02 11:52:33 andy_seaborne Exp $
 *****************************************************************/
package com.hp.hpl.jena.reasoner.rulesys.impl.oldCode;

import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.reasoner.rulesys.impl.BindingVector;
import com.hp.hpl.jena.reasoner.rulesys.impl.RuleStore;
import com.hp.hpl.jena.reasoner.rulesys.impl.StateFlag;
import com.hp.hpl.jena.reasoner.*;
import com.hp.hpl.jena.util.PrintUtil;
import com.hp.hpl.jena.graph.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.*;

/**
 * Part of the backward chaining rule interpreter. Maintains an agenda containing
 * an ordered list of RuleStates awaiting processing (each RuleState
 * represents the tip of a partially expanded search tree).   
 * <p>
 * This object does the top level scheduling of rule processing. By default
 * it batches up several results from the top rule in the agenda before
 * switching to expand other trees. The size of this batch is adjustable.
 * </p>
 * 
 * @author <a href="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
 * @version $Revision: 1.7 $ on $Date: 2007/01/02 11:52:33 $
 */
public class BRuleEngine {
    
//  =======================================================================
//  Variables

    /** a list of active RuleStates to be processed */
    protected LinkedList agenda = new LinkedList();
    
//    /** the RuleState currently being procssed */
//    protected RuleState current;

    /** The table of all goals */
    protected GoalTable goalTable;
    
    /** The inference graph which is using this engine - used for calling builtins */
    protected BackwardRuleInfGraphI infGraph;
    
    /** Indexed version of the rule set */
    protected RuleStore ruleStore;
    
    /** True if debug information should be written out */
    protected boolean traceOn = false;
    
    /** Set to true to flag that derivations should be logged */
    protected boolean recordDerivations;
    
    /** performance stats - number of rules fired */
    protected long nRulesFired = 0;
    
    /** The size of the result batch permitted before a rule should 
     * reschedule itself lower on the agenda */
    protected int batchSize = 100000;
    
    static Log logger = LogFactory.getLog(BRuleEngine.class);
    
//  =======================================================================
//  Constructors
    
    /**
     * Constructor.
     * @param infGraph the parent inference graph which is using this engine
     * @param rules the indexed set of rules to process
     */
    public BRuleEngine(BackwardRuleInfGraphI infGraph, RuleStore rules) {
        this.infGraph = infGraph;
        goalTable = new GoalTable(this);
        ruleStore = rules;
    }
    
    /**
     * Constructor. Creates an empty engine to which rules must be added.
     * @param infGraph the parent inference graph which is using this engine
     */
    public BRuleEngine(BackwardRuleInfGraphI infGraph) {
        this.infGraph = infGraph;
        goalTable = new GoalTable(this);
        ruleStore = new RuleStore();
    }
    
//  =======================================================================
//  Control methods
    
    /**
     * Clear all tabled results.
     */
    public synchronized void reset() {
        agenda.clear();
        goalTable.reset();
    }
    
    /**
     * Add a single rule to the store.
     * N.B. This will invalidate current partial results and the engine
     * should be reset() before future queries. 
     */
    public void addRule(Rule rule) {
//        System.out.println("Adding rule: " + rule);
        ruleStore.addRule(rule);
    }
    
    /**
     * Remove a single rule from the store.
     * N.B. This will invalidate current partial results and the engine
     * should be reset() before future queries. 
     */
    public void deleteRule(Rule rule) {
        ruleStore.deleteRule(rule);
    }
    
    /**
     * Return an ordered list of all registered rules.
     */
    public List getAllRules() {
        return ruleStore.getAllRules();
    }
    
    /**
     * Delete all the rules.
     */
    public void deleteAllRules() {
        ruleStore.deleteAllRules();     
    }
    
    /**
     * Stop the current work. This is called if the top level results iterator has
     * either finished or the calling application has had enough. We leave any completed 
     * results in the GoalTable but clear out the agenda and all non-compelted results.
     */
    public synchronized void halt() {
        // Clear agenda
        for (Iterator i = agenda.iterator(); i.hasNext(); ) {
            RuleState item = (RuleState)i.next();
            // don't call item.close(), that would update the ref count and set a completion flag
            if (item.goalState != null) item.goalState.close();     
        }
        agenda.clear();
        // Clear the goal table
        goalTable.removePartialGoals();
    }
    
    /**
     * Find the set of memoized solutions for the given goal
     * and return a GoalState that can traverse all the solutions.
     * 
     * @param goal the goal to be solved
     * @return a GoalState which can iterate over all of the goal solutions
     */
    public synchronized GoalState findGoal(TriplePattern goal) {
        return goalTable.findGoal(goal);
    }
   
    /**
     * Set the state of the trace flag. If set to true then rule firings
     * are logged out to the Log at "INFO" level.
     */
    public void setTraceOn(boolean state) {
        traceOn = state;
    }
    
    /**
     * Return true if traces of rule firings should be logged.
     */
    public boolean isTraceOn() {
        return traceOn;
    }
   
    /**
     * Return the number of rules fired since this rule engine instance
     * was created and initialized
     */
    public long getNRulesFired() {
        return nRulesFired;
    }
    
    /**
     * Set to true to enable derivation caching
     */
    public void setDerivationLogging(boolean recordDerivations) {
        this.recordDerivations = recordDerivations;
    }

    /**
     * Dump an a summary of the goal table state to stdout.
     * Just debugging, do not use for real.
     */
    public void dump() {
        goalTable.dump();        
    }
    
//  =======================================================================
//  Engine implementation  
    
    /**
     * Append a new rule node to the end of the agenda.
     */
    public synchronized void appendToAgenda(RuleState rs) {
        if (!rs.isScheduled) {
            if (traceOn) {
//                logger.debug("append to agenda: " + rs);
            }
            agenda.add(rs);
            rs.isScheduled = true;
        }
    }
    
    /**
     * Prepend a new rule node to the head of the agenda.
     */
    public synchronized void prependToAgenda(RuleState rs) {
        if (!rs.isScheduled) {
            if (traceOn) {
//                logger.debug("prepend to agenda: " + rs);
            }
            agenda.add(0, rs);
            rs.isScheduled = true;
        }
    }
    
    /**
     * Get next agenda item. May do heuristic selection of next item to process.
     */
    public RuleState nextAgendaItem() {
        RuleState next = (RuleState)agenda.removeFirst();
        next.isScheduled = false;
        return next;
        

⌨️ 快捷键说明

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