;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: uncertainty/algorithms/read-bif.lisp

;;;; Reading Bayesian Networks in the Bayesian Interchange Format (BIF)

;;; BIF is the format of the Bayesian Network Repository; for example
;;;   variable Age { type discrete [ 3 ] { Adolescent, Adult, Senior }; }
;;;   probability ( Age ) { table 0.2, 0.6, 0.2; }
;;;   probability ( SocioEcon | Age ) { (Adolescent) 0.40, 0.40, 0.19, 0.01; ... }
;;; READ-BIF turns such a text into a BAYES-NET (see bayes-nets.lisp) whose
;;; variables and values are symbols, with the nodes in topological order.

(defun bif-word-char? (c)
  (or (alphanumericp c) (member c '(#\_ #\- #\. #\+))))

(defun bif-tokens (text)
  "Split a BIF text into words and the punctuation { } ( ) [ ] | , ;,
  dropping the // comments."
  (let ((tokens nil) (i 0) (n (length text)))
    (loop while (< i n) do
	  (let ((c (char text i)))
	    (cond ((member c '(#\{ #\} #\( #\) #\[ #\] #\| #\, #\;))
		   (push (string c) tokens)
		   (incf i))
		  ((and (char= c #\/) (< (+ i 1) n) (char= (char text (+ i 1)) #\/))
		   (setf i (or (position #\Newline text :start i) n)))
		  ((bif-word-char? c)
		   (let ((j (or (position-if-not #'bif-word-char? text :start i) n)))
		     (push (subseq text i j) tokens)
		     (setf i j)))
		  (t (incf i)))))
    (nreverse tokens)))

(defun bif-symbol (word)
  (intern (string-upcase word)))

(defun bif-number (word)
  (let ((x (let ((*read-default-float-format* 'double-float)
		 (*read-eval* nil))
	     (read-from-string word))))
    (if (numberp x) x (error "Not a number in BIF: ~A" word))))

(defun read-bif (source)
  "Read a Bayesian network in BIF from SOURCE, a pathname or the BIF text,
  and return it as a BAYES-NET."
  (let ((tokens (bif-tokens
		 (if (pathnamep source)
		     (with-open-file (stream source)
		       (let ((text (make-string (file-length stream))))
			 (subseq text 0 (read-sequence text stream))))
		   source)))
	(domains nil)                   ; alist variable -> values
	(specs nil))                    ; alist variable -> (parents cpt)
    (labels ((next () (pop tokens))
	     (skip-block ()
	       ;; Skip up to the "{" and then to its matching "}"
	       (loop until (equal (next) "{"))
	       (let ((depth 1))
		 (loop until (= depth 0) do
		       (let ((token (next)))
			 (cond ((equal token "{") (incf depth))
			       ((equal token "}") (decf depth)))))))
	     (numbers-until-semicolon ()
	       (loop for token = (next)
		     until (equal token ";")
		     unless (equal token ",") collect (bif-number token))))
      (loop while tokens do
	    (let ((token (next)))
	      (cond
	       ((equal token "variable")
		;; variable NAME { type discrete [ k ] { v1, v2, ... }; ... }
		(let ((name (bif-symbol (next)))
		      (values nil))
		  (loop until (equal (next) "{"))
		  (let ((depth 1))
		    (loop until (= depth 0) do
			  (let ((token (next)))
			    (cond ((equal token "{") (incf depth))
				  ((equal token "}") (decf depth))
				  ((and (= depth 2) (not (equal token ",")))
				   (push (bif-symbol token) values))))))
		  (push (cons name (nreverse values)) domains)))
	       ((equal token "probability")
		;; probability ( VAR | P1, P2 ) { (v1, v2) p, ...; ... }
		(next)                  ; "("
		(let ((variable (bif-symbol (next)))
		      (parents nil)
		      (cpt nil))
		  (loop for token = (next)
			until (equal token ")")
			unless (member token '("|" ",") :test #'equal)
			do (push (bif-symbol token) parents))
		  (setf parents (nreverse parents))
		  (next)                ; "{"
		  (loop for token = (next)
			until (equal token "}")
			do (cond ((equal token "table")
				  (push (cons nil (numbers-until-semicolon)) cpt))
				 ((equal token "(")
				  (let ((key (loop for v = (next)
						   until (equal v ")")
						   unless (equal v ",")
						   collect (bif-symbol v))))
				    (push (cons key (numbers-until-semicolon)) cpt)))
				 ((equal token "default")
				  (numbers-until-semicolon))))
		  (push (list variable parents (nreverse cpt)) specs)))
	       ((equal token "network") (skip-block)))))
      (setf specs (nreverse specs))
      ;; Build the nodes, parents before children
      (let ((added nil) (nodes nil))
	(labels ((add (variable)
		   (unless (member variable added)
		     (destructuring-bind (parents cpt)
			 (cdr (assoc variable specs))
		       (mapc #'add parents)
		       (let ((values (cdr (assoc variable domains))))
			 (push (list variable parents
				     (mapcar #'(lambda (entry)
						 (cons (car entry)
						       (mapcar #'cons values
							       (cdr entry))))
					     cpt)
				     values)
			       nodes))
		       (push variable added)))))
	  (mapc #'add (mapcar #'car specs)))
	(bayes-net
	 (mapcar #'(lambda (node)
		     ;; A root's CPT is just its distribution
		     (destructuring-bind (variable parents cpt values) node
		       (list variable parents
			     (if parents cpt (cdr (first cpt)))
			     values)))
		 (nreverse nodes)))))))
