def poss_or_ssa(action_str, fluent=None): #print("aaaaa",action_str) ''' #take(1,X,fun(1,2)) -> take 1,X,fun(1,2) action_name, action_args_str, nothing= parse_function(action_str) #print action_name, action_args_str # 1,X,fun(1,2) -> 1,X,fun[1_2] -> ['1', 'X', 'fun[1_2]'] -> ['1', 'X', 'fun[1_2]'] -> ['1','X','fun(1,2)'] para_list = get_paras_from_str(action_args_str) #['1','X','fun(1,2)'] -> take_1_X_fun(1,2) action_feature = action_name + '_' + '_'.join(para_list) action_feature = re.sub(r'\s+', '', action_feature) print action_feature ''' #print 'action_str,fluent', action_str, fluent axiom_name = "poss" feature = Util.generate_function_feature(action_str) #take_1_X_fun(1,2) -> function to handle this function, parameters ['X', 'fun(1,2)'] #print('feature', feature) #print('fluent', fluent) if fluent: feature = Util.generate_function_feature(fluent)+'_'+feature axiom_name = "ssa" lambda_function, para_selected_list= context_operator.find_axiom_with_feature(axiom_name, feature) #print '----', lambda_function, para_selected_list formula = lambda_function if isinstance(lambda_function, str) else lambda_function(para_selected_list) return formula
def get_smt_body(formula): #print '-----need to tans formula is:', formula formula = __logicSym_to_smtSym(formula) fluents = context_operator.get_fluents() fluent_sub = '|'.join([r"(?:(%s)\(([\w,\s]*)\))" % fun for fun in fluents]) #print fluents fluent_sub_pattern = re.compile(fluent_sub) temp_formula = "" while temp_formula != formula: temp_formula = formula #formula = fluent_sub_pattern.sub(__mrepl_fluent, formula) formula = Util.repeat_replace_inner_with_pattern( fluent_sub_pattern, __mrepl_fluent, formula) #print "repl_fluent---",formula #formula = Util.repeat_replace_inner_with_pattern(most_inner_pattern, __mrepl_no_inner_formula, formula) formula = most_inner_pattern.sub(__mrepl_no_inner_formula, formula) #print "inner_pattern---",formula formula = Util.repeat_replace_inner_with_pattern( quantifier_pattern, __mrepl_quntifier, formula) #formula = quantifier_pattern.sub(__mrepl_quntifier, formula) formula = re.sub(r'.*', __mrepl_no_inner_formula, formula) repl_list = context_operator.get_replace_list() repl_list.reverse() #print repl_list formula = Util.repeat_do_function(Util.sub_lambda_exp, repl_list, formula) #print formula context_operator.clear_replace_list() return formula
def __to_python_formula(formula): formula = Util.endecode_string(formula, encode_pair_logic[0], encode_pair_logic[1]) formula = formula.replace('=', '==') formula = Util.endecode_string(formula, encode_pair_logic[1], encode_pair_logic[0]) return formula.replace('!', ' not ').replace('&', ' and ').replace('|', ' or ')
def transform_entailment(formula): old_formula = "" while old_formula != formula: old_formula = formula formula = Util.repeat_replace_inner_with_pattern( quantifier_pattern, __mrepl_entailment_quantifier, old_formula) return Util.endecode_string(__eliminate_bracket(formula), encode_pair[1], encode_pair[0])
def __model_ssa(fluent, action_str, model): feature = Util.generate_function_feature(fluent)+'_'+Util.generate_function_feature(action_str) lambda_function, para_selected_list= context_operator.find_axiom_with_feature("ssa", feature) #print '----', lambda_function, para_selected_list formula = lambda_function if isinstance(lambda_function, str) else lambda_function(para_selected_list) #print 'ffff', formula return model_checker.sat_formula(model, formula)#eval(__replace_model(ground_formula, model))
def ____add_sort_forall(rule_list): for e, rule in enumerate(rule_list): new_formula = Util.repeat_replace_inner_with_pattern( addsort_pattern, ______mrepl_addsort_forall, rule[2]) new_formula = Util.endecode_string(new_formula, Util.encode_pair_forall[1], Util.encode_pair_forall[0]) rule_list[e] = (rule[0], rule[1], new_formula) return rule_list
def ____handle_0arity_fluents(rule_list, zero_arity_fluents): old_strs = [r'\b' + str(fluent) + r'\b' for fluent in zero_arity_fluents] replaces = [fluent + '()' for fluent in zero_arity_fluents] for e, rule in enumerate(rule_list): relations = Util.repeat_do_function(Util.sub_lambda_exp, zip(zero_arity_fluents, replaces), rule[1]) formula = Util.repeat_do_function(Util.sub_lambda_exp, zip(zero_arity_fluents, replaces), rule[2]) rule_list[e] = (rule[0], relations, formula) return rule_list
def __normalize_formula(formula): encoded_normal_str = Util.repeat_replace_inner_with_pattern(forall_pattern, __mrepl_handle_forall, formula) context_operator.use_local_dict() encoded_normal_str = __normalize_fluents(encoded_normal_str) add_formula = __get_formula_from_local_dict() #add_formula = Util.endecode_string(add_formula, Util.encode_pair[1], Util.encode_pair[0]) #--(***)--- encoded_normal_str = add_formula+ "&( " + encoded_normal_str + ")}" if add_formula!="" else encoded_normal_str normal_str = Util.endecode_string(encoded_normal_str,encode_pair_forall[1],encode_pair_forall[0]) return normal_str
def ____get_features_vars(m_str): #print '1111',m_str feature_list = list() var_list = list() names_list = list() functions = Util.get_paras_from_str(m_str) for function in functions: fun_name, fun_para, fun_value = Util.parse_relation_or_function( function) var_list += [ mvar for mvar in Util.get_paras_from_str(fun_para) + [fun_value] if Util.isVar(mvar) ] feature_list.append(Util.generate_function_feature(function)) names_list.append(fun_name) return names_list, feature_list, var_list
def __mrepl_ground(match): logical_connector = "&" if match.group('head') == 'forall' else '|' #universe = {'Int': ['1', '0', '3', '2'], '_S1': [], '_S2': ['p2', 'p1'], 'Bool': ['True', 'False']} universe, assignment, default_value = context_operator.get_current_model() vars_sorts = { elem.split(':')[0]: elem.split(':')[1] for elem in match.group('var').split(',') } var_list = vars_sorts.keys() #var_constraint_dict = __get_constraint_var_dict(var_list, match.group('body')) #vars_consts = [ (var, var_constraint_dict[var])if var in var_constraint_dict else (var, universe[sort]) for var, sort in vars_sorts.iteritems()] vars_consts = [(var, universe[sort]) for var, sort in vars_sorts.iteritems()] vars_list = [r'\b' + var + r'\b' for var in zip(*vars_consts)[0]] consts_list = list(itertools.product(*zip(*vars_consts)[1])) instances = [ Util.repeat_do_function(Util.sub_lambda_exp, zip(vars_list, list(consts)), match.group('body')) for consts in consts_list ] return "(%s)" % logical_connector.join(["(%s)" % ins for ins in instances])
def __get_ispl_formula(formula, model, fluent_tuple_list): #print formula ispl_fluent_list = ['%s%s'%(f,'_'.join(para_list)) for f, para_list, sort in fluent_tuple_list] fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list \ if f in context_operator.get_predicates()] formula = Formula.transform_entailment(formula) formula = ____add_env(formula, fluent_list) #print formula formula = Formula.grounding(formula, model) #print formula formula = ____ispl_simplify(formula, 'Environment.Action') #print formula formula = ____to_ispl_preds(formula, pred_fluent_list) #print formula #formula = ____add_env(formula, fluent_list) #print formula formula = Util.endecode_string(formula, fluent_list, ispl_fluent_list) #print formula formula = ____to_ispl_logic(formula) #print formula #print return formula
def generate_sort_from_formula(formula): #logger.debug("get sort from formula:%s\n"%formula) #print "get sort from formula:%s\n"%formula formula = Util.repeat_replace_inner_with_pattern(Util.rename_pattern, __mrepl_getsort_fol, formula) __get_sort_from_qf_formula(formula)
def poss(action_str, model): feature = Util.generate_function_feature(action_str) lambda_function, para_selected_list= context_operator.find_axiom_with_feature('poss', feature) #print '----', lambda_function, para_selected_list formula = lambda_function if isinstance(lambda_function, str) else lambda_function(para_selected_list) return model_checker.sat_formula(model, formula)
def ____get_vars_from_relations(relation_list): if relation_list == [""]: return list() var_list = list() for relation in relation_list: fun_name, fun_para, fun_value = Util.parse_relation(relation) fun_name2, fun_para2, fun_value2 = Util.parse_function(relation) if fun_name == None and fun_name2 == None: print '~~~~~~(ERROR):', relation error_message = "#Error-----when parsing str %s-----Util.parse_relation: Exist" % relation raise Exception(error_message) if fun_name == None: fun_name, fun_para, fun_value = fun_name2, fun_para2, fun_value2 var_list += [ mvar for mvar in Util.get_paras_from_str(fun_para) + [fun_value] if Util.isVar(mvar) ] return var_list
def __eliminate_bracket(formula): old_formula = "" while old_formula != formula: old_formula = formula #print '1',formula formula = Util.repeat_replace_inner_with_pattern( most_inner_pattern, ____mrepl_entailment_inner, old_formula) #print '2',formula return ____eliminate_entailment(formula)
def __get_sort_from_function(function): #print '!!!',function fun_name, fun_paras, fun_value = Util.parse_relation_or_function(function) para_list = Util.get_paras_from_str(fun_paras) #symbol_sort = [(symbol, (fun_name, pos+1)) for pos, symbol in enumerate(para_list) if not isMath(symbol)] #symbol_INT = sum([ __get_INTsymbol_from_expression(symbol) for pos, symbol in enumerate(para_list) if isMath(symbol)],[]) symbol_sort = list() equal_symbols = list() for pos, symbol in enumerate(para_list): if not isMath(symbol): symbol_sort += [(symbol.strip(), (fun_name, pos + 1))] else: symbol_INT, words = __get_INTsymbol_from_expression(symbol.strip()) symbol_sort += symbol_INT symbol_sort += [(symbol.strip(), (fun_name, pos + 1)) for symbol in words] return symbol_sort
def ____rename_rule_vars(rule_list, varlist_list): #rename free varable for e, rename_var_list in enumerate(varlist_list): #print "rename##########:", rename_var_list new_var_list = [ context_operator.get_new_var() for i in rename_var_list ] #print "new_var#########",new_var_list rename_var_list = [r'\b' + elem + r'\b' for elem in rename_var_list] temp_rule = Util.repeat_do_function( Util.sub_lambda_exp, zip(rename_var_list, new_var_list), rule_list[e][1] + "#" + rule_list[e][2]) #print "temp_rule ~~~~~~~~>:", temp_rule #print Util.rename_forall(temp_rule.split('&')[1]) rule_list[e] = (rule_list[e][0], temp_rule.split('#')[0], Util.rename_forall(temp_rule.split('#')[1])) return rule_list
def ______mrepl_addsort_forall(matched): sort_dict = context_operator.get_symbol_sorts_dict() var_list = matched.group("var").split(",") var_sort_list = [var + ":" + sort_dict[var] for var in var_list] var_sort_str = ",".join(var_sort_list) var_sort_str = matched.group( "head") + "(" + var_sort_str + ")" + matched.group('body') return Util.endecode_string(var_sort_str, Util.encode_pair_forall[0], Util.encode_pair_forall[1])
def __normalize_fluents(encoded_str): encoded_str = " "+encoded_str+" " # in order to detect fun_pre and fun_pos (sometimes fails) new_encoded_str = encoded_str while True: if context_operator.get_nregx_function_patterns() ==list(): break #for nreg_fluent_pattern in nreg_fluent_pattern_list: for nreg_fluent_pattern in context_operator.get_nregx_function_patterns(): new_encoded_str = Util.repeat_replace_inner_with_pattern(nreg_fluent_pattern, __mrepl_detect_fluent, encoded_str) encoded_str = new_encoded_str #print '---',encoded_str if new_encoded_str == encoded_str: new_encoded_str = re.sub(pattern.inner_parenth, __mrepl_encode, encoded_str) #print "replace () -> []", new_encoded_str if encoded_str == new_encoded_str: break encoded_str = new_encoded_str return Util.endecode_string(encoded_str, encode_pair[1], encode_pair[0]).strip()
def __set_default_value(logical_formula, default_value): """ set the unknown fluent not in assignment with the default value """ encode_pair_list = default_value.items() logical_formula = Util.repeat_do_function(Util.sub_lambda_exp, encode_pair_list, logical_formula) return logical_formula
def __assignment(formula, assignment): replace_list = [(r'\b%s' % (fluent.replace('(', '\(').replace(')', '\)')), str(value)) for fluent, value in assignment.iteritems()] #print replace_list while True: new_formula = Util.repeat_do_function(Util.sub_lambda_exp, replace_list, formula) if new_formula == formula: return formula else: formula = new_formula
def __mrepl_handle_forall(matched): context_operator.use_local_dict() # a dict to store { fluent: var} encoded_str = Util.endecode_string(matched.group(), encode_pair_forall[0],encode_pair_forall[1]) body_str = matched.group('body') #print "body", body_str normal_str = __normalize_fluents(body_str) #print "normal", normal_str add_formula = __get_formula_from_local_dict() #--(***)---return matched.group('head')+ '{'+ add_formula+' and '+normal_str+ '}' if add_formula!="" else encoded_str #print matched.group() #exit(0) return "%s{ %s&(%s)} }"% (matched.group('head'), add_formula, normal_str) if add_formula!="" else encoded_str
def __get_ispl_update(fluent_tuple_list, p1_action_tuple_list, p2_action_tuple_list, model): universe, assignment, default_value = model ispl_fluent_list = ['%s%s'%(f,'_'.join(para_list)) for f, para_list, sort in fluent_tuple_list] fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list] predicates = context_operator.get_predicates() fun_fluent_list = [('%s(%s)'%(f,','.join(para_list)), sort) for f, para_list, sort in fluent_tuple_list if f not in predicates] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list if f in predicates and f!='turn'] #print fun_fluent_list #print pred_fluent_list fluent_value_list = sum([list(itertools.product([fluent],universe[sort])) \ for fluent, sort in fun_fluent_list] ,[]) fluent_value_list = ['%s=%s'%(fluent,value) for fluent, value in fluent_value_list] fluent_value_list.extend(pred_fluent_list) ispl_p1_action_list = ['Player1.Action = %s%s'%(a,'_'.join(para_list)) for a, para_list in p1_action_tuple_list] p1_action_list = ['%s(%s)'%(a,','.join(para_list)) for a, para_list in p1_action_tuple_list] ispl_p2_action_list = ['Player2.Action = %s%s'%(a,'_'.join(para_list)) for a, para_list in p2_action_tuple_list] p2_action_list = ['%s(%s)'%(a,','.join(para_list)) for a, para_list in p2_action_tuple_list] action_pair_list = [(a,b) for a, b in zip(p1_action_list+p2_action_list, ispl_p1_action_list+ispl_p2_action_list)] update_pair_list = [ (a,b,c) for a, (b,c) in itertools.product(fluent_value_list, action_pair_list)] update_pair_list = [ (fluent, atomic_regress.poss_or_ssa(action, fluent), ispl_action) \ for fluent, action, ispl_action in update_pair_list] # transform (=>) to (not or) update_pair_list = [ (a, Formula.transform_entailment(b), c) for a, b, c in update_pair_list] update_pair_list = [ (a, Formula.grounding(b,model), c) for a, b, c in update_pair_list] update_pair_list = [ (a, ____ispl_simplify(b,'Player1.Action'), c) for a, b, c in update_pair_list] #update_pair_list = [ (a, b, c) for a, b, c in update_pair_list if b is not None] pred_fluent_list = ['%s(%s)'%(f,','.join(para_list)) for f, para_list, sort in fluent_tuple_list if f in predicates] # add =true to each predicates update_pair_list = [ (fluent, ____to_ispl_preds(update, pred_fluent_list), ispl_action) for fluent, update, ispl_action in update_pair_list] fun_update_pair_list = [ (fluent, update, ispl_action) for fluent, update, ispl_action in update_pair_list if fluent not in pred_fluent_list and update !='false'] pred_update_pair_list = [ (fluent, update, ispl_action) for fluent, update, ispl_action in update_pair_list if fluent in pred_fluent_list] update_list = ['%s if (%s) and %s;'%(fluent, update, ispl_action) for fluent, update, ispl_action in fun_update_pair_list ] update_list += ['%s=true if (%s) and %s;'%(fluent, update, ispl_action) for fluent, update, ispl_action in pred_update_pair_list if update !='false' ] update_list += ['%s=false if !(%s) and %s;'%(fluent, update, ispl_action) for fluent, update, ispl_action in pred_update_pair_list if update !='false' ] update_list += ['%s=false if %s;'%(fluent, ispl_action) for fluent, update, ispl_action in pred_update_pair_list if update =='false' ] update_list += turn_list #update_list = [____add_env(formula, fluent_list) for formula in update_list] update_list = [ Util.endecode_string(formula, fluent_list, ispl_fluent_list) for formula in update_list] update_list = [ ____to_ispl_logic(formula) for formula in update_list] #return '\n '.join(update_list) return update_list
def ____generate_feature_pattern(feature_list, var_list): #print feature_list, var_list feature = '_'.join(feature_list) replace_pattern_list = ['_' + mvar + '_' for mvar in var_list] #print replace_pattern_list replace_pattern_list = zip(replace_pattern_list, ['_(.+?)_'] * (len(replace_pattern_list))) #print replace_pattern_list feature = Util.repeat_do_function(Util.replace_lambda_exp, replace_pattern_list, feature).replace("pi_", "") #print "--feature for pattern--",feature,feature.replace("pi_","") context_operator.add_feature((feature_list, var_list, feature)) return re.compile(feature) #handle pi(A) which means A is variable
def __get_sort_from_qf_formula(qf_formula): expressions = re.split(r'\&|\||\=\>', qf_formula) expressions = [ Util.eliminate_unmatched(expression) for expression in expressions ] #logger.debug("get sort from expressions: %s"%expressions) #print("get sort from expressions: %s"%expressions) for expression in expressions: #logger.debug("get sort from expression: %s"%expression) #print("get sort from expression: %s"%expression) while True: expression = Util.repeat_replace_inner_with_pattern( inner_function_pattern, __mrepl_getsort_exp, expression) new_expression = re.sub(r"\((?P<exp>[^\(\)]*)\)", r"\g<exp>", expression) if new_expression == expression: break else: expression = new_expression sort_symbol_list, symbol_group = __get_sort_from_basic_expression( expression) #logger.debug("get sort from basic expression: %s result: %s %s"%(expression,sort_symbol_list,symbol_group)) context_operator.add_symbol_to_sort_list(sort_symbol_list) context_operator.add_symbols_equal_list(symbol_group)
def __grounding_conjunct(var_list, sorts, formula, universe, var_constraint_dict=None): #vars_consts = [ (var, var_constraint_dict[var]) if var in var_constraint_dict else (var, universe[sorts[e]]) for e, var in enumerate(var_list) ] #print '~~~~', var_list, sorts, formula, universe vars_consts = [(var, universe[sorts[e]]) for e, var in enumerate(var_list)] #print vars_consts consts_list = list(itertools.product(*zip(*vars_consts)[1])) #print consts_list instances = [ Util.endecode_string(formula, var_list, list(consts)) for consts in consts_list ] return '|'.join(instances)
def __pre_parse(rule_list): relation_list = ____get_relations_from_rules(rule_list) zero_arity_fluents = ____get_0arity_functions(relation_list) rule_list = ____handle_0arity_fluents(rule_list, zero_arity_fluents) relationlist_list = ____get_relationlist_list_from_rules(rule_list) varlist_list = ____get_vars_from_relationlist_list(relationlist_list) rule_list = ____rename_rule_vars(rule_list, varlist_list) #return rule_list #exit(0) context_operator.set_zero_fluent(zero_arity_fluents) #print "hello", rule_list for rule in rule_list: functions = Util.get_paras_from_str(rule[1]) [ sort_system.generate_sort_from_formula(item) for item in functions + [rule[2]] ] equal_sort_list = sort_system.discover_sorts() sort_system.generate_new_sorts(equal_sort_list) #print context_operator.get_symbol_sorts_dict() #print context_operator.get_sort_symbols_dict() #print context_operator.get_sorts() #logger.info("after detecting sort: %s\n %s\n %s\n"%(context_operator.get_symbol_sorts_dict(), context_operator.get_sort_symbols_dict(),context_operator.get_sorts()) ) #print context_operator.get_sorts() #print #print context_operator.get_symbol_sorts_dict() #print #print context_operator.get_sort_symbols_dict() rule_list = ____add_sort_forall(rule_list) #print rule_list return rule_list
def __mrepl_fluent_regress(matched): fluent_str =matched.group() #print fluent_str match_fluent_str = Util.eliminate_unmatched(fluent_str).strip() #handle regression:######### action_str = context_operator.get_global_action() #if __uneffect(match_fluent_str, action_str): # return matched.group() #regress_str = get_ssa(fluent_str,action_str) #regress_str = context_operator.get_axioms()['ssa'] #print action_str, match_fluent_str regress_str = poss_or_ssa(action_str, match_fluent_str) #print '~~~',match_fluent_str, action_str, regress_str regress_str = "(%s)"%regress_str #logger.debug("#regress fluent: %s, after regress %s" %(match_fluent_str,regress_str)) ########## encoded_fluent_str = encode_handle_fluent(regress_str) new_str = fluent_str.replace(match_fluent_str, encoded_fluent_str) return new_str
def __assignment_light(formula, assignment): #print replace_list return Util.repeat_do_function(Util.replace_lambda_exp, list(assignment.items()), formula)
def ____add_env(formula, fluent_list): new_fleunt_list = ['Environment.%s'%(fluent) for fluent in fluent_list] return Util.endecode_string(formula, fluent_list, new_fleunt_list)