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

📄 createkb.java

📁 Mandarax是一个规则引擎的纯Java实现。它支持多类型的事实和基于反映的规则
💻 JAVA
字号:
/*
 * Copyright (C) 1999-2004 <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</a>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package org.mandarax.examples.db;

import java.io.File;
import java.util.Date;

import org.mandarax.kernel.Fact;
import org.mandarax.kernel.KnowledgeBase;
import org.mandarax.kernel.Rule;
import org.mandarax.kernel.SimplePredicate;
import org.mandarax.lib.math.DoubleArithmetic;
import org.mandarax.lib.math.IntArithmetic;
import org.mandarax.reference.AdvancedKnowledgeBase;
import org.mandarax.sql.OneColumnMapping;
import org.mandarax.sql.SQLFunction;
import org.mandarax.util.LogicFactorySupport;
import org.mandarax.zkb.*;
import org.mandarax.zkb.framework.ZKBDriver_1_1;


/**
 * This class creates the knowledge base for the discount example. To generate the knowledge base, run the main method.
 * <p>
 * Note that the example works with a relational database. Any database should do as long as aggregation
 * functions are supported. E.g., the free MySQL database or Oracle8 can be used. 
 * The example uses a <code>SimpleDataSource</code> to connect to the database. 
 * How to configure a particular database is described in the comment of this class.
 * <p>
 * In a real world scenario a knowledge base is probably created using a GUI and not by the direct execution
 * of a script as it is done here.
 * <p>
 * Mandarax uses other (open source) libraries such as JDOM, the apache log4j
 * logging library and the junit testing framework. The mandarax distribution 
 * contains the respective libraries. Please but these jar files in the classpath 
 * before running the example! In addition, the JDBC driver for the database used must 
 * also be in the classpath.
 * @see SimpleDataSource
 * @see CreateDB
 * @since 2.2
 * @author <A href="http://www-ist.massey.ac.nz/JBDietrich" target="_top">Jens Dietrich</A>
 * @version 3.4 <7 March 05>
 */
public class CreateKB {

	private LogicFactorySupport lfs = new LogicFactorySupport();

	// queries for functions
	public static final String QUERY_MAX_AMOUNT_BY_CUSTOMER =
		"SELECT MAX(AMOUNT) FROM CUSTOMER_TRANSACTIONS WHERE CUSTOMER=? GROUP BY CUSTOMER";
	public static final String QUERY_SUM_AMOUNT_BY_CUSTOMER =
		"SELECT SUM(AMOUNT) FROM CUSTOMER_TRANSACTIONS WHERE CUSTOMER=? GROUP BY CUSTOMER";
	public static final String QUERY_NUMBER_OF_TRANSACTIONS_BY_CUSTOMER =
		"SELECT COUNT(*) FROM CUSTOMER_TRANSACTIONS WHERE CUSTOMER=?";
	public static final String QUERY_DATE_OF_LAST_TRANSACTION_BY_CUSTOMER =
		"SELECT MAX(TRANSACTION_DATE) FROM CUSTOMER_TRANSACTIONS WHERE CUSTOMER=? GROUP BY CUSTOMER";

	// functions
	public SQLFunction function_max_amount_by_customer = null;
	public SQLFunction function_sum_amount_by_customer = null;
	public SQLFunction function_number_transactions_by_customer = null;
	public SQLFunction function_last_transaction_date_by_customer = null;

	// predicates
	public SimplePredicate has_category = null;
	public SimplePredicate gets_discount = null;
	
	/**
	 * Create the knowledge base.
	 */
	public static void main(String[] args) {
		// uncomment the following line to switch on logging
		// org.apache.log4j.BasicConfigurator.configure();
		
		CreateKB kbCreator = new CreateKB();
		kbCreator.initFunctionsAndPredicates();
		KnowledgeBase kb = kbCreator.createKB();
		kbCreator.saveKB(kb);
	}
	/**
	 * Return the knowledge base for this example.
	 * @return a knowledge base
	 */
	public KnowledgeBase createKB() {

		KnowledgeBase kb = new AdvancedKnowledgeBase();
		// Initialize functions and predicates
		
		// add rules
		Rule rule1 =
			lfs.rule(
				lfs.prereq(
					DoubleArithmetic.LESS_THAN,
					new Double(200.00),
					lfs.cplx(function_sum_amount_by_customer, lfs.variable("a customer"))),
				lfs.fact(has_category, lfs.variable("a customer"), "GOLD"));
		kb.add(rule1);
		Rule rule2 =
			lfs.rule(
				lfs.prereq(has_category, lfs.variable("a customer"), "GOLD"),
				lfs.fact(gets_discount, lfs.variable("a customer"), new Discount(5.0, true)));
		kb.add(rule2);
		Rule rule3 =
			lfs.rule(
				lfs.prereq(has_category, lfs.variable("a customer"), "SILVER"),
				lfs.fact(gets_discount, lfs.variable("a customer"), new Discount(3.0, true)));
		kb.add(rule3);
		Rule rule4 =
			lfs.rule(
				lfs.prereq(has_category, lfs.variable("a customer"), "STANDARD"),
				lfs.fact(gets_discount, lfs.variable("a customer"), new Discount(0.0, true)));
		kb.add(rule4);
		Rule rule5 =
			lfs.rule(
				lfs.prereq(
					IntArithmetic.LESS_THAN,
					new Integer(2),
					lfs.cplx(function_number_transactions_by_customer, lfs.variable("a customer"))),
				lfs.fact(has_category, lfs.variable("a customer"), "SILVER"));
		kb.add(rule5);
		Rule rule6 =
			lfs.rule(
				lfs.prereq(
					DoubleArithmetic.LESS_THAN,
					new Double(100.0),
					lfs.cplx(function_max_amount_by_customer, lfs.variable("a customer"))),
				lfs.fact(has_category, lfs.variable("a customer"), "GOLD"));
		kb.add(rule6);
		Fact fact = lfs.fact(has_category, lfs.variable("each customer"), "STANDARD");
		kb.add(fact);
		
		// add queries
		kb.addQuery(lfs.query(
			lfs.fact(gets_discount, "Tom", lfs.variable("discount", Discount.class)),
			"Discount for customer \"Tom\""));			
		kb.addQuery(lfs.query(
			lfs.fact(gets_discount, "John", lfs.variable("discount", Discount.class)),
			"Discount for customer \"John\""));
		kb.addQuery(lfs.query(
			lfs.fact(gets_discount, "Jim", lfs.variable("discount", Discount.class)),
			"Discount for customer \"Jim\""));
		kb.addQuery(lfs.query(
			lfs.fact(gets_discount, "Ralf", lfs.variable("discount", Discount.class)),
			"Discount for customer \"Ralf\""));
		kb.addQuery(lfs.query(
			lfs.fact(gets_discount, "Bill", lfs.variable("discount", Discount.class)),
			"Discount for customer \"Bill\""));

		return kb;
	}
	/**
	 * Initialize the functions and predicates.
	 */
	private void initFunctionsAndPredicates() {

		// init data source
		SimpleDataSource dataSource = new SimpleDataSource();

		// init functions
		Class[] struct = { String.class };

		function_max_amount_by_customer = new SQLFunction();
		function_max_amount_by_customer.setDataSource(dataSource);
		function_max_amount_by_customer.setQuery(QUERY_MAX_AMOUNT_BY_CUSTOMER);
		function_max_amount_by_customer.setObjectRelationalMapping(new OneColumnMapping(Double.class));
		function_max_amount_by_customer.setName("max transaction amount of a customer");
		function_max_amount_by_customer.setStructure(struct);

		function_sum_amount_by_customer = new SQLFunction();
		function_sum_amount_by_customer.setDataSource(dataSource);
		function_sum_amount_by_customer.setQuery(QUERY_SUM_AMOUNT_BY_CUSTOMER);
		function_sum_amount_by_customer.setObjectRelationalMapping(new OneColumnMapping(Double.class));
		function_sum_amount_by_customer.setName("value of all transactions of a customer");
		function_sum_amount_by_customer.setStructure(struct);

		function_number_transactions_by_customer = new SQLFunction();
		function_number_transactions_by_customer.setDataSource(dataSource);
		function_number_transactions_by_customer.setQuery(QUERY_NUMBER_OF_TRANSACTIONS_BY_CUSTOMER);
		function_number_transactions_by_customer.setObjectRelationalMapping(new OneColumnMapping(Integer.class));
		function_number_transactions_by_customer.setName("number of all transactions of a customer");
		function_number_transactions_by_customer.setStructure(struct);

		function_last_transaction_date_by_customer = new SQLFunction();
		function_last_transaction_date_by_customer.setDataSource(dataSource);
		function_last_transaction_date_by_customer.setQuery(QUERY_DATE_OF_LAST_TRANSACTION_BY_CUSTOMER);
		function_last_transaction_date_by_customer.setObjectRelationalMapping(new OneColumnMapping(Date.class));
		function_last_transaction_date_by_customer.setName("date of the last transactions of a customer");
		function_last_transaction_date_by_customer.setStructure(struct);

		// predicates
		Class[] struct2 = { String.class, Discount.class };
		gets_discount = new SimplePredicate("a customer gets a discount", struct2);

		Class[] struct3 = { String.class, String.class };
		has_category = new SimplePredicate("a customer has a category", struct3);

	}
	/**
	 * Save knowledge base to a file "kb.xml".
	 * @param kb a knowledge base
	 */
	public void saveKB(KnowledgeBase kb) {
		ZKBManager zkbManager = new ZKBManager();
		zkbManager.setDriver(new ZKBDriver_1_1());
		try {
			//zkbManager.setOps(new XMLSerializationOPS());
			zkbManager.exportKnowledgeBase(new File("kb.zip"),kb);			
			System.out.println("Knowledge base exported to kb.zip");
		}
		catch (ZKBException x) {
			System.err.println("Cannot export knowledge base");
			x.printStackTrace();
		}		
	}
	

}

⌨️ 快捷键说明

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