Search code examples
pyke

PYKE rules to add the count of similar statements


I am very new to PYKE, I have a small problem with writing rules in PYKE.

I have following statement in my kfb file.

ent_rel(1, sam, helsen,2)
ent_rel(1, sam, dunkin,1)
ent_rel(1, pirate, sam,2)

ent_rel(2, van, helsen,2)
ent_rel(2, sam, helsen,2)
ent_rel(2, pirate, bay,1)
ent_rel(2, van, burger,1)

ent_rel(3, burger, house,1)
ent_rel(3, sam, helsen,1)

I want to write a rule that produces an output like below:

ent_rel1(sam, helsen,5)
ent_rel1(sam, dunkin,1)
ent_rel1(pirate, sam,2)
ent_rel1(pirate, bay,1)
ent_rel1(van, helsen,2)
ent_rel1(van, burger,1)
ent_rel1(burger, house,1)

I am simply trying to add similar statements regardless of the ID.

I have written the below rule, but this gives a different output.

relationship_cnt
    foreach
        a.ent_rel($id1, $f1, $s1, $n1)
        a.ent_rel($id2, $f2, $s2, $n2)
        check $id1 != $id2
        check $f1 == $f2
        check $s1 == $s2
        $tot = $n1 + $n2
    assert
        a.ent_rel1($f1,$s1,$tot)

Ouput:

ent_rel1('sam', 'helsen', 4)
ent_rel1('sam', 'helsen', 3)

I get it why my output is not proper, as I have mentioned $id1 and $id2. which looks for the same name "sam" and "helsen" in two different ids and add them.

However I am unable to write the proper rule. I'd really appreciate any help.

Thanks


Solution

  • My solution:

    relationship_cnt
        foreach
            data.ent_rel($id1, $f1, $s1, $n1)
    
            python tot = $n1
    
            forall
                data.ent_rel($id2, $f1, $s1, $n2)
                check $id1 != $id2
                python tot = tot + $n2
    
            $tot = int(tot)
        assert
            data.ent_rel1($f1, $s1, $tot)
    

    Loop over each tuple ($f1, $s1) with the forall, ensuring unique $id's with the check. In order to do the sum, use a python variable, because the value for $n2 is not bound outside the forall premise; see pyke: Notes on Forall and Notany Premises