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

📄 custominferenceservices.java

📁 这是外国一个开源推理机
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		// for axioms (two '0' values), and statements that are dependent		// of only one statement (dep2 is '0').		_sail._rdbms.executeUpdate(				"INSERT INTO " + GROUNDED_TRIPLES_TABLE + " VALUES(0)");		// All explicit statements are grounded:		_sail._rdbms.executeUpdate(				"INSERT INTO " + GROUNDED_TRIPLES_TABLE +				" SELECT id FROM " + TRIPLES_TABLE +				" WHERE explicit = " + _sail._rdbms.TRUE);		int count;		do {			String query =				"INSERT INTO " + NEW_GROUNDED_TRIPLES_TABLE +				" SELECT DISTINCT d.id FROM " + DEPEND_TABLE + " d" +				" LEFT JOIN " + GROUNDED_TRIPLES_TABLE + " g ON d.id = g.id";			for (int i = 1; i <= maxTemplateCountsPerRule; i++) {				query += 					" LEFT JOIN " + GROUNDED_TRIPLES_TABLE + " g" + i +					" ON d.dep" + i + " = g" + i + ".id";			}			query += " WHERE g.id IS NULL";			for (int i = 1; i <= maxTemplateCountsPerRule; i++) {				query += " AND g" + i + ".id IS NOT NULL";			}			count = _sail._rdbms.executeUpdate(query.toString());			if (count > 0) {				// Some more grounded statements were found				_sail._rdbms.copyRows(NEW_GROUNDED_TRIPLES_TABLE, GROUNDED_TRIPLES_TABLE);				_sail._rdbms.clearTable(NEW_GROUNDED_TRIPLES_TABLE);				_sail._rdbms.optimizeTable(GROUNDED_TRIPLES_TABLE);			}		}		while (count > 0);	}	/**	 * invoked when some staements are being added so to infer the dependancy information for them	 * @throws SQLException	 */	public void processNewStatements() {		if (_useDependencyInferencer) {			Iterator iter = dependenceSQLs.iterator();			while (iter.hasNext()) {				String s = (String)iter.next();				//System.out.println("inferencer query = " +s);				try {					_sail._rdbms.executeUpdate(s);				}				catch (SQLException e) {					e.printStackTrace();				}			}		}	}	/**	 * invoked to mark the currently added statements as axioms	 * @throws SQLException	 */	public void markAxioms() {		if (_useDependencyInferencer) {			ThreadLog.trace("adding dependencies for axioms");			try {				String query =						"INSERT INTO " + DEPEND_TABLE +						" SELECT id";				for (int i = 1; i <= maxTemplateCountsPerRule; i++) {					query += ", 0";				}				query += " FROM " + ALL_NEW_TRIPLES_TABLE;				_sail._rdbms.executeUpdate(query);			}			catch (SQLException e) {				e.printStackTrace();			}			ThreadLog.trace("dependencies for axioms added");		}	}	/**	 * Prepares a connection and a PreparedStatement for adding	 * rows to the INFERRED_TABLE.	 **/	protected void _prepareInsertConnection()		throws SQLException	{		_insertCon = _sail._rdbms.getConnection();		_insertCon.setAutoCommit(false);		_insertSt = _insertCon.prepareStatement(				"INSERT INTO " + INFERRED_TABLE +				" VALUES(?, ?, ?, ?, ?)");		// All statements are implicit here:		_insertSt.setBoolean(5, false);	}	/**	 * Closes the connection that was prepared in _prepareInsertConnection().	 * If <tt>mustCommit</tt> is true, the started transaction is committed	 * first.	 **/	protected void _closeInsertConnection(boolean mustCommit)		throws SQLException	{		if (mustCommit) {			_insertCon.commit();		}		_insertSt.close();		_insertCon.close();	}	protected void _addAxioms()		throws SailUpdateException	{		ThreadLog.trace("adding axioms");		try {			// Insert all axioms into INFERRED_TABLE			_prepareInsertConnection();			// Axiomatic triples from RDF Semantics, section 3.3:			Iterator iter = axioms.iterator();			while (iter.hasNext()) {				TripleTemplate t = (TripleTemplate)iter.next();				_insertSt.setInt(1, _sail._getNextStatementId());				_insertSt.setInt(2, Rule.getIntId(t.subject));				_insertSt.setInt(3, Rule.getIntId(t.predicate));				_insertSt.setInt(4, Rule.getIntId(t.object));				_insertSt.executeUpdate();			}			_closeInsertConnection(true);			// Copy all axioms that are not yet in the triples table			int newAxioms = _sail._rdbms.executeUpdate(					"INSERT INTO " + NEW_TRIPLES_TABLE +					" SELECT inf.*" +					" FROM " + INFERRED_TABLE + " inf" +					" LEFT JOIN " + TRIPLES_TABLE + " t ON" +						" inf.subj = t.subj AND" +						" inf.pred = t.pred AND" +						" inf.obj = t.obj" +					" WHERE t.subj IS NULL");			if (newAxioms > 0) {				_sail._rdbms.copyRows(NEW_TRIPLES_TABLE, TRIPLES_TABLE);				_sail._rdbms.copyRows(NEW_TRIPLES_TABLE, ALL_NEW_TRIPLES_TABLE);			}			// Clear INFERRED_TABLE			_sail._rdbms.clearTable(INFERRED_TABLE);		}		catch (SQLException e) {			throw new SailUpdateException(e);		}	}	protected int _applyRule(int ruleNo, String query)		throws SailUpdateException	{		long startTime = System.currentTimeMillis();		int nofInferred = 0;		try {			_prepareInsertConnection();			Connection queryCon = _sail._rdbms.getConnection();			java.sql.Statement querySt = queryCon.createStatement();			ResultSet rs = querySt.executeQuery(query);			while (rs.next()) {				_insertSt.setInt(1, _sail._getNextStatementId()); // id				_insertSt.setInt(2, rs.getInt(1)); // subj				_insertSt.setInt(3, rs.getInt(2)); // pred				_insertSt.setInt(4, rs.getInt(3)); // obj				_insertSt.executeUpdate();				nofInferred++;			}			rs.close();			querySt.close();			queryCon.close();			_closeInsertConnection(nofInferred > 0);			if (nofInferred > 0) {				_ruleCount[ruleNo] += nofInferred;				// Copy the newly inferred statements from INFERRED_TABLE to				// ALL_INFERRED_TABLE...				_sail._rdbms.copyRows(INFERRED_TABLE, ALL_INFERRED_TABLE);				// ...and to TRIPLES_TABLE.				_sail._rdbms.copyRows(INFERRED_TABLE, TRIPLES_TABLE);				// Clear INFERRED_TABLE				_sail._rdbms.clearTable(INFERRED_TABLE);			}		}		catch (SQLException e) {			ThreadLog.error("SQL error on rule(" + ruleNo + "): " + query);			throw new SailUpdateException(e);		}		long endTime = System.currentTimeMillis();		_ruleTime[ruleNo] += (endTime - startTime);		return nofInferred;	}	/**	 * need to handle creation of DEPEND table because some of the rules may need more	 * than 2 columns to store the dependancy (rules with t=hree or more triple templates in CustomInferencer)	 * An example of such rule:	 *	 a rdf:type owl:TransitiveProperty	 *	 x a b	 *	 b a c	 * infer:	 *	 x a c	 * so the (x a c) triple is dependant from all those	 * @throws SQLException	 */	public void createDependenciesTable()		throws SQLException	{		if (_useDependencyInferencer) {			String[] index1Opts = new String[maxTemplateCountsPerRule + 1];			String[] index2Opts = new String[maxTemplateCountsPerRule];			index1Opts[0] = "id";			index1Opts[1] = "dep1";			index1Opts[2] = "dep2";			index2Opts[0] = "dep1";			index2Opts[1] = "dep2";			String query =					"CREATE TABLE " + DEPEND_TABLE +					" (id " + _sail._rdbms.ID_INT + " NOT NULL ";			for (int i = 1; i <= maxTemplateCountsPerRule; i++) {				query += ", dep" + i + " " + _sail._rdbms.ID_INT + " NOT NULL";				index1Opts[i] = "dep" + i;				index2Opts[i - 1] = "dep" + i;			}			query += ")";			_sail._rdbms.executeUpdate(query);			_sail._rdbms.createIndex(DEPEND_TABLE, index1Opts, false);			_sail._rdbms.createIndex(DEPEND_TABLE, index2Opts, false);		}	}	/**	 * invoked to ensure that thre RDBMS instance is already created within Sail	 */	public void afterInitialize() {		//System.out.println("* AfterInit custom inference");		if (_sail._rdbms instanceof PostgreSQL) {			//System.out.println("* Running postgres");			try {				_sail._rdbms.executeUpdate(						"CREATE FUNCTION \"concat\" (text,text)" +						" RETURNS text AS 'SELECT $1 || $2;' LANGUAGE 'sql';");			}			catch (SQLException e) {				String msg = e.getMessage();				if (msg.indexOf("already exists") > -1) {					// FIXME there has to be a better way to handle this					// concat function already specified, ignore error				}				else {					throw new SailInternalException(e);				}			}		}	}	/**	 * matchTriples - given a consequent and a premise it simply mathces them	 * reporting that the consequent can be a premise for a rule	 * @param t1	 * @param t2	 * @return true if it si applicable. the arguments are compared by-component.	 * In case of a varible both componets of the triple can be unified.	 * In case of an explicit URIs they should be exactly the same.	 */	protected boolean matchTriples(TripleTemplate t1, TripleTemplate t2) {		// special case on transitivity rules		if (t1.subject.isVar() && t1.object.isVar() &&			t2.subject.isVar() && t2.object.isVar() &&			t1.subject.value().equalsIgnoreCase(t1.object.value()) &&			!t2.subject.value().equalsIgnoreCase(t2.object.value()))		{			return false;		}		if (!t1.subject.isVar() && !t2.subject.isVar() &&			!t1.subject.value().equalsIgnoreCase(t2.subject.value()))		{			return false;		}		if (!t1.predicate.isVar() && !t2.predicate.isVar() &&			!t1.predicate.value().equalsIgnoreCase(t2.predicate.value()))		{			return false;		}		if (!t1.object.isVar() && !t2.object.isVar() &&			!t1.object.value().equalsIgnoreCase(t2.object.value()))		{			return false;		}		return true;	} //matchTriples()	/**	 * method buildTriggers - given a list of rules it builds the inter-rule dependancy table.	 * e.g. If a rule inferrs some new statemnents which rules should be applied on next iteration.	 * This method is implementation specific because it deals with several variants of a rule.	 * @param rules ArrayList with the Rule instances	 * @return square array of boolean values. each row holds the flags that indicate which rules(	 * rule variants) are trigered by this rule(rule variant)	 */	protected boolean[][] buildTriggers(ArrayList rules) {		// Determine the total number of rule variants, which is equal		// to the amount of premises for the complete set of rules		int num_rule_variants = 0;		for (int i = 0; i < rules.size(); i++) {			Rule r = (Rule)rules.get(i);			num_rule_variants += r.getPremiseCount();		}		// Create a square triggers array		boolean[][] result = new boolean[num_rule_variants][num_rule_variants];		int rowIndex = 0;		for (int i = 0; i < rules.size(); i++) {			Rule activator = (Rule)rules.get(i);			int colIndex = 0;			for (int j = 0; j < rules.size(); j++) {				Rule activated = (Rule)rules.get(j);				// Determine if 'activator' triggers 'activated'				boolean inTrigersList = false;				if (activator.getTriggersRule() != null) {					Iterator trIter = activator.getTriggersRule().iterator();					while (trIter.hasNext()) {						String toCheck = (String)trIter.next();						if (toCheck.equalsIgnoreCase(activated.getName())) {							inTrigersList = true;							break;						}					}				}				if (inTrigersList) {					TripleTemplate consequent = activator.getConsequent();					for (int indexActivated = 0; indexActivated < activated.getPremiseCount(); indexActivated++) {						TripleTemplate premiseToCheck =								(TripleTemplate)activated.getPremiseCollection().get(indexActivated);						boolean valueToSet = matchTriples(consequent, premiseToCheck);						for (int activatorSize = 0; activatorSize < activator.getPremiseCount(); activatorSize++) {							result[rowIndex + activatorSize][colIndex + indexActivated] = valueToSet;						}					}				}				colIndex += activated.getPremiseCount();			}			rowIndex += activator.getPremiseCount();		}		return result;	} // buildTriggers();	private void _removeAllInferred()		throws SQLException	{		_sail._rdbms.executeUpdate(				"DELETE FROM " + TRIPLES_TABLE +				" WHERE explicit = " + _sail._rdbms.FALSE);	}}

⌨️ 快捷键说明

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