Physiology_thread.lisp 57.6 KB
Newer Older
1
#| Copyright 2019 Christopher L. Dancy II
root's avatar
root committed
2 3 4 5 6 7 8 9 10 11 12 13
		This program is free software: you can redistribute it and/or modify
		 it under the terms of the GNU General Public License as published by
		 the Free Software Foundation, either version 3 of the License, or
		 (at your option) any later version.

		 This program is distributed in the hope that it will be useful,
		 but WITHOUT ANY WARRANTY; without even the implied warranty of
		 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
		 GNU General Public License for more details.

		 You should have received a copy of the GNU General Public License
		 along with this program.	If not, see <http://www.gnu.org/licenses/>.
14 15 16
|#

;;;By Christopher L. Dancy II
root's avatar
root committed
17
;;;Dept of Computer Science, Bucknell University
18
;;;Made to be used with HumMod v1.6.2 - Modular
19 20 21
;;;---------------
;;; ---For any nerve activity related to heart-rate, HR shouldn't go above : 208-(0.7*age) : (from H Tanaka, KD Monahan 2001).

root's avatar
root committed
22 23
;;; Tested w/ CCL
;;; Should theoretically work with sbcl
24
;;;	(*features* stil need to be tested for all implementation specific functions)
25 26 27 28


;;Thread library
;(eval-when (:compile-toplevel :load-toplevel :execute)
root's avatar
root committed
29 30
;	(let ((*compile-file-pathname* nil))
;		(asdf:load-system :bordeaux-threads)))
31

root's avatar
root committed
32
;;;Function to test for non ACT-R/Phi based events in queue (modified run function in scheduling.lisp to use)
33
(defun non-phi-events ()
34 35 36 37 38 39 40 41 42 43 44 45
	(or
		(mp-modules-events 'procedural)
		(mp-modules-events 'declarative)
		(mp-modules-events :fatigue)
		(mp-modules-events 'vision)
		(mp-modules-events 'audio)
		(mp-modules-events 'blending)
		(mp-modules-events 'temporal)
		(mp-modules-events 'goal)
		(mp-modules-events 'imaginal)
		(mp-modules-events 'motor)
		(mp-modules-events 'speech))
46 47
)

48 49 50 51 52 53 54 55 56
(defun wait-delete-output (out-file &optional (time-out 500))
	(let ((timed-out nil)
		    (end-time (+ (get-universal-time) time-out)))
		(while (and (not (probe-file out-file)) (< (get-universal-time) end-time)))
		(when (not (probe-file out-file)) (setf timed-out t))
		(handler-case
			(delete-file out-file)
			(error () nil))
		timed-out))
57

root's avatar
root committed
58 59 60
(defvar *HumModOutStream* (make-string-output-stream))

(defvar *HumModInStream* nil)
61 62
;;;Custom Physiology Function Section
;;HumMod Directory variable
63 64
#+:windows	(defvar *HumModDir* (subseq (namestring *LOAD-TRUENAME*) 0 (search (file-namestring *LOAD-TRUENAME*) (namestring *LOAD-TRUENAME*))))
#-:windows	(defvar *HumModDir* (substitute #\\ #\/ (subseq (namestring *LOAD-TRUENAME*) 0 (search (file-namestring *LOAD-TRUENAME*) (namestring *LOAD-TRUENAME*)))) :from-end t :count 1)
65 66 67 68 69 70

;;We use this so we have a reference to the next update-event that is scheduled to be run
(defvar *nextUpdateEvent* nil)

;;;Print out all key-value pairs: used with
(defun print-hash-table (key value)
root's avatar
root committed
71
	(format t "~s - ~s" key value))
72 73 74

;;;clear out any unwanted files
(defun clear-phys-files ()
root's avatar
root committed
75
	(sleep 0.005)
root's avatar
root committed
76
	(dolist (fileName (directory (concatenate 'string *HumModDir* "SolverOut" (phys-module-pipeID (get-module physio)))))
root's avatar
root committed
77
		(handler-case (delete-file fileName) (error () nil)))
root's avatar
root committed
78
	(dolist (fileName (directory (concatenate 'string *HumModDir* "SolverIn" (phys-module-pipeID (get-module physio)))))
root's avatar
root committed
79
		(handler-case (delete-file fileName) (error () nil)))
root's avatar
root committed
80
	(dolist (fileName (directory (concatenate 'string *HumModDir* (phys-module-pipeID (get-module physio)) ".tem")))
root's avatar
root committed
81
		(handler-case (delete-file fileName) (error () nil))))
82 83

;;;Initialize Variable and Variable Order Hash-Table for physiological variable order
root's avatar
root committed
84 85 86 87 88 89 90 91 92 93 94
(defun init-var-list-to-hash (myList)
	(handler-case
		(let ((phys (get-module physio)))
			(loop
				for k in myList
				do (when (not (equal ':|solverout| k))
					(loop
						for k2 in k
						do (when (not (equal ':|varroster| k2))
							(setf (gethash (cadr k2) (phys-module-vars phys)) 0))))))
		(error (e) (progn (print e) nil (return-from init-var-list-to-hash))))
95 96
t)

97 98
;;;Request values from Model Solver
(defun set-as-init-cond ()
99
"Sets current state as initial conditions for model"
100 101 102 103 104 105 106 107 108 109 110
	(let* ((phys (get-module physio))
				 (solver-input-file (concatenate 'string *HumModDir* "SolverIn" (phys-module-pipeID phys)))
				 (solver-in-msg "<solverin><newics/></solverin>")
				 (solver-out-file (concatenate 'string *HumModDir* "SolverOut" (phys-module-pipeID phys))))
		(with-open-file
			(messageStream	solver-input-file
				:direction :output :if-exists :overwrite :if-does-not-exist :create)
			(format messageStream solver-in-msg))
		(while (not (probe-file solver-out-file)))))

(defun create-ics-from-out (out-file ics-file-name phys &optional (delete-solverout? nil))
111
"Creates a suitable initial conditions file from the given output file"
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	(let ((out-vals (cdadr (s-xml:parse-xml-file out-file)))
				(init-str "<ics>"))
		(loop for val in out-vals and var in (cdadr (phys-module-physVarList phys))
			do (progn
				(setf init-str
					(concatenate 'string init-str "~&<var>~&<name>" (cadr var) "</name>~&<val>"
					 (cadr val) "</val>~&</var>"))))
		(setf init-str (concatenate 'string init-str "</ics>"))
		(with-open-file
			(msg-stream ics-file-name :direction :output :if-exists :overwrite
				:if-does-not-exist :create)
			(format msg-stream init-str)))
		(when delete-solverout?
			(delete-file out-file)))

127 128
;;;Advance the HumMod model a specified amount of time (mins)
(defun advance-phys (timeSlice)
129 130
"Advance the modelsolver forward in time
	timeSlice - The time in minutes"
root's avatar
root committed
131
	(let*	((advanceMessage
root's avatar
root committed
132
				 (concatenate 'string
root's avatar
root committed
133 134 135 136 137
						"\"<solverin><gofor><solutionint>"
						(format nil "~10,$" timeSlice)
						"</solutionint><displayint>"
						(format nil "~10,$" timeSlice)
						"</displayint></gofor></solverin>\""))
root's avatar
root committed
138 139
				 (phys (get-module physio))
				 (solverInputFile
root's avatar
root committed
140 141
					(concatenate 'string
						*HumModDir* "SolverIn" (phys-module-pipeID phys)))
root's avatar
root committed
142
				 (solverOutputFile
root's avatar
root committed
143
					(concatenate 'string
root's avatar
root committed
144 145 146 147 148 149 150 151 152
						*HumModDir* "SolverOut" (phys-module-pipeID phys)))
				 (max-wait
					(cond
						((<= timeSlice 2) 1)
						((< timeSlice 10) 6)
						((< timeSlice 60) 12)
						((< timeSlice 600) 24)
						((< timeSlice 3600) 48)
						(t 480))))
root's avatar
root committed
153 154
		(clear-phys-files) ;;Make sure we don't have any files left over for some reason

155
	(tagbody resetAdvance
root's avatar
root committed
156 157 158 159 160 161 162 163 164 165 166 167 168
		(model-output "Advancing: ~S~&" timeSlice)
		;;Create new input file for modelsolver to digest w/ advance time message
		;; (or keep trying until we don't get an error)
		(handler-case
			(with-open-file
				(messageStream	solverInputFile
					:direction :output :if-exists :overwrite :if-does-not-exist :create)
				(format messageStream advanceMessage))
			((or
					#+:ccl ccl::simple-file-error
					#+:sbcl sb-impl::simple-file-error
					simple-error) () (go resetAdvance)))
		;;Wait for file to be digested by ModelSolver
169
		(while (probe-file solverInputFile))
root's avatar
root committed
170 171 172
		;;Wait for ModelSolver to advance and output data from advancing specified time
		(let ((currTime (get-universal-time)))
			(handler-case
root's avatar
root committed
173
				(while (and (not (probe-file solverOutputFile)) (< (- (get-universal-time) currTime) max-wait)))
174
				(error (e) (print (concatenate 'string "Error near line 139 in Phys Module - " (write-to-string e)))))
CD's avatar
CD committed
175

root's avatar
root committed
176
		;;If we didn't get the output file, go back and do this all over again
177
		(when (not (probe-file solverOutputFile)) (print "Issue @ 141 - PT") (print (- (get-universal-time) currTime)) (go resetAdvance))))
178

root's avatar
root committed
179
	;;Translate those output data (which are in an xml file) into a list
180
	(tagbody parseValList
root's avatar
root committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
		(handler-case (setf physValueList (s-xml:parse-xml-file solverOutputFile))
			((or file-error s-xml::xml-parser-error type-error) ()
			(go parseValList)))
		(when (not physValueList)
			(go parseValList))
		;;If the modelsolver gave us a variable roster instead of the corresponding value list
		;; (When does this happen? Keeping it, but should investigate at some point)
		(when (equal (caadr physValueList) ':|varroster|)
			(while (not (handler-case (delete-file solverOutputFile)
				(error () nil))))
			(go parseValList)))
	;;Delete the output file after we've harvested those data
	(while (probe-file solverOutputFile)
		(handler-case
			(delete-file solverOutputFile)
			(error () nil)))
197

root's avatar
root committed
198
	;;Save the new list of values
199
	(setf (phys-module-physValList phys) physValueList)
root's avatar
root committed
200
	;;Record values requested by model to list (so that they can be analyzed later)
201
	(let ((newVals (record-phys-vals (phys-module-recordedPhys phys) physValueList (phys-module-vals-analysis phys))))
root's avatar
root committed
202 203 204 205
		(when (car newVals) (setf (phys-module-vals-analysis phys) newVals)))

		;;Record advance-phys to internal event trace
		(push (list #'advance-phys (list timeSlice)) (phys-module-solverActionTrace phys))))
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
;;Function to retrieve phys values for specified list
(defun get-phys-vals (baseLine physVals)
 (let ((myHash (phys-module-vars (get-module physio)))
		 (varValList nil)
		 (valList nil))
		(if baseLine
			(setf valList (phys-module-physValList-baseline (get-module physio)))
			(setf valList (phys-module-physValList (get-module physio))))
		(dolist (var physVals)
			(let ((valNum (gethash (car var) myHash)))
				(setf varValList
					(list
						(if varValList
							(append varValList (list (append (list (car var)) (list (cadar (nthcdr valNum (cadr valList)))))))
							(list (append (list (car var)) (list (cadar (nthcdr valNum (cadr valList)))))))))))
		varValList))

224 225
;;;Set HumMod Vars using specified list
(defun set-phys-vals (varValList)
226 227
"Set HumMod variables using the input list
	varValList - a list of (variable value) pairs"
root's avatar
root committed
228 229 230
	(tagbody resetSetVal
		(clear-phys-files)
		(model-output "Changing the following physiology: ~a~&" varValList)
root's avatar
root committed
231
		;(format t "Changing the following physiology: ~a~&" varValList)
root's avatar
root committed
232
		(let ((phys (get-module physio))
233 234 235
					(setPhysMessage "<solverin>")
					(timeOut 6)
					(num-param-changes 0))
236 237
		;;Construct message to be sent to new HumMod Solver Process
		;; -We must find the chunk in the hash-table because the request to HumMod is case sensitive
root's avatar
root committed
238 239 240 241 242 243 244 245 246
		(dolist (v varValList)
			(loop
				for k being the hash-keys in (phys-module-vars phys)
				do
					(when (equal (string-upcase (car v)) (string-upcase k))
						(setq setPhysMessage
							(concatenate 'string
								setPhysMessage
								"<setvalue><var>" k "</var><val>"
247 248 249
								(format nil "~10,$" (cadr v)) "</val></setvalue>"))
						(incf num-param-changes))))
		(setf setPhysMessage (concatenate 'string setPhysMessage "</solverin>"))
root's avatar
root committed
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
		(let ((solverOutputFile (concatenate 'string *HumModDir* "SolverOut" (phys-module-pipeID phys)))
					(solverInputFile (concatenate 'string *HumModDir* "SolverIn" (phys-module-pipeID phys))))
			(tagbody startGetVals
				;;Set HumMod variables (by writing file to be digested by HumMod)
				(handler-case
					(with-open-file
						(messageStream solverInputFile
							:direction :output :if-exists :supersede :if-does-not-exist :create)
						(format messageStream setPhysMessage))
					((or
							#+:ccl ccl::simple-file-error
							#+:sbcl sb-impl::simple-file-error
							simple-error) () (go startGetVals)))
				(while (probe-file solverInputFile))
				(let ((currTime (get-universal-time)))
					;;We only wait so long for the file to be created
					(handler-case
						(while
							(and (not (probe-file solverOutputFile))
								(< (- (get-universal-time) currTime) timeOut)))
						(error (e) (format t "Error 200 Phys - ~a~%" (write-to-string e)))))
				;;If we ran out of time waiting for the file, start over
				(when (not (probe-file solverOutputFile)) (go startGetVals)))
				(let ((checkError nil))
					(handler-case
						(setf checkError (s-xml:parse-xml-file solverOutputFile))
						((or file-error s-xml::xml-parser-error type-error) () nil))
					;;The model solver may output multiple files (one for each parameter changed)
					(let ((currTime (get-universal-time)))
						;;We only wait so long for the file to be created
						(handler-case
							(while
								(and (not (probe-file solverOutputFile))
									(< (- (get-universal-time) currTime) timeOut)))
							(error (e) (format t "Error 214 Phys - ~a~%" (write-to-string e)))))
285 286
					;;The multiple output files don't occur for the prebuilt (Windows) Model Solver
					(wait-delete-output solverOutputFile)
287
					;;How many output files we should expect depends upon the number of param changes
288
					#|(while (> num-param-changes 0)
289 290 291 292
						(wait-delete-output solverOutputFile)
						(print "236 PT")
						(wait-delete-output solverOutputFile)
						(decf num-param-changes)
293
						(print "239 PT"))|#
root's avatar
root committed
294 295 296 297 298 299 300
					(dolist (v checkError)
						;;If we have an error, then we reset the entire physiology system and
						;; (try to) update it back to its last state
						;;This has been improved so that we now should be able to update to
						;; our state before the parameter change issue
						(when (equal ':|parameterchangefailed| v)
							(format t "236 PhysThread")
301
							(create-phys-vars)
root's avatar
root committed
302 303 304 305 306 307 308
							;;Go through list of actions affecting modelsolver and complete all of the actions
							;; (we reverse the list so we start from the beginning of the model run)
							(dolist (msAction (reverse (phys-module-solverActionTrace phys)))
								(apply (car msAction) (cdr msAction)))
							(go resetSetVal)))))
	;;Record set-phys-vals call to internal event trace
	(push (list #'set-phys-vals (list varValList)) (phys-module-solverActionTrace phys)))))
309 310 311

(define-condition modelSolver-error (error)
 ((text :initarg :text :reader text)))
312

root's avatar
root committed
313
(defun start-HumMod (phys)
314
"Starts HumMod (the ModelSolver)"
root's avatar
root committed
315 316 317 318 319 320 321
	;;So we can use basic windows api functions to restart a process if we're on a windows platform
	;; This doesn't seem to be needed anymore, but keeping here for legacy purposes for now
	;#+:Windows (open-shared-library "kernel32.dll")
	(let* ((old-dir)
				(get-module-physio)
				(progName
					#+:windows	"ModelSolver.exe"
322
					#+:darwin		"./ModelSolverMac"
root's avatar
root committed
323 324 325
					#+:linux		"./ModelSolverLinux"
					)
				(pipeID (phys-module-pipeID phys))
326 327 328 329 330 331 332
				(solverOutputFile (concatenate 'string *HumModDir* "SolverOut" pipeID))
				(model (concatenate 'string
				  "\"<root><model>" *HumModDir* "HumMod.DES</model><pipeid>"
				  pipeID "</pipeid></root>\""))
				(hide-gui "\"False\"")
				(non-gui-version "\"False\"")
				(activity-timeout "60"))
root's avatar
root committed
333 334 335 336 337 338 339 340 341

		(setf old-dir
			#+:ccl	(ccl::current-directory-name)
			#+:sbcl	(sb-posix:getcwd)
			)
		#+:ccl	(ccl::cwd *HumModDir*)
		#+:sbcl	(sb-posix:chdir *HumModDir*)
		(setf (phys-module-HProc phys)
			(run-program progName
342
				(list (concatenate 'string model hide-gui non-gui-version activity-timeout))
root's avatar
root committed
343 344 345 346 347
								:wait nil :output *HumModOutStream*))
		;;This gives the modelsolver time to process the initial HumMod model
		#+:ccl	(ccl::cwd old-dir)
		#+:sbcl	(sb-posix:chdir old-dir)
		;;Wait for the output file from starting HumMod, then delete it
348
		(while (not(probe-file solverOutputFile)))
root's avatar
root committed
349 350 351

		(handler-case (delete-file solverOutputFile)	(error () nil))))

352
;;Can be used to close HumMod from terminal
root's avatar
root committed
353 354 355 356 357 358 359 360 361 362
(defun close-HumMod (phys)
	(when (and (phys-module-HProc phys) (external-process-id (phys-module-HProc phys)))
		#+:Windows (external-call "TerminateProcess" (:* T) (external-process-id (phys-module-HProc phys)) :UNSIGNED 1)
		#+:Unix (signal-external-process (phys-module-HProc phys) 9)
		(setf (phys-module-HProc phys) nil)))

(setf ccl:*break-hook*
	(lambda (cond hook)
		(declare (ignore cond hook))
		(format t "Cleaning up ...")
CD's avatar
CD committed
363
		(close-HumMod (get-module physio))
root's avatar
root committed
364 365 366
		(ccl:quit)))

;;;Can be used to reset HumMod variables to initial model
367
(defun reset-HumMod ()
root's avatar
root committed
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
	(tagbody resetCreate
		(clear-phys-files)
		(let* ((phys (get-module physio))
					(pipeID (phys-module-pipeID phys)) ;Used by model solver as UID for in/out files
					(solverInputFile (concatenate 'string *HumModDir* "SolverIn" pipeID)) ;Filename for file that will be digested by modelsolver
					(solverOutputFile (concatenate 'string *HumModDir* "SolverOut" pipeID)) ;Filename for file that will be output by modelsolver
					;Reset/Restart Utility Message (needed to start getting values from HumMod model solver)
					(resetMessage "\"<solverin><restart/></solverin>\""))
			;;Create input file & place reset message in file
			;; This will tell the modelsolver to restart (needed to work correctly)
			(handler-case
				(with-open-file
					(messageStream	solverInputFile
					:direction :output :if-exists :overwrite :if-does-not-exist :create)
					(format messageStream resetMessage))
				((or
					#+:ccl ccl::simple-file-error
					#+:sbcl sb-impl::simple-file-error
					simple-error) () (go resetCreate)))

			(while (probe-file solverInputFile))
			(let ((currTime (get-universal-time)))
				(while (and (not (probe-file solverOutputFile)) (< (- (get-universal-time) currTime) 5))))
			(when (not (probe-file solverOutputFile)) (go resetCreate))
		(while (and (probe-file solverOutputFile) (not (handler-case (delete-file solverOutputFile)
			(error () nil))))))))
394

395 396 397 398 399 400
(defun load-HumMod-ICs (init-filename)
	"Used to load initial conditions based on ICS file saved from HumMod
		Inputs:
			filename - Name of file to be read in and parsed"

	(let* ((phys (get-module physio))
401 402
				 (solverInputFile (concatenate 'string *HumModDir* "SolverIn" (phys-module-pipeID phys)))
				 (solverOutputFile (concatenate 'string *HumModDir* "SolverOut" (phys-module-pipeID phys)))
403
				 (init-vals-msg "<solverin>")
404
				 ordered-val-list
405
				 old-dir
406
				 ics-val-list)
407 408 409 410 411 412 413 414
		(setf old-dir
			#+:ccl	(ccl::current-directory-name)
			#+:sbcl	(sb-posix:getcwd)
			)
		#+:ccl	(ccl::cwd *HumModDir*)
		#+:ccl	(ccl::cwd "../")
		#+:sbcl	(sb-posix:chdir *HumModDir*)
		#+:sbcl	(sb-posix:chdir "../")
415
		(setf ics-val-list (cdr (s-xml:parse-xml-file init-filename)))
416
		(setf init-vals-msg (concatenate 'string init-vals-msg (list #\newline) "<sending_current_values>" (list #\newline)))
417 418 419 420 421 422 423 424
		;Go through list returned by parsing and pull vals out
		; and put into msg (assuming 1st 2 elements are ICS & time)
		(dolist (var-val ics-val-list)
			(setf init-vals-msg
				(concatenate 'string init-vals-msg "<val>" (remove #\Space (cadr (caddr var-val))) "</val>" (list #\newline) )))
		;Add closing tag
		(setf init-vals-msg (concatenate 'string init-vals-msg "</sending_current_values>~&"))
		(setf init-vals-msg (concatenate 'string init-vals-msg "</solverin>"))
425

426
		(with-open-file
427
			(messageStream	(concatenate 'string init-filename ".ICSconv")
428 429 430
			:direction :output :if-exists :overwrite :if-does-not-exist :create)
			(format messageStream init-vals-msg))

431 432 433 434 435 436 437 438 439
		;;Send new values to model solver
		(handler-case
			(with-open-file
				(messageStream	solverInputFile
				:direction :output :if-exists :overwrite :if-does-not-exist :create)
				(format messageStream init-vals-msg))
			((or
				#+:ccl ccl::simple-file-error
				#+:sbcl sb-impl::simple-file-error
440
				simple-error) (e) (format t "Error loading ICS file!~&" e)))
441 442 443 444
			;Wait for solverInput file to be digested (and get of Output files if there are any holdin up the ModelSolver digesting the input files
			(while (probe-file solverInputFile)
				(handler-case (delete-file solverOutputFile)
					(error () nil)))
445
			#+:ccl	(ccl::cwd old-dir)
446 447
			#+:sbcl	(sb-posix:chdir old-dir)); (sleep 20)
			)
448

449 450
;;Generate hash-table of physiological variables & Hash-Table of the order of the variables
;; and default values
451
(defun create-phys-vars ()
root's avatar
root committed
452 453 454 455 456 457
	(let ((phys (get-module physio)))
		(tagbody resetCreate
			(clear-phys-files)
			(setf (phys-module-init phys) t)
			;;Set Physiology Substrate periodic communication time (HumMod)
			(let*	((pipeID (phys-module-pipeID phys))
root's avatar
root committed
458 459 460 461
						 ;;Set the name of the files used to input to model solver stream and to which solver outputs results
						 (solverInputFile (concatenate 'string *HumModDir* "SolverIn" pipeID))
						 (solverOutputFile (concatenate 'string *HumModDir* "SolverOut" pipeID))
						 (initial-advance-time (format nil "~10,$" (phys-module-initial-advance phys)))
root's avatar
root committed
462

463
						 ;Restart Utility Message (needed to start getting values from HumMod model solver)
464
						 (resetMessage "<solverin><restart/></solverin>~&")
root's avatar
root committed
465

root's avatar
root committed
466
						 ;Get Variables Message
467
						 (getVarsMessage "<solverin><requestvarroster/></solverin>~&")
root's avatar
root committed
468

root's avatar
root committed
469
						 (getValsMessage
root's avatar
root committed
470
							(concatenate 'string
471
								"<solverin><gofor><solutionint>" initial-advance-time
root's avatar
root committed
472
								"</solutionint><displayint>" initial-advance-time
473
								"</displayint></gofor></solverin>~&"))
root's avatar
root committed
474 475
						 (physVarList nil)
						 (physValueList nil))
476
				;;Send restart message to solver
root's avatar
root committed
477
				;; *This is needed for solver to correctly process messages sent*
CD's avatar
CD committed
478
				(clear-phys-files)
root's avatar
root committed
479 480 481 482 483 484 485 486 487
				(handler-case
					(with-open-file
						(messageStream	solverInputFile
							:direction :output :if-exists :overwrite :if-does-not-exist :create)
							(format messageStream resetMessage))
					((or
							#+:ccl ccl::simple-file-error
							#+:sbcl sb-impl::simple-file-error
							simple-error) () (go resetCreate)))
488
				;Wait for solverInput file to be digested (and get of Output files if there are any holdin up the ModelSolver digesting the input files
489 490
				(while (probe-file solverInputFile))
				(when (wait-delete-output SolverOutputFile 5) (go resetCreate))
491 492
				;; Initialize with stable values (default is obtained from running sim 1 week)
				(load-HumMod-ICs (phys-module-ics-file phys))
CD's avatar
CD committed
493

494
;(sleep 0.05)
root's avatar
root committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
				;Create input file for hummod to give us a list of variables and digest the output file created by HumMod (w/ the variables). Loop back around if there is an error
				(tagbody getVars
					(handler-case
						(delete-file solverOutputFile)
						(error () nil))
					(when (not (phys-module-vars-baseLine-init phys))
					(handler-case
						(with-open-file
							(messageStream	solverInputFile
								:direction :output :if-exists :overwrite :if-does-not-exist :create)
							(format messageStream getVarsMessage))
						((or
								#+:ccl ccl::simple-file-error
								#+:sbcl sb-impl::simple-file-error
								simple-error) () (go getVars)))
					;;Wait for input file to get digested by ModelSolver
					(let ((currTime (get-universal-time)))
512
						(while (and (not (probe-file solverOutputFile)) (< (- (get-universal-time) currTime) 10))))
root's avatar
root committed
513 514 515 516 517 518 519 520 521
					;;If we ran out of time for some reason, start the process all over again
					(when (not (probe-file solverOutputFile))
						(handler-case
							(delete-file solverOutputFile)
							(error () nil))
						(go getVars))
					;;Parse the list of variables output by the ModelSolver
					(let ((parseStart (get-universal-time)))
						(tagbody parseVarList
522
							(when (> (- (get-universal-time) parseStart) 10)
root's avatar
root committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
								(go getVars))
							(handler-case
								(setf physVarList (s-xml:parse-xml-file solverOutputFile))
								((or file-error s-xml::xml-parser-error type-error) () (go parseVarList)))
							;;To handle the times when the solver is on a slower machine
							;; and the files are output slower than expected at the initial setup
							(when (equal (cadr physVarList) ':|valuesframe|)
								(handler-case
									(delete-file solverOutputFile)
									(error () nil))
								(handler-case
									(setf physVarList (s-xml:parse-xml-file solverOutputFile))
									((or file-error s-xml::xml-parser-error type-error) () (go parseVarList))))
							(setf (phys-module-physVarList phys) physVarList)
							(when (not (init-var-list-to-hash physVarList)) (print "problem with init")
								(go getVars))
							(when (not physVarList) (go parseVarList))))))
				;Delete output file when finished with it
				(handler-case (delete-file solverOutputFile)
						(error () nil))
root's avatar
root committed
543
				(let ((timeOut 120))
root's avatar
root committed
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
					(tagbody startGetVals
						;;Get new value list output by the ModelSolver
						(handler-case
							(with-open-file
								(messageStream solverInputFile
									:direction :output :if-exists :overwrite :if-does-not-exist :create)
								(format messageStream getValsMessage))
							((or
									#+:ccl ccl::simple-file-error
									#+:sbcl sb-impl::simple-file-error
									simple-error) ()
								(progn
									(handler-case
										(progn (delete-file solverInputFile) (delete-file solverOutputFile))
										(error () nil))
									(go startGetVals))))

						(while (probe-file solverInputFile)) ;Wait for input file to be digested
						(let ((currTime (get-universal-time)))
							;;We only wait so long for the file to be created
							(handler-case
								(while (and (not (probe-file solverOutputFile)) (< (- (get-universal-time) currTime) timeOut)))
								(error () nil)))
						;;When we ran out of time, start this section of the code over
						(when (not (probe-file solverOutputFile)) (go startGetVals))
						;;Parse the list of values output by ModelSolver
						(let ((parseStart (get-universal-time)))
							(tagbody parseValList
								(when (> (- (get-universal-time) parseStart) 4) (go startGetVals))
								(handler-case
									(setf physValueList (s-xml:parse-xml-file solverOutputFile))
									((or file-error s-xml::xml-parser-error type-error) () (go parseValList)))
								;;If parsing the output file didn't error, but physValList is still nil
								;; (Can this actually happen?
								;; May want to explore in the future to see if I need to do this)
								(when (not physValueList)
									(go parseValList))

								;;If the modelsolver happens to give us a variable roster
								;; instead of list, delete and redo this section of code
								(when (equal (caadr physValueList) ':|varroster|)
									(while (not (handler-case (delete-file solverOutputFile)
										(error () nil))))
									(go parseValList))))))

				(while (not (handler-case (delete-file solverOutputFile) (error () nil))))
				;;Set our current values
591
				(setf (phys-module-physValList (get-module physio)) physValueList)
592 593 594
				;;Go through lists and replace matching values in hash table
				;; This is done because HumMod outputs values without corresponding
				;; variable names, instead the original order is maintained
595
				(let ((varCount 0))
root's avatar
root committed
596 597 598 599 600 601 602 603 604
					(dolist (k (phys-module-physVarList phys))
						(if (not(equal ':|solverout| k))
							(dolist (k2 k)
								(if (equal ':|valuesframe| k2) (go resetCreate))
								(when (and (not (equal ':|varroster| k2)) (not (equal ':|solutiondone| k2)))
									(setf varCount (+ varCount 1))
									(when (not (phys-module-vars-baseLine-init phys))
										(setf (gethash (cadr k2) (phys-module-vars phys))
										 varCount))))))
605 606
					;;Record total number of variables
					(setf (phys-module-varCount phys) varCount))
607 608
				;;Record values requested by model to list (to be analyzed later)
				(setf (phys-module-vals-analysis phys) (record-phys-vals (phys-module-recordedPhys phys) physValueList (phys-module-vals-analysis phys)))
root's avatar
root committed
609 610 611
			;;If our variable hash-table didn't get filled, run code again
			(when (eq (hash-table-count (phys-module-vars phys)) 0)
				(go resetCreate))
612 613 614
		;; If we have initial conditions for an experiment, load those initial conditions
		(when (phys-module-ics-exp-file phys)
			(load-HumMod-ICs (phys-module-ics-exp-file phys)))
root's avatar
root committed
615 616 617 618
		(setf (phys-module-physValList phys) physValueList)
		(setf (phys-module-physValList-baseline phys) physValueList)
		(setf (phys-module-vars-baseLine-init phys) t))))
	(clear-phys-files))
619 620 621 622

;;Record values for variables specified by model
(defun record-phys-vals (recVarList allValList savedValList)
	(let ((valNumbers nil)
root's avatar
root committed
623 624 625 626 627 628 629 630 631 632 633 634 635
				(tempValList nil))
	;Get value places and use those places to find value in allValList
		(dolist (recVar recVarList)
			(let ((valNum (gethash recVar (phys-module-vars (get-module physio)))))
				(when valNum
					(setf tempValList
						(if tempValList
							(append tempValList (list (list recVar (cadar (nthcdr valNum (cadr allValList))))))
							(list (list recVar (cadar (nthcdr valNum (cadr allValList))))))))))
		;;;Return values either as new list, or appended to existing list
		(if savedValList
			(append savedValList (list tempValList))
			(list tempValList))))
636

637 638
;;;find the time (in seconds) of the last event within the specified modules
(defun find-last-event-time (moduleList)
639
 (verify-current-mp
root's avatar
root committed
640 641
	 "mp-show-queue called with no current meta-process."
	 (let ((events (meta-p-events (current-mp)))
642
		(lastTime nil))
root's avatar
root committed
643
		(dolist (event events (length events))
644 645
	(dolist (mod moduleList (length moduleList))
	 (if (or (eq (evt-module event) mod)
root's avatar
root committed
646
			(eq (evt-module event) 'NONE))
647
			(if (or (eq lastTime nil)
root's avatar
root committed
648
					(> (evt-time event) lastTime))
649 650 651
					(setf lastTime (evt-time event))
					))))
	 (if lastTime
root's avatar
root committed
652 653
		lastTime
		0))))
654 655 656

;;;
(defun schedule-update-phys (delay)
657
 ;;if no events are currently scheduled,
658 659
 ;; schedule for update function to be run again later if there is a conflict resolution event eventually scheduled
 ;; Else check to see if last event is after the current time + delay and if it isn't, schedule next update and continue
root's avatar
root committed
660
 (if (not (non-phi-events))
661
	(progn
662 663 664 665
	 (setf *nextUpdateEvent* (schedule-event-after-change 'update-phys-vars :module 'physio :delay t :output t :maintenance t))
	 (return-from schedule-update-phys t)
	 (setf (phys-module-updateSwitch (get-module physio)) nil))
	(progn
666
	 (if (and
root's avatar
root committed
667 668 669 670 671
			(not (phys-module-updateSwitch (get-module physio)))
			(> (+ (phys-module-lastUpdate (get-module physio)) delay) (find-last-event-time (list 'procedural 'declarative :fatigue 'vision 'audio 'blending 'temporal 'goal 'imaginal 'motor 'speech))))
		(progn
		 (setf *nextUpdateEvent* (schedule-event-after-change 'update-phys-vars :module 'physio :delay t :output t :maintenance t))
		 (if (phys-module-physValList (get-module physio))
672 673 674
		(return-from schedule-update-phys nil)
		(return-from schedule-update-phys t))
		(setf (phys-module-updateSwitch (get-module physio)) t))
root's avatar
root committed
675 676 677 678
		(progn
		 (setf *nextUpdateEvent* (schedule-event-relative delay 'update-phys-vars :module 'physio :priority :max :output t :maintenance t))
		 (setf (phys-module-updateSwitch (get-module physio)) nil)
		 (return-from schedule-update-phys t)))))
679
)
680

681 682 683
;;;Update Phys Variable Hash Table with variable info from
;;; HumMod *updateDelay should be obtained from buffer parameter and be in ms*
(defun update-phys-vars ()
root's avatar
root committed
684
 (tagbody startUpdate
685
	(let*
686
	 ((phys (get-module physio))
root's avatar
root committed
687
	 (start-update-time (get-internal-real-time))
688 689 690
	 ;;Convert update delay to HumMod format (mins) and then to string
	 (physUpdateDelay (float (/ (phys-module-delay phys) 60)))
	 (pipeID (phys-module-pipeID phys)))
691 692 693 694 695 696 697 698 699 700 701 702
		(let*
		 ((physUpdateDelay (format nil "~10,$" physUpdateDelay))
		 ;;Set the name of the files used to input to model solver stream and to which solver outputs results
		 (solverInputFile (concatenate 'string *HumModDir* "SolverIn" pipeID))
		 (solverOutputFile (concatenate 'string *HumModDir* "SolverOut" pipeID))
		 (physValueList nil)
		 ;;Utility Messages that can be sent to solver
		 (getValsMessage
				 (concatenate 'string "\"<solverin><gofor><solutionint>" physUpdateDelay
				 "</solutionint><displayint>" physUpdateDelay "</displayint></gofor></solverin>\"")))
			;;
			(when (null (schedule-update-phys (phys-module-delay phys))) (return-from update-phys-vars))
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
			(tagbody startGetVals
				(while (probe-file solverOutputFile)
					(handler-case (delete-file solverOutputFile)	(error () nil)))
				 ;;Get new HumMod value list
				(handler-case
					(with-open-file
						(messageStream solverInputFile
							:direction :output :if-exists :overwrite :if-does-not-exist :create)
							(format messageStream getValsMessage)) ((or simple-error (or file-error))
							() (go startGetVals)))

				;wait for HumMod to digest input file
				(let ((startTime (get-universal-time)))
					(while (probe-file solverInputFile)
						(when (and (> (- (get-universal-time) startTime) 2) (probe-file solverOutputFile))
							(handler-case (delete-file solverOutputFile)	(error () nil)))))
				;wait for HumMod to output corresponding file and if it takes too long, reset
				(let ((startTime2 (get-universal-time)))
					(while (and (not (probe-file solverOutputFile)) (< (- (get-universal-time) startTime2) 2)))
					(when (not (probe-file solverOutputFile)) (model-output "Issue at line 617 in physiology module") (go startGetVals)))
				 (tagbody parseValList
					(handler-case (setf physValueList (s-xml:parse-xml-file solverOutputFile))
						((or file-error s-xml::xml-parser-error type-error) ()
							 (progn (print "ISSUE 2")(go startGetVals))))
					(when (not physValueList)
						(go parseValList))
					(when (equal (caadr physValueList) ':|varroster|)
						(while (not (handler-case (delete-file solverOutputFile)
							(error () nil))))
						(go parseValList))))

			(handler-case (delete-file solverOutputFile)
				 (error () nil))

		(setf (phys-module-physValList phys) physValueList)
		;;Record values requested by model to list (to be analyzed later)
		(let ((newVals (record-phys-vals (phys-module-recordedPhys phys) physValueList (phys-module-vals-analysis phys))))
			(when (car newVals) (setf (phys-module-vals-analysis phys) newVals)))
742

743 744 745
		(incf (phys-module-timeSliceCount phys)))
		;;Record update-phys to internal event trace
		(push (list #'update-phys-vars '()) (phys-module-solverActionTrace phys))
root's avatar
root committed
746
	)))
747 748 749 750 751 752 753

;;;Generate chunks from list of physiological variables
;;; and corresponding values
(defun phys-chunk-list (physVarList)
	(let ((newList '(ISA phys-var)))
	;;for each variable in our list
	(dolist (currSlot physVarList)
754
		;;append the slot (or slot value) to the list
755 756 757
		(setf newList (append newList (list (read-from-string
				(string-upcase (remove #\space (car currSlot))))))))
	;make a chunk from our list
root's avatar
root committed
758
	(define-chunks-fct (list newList))))
759 760 761

(defun schedule-phys-events ()
	(let ((phys (get-module physio)))
root's avatar
root committed
762 763
		(if (phys-module-enabled phys)
			(progn
764 765
				(if (not (phys-module-HProc phys))
					;;Start HumMod
CD's avatar
CD committed
766 767 768 769
					(progn
						(start-HumMod phys)
						(setf (phys-module-first-run phys) t))
					(setf (phys-module-first-run phys) nil))
root's avatar
root committed
770 771 772 773 774 775 776 777 778 779 780 781 782
				;;All chunk-types used in the efferent buffer should be a subtype of phys-var
				(chunk-type phys-var)
				(setf (phys-module-physValList phys) nil)
				(setf (phys-module-physValList-baseLine phys) nil)
				(schedule-event-relative 0.005 'create-phys-vars :module 'physio :priority :max :details "initialize physiological simulation system" :maintenance t)
				;;Schedule the function to keep these physiological values updated
				(setf *nextUpdateEvent* (schedule-event-relative 0.006 'update-phys-vars :module 'physio :priority :max :output t :maintenance t))
				#|(schedule-event 0.015 'set-food-intake :module 'physio :priority :min :params (list 0) :details "Make ACT-R control food intake")
				(schedule-event 0.015 'set-liquid-intake :module 'physio :priority :min :params (list 0) :details "Make ACT-R control liquid intake")|#)
			(close-hummod (get-module physio)))))

#|Begin phys change functions|#
;;;;;Cognition - Physiology Connection Function Section
783

root's avatar
root committed
784 785
(defvar *stress-on* nil)

root's avatar
root committed
786 787
(defun create-high-stress ()
	"Simulate the physiology side of (high) stress"
root's avatar
root committed
788
	(setf *stress-on* t)
789
	(cleanup-de-stress)
root's avatar
root committed
790
	(set-phys-vals
791 792 793 794 795 796
		(list (list "Sympathetics-Adrenal.ClampLevel" 2)
			(list "Sympathetics-Adrenal.ClampSwitch" 1)))
	(set-phys-vals
		(list (list "Sympathetics-General.EssentialEffect" 1)))
	(set-phys-vals
		(list (list "CorticotropinReleasingFactor.Stress" 4))))
root's avatar
root committed
797

root's avatar
root committed
798 799 800
(defun create-mid-stress ()
	"Simulate the physiology side of (medium) stress"
	(setf *stress-on* t)
801
	(cleanup-de-stress)
root's avatar
root committed
802 803 804 805 806 807
	(set-phys-vals
		(list (list "Sympathetics-General.EssentialEffect" 0.5)
			(list "CorticotropinReleasingFactor.Stress" 3)
			(list "Sympathetics-Adrenal.ClampSwitch" 1)
			(list "Sympathetics-Adrenal.ClampLevel" 1.5))))

root's avatar
root committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
(defun create-graded-symp-stress (&optional (length 20) (perc-inc 100) (num-steps 10))
	"Function to allowed a graded increase in sympathetic activity
	(presumably due to stress)
	Inputs:
		length: length of time in mins for (graded) stress increase (int)
		perc-inc: percentage of 'stress' that we move towards (double 0-100)
			(for now, we assume a max value for relevant phys vars)
		num-steps: number of iterations to increase towards increase-perc (int)"
	(let ((perc-per (/ perc-inc num-steps))
				(time-per (/ length num-steps))
				(+END-SYMP-ACT+ 1.1))
		(dotimes (i num-steps)
			(let ((symp-act (* perc-per i +END-SYMP-ACT+)))
				(schedule-event-relative 0.001 'set-phys-vals :module 'physio
					:params (list (list (list "Sympathetics-General.EssentialEffect" ())))
					:priority :max :details "Graded stress")
				(schedule-event-relative 0.002 'advance-phys
					:module :physio :priority :max :params (list time-per))))))

(defun de-stress ()
	"Turn stress-based params back to normal"
	(setf *stress-on* nil)
CD's avatar
CD committed
830
	(schedule-event-relative 0.001 'set-phys-vals :module 'physio
831 832 833
		:params
			(list (list	(list "Sympathetics-Adrenal.ClampSwitch" 0)))
		:priority :max :details "Turn stress off")
CD's avatar
CD committed
834
	(schedule-event-relative 0.002 'set-phys-vals :module 'physio
835 836 837
		:params
			(list (list (list "Sympathetics-General.EssentialEffect" 0)))
		:priority :max :details "Turn stress off")
CD's avatar
CD committed
838
	(schedule-event-relative 0.003 'set-phys-vals :module 'physio
839 840 841
		:params
			(list (list (list "CorticotropinReleasingFactor.Stress" 2)))
		:priority :max :details "Turn stress off"))
root's avatar
root committed
842

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
(defun de-stress-graded (&optional (ds-steps 5) (ds-len 60))
	"Turn stress back to normal in a graded manner
		Inputs:
			ds-steps - de-stress steps, provides number of steps to be used for grading de-stress [OPTIONAL]
			ds-len - de-stress length, provides length (seconds) of graded de-stress [OPTIONAL]
			*note* the above are only used if module ds-state is inactive (i.e., ==nil)"
	(setf *stress-on* nil)
	;ds-state will hold all of the state information we need
	(let* ((phys (get-module physio))
				 (ds-state (phys-module-de-stress phys))
				 (ds-steps (if ds-state (elt ds-state 0) ds-steps))
				 (ds-len (if ds-state (elt ds-state 1) ds-len))
				 (perc-per (/ 1 ds-steps))
				 (END-SYMP-ACT 1))
		;;If we haven't turned off the ClampSwitch, do so now
		(when (or (not ds-state) (not (= (elt ds-state 3) 0)))
			(schedule-event-relative 0.020 'set-phys-vals :module 'physio
				:params (list (list (list "Sympathetics-Adrenal.ClampSwitch" 0)))
				:priority :max :details "Graded stress reduction Adrenal")
			(if ds-state
				(setf (elt ds-state 3) 0)
				(setf ds-state (list ds-steps ds-len (mp-time) 0 nil nil))))
865

866 867 868 869 870
			;If we've already done as much graded de-stress as needed, reset state variable, else continue
			(if (> (- (mp-time) (elt ds-state 2)) ds-len)
				(setf (phys-module-de-stress phys) nil)
				(let* ((step (floor (* (/ (- (mp-time) (elt ds-state 2)) ds-len) ds-steps)))
							 (symp-act (- END-SYMP-ACT (* perc-per step END-SYMP-ACT))))
871

872 873 874 875 876
					(setf (elt ds-state 4) symp-act) ;Update our saved sympathetic activity state
					;General sympathetic arousal
					(schedule-event-relative 0.021 'set-phys-vals :module 'physio
						:params (list (list (list "Sympathetics-General.EssentialEffect"  symp-act)))
						:priority :max :details "Graded stress reduction Symp Essential")
877 878

					(print ds-state)
879
					;Reduce CRH-based stress
880
					(if (and (elt ds-state 5) (= (elt ds-state 5) 3) (> (- (mp-time) (elt ds-state 2)) (* ds-len 0.75)))
881
						(progn
882

883 884 885 886 887 888 889
							(setf (elt ds-state 5) 2)
							(schedule-event-relative 0.022 'set-phys-vals :module 'physio
								:params (list (list (list "CorticotropinReleasingFactor.Stress" 2)))
								:priority :max :details "Graded stress reduction CRF/CRH")
							(setf (phys-module-de-stress-evt phys)
								(schedule-event-relative (* (/ ds-steps ds-len) ds-len) 'de-stress-graded :module 'physio
									:priority :max :details "Global graded stress reduction")))
890 891
						(when (and (or (not (elt ds-state 5)) (= (elt ds-state 5) 4)) (> (- (mp-time) (elt ds-state 2)) (* ds-len 0.375)))

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
							(setf (elt ds-state 5) 3)
							(schedule-event-relative 0.022 'set-phys-vals :module 'physio
							 :params (list (list (list "CorticotropinReleasingFactor.Stress" 3)))
							 :priority :max :details "Graded stress reduction")
							(setf (phys-module-de-stress-evt phys)
								(schedule-event-relative (* (/ ds-steps ds-len) ds-len) 'de-stress-graded :module 'physio
									:priority :max :details "Global graded stress reduction"))))
					;If our sympathetic actitity is 0, then we no longer need to de-stress
					; cleanup any vars
					(when (= symp-act 0)
						(cleanup-de-stress))))))

(defun cleanup-de-stress ()
	"Used to cleanup any on-going (i.e., graded) de-stress process
	Also may be used to stop de-stress process when a new stressfule event occurs"
	(let ((phys (get-module physio)))
		(setf (phys-module-de-stress phys) nil)
		(when (phys-module-de-stress-evt phys)
			(delete-event (phys-module-de-stress-evt phys))
			(setf (phys-module-de-stress-evt phys) nil))))

root's avatar
root committed
913 914 915 916 917
(defun start-slow-breathing ()
	"Start deep slow breaths"
	(set-phys-vals
		(list (list " ControlledBreathing.RespRate" 6)
			(list "ControlledBreathing.TidalVolumeMax" 3000)
root's avatar
root committed
918
			(list "ControlledBreathing.TidalVolumeMin" 1200)
root's avatar
root committed
919 920 921
			(list "ControlledBreathing.ControlledBreathing" 1)))
		(de-stress))

root's avatar
root committed
922
(defun stop-controlled-breathing ()
root's avatar
root committed
923 924
	"Move to spontaneous breath"
	(set-phys-vals (list (list "ControlledBreathing.ControlledBreathing" 0))))
925 926 927 928 929 930 931 932 933 934 935

;;;Set food intake (eating) variable to a value
(defun set-food-intake (value)
	(set-phys-vals (list (list "DietIntakeNutrition.Fixed?" 1) (list "DietIntakeNutrition.FixedIntake(xGoal)" value)))
)

;;;Set liquid intake (drinking) variable to a value
(defun set-liquid-intake (value)
	(set-phys-vals (list (list "DietIntakeH2O.Fixed?" 1) (list "DietGoalH2O.Rate(L/Day)" value)))
)

root's avatar
root committed
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
#|End phys change functions|#

#|Begin phys state functions|#
;;;Compute CRH-based arousal
;; See epinephrine comments below for current state update
(defun compute-crh-arousal (&optional test)
	"crh(t_n)/crh(t_0)"
	(let* ((crh (read-from-string (cadar (car (get-phys-vals nil (list '("CorticotropinReleasingFactor.[CRF(pG/mL)]")))))))
	       (crh-stress (read-from-string (cadar (car (get-phys-vals nil (list '("CorticotropinReleasingFactor.StressEffect")))))))
	       (crh-base (read-from-string (cadar	(car (get-phys-vals t (list '("CorticotropinReleasingFactor.[CRF(pG/mL)]")))))))
	       (phys (get-module physio))
	       (crh-factor (/ crh crh-base)));(+ (- crh crh-base) (* (- (phys-module-max-crh phys) crh-base) 0.25)) (- (phys-module-max-crh phys) crh-base)))
		;Write to output file if we are testing things
		(if test
			(with-open-file
				(msgStream (concatenate 'string "CRH-Raw" *START-TIME* ".txt")
					:direction :output :if-exists :append :if-does-not-exist :create)
953
				(format msgStream "~S~T~10$~T~10$~&" crh-stress crh crh-base)))
root's avatar
root committed
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
		;Return the CRH factor or 0 if less than 0
		(if (< crh-factor 0) 0 crh-factor)))

;;;Compute Epinephrine-based arousal
;; At the moment, we're using a simple ratio (despite what the function comment
;; indicates). This is meant to keep things more simple right now.
;; Will reconsider the eqn in the future - ((epi-base)+((max-base)*0.25))/(max-base)
(defun compute-epi-arousal (&optional test)
	"epi(t_n)/epi(t_0)"
	(let* ((epi-base (read-from-string (cadar (car (get-phys-vals t (list '("EpiPool.[Epi(pG/mL)]")))))))
	       (epi (read-from-string (cadar (car (get-phys-vals nil (list '("EpiPool.[Epi(pG/mL)]")))))))
	       (phys (get-module physio))
	       (epi-factor (/ epi epi-base)));(+ (- epi epi-base) (* (- (phys-module-max-epi phys) epi-base) 0.25)) (- (phys-module-max-epi phys) epi-base)))))
		;Write to output file if we are testing things
		(if test
			(with-open-file
				(msgStream (concatenate 'string "EPI-RAW" *START-TIME* ".txt")
					:direction :output :if-exists :append :if-does-not-exist :create)
				(format msgStream "~10$~T~10$~&" epi epi-base)))
		;Return the epi factor or 0 if less than 0
		(if (< epi-factor 0) 0 epi-factor)))

#| Keeping these for historical purposes, but now just using
		compute-***-arousal functions above in Affective-Associations
		Could use some of this in new format in the future
979 980 981 982
;Arousal = Arousal(fear) + Arousal(Epi,CRH)
;Arousal(Epi,CRH) = CRH-base/(3*((CRH-High-Perc*CRH-MAX)-base)) + EPI-base/(3*((EPI-High-Perc*EPI-MAX)-base))
;;;Compute current arousal level
(defun compute-phys-arousal ()
root's avatar
root committed
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
	;If we havent had a chance to get phys variable values return 1, else compute
	(if (< (mp-time) 0.006)
	 1
	 (let* ((physio (get-module physio))
			 (epi (cadar (car (get-phys-vals nil (list '("EpiPool.[Epi(pG/mL)]"))))))
			 (crh (cadar (car (get-phys-vals nil (list '("CorticotropinReleasingFactor.StressEffect"))))))
			 ;(crh (cadar (car (get-phys-vals nil (list '("CorticotropinReleasingFactor.StressFactor"))))))
			 (epi-base (cadar (car (get-phys-vals t (list '("EpiPool.[Epi(pG/mL)]"))))))
			 (crh-base (cadar	(car (get-phys-vals t (list '("CorticotropinReleasingFactor.StressEffect"))))))
			 (arousal 0)
			 (crh-max (phys-module-crh-max (get-module physio)))
			 (crh-high-perc (phys-module-crh-high-perc (get-module physio)))
			 (epi-max (phys-module-epi-max (get-module physio)))
			 (epi-high-perc (phys-module-epi-high-perc (get-module physio)))
			 (crh-val (if (and crh crh-base)
					 (calc-crh-arousal (read-from-string crh) (read-from-string crh-base) crh-high-perc crh-max)
					 (/ 1 2)))
			 (epi-val (if (and epi epi-base)
					 (calc-epi-arousal (read-from-string epi) (read-from-string epi-base) epi-high-perc epi-max)
					 (/ 1 2))))
		 (setf arousal (+ crh-val epi-val))
		 arousal
	)))

1007 1008 1009

;;Compute crh arousal value
(defun calc-crh-arousal (crh crh-base crh-high-perc crh-max)
root's avatar
root committed
1010
 (* 0.5 (/ crh crh-base));(+ (/ (- crh crh-base) (* 6 (- (* crh-high-perc crh-max) crh-base))) (- 1 crh-high-perc)))
1011 1012 1013

;;Compute epinephrine arousal value
(defun calc-epi-arousal (epi epi-base epi-high-perc epi-max)
root's avatar
root committed
1014 1015 1016
 (* 0.5 (/ epi epi-base ));(+ (/ (- epi epi-base) (* 6 (- (* epi-high-perc epi-max) epi-base))) (- 1 epi-high-perc)))

|#
1017 1018

;;Compute cortisol factor
root's avatar
root committed
1019
(defun compute-cort (&optional test)
1020
	"(cort(t_n)/cort(t_0) + cortisol[uG/dL](t_n)/cortisol[uG/dL](t_0))/2
root's avatar
root committed
1021 1022
	cort(t_n) == (cort.gain(t_n)/cort.loss(t_n)
	That is, the average of the Cortisol circulating and the more rapid change in cortisol"
root's avatar
root committed
1023 1024 1025 1026 1027 1028 1029 1030 1031
	(let* ((cort (read-from-string (cadar (car (get-phys-vals nil (list '("Cortisol.[Conc(uG/dL)]")))))))
				 (cort-base (read-from-string (cadar (car (get-phys-vals t (list '("Cortisol.[Conc(uG/dL)]")))))))
				 (cort-gain (read-from-string (cadar (car (get-phys-vals nil (list '("Cortisol.Gain")))))))
				 (cort-gain-base (read-from-string (cadar (car (get-phys-vals t (list '("Cortisol.Gain")))))))
				 (cort-loss (read-from-string (cadar (car (get-phys-vals nil (list '("Cortisol.Loss")))))))
				 (cort-loss-base (read-from-string (cadar (car (get-phys-vals t (list '("Cortisol.Loss")))))))
				 (cort-ratio (if (and cort-gain cort-loss) (/ cort-gain cort-loss) nil))
				 (cort-ratio-base (if (and cort-gain-base cort-loss-base) (/ cort-gain-base cort-loss-base) nil)))
		(setf cort-norm
root's avatar
root committed
1032 1033
			(if (and cort-ratio cort-ratio-base cort cort-base)
				(/ (+ (/ cort-ratio cort-ratio-base) (/ cort cort-base)) 2) 0))
root's avatar
root committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
		;Write to output file if we are testing things
		(if test
			(with-open-file
				(msgStream (concatenate 'string "CORT-RAW" *START-TIME* ".txt")
					:direction :output :if-exists :append :if-does-not-exist :create)
				(format msgStream "~5$~T~5$~T~5$~T~5$~&" cort cort-base cort-ratio cort-ratio-base)))
		;Return the cort factor or 0 if less than 0
		(if (<= cort-norm 0) 0 cort-norm)))

#|End phys state functions|#
1044

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
#|---Begin Physiological Initial Condition Functions
		Provides some useful functions that can create initial condition files that can be used to run simulations under various conditions
		Initial condition files help us avoid having to take the time to get to some stable state related to a particular physiological state
|#
(defun make-Racinais08-ICS (new-ics-file-name phys)
	"Sets up physiology in a scenario that matches:
		Racinais, S., Gaoua, N., & Grantham, J. (2008).
		Hyperthermia impairs short-term memory and peripheral motor drive transmission.
		The Journal of Physiology, 586(19), 4751-4762."
	(schedule-event-relative 0.020 'set-phys-vals :module 'physio
		:params (list (list (list "PostureControl.Request" 3)))
		:priority :max :details "Change to standing posture")
	(schedule-event-relative 0.021 'set-phys-vals :module 'physio
		:params (list (list (list "Exercise-Control.Request" 2)))
		:priority :max :details "Use the treadmill")
	(schedule-event-relative 0.022 'set-phys-vals :module 'physio
		:params (list (list (list "AmbientTemperature.Temp(F)" 122)
												(list "RelativeHumidity.Percent" 50)))
		:priority :max :details "Change temperature and humidity")
	(schedule-event-relative 0.023 'advance-phys :module 'physio
		:module :physio :priority :max :params '(15)
		:details "Advance physiology 15 minutes")
	(schedule-break-relative 0.024)
	(run 0.5)
	(set-as-init-cond)
	(let ((solver-out-file (concatenate 'string *HumModDir* "SolverOut" (phys-module-pipeID phys)))
		    (ics-out-file (concatenate 'string *HumModDir* "../ICS/Racinais-2008_Hot.ICS")))
	(create-ics-from-out solver-out-file ics-out-file phys)))

#|---End Physiological Initial Condition Functions---|#

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
;;;
;;;;Helpful functions for examining physiological data
(defun get-recorded-vals ()
	(phys-module-vals-analysis (get-module physio)))


;;;
;;;;;ACT-R Module Section
(defstruct phys-module
	;;Delay to update HumMod variables
	(delay)
1087

1088 1089 1090 1091 1092 1093 1094
	;Switch that allows us to schedule an update-phys event x seconds(S.T. 0 <= x <= delay) past the end of any particular run
	(updateSwitch nil)

	;;Events (recorded so that we can delete them if we need to)
	(create-phys-event)
	(set-food-event)
	(set-drink-event)
1095

1096
	;;Initial time to advance model
1097 1098 1099 1100 1101
	(initial-advance 1)

	;File to be used for initial conditions
	ics-file

1102 1103
	;Flag used to tell us whether the ICS file is one
	; created by HumMod (thus needing to read in and converted in a way suitable for the Model Solver)
1104
	ics-exp-file
1105

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
	esc
	busy

	(vars-baseLine-init nil)
	;;List used to record values and conduct data analysis
	(vals-analysis nil)

	(enabled nil)

	;;Number of times we skip updating values due to errors (Used for debugging)
	(skipCount 0)

	;;Number of times we successfully update the values (Used for debugging)
	(timeSliceCount 0)

	;;Used to communicate with HumMod Process
root's avatar
root committed
1122
	(pipeID (write-to-string (random(get-universal-time))))
1123 1124
	(init nil)

root's avatar
root committed
1125
	;;Holds our physiological variables (key) and place in value list (val; e.g., 1, 2, 3, etc.)
1126 1127
	(vars (make-hash-table :test #'equal))
	;(vars-order (make-hash-table :test #'equal))
1128

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
	;List form of physiological variables
	(physVarList nil)

	;List that holds current physiological values
	(physValList nil)

	;List that holds baseline physiological values
	(physValList-baseLine nil)

	;;HumMod Process Identifier
	(HProc nil)

	;;Switch for continuous startle reflex effect on memory noise (:ans)
	epi-ans
1143

1144 1145 1146 1147 1148 1149 1150
	;;Parameter set by user to record certain variables
	(recordedPhys nil);

	;;Debug param used to count num of times going thru vars analysis loop
	(debugMe 0)

	(changeVar-List nil)
1151

1152 1153 1154
	;Total number of physiological variables
	(varCount 0)

root's avatar
root committed
1155 1156
	 ;;;Arousal Related vars
	 ;;Internal arousal value (linked to epi & CRF and used by DM)
1157 1158
	(arousal 0)

root's avatar
root committed
1159 1160 1161
	;;Obtained by setting integration nerve to value that results in max HR from
	;; (from Nater, La Marca 2006 - Stress-induced changes in human salivary
	;;	alpha-amylase activity-associations with adrenergic activity)
1162 1163
	(epi-max 67)

root's avatar
root committed
1164
	(crh-max 5)
1165 1166

	;;Found using highest value from Kirschbaum (1993) study (TSST)
root's avatar
root committed
1167
	(cort-max 28)
1168

root's avatar
root committed
1169
	(epi-high-perc 0.6)
1170 1171 1172 1173
	(crh-high-perc 0.75)
	(cort-high-perc 0.75)

	(max-integ-nerve-activation 2.7)
1174

1175 1176
	;;Holds the time of the (in ms) that the update-phys-vars function was run
	(lastUpdate 0)
root's avatar
root committed
1177 1178 1179 1180

	;;A trace of all previous functions called w/ their parameters
	;; (used if we get an error that forces us to restart)
	(solverActionTrace '())
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

	;[NOT IMPLEMENTED YET] Use this to save what physiological events we have in queue
	; an attempt to stop wierd overriding behavior by deleting events before
	(phys-sched '())

	;Used to save current state of de-stress
	; If active then == `(steps len[secs] last-time[secs] symp-adrenal symp-act crh)
	; else (inactive) then == nil
	(de-stress nil)
	;Hold the next de-stress event (if there is one in the mp queue)
	(de-stress-evt nil)
CD's avatar
CD committed
1192 1193
	;Tells us whether this is the 1st run of the module (i.e., it was reset once)
	(first-run nil)
1194 1195 1196 1197 1198 1199 1200 1201 1202
)

;Create module everytime new model is defined
(defun create-phys-module (model-name)
	 (declare (ignore model-name))
	 (make-phys-module))

;Delete module when model is deleted (not needed right now)
(defun delete-phys-module (phys)
root's avatar
root committed
1203
	(close-hummod phys))
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
;(start-HumMod)
;Reset module after model is reset or after initial creation of model
(defun reset-phys-module (phys)
	;;Close any previous versions of HumMod
	(schedule-event-relative 0.005 'schedule-phys-events :module 'physio :priority :max :details "Schedule all physio module-based setup events")
)

;Define our parameters created in define-module-fct
(defun phys-module-params (phys param)
	(if (consp param)
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
		(case (car param)
			(:phys-delay
				(setf (phys-module-delay phys) (cdr param) ))
			(:epi-ans
				(setf (phys-module-epi-ans phys) (cdr param) ))
			(:phys-enabled
				(setf (phys-module-enabled phys) (cdr param) ))
			(:esc
				(setf (phys-module-esc phys) (cdr param) ))
			(:recorded-phys
				(setf (phys-module-recordedPhys phys) (cdr param)))
			(:phys-ics-file
				(setf (phys-module-ics-file phys) (cdr param)))
1227 1228
			(:phys-ics-exp-file
				(setf (phys-module-ics-exp-file phys) (cdr param))))
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

		(case param
			(:phys-delay
				(phys-module-delay phys))
			(:epi-ans
				(phys-module-epi-ans phys))
			(:phys-enabled
				(phys-module-enabled phys))
			(:esc
				(phys-module-esc phys))
			(:recorded-phys
				(phys-module-recordedPhys phys))
			(:phys-ics-file
				(phys-module-ics-file phys))
1243 1244
			(:phys-ics-exp-file
				(phys-module-ics-exp-file phys)))))
1245 1246 1247 1248 1249

;Define query function for module (b = buffer)
(defun phys-module-query (phys b slot value)
	(case slot
	 (state
root's avatar
root committed
1250 1251 1252 1253 1254 1255
		(case value
		 (error nil)
		 (busy (phys-module-busy phys))
		 (free (not (phys-module-busy phys)))
		 (t (print-warning
			 "Bad state query to ~s buffer" b))))
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
	 (t (print-warning
		 "Invalid slot ~s in query to buffer ~s" slot b)))
)

(defun free-phys-module (phys)
	(setf (phys-module-busy phys) nil)
)

;;;Define request function for module (slides 53-54 in extending-actr.ppt)
(defun phys-module-requests (phys buffer spec)
1266
	;;start underlying substrate
1267 1268 1269 1270
	(if (not (phys-module-init phys))
	 (progn
		;;Schedule periodic updating of ans parameter (eventually I need to make this only happen if call to phys-substrate buffer is made)
		(if (phys-module-epi-ans phys)
root's avatar
root committed
1271 1272
			(schedule-periodic-event (phys-module-delay phys) 'do-epi-ans2
			:priority :max :initial-delay 1 :module :none :output nil :maintenance t))
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283

		;;Make it so cognition controlls eating (as opposed to HumMod)
		(set-food-intake 0)))
	(if (eq buffer 'efferent)
		(phys-create-chunk phys spec))
)

;;;;For now only explicit changes of the value will be parsed, later we will add relative changes (i.e. original value +- chunk slot value)
(defun phys-create-chunk (phys spec)
		(progn	(if (or (eq (chunk-spec-chunk-type spec) 'phys-var)
						(eq (cadr (chunk-type-supertypes-fct (chunk-spec-chunk-type spec))) 'phys-var))
root's avatar
root committed
1284
					(let ((delay 0))
1285 1286 1287 1288 1289 1290 1291
					(dolist (changeVar (chunk-spec-slot-spec spec))
					 (schedule-event-relative delay 'set-phys-vals
						:module 'physio :priority :min :params (list (list (list (write-to-string (cadr changeVar)) (caddr changeVar))))
						:details "Setting physiological variables"))
						 (setf (phys-module-busy phys) t)
						;;Put chunk into buffer and set module back to free after delay seconds
						;;Use schedule event to update variables every delay
1292
						(schedule-set-buffer-chunk 'efferent (define-chunks-fct (list (chunk-spec-to-chunk-def spec))) delay
1293
							:module 'physio :priority :min))
root's avatar
root committed
1294
					(progn (print (chunk-spec-chunk-type spec))
1295 1296 1297 1298
					 (print "Warning - invalid chunk-type in efferent buffer")))))


(define-module-fct 'physio
root's avatar
root committed
1299
	'(phys-substrate efferent output)
1300 1301
	(list
		(define-parameter
1302 1303
			:phys-delay
			:documentation "Delta for HumMod updates"
root's avatar
root committed
1304
			:default-value .05
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
			:valid-test (lambda (x) (and (numberp x) (>= x 0.002)))
			:warning "Non-negative number greater than 2ms"
			:owner t)
		(define-parameter
			:esc
			:owner nil)
		(define-parameter
			:epi-ans
			:documentation "Switch to turn on/off Epinephrine effect on memory noise (:ans)"
			:default-value nil
			:valid-test (lambda (x) (or (typep x 't) (typep x 'nil)))
			:owner t)
1317

1318 1319 1320 1321 1322 1323 1324 1325 1326
		(define-parameter
		:recorded-phys
		:documentation "Physiological (HumMod) variables to be recorded during the simulation"
		:default-value nil
		:valid-test (lambda (x) (listp x))
		:owner t)

		(define-parameter
		:phys-enabled
root's avatar
root committed
1327
		:documentation "Switch variable for physiology to continue to run w/ model"
1328 1329 1330
		:default-value nil
		:valid-test (lambda (x) (or (typep x 't) (typep x 'nil)))
		:owner t)
1331 1332 1333 1334 1335

		(define-parameter
		:phys-ics-file
		:documentation "File used to load initial conditions"
		:default-value "ICS/1wkNormal.ICS"
1336
		:valid-test (lambda (x) (or (typep x 'string) ))
1337
		:owner t)
1338 1339

		(define-parameter
1340 1341
		:phys-ics-exp-file
		:documentation "File used to load initial conditions for an experiment"
1342
		:default-value nil
1343
		:valid-test (lambda (x) (or (typep x 'string) (equal x nil)))
1344
		:owner t))
1345 1346 1347 1348 1349 1350 1351 1352 1353
	:version "1.0"
	:documentation
		"Module for underlying physiological substrate (via HumMod mechanisms)"
	:creation 'create-phys-module
	:reset 'reset-phys-module
	:delete 'delete-phys-module
	:params 'phys-module-params
	:query 'phys-module-query
	:request 'phys-module-requests
root's avatar
root committed
1354
)