;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; actr-driver2.lisp
;;; dvr - 05/15/02
;;;
;;;      Driver model
;;;      Actr5 extended with segman v3.1
;;;      
;;;      defun drive
;;;   -------------------------------------
;;;   i. initialize perceptual-motor modules
;;;  ii. initialize segman
;;; iii. simulation variables
;;;  iv. Control centre
;;;   v. ACT-R model
;;;      with overlay
;;;
;;;
;;; INSTRUCTIONS
;;; To run this model:
;;; 1. Start Allegro ACL Professional Ed. 5.0.1 (6.0 has not been tested).
;;; 2. Start Act-r 5.0 by loading "d:/segman-v3.1/actr5/loadme.lsp" into ACL.
;;; 3. Start segman by loading "d:/segman-v3.1/load-system.lisp" into ACL.
;;; 4. Load DUMAS (this file) into ACL
;;; 5. Run the driver game by running the command
;;;             d:\segman-v3.1\driving-environment\driveraligned.html
;;;    This will automatically place the Game window in a position that DUMAS can
;;;    handle.  
;;; 6. Typing (drive) in the ACL debug window will start the simulation.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;To start the simulation type (drive)
; The game environment is somewhat unstable.  Test manually to see if steering 
; and accelerating works before starting the simulation.		       

(defun drive ()
  ;; This driver does not use pm to look at the game and is more effecient
  (segman::single-click)
  (vision::attend-road)
  ;; Gathering visual points
  (vision::far-focus)
  (vision::near-focus)
  (segman::single-click)
  ;; adjusting speed
  (segman::single-click)
;  (sleep 1)
  (vision::driving-key #\a 0.45)
;  (sleep 1)
;  (vision::driving-key #\z 0.25)
  (sleep 1)
  ;; This resets the actr model to its initial state.
  (reset)
  ;; some variables initializations
  (Setf force 0)
  (setf difference 0)
  (setf count 0)
  (run))				;run the actr model # times
;;;----------------------------------------------------------------------------------
;;; i. initialize  RPM
(defvar *experiment-window* nil "a global variable to hold
 the interactive display")   
(defvar *response* nil "a variable to hold the key press value")
(defmethod rpm-window-key-event-handler ((win rpm-window) key)
  (setf *response* (string-upcase (string key)))
  (remove-all-items-from-rpm-window *experiment-window*)
  (when *actr-enabled-p* 
    (pm-proc-display)))          

(defmethod rpm-window-key-event-handler ((win virtual-window) key)
  (setf *response* (string-upcase (string key)))
  (remove-all-items-from-rpm-window *experiment-window*)
  (when *actr-enabled-p* 
    (pm-proc-display)))

(defun do-experiment ()    
    (if *actr-enabled-p*  ;; If the model is doing the task
        (pm-run 10)       ;; Then run it for up to 10 seconds 
      (while (null *response*);; Else wait for key pres
        (allow-event-manager *experiment-window*)))
    ;; and give the system a chance to process events. 
    ;; Return the key press.
    *response*)

(clear-all)
(pm-reset)
(sgp :er t :v t)
(pm-set-params :real-time t :show-focus nil)
;;;----------------------------------------------------------------------------------
;;;  ii. simulation variables
;; data-structures to collect driving data
(setf drive_data1 (make-hash-table))
(gethash '*time* drive_data1)
(setf drive_data2 (make-hash-table))
(gethash '*time* drive_data2)
(setf drive_data3 (make-hash-table))
(gethash 'count drive_data3)

(defun putout ()
  (out)
 ; (outb)
  ;(outc)
  )

(defun out ()
  (with-open-file (output "d:/segman-v3.1/driver/data.txt"
		   :direction :output :if-exists :supersede)
    (maphash #'(lambda (k v)
		 (format output "~% ~,3F ~,3F" k v))
	     drive_data1))
  (format t "~% <<<<<<<Writing data to data.txt>>>>>>")
  )

;(defun outb ()
;  (with-open-file (output "d:/segman-v3.1/driver/speed1/datab.txt"
;		   :direction :output :if-exists :supersede)
;    (maphash #'(lambda (k v)
;		 (format output "~% ~,3F ~,1F" k v))
;	     drive_data2))
;  (format t "~% <<<<<<<Writing data to datab.txt>>>>>>")
;  )

;(defun outc ()
;  (with-open-file (output "d:/segman-v3.1/driver/datac.txt"
;		   :direction :output :if-exists :supersede)
;    (maphash #'(lambda (k v)
;		 (format output "~% ~,1F ~,3F" k v))
;	     drive_data3))
;  (format t "~% <<<<<<<Writing data to datac.txt>>>>>>")
;  )  
;;;----------------------------------------------------------------------------------
;;;  iii. segman initializations
;originally defined in d:/segman-v3.1/driving-vision/routines.lisp
;hacked for current settings 
(defun horizon (&optional (defaultp t))
  (declare (ignorable defaultp))
  #+jlinker (loop for horizon = (jcall "get_horizon" *road*)
		until horizon
		finally (return horizon))
  ;; Something here seems to be broken.
  #-jlinker (let ((horizon (c_get_horizon)))
	      (if (and (zerop horizon) defaultp)
		  (- 600 (field-bounds nil :top)) ; Constant, hacked default
		horizon)))

;steering and breaking
(defparameter time 0.05)

(defun driving-key (key time)
  (segman::key-down key)
  (mp::process-run-function (format t "Press ~S for ~A seconds." key time)
			    #'(lambda ()
				(sleep time)
				(segman::key-up key))))
;steering
(defparameter *steering-scale* 1.9)	;estimated 

(defun steer-left (&key magnitude)
  (driving-key :LEFT (* magnitude *steering-scale*)))

(defun steer-right (&key magnitude)
  (driving-key :RIGHT (* magnitude *steering-scale*)))

;;;----------------------------------------------------------------------------------
;;; iv. Control centre
(defun controlloop ()
  (if (<= deviation 4.3)
      (modwme drive state control direction ahead)
    (takeaction)))

(defun takeaction ()
  (if  (> deviation 15)
      (modwme drive state control-speed)
     (modwme drive state control)))
  
(defun change-speed (&key inverse-magnitude)
  (progn (vision::driving-key #\z force)
	 (cond ((> difference 17) (setf force 0.40))
	       ((> difference 13) (setf force 0.25))
	       ((> difference 8) (setf force 0.01)))))

(defun getdirection ()
  (progn
    ;1.Look at screen and collect environment dataa
;    (segman::single-click)
    (vision::attend-road)
    (vision::far-focus)
    (vision::near-focus)
    ; bind degrees of deviation and direction
    (Setf direction (nth 1 (multiple-value-list (vision::lane-deviation :'2 :'4))))
    (Setf deviation (nth 0 (multiple-value-list (vision::lane-deviation :'-30.0 :'4))))
    (cond ((> deviation 36) (modwme drive state crash))
	  ((eql direction ':right) (modwme drive direction right))
	  ((eql direction ':left) (modwme drive direction left))
	  ((eql direction nil)  (modwme drive direction ahead))	;Pass info to actr5
	  (t "bufferstuffing galore!"))
    ;calculate magnitude variable for steering and breaking
    (setf magnit (+ (/ deviation 100) .03))
    (if (< magnit .001)
	(Setf magnit .001))
    (defparameter magn (* magnit *steering-scale*)) ;estimated)
    (setf magnveryhard (+ 1.5 magnit))
    ;2.Put in hash-tables
    (setf (gethash *time* drive_data1) deviation)
    (cond ((eql direction ':right) (setf (gethash *time* drive_data2) 1))
	  ((eql direction ':left)  (setf (gethash *time* drive_data2) 2))
 	  ((eql direction  nil) (setf (gethash *time* drive_data2) 3)))
    (setf (gethash count drive_data3) deviation)
    (setf (gethash (- count 1) drive_data3) 0)
;   (format t "~% count is ~A " count)
    (format t "~% deviation is ~A degrees" deviation)
    (setf difference (abs(- deviation (gethash (- count 1) drive_data3))))))

;;;----------------------------------------------------------------------------------
;;;  v. ACT-R model
;;;Overlay
;;Manipulate working memory size, see
;;     * Lovett, M. C., Daily, L. Z., & Reder, L. M. (2000). A source activation theory
;;       of working memory: Cross-task predictions of performance in ACT-R. Journal of
;;       Cognitive Systems Research, 1, 99-118.
(defvar *goal-activation* 1.0
  "Amount of activation source level to be evenly split among goal elements.")

;;;Decalarative memory    
(chunk-type driving state direction )
(add-dm (drive isa driving state start))
;;; place the chunk named goal in the goal buffer
(goal-focus drive)
;;;Productions
(P go
   =goal>
      ISA         driving
      state       start
==>
      !Output!    (************************GO!!*************************)
   =goal>
      state       perceive
      )

;;Look the driving environment
(P perceive-environment
   =goal>
      ISA         driving
      state       perceive
==>
   =goal>
      state       decide
      !eval!      (getdirection)
      !eval!      (setf count (+ count 1))
      )

;;Decide what to do
(P decide-action
   =goal>
      ISA         driving
      state       decide
==>
   =goal>
      state       control-speed
      !eval!      (controlloop)
      )

;;Brake if necessary
(P brake
   =goal>
      ISA         driving
      state       control-speed
==>
   =goal>
      state       danger
     !eval!       (change-speed :inverse-magnitude force)
)

;;Steer to the right
(P steer-right
  =goal>
     ISA         driving
     state       control
     direction   right
 ==>
 !output!    (Going to the right >>>>>>>>>>>>>>>>>>>>>>>>)
 =goal>
    state        perceive		;back to check
    !eval!       (vision::steer-right :magnitude magn)
)

;;Steer to the left
(P steer-left
   =goal>
      ISA         driving
      state       control
      direction   left
==>
      !output!    (<<<<<<<<<<<<<<<<<<<<Going to the left)
   =goal>
      state       perceive		;back to check
      !eval!      (vision::steer-left :magnitude magn)
)

;;Steer hard to right
(P steer-hard-right
   =goal>
      ISA         driving
      state       danger		;indicates roadedge is near
      direction   right
==>
      !output!    (***Good Golly!***)
   =goal>
    state        perceive		;back to check
    !eval!       (vision::steer-right :magnitude magnveryhard)
)

;;Steer hard to left
(P steer-hard-left
   =goal>
      ISA         driving
      state       danger		;indicates roadedge is near
      direction   left
==>
      !output!    (***Good Golly!***)
   =goal>
    state        perceive		;back to check
    !eval!      (vision::steer-left :magnitude magnveryhard)
)


;; Just-a-cruising
(P cruising
   =goal>
      ISA         driving
      state       control
      direction   ahead
==>
      !output!    (Cruising)
   =goal>
      state       perceive		;back to check
)

;; Just crashing
(P crashing
   =goal>
      ISA         driving
      state       crash
==>
      !output!    (************************Crash*************************)
   =goal>
   !eval!         (putout)			;create a data-file for each run
   !pop!       
)