Ejemplo n.º 1
0
def nudge_down3(key: str,
                key2,
                key3,
                data: dict,
                solution: dict,
                delta_past=-1,
                limit=30):
    if not limit:
        return data[key][key2][key3]
    if delta_past == -1:
        delta_past = data[key][key2][key3] * 0.5
    data = data.copy()
    delta = int(delta_past * 0.5)
    data[key][key2][key3] -= delta
    if data[key][key2][key3] < 1:
        return 0
    new_solution = optimize(data)
    if diff(solution, new_solution):
        data[key][key2][key3] += delta
        return nudge_down3(key, key2, key3, data, solution, delta, limit - 1)
    else:
        if not delta:
            return data[key][key2][key3]
        else:
            return nudge_down3(key, key2, key3, data, solution, delta * 2,
                               limit - 1)
Ejemplo n.º 2
0
def nudge_up(key: str, data: dict, solution: dict, delta_past=-1, limit=30):
    if not limit:
        return 'Inf'
    if delta_past == -1:
        delta_past = data[key]
    data = data.copy()
    delta = int(delta_past * 0.5)
    data[key] += delta
    new_solution = optimize(data)
    if diff(solution, new_solution):
        data[key] -= delta
        return nudge_up(key, data, solution, delta, limit - 1)
    else:
        if not delta:
            return data[key]
        else:
            return nudge_up(key, data, solution, delta * 2, limit - 1)
Ejemplo n.º 3
0
def main():
    with open('data.json') as f:
        data = json.loads(f.read())
    f = open('result.txt', 'w')

    print('Initial optimization')

    solution = optimize(data)

    print('Starting sensibility analysis')

    to_nudge = ["sueldo_fijo", "vol_max", "entrada"]
    to_nudge_once = [
        "donaciones_monetarias", "visitas", "volumen_alimentos",
        "duracion_alimentos", "costo_alimento"
    ]
    to_nudge_twice = ["cantidad_alimento"]

    bar = tqdm(total=sum(len(data[x]) for x in to_nudge_once) + len(to_nudge) +
               sum(sum(len(y) for y in data[x]) for x in to_nudge_twice))

    for i in to_nudge:
        print(i, 'limit up', nudge_up(i, data, solution), file=f)
        print(i, 'limit down', nudge_down(i, data, solution), file=f)
        bar.update()
        f.flush()
        os.fsync(f.fileno())

    for i in to_nudge_once:
        for j in range(len(data[i])):
            print(i, j, 'limit up', nudge_up2(i, j, data, solution), file=f)
            print(i,
                  j,
                  'limit down',
                  nudge_down2(i, j, data, solution),
                  file=f)
            bar.update()
            f.flush()
            os.fsync(f.fileno())

    for i in to_nudge_twice:
        for j in range(len(data[i])):
            for k in range(len(data[i][j])):
                print(i,
                      j,
                      k,
                      'limit up',
                      nudge_up3(i, j, k, data, solution),
                      file=f)
                print(i,
                      j,
                      k,
                      'limit down',
                      nudge_down3(i, j, k, data, solution),
                      file=f)
                bar.update()
                f.flush()
                os.fsync(f.fileno())

    bar.close()
    f.close()
Ejemplo n.º 4
0
def optimize(func_def, axiom_srcs, line_durations):

    peg = compute_peg(func_def, line_durations)

    print('Optimizing ' + func_def.name + '...')

    render(peg.root, 'peg_' + func_def.name)

    env = clips.Environment()

    env.eval('(open "clips_data.txt" output-file "w")')
    env.strategy = clips.Strategy.BREADTH

    env.eval('(load "clips_constructs.clp")')

    # env.eval('(watch facts)')
    #env.eval('(watch activations)')
    #env.eval('(watch instances)')

    for i in range(len(axiom_srcs)):
        ax_func_def_format = ax_format_to_funcdef(axiom_srcs[i])
        axiom_peg = compute_axiom_peg(ax_func_def_format, name='ax_' + str(i))
        rule = create_rule(axiom_peg)
        env.build(rule)

    instances = peg_to_instances(peg)
    for instance in instances.splitlines():
        env.eval(instance)

#  print('FACTS================================')
#  for f in env.facts():
#     print(str(f))

    print('RULES================================')
    for r in env.rules():
        print(r)

    env.run(1000)

    print('INSTANCES================================')
    for i in env.instances():
        print(i)

    epeg = EPEG(peg)

    clips_data_file = open('clips_data.txt', 'r')
    equalities = {}

    for line in clips_data_file.readlines():
        pair = tuple(line.split()[1:3])
        add_equality(pair, equalities)

    epeg.saturate(env, equalities)

    env.eval('(close)')

    epeg.root_class = map_to_eq_class(epeg.root_class, equalities)

    epeg.compute_predecessors()

    filter_constant_classes(epeg)
    apply_constant_folding(epeg)
    apply_broadcasting(epeg)
    apply_constant_folding(epeg)
    remove_useless_evals(epeg)

    epeg.filter_reachable_classes()

    import graphviz
    g = graphviz.Digraph(name='epeg_' + func_def.name,
                         format='png',
                         strict=False)

    for k, v in epeg.classes.items():

        with g.subgraph(name='cluster_' + k) as c:

            for node in v:
                c.node(str(node.id),
                       label=str(node) + ' (cost ' + str(node.cost) + ')')
                for child in node.children:
                    g.edge(str(node.id), str(child.id))
            c.attr(label=k)
            c.attr(color='green')

    g.view()

    import solver

    start_cost = epeg.start_peg_cost
    root = solver.optimize(epeg)

    render(root, 'peg_opt' + func_def.name)

    assert root != None

    from peg_builder import get_nodes
    peg.ctx = {'retvar': root}
    peg.root = root
    peg.nodes = get_nodes(root)

    if sum([n.cost for n in peg.nodes]) == start_cost:
        return None

    gen = CodeFromPEGGenerator(peg)

    code = gen.get_code()

    return code