Exemple #1
0
    def test_issue_8(self):
        """
        Callbacks can cause segv's

        https://code.google.com/p/pyswip/issues/detail?id=8
        """

        from pyswip import Prolog, registerForeign

        callsToHello = []

        def hello(t):
            callsToHello.append(t)

        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("parent(michael,john)")
        prolog.assertz("parent(michael,gina)")
        p = prolog.query("parent(michael,X), hello(X)")
        result = list(p)  # Will run over the iterator

        self.assertEqual(len(callsToHello), 2)  # ['john', 'gina']
        self.assertEqual(len(result), 2)  # [{'X': 'john'}, {'X': 'gina'}]
Exemple #2
0
    def test_issue_Unicode(self):
        """
        Unicode support
        """

        from pyswip import Prolog, registerForeign

        Prolog.assertz('отец(дима,миша)')
        Prolog.assertz('отец(дима,настя)')
        Prolog.assertz('отец(дима,света)')
        Prolog.assertz('отец(сергей,оля)')
        Prolog.assertz('отец(сергей,саша)')
        results = list(Prolog.query('отец(дима,Ребенок)'))
        self.assertEqual(len(results), 3)

        results = list(Prolog.query('отец(Отец,Ребенок)'))
        self.assertEqual(len(results), 5)

        callsToHello = []
        def hello(t):
            callsToHello.append(t.value)
        hello.arity = 1

        registerForeign(hello)

        p = Prolog.query("отец(дима,X), hello(X)")
        result = list(p)

        self.assertEqual(callsToHello, ['миша', 'настя', 'света'])
Exemple #3
0
    def test_nondeterministic_foreign(self):
        prolog = Prolog()

        def nondet(a, context):
            control = PL_foreign_control(context)
            context = PL_foreign_context(context)
            if control == PL_FIRST_CALL:
                context = 0
                a.unify(int(context))
                context += 1
                return PL_retry(context)
            elif control == PL_REDO:
                a.unify(int(context))
                if context == 10:
                    return False
                context += 1
                return PL_retry(context)
            elif control == PL_PRUNED:
                pass

        nondet.arity = 1
        registerForeign(nondet, flags=PL_FA_NONDETERMINISTIC)
        result = list(prolog.query("nondet(X)"))

        self.assertEqual(len(result), 10, 'Query should return 10 results')
        for i in range(10):
            self.assertTrue({'X': i} in result,
                            'Expected result  X:{} not present'.format(i))
Exemple #4
0
    def run(self) -> None:
        prolog = PrologMT()
        prolog.consult(
            "C:/Users/Deniz Gorur/PycharmProjects/SummerProject/simulator.pl")

        registerForeign(t.process_event)

        arr = "[set(cooperationcost(1)), set(cooperationbenefit(10)), set(starttime(0)), set(rounds(1, 2)), set(generationinfo(1, 10)), output(resultsin('resultsexp1.pl')), output(eventsin('historyexp1.pl'))]"
        list(prolog.query("run(" + arr + ")"))
Exemple #5
0
    def test_nested_lists(self):
        def get_list_of_lists(result):
            result.value = [[1], [2]]

        get_list_of_lists.arity = 1

        registerForeign(get_list_of_lists)

        prolog = Prolog()

        result = list(prolog.query("get_list_of_lists(Result)"))
        self.assertTrue(
            {'Result': [[1], [2]]} in result,
            'Nested lists should be unified correctly as return value.')
Exemple #6
0
    def test_register_with_module(self):
        def get_int(result):
            result.value = 1

        get_int.arity = 1

        registerForeign(get_int, module="my_module")

        prolog = Prolog()

        result = list(prolog.query("my_module:get_int(Result)"))
        self.assertTrue(
            {'Result': 1} in result,
            'One should be able to call the foreign predicate by using the module name.'
        )
Exemple #7
0
    def test_deterministic_foreign(self):
        def hello(t):
            print("Hello,", t)

        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("father(michael,john)")
        prolog.assertz("father(michael,gina)")
        result = list(prolog.query("father(michael,X), hello(X)"))
        self.assertEqual(len(result), 2, 'Query should return two results')
        for name in ('john', 'gina'):
            self.assertTrue({'X': name} in result,
                            'Expected result  X:{} not present'.format(name))
Exemple #8
0
    def load_plugins(self):
        self.classes = set()
        geolog_core.predicate.get_classes_from_paths(self.plugins,
                                                     self.classes)
        for cls in self.classes:
            if cls.get_predicate_name():

                for arity in range(cls.get_minimum_arity(),
                                   cls.get_maximum_arity() + 1):
                    if cls.is_deterministic():
                        pyswip.registerForeign(cls.execute,
                                               name=cls.get_predicate_name(),
                                               arity=arity,
                                               module=cls.get_module_name())
                    else:
                        pyswip.registerForeign(
                            cls.execute,
                            name=cls.get_predicate_name(),
                            arity=arity,
                            flags=pyswip.core.PL_FA_NONDETERMINISTIC,
                            module=cls.get_module_name())
Exemple #9
0
    def test_atoms_and_strings_distinction(self):
        test_string = "string"

        def get_str(string):
            string.value = test_string

        def test_for_string(string, test_result):
            test_result.value = (test_string == string.decode('utf-8'))

        get_str.arity = 1
        test_for_string.arity = 2

        registerForeign(get_str)
        registerForeign(test_for_string)

        prolog = Prolog()

        result = list(
            prolog.query("get_str(String), test_for_string(String, Result)"))
        self.assertEqual(
            result[0]['Result'], 'true',
            'A string return value should not be converted to an atom.')
Exemple #10
0
    def test_atoms_and_strings_distinction(self):
        def get_str(string):
            string.value = "string"

        def test_for_string(string, result):
            result.value = isinstance(string, str)

        get_str.arity = 1
        test_for_string.arity = 2

        registerForeign(get_str)
        registerForeign(test_for_string)

        prolog = Prolog()

        result = list(
            prolog.query("get_str(String), test_for_string(String, Result)"))
        self.assertTrue(
            {
                'Result': 'true',
                'String': 'string'
            } in result,
            'A string return value should not be converted to an atom.')
Exemple #11
0
    def test_issue_8(self):
        """
        Callbacks can cause segv's

        https://code.google.com/p/pyswip/issues/detail?id=8
        """

        from pyswip import Prolog, registerForeign

        callsToHello = []
        def hello(t):
            callsToHello.append(t)
        hello.arity = 1

        registerForeign(hello)

        prolog = Prolog()
        prolog.assertz("parent(michael,john)")
        prolog.assertz("parent(michael,gina)")
        p = prolog.query("parent(michael,X), hello(X)")
        result = list(p)   # Will run over the iterator
        
        self.assertEqual(len(callsToHello), 2)  # ['john', 'gina']
        self.assertEqual(len(result), 2) # [{'X': 'john'}, {'X': 'gina'}]
Exemple #12
0
from pyswip import Prolog, registerForeign

prolog = Prolog()
prolog.consult("solver2.pl")
prolog.consult("problem.pl")


class ScoreFunction():
    def __init__(self):
        self.i = 0
        self.arity = 2
        self.__name__ = 'foreign_score'

    def __call__(self, goal, res):
        print(goal)
        res.unify(self.i)
        self.i -= 1
        return True


foreign_score = ScoreFunction()
registerForeign(foreign_score)
query = 'solve(path(a,e), P)'

for l in prolog.query(query):
    print(l)
Exemple #13
0
from pyswip import Prolog,registerForeign

factsDic={}
def verify(Question):
    if Question in factsDic:
        if factsDic[Question]=='y':
            return 1
        if factsDic[Question]=='n':
            return 0
    else:
        print('Does the animal has the attribute :',Question,'(y/n)?')
        Response = input()
        if Response == 'y':
            factsDic[Question]='y'
            return 1
        else:
            factsDic[Question]='n'
            return 0
verify.arity=1        

registerForeign(verify)
prolog = Prolog()
prolog.consult('animalPy.pl')
for soln in prolog.query("hypothesize(X)"):
    print("This animal is:",soln["X"])
Exemple #14
0
def solve(*a):
    eqs = [parse_expr(s) for s in str(a[0]).split(',')]
    target = parse_expr(str(a[1]) + '-chi')
    eqs.append(target)
    xs = set()
    for eq in eqs:
        xs.update(eq.free_symbols)
    xs = list(xs)
    xi = xs.index(Symbol('chi'))
    sols = nonlinsolve(eqs, xs)
    sol = sols.args[0]
    a[2].value = str(sol[xi])
    return True


registerForeign(solve, arity=3)

prolog = Prolog()
prolog.consult('mybot.pl')

model = {'nodes': {}}


def getCNode(model, sentenceNo, wordNo):
    return model['nodes'][sentenceNo][wordNo]


def findCNode(model, sent, noun=None, number=None, poss=None):
    def compareNouns(noun1, noun2):
        return stemmer.lemmatize(noun1) == stemmer.lemmatize(noun2)
Exemple #15
0
from pyswip import Prolog, registerForeign


def hello(t):  # 包含一个参数,返回值为布尔类型
    print("Hello,", t)


hello.arity = 1  # 这个属性是必须的
registerForeign(hello)
prolog = Prolog()
prolog.assertz("father(michael,john)")  # 事实1:michael 是john 的父亲
prolog.assertz("father(michael,gina)")  # 事实2:michael 是gina 的父亲

print(list(prolog.query("father(michael,X), hello(X)")))  # 查询
Exemple #16
0
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


from pyswip import Prolog, registerForeign, Atom


def atom_checksum(*a):
    if isinstance(a[0], Atom):
        r = sum(ord(c)&0xFF for c in str(a[0]))
        a[1].value = r&0xFF
        return True
    else:
        return False

p = Prolog()
registerForeign(atom_checksum, arity=2)
print list(p.query("X='Python', atom_checksum(X, Y)", catcherrors=False))
Exemple #17
0
    Value.unify(result)
    return True
python_value.arity = 2

def python_policy(State, Score):
    sparse = dok_matrix((1, n_features), dtype=np.float32)
    for (k,v) in State:
        sparse[0, k] = v
    if args.model_type == "Simple Dense":
        result = policy_NN(sparse)
    result = int(result * 1e8)
    Score.unify(result)
    return True
python_policy.arity=2

pyswip.registerForeign(python_value)
pyswip.registerForeign(python_policy)

leancop_settings = "conj,def"
leancop_settings = "{},comp({})".format(leancop_settings, args.pathlim)
leancop_settings = "{},eager_reduction({})".format(leancop_settings, args.eager_reduction)
leancop_settings = "{},paramodulation({})".format(leancop_settings, args.paramodulation)
leancop_settings = "{},extra_axioms(\"{}\")".format(leancop_settings, args.extra_axioms)

Params = "guided({}),cp({}),sim_depth({}),playout_count({}),min_visit_count({}),n_dim({}),playout_time({}), output_format({}), leancop_settings([{}])".format(args.guided, args.cp, args.sim_depth, args.playout, args.min_visit_count, args.n_dim, args.playout_time, args.output_format, leancop_settings)
Params = "{},return_to_root({})".format(Params, args.return_to_root)
Params = "{},save_all_proofs({})".format(Params, args.save_all_proofs)
Params = "{},temperature({})".format(Params, args.temperature)
Params = "{},save_all_policy({})".format(Params, args.save_all_policy)
Params = "{},save_all_value({})".format(Params, args.save_all_value)
Params = "{},lemma_features({})".format(Params, args.lemma_features)
Exemple #18
0
        for (k, v) in a:
            state[i, k] = v

    d_state = xgb.DMatrix(state)
    scores = policy_model.predict(d_state)
    expScores = np.exp(scores / Temp)
    sumExpScores = np.sum(expScores)
    probs = expScores / sumExpScores
    Probs.unify(",".join([str(p) for p in probs]))

    # print("value: ", value)
    # print("policy: " , probs)


python_xgboost_predict.arity = 5
pyswip.registerForeign(python_xgboost_predict)


def python_nn_predict(StateV, StateP, Actions, Temp, Value, Probs):
    # t0 = time.time()
    value_dimension = 128
    state = np.array(StateV)
    keys = np.array([state[:, 0]])
    vals = np.array([state[:, 1]])
    vals = np.minimum(vals, np.ones_like(vals) * 10)

    if args.densify == 1:
        model_input = sparse_to_dense(keys, vals, value_dimension)
    else:
        model_input = [keys, vals]
    # t1 = time.time()
from pyswip import Prolog, Variable, Query, call, Functor, registerForeign
# Primera prueba de funcionamiento
"""
def hello(x):
    print(x)
hello.arity = 1
registerForeign(hello)
prolog = Prolog()
prolog.consult("Parientes.pl")
result = []
x = ''
print(list(prolog.query("progenitor(pedro,X). , hello(X)")))
"""


def main():
    prolog = Prolog()
    prolog.consult("Parientes.pl")
    result = []
    progenitor = Functor("progenitor", 2)

    X = Variable()

    q = Query(progenitor("pedro", X))
    while q.nextSolution():
        print(X.value)
        result.append(X.value)
    q.closeQuery()
    return result
Exemple #20
0
from pyswip import Prolog, registerForeign, Atom

def atom_checksum(*a):
    print a
    if isinstance(a[0], Atom):
        r = sum(ord(c)&0xFF for c in str(a[0]))
        a[1].value = r&0xFF
        return True
    else:
        return False

p = Prolog()
registerForeign(atom_checksum, arity=2)
print list(p.query("X='Python', atom_checksum(X, Y)"))
Exemple #21
0
    def get_v_str(self, x):
        return x.chars

import pyswip
prolog = pyswip.Prolog()
prolog.consult("term2list.pl")

graph = TermGraph(PrologDecoder(prolog))

def gnn_test_policy(State, Score):
    #res = next(prolog.query("term2list(f(a)+X+X*Y-f(a), TermEncoding)"))["TermEncoding"]
    res = State
    #print('root index', graph.get_term(res))
    #print('fun_d', graph.fun_d)
    #print('node_d', graph.node_d)
    node_inputs, symbol_inputs = graph.export_indices()
    for i,d in enumerate(node_inputs):
        name = "node_inputs{}/".format(i+1)
        for key, val in d.items():
            print(name+key, val)
    name = "symbol_inputs/"
    for key, val in symbol_inputs.items():
        print(name+key, val)
    result = int(1)
    Score.unify(result)
    return True
gnn_test_policy.arity=2
        
pyswip.registerForeign(gnn_test_policy)