From 1fa6e8fedce3f2740edd18ebd1ff38dc83177115 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 28 Jan 2022 11:12:28 -0500 Subject: [PATCH] Moving to python3 and adding a subtle fix for an FD translator corner case. --- prp-scripts/fault-tolerant-conversion.py | 108 +++++++++--------- prp-scripts/fondparser/action.py | 14 +-- prp-scripts/fondparser/formula.py | 10 +- prp-scripts/fondparser/grounder.py | 44 +++---- prp-scripts/fondparser/parser.py | 42 +++---- prp-scripts/fondparser/pddl_tree.py | 10 +- prp-scripts/fondparser/utils.py | 6 +- prp-scripts/normalizer.py | 14 +-- prp-scripts/policy_analyze.py | 139 +++++++++++------------ prp-scripts/policy_experiment.py | 42 +++---- prp-scripts/prp_api.py | 56 ++++----- prp-scripts/translate_policy.py | 18 +-- prp-scripts/validator.py | 53 +++++---- prp-scripts/validators/grendel.py | 10 +- prp-scripts/validators/prp.py | 10 +- 15 files changed, 289 insertions(+), 287 deletions(-) diff --git a/prp-scripts/fault-tolerant-conversion.py b/prp-scripts/fault-tolerant-conversion.py index 204d98777..d24dd2d24 100644 --- a/prp-scripts/fault-tolerant-conversion.py +++ b/prp-scripts/fault-tolerant-conversion.py @@ -8,39 +8,39 @@ def get_choice(query, options): not_valid = True while not_valid: - print - print query + print() + print(query) i = 1 for opt in options: - print " %d. %s" % (i, opt) + print(" %d. %s" % (i, opt)) i += 1 - answer = raw_input("? ") + answer = input("? ") try: choice = int(answer) assert 0 < choice < i not_valid = False except: - print "\nError: You must select a number between 1 and %d" % (i-1) + print("\nError: You must select a number between 1 and %d" % (i-1)) return choice - 1 def print_domain_stats(p): - print - print "Actions:\t %d" % len(p.actions) - print "Max faults:\t %d" % p.max_faults - print "1-Normative:\t %s" % str(is_normative(p)) + print() + print("Actions:\t %d" % len(p.actions)) + print("Max faults:\t %d" % p.max_faults) + print("1-Normative:\t %s" % str(is_normative(p))) def load_problem(dom_name): - print "Parsing..." + print("Parsing...") p = parser.Problem(dom_name) p.max_faults = -1 - print "Normalizing..." + print("Normalizing...") for a in p.actions: normalize(a) - print "Ready!" + print("Ready!") return p @@ -70,36 +70,36 @@ def add_fault_limit(p, max_faults): [], parser.Not([parser.Primitive(started)]), None, - parser.And(map(parser.Primitive, [started, p.faults[0]])))) + parser.And(list(map(parser.Primitive, [started, p.faults[0]]))))) def pick_faulty_outcome(p, action): - effs = filter(lambda eff: not eff.faulty, action.effect.args) + effs = [eff for eff in action.effect.args if not eff.faulty] if len(effs) < 1: - print "Error: No more normal effects to become faulty." + print("Error: No more normal effects to become faulty.") return False elif len(effs) == 1: - print "\nWarning: You are about to make the final effect faulty." + print("\nWarning: You are about to make the final effect faulty.") if 1 == get_choice('Continue?', ['Yes', 'No']): return False - print "\nYou have the following choice of outcomes:" + print("\nYou have the following choice of outcomes:") for i in range(len(effs)): - print "\n\t--- %d ---" % (i+1) - print str(effs[i]) - print + print("\n\t--- %d ---" % (i+1)) + print(str(effs[i])) + print() outcome_choice = get_choice('Which outcome?', ['' for i in range(len(effs))] + ['Cancel']) if outcome_choice == len(effs): - print "Cancelling..." + print("Cancelling...") return False eff = effs[outcome_choice] make_outcome_faulty(p, eff) - print "Done..." + print("Done...") return @@ -133,7 +133,7 @@ def is_normative(p): for a in p.actions: if isinstance(a.effect, parser.Oneof): - return 1 == len(filter(lambda eff: not eff.faulty, a.effect.args)) + return 1 == len([eff for eff in a.effect.args if not eff.faulty]) def convert(dom_name): @@ -154,65 +154,65 @@ def convert(dom_name): 'Quit']) # 8 if 0 == next_action: - print - print "Actions:" + print() + print("Actions:") for a in p.actions: - print " - %s" % a.name - print + print(" - %s" % a.name) + print() elif 1 == next_action: - print + print() if -1 != p.max_faults: - print "Error: Max faults already set (reload the domain first)" + print("Error: Max faults already set (reload the domain first)") else: - answer = raw_input("Maximum number of faults? ") + answer = input("Maximum number of faults? ") try: choice = int(answer) if choice < 1: - print "\nError: You must select a positive number for max faults." + print("\nError: You must select a positive number for max faults.") else: add_fault_limit(p, choice) except ValueError: - print "\nError: You must select a number for max faults (%s)" % str(answer) + print("\nError: You must select a number for max faults (%s)" % str(answer)) elif 2 == next_action: - print + print() if -1 == p.max_faults: - print "Error: You must first set the maximum number of faults." + print("Error: You must first set the maximum number of faults.") continue - suitable_actions = filter(action_valid, p.actions) + suitable_actions = list(filter(action_valid, p.actions)) if not suitable_actions: - print "Error: No actions available to make faulty." + print("Error: No actions available to make faulty.") continue action_choice = get_choice('Which action?', [a.name for a in suitable_actions]) action = p.actions[action_choice] if not isinstance(action.effect, parser.Oneof): - print "Error: You can only make non-deterministic effects faulty." + print("Error: You can only make non-deterministic effects faulty.") else: pick_faulty_outcome(p, action) elif 3 == next_action: - print + print() if -1 == p.max_faults: - print "Error: You must first set the maximum number of faults." + print("Error: You must first set the maximum number of faults.") continue - suitable_actions = filter(action_valid, p.actions) + suitable_actions = list(filter(action_valid, p.actions)) if not suitable_actions: - print "Error: No actions available to make faulty." + print("Error: No actions available to make faulty.") continue for act in suitable_actions: - effs = filter(lambda eff: not eff.faulty, act.effect.args) + effs = [eff for eff in act.effect.args if not eff.faulty] if len(effs) > 1: - print "\nMaking action %s faulty." % act.name - print "You have the following choice of outcomes:" + print("\nMaking action %s faulty." % act.name) + print("You have the following choice of outcomes:") for i in range(len(effs)): - print "\n\t--- %d ---" % (i+1) - print str(effs[i]) - print + print("\n\t--- %d ---" % (i+1)) + print(str(effs[i])) + print() outcome_choice = get_choice('Which is the normal (i.e., non-faulty) outcome?', ['' for i in range(len(effs))]) @@ -223,24 +223,24 @@ def convert(dom_name): elif 4 == next_action: print_domain_stats(p) elif 5 == next_action: - print "\n\n-----------------\n" + print("\n\n-----------------\n") p._export_domain(sys.stdout) - print "\n\n-----------------\n" + print("\n\n-----------------\n") elif 6 == next_action: - print - answer = raw_input("What filename would you like to use? ") + print() + answer = input("What filename would you like to use? ") p.export(answer, '') elif 7 == next_action: p = load_problem(dom_name) elif 8 == next_action: - print + print() return if __name__ == '__main__': - print + print() if len(sys.argv) != 2: - print " Usage: python %s \n" % sys.argv[0] + print(" Usage: python %s \n" % sys.argv[0]) sys.exit(1) convert(sys.argv[1]) diff --git a/prp-scripts/fondparser/action.py b/prp-scripts/fondparser/action.py index 1037b2ea5..ea630c731 100644 --- a/prp-scripts/fondparser/action.py +++ b/prp-scripts/fondparser/action.py @@ -1,5 +1,5 @@ -from formula import Formula -from predicate import Predicate +from .formula import Formula +from .predicate import Predicate class Action (object): """ @@ -124,11 +124,11 @@ def dump (self, lvl=0): lvl: Tab level """ - print "\t" * lvl + "Action %s" % self.name - print "\t" * (lvl + 1) + "Parameters: " + ", ".join([v_type + " " + v_name for v_name, v_type in self.parameters]) + print(("\t" * lvl + "Action %s" % self.name)) + print(("\t" * (lvl + 1) + "Parameters: " + ", ".join([v_type + " " + v_name for v_name, v_type in self.parameters]))) - print (lvl + 1) * "\t" + "Precondition: " + str (self.precondition) + print(((lvl + 1) * "\t" + "Precondition: " + str (self.precondition))) - print (lvl + 1) * "\t" + "Effect: " + str (self.effect) + print(((lvl + 1) * "\t" + "Effect: " + str (self.effect))) - print (lvl + 1) * "\t" + "Observe: " + str(self.observe) + print(((lvl + 1) * "\t" + "Observe: " + str(self.observe))) diff --git a/prp-scripts/fondparser/formula.py b/prp-scripts/fondparser/formula.py index 055078234..8d1fffbc5 100644 --- a/prp-scripts/fondparser/formula.py +++ b/prp-scripts/fondparser/formula.py @@ -1,5 +1,5 @@ -from predicate import Predicate +from .predicate import Predicate class Formula(object): @@ -231,8 +231,8 @@ def __init__(self, args): Inputs: args: list of formula objects """ - args = filter(lambda x: not isinstance(x, And), args) + \ - [item for andarg in filter(lambda x: isinstance(x, And), args) for item in andarg.args] + args = [x for x in args if not isinstance(x, And)] + \ + [item for andarg in [x for x in args if isinstance(x, And)] for item in andarg.args] super(And, self).__init__("and", args) @@ -432,8 +432,8 @@ def to_ground (self, fluent_dict): self.predicate.args = None if hash (self.predicate) not in fluent_dict: for p in sorted (fluent_dict.values()): - print p - print "Did not find %s" % str(self.predicate) + print(p) + print(("Did not find %s" % str(self.predicate))) self.predicate = fluent_dict[hash(self.predicate)] def __eq__ (self, f): diff --git a/prp-scripts/fondparser/grounder.py b/prp-scripts/fondparser/grounder.py index 77a7df6db..11f5acd07 100644 --- a/prp-scripts/fondparser/grounder.py +++ b/prp-scripts/fondparser/grounder.py @@ -1,7 +1,7 @@ -from parser import Problem -from action import Action -from formula import Primitive, Forall, When, And -from predicate import Predicate +from .parser import Problem +from .action import Action +from .formula import Primitive, Forall, When, And +from .predicate import Predicate import itertools @@ -98,34 +98,34 @@ def is_equal (self, p): assert isinstance (p, GroundProblem), "Must compare two ground problems" if self.objects != p.objects: - print "objects" + print("objects") return False if self.init != p.init: return False if self.goal != p.goal: - print "goal" + print("goal") return False if not all ([sa == pa for sa, pa in \ zip (sorted (list (self.operators)), \ sorted (list (p.operators)))]): - print "operators" + print("operators") return False if not all ([sp == pp for sp, pp in \ zip (sorted (list (self.fluents)), \ sorted (list (p.fluents)))]): - print "fluents" - print "*self*" - print sorted( list( self.fluents)) - print "*p*" - print sorted (list( p.fluents)) + print("fluents") + print("*self*") + print((sorted( list( self.fluents)))) + print("*p*") + print((sorted (list( p.fluents)))) return False if self.types != p.types or self.parent_types != p.parent_types: - print "types" + print("types") return False return True @@ -148,7 +148,7 @@ def _export_domain (self, fp, sp=" "): # types #TODO likely wrong, doesn't capture the type hierarchy - s = " ".join (filter(lambda t: t!= Predicate.OBJECT, self.types)) + s = " ".join ([t for t in self.types if t!= Predicate.OBJECT]) fp.write (sp + "(:types %s)%s" %(s, "\n")) # fluents (ground predicates) @@ -403,16 +403,16 @@ def dump(self): "Fluents": self.fluents } - for k, v in d.iteritems(): - print "*** %s ***" % k + for k, v in list(d.items()): + print(("*** %s ***" % k)) if k == "Operators": for op in self.operators: op.dump(lvl=1) # inherited from superclass Action elif hasattr(v, "__iter__"): for item in v: - print "\t" + str(item) + print(("\t" + str(item))) else: - print "\t" + str(v) + print(("\t" + str(v))) class Operator(Action): @@ -465,12 +465,12 @@ def dump(self, lvl=0): """ # for operators, sufficient just to print the name, because pretty self-explanatory - print "\t" * lvl + "Operator %s" % self.name + print(("\t" * lvl + "Operator %s" % self.name)) if len(self.parameters) > 0: - print "\t" * (lvl + 1) + "Parameters: " + \ - ", ".join([v_type + " " + v_name for v_name, v_type in self.parameters]) + print(("\t" * (lvl + 1) + "Parameters: " + \ + ", ".join([v_type + " " + v_name for v_name, v_type in self.parameters]))) else: - print "\t" * (lvl + 1) + "Parameters: " + print(("\t" * (lvl + 1) + "Parameters: ")) #print(lvl + 1) * "\t" + "Precondition: " + str(self.precondition) #print(lvl + 1) * "\t" + "Effect: " + str(self.effect) #print(lvl + 1) * "\t" + "Observe: " + str(self.observe) diff --git a/prp-scripts/fondparser/parser.py b/prp-scripts/fondparser/parser.py index 5fe50dd28..ea3b86bc8 100644 --- a/prp-scripts/fondparser/parser.py +++ b/prp-scripts/fondparser/parser.py @@ -1,9 +1,9 @@ from collections import OrderedDict -from formula import Formula, And, Primitive, Forall, When, Xor, Not, Oneof, Or -from action import Action -from predicate import Predicate -from pddl_tree import PDDL_Tree -from utils import PDDL_Utils +from .formula import Formula, And, Primitive, Forall, When, Xor, Not, Oneof, Or +from .action import Action +from .predicate import Predicate +from .pddl_tree import PDDL_Tree +from .utils import PDDL_Utils class Problem(object): @@ -80,7 +80,7 @@ def is_equal (self, p): """Return True iff this problem is the same as the given problem.""" assert isinstance (p, Problem), "Must be comparing two of same type" if self.objects != p.objects: - print "objects" + print("objects") return False if self.init != p.init: @@ -92,19 +92,19 @@ def is_equal (self, p): return False if self.goal != p.goal: - print "goal" + print("goal") return False if not all ([sa == pa for sa, pa in zip (self.actions, p.actions)]): - print "actions" + print("actions") return False if not all ([sp == pp for sp, pp in zip (self.predicates, p.predicates)]): - print "predicates" + print("predicates") return False if self.types != p.types or self.parent_types != p.parent_types: - print "types" + print("types") return False return True @@ -126,7 +126,7 @@ def _export_domain (self, fp, sp=" "): # types #TODO likely wrong, doesn't capture the type hierarchy - s = " ".join (filter(lambda t: t!= Predicate.OBJECT, self.types)) + s = " ".join ([t for t in self.types if t!= Predicate.OBJECT]) fp.write (sp + "(:types %s)%s" %(s, "\n")) # predicates @@ -214,24 +214,24 @@ def dump(self): d["Obj -> Type Mapping"] = self.obj_to_type #d["Type -> Obj Mapping"] = self.type_to_obj - for k, v in d.iteritems(): - print "*** %s ***" % k + for k, v in list(d.items()): + print(("*** %s ***" % k)) if isinstance(v, dict): if len(v) == 0: - print "\t" - for k, val in v.iteritems(): - print "\t%s -> %s" % (k, str(val)) + print("\t") + for k, val in list(v.items()): + print(("\t%s -> %s" % (k, str(val)))) elif hasattr(v, '__iter__'): if len(v) == 0: - print "\tNone" + print("\tNone") elif k == "Actions": for action in self.actions: action.dump(lvl=1) else: - print "\t" + "\n\t".join([str(item) for item in v]) + print(("\t" + "\n\t".join([str(item) for item in v]))) else: - print "\t" + str(v) - print "" + print(("\t" + str(v))) + print("") def _parse_domain(self, f_domain): """ @@ -282,7 +282,7 @@ def _parse_domain(self, f_domain): self.parent_types[Predicate.OBJECT] = None self.types.add(Predicate.OBJECT) self.type_to_obj[Predicate.OBJECT] = set([]) - for obj, type_list in self.obj_to_type.iteritems(): + for obj, type_list in list(self.obj_to_type.items()): type_list.add(Predicate.OBJECT) self.type_to_obj[Predicate.OBJECT].add(obj) diff --git a/prp-scripts/fondparser/pddl_tree.py b/prp-scripts/fondparser/pddl_tree.py index 07fe298a7..1b30f76f5 100644 --- a/prp-scripts/fondparser/pddl_tree.py +++ b/prp-scripts/fondparser/pddl_tree.py @@ -1,10 +1,10 @@ # my utility function -from utils import get_contents +from .utils import get_contents # related classes -from predicate import Predicate -from formula import * -from action import Action +from .predicate import Predicate +from .formula import * +from .action import Action # from stdlib import re @@ -75,7 +75,7 @@ def dump (self): def print_tree (self, lvl=0): """Print the entire tree to the console.""" - print PDDL_Tree.TAB * lvl + str(self.name) + print((PDDL_Tree.TAB * lvl + str(self.name))) for child in self.children: child.print_tree(lvl + 1) diff --git a/prp-scripts/fondparser/utils.py b/prp-scripts/fondparser/utils.py index 524859e9b..2d1f0921e 100644 --- a/prp-scripts/fondparser/utils.py +++ b/prp-scripts/fondparser/utils.py @@ -1,7 +1,7 @@ # helper classes -from action import Action -from predicate import Predicate -from formula import * +from .action import Action +from .predicate import Predicate +from .formula import * """ General purpose utilities diff --git a/prp-scripts/normalizer.py b/prp-scripts/normalizer.py index 7de0806b8..5eef33480 100644 --- a/prp-scripts/normalizer.py +++ b/prp-scripts/normalizer.py @@ -19,28 +19,28 @@ def flatten(op): def combine(eff_lists): if DEBUG: - print "\nCombining:\n%s" % '\n'.join(map(str, eff_lists)) - print "Result: %s\n" % [And(filter(lambda x: x != And([]), list(choice))) for choice in product(*eff_lists)] - return [And(filter(lambda x: x != And([]), list(choice))) for choice in product(*eff_lists)] + print("\nCombining:\n%s" % '\n'.join(map(str, eff_lists))) + print("Result: %s\n" % [And([x for x in list(choice) if x != And([])]) for choice in product(*eff_lists)]) + return [And([x for x in list(choice) if x != And([])]) for choice in product(*eff_lists)] def _flatten(eff): if DEBUG: - print "Flattening %s" % str(eff) + print("Flattening %s" % str(eff)) if isinstance(eff, And): if 0 == len(eff.args): return [eff] else: - return combine(map(_flatten, eff.args)) + return combine(list(map(_flatten, eff.args))) elif isinstance(eff, Oneof): - return list(chain(*(map(_flatten, eff.args)))) + return list(chain(*(list(map(_flatten, eff.args))))) elif isinstance(eff, When): return [When(eff.condition, res) for res in _flatten(eff.result)] else: if DEBUG: - print "Base: %s" % str(eff) + print("Base: %s" % str(eff)) return [eff] diff --git a/prp-scripts/policy_analyze.py b/prp-scripts/policy_analyze.py index 4da938888..c5d849e11 100644 --- a/prp-scripts/policy_analyze.py +++ b/prp-scripts/policy_analyze.py @@ -36,7 +36,7 @@ def filter_prp_settings(data, online_deadends, optimized_scd): - return filter(lambda x: x[5] == jiclimit and \ + return [x for x in data if x[5] == jiclimit and \ x[7] == forgetpolicy and \ x[8] == fullstate and \ x[9] == planlocal and \ @@ -46,8 +46,7 @@ def filter_prp_settings(data, x[13] == detect_deadends and \ x[14] == generalize_deadends and \ x[15] == online_deadends and \ - x[16] == optimized_scd, - data) + x[16] == optimized_scd] def average_prp_data(data): new_data = [] @@ -59,7 +58,7 @@ def average_prp_data(data): else: mapping[key] = [line] - for (dom,prob) in mapping.keys(): + for (dom,prob) in list(mapping.keys()): new_data.append([dom,prob]) for i in range(2,len(data[0])): if i in [4, len(data[0]) - 2]: @@ -78,10 +77,10 @@ def average_prp_data(data): return new_data def print_setting(s): - print "jic-limit(%s), forgetpolicy(%s), fullstate(%s),\ + print("jic-limit(%s), forgetpolicy(%s), fullstate(%s),\ \nplanlocal(%s), partial-planloca(%s), usepolicy(%s),\ \nlimit-planlocal(%s), detect-deadends(%s), generalize-deadends(%s),\ - \nonline-deadends(%s), optimized-scd(%s)" % (s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10]) + \nonline-deadends(%s), optimized-scd(%s)" % (s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10])) def do_anova(domain, dep): if 'every' == domain: @@ -107,7 +106,7 @@ def do_anova(domain, dep): else: prp_data = load_CSV("RESULTS/prp-%s-results.csv" % domain) - solved_prp_data = filter(lambda x: x[-2] == 'True', prp_data) + solved_prp_data = [x for x in prp_data if x[-2] == 'True'] anova([prp_data[0]] + solved_prp_data, ['fullstate','planlocal','usepolicy'], dependent = dep) @@ -143,19 +142,19 @@ def prp_compare_two(domain, type1, type2, name1, name2): return _prp_compare_two(domain, type1, type2, name1, name2, prp_data) def _prp_compare_two(domain, type1, type2, name1, name2, prp_data): - print "\nAnalyzing Two PRP Settings for %s:" % domain + print("\nAnalyzing Two PRP Settings for %s:" % domain) print_setting(type1) - print "\n -vs-\n" + print("\n -vs-\n") print_setting(type2) - print + print() # Load both sets prp_data1 = [prp_data[0]] + filter_prp_settings(prp_data, *type1) - solved_prp_data1 = filter(lambda x: x[-2] == 'True', prp_data1) + solved_prp_data1 = [x for x in prp_data1 if x[-2] == 'True'] solved_prp_data1 = average_prp_data(solved_prp_data1) # Filter and average based on what FIP has solved. prp_data2 = [prp_data[0]] + filter_prp_settings(prp_data, *type2) - solved_prp_data2 = filter(lambda x: x[-2] == 'True', prp_data2) + solved_prp_data2 = [x for x in prp_data2 if x[-2] == 'True'] solved_prp_data2 = average_prp_data(solved_prp_data2) # Filter and average based on what FIP has solved. prp_mapping1 = {} @@ -173,9 +172,9 @@ def _prp_compare_two(domain, type1, type2, name1, name2, prp_data): prp_solved2 = set(prp_mapping2.keys()) both_solved = prp_solved1 & prp_solved2 - print "%s Coverage: %d" % (name1, len(prp_solved1)) - print "%s Coverage: %d" % (name2, len(prp_solved2)) - print "Combined Coverage: %d" % len(both_solved) + print("%s Coverage: %d" % (name1, len(prp_solved1))) + print("%s Coverage: %d" % (name2, len(prp_solved2))) + print("Combined Coverage: %d" % len(both_solved)) time_data = [] size_data = [] @@ -187,12 +186,12 @@ def _prp_compare_two(domain, type1, type2, name1, name2, prp_data): time_data.append((float(prp_mapping1[(dom,prob)][2]), float(prp_mapping2[(dom,prob)][2]))) size_data.append((float(prp_mapping1[(dom,prob)][3]), float(prp_mapping2[(dom,prob)][3]))) - print "%s Avg time: %f" % (name1, sum([item[0] for item in time_data]) / float(len(time_data))) - print "%s Avg time: %f" % (name2, sum([item[1] for item in time_data]) / float(len(time_data))) - print "%s Total time: %f" % (name1, sum([item[0] for item in time_data])) - print "%s Total time: %f" % (name2, sum([item[1] for item in time_data])) - print "%s Avg size: %f" % (name1, sum([item[0] for item in size_data]) / float(len(size_data))) - print "%s Avg size: %f" % (name2, sum([item[1] for item in size_data]) / float(len(size_data))) + print("%s Avg time: %f" % (name1, sum([item[0] for item in time_data]) / float(len(time_data)))) + print("%s Avg time: %f" % (name2, sum([item[1] for item in time_data]) / float(len(time_data)))) + print("%s Total time: %f" % (name1, sum([item[0] for item in time_data]))) + print("%s Total time: %f" % (name2, sum([item[1] for item in time_data]))) + print("%s Avg size: %f" % (name1, sum([item[0] for item in size_data]) / float(len(size_data)))) + print("%s Avg size: %f" % (name2, sum([item[1] for item in size_data]) / float(len(size_data)))) if name1 == name2: return @@ -203,12 +202,12 @@ def _prp_compare_two(domain, type1, type2, name1, name2, prp_data): plot([item[0] for item in size_data], [item[1] for item in size_data], x_label = "%s Policy Size" % name1, y_label = "%s Policy Size" % name2, makesquare = True, x_log = True, y_log = True, col = False) - x1,y1 = create_time_profile([float(item[2]) for item in prp_mapping1.values()]) - x2,y2 = create_time_profile([float(item[2]) for item in prp_mapping2.values()]) + x1,y1 = create_time_profile([float(item[2]) for item in list(prp_mapping1.values())]) + x2,y2 = create_time_profile([float(item[2]) for item in list(prp_mapping2.values())]) plot([x1,x2], [y1,y2], x_label = "Time (s)", y_label = "Problems Solved", no_scatter = True, xyline = False, names = [name1, name2], x_log = True, col = False) - print + print() def fip_vs_prp(domain): if 'every' in domain: @@ -252,16 +251,16 @@ def fip_vs_prp(domain): fip_data = load_CSV("RESULTS/fip-%s-results.csv" % domain) prp_data = load_CSV("RESULTS/prp-%s-results.csv" % domain) - print "\nAnalyzing FIP vs PRP for %s:" % domain + print("\nAnalyzing FIP vs PRP for %s:" % domain) # Load both sets - solved_fip_data = filter(lambda x: x[-1] == '-' and x[-2] != '0', fip_data) - nosol_fip_data = filter(lambda x: x[-1] == 'N', fip_data) + solved_fip_data = [x for x in fip_data if x[-1] == '-' and x[-2] != '0'] + nosol_fip_data = [x for x in fip_data if x[-1] == 'N'] prp_data = [prp_data[0]] + filter_prp_settings(prp_data, '18000', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1') - solved_prp_data = filter(lambda x: x[-2] == 'True', prp_data) + solved_prp_data = [x for x in prp_data if x[-2] == 'True'] solved_prp_data = average_prp_data(solved_prp_data) - nosol_prp_data = filter(lambda x: x[4] == 'N' or x[-2] == 'False', prp_data) + nosol_prp_data = [x for x in prp_data if x[4] == 'N' or x[-2] == 'False'] nosol_prp_data = average_prp_data(nosol_prp_data) fip_mapping = {} @@ -279,10 +278,10 @@ def fip_vs_prp(domain): prp_solved = set(prp_mapping.keys()) both_solved = fip_solved & prp_solved - print "FIP Coverage: %d / %d" % (len(fip_solved), len(nosol_fip_data)) - print "PRP Coverage: %d / %d" % (len(prp_solved), len(nosol_prp_data)) - print "Combined Coverage: %d" % len(both_solved) - print "FIP - PRP: %s" % str(fip_solved - prp_solved) + print("FIP Coverage: %d / %d" % (len(fip_solved), len(nosol_fip_data))) + print("PRP Coverage: %d / %d" % (len(prp_solved), len(nosol_prp_data))) + print("Combined Coverage: %d" % len(both_solved)) + print("FIP - PRP: %s" % str(fip_solved - prp_solved)) all_time_data = [] time_data = [] @@ -309,7 +308,7 @@ def fip_vs_prp(domain): plot([x1,x2], [y1,y2], x_label = "Time", y_label = "Problems Solved", no_scatter = True, xyline = False, names = ["FIP", "PRP"], x_log = True, col = False) - print + print() def online_compare(domain): @@ -350,8 +349,8 @@ def online_compare(domain): ffr_data = load_CSV("RESULTS/ffr-prp-%s-results.csv" % domain) # Load both sets - solved_prp_data = filter(lambda x: x[4] == '-', prp_data) - solved_ffr_data = filter(lambda x: x[4] == '-', ffr_data) + solved_prp_data = [x for x in prp_data if x[4] == '-'] + solved_ffr_data = [x for x in ffr_data if x[4] == '-'] prp_mapping = {} ffr_mapping = {} @@ -387,20 +386,20 @@ def online_compare(domain): ffr_times.append(float(ffr_mapping[(dom,prob)][-7]) / float(ffr_mapping[(dom,prob)][6])) prp_times.append(float(prp_mapping[(dom,prob)][-7]) / float(prp_mapping[(dom,prob)][6])) - print "Online replanning for domain %s:\n" % domain - print "Total ffr successful runs: %d" % len(ffr_solved) - print "Total prp successful runs: %d" % len(prp_solved) - print "Total shared successful runs: %d\n" % len(both_solved) - print "FFR Average Actions: %f" % (sum(ffr_actions) / float(len(ffr_actions))) - print "PRP Average Actions: %f\n" % (sum(prp_actions) / float(len(prp_actions))) - print "FFR Average Replans: %f" % (sum(ffr_replans) / float(len(ffr_replans))) - print "PRP Average Replans: %f\n" % (sum(prp_replans) / float(len(prp_replans))) - print "FFR Average Success: %f" % (sum(ffr_success) / float(len(ffr_success))) - print "PRP Average Success: %f\n" % (sum(prp_success) / float(len(prp_success))) - print "FFR Total Success: %d" % int(sum(ffr_success)) - print "PRP Total Success: %d\n" % int(sum(prp_success)) - print "FFR Average Time: %f" % (sum(ffr_times) / float(len(ffr_times))) - print "PRP Average Time: %f\n" % (sum(prp_times) / float(len(prp_times))) + print("Online replanning for domain %s:\n" % domain) + print("Total ffr successful runs: %d" % len(ffr_solved)) + print("Total prp successful runs: %d" % len(prp_solved)) + print("Total shared successful runs: %d\n" % len(both_solved)) + print("FFR Average Actions: %f" % (sum(ffr_actions) / float(len(ffr_actions)))) + print("PRP Average Actions: %f\n" % (sum(prp_actions) / float(len(prp_actions)))) + print("FFR Average Replans: %f" % (sum(ffr_replans) / float(len(ffr_replans)))) + print("PRP Average Replans: %f\n" % (sum(prp_replans) / float(len(prp_replans)))) + print("FFR Average Success: %f" % (sum(ffr_success) / float(len(ffr_success)))) + print("PRP Average Success: %f\n" % (sum(prp_success) / float(len(prp_success)))) + print("FFR Total Success: %d" % int(sum(ffr_success))) + print("PRP Total Success: %d\n" % int(sum(prp_success))) + print("FFR Average Time: %f" % (sum(ffr_times) / float(len(ffr_times)))) + print("PRP Average Time: %f\n" % (sum(prp_times) / float(len(prp_times)))) return @@ -425,12 +424,12 @@ def get_score(_x, y): else: return min(x,y) / x - res1_experiments = set(map(lambda x: x.split('/')[-1], get_file_list(res1, match_list=['.csv']))) - res2_experiments = set(map(lambda x: x.split('/')[-1], get_file_list(res2, match_list=['.csv']))) + res1_experiments = set([x.split('/')[-1] for x in get_file_list(res1, match_list=['.csv'])]) + res2_experiments = set([x.split('/')[-1] for x in get_file_list(res2, match_list=['.csv'])]) shared_results = list(res1_experiments & res2_experiments) - print - print "Found %d overlapping experiments to compare." % len(shared_results) + print() + print("Found %d overlapping experiments to compare." % len(shared_results)) time_score = [0.0, 0.0] size_score = [0.0, 0.0] @@ -441,7 +440,7 @@ def get_score(_x, y): data2 = load_CSV(res2+'/'+res)[1:] if len(data1) != len(data2): - print "Error with %s experiment -- different number of data points." % res + print("Error with %s experiment -- different number of data points." % res) continue times1 = [get_time(line) for line in data1] @@ -454,8 +453,8 @@ def get_score(_x, y): size1 = sum([get_score(sizes1[i], sizes2[i]) for i in range(len(data1))]) size2 = sum([get_score(sizes2[i], sizes1[i]) for i in range(len(data1))]) - cov1 = len(filter(lambda x: x[4] == '-', data1)) - cov2 = len(filter(lambda x: x[4] == '-', data2)) + cov1 = len([x for x in data1 if x[4] == '-']) + cov2 = len([x for x in data2 if x[4] == '-']) time_score[0] += time1 time_score[1] += time2 @@ -464,16 +463,16 @@ def get_score(_x, y): coverage[0] += cov1 coverage[1] += cov2 - print "\n [ %s ]\n" % res.split('-results.csv')[0] - print " Coverage: %d -vs- %d" % (cov1, cov2) - print "Size Score: %.2f -vs- %.2f" % (size1, size2) - print "Time Score: %.2f -vs- %.2f\n" % (time1, time2) + print("\n [ %s ]\n" % res.split('-results.csv')[0]) + print(" Coverage: %d -vs- %d" % (cov1, cov2)) + print("Size Score: %.2f -vs- %.2f" % (size1, size2)) + print("Time Score: %.2f -vs- %.2f\n" % (time1, time2)) - print "\n [ OVERALL ]" - print " Coverage: %d -vs- %d" % (coverage[0], coverage[1]) - print "Size Score: %.2f -vs- %.2f" % (size_score[0], size_score[1]) - print "Time Score: %.2f -vs- %.2f" % (time_score[0], time_score[1]) - print + print("\n [ OVERALL ]") + print(" Coverage: %d -vs- %d" % (coverage[0], coverage[1])) + print("Size Score: %.2f -vs- %.2f" % (size_score[0], size_score[1])) + print("Time Score: %.2f -vs- %.2f" % (time_score[0], time_score[1])) + print() if __name__ == '__main__': @@ -481,15 +480,15 @@ def get_score(_x, y): if 'ab-compare' in flags: if '-res1' not in myargs or '-res2' not in myargs: - print "Error: Must specify two result directories:" - print USAGE_STRING + print("Error: Must specify two result directories:") + print(USAGE_STRING) os._exit(1) ab_compare(myargs['-res1'], myargs['-res2']) os._exit(1) if '-domain' not in myargs: - print "Error: Must choose a domain:" - print USAGE_STRING + print("Error: Must choose a domain:") + print(USAGE_STRING) os._exit(1) if 'fip-vs-prp' in flags: diff --git a/prp-scripts/policy_experiment.py b/prp-scripts/policy_experiment.py index 4e58e74e1..0e44aede8 100644 --- a/prp-scripts/policy_experiment.py +++ b/prp-scripts/policy_experiment.py @@ -24,7 +24,7 @@ """ if not os.path.exists('settings.py'): - print "\nNo settings detected. Creating settings.py...\n" + print("\nNo settings detected. Creating settings.py...\n") s = "TRIALS = 10\n" s += "CORES = 1\n" s += "MEM_LIMIT = 2000\n" @@ -209,7 +209,7 @@ def parse_fip(outfile): runtime = get_value(outfile, '.* ([0-9]+\.?[0-9]+) seconds searching.*', float) - policy_size = len(filter(lambda x: 'case S' in x, read_file(outfile))) + policy_size = len([x for x in read_file(outfile) if 'case S' in x]) return runtime, policy_size def check_segfault(outfile): @@ -298,7 +298,7 @@ def doit(domain, dofip = True, doprp = True, redundant = 0, prp_params = PRP_PAR def doit_fip(domain, dom_probs, exp_name = 'fip'): - print "\n\nRunning FIP experiments on domain, %s" % domain + print("\n\nRunning FIP experiments on domain, %s" % domain) fip_args = ["-o ../%s.fip -f ../%s" % (item[0], item[1]) for item in dom_probs] @@ -340,15 +340,15 @@ def doit_fip(domain, dom_probs, exp_name = 'fip'): run, size = parse_fip(result.output_file) fip_csv.append("%s,%s,%f,%d,-" % (domain, prob, run, size)) - print "\nTimed out %d times." % timeouts - print "Ran out of memory %d times." % memouts - print "Unknown error %d times." % errorouts + print("\nTimed out %d times." % timeouts) + print("Ran out of memory %d times." % memouts) + print("Unknown error %d times." % errorouts) append_file("RESULTS/%s-%s-results.csv" % (exp_name, domain), fip_csv) def doit_prp(domain, dom_probs, prp_params, exp_name = 'prp'): - print "\n\nRunning %s experiments on domain, %s" % (exp_name, domain) + print("\n\nRunning %s experiments on domain, %s" % (exp_name, domain)) prp_args = ["../%s ../%s" % (item[0], item[1]) for item in dom_probs] @@ -409,17 +409,17 @@ def doit_prp(domain, dom_probs, prp_params, exp_name = 'prp'): successful_states, replans, actions, policy_score, str(strongly_cyclic), str(succeeded))) - print "\nTimed out %d times." % timeouts - print "Ran out of memory %d times." % memouts - print "Unknown error %d times." % errorouts - print "Invalid parameter settings %d times." % parametererrors + print("\nTimed out %d times." % timeouts) + print("Ran out of memory %d times." % memouts) + print("Unknown error %d times." % errorouts) + print("Invalid parameter settings %d times." % parametererrors) append_file("RESULTS/%s-%s-results.csv" % (exp_name, domain), prp_csv) def dojic(dom, prob, max_jic): - print "Running a varied jic experiment for the following domain / problem:" - print dom - print prob + print("Running a varied jic experiment for the following domain / problem:") + print(dom) + print(prob) exp_name = "jic" domain = dom.split('/')[-2] @@ -463,8 +463,8 @@ def dojic(dom, prob, max_jic): TRIALS = int(myargs['-trials']) if '-domain' not in myargs: - print "Error: Must choose a domain:" - print USAGE_STRING + print("Error: Must choose a domain:") + print(USAGE_STRING) os._exit(1) if 'ablation' in flags: @@ -500,17 +500,17 @@ def dojic(dom, prob, max_jic): doit(myargs['-domain'], prp_params = PRP_PARAMS['best']) if 'redundant' in flags: - for i in REDUNDANT_DOMAINS[myargs['-domain']].keys(): + for i in list(REDUNDANT_DOMAINS[myargs['-domain']].keys()): doit(myargs['-domain'], redundant = i) if 'jic' in flags: if '-problem' not in myargs: - print "Error: Must choose a problem:" - print USAGE_STRING + print("Error: Must choose a problem:") + print(USAGE_STRING) os._exit(1) if '-limit' not in myargs: - print "Error: Must choose a limit:" - print USAGE_STRING + print("Error: Must choose a limit:") + print(USAGE_STRING) os._exit(1) dojic(myargs['-domain'], myargs['-problem'], int(myargs['-limit'])) diff --git a/prp-scripts/prp_api.py b/prp-scripts/prp_api.py index f73a41e26..1a688e421 100644 --- a/prp-scripts/prp_api.py +++ b/prp-scripts/prp_api.py @@ -48,7 +48,7 @@ class PRPPolicy: def __init__(self, sol): with open(sol) as f: - data = filter(lambda x: x!='', [l.strip() for l in f.readlines()]) + data = [x for x in [l.strip() for l in f.readlines()] if x!=''] self.mapping = TwoWayDict() self.policy = [] @@ -96,18 +96,18 @@ def get_action(state): def display(p): from pprint import pprint - print - print "Mapping:" + print() + print("Mapping:") pprint(p.mapping) - print - print "Policy:" + print() + print("Policy:") pprint(p.policy) - print - print "FSAP:" + print() + print("FSAP:") pprint(p.fsap) - print + print() @@ -117,7 +117,7 @@ def partial_state_clause(ps): from krrt.sat import CNF new_clauses = [] aux = '+'.join(sorted(ps)) - new_clauses.append(map(CNF.Not, ps) + [aux]) + new_clauses.append(list(map(CNF.Not, ps)) + [aux]) for f in ps: new_clauses.append([CNF.Not(aux), f]) return (aux, new_clauses) @@ -136,9 +136,9 @@ def action_circuit(p, mapfile, cnffile): CLAUSES = [] for psap in p.policy: - print CLAUSES.extend(partial_state_clause(psap[0])[1]) - print psap[1] - print + print(CLAUSES.extend(partial_state_clause(psap[0])[1])) + print(psap[1]) + print() def count_circuit(p, mapfile, cnffile, force_full=False): @@ -159,15 +159,15 @@ def fluentvar(f): if not force_full and len(p.fsap) == 0: inverted = True - CLAUSES = [map(neg, map(fluentvar, psap[0])) for psap in p.policy] + CLAUSES = [list(map(neg, list(map(fluentvar, psap[0])))) for psap in p.policy] else: inverted = False - print "Warning: Mixing FSAP and Policy leads to difficult CNF theories" + print("Warning: Mixing FSAP and Policy leads to difficult CNF theories") # For every a, a -> \/_{ in P}, ps A = set([psap[1] for psap in p.policy]) for a in A: - PS = [psap[0] for psap in filter(lambda x: x[1] == a, p.policy)] + PS = [psap[0] for psap in [x for x in p.policy if x[1] == a]] psaux = [] for ps in PS: (aux, clauses) = partial_state_clause(ps) @@ -180,46 +180,46 @@ def fluentvar(f): # To avoid projection: For every , ps->a for psap in p.policy: - CLAUSES.append([psap[1]] + map(CNF.Not, map(fluentvar, psap[0]))) + CLAUSES.append([psap[1]] + list(map(CNF.Not, list(map(fluentvar, psap[0]))))) # For every , de->!a for act in p.fsap: for de in p.fsap[act]: - CLAUSES.append(map(neg, map(fluentvar, de)) + [CNF.Not(act)]) + CLAUSES.append(list(map(neg, list(map(fluentvar, de)))) + [CNF.Not(act)]) # At least one action is applicable CLAUSES.append(set([psap[1] for psap in p.policy])) if DEBUG: - print '\n'.join(map(str, CLAUSES)) + print('\n'.join(map(str, CLAUSES))) F = CNF.Formula(CLAUSES) F.writeMapping(mapfile) F.writeCNF(cnffile) cmd = "./bin/sharpSAT %s > %s.log" % (cnffile, cnffile) - print "\nRunning sharpSAT Command: %s" % cmd - print "Solving..." + print("\nRunning sharpSAT Command: %s" % cmd) + print("Solving...") os.system(cmd) - print "Counting..." + print("Counting...") count = int(get_lines("%s.log" % cnffile, lower_bound='# solutions', upper_bound='# END')[0].strip()) if inverted: - print "Inverting..." + print("Inverting...") count = 2**len(FLUENTS) - count - print "\nStates Handled: %d\n" % count + print("\nStates Handled: %d\n" % count) #print "\nD# Command: ./dsharp -projectionViaPriority -priority %s %s\n" % \ # (','.join(map(str, sorted([F.mapping[f] for f in FLUENTS]))), cnffile) if __name__ == '__main__': if len(os.sys.argv) != 3: - print "\nError with input." - print USAGE_STRING + print("\nError with input.") + print(USAGE_STRING) os.sys.exit(1) - print "Parsing solution..." + print("Parsing solution...") p = PRPPolicy(os.sys.argv[2]) if 'display' == os.sys.argv[1]: @@ -229,6 +229,6 @@ def fluentvar(f): elif 'action-circuit' == os.sys.argv[1]: action_circuit(p, os.sys.argv[2]+'.map', os.sys.argv[2]+'.cnf') else: - print "\nError with input." - print USAGE_STRING + print("\nError with input.") + print(USAGE_STRING) os.sys.exit(1) diff --git a/prp-scripts/translate_policy.py b/prp-scripts/translate_policy.py index 493703669..aa449b063 100644 --- a/prp-scripts/translate_policy.py +++ b/prp-scripts/translate_policy.py @@ -88,23 +88,23 @@ def parse_var(lines, index): for j in range(len(vals)): mapping["%s:%s" % (name, j)] = vals[j] -print "Mapping:\n" -print '\n'.join([" %s\t<-> \t %s" % (k,mapping[k]) for k in sorted(mapping.keys())]) -print +print("Mapping:\n") +print('\n'.join([" %s\t<-> \t %s" % (k,mapping[k]) for k in sorted(mapping.keys())])) +print() def translate_lines(lines): for line in lines: if 'If' == line[:2]: - print "If holds: %s" % '/'.join([mapping[item] for item in line.split(' ')[2:]]) + print("If holds: %s" % '/'.join([mapping[item] for item in line.split(' ')[2:]])) else: - print line + print(line) -print "Policy:" +print("Policy:") policy_lines = read_file('policy.out') translate_lines(policy_lines) -print +print() -print "FSAP:" +print("FSAP:") fsap_lines = read_file('policy.fsap') translate_lines(fsap_lines) -print +print() diff --git a/prp-scripts/validator.py b/prp-scripts/validator.py index e74879392..7534bc725 100644 --- a/prp-scripts/validator.py +++ b/prp-scripts/validator.py @@ -42,8 +42,8 @@ def is_goal(self, goal): class VALAction: def __init__(self, prec, effs, name, mapping): self.name = name - self.ppres = set(filter(lambda x: x > 0, prec)) - self.npres = set([-1 * i for i in filter(lambda x: x < 0, prec)]) + self.ppres = set([x for x in prec if x > 0]) + self.npres = set([-1 * i for i in [x for x in prec if x < 0]]) self.effs = effs self.mapping = mapping @@ -56,7 +56,7 @@ def __str__(self): def validate(dfile, pfile, sol, val): - print "\nParsing the problem..." + print("\nParsing the problem...") problem = grounder.GroundProblem(dfile, pfile) @@ -98,7 +98,7 @@ def validate(dfile, pfile, sol, val): val.load(sol, fluents) - print "\nStarting the FOND simulation..." + print("\nStarting the FOND simulation...") unhandled = [] @@ -117,6 +117,13 @@ def validate(dfile, pfile, sol, val): unhandled.append(u) else: i = 0 + + # This is a fix for certain circumstances where the action name + # is changed by the FD translator to include a version at the end. + # This is a hack, but it works for now. + if a not in actions and a.split('_')[-1][0] == 'v': + a = '_'.join(a.split('_')[:-1]) + for outcome in actions[a]: v = progress(u, outcome, unfluents) @@ -136,13 +143,13 @@ def validate(dfile, pfile, sol, val): # Analyze the final controller - print "\nSimulation finished!\n" - print "\n-{ Controller Statistics }-\n" - print "\t Nodes: %d" % G.number_of_nodes() - print "\t Edges: %d" % G.number_of_edges() - print " Unhandled: %d" % len(unhandled) - print "\tStrong: %s" % str(0 == len(list(nx.simple_cycles(G)))) - print " Strong Cyclic: %s" % str(G.number_of_nodes() == len(nx.single_source_shortest_path(G.reverse(), nodes[goal_state]))) + print("\nSimulation finished!\n") + print("\n-{ Controller Statistics }-\n") + print("\t Nodes: %d" % G.number_of_nodes()) + print("\t Edges: %d" % G.number_of_edges()) + print(" Unhandled: %d" % len(unhandled)) + print("\tStrong: %s" % str(0 == len(list(nx.simple_cycles(G))))) + print(" Strong Cyclic: %s" % str(G.number_of_nodes() == len(nx.single_source_shortest_path(G.reverse(), nodes[goal_state])))) write_dot(G, 'graph.dot') @@ -152,24 +159,24 @@ def validate(dfile, pfile, sol, val): i = 0 for outcome in actions[a]: i += 1 - f.write("%d: %s\n" % (i, " / ".join(["%s -> %s" % (map(str, [unfluents[fl] for fl in c]), map(str, [unfluents[fl] for fl in e])) for (c,e) in outcome.effs]))) + f.write("%d: %s\n" % (i, " / ".join(["%s -> %s" % (list(map(str, [unfluents[fl] for fl in c])), list(map(str, [unfluents[fl] for fl in e]))) for (c,e) in outcome.effs]))) if len(unhandled) > 0: with open('unhandled.states', 'w') as f: for s in unhandled: f.write("\n%s\n" % _state_string(unfluents, s)) - print "\n Plan output: graph.dot" - print " Action mapping: action.map" + print("\n Plan output: graph.dot") + print(" Action mapping: action.map") if len(unhandled) > 0: - print "Unhandled states: unhandled.states" + print("Unhandled states: unhandled.states") - print + print() def _convert_cond_effect(mapping, eff): if isinstance(eff, And): - return [_create_cond(mapping, f) for f in filter(lambda x: '=' not in str(x), eff.args)] + return [_create_cond(mapping, f) for f in [x for x in eff.args if '=' not in str(x)]] elif isinstance(eff, Primitive) or (isinstance(eff, Not) and isinstance(eff.args[0], Primitive)): return [_create_cond(mapping, eff)] elif isinstance(eff, When): @@ -187,7 +194,7 @@ def _create_cond(mapping, eff): def _convert_conjunction(mapping, conj): if isinstance(conj, And): - return [mapping[str(f).lower()] for f in filter(lambda x: '=' not in str(x), conj.args)] + return [mapping[str(f).lower()] for f in [x for x in conj.args if '=' not in str(x)]] elif isinstance(conj, Primitive) or (isinstance(conj, Not) and isinstance(conj.args[0], Primitive)): return [mapping[str(conj).lower()]] else: @@ -207,9 +214,9 @@ def progress(s, o, m): adds = set() dels = set() for eff in o.effs: - negeff = set(filter(lambda x: x < 0, eff[0])) + negeff = set([x for x in eff[0] if x < 0]) poseff = eff[0] - negeff - negeff = set(map(lambda x: x * -1, negeff)) + negeff = set([x * -1 for x in negeff]) if (poseff <= s.fluents) and 0 == len(negeff & s.fluents): for reff in eff[1]: if reff < 0: @@ -218,7 +225,7 @@ def progress(s, o, m): adds.add(reff) if 0 != len(adds & dels): - print "Warning: Conflicting adds and deletes on action %s" % str(o) + print("Warning: Conflicting adds and deletes on action %s" % str(o)) return State(((s.fluents - dels) | adds)) @@ -227,8 +234,8 @@ def progress(s, o, m): try: (dom, prob, sol, interp) = os.sys.argv[1:] except: - print "\nError with input." - print USAGE_STRING + print("\nError with input.") + print(USAGE_STRING) os.sys.exit(1) validate(dom, prob, sol, importlib.import_module("validators.%s" % interp)) diff --git a/prp-scripts/validators/grendel.py b/prp-scripts/validators/grendel.py index d1704b22d..7e69139ea 100644 --- a/prp-scripts/validators/grendel.py +++ b/prp-scripts/validators/grendel.py @@ -12,10 +12,10 @@ def _translate_grendel_fluent(f): def load(pol, fmap): global POLICY - print "\nLoading GRENDEL policy..." + print("\nLoading GRENDEL policy...") with open(pol, 'r') as f: - file_lines = filter(lambda x: x != '', [line.rstrip("\n") for line in f.readlines()]) + file_lines = [x for x in [line.rstrip("\n") for line in f.readlines()] if x != ''] POLICY = [] @@ -26,12 +26,10 @@ def load(pol, fmap): assert ')' == file_lines.pop(0) nfluents = set([fmap[_translate_grendel_fluent(f)] for f in \ - filter(lambda x: '(not' == x[:4], \ - fluent_line.split('(and ')[-1][:-1].split('/'))]) + [x for x in fluent_line.split('(and ')[-1][:-1].split('/') if '(not' == x[:4]]]) pfluents = set([fmap[_translate_grendel_fluent(f)] for f in \ - filter(lambda x: '(not' != x[:4], \ - fluent_line.split('(and ')[-1][:-1].split('/'))]) + [x for x in fluent_line.split('(and ')[-1][:-1].split('/') if '(not' != x[:4]]]) action = action_line.split(':action ')[-1][1:-1].strip().replace(' ', '_') POLICY.append((nfluents, pfluents, action)) diff --git a/prp-scripts/validators/prp.py b/prp-scripts/validators/prp.py index e68138663..5c512062d 100644 --- a/prp-scripts/validators/prp.py +++ b/prp-scripts/validators/prp.py @@ -23,10 +23,10 @@ def load(pol, fmap): global POLICY global FSAP - print "\nLoading PRP policy..." + print("\nLoading PRP policy...") with open(pol, 'r') as f: - file_lines = filter(lambda x: x != '', [line.rstrip("\n") for line in f.readlines()]) + file_lines = [x for x in [line.rstrip("\n") for line in f.readlines()] if x != ''] POLICY = [] FSAP = {} @@ -50,11 +50,9 @@ def load(pol, fmap): continue nfluents = set([fmap[f.strip().replace(',', '')[4:-1]] for f in \ - filter(lambda x: 'not(' == x[:4], \ - fluent_line.split(':')[-1][1:].split('/'))]) + [x for x in fluent_line.split(':')[-1][1:].split('/') if 'not(' == x[:4]]]) pfluents = set([fmap[f.strip().replace(',', '')] for f in \ - filter(lambda x: ('not(' != x[:4]) and (len(x) > 0), \ - fluent_line.split(':')[-1][1:].split('/'))]) + [x for x in fluent_line.split(':')[-1][1:].split('/') if ('not(' != x[:4]) and (len(x) > 0)]]) action = file_lines.pop(0).split(':')[-1].split('/')[0][1:-1].strip().replace(' ', '_') if STAGE_POL == stage: