Example #1
0
    def assert_fact(self, fact: Atom) -> None:
        try:
            fact.get_predicate().get_engine_obj(KANREN_LOGPY)
        except Exception:
            fact.get_predicate().add_engine_object(
                (KANREN_LOGPY, kanren.Relation()))

        kanren.fact(fact.get_predicate().get_engine_obj(KANREN_LOGPY),
                    *[x.as_kanren() for x in fact.get_terms()])
Example #2
0
    def assert_fact(self, fact: Atom) -> None:
        self.add_variable_mapping(fact.get_predicate())
        for term in fact.get_terms():
            self.add_variable_mapping(term)

        kanren.fact(
            fact.get_predicate().as_kanren(), *[
                x.as_kanren() if getattr(x, "as_kanren", None) else x
                for x in fact.get_terms()
            ])
Example #3
0
def gather_inside_outside_quote_facts(R, doc):
    inside = False
    R['insideq'] = Relation('insideq')
    R['outsideq'] = Relation('outsideq')
    for token in doc:
        if token.text == '"':
            inside = not inside
        else:
            if inside:
                fact(R['insideq'], token.i)
            else:
                fact(R['outsideq'], token.i)
Example #4
0
def gather_facts(doc):
    R = {'LEMMA': Relation('LEMMA'),
         'root': Relation('root'),
         'head': Relation('head')}
    for rel in DEPS:
        R[rel] = Relation(rel)
    for tok in doc:
        facts(R['LEMMA'], (tok.i, tok.lemma_))
        if not tok.pos_ in R:
            R[tok.pos_] = Relation(tok.pos_)
        fact(R[tok.pos_], (tok.i))

        facts(R[tok.dep_ if tok.head.i != tok.i else 'root'],
              (tok.head.i if tok.head.i != tok.i else -1, tok.i))
        facts(R['head'], (tok.head.i if tok.head.i != tok.i else -1, tok.i))

        if not tok.ent_type_ in R:
            R[tok.ent_type_] = Relation(tok.ent_type_)
        fact(R[tok.ent_type_], (tok.i))

    gather_inside_outside_quote_facts(R, doc)

    return R
Example #5
0
def test_KanrenRelationSub_filters():
    x_at = at.vector("x")
    y_at = at.vector("y")
    z_at = at.vector("z")
    A_at = at.matrix("A")

    fact(commutative, _dot)
    fact(commutative, at.add)
    fact(associative, at.add)

    Z_at = A_at.dot((x_at + y_at) + z_at)

    fgraph = FunctionGraph(outputs=[Z_at], clone=False)

    def distributes(in_lv, out_lv):
        A_lv, x_lv, y_lv, z_lv = vars(4)
        return lall(
            # lhs == A * (x + y + z)
            eq_assoccomm(
                etuple(_dot, A_lv,
                       etuple(at.add, x_lv, etuple(at.add, y_lv, z_lv))),
                in_lv,
            ),
            # This relation does nothing but provide us with a means of
            # generating associative-commutative matches in the `kanren`
            # output.
            eq((A_lv, x_lv, y_lv, z_lv), out_lv),
        )

    def results_filter(results):
        _results = [eval_if_etuple(v) for v in results]

        # Make sure that at least a couple permutations are present
        assert (A_at, x_at, y_at, z_at) in _results
        assert (A_at, y_at, x_at, z_at) in _results
        assert (A_at, z_at, x_at, y_at) in _results

        return None

    _ = KanrenRelationSub(distributes,
                          results_filter=results_filter).transform(
                              fgraph, fgraph.outputs[0].owner)

    res = KanrenRelationSub(distributes,
                            node_filter=lambda x: False).transform(
                                fgraph, fgraph.outputs[0].owner)
    assert res is False
Example #6
0
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative

add = 'add'
mul = 'mul'

fact(commutative, mul)
fact(commutative, add)
fact(associative, mul)
fact(associative, add)

a, b = var('a'), var('b')

original_pattern = (mul, (add, 5, a), b)

exp1 = (mul, 2, (add, 3, 1))
exp2 = (add, 5, (mul, 8, 1))

print(run(0, (a, b), eq(original_pattern, exp1)))
print(run(0, (a, b), eq(original_pattern, exp2)))
Example #7
0
from kanren import run, var, fact
import kanren.assoccomm as ka

# Define mathematical operations
add = 'addition'
mul = 'multiplication'

# Deckare that these operations are commutative
# using the facts system
fact(ka.commutative, mul)
fact(ka.commutative, add)
fact(ka.associative, mul)
fact(ka.associative, add)

# Define some variables
a, b, c = var('a'), var('b'), var('c')

# Generate expressions
expression_orig = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1))
expression1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c))
expression2 = (add, (mul, c, 3), (mul, b, (add, (mul, 2, a), 1)))
expression3 = (add, (add, (mul, (mul, 2, a), b), b), (mul, 3, c))

# Compare expressions
print(run(0, (a, b, c), ka.eq_assoccomm(expression1, expression_orig)))
print(run(0, (a, b, c), ka.eq_assoccomm(expression2, expression_orig)))
print(run(0, (a, b, c), ka.eq_assoccomm(expression3, expression_orig)))
Example #8
0
The `adjacency` relation expresses which states border each other.
The `coastal` relation expresses which states border the ocean.
"""
from kanren import Relation, fact, run, var

adjacent = Relation()
coastal = Relation()

coastal_states = (
    "WA,OR,CA,TX,LA,MS,AL,GA,FL,SC,NC,VA,MD,DE,NJ,NY,CT,RI,MA,ME,NH,AK,HI".
    split(","))

# ['NY', 'NJ', 'CT', ...]
for state in coastal_states:
    # E.g. 'NY' is coastal
    fact(coastal, state)

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

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

#opens the .txt file in order to obtain the synonym words
with open('synonyms.txt') as file:
    synlist = [
        line.strip().split(',') for line in file if line and line[0].isalpha()
    ]

#for loop function creates the word to synonym word relation
for L in synlist:
    head, tail = L[0], L[1:]

    #head is the main word
    #tail are the synonym words
    for state in tail:
        fact(synonym, head, state)

#holds the value when no synonyms are found
empty = (run(1, x, no_synonym("", x)))

#a prompt for the user to understand what this program is, and how to use it
print("######################################################################")
print("Hello, this program will help elevate the writer's paper by providing")
print("different word suggestions. Before proceeding any further,")
print("please import wanted .docx files into this directory first")
print(
    "######################################################################\n")

#the user inputs what file he/she wants to check for improvement
user_input = input("Please input doc name: ")
## expression matcher
from kanren import run, var, fact
import kanren.assoccomm as la

add = 'addition'
mul = 'multiplication'

fact(la.commutative, mul)
fact(la.commutative, add)
fact(la.commutative, mul)
fact(la.commutative, add)

a, b, c = var('a'), var('b'), var('c')

# (3*(-2)) + ((1+2*3)*(-1))
expression_orig = (add, (mul, 3, -2), (mul, (add, 1, (mul, 2, 3)), -1))
# (1 + (2*a))*b + 3*c
expression1 = (add, (mul, (add, 1, (mul, 2, a)), b), (mul, 3, c))
# c*3 + b*(2*a + 1)
expression2 = (add, (mul, c, 3), (mul, b, (add, (mul, 2, a), 1)))
# 2*a*b + b + 3*c
expression3 = (add, (add, (mul, (mul, 2, a), b)), (mul, 3, c))

print(run(0, (a, b, c), la.eq_assoccomm(expression1, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression2, expression_orig)))
print(run(0, (a, b, c), la.eq_assoccomm(expression3, expression_orig)))

## Check prime number
import itertools as it
from kanren import isvar, membero, var, run, eq
from kanren.core import success, fail, condeseq
Example #11
0
from kanren import run, var, fact, Relation

x = var()
human = Relation()

fact(human, "Socrates")


def mortal(x):
    return human(x)


sol = run(1, x, mortal(x))
print(sol)
Example #12
0
from kanren import run, var, fact
from kanren.assoccomm import eq_assoccomm as eq
from kanren.assoccomm import commutative, associative

add = 'add'  #Defining operations
mul = 'mul'
fact(commutative,
     mul)  #Addition and multiplication are commutative and associative
fact(commutative, add)
fact(associative, mul)
fact(associative, add)
x = var()
print(
    "This program solves variable x for the general equation \"ax + b = 0\" with the provided a and b from user"
)
print("Enter a: ")
a = int(input())
print("Enter b: ")
b = int(input())
expression = (add, (mul, a, x), b)
expr1 = expression
expression = (add, (mul, a, (-b / a)), b)
print("x = ", run(1, x, eq(expr1, expression)))
Example #13
0
This example builds a small database of the US states.

The `adjacency` relation expresses which states border each other
The `coastal` relation expresses which states border the ocean
"""
from kanren import run, fact, eq, Relation, var

adjacent = Relation()
coastal = Relation()

coastal_states = 'WA,OR,CA,TX,LA,MS,AL,GA,FL,SC,NC,VA,MD,DE,NJ,NY,CT,RI,MA,ME,NH,AK,HI'.split(
    ',')

for state in coastal_states:  # ['NY', 'NJ', 'CT', ...]
    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()
Example #14
0
adjacent = Relation()
coastal = Relation()

file_coastal = '/home/pi/december-2018/coastal_states.txt'
file_adjacent = '/home/pi/december-2018/adjacent_states.txt'

#read the file containing the coastal states
with open(file_coastal, 'r') as f:
    line = f.read()
    c_states = line.split(',')
    coastal_states = [state.lower() for state in c_states]

#add the info to the fact base
for state in coastal_states:
    fact(coastal, state)

#read the file containing the adjacent states

adjlist = []
with open(file_adjacent, 'r') as f:
    adjlist_raw = [
        line.strip().split(',') for line in f if line and line[0].isalpha()
    ]
    for adj in adjlist_raw:
        ll1 = []
        for adj1 in adj:
            ll1.append(adj1.lower())
        adjlist.append(ll1)

#add info to fact base
Example #15
0
This example builds a small database of the US states.

The `adjacency` relation expresses which states border each other
The `coastal` relation expresses which states border the ocean
"""
from kanren import run, fact, eq, Relation, var

adjacent = Relation()
coastal  = Relation()


coastal_states = 'WA,OR,CA,TX,LA,MS,AL,GA,FL,SC,NC,VA,MD,DE,NJ,NY,CT,RI,MA,ME,NH,AK,HI'.split(',')

for state in coastal_states:        # ['NY', 'NJ', 'CT', ...]
    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?
Example #16
0
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