plannerRepair.java
Go to the documentation of this file.
00001 /*
00002 * Copyright (c).2012. OWNER: Institute for Software Technology TU-Graz Austria.
00003 * Authors: Safdar Zaman, Gerald Steinbauer. (szaman@ist.tugraz.at, steinbauer@ist.tugraz.at)
00004 * All rights reserved.
00005 * Redistribution and use in source and binary forms, with or without
00006 * modification, are permitted provided that the following conditions are met:
00007 * 1. Redistributions of source code must retain the above copyright notice,
00008 * this list of conditions and the following disclaimer.
00009 * 2. Redistributions in binary form must reproduce the above copyright notice,
00010 * this list of conditions and the following disclaimer in the documentation 
00011 * and/or other materials provided with the distribution.
00012 * 3. Neither the name of the <ORGANIZATION> nor the names of its contributors
00013 * may be used to endorse or promote products derived from this software without
00014 * specific prior written permission.
00015 *
00016 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00017 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
00018 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00019 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
00020 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSE-
00021 * QUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
00022 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
00023 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00024 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
00025 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
00026 * DAMAGE.
00027 */
00028 
00029 import java.util.*;
00030 import java.io.*;
00031 import java.util.concurrent.locks.Condition;
00032 import java.util.concurrent.locks.ReentrantLock;
00033 
00034 import java.util.Properties;
00035 import pddl4j.ErrorManager;
00036 import pddl4j.PDDLObject;
00037 import pddl4j.ErrorManager.Message;
00038 import pddl4j.Parser;
00039 import pddl4j.exp.term.Term;
00040 import pddl4j.exp.AtomicFormula;
00041 
00042 import org.apache.commons.logging.Log;
00043 import com.google.common.base.Preconditions;
00044 import org.ros.node.Node;
00045 import org.ros.node.NodeMain;
00046 import org.ros.node.NodeConfiguration;
00047 import org.ros.node.parameter.ParameterTree;
00048 import org.ros.namespace.GraphName;
00049 import org.ros.node.topic.Publisher;
00050 import org.ros.node.topic.Subscriber;
00051 import org.ros.internal.loader.CommandLineLoader;
00052 import org.ros.namespace.GraphName;
00053 
00054 
00055 import org.ros.node.AbstractNodeMain;
00056 import org.ros.node.ConnectedNode;
00057 import org.ros.message.MessageListener;
00058 /*
00059 import org.ros.message.MessageListener;
00060 import org.ros.message.diagnosis_msgs.Diagnosis;
00061 import org.ros.message.diagnosis_msgs.DiagnosisResults;
00062 import org.ros.message.diagnosis_msgs.Observations;
00063 
00064 import org.ros.message.diagnosis_msgs.DiagnosisRepairGoal;
00065 
00066 import org.ros.actionlib.client.SimpleActionClient;
00067 import org.ros.actionlib.ActionSpec;
00068 import org.ros.actionlib.client.SimpleActionClientCallbacks;
00069 import org.ros.actionlib.state.SimpleClientGoalState;
00070 
00071 
00072 import org.ros.message.diagnosis_msgs.DiagnosisRepairAction;
00073 import org.ros.message.diagnosis_msgs.DiagnosisRepairActionFeedback;
00074 import org.ros.message.diagnosis_msgs.DiagnosisRepairActionGoal;
00075 import org.ros.message.diagnosis_msgs.DiagnosisRepairActionResult;
00076 import org.ros.message.diagnosis_msgs.DiagnosisRepairFeedback;
00077 import org.ros.message.diagnosis_msgs.DiagnosisRepairGoal;
00078 import org.ros.message.diagnosis_msgs.DiagnosisRepairResult;
00079 
00080 
00081 import org.ros.actionlib.client.ActionClient;
00082 */
00083 import org.ros.exception.RosException;
00084 //import org.ros.node.DefaultNodeRunner;
00085 import java.util.concurrent.TimeUnit;
00086 import org.ros.time.WallTimeProvider;
00087 
00088 import pddl4j.exp.action.Action;
00089 import pddl4j.exp.action.ActionDef;
00090 import pddl4j.exp.action.ActionID;
00091 
00092 
00093 import java.util.HashMap;
00094 import java.util.Iterator;
00095 import java.util.Map;
00096 import java.util.Set;
00097 import java.util.List;
00098 
00104 public class plannerRepair implements NodeMain{
00105     
00106     private String[] excluded_nodes;
00107     
00111     private Parser _parser;
00112 
00116     private Properties _options;
00117 
00121     private PDDLObject _domain;
00122 
00126                 private ConnectedNode _node;
00127 
00131     private ArrayList<String> obs_list = new ArrayList<String>();
00132     
00136     private Map<String,SimpleActionClient> mp;
00137 
00141     private DiagnosisRepairActionNodeSimpleClient sac;
00142 
00146     private DiagnosisRepairActionNodeSpec spec;
00147 
00151     private WallTimeProvider t;
00152 
00156                 private Log log;
00157 
00161     private File domain_file;
00162                 private String domain_file_name;
00163 
00167     private Object threadSync = new Object();
00168 
00172     protected ReentrantLock lock = new ReentrantLock(true);
00173 
00177     protected Condition c = lock.newCondition(); 
00178 
00182     private static boolean executing_plan, goal_processed;
00183 
00187     public plannerRepair(){
00188      executing_plan = false;
00189      goal_processed = false;
00190      mp = new HashMap<String,SimpleActionClient>();
00191      t = new WallTimeProvider();
00192      try{
00193          spec = new DiagnosisRepairActionNodeSpec();
00194      }catch(RosException e){}
00195     }
00196       
00204     @Override
00205   public GraphName getDefaultNodeName() {
00206     return GraphName.of("diagnosis_engine/diagnosis_engine");
00207   }
00208 
00209   @Override
00210   public void onShutdownComplete(Node node) {
00211   }
00212 
00213   @Override
00214   public void onError(Node node, Throwable throwable) {
00215   }
00216 
00217     @Override
00218     public void onShutdown(Node node) {
00219      node.shutdown();
00220      node = null;
00221     }
00222 
00228     @Override
00229     public void onStart(ConnectedNode node){
00230          ParameterTree prm = node.newParameterTree();
00231          //NodeConfiguration nodeConfiguration = node.nodeConfiguration.getNodeName();
00232          domain_file_name = prm.getString("file","repair_domain.pddl");
00233          String param_str = prm.getString("excluded_nodes","node");
00234          excluded_nodes = param_str.split(",");
00235          //System.out.println("param1="+excluded_nodes+"\n"+domain_file_name);
00236          //System.out.println(node.getName());
00237          _node = node;
00238          main_runner();
00239 
00240         
00241     }
00242 
00249     public void main_runner() {
00250         log = _node.getLog();
00251         _options = Graphplan.getParserOptions();
00252         _parser = new Parser(_options);
00253       try{
00254             domain_file = new File(domain_file_name);
00255             if (!domain_file.exists()) {
00256                                                 System.out.println("domain file does not exist");
00257                                                 System.exit(0);
00258             }
00259                    _domain = _parser.parse(domain_file);
00260                                          
00261       }catch(FileNotFoundException e){
00262                                   System.err.println(e.getMessage());
00263                                         e.printStackTrace(System.err);
00264                                                         }
00265                                                                 
00266         connectActionServers();
00267 
00272         Subscriber<diagnosis_msgs.Diagnosis> subscriber = _node.newSubscriber("/diagnosis", diagnosis_msgs.Diagnosis._TYPE);
00273         subscriber.addMessageListener(new MessageListener<diagnosis_msgs.Diagnosis>(){
00274               @Override
00275               public void onNewMessage(diagnosis_msgs.Diagnosis diag_msg) {
00276 
00277                               diagnosis_msgs.DiagnosisResults diag_r; // =  new org.ros.message.diagnosis_msgs.DiagnosisResults();
00278                               List<diagnosis_msgs.DiagnosisResults> diag;// = new ArrayList<org.ros.message.diagnosis_msgs.DiagnosisResults>();
00279                           diag = diag_msg.getDiag();
00280                           diag_r = diag.get(0);
00281                         List<String> good = diag_r.getGood();
00282                         List<String> bad =  diag_r.getBad();
00283                         for(int i=0;i<excluded_nodes.length;i++)
00284                         if(bad.contains(excluded_nodes[i]))
00285                         {
00286                          bad.remove(excluded_nodes[i]);
00287                          System.out.println(excluded_nodes[i]+" excluded.");}
00288                                                                                         
00289                                                                         if(bad.size()>0 && !executing_plan){
00290                                                                                  executing_plan = true;
00291                                                                                  make_probPDDL_file(good,bad);
00292                          get_plan();
00293                   }
00294              }
00295                         }); //newSubscriber
00296 
00300          Subscriber<diagnosis_msgs.Observations> sub_Obs = _node.newSubscriber("/observations", diagnosis_msgs.Observations._TYPE);
00301           sub_Obs.addMessageListener(new MessageListener<diagnosis_msgs.Observations>(){
00302             @Override
00303             public void onNewMessage(diagnosis_msgs.Observations msg) {
00304               try{
00305               List<String> obs_msg = msg.getObs();
00306                 synchronized (threadSync){
00307                 Iterator it = obs_msg.iterator();
00308                 while(it.hasNext()) {
00309                 //for(int m=0; m<obs_msg.length; m++) {
00310                    String s = (String) it.next();
00311                                                                          if(!obs_list.contains(s)) {
00312                       String ns = "@";  
00313                                 if(s.charAt(0)=='~')
00314                                 ns = s.substring(1);
00315                                 else
00316                                 ns = "~" + s;
00317                                                                                         int k = obs_list.indexOf(ns);
00318                                                 if(k!=-1)
00319                                                  obs_list.set(k,s);
00320                       else
00321                                                                                                  obs_list.add(s);
00322                    } //if
00323                  } // while
00324                                                         }// synchronized
00325                                         }catch(Exception e){
00326               System.out.println("Error while updating the observation list.");
00327            }    
00328                         } // On New Mssage
00329                 }); // Subscriber
00330         
00331     }//main_runner
00332 
00333 
00334 
00340      public void connectActionServers(){
00341                          try{
00342             Iterator<ActionDef> i = _domain.actionsIterator();
00343                         while (i.hasNext()) {
00344                         ActionDef a = i.next();
00345                         Action op = (Action) a;
00346                                                                 //System.out.println(op.getName().toString());
00347                 sac = spec.buildSimpleActionClient(op.getName().toString());
00348                                                                 sac.addClientPubSub(_node);
00349                                                                 //mp.put(op.getName().toString(),sac);
00350                         }
00351             System.out.println("Planner is waiting for Action Server to start......!");
00352                         sac.waitForServer();
00353                         System.out.println("Connected with Server and Planner is Up....");
00354        }catch(Exception e){}
00355      }
00356 
00362      public void make_probPDDL_file(List<String> good, List<String> bad) {
00363                                          synchronized (threadSync){
00364                                                          ArrayList<String> list = new ArrayList<String>();
00365                                                          lock.lock();
00366                                                          c.signalAll();
00367                                                          list = obs_list;
00368                lock.unlock();
00369                                                          String prob_text = "define (problem repair_goal)(:domain repair_domain)(:requirements :strips :equality :typing :negative-preconditions)(:objects ";
00370                                                          String co_problem="";
00371                                                    String goal = "(:goal (and ";
00372                                                    String init="(:init ";
00373                                                          for(int i=0;i<list.size();i++) {
00374                                 String parameter = list.get(i).substring(list.get(i).indexOf("(")+1,list.get(i).indexOf(")"));
00375                                                                                         parameter = parameter.replace(",","_");
00376                                 co_problem = co_problem + parameter + " ";
00377                                 if(list.get(i).charAt(0)=='~') {
00378                                 String predicate = list.get(i).substring(1,list.get(i).indexOf("("));
00379                           //if(!predicate.equals("ok"))
00380                                                                                                           init = init + "(not_"+predicate+" "+parameter+")";
00381                                 } else {
00382                                 String predicate = list.get(i).substring(0,list.get(i).indexOf("("));
00383                           //if(!predicate.equals("ok"))
00384                             init = init + "("+predicate+" "+parameter+")";               
00385                                 }               
00386                                                          }
00387                                                          Iterator good_it=good.iterator();
00388                                                          while(good_it.hasNext()){
00389                                                                                         String good_str=(String)good_it.next();
00390                                         init = init + "(good "+good_str+")";
00391                                         goal=goal+"(good "+good_str+")";
00392                       //co_problem = co_problem + good[i] + " ";
00393                }
00394                                                          Iterator bad_it=bad.iterator();
00395                  while(bad_it.hasNext()){
00396                       String bad_str=(String)bad_it.next();
00397                                         init = init + "(bad "+bad_str+")";
00398                                 goal=goal+"(good "+bad_str+")";
00399                       //co_problem = co_problem + bad[i] + " ";
00400                }
00401                co_problem = co_problem + ")";
00402                init = init + ")";
00403                goal=goal+"))";
00404                String prob = "(" + prob_text + co_problem + init + goal + ")";
00405                                                          System.out.println(prob);
00406                                                    try{
00407                              BufferedWriter out=new BufferedWriter(new FileWriter("repair_goal.pddl"));
00408                              out.write(prob);
00409                              out.close();
00410                }catch(IOException e){}
00411                                  }//synchronized
00412      } //make_probPDDL_file
00413 
00414 
00419      public void get_plan(){
00420            try{  
00421                                                                         log.info("Planner called.");
00422                                                                         PDDLObject problem = _parser.parse(new File("repair_goal.pddl"));
00423                                                                         PDDLObject pb = null;
00424                                 if (_domain != null && problem != null){
00425                     pb = _parser.link(_domain, problem);
00426                         }
00427                         ErrorManager mgr = _parser.getErrorManager();
00428                         if (mgr.contains(Message.ERROR))
00429                     mgr.print(Message.ALL);
00430                         else {
00431                                 mgr.print(Message.WARNING);
00432                                 Graphplan gplan = new Graphplan(pb);
00433                                 gplan.preprocessing();
00434                                                                                                         Plan plan = gplan.solve();
00435                                                                                                   if (plan != Plan.FAILURE) {
00436                                         String actionServer=null;
00437                                                                                                                         String param = null;
00438                                                                                                                         for (Set<AtomicFormula> layer : plan) {
00439                                                                                                                                         for (AtomicFormula action : layer) {
00440                                                                                                                                                         actionServer = action.getPredicate();
00441                                                                                                                                                         ArrayList<String> params = new ArrayList<String>();
00442                                                                                                                                                         for (Term parameter : action) 
00443                                                                 params.add(parameter.getImage());
00444                                                                                                                                                         goal_processed = false;
00445                                       while(!goal_processed){
00446                                           log.info("Repair called: "+actionServer+"("+params.get(0).toString()+")");
00447                                                             execute_plan(actionServer, params);
00448                                                                                                                                                         }
00449                                                                                                                                         }
00450                                                                                                                         }
00451                                                                                                                         
00452                                                                                                                         log.info("Planner finished.");
00453                                                                                                                         Thread.currentThread().sleep(3000);
00454                                                                                                                         plan.actions.clear();
00455                                                                                                                         executing_plan = false;
00456                                                                                                                         plan = null;
00457                                         }else
00458                                         log.info("\nno solution plan found\n");
00459                                                                                 }//else
00460             }catch(Throwable t){
00461                                                                         System.err.println(t.getMessage());
00462                                         t.printStackTrace(System.err);
00463                                   executing_plan = false;
00464                                                         }
00465    } //get_plan
00466 
00467 
00474         public void execute_plan(String actionServer, ArrayList<String> params){
00475        try{ 
00476             sac = spec.buildSimpleActionClient(actionServer);
00477                                                 sac.addClientPubSub(_node);
00478                 diagnosis_msgs.DiagnosisRepairGoal repairGoal; //= spec.createGoalMessage();
00479                 repairGoal.setParameter(params);
00480             
00481                 sac.sendGoal(repairGoal);
00482                 SimpleClientGoalState state = sac.getState();
00483           
00484                   boolean finished_before_timeout = sac.waitForResult(10, TimeUnit.SECONDS);
00485                                                 if (finished_before_timeout) {
00486               diagnosis_msgs.DiagnosisRepairResult res = (diagnosis_msgs.DiagnosisRepairResult) sac.getResult();
00487               state = sac.getState();
00488               log.info("Repair finished with state "+state.toString()+".");
00489               goal_processed = true;
00490                                                 }else{
00491                   log.info("Repair Action did not finish before the time out"); 
00492                                                                         goal_processed = false;         
00493                                         }
00494             
00495         }catch(Throwable t){
00496                                   System.err.println(t.getMessage());
00497                                         t.printStackTrace(System.err);
00498                                                                         goal_processed = true;
00499          }
00500   }// execute_plan
00501 
00502 }//class


tug_ist_diagnosis_repair
Author(s): Safdar Zaman
autogenerated on Mon Jan 6 2014 11:51:12