;;;Hopfield nets
(require "binry-hop")

;;;lisp pbm utilities
(require "bit-d-generate")

;;; Hardcoding the number 64 everywhere,
;;; even though it's returned as the second value somewhere.
(defvar *cols* '64)
(defvar *rows* '64)

;;; directory of memories
(defvar *dir* (mapcar 'enough-namestring
              (directory #p"memories/*.*")))

;;; a hopfield net closure
(defvar *bunny* (hop::closure-hop-net (* *cols* *rows*)))

;;; ~/fun/ format string to print input/output matrix
(defun cl-user::format-a2a (stream arg &rest ignored)
(declare (ignore ignored)) (bdg::arr2ascii arg *cols* stream))
(funcall *bunny* :format-pot-mems "~/cl-user::format-a2a/~%")

;;; Initially set the input potentials
(defvar *input* (bdg::pbm2arr #p"input.pbm"))
(funcall *bunny* :set-potential *input*)

;;; Changing memories to reach different results
(defvar *n-images* 5)
(dolist (s (subseq *dir* 0 *n-images*))
(print s)(terpri)
(funcall *bunny* :push-memory (bdg::pbm2arr s)))

;;; Breadth first update until probably converged
;;; Pause after updates for y/n <ret> but don't use it
(defvar *last-count* '0)
(loop for n from 0
for out = (with-output-to-string (*standard-output*)
           (funcall *bunny* :format-pot-mems t))
for new-count = (loop for ch across out summing (if (char= #\1 ch) 1 0))
do (print out)
do (format t "~r:~%" n)
do (format t "old: ~d new: ~d~%" *last-count* new-count)
do (funcall *bunny* :update t)
do (y-or-n-p "Are you not satisfied?")
do (print '(I dont care))
do (terpri)
while (not (equal *last-count* new-count))
do (setq *last-count* new-count))

(si:quit)