00001 package edu.tum.cs.logic;
00002
00003 import edu.tum.cs.srl.Database;
00004
00005 import java.util.Collection;
00006 import java.util.Vector;
00007
00008 public class Negation extends ComplexFormula {
00009 public Negation(Formula f) {
00010 super(new Formula[]{f});
00011 }
00012
00013 public Negation(Collection<Formula> children) throws Exception {
00014 super(children);
00015 if (children.size() != 1)
00016 throw new Exception("A negation can have but one child.");
00017 }
00018
00019 public String toString() {
00020 return "!(" + this.children[0].toString() + ")";
00021 }
00022
00023 @Override
00024 public boolean isTrue(IPossibleWorld w) {
00025 return !children[0].isTrue(w);
00026 }
00027
00028 @Override
00029 public Formula toCNF() {
00030 Formula f = children[0].toCNF();
00031 if (f instanceof ComplexFormula) {
00032 Vector<Formula> negChildren = new Vector<Formula>();
00033 for (Formula child : ((ComplexFormula) f).children)
00034 negChildren.add(new Negation(child));
00035 if (f instanceof Disjunction)
00036 return new Conjunction(negChildren).toCNF();
00037 else
00038 return new Disjunction(negChildren).toCNF();
00039 } else {
00040 if (f instanceof GroundLiteral) {
00041 GroundLiteral l = (GroundLiteral) f;
00042 return new GroundLiteral(!l.isPositive, l.gndAtom);
00043 } else if (f instanceof TrueFalse) {
00044 TrueFalse tf = (TrueFalse) f;
00045 return TrueFalse.getInstance(!tf.isTrue());
00046 }
00047 else if(f instanceof GroundAtom) {
00048 return new GroundLiteral(false, (GroundAtom)f);
00049 }
00050 throw new RuntimeException("CNF conversion of negation of " + children[0].getClass().getSimpleName() + " not handled.");
00051 }
00052 }
00053
00054 @Override
00055 public Formula toNNF() {
00056 Formula f = children[0].toNNF();
00057 if (f instanceof ComplexFormula) {
00058 Vector<Formula> negChildren = new Vector<Formula>();
00059 for (Formula child : ((ComplexFormula) f).children)
00060 negChildren.add(new Negation(child));
00061 if (f instanceof Disjunction)
00062 return new Conjunction(negChildren).toNNF();
00063 else
00064 return new Disjunction(negChildren).toNNF();
00065 } else {
00066 if (f instanceof GroundLiteral) {
00067 GroundLiteral l = (GroundLiteral) f;
00068 return new GroundLiteral(!l.isPositive, l.gndAtom);
00069 } else if (f instanceof TrueFalse) {
00070 TrueFalse tf = (TrueFalse) f;
00071 return TrueFalse.getInstance(!tf.isTrue());
00072 }
00073 else if(f instanceof GroundAtom) {
00074 return new GroundLiteral(false, (GroundAtom)f);
00075 }
00076 throw new RuntimeException("CNF conversion of negation of " + children[0].getClass().getSimpleName() + " not handled.");
00077 }
00078 }
00079
00085 @Override
00086 public Formula simplify(Database evidence) {
00087
00088 Formula f = this.children[0].simplify(evidence);
00089
00090 if(f instanceof TrueFalse)
00091 return TrueFalse.getInstance(!((TrueFalse) f).isTrue());
00092
00093 return new Negation(f);
00094 }
00095 }