Search code examples
protegejess

JessTab: Can we count all subclass instances?


I have a class A which consists of two subclasses B and C. Class B has three instances, while C two. Can I write a JessTab rule which will count all implicit instances of A i.e. give me 5?

Mapping class A in Jess:

(mapclass http...#A)

Rule to count instances which gives me 0 since there are no direct instances of A:

Originally:

(defrule countAinstances 
?c <- (accumulate (bind ?count 0) 
(bind ?count (+ ?count 1)) 
?count 
(object (ís-a http...#A))
) 
=> 
(printout t ?c " number of class A instances." crlf))

This doesn't count instances of subclasses of A.

Modified version:

(defrule countAinstances 
?c <- (accumulate (bind ?count 0) 
(bind ?count (+ ?count 1)) 
?count 
(object (OBJECT ?x&:(instanceof ?x http...#A)))
) 
=> 
(printout t ?c " number of class A instances." crlf))

The following error appears:

Jess reported an error in routine instanceof while executing (instanceof ?_20_x(0,2,-1) http...#A) while executing rule LHS (TEQ) while executing rule LHS (TECT). Message: Class not found: http...#A. Program text: ( defrule countAinstances ?c <- ( accumulate ( bind ?count 0 ) ( bind ?count ( + ?count 1 ) ) ?count ( object ( OBJECT ?x & : ( instanceof ?x http...#A ) ) ) ) = > ( printout t ?c " number of class A instances." crlf ) ) at line 20.

Nested exception is: http...#A


Solution

  • Access the object and rely on Jess' own function instanceof, not the protege slot is-a:

    (object (OBJECT ?x&:(instanceof ?x A))) 
    

    Use the full class name if A isn't imported.

    if you don't have the Java class name, you'll have to test for all classes and subclasses in that pattern, using an (or) function. Rather tedious.

    Later

    Seeing that is-a contains class references that can be compared to class names, this would be the simplest way of writing the rule:

    defrule countAinstances
    ?c <- (accumulate (bind ?count 0) 
    (bind ?count (+ ?count 1)) 
    ?count 
    (object (is-a ?x&B|C))
          )
    => 
    (printout t ?c " number of subclass instances." crlf))