コード例 #1
0
def test_graph_applyo_misc():
    q_lv = var('q')
    expr = etuple(add, etuple(mul, 2, 1), etuple(add, 1, 1))
    assert len(
        run(0, q_lv, graph_applyo(eq, expr, expr, preprocess_graph=None))) == 1

    expr2 = etuple(add, etuple(mul, 2, 1), etuple(add, 2, 1))
    assert len(
        run(0, q_lv, graph_applyo(eq, expr, expr2,
                                  preprocess_graph=None))) == 0

    assert len(
        run(0, q_lv, graph_applyo(eq,
                                  etuple(),
                                  etuple(),
                                  preprocess_graph=None))) == 1

    def one_to_threeo(x, y):
        return conde([eq(x, 1), eq(y, 3)])

    res = run(
        0, q_lv,
        graph_applyo(one_to_threeo, [1, [1, 2, 4], 2, [[4, 1, 1]], 1],
                     q_lv,
                     preprocess_graph=None))

    assert res[0] == [3, [3, 2, 4], 2, [[4, 3, 3]], 3]
コード例 #2
0
def test_graph_applyo_reverse():
    """Test `graph_applyo` in "reverse" (i.e. specify the reduced form and generate the un-reduced form)."""
    q_lv = var('q')

    test_res = run(2, q_lv, fixedp_graph_applyo(math_reduceo, q_lv, 5))
    assert test_res == (etuple(log, etuple(exp, 5)),
                        etuple(log, etuple(exp, etuple(log, etuple(exp, 5)))))
    assert all(e.eval_obj == 5.0 for e in test_res)

    # Make sure we get some variety in the results
    test_res = run(2, q_lv,
                   fixedp_graph_applyo(math_reduceo, q_lv, etuple(mul, 2, 5)))
    assert test_res == (
        # Expansion of the term's root
        etuple(add, 5, 5),
        # Two step expansion at the root
        etuple(log, etuple(exp, etuple(add, 5, 5))),
        # Expansion into a sub-term
        # etuple(mul, 2, etuple(log, etuple(exp, 5)))
    )
    assert all(e.eval_obj == 10.0 for e in test_res)

    r_lv = var('r')
    test_res = run(4, [q_lv, r_lv],
                   fixedp_graph_applyo(math_reduceo, q_lv, r_lv))
    expect_res = ([etuple(add, 1, 1), etuple(mul, 2, 1)], [
        etuple(log, etuple(exp, etuple(add, 1, 1))),
        etuple(mul, 2, 1)
    ], [etuple(), etuple()], [
        etuple(add, etuple(mul, 2, 1), etuple(add, 1, 1)),
        etuple(mul, 2, etuple(mul, 2, 1))
    ])
    assert list(
        unify(a1, a2) and unify(b1, b2)
        for [a1, b1], [a2, b2] in zip(test_res, expect_res))
コード例 #3
0
def test_seq_apply_anyo_types():
    """Make sure that `applyo` preserves the types between its arguments."""
    q_lv = var()
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), [1], q_lv))
    assert res[0] == [1]
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), (1, ), q_lv))
    assert res[0] == (1, )
    res = run(
        1, q_lv,
        seq_apply_anyo(lambda x, y: eq(x, y), etuple(1, ), q_lv,
                       skip_op=False))
    assert res[0] == etuple(1, )
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), q_lv, (1, )))
    assert res[0] == (1, )
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), q_lv, [1]))
    assert res[0] == [1]
    res = run(
        1, q_lv,
        seq_apply_anyo(lambda x, y: eq(x, y), q_lv, etuple(1), skip_op=False))
    assert res[0] == etuple(1)
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), [1, 2], [1, 2]))
    assert len(res) == 1
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), [1, 2], [1, 3]))
    assert len(res) == 0
    res = run(1, q_lv, seq_apply_anyo(lambda x, y: eq(x, y), [1, 2], (1, 2)))
    assert len(res) == 0
    res = run(
        0, q_lv,
        seq_apply_anyo(lambda x, y: eq(y, etuple(mul, 2, x)),
                       etuple(add, 1, 2),
                       q_lv,
                       skip_op=True))
    assert len(res) == 3
    assert all(r[0] == add for r in res)
コード例 #4
0
def tios(x, z):
    y = var()
    w = var()
    lista = set(run(16, x, conde((padre(y, x), padre(y, w), padre(w, z)))))
    p = list(run(8, x, padre(x, z)))
    for i in p:
        lista.discard(i)
    return lista
コード例 #5
0
def tios(x, z):
    y = var()
    w = var()
    vtios=set(run(10, x, conde((parent(y,x), parent(y,w), parent(w,z)))))
    p=list(run(10, x, parent(x, z)))
    for i in p:
        vtios.discard(i)
    return vtios
コード例 #6
0
def test_distributions():
    res = run(0, var('q'), eq(var('q'), mt(1)),
              constant_neq(var('q'), np.array(1.)))

    assert not res

    res = run(0, var('q'), eq(var('q'), mt(2)),
              constant_neq(var('q'), np.array(1.)))

    assert res
コード例 #7
0
def test_map_anyo_misc():
    q_lv = var("q")

    res = run(0, q_lv, map_anyo(eq, [1, 2, 3], [1, 2, 3]))
    # TODO: Remove duplicate results
    assert len(res) == 7
    res = run(0, q_lv, map_anyo(eq, [1, 2, 3], [1, 3, 3]))
    assert len(res) == 0

    def one_to_threeo(x, y):
        return conde([eq(x, 1), eq(y, 3)])

    res = run(0, q_lv, map_anyo(one_to_threeo, [1, 2, 4, 1, 4, 1, 1], q_lv))

    assert res[0] == [3, 2, 4, 3, 4, 3, 3]

    assert (len(
        run(4, q_lv, map_anyo(math_reduceo, [etuple(mul, 2, var("x"))],
                              q_lv))) == 0)

    test_res = run(4, q_lv, map_anyo(math_reduceo, [etuple(add, 2, 2), 1],
                                     q_lv))
    assert test_res == ([etuple(mul, 2, 2), 1], )

    test_res = run(4, q_lv, map_anyo(math_reduceo, [1, etuple(add, 2, 2)],
                                     q_lv))
    assert test_res == ([1, etuple(mul, 2, 2)], )

    test_res = run(4, q_lv, map_anyo(math_reduceo, q_lv, var("z")))
    assert all(isinstance(r, list) for r in test_res)

    test_res = run(4, q_lv, map_anyo(math_reduceo, q_lv, var("z"), tuple))
    assert all(isinstance(r, tuple) for r in test_res)

    x, y, z = var(), var(), var()

    def test_bin(a, b):
        return conde([eq(a, 1), eq(b, 2)])

    res = run(10, (x, y), map_anyo(test_bin, x, y, null_type=tuple))
    exp_res_form = (
        ((1, ), (2, )),
        ((x, 1), (x, 2)),
        ((1, 1), (2, 2)),
        ((x, y, 1), (x, y, 2)),
        ((1, x), (2, x)),
        ((x, 1, 1), (x, 2, 2)),
        ((1, 1, 1), (2, 2, 2)),
        ((x, y, z, 1), (x, y, z, 2)),
        ((1, x, 1), (2, x, 2)),
        ((x, 1, y), (x, 2, y)),
    )

    for a, b in zip(res, exp_res_form):
        s = unify(a, b)
        assert s is not False
        assert all(isvar(i) for i in reify((x, y, z), s))
コード例 #8
0
def test_walko_misc():
    q_lv = var(prefix="q")

    expr = etuple(add, etuple(mul, 2, 1), etuple(add, 1, 1))
    res = run(0, q_lv, walko(eq, expr, expr))
    # TODO: Remove duplicates
    assert len(res) == 162

    expr2 = etuple(add, etuple(mul, 2, 1), etuple(add, 2, 1))
    res = run(0, q_lv, walko(eq, expr, expr2))
    assert len(res) == 0

    def one_to_threeo(x, y):
        return conde([eq(x, 1), eq(y, 3)])

    res = run(
        1,
        q_lv,
        walko(
            one_to_threeo,
            [1, [1, 2, 4], 2, [[4, 1, 1]], 1],
            q_lv,
        ),
    )
    assert res == ([3, [3, 2, 4], 2, [[4, 3, 3]], 3], )

    assert run(2, q_lv, walko(eq, q_lv, q_lv, null_type=ExpressionTuple)) == (
        q_lv,
        etuple(),
    )

    res = run(
        1,
        q_lv,
        walko(
            one_to_threeo,
            etuple(
                add,
                1,
                etuple(mul, etuple(add, 1, 2), 1),
                etuple(add, etuple(add, 1, 2), 2),
            ),
            q_lv,
            # Only descend into `add` terms
            rator_goal=lambda x, y: lall(eq(x, add), eq(y, add)),
        ),
    )

    assert res == (etuple(add, 3, etuple(mul, etuple(add, 1, 2), 1),
                          etuple(add, etuple(add, 3, 2), 2)), )
コード例 #9
0
def star_wars_logic():

    x = var()

    parent = Relation()
    facts(parent, ("Darth Vader", "Luke Skywalker"),
          ("Darth Vader", "Leia Organa"), ("Han Solo", "Kylo Ren"),
          ("Leia Organa", "Kylo Ren"))
    print(run(0, x, parent(x, "Luke Skywalker")))
    print(run(0, x, parent("Darth Vader", x)))

    grandparent = Relation()
    facts(grandparent, ("Darth Vader", "Kylo Ren"))
    print(run(1, x, grandparent(x, "Kylo Ren")))
コード例 #10
0
def test_seq_apply_anyo_misc():
    q_lv = var('q')

    assert len(run(0, q_lv, seq_apply_anyo(eq, [1, 2, 3], [1, 2, 3]))) == 1

    assert len(run(0, q_lv, seq_apply_anyo(eq, [1, 2, 3], [1, 3, 3]))) == 0

    def one_to_threeo(x, y):
        return conde([eq(x, 1), eq(y, 3)])

    res = run(0, q_lv,
              seq_apply_anyo(one_to_threeo, [1, 2, 4, 1, 4, 1, 1], q_lv))

    assert res[0] == [3, 2, 4, 3, 4, 3, 3]

    assert len(
        run(4, q_lv,
            seq_apply_anyo(math_reduceo, [etuple(mul, 2, var('x'))],
                           q_lv))) == 0

    test_res = run(4, q_lv,
                   seq_apply_anyo(math_reduceo, [etuple(add, 2, 2), 1], q_lv))
    assert test_res == ([etuple(mul, 2, 2), 1], )

    test_res = run(4, q_lv,
                   seq_apply_anyo(math_reduceo, [1, etuple(add, 2, 2)], q_lv))
    assert test_res == ([1, etuple(mul, 2, 2)], )

    test_res = run(4, q_lv, seq_apply_anyo(math_reduceo, q_lv, var('z')))
    assert all(isinstance(r, list) for r in test_res)

    test_res = run(4, q_lv,
                   seq_apply_anyo(math_reduceo, q_lv, var('z'), tuple()))
    assert all(isinstance(r, tuple) for r in test_res)
コード例 #11
0
ファイル: Processor.py プロジェクト: josericardojr/MorphWing
def adjust_difficulty(factor):
    x = var()
    y = var()
    z = var()
    hap_factor = float(happenings[factor])
    hit_factor = float(hits[factor])
    bal_factor = run(1, x, balanceFactor("enemy{0}".format(factor + 1), x))
    min_adjust = run(1, y, difficultyAdjustMin("enemy{0}".format(factor + 1), y))
    max_adjust = run(1, z, difficultyAdjustMax("enemy{0}".format(factor + 1), z))

    if hap_factor > 0:
        result = min(max(0.05 * hap_factor - 0.05 * hit_factor * float(bal_factor[0]), float(min_adjust[0])), float(max_adjust[0]))
        enemy_difficult[factor] = format_number(result)
        print("{0}:{1};".format(key_enemy[factor], format_number(result)))
コード例 #12
0
def test_seq_apply_anyo_reverse():
    """Test `seq_apply_anyo` in "reverse" (i.e. specify the reduced form and generate the un-reduced form)."""
    # Unbounded reverse
    q_lv = var()
    rev_input = [etuple(mul, 2, 1)]
    test_res = run(4, q_lv, (seq_apply_anyo, math_reduceo, q_lv, rev_input))
    assert test_res == ([etuple(add, 1, 1)],
                        [etuple(log, etuple(exp, etuple(mul, 2, 1)))])

    # Guided reverse
    test_res = run(4, q_lv,
                   (seq_apply_anyo, math_reduceo, [etuple(add, q_lv, 1)
                                                   ], [etuple(mul, 2, 1)]))

    assert test_res == (1, )
コード例 #13
0
def I():

    parent = Relation()
    facts(parent, ("Darth Vader", "Luke Skywalker"),
          ("Darth Vader", "Leia Organa"), ("Leia Organa", "Kylo Ren"),
          ("Han Solo", "Kylo Ren"))
    x = var()
    print(run(1, x, parent(x, "Luke Skywalker")))
    y = var()
    print(run(2, y, parent("Darth Vader", y)))

    grand_parents = Relation()
    facts(grand_parents, ("Darth Vader", "Kylo Ren"))
    z = var()
    print(run(1, z, grand_parents(z, "Kylo Ren")))
コード例 #14
0
def six():
    temp = var()
    temp = run(int(a), n, prime_test(n))
    i = int
    i = 0
    z = int
    z = 0

    while int(temp[i]) < int(a):
        i = i + 1

    if int(temp[i]) == int(a):
        j = int
        k = int
        jresult = False
        kresult = False
        j = int(temp[i]) + 6
        k = int(temp[i]) - 6
        temp = run(int(j), n, prime_test(n))

        while z < int(j):
            if (int(j) == int(temp[z])):
                jresult = True
                z = z + 1
            else:
                z = z + 1

        z = 0

        while z < int(k):
            if (int(k) == int(temp[z])):
                kresult = True
                z = z + 1
            else:
                z = z + 1

        if jresult == True and kresult == False:
            return ("{} is a Sexy Prime with {}".format(a, str(j)))
        elif kresult == True and jresult == False:
            return ("{} is a Sexy Prime with {}".format(a, str(k)))
        elif jresult == True and kresult == True:
            return ("{} is a Sexy Prime with {} and {}".format(
                a, str(j), str(k)))
        else:
            return ("{} does not have a Sexy prime".format(a))

    else:
        return ("{} is not a prime number".format(a))
コード例 #15
0
ファイル: test_sudoku.py プロジェクト: yusuf-kayyalie/logpy
def sudoku_solver(hints):
    variables = vars(hints)
    rows = get_rows(variables)
    cols = get_columns(rows)
    sqs = get_squares(rows)
    return run(1, variables, everyg(all_numbers, rows),
               everyg(all_numbers, cols), everyg(all_numbers, sqs))
コード例 #16
0
def validate(sb):
    rows = get_rows(sb)
    cols = get_cols(sb)
    squares = get_squares(sb)
    x = var('x')
    return run(0, x, everyg(test, rows), everyg(test, cols),
               everyg(test, squares))
コード例 #17
0
def three():
    i = int
    i = 0
    factor = []
    temp = var()
    result = False
    temp = run(int(a), n, prime_test(n))
    while i < int(a):
        if (int(a) == int(temp[i])):
            result = True
            i = i + 1
        else:
            i = i + 1
    if result == True:
        return ("{} is a prime number".format(a))
    else:
        i = 0
        while int(temp[i]) < int(a):
            if (int(a) % int(temp[i]) == 0):
                factor.append(int(temp[i]))
                i = i + 1
            else:
                i = i + 1

    return (factor)
コード例 #18
0
    def transform(self, node):
        if not isinstance(node, tt.Apply):
            return False

        if self.node_filter(node):
            return False

        input_expr = node.default_output()

        with variables(*self.relation_lvars):
            q = var()
            kanren_results = run(1, q, (self.kanren_relation, input_expr, q))

        chosen_res = self.results_filter(kanren_results)

        if chosen_res:
            # Turn the meta objects and tuple-form expressions into Theano
            # objects.
            if isinstance(chosen_res, tuple) and chosen_res[0] == dict:
                # We got a dictionary of replacements.
                new_node = {k.obj: reify_meta(v)
                            for k, v in evalt(chosen_res).items()}

                assert all(k in node.fgraph.variables
                           for k in new_node)
            else:
                new_node = self.adjust_outputs(node, reify_meta(chosen_res))

            return new_node
        else:
            return False
コード例 #19
0
def five():
    i = int
    i = 0
    temp = var()
    temp = run(int(a), n, prime_test(n))

    while int(temp[i]) < int(a):
        i = i + 1

    i = i - 1
    if int(temp[i + 1]) == int(a):
        return ("{} is a prime number".format(a))

    else:
        j = int
        k = int
        j = int(a) - int(temp[i])
        k = int(temp[i + 1]) - int(a)
        if j < k:
            return ("{} is the closest prime number".format(temp[i]))
        elif k < j:
            return ("{} is the closest prime number".format(temp[i + 1]))
        else:
            return ("{} and {} are the closest prime numbers".format(
                temp[i], temp[i + 1]))
コード例 #20
0
def test_constant_neq():
    q_lv = var()

    res = run(0, q_lv, eq(q_lv, mt(1)), constant_neq(q_lv, np.array(1.0)))
    assert not res

    # TODO: If `constant_neq` was a true constraint, this would work.
    # res = run(0, q_lv, constant_neq(q_lv, np.array(1.0)), eq(q_lv, mt(1)))
    # assert not res

    # TODO: If `constant_neq` was a true constraint, this would work.
    # res = run(0, q_lv, constant_neq(q_lv, np.array(1.0)), eq(q_lv, mt(2)))
    # assert res == (mt(2),)

    res = run(0, q_lv, eq(q_lv, mt(2)), constant_neq(q_lv, np.array(1.0)))
    assert res == (mt(2), )
コード例 #21
0
    def _query(self, num_solutions, *atoms: Atom):
        # find variables
        vars = OrderedSet()
        for atom in atoms:
            for var in atom.get_variables():
                if var not in vars:
                    vars.add(var)

        if len(vars) == 0:
            for atom in atoms:
                for term in atom.get_terms():
                    if term not in vars:
                        vars.add(term)

        ori_vars = list(vars)
        vars = [
            x.as_kanren() if getattr(x, "as_kanren", None) else x
            for x in ori_vars
        ]
        goals = [
            x.as_kanren() if getattr(x, "as_kanren", None) else x
            for x in atoms
        ]

        return kanren.run(num_solutions, vars, *goals), ori_vars
コード例 #22
0
def test_commutativity():
    with enable_lvar_defaults('names'):
        add_1_mt = mt(1) + mt(2)
        add_2_mt = mt(2) + mt(1)

    res = run(0, var('q'), commutative(add_1_mt.base_operator))
    assert res is not False

    res = run(0, var('q'), eq_comm(add_1_mt, add_2_mt))
    assert res is not False

    with enable_lvar_defaults('names'):
        add_pattern_mt = mt(2) + var('q')

    res = run(0, var('q'), eq_comm(add_1_mt, add_pattern_mt))
    assert res[0] == add_1_mt.base_arguments[0]
コード例 #23
0
def possible(y, x, n):
    ''' initialize variables'''
    global grid
    array = []
    ''' initialize for loop and if true there is no number similar to the
    input number inside the row or column of the grid or board.'''
    for i in range(0, 9):
        if grid[y][i] == n:
            if grid[i][x] == n:
                return False
    ''' initialize variables and calculate the index location of the board.'''
    output = var()
    x0 = (x // 3) * 3
    y0 = (y // 3) * 3
    ''' initialize a for loop and store the values inside array'''
    for i in range(0, 3):
        for j in range(0, 3):
            array.append(grid[y0 + i][x0 + j])
    ''' Applying Kanren functions into the Sudoku algorithm.
    The functions are use to implement a logic program to verify
    whether the input variable is identical to the numbers inside the array.
    If there is no numbers identical to the numbers inside the array, then
    the function will return True.'''
    find_number = run(1, output, eq(output, n), membero(output, array))
    if len(find_number) != 0:
        return False
    return True
コード例 #24
0
def interp(expr):
    print("Program to be evaluated:\n{}".format(expr))
    program_ast = ast.parse(expr)
    # program_ast = ast.Num(n=1)
    print("AST of the program: \n{}".format(ast.dump(program_ast)))
    x = var()
    evaluated_program = run(0, x, evalo(program_ast, x))
    print("Evaluated program: {}".format(evaluated_program))
コード例 #25
0
def test_eq_length():
    q_lv = var()

    res = run(0, q_lv, eq_length([1, 2, 3], q_lv))
    assert len(res) == 1 and len(res[0]) == 3 and all(isvar(q) for q in res[0])

    res = run(0, q_lv, eq_length(q_lv, [1, 2, 3]))
    assert len(res) == 1 and len(res[0]) == 3 and all(isvar(q) for q in res[0])

    res = run(0, q_lv, eq_length(cons(1, q_lv), [1, 2, 3]))
    assert len(res) == 1 and len(res[0]) == 2 and all(isvar(q) for q in res[0])

    v_lv = var()
    res = run(3, (q_lv, v_lv), eq_length(q_lv, v_lv, default_ConsNull=tuple))
    assert len(res) == 3 and all(
        isinstance(a, tuple) and len(a) == len(b) and
        (len(a) == 0 or a != b) and all(isvar(r) for r in a) for a, b in res)
コード例 #26
0
ファイル: LogicProgramming.py プロジェクト: HernanRossi/AI_A4
    def start(self):
        self.parent = Relation()
        x = var()
        facts(self.parent,
              ("DarthVader", "LukeSkywalker"),
              ("DarthVader", "LeiaOrgana"),
              ("LeiaOrgana", "KyloRen"),
              ("HanSolo", "KyloRen")
              )

        lukesParent = run(1, x, self.parent(x, "LukeSkywalker"))
        darthsChildren =run(2, x, self.parent("DarthVader", x))
        print("Luke Skywalkers parent is: ", lukesParent)
        print("Darth Vaders children are: ", darthsChildren)
        kylosGrandparent = run(1, x,self.grandparent(x, "KyloRen"))
        print("Kylo Ren's grand parent is: ", kylosGrandparent)
        self.familyTreeDataStructures()
コード例 #27
0
ファイル: cipher.py プロジェクト: john299792/Narrated-Code
def logicBased():
    x = var()
    print(run(1, x, eq(x, 5)))
    z = var()
    print(run(1, x, eq(x, z), eq(z, 3)))

    print(run(1, x, eq((1, 2), (1, x))))

    print(run(2, x, membero(x, (1, 2, 3)), membero(x, (2, 3, 4))))

    z = var('test')
    print(z)

    a, b, c = vars(3)
    print(a)
    print(b)
    print(c)

    parent = Relation()
    facts(parent, ("Homer", "Bart"), ("Homer", "Lias"), ("Abe", "Homer"))
    print(run(2, x, parent("Homer", x)))

    y = var()
    print(run(1, x, parent(x, y), parent(y, 'Bart')))

    def grandparent(x, z):
        y = var()
        return conde((parent(x, y), parent(y, z)))

    print(run(1, x, grandparent(x, 'Bart')))
    menu()  #calls the menu function (a menu loop)
コード例 #28
0
def test_assoccomm():
    x, a, b, c = tt.dvectors("xabc")
    test_expr = x + 1
    q = var()

    res = run(1, q, applyo(tt.add, etuple(*test_expr.owner.inputs), test_expr))
    assert q == res[0]

    res = run(1, q, applyo(q, etuple(*test_expr.owner.inputs), test_expr))
    assert tt.add == res[0].reify()

    res = run(1, q, applyo(tt.add, q, test_expr))
    assert mt(tuple(test_expr.owner.inputs)) == res[0]

    x = var()
    res = run(0, x, eq_comm(mt.mul(a, b), mt.mul(b, x)))
    assert (mt(a), ) == res

    res = run(0, x, eq_comm(mt.add(a, b), mt.add(b, x)))
    assert (mt(a), ) == res

    (res, ) = run(0, x, eq_assoc(mt.add(a, b, c), mt.add(a, x)))
    assert res == mt(b + c)

    (res, ) = run(0, x, eq_assoc(mt.mul(a, b, c), mt.mul(a, x)))
    assert res == mt(b * c)
コード例 #29
0
def test_assoccomm():
    from symbolic_pymc.relations import buildo

    x, a, b, c = tt.dvectors('xabc')
    test_expr = x + 1
    q = var('q')

    res = run(1, q, buildo(tt.add, test_expr.owner.inputs, test_expr))
    assert q == res[0]

    res = run(1, q, buildo(q, test_expr.owner.inputs, test_expr))
    assert tt.add == res[0].reify()

    res = run(1, q, buildo(tt.add, q, test_expr))
    assert mt(tuple(test_expr.owner.inputs)) == res[0]

    res = run(0, var('x'), eq_comm(mt.mul(a, b), mt.mul(b, var('x'))))
    assert (mt(a), ) == res

    res = run(0, var('x'), eq_comm(mt.add(a, b), mt.add(b, var('x'))))
    assert (mt(a), ) == res

    res = run(0, var('x'), (eq_assoc, mt.add(a, b, c), mt.add(a, var('x'))))

    # TODO: `res[0]` should return `etuple`s.  Since `eq_assoc` effectively
    # picks apart the results of `arguments(...)`, I don't know if we can
    # keep the `etuple`s around.  We might be able to convert the results
    # to `etuple`s automatically by wrapping `eq_assoc`, though.
    res_obj = etuple(*res[0]).eval_obj
    assert res_obj == mt(b + c)

    res = run(0, var('x'), (eq_assoc, mt.mul(a, b, c), mt.mul(a, var('x'))))
    res_obj = etuple(*res[0]).eval_obj
    assert res_obj == mt(b * c)
コード例 #30
0
def finish_maze(current_position, path):
    x = var()
    if current_position == 1:
        path = path[::-1]
        print(path)
    else:
        current_position = run(1, x, maze_path(x, current_position))[0]
        path += ">-%d" % current_position
        finish_maze(current_position, path)
コード例 #31
0
ファイル: test_sudoku.py プロジェクト: logpy/logpy
def sudoku_solver(hints):
    variables = vars(hints)
    rows = get_rows(variables)
    cols = get_columns(rows)
    sqs = get_squares(rows)
    return run(
        1,
        variables,
        everyg(all_numbers, rows),
        everyg(all_numbers, cols),
        everyg(all_numbers, sqs)
    )
コード例 #32
0
ファイル: user_classes.py プロジェクト: logpy/logpy
            Account('Carl', 'Marx', 2, 3),
            Account('John', 'Rockefeller', 3, 1000))

# optional name strings are helpful for debugging
first = var('first')
last = var('last')
ident = var('ident')
balance = var('balance')
newbalance = var('newbalance')

# Describe a couple of transformations on accounts
source = Account(first, last, ident, balance)
target = Account(first, last, ident, newbalance)

theorists = ('Adam', 'Carl')
# Give $10 to theorists
theorist_bonus = lall((membero, source, accounts),
                      (membero, first, theorists),
                      (add, 10, balance, newbalance))

# Take $10 from anyone with more than $100
tax_the_rich = lall((membero, source, accounts),
                    (gt, balance, 100),
                    (sub, balance, 10, newbalance))

print("Take $10 from anyone with more than $100")
print((run(0, target, tax_the_rich)))

print("Give $10 to theorists")
print((run(0, target, theorist_bonus)))
コード例 #33
0
ファイル: test_arith.py プロジェクト: logpy/logpy
def test_complex():
    numbers = tuple(range(10))
    results = set(run(0, x, (sub, y, x, 1), (membero, y, numbers), (
        mod, y, 2, 0), (membero, x, numbers)))
    expected = set((1, 3, 5, 7))
    assert results == expected
コード例 #34
0
ファイル: states.py プロジェクト: logpy/logpy
    fact(coastal, state)            # e.g. 'NY' is coastal

with open('examples/data/adjacent-states.txt') as f: # lines like 'CA,OR,NV,AZ'
    adjlist = [line.strip().split(',') for line in f
                                       if line and line[0].isalpha()]

for L in adjlist:                   # ['CA', 'OR', 'NV', 'AZ']
    head, tail = L[0], L[1:]        # 'CA', ['OR', 'NV', 'AZ']
    for state in tail:
        fact(adjacent, head, state) # e.g. 'CA' is adjacent to 'OR',
                                    #      'CA' is adjacent to 'NV', etc...

x = var()
y = var()

print((run(0, x, adjacent('CA', 'NY')))) # is California adjacent to New York?
# ()

print((run(0, x, adjacent('CA', x))))    # all states next to California
# ('OR', 'NV', 'AZ')

print((run(0, x, adjacent('TX', x),    # all coastal states next to Texas
                coastal(x))))
# ('LA',)

print((run(5, x, coastal(y),           # five states that border a coastal state
                adjacent(x, y))))
# ('VT', 'AL', 'WV', 'DE', 'MA')

print((run(0, x, adjacent('TN', x),    # all states adjacent to Tennessee
                adjacent('FL', x))))    #        and adjacent to Florida
コード例 #35
0
ファイル: commutative.py プロジェクト: logpy/logpy
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative

# Define some dummy Operationss
add = 'add'
mul = 'mul'
# Declare that these ops are commutative using the facts system
fact(commutative, mul)
fact(commutative, add)
fact(associative, mul)
fact(associative, add)

# Define some wild variables
x, y = var('x'), var('y')

# Two expressions to match
pattern = (mul, (add, 1, x), y)                # (1 + x) * y
expr    = (mul, 2, (add, 3, 1))                # 2 * (3 + 1)
print(run(0, (x,y), eq(pattern, expr)))        # prints ((3, 2),) meaning
                                               #   x matches to 3
                                               #   y matches to 2
コード例 #36
0
ファイル: corleone.py プロジェクト: logpy/logpy
              ('Sonny', 'Frank'),
              ('Sonny', 'Santino'))

facts(mother, ('Carmela', 'Michael'),
              ('Carmela', 'Sonny'),
              ('Carmela', 'Fredo'),
              ('Kay', 'Mary'),
              ('Kay', 'Anthony'),
              ('Sandra', 'Francesca'),
              ('Sandra', 'Kathryn'),
              ('Sandra', 'Frank'),
              ('Sandra', 'Santino'))

q = var()

print((run(0, q, father('Vito', q))))          # Vito is the father of who?
# ('Sonny', 'Michael', 'Fredo')


print((run(0, q, father(q, 'Michael'))))       # Who is the father of Michael?
# ('Vito',)

def parent(p, child):
    return conde([father(p, child)], [mother(p, child)])


print((run(0, q, parent(q, 'Michael'))))       # Who is a parent of Michael?
# ('Vito', 'Carmela')

def grandparent(gparent, child):
    p = var()