00001 package edu.tum.cs.probcog;
00002
00003 import java.io.BufferedReader;
00004 import java.io.IOException;
00005 import java.io.InputStreamReader;
00006 import java.util.Arrays;
00007 import java.util.Collection;
00008 import java.util.Collections;
00009 import java.util.LinkedList;
00010 import java.util.Vector;
00011 import java.util.regex.Matcher;
00012 import java.util.regex.Pattern;
00013
00014 import edu.tum.cs.logic.parser.ParseException;
00015 import edu.tum.cs.srl.Signature;
00016
00022 public class Server {
00023 ModelPool modelPool;
00024
00025 public Server(String modelPoolFile) throws IOException, ParseException, Exception {
00026 modelPool = new ModelPool(modelPoolFile);
00027 }
00028
00029 protected static Vector<String[]> readListOfLispTuples(String s) {
00030 Vector<String[]> ret = new Vector<String[]>();
00031 s = s.substring(2, s.length()-2);
00032 String[] tuples = s.split("\\)\\s*\\(");
00033 for(String tuple : tuples)
00034 ret.add(tuple.split("\\s+"));
00035 return ret;
00036 }
00037
00046 public Vector<InferenceResult> query(String request) throws IOException, ParseException, Exception {
00047
00048 String[] qs = request.split(";");
00049 String query = qs[0];
00050 String evidence = qs[1];
00051
00052
00053 Collection<String[]> queryTuples = readListOfLispTuples(query);
00054 Vector<String> queries = queriesFromTuples(queryTuples);
00055
00056
00057 Collection<String[]> evidenceTuples = readListOfLispTuples(evidence);
00058
00059 return query("tableSetting", queries, evidenceTuples);
00060 }
00061
00062 public Vector<String[]> getPredicates(String modelName) {
00063 return modelPool.getModel(modelName).getPredicates();
00064 }
00065
00066 public Vector<String[]> getDomains(String modelName) {
00067 return modelPool.getModel(modelName).getDomains();
00068 }
00069
00070 public Model getModel(String modelName) {
00071 return modelPool.getModel(modelName);
00072 }
00073
00080 protected static Vector<String> queriesFromTuples(Collection<String[]> queryTuples) {
00081 Vector<String> queries = new Vector<String>();
00082 for(String[] tuple : queryTuples) {
00083
00084 StringBuffer sb = new StringBuffer(tuple[0] + "(");
00085 for(int i = 1; i < tuple.length; i++) {
00086 if(i > 1)
00087 sb.append(',');
00088 if(tuple[i].charAt(0) == '?')
00089 sb.append("a" + i);
00090 else
00091 sb.append(tuple[i]);
00092 }
00093 sb.append(')');
00094 System.out.println("query: " + sb.toString());
00095 queries.add(sb.toString());
00096 }
00097 return queries;
00098 }
00099
00109 public Vector<InferenceResult> query(String modelName, Collection<String> queries, Collection<String[]> evidence) throws Exception {
00110
00111 Model model = modelPool.getModel(modelName);
00112
00113 model.setEvidence(evidence);
00114
00115 System.out.printf("instantiating model from %s\n", model.toString());
00116 model.instantiate();
00117 Vector<InferenceResult> results = model.infer(queries);
00118
00119 boolean verbose = true;
00120 if(verbose) {
00121 System.out.println("\nEvidence:");
00122 for(String[] e : evidence)
00123 System.out.println(Arrays.toString(e));
00124 System.out.println("\nResults:");
00125 LinkedList<InferenceResult> sortedres = new LinkedList<InferenceResult>(results);
00126 Collections.sort(sortedres);
00127 for(InferenceResult r : sortedres)
00128 r.print(System.out);
00129 }
00130
00131 return results;
00132 }
00133
00142 public Vector<InferenceResult> query(String modelName, Collection<String> queries, Iterable<String> evidence) throws Exception {
00143
00144 Pattern atom = Pattern.compile("(\\w+)\\((.*?)\\)");
00145 Vector<String[]> newEv = new Vector<String[]>();
00146 for(String var : evidence) {
00147 Matcher m = atom.matcher(var);
00148 if(!m.matches())
00149 throw new IllegalArgumentException("Evidence variable formatted incorrectly: " + var);
00150 String fName = m.group(1);
00151 String[] params = m.group(2).split("\\s*,\\s*");
00152 String[] seq = new String[params.length+1];
00153 seq[0] = fName;
00154 for(int i = 0; i < params.length; i++)
00155 seq[i+1] = params[i];
00156 newEv.add(seq);
00157 }
00158
00159 return query(modelName, queries, newEv);
00160 }
00161
00162 protected static String inferenceResults2LispTuples(Vector<InferenceResult> results) {
00163 StringBuffer sb = new StringBuffer('(');
00164 for(InferenceResult res : results) {
00165 sb.append('(');
00166 sb.append(res.functionName).append(' ');
00167 for(int i = 0; i < res.params.length; i++)
00168 sb.append(res.params[i]).append(' ');
00169 sb.append(res.probability);
00170 sb.append(')');
00171 }
00172 sb.append(')');
00173 return sb.toString();
00174 }
00175
00176 public static void main(String[] args) {
00177 try {
00178 Server server = new Server("/tmp/buildd/ros-diamondback-knowrob-0.2.0/debian/ros-diamondback-knowrob/opt/ros/diamondback/stacks/knowrob/srldb/models/models.xml");
00179 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
00180 System.err.println("ProbCog Server Test");
00181
00182 boolean testKnowRob = true;
00183 boolean testLISP = false;
00184 if(testKnowRob) {
00185 String modelName = "tableSetting_fall09";
00186 Model model = server.getModel(modelName);
00187
00188 Vector<String> evidence = new Vector<String>();
00189 evidence.add("takesPartIn(person1,meal1)");
00190 evidence.add("mealT(meal1,Breakfast)");
00191 boolean autoUsage = false;
00192 if(!autoUsage) {
00193 evidence.add("consumesAnyIn(person1,CowsMilk-Product,meal1)");
00194
00195 }
00196 else {
00197 String[] observedClasses = new String[]{"Milk", "Cereals"};
00198 for(String instance : observedClasses) {
00199 String objType = instance;
00200 String constantType = model.getConstantType(objType);
00201 String predicate = null;
00202 if(constantType != null) {
00203 if(constantType.equalsIgnoreCase("domUtensilT"))
00204 predicate = "usesAnyIn";
00205 else if(constantType.equalsIgnoreCase("objType_g"))
00206 predicate = "consumesAnyIn";
00207 if(predicate != null) {
00208 String evidenceAtom = String.format("%s(P,%s,M)", predicate, objType);
00209 evidence.add(evidenceAtom);
00210 }
00211 else
00212 System.err.println("Warning: Evidence on instance '" + instance + "' not considered because it is neither a utensil nor a consumable object known to the model.");
00213 }
00214 else
00215 System.err.println("Warning: Evidence on instance '" + instance + "' not considered because its type is not known to the model.");
00216 }
00217 }
00218
00219 Vector<String> queries = new Vector<String>();
00220 queries.add("usesAnyIn");
00221 queries.add("consumesAnyIn");
00222
00223 Vector<InferenceResult> results = server.query(modelName, queries, evidence);
00224 System.out.println();
00225 for(InferenceResult res : results) {
00226 res.print(System.out);
00227 }
00228 }
00229 if(testLISP) {
00230 String input = "((sitsAtIn ?PERSON ?SEATING-LOCATION M) (usesAnyIn ?PERSON ?UTENSIL M));((takesPartIn P1 M) (name P1 Anna) (takesPartIn P2 M) (name P2 Bert) (takesPartIn P3 M) (name P3 Dorothy) (mealT M Breakfast))";
00231 String output = inferenceResults2LispTuples(server.query(input));
00232 System.out.println(output);
00233 }
00234
00235 while(true) {
00236 System.err.println("Waiting for Input");
00237 String line = br.readLine();
00238 if(line.equals("close")) {
00239 System.err.println("ProbCog Server closed");
00240 break;
00241 }
00242 System.err.println("Received query: " + line);
00243 String result = inferenceResults2LispTuples(server.query(line));
00244 System.out.println(result);
00245 }
00246 }
00247 catch(Exception e) {
00248 e.printStackTrace();
00249 }
00250 }
00251 }