def _benchmark_setup():
    with kb_context("test_predicate_node"):
        kb = KnowledgeBase()
        pn = get_alpha_predicate_node(BOOPType,"B", "<",50)
        ld = generate_link_data(pn,kb)
        # kb.add_subscriber(pn)
        return (kb, pn, ld), {}
def test_predicate_node_sanity():
    with kb_context("test_predicate_node_sanity"):
        BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})
        kb = KnowledgeBase()

        pn = get_alpha_predicate_node(BOOPType,"B", "<",9)
        pnc = cast(pn, BasePredicateNodeType)
        png = cast(pn, GenericAlphaPredicateNodeType)
        attrs_pn  = np.array([struct_get_attr_offset(pnc,x[0]) for x in base_subscriber_fields+basepredicate_node_fields])
        attrs_pnc = np.array([struct_get_attr_offset(pn, x[0]) for x in base_subscriber_fields+alpha_predicate_node_fields])
        attrs_png = np.array([struct_get_attr_offset(png,x[0]) for x in base_subscriber_fields+alpha_predicate_node_fields])
        assert np.array_equal(attrs_pn,attrs_pnc[:len(attrs_pn)])
        assert np.array_equal(attrs_pn,attrs_png[:len(attrs_pn)])
        assert np.array_equal(attrs_pnc,attrs_png)
        
        ld = generate_link_data(pnc, kb)

        assert len(filter_alpha(png, ld, np.arange(5)))==0

        pn = get_beta_predicate_node(BOOPType,"B", "<", BOOPType,"B")
        pnc = cast(pn, BasePredicateNodeType)
        png = cast(pn, GenericBetaPredicateNodeType)

        ld = generate_link_data(pnc, kb)

        attrs_pn  = np.array([struct_get_attr_offset(pnc,x[0]) for x in base_subscriber_fields+basepredicate_node_fields])
        attrs_pnc = np.array([struct_get_attr_offset(pn, x[0]) for x in base_subscriber_fields+beta_predicate_node_fields])
        attrs_png = np.array([struct_get_attr_offset(png,x[0]) for x in base_subscriber_fields+beta_predicate_node_fields])

        assert np.array_equal(attrs_pn,attrs_pnc[:len(attrs_pn)])
        assert np.array_equal(attrs_pn,attrs_png[:len(attrs_pn)])
        assert np.array_equal(attrs_pnc,attrs_png)
        assert len(filter_beta(png, ld, np.arange(5), np.arange(5))) == 0
def test_inheritence():
    with kb_context("test_inheritence") as context:
        spec1 = {"A": "string", "B": "number"}
        BOOP1, BOOP1Type = define_fact("BOOP1",
                                       spec1,
                                       context="test_inheritence")
        spec2 = {"inherit_from": BOOP1, "C": "number"}
        BOOP2, BOOP2Type = define_fact("BOOP2",
                                       spec2,
                                       context="test_inheritence")
        spec3 = {"inherit_from": BOOP2, "D": "number"}
        BOOP3, BOOP3Type = define_fact("BOOP3",
                                       spec3,
                                       context="test_inheritence")

        assert context.parents_of["BOOP3"] == ["BOOP1", "BOOP2"]
        assert context.children_of["BOOP3"] == []
        assert context.parents_of["BOOP2"] == ["BOOP1"]
        assert context.children_of["BOOP2"] == ["BOOP3"]
        assert context.parents_of["BOOP1"] == []
        assert context.children_of["BOOP1"] == ["BOOP2", "BOOP3"]

        b1 = BOOP1("A", 7)

        @njit
        def check_has_base(b):
            return b.idrec

        assert check_has_base(b1) == u8(-1)
        assert check_has_base.py_func(b1) == u8(-1)
示例#4
0
def test_matching():
    with kb_context("test_link"):
        BOOP, BOOPType = define_fact("BOOP", {"A": "string", "B": "number"})
        l1, l2 = Var(BOOPType, "l1"), Var(BOOPType, "l2")
        r1, r2 = Var(BOOPType, "r1"), Var(BOOPType, "r2")

        c = (l1.B > 0) & (l1.B != 3) & (l1.B < 4) & (l2.B != 3) | \
            (l1.B == 3)

        kb = KnowledgeBase()
        kb.declare(BOOP("0", 0))
        kb.declare(BOOP("1", 1))
        kb.declare(BOOP("2", 2))
        kb.declare(BOOP("3", 3))
        kb.declare(BOOP("4", 4))

        cl = get_linked_conditions_instance(c, kb)

        conditions_get_matches(cl)

        print("----------")

        c = (l1.B <= 1) & (l1.B < l2.B) & (l2.B <= r1.B)

        cl = get_linked_conditions_instance(c, kb)

        conditions_get_matches(cl)
示例#5
0
def test_term():
    with kb_context("test_term"):
        # BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})
        l1, l2 = Var(BOOPType, "l1"), Var(BOOPType, "l2")
        c1 = l1.B < 1
        print(first_alpha(c1))
        # print(c1.dnf[0][0][0].is_alpha)
        c2 = l1.B < l2.B
        print(first_beta(c2))
def _beta_setup():
    with kb_context("test_predicate_node"):
        kb = KnowledgeBase()
        pn = get_beta_predicate_node(BOOPType,"B", "<", BOOPType,"B")
        # kb.add_subscriber(pn)
        ld = generate_link_data(pn, kb)
        idrecs = np.empty((100,),dtype=np.int64)
        for i in range(100):
            idrecs[i] = kb.declare(BOOP("?",i))
        return (kb, pn, ld, np.arange(100), idrecs), {}
示例#7
0
def test_retract_keyerror():
    with kb_context("test_retract_keyerror"):
        #NRT version
        kb = KnowledgeBase()
        with pytest.raises(KeyError):
            retract_keyerror(kb)

        #Python version
        kb = KnowledgeBase()
        with pytest.raises(KeyError):
            retract_keyerror.py_func(kb)
示例#8
0
def test_all_facts_of_type():
    with kb_context("test_all_facts_of_type"):
        #NRT version
        kb = KnowledgeBase()
        declare_retract(kb)
        all_tf = all_of_type(kb)
        assert isinstance(all_tf[0], TextField)
        assert len(all_tf) == 90

        all_tf = all_of_type.py_func(kb)
        assert isinstance(all_tf[0], TextField)
        assert len(all_tf) == 90
def test_protected_mutability():
    print("RUNTIME1.")
    with kb_context("test_protected_mutability") as context:
        print("RUNTIME1.2")
        spec = {"A": "string", "B": "number"}
        BOOP, BOOPType = define_fact("BOOP",
                                     spec,
                                     context="test_protected_mutability")
        print("RUNTIME1.3")
        kb = KnowledgeBase(context="test_protected_mutability")
        print("RUNTIME1")
        b1 = BOOP("A", 0)
        b2 = BOOP("B", 0)
        print("RUNTIME1")

        @njit
        def edit_it(b):
            b.B += 1

        print("RUNTIME2")

        edit_it(b1)
        edit_it(b2)
        # edit_it.py_func(b2)
        print("RUNTIME3")

        @njit
        def declare_it(kb, b, name):
            kb.declare(b, name)

        print("RUNTIME3.1", b1.fact_num)
        declare_it(kb, b1, "b1")
        print("RUNTIME3.2")
        declare_it.py_func(kb, b2, "b2")

        print("RUNTIMEz")

        with pytest.raises(AttributeError):
            print("RUNTIME_PY")
            edit_it.py_func(b1)

        with pytest.raises(AttributeError):
            print("RUNTIME_PY")
            edit_it.py_func(b2)

        with pytest.raises(AttributeError):
            print("RUNTIME_NB", b1.B)
            edit_it(b1)

        with pytest.raises(AttributeError):
            print("RUNTIME_NB", b1.B)
            edit_it(b1)
def get_beta_predicate_node_definition(left_fact_type, left_attr_chain, op_str, right_fact_type, right_attr_chain):
    '''Gets various definitions for an BetaPredicateNode, returns a dict with 'ctor'
         'pnode_type', 'left_type', 'left_attr_offsets', 'left_t_id', 'right_type', 'right_attr_offsets', 'right_t_id' '''
    context = kb_context()    
    left_t_id = context.fact_to_t_id[left_fact_type._fact_name]
    right_t_id = context.fact_to_t_id[right_fact_type._fact_name]

    if(not isinstance(left_attr_chain,list)): attr_chain = [left_attr_chain]
    if(not isinstance(right_attr_chain,list)): attr_chain = [right_attr_chain]
    
    left_type, left_attr_offsets = resolve_deref(left_fact_type, left_attr_chain)
    right_type, right_attr_offsets = resolve_deref(right_fact_type, right_attr_chain)
    ctor, pnode_type = define_beta_predicate_node(left_type, op_str, right_type)

    return locals()
def _fact_from_fields(name, fields, context=None):
    context = kb_context(context)
    hash_code = unique_hash([name,fields])
    if(not source_in_cache(name,hash_code)):
        fact_num = lines_in_fact_registry()
        source = gen_fact_code(name,fields,fact_num)
        source_to_cache(name, hash_code, source)
        add_to_fact_registry(name, hash_code)
        
    fact_ctor, fact_type = import_from_cached(name, hash_code,[name,name+"Type"]).values()
    fact_ctor._hash_code = hash_code
    fact_type._hash_code = hash_code
    # fact_type = fact_type_template(fields=fields)
    # print("fact_type",fact_type)

    return fact_ctor, fact_type
示例#12
0
def test_modify():
    with kb_context("test_modify"):
        TextField, TextFieldType = define_fact("TextField", tf_spec)
        kb = KnowledgeBase()
        fact = TextField("A", "B", "C", "D", "E")

        modify_right(kb, fact, "nb")
        assert fact.to_right == "nb"

        modify_right.py_func(kb, fact, "py")
        assert fact.to_right == "py"

        with pytest.raises(TypingError):
            bad_modify_type(kb)

        with pytest.raises(TypingError):
            bad_modify_type.py_func(kb)
示例#13
0
def test_grow_change_queues():
    with kb_context("test_grow_change_queues"):
        TextField, TextFieldType = define_fact("TextField", tf_spec)
        #NRT version
        kb = KnowledgeBase()
        dummy_subscriber = dummy_subscriber_ctor()
        kb.add_subscriber(dummy_subscriber)

        idrec = kb.declare(TextField("A", "B", "C", "D", "E"))

        # assert kb.kb_data.subscribers[0].grow_queue.data[0] == idrec
        gr_q = kb.kb_data.grow_queue
        assert gr_q.data[gr_q.head - 1] == idrec

        kb.retract(idrec)

        # assert kb.kb_data.subscribers[0].change_queue.data[0] == idrec
        ch_q = kb.kb_data.change_queue
        assert ch_q.data[ch_q.head - 1] == idrec
def test__merge_spec_inheritance():
    context = kb_context("test__merge_spec_inheritance")
    spec1 = {"A": "string", "B": "number"}
    BOOP, BOOPType = define_fact("BOOP",
                                 spec1,
                                 context="test__merge_spec_inheritance")

    #Should be able to inherit from ctor, type or type string
    spec2 = {"inherit_from": BOOP, "C": "number"}
    spec_out, inherit_from = _merge_spec_inheritance(spec2, context)
    assert inherit_from._fact_name == "BOOP"
    assert "inherit_from" not in spec_out

    spec2 = {"inherit_from": BOOPType, "C": "number"}
    spec_out, inherit_from = _merge_spec_inheritance(spec2, context)
    assert inherit_from._fact_name == "BOOP"
    assert "inherit_from" not in spec_out

    spec2 = {"inherit_from": "BOOP", "C": "number"}
    spec_out, inherit_from = _merge_spec_inheritance(spec2, context)
    assert inherit_from._fact_name == "BOOP"
    assert "inherit_from" not in spec_out

    assert "A" in spec_out
    assert "B" in spec_out

    #It is illegal to redefine an attribute to have a new type
    with pytest.raises(TypeError):
        spec2 = _standardize_spec({
            "inherit_from": "BOOP",
            "B": "string",
            "C": "string"
        })
        spec_out, inherit_from = _merge_spec_inheritance(spec2, context)

    #But okay to to redefine an attribute if the types match
    spec2 = _standardize_spec({
        "inherit_from": "BOOP",
        "B": "number",
        "C": "string"
    })
    spec_out, inherit_from = _merge_spec_inheritance(spec2, context)
def define_fact(name : str, spec : dict, context=None):
    '''Defines a new fact.'''
    context = kb_context(context)

    spec = _standardize_spec(spec)
    spec, inherit_from = _merge_spec_inheritance(spec,context)

    if(name in context.fact_types):
        assert context.fact_types[name].spec != spec, \
        f"Redefinition of fact '{name}' in context '{context.name}' not permitted"

    fact_ctor, fact_type = _fact_from_spec(name, spec, context=context)
    context._assert_flags(name,spec)
    # print("PASSING IN", inherit_from)
    context._register_fact_type(name,spec,fact_ctor,fact_type,inherit_from=inherit_from)

    # fact_ctor.name = fact_type.name = name
    fact_ctor.spec = fact_type.spec = spec

    return fact_ctor, fact_type
示例#16
0
def test_link():
    with kb_context() as context:
        print(context.fact_types)
        # BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})

        l1, l2 = Var(BOOPType, "l1"), Var(BOOPType, "l2")
        r1, r2 = Var(BOOPType, "r1"), Var(BOOPType, "r2")

        c = (l1.B < 1) & (l1.B > 7) & (l2.B < r1.B) & (r2.B < l1.B) |\
             (l2.B < 1) & (l2.B > 7) & (l2.B < r1.B) & (r1.B < r2.B) |\
             (l2.B < 1) & (l2.B > 7) & (l2.B < r1.B) & (l1.B < l2.B)

        kb = KnowledgeBase()
        cl = get_linked_conditions_instance(c, kb)

        assert get_pointer(cl) == get_pointer(c)

        cl = get_linked_conditions_instance(c, kb, copy=True)

        assert get_pointer(cl) != get_pointer(c)
def cast_fact(typ, val):
    '''Casts a fact to a new type of fact if possible'''
    context = kb_context()    
    inst_type = typ.instance_type
    # print("CAST", val._fact_name, "to", inst_type._fact_name)

    #Check if the fact_type can be casted 
    if(inst_type._fact_name != "BaseFact" and val._fact_name != "BaseFact" and
       inst_type._fact_name not in context.children_of[val._fact_name] and 
       inst_type._fact_name not in context.parents_of[val._fact_name]
       
    ):
        error_message = f"Cannot cast fact of type '{val._fact_name}' to '{inst_type._fact_name}.'"
        #If it shouldn't be possible then throw an error
        def error(typ,val):
            raise TypeError(error_message)
        return error
    
    def impl(typ,val):
        return _cast_structref(inst_type,val)

    return impl
示例#18
0
def test_initialize():
    with kb_context("test_initialize"):
        # BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})

        l1, l2 = Var(BOOPType, "l1"), Var(BOOPType, "l2")
        r1, r2 = Var(BOOPType, "r1"), Var(BOOPType, "r2")

        c = (l1.B < 1) & (l1.B > 7) & (l2.B < r1.B) & (r2.B < l1.B) |\
             (l2.B < 1) & (l2.B > 7) & (l2.B < r1.B) & (r1.B < r2.B) |\
             (l2.B < 1) & (l2.B > 7) & (l2.B < r1.B) & (l1.B < l2.B)

        assert [x.alias for x in cond_get_vars(c)] == ['l1', 'l2', 'r1', 'r2']

        initialize_conditions(c)
        print("DONE")
        alpha_sizes, beta_sizes = get_init_cond_sizes(c)

        print(alpha_sizes)
        print(beta_sizes)
        assert [list(x) for x in alpha_sizes] == [[2, 0, 0, 0], [0, 2, 0, 0],
                                                  [0, 2, 0, 0]]
        assert [list(x) for x in beta_sizes] == [[1, 1], [1, 1], [1, 1]]
示例#19
0
def test_declare_retract():
    with kb_context("test_declare_retract"):
        #NRT version
        kb = KnowledgeBase()
        assert declare_retract(kb) == 10
        assert declare_again(kb) == 0

        #Python version
        kb = KnowledgeBase()
        assert declare_retract.py_func(kb) == 10
        assert declare_again.py_func(kb) == 0

        with pytest.raises(TypingError):
            bad_declare_type(kb)

        with pytest.raises(TypingError):
            bad_declare_type.py_func(kb)

        with pytest.raises(TypingError):
            bad_retract_type(kb)

        with pytest.raises(TypingError):
            bad_retract_type.py_func(kb)
def test_cast_fact():
    with kb_context("test_cast_fact") as context:
        spec1 = {"A": "string", "B": "number"}
        BOOP1, BOOP1Type = define_fact("BOOP1",
                                       spec1,
                                       context="test_cast_fact")
        spec2 = {"inherit_from": BOOP1, "C": "number"}
        BOOP2, BOOP2Type = define_fact("BOOP2",
                                       spec2,
                                       context="test_cast_fact")
        spec3 = {"inherit_from": BOOP2, "D": "number"}
        BOOP3, BOOP3Type = define_fact("BOOP3",
                                       spec3,
                                       context="test_cast_fact")

        b1 = BOOP1("A", 7)
        b3 = BOOP3("A", 1, 2, 3)
        bs = BaseFact()

        #Downcast
        @njit
        def down_cast(b):
            return cast_fact(BOOP1Type, b)

        _b1 = down_cast(b3)
        assert type(b1) == type(_b1)
        _b1 = down_cast.py_func(b3)
        assert type(b1) == type(_b1)

        #Upcast back
        @njit
        def up_cast(b):
            return cast_fact(BOOP3Type, b)

        _b3 = up_cast(_b1)
        assert type(b3) == type(_b3)
        _b3 = up_cast.py_func(_b1)
        assert type(b3) == type(_b3)

        FLOOP, FLOOPType = define_fact("FLOOP",
                                       spec3,
                                       context="test_cast_fact")

        #Bad cast
        @njit
        def bad_cast(b):
            return cast_fact(FLOOPType, b)

        with pytest.raises(TypeError):
            bad_cast(b3)

        with pytest.raises(TypeError):
            bad_cast.py_func(b3)

        #Always allow casting to and from BaseFact
        @njit
        def base_down_cast(b):
            return cast_fact(BaseFactType, b)

        _bs = base_down_cast(_b1)
        assert type(bs) == type(_bs)
        _bs = base_down_cast.py_func(_b1)
        assert type(bs) == type(_bs)

        @njit
        def base_up_cast(b):
            return cast_fact(BOOP1Type, b)

        _b1 = base_up_cast(_bs)
        assert type(b1) == type(_b1)
        _b1 = base_up_cast.py_func(_bs)
        assert type(b1) == type(_b1)
def test_alpha_predicate_node():
    with kb_context("test_alpha_predicate_node"):
        BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})

        kb = KnowledgeBase()
        pn = get_alpha_predicate_node(BOOPType,"B", "<",9)
        ld = generate_link_data(pn, kb)

        # kb.add_subscriber(pn)

        x = BOOP("x",7)
        y = BOOP("y",11)
        z = BOOP("z",8)

        assert len(ld.truth_values) == 0        

        kb.declare(x)
        kb.declare(y)
        kb.declare(z)

        # njit_update(pn)
        inds = filter_alpha(pn, ld, np.arange(3))
        assert np.array_equal(inds, [0,2]) 
        assert all(ld.truth_values[:3,0] == [1,0,1])

        kb.modify(x,"B", 100)
        kb.modify(y,"B", 3)
        kb.modify(z,"B", 88)

        #Checks doesn't change before update
        assert all(ld.truth_values[:3,0] == [1,0,1])
        inds = filter_alpha(pn, ld, np.arange(3))
        assert np.array_equal(inds, [1]) 
        assert all(ld.truth_values[:3,0] == [0,1,0])

        kb.retract(x)
        kb.retract(y)
        kb.retract(z)

        #Checks doesn't change before update
        assert all(ld.truth_values[:3,0] == [0,1,0])

        inds = filter_alpha(pn, ld, np.arange(3))
        print(inds)
        assert np.array_equal(inds, []) 

        # print(ld.truth_values)
        #Checks that retracted facts show up as u1.nan = 0XFF
        assert all(ld.truth_values[:3,0] == [0xFF,0xFF,0xFF])

        kb.declare(x)
        kb.declare(y)
        kb.declare(z)
        kb.modify(z,"A","Z")
        kb.modify(x,"B",0)
        kb.modify(y,"B",0)
        kb.modify(z,"B",0)

        inds = filter_alpha(pn, ld, np.arange(3))
        assert np.array_equal(inds, [0,1,2]) 

        assert all(ld.truth_values[:3,0] == [1,1,1])
示例#22
0
import pytest
from collections import namedtuple
from cre.subscriber import BaseSubscriberType, init_base_subscriber
from cre.utils import _struct_from_meminfo

tf_spec = {
    "value": "string",
    "above": "string",
    "below": "string",
    "to_left": "string",
    "to_right": "string",
}

##### test_declare_retract #####

with kb_context("test_declare_retract"):
    TextField, TextFieldType = define_fact("TextField", tf_spec)


@njit(cache=True)
def declare_retract(kb):
    for i in range(100):
        i_s = "A" + str(i)
        kb.declare(TextField(i_s, i_s, i_s, i_s, i_s), i_s)

    for i in range(0, 100, 10):
        i_s = "A" + str(i)
        kb.retract(i_s)

    # print(kb.kb_data.empty_f_id_heads)
    t_id = kb.context_data.fact_to_t_id["TextField"]
示例#23
0
def test_declare_overloading():
    with kb_context("test_declare_overloading"):
        kb = KnowledgeBase()
        idrec1 = declare_unnamed(kb)
        idrec2 = declare_unnamed.py_func(kb)
        assert idrec1 != idrec2
示例#24
0
def test_build_conditions():
    with kb_context("test_build_conditions"):
        # BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})

        l1, l2 = Var(BOOPType, "l1"), Var(BOOPType, "l2")
        r1, r2 = Var(BOOPType, "r1"), Var(BOOPType, "r2")

        c1 = l1.B < 1
        c2 = l1.B < l2.B

        assert str(c1) == "(l1.B < ?)"
        assert str(c2) == "(l1.B < l2.B)"

        ### LT + AND/OR ###

        c3 = (l1.B < 1) & (l1.B > 7) & (l1.B < r1.B) & (l1.B < r2.B) |\
             (l2.B < 1) & (l2.B > 7) & (l2.B < r1.B) & (l2.B < r2.B)

        c3_str = \
'''(l1.B < ?) & (l1.B > ?) & (l1.B < r1.B) & (l1.B < r2.B) |\\
(l2.B < ?) & (l2.B > ?) & (l2.B < r1.B) & (l2.B < r2.B)'''

        assert str(c3) == c3_str

        ### NOT ###

        nc3_str = \
'''~(l1.B < ?) & ~(l2.B < ?) |\\
~(l1.B < ?) & ~(l2.B > ?) |\\
~(l1.B < ?) & ~(l2.B < r1.B) |\\
~(l1.B < ?) & ~(l2.B < r2.B) |\\
~(l1.B > ?) & ~(l2.B < ?) |\\
~(l1.B > ?) & ~(l2.B > ?) |\\
~(l1.B > ?) & ~(l2.B < r1.B) |\\
~(l1.B > ?) & ~(l2.B < r2.B) |\\
~(l2.B < ?) & ~(l1.B < r1.B) |\\
~(l2.B > ?) & ~(l1.B < r1.B) |\\
~(l1.B < r1.B) & ~(l2.B < r1.B) |\\
~(l1.B < r1.B) & ~(l2.B < r2.B) |\\
~(l2.B < ?) & ~(l1.B < r2.B) |\\
~(l2.B > ?) & ~(l1.B < r2.B) |\\
~(l1.B < r2.B) & ~(l2.B < r1.B) |\\
~(l1.B < r2.B) & ~(l2.B < r2.B)'''
        assert str(~c3) == nc3_str

        ### EQ / NEQ ###

        c4 = (l1.B == 5) & (l1.B == 5) & (l1.B == l2.B) & (l1.B != l2.B)

        c4_str = \
'''(l1.B == ?) & (l1.B == ?) & (l1.B == l2.B) & ~(l1.B == l2.B)'''
        assert str(c4) == c4_str

        nc4_str = \
'''~(l1.B == ?) |\\
~(l1.B == ?) |\\
~(l1.B == l2.B) |\\
(l1.B == l2.B)'''
        assert str(~c4) == nc4_str

        ### AND / OR btw DNFS ###

        c3_and_c4_str = \
'''(l1.B < ?) & (l1.B > ?) & (l1.B == ?) & (l1.B == ?) & (l1.B < r1.B) & (l1.B < r2.B) & (l1.B == l2.B) & ~(l1.B == l2.B) |\\
(l2.B < ?) & (l2.B > ?) & (l1.B == ?) & (l1.B == ?) & (l2.B < r1.B) & (l2.B < r2.B) & (l1.B == l2.B) & ~(l1.B == l2.B)'''
        assert str(c3 & c4) == c3_and_c4_str
        c3_or_c4_str = \
'''(l1.B < ?) & (l1.B > ?) & (l1.B < r1.B) & (l1.B < r2.B) |\\
(l2.B < ?) & (l2.B > ?) & (l2.B < r1.B) & (l2.B < r2.B) |\\
(l1.B == ?) & (l1.B == ?) & (l1.B == l2.B) & ~(l1.B == l2.B)'''
        assert str(c3 | c4) == c3_or_c4_str
示例#25
0
def _benchmark_setup():
    with kb_context("test_kb"):
        kb = KnowledgeBase()
    return (kb, ), {}
def _get_alpha_predicate_node():
    with kb_context("test_predicate_node"):
        pn = get_alpha_predicate_node(BOOPType,"B", "<",50)
        pn = get_alpha_predicate_node(BOOPType,"B", "<",49)
def test_beta_predicate_node_2_typed():
    with kb_context("test_beta_predicate_node_2_typed"):
        BOOP1, BOOP1Type = define_fact("BOOP1",{"A": "number", "B" : "string"})
        BOOP2, BOOP2Type = define_fact("BOOP2",{"A": "string", "B" : "number"})

        kb = KnowledgeBase()

        pn = get_beta_predicate_node(BOOP1Type,"A", "<", BOOP2Type,"B")
        ld = generate_link_data(pn, kb)
        # kb.add_subscriber(pn)

        x1,x2 = BOOP1(7,"x"),  BOOP2("x",7.5) #<- slightly different
        y1,y2 = BOOP1(11,"y"), BOOP2("y",11)
        z1,z2 = BOOP1(8,"z"),  BOOP2("z",8)

        assert len(ld.truth_values) == 0        

        kb.declare(x1); kb.declare(x2)
        kb.declare(y1); kb.declare(y2)
        kb.declare(z1); kb.declare(z2)
        
        inds = filter_beta(pn, ld, np.arange(3), np.arange(3))
        # print(inds)

        # print(ld.truth_values)
        assert np.array_equal(inds, [[0,0],[0, 1], [0, 2], [2, 1]])
        assert all(ld.truth_values[0,:3] == [1,1,1])
        assert all(ld.truth_values[1,:3] == [0,0,0])
        assert all(ld.truth_values[2,:3] == [0,1,0])

        q1, q2 = BOOP1(-7,"q"),  BOOP2("q",-7)
        r1, r2 = BOOP1(-11,"r"), BOOP2("r",-11)
        t1, t2 = BOOP1(-8,"t"),  BOOP2("t",-8)
        kb.declare(q1); kb.declare(q2)
        kb.declare(r1); kb.declare(r2)
        kb.declare(t1); kb.declare(t2)

        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))
        # print(inds)
        # print(ld.truth_values[:6,:6])
        assert np.array_equal(inds,[[0,0],[0,1],[0,2],[2,1],[3,0],[3,1],
                [3,2],[4,0],[4,1],[4,2],[4,3],[4,5],[5,0],[5,1],[5,2],[5,3]])
        assert all(ld.truth_values[0,:6] == [1,1,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,1,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,1,1,0,0,0])
        assert all(ld.truth_values[4,:6] == [1,1,1,1,0,1])
        assert all(ld.truth_values[5,:6] == [1,1,1,1,0,0])

        kb.modify(r1,"A", 0); kb.modify(r2,"B", 0)
        kb.modify(y1,"A", 0); kb.modify(y2,"B", 0)

        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))
        # print(ld.truth_values[:6,:6])
        assert all(ld.truth_values[0,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,1,1,0,1,0])
        assert all(ld.truth_values[4,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[5,:6] == [1,1,1,1,1,0])

        kb.retract(r1); kb.retract(r2)
        kb.retract(y1); kb.retract(y2)
        
        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))
        # print(ld.truth_values[:6,:6])
        assert all(ld.truth_values[0,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[4,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[5,:6] == [1,0,1,1,0,0])
def test_beta_predicate_node_1_typed():
    with kb_context("test_beta_predicate_node_1_typed"):
        BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})

        kb = KnowledgeBase()
        pn = get_beta_predicate_node(BOOPType,"B", "<", BOOPType,"B")
        # png = cast(pn, GenericBetaPredicateNodeType)
        ld = generate_link_data(pn, kb)
        # kb.add_subscriber(pn)

        x = BOOP("x",7)
        y = BOOP("y",11)
        z = BOOP("z",8)

        assert len(ld.truth_values) == 0        

        kb.declare(x)
        kb.declare(y)
        kb.declare(z)

        # njit_update(pn)
        inds = filter_beta(pn, ld, np.arange(3), np.arange(3))
        # print("B")
        # print(inds)

        assert np.array_equal(inds, [[0, 1], [0, 2], [2, 1]])
        # print(ld.truth_values)
        assert all(ld.truth_values[0,:3] == [0,1,1])
        assert all(ld.truth_values[1,:3] == [0,0,0])
        assert all(ld.truth_values[2,:3] == [0,1,0])

        q = BOOP("q",-7)
        r = BOOP("r",-11)
        t = BOOP("t",-8)
        kb.declare(q)
        kb.declare(r)
        kb.declare(t)

        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))
        # print(inds)
        assert np.array_equal(inds,[[0,1],[0,2],[2,1],[3,0],[3,1],
                [3,2],[4,0],[4,1],[4,2],[4,3],[4,5],[5,0],[5,1],[5,2],[5,3]])
        # njit_update(pn)
        # print(ld.truth_values[:6,:6])
        assert all(ld.truth_values[0,:6] == [0,1,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,1,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,1,1,0,0,0])
        assert all(ld.truth_values[4,:6] == [1,1,1,1,0,1])
        assert all(ld.truth_values[5,:6] == [1,1,1,1,0,0])

        kb.modify(r,"B", 0)
        kb.modify(y,"B", 0)

        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))

        # njit_update(pn)
        # print(ld.truth_values[:6,:6])
        assert all(ld.truth_values[0,:6] == [0,0,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,1,1,0,1,0])
        assert all(ld.truth_values[4,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[5,:6] == [1,1,1,1,1,0])

        kb.retract(r)
        kb.retract(y)

        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))

        # njit_update(pn)
        # print(ld.truth_values[:6,:6])
        assert all(ld.truth_values[0,:6] == [0,0,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[4,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[5,:6] == [1,0,1,1,0,0])
        inds = filter_beta(pn, ld, np.arange(6), np.arange(6))
        # print(ld.truth_values[:6,:6])
        assert all(ld.truth_values[0,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[1,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[2,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[3,:6] == [1,0,1,0,0,0])
        assert all(ld.truth_values[4,:6] == [0,0,0,0,0,0])
        assert all(ld.truth_values[5,:6] == [1,0,1,1,0,0])





# import time

with kb_context("test_predicate_node"):
    BOOP, BOOPType = define_fact("BOOP",{"A": "string", "B" : "number"})

#### get_alpha_predicate_node ####

def _get_alpha_predicate_node():
    with kb_context("test_predicate_node"):
        pn = get_alpha_predicate_node(BOOPType,"B", "<",50)
        pn = get_alpha_predicate_node(BOOPType,"B", "<",49)

@pytest.mark.benchmark(group="setup")
def test_b_get_alpha_predicate_node(benchmark):
    benchmark.pedantic(_get_alpha_predicate_node, iterations=1)


#### setup ####