00001
00002
00003
00004
00005
00006
00007 package edu.tum.cs.srl.mln.inference;
00008
00009 import java.io.BufferedReader;
00010 import java.io.File;
00011 import java.io.IOException;
00012 import java.io.InputStream;
00013 import java.io.InputStreamReader;
00014 import java.util.ArrayList;
00015
00016 import edu.tum.cs.logic.GroundAtom;
00017 import edu.tum.cs.logic.PossibleWorld;
00018 import edu.tum.cs.srl.mln.MarkovRandomField;
00019 import edu.tum.cs.wcsp.WCSPConverter;
00020
00021 public class Toulbar2MAPInference extends MAPInferenceAlgorithm {
00022
00023 protected PossibleWorld state;
00024
00025 public Toulbar2MAPInference(MarkovRandomField mrf) throws Exception {
00026 super(mrf);
00027 state = new PossibleWorld(mrf.getWorldVariables());
00028 }
00029
00030 @Override
00031 public double getResult(GroundAtom ga) {
00032 return state.get(ga.index) ? 1.0 : 0.0;
00033 }
00034
00035 @Override
00036 public ArrayList<InferenceResult> infer(Iterable<String> queries, int maxSteps) throws Exception {
00037
00038
00039 System.out.println("performing WCSP conversion...");
00040 WCSPConverter converter = new WCSPConverter(mrf);
00041 converter.run("temp.wcsp", null);
00042
00043
00044 System.out.println("running Toulbar2...");
00045 Process p = Runtime.getRuntime().exec("toulbar2 temp.wcsp s");
00046 InputStream s = p.getInputStream();
00047 BufferedReader br = new BufferedReader(new InputStreamReader(s));
00048 String solution = null;
00049 while(true) {
00050 try {
00051 String l = br.readLine();
00052 if(l == null)
00053 break;
00054 if(l.startsWith("New solution:")) {
00055 solution = br.readLine();
00056 }
00057
00058 }
00059 catch(IOException e) {
00060 break;
00061 }
00062 }
00063
00064
00065 System.out.println("WCSP solution: " + solution);
00066 String[] solutionParts = solution.trim().split(" ");
00067 for(int i = 0; i < solutionParts.length; i++) {
00068 int domIdx = Integer.parseInt(solutionParts[i]);
00069 converter.setGroundAtomState(state, i, domIdx);
00070 }
00071
00072
00073 state.setEvidence(mrf.getDb());
00074
00075
00076 new File("temp.wcsp").delete();
00077
00078 return getResults(queries);
00079 }
00080
00081 @Override
00082 public PossibleWorld getSolution() {
00083 return state;
00084 }
00085
00086 }