00001 package edu.tum.cs.logic;
00002
00003 import java.io.BufferedReader;
00004 import java.io.IOException;
00005 import java.io.StringReader;
00006 import java.util.HashMap;
00007 import java.util.Iterator;
00008 import java.util.Vector;
00009 import java.util.regex.Matcher;
00010 import java.util.regex.Pattern;
00011
00012 import edu.tum.cs.logic.parser.FormulaParser;
00013 import edu.tum.cs.logic.parser.ParseException;
00014 import edu.tum.cs.srl.Database;
00015 import edu.tum.cs.util.FileUtil;
00016
00022 public class KnowledgeBase implements Iterable<Formula> {
00023 protected Vector<Formula> formulas;
00027 protected HashMap<Formula, Integer> templateIDs;
00028
00029 public KnowledgeBase() {
00030 formulas = new Vector<Formula>();
00031 templateIDs = new HashMap<Formula, Integer>();
00032 }
00033
00040 public KnowledgeBase(String filename) throws IOException, ParseException {
00041 this();
00042
00043 String fileContent = FileUtil.readTextFile(filename);
00044
00045 Pattern comments = Pattern.compile("//.*?$|/\\*.*?\\*/", Pattern.MULTILINE | Pattern.DOTALL);
00046 Matcher matcher = comments.matcher(fileContent);
00047 fileContent = matcher.replaceAll("");
00048
00049 BufferedReader br = new BufferedReader(new StringReader(fileContent));
00050 String line;
00051 for(;;) {
00052 line = br.readLine();
00053 if(line == null)
00054 break;
00055 line = line.trim();
00056 if(line.length() == 0)
00057 continue;
00058 if(line.endsWith("."))
00059 formulas.add(FormulaParser.parse(line.substring(0, line.length()-1)));
00060 else
00061 System.err.println("Warning: Line without terminating period ignored: " + line);
00062 }
00063 }
00064
00065 public Vector<Formula> getFormulas() {
00066 return formulas;
00067 }
00068
00077 public KnowledgeBase ground(Database db, WorldVariables worldVars, boolean simplify) throws Exception {
00078 KnowledgeBase ret = new KnowledgeBase();
00079 Integer formulaID = 0;
00080 for(Formula f : formulas) {
00081 int i = ret.formulas.size();
00082 f.addAllGroundingsTo(ret.formulas, db, worldVars, simplify);
00083 for(; i < ret.formulas.size(); i++) {
00084 templateIDs.put(ret.formulas.get(i), formulaID);
00085 }
00086 formulaID++;
00087 }
00088 return ret;
00089 }
00090
00091 public Iterator<Formula> iterator() {
00092 return formulas.iterator();
00093 }
00094
00095 public int size() {
00096 return formulas.size();
00097 }
00098
00099 public Integer getTemplateID(Formula f) {
00100 return templateIDs.get(f);
00101 }
00102 }