00001 package edu.tum.cs.logic.sat.weighted;
00002
00003 import java.util.HashMap;
00004 import java.util.Iterator;
00005 import java.util.Set;
00006 import java.util.Vector;
00007 import java.util.Map.Entry;
00008
00009 import edu.tum.cs.logic.Conjunction;
00010 import edu.tum.cs.logic.Formula;
00011 import edu.tum.cs.logic.TrueFalse;
00012 import edu.tum.cs.logic.sat.Clause.TautologyException;
00013
00018 public class WeightedClausalKB implements Iterable<WeightedClause> {
00019
00020 protected Vector<WeightedClause> clauses;
00021 protected HashMap<WeightedClause, Formula> cl2Formula;
00022 protected edu.tum.cs.util.datastruct.Map2List<WeightedFormula, WeightedClause> formula2clauses;
00023
00030 public WeightedClausalKB(Iterable<WeightedFormula> kb, boolean requirePositiveWeights) throws Exception {
00031 this();
00032 for(WeightedFormula wf : kb) {
00033 addFormula(wf, requirePositiveWeights);
00034 }
00035 }
00036
00040 public WeightedClausalKB() {
00041 clauses = new Vector<WeightedClause>();
00042 cl2Formula = new HashMap<WeightedClause, Formula>();
00043 formula2clauses = new edu.tum.cs.util.datastruct.Map2List<WeightedFormula, WeightedClause>();
00044 }
00045
00052 public void addFormula(WeightedFormula wf, boolean makeWeightPositive) throws Exception {
00053 if(makeWeightPositive && wf.weight < 0) {
00054 wf.weight *= -1;
00055 wf.formula = new edu.tum.cs.logic.Negation(wf.formula);
00056 }
00057
00058 Formula cnf = wf.formula.toCNF();
00059
00060 if(cnf instanceof Conjunction) {
00061 Conjunction c = (Conjunction) cnf;
00062 int numChildren = c.children.length;
00063 for(Formula child : c.children) {
00064 try {
00065 addClause(wf, new WeightedClause(child, wf.weight / numChildren, wf.isHard));
00066 }
00067 catch(TautologyException e) {}
00068 }
00069 }
00070 else if(!(cnf instanceof TrueFalse)) {
00071 try {
00072 addClause(wf, new WeightedClause(cnf, wf.weight, wf.isHard));
00073 }
00074 catch(TautologyException e) {}
00075 }
00076 }
00077
00083 public void addClause(WeightedFormula wf, WeightedClause wc) {
00084 cl2Formula.put(wc, wf.formula);
00085 clauses.add(wc);
00086 formula2clauses.add(wf, wc);
00087 }
00088
00093 public void addClause(WeightedClause wc) {
00094 addClause(new WeightedFormula(wc, wc.weight, wc.isHard), wc);
00095 }
00096
00101 public Iterator<WeightedClause> iterator() {
00102 return clauses.iterator();
00103 }
00104
00109 public int size() {
00110 return clauses.size();
00111 }
00112
00116 public void print() {
00117 int i = 0;
00118 for (WeightedClause c : this)
00119 System.out.printf("%4d %s\n", ++i, c.toString());
00120 }
00121
00125 public HashMap<WeightedClause, Formula> getClause2Formula() {
00126 return cl2Formula;
00127 }
00128
00133 public Set<Entry<WeightedFormula,Vector<WeightedClause>>> getFormulasAndClauses() {
00134 return formula2clauses.entrySet();
00135 }
00136 }