Example #1
0
    def test_double(self):

        with pytest.raises(DobuleInitalizationException):
            logicnet = LogicNet()
            logicnet.predicate("country", argument_size=10)
            logicnet.predicate("country", argument_size=10)
Example #2
0
from pymetheus.pymetheus import LogicNet

ll = LogicNet()

ll.constant("a")
ll.constant("b")
ll.constant("c")
ll.constant("d")
ll.constant("e")
ll.constant("k")
ll.constant("p")
ll.constant("n")
ll.constant("a1")
ll.constant("a2")
ll.constant("a3")
ll.constant("a4")
ll.constant("a5")
ll.constant("a6")
ll.constant("a7")
ll.constant("a8")
ll.constant("a9")
ll.constant("a10")
ll.constant("a11")
ll.constant("a12")

ll.constant("a13")
ll.constant("a14")

ll.constant("a15")
ll.constant("a16")
Example #3
0
        # We want only binary axioms between entities/properties (no assertions)
        if re.search(regex, axiom):
            match = re.match(regex, axiom)
            predicates.add(match.group(1))
            constants.update([match.group(2), match.group(3)])
            axioms.append({
                'pred': match.group(1),
                's': match.group(2),
                'o': match.group(3)
            })

print(len(predicates))
print(len(constants))

# Build the network
ll = LogicNet()
for pred in predicates:
    ll.predicate(pred, argument_size=100)

for const in constants:
    ll.constant(const, argument_size=100)

for axiom in axioms:
    ll.knowledge(f'"{axiom["pred"]}"("{axiom["s"]}","{axiom["o"]}")')

ll.fit()

ll.reason(
    'SubClassOf("<http://dbpedia.org/ontology/Meeting>","<http://dbpedia.org/ontology/SocietalEvent>")',
    True)
ll.reason(
Example #4
0
    def test_double(self):

        with pytest.raises(DobuleInitalizationException):
            logicnet = LogicNet()
            logicnet.constant("Rome", argument_size=10)
            logicnet.constant("Rome", argument_size=10)
Example #5
0
    def test_size(self):
        logicnet = LogicNet()
        logicnet.constant("Rome", argument_size=10)

        assert len(logicnet.constants["Rome"]) == 10
Example #6
0
from pymetheus.pymetheus import LogicNet

ll = LogicNet()

ll.constant("Rome")

ll.constant("Italy")
ll.constant("France")
ll.constant("Paris")
ll.constant("Lion")
ll.constant("Turin")
ll.constant("Milan")
ll.constant("Berlin")
ll.constant("Monaco")
ll.constant("Germany")

ll.constant("Duomo")
ll.constant("Trevi")
ll.constant("Mole")

ll.constant("Italian")
ll.constant("French")

ll.predicate("location")
ll.predicate("capital")
ll.predicate("country")
ll.predicate("lives")

ll.knowledge("lives(Italian,Italy)")
ll.knowledge("~lives(Italian,Italian)")
ll.knowledge("lives(French,France)")
Example #7
0
import cloudpickle
from pymetheus.pymetheus import LogicNet

# Read vectors for training
vectors = cloudpickle.load(open('data/vectors.pickle', 'rb'))
fr = vectors['FR'][:200]
it = vectors['IT'][:200]

# Define the LTN
ll = LogicNet()
ll.predicate("country", argument_size=200)
ll.constant("France", definition=vectors['France']['vec'])
ll.constant("Italy", definition=vectors['Italy']['vec'])
for f in fr:
    ll.constant(f['uri'], definition=f['vec'])
for i in it:
    ll.constant(i['uri'], definition=i['vec'])

for f in fr:
    for i in it:
        ll.knowledge(f"country({f['uri']},France)")
        ll.knowledge(f"~country({f['uri']},Italy)")
        ll.knowledge(f"country({i['uri']},Italy)")
        ll.knowledge(f"~country({i['uri']},France)")

ll.variable("?a", (list(map(lambda x: x['uri'], fr)) +
                   list(map(lambda x: x['uri'], it))))  # all cities
ll.variable("?b", ['Italy', 'France'])  # all countries
rule_3 = "forall ?a,?b: country(?a,?b) -> ~country(?b,?a)"  # country is not symmetric
rule_4 = "forall ?a: ~country(?a,?a)"  # cities are not the country of themselves
rule_6 = "forall ?a,?b: ~country(?b,?a)"  # country is defined from cities to countries and not vice-versa
Example #8
0
import pymetheus
from pymetheus.pymetheus import LogicNet
import numpy as np
ll = LogicNet()

ll.constant('John', definition=np.random.normal(0,.1,size=2))
ll.constant('Jim', definition=np.random.normal(0,.1,size=2))

ll.predicate('Male', arity=1, argument_size = 2) # A is a unary predicate on objects with 2 features
ll.predicate('CanPlayWith', arity=2, argument_size = 2)


print(ll.reason("CanPlayWith(John,Jim)"))

domain_of_variables = np.random.uniform(0,1,size=(100,2))

ll.variable('?x', domain_of_variables, labelled=False)

ll.universal_rule('forall ?x: Male(?x) -> Male(?x)')

print(ll.reason("forall ?x: Male(?x) -> Male(?x)"))
Example #9
0
from pymetheus.pymetheus import LogicNet

ll = LogicNet()

g1,g2='abcdefgh','ijklmn'
g=g1+g2
for l in g:
    ll.constant(l)

friends = [('a','b'),('a','e'),('a','f'),('a','g'),('b','c'),('c','d'),('e','f'),('g','h'),
           ('i','j'),('j','m'),('k','l'),('m','n')]

ll.predicate("Friends")
ll.predicate("Cancer", arity=1)
ll.predicate("Smokes", arity=1)

[ll.knowledge("Friends(%s,%s)" %(x,y)) for (x,y) in friends]
[ll.knowledge("~Friends(%s,%s)" %(x,y)) for x in g1 for y in g1 if (x,y) not in friends and x < y]
[ll.knowledge("~Friends(%s,%s)" %(x,y)) for x in g2 for y in g2 if (x,y) not in friends and x < y]

smokes = ['a','e','f','g','j','n']
[ll.knowledge("Smokes(%s)" % x) for x in smokes]
[ll.knowledge("~Smokes(%s)" % x) for x in g if x not in smokes]

cancer = ['a','e']
[ll.knowledge("Cancer(%s)" % x) for x in cancer]
[ll.knowledge("~Cancer(%s)" % x) for x in g1 if x not in cancer]



#var = ["Paris", "France", "Italy", "Rome", "Milan"]#, "Turin", "Lion", "Mole", "Duomo", "Trevi", "Berlin", "Monaco", "Germany", "Italian", "French"]
Example #10
0
from pymetheus.pymetheus import LogicNet
from pymetheus.logics.fuzzy_logic import *
from pymetheus.parser import rule_parser as parser

ll = LogicNet()


ll.constant("Rome")
ll.constant("Italy")
ll.constant("Paris")


ll.variable("?a", ["Rome", "Paris"])

print(ll.variables["?a"])


print("constants are vectors in a dictionary")
print(ll.constants["Rome"])

ll.predicate("country")
ll.predicate("capital")
print()
print("predicates are networks in a dictionary")
print(ll.networks["country"])

print()
ll.knowledge("country(Rome,Italy)")
ll.knowledge("~country(Paris,Italy)")
print("training samples are stored as tuples")
print(ll.axioms)
Example #11
0
from pymetheus.pymetheus import LogicNet
import torch
import torch.nn.functional as F

ll = LogicNet()


class equal_simple(torch.nn.Module):
    def __init__(self):
        super(equal_simple, self).__init__()
        self.system = False

    def forward(self, x, y):
        assert x.shape == y.shape

        delta = torch.nn.PairwiseDistance()(x, y)
        #delta = F.relu(delta)

        similarity = torch.exp(-delta).reshape(-1, 1)

        return similarity


city = [
    'Paris_fr', 'Montpellier_fr', 'Nice_fr', 'NewYork_us', 'Paris_us',
    'Austin_us', 'Washingtondc_us'
]
nation = ['France', 'UnitedStates']

all_value = city + nation
Example #12
0
from pymetheus.pymetheus import LogicNet

from pymetheus.pymetheus import LogicNet
import pandas as pd
from sklearn.metrics import f1_score, accuracy_score, recall_score,precision_score

ll = LogicNet()

ll.predicate("subclass")


entities = ["Cat", "Feline", "Mammal", "Agent", "Thing", "Dog", "Human",
            "Reptile", "Organization", "Company", "Animal", "Bank", "Snake", "Squirrel", "Dolphin", "Shark", "Bird",
            "Fish", "Lizard", "Crocodile", "BlueFish", "LilBird", "Eagle", "BaldEagle"]

relationships = (
    ("Cat", "Feline"), ("Feline", "Mammal"), ("Mammal", "Animal"), ("Animal", "Agent"), ("Agent", "Thing"),
    ("Dog", "Mammal"), ("Human", "Mammal"), ("Organization", "Agent"), ("Company", "Organization"),
    ("Bank", "Company"), ("Snake", "Reptile"), ("Reptile", "Animal"),
    ("Dolphin", "Mammal"), ("Shark", "Fish"), ("Lizard", "Reptile"),
    ("Crocodile", "Reptile"), ("BlueFish", "Fish"),
    ("LilBird", "Bird"), ("Eagle", "Bird"), ("BaldEagle", "Bird"), ("Bird", "Animal"), ("Fish", "Animal"),
    ("Shark", "Fish"), ("Squirrel", "Mammal"))

for a in entities:
    ll.constant(a)

for a, b in relationships:
    ll.knowledge("subclass(" + a + "," + b + ")")

#ll.zeroing()