rulesexpressivity.java

来自「Semantic Web Ontology Editor」· Java 代码 · 共 1,433 行 · 第 1/3 页

JAVA
1,433
字号
/** *  * @author Bernardo Cuenca *  * @author Edna Ruckhaus *  *  *  * TODO To change the template for this generated type comment go to Window - *  * Preferences - Java - Code Generation - Code and Comments *   *///package org.mindswap.swoop.utils;import java.io.BufferedWriter;import java.io.FileWriter;import java.io.IOException;import java.net.URI;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.Map;import java.util.Set;import jpl.Atom;import jpl.Compound;import jpl.Query;import jpl.Term;import jpl.Variable;import org.apache.commons.httpclient.HttpURL;import org.apache.webdav.lib.WebdavResource;import org.mindswap.pellet.jena.OWLReasoner;import org.mindswap.swoop.ModelChangeEvent;import org.mindswap.swoop.SwoopModel;import org.mindswap.swoop.SwoopModelListener;import org.mindswap.swoop.reasoner.SwoopReasoner;import org.semanticweb.owl.io.owl_rdf.SWRLParser;import org.semanticweb.owl.model.OWLAnnotationInstance;import org.semanticweb.owl.model.OWLClass;import org.semanticweb.owl.model.OWLDataProperty;import org.semanticweb.owl.model.OWLDataValue;import org.semanticweb.owl.model.OWLDescription;import org.semanticweb.owl.model.OWLEntity;import org.semanticweb.owl.model.OWLException;import org.semanticweb.owl.model.OWLIndividual;import org.semanticweb.owl.model.OWLNamedObject;import org.semanticweb.owl.model.OWLObject;import org.semanticweb.owl.model.OWLObjectProperty;import org.semanticweb.owl.model.OWLOntology;import org.semanticweb.owl.model.helper.OntologyHelper;import org.semanticweb.owl.rules.OWLRule;import org.semanticweb.owl.rules.OWLRuleAtom;import org.semanticweb.owl.rules.OWLRuleClassAtom;import org.semanticweb.owl.rules.OWLRuleDObject;import org.semanticweb.owl.rules.OWLRuleDVariable;import org.semanticweb.owl.rules.OWLRuleDataPropertyAtom;import org.semanticweb.owl.rules.OWLRuleDataValue;import org.semanticweb.owl.rules.OWLRuleEqualityAtom;import org.semanticweb.owl.rules.OWLRuleIObject;import org.semanticweb.owl.rules.OWLRuleIVariable;import org.semanticweb.owl.rules.OWLRuleIndividual;import org.semanticweb.owl.rules.OWLRuleInequalityAtom;import org.semanticweb.owl.rules.OWLRuleObjectPropertyAtom;public class RulesExpressivity implements SwoopModelListener, Cloneable {	SwoopModel swModel;	HashMap ruleMap = new HashMap();	// Expressivity of the set of rules in the ontology	String rulesExpress;	// Number of rules in each expressivity "level"	int[] numRulesExpress = new int[6];	Set nonDLAtoms = new HashSet();	String[] typeRulesExpress = new String[6];	int numRules;	// Stream for allog database that will be used by allog reasoner for	// answering queries	BufferedWriter allogStream;	public final boolean USE_PROLOG_ENGINE = false;		// Rules expressivity levels	final int SYNTACTIC_SUGAR = 0;	final int AL_LOG = 1;	final int CARIN = 3;	final int DL_SAFE = 4;	final int CARIN_AND_DL_SAFE = 2;	final int SWRL = 5;	public String getRulesExpress() {		return rulesExpress;	}		public HashMap getRuleMap() {		return ruleMap;	}		public void setRuleMap(HashMap newRulesMap) {		ruleMap = newRulesMap;	}		public int getNumRules() {		return numRules;	}	public int[] getNumRulesExpress() {		return numRulesExpress;	}	public String[] getTypeRulesExpress() {		return typeRulesExpress;	}		 public Object clone() {	 	RulesExpressivity newRE = null;         try {            newRE =  (RulesExpressivity) super.clone();        }        catch (CloneNotSupportedException e) {            // This should never happen            throw new InternalError(e.toString());        }                //perform a deep copy on the ruleMap        newRE.ruleMap = new HashMap();        			        for (Iterator i = ruleMap.entrySet().iterator(); i.hasNext(); ) {            Map.Entry e = (Map.Entry) i.next();            newRE.ruleMap.put(e.getKey(), e.getValue());        }                return newRE;    }	 	public RulesExpressivity(SwoopModel swoopModel) {		swModel = swoopModel;		swModel.addListener(this);		typeRulesExpress[0] = "OWL Syntactic Sugar";		typeRulesExpress[1] = "AL_log";		typeRulesExpress[2] = "CARIN_and_DL_Safe";		typeRulesExpress[3] = "CARIN";		typeRulesExpress[4] = "DL_Safe";		typeRulesExpress[5] = "SWRL";	}	private void init() {		numRules = 0;		ruleMap = new HashMap();		rulesExpress = "";		nonDLAtoms = new HashSet();		for (int i = 0; i < 6; i++) {			numRulesExpress[i] = 0;		}			}	 // returns a set of OWLRuleImpl's	public Set loadRules() {		init();				HashSet importedOnts = new HashSet();		Set rules = new HashSet();		OWLOntology ontology = swModel.getSelectedOntology();		try {		URI uri = ontology.getPhysicalURI();		//			URI uri = ontology.getURI();		//			URI uri = swModel.getCurrentlyLoadingURI();		if (!(ontology.equals(null))) {			SWRLParser parser = new SWRLParser();			// For imported ontologies			importedOnts = (HashSet) ontology.getIncludedOntologies();			// If there is no imported ontology in the rules file it assumes			// that rules and ontology are in the same file			if (importedOnts.isEmpty()) {				parser.setOntology(ontology);				rules = parser.parseRules(uri);				numRules = rules.size();			} else {				Iterator it = importedOnts.iterator();				ontology = (OWLOntology) it.next();				parser.setOntology(ontology);				rules = parser.parseRules(uri);				numRules = rules.size();			}					}		} catch (Exception e) {			// e.printStackTrace();			return rules;		}		return rules;	}		// returns a set of RuleValues	public Set getRulesFromMap(HashMap ruleMap) {				Set rules = new HashSet();				for (Iterator it = ruleMap.values().iterator(); it.hasNext();)		{		   rules.addAll((HashSet)it.next());		} 		numRules = rules.size();		return rules;	}		public void preprocess() throws Exception {		try {			if (USE_PROLOG_ENGINE)				allogStream = new BufferedWriter(new FileWriter("allog/allogDB.pl"));		} catch (Exception e) {			e.printStackTrace();		}		nonDLAtoms = new HashSet();				Set rules = new HashSet();		boolean addRulesToMap = false;		if (ruleMap.isEmpty()) {			rules = loadRules();			//need to convert the OWLRuleImpl's to RuleValues						Set ruleValues = new HashSet();					for (Iterator it = rules.iterator(); it.hasNext();)			{			  			  			   ruleValues.add(new RuleValue((OWLRule) it.next(), -1));			} 			numRules = rules.size();			rules = ruleValues;			addRulesToMap = true;		} else {			for (int i = 0; i < 6; i++) {				numRulesExpress[i] = 0;			}			rules = getRulesFromMap(ruleMap);		}				if (rules.size()==0) return;				OWLOntology ontology = swModel.getSelectedOntology();		Set importedOnts = ontology.getIncludedOntologies(); 		if (!importedOnts.isEmpty()) {			Iterator it = importedOnts.iterator();			ontology = (OWLOntology) it.next();		}		// Expressivity of one rule		int levelExpressRule;		if (numRules != 0) {			for (Iterator it = rules.iterator(); it.hasNext();) {				OWLRule rule = ((RuleValue) it.next()).getRule();				// Expressivity of each rule				levelExpressRule = calcOneRuleExpress(rule, ontology, true);								if (levelExpressRule == AL_LOG) {					// add rule and all non-DL atom to Allog stream					writeAllog(rule, ontology);				}							}		}		//find the al-log rules and write them to allogStream				if (USE_PROLOG_ENGINE) {						allogStream.flush();			allogStream.close();						// Pre-process all the DL atoms and add them to the Datalog		// 	database		//			  Query q1 = new Query("spy(shell)");//			  System.out.println("consult q1 " + (q1.hasSolution() ? "succeeded" : "failed"));						if ((numRulesExpress[0] + numRulesExpress[1]) > 0) {				Atom of = new Atom(ontology.getPhysicalURI().toString());				Atom ol = new Atom(ontology.getLogicalURI().toString());				System.out.println("logical URI is " + ol.toString());				Term t = new Compound("preProcess", new Term[] { of, ol });				Query q1 = new Query(t);				System.out.println("consult q1 "						+ (q1.hasSolution() ? "succeeded" : "failed"));				q1 = new Query("listing(clause1)");				System.out.println("consult q1 "						+ (q1.hasSolution() ? "succeeded" : "failed"));			}		}	}			// Calculates the expressivity of the set of rules	// split this in two, one function to load and parse rules, another to calc expressivity	public void setRulesExpress() throws OWLException {			nonDLAtoms = new HashSet();						Set rules = new HashSet();		boolean addRulesToMap = false;		if (ruleMap.isEmpty()) {			rules = loadRules();			//need to convert the OWLRuleImpl's to RuleValues						Set ruleValues = new HashSet();					for (Iterator it = rules.iterator(); it.hasNext();)			{			  			  			   ruleValues.add(new RuleValue((OWLRule) it.next(), -1));			} 			numRules = rules.size();			rules = ruleValues;			addRulesToMap = true;		} else {			for (int i = 0; i < 6; i++) {				numRulesExpress[i] = 0;			}			rules = getRulesFromMap(ruleMap);		}				if (rules.size()==0) return;				OWLOntology ontology = swModel.getSelectedOntology();		Set importedOnts = ontology.getIncludedOntologies(); 		if (!importedOnts.isEmpty()) {			Iterator it = importedOnts.iterator();			ontology = (OWLOntology) it.next();		}		// Expressivity of the set of rules. It is the maximum of the		// expressivity levels in the set		int levelExpress = 0;		// Expressivity of one rule		int levelExpressRule;		if (numRules != 0) {			for (Iterator it = rules.iterator(); it.hasNext();) {				OWLRule rule = ((RuleValue) it.next()).getRule();				// Expressivity of each rule				levelExpressRule = calcOneRuleExpress(rule, ontology, true);												OWLRuleAtom consAtom = (OWLRuleAtom) rule.getConsequents().iterator().next();				// Create HashMap for rules (class or property)				// Key is consequent and object is its set of rules				// values				// Each rule value is a pair (rule, expressivity)				RuleValue ruleValue = new RuleValue(rule, levelExpressRule);				if (addRulesToMap) {					addMap(ruleValue, consAtom);				}				// Maximum of set of rules expressivity				if (levelExpressRule > levelExpress) {					levelExpress = levelExpressRule;				}			}						// Setting the expressivity level variable			switch (levelExpress) {			case SYNTACTIC_SUGAR:				rulesExpress = "Syntactic Sugar for OWL";				rulesExpress += "<br>"					+ "Antecedent and Consequent have exactly one common variable ";				rulesExpress += "<br>"					+ "Or no common variables and at least one common individual";				break;			case AL_LOG:				rulesExpress = "AL-log";				rulesExpress += "<br>"					+ "Class DL-Atoms in Antecedent of rules";				break;			case CARIN_AND_DL_SAFE:				rulesExpress = "CARIN and DL-Safe";				rulesExpress += "<br>"					+ "Class and Role DL-Atoms in Antecedent of rules";				rulesExpress += "<br>"					+ "Each variable in a rule appears in a non-DL atom in the body of the rule";				break;			case CARIN:				rulesExpress = "CARIN";				rulesExpress += "<br>"					+ "Class and Role DL-Atoms in Antecedent of rules";				break;			case DL_SAFE:				rulesExpress = "DL-Safe";				rulesExpress += "<br>"					+ "Class and Role DL-Atoms in Antecedent and Consequent of rules";				rulesExpress += "<br>"					+ "Each variable in a rule appears in a non-DL atom in the body of the rule";				break;			case SWRL:				rulesExpress = "SWRL";				rulesExpress += "<br>"					+ "Class and Role DL-Atoms in Antecedent and Consequent of rules";				break;			}		}	}				public void addMap(RuleValue ruleValue, OWLRuleAtom consAtom) {		HashSet rulesSet = new HashSet();		OWLObject key = null;		Set antecedents;		Set consequents;		try {			antecedents = ruleValue.getRule().getAntecedents();			consequents = ruleValue.getRule().getConsequents();			if (consAtom instanceof OWLRuleClassAtom) {				key = ((OWLRuleClassAtom) consAtom).getDescription();			} else {				if (consAtom instanceof OWLRuleDataPropertyAtom) {					key = ((OWLRuleDataPropertyAtom) consAtom).getProperty();				} else {					if (consAtom instanceof OWLRuleObjectPropertyAtom) {						key = ((OWLRuleObjectPropertyAtom) consAtom)								.getProperty();					}				}			}			if (ruleMap.containsKey(key))				rulesSet = (HashSet) ruleMap.get(key);			rulesSet.add(ruleValue);			ruleMap.put(key, rulesSet);		} catch (Exception e) {			e.printStackTrace();		}	}	public int calcOneRuleExpress(OWLRule rule, OWLOntology onto, boolean update) {		int answer = 0;		boolean isDLSafe = false;		boolean isCARIN = false;		if (checkSyntSugar(rule)) {			answer = SYNTACTIC_SUGAR;		} else {			if (checkALLog(rule, onto)) {				answer = AL_LOG;			} else {				isDLSafe = checkDLSafe(rule, onto);				isCARIN = checkCARIN(rule, onto);				if (isCARIN & isDLSafe) {					answer = CARIN_AND_DL_SAFE;				} else {					if (isCARIN) {						answer = CARIN;					} else {						if (isDLSafe) {							answer = DL_SAFE;						} else {							answer = SWRL;						}					}				}			}		}		if (update) numRulesExpress[answer]++;		return (answer);	}	/**	 * Checks if a given SWRL rule is a CARIN rule	 *  	 */	public boolean checkCARIN(OWLRule rule, OWLOntology onto) {		try {			Set antecedent = rule.getAntecedents();			Set consequent = rule.getConsequents();

⌨️ 快捷键说明

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