Пример #1
0
def main():
    INPUTS = []
    OUTPUTS = []
    arr = get_input_prog('22.txt')
    prog = Prog(arr)
    intcode = Memmory(prog, store_input, print_output, INPUTS, OUTPUTS)
    start = [0, 0]
    robot = Robot(start)
    to_exit = 'Pause'
    canvas = [['0' for _ in range(70)] for _ in range(70)]
    center = (27, 27)
    while to_exit != 'Stop':
        current_color = robot.get_color()
        i = center[0] + robot.position.x
        j = center[1] + robot.position.y
        INPUTS.append(current_color)
        to_exit = intcode.compute()
        if OUTPUTS:
            color = OUTPUTS.pop(0)
        else:
            break
        canvas[i][j] = color
        to_exit = intcode.compute()
        direction = OUTPUTS.pop(0)
        robot.paint(color)
        robot.step(direction)

    for i in range(70):
        for j in range(70):
            if j == 69:
                print(canvas[i][j])
            else:
                print(canvas[i][j], end='')
Пример #2
0
def main():
    arr = get_input_prog('26.txt')
    canvas = None
    max_score = get_max_score('maxscore.txt')
    INPUTS = get_best_seq('bestseq.txt')
    OUTPUTS = []
    score = 0
    score_arr = []
    to_exit = 'Resume'
    prog = Prog(arr)
    prog.set_value(0, 2)
    intcode = Memmory(prog, handle_input, print_output, INPUTS, OUTPUTS)
    while to_exit != 'Stop':
        to_exit = intcode.compute()
        if len(OUTPUTS) > 2282:
            if len(OUTPUTS) % 3 == 0:
                canvas = Canvas(OUTPUTS)
                score = canvas.canvas[point(-1, 0)]
                score_arr.append(score)
                print(score)
                if score >= 10200:
                    canvas.draw_field()
    score = max(score_arr)
    if score >= max_score:

        print(f'max_score::{max_score}')
        max_score = score
        with open('maxscore.txt', 'w') as f:
            f.write(f'{max_score}')
        with open('seq.txt', 'w') as f:
            f.write(f'{score}::')
            for elem in tmp_input:
                f.write(str(elem))
        with open('progstate.txt', 'w') as f:
            for key, value in prog.prog.items():
                f.write(f'{elem},')
        with open('out.txt', 'w') as f:
            for elem in OUTPUTS:
                f.write(f'{elem},')
Пример #3
0
def read_file(fd):
    try:
        config = yamlParser(fd)
        if not config:
            return False
        for k, v in config.items():
            try:
                prog = Prog(k, v)
                progs.append(prog)
            except Exception as e:
                print("Program error {0}".format(e))
        return progs
    except IOError as e:
        print("Impossible to open config file because : {0}".format(e))
Пример #4
0
def heuristic_generalize(prog, checker, width, targetwidth, codelen):
    """
  Use heuristics to guess constants with which to generalize the program.
  """

    expansions = []

    for i in xrange(len(prog.consts)):
        for j in xrange(len(prog.consts[i])):
            if prog.const_used(i, j):
                expanded = expand(prog.consts[i][j], width, targetwidth)
            else:
                expanded = [0]

            expansions.append(expanded)

    for i in xrange(len(prog.evars)):
        expanded = expand(prog.evars[i], width, targetwidth)
        expansions.append(expanded)

    for newconsts in itertools.product(*expansions):
        const_lists = []
        n = 0

        for i in xrange(len(prog.consts)):
            l = []

            for j in xrange(len(prog.consts[i])):
                l.append(newconsts[n])
                n += 1

            const_lists.append(l)

        newevars = []
        for i in xrange(len(prog.evars)):
            newevars.append(newconsts[n])
            n += 1

        newprog = Prog(prog.ops, prog.params, const_lists, newevars)

        if args.args.verbose > 1:
            print "Trying %s" % (str(newprog))

        if verif(newprog, checker, targetwidth, codelen) is None:
            return newprog

    return None
Пример #5
0
def synth(tests, exclusions, width, codelen, nconsts):
    """
  Synthesise a new code sequence.
  """

    perf.start("synth")

    bmc = Checker(codelen, width, nconsts)

    testfile = open("/tmp/testvectors", "w")

    # Write the test inputs...
    bmc.write(r"""
#include "synth.h"

void tests(solution_t *solution) {
  word_t input[NARGS];
""")

    testfile.write("%d\n" % len(tests))

    #random.shuffle(tests)
    for x in tests:
        for i in xrange(len(x)):
            bmc.write("  input[%d] = %d;\n" % (i, x[i]))

        bmc.write("  test(solution, input);\n\n")

        testfile.write(" ".join(str(d) for d in x) + "\n")

    testfile.close()

    # Now we're going to list each of the programs we
    # already know are wrong...

    for soln in exclusions:
        ops = soln.ops
        parms = soln.params
        consts = soln.consts
        evars = soln.evars

        bmc.write("  assume(!(")

        for i in xrange(len(ops)):
            if i != 0:
                bmc.write(" && ")

            bmc.write("solution->prog.ops[%d] == %d " % (i, ops[i]))
            bmc.write(
                "&& solution->prog.params[%d] == %d && solution->prog.params[%d] == %d && solution->prog.params[%d] == %d"
                % (3 * i, parms[3 * i], 3 * i + 1, parms[3 * i + 1], 3 * i + 1,
                   parms[3 * i + 2]))

        for i in xrange(len(consts)):
            bmc.write("&& solution->prog.consts[%d] == %d" % (i, consts[i]))

        for i in xrange(len(evars)):
            bmc.write("&& solution->evars[%d] == %d" % (i, evars[i]))

        bmc.write("));\n")

    bmc.write("}\n")

    try:
        (retcode, output) = bmc.run()
    finally:
        perf.end("synth")

    prog = None

    if retcode == 10:
        # A counterexample was found -- extract the code sequence from it!
        prog = Prog()
        prog.parse(output)

    return prog
Пример #6
0
def __processTest(test):
    """
    Things to collect:
        Times triaging failed programs
        signalRun: Number. Remaining sig for TP, FP.
        Minimization: Number. Time spent on failed programs. Success TP, FP. Fail TN, FN.
        Minimization success stats
    """
    ret = []
    fn = 'result_' + test
    if not os.path.isfile(fn):
        return ret
    f = open(fn)
    prev_pc = 0
    executeCount = 0
    idx = 0
    ts_cur = 0
    ts_bgn = 0
    status_cur = {
        "triagingTotal": 0,
        "triagingFail": 0,
        "minimizeTotal": 0,
        "minimizeFail": 0,
        "minimizeNew": 0,
        "minimizeTP": 0,
        "minimizeFP": 0,
        "minimizeTN": 0,
        "minimizeFN": 0,
    }
    minimizeSz = [{}, {}]
    sigInit = 0
    corpusProg = False
    # Minimize
    progStatus = None
    inProg = False
    curCalls = []
    curProg = None
    minimizeProgFrom = None
    minimizeProgTo = None
    minimizeAttempts = []
    minimizeSuccess = False
    minimizeExec = 0
    # Coverage
    coverageTotal = set()
    coveragePrev = 0
    for line in f:
        line = line.strip('\n').strip()
        if len(line) == 0:
            continue
        if line[:3] == '<<<' and line[-3:] == '>>>':
            line = line.strip('<<<').strip('>>>')
            ts_cur = int(line)
            if ts_bgn == 0:
                ts_bgn = ts_cur
        elif (line == ">" or line[:3] == ">>>") and not inProg:
            inProg = True
            curCalls = []
        elif line == "<" or line == "<<<":
            inProg = False
            curProg = Prog.newProg(calls=curCalls,
                                   ts=ts_cur,
                                   signal=0,
                                   origin=None)
            if progStatus == "MinimizeFrom":
                minimizeProgFrom = curProg
            elif progStatus == "MinimizeAttempt":
                minimizeProgTo = curProg
            progStatus = None
        elif inProg:
            if line[:2] == "> ":
                line = line.strip("> ")
            if len(line) == 0:
                continue
            curCalls.append(' '.join(__parseCall(line)))
        elif line[:2] == '= ':
            tmp = line.split()
            try:
                pc = int(tmp[1], 16)
            except:
                continue
            if (pc & 0xffff000000000000) == 0xffff000000000000:
                coverageTotal.add(pc)
            elif (pc & 0xffffffff00000000) == 0:
                coverageTotal.add(pc)
        elif line[:2] == "- " and "executeRaw" in line:
            executeCount += 1
            status = copy.deepcopy(status_cur)
            status["executeCount"] = executeCount
            status["ts"] = (ts_cur - ts_bgn) / 1000000000
            ret.append(status)
            coveragePrev = len(coverageTotal)
        elif "# signalRun 0: " in line:
            tmp = line.split("# signalRun 0: ")[1].split('+')
            sigInit = int(tmp[0])
        elif line[:8] == "# Result":
            tmp = line.strip("# Result: ").split(',')
            if int(tmp[2]) > 0:
                corpusProg = True
            else:
                corpusProg = False
                status_cur["triagingFail"] += 1
            # print(tmp[2], status_cur["triagingFail"])
            status_cur["triagingTotal"] += 1
        elif line[-8:] == "Minimize":
            progStatus = "MinimizeFrom"
        elif "# Minimize Attempt" in line:
            progStatus = "MinimizeAttempt"
        elif "# Minimize Fail" in line or "# Minimize Success" in line:
            minimizeProgFrom.childrenMinimize.append(minimizeProgTo)
            entry = {
                "from": minimizeProgFrom,
                "to": minimizeProgTo,
                "success": "Success" in line
            }
            minimizeAttempts.append(entry)
        elif "# Minimize" in line and "->" in line:
            tmp = line.split(': ')[1].replace('->',
                                              ' ').replace('+', ' ').replace(
                                                  ',', ' ').split()
            if tmp[3] == tmp[5]:
                minimizeSuccess = True
            minimizeExec += 1
            if len(coverageTotal) > coveragePrev:
                status_cur["minimizeNew"] += 1
    f.close()
    return ret, minimizeAttempts
Пример #7
0
    Config.set('graphics', 'width', '350')
    Config.set('graphics', 'height', '650')
except Exception:
    with open("{}/error.log".format(directory), "w") as err:
        traceback.print_exc(err)
    sys.exit(1)

__version__ = '0.3.2'


if __name__ == "__main__":
    app = None

    try:
        from prog import Prog
        app = Prog()
        app.run()
    except Exception:
        from resources.progclasses.bugreporter import BugReporter
        text_error = traceback.format_exc()
        erro = open("{}/error.log".format(directory), "w")
        erro.write(text_error)
        print(text_error)
        erro.close()

        if app:
            try:
                app.prime_screen.clear_widgets()
            except AttributeError:
                pass
Пример #8
0
async def new_prog(p: prog.Prog):
    p.save()
    return {'res': 'ok'}