logicmoo_hyhtn

% Provides a prolog database env % % % % Logicmoo Project PrologMUD: A MUD server written in Prolog % Maintainer: Douglas Miles % Denton, TX 2005, 2010, 2014 % Dec 13, 2035 % */

   12:-module(logicmoo_hyhtn_works,[]).   13
   14:-multifile(user:push_env_ctx/0).   15:-dynamic(user:push_env_ctx/0).   16
   17/* ***********************************/
   18/* Douglas Miles 2005, 2010, 2014 */
   19/* Denton, TX */
   20/* ***********************************/
   21
   22:- style_check(-singleton).   23
   24:- use_module(library(prolog_pack)).   25:- if( \+ prolog_pack:current_pack(planner_api)).   26:- dynamic   user:file_search_path/2.   27:- multifile user:file_search_path/2.   28:- prolog_load_context(directory,Dir),
   29   DirFor = planner,
   30   (( \+ user:file_search_path(DirFor,Dir)) ->asserta(user:file_search_path(DirFor,Dir));true),
   31   absolute_file_name('../..',Y,[relative_to(Dir),file_type(directory)]),
   32   (( \+ user:file_search_path(pack,Y)) ->asserta(user:file_search_path(pack,Y));true).   33:- attach_packs.   34:- initialization(attach_packs).   35:- endif.   36
   37
   38:- if( \+  user:file_search_path(pddl,_) ).   39:- prolog_load_context(directory,Dir),
   40   must((absolute_file_name('../pddl',Y,[relative_to(Dir),file_type(directory)]),
   41   asserta(user:file_search_path(pddl,Y)))).   42:- endif.   43
   44% [Required] Load the Logicmoo Library Utils
   45:- ensure_loaded(library(logicmoo_utils)).   46
   47:- kb_shared(baseKB:mpred_prop/3).   48
   49:- ensure_loaded(library(logicmoo_util_structs)).   50:- ensure_loaded(library(logicmoo_util_bb_env)).   51:- prolog_load_context(file,File),ain(user:env_source_file(File)).   52
   53:-op(500,fx,env_call).   54/*
   55 * GIPO COPYRIGHT NOTICE, LICENSE AND DISCLAIMER.
   56 *
   57 * Copyright 2001 - 2003 by R.M.Simpson W.Zhao T.L.McCLuskey D Liu D. Kitchin
   58 *
   59 * Permission to use, copy, modify, and distribute this software and its
   60 * documentation for any purpose and without fee is hereby granted,
   61 * provided that the above copyright notice appear in all copies and that
   62 * both the copyright notice and this permission notice and warranty
   63 * disclaimer appear in supporting documentation, and that the names of
   64 * the authors or their employers not be used in advertising or publicity 
   65 * pertaining to distribution of the software without specific, written 
   66 * prior permission.
   67 *
   68 * The authors and their employers disclaim all warranties with regard to 
   69 * this software, including all implied warranties of merchantability and 
   70 * fitness.  In no event shall the authors or their employers be liable 
   71 * for any special, indirect or consequential damages or any damages 
   72 * whatsoever resulting from loss of use, data or profits, whether in an 
   73 * action of contract, negligence or other tortious action, arising out of 
   74 * or in connection with the use or performance of this software.
   75 */
   76 /* gipohyhtn.pl */
   77/* HyHTN planning: do preprocess first  */
   78/* make all method and operators primitive */
   79:-use_module(library(system)).   80/*********************** initialisation**************/
   81:- dynamic op_num/1, my_stats/1. 
   82:- dynamic node/7,final_node/1.   83:- dynamic methodC/7, opParent/6,operatorC/5,gOperator/3.   84:- dynamic tp_goal/3,tp_node/6,closed_node/6,solved_node/5.   85:- dynamic goal_related/4.   86:- dynamic tn/6. % Used to store full expanded steps
   87:- dynamic opCounter/1, temp/1. % Used for grounding operators
   88:- dynamic objectsC/2,atomic_invariantsC/1.% Used only dynamic objects
   89:- dynamic objectsOfSort/2.      % Used to store all objects of a sort
   90% for boot..
   91:- dynamic kill_file/1,solution_file/1.   92%
   93%:- prolog_flag(single_var_warnings, _, off).
   94%:-set_prolog_flag(unknown,fail).
   95%:- unknown(error,fail).
   96:- op(100,xfy,'=>').   97%---------------------structure--------------------
   98% for whole search:
   99% node(Nodeid, Precond, Decomps, Temp, Statics)
  100% tn(Tnid, Name, Precond, Postcond,Temp, Decomps)
  101% tn is a full expanded node, it has fixed decomps and postcondtion
  102% step(HPid,ActName,Precond,Postcond,Expansion)
  103% for fwsearch achieve(Goal) only:
  104% tp_goal(Pre,Goal,Statics)
  105% goal_related(se(Sort,Obj,SEpre),Opls,LengthToGoal)
  106% tp_node(TPid,Pre,Statics,from(Parentid),Score,Steps)
  107% closed_node(TPid,Pre,from(Parentid),Score,Steps)
  108%---------------------structure end--------------------
  109
  110op_num(0).
  111my_stats(0).
  112
  113startOCL(Goal,Init):-
  114   dmsg('startOCL-PLANNER-TASK'(Goal)),
  115	planner_interface(Goal,Init,Sol,_,TNLst),
  116	solution_file(F),
  117	tell(F),
  118	write('TASK '),write(Id),nl,
  119	write('SOLUTION'),nl,
  120	display_sol(Sol),
  121	write('END FILE'),nl,nl,
  122	reverse(TNLst,TNForward),
  123	display_details(TNForward),
  124	write('END PLANNER RESULT'),
  125	told,(clean).
  126
  127solve(Id) :-
  128	htn_task(Id,Goal,Init),
  129	planner_interface(Goal,Init,Sol,_,TNLst),
  130	solution_file(F),
  131	tell(F),
  132	write('TASK '),write(Id),nl,
  133	write('SOLUTION'),nl,
  134	display_sol(Sol),
  135	write('END FILE'),nl,nl,
  136	reverse(TNLst,TNForward),
  137	display_details(TNForward),
  138	write('END PLANNER RESULT'),
  139	told,
  140	clean.
  141
  142solve(Id) :-
  143	planner_task(Id,Goal,Init),
  144	planner_interface(Goal,Init,Sol,_,TNLst),
  145	solution_file(F),
  146	tell(F),
  147	write('TASK '),write(Id),nl,
  148	write('SOLUTION'),nl,
  149	display_sol(Sol),
  150	write('END FILE'),nl,nl,
  151	reverse(TNLst,TNForward),
  152	display_details(TNForward),
  153	write('END PLANNER RESULT'),
  154	told,
  155	clean.
  156
  157display_sol([]).
  158display_sol([H|T]) :-
  159	write(H),
  160	nl,
  161	display_sol(T).
  162
  163display_details([]).
  164display_details([tn(TN,Name,Pre,Post,Temp,Dec)|Rest]) :-
  165%    write('method::Description:'),write(';'),
  166    nl,write('BEGIN METHOD'),nl,write(TN),write(';'),
  167    nl,write('Name:'),write(Name),write(';'),
  168    nl,write('Pre-condition:'),write(Pre),write(';'),
  169%    write('Index Transitions:'),write(Pre),write('=>'),write(Post1),write(';'),
  170%    write('Static:'),write(';'),
  171    nl,write('Temporal Constraints:'),write(Temp),write(';'),
  172    nl,write('Decomposition:'),write(Dec),write(';'),
  173    nl,
  174    display_details(Rest).
  175
  176
  177clean:-
  178	retractall(op_num(_)),
  179	retractall(my_stats(_)),
  180	retractall(current_num(_,_)),
  181	retractall(node(_,_,_,_,_)),
  182	retractall(final_node(_)),
  183	retractall(tn(_,_,_,_,_,_)),
  184	retractall(methodC(_,_,_,_,_,_,_)),
  185	retractall(operatorC(_,_,_,_,_)),
  186	retractall(gOperator(_,_,_)),
  187	retractall(goal_related(_,_,_)),
  188	retractall(goal_related_search(_)),
  189	retractall(opCounter(_)),
  190	retractall(opParent(_,_,_,_,_,_)),
  191	retractall(temp(_)),
  192	retractall(objectsOfSort(_,_)),
  193	retractall(related_op(_)),
  194	retractall(op_score(_,_)),
  195	retractall(objectsC(_,_)),
  196	retractall(solved_node(_,_)),
  197	retractall(tp_node(_,_,_,_,_,_)),
  198	retractall(closed_node(_,_,_,_,_,_)),
  199	retractall(score_list(_)),
  200	retractall(atomic_invariantsC(_)),
  201	retractall(gsubstate_classes(_,_,_)),
  202	retractall(is_of_sort(_,_)),
  203	retractall(is_of_primitive_sort(_,_)),
  204	retractall(objectsD(_,_)),
  205	assert(op_num(0)),
  206	assert(my_stats(0)).
  207
  208planner_interface(G,I, SOLN,OPNUM,TNList):-
  209	change_obj_list(I),
  210	ground_op,
  211	assert_is_of_sort,
  212	change_op_representation,
  213	prim_substate_class,
  214        retract(op_num(_)),
  215        assert(op_num(0)),
  216        statistics(runtime,[_,Time]),
  217        (retract(my_stats(_)) ; true),
  218        assert(my_stats(Time)),
  219        make_problem_into_node(I, G, Node),
  220        assert(Node),
  221	start_solve(SOLN,OPNUM,TNList).
  222planner_interface(G,I, SOLN,OPNUM,TNList):-
  223	tell(user),nl,write('failure in initial node'),!.
  224
  225/******************** Nodes *******************/
  226% node(Name, Precond ,Decomps, Temp, Statics)
  227% Initial Node: node(root, Init, Decomps, Temp, Statics)
  228
  229getN_name(node(Name, _, _, _,_),  Name).
  230getN_pre(node(_,Pre, _, _, _),  Pre).
  231getN_decomp(node(_, _, Decomp,_,_),  Decomp).
  232getH_temp(node(_, _, _,Temps, _),  Temps).
  233getN_statics(node(_,_,_,_,Statics),  Statics).
  234
  235%Ron  21/9/01 - Try to give a closedown method
  236start_solve(SOLN,OPNUM,_):-
  237	kill_file(Kill),
  238	file_exists(Kill).
  239%	write('Found kill file'),nl.
  240
  241start_solve(Sol,OPNUM,TNList):-
  242   retract(final_node(Node)),
  243   retractall(current_num(_,_)),
  244   getN_statics(Node,Statics),
  245   statics_consist(Statics),
  246   extract_solution(Node,Sol,SIZE,TNList),
  247   statistics(runtime,[_,CP]),
  248   TIM is CP/1000, tell(user),
  249   retract(op_num(OPNUM)),
  250   assert(op_num(0)),
  251   nl, nl, write('CPU Time = '),write(CP),nl,
  252   write('TIME TAKEN = '),write(TIM),
  253   write(' SECONDS'),nl,
  254   write('Solution SIZE = '),write(SIZE),nl,
  255   write('Operator Used = '),write(OPNUM),nl,
  256   write('***************************************'),
  257   assert(time_taken(CP)),  
  258   assert(soln_size(SIZE)),
  259   retractall(tn(_,_,_,_,_,_)),
  260   !.
  261start_solve(Sol,OPNUM,TNList):-
  262   select_node(Node),
  263%   nl,write('processing '),write(Node),nl,
  264            % expand/prove its hps
  265   process_node(Node),
  266   start_solve(Sol,OPNUM,TNList).
  267start_solve(Sol,OPNUM,TNList):-
  268    tell(user), write('+++ task FAILED +++'),
  269    clean.
  270
  271:- discontiguous expand_decomp/8.  272:- discontiguous expand_node1/8.  273
  274/******************************** MAIN LOOP **********/
  275
  276% expand a node..
  277process_node(Node) :-
  278   getN_name(Node,  Name),
  279   getN_pre(Node, Pre),
  280   getN_decomp(Node, Dec),
  281   getH_temp(Node, Temps),
  282   getN_statics(Node, Statics),
  283   expand_decomp(Dec,Pre,Post,Temps,Temp1,Statics,Statics1,Dec1),
  284   statics_consist(Statics),
  285   assert_node(Name,Pre,Dec1,Temp1,Statics1).
  286
  287assert_node(Name,Pre,Decomp,Temp,Statics):-
  288   all_HP_expanded(Decomp),
  289   assert(final_node(node(Name,Pre,Decomp,Temp,Statics))),!.
  290assert_node(Name,Pre,Dec,Temp,Statics):-
  291   gensym(root,SYM),
  292   assert(node(SYM,Pre,Dec,Temp,Statics)),!.
  293
  294all_HP_expanded([]):-!.
  295all_HP_expanded([step(HPid,Name,_,_,exp(TN))|THPS]):-
  296   all_HP_expanded(THPS),!.
  297
  298/************ expand every step in Dec *********************/
  299% expand_decomp(Dec,Pre,Post,Temps,Temp1,Statics,Statics1,Dec1)
  300% Pre and Post here is the current ground states changes
  301% starts from Initial states to final ground states
  302% 0. end, Post is the final ground states
  303expand_decomp([],Post,Post,Temp,Temp,Statics,Statics,[]):-!.
  304
  305% 1. if the step has expand already, get the state change, go to next
  306expand_decomp([step(HPid,Name,Pre0,Post0,exp(TN))|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,[step(HPid,Name,Pre,State,exp(TN))|Decomp1]):-
  307   state_achieved(Pre0,Pre),
  308   state_change(Pre,Pre0,Post0,State),
  309   statics_consist(Statics),
  310   expand_decomp(Decomp,State,Post,Temp,Temp1,Statics,Statics1,Decomp1),!.
  311
  312% 2. if it is an achieve goal
  313expand_decomp([step(HPid,ACH,Pre0,Post0,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,Decomp1):-
  314   ACH=..[achieve|_],
  315   statics_consist(Statics),
  316   expand_decomp_ach([step(HPid,ACH,Pre,Post0,unexp)|Decomp],Pre,Post,
  317        Temp,Temp1,Statics,Statics1,Decomp1),!.
  318
  319% 3. if HP's name and it's Pre meet an operator, return operator's name
  320expand_decomp([step(HPid,Name,undefd,undefd,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,[step(HPid,Name,Pre,State,exp(Name))|Decomp1]):-
  321   apply_op(Name,HPid,Name,Pre,undefd,State,Statics,Statics2),
  322   expand_decomp(Decomp,State,Post,Temp,Temp1,Statics2,Statics1,Decomp1),!.
  323
  324% apply operator by known its name and post state
  325apply_op(Name,HPid,Name,Pre,Post,State,Statics,Statics1):-
  326   operatorC(Name,Pre0,Post0,Cond,Statics0),
  327   statics_append(Statics0,Statics,Statics2),
  328   state_achieved(Pre,Pre0,Statics2),
  329   state_change(Pre,Pre0,Post0,State2),
  330   cond_state_change(State2,Cond,State),
  331   all_achieved(Post,Statics2,State),
  332   remove_unneed(Statics2,[],Statics1),
  333   statics_consist_instance(Statics1),
  334   statics_consist_instance(Statics0),
  335   retract(op_num(N)),
  336   N1 is N+1,
  337   assert(op_num(N1)),!.
  338
  339% 4. if HP's name meet an method, and it's precondition  achieved
  340% expand it and make it to that TNs
  341expand_decomp([step(HPid,Name,undefd,undefd,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,[step(HPid,Name,Pre,State,exp(TN))|Decomp1]):-
  342   apply_method(TN,HPid,Name,Pre,undefd,State,Statics,Statics2),
  343   expand_decomp(Decomp,State,Post,Temp,Temp1,Statics2,Statics1,Decomp1),!.
  344
  345% apply an method by its name
  346apply_method(TN,HPid,Name,Pre,Post,State,Statics,Statics1):-
  347   methodC(Name,Pre0,Post0,Statics0,Temp0,achieve(ACH0),Dec0),
  348   statics_append(Statics0,Statics,Statics2),
  349   all_achieved(Pre0,Statics2,Pre),
  350   remove_unneed(Statics2,[],Statics21),
  351   make_dec1(HPid,Pre,ACH0,Statics21,Temp0,Dec0,Temp2,Dec2),
  352   expand_decomp(Dec2,Pre,State,Temp2,Temp1,Statics21,Statics1,Dec1),
  353   all_achieved(Post,Statics1,State),
  354   retract(op_num(N)),
  355   N1 is N+1,
  356   assert(op_num(N1)),
  357   make_tn(TN,Name,Pre,State,Temp1,Dec1),!.
  358
  359% 5. get another step which matchs and not after it before it to give a try
  360expand_decomp([step(HP,N,Pre0,Post0,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,Decomp1):-  
  361   get_another_step(step(HP2,N2,Pre2,Post2,Exp),Pre,Statics,
  362                                  HP,Temp,Temp2,Decomp,Decomp2),
  363   expand_decomp([step(HP2,N2,Pre2,Post2,Exp),step(HP,N,Pre0,Post0,unexp)|Decomp2],
  364                     Pre,Post,Temp2,Temp1,Statics,Statics1,Decomp1).
  365
  366% 6. all failed, expanding failed 
  367/************ end of expand_decomp *********************/
  368
  369% get another step which is not after it before it
  370get_another_step(A,Pre,Statics,HP,Temp,Temp1,[],Dec2):-fail.
  371get_another_step(step(HP2,Name2,Pre2,Post2,Exp),Pre,Statics,HP,Temp,[before(HP2,HP)|Temp],Dec,Dec2):-
  372   member(step(HP2,Name2,Pre2,Post2,Exp),Dec),
  373   not(necessarily_before(HP,HP2, Temp)),
  374   state_achieved(Pre2,Pre,Statics),
  375   list_take(Dec,[step(HP2,Name2,Pre2,Post2,Exp)],Dec2).
  376
  377% ***********expand the achieve goal***********
  378% 1.if the ACH is achieved already
  379%   remove it from decomposion and do the next
  380expand_decomp_ach([step(HPid,ACH,Pre,Post0,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,Decomp1):-
  381   state_achieved(Post0,Pre),
  382%   nl,write('step '),write(HPid),
  383%   write('is already achieved'),nl,
  384   remove_temp(Temp,HPid,Temp,Temp2),
  385   expand_decomp(Decomp,Pre,Post,Temp2,Temp1,Statics,Statics1,Decomp1),!.
  386
  387% 2.do expanding achieve goal
  388expand_decomp_ach([step(HPid,ACH,Pre,Post0,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,[step(HPid,ACH,Pre,Post0,exp(TN))|Decomp1]):-
  389   expand_ach_goal(HPid,TN,ACH,Pre,Post0,State,Statics,Statics2),
  390   expand_decomp(Decomp,State,Post,Temp,Temp1,Statics2,Statics1,Decomp1),!.
  391
  392% 3. get another step which matchs and not after it before it to give a try
  393expand_decomp_ach([step(HPid,ACH,Pre,Post0,unexp)|Decomp],Pre,Post,Temp,Temp1,Statics,Statics1,[step(HPid,ACH,Pre,Post0,exp(TN))|Decomp1]):-  
  394   get_another_step(step(HP2,N2,Pre2,Post2,Exp),Pre,Statics,
  395                                  HP,Temp,Temp2,Decomp,Decomp2),
  396   expand_decomp([step(HP2,N2,Pre2,Post2,Exp),step(HPid,ACH,Pre,Post0,unexp)|Decomp2], Pre,Post,Temp2,Temp1,Statics,Statics1,Decomp1).
  397
  398% 4. all failed, expanding failed 
  399/************ end of expand_decomp_ach *********************/
  400       
  401%************ expand an achive goal *********************/
  402% 1. directly achieve goal's Pre and Post by operator,method or tn
  403expand_ach_goal(HPid,TN,ACH,Pre,Post,State,Statics,Statics1):-
  404   direct_expand_ach_goal(HPid,TN,ACH,Pre,Post,State,Statics,Statics1),!.
  405
  406% 2. else, nothing directly can achieve HP's Pre and Post
  407% assert a temporely node for forward search
  408% tp_node(TPid,Pre,Statics,from(Parentid),Score,Steps)
  409expand_ach_goal(HPid,TN,ACH,Pre,Post,State,Statics,Statics1):-
  410   make_tpnodes(Pre,Post,Statics),
  411%   tell(fred),
  412   fwsearch(TN,State),
  413%   told,
  414%   all_achieved(Post,Statics1,State),
  415   clean_temp_nodes.
  416
  417% 3. else, fail expand
  418/************ end of expand_ach_goal *********************/
  419
  420% -------direct expand an achieve goal-----------------------
  421%1. if an achieve action meets an TN Pre and post
  422direct_expand_ach_goal(HPid,TN,ACH,Pre,Post,State,Statics,Statics):-
  423   apply_tn(TN,HPid,ACH,Pre,Post,State,Statics,Statics).
  424%2. if an action's action meets an operator Pre and post
  425direct_expand_ach_goal(HPid,OP,ACH,Pre,Post,State,Statics,Statics1):-
  426   dir_apply_op(OP,HPid,ACH,Pre,Post,State,Statics,Statics1).
  427%3. if an achieve action meets a method's pre and post,
  428%    expand it and make it to that TNs
  429direct_expand_ach_goal(HPid,TN,ACH,Pre,Post,State,Statics,Statics1):-
  430   dir_apply_method(TN,HPid,ACH,Pre,Post,State,Statics,Statics1),!.
  431%4. else, failed for direct expand an achieve goal------
  432
  433% apply an TN to an achieve goal that matches both pre and post conditions
  434apply_tn(Tn0,HPid,ACH,Pre,Post,State,Statics,Statics):-
  435   tn(Tn0,Name,Pre0,Post0,Temp0,Decomp0),
  436   state_achieved(Pre0,Pre),
  437   state_change(Pre,Pre0,Post0,State),
  438   all_achieved(Post,Statics,State),
  439%   nl,write('step '),write(HPid),
  440    retract(op_num(N)),
  441    N1 is N+1,
  442    assert(op_num(N1)),!.
  443%    write('can be expand by tn '),write(Tn0),nl,!.
  444
  445% directly apply an operator when its Pre and Post matches
  446dir_apply_op(Name,HPid,ACH,Pre,Goal,State,Statics,Statics1):-
  447%   ACH=..[achieve|Rest],
  448   make_se_primitive(Goal,Post),
  449   operatorC(Name,Pre0,Post0,Cond,Statics0),
  450   statics_append(Statics0,Statics,Statics2),
  451   state_related(Post0,Cond,Post),
  452%   state_achieved(Pre,Pre0,Statics2),% can't say because not full instatiate
  453   state_change(Pre,Pre0,Post0,State2),
  454   cond_state_change(State2,Cond,State),
  455   all_achieved(Post,Statics2,State),
  456   remove_unneed(Statics2,[],Statics1),
  457   statics_consist(Statics1),
  458%   nl,write('step '),write(HPid),
  459%   write('can be expand by operator '),write(Name),nl,
  460   retract(op_num(N)),
  461   N1 is N+1,
  462   assert(op_num(N1)),!.
  463
  464% apply mehtod when Pre and Post condition matchs
  465dir_apply_method(TN,HPid,ACH,Pre,Goal,State,Statics,Statics1):-
  466%   ACH=..[achieve|Rest],
  467   make_se_primitive(Goal,Post),
  468   methodC(Name,Pre0,Post0,Statics0,Temp0,achieve(ACH0),Dec0),
  469   statics_append(Statics0,Statics,Statics2),
  470   state_related(Post0,Post),
  471%   state_achieved(Pre0,Pre,Statics2),
  472   state_change(Pre,Pre0,Post0,State2),
  473%   rough_state_change(Pre,Pre0,Post0,State2),
  474   may_achieved(Post,Statics2,State2),
  475%   remove_unneed(Statics2,[],Statics21),
  476   make_dec1(HPid,Pre,ACH0,Statics2,Temp0,Dec0,Temp2,Dec2),
  477   expand_decomp(Dec2,Pre,State,Temp2,Temp1,Statics2,Statics1,Dec1),
  478   all_achieved(Post,Statics1,State),
  479%   nl,write('step '),write(HPid),
  480%   write('can be expand by method '),write(Name),nl,
  481   retract(op_num(N)),
  482   N1 is N+1,
  483   assert(op_num(N1)),
  484   make_tn(TN,Name,Pre,State,Temp1,Dec1),!.
  485
  486% make decomposition steps when expand a method
  487make_dec1(HPid,Pre,ACH,Statics,Temp,Dec,Temp1,Dec1):-
  488   var(HPid),
  489   gensym(hp,HPid),
  490   make_dec1(HPid,Pre,ACH,Statics,Temp,Dec,Temp1,Dec1),!.
  491make_dec1(HPid,Pre,ACH,Statics,Temp,Dec,Temp1,Dec1):-
  492   all_achieved(ACH,Statics,Pre),
  493   make_dec01(HPid,1,Dec,Dec1),
  494   change_temp(HPid,Temp,[],Temp1),!.
  495make_dec1(HPid,Pre,ACH,Statics,Temp,Dec,[before(STID0,STID1)|Temp1],[step(STID0,achieve(ACH),Pre,ACH,unexp)|Dec1]):-
  496   gensym_num(HPid,0,STID0),
  497   gensym_num(HPid,1,STID1),
  498   make_dec01(HPid,1,Dec,Dec1),
  499   change_temp(HPid,Temp,[],Temp1),!.
  500
  501make_dec01(HPid,_,[],[]):-!.
  502make_dec01(HPid,Num,[HDec|TDec],[step(STID,HDec,undefd,undefd,unexp)|TDec0]):-
  503   operatorC(HDec,_,_,_,_),
  504   gensym_num(HPid,Num,STID),
  505   Num1 is Num + 1,
  506   make_dec01(HPid,Num1,TDec,TDec0).
  507make_dec01(HPid,Num,[HDec|TDec],[step(STID,HDec,undefd,undefd,unexp)|TDec0]):-
  508   methodC(HDec,_,_,_,_,_,_),
  509   gensym_num(HPid,Num,STID),
  510   Num1 is Num + 1,
  511   make_dec01(HPid,Num1,TDec,TDec0).
  512
  513change_temp(HPid,[],Temp2,Temp2):-!.
  514change_temp(HPid,[before(N1,N2)|Temp],Temp2,[before(ST1,ST2)|Temp0]):-
  515   gensym_num(HPid,N1,ST1),
  516   gensym_num(HPid,N2,ST2),
  517   change_temp(HPid,Temp,Temp2,Temp0),!.
  518% --------------------end of dir_apply_method/8---------------------
  519/************ end of direct_expand_ach_goal *********************/
  520
  521% ----------------forward searching--------------
  522% make tp_node(TPID, Pre,Statics,from(Parent),Score,Steps)
  523make_tpnodes(Pre,Post, Statics):-
  524   opCounter(Num),
  525   Num>=1000,
  526   retractall(tp_goal(_,_,_)),
  527   retractall(related_op(_,_)),
  528   assert(tp_goal(Pre,Post,Statics)),
  529   assert(tp_node(init,Pre,Statics,from(init),0,[])),!.
  530
  531make_tpnodes(Pre,Post, Statics):-
  532   retractall(tp_goal(_,_,_)),
  533   retractall(related_op(_,_)),
  534   assert(tp_goal(Pre,Post,Statics)),
  535   assert_goal_related_init(Pre,Post,Statics),
  536   assert(op_score(goal,0)),
  537   find_all_related_goals(Pre,Statics,1,N),
  538%   find_all_related_op,
  539   assert(tp_node(init,Pre,Statics,from(init),0,[])),!.
  540
  541%tp_node(TP,Pre,Statics,from(Parent),Score,Steps)
  542% forward search for operators can't directly solved
  543fwsearch(TN,State):-
  544   retract(solved_node(_,step(HP,Name,Pre,State,exp(TN)))).
  545fwsearch(TN,State):-
  546   select_tnode(tp_node(TP,Pre,Statics,from(PR),Score,Steps)),
  547   assert(closed_node(TP,Pre,Statics,from(PR),Score,Steps)),
  548   expand_node(TP,OP,Statics,Statics1,Pre,Post,from(PR),Steps,Steps1),
  549   assert_tnode(TP,OP,PR,Score1,Post,Statics1,Steps1),
  550   solved_node(_,_),%expand every possible way until find solution
  551   fwsearch(TN,State).
  552fwsearch(TN,State):-
  553   tp_node(TP,Pre,Statics,from(PR),Score,Steps),
  554   fwsearch(TN,State).
  555
  556clean_temp_nodes:-
  557   retractall(tp_goal(_,_)),
  558   retractall(goal_related(_,_,_)),
  559   retractall(goal_related_search(_)),
  560   retractall(related_op(_)),
  561   retractall(op_score(_,_)),
  562   retractall(score_list(_)),
  563   retractall(solved_node(_,_)),
  564   retractall(current_num(tp,_)),
  565   retractall(tp_node(_,_,_,_,_,_)),
  566   retractall(closed_node(_,_,_,_,_,_)),!.
  567
  568% expand all way possible to achieve the Post
  569% if Post is achieved by Pre, finish
  570expand_node(TP,done,Statics,Statics,Pre,Pre,from(PR),List,List):-
  571   tp_goal(_,Goal,_),
  572   state_achieved(Goal,Pre,Statics),!.
  573expand_node(TP,TN,Statics,Statics1,Pre,State,from(PR),List,List1):-
  574   expand_node1(TN,Statics,Statics1,Pre,State,from(PR),List,List1).
  575
  576% check the Post can be solved by direct expand (Operator or Method)
  577expand_node1(TN,Statics,Statics1,Pre,State,from(PR),List,List1):-
  578   tp_goal(_,Goal,_),
  579   direct_expand(HP,TN,achieve(Goal),Pre,Goal,State,Statics,Statics1),
  580%   gensym(hp,HP),
  581   append_dcut(List,[step(HP,achieve(Goal),Pre,State,exp(TN))],List1),!.
  582% -------direct expand -----------------------
  583% if the goal canbe achieved by a method's pre and post,
  584%    expand it and make it to that TNs
  585direct_expand(HPid,TN,ACH,Pre,Post,State,Statics,Statics1):-
  586   dir_apply_method(TN,HPid,ACH,Pre,Post,State,Statics,Statics1),!.
  587
  588% search forwards use ground operators only
  589expand_node1(ID,Statics,Statics,Pre,State,from(PR),List,List1):-
  590   find_related_op(Pre,[],OPls),
  591   member(ID,OPls),
  592   gOperator(ID,_,OP),
  593   apply_ground_op(OP,Pre,State,List,List1).
  594expand_node1(OP,Statics,Statics1,Pre,State,from(PR),List,List1):-
  595   not(goal_related(_,_,_)),
  596   operatorC(OP,Pre0,Post0,Cond,ST),
  597   apply_unground_op(OP,Pre0,Post0,Cond,ST,Statics,Statics1,Pre,State,List,List1).
  598
  599apply_ground_op(operator(OP,Prev,Nec,Cond),Pre,State,List,List1):-
  600   state_achieved(Prev,Pre),
  601   nec_state_change(Pre,Nec,State2),
  602   cond_state_change(State2,Cond,State),
  603   gensym(hp,HP),
  604   append_dcut(List,[step(HP,OP,Pre,State,exp(OP))],List1),
  605   retract(op_num(N)),
  606   N1 is N+1,
  607   assert(op_num(N1)),!.
  608
  609apply_unground_op(OP,Pre0,Post0,Cond,ST,Statics,Statics1,Pre,State,List,List1):-
  610   statics_append(ST,Statics,Statics2),
  611   state_achieved(Pre0,Pre,Statics2),
  612   state_change(Pre,Pre0,Post0,State2),
  613   cond_state_change(State2,Cond,State),
  614   statics_consist_instance(ST),
  615   remove_unneed(Statics2,[],Statics1),
  616   gensym(hp,HP),
  617   append_dcut(List,[step(HP,OP,Pre,State,exp(OP))],List1),
  618   retract(op_num(N)),
  619   N1 is N+1,
  620   assert(op_num(N1)).
  621
  622find_related_op([],Ops1,Ops):-
  623   remove_dup(Ops1,[],Ops),!.
  624find_related_op([Head|Pre],List,Ops):-
  625   setof(OPls,Head^Level^goal_related(Head,OPls,Level),OPs0),
  626   flatten(OPs0,[],OPs1),
  627   append_dcut(List,OPs1,List1),
  628   find_related_op(Pre,List1,Ops),!.
  629find_related_op([Head|Pre],List,Ops):-
  630   find_related_op(Pre,List,Ops),!.
  631
  632% select a tp_node with lowest score
  633select_tnode(tp_node(TPid,Pre,Statics,Parents,Score,Dec)) :-
  634   retractall(score_list(LS)),
  635   assert(score_list([])),
  636   lowest_score(Score),
  637   retract(tp_node(TPid,Pre,Statics,Parents,Score,Dec)),!.
  638%   tell(user),nl,write('new level'),nl,told,!.
  639
  640% find the lowest_score of tp_node
  641lowest_score(LScore):-
  642     tp_node(HPid,Pre,Statics,Parents,Score,Dec),
  643     retract(score_list(LS)),
  644     assert(score_list([Score|LS])),
  645     fail.
  646lowest_score(LScore):-
  647     retract(score_list(D)),
  648     sort(D,[LScore|SD]).
  649
  650% assert assert_tnode(TP,OP,PR,Score,Post,Statics1,Steps1),
  651%if goal achieved, assert solved_node
  652assert_tnode(TP,OP,PR,Score,Post,Statics,[]):-!.
  653assert_tnode(TP,OP,PR,Score,Post,Statics,Steps):-
  654   tp_goal(Pre,Goal,Statics1),
  655   state_achieved(Goal,Post,Statics),
  656   combine_exp_steps(Post,Steps,OneStep),
  657   assert(solved_node(Statics,OneStep)),!.
  658assert_tnode(TP,OP,PR,Score,Post,Statics,Steps):-
  659   existing_node(Post,Statics),!.
  660assert_tnode(TP,OP,PR,Score,Post,Statics,Steps):-
  661   get_score(PR,Post,Steps,Score),
  662%   op_score(OP,SS),
  663%   Score is Score1-SS,
  664   gensym(tp,TP1),
  665%   write(TP1),nl,
  666%   write(Steps),nl,
  667   assert(tp_node(TP1,Post,Statics,from(TP),Score,Steps)),!.
  668
  669combine_exp_steps(Post,Steps,step(HP,achieve(Goal),Pre,Post,exp(TN))):-
  670   tp_goal(Pre,Goal,Statics),
  671   get_action_list(Steps,[],ACTls),
  672   make_temp(ACTls,[],Temp),
  673   gensym(hp,HP),
  674   make_tn(TN,achieve(Goal),Pre,Post,Temp,Steps),!.
  675
  676% get the temperal from an ordered steps
  677get_action_list([],ACTls,ACTls):-!.
  678get_action_list([step(HP,_,_,_,_)|Steps],List,ACTls):-
  679    append_cut(List,[HP],List1),
  680    get_action_list(Steps,List1,ACTls),!.
  681
  682make_temp([HP|[]],Temp,Temp):-!.
  683make_temp([HP1|[HP2|Rest]],List,Temp):-
  684    append_cut(List,[before(HP1,HP2)],List1),
  685    make_temp([HP2|Rest],List,Temp),!.
  686
  687existing_node(Post,Statics):-
  688    tp_node(_,Post,_,_,_,_).
  689existing_node(Post,Statics):-
  690    closed_node(_,Post,_,_,_,_).
  691% ------------------related goals------------------
  692
  693assert_goal_related_init(Pre,[],Statics):-!.
  694%assert_goal_related_init(Pre,[se(Sort,Obj,SE)|Post],Statics):-
  695%    state_achieved([se(Sort,Obj,SE)],Pre,Statics),!.
  696assert_goal_related_init(Pre,[se(Sort,Obj,SE)|Post],Statics):-
  697    ground(Obj),
  698    is_of_primitive_sort(Obj,SortP),
  699    assert(goal_related(se(SortP,Obj,SE),[],0)),
  700    assert_goal_related_init(Pre,Post,Statics),!.
  701assert_goal_related_init(Pre,[se(Sort,Obj,SE)|Post],Statics):-
  702    assert_related_goals_varible(Sort,Obj,SE,goal,0),
  703    assert_goal_related_init(Pre,Post,Statics),!.
  704
  705% find_all_related_goals: backward search
  706% until all preconditions have found
  707find_all_related_goals(Pre,Statics,N,N):-
  708    get_all_state(States),
  709    all_found(States,Pre,Statics),
  710    assert(goal_related_search(succ)),
  711    find_all_related_goals_final(Statics,N),!.
  712find_all_related_goals(Pre,Statics,I,N):-
  713    I1 is I-1,
  714    goal_related(_,_,I1),
  715    find_related_goal(Statics,I1,I),
  716    I2 is I+1,
  717    find_all_related_goals(Pre,Statics,I2,N),!.
  718find_all_related_goals(Pre,Statics,N,N):-
  719    not(goal_related(_,_,N)),
  720    assert(goal_related_search(fail)),
  721    write('related goal search failed'),
  722    retractall(goal_related(_,_,_)),!.
  723    %fail to find out, don't search any more
  724    % fwsearch use all the ground ops.
  725
  726
  727% final find the actions to recover initial states:
  728% in case the initial states was deleted by other actions
  729find_all_related_goals_final(Statics,N):-
  730    N1 is N-1,
  731    goal_related(Pre,_,N1),
  732    find_related_goal(Statics,N1,N),!.
  733find_all_related_goals_final(Statics,N):-!.
  734
  735% get all the found goal related states
  736get_all_state(States):-
  737   setof(Goal, Statics^Level^OP^goal_related(Goal,OP,Level),States11),
  738   put_one_obj_together(States11,[],States),!.
  739
  740put_one_obj_together([],States,States):-!.
  741put_one_obj_together([se(Sort,Obj,ST)|States1],List,States):-
  742   put_one_obj_together1(se(Sort,Obj,ST),List,List1),
  743   put_one_obj_together(States1,List1,States),!.
  744
  745put_one_obj_together1(se(Sort,Obj,ST),[],[se(Sort,Obj,ST)]):-!.
  746put_one_obj_together1(se(Sort,Obj,ST),[se(Sort,Obj,ST00)|List],[se(Sort,Obj,ST1)|List]):-
  747   set_append_e(ST,ST00,ST1),!.
  748put_one_obj_together1(se(Sort,Obj,ST),[se(Sort1,Obj1,ST1)|List],[se(Sort1,Obj1,ST1)|List1]):-
  749   Obj\==Obj1,
  750   put_one_obj_together1(se(Sort,Obj,ST),List,List1),!.
  751
  752% all the Precondition states in backward search can reach initial states
  753all_found([],States,Statics):-!.
  754all_found([se(Sort,Obj,ST)|States],Pre,Statics):-
  755   member(se(Sort,Obj,SPre),Pre),
  756   subtract(SPre,ST,Diff),
  757   isemptylist(Diff),
  758   all_found(States,Pre,Statics),!.
  759
  760% find all the states that can achieve the goal state
  761% separete ground operators to related-op and unrelated op
  762find_related_goal(Statics,I1,I):-
  763    gOperator(OPID,ID,operator(Name,Prev,Nec,Cond)),
  764    find_related_goal_nec(OPID,Name,Prev,Nec,Statics,I1,I),
  765    find_related_goal_cond(OPID,Name,Prev,Nec,Cond,Statics,I1,I),
  766    fail.
  767find_related_goal(Statics,I1,I).
  768
  769find_related_goal_nec(ID,Name,Prev,Nec,Statics,I1,I):-
  770    goal_related(se(Sort,Obj,SE),Ops,I1),
  771    member(sc(Sort,Obj,Lhs=>Rhs),Nec),
  772    state_match(Sort,Obj,SE,Rhs),
  773    statics_consist(Statics),
  774%    assert_op_score(ID,OPs),
  775    assert_goal_related(Prev,Nec,ID,I).
  776find_related_goal_cond(ID,Name,Prev,Nec,[],Statics,I1,I):-
  777    !.
  778find_related_goal_cond(ID,Name,Prev,Nec,Cond,Statics,I1,I):-
  779    goal_related(se(Sort,Obj,SE),Ops,I1),
  780    member(sc(Sort0,Obj,LHS=>RHS),Cond),
  781    is_of_sort(Obj,Sort0),
  782    is_of_sort(Obj,Sort),%Sort is a primitive sort changed at init
  783    filterInvars(LHS,LInVars,LIsOfSorts,LNEs,FLHS),
  784    filterInvars(RHS,RInVars,RIsOfSorts,RNEs,FRHS),
  785    can_achieve_g([se(Sort,Obj,FRHS)],[se(Sort,Obj,SE)],Statics),
  786    statics_consist(Statics),
  787    checkInVars(LInVars),
  788    checkInVars(RInVars),
  789    checkIsOfSorts(LIsOfSorts),
  790    checkIsOfSorts(RIsOfSorts),
  791    obeysNEs(LNEs),
  792    obeysNEs(RNEs),
  793%    assert_op_score(ID,OPs),
  794    assert_goal_related(Prev,[sc(Sort,Obj,FLHS=>FRHS)|Nec],ID,I).
  795
  796% filter out invars, is_of_sorts and nes from a state list
  797filterInvars([],[],[],[],[]):-!.
  798filterInvars([is_of_sort(A,B)|State],InVars,[is_of_sort(A,B)|IsOfSorts],NEs,FState):-	
  799    !,
  800    filterInvars(State,InVars,IsOfSorts,NEs,FState).	
  801filterInvars([ne(A,B)|State],InVars,IsOfSorts,[ne(A,B)|NEs],FState):-
  802    !,
  803    filterInvars(State,InVars,IsOfSorts,NEs,FState).	
  804filterInvars([is_of_primitive_sort(A,B)|State],InVars,[is_of_sort(A,B)|IsOfSorts],NEs,FState):-	
  805    !,
  806    filterInvars(State,InVars,IsOfSorts,NEs,FState).
  807filterInvars([Pred|State],[Pred|InVars],IsOfSorts,NEs,FState):-
  808    functor(Pred,FF,NN),
  809    functor(Pred1,FF,NN),
  810    atomic_invariantsC(Atom),
  811    member_cut(Pred1,Atom),!,
  812    filterInvars(State,InVars,IsOfSorts,NEs,FState).
  813filterInvars([Pred|State],InVars,IsOfSorts,NEs,[Pred|FState]):-
  814    filterInvars(State,InVars,IsOfSorts,NEs,FState).
  815
  816% filter out nes from a state list
  817filterNes([],[],[]):-!.
  818filterNes([ne(A,B)|State],[ne(A,B)|NEs],FState):-
  819    !,
  820    filterNes(State,NEs,FState).
  821filterNes([Pred|State],NEs,[Pred|FState]):-
  822    filterNes(State,NEs,FState).	
  823
  824assert_related_op(OP,I):-
  825    related_op(OP,_),!.
  826assert_related_op(OP,I):-
  827    asserta(related_op(OP,I)),!.
  828
  829% State2 can be achieved by State1
  830can_achieve_g([],State2,Statics):-!.
  831can_achieve_g(State1,State2,Statics):-
  832    can_achieve_g(State1,State2),
  833    statics_consist(Statics).
  834
  835can_achieve_g([se(Sort,Obj,ST1)|State1],[se(Sort,Obj,ST2)]):-
  836    state_match(Sort,Obj,ST2,ST1).
  837can_achieve_g([Head|State1],State2):-
  838    can_achieve_g(State1,State2).
  839
  840% assert:goal_related(Pre,Post,Op,DistanseFromGoal)
  841assert_goal_related(Prev,Nec,OP,I):-
  842    assert_goal_related1(Prev,OP,I),!,
  843    assert_goal_related1(Nec,OP,I).
  844
  845assert_goal_related1([],Op,I):-!.
  846assert_goal_related1([se(Sort,Obj,SE)|Prev],Op,I):-
  847    assert_goal_related2(se(Sort,Obj,SE),Op,I),
  848    assert_goal_related1(Prev,Op,I),!.
  849assert_goal_related1([sc(Sort,Obj,LH=>RH)|Nec],Op,I):-
  850    ground(Obj),%because conditional didn't ground, so the Sort maybe nonprim
  851    is_of_primitive_sort(Obj,PSort),!,
  852    assert_goal_related2(se(PSort,Obj,LH),Op,I),
  853    assert_goal_related1(Nec,Op,I).
  854assert_goal_related1([sc(Sort,Obj,LH=>RH)|Nec],Op,I):-
  855    var(Obj),
  856    assert_related_goals_varible(Sort,Obj,LH,Op,I),
  857    assert_goal_related1(Nec,Op,I).
  858
  859assert_goal_related2(se(Sort,Obj,SE),goal,I):-
  860    assert(goal_related(se(Sort,Obj,SE),[],I)),!.
  861assert_goal_related2(se(Sort,Obj,SE),Op,I):-
  862    goal_related(se(Sort,Obj,SE1),Ops,I),
  863    not(is_diff(SE,SE1)),
  864    retract(goal_related(se(Sort,Obj,SE),Ops,I)),
  865    assert(goal_related(se(Sort,Obj,SE),[Op|Ops],I)),!.
  866assert_goal_related2(se(Sort,Obj,SE),Op,I):-
  867    assert(goal_related(se(Sort,Obj,SE),[Op],I)),!.
  868
  869assert_related_goals_varible(Sort,Obj,SE,Op,I):-
  870    find_prim_sort(Sort,PSorts),
  871    member(Sort1,PSorts),
  872    assert_goal_related2(se(Sort1,Obj,SE),Op,I),
  873    fail.
  874assert_related_goals_varible(Sort,Obj,SE,Op,I).
  875
  876%assert score for Op, the further from goal, the higher the score
  877assert_op_score(OP,OPB):-
  878     op_score(OP,_),!.
  879assert_op_score(OP,OPB):-
  880     op_score(OPB,I),
  881     I1 is I+1,
  882     assert(op_score(OP,I1)),!.
  883
  884get_score(PR,Post,Steps,Score):-
  885    tp_goal(Pre,Goal,Statics),
  886    get_distance(Pre,Post,Goal,0,Dis),%length from Present to Goal
  887%    length(Pre,Obj_Num),
  888    get_length(PR,1,Len),
  889%    Num1 is Obj_Num*Dis,%distanse the smaller the better
  890%    Num2 is Obj_Num*Len1,%length of the plan the smaller the better
  891%    Score is Num1+Num2,!.
  892    Score is Dis+Len,!.
  893
  894get_distance(Pre,[],Goal,Dis,Dis):-!.
  895get_distance(Pre,[se(Sort,Obj,SE)|Post],Goal,Dis1,Dis):-
  896    member(se(Sort,Obj,SE0),Goal),
  897    state_match(Sort,Obj,SE0,SE),%if it achieved goal
  898    get_distance(Pre,Post,Goal,Dis1,Dis),!.
  899get_distance(Pre,[se(Sort,Obj,SE)|Post],Goal,Dis1,Dis):-
  900    goal_related(se(Sort,Obj,SE0),_,Level),
  901    state_match(Sort,Obj,SE0,SE),
  902    Dis2 is Dis1+Level,
  903    get_distance(Pre,Post,Goal,Dis2,Dis),!.
  904get_distance(Pre,[se(Sort,Obj,SE)|Post],Goal,Dis1,Dis):-
  905    member(se(Sort,Obj,SE0),Pre),
  906    state_match(Sort,Obj,SE,SE0),%if it does't change initial state
  907    Dis2 is Dis1+1,
  908    get_distance(Pre,Post,Goal,Dis2,Dis),!.
  909get_distance(Pre,[se(Sort,Obj,SE)|Post],Goal,Dis1,Dis):-
  910    Dis2 is Dis1+100,
  911    get_distance(Pre,Post,Goal,Dis2,Dis),!.
  912
  913get_length(init,Len,Len):-!.
  914get_length(TP,Len1,Len):-
  915    closed_node(TP,_,_,from(PR),_,_),
  916    Len2 is Len1+1,
  917    get_length(PR,Len2,Len),!.
  918
  919
  920% the states that can achieve a state
  921% that is:
  922% for a state in the rhs of operator
  923% all the states in the lhs
  924find_relate_state:-
  925   operatorC(A,Pre,Post,Cond,ST),
  926   assert_related_states(A,Pre,Post,Cond,ST),
  927   fail.
  928find_relate_state.
  929
  930assert_related_states(A,Pre,Post,Cond,ST):-
  931   assert_related_states1(A,Pre,Post,ST),
  932   assert_related_states2(A,Pre,Cond,ST).
  933% find relate in nec
  934% the sorts here are primitive
  935assert_related_states1(A,Pre,[],ST):-!.
  936%when prev
  937assert_related_states1(A,Pre,[se(Sort,Obj,SE)|Post],ST):-
  938   u_mem_cut(se(Sort,Obj,SE),Pre),
  939   assert_related_states1(A,Pre,Post,ST),!.
  940%when nec
  941assert_related_states1(A,Pre,[se(Sort,Obj,SE)|Post],ST):-
  942   assert(produce(se(Sort,Obj,SE),A,Pre,ST)),
  943   assert_related_states1(A,Pre,Post,ST),!.
  944
  945% find relate in conditional
  946% the sorts here are not primitive
  947assert_related_states2(A,Pre,SC,ST):-
  948   make_sc_primitive(SC,PSC),
  949   assert_related_states21(A,Pre,PSC,ST).
  950
  951assert_related_states21(A,Pre,[],ST):-!.
  952assert_related_states21(A,Pre,[sc(Sort,Obj,SE=>SS)|Trans],ST):-
  953   rem_statics([se(Sort,Obj,SE)],[se(Sort,Obj,SER)],St1),
  954   rem_statics([se(Sort,Obj,SS)],[se(Sort,Obj,SSR)],St2),
  955   append_cut(ST,St1,ST1),
  956   append_cut(ST1,St2,ST21),
  957   remove_unneed(ST21,[],ST2),
  958   append_cut(Pre,[se(Sort,Obj,SER)],Pre1),
  959   assert(produce(se(Sort,Obj,SSR),A,Pre1,ST2)),
  960   assert_related_states21(A,Pre,Trans,ST),!.
  961
  962%-------------------------------------------
  963% remove HP1 from the temp list
  964% if  HP1<HP2, then all HP3<HP1 => HP3<HP2
  965% if  HP2<HP1, then all HP1<HP3 => HP2<HP3
  966remove_temp([],HP1,List,List):-!.
  967remove_temp([before(HP1,HP2)|Temp],HP1,List,Temp1):-
  968    remove_temp_before(List,before(HP1,HP2),List2),
  969    remove_temp(Temp,HP1,List2,Temp1),!.
  970remove_temp([before(HP2,HP1)|Temp],HP1,List,Temp1):-
  971    remove_temp_after(List,before(HP2,HP1),List2),
  972    remove_temp(Temp,HP1,List2,Temp1),!.
  973remove_temp([before(HPX,HPY)|Temp],HP1,List,Temp1):-
  974    remove_temp(Temp,HP1,List,Temp1),!.
  975
  976% if  HP1<HP2, remove HP1<HP2, and change all HP3<HP1 => HP3<HP2
  977remove_temp_before([],before(HP1,HP2),[]):-!.
  978remove_temp_before([before(HP1,HP2)|T],before(HP1,HP2),T1):-
  979   remove_temp_before(T,before(HP1,HP2),T1),!.
  980remove_temp_before([before(HP3,HP1)|T],before(HP1,HP2),[before(HP3,HP2)|T1]):-
  981   remove_temp_before(T,before(HP1,HP2),T1),!.
  982remove_temp_before([before(HPX,HPY)|T],before(HP1,HP2),[before(HPX,HPY)|T1]):-
  983   remove_temp_before(T,before(HP1,HP2),T1),!.
  984% if  HP2<HP1, remove HP2<HP1, and change all HP1<HP3 => HP2<HP3
  985remove_temp_after([],before(HP1,HP2),[]):-!.
  986remove_temp_after([before(HP2,HP1)|T],before(HP2,HP1),T1):-
  987   remove_temp_after(T,before(HP2,HP1),T1),!.
  988remove_temp_after([before(HP1,HP3)|T],before(HP2,HP1),[before(HP2,HP3)|T1]):-
  989   remove_temp_after(T,before(HP2,HP1),T1),!.
  990remove_temp_after([before(HPX,HPY)|T],before(HP2,HP1),[before(HPX,HPY)|T1]):-
  991   remove_temp_after(T,before(HP2,HP1),T1),!.
  992
  993remove_dec(HPid,[],[]):-!.
  994remove_dec(HPid,[step(HPid,_,_,_,_)|Dec],Dec1):-
  995   remove_dec(HPid,Dec,Dec1),!.
  996remove_dec(HPid,[step(A,B,C,D,F)|Dec],[step(A,B,C,D,F)|Dec1]):-
  997   remove_dec(HPid,Dec,Dec1),!.
  998   
  999/******************************************************/
 1000% State2 is achieved by State1
 1001% the two states need to be primitive
 1002state_achieved(undefd,State,Statics):-!.
 1003state_achieved([],State2,Statics):-!.
 1004state_achieved(State1,State2,Statics):-
 1005    state_achieved(State1,State2),
 1006    statics_consist(Statics).
 1007
 1008state_achieved(undefd,State):-!.
 1009state_achieved([],State2).
 1010state_achieved([se(Sort,Obj,ST1)|State1],State2):-
 1011    member(se(Sort,Obj,ST2),State2),
 1012    is_of_sort(Obj,Sort),
 1013    state_match(Sort,Obj,ST1,ST2),
 1014    list_take(State2,[se(Sort,Obj,ST2)],State21),
 1015    state_achieved(State1,State21).
 1016state_achieved([se(Sort,Obj,ST1)|State1],State2):-
 1017    not(member(se(Sort,Obj,ST2),State2)),
 1018    state_achieved(State1,State2),!.
 1019
 1020/************ states ST matchs ST1  ********/
 1021% state_match: ST is achieved by ST1
 1022% ST=ST1
 1023state_match(Sort,Obj,ST,ST1):-
 1024    not(is_diff(ST,ST1)),!.
 1025% when ST is the subset of ST1,
 1026% in some domain, one substateclass is anothers's subset
 1027% they cann't consider as match each other
 1028% for example [on_block(a,b)] and [on_block(a,b),clear(a)]
 1029state_match(Sort,Obj,ST,ST1):-
 1030    is_achieved(ST,ST1),
 1031    gsubstate_classes(Sort,Obj,Substateclasses),
 1032    not(in_different_states(ST,ST1,Substateclasses)),!.
 1033% when ST is not the subset of ST1,
 1034% in hierarchical domain, maybe one is inhiered by the upperlevel
 1035state_match(Sort,Obj,ST,ST1):-
 1036    not(is_achieved(ST,ST1)),    
 1037    set_append(ST,ST1,ST0),
 1038    gsubstate_classes(Sort,Obj,Substateclasses),
 1039    in_same_sub_states(ST0,Substateclasses),!.
 1040
 1041% in_same_sub_states: check if ST1+ST2 in one states
 1042in_same_sub_states(ST0,[State|SCls]):-
 1043    is_achieved(ST0,State),!.
 1044in_same_sub_states(ST0, [State|SCls]):-
 1045    in_same_sub_states(ST0,SCls),!.
 1046
 1047% in_different_states: check if ST,ST1 in different states
 1048in_different_states(ST,ST1, [State|SCls]):-
 1049    max_member(ST,Substateclasses,MSub, _),
 1050    max_member(ST1,Substateclasses,MSub1, _),
 1051    MSub\==MSub1,!.
 1052
 1053max_member(State, Stateclass, MSub, Others):-
 1054    max_member1(State, Stateclass, 0, [],MSub),
 1055    subtract(State,MSub,Others),!.
 1056
 1057% find out the biggest same items
 1058max_member1(State, [], Num, MSub, MSub):-!.
 1059% find it out the biggest set of common items in substateclass and State
 1060max_member1(State, [State1|SCls], Num, MSub1, MSub):-
 1061    same_items(State1,State,MSSt),
 1062    length(MSSt,Len),
 1063    Len > Num,
 1064    max_member1(State, SCls, Len, MSSt, MSub),!.
 1065max_member1(State, [State1|SCls], Num, MSub1,MSub):-
 1066    max_member1(State, SCls, Num, MSub1,MSub),!.
 1067
 1068% find it out the same items in two list
 1069same_items([],List2,[]):-!.
 1070same_items([X|List1],List2,[X|Same]):-
 1071    member(X,List2),
 1072    same_items(List1,List2,Same),!.
 1073same_items([X|List1],List2,Same):-
 1074    same_items(List1,List2,Same),!.
 1075
 1076
 1077% all the element in list1 are static or in list2
 1078is_achieved([],_):-!.
 1079is_achieved([H|T], State) :-
 1080    is_statics(H),
 1081    is_achieved(T,State),!.
 1082is_achieved([H|T], State) :-
 1083    member(H,State),
 1084    is_achieved(T,State),!.
 1085
 1086% check if a predicate is statics or not
 1087is_statics(ne(A,B)):-!.
 1088is_statics(is_of_sort(A,B)):-!.
 1089is_statics(is_of_primitive_sort(A,B)):-!.
 1090is_statics(Pred):-
 1091    functor(Pred,FF,NN),
 1092    functor(Pred1,FF,NN),
 1093    atomic_invariantsC(Atom),
 1094    member_cut(Pred1,Atom),!.
 1095
 1096/************ state changes by actions ********/
 1097% on the condition that:
 1098% an object's state meet action's precondition
 1099% it change to the postcondition
 1100% Pre is the current ground states(Sort is primitive)
 1101% Pre0 and Post0 are from an Operator or Method(
 1102% Sorts are all primitive
 1103state_change([],Pre0,Post0,[]):-!.
 1104state_change(Pre,[],[],Pre):-!.
 1105state_change([se(Sort,Obj,SPre)|Pre],Pre0,Post0,[se(Sort,Obj,STPost)|Post]):-
 1106    state_achieved([se(Sort,Obj,SPre)],Pre0),
 1107    state_change0(Sort,Obj,SPre,Pre0,Post0,Pre1,Post1,STPost),
 1108    state_change(Pre,Pre1,Post1,Post).
 1109state_change([se(Sort,Obj,SPre)|Pre],Pre0,Post0,[se(Sort,Obj,STPost)|Post]):-
 1110    not(member(se(Sort,Obj,SPre0),Pre0)),
 1111    state_change(Pre,Pre1,Post1,Post).
 1112		 
 1113% change the obj's post state with action's post
 1114state_change0(Sort,Obj,SPre,[],[],[],[],SPre):-!.
 1115state_change0(Sort,Obj,SPre,[se(Sort,Obj,SPre0)|Pre0],[se(Sort,Obj,SPost0)|Post0],Pre0,Post0,STPost):-
 1116    state_change1(SPre,SPre0,SPost0,STPost).
 1117state_change0(Sort,Obj,SPre,[se(Sort1,Obj1,SPre0)|Pre0],[se(Sort1,Obj1,SPost0)|Post0],[se(Sort1,Obj1,SPre0)|Pre1],[se(Sort1,Obj1,SPost0)|Post1],STPost):-
 1118    Obj\==Obj1,
 1119    state_change0(Sort,Obj,SPre,Pre0,Post0,Pre1,Post1,STPost).
 1120
 1121state_change1([],SPre0,SPost0,SPost0):-!.
 1122state_change1(Pre,[],[],Pre):-!.
 1123%if the pre state in action's pre, not in post, remove that
 1124state_change1([Head|SPre],SPre0,SPost0,STPost):-
 1125    member(Head,SPre0),
 1126    not(member(Head,SPost0)),
 1127    state_change1(SPre,SPre0,SPost0,STPost).
 1128% if the pre state is not action's pre, neither in post, add that
 1129state_change1([Head|SPre],SPre0,SPost0,[Head|STPost]):-
 1130    not(member(Head,SPre0)),
 1131    not(member(Head,SPost0)),
 1132    state_change1(SPre,SPre0,SPost0,STPost),!.
 1133% if the pre state is in post, don't need to add
 1134% because it will be add at last
 1135state_change1([Head|SPre],SPre0,SPost0,STPost):-
 1136    member(Head,SPost0),
 1137    state_change1(SPre,SPre0,SPost0,STPost).
 1138
 1139% rough change the obj's post state with action's post
 1140rough_state_change(Pre,[],[],Pre):-!.
 1141rough_state_change([],_,_,[]):-!.
 1142rough_state_change([se(Sort,Obj,SE)|Pre],Pre0,Post0,[se(Sort,Obj,SS0)|Post]):-
 1143    member(se(Sort,Obj,SE0),Pre0),
 1144    member(se(Sort,Obj,SS0),Post0),
 1145    is_of_sort(Obj,Sort),
 1146    state_achieved([se(Sort,Obj,SE0)],[se(Sort,Obj,SE)]),
 1147    list_take(Pre0,[se(Sort,Obj,SE0)],Pre01),
 1148    list_take(Post0,[se(Sort,Obj,SS0)],Post01),
 1149    rough_state_change(Pre,Pre01,Post01,Post),!.
 1150rough_state_change([se(Sort,Obj,SE)|Pre],Pre0,Post0,[se(Sort,Obj,SE)|Post]):-
 1151    rough_state_change(Pre,Pre0,Post0,Post),!.
 1152
 1153% a simple state_change for ground operators
 1154state_changeG([],Pre0,Post0,[]):-!.
 1155state_changeG([se(Sort,Obj,SE)|Pre],Pre0,Post0,[se(Sort,Obj,RHS)|State]):-
 1156   member(se(Sort,Obj,LHS),Pre0),
 1157   member(se(Sort,Obj,RHS),Post0),
 1158   state_match(Sort,Obj,SE,LHS),
 1159   state_changeG(Pre,Pre0,Post0,State),!.
 1160state_changeG([se(Sort,Obj,SE)|Pre],Pre0,Post0,[se(Sort,Obj,SE)|State]):-
 1161   not(member(se(Sort,Obj,LHS),Pre0)),
 1162   state_changeG(Pre,Pre0,Post0,State),!.
 1163
 1164find_lower_sort(Sort,Sort,Sort):-!.
 1165find_lower_sort(Sort,Sort1,Sort1):-
 1166    subsorts(Sort,Sortls),
 1167    member(Sort1,Sortls),!.
 1168find_lower_sort(Sort,Sort1,Sort):-
 1169    subsorts(Sort1,Sortls),
 1170    member(Sort,Sortls),!.
 1171%-------------------------------------------------
 1172/************ state changes by necessery changes ********/
 1173% for all the object's state meet the precondition
 1174% it change to the postcondition
 1175% this is only used in apply grounded operators
 1176nec_state_change([],Nec,[]):-!.
 1177nec_state_change([se(Sort,Obj,SE)|Pre],Nec,[se(Sort,Obj,Post)|State]):-
 1178    member(sc(Sort,Obj,Lhs=>Rhs),Nec),
 1179    state_match(Sort,Obj,Lhs,SE),
 1180    state_change1(SE,Lhs,Rhs,Post),
 1181    nec_state_change(Pre,Nec,State),!.
 1182nec_state_change([se(Sort,Obj,SE)|Pre],Nec,[se(Sort,Obj,SE)|State]):-
 1183    not(member(sc(Sort,Obj,Lhs=>Rhs),Nec)),
 1184    nec_state_change(Pre,Nec,State),!.
 1185%-------------------------------------------------
 1186/************ state changes by conditions ********/
 1187% for all the object's state meet the precondition
 1188% it change to the postcondition
 1189cond_state_change([],Cond,[]):-!.
 1190cond_state_change(State,[],State):-!.
 1191cond_state_change([se(Sort,Obj,SE)|Pre],Cond,[NewSS|State]):-
 1192    member(sc(Sort1,Obj1,SE0=>SS0),Cond),
 1193%    var(Obj1),
 1194    subsorts(Sort1,Subsorts),
 1195    member(Sort,Subsorts),
 1196    copy_states(se(Sort1,Obj1,SE0),se(Sort,Obj,SE2)),
 1197    copy_states(se(Sort1,Obj1,SS0),se(Sort,Obj,SS2)),
 1198%    state_match(Sort,Obj,SE,SE0),
 1199    filterInvars(SE2,LInVars,LIsOfSorts,LNEs,FSE),
 1200    filterInvars(SS2,RInVars,RIsOfSorts,RNEs,FSS),
 1201    state_match(Sort,Obj,SE,FSE),
 1202    state_change([se(Sort,Obj,SE)],[se(Sort,Obj,FSE)],
 1203                              [se(Sort,Obj,FSS)],[NewSS]),
 1204    checkInVars(LInVars),
 1205    checkInVars(RInVars),
 1206    checkIsOfSorts(LIsOfSorts),
 1207    checkIsOfSorts(RIsOfSorts),
 1208    obeysNEs(LNEs),
 1209    obeysNEs(RNEs),    
 1210    cond_state_change(Pre,Cond,State),!.
 1211cond_state_change([se(Sort,Obj,SE)|Pre],Cond,[se(Sort,Obj,SE)|State]):-
 1212    cond_state_change(Pre,Cond,State),!.
 1213
 1214% copy the states so that the Obj won't be instiated
 1215copy_states(se(Sort1,Obj1,SE0),se(Sort,Obj,SE2)):-
 1216    copy_states1(Obj1,SE0,Obj,SE2),!.
 1217copy_states1(Obj1,[],Obj,[]):-!.
 1218copy_states1(Obj1,[Pred|SE0],Obj,[Pred2|SE2]):-
 1219     functor(Pred,FF,NN),
 1220     functor(Pred2,FF,NN),
 1221     Pred=..[Name|Vars],
 1222     Pred2=..[Name|Vars2],
 1223     copy_pred(Obj1,Obj,Vars,Vars2),
 1224     copy_states1(Obj1,SE0,Obj,SE2),!.
 1225
 1226copy_pred(Obj1,Obj,[],[]):-!.
 1227copy_pred(Obj1,Obj,[Var|Vars],[Var2|Vars2]):-
 1228     Obj1==Var,
 1229     Var2=Obj,
 1230     copy_pred(Obj1,Obj,Vars,Vars2),!.
 1231copy_pred(Obj1,Obj,[Var|Vars],[Var|Vars2]):-
 1232     copy_pred(Obj1,Obj,Vars,Vars2),!.
 1233%-------------------------------------------
 1234% every states in List1 is achieved by List2
 1235all_achieved(undefd,Statics,List2):-!.
 1236all_achieved([],Statics,List2):-!.
 1237all_achieved(List1,Statics,List2):-
 1238    all_achieved(List1,List2),
 1239    statics_consist(Statics).
 1240
 1241all_achieved([],List2).
 1242all_achieved([se(Sort,Obj,SL)|List1],List2):-
 1243    member(se(Sort1,Obj,SR),List2),
 1244    is_of_sort(Obj,Sort1),
 1245    is_of_sort(Obj,Sort),
 1246    is_of_primitive_sort(Obj,PSort),
 1247    state_match(PSort,Obj,SL,SR),
 1248    all_achieved(List1,List2).
 1249%-------------------------------------------
 1250% may_achieved: every states in Pre is not conflict with Post
 1251may_achieved(undefd,Statics,Post):-!.
 1252may_achieved([],Statics,Post):-!.
 1253may_achieved(Pre,Statics,Post):-
 1254    may_achieved(Pre,Post),
 1255    statics_consist(Statics),!.
 1256may_achieved([],Post).
 1257may_achieved([se(Sort,Obj,SL)|Pre],Post):-
 1258    member(se(Sort1,Obj,SR),Post),
 1259    is_of_sort(Obj,Sort1),
 1260    is_of_sort(Obj,Sort),
 1261    is_of_primitive_sort(Obj,PSort),
 1262    state_may_achieved(PSort,Obj,SL,SR),
 1263    may_achieved(Pre,Post),!.
 1264
 1265% if the ST1 is a subset of ST2
 1266state_may_achieved(Sort,Obj,[],ST2):-!.
 1267state_may_achieved(Sort,Obj,ST1,ST2):-
 1268    is_achieved(ST1,ST2),!.
 1269%-------------------------------------------
 1270% instantiate a bit
 1271% use action's state change include the postcondition
 1272post_instant(Post0,Cond,Statics,undefd):-!.
 1273post_instant(Post0,Cond,Statics,[]):-!.
 1274post_instant(Post0,Cond,Statics,[se(Sort,Obj,SE)|Post]):-
 1275    member(se(Sort,Obj,SE0),Post0),
 1276    statics_consist(Statics).
 1277post_instant(Post0,Cond,Statics,[se(Sort,Obj,SE)|Post]):-
 1278    member(sc(Sort,Obj,SE1=>SS),Cond),
 1279    statics_consist(Statics).
 1280post_instant(Post0,Cond,Statics,[se(Sort,Obj,SE)|Post]):-
 1281    member(sc(Sort0,Obj,SE1=>SS),Cond),
 1282    not(objectsC(Sort0,_)),
 1283    subsorts(Sort0,Sortls),
 1284    not(not(member(Sort,Sortls))),
 1285    statics_consist(Statics).
 1286post_instant(Post0,Cond,Statics,[se(Sort,Obj,SE)|Post]):-
 1287    post_instant(Post0,Cond,Statics,Post),!.
 1288
 1289/********* check for statics consist without instanciate them***/
 1290% only instance the variable when there is one choice of from the ground lists
 1291statics_consist([]):-!.
 1292statics_consist(Statics):-
 1293   get_invariants(Invs),
 1294   statics_consist(Invs,Statics),!.
 1295statics_consist(Invs,[]):-!.
 1296statics_consist(Invs,[ne(A,B)|Statics]):-
 1297   not(A==B),!,
 1298   statics_consist(Invs,Statics).
 1299statics_consist(Invs,[is_of_sort(Obj,Sort)|Statics]):-
 1300   not(not(is_of_sort(Obj,Sort))),!,
 1301   statics_consist(Invs,Statics).
 1302statics_consist(Invs,[is_of_primitive_sort(Obj,Sort)|Statics]):-
 1303   not(not(is_of_primitive_sort(Obj,Sort))),!,
 1304   statics_consist(Invs,Statics).
 1305statics_consist(Invs,[Pred|Statics]):-
 1306   pred_member(Pred,Invs),!,
 1307   statics_consist(Invs,Statics).
 1308
 1309/*********check for statics consist and instanciate them***/
 1310statics_consist_instance([]):-!.
 1311statics_consist_instance(Statics):-
 1312   get_invariants(Invs),
 1313   statics_consist_instance(Invs,Statics).
 1314
 1315statics_consist_instance(Invs,[]):-!.
 1316statics_consist_instance(Invs,[is_of_sort(Obj,Sort)|Atom]):-
 1317   ground(Obj),
 1318   is_of_sort(Obj,Sort),!,
 1319   statics_consist_instance(Invs,Atom).
 1320statics_consist_instance(Invs,[is_of_sort(Obj,Sort)|Atom]):-
 1321   var(Obj),
 1322   is_of_sort(Obj,Sort),
 1323   statics_consist_instance(Invs,Atom).
 1324statics_consist_instance(Invs,[is_of_primitive_sort(Obj,Sort)|Atom]):-
 1325   ground(Obj),
 1326   is_of_primitive_sort(Obj,Sort),!,
 1327   statics_consist_instance(Invs,Atom).
 1328statics_consist_instance(Invs,[is_of_primitive_sort(Obj,Sort)|Atom]):-
 1329   var(Obj),
 1330   is_of_primitive_sort(Obj,Sort),
 1331   statics_consist_instance(Invs,Atom).
 1332statics_consist_instance(Invs,[ne_back(A,B)|Atom]):-
 1333   A\==B,
 1334   statics_consist_instance(Invs,Atom).
 1335statics_consist_instance(Invs,[ne(A,B)|Atom]):-
 1336   append_dcut(Atom,[ne_back(A,B)],Atom1),!,
 1337   statics_consist_instance(Invs,Atom1).
 1338statics_consist_instance(Invs,[Pred|Atom]):-
 1339   ground(Pred),
 1340   member(Pred,Invs),!,
 1341   statics_consist_instance(Invs,Atom).
 1342statics_consist_instance(Invs,[Pred|Atom]):-
 1343   not(ground(Pred)),
 1344   member(Pred,Invs),
 1345   statics_consist_instance(Invs,Atom).
 1346
 1347
 1348
 1349/*********************Initial process *********************/
 1350%node(Name, Precond, Decomps, Temp, Statics)
 1351% When inputting new methods etc filter all statics into
 1352% static slot
 1353
 1354make_problem_into_node(I,goal(L,TM,STATS),  NN) :-
 1355     make_problem_up(L, STEPS),
 1356     make_num_hp(TM,Temp),
 1357     sort_steps(STEPS,Temp,STEPS1),
 1358     make_ss_to_se(I,I_Pre),
 1359     NN = node(root,I_Pre,STEPS1 ,Temp, STATS),!.
 1360make_problem_into_node(I,L,  NN) :-
 1361     make_problem_up([achieve(L)], STEPS),
 1362     make_num_hp(TM,Temp),
 1363     sort_steps(STEPS,Temp,STEPS1),
 1364     make_ss_to_se(I,I_Pre),
 1365     NN = node(root,I_Pre,STEPS1 ,Temp, STATS),!.
 1366
 1367% make problem to steps
 1368make_problem_up([],[]):-!.
 1369make_problem_up([achieve(L)|R],[step(HP,achieve(L1),undefd,[L1],unexp)|RS]):- 
 1370                             %preconditon here is undefd
 1371    make_ss_to_se([L],[L1]),
 1372    gensym(hp,HP),
 1373    make_problem_up(R, RS),!.
 1374make_problem_up([achieve(L)|R],[step(HP,achieve(L1),undefd,L1,unexp)|RS]):- 
 1375                             %preconditon here is undefd
 1376    make_ss_to_se(L,L1),
 1377    gensym(hp,HP),
 1378    make_problem_up(R, RS),!.
 1379make_problem_up([O|R],[step(HP,O,undefd,undefd,unexp)|RS]):-
 1380    methodC(O,Pre,Post,Statics1,Temp,ACH,Dec),
 1381    gensym(hp,HP),
 1382    make_problem_up(R, RS),!.
 1383make_problem_up([O|R],     
 1384           [step(HP,O,undefd,undefd,unexp)|RS]):-
 1385    operatorC(O,Pre,Post,Cond,Statics1),
 1386    gensym(hp,HP),
 1387    make_problem_up(R, RS),!.
 1388
 1389make_num_hp([],[]):-!.
 1390make_num_hp([before(N1,N2)|TM],[before(H1,H2)|Temp]):-
 1391    gensym_num(hp,N1,H1),
 1392    gensym_num(hp,N2,H2),
 1393    make_num_hp(TM,Temp),!.
 1394
 1395%**************sort steps*********************************
 1396% sort steps by temporal constraints.
 1397sort_steps(Steps,[],Steps):-!.
 1398sort_steps([Steps|[]],[],[Steps]):-!.
 1399sort_steps(Steps,Temp,OrderedST):-
 1400   steps_in_temp(Temp,[],ST),
 1401   sort_steps1(Temp,ST,OrderedSTID),
 1402   sort_steps2(Steps,OrderedSTID,[],OrderedST),!.
 1403
 1404% find out the steps in temporal constraints.
 1405steps_in_temp([],ST,ST):-!.
 1406steps_in_temp([before(H1,H2)|TT],List,ST):-
 1407   set_append_e(List,[H1,H2],List1),
 1408   steps_in_temp(TT,List1,ST),!.
 1409
 1410% sort the steps_id(hps) by temporal constraints.
 1411sort_steps1(Temp,[],[]):-!.
 1412sort_steps1(Temp,[HP1|TST],[HPF|OST]):-
 1413   earliest_step(HP1,HPF,Temp,TST,TST1),
 1414   sort_steps1(Temp,TST1,OST),!.
 1415   
 1416earliest_step(HPF,HPF,Temp,[],[]):-!.
 1417earliest_step(HP1,HPF,Temp,[HP2|TST],[HP1|TST1]):-
 1418   member(before(HP2,HP1),Temp),
 1419   earliest_step(HP2,HPF,Temp,TST,TST1),!.
 1420earliest_step(HP1,HPF,Temp,[HP2|TST],[HP2|TST1]):-
 1421   earliest_step(HP1,HPF,Temp,TST,TST1),!.
 1422
 1423% sort the steps, put the unordered steps in the front
 1424sort_steps2(OtherST,[],OrderedST1,OrderedST):-
 1425   append_dcut(OrderedST1,OtherST,OrderedST),!.
 1426sort_steps2(Steps,[HP|THPS],List,OrderedST):-
 1427   member(step(HP,N,Pre,Post,F),Steps),
 1428   append_dcut(List,[step(HP,N,Pre,Post,F)],List1),
 1429   list_take(Steps,[step(HP,N,Pre,Post,F)],Steps1),
 1430   sort_steps2(Steps1,THPS,List1,OrderedST),!.
 1431sort_steps2(Steps,[HP|THPS],List,OrderedST):-
 1432   sort_steps2(Steps,THPS,List,OrderedST),!.
 1433%*******************************************************
 1434
 1435% replace ss to se
 1436make_ss_to_se([],[]):-!.
 1437make_ss_to_se([ss(Sort,Obj,Post)|TPost],[se(Sort,Obj,Post)|TPre]):-
 1438     make_ss_to_se(TPost,TPre),!.
 1439make_ss_to_se([se(Sort,Obj,Post)|TPost],[se(Sort,Obj,Post)|TPre]):-
 1440     make_ss_to_se(TPost,TPre),!.
 1441
 1442%*******************************************************
 1443% extract_solution(Node,..
 1444% recurvise routine to work down tree and
 1445% print out a linearisation of it
 1446extract_solution(Node,PHPs,SIZE1,TNList) :-
 1447       % its the name of a hierarchical op......
 1448   getN_decomp(Node, HPs),
 1449   push_to_primitive(HPs,[],PHPs,[],TNList),
 1450   pprint(PHPs,1,SIZE),
 1451   SIZE1 is SIZE -1,!.
 1452
 1453/************ change_op_representation ***********/
 1454% make pre and post explicit
 1455% filter out statics and put in a new slot
 1456change_op_representation :-    
 1457    method(A,B,C,Stat,T,Dec),
 1458    make_ss_to_se(B,B0),
 1459    make_se_primitive(B0,B1),
 1460    make_sc_primitive(C,C1),
 1461    get_preconditions(C1,B1,Pre,Post),
 1462    rem_statics(Post, PostR,St1),
 1463    rem_statics(Pre, PreR,St2),
 1464    append_cut(St1,St2,Statics),
 1465    append_cut(Stat,Statics,Statics1),
 1466    remove_unneed(Statics1,[],Statics2),
 1467    get_achieval(A,Dec,T,Dec1,T1,ACH),
 1468    assert(methodC(A,PreR,PostR,Statics2,T1,achieve(ACH),Dec1)),
 1469    fail.
 1470change_op_representation :-
 1471    operator(A,B,C,D),
 1472    make_ss_to_se(B,B0),
 1473    make_se_primitive(B0,B1),
 1474    make_sc_primitive(C,C1),
 1475%    make_sc_primitive(D,D1),
 1476	%can't do that because it narrow the conditional change 
 1477    get_preconditions(C1,B1,Pre,Post),
 1478    rem_statics(Post, PostR,St1),
 1479    rem_statics(Pre, PreR,St2),
 1480    append_cut(St1,St2,Statics1),
 1481    remove_unneed(Statics1,[],Statics),
 1482    statics_consist(Statics),
 1483    assert(operatorC(A,PreR,PostR,D,Statics)),
 1484    fail.
 1485change_op_representation:-
 1486    retractall(current_num(sm,_)),!.
 1487
 1488get_preconditions([],Prev,Prev,Prev) :-!.
 1489get_preconditions([sc(S,X,From =>To)|Rest],Prev,[se(S,X,From1)|Pre],[se(S,X,To1)|Post]):-
 1490     member_e(se(S,X,PSE),Prev),
 1491     append_dcut(PSE,From,From1),
 1492     append_dcut(PSE,To,To1),
 1493     list_take(Prev,[se(S,X,PSE)],Prev1),
 1494     get_preconditions(Rest,Prev1, Pre,Post),!.
 1495get_preconditions([sc(S,X,From =>To)|Rest],Prev,[se(S,X,From)|Pre],[se(S,X,To)|Post]):-
 1496     get_preconditions(Rest,Prev, Pre,Post),!.
 1497get_preconditions([],Prev,Prev,Prev) :-!.
 1498
 1499% get all achieve goals out
 1500get_achieval(A,Dec,T,Dec1,T1,Achieval):-
 1501     retractall(current_num(sm,_)),
 1502     make_dec(A,Dec,Dec1,T,T1,[],Achieval),!.
 1503make_dec(A,[],[],Temp,Temp,Achieval,Achieval):-!.
 1504make_dec(A,[HD|TD],TD1,Temp,Temp1,Achieval,Achieval1):-
 1505     HD=..[achieve|Goal],
 1506     current_num(sm,Num),
 1507     replace_achieval_temp(Temp,Temp0,Num),
 1508     make_ss_to_se(Goal,Goal0),
 1509     append_dcut(Achieval,Goal0,Achieval0),
 1510     make_dec(A,TD,TD1,Temp0,Temp1,Achieval0,Achieval1),!.
 1511make_dec(A,[HD|TD],TD1,Temp,Temp1,Achieval,Achieval1):-
 1512     HD=..[achieve|Goal],
 1513     not(current_num(sm,Num)),
 1514     replace_achieval_temp(Temp,Temp0,1),
 1515     make_ss_to_se(Goal,Goal0),
 1516     append_dcut(Achieval,Goal0,Achieval0),
 1517     make_dec(A,TD,TD1,Temp0,Temp1,Achieval0,Achieval1).
 1518make_dec(A,[HD|TD],[HD|TD1],Temp,Temp1,Achieval,Achieval1):-
 1519     HD=..[DecName|Goal],
 1520     DecName\==achieve,
 1521     gensym(sm,SM),
 1522     current_num(sm,Num),
 1523     make_dec(A,TD,TD1,Temp,Temp1,Achieval,Achieval1),!.
 1524
 1525% get rid of the achievals in temp orders
 1526replace_achieval_temp(Temp,Temp1,Num):-
 1527     change_all_numbers(Temp,Num,Temp00),
 1528     tidy_temp(Temp00,Temp1).
 1529
 1530change_all_numbers([],Num,[]):-!.
 1531change_all_numbers([HTemp|TTemp],Num,[HTemp00|TTemp00]):-
 1532     HTemp=..[before|Nums],
 1533     change_nums(Nums,Num,Nums1),
 1534     HTemp00=..[before|Nums1],
 1535     change_all_numbers(TTemp,Num,TTemp00).
 1536
 1537change_nums([],Num,[]):-!.
 1538change_nums([Num1|TN],Num,[Num1|TN1]):-
 1539    Num1<Num,
 1540    change_nums(TN,Num,TN1),!.
 1541change_nums([Num1|TN],Num,[Num2|TN1]):-
 1542    Num1>Num,
 1543    Num2 is Num1-1,
 1544    change_nums(TN,Num,TN1),!.
 1545change_nums([Num|TN],Num,[0|TN1]):-
 1546    change_nums(TN,Num,TN1),!.
 1547
 1548% since assumed achieval only happen at first, so only change the after ones
 1549tidy_temp(Temp,Temp1):-
 1550     member(before(Num,0),Temp),
 1551     list_take(Temp,[before(Num,0)],Temp0),
 1552     change_laters(Temp0,Num,Temp01),
 1553     tidy_temp(Temp01,Temp1).
 1554tidy_temp([],[]):-!.
 1555tidy_temp([before(0,Num)|Temp],Temp0):-
 1556     tidy_temp(Temp,Temp0),!.
 1557tidy_temp([before(Num1,Num2)|Temp],[before(Num1,Num2)|Temp0]):-
 1558     tidy_temp(Temp,Temp0),!.
 1559
 1560change_laters([before(0,Num2)|Temp],Num,[before(Num,Num2)|Temp0]):-
 1561     change_laters(Temp,Num,Temp0).
 1562change_laters([before(Num1,0)|Temp],Num,[before(Num1,0)|Temp0]):-
 1563     change_laters(Temp,Num,Temp0).
 1564change_laters([before(Num1,Num2)|Temp],Num,[before(Num1,Num2)|Temp0]):-
 1565     change_laters(Temp,Num,Temp0).
 1566
 1567% change the states to primitive states
 1568make_se_primitive([],[]).
 1569make_se_primitive([se(Sort,Obj,ST)|SE],[se(Sort,Obj,ST)|SE0]):-
 1570    objectsC(Sort,Objls),!,
 1571    make_se_primitive(SE,SE0).
 1572make_se_primitive([se(Sort,Obj,ST)|SE],[se(PSort,Obj,ST)|SE0]):-
 1573    find_prim_sort(Sort,PSorts),
 1574    member(PSort,PSorts),
 1575    make_se_primitive(SE,SE0).
 1576
 1577% change the state changes to primitive states
 1578make_sc_primitive([],[]).
 1579make_sc_primitive([sc(Sort,Obj,SE1=>SE2)|ST],[sc(Sort,Obj,SE1=>SE2)|ST0]):-
 1580    objectsC(Sort,Objls),!,
 1581    make_sc_primitive(ST,ST0).
 1582make_sc_primitive([sc(Sort,Obj,SE1=>SE2)|ST],[sc(PSort,Obj,SE1=>SE2)|ST0]):-
 1583    find_prim_sort(Sort,PSorts),
 1584    member(PSort,PSorts),
 1585    make_sc_primitive(ST,ST0).
 1586
 1587
 1588% ------------ end of change operator ----------------------
 1589/********make_tn: save the expansion results*****/
 1590make_tn(TN,Name,Pre,Post,Temp,Dec):-
 1591    find_only_changed(Pre,Post,[],Pre1,[],Post1),
 1592    not(isemptylist(Post1)),
 1593    not(exist_tn(Pre,Post)),
 1594    gensym(tn,TN),
 1595%    tell(user),nl,write(tn(TN,Name,Pre1,Post1,Temp,Dec)),nl,told,
 1596    assert(tn(TN,Name,Pre1,Post1,Temp,Dec)),!.
 1597
 1598exist_tn(Pre,Post):-
 1599    tn(_,_,Pre,Post1,_,_),
 1600    state_achieved(Post,Post1),!.
 1601find_only_changed([],[],Pre,Pre,Post,Post):-!.
 1602% just a lazy check if they are in exactly same sequence
 1603find_only_changed([se(Sort,Obj,ST)|Pre],[se(Sort,Obj,ST)|Post],Pre0,Pre1,Post0,Post1):-
 1604    find_only_changed(Pre,Post,Pre0,Pre1,Post0,Post1),!.
 1605find_only_changed([se(Sort,Obj,ST)|Pre],Post,Pre0,Pre1,Post0,Post1):-
 1606    member(se(Sort,Obj,ST1),Post),
 1607    list_take(Post,[se(Sort,Obj,ST1)],Post2),
 1608    append_changed(se(Sort,Obj,ST),se(Sort,Obj,ST1),Pre0,Pre3,Post0,Post3),
 1609    find_only_changed(Pre,Post2,Pre3,Pre1,Post3,Post1),!.
 1610find_only_changed([se(Sort,Obj,ST)|Pre],Post,Pre0,Pre1,Post0,Post1):-
 1611    member(se(SortN,Obj,ST1),Post),
 1612    list_take(Post,[se(SortN,Obj,ST1)],Post2),
 1613    append_changed(se(Sort,Obj,ST),se(SortN,Obj,ST1),Pre0,Pre3,Post0,Post3),
 1614    find_only_changed(Pre,Post2,Pre3,Pre1,Post3,Post1),!.
 1615% other fail. 
 1616
 1617% append_dcut  only changed states
 1618% state_match here means not changed
 1619append_changed(se(Sort,Obj,ST),se(Sort1,Obj,ST1),Pre0,Pre0,Post0,Post0):-
 1620    state_match(Sort,Obj,ST,ST1),!.
 1621append_changed(se(Sort,Obj,ST),se(Sort1,Obj,ST1),Pre0,Pre3,Post0,Post3):-
 1622    append_dcut(Pre0,[se(Sort,Obj,ST)],Pre3),
 1623    append_dcut(Post0,[se(Sort,Obj,ST1)],Post3),!.
 1624
 1625%***********print out solution**************************   
 1626push_to_primitive([],PHPs,PHPs,TNLst,TNLst) :-!.
 1627push_to_primitive([step(HPID,_,_,_,exp(TN))|HPs],List,PHPs,TNSoFar,TNFinal) :-
 1628   tn(TN,Name,Pre,Post,Temp,Dec),
 1629   push_to_primitive(Dec,List,Dec1,[tn(TN,Name,Pre,Post,Temp,Dec)|TNSoFar],TNNext),
 1630   push_to_primitive(HPs,Dec1,PHPs,TNNext,TNFinal),!.
 1631push_to_primitive([step(HPID,_,_,_,exp(Name))|HPs],List,PHPs,TNSoFar,TNFinal):-
 1632   append_dcut(List,[Name],List1),
 1633   push_to_primitive(HPs,List1,PHPs,TNSoFar,TNFinal),!.
 1634
 1635/*********** TEMPORAL AND DECLOBBERING ************/
 1636
 1637possibly_before(I,J,Temps) :-
 1638    \+ necessarily_before(J,I,Temps), !.
 1639
 1640necessarily_before(J,I,Temps) :-
 1641    member(before(J,I),Temps),!.
 1642necessarily_before(J,I,Temps) :-
 1643    member(before(J,Z),Temps),
 1644    necessarily_before(Z,I,Temps),!.
 1645
 1646select_node(node(Name,Pre,Temp,Decomp,Statics)) :-
 1647   retract(node(Name,Pre,Temp,Decomp,Statics)),
 1648%   nl,nl,write(Name),write(' RETRACTED'),nl,nl,
 1649%   tell(user),
 1650%   nl,nl,write(Name),write(' RETRACTED'),nl,nl,
 1651%   tell(FF),
 1652    !.
 1653
 1654get_obj_prim_sort([],[]):-!.
 1655get_obj_prim_sort([HSort|TV],[HObj|TS]):-
 1656     is_of_primitive_sort(HObj,HSort),
 1657     get_obj_prim_sort(TV,TS),!.
 1658/*
 1659is_of_primitive_sort(X,Y) :-
 1660    objectsC(Y,L),member(X,L).
 1661is_of_sort(X,Y) :-
 1662    is_of_primitive_sort(X,Y).
 1663is_of_sort(X,Y) :-
 1664    sorts(Y,SL),member(Z,SL),is_of_sort(X,Z).
 1665*/
 1666find_all_upper([],[]).
 1667find_all_upper([HVars|TV],[HSorts|TS]):-
 1668     uppersorts(HSorts,Upsorts),
 1669     member(HVars,Upsorts),
 1670     find_all_upper(TV,TS).
 1671     
 1672% find out primitive sorts of a sort.
 1673find_prim_sort(Sort,PS):-
 1674  subsorts(Sort,Subsorts),
 1675  split_prim_noprim(Subsorts,PS,NP),!.
 1676
 1677% find out the objects of a sort
 1678get_sort_objects(Sort,Objs):-
 1679   find_prim_sort(Sort,PSorts),
 1680   get_objects1(PSorts,Objls),
 1681   flatten(Objls,[],Objs),!.
 1682
 1683get_objects1([],[]):-!.
 1684get_objects1([PS1|RS],[Objls1|Objls]):-
 1685   objectsC(PS1,Objls1),
 1686   get_objects1(RS,Objls),!.
 1687
 1688% find subsorts of a sort(exclude).
 1689subsortse(Sort,Subsorts):-
 1690  subsorts(Sort,Subsorts1),
 1691  subtract(Subsorts1,[Sort],Subsorts),!.
 1692% find subsorts of a sort(include).
 1693subsorts(Sort,Subsorts):-
 1694  sort_down([Sort],[],Subsorts),!.
 1695
 1696sort_down([],Subsorts,Subsorts):-!.
 1697sort_down([HOpen|TOpen],List,Subsorts):-
 1698  objectsC(HOpen,Objls),
 1699  append_dcut(List,[HOpen],List1),
 1700  sort_down(TOpen,List1,Subsorts),!.
 1701sort_down([HOpen|TOpen],List,Sortslist):-
 1702  sorts(HOpen,Sorts),
 1703  sort_down(Sorts,List,List2),
 1704  sort_down(TOpen,[HOpen|List2],Sortslist),!.
 1705sort_down([HOpen|TOpen],List,Sortslist):-
 1706  sort_down(TOpen,List,Sortslist),!.
 1707
 1708% find uppersorts of a sort(excludes).
 1709uppersortse(Sort,Uppersorts):-
 1710  uppersorts(Sort,Uppersortsf),
 1711  subtract(Uppersortsf,[Sort],Uppersorts),!.  
 1712% find uppersorts of a sort or object(include).
 1713uppersorts(Sort,Uppersorts):-
 1714  objectsC(Sort,Objls),
 1715  sort_up(Sort,[Sort],Uppersorts),!.
 1716uppersorts(Sort,Uppersorts):-
 1717  sorts(Sort,Sortls),
 1718  sort_up(Sort,[Sort],Uppersorts),!.
 1719uppersorts(Obj,Sortls):-
 1720  objectsC(Sort,Objls),
 1721  member(Obj, Objls),
 1722  sort_up(Sort,[Sort],Sortls),!.
 1723
 1724sort_up(Sort, List,Sortslist):-
 1725  sorts(NPSort, NPSortls),
 1726  NPSort \== non_primitive_sorts,
 1727  NPSort \== primitive_sorts,
 1728  member(Sort,NPSortls),
 1729  sort_up(NPSort,[NPSort|List],Sortslist).
 1730sort_up(Sort, List,List):-!.
 1731
 1732% sametree: Sort1 and Sort2 are in same sort tree.
 1733sametree(Sort1,Sort2):-
 1734     Sort1==Sort2,!.
 1735sametree(Sort1,Sort2):-
 1736     var(Sort1),!.
 1737sametree(Sort1,Sort2):-
 1738     var(Sort2),!.
 1739sametree(Sort1,Sort2):-
 1740     uppersorts(Sort2,Sortls),
 1741     member(Sort1,Sortls),!.
 1742sametree(Sort1,Sort2):-
 1743     uppersorts(Sort1,Sortls),
 1744     member(Sort2,Sortls),!.
 1745
 1746% split a sortlist to  primitive sorts and non-primitive sorts.
 1747split_prim_noprim([],[],[]):-!.
 1748split_prim_noprim([HS|TS],[HS|TP],NP):-
 1749     objectsC(HS,Obj),
 1750     split_prim_noprim(TS,TP,NP),!.		
 1751split_prim_noprim([HS|TS],PS,[HS|NP]):-
 1752     split_prim_noprim(TS,PS,NP),!.
 1753
 1754/***************** local utils *****************/
 1755
 1756/*********** DOMAIN MODEL FUNCTIONS *****************/
 1757get_invariants(Invs) :-
 1758    atomic_invariantsC(Invs),!.
 1759
 1760rem_statics([sc(S,X,Lhs=>Rhs)|ST], [sc(S,X,LhsR=>RhsR)|STR],Rt1) :-
 1761    split_st_dy(Lhs,[],LR, [],LhsR),
 1762    split_st_dy(Rhs,[],RR,[],RhsR),
 1763    append_dcut(LR,RR,R),
 1764    rem_statics(ST, STR,Rt),
 1765    append_dcut(Rt,[is_of_sort(X,S)|R],Rt1),!.
 1766rem_statics([ss(S,X,Preds)|Post], [ss(S,X,PredR)|PostR],Rt1) :-
 1767    split_st_dy(Preds,[],R, [],PredR),
 1768    rem_statics(Post, PostR,Rt),
 1769    append_dcut(Rt,[is_of_sort(X,S)|R],Rt1),!.
 1770rem_statics([se(S,X,Preds)|Post], [se(S,X,PredR)|PostR],Rt1) :-
 1771    split_st_dy(Preds,[],R, [],PredR),
 1772    rem_statics(Post, PostR,Rt),
 1773    append_dcut(Rt,[is_of_sort(X,S)|R],Rt1),!.
 1774rem_statics([], [],[]) :-!.
 1775
 1776
 1777% ----------------------utilities---------------------
 1778
 1779% not(X):- \+X.
 1780isemptylist([]):-!.
 1781
 1782%instantiate variables
 1783/*
 1784member(X,[X|_]).
 1785member(X,[_|L]) :- member(X,L).
 1786*/
 1787
 1788member_cut(X,[X|_]) :- !.
 1789member_cut(X,[_|Y]) :- member_cut(X,Y),!.
 1790
 1791% member_e: X is the exact memeber of List
 1792member_e(X,[Y|_]):-
 1793     X==Y,!.
 1794member_e(X,[Y|L]):-
 1795     var(Y),
 1796     member_e(X,L),!.
 1797member_e(ss(Sort,Obj,SE),[ss(Sort,Obj1,SE)|_]):-
 1798     Obj==Obj1,!.
 1799member_e(se(Sort,Obj,SE),[se(Sort,Obj1,SE)|_]):-
 1800     Obj==Obj1,!.
 1801member_e(sc(Sort,Obj,SE1=>SE2),[sc(Sort,Obj1,SE1=>SE2)|_]):-
 1802     Obj==Obj1,!.
 1803member_e(X,[Y|L]):- member_e(X,L),!.
 1804
 1805
 1806% u_mem in ob_utils is SLOW!?.
 1807% this is a fast impl.
 1808u_mem_cut(_,[]):-!,fail.
 1809u_mem_cut(X,[Y|_]) :- X == Y,!.
 1810u_mem_cut(X,[_|L]) :- u_mem_cut(X,L),!.
 1811% check if object X is a member of a objects list
 1812% 1. if it is not a variable, check if it is in the list
 1813% 2. X is a variable, and the list only has one objects, make X as that obj
 1814% 3. X is a variable, but the list has more than one objects, leave X unchange
 1815obj_member(X,[X|[]]):-!. 
 1816obj_member(X,List):-     
 1817    obj_member0(X,List),!.
 1818obj_member0(X,[Y|_]):-
 1819    var(X),!.%if X is var, but Y not, the leave X as that variable
 1820obj_member0(X,[Y|_]):-
 1821    X==Y,!.
 1822obj_member0(X,[_|Y]) :- obj_member0(X,Y),!.
 1823
 1824
 1825% check if a predicate is a member of a ground predicate list,
 1826% just used in binding the predicates to a sort without instantiate it
 1827% for efficiency, instantiate the variable if the list only have one atom
 1828pred_member(X,List):-
 1829    ground(X),
 1830    member(X,List),!.
 1831pred_member(X,List):-
 1832    setof(X,member(X,List),Refined),
 1833    pred_member0(X,Refined),!.
 1834
 1835pred_member0(X,[X|[]]):-!.
 1836pred_member0(X,Y):-
 1837    pred_member1(X,Y),!.
 1838pred_member1(X,[Y|_]):-
 1839    X=..[H|XLs],
 1840    Y=..[H|YLs],
 1841    vequal(XLs,YLs),!.
 1842pred_member1(X,[_|Y]):- pred_member1(X,Y),!.
 1843
 1844statics_append([],L,L):-
 1845    statics_consist(L),!.
 1846statics_append(L,[],L):-
 1847    statics_consist(L),!.
 1848statics_append(List1,List2,L):-
 1849    statics_consist(List1),
 1850    statics_consist(List2),
 1851    statics_append1(List1,List2,[],L),
 1852    statics_consist(L),!.
 1853
 1854statics_append1([],List2,L1,L):-
 1855    append_dcut(List2,L1,L),!.
 1856statics_append1([H|List1],List2,L,Z) :-
 1857    statics_append0(H,List2,L,L1),
 1858    statics_append1(List1,List2,L1,Z),!.
 1859
 1860statics_append0(H,[],L,[H|L]):-!.
 1861statics_append0(H,[H|Z],L,L):-!.
 1862statics_append0(H,[X|Z],L1,L):-
 1863    statics_append0(H,Z,L1,L),!.
 1864
 1865append_dcut([],L,L):-!.
 1866append_dcut([H|T],L,[H|Z]) :- append_dcut(T,L,Z),!.
 1867
 1868append_cut([],L,L) :- !.
 1869append_cut([H|T],L,[H|Z]) :- append_cut(T,L,Z),!.
 1870
 1871% append_st: append_dcut two statics
 1872% remove the constants that no need
 1873% instanciate the viables that all ready been bind
 1874% ------------------------------------------
 1875append_st(ST1,ST2,ST):-
 1876    append_cut(ST1,ST2,ST0),
 1877    remove_unneed(ST0,[],ST),!.
 1878
 1879% remove the constants that no need
 1880% instanciate the variables that all ready been bind
 1881remove_unneed([],C,C):-!.
 1882remove_unneed([A|B], Z, C):-
 1883    var(A),
 1884    member_e(A,Z),
 1885    remove_unneed(B, Z, C),! .
 1886remove_unneed([A|B], Z, C):-
 1887    var(A),
 1888    append_dcut(Z,[A],D),
 1889    remove_unneed(B, D, C),!.
 1890remove_unneed([A|B], Z, C):-
 1891    ground(A),
 1892    remove_unneed(B, Z, C),!.
 1893remove_unneed([A|B], Z, C):-
 1894    A=..[ne|Paras],
 1895    append_dcut(Z,[A],D),
 1896    remove_unneed(B, D, C),!.
 1897remove_unneed([A|B], Z, C):-
 1898    A=..[Pred|Paras],
 1899    same_var_member(A,Z),
 1900    remove_unneed(B, Z, C),!.
 1901remove_unneed([A|B], Z, C):-
 1902    append_dcut(Z,[A],D),
 1903    remove_unneed(B, D, C),!.
 1904
 1905same_var_member(Pred,[Pred1|List]):-
 1906     var(Pred1),
 1907     same_var_member(Pred,List),!.
 1908same_var_member(Pred,[Pred1|List]):-
 1909     Pred==Pred1,!.
 1910same_var_member(Pred,[Pred1|List]):-
 1911     Pred=..[H|T],
 1912     Pred1=..[H|T1],
 1913     same_var_member1(T,T1),!.
 1914same_var_member(Pred,[Pred1|List]):-
 1915     same_var_member(Pred,List),!.
 1916
 1917same_var_member1([],[]):-!.
 1918same_var_member1([H1|T],[H2|T]):-
 1919     var(H1),
 1920     H1==H2,!.
 1921same_var_member1([H|T1],[H|T2]):-
 1922     var(T1),
 1923     T1==T2,!.
 1924same_var_member1([H1|T1],[H2|T2]):-
 1925     H1==H2,
 1926     same_var_member1(T1,T2),!.
 1927
 1928% two states or lists are equal
 1929is_equal_list(List1,List2):-
 1930    List1==List2,!.
 1931is_equal_list([],[]):-!.
 1932is_equal_list(List1,List2):-
 1933    length(List1,L),
 1934    length(List2,L),
 1935    is_equal_list1(List1,List2),!.
 1936is_equal_list1([],[]):-!.
 1937is_equal_list1([Head1|List1],[Head2|List2]):-
 1938    Head1==Head2,
 1939    is_equal_list1(List1,List2),!.
 1940is_equal_list1([se(Sort,Obj,Head1)|List1],[se(Sort,Obj,Head2)|List2]):-
 1941    is_equal_list(Head1,Head2),
 1942    is_equal_list1(List1,List2),!.
 1943is_equal_list1([Head1|List1],[Head2|List2]):-
 1944    Head1=..[FF|Var1],
 1945    Head2=..[FF|Var2],
 1946    FF\==se,
 1947    vequal(Var1,Var2),
 1948    is_equal_list1(List1,List2),!.
 1949is_equal_list1([Head1|List1],List2):-
 1950    member(Head1,List2),
 1951    append_cut(List1,[Head1],List10),
 1952    is_equal_list1(List10,List2),!.
 1953
 1954% two states or lists are different
 1955is_diff(List1,List2):-
 1956    length(List1,L1),
 1957    length(List2,L2),
 1958    L1\==L2,!.
 1959is_diff([Head|List1],List2):-
 1960    not_exist(Head,List2),!.
 1961is_diff([Head|List1],List2):-
 1962    list_take(List2,[Head],List21),
 1963    is_diff(List1,List21),!.
 1964
 1965not_exist(Pred,List2):-
 1966    not(member(Pred,List2)),!.
 1967not_exist(se(Sort,Obj,Head1),List2):-
 1968    not(member(se(Sort,Obj,Head),List2)),!.
 1969not_exist(se(Sort,Obj,Head1),List2):-
 1970    member(se(Sort,Obj,Head2),List2),
 1971    is_diff(Head1,Head2),!.
 1972
 1973% set_append: list1 + list2 -> list
 1974% no duplicate, do instanciation
 1975% ------------------------------------------
 1976set_append([], Z, Z):-! .
 1977set_append([A|B], Z, C) :-
 1978        not(not(member(A, Z))) ,
 1979        set_append(B, Z, C),! .
 1980set_append([A|B], Z, [A|C]) :-
 1981        set_append(B, Z, C) .
 1982
 1983% set_append_e: list1 + list2 -> list
 1984% no duplicate, no instanciation
 1985% ------------------------------------------
 1986set_append_e(A,B,C):-
 1987    append_cut(A,B,D),
 1988    remove_dup(D,[],C),!.
 1989
 1990% remove duplicate
 1991remove_dup([],C,C):-!.
 1992remove_dup([A|B],Z,C) :-
 1993    member_e(A, Z),
 1994    remove_dup(B, Z, C),! .
 1995remove_dup([A|B], Z, C):-
 1996    append_dcut(Z,[A],D),
 1997    remove_dup(B, D, C),!.
 1998
 1999% two atom lists equals (without instantiate variables)
 2000vequal([],[]):-!.
 2001vequal([X|XLs],[Y|YLs]):-
 2002    X==Y,	
 2003    vequal(XLs,YLs),!.
 2004vequal([X|XLs],[Y|YLs]):-
 2005    var(X),
 2006    vequal(XLs,YLs),!.
 2007vequal([X|XLs],[Y|YLs]):-
 2008    var(Y),
 2009    vequal(XLs,YLs),!.
 2010
 2011
 2012% subtract(A,B,C): subtract B from A
 2013% -------------------------------------
 2014subtract([],_,[]):-!.
 2015subtract([A|B],C,D) :-
 2016        member(A,C),
 2017        subtract(B,C,D),!.
 2018subtract([A|B],C,[A|D]) :-
 2019        subtract(B,C,D),!.
 2020
 2021/* arg1 - arg2 = arg3 */
 2022
 2023list_take(R,[E|R1],R2):-
 2024        remove_el(R,E,RR),
 2025        list_take(RR,R1,R2),!.
 2026list_take(R,[_|R1],R2):-
 2027        list_take(R,R1,R2),!.
 2028list_take(A,[],A) :- !.
 2029
 2030% remove_el: list * el -> list-el 
 2031% ----------------------------------
 2032remove_el([],_,[]) :- ! .
 2033remove_el([A|B],A,B) :- ! .
 2034remove_el([A|B],C,[A|D]) :-
 2035        remove_el(B,C,D) .
 2036
 2037/* generate symbol predicate  (from file futile)*/
 2038
 2039gensym(Root,Atom) :-
 2040                        getnum(Root,Num),
 2041                        name(Root,Name1),
 2042                        name(Num,Name2),
 2043                        append_dcut(Name1,Name2,Name),
 2044                        name(Atom,Name).
 2045
 2046getnum(Root,Num) :-
 2047                        retract(current_num(Root,Num1)),!,
 2048                        Num is Num1+1,
 2049                        asserta(current_num(Root,Num)).
 2050
 2051getnum(Root,1) :- asserta(current_num(Root,1)).
 2052
 2053gensym_num(Root,Num,Atom):-
 2054     name(Root,Name),
 2055     name(Num,Name1),
 2056     append_dcut(Name,Name1,Name2),
 2057     name(Atom,Name2),!.
 2058
 2059
 2060pprint([],SIZE,SIZE):-!.
 2061pprint([HS|TS],Size0,SIZE):-
 2062    list(HS),
 2063    pprint(HS,Size0,Size1),
 2064    pprint(TS,Size1,SIZE),!.
 2065pprint([HS|TS],Size0,SIZE):-
 2066%    write('step '),write(Size0),write(': '),
 2067%    write(HS),nl,
 2068    Size1 is Size0+1,
 2069    pprint(TS,Size1,SIZE),!.
 2070
 2071/* split static and dynamic from states*/
 2072
 2073split_st_dy([],ST,ST,DY,DY):-!.
 2074split_st_dy([Pred|TStates],ST0,ST,DY0,DY):-
 2075  is_statics(Pred),
 2076  append_cut(ST0,[Pred],ST1),
 2077  split_st_dy(TStates,ST1,ST,DY0,DY),!.
 2078split_st_dy([Pred|TStates],ST0,ST,DY0,DY):-
 2079  append_cut(DY0,[Pred],DY1),
 2080  split_st_dy(TStates,ST0,ST,DY1,DY),!.
 2081
 2082% list of lists -> list
 2083
 2084flatten([HO|TO], List, O_List):-
 2085	append_dcut(HO, List, List_tmp),
 2086	flatten(TO, List_tmp, O_List),!.
 2087flatten([H|TO], List,O_List):-
 2088	append_dcut([H], List, List_tmp),
 2089	flatten(TO, List_tmp, O_List).
 2090flatten([], [HList|T], O_List):-
 2091	HList = [],
 2092	flatten(T, [], O_List).
 2093flatten([], [HList|T], O_List):-
 2094	list(HList),
 2095	flatten([HList|T],[], O_List),!.
 2096flatten([], L,L):-!.
 2097
 2098% flatten with no duplicate
 2099set_flatten([HO|TO], List, O_List):-
 2100	set_append_e(HO, List, List_tmp),
 2101	set_flatten(TO, List_tmp, O_List),!.
 2102set_flatten([H|TO], List,O_List):-
 2103	set_append_e([H], List, List_tmp),
 2104	set_flatten(TO, List_tmp, O_List).
 2105set_flatten([], [HList|T], O_List):-
 2106	HList = [],
 2107	set_flatten(T, [], O_List).
 2108set_flatten([], [HList|T], O_List):-
 2109	list(HList),
 2110	set_flatten([HList|T],[], O_List),!.
 2111set_flatten([], L,L):-!.
 2112
 2113
 2114% list: [el1,el2, ...] --> bool
 2115% -----------------------------
 2116list(A) :-
 2117        var(A) ,
 2118        ! ,
 2119        fail .
 2120list(A) :-
 2121        functor(A,'.',_).
 2122
 2123reverse(L,RL) :-
 2124	revSlave(L,[],RL).
 2125
 2126revSlave([],RL,RL).
 2127revSlave([H|T],Sofar,Final) :-
 2128	revSlave(T,[H|Sofar],Final).
 2129
 2130% ***********************for multy tasks*****************
 2131:- assert(time_taken(0)). 2132:- assert(soln_size(0)). 2133
 2134solve(N,FN):-
 2135   N < FN,
 2136   nl,write('task '), write(N),write(': '),nl,
 2137   solve(N),
 2138   Ni is N+1,
 2139   solve(Ni,FN).
 2140solve(FN,FN):-
 2141   nl,write('task '), write(FN),write(': '),nl,
 2142   solve(FN),
 2143   retractall(sum(_)),
 2144   assert(sum(0)),
 2145   sum_time(CP),
 2146   retractall(sum(_)),
 2147   assert(sum(0)),
 2148   sum_size(SIZE),
 2149   TIM is CP /1000,
 2150   retractall(time_taken(_)),
 2151   retractall(soln_size(_)),
 2152   nl,write('total time '),write(TIM),write(' seconds'),
 2153   nl,write('total size '),write(SIZE),nl.
 2154solve(N,N).
 2155
 2156sum_time(TIM):-
 2157   time_taken(CP),
 2158   retract(sum(N)),
 2159   N1 is N +CP,
 2160   assert(sum(N1)),
 2161   fail.
 2162sum_time(TIM):-
 2163   sum(TIM).
 2164sum_size(SIZE):-
 2165   soln_size(S),
 2166   retract(sum(N)),
 2167   N1 is N +S,
 2168   assert(sum(N1)),
 2169   fail.
 2170sum_size(SIZE):-
 2171   sum(SIZE).
 2172
 2173stoppoint.
 2174% State1 has relation with State2
 2175state_related(Post,Cond,undefd):-!.
 2176state_related(Post,Cond,[]):-!.
 2177state_related(Post,Cond,State2):-
 2178     append_cut(Post,Cond,State1),
 2179     state_related(State1,State2).
 2180
 2181% all states in necc are primitive
 2182% so does the goal state--State2
 2183state_related([se(Sort,Obj,SE1)|State1],State2):-
 2184     member(se(Sort,Obj,SE2),State2),
 2185     state_related0(SE1,SE2).
 2186% states in Cond are not neccessary primitive
 2187state_related([sc(Sort1,Obj,SE1=>SS1)|State1],State2):-
 2188     member(se(Sort,Obj,SE2),State2),
 2189     is_of_sort(Obj,Sort1),
 2190     is_of_sort(Obj,Sort).
 2191state_related([se(Sort,Obj,SE)|State1],State2):-
 2192     state_related(State1,State2),!.
 2193state_related([sc(Sort,Obj,SE=>SS)|State1],State2):-
 2194     state_related(State1,State2),!.
 2195
 2196%instatiate abit the variables
 2197state_related0([],SE2):-!.
 2198state_related0([Head|SE1],SE2):-
 2199     member(Head,SE2),
 2200     state_related0(SE1,SE2).
 2201state_related0([Head|SE1],SE2):-
 2202     state_related0(SE1,SE2).
 2203
 2204% change_obj_list: narrow down objects
 2205% by just using the objects occure in initial states(world state)
 2206change_obj_list(I):-
 2207    find_dynamic_objects(I),
 2208    collect_dynamic_obj,
 2209    change_obj_list1,
 2210    change_atomic_inv,!.
 2211
 2212change_obj_list1:-
 2213    objects(Sort,OBjls),
 2214    change_obj_list2(Sort),
 2215    fail.
 2216change_obj_list1.
 2217
 2218% only keep the dynamic objects that used in tasks
 2219change_obj_list2(Sort):-
 2220    objectsC(Sort,Objls),!.
 2221% statics objects: keep
 2222change_obj_list2(Sort):-
 2223    objects(Sort,Objls),
 2224    assert(objectsC(Sort,Objls)),!.
 2225
 2226% only keep the dynamic objects in atomic_invariants
 2227change_atomic_inv:-
 2228    atomic_invariants(Atom),
 2229    change_atomic_inv1(Atom,Atom1),
 2230    assert(atomic_invariantsC(Atom1)),!.
 2231change_atomic_inv.
 2232
 2233change_atomic_inv1([],[]).
 2234change_atomic_inv1([Pred|Atom],[Pred|Atom1]):-
 2235    Pred=..[Name|Objs],
 2236    just_dynamic_objects(Objs),
 2237    change_atomic_inv1(Atom,Atom1).
 2238change_atomic_inv1([Pred|Atom],Atom1):-
 2239    change_atomic_inv1(Atom,Atom1).
 2240
 2241just_dynamic_objects([]).
 2242just_dynamic_objects([Head|Objs]):-
 2243    objectsC(Sort,Objls),
 2244    member(Head,Objls),!,
 2245    just_dynamic_objects(Objs).
 2246
 2247find_dynamic_objects([]):-!.
 2248find_dynamic_objects([SE|Rest]):-
 2249    find_dynamic_objects(SE),
 2250    find_dynamic_objects(Rest),!.
 2251find_dynamic_objects(ss(Sort,Obj,_)):-
 2252    assert(objectsD(Sort,Obj)),!.
 2253
 2254collect_dynamic_obj:-
 2255    objectsD(Sort,_),
 2256    setof(Obj, objectsD(Sort,Obj), Objls),
 2257    retractall(objectsD(Sort,_)),
 2258    assert(objectsC(Sort,Objls)),
 2259    fail.
 2260collect_dynamic_obj.
 2261
 2262get_preconditions_g([],Prev,Prev,Prev):-!.
 2263get_preconditions_g([sc(S,X,From =>To)|Rest],Prev,[se(S,X,From)|Pre],[se(S,X,To)|Post]):-
 2264     !,
 2265     get_preconditions_g(Rest,Prev, Pre,Post).
 2266
 2267% ********************************************************************
 2268% ground all operators% enumerateOps
 2269
 2270ground_op :-
 2271	assert_sort_objects,
 2272	enumerateOps,
 2273	instOps,
 2274	opCounter(Top),
 2275	write(Top),nl.
 2276
 2277enumerateOps :-
 2278	retractall(opCounter),
 2279	assert(opCounter(1)),
 2280	enumOps.
 2281
 2282enumOps :-
 2283	operator(Name,Prev,Nec,Cond),
 2284	retract(opCounter(Count)),
 2285	containsInvars(operator(Name,Prev,Nec,Cond),InVars,IsOfSorts,FPrev,FNec), 
 2286						%Find the atomic_invariants
 2287	findVarsAndTypes(operator(Name,Prev,Nec,Cond),VT,NEs),
 2288	assert(opParent(Count,operator(Name,FPrev,FNec,Cond),VT,NEs,InVars,IsOfSorts)),
 2289	Next is Count + 1,
 2290	assert(opCounter(Next)),
 2291	fail.
 2292
 2293enumOps.
 2294
 2295
 2296% *********************************************************************
 2297% findVarsAndTypes - collect a list of all variables and their
 2298%                    types as they occur in an operator
 2299%                    also collect the list of "ne" constraints
 2300%                    that apply to variables
 2301%                    [<Type>,<Variable>|<Rest>]
 2302%
 2303% findVarsAndTypes(+Operator,-TypeVarList,-Nes)
 2304
 2305
 2306findVarsAndTypes(operator(_,Pre,Nec,Cond),Vars,NEs) :-
 2307	vtPrevail(Pre,PreVars,PreNEs),
 2308	vtEffects(Nec,NecVars,NecNEs),
 2309	append_dcut(PreVars,NecVars,Vars),
 2310	append_dcut(PreNEs,NecNEs,NEs),
 2311	!.
 2312
 2313% collect all Vars and types in a changes clause
 2314%vtEffects(+EffectsClause,-VarsTypes,-NEClauses).
 2315
 2316vtEffects([],[],[]).
 2317
 2318vtEffects([sc(Type,Obj1,Preds)|Rest],VT,NEs) :-
 2319	vtPreds(Preds,Related,NEs1),
 2320	append_dcut([Type,Obj1],Related,Obj1VT),
 2321	vtEffects(Rest,RestVT,RestNEs),
 2322	append_dcut(Obj1VT,RestVT,VT),
 2323	append_dcut(NEs1,RestNEs,NEs).
 2324
 2325% collect all Vars and types in a Prevail clause
 2326%vtPrevail(+PrevailClause,-VarsTypes,-NEClauses).
 2327
 2328vtPrevail([],[],[]).
 2329
 2330vtPrevail([se(Type,Obj1,Preds)|Rest],VT,NEs) :-
 2331	vtPLst(Preds,Related,NEs1),
 2332	append_dcut([Type,Obj1],Related,Obj1VT),
 2333	vtPrevail(Rest,RestVT,RestNEs),
 2334	append_dcut(Obj1VT,RestVT,VT),
 2335	append_dcut(NEs1,RestNEs,NEs).
 2336
 2337% Deal with the change predicates in a changes clause
 2338% vtPreds(+ChangeProps,-VarsTypes,-NEClauses).
 2339
 2340vtPreds((Pre => Add),Res,NEs) :-
 2341	vtPLst(Pre,VTPre,NEs1),
 2342	vtPLst(Add,VTAdd,NEs2),
 2343	append_dcut(VTPre,VTAdd,Res),
 2344	append_dcut(NEs1,NEs2,NEs).
 2345
 2346% Deal with a list of literals
 2347% vtPLst(+Literals,-VarTypes,-NEClauses).
 2348
 2349vtPLst([],[],[]).
 2350
 2351vtPLst([ne(X,Y)|Rest],Res,[ne(X,Y)|RestNEs]) :-
 2352	!,
 2353	vtPLst(Rest,Res,RestNEs).
 2354
 2355vtPLst([Pred|Preds],Res,NEs) :-
 2356	functor(Pred,_,1),
 2357	!,
 2358	vtPLst(Preds,Res,NEs).
 2359
 2360vtPLst([is_of_sort(_,_)|Preds],Res,NEs) :-
 2361	!,
 2362	vtPLst(Preds,Res,NEs).
 2363
 2364% here is the hard bit, Create a dummy literal - instantiate it with
 2365% the OCL predicate list to find the types then
 2366% match up the type with the original literal variables.
 2367
 2368vtPLst([Pred|Preds],Res,NEs) :-
 2369	functor(Pred,Name,Arity),
 2370	Pred =.. [Name,Obj1|Rest],
 2371	VNeeded is Arity - 1,
 2372	createVarList(VNeeded,VN),
 2373	DummyPred =.. [Name,X|VN],
 2374	predicates(PList),
 2375	member(DummyPred,PList),
 2376	pair(VN,Rest,This),
 2377	vtPLst(Preds,RestPre,NEs),
 2378	append_dcut(This,RestPre,Res).
 2379
 2380% Create a list of new uninstantiated variables
 2381% createVarList(+NoOfVariablesNeeded, -ListOfvariables).
 2382
 2383createVarList(1,[X]) :-
 2384	!.
 2385
 2386createVarList(N,[X|Rest]) :-
 2387	Next is N - 1,
 2388	createVarList(Next,Rest).
 2389
 2390% merge the list of variables and the list of types
 2391% pair(+TypeList,+VarList,-varTypeList).
 2392
 2393pair([],[],[]).
 2394
 2395pair([Type|Types],[Var|Vars],[Type,Var|Rest]) :-
 2396	pair(Types,Vars,Rest).	
 2397
 2398
 2399
 2400% **********************************************************************
 2401% Top Level Routine to instantiate / ground operators in all legal ways
 2402%
 2403% instOps
 2404
 2405instOps :-
 2406	retractall(opCounter(_)),
 2407	assert(opCounter(1)),
 2408	opParent(No,Operator,VT,NEs,InVars,IsOfSorts),
 2409	checkIsOfSorts(IsOfSorts),
 2410	checkInVars(InVars),
 2411	chooseVals(VT,NEs,InVars,Vals),
 2412	obeysNEs(NEs),		
 2413	retract(opCounter(Count)),
 2414	operator(Name,Prev,Nec,Cond) = Operator,
 2415	filterSE(Prev,FPrev),
 2416	filterSC(Nec,FNec),
 2417	assert(gOperator(Count,No,operator(Name,FPrev,FNec,Cond))),
 2418	Next is Count + 1,
 2419	assert(opCounter(Next)),
 2420	fail.
 2421
 2422instOps.
 2423
 2424
 2425checkInVars([]):- !.
 2426checkInVars(Preds):-
 2427	atomic_invariantsC(Invars),
 2428	doCheckInvars(Preds,Invars).
 2429
 2430doCheckInvars([],_).
 2431doCheckInvars([Pred|Rest],Invars) :-
 2432	member(Pred,Invars),
 2433	doCheckInvars(Rest,Invars).
 2434
 2435checkIsOfSorts([]).
 2436checkIsOfSorts([is_of_sort(V,Sort)|Rest]) :-
 2437	objectsOfSort(Sort,Objs),
 2438	member(V,Objs),
 2439	checkIsOfSorts(Rest).
 2440	
 2441
 2442% filterSE - remove ne and is_of_sort clauses
 2443
 2444filterSE([],[]) :- !.
 2445filterSE([se(Sort,Id,Preds)|Rest],[se(Sort,Id,FPreds)|FRest]) :-
 2446	filterPreds(Preds,FPreds),!,
 2447	filterSE(Rest,FRest).
 2448
 2449% filterSC - remove ne and is_of_sort clauses
 2450
 2451filterSC([],[]) :- !.
 2452filterSC([sc(Sort,Id,(Pre => Post))|Rest],[sc(Sort,Id,(FPre => FPost))|FRest]) :-
 2453	filterPreds(Pre,FPre),
 2454	filterPreds(Post,FPost),
 2455	!,
 2456	filterSC(Rest,FRest).
 2457
 2458% FilterPreds - remove ne and is_of_sort clauses
 2459
 2460filterPreds([],[]).
 2461filterPreds([ne(_,_)|Rest],FRest) :-
 2462	!,
 2463	filterPreds(Rest,FRest).
 2464filterPreds([is_of_sort(_,_)|Rest],FRest) :-
 2465	!,
 2466	filterPreds(Rest,FRest).
 2467%filterPreds([Pred|Rest],FRest) :-
 2468%	atomic_invariantsC(Invars),
 2469%	member(Pred,Invars),
 2470%	!,
 2471%	filterPreds(Rest,FRest).
 2472filterPreds([H|T],[H|FT]) :-
 2473	filterPreds(T,FT).
 2474
 2475
 2476% Collect all possible ways of instantiating the conditional effects
 2477
 2478collectAllConds(_,_,_,_,[],[]) :- !.
 2479
 2480collectAllConds(CondVT,NEs,InVars,CondVals,Cond,_) :-
 2481	retractall(temp(_)),
 2482	chooseVals(CondVT,NEs,InVars,Vals),
 2483	assertIndivConds(Cond),
 2484	fail.
 2485
 2486collectAllConds(_,_,_,_,_,NewConds) :-
 2487	setof(Cond,temp(Cond),NewConds).
 2488
 2489assertIndivConds([]) :- !.
 2490
 2491assertIndivConds([H|T]) :-
 2492	assert(temp(H)),
 2493	assertIndivConds(T).
 2494
 2495% Find the atomic_invariants in the Operator 
 2496
 2497containsInvars(operator(Name,Prev,Nec,Cond),InVars,IsOfSorts,FPrev,FNec) :-
 2498	prevInvars(Prev,PInVars,PIsOfSorts,FPrev),
 2499	necInvars(Nec,NecInVars,NIsOfSorts,FNec),
 2500	append_dcut(NecInVars,PInVars,InVars),
 2501	append_dcut(PIsOfSorts,NIsOfSorts,IsOfSorts),
 2502	!.
 2503
 2504prevInvars([],[],[],[]).
 2505prevInvars([se(Type,Obj,Props)|Rest],InVars,IsOfSorts,[se(Type,Obj,FProps)|RFPrev]) :-
 2506	   propsInvars(Props,PInvars,PIsOfSorts,FProps),
 2507	   prevInvars(Rest,RInVars,RIsOfSorts,RFPrev),
 2508	   append_dcut(PInVars,RInVars,InVars),
 2509	   append_dcut([is_of_sort(Obj,Type)|PIsOfSorts],RIsOfSorts,IsOfSorts).
 2510
 2511necInvars([],[],[],[]).
 2512necInvars([sc(Type,Obj,(Props => Adds))|Rest],Invars,IsOfSorts,[sc(Type,Obj,(FProps => FAdds))|RFNec]) :-
 2513	   propsInvars(Props,PInvars,PIsOfSorts,FProps),
 2514	   propsInvars(Adds,AInvars,AIsOfSorts,FAdds),
 2515	   necInvars(Rest,RInvars,RIsOfSorts,RFNec),
 2516	   append_dcut(AInvars,PInvars,Temp),
 2517	   append_dcut(Temp,RInvars,Invars),
 2518	   append_dcut(PIsOfSorts,AIsOfSorts,SortsTemp),
 2519	   append_dcut([is_of_sort(Obj,Type)|SortsTemp],RIsOfSorts,IsOfSorts).
 2520
 2521propsInvars([],[],[],[]).
 2522propsInvars([Prop|Props],[Prop|Rest],IsOfSorts,FProps) :-
 2523	isInvariant(Prop),
 2524	!,
 2525	propsInvars(Props,Rest,IsOfSorts,FProps).
 2526propsInvars([is_of_sort(X,Y)|Props],InVars,[is_of_sort(X,Y)|IsOfSorts],FProps):- 
 2527	!,
 2528	propsInvars(Props,InVars,IsOfSorts,FProps).
 2529
 2530propsInvars([Pred|Props],Rest,IsOfSorts,[Pred|FProps]) :-
 2531	propsInvars(Props,Rest,IsOfSorts,FProps).
 2532
 2533isInvariant(Prop) :-
 2534	atomic_invariantsC(Invars),
 2535	functor(Prop,Name,Arity),
 2536	createVarList(Arity,VN),
 2537	Pred =.. [Name | VN],
 2538	member(Pred,Invars).
 2539
 2540% Select values for the variables in the operator
 2541%
 2542% chooseVals(+TypeVarList,+NEList,+Invariants,-VarValueList)
 2543
 2544chooseVals([],_,_,[]).
 2545
 2546chooseVals([Type,Var|TypeVars],NEs,InVars,Vals) :-
 2547	ground(Var),
 2548	!,
 2549	chooseVals(TypeVars,NEs,InVars,Vals).
 2550
 2551chooseVals([Type,Var|TypeVars],NEs,InVars,[Var|Vals]) :-
 2552	objectsOfSort(Type,AllVals),
 2553	member(Var,AllVals),
 2554	chooseVals(TypeVars,NEs,InVars,Vals).
 2561assert_sort_objects :-
 2562	objectsC(Type,Objects),
 2563	assert(objectsOfSort(Type,Objects)),
 2564	fail.
 2565
 2566assert_sort_objects :-
 2567	sorts(Type,SubTypes),
 2568	Type \== primitive_sorts,
 2569	Type \== non_primitive_sorts,
 2570	all_objects(Type,Objs),
 2571	assert(objectsOfSort(Type,Objs)),
 2572	fail.
 2573
 2574assert_sort_objects.
 2575
 2576all_objects(Type,Objs) :-
 2577	objectsC(Type,Objs),
 2578	!.
 2579all_objects(Type,Objs) :-
 2580	sorts(Type,SubSorts),
 2581	!,
 2582	collect_subsort_objects(SubSorts,Objs).
 2583
 2584collect_subsort_objects([],[]).
 2585collect_subsort_objects([Sort|Rest],Objs ) :-
 2586	all_objects(Sort,SortObjs),
 2587	!,
 2588	collect_subsort_objects(Rest,RestObjs),
 2589	append_dcut(SortObjs,RestObjs,Objs).
 2590
 2591obeysNEs([]).
 2592
 2593obeysNEs([ne(V1,V2)|Rest]) :-
 2594	V1 \== V2,
 2595	obeysNEs(Rest).
 2596
 2597obeysInVars([]).
 2598obeysInVars([Prop|Rest]) :-
 2599	atomic_invariantsC(Invars),
 2600	member(Prop,Invars),
 2601	!.
 2602
 2603% **********************************************************************
 2604% prettyPrinting Routines for ground OCL operators 
 2605% long and boring
 2606
 2607
 2608% prettyPrintOp(+<Ground Operator>)
 2609
 2610prettyPrintOp(gOperator(No,Par,Op)) :-
 2611	write('gOperator('),
 2612	write(No),write(','),
 2613	write(Par),write(','),nl,
 2614	writeOp(4,Op),
 2615	!.
 2616
 2617writeOp(TabVal,operator(Name,Prev,Nec,Cond)) :-
 2618	tab(TabVal),
 2619	write('operator('),write(Name),write(','),nl,
 2620	tab(8),write('% Prevail'),nl,
 2621        tab(8),write('['),nl,
 2622        writePrevailLists(8,Prev),
 2623	tab(8),write('],'),nl,
 2624	tab(8),write('% Necessary'),nl,
 2625        tab(8),write('['),nl,
 2626	writeChangeLists(10,Nec),
 2627	tab(8),write('],'),nl,
 2628	tab(8),write('% Conditional'),nl,
 2629        tab(8),write('['),nl,
 2630	writeChangeLists(10,Cond),
 2631	tab(8),write('])).'),nl.
 2632	
 2633writePropList(TabVal,[]) :-
 2634	tab(TabVal),
 2635	write('[]').
 2636
 2637writePropList(TabVal,[ne(_,_)|Props]) :-
 2638	!,
 2639	writePropList(Indent,Props).
 2640
 2641writePropList(TabVal,[Prop|Props]) :-
 2642	atomic_invariantsC(Invars),
 2643	member(Prop,Invars),
 2644	writePropList(TabVal,Props).
 2645
 2646writePropList(TabVal,[Prop|Props]) :-
 2647	tab(TabVal),
 2648	write('['),
 2649	write(Prop),
 2650	Indent is TabVal + 1,
 2651	writePList(Indent,Props).
 2652
 2653writePList(TabVal,[]) :-
 2654	nl,
 2655	tab(TabVal),
 2656	write(']').
 2657
 2658writePList(TabVal,[ne(_,_)]) :-
 2659	!,
 2660	nl,
 2661	tab(TabVal),
 2662	write(']').
 2663
 2664writePList(TabVal,[Prop]) :-
 2665	atomic_invariantsC(Invars),
 2666	member(Prop,Invars),
 2667	!,
 2668	nl,
 2669	tab(TabVal),
 2670	write(']').
 2671
 2672writePList(TabVal,[Prop]) :-
 2673	write(','),
 2674	nl,
 2675	tab(TabVal),
 2676	write(Prop),
 2677	write(']').
 2678
 2679writePList(TabVal,[ne(_,_),P2|Rest]) :-
 2680	!,
 2681	writePList(TabVal,[P2|Rest]).
 2682
 2683writePList(TabVal,[Prop,P2|Rest]) :-
 2684	atomic_invariantsC(Invars),
 2685	member(Prop,Invars),
 2686	!,
 2687	writePList(TabVal,[P2|Rest]).
 2688
 2689writePList(TabVal,[P1,P2|Rest]) :-
 2690	write(','),
 2691	nl,
 2692	tab(TabVal),
 2693	write(P1),
 2694	writePList(TabVal,[P2|Rest]).
 2695
 2696writeChangeLists(_,[]).
 2697
 2698writeChangeLists(TabVal,[sc(Type,Obj,(Req => Add))|Rest]) :-
 2699	tab(TabVal),
 2700	write('sc('),write(Type),write(','),write(Obj),write(',('),nl,
 2701	Indent is TabVal + 12,
 2702	writePropList(Indent,Req),
 2703	nl,
 2704	tab(Indent),
 2705	write('=>'),
 2706	nl,
 2707	writePropList(Indent,Add),
 2708	write('))'),writeComma(Rest),
 2709	nl,
 2710	writeChangeLists(TabVal,Rest).
 2711
 2712writeComma([]).
 2713writeComma(_) :-
 2714	write(',').
 2715
 2716writePrevailLists(_,[]).
 2717
 2718writePrevailLists(TabVal,[se(Type,Obj,Props)|Rest]) :-
 2719	tab(TabVal),
 2720	write('se('),write(Type),write(','),write(Obj),write(','),nl,
 2721	Indent is TabVal + 12,
 2722	writePropList(Indent,Props),
 2723	write(')'),writeComma(Rest),
 2724	nl,
 2725	writePrevailLists(TabVal,Rest).
 2726
 2727
 2728assert_is_of_sort :-
 2729	objectsOfSort(Type,Objects),
 2730	member(Obj,Objects),
 2731	assert_is_of_sort1(Type,Obj),
 2732	fail.
 2733assert_is_of_sort :-
 2734	objectsC(Type,Objects),
 2735	member(Obj,Objects),
 2736	assert_is_of_primitive_sort(Type,Obj),
 2737	fail.
 2738assert_is_of_sort.
 2739
 2740assert_is_of_sort1(Type,Obj):-
 2741	assert(is_of_sort(Obj,Type)),!.
 2742assert_is_of_primitive_sort(Type,Obj):-
 2743	assert(is_of_primitive_sort(Obj,Type)),!.
 2744
 2745% change substate_class to primary sort level
 2746% assert in prolog database as gsubstate_class(Sort,Obj,States)
 2747prim_substate_class:-
 2748     substate_classes(Sort,Obj,Substate),
 2749     find_prim_sort(Sort,PS),
 2750     assert_subclass(PS,Obj,Substate),
 2751     fail.
 2752prim_substate_class:-
 2753     collect_prim_substates.
 2754
 2755assert_subclass([],Obj,Substate).
 2756assert_subclass([HS|TS],Obj,Substate):-
 2757     assert(gsstates(HS,Obj,Substate)),
 2758     assert_subclass(TS,Obj,Substate).
 2759
 2760collect_prim_substates:-
 2761     gsstates(Sort,Obj,_),
 2762     setof(SStates,gsstates(Sort,Obj,SStates),GSStates),
 2763     retractall(gsstates(Sort,Obj,_)),
 2764     all_combined(GSStates,GSStates0),
 2765     assert(gsubstate_classes(Sort,Obj,GSStates0)),
 2766     fail.
 2767collect_prim_substates.
 2768
 2769all_combined(SStates,CSStates):-
 2770     xprod(SStates,CSStates1),
 2771     flat_interal(CSStates1,CSStates),!.
 2772
 2773flat_interal([],[]):-!.
 2774flat_interal([HSS1|TSS1],[HSS|TSS]):-
 2775     flatten(HSS1,[],HSS),
 2776     flat_interal(TSS1,TSS),!.
 2777
 2778% xprod: list * list --> (list X list)
 2779% -----------------------------------
 2780xprod(A,B,C) :-
 2781        xprod([A,B],C) .
 2782 
 2783xprod([],[]).
 2784xprod(A,E) :-
 2785        xprod(A,B,C,D) ,
 2786        F =..[^,C,D] ,
 2787        call(setof(B,F,E)) .
 2788 
 2789xprod([X],[A],A,member(A,X)) .
 2790xprod([X,Y],[A,B],C,(D,E)) :-
 2791        C =..[^,A,B] ,
 2792        D =..[member,A,X] ,
 2793        E =..[member,B,Y] .
 2794xprod([X|Y],[A|E],D,(F,G)) :-
 2795        D =..[^,A,C] ,
 2796        F =..[member,A,X] ,
 2797        xprod(Y,E,C,G).
 2798
 2799
 2800:-retractall(solution_file(_)). 2801:-asserta(solution_file(user)). 2802
 2803% :-sleep(1).
 2804% :-tell(user),run_header_tests.
 2805
 2806
 2807
 2808lws:- listing(ocl:[method,
 2809operator,implied_invariant,atomic_invariants,inconsistent_constraint,predicates,objects,substate_classes,sorts,domain_name,planner_task_slow,planner_task,
 2810htn_task,tp_node,tn,current_num,goal_related,goal_related_search,solved_node,closed_node,tp_goal,final_node,node,op_score,gsstates,gsubstate_classes,related_op,
 2811objectsOfSort,atomic_invariantsC,objectsD,objectsC,gOperator,operatorC,opParent,methodC,is_of_sort,is_of_primitive_sort,temp_assertIndivConds]).
 2812
 2813lws(F):-tell(F),lws,told.
 2814
 2815:-export(rr/0). 2816:-export(rr1/0). 2817rr:- test_ocl('domains_ocl/chameleonWorld.ocl').
 2818rr1:- test_ocl('domains_ocl/translog.ocl').
 2819:- fixup_exports.