-
Notifications
You must be signed in to change notification settings - Fork 1
/
nm-code-1.lisp
2157 lines (1840 loc) · 73.6 KB
/
nm-code-1.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#|
Copyright (c) 1986-1993 Kenneth D. Forbus, Johan de Kleer and Xerox
Corporation. All Rights Reserved.
Use, reproduction, and preparation of derivative works are permitted.
Any copy of this software or of any derivative work must include the
above copyright notice and this paragraph. Any distribution of this
software or derivative works must comply with all applicable United
States export control laws. This software is made available as is, and
Kenneth D. Forbus, Johan de Kleer and Xerox Corporation disclaim all
warranties, express or implied, including without limitation the implied
warranties of merchantability and fitness for a particular purpose, and
notwithstanding any other provision contained herein, any liability for
damages resulting from the software or its use is expressly disclaimed,
whether arising in contract, tort (including negligence) or strict
liability, even if Kenneth D. Forbus, Johan de Kleer or Xerox
Corporation is advised of the possibility of such damages.
This software has been worked upon to make it work for step-by-step
differentiation, in case of queries, please mail to [email protected]
|#
;;; Justification-based Truth Maintenence System (JTMS)
(defstruct (jtms (:PRINT-FUNCTION print-jtms))
(title nil)
(node-counter 0) ;; unique namer for nodes.
(just-counter 0) ;; unique namer for justifications.
(nodes nil) ;; list of all tms nodes.
(justs nil) ;; list of all justifications
(debugging nil) ;; debugging flag
(contradictions nil) ;; list of contradiction nodes.
(assumptions nil) ;; list of assumption nodes.
(checking-contradictions T) ;; For external systems
(node-string nil)
(contradiction-handler nil)
(enqueue-procedure nil))
(defun print-jtms (jtms stream ignore)
(declare (ignore ignore))
(format stream "#<JTMS: ~A>" (jtms-title jtms)))
(defstruct (tms-node (:PRINT-FUNCTION print-tms-node))
(index 0)
(datum nil) ;; pointer to external problem solver
(label :OUT) ;; :IN means believed, :OUT means disbelieved
(support nil) ;; Current justification or premise marker
(justs nil) ;; Possible justifications
(consequences nil) ;; Justifications in which it is an antecedent
(mark nil) ;; Marker for sweep algorithms
(contradictory? nil) ;; Flag marking it as contradictory
(assumption? nil) ;; Flag marking it as an assumption.
(in-rules nil) ;; Rules that should be triggered when node goes in
(out-rules nil) ;; Rules that should be triggered when node goes out
(jtms nil)) ;; The JTMS in which this node appears.
(defun print-tms-node (node stream ignore)
(declare (ignore ignore))
(format stream "#<Node: ~A>" (node-string node)))
(defstruct (just (:PRINT-FUNCTION print-just))
(index 0)
informant
consequence
antecedents)
(defun print-just (just stream ignore)
(declare (ignore ignore))
(format stream "#<Just ~D>" (just-index just)))
(defun tms-node-premise? (node &aux support)
(and (setq support (tms-node-support node))
(not (eq support :ENABLED-ASSUMPTION))
(null (just-antecedents support))))
;;; Simple utilities:
(defun node-string (node)
(funcall (jtms-node-string (tms-node-jtms node)) node))
(defmacro debugging-jtms (jtms msg &optional node &rest args)
`(when (jtms-debugging ,jtms)
(format *trace-output* ,msg (if ,node (node-string ,node)) ,@args)))
(defun tms-error (string node) (error string (node-string node)))
(defun default-node-string (n) (format nil "~A" (tms-node-datum n)))
(defun create-jtms (title &key (node-string 'default-node-string)
debugging
(checking-contradictions t)
(contradiction-handler 'ask-user-handler)
enqueue-procedure)
(make-jtms :TITLE title
:NODE-STRING node-string
:DEBUGGING debugging
:CHECKING-CONTRADICTIONS checking-contradictions
:CONTRADICTION-HANDLER contradiction-handler
:ENQUEUE-PROCEDURE enqueue-procedure
))
(defun change-jtms (jtms &key contradiction-handler node-string
enqueue-procedure debugging
checking-contradictions)
(if node-string (setf (jtms-node-string jtms) node-string))
(if debugging (setf (jtms-debugging jtms) debugging))
(if checking-contradictions
(setf (jtms-checking-contradictions jtms)
checking-contradictions))
(if contradiction-handler
(setf (jtms-contradiction-handler jtms) contradiction-handler))
(if enqueue-procedure
(setf (jtms-enqueue-procedure jtms) enqueue-procedure)))
;;; Basic inference-engine interface.
(defun in-node? (node) (eq (tms-node-label node) :IN))
(defun out-node? (node) (eq (tms-node-label node) :OUT))
(defun tms-create-node (jtms datum &key assumptionp contradictoryp)
(let ((node (make-tms-node :INDEX (incf (jtms-node-counter jtms))
:DATUM datum
:ASSUMPTION? assumptionp
:CONTRADICTORY? contradictoryp
:JTMS jtms)))
(if assumptionp (push node (jtms-assumptions jtms)))
(if contradictoryp (push node (jtms-contradictions jtms)))
(push node (jtms-nodes jtms))
node))
;;; Converts a regular node to an assumption and enables it.
(defun assume-node (node &aux (jtms (tms-node-jtms node)))
(unless (tms-node-assumption? node)
(debugging-jtms jtms "~%Converting ~A into an assumption" node)
(setf (tms-node-assumption? node) t))
(enable-assumption node))
(defun make-contradiction (node &aux (jtms (tms-node-jtms node)))
(unless (tms-node-contradictory? node)
(setf (tms-node-contradictory? node) t)
(push node (jtms-contradictions jtms))
(check-for-contradictions jtms)))
(defun justify-node (informant consequence antecedents &aux just jtms)
(setq jtms (tms-node-jtms consequence)
just (make-just :INDEX (incf (jtms-just-counter jtms))
:INFORMANT informant
:CONSEQUENCE consequence
:ANTECEDENTS antecedents))
(push just (tms-node-justs consequence))
(dolist (node antecedents) (push just (tms-node-consequences node)))
(push just (jtms-justs jtms))
(debugging-jtms jtms
"~%Justifying ~A by ~A using ~A."
consequence
informant
(mapcar #'node-string antecedents))
(if (or antecedents (out-node? consequence))
(if (check-justification just) (install-support consequence just))
(setf (tms-node-support consequence) just))
(check-for-contradictions jtms))
;;;; Support for adding justifications
(defun check-justification (just)
(and (out-node? (just-consequence just))
(justification-satisfied? just)))
(defun justification-satisfied? (just)
(every #'in-node? (just-antecedents just)))
(defun install-support (conseq just)
(make-node-in conseq just)
(propagate-inness conseq))
(defun propagate-inness (node &aux (jtms (tms-node-jtms node)) (q (list node)))
(do () ((null (setq node (pop q))))
(debugging-jtms jtms "~% Propagating belief in ~A." node)
(dolist (justification (tms-node-consequences node))
(when (check-justification justification)
(make-node-in (just-consequence justification) justification)
(push (just-consequence justification) q)))))
(defun make-node-in (conseq reason &aux jtms enqueuef)
(setq jtms (tms-node-jtms conseq)
enqueuef (jtms-enqueue-procedure jtms))
(debugging-jtms jtms "~% Making ~A in via ~A."
conseq
(if (symbolp reason)
reason
(cons (just-informant reason)
(mapcar (jtms-node-string jtms)
(just-antecedents reason)))))
(setf (tms-node-label conseq) :IN)
(setf (tms-node-support conseq) reason)
(when enqueuef
(dolist (in-rule (tms-node-in-rules conseq))
(funcall enqueuef in-rule))
(setf (tms-node-in-rules conseq) nil)))
;;; Assumption Manipulation
(defun retract-assumption (node &aux jtms)
(when (eq (tms-node-support node) :ENABLED-ASSUMPTION)
(setq jtms (tms-node-jtms node))
(debugging-jtms jtms "~% Retracting assumption ~A." node)
(make-node-out node)
(find-alternative-support jtms (cons node (propagate-outness node jtms)))))
(defun enable-assumption (node &aux (jtms (tms-node-jtms node)))
(unless (tms-node-assumption? node)
(tms-error "Can't enable the non-assumption ~A" node))
(debugging-jtms jtms "~% Enabling assumption ~A." node)
(cond ((out-node? node) (make-node-in node :ENABLED-ASSUMPTION)
(propagate-inness node))
((or (eq (tms-node-support node) :ENABLED-ASSUMPTION)
(null (just-antecedents (tms-node-support node)))))
(t (setf (tms-node-support node) :ENABLED-ASSUMPTION)))
(check-for-contradictions jtms))
(defun make-node-out (node &aux jtms enqueuef)
(setq jtms (tms-node-jtms node)
enqueuef (jtms-enqueue-procedure jtms))
(debugging-jtms jtms "~% retracting belief in ~a." node)
(setf (tms-node-support node) nil)
(setf (tms-node-label node) :OUT)
(if enqueuef (dolist (out-rule (tms-node-out-rules node))
(funcall enqueuef out-rule)))
(setf (tms-node-out-rules node) nil))
(defun propagate-outness (node jtms &aux out-queue)
(debugging-jtms jtms "~% Propagating disbelief in ~A." node)
(do ((js (tms-node-consequences node) (append (cdr js) new))
(new nil nil)
(conseq nil))
((null js) out-queue)
;;For each justification using the node, check to see if
;;it supports some other node. If so, forget that node,
;;queue up the node to look for other support, and recurse
(setq conseq (just-consequence (car js)))
(when (eq (tms-node-support conseq) (car js))
(make-node-out conseq)
(push conseq out-queue)
(setq new (tms-node-consequences conseq)))))
(defun find-alternative-support (jtms out-queue)
(debugging-jtms jtms "~% Looking for alternative supports.")
(dolist (node out-queue)
(unless (in-node? node)
(dolist (just (tms-node-justs node))
(when (check-justification just)
(install-support (just-consequence just)
just)
(return just))))))
;;; Contradiction handling interface
(defun check-for-contradictions (jtms &aux contradictions)
(when (jtms-checking-contradictions jtms)
(dolist (cnode (jtms-contradictions jtms))
(if (in-node? cnode) (push cnode contradictions)))
(if contradictions
(funcall (jtms-contradiction-handler jtms) jtms contradictions))))
(defmacro without-contradiction-check (jtms &body body)
(contradiction-check jtms nil body))
(defmacro with-contradiction-check (jtms &body body)
(contradiction-check jtms t body))
(defun contradiction-check (jtms flag body)
(let ((jtmsv (gensym)) (old-value (gensym)))
`(let* ((,jtmsv ,jtms)
(,old-value (jtms-checking-contradictions ,jtmsv)))
(unwind-protect
(progn (setf (jtms-checking-contradictions ,jtmsv) ,flag) ,@body)
(setf (jtms-checking-contradictions ,jtmsv) ,old-value)))))
(defmacro with-contradiction-handler (jtms handler &body body)
(let ((jtmsv (gensym)) (old-handler (gensym)))
`(let* ((,jtmsv ,jtms)
(,old-handler (jtms-contradiction-handler ,jtmsv)))
(unwind-protect
(progn (setf (jtms-contradiction-handler ,jtmsv) ,handler) ,@body)
(setf (jtms-contradiction-handler ,jtmsv) ,old-handler)))))
(defun default-assumptions (jtms)
(with-contradiction-check jtms
(with-contradiction-handler jtms #'(lambda (&rest ignore)
(declare (ignore ignore))
(throw 'CONTRADICTION t))
(dolist (assumption (jtms-assumptions jtms))
(cond ((eq (tms-node-support assumption) :ENABLED-ASSUMPTION))
((not (eq :DEFAULT (tms-node-assumption? assumption))))
((catch 'CONTRADICTION (enable-assumption assumption))
(retract-assumption assumption)))))))
;;; Well-founded support inqueries
(defun supporting-justification-for-node (node) (tms-node-support node))
(defun assumptions-of-node (node &aux assumptions (marker (list :MARK)))
(do ((nodes (list node) (append (cdr nodes) new))
(new nil nil))
((null nodes) assumptions)
(let ((node (car nodes)))
(cond ((eq (tms-node-mark node) marker))
((eq (tms-node-support node) :ENABLED-ASSUMPTION)
(push node assumptions))
((in-node? node)
(setq new (just-antecedents (tms-node-support node)))))
(setf (tms-node-mark node) marker))))
(defun enabled-assumptions (jtms &aux result)
(dolist (assumption (jtms-assumptions jtms) result)
(if (eq (tms-node-support assumption) :ENABLED-ASSUMPTION)
(push assumption result))))
;;; Inference engine stub to allow this JTMS to be used stand alone
(defun why-node (node &aux justification)
(setq justification (tms-node-support node))
(cond ((eq justification :ENABLED-ASSUMPTION)
(format t "~%~A is an enabled assumption"
(node-string node)))
(justification (cons (replac-to-maxima (cadr (node-string node)))
(replac-to-maxima (cddr (node-string node)))) (princ '=>)
(dolist (anode (just-antecedents justification))
(progn (terpri)(cons (replac-to-maxima (cadr (node-string anode)))
(replac-to-maxima (cddr (node-string anode)))))
))
(T (format t "~%~A is OUT." (node-string node))))
node)
(defun why-nodes (jtms)
(dolist (node (jtms-nodes jtms)) (why-node node)))
(proclaim '(special *contra-assumptions*))
(defun ask-user-handler (jtms contradictions)
(handle-one-contradiction (car contradictions))
(check-for-contradictions jtms))
(defun handle-one-contradiction (contra-node
&aux the-answer *contra-assumptions*)
(setq *contra-assumptions* (assumptions-of-node contra-node))
(unless *contra-assumptions*
(tms-error "~%There is a flaw in the universe...~A" contra-node))
(format t "~%Contradiction found: ~A" (node-string contra-node))
(print-contra-list *contra-assumptions*)
(format t "~%Call (TMS-ANSWER <number>) to retract assumption.")
(setq the-answer
(catch 'tms-contradiction-handler
(break "JTMS contradiction break")))
(if (and (integerp the-answer)
(> the-answer 0)
(not (> the-answer (length *contra-assumptions*))))
(retract-assumption (nth (1- the-answer)
*contra-assumptions*))))
(defun print-contra-list (nodes)
(do ((counter 1 (1+ counter))
(nn nodes (cdr nn)))
((null nn))
(format t "~%~A ~A" counter
(node-string (car nn)))))
(defun tms-answer (num)
(if (integerp num)
(if (> num 0)
(if (not (> num (length *contra-assumptions*)))
(throw 'tms-contradiction-handler num)
(format t "~%Ignoring answer, too big."))
(format t "~%Ignoring answer, too small"))
(format t "~%Ignoring answer, must be an integer.")))
(defun explore-network (node)
(unless (in-node? node)
(format t "~% Sorry, ~A not believed." (node-string node))
(return-from explore-network node))
(do ((stack nil)
(current node)
(options nil)
(olen 0)
(done? nil))
(done? current)
(why-node current)
(setq options (if (typep (tms-node-support current) 'just)
(just-antecedents (tms-node-support current))))
(setq olen (length options))
(do ((good? nil)
(choice 0))
(good? (case good?
(q (return-from explore-network current))
(0 (if stack
(setq current (pop stack))
(return-from explore-network current)))
(t (push current stack)
(setq current (nth (1- good?) options)))))
;(format t "~%>>>")
(setq choice 0) ;(setq choice (read))
(cond ((or (eq choice 'q)
(and (integerp choice)
(not (> choice olen))
(not (< choice 0))))
(setq good? choice))
(t (format t
"~% Must be q or an integer from 0 to ~D."
olen))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; JTRE definitions : jinter.lisp
(defstruct (jtre (:PRINT-FUNCTION jtre-printer))
title ; Pretty name
jtms ; Pointer to its JTMS
(dbclass-table nil) ; Table of dbclasses
(datum-counter 0) ; Unique ID for asserts
(rule-counter 0) ; Unique ID for rules
(debugging nil) ; If non-NIL, show basic operations
(queue nil) ; Rule queue
(rules-run 0)) ; Statistic
(defun jtre-printer (j st ignore)
(format st "<JTRE: ~A>" (jtre-title j)))
(defvar *JTRE* nil)
(defmacro With-Jtre (jtre &rest forms); (print `(with-jtre ,jtre forms))
`(let ((*JTRE* ,jtre)) ,@ forms))
(defun In-Jtre (jtre) (setq *JTRE* jtre))
(defmacro debugging-jtre (msg &rest args)
`(when (jtre-debugging *JTRE*) (format t ,msg ,@args)))
(defun create-jtre (title &key debugging)
(let ((j (make-jtre
:TITLE title
:JTMS (create-jtms (list :JTMS-OF title)
:NODE-STRING 'view-node)
:DBCLASS-TABLE (make-hash-table :TEST #'eq)
:DEBUGGING debugging)))
(change-jtms (jtre-jtms j)
:ENQUEUE-PROCEDURE
#'(lambda (rule) (enqueue rule j)))
j))
(defun change-jtre (jtre &key (debugging :NADA))
(unless (eq debugging :NADA)
(setf (jtre-debugging jtre) debugging)))
;;;; Running JTRE
(defun uassert! (fact &optional (just 'user))
(assert! fact just) ;; Do internal operation
(run-rules *JTRE*)) ;; Run the rules
(defun uassume! (fact reason) ;; Similar to UASSERT!
(assume! fact reason *JTRE*)
(run-rules *JTRE*))
(defun run-forms (forms &optional (*JTRE* *JTRE*))
(dolist (form forms) (eval form) (run-rules *JTRE*)))
(defun run (&optional (*JTRE* *JTRE*)) ;; Toplevel driver function
(format T "~%>>")
(do ((form (read) (read)))
((member form '(quit stop exit abort)) nil)
(format t "~%~A" (eval form))
(run-rules)
(format t "~%>>")))
(defun show (&optional (*JTRE* *JTRE*) (stream *standard-output*))
(show-data *JTRE* stream) (show-rules *JTRE* stream))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;jdata.lisp
;; -*- Mode: Lisp; -*-
;;;; Database for Tiny Rule Engine using JTMS
;;;; Database structure and contents
(defstruct (dbclass (:PRINT-FUNCTION jtre-dbclass-printer))
name ; Corresponding symbol
jtre ; JTRE it is part of.
facts ; Associated facts
rules) ; Associated rules
(defun jtre-dbclass-printer (r st ignore)
(declare (ignore ignore))
(format st "<Dbclass ~A>" (dbclass-name r)))
(defstruct (datum (:PRINT-FUNCTION jtre-datum-printer))
id ; Unique ID for easy lookup
lisp-form ; Expression for pattern-matching
(tms-node nil) ; Pointer into TMS
dbclass ; Dbclass of the corresponding pattern
(assumption? nil) ; if non-nil, indicates informant
(plist nil)) ; local property list
(defun jtre-datum-printer (d st ignore)
(declare (ignore ignore))
(format st "<Datum ~D>" (datum-id d)))
;;;; Making statements
(defun assert! (fact just &optional (*JTRE* *JTRE*) &aux datum node)
(setq datum (referent fact t)
node (datum-tms-node datum))
(unless (listp just) (setq just (list just)))
(debugging-jtre "~% Asserting ~A via ~A." fact just)
(justify-node (car just) node
(mapcar #'(lambda (f) (datum-tms-node (referent f t)))
(cdr just)))
datum)
(defmacro rassert! (fact just)
`(assert! ,(quotize fact) ,(quotize just)))
(defun quiet-assert! (fact just &optional (*JTRE* *JTRE*))
(without-contradiction-check (jtre-jtms *JTRE*) (assert! fact just)))
(defun assume! (fact reason &optional (*JTRE* *JTRE*) &aux datum node)
(setq datum (referent fact t)
node (datum-tms-node datum))
(cond ((not (datum-assumption? datum))
(setf (datum-assumption? datum) reason)
(debugging-jtre "~% Assuming ~A via ~A." fact reason)
(assume-node node)
(enable-assumption node))
((eq reason (datum-assumption? datum)))
(t (error
"Fact ~A assumed because of ~A assumed again because of ~A"
(show-datum datum) (datum-assumption? datum) reason)))
datum)
(defun already-assumed? (fact) (datum-assumption? (referent fact t)))
;;;; Retraction
(defun retract! (fact &optional (just 'user) (quiet? nil)
(*JTRE* *JTRE*) &aux datum node)
(setq datum (referent fact t)
node (datum-tms-node datum))
(cond ((not (tms-node-assumption? node))
(unless quiet?
(format t "~%~A isn't an assumption."
(show-datum datum))))
((not (in-node? node))
(unless quiet?
(format T
"~%The assumption ~A is not currently in."
fact)))
((eq just (datum-assumption? datum))
(debugging-jtre "~% Retracting ~A via ~A."
fact just)
(setf (datum-assumption? datum) nil)
(retract-assumption node))
((not quiet?)
(format t "~%~A not source of assumption for ~A"
just fact)))
node)
(defmacro rretract! (fact &optional (just 'USER))
`(retract! ,(quotize fact) ,(quotize just)))
(defun contradiction (fact &optional (*JTRE* *JTRE*))
(make-contradiction (datum-tms-node (referent fact t))))
;;;; Interface and display of data
(defun in? (fact &optional (*JTRE* *JTRE*) &aux r)
(when (setq r (referent fact))
(in-node? (datum-tms-node r))))
(defun out? (fact &optional (*JTRE* *JTRE*) &aux r)
(when (setq r (referent fact))
(out-node? (datum-tms-node r))))
(defun why? (fact &optional (*JTRE* *JTRE*) &aux r)
(when (setq r (referent fact))
(why-node (datum-tms-node r))))
(defun assumptions-of (fact &optional (*JTRE* *JTRE*))
(mapcar #'view-node
(assumptions-of-node
(datum-tms-node (referent fact *jtre* t)))))
(defun fetch (pattern &optional (*JTRE* *JTRE*) &aux bindings unifiers)
(dolist (candidate (get-candidates pattern) unifiers)
(setq bindings (unify pattern (datum-lisp-form candidate)))
(unless (eq bindings :FAIL)
(push (sublis bindings pattern) unifiers))))
;;;; More display-intensive procedures
(defun wfs (fact &optional (*JTRE* *JTRE*))
;; Displays well-founded support for a fact
(cond ((out? fact) (format t "~% ~A is OUT." fact))
(t (do ((queue (list (get-tms-node fact))
(nconc (cdr queue) new-antes))
(so-far (list (get-tms-node fact)))
(new-antes nil nil))
((null queue) (format t "~%--------") fact)
(why-node (car queue))
(unless (or (out-node? (car queue))
(tms-node-assumption? (car queue)))
;; Go down the support
(dolist (ante (just-antecedents
(tms-node-support (car queue))))
(unless (member ante so-far)
(push ante so-far)
(push ante new-antes))))))))
(defun say-datum-belief (pr &optional (*jtre* *jtre*)
(indent ""))
(format t "~%~A~A: ~A" indent pr
(if (in-node? (get-tms-node pr *jtre*))
"IN" "OUT")))
(defun show-justifications (fact &optional (*jtre* *jtre*))
(format t "~% ~A::" fact)
(let* ((node (get-tms-node fact *jtre*))
(justs (tms-node-justs node)))
(unless justs
(format t " No justifications.")
(return-from show-justifications node))
(dolist (j justs)
(format t "~% ~A" (just-informant j))
(cond ((just-antecedents j)
(format t ", on:")
(dolist (ante (just-antecedents j))
(say-datum-belief
(view-node ante) *jtre* " "))
(format t "."))
(t (format t "."))))))
(defun show-data (&optional (*JTRE* *JTRE*)
(stream *standard-output*))
(format stream
"~%~D facts total." (jtre-datum-counter *JTRE*))
(map-dbclass
#'(lambda (dbclass)
(dolist (datum (dbclass-facts dbclass))
(format stream "~%~A: ~A" (show-datum datum)
(if (in-node? (datum-tms-node datum))
"IN" "OUT"))))))
;;;; Database system
(defun get-dbclass (fact &optional (*JTRE* *JTRE*)
&aux dbclass)
(cond ((null fact) (error "~% NIL can't be a dbclass."))
((listp fact) (get-dbclass (car fact) *JTRE*))
((variable? fact)
(cond ((boundp fact)
(get-dbclass (symbol-value fact) *JTRE*))
(t (error "~%Dbclass unbound: ~A" fact))))
((symbolp fact)
(cond ((setq dbclass
(gethash fact
(jtre-dbclass-table *JTRE*)))
dbclass)
(t (setq dbclass
(make-dbclass :NAME fact :FACTS nil
:RULES nil :JTRE *JTRE*))
(setf (gethash fact
(jtre-dbclass-table *JTRE*))
dbclass)
dbclass)))
(t (error "Bad dbclass type: ~A" fact))))
(defun referent (fact &optional (virtual? nil)
(*JTRE* *JTRE*))
(if virtual? (insert fact) (referent1 fact)))
(defun referent1 (fact)
(dolist (candidate (dbclass-facts (get-dbclass fact)))
(when (equal (datum-lisp-form candidate) fact)
(return candidate))))
(defun insert (fact &aux datum)
(setq datum (referent1 fact))
(cond (datum (values datum t))
(t (setq datum
(make-datum
:ID (incf (jtre-datum-counter *JTRE*))
:LISP-FORM fact
:DBCLASS (get-dbclass fact)))
(setf (datum-tms-node datum)
(tms-create-node (jtre-jtms *JTRE*) datum))
(push datum (dbclass-facts (datum-dbclass datum)))
(try-rules datum)
(values datum nil))))
(defun get-candidates (pattern)
(dbclass-facts (get-dbclass pattern)))
(defun map-dbclass (proc &optional (*JTRE* *JTRE*))
(maphash #'(lambda (name dbclass) (declare (ignore name))
(funcall proc dbclass))
(jtre-dbclass-table *JTRE*)))
(defun get-tms-node (fact &optional (*JTRE* *JTRE*))
(datum-tms-node (referent fact t)))
(defun view-node (node)
(datum-lisp-form (tms-node-datum node)))
;;;; More query routines
(defun show-datum (datum)
(format nil "~A" (datum-lisp-form datum)))
(defun get-tms-datum (num &optional (*JTRE* *JTRE*))
(map-dbclass
#'(lambda (dbclass)
(dolist (datum (dbclass-facts dbclass))
(when (= (datum-id datum) num)
(return-from get-tms-datum datum))))))
(defun get-just (num &optional (*JTRE* *JTRE*))
(dolist (just (jtms-justs (jtre-jtms *JTRE*)))
(when (= (just-index just) num)
(return-from GET-just just))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; This file is jrules.lisp
(proclaim '(special *JTRE* *bound-vars* *rule-procedures*))
(defstruct (rule (:PRINT-FUNCTION jtre-rule-printer))
id ; Unique ID for easy lookup
jtre ; The JTRE it is part of
dbclass ; Dbclass of associated pattern
matcher ; Procedure that performs the match.
body) ; Procedure that does the work.
(defun jtre-rule-printer (r st ignore)
(declare (ignore ignore))
(format st "<Rule ~D>" (rule-id r)))
(defvar *file-counter* 0)
(defvar *file-prefix* "")
(defmacro Rule-File (prefix)
`(eval-when (compile load eval)
(setq *file-counter* 0)
(setq *file-prefix* ,prefix)))
;;;; Building and installing rules
(defmacro rule (triggers &rest body) (do-rule triggers body))
;(defun my-rule(triggers &rest body)(do-rule triggers body))
(defun do-rule (triggers body)
(let ((*rule-procedures* nil)
(*bound-vars* nil)
(index-form nil))
(setq index-form
(build-rule (car triggers)
(subst 'internal-rule
'rule
(make-nested-rule
(cdr triggers) body))))
;(print index-form)
`(progn ,@ *rule-procedures* ,index-form)))
(defmacro internal-rule (triggers &rest body)
`(add-internal-rule ,(car triggers)
,(make-nested-rule (cdr triggers) body)))
(defun make-nested-rule (triggers body)
(cond ((null triggers) body)
(t `((add-internal-rule ,(car triggers)
,(make-nested-rule (cdr triggers) body))))))
(defmacro add-internal-rule (trigger body)
(build-rule trigger body))
;;;; Details of rule-building
(defun build-rule (trigger body &aux match-procedure body-procedure)
(multiple-value-bind (pattern condition var test)
(parse-rule-trigger trigger)
(setq match-procedure
(generate-match-procedure pattern var test condition))
(setq body-procedure
(generate-body-procedure pattern condition var body))
(push match-procedure *rule-procedures*)
(push body-procedure *rule-procedures*)
`(insert-rule
(get-dbclass ,(get-trigger-dbclass pattern))
;return form to index rule
(function ;the match function for rule
,(if *bound-vars*
`(lambda (p)
(,(cadr match-procedure) p ,@ *bound-vars*))
(cadr match-procedure)))
(function ;;the body function for rule
,(if (or *bound-vars*
(not (eq condition :INTERN)))
(let ((tv (nreverse
(pattern-free-variables trigger))))
(unless (eq condition :INTERN)
(push 'TRIGGER-NODE tv))
`(lambda ,tv
(,(cadr body-procedure) ,@ tv
;(fn-name parameters)
,@ (scratchout tv *bound-vars*))))
(cadr body-procedure))))))
(defun parse-rule-trigger (trigger)
(values (cadr trigger)
(cond ((member (car trigger) '(:INTERN :IN :OUT))
(car trigger))
(t (error
"~% Unknown belief condition ~A in trigger ~A."
(car trigger) trigger)))
(cadr (member :VAR (cddr trigger)))
(cadr (member :TEST (cddr trigger)))))
(defun get-trigger-dbclass (trigger)
(cond ((variable? trigger)
(if (member trigger *bound-vars*) trigger
(error "~%Trigger dbclass is unbound -- ~A."
trigger)))
((atom trigger) (list 'QUOTE trigger))
(t (get-trigger-dbclass (car trigger)))))
;;;; Generating the body function
(defmacro with-pushed-variable-bindings (new-bindings
&rest body)
`(let ((*bound-vars* (append ,new-bindings
(scratchout ,new-bindings
*bound-vars*))))
,@ body))
(defun generate-body-procedure (pattern condition var body
&aux newly-bound env fname)
(setq newly-bound (pattern-free-variables pattern))
(if var (push var newly-bound))
(setq body (with-pushed-variable-bindings
newly-bound (fully-expand-body body)))
(setq env (append newly-bound
(scratchout newly-bound *bound-vars*)))
(unless (eq condition :INTERN) (push 'trigger-node env))
(setq fname (generate-rule-procedure-name pattern))
`(defun ,fname ,env
,@ (cond ((eq condition :INTERN) body) ;; Just do it
(t ;; Must check and see if the node's belief state
;; matches the rule's requirements
`((cond ((,(case condition
(:IN 'in-node?)(:OUT 'out-node?)
(t (error "~A bad condition -- GBF"
condition)))
TRIGGER-NODE) ,@ body)
(t (push (list ',fname ,@ env)
,(ecase condition
(:IN `(tms-node-in-rules TRIGGER-NODE))
(:OUT `(tms-node-out-rules TRIGGER-NODE)
))))))))))
(defun generate-match-procedure (pattern var test condition)
(multiple-value-bind (tests binding-specs)
(generate-match-body
pattern (pattern-free-variables pattern) test)
`(defun ,(generate-rule-procedure-name pattern)
(P ,@ *bound-vars*)
;;first arg, P, is the pattern
(if (and ,@ tests)
(values T (list ,@ (if var '(P))
,@ (reverse binding-specs))
,(unless (eq condition :INTERN) t))))))
(defun scratchout (l1 l2) ;non-destructive and order-preserving
(dolist (el1 l1 l2) (setq l2 (remove el1 l2))))
(defun generate-rule-procedure-name (pattern)
(intern (format nil "~A-~A-~A" *file-prefix* pattern (incf *file-counter*))))
;;;; Recursive macroexpansion
(defvar *macros-to-expand*
'(rule rlet rassert! rretract!
internal-rule add-internal-rule with-pushed-variable-bindings
without-contradiction-check with-contradiction-check
with-contradiction-handler with-JTRE))
(defun fully-expand-body (body)
(cond ((null body) nil)
((not (listp body)) body)
((symbolp (car body))
(cond ((member (car body) *macros-to-expand*)
(fully-expand-body (macroexpand body)))
(t (cons (car body)
(fully-expand-body (cdr body))))))
(t (cons (fully-expand-body (car body))
(fully-expand-body (cdr body))))))
;;;; Running rules
(defun insert-rule (dbclass matcher body &aux rule)
(let ((*JTRE* (dbclass-jtre dbclass)))
(setq rule (make-rule :MATCHER matcher
:BODY body
:DBCLASS dbclass
:ID (incf (jtre-rule-counter *JTRE*))))
(push rule (dbclass-rules dbclass))
(dolist (candidate (dbclass-facts dbclass))
(try-rule-on rule candidate))))
(defun try-rules (datum)
(dolist (rule (dbclass-rules (datum-dbclass datum)))
(try-rule-on rule datum)))
(defun try-rule-on (rule datum)
(let ((*JTRE* (dbclass-jtre (datum-dbclass datum))))
(multiple-value-bind (okay? bindings node?)
(funcall (rule-matcher rule)
(datum-lisp-form datum))
(when okay?
(when node?
(push (datum-tms-node datum) bindings))
(enqueue (cons (rule-body rule) bindings) *JTRE*)))))
(defun run-rules (&optional (*JTRE* *JTRE*))
(do ((form (dequeue *JTRE*) (dequeue *JTRE*))
(counter 0 (1+ counter)))
((null form)
(debugging-jtre "~% ~A rules run." counter)
(incf (jtre-rules-run *JTRE*) counter))
(apply (car form) (cdr form))))
(defun rules-waiting? (jtre) (jtre-queue jtre))
(defun enqueue (new j) (push new (jtre-queue j)))
(defun dequeue (jtre) (pop (jtre-queue jtre)))
;;;; Display routines
(defun show-rules (&optional (*JTRE* *JTRE*) (stream *standard-output*))
(format t "~%There are ~D rules in ~A:"
(jtre-rule-counter *JTRE*) (jtre-title *JTRE*))
(format stream "~% ~A queued." (if (null (jtre-queue *JTRE*)) "None"
(length (jtre-queue *JTRE*))))
(map-dbclass #'(lambda (dbclass)
(dolist (rule (dbclass-rules dbclass))
(print-rule rule stream)))))
(defun print-rule (rule &optional (stream *standard-output*))
(format stream "~% ~A: ~A, ~A" rule
(rule-matcher rule) (rule-body rule)))
(defun test-rule-expansion ()
(pprint (macroexpand
'(rule ((:IN (implies ?p ?q) :VAR ?f1)
(:IN ?p)) (rassert! ?q (:CE ?f1 ?p))))))
(defun get-rule (num &optional (*JTRE* *JTRE*))
(map-dbclass #'(lambda (dbclass)
(dolist (rule (dbclass-rules dbclass))
(when (= (rule-id rule) num)
(return-from GET-RULE rule))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -*- unify.lisp; -*-
;;;; Variables and unification
(defun variable? (x)
(and (symbolp x) ;A symbol whose first character is "?"
(char= #\? (elt (symbol-name x) 0))))
(defun unify (a b &optional (bindings nil))
(cond ((equal a b) bindings)
((variable? a) (unify-variable a b bindings))
((variable? b) (unify-variable b a bindings))
((or (not (listp a)) (not (listp b))) :FAIL)
((not (eq :FAIL (setq bindings
(unify (car a) (car b) bindings))))
(unify (cdr a) (cdr b) bindings))
(t :FAIL)))
(defun unify-variable (var exp bindings &aux val)
;; Must distinguish no value from value of nil
(setq val (assoc var bindings))
(cond (val (unify (cdr val) exp bindings))
;; If safe, bind <var> to <exp>