def parse_output_popf(file_name): from krrt.utils import match_value, read_file popf_lines = read_file(file_name) assert '; Plan found with metric' in popf_lines[0] assert '; States evaluated' in popf_lines[1] assert '; Time' in popf_lines[2] # Get the plan lines popf_actions = popf_lines[3:] time_slots = [popf_actions[0].split(':')[0]] for act in popf_actions: if time_slots[-1] != act.split(':')[0]: time_slots.append(act.split(':')[0]) layered_solution = [] for time in time_slots: actions = filter(lambda x: x.split(':')[0] == time, popf_actions) layered_solution.append([]) for act in actions: action_line = act.split('(')[1].split(')')[0] layered_solution[-1].append(Action(action_line)) return layered_solution
def convert_PRE(input, output): def cpyrtn(old, new): new.append(old[0]) return old.pop(0) old_lines = read_file(input) new_lines = [] #-- Pop the top MPT flag old_lines.pop(0) #-- Convert the operators back to normal form #- Find the operator section while 'end_goal' != old_lines[0]: new_lines.append(old_lines.pop(0)) new_lines.append(old_lines.pop(0)) #- Get the number of operators num_ops = int(old_lines.pop(0)) new_lines.append(str(num_ops)) for op_num in range(num_ops): assert('begin_operator' == cpyrtn(old_lines, new_lines)) op_name = cpyrtn(old_lines, new_lines) num_prevail = int(cpyrtn(old_lines, new_lines)) for prev_num in range(num_prevail): cpyrtn(old_lines, new_lines) num_effects = int(cpyrtn(old_lines, new_lines)) for eff_num in range(num_effects): preconds = [] num_precond = old_lines.pop(0) for precond_num in range(int(num_precond)): var, val = old_lines.pop(0).split() preconds.append(var + " " + val) effect = old_lines.pop(0) new_lines.append(num_precond + " " + " ".join(preconds) + " " + effect) op_cost = int(cpyrtn(old_lines, new_lines)) assert('end_operator' == cpyrtn(old_lines, new_lines)) #-- Get rid of SG and everything after it. while 'begin_SG' != old_lines[0]: new_lines.append(old_lines.pop(0)) write_file(output, new_lines)
def doit_fip(domain, dom_probs, exp_name='fip'): 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 ] fip_results = run_experiment( base_command='./../fip', single_arguments={'domprob': fip_args}, time_limit=TIME_LIMIT, memory_limit=MEM_LIMIT, results_dir="RESULTS/%s-%s" % (exp_name, domain), progress_file=None, processors=CORES, sandbox=exp_name, clean_sandbox=True, output_file_func=( lambda res: res.single_args['domprob'].split('/')[-1] + '.out'), error_file_func=( lambda res: res.single_args['domprob'].split('/')[-1] + '.err')) timeouts = 0 memouts = 0 errorouts = 0 fip_csv = ['domain,problem,runtime,size,status'] for res_id in fip_results.get_ids(): result = fip_results[res_id] prob = result.single_args['domprob'].split(' ')[3].split('/')[-1] if match_value(result.output_file, 'No plan will solve it' ) or 'No solutions are found!' in read_file( result.output_file)[-1]: fip_csv.append("%s,%s,-1,-1,N" % (domain, prob)) else: if result.timed_out: timeouts += 1 fip_csv.append("%s,%s,-1,-1,T" % (domain, prob)) elif result.mem_out: memouts += 1 fip_csv.append("%s,%s,-1,-1,M" % (domain, prob)) elif not result.clean_run or check_segfault(result.output_file): errorouts += 1 fip_csv.append("%s,%s,-1,-1,E" % (domain, prob)) else: 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 append_file("RESULTS/%s-%s-results.csv" % (exp_name, domain), fip_csv)
def _parse_file(self, filename): #--- First and last line are useless lines = read_file(filename)[1:-1] #--- Second line is number of groups self.num_groups = int(lines.pop(0)) #--- Parse each group for i in xrange(self.num_groups): self.groups.append(self._parse_group(lines)) #--- Sanity check assert 0 == len(lines)
def parse_output_mp(file_name): from krrt.utils import read_file mp_lines = read_file(file_name) layered_solution = [] for line in mp_lines: acts = line.split(': ')[1].split() layered_solution.append( map(Action, [("%s %s" % (a.split('(')[0], ' '.join( a.split('(')[1][:-1].split(',')))).strip() for a in acts])) return layered_solution
def parseNNF(fname): lines = read_file(fname) (nNodes, nEdges, nVars) = map(int, lines.pop(0).split()[1:]) assert nNodes == len(lines) # TODO: Double check that this badlist isn't included in the final d-DNNF badlist = set() allvars = set() nodes = [] for line in lines: parts = line.split() if 'A 0' == line: nodes.append(True) elif 'O 0 0' == line: nodes.append(False) elif 'L' == parts[0]: num = int(parts[1]) lit = CNF.Variable(abs(num)) allvars.add(lit) if num < 0: lit = CNF.Not(lit) nodes.append(Lit(lit)) elif 'A' == parts[0]: nCh = int(parts[1]) children = list(map(int, parts[2:])) assert nCh == len(children), "Bad line? %s" % line assert max(children) < len(nodes) nodes.append(And([nodes[i] for i in children])) elif 'O' == parts[0]: switch = int(parts[1]) nCh = int(parts[2]) children = list(map(int, parts[3:])) assert nCh == len(children), "Bad line? %s" % line assert max(children) < len(nodes) nodes.append(Or([nodes[i] for i in children], switch)) if 0 == switch: badlist.add(len(nodes) - 1) else: assert False, "Unrecognized line: %s" % line return dDNNF(nodes[-1], allvars)
def parse_output_ipc(file_name): from krrt.utils import read_file # Check for the failed solution #if match_value(file_name, '.* No plan will solve it.*'): # print "No solution." # return None # Get the plan action_list = read_file(file_name) actions = [Action(line[1:-1].strip(' ').lower()) for line in action_list] return Plan(actions)
def test_kripke(kb, rmls): print print kb print "\nClosing...\n" kb.logically_close() print kb print "Consistent: %s" % str(kb.is_consistent()) print "\nGenerating compressed kripke..." M = kb.generate_kripke(True) print print "Generating dot export..." M.generate_dot("graph.dot", True) lines = read_file("graph.dot") lines = [lines[0], " rankdir=LR;"] + lines[1:] write_file("graph.dot", lines) os.system("dot -Tpng graph.dot > graph.png") print "\nGenerating full kripke..." M = kb.generate_kripke(False) print print M.get_stats() print for rml in rmls: print "Assessing %s: %s" % (str(rml), M.assess_rml(Belief(0, rml))) print all_match = all([M.assess_rml(rml) for rml in kb.perspectival_view()]) print "All rmls match: %s" % str(all_match) if not all_match: print "Non-matching:" for rml in kb.construct_closed_world(): if not M.assess_rml(rml): print " %s" % str(rml) print
def parse_test_pdkb(fname): lines = read_file(fname) (depth, num_ag, props) = lines.pop(0).split(' ') depth = int(depth) num_ag = int(num_ag) props = props.split(',') assert 'B' not in props, "Error: Can't use 'B' as a proposition." assert num_ag < 10, "Error: Can't use more than 10 agents." def parse_rml(s): if '!' == s[0]: return neg(parse_rml(s[1:])) elif 'B' == s[0]: return Belief(int(s[1]), parse_rml(s[2:])) elif 'P' == s[0]: return Possible(int(s[1]), parse_rml(s[2:])) else: return Literal(s) rmls = [parse_rml(l.replace(' ', '')) for l in lines[:lines.index('END')]] desc = "\n".join(lines[lines.index('END') + 1:]) if desc: print "Running test with the following description:" print "\n--------\n" print desc print "\n-----\n" kb = PDKB(depth, list(range(1, num_ag + 1)), map(Literal, props)) for rml in rmls: kb.add_rml(rml) return rmls test_kripke(kb, rmls)
def read_pdkbddl_file(fname): lines = read_file(fname) found = True count = 0 while found: count += 1 if count > 100: assert False, "Error: Already attempted at least 100 imports. Did you recursively import something?" found = False include_indices = [] for i in range(len(lines)): if lines[i].find('{include') == 0: include_indices.append(i) found = True for index in reversed(include_indices): new_file = '/'.join( fname.split('/')[:-1]) + '/' + lines[index].split(':')[1][:-1] lines = lines[:index] + read_pdkbddl_file(new_file) + lines[index + 1:] # Strip out the comments and empty lines lines = filter(lambda x: x != '', lines) lines = filter(lambda x: x[0] != ';', lines) lines = map(lambda x: x.split(';')[0], lines) # Convert the [] and <> notation to nested B's def replace_modal(left, right, sym, line): new_line = '' bracket_count = 0 negate = '' for c in line: if negate != '' and c != left: new_line += '!' negate = '' if c == left: new_line += "(%s%s{" % (negate, sym) bracket_count += 1 negate = '' elif c == right: new_line += '}' elif c == '!': negate = '!' else: new_line += c if c == ')': while bracket_count: new_line += ')' bracket_count -= 1 return new_line def replace_belief(line): return replace_modal('[', ']', 'B', line) def replace_possible(line): return replace_modal('<', '>', 'P', line) def replace_alwaysknow(line): assert '%' not in line, "Error: Custom character % must be avoided" assert '&' not in line, "Error: Custom character & must be avoided" return replace_modal('&', '%', 'AK', line.replace('{AK}', '&%')) for func in [replace_belief, replace_possible, replace_alwaysknow]: lines = map(func, lines) return lines
import os from krrt.utils import get_file_list, read_file, write_file, get_lines domains = get_file_list('.', ['fixed', 'fip'], ['d_']) print domains for dom in domains: # Fix the original domain lines = read_file(dom) fixed_dom = '.'+''.join(dom.split('.')[:-1])+'-fixed.pddl' write_file(fixed_dom, [lines[0]] + ["(:requirements :typing :strips :non-deterministic)"] + lines[1:]) # Fix the fip version preface = get_lines(dom, upper_bound = ':action') fixed_dom_fip = fixed_dom + '.fip' write_file(fixed_dom_fip, preface) print "python ../../src/translate/determinizer.py %s p_1_1.pddl >> %s" % (fixed_dom, fixed_dom_fip) os.system("python ../../src/translate/determinizer.py %s p_1_1.pddl >> %s" % (fixed_dom, fixed_dom_fip)) os.system('echo ")" >> ' + fixed_dom_fip)
SYMBOLS = ['s', 'x', 'o', '^', '>', 'v', '<', 'd', 'p', 'h', '8'] COLOURS = ['b','g','k','m'] LINES = ['-', '--', '-.', ':'] handle = ax1.plot(xs, data, c='b', ls='-') ax1.set_title(title) if logplot: ax1.set_yscale('log') pylab.show() if '-csv' in get_opts()[0]: data = [line.split(',') for line in read_file(get_opts()[0]['-csv'])[1:]] times = [float(i[0]) for i in data] sizes = [float(i[1]) for i in data] print "Mean time: %f" % (sum(times) / len(times)) print "Mean size: %f" % (sum(sizes) / len(sizes)) elif '-size' in get_opts()[0]: dom = get_opts()[0]['-size'] fname = "%s.csv" % dom data = [line.split(',') for line in read_file(fname)[1:]] times = sorted([float(i[0]) for i in data]) sizes = sorted([float(i[1]) for i in data]) xs = [i+1 for i in range(len(data))] individual_plot(xs, sizes, False, title_lookup[dom])
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))) return runtime, policy_size