00001 package edu.tum.cs.logic;
00002
00003 import java.util.Map;
00004 import java.util.Set;
00005 import java.util.regex.Matcher;
00006 import java.util.regex.Pattern;
00007
00008 import edu.tum.cs.srl.Database;
00009 import edu.tum.cs.util.StringTool;
00010
00011 public class GroundAtom extends Formula {
00012 public String predicate;
00013 public String[] args;
00014 public int index;
00015
00016 public GroundAtom(String predicate, String[] args) {
00017 this.predicate = predicate;
00018 this.args = args;
00019 index = -1;
00020 }
00021
00022 public GroundAtom(String gndAtom) {
00023 Pattern p = Pattern.compile("(\\w+)\\(([^\\)]+)\\)");
00024 Matcher m = p.matcher(gndAtom);
00025 if(!m.matches()) {
00026 throw new RuntimeException("Could not parse ground atom '" + gndAtom + "'");
00027 }
00028 predicate = m.group(1);
00029 args = m.group(2).split("\\s*,\\s*");
00030 index = -1;
00031 }
00032
00033 public boolean isTrue(IPossibleWorld w) {
00034 return w.isTrue(this);
00035 }
00036
00037 public void setIndex(int i) {
00038 index = i;
00039 }
00040
00041 @Override
00042 public void getVariables(Database db, Map<String, String> ret) {
00043 }
00044
00045 @Override
00046 public Formula ground(Map<String, String> binding, WorldVariables vars, Database db) {
00047 return this;
00048 }
00049
00050 @Override
00051 public void getGroundAtoms(Set<GroundAtom> ret) {
00052 ret.add(this);
00053 }
00054
00055 @Override
00056 public String toString() {
00057 return predicate + "(" + StringTool.join(",", args) + ")";
00058 }
00059
00060 @Override
00061 public Formula toCNF() {
00062 return this;
00063 }
00064
00065 @Override
00066 public Formula toNNF() {
00067 return this;
00068 }
00069
00070 @Override
00071 public boolean equals(Object other) {
00072 int otherIdx = ((GroundAtom)other).index;
00073 if(this.index == -1 || otherIdx == -1)
00074 throw new RuntimeException("Cannot compare GroundAtoms that are not yet part of a WorldVariables collection.");
00075 return this.index == otherIdx;
00076 }
00077
00078 @Override
00079 public int hashCode() {
00080 if(this.index == -1)
00081 throw new RuntimeException("Tried to compute hash code of GroundAtom that was not yet added to a collection of world variables.");
00082 return this.index;
00083 }
00084
00090 @Override
00091 public Formula simplify(Database evidence) {
00092 try {
00093
00094 if(evidence != null) {
00095 String value = evidence.getVariableValue(this.toString(), false);
00096 if(value != null) {
00097 if(value.equals("True"))
00098 return TrueFalse.TRUE;
00099 else if (value.equals("False"))
00100 return TrueFalse.FALSE;
00101 else
00102 throw new RuntimeException("Database contains invalid boolean value '" + value + "' for atom " + this.toString());
00103 }
00104 }
00105
00106 return this;
00107 }
00108 catch(Exception e) {
00109 throw new RuntimeException(e.getMessage());
00110 }
00111 }
00112 }