id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14,231 | addition.lisp | asmaloney_ACT-R/tutorial/unit1/addition.lisp |
(clear-all)
(define-model addition
(sgp :esc t :lf .05)
(chunk-type number number next)
(chunk-type add arg1 arg2 sum count)
(add-dm
(zero isa number number zero next one)
(one isa number number one next two)
(two isa number number two next three)
(three isa number number three next four)
(four isa number number four next five)
(five isa number number five next six)
(six isa number number six next seven)
(seven isa number number seven next eight)
(eight isa number number eight next nine)
(nine isa number number nine next ten)
(ten isa number number ten)
(second-goal ISA add arg1 five arg2 two))
(P initialize-addition
=goal>
ISA add
arg1 =num1
arg2 =num2
sum nil
==>
=goal>
ISA add
sum =num1
count zero
+retrieval>
ISA number
number =num1
)
(P terminate-addition
=goal>
ISA add
count =num
arg2 =num
sum =answer
=retrieval>
ISA number
number =answer
==>
=goal>
ISA add
count nil
!output! =answer
)
(P increment-count
=goal>
ISA add
sum =sum
count =count
=retrieval>
ISA number
number =count
next =newcount
==>
=goal>
ISA add
count =newcount
+retrieval>
ISA number
number =sum
)
(P increment-sum
=goal>
ISA add
sum =sum
count =count
- arg2 =count
=retrieval>
ISA number
number =sum
next =newsum
==>
=goal>
ISA add
sum =newsum
+retrieval>
ISA number
number =count
)
(goal-focus second-goal)
)
| 1,872 | Common Lisp | .lisp | 85 | 17.482353 | 43 | 0.539111 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c86b01f3578ce1d17cd8ad00c5adcc508eee8ef7b280b211f2b53ce3adf8d9f4 | 14,231 | [
107259
] |
14,232 | subitize-model.lisp | asmaloney_ACT-R/tutorial/unit3/subitize-model.lisp | (clear-all)
(define-model subitize
(sgp :v t)
(sgp :show-focus t
:visual-num-finsts 10
:visual-finst-span 10)
(chunk-type count count step)
(chunk-type number number next vocal-rep)
(add-dm (zero isa number number zero next one vocal-rep "zero")
(one isa number number one next two vocal-rep "one")
(two isa number number two next three vocal-rep "two")
(three isa number number three next four vocal-rep "three")
(four isa number number four next five vocal-rep "four")
(five isa number number five next six vocal-rep "five")
(six isa number number six next seven vocal-rep "six")
(seven isa number number seven next eight vocal-rep "seven")
(eight isa number number eight next nine vocal-rep "eight")
(nine isa number number nine next ten vocal-rep "nine")
(ten isa number number ten next eleven vocal-rep "ten")
(eleven isa number number eleven)
(goal isa count step start)
(start))
(goal-focus goal)
)
| 1,030 | Common Lisp | .lisp | 24 | 36.75 | 68 | 0.678357 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 18609ff7a26d93ad6331ef4d7e73b311862ef14954ea654c8cdf2935cdca9952 | 14,232 | [
-1
] |
14,233 | sperling-model.lisp | asmaloney_ACT-R/tutorial/unit3/sperling-model.lisp | (clear-all)
(define-model sperling
(sgp :v t :declarative-finst-span 10)
(sgp :show-focus t :trace-detail low)
(sgp :seed (100 0))
(chunk-type read-letters location tone step upper-y lower-y)
(chunk-type report-row row)
(add-dm
(attending isa chunk)
(medium isa chunk)
(find isa chunk)
(encode isa chunk)
(goal isa read-letters step attending upper-y 400 lower-y 600))
(p detected-sound
=aural-location>
?aural>
state free
==>
+aural>
event =aural-location)
(p sound-respond-low
=goal>
isa read-letters
tone nil
=aural>
isa sound
content 500
==>
=goal>
tone low
upper-y 500
lower-y 520)
(p sound-respond-medium
=goal>
isa read-letters
tone nil
=aural>
isa sound
content 1000
==>
=goal>
tone medium
upper-y 450
lower-y 470)
(p sound-respond-high
=goal>
isa read-letters
tone nil
=aural>
isa sound
content 2000
==>
=goal>
tone high
upper-y 400
lower-y 420)
(p attend-low
=goal>
isa read-letters
step attending
=visual-location>
isa visual-location
> screen-y 500
< screen-y 520
?visual>
state free
==>
=goal>
location low
step encode
+visual>
cmd move-attention
screen-pos =visual-location)
(p attend-medium
=goal>
isa read-letters
step attending
=visual-location>
isa visual-location
> screen-y 450
< screen-y 470
?visual>
state free
==>
=goal>
location medium
step encode
+visual>
cmd move-attention
screen-pos =visual-location)
(p attend-high
=goal>
isa read-letters
step attending
=visual-location>
isa visual-location
> screen-y 400
< screen-y 420
?visual>
state free
==>
=goal>
location high
step encode
+visual>
cmd move-attention
screen-pos =visual-location)
(p encode-row-and-find
=goal>
isa read-letters
location =pos
upper-y =uy
lower-y =ly
=visual>
==>
=visual>
status =pos
-visual>
=goal>
location nil
step attending
+visual-location>
:attended nil
> screen-y =uy
< screen-y =ly)
(P start-report
=goal>
isa read-letters
tone =tone
?visual>
state free
==>
+goal>
isa report-row
row =tone
+retrieval>
status =tone)
(P do-report
=goal>
isa report-row
row =tone
=retrieval>
status =tone
value =val
?manual>
state free
==>
+manual>
cmd press-key
key =val
+retrieval>
status =tone
:recently-retrieved nil)
(p stop-report
=goal>
isa report-row
row =row
?retrieval>
buffer failure
?manual>
state free
==>
+manual>
cmd press-key
key space
-goal>)
(goal-focus goal)
(spp start-report :u -2)
(spp detected-sound :u 10)
(spp sound-respond-low :u 10)
(spp sound-respond-medium :u 10)
(spp sound-respond-high :u 10)
)
| 3,344 | Common Lisp | .lisp | 173 | 14.635838 | 64 | 0.563555 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0b56b0113409041eab24b86be779ece32d4bc244b8e308189e245a5c100b8772 | 14,233 | [
-1
] |
14,234 | perceptual-motor-issues-model.lisp | asmaloney_ACT-R/tutorial/unit3/perceptual-motor-issues-model.lisp | (clear-all)
(define-model perceptual-motor-issues
(sgp :seed (101 0))
(sgp :v t :show-focus t :trace-detail medium :er t)
(chunk-type letter name next previous)
(chunk-type task letter)
(add-dm
(a isa letter name "a" next "b" previous "z")
(b isa letter name "b" next "c" previous "a")
(c isa letter name "c" next "d" previous "b")
(d isa letter name "d" next "e" previous "c")
(e isa letter name "e" next "f" previous "d")
(f isa letter name "f" next "g" previous "e")
(g isa letter name "g" next "h" previous "f")
(h isa letter name "h" next "i" previous "g")
(i isa letter name "i" next "j" previous "h")
(j isa letter name "j" next "k" previous "i")
(k isa letter name "k" next "l" previous "j")
(l isa letter name "l" next "m" previous "k")
(m isa letter name "m" next "n" previous "l")
(n isa letter name "n" next "o" previous "m")
(o isa letter name "o" next "p" previous "n")
(p isa letter name "p" next "q" previous "o")
(q isa letter name "q" next "r" previous "p")
(r isa letter name "r" next "s" previous "q")
(s isa letter name "s" next "t" previous "r")
(t isa letter name "t" next "u" previous "s")
(u isa letter name "u" next "v" previous "t")
(v isa letter name "v" next "w" previous "u")
(w isa letter name "w" next "x" previous "v")
(x isa letter name "x" next "y" previous "w")
(y isa letter name "y" next "z" previous "x")
(z isa letter name "z" next "a" previous "y"))
(add-dm
(start isa chunk) (attend isa chunk)
(respond isa chunk) (done isa chunk))
(p find-letter
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
+imaginal>
)
(p encode-letter
=imaginal>
isa task
letter nil
=visual>
isa visual-object
value =letter
==>
=imaginal>
letter =letter
)
(p respond-next
=imaginal>
isa task
letter =letter
=visual>
isa visual-object
value "next"
?manual>
state busy
==>
+retrieval>
isa letter
previous =letter
+manual>
cmd press-key
key =letter
)
(p respond-previous
=imaginal>
isa task
letter =letter
=visual>
isa text
value "previous"
?manual>
state free
==>
+retrieval>
isa letter
next =letter
+manual>
cmd press-key
key =letter
)
(p respond-final
=retrieval>
isa letter
name =letter
==>
+manual>
cmd press-key
key =letter
))
| 2,770 | Common Lisp | .lisp | 100 | 22.97 | 56 | 0.560045 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 28e7c1d0ec4f3ef83f3518c5a5d6aa94b474ffa2a275e94750058d0028ab407d | 14,234 | [
-1
] |
14,235 | demo2-model.lisp | asmaloney_ACT-R/tutorial/unit2/demo2-model.lisp |
(clear-all)
(define-model demo2
(sgp :seed (123456 0))
(sgp :v t :show-focus t :trace-detail high)
(chunk-type read-letters step)
(chunk-type array letter)
(add-dm
(start isa chunk) (attend isa chunk)
(respond isa chunk) (done isa chunk)
(goal isa read-letters step start))
(P find-unattended-letter
=goal>
ISA read-letters
step start
==>
+visual-location>
:attended nil
=goal>
step find-location
)
(P attend-letter
=goal>
ISA read-letters
step find-location
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
step attend
)
(P encode-letter
=goal>
ISA read-letters
step attend
=visual>
value =letter
?imaginal>
state free
==>
=goal>
step respond
+imaginal>
isa array
letter =letter
)
(P respond
=goal>
ISA read-letters
step respond
=imaginal>
isa array
letter =letter
?manual>
state free
==>
=goal>
step done
+manual>
cmd press-key
key =letter
)
(goal-focus goal)
)
| 1,313 | Common Lisp | .lisp | 67 | 15.208955 | 43 | 0.548335 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6ae0fef8eecc5b3bebbdf28216f68dc401053309c9b03e0d2d83a4c98e12d7cc | 14,235 | [
-1
] |
14,236 | unit2-assignment-model.lisp | asmaloney_ACT-R/tutorial/unit2/unit2-assignment-model.lisp | (clear-all)
(define-model unit2
(sgp :v t :show-focus t)
(chunk-type read-letters step)
(chunk-type array letter1 letter2 letter3)
(add-dm
(start isa chunk)
(goal isa read-letters step start))
(goal-focus goal)
)
| 228 | Common Lisp | .lisp | 10 | 20.3 | 42 | 0.757282 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 22f98f0a31e79ceb98a3433c34835032579c00112b8bc90302e1b2926eda66a6 | 14,236 | [
-1
] |
14,237 | bst-model.lisp | asmaloney_ACT-R/tutorial/unit6/bst-model.lisp |
(clear-all)
(define-model bst
(sgp :v nil :esc t :egs 3 :show-focus t :ul t :ult t :needs-mouse t)
(chunk-type try-strategy strategy state)
(chunk-type encoding a-loc b-loc c-loc goal-loc length over under)
(define-chunks
(goal isa try-strategy state start)
(start) (find-line) (looking) (attending)
(encode-under) (encode-over) (choose-strategy)
(calculate-difference) (consider-next) (check-for-done)
(read-done) (evaluate-c) (prepare-mouse) (evaluate-a)
(over) (under) (move-mouse) (wait-for-click))
(p start-trial
=goal>
isa try-strategy
state start
?visual-location>
buffer unrequested
==>
=goal>
state find-line)
(p find-next-line
=goal>
isa try-strategy
state find-line
==>
+visual-location>
isa visual-location
:attended nil
kind line
screen-y lowest
=goal>
state looking)
(p attend-line
=goal>
isa try-strategy
state looking
=visual-location>
?visual>
state free
==>
=goal>
state attending
+visual>
isa move-attention
screen-pos =visual-location)
(p encode-line-a
=goal>
isa try-strategy
state attending
=visual>
isa line
screen-pos =pos
?imaginal>
buffer empty
state free
==>
+imaginal>
isa encoding
a-loc =pos
=goal>
state find-line)
(p encode-line-b
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
a-loc =a
b-loc nil
=visual>
isa line
screen-pos =pos
==>
=imaginal>
b-loc =pos
=goal>
state find-line)
(p encode-line-c
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
b-loc =b
c-loc nil
=visual>
isa line
screen-pos =pos
==>
=imaginal>
c-loc =pos
=goal>
state find-line)
(p encode-line-goal
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
c-loc =c
goal-loc nil
=visual>
isa line
screen-pos =pos
width =length
?visual>
state free
==>
=imaginal>
goal-loc =pos
length =length
=goal>
state encode-under
+visual>
isa move-attention
screen-pos =c)
(p encode-under
=goal>
isa try-strategy
state encode-under
=imaginal>
isa encoding
b-loc =b
length =goal-len
=visual>
isa line
width =c-len
?visual>
state free
==>
!bind! =val (- =goal-len =c-len)
=imaginal>
under =val
=goal>
state encode-over
+visual>
isa move-attention
screen-pos =b)
(p encode-over
=goal>
isa try-strategy
state encode-over
=imaginal>
isa encoding
length =goal-len
=visual>
isa line
width =b-len
==>
!bind! =val (- =b-len =goal-len)
=imaginal>
over =val
=goal>
state choose-strategy)
(p encode-line-current
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
goal-loc =goal-loc
=visual>
isa line
width =current-len
?visual>
state free
==>
=imaginal>
length =current-len
=goal>
state calculate-difference
+visual>
isa move-attention
screen-pos =goal-loc)
(p calculate-difference
=goal>
isa try-strategy
state calculate-difference
=imaginal>
isa encoding
length =current-len
=visual>
isa line
width =goal-len
==>
!bind! =val (abs (- =current-len =goal-len))
=imaginal>
length =val
=goal>
state consider-next)
(p check-for-done
=goal>
isa try-strategy
state consider-next
=imaginal>
isa encoding
length 0
==>
=goal>
state check-for-done
+visual-location>
isa visual-location
value "done")
(p find-done
=goal>
isa try-strategy
state check-for-done
=visual-location>
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
=goal>
state read-done)
(p read-done
=goal>
isa try-strategy
state read-done
=visual>
isa text
value "done"
==>
+goal>
isa try-strategy
state start)
(p consider-c
=goal>
isa try-strategy
state consider-next
=imaginal>
isa encoding
c-loc =c-loc
> length 0
?visual>
state free
==>
=imaginal>
=goal>
state evaluate-c
+visual>
isa move-attention
screen-pos =c-loc)
(p choose-c
=goal>
isa try-strategy
state evaluate-c
=imaginal>
isa encoding
length =difference
=visual>
isa line
<= width =difference
==>
=imaginal>
=goal>
state prepare-mouse
+visual-location>
isa visual-location
kind oval
value "c")
(p consider-a
=goal>
isa try-strategy
state evaluate-c
=imaginal>
isa encoding
a-loc =a-loc
length =difference
=visual>
isa line
> width =difference
?visual>
state free
==>
=imaginal>
=goal>
state evaluate-a
+visual>
isa move-attention
screen-pos =a-loc)
(p choose-a
=goal>
isa try-strategy
state evaluate-a
=imaginal>
isa encoding
length =difference
=visual>
isa line
<= width =difference
==>
=imaginal>
=goal>
state prepare-mouse
+visual-location>
isa visual-location
kind oval
value "a")
(p reset
=goal>
isa try-strategy
state evaluate-a
=imaginal>
isa encoding
length =difference
=visual>
isa line
> width =difference
==>
=imaginal>
=goal>
state prepare-mouse
+visual-location>
isa visual-location
kind oval
value "reset")
(p decide-over
=goal>
isa try-strategy
state choose-strategy
strategy nil
=imaginal>
isa encoding
under =under
over =over
!eval! (< =over (- =under 25))
==>
=imaginal>
=goal>
state prepare-mouse
strategy over
+visual-location>
isa visual-location
kind oval
value "b")
(p force-over
=goal>
isa try-strategy
state choose-strategy
- strategy over
==>
=goal>
state prepare-mouse
strategy over
+visual-location>
isa visual-location
kind oval
value "b")
(p decide-under
=goal>
isa try-strategy
state choose-strategy
strategy nil
=imaginal>
isa encoding
over =over
under =under
!eval! (< =under (- =over 25))
==>
=imaginal>
=goal>
state prepare-mouse
strategy under
+visual-location>
isa visual-location
kind oval
value "c")
(p force-under
=goal>
isa try-strategy
state choose-strategy
- strategy under
==>
=goal>
state prepare-mouse
strategy under
+visual-location>
isa visual-location
kind oval
value "c")
(p move-mouse
=goal>
isa try-strategy
state prepare-mouse
=visual-location>
?visual>
state free
?manual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
=goal>
state move-mouse
+manual>
isa move-cursor
loc =visual-location)
(p click-mouse
=goal>
isa try-strategy
state move-mouse
?manual>
state free
==>
=goal>
state wait-for-click
+manual>
isa click-mouse)
(p look-for-current
=goal>
isa try-strategy
state wait-for-click
?manual>
state free
=visual>
- value "reset"
==>
+visual-location>
isa visual-location
kind line
screen-y highest
=goal>
state looking)
(p pick-another-strategy
=goal>
isa try-strategy
state wait-for-click
?manual>
state free
=visual>
value "reset"
==>
=goal>
state choose-strategy)
(goal-focus goal)
(spp decide-over :u 13)
(spp decide-under :u 13)
(spp force-over :u 10)
(spp force-under :u 10)
(spp pick-another-strategy :reward 0)
(spp read-done :reward 20))
| 9,239 | Common Lisp | .lisp | 445 | 15.465169 | 68 | 0.533067 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 90179eec70c02deb6e6529d573147375e4b4106aae5bf7673e8543b42a34732e | 14,237 | [
-1
] |
14,238 | production-compilation-issues-model.lisp | asmaloney_ACT-R/tutorial/unit7/production-compilation-issues-model.lisp | (clear-all)
(define-model compilation-test
(sgp :esc t :lf .5 :bll .5 :mp 18 :rt -3 :ans .25)
(sgp :style-warnings nil)
(sgp :v nil)
(chunk-type task state)
(chunk-type number visual-rep)
(chunk-type response key (is-response t))
(chunk-type trial num1 num2 result response)
(define-chunks (win isa chunk)
(draw isa chunk)
(lose isa chunk)
(attend-num-1 isa chunk)
(encode-num-1 isa chunk)
(find-num-2 isa chunk)
(attend-num-2 isa chunk)
(encode-num-2 isa chunk)
(num2 isa chunk)
(retrieve-past-trial isa chunk)
(process-past-trial isa chunk)
(respond isa chunk)
(guess-other isa chunk)
(detect-feedback isa chunk)
(encode-feedback isa chunk))
(add-dm (zero isa number visual-rep "0")
(one isa number visual-rep "1")
(two isa number visual-rep "2")
(three isa number visual-rep "3"))
(add-dm (response-1 isa response key "s")
(response-2 isa response key "d")
(response-3 isa response key "f"))
(set-similarities (win draw -.2) (win lose -.15)
(zero one -.1) (one two -.1) (two three -.1)
(zero two -.2) (one three -.2)
(zero three -.3))
(set-all-base-levels 1000 -100)
(goal-focus-fct (car (define-chunks (isa task))))
(p detect-trial-start
=goal>
isa task
state nil
=visual-location>
isa visual-location
?visual>
state free
?imaginal>
state free
==>
=goal>
state attend-num-1
+imaginal>
isa trial
+visual>
cmd move-attention
screen-pos =visual-location)
(p attend-num-1
=goal>
isa task
state attend-num-1
=visual>
isa visual-object
value =val
==>
=goal>
state encode-num-1
+retrieval>
isa number
visual-rep =val)
(p encode-num-1
=goal>
isa task
state encode-num-1
=retrieval>
isa number
=imaginal>
isa trial
==>
=imaginal>
num1 =retrieval
=goal>
state find-num-2
+visual-location>
isa visual-location
> screen-x current
:attended nil)
(p find-num-2
=goal>
isa task
state find-num-2
=visual-location>
isa visual-location
?visual>
state free
==>
=goal>
state attend-num-2
+visual>
cmd move-attention
screen-pos =visual-location)
(p attend-num-2
=goal>
isa task
state attend-num-2
=visual>
isa visual-object
value =val
==>
=goal>
state encode-num-2
+retrieval>
isa number
visual-rep =val)
(p encode-num-2
=goal>
isa task
state encode-num-2
=retrieval>
isa number
=imaginal>
isa trial
==>
=imaginal>
num2 =retrieval
=goal>
state retrieve-past-trial)
(p retrieve-past-trial
=goal>
isa task
state retrieve-past-trial
=imaginal>
isa trial
num1 =n1
num2 =n2
==>
=imaginal>
+retrieval>
isa trial
num1 =n1
num2 =n2
result win
=goal>
state process-past-trial)
(p no-past-trial
=goal>
isa task
state process-past-trial
?retrieval>
buffer failure
==>
+retrieval>
isa response
=goal>
state respond)
(p retrieved-a-win
=goal>
isa task
state process-past-trial
=retrieval>
isa trial
result win
response =response
==>
+retrieval> =response
=goal>
state respond)
(p retrieved-a-non-win
=goal>
isa task
state process-past-trial
=retrieval>
isa trial
- result win
response =response
==>
+retrieval> =response
=goal>
state guess-other)
(p guess-other
=goal>
isa task
state guess-other
=retrieval>
isa response
key =key
==>
+retrieval>
isa response
- key =key
=goal>
state respond)
(p respond
=goal>
isa task
state respond
=retrieval>
isa response
key =key
?manual>
state free
=imaginal>
isa trial
==>
=imaginal>
response =retrieval
+manual>
cmd press-key
key =key
=goal>
state detect-feedback)
(p respond-when-response-failure
=goal>
isa task
state respond
?retrieval>
buffer failure
?manual>
state free
=imaginal>
isa trial
==>
=imaginal>
response response-2
+manual>
cmd press-key
key "d"
=goal>
state detect-feedback)
(p detect-feedback
=goal>
isa task
state detect-feedback
=visual-location>
isa visual-location
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
state encode-feedback)
(p encode-feedback-win
=goal>
isa task
state encode-feedback
=imaginal>
isa trial
=visual>
isa visual-object
value "win"
?manual>
state free
==>
=imaginal>
result win
+manual>
cmd press-key
key space
+goal>
isa task)
(p encode-feedback-lose
=goal>
isa task
state encode-feedback
=imaginal>
isa trial
=visual>
isa visual-object
value "lose"
?manual>
state free
==>
=imaginal>
result lose
+manual>
cmd press-key
key space
+goal>
isa task)
(p encode-feedback-draw
=goal>
isa task
state encode-feedback
=imaginal>
isa trial
=visual>
isa visual-object
value "draw"
?manual>
state free
==>
=imaginal>
result draw
+manual>
cmd press-key
key space
+goal>
isa task)
)
| 6,194 | Common Lisp | .lisp | 299 | 13.602007 | 65 | 0.551724 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 47f868525b3bc26c5a6229936e60896ae17c29466514c3b47bf265159ff0045d | 14,238 | [
-1
] |
14,239 | utility-learning-issues-model.lisp | asmaloney_ACT-R/tutorial/unit7/utility-learning-issues-model.lisp | (clear-all)
(define-model utility-learning-test
(sgp :seed (100 2))
(sgp :esc t :ul t :egs .5)
(chunk-type choose choice)
(chunk-type response answer)
(define-chunks (initial-goal isa choose) (response isa response)
(a isa chunk) (b isa chunk))
(declare-buffer-usage imaginal response answer)
(p choose-a
=goal>
isa choose
choice nil
==>
=goal>
choice a)
(p choose-b
=goal>
isa choose
choice nil
==>
=goal>
choice b)
(p response-matches
=goal>
isa choose
choice =choice
=imaginal>
isa response
answer =choice
==>
-goal>)
(p response-doesnt-match
=goal>
isa choose
choice =choice
=imaginal>
isa response
- answer =choice
- answer nil
==>
-goal>)
(p unknown-response
=goal>
isa choose
choice =choice
=imaginal>
isa response
answer nil
==>
-goal>)
(spp response-matches :reward 4)
(spp response-doesnt-match :reward 0)
(schedule-event 0 "utility-learning-issues-choose" :output 'medium))
| 1,182 | Common Lisp | .lisp | 54 | 15.388889 | 70 | 0.596475 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 459373209362c8f7b3927d73dcad6c0158f012347b58e77d6b9f89bde0cb6e82 | 14,239 | [
104249
] |
14,240 | paired-learning-model.lisp | asmaloney_ACT-R/tutorial/unit7/paired-learning-model.lisp | (clear-all)
(define-model paired-learning
(sgp :esc t :v nil :pct t :ul t :epl t :rt -1.7 :lf 0.2 :ans 0.4 :egs 0.1 :bll 0.5 :trace-detail low :iu 5 :alpha 0.2 :ncnar nil)
(chunk-type operator pre action arg1 arg2 post)
(chunk-type task state step)
(chunk-type args arg1 arg2)
(define-chunks ready start stimulus-read create read recalled
fill filled associate wait respond test-arg2 response
type new-trial complete-task retrieving-operator attending retrieving-response)
(add-dm
(goal isa task state start step ready)
(op1 isa operator pre start action read arg1 create post stimulus-read)
(op2 isa operator pre stimulus-read action associate arg1 filled arg2 fill post recalled)
(op3 isa operator pre recalled action test-arg2 arg1 respond arg2 wait)
(op4 isa operator pre respond action type arg2 response post wait)
(op5 isa operator pre wait action read arg2 fill post new-trial)
(op6 isa operator pre new-trial action complete-task post start))
(set-all-base-levels 1000)
(p retrieve-operator
=goal>
isa task
state =state
step ready
==>
+retrieval>
isa operator
pre =state
=goal>
step retrieving-operator)
(p read-arg1
=goal>
isa task
step retrieving-operator
=retrieval>
isa operator
action read
arg1 create
post =state
=visual-location>
?visual>
state free
?imaginal>
state free
==>
+imaginal>
isa args
arg1 fill
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
step attending
state =state)
(p encode-arg1
=goal>
isa task
step attending
=visual>
isa text
value =val
=imaginal>
isa args
arg1 fill
?imaginal>
state free
==>
*imaginal>
arg1 =val
=goal>
step ready)
(p retireve-associate
=goal>
isa task
step retrieving-operator
=imaginal>
isa args
arg1 =stimulus
=retrieval>
isa operator
action associate
arg1 filled
arg2 fill
post =state
?imaginal>
state free
==>
+retrieval>
isa args
arg1 =stimulus
*imaginal>
arg2 fill
=goal>
step retrieving-response
state =state)
(p retrieval-arg2-unsuccessful
=goal>
isa task
step retrieving-response
=imaginal>
isa args
arg2 fill
?retrieval>
state error
?imaginal>
state free
==>
*imaginal>
arg2 nil
=goal>
step ready)
(p retrieval-arg2-successful
=goal>
isa task
step retrieving-response
=imaginal>
isa args
arg2 fill
=retrieval>
isa args
arg2 =val
?imaginal>
state free
==>
*imaginal>
arg2 =val
=goal>
step ready)
(p respond-to-retrieval-failure
=goal>
isa task
step retrieving-operator
=imaginal>
isa args
arg2 nil
=retrieval>
isa operator
action test-arg2
arg2 =state
?imaginal>
state free
==>
=imaginal>
=goal>
state =state
step ready)
(p respond-to-retrieval-success
=goal>
isa task
step retrieving-operator
=imaginal>
isa args
arg2 =val
=retrieval>
isa operator
action test-arg2
arg1 =state
?imaginal>
state free
==>
=imaginal>
=goal>
state =state
step ready)
(p type-arg2
=goal>
isa task
step retrieving-operator
=imaginal>
isa args
arg2 =val
=retrieval>
isa operator
action type
arg2 response
post =state
?imaginal>
state free
?manual>
state free
==>
=imaginal>
+manual>
cmd press-key
key =val
=goal>
state =state
step ready)
(p read-arg2
=goal>
isa task
step retrieving-operator
=imaginal>
=retrieval>
isa operator
action read
arg2 fill
post =state
=visual-location>
?visual>
state free
?imaginal>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
*imaginal>
arg2 fill
=goal>
step attending
state =state)
(p encode-arg2
=goal>
isa task
step attending
=imaginal>
isa args
arg2 fill
=visual>
isa text
value =val
?imaginal>
state free
==>
*imaginal>
arg2 =val
=goal>
step ready)
(p complete-task
=goal>
isa task
step retrieving-operator
=retrieval>
isa operator
action complete-task
post =state
==>
+goal>
isa task
state =state
step ready)
(spp complete-task :reward 20)
(goal-focus goal)
)
| 5,013 | Common Lisp | .lisp | 244 | 15.75 | 129 | 0.591695 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6678dc399608d09736c727bb6aa5a91afc05296172e8bce8b2120e3d30cf5eaf | 14,240 | [
72284
] |
14,241 | past-tense-model.lisp | asmaloney_ACT-R/tutorial/unit7/past-tense-model.lisp | (clear-all)
(define-model past-tense
(sgp
:V t
:esc T
:ul t
:OL 6
:BLL 0.5
:ANs 0.1
:EGs 0.2
:mas 3.5
:LF 0.5
:RT 0.5
:epl t
:alpha 0.1
:pct t
:iu 5
:ncnar nil
:do-not-harvest imaginal)
(chunk-type past-tense verb stem suffix)
(chunk-type goal state)
(define-chunks
(starting-goal isa goal state start)
(start isa chunk) (blank isa chunk) (done isa chunk))
(declare-buffer-usage goal goal state)
(declare-buffer-usage imaginal past-tense :all)
;;; When there is a stem and no suffix we have an irregular
(p past-tense-irregular
=goal>
isa goal
state done
=imaginal>
isa past-tense
verb =word
stem =past
suffix blank
==>
=goal>
state nil)
(spp past-tense-irregular :reward 5)
;;; When the stem matches the verb and the suffix is not "blank" consider it regular
(p past-tense-regular
=goal>
isa goal
state done
=imaginal>
isa past-tense
verb =stem
stem =stem
suffix =suffix
!safe-eval! (not (eq =suffix 'blank))
==>
=goal>
state nil)
(spp past-tense-regular :reward 4.2)
;;; when there's no stem and no suffix that's a "give up" result
(p no-past-tense-formed
=goal>
isa goal
state done
=imaginal>
isa past-tense
stem nil
suffix nil
==>
=goal>
state nil)
(spp no-past-tense-formed :reward 3.9)
)
| 1,596 | Common Lisp | .lisp | 69 | 16.84058 | 85 | 0.572575 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | bac02db06bb2fef51076f49a768a3c424c5e1eee1246be20f1ecdbfcfedf8766 | 14,241 | [
-1
] |
14,242 | zbrodoff-model.lisp | asmaloney_ACT-R/tutorial/unit4/zbrodoff-model.lisp |
(clear-all)
(define-model zbrodoff
(sgp :v nil :esc t :lf 0.4 :bll 0.5 :ans 0.5 :rt 0 :ncnar nil)
(sgp :show-focus t)
(chunk-type problem arg1 arg2 result)
(chunk-type goal state count target next-let next-num)
(chunk-type number number next visual-rep vocal-rep)
(chunk-type letter letter next visual-rep vocal-rep)
(add-dm
(zero ISA number number zero next one visual-rep "0" vocal-rep "zero")
(one ISA number number one next two visual-rep "1" vocal-rep "one")
(two ISA number number two next three visual-rep "2" vocal-rep "two")
(three ISA number number three next four visual-rep "3" vocal-rep "three")
(four ISA number number four next five visual-rep "4" vocal-rep "four")
(five isa number number five)
(a ISA letter letter a next b visual-rep "a" vocal-rep "a")
(b ISA letter letter b next c visual-rep "b" vocal-rep "b")
(c ISA letter letter c next d visual-rep "c" vocal-rep "c")
(d ISA letter letter d next e visual-rep "d" vocal-rep "d")
(e ISA letter letter e next f visual-rep "e" vocal-rep "e")
(f ISA letter letter f next g visual-rep "f" vocal-rep "f")
(g ISA letter letter g next h visual-rep "g" vocal-rep "g")
(h ISA letter letter h next i visual-rep "h" vocal-rep "h")
(i ISA letter letter i next j visual-rep "i" vocal-rep "i")
(j ISA letter letter j next k visual-rep "j" vocal-rep "j")
(k isa letter letter k next l visual-rep "k" vocal-rep "k")
(l isa letter letter l)
(goal isa goal)
(attending) (read) (count) (counting) (encode))
(set-visloc-default screen-x lowest)
(P attend
=goal>
ISA goal
state nil
=visual-location>
?visual>
state free
==>
=goal>
state attending
+visual>
cmd move-attention
screen-pos =visual-location
)
(P read-first
=goal>
ISA goal
state attending
=visual>
ISA visual-object
value =char
?imaginal>
buffer empty
state free
==>
+imaginal>
+retrieval>
isa letter
visual-rep =char
=goal>
state nil
+visual-location>
ISA visual-location
> screen-x current
screen-x lowest
- value "+"
)
(p encode-first
=goal>
isa goal
state attending
=retrieval>
letter =let
vocal-rep =word
=imaginal>
arg1 nil
?vocal>
preparation free
==>
+vocal>
cmd subvocalize
string =word
=imaginal>
arg1 =let
=goal>
state read
)
(P read-second
=goal>
ISA goal
state read
=visual>
ISA visual-object
value =char
=imaginal>
isa problem
- arg1 nil
arg2 nil
==>
=imaginal>
+retrieval>
isa number
visual-rep =char
=goal>
state nil
+visual-location>
ISA visual-location
screen-x highest
)
(p encode-second
=goal>
isa goal
state attending
=retrieval>
number =num
vocal-rep =word
=imaginal>
- arg1 nil
arg2 nil
?vocal>
preparation free
==>
+vocal>
cmd subvocalize
string =word
=imaginal>
arg2 =num
=goal>
state read
)
(P read-third
=goal>
ISA goal
state read
=imaginal>
isa problem
arg1 =arg1
arg2 =arg2
=visual>
ISA visual-object
value =char
?visual>
state free
==>
=imaginal>
+retrieval>
isa letter
visual-rep =char
=goal>
state encode
+visual>
cmd clear
)
(p encode-third
=goal>
isa goal
state encode
target nil
=retrieval>
letter =let
vocal-rep =word
=imaginal>
arg1 =a1
arg2 =a2
?vocal>
preparation free
==>
+vocal>
cmd subvocalize
string =word
=goal>
target =let
state count
=imaginal>
)
(P start-counting
=goal>
ISA goal
state count
=imaginal>
isa problem
arg1 =a
arg2 =val
==>
=imaginal>
result =a
=goal>
state counting
+retrieval>
ISA letter
letter =a
)
(p initialize-counting
=goal>
isa goal
state counting
count nil
=retrieval>
isa letter
letter =l
next =new
vocal-rep =t
?vocal>
state free
==>
+vocal>
isa subvocalize
string =t
=goal>
next-num one
next-let =new
count zero
+retrieval>
isa letter
letter =new
)
(P update-result
=goal>
ISA goal
count =val
next-let =let
next-num =n
=imaginal>
isa problem
- arg2 =val
=retrieval>
ISA letter
letter =let
next =new
vocal-rep =txt
?vocal>
state free
==>
=goal>
next-let =new
+vocal>
cmd subvocalize
string =txt
=imaginal>
result =let
+retrieval>
ISA number
number =n
)
(P update-count
=goal>
ISA goal
next-let =let
next-num =n
=retrieval>
ISA number
number =val
next =new
vocal-rep =txt
?vocal>
preparation free
==>
+vocal>
cmd subvocalize
string =txt
=goal>
count =val
next-num =new
+retrieval>
ISA letter
letter =let
)
(P final-answer-yes
=goal>
ISA goal
target =let
count =val
=imaginal>
isa problem
result =let
arg2 =val
?manual>
state free
==>
+goal>
+manual>
cmd press-key
key "k"
)
(P final-answer-no
=goal>
ISA goal
count =val
- target =let
=imaginal>
isa problem
result =let
arg2 =val
?manual>
state free
==>
+goal>
+manual>
cmd press-key
key "d"
)
(set-all-base-levels 100000 -1000)
(goal-focus goal)
)
| 6,540 | Common Lisp | .lisp | 304 | 16.779605 | 75 | 0.52411 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d3b9f655a5104d2ca1dab7b1b5f08e3f3b0e4120abdf4d2c3dcaf19607ef200b | 14,242 | [
-1
] |
14,243 | paired-model.lisp | asmaloney_ACT-R/tutorial/unit4/paired-model.lisp |
(clear-all)
(define-model paired
(sgp :v t :esc t :rt -2 :lf 0.4 :ans 0.5 :bll 0.5 :act nil :ncnar nil)
(sgp :seed (200 4))
(chunk-type goal state)
(chunk-type pair probe answer)
(add-dm
(start isa chunk) (attending-target isa chunk)
(attending-probe isa chunk)
(testing isa chunk) (read-study-item isa chunk)
(goal isa goal state start))
(p attend-probe
=goal>
isa goal
state start
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
state attending-probe
)
(p read-probe
=goal>
isa goal
state attending-probe
=visual>
isa visual-object
value =val
?imaginal>
state free
==>
+imaginal>
isa pair
probe =val
+retrieval>
isa pair
probe =val
=goal>
state testing
)
(p recall
=goal>
isa goal
state testing
=retrieval>
isa pair
answer =ans
?manual>
state free
?visual>
state free
==>
+manual>
cmd press-key
key =ans
=goal>
state read-study-item
+visual>
cmd clear
)
(p cannot-recall
=goal>
isa goal
state testing
?retrieval>
buffer failure
?visual>
state free
==>
=goal>
state read-study-item
+visual>
cmd clear
)
(p detect-study-item
=goal>
isa goal
state read-study-item
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
state attending-target
)
(p associate
=goal>
isa goal
state attending-target
=visual>
isa visual-object
value =val
=imaginal>
isa pair
probe =probe
?visual>
state free
==>
=imaginal>
answer =val
-imaginal>
=goal>
state start
+visual>
cmd clear
)
(goal-focus goal)
)
| 2,188 | Common Lisp | .lisp | 115 | 13.478261 | 71 | 0.530702 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 7461d200f786d843dd92269cf4ff243a6b11b0b4cad6d377679ee2e9dd91076c | 14,243 | [
205461
] |
14,244 | declarative-issues.lisp | asmaloney_ACT-R/tutorial/unit5/declarative-issues.lisp | (clear-all)
(define-model declarative-issues
;; Set an explicit seed value so that the model performs
;; the same everytime.
(sgp :seed (100 1))
;; Set the ACT-R parameters.
(sgp :esc t :v t :bll .5 :ans .25 :mas 2 :mp 10)
;; Specify the new chunk-types that the model will use.
(chunk-type simple-value result)
(chunk-type simple-fact item attribute)
(chunk-type task-state state)
(chunk-type number visual-rep)
(chunk-type math-fact arg1 arg2 result operator)
(chunk-type context val1 val2 val3 goal)
;; Define chunks for the states used in the goal to avoid the
;; warnings for undefined chunks.
(define-chunks (r2 isa chunk) (r3 isa chunk) (r4 isa chunk)
(r5 isa chunk) (r6 isa chunk) (r7 isa chunk) (r8 isa chunk))
;; Create the initial declarative memory chunks.
(add-dm
(zero isa number visual-rep "0")
(one isa number visual-rep "1")
(two isa number visual-rep "2")
(three isa number visual-rep "3")
(add isa chunk)
(subtract isa chunk)
(sky isa chunk)
(grass isa chunk)
(rose isa chunk)
(1-1 isa math-fact arg1 one arg2 one result zero operator subtract)
(2-1 isa math-fact arg1 two arg2 one result one operator subtract)
(3-2 isa math-fact arg1 three arg2 two result one operator subtract)
(1+1 isa math-fact arg1 one arg2 one result two operator add)
(1+2 isa math-fact arg1 one arg2 two result three operator add)
(v1 isa simple-value result "true")
(v2 isa simple-value result "false")
(v3 isa simple-value result nil)
(f1 isa simple-fact item sky attribute blue)
(f2 isa simple-fact item rose attribute red)
(f3 isa simple-fact item grass attribute green)
(g1 isa task-state state r8)
(old-context isa context val1 one val2 two val3 add goal g1))
;; Set the history of use explicitly for some chunks.
(set-base-levels (v1 1 -1500)
(v2 1 -1500)
(v3 1 -1500))
;; Note that we are using all the slots of the context type
;; in the imaginal buffer to avoid warnings.
(declare-buffer-usage imaginal context :all)
;; The productions which perform the demonstration actions.
(p p1
?goal>
buffer empty
==>
+goal>
isa task-state
state r2
+retrieval>
isa simple-value
- result nil)
(p p2
=goal>
isa task-state
state r2
=retrieval>
==>
=goal>
state r3
+retrieval>
isa simple-value)
(p p3
=goal>
isa task-state
state r3
=retrieval>
isa simple-value
==>
=goal>
state r4
+retrieval>
isa simple-fact
attribute pink)
(p p4
=goal>
isa task-state
state r4
?retrieval>
state free
==>
=goal>
state r5
+retrieval>
isa simple-fact
attribute black)
(p p5
=goal>
isa task-state
state r5
?imaginal>
state free
=retrieval>
==>
=goal>
state r6
+imaginal>
isa context
val1 one
val2 two
+retrieval>
isa math-fact
- arg1 nil
- arg2 nil
- result nil)
(p p6
=goal>
isa task-state
state r6
=imaginal>
isa context
==>
+retrieval>
isa math-fact
- arg1 nil
- arg2 nil
- result nil
=goal>
state r7
=imaginal>
val3 add)
(p p7
=goal>
isa task-state
state r7
=imaginal>
=retrieval>
==>
=goal>
state r8
=imaginal>
goal =goal)
(p p8
=goal>
isa task-state
state r8
==>
+goal>
-imaginal>)
)
| 3,758 | Common Lisp | .lisp | 148 | 19.006757 | 71 | 0.614574 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b7778ce779c082ee9085696e031c810b62db582c2ef9e79262b95cb8fa10d05e | 14,244 | [
461967
] |
14,245 | 1hit-blackjack-model.lisp | asmaloney_ACT-R/tutorial/unit5/1hit-blackjack-model.lisp | (clear-all)
(define-model 1-hit-model
;; do not change these parameters
(sgp :esc t :bll .5 :ol t :sim-hook "1hit-bj-number-sims"
:cache-sim-hook-results t :er t :lf 0)
;; adjust these as needed
(sgp :v nil :ans .2 :mp 10.0 :rt -60)
;; This type holds all the game info
(chunk-type game-state
mc1 mc2 mc3 mstart mtot mresult oc1 oc2 oc3 ostart otot oresult state)
;; This chunk-type should be modified to contain the information needed
;; for your model's learning strategy
(chunk-type learned-info mc1 action)
;; Declare the slots used for the goal buffer since it is
;; not set in the model defintion or by the productions.
;; See the experiment code text for more details.
(declare-buffer-usage goal game-state :all)
;; Create chunks for the items used in the slots for the game
;; information and state
(define-chunks win lose bust retrieving start results)
;; Provide a keyboard for the model's motor module to use
(install-device '("motor" "keyboard"))
(p start
=goal>
isa game-state
state start
MC1 =c
==>
=goal>
state retrieving
+retrieval>
isa learned-info
MC1 =c
- action nil)
(p cant-remember-game
=goal>
isa game-state
state retrieving
?retrieval>
buffer failure
?manual>
state free
==>
=goal>
state nil
+manual>
cmd press-key
key "s")
(p remember-game
=goal>
isa game-state
state retrieving
=retrieval>
isa learned-info
action =act
?manual>
state free
==>
=goal>
state nil
+manual>
cmd press-key
key =act
@retrieval>)
(p results-should-hit
=goal>
isa game-state
state results
mresult =outcome
MC1 =c
?imaginal>
state free
==>
!output! (I =outcome)
=goal>
state nil
+imaginal>
MC1 =c
action "h")
(spp results-should-hit :u 10)
(p results-should-stay
=goal>
isa game-state
state results
mresult =outcome
MC1 =c
?imaginal>
state free
==>
!output! (I =outcome)
=goal>
state nil
+imaginal>
MC1 =c
action "s")
(p clear-new-imaginal-chunk
?imaginal>
state free
buffer full
==>
-imaginal>)
)
| 2,466 | Common Lisp | .lisp | 102 | 17.607843 | 75 | 0.603741 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 23c9555db550d9dc1f06111e5055847713d1bf1ce17099086a9a5728cf23d341 | 14,245 | [
89890
] |
14,246 | siegler-model.lisp | asmaloney_ACT-R/tutorial/unit5/siegler-model.lisp | (clear-all)
(define-model siegler
(sgp :rt -.45 :esc t :v nil :act nil :ans 0.5 :mp 16)
(chunk-type plus-fact addend1 addend2 sum)
(chunk-type number aural-rep vocal-rep)
(add-dm
(zero ISA number aural-rep 0 vocal-rep "zero")
(one ISA number aural-rep 1 vocal-rep "one")
(two ISA number aural-rep 2 vocal-rep "two")
(three ISA number aural-rep 3 vocal-rep "three")
(four ISA number aural-rep 4 vocal-rep "four")
(five ISA number aural-rep 5 vocal-rep "five")
(six ISA number aural-rep 6 vocal-rep "six")
(seven ISA number aural-rep 7 vocal-rep "seven")
(eight ISA number aural-rep 8 vocal-rep "eight")
(nine ISA number aural-rep 9 vocal-rep "nine")
(f00 ISA plus-fact addend1 zero addend2 zero sum zero)
(f01 ISA plus-fact addend1 zero addend2 one sum one)
(f02 ISA plus-fact addend1 zero addend2 two sum two)
(f03 ISA plus-fact addend1 zero addend2 three sum three)
(f04 ISA plus-fact addend1 zero addend2 four sum four)
(f05 ISA plus-fact addend1 zero addend2 five sum five)
(f10 ISA plus-fact addend1 one addend2 zero sum one)
(f11 ISA plus-fact addend1 one addend2 one sum two)
(f12 ISA plus-fact addend1 one addend2 two sum three)
(f13 ISA plus-fact addend1 one addend2 three sum four)
(f14 ISA plus-fact addend1 one addend2 four sum five)
(f15 ISA plus-fact addend1 one addend2 five sum six)
(f20 ISA plus-fact addend1 two addend2 zero sum two)
(f21 ISA plus-fact addend1 two addend2 one sum three)
(f22 ISA plus-fact addend1 two addend2 two sum four)
(f23 ISA plus-fact addend1 two addend2 three sum five)
(f24 ISA plus-fact addend1 two addend2 four sum six)
(f25 ISA plus-fact addend1 two addend2 five sum seven)
(f30 ISA plus-fact addend1 three addend2 zero sum three)
(f31 ISA plus-fact addend1 three addend2 one sum four)
(f32 ISA plus-fact addend1 three addend2 two sum five)
(f33 ISA plus-fact addend1 three addend2 three sum six)
(f34 ISA plus-fact addend1 three addend2 four sum seven)
(f35 ISA plus-fact addend1 three addend2 five sum eight)
(f40 ISA plus-fact addend1 four addend2 zero sum four)
(f41 ISA plus-fact addend1 four addend2 one sum five)
(f42 ISA plus-fact addend1 four addend2 two sum six)
(f43 ISA plus-fact addend1 four addend2 three sum seven)
(f44 ISA plus-fact addend1 four addend2 four sum eight)
(f45 ISA plus-fact addend1 four addend2 five sum nine)
(f50 ISA plus-fact addend1 five addend2 zero sum five)
(f51 ISA plus-fact addend1 five addend2 one sum six)
(f52 ISA plus-fact addend1 five addend2 two sum seven)
(f53 ISA plus-fact addend1 five addend2 three sum eight)
(f54 ISA plus-fact addend1 five addend2 four sum nine))
(p hear-sound
=aural-location>
isa audio-event
location external
?aural>
state free
==>
+aural>
event =aural-location)
(p encode-digit
=aural>
isa sound
content =val
?retrieval>
state free
==>
+retrieval>
isa number
aural-rep =val)
(p harvest-arg1
=retrieval>
?imaginal>
buffer empty
state free
==>
+imaginal>
isa plus-fact
addend1 =retrieval)
(p harvest-arg2
=retrieval>
=imaginal>
isa plus-fact
addend2 nil
?imaginal>
state free
==>
*imaginal>
addend2 =retrieval)
(P retrieve-answer
=imaginal>
ISA plus-fact
addend1 =val1
addend2 =val2
sum nil
?retrieval>
state free
buffer empty
==>
=imaginal>
+retrieval>
ISA plus-fact
addend1 =val1
addend2 =val2)
(P harvest-answer
=retrieval>
ISA plus-fact
sum =number
=imaginal>
isa plus-fact
?imaginal>
state free
==>
*imaginal>
sum =number
+retrieval> =number)
(P respond
=imaginal>
isa plus-fact
sum =result
=retrieval>
ISA number
vocal-rep =name
?vocal>
state free
==>
+vocal>
cmd speak
string =name)
;; The base level activation of the number chunks are
;; set high so that there are no errors in retrieving them -
;; the assumption is that the kids know the numbers and have
;; no errors from hearing or speaking them.
(set-base-levels
(zero 10) (one 10) (two 10) (three 10) (four 10) (five 10)
(six 10) (seven 10) (eight 10) (nine 10))
;; The similarity between the numbers are set with a simple
;; linear distance measure:
;; Mji = -.1 * |val(i) - val(j)|
(Set-similarities
(zero one -0.1) (one two -0.1) (two three -0.1) (three four -0.1) (four five -0.1)
(zero two -0.2)(one three -0.2)(two four -0.2)(three five -0.2)
(zero three -0.3)(one four -0.3) (two five -0.3)
(zero four -0.4)(one five -0.4)
(zero five -0.5))
;; Set the base-levels of the small facts (sum <= 5) slightly
;; above the default of 0.0 because more errors occurred to low side
;; of answer and other research has found that small addition
;; problems occur more frequently.
;; Use the same offset for all of them because the objective is not
;; to try and engineer every detail found in the data.
(set-base-levels
(f00 .65)(f01 .65)(f02 .65)(f03 .65)(f04 .65)
(f10 .65)(f11 .65)(f12 .65)(f13 .65)
(f20 .65)(f21 .65)(f22 .65)
(f30 .65)(f31 .65)
(f40 .65))
)
| 5,383 | Common Lisp | .lisp | 158 | 30.563291 | 84 | 0.672829 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a1772381e0cb087993d840ad1f7919a76889b3298251d507fffebcadbbba1a8b | 14,246 | [
404075
] |
14,247 | fan-no-pm-model.lisp | asmaloney_ACT-R/tutorial/unit5/fan-no-pm-model.lisp | (clear-all)
(define-model fan
(sgp :v t :act nil :esc t :lf .63 :mas 1.6 :ga 1.0)
(sgp :style-warnings nil)
(chunk-type comprehend-sentence relation arg1 arg2)
(chunk-type meaning word)
(add-dm
(p1 ISA comprehend-sentence relation in arg1 hippie arg2 park)
(p2 ISA comprehend-sentence relation in arg1 hippie arg2 church)
(p3 ISA comprehend-sentence relation in arg1 hippie arg2 bank)
(p4 ISA comprehend-sentence relation in arg1 captain arg2 park)
(p5 ISA comprehend-sentence relation in arg1 captain arg2 cave)
(p6 ISA comprehend-sentence relation in arg1 debutante arg2 bank)
(p7 ISA comprehend-sentence relation in arg1 fireman arg2 park)
(p8 ISA comprehend-sentence relation in arg1 giant arg2 beach)
(p9 ISA comprehend-sentence relation in arg1 giant arg2 castle)
(p10 ISA comprehend-sentence relation in arg1 giant arg2 dungeon)
(p11 ISA comprehend-sentence relation in arg1 earl arg2 castle)
(p12 ISA comprehend-sentence relation in arg1 earl arg2 forest)
(p13 ISA comprehend-sentence relation in arg1 lawyer arg2 store)
(guard ISA meaning word "guard")
(beach ISA meaning word "beach")
(castle ISA meaning word "castle")
(dungeon ISA meaning word "dungeon")
(earl ISA meaning word "earl")
(forest ISA meaning word "forest")
(giant ISA meaning word "giant")
(hippie ISA meaning word "hippie")
(park ISA meaning word "park")
(church ISA meaning word "church")
(captain ISA meaning word "captain")
(cave ISA meaning word "cave")
(debutante ISA meaning word "debutante")
(bank ISA meaning word "bank")
(fireman ISA meaning word "fireman")
(lawyer ISA meaning word "lawyer")
(store ISA meaning word "store")
(in ISA meaning word "in"))
(set-base-levels
(guard 10) (beach 10) (castle 10) (dungeon 10) (earl 10)
(forest 10) (hippie 10) (park 10) (church 10) (bank 10)
(captain 10) (cave 10) (giant 10) (debutante 10) (fireman 10)
(lawyer 10) (store 10) (in 10))
(chunk-type sentence-goal arg1 arg2 state)
(define-chunks (test isa chunk) (harvest-person isa chunk)
(harvest-location isa chunk) (get-retrieval isa chunk)
(goal isa sentence-goal state test))
(goal-focus goal)
(P start
=goal>
ISA sentence-goal
arg1 =person
state test
==>
=goal>
state harvest-person
+retrieval>
ISA meaning
word =person)
(P harvest-person
=goal>
ISA sentence-goal
arg2 =location
state harvest-person
=retrieval>
==>
=goal>
arg1 =retrieval
state harvest-location
+retrieval>
ISA meaning
word =location)
(p harvest-location
=goal>
ISA sentence-goal
state harvest-location
=retrieval>
ISA meaning
==>
=goal>
arg2 =retrieval
state get-retrieval)
(P retrieve-from-person
=goal>
ISA sentence-goal
arg1 =person
state get-retrieval
==>
=goal>
state nil
+retrieval>
ISA comprehend-sentence
arg1 =person)
(P retrieve-from-location
=goal>
ISA sentence-goal
arg2 =location
state get-retrieval
==>
=goal>
state nil
+retrieval>
ISA comprehend-sentence
arg2 =location)
(P respond-yes
=goal>
ISA sentence-goal
arg1 =person
arg2 =location
state nil
=retrieval>
ISA comprehend-sentence
arg1 =person
arg2 =location
==>
=goal>
state "k")
(P mismatch-person-no
=goal>
ISA sentence-goal
arg1 =person
arg2 =location
state nil
=retrieval>
ISA comprehend-sentence
- arg1 =person
==>
=goal>
state "d")
(P mismatch-location-no
=goal>
ISA sentence-goal
arg1 =person
arg2 =location
state nil
=retrieval>
ISA comprehend-sentence
- arg2 =location
==>
=goal>
state "d")
(spp mismatch-location-no :at .21)
(spp mismatch-person-no :at .21)
(spp respond-yes :at .21)
(spp start :at .250)
(spp harvest-person :at .285)
)
| 4,608 | Common Lisp | .lisp | 147 | 25.068027 | 68 | 0.590468 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ab8a6d9195e43e84f2e7813124a29d01e76a8cc43f3c80013418453dd7918a7e | 14,247 | [
276152
] |
14,248 | fan-model.lisp | asmaloney_ACT-R/tutorial/unit5/fan-model.lisp | (clear-all)
(define-model fan
(sgp :v t :act nil :esc t :lf .63 :mas 1.6)
(sgp :style-warnings nil)
(chunk-type comprehend-sentence relation arg1 arg2)
(chunk-type meaning word)
(add-dm
(p1 ISA comprehend-sentence relation in arg1 hippie arg2 park)
(p2 ISA comprehend-sentence relation in arg1 hippie arg2 church)
(p3 ISA comprehend-sentence relation in arg1 hippie arg2 bank)
(p4 ISA comprehend-sentence relation in arg1 captain arg2 park)
(p5 ISA comprehend-sentence relation in arg1 captain arg2 cave)
(p6 ISA comprehend-sentence relation in arg1 debutante arg2 bank)
(p7 ISA comprehend-sentence relation in arg1 fireman arg2 park)
(p8 ISA comprehend-sentence relation in arg1 giant arg2 beach)
(p9 ISA comprehend-sentence relation in arg1 giant arg2 castle)
(p10 ISA comprehend-sentence relation in arg1 giant arg2 dungeon)
(p11 ISA comprehend-sentence relation in arg1 earl arg2 castle)
(p12 ISA comprehend-sentence relation in arg1 earl arg2 forest)
(p13 ISA comprehend-sentence relation in arg1 lawyer arg2 store)
(guard ISA meaning word "guard")
(beach ISA meaning word "beach")
(castle ISA meaning word "castle")
(dungeon ISA meaning word "dungeon")
(earl ISA meaning word "earl")
(forest ISA meaning word "forest")
(giant ISA meaning word "giant")
(hippie ISA meaning word "hippie")
(park ISA meaning word "park")
(church ISA meaning word "church")
(captain ISA meaning word "captain")
(cave ISA meaning word "cave")
(debutante ISA meaning word "debutante")
(bank ISA meaning word "bank")
(fireman ISA meaning word "fireman")
(lawyer ISA meaning word "lawyer")
(store ISA meaning word "store")
(in ISA meaning word "in"))
(set-base-levels
(guard 10) (beach 10) (castle 10) (dungeon 10) (earl 10)
(forest 10) (hippie 10) (park 10) (church 10) (bank 10)
(captain 10) (cave 10) (giant 10) (debutante 10) (fireman 10)
(lawyer 10) (store 10) (in 10))
(P find-person
?visual-location>
buffer unrequested
?imaginal>
state free
==>
+imaginal>
+visual-location>
ISA visual-location
screen-x lowest)
(P attend-visual-location
=visual-location>
?visual-location>
buffer requested
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location)
(P retrieve-meaning
=visual>
ISA visual-object
value =word
==>
+retrieval>
ISA meaning
word =word)
(P encode-person
=retrieval>
=imaginal>
ISA comprehend-sentence
arg1 nil
==>
=imaginal>
arg1 =retrieval
+visual-location>
ISA visual-location
screen-x highest)
(P encode-location
=retrieval>
=imaginal>
ISA comprehend-sentence
arg1 =arg
arg2 nil
==>
=imaginal>
arg2 =retrieval)
(P retrieve-from-person
=imaginal>
ISA comprehend-sentence
arg1 =person
arg2 =location
?retrieval>
state free
buffer empty
==>
=imaginal>
+retrieval>
ISA comprehend-sentence
arg1 =person)
(P retrieve-from-location
=imaginal>
ISA comprehend-sentence
arg1 =person
arg2 =location
?retrieval>
state free
buffer empty
==>
=imaginal>
+retrieval>
ISA comprehend-sentence
arg2 =location)
(P yes
=imaginal>
ISA comprehend-sentence
arg1 =person
arg2 =location
=retrieval>
ISA comprehend-sentence
arg1 =person
arg2 =location
?manual>
state free
==>
+manual>
cmd press-key
key "k")
(P mismatch-person
=imaginal>
ISA comprehend-sentence
arg1 =person
arg2 =location
=retrieval>
ISA comprehend-sentence
- arg1 =person
?manual>
state free
==>
+manual>
ISA press-key
key "d")
(P mismatch-location
=imaginal>
ISA comprehend-sentence
arg1 =person
arg2 =location
=retrieval>
ISA comprehend-sentence
- arg2 =location
?manual>
state free
==>
+manual>
cmd press-key
key "d"))
| 4,810 | Common Lisp | .lisp | 160 | 23.3875 | 68 | 0.575764 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ade08a4b797acb59d799e840f3d06d06f90faa5a87fbb683ec5f832371ce2726 | 14,248 | [
372805
] |
14,249 | grouped-model.lisp | asmaloney_ACT-R/tutorial/unit5/grouped-model.lisp | (clear-all)
(define-model grouped
(sgp :rt -.5 :ans .15 :esc t :mp 1.0 :v t :act nil
:declarative-num-finsts 15
:declarative-finst-span 20
:trace-detail low)
(sgp :seed (77093543977 39813))
(chunk-type recall-list group element list group-position)
(chunk-type group id parent position)
(chunk-type item name group position)
(add-dm
(list ISA chunk)
(first isa chunk) (second isa chunk)
(third isa chunk) (fourth isa chunk)
(group1 ISA group parent list position first id group1)
(group2 ISA group parent list position second id group2)
(group3 ISA group parent list position third id group3)
(item1 ISA item name "1" group group1 position first)
(item2 ISA item name "2" group group1 position second)
(item3 ISA item name "3" group group1 position third)
(item4 ISA item name "4" group group2 position first)
(item5 ISA item name "5" group group2 position second)
(item6 ISA item name "6" group group2 position third)
(item7 ISA item name "7" group group3 position first)
(item8 ISA item name "8" group group3 position second)
(item9 ISA item name "9" group group3 position third)
(goal ISA recall-list list list))
(p recall-first-group
=goal>
isa recall-list
list =list
?retrieval>
buffer empty
state free
- state error
==>
=goal>
group-position first
+retrieval>
isa group
parent =list
position first)
(p start-recall-of-group
=goal>
isa recall-list
list =list
=retrieval>
isa group
id =group
==>
=goal>
group =group
element first
+retrieval>
isa item
group =group
position first
:recently-retrieved nil)
(p harvest-first-item
=goal>
isa recall-list
element first
group =group
=retrieval>
isa item
name =name
==>
=goal>
element second
+retrieval>
isa item
group =group
position second
:recently-retrieved nil
!eval! ("grouped-response" =name))
(p harvest-second-item
=goal>
isa recall-list
element second
group =group
=retrieval>
isa item
name =name
==>
=goal>
element third
+retrieval>
isa item
group =group
position third
:recently-retrieved nil
!eval! ("grouped-response" =name))
(p harvest-third-item
=goal>
isa recall-list
element third
group =group
=retrieval>
isa item
name =name
==>
=goal>
element fourth
+retrieval>
isa item
group =group
position fourth
:recently-retrieved nil
!eval! ("grouped-response" =name))
(p second-group
=goal>
isa recall-list
group-position first
list =list
?retrieval>
state error
==>
=goal>
group-position second
+retrieval>
isa group
parent =list
position second)
(p third-group
=goal>
isa recall-list
group-position second
list =list
?retrieval>
state error
==>
=goal>
group-position third
+retrieval>
isa group
parent =list
position third)
(goal-focus goal)
(set-similarities
(first second -0.5)
(second third -0.5))
)
| 3,423 | Common Lisp | .lisp | 142 | 19.007042 | 59 | 0.615432 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5de0ddab04ec77b3a4891d516b9c6ff57b13b9670744f4c5fc703d3148900bac | 14,249 | [
111057
] |
14,250 | semantic-dynamic-model.lisp | asmaloney_ACT-R/tutorial/unit8/semantic-dynamic-model.lisp | (clear-all)
(define-model semantic
(sgp :esc t :lf .05)
(chunk-type property object category dangerous locomotion edible
breathe moves skin color sings flies height wings)
(chunk-type test-attribute object original attribute value state answer)
(add-dm
(shark) (salmon) (fish) (animal) (canary) (ostrich) (bird)
(dangerous) (locomotion) (category) (edible) (breathe) (moves)
(skin) (color) (sings) (flies) (height) (wings)
(gills) (swimming) (tall) (flying) (true) (false)
(yes) (no) (dont-know)
(attr-check) (record) (create) (done) (check-category)
(p1 ISA property object shark dangerous true)
(p2 ISA property object shark locomotion swimming)
(p3 ISA property object shark category fish)
(p4 ISA property object salmon edible true)
(p5 ISA property object salmon locomotion swimming)
(p6 ISA property object salmon category fish)
(p7 ISA property object fish breathe gills)
(p8 ISA property object fish locomotion swimming)
(p9 ISA property object fish category animal)
(p10 ISA property object animal moves true)
(p11 ISA property object animal skin true)
(p12 ISA property object canary color yellow)
(p13 ISA property object canary sings true)
(p14 ISA property object canary category bird)
(p15 ISA property object ostrich flies false)
(p16 ISA property object ostrich height tall)
(p17 ISA property object ostrich category bird)
(p18 ISA property object bird wings true)
(p19 ISA property object bird locomotion flying)
(p20 ISA property object bird category animal)
(p21 ISA property object bird flies true)
(g1 ISA test-attribute object canary attribute category value bird)
(g2 ISA test-attribute object canary attribute wings value true)
(g3 ISA test-attribute object canary attribute dangerous value true))
(declare-buffer-usage goal test-attribute :all)
(p retrieve-attribute
=goal>
ISA test-attribute
object =obj
attribute =attr
value =val
state nil
==>
=goal>
state attr-check
+retrieval>
ISA property
object =obj
- =attr nil)
(P direct-verify
=goal>
ISA test-attribute
original nil
object =obj
attribute =attr
value =val
state attr-check
=retrieval>
ISA property
object =obj
=attr =val
==>
=goal>
answer yes
state done)
(P indirect-verify
=goal>
ISA test-attribute
original =ori
object =obj
attribute =attr
value =val
state attr-check
=retrieval>
ISA property
object =obj
=attr =val
==>
=goal>
object =ori
answer yes
state record)
(p record-result
=goal>
ISA test-attribute
object =obj
attribute =attr
value =val
state record
?imaginal>
state free
==>
+imaginal>
object =obj
=attr =val
=goal>
answer yes
state create)
(p create
=goal>
isa test-attribute
state create
?imaginal>
state free
buffer full
==>
-imaginal>
=goal>
state done)
(P disprove
=goal>
ISA test-attribute
object =obj
attribute =attr
value =val
state attr-check
=retrieval>
ISA property
object =obj
- =attr =val
==>
=goal>
answer no
state done)
(P missing-attr
=goal>
ISA test-attribute
object =obj
state attr-check
?retrieval>
buffer failure
==>
=goal>
state check-category
+retrieval>
isa property
object =obj
- category nil
)
(P chain-first-category
=goal>
ISA test-attribute
original nil
object =obj
state check-category
=retrieval>
ISA property
object =obj
category =obj2
==>
=goal>
original =obj
object =obj2
state nil)
(P chain-subsequent-category
=goal>
ISA test-attribute
- original nil
object =obj
state check-category
=retrieval>
ISA property
object =obj
category =obj2
==>
=goal>
object =obj2
state nil)
(P failed-to-find-category
=goal>
ISA test-attribute
state check-category
?retrieval>
buffer failure
==>
=goal>
answer dont-know
state done)
(p respond
=goal>
isa test-attribute
state done
object =obj
attribute =attr
value =val
answer =ans
==>
!output! (=obj =attr =val answer is =ans)
-goal>)
)
| 4,893 | Common Lisp | .lisp | 193 | 20.860104 | 72 | 0.603164 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1594baca9e06ecc0a4a0d7b6c66093ef3f60a16e10b0f571521e3b5692dde9fb | 14,250 | [
114820
] |
14,251 | simple-ppm-model.lisp | asmaloney_ACT-R/tutorial/unit8/simple-ppm-model.lisp | (clear-all)
(define-model test-ppm
(sgp :v t :trace-detail high :esc t :ppm nil :egs 0 :cst t)
(add-dm (small isa chunk)
(medium isa chunk)
(large isa chunk))
(chunk-type test value)
(set-similarities (small medium -.5) (medium large -.5))
(set-buffer-chunk 'goal (car (define-chunks (isa test value small))))
(p small
=goal>
isa test
value small
value =val
==>
!output! =val
-goal>)
(p medium
=goal>
isa test
value medium
value =val
==>
!output! =val
-goal>)
(p large
=goal>
isa test
value large
value =val
==>
!output! =val
-goal>))
| 718 | Common Lisp | .lisp | 33 | 15.212121 | 71 | 0.547655 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b3b1d2d86ff243fbf1eebbce7781e46f1e4a9d863d5605fafdfb2b3b64d40b91 | 14,251 | [
166267
] |
14,252 | bst-ppm-model.lisp | asmaloney_ACT-R/tutorial/unit8/bst-ppm-model.lisp | (clear-all)
(define-model bst-learn
(sgp :v nil :esc t :egs 3 :show-focus t :trace-detail medium :ul t :ult t :needs-mouse t)
(sgp :ppm 40 :sim-hook "bst-number-sims")
(sgp :cache-sim-hook-results t)
(chunk-type try-strategy strategy state)
(chunk-type encoding a-loc b-loc c-loc goal-loc length goal-length b-len c-len difference)
(define-chunks start find-line looking attending choose-strategy
consider-next check-for-done read-done evaluate-c prepare-mouse
evaluate-a over under move-mouse wait-for-click)
(add-dm (goal isa try-strategy state start))
(declare-buffer-usage imaginal encoding difference length)
(p start-trial
=goal>
isa try-strategy
state start
?visual-location>
buffer unrequested
==>
=goal>
state find-line)
(p find-next-line
=goal>
isa try-strategy
state find-line
==>
+visual-location>
isa visual-location
:attended nil
kind line
screen-y lowest
=goal>
state looking)
(p attend-line
=goal>
isa try-strategy
state looking
=visual-location>
?visual>
state free
==>
=goal>
state attending
+visual>
cmd move-attention
screen-pos =visual-location)
(p encode-line-a
=goal>
isa try-strategy
state attending
=visual>
isa line
screen-pos =pos
?imaginal>
buffer empty
state free
==>
+imaginal>
isa encoding
a-loc =pos
=goal>
state find-line)
(p encode-line-b
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
a-loc =a
b-loc nil
=visual>
isa line
screen-pos =pos
width =b-len
==>
=imaginal>
b-loc =pos
b-len =b-len
=goal>
state find-line)
(p encode-line-c
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
b-loc =b
c-loc nil
=visual>
isa line
screen-pos =pos
width =c-len
==>
=imaginal>
c-loc =pos
c-len =c-len
=goal>
state find-line)
(p encode-line-goal
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
c-loc =c
goal-loc nil
=visual>
isa line
screen-pos =pos
width =length
?visual>
state free
==>
=imaginal>
goal-loc =pos
goal-length =length
=goal>
state choose-strategy)
(p encode-line-current
=goal>
isa try-strategy
state attending
=imaginal>
isa encoding
goal-loc =goal-loc
=visual>
isa line
width =current-len
?visual>
state free
?imaginal-action>
state free
==>
=imaginal>
length =current-len
+imaginal-action>
action "bst-compute-difference"
simple t
=goal>
state consider-next
+visual>
cmd move-attention
screen-pos =goal-loc)
(p check-for-done
=goal>
isa try-strategy
state consider-next
=imaginal>
isa encoding
> difference -1
< difference 1
?imaginal>
state free
==>
=goal>
state check-for-done
+visual-location>
isa visual-location
value "done")
(p find-done
=goal>
isa try-strategy
state check-for-done
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
state read-done)
(p read-done
=goal>
isa try-strategy
state read-done
=visual>
isa text
value "done"
==>
+goal>
isa try-strategy
state start)
(p consider-c
=goal>
isa try-strategy
state consider-next
=imaginal>
isa encoding
c-loc =c-loc
- difference 0
?imaginal>
state free
?visual>
state free
==>
=imaginal>
=goal>
state evaluate-c
+visual>
cmd move-attention
screen-pos =c-loc)
(p choose-c
=goal>
isa try-strategy
state evaluate-c
=imaginal>
isa encoding
difference =difference
=visual>
isa line
<= width =difference
==>
=imaginal>
=goal>
state prepare-mouse
+visual-location>
isa visual-location
kind oval
value "c")
(p consider-a
=goal>
isa try-strategy
state evaluate-c
=imaginal>
isa encoding
a-loc =a-loc
difference =difference
=visual>
isa line
> width =difference
?visual>
state free
==>
=imaginal>
=goal>
state evaluate-a
+visual>
cmd move-attention
screen-pos =a-loc)
(p choose-a
=goal>
isa try-strategy
state evaluate-a
=imaginal>
isa encoding
difference =difference
=visual>
isa line
<= width =difference
==>
=imaginal>
=goal>
state prepare-mouse
+visual-location>
isa visual-location
kind oval
value "a")
(p reset
=goal>
isa try-strategy
state evaluate-a
=imaginal>
isa encoding
difference =difference
=visual>
isa line
> width =difference
==>
=imaginal>
=goal>
state prepare-mouse
+visual-location>
isa visual-location
kind oval
value "reset")
(p decide-over
=goal>
isa try-strategy
state choose-strategy
- strategy over
=imaginal>
isa encoding
goal-length =d
b-len =d
==>
=imaginal>
=goal>
state prepare-mouse
strategy over
+visual-location>
isa visual-location
kind oval
value "b")
(p decide-under
=goal>
isa try-strategy
state choose-strategy
- strategy under
=imaginal>
isa encoding
goal-length =d
c-len =d
==>
=imaginal>
=goal>
state prepare-mouse
strategy under
+visual-location>
isa visual-location
kind oval
value "c")
(p move-mouse
=goal>
isa try-strategy
state prepare-mouse
=visual-location>
?visual>
state free
?manual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
=goal>
state move-mouse
+manual>
cmd move-cursor
loc =visual-location)
(p click-mouse
=goal>
isa try-strategy
state move-mouse
?manual>
state free
==>
=goal>
state wait-for-click
+manual>
cmd click-mouse)
(p look-for-current
=goal>
isa try-strategy
state wait-for-click
?manual>
state free
=visual>
- value "reset"
==>
+visual-location>
isa visual-location
kind line
screen-y highest
=goal>
state looking)
(p pick-another-strategy
=goal>
isa try-strategy
state wait-for-click
?manual>
state free
=visual>
value "reset"
==>
=goal>
state choose-strategy)
(goal-focus goal)
(spp decide-over :u 10)
(spp decide-under :u 10)
(spp pick-another-strategy :reward 0)
(spp read-done :reward 20)
)
| 7,920 | Common Lisp | .lisp | 373 | 15.589812 | 91 | 0.536332 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 292c594df4c2ebb6610f98516c242352eb9cb51708e2c6a543a75eabdd7b6cb6 | 14,252 | [
-1
] |
14,253 | simple-dynamic-model.lisp | asmaloney_ACT-R/tutorial/unit8/simple-dynamic-model.lisp | (clear-all)
(define-model dynamic-introduction
(sgp :v t :trace-detail high :cst t :style-warnings nil)
(chunk-type fact context data)
(chunk-type step step destination)
(chunk-type result data1 data2)
(add-dm (first isa chunk) (second isa chunk)
(destination isa chunk) (data2 isa chunk)
(data3 isa chunk) (data isa chunk)
(a isa step step first destination data2)
(b isa step step second destination data3))
(goal-focus-fct (car (define-chunks (isa fact context data data 10))))
(p start
=goal>
isa fact
context =context
=context =x
?imaginal>
state free
buffer empty
==>
=goal>
context destination
+imaginal>
isa result
data1 =x
+retrieval>
isa step
step first)
(p retrieve-first-step
=goal>
isa fact
context =slot
data =x
=imaginal>
isa result
data1 =x
=retrieval>
isa step
=slot =target
step first
==>
=goal>
data 11
=imaginal>
=target =x
+retrieval>
isa step
step second)
(p retrieve-second-step
=goal>
isa fact
context =slot
data =x
=imaginal>
=retrieval>
isa step
=slot =target
step second
==>
=imaginal>
=target =x))
| 1,477 | Common Lisp | .lisp | 62 | 16.790323 | 72 | 0.544932 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c102d545a915abaccb5093a4b134ff9df472c4f6a77eb29f0570b832beb3c0e9 | 14,253 | [
-1
] |
14,254 | paired-dynamic-model.lisp | asmaloney_ACT-R/tutorial/unit8/paired-dynamic-model.lisp | (clear-all)
(define-model paired-learning-dynamic
(sgp :esc t :v t :pct t :ul t :epl t :rt -1.7 :lf 0.2 :ans 0.4 :egs 0.1 :bll 0.5 :trace-detail low :iu 5 :alpha 0.2)
(sgp :do-not-harvest imaginal)
(chunk-type operator pre action arg1 arg2 post label required slot success failure)
(chunk-type task state step context)
(define-chunks (stimulus-read)(read)(start)(recalled)(number)(retrieve)(wait)
(respond)(type)(new-trial)(complete-task)(ready)(retrieving-operator)(process)(retrieving-result))
(add-dm
(op1 isa operator pre start action read label word post stimulus-read)
(op2 isa operator pre stimulus-read action retrieve required word label number post recalled)
(op3 isa operator pre recalled slot number success respond failure wait)
(op4 isa operator pre respond action type required number post wait)
(op5 isa operator pre wait action read label number post new-trial)
(op6 isa operator pre new-trial action complete-task post start))
(set-all-base-levels 1000)
(goal-focus-fct (car (define-chunks (isa task state start step ready))))
(p retrieve-operator
=goal>
isa task
state =state
step ready
==>
+retrieval>
isa operator
pre =state
=goal>
step retrieving-operator
context nil)
(p read-and-create
=goal>
isa task
step retrieving-operator
=retrieval>
isa operator
action read
label =destination
post =state
=visual-location>
?visual>
state free
?imaginal>
buffer empty
state free
==>
+imaginal>
+visual>
isa move-attention
screen-pos =visual-location
=goal>
context =destination
step process
state =state)
(p read
=goal>
isa task
step retrieving-operator
=retrieval>
isa operator
action read
label =destination
post =state
=visual-location>
?visual>
state free
?imaginal>
buffer full
==>
+visual>
isa move-attention
screen-pos =visual-location
=goal>
context =destination
step process
state =state)
(p encode
=goal>
isa task
step process
context =which-slot
=visual>
isa text
value =val
=imaginal>
?imaginal>
state free
==>
*imaginal>
=which-slot =val
=goal>
step ready)
(p retrieve-associate
=goal>
isa task
step retrieving-operator
=imaginal>
=target =stimulus
=retrieval>
isa operator
action retrieve
required =target
label =other
post =state
==>
+retrieval>
=target =stimulus
=goal>
step retrieving-result
context =other
state =state)
(p retrieval-unsuccessful
=goal>
isa task
step retrieving-result
context =dest
=imaginal>
?retrieval>
buffer failure
?imaginal>
state free
==>
*imaginal>
=dest nil
=goal>
step ready)
(p retrieval-successful
=goal>
isa task
step retrieving-result
context =dest
=imaginal>
=retrieval>
=dest =val
?imaginal>
state free
==>
*imaginal>
=dest =val
=goal>
step ready)
(p unsuccessful-test
=goal>
isa task
step retrieving-operator
=imaginal>
=dest nil
=retrieval>
isa operator
slot =dest
failure =state
?imaginal>
state free
==>
=goal>
state =state
step ready)
(p successful-test
=goal>
isa task
step retrieving-operator
=imaginal>
=dest =val
=retrieval>
isa operator
slot =dest
success =state
?imaginal>
state free
==>
=goal>
state =state
step ready)
(p type
=goal>
isa task
step retrieving-operator
=imaginal>
=slot =val
=retrieval>
isa operator
action type
required =slot
post =state
?manual>
state free
==>
+manual>
cmd press-key
key =val
=goal>
state =state
step ready)
(p complete-task
=goal>
isa task
step retrieving-operator
=retrieval>
isa operator
action complete-task
post =state
?imaginal>
state free
==>
-imaginal>
+goal>
isa task
state =state
step ready)
(spp complete-task :reward 20)
)
| 4,699 | Common Lisp | .lisp | 210 | 17.590476 | 116 | 0.586655 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a14563c9366e705ea398c98bcce39f64722a093113e402e33364ef0dd7867b18 | 14,254 | [
-1
] |
14,255 | categorize-model.lisp | asmaloney_ACT-R/tutorial/unit8/categorize-model.lisp | (clear-all)
(define-model categorize
(sgp :v t :act t)
(sgp :esc t :lf .01 :blc 10 :rt -100 :do-not-harvest imaginal)
(sgp :sim-hook "size-similarities" :cache-sim-hook-results t)
(sgp :mp 1 :ppm 1 :egs .25 :ans .25)
(chunk-type goal state name value)
(chunk-type example category)
(add-dm (small isa chunk)
(medium isa chunk)
(large isa chunk)
(unknown isa chunk))
(define-chunks (categorize) (add-attribute))
(call-act-r-command "create-example-memories")
(set-similarities (small medium -.4)
(medium large -.4)
(small large -.8))
(set-buffer-chunk 'imaginal '(category unknown))
;; Declare the goal buffer chunk-type usage which is going to be set from
;; outside of the model.
(declare-buffer-usage goal goal :all)
)
| 856 | Common Lisp | .lisp | 22 | 31.772727 | 75 | 0.646617 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | dd3817fb6d180265a74ad6ff5ccd9ea7825faf5ea46e7e1c64da30637a08436a | 14,255 | [
-1
] |
14,256 | biased.lisp | asmaloney_ACT-R/extras/tracker/biased.lisp | #|
This file contains a model with no experiment.
The model consists of just one production which creates
two trackers showing the options for creating a bias in
the initial distribution. That can be done by providing
either a list of arbitrary x,y values to initialize the
quadratic or by just providing the y values in which case
the x values used will be the possible choices (in order).
After running the model to fire the production the stats
of the trackers can be inspected with print-tracker-stats
to see the distrubitions. There is an example run provided
at the end of this file.
|#
(clear-all)
(require-extra "tracker")
(define-model bias-initial
;; set a seed to generate the specific trace below
(sgp :seed (1045 1))
(sgp :v t :trace-detail low)
;; create a chunk-type to provide the slot names
;; used in the example.
(chunk-type dummy x-y-values only-y-values)
;; create chunks for tracker names and good slot to avoid warnings
(define-chunks x-y-values only-y-values color)
(p create
?goal>
buffer empty
==>
+goal>
;; First tracker generated with specific x,y values
;; to create the initial quadratic
+tracker>
isa track-outcome
control-slot x-y-values
good-slot color
min 9 max 18
x-bias (2 5 20 20)
y-bias (-10 -1 2 2)
;; second tracker, specify values for
;; the possible choices
+tracker>
isa track-outcome
control-slot only-y-values
good-slot color
min 9 max 18
y-bias (-10 -10 -10 -10 0 0 0 0 0 0 2 2 2 2 2 2 2 2 2 2 2)))
#| Example run
CG-USER(140): (run .05)
0.050 PROCEDURAL PRODUCTION-FIRED CREATE
0.050 GOAL SET-BUFFER-CHUNK-FROM-SPEC GOAL
0.050 ------ Stopped because time limit reached
0.05
19
NIL
CG-USER(141): (print-tracker-stats)
Tracker named TRACKER1 for slot ONLY-Y-VALUES (active)
Good slot is COLOR in buffer IMAGINAL with weight 1
Current temperature is: 1.0
Current equation is: -234022/3059 + 345700/33649x + -302000/908523x^2
Choices: 9.000 9.450 9.900 10.350 10.800 11.250 11.700 12.150 12.600 13.050 13.500 13.950 14.400 14.850 15.300 15.750 16.200 16.650 17.100 17.550 18.000
Probs: 0.000 0.000 0.000 0.000 0.000 0.000 0.001 0.004 0.010 0.022 0.042 0.070 0.102 0.131 0.147 0.144 0.123 0.092 0.060 0.034 0.017
Current setting is: 15.3
Tracker named TRACKER0 for slot X-Y-VALUES (active)
Good slot is COLOR in buffer IMAGINAL with weight 1
Current temperature is: 1.0
Current equation is: -158/9 + 184/45x + -7/45x^2
Choices: 9.000 9.450 9.900 10.350 10.800 11.250 11.700 12.150 12.600 13.050 13.500 13.950 14.400 14.850 15.300 15.750 16.200 16.650 17.100 17.550 18.000
Probs: 0.007 0.012 0.020 0.030 0.043 0.058 0.073 0.087 0.097 0.101 0.099 0.091 0.079 0.064 0.049 0.035 0.024 0.015 0.009 0.005 0.003
Current setting is: 12.6
((TRACKER1 ONLY-Y-VALUES 1 (-234022/3059 345700/33649 -302000/908523)) (TRACKER0 X-Y-VALUES 1 (-158/9 184/45 -7/45)))
|#
| 3,220 | Common Lisp | .lisp | 71 | 39.830986 | 158 | 0.669585 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 74431907adae0c5f49c3725e2b13e636f57262ecb03cd15f5f124080945d8bd3 | 14,256 | [
-1
] |
14,257 | simple.lisp | asmaloney_ACT-R/extras/tracker/simple.lisp | #|
This file contains a simple experiment and a model which uses a
tracker to learn the correct response to the experiment.
In the experiment the model is to press one of three keys, 1, 2, or 3
when prompted to choose. It will then be provided feedback of whether
that answer was correct or not and given 5 seconds to process that
before the next choose prompt. One of the choices will always be the
correct answer and the other two will always be wrong, and the model
is trying to learn the correct choice.
This is not the type of task for which the tracker is intended because
the existing declarative or procedural learning approaches could easily
be applied to learn this simple choice response since the responses
are discrete and there is no ambiguity in credit assignment from the
feedback, but by using such a simple task the operation of the tracker
should be easy to follow for example purposes.
To run the task call run-test and provide the length of time (in seconds)
to have the model perform the task, and optionally provide the correct
response (which defaults to 2).
There is an example run provided at the end of this file.
|#
(defvar *target* nil)
(defvar *feature* nil)
(defun response (model key)
(declare (ignore model))
(if (equal key *target*)
(modify-visicon-features (list *feature* 'prompt 'correct))
(modify-visicon-features (list *feature* 'prompt 'wrong)))
(schedule-event-relative 5 'choose :output nil :maintenance t))
(defun choose ()
(modify-visicon-features (list *feature* 'prompt 'choose)))
(defun run-test (time &optional (value 2))
(if (< 0 value 4)
(setf *target* (princ-to-string value))
(setf *target* "2"))
(reset)
(install-device (list "motor" "keyboard"))
(add-act-r-command "response" 'response "Process key response")
(monitor-act-r-command "output-key" "response")
(setf *feature* (car (add-visicon-features '(screen-x 100 screen-y 100 prompt choose))))
(run time)
(remove-act-r-command-monitor "output-key" "response")
(remove-act-r-command "response"))
(clear-all)
(require-extra "tracker")
(define-model simple-tracker-test
(sgp :v t :trace-tracker t :trace-detail high)
; Seed which generated the test run below
; (sgp :seed (57531033409 0))
;; create chunk-types for the goal, imaginal, and visual-location chunks
(chunk-type guess value)
(chunk-type result good bad)
(chunk-type prompt screen-x screen-y prompt)
;; avoid warnings for the slots in productions that are modified and untested or vice-versa
(declare-buffer-usage goal guess value)
(declare-buffer-usage imaginal result :all)
;; Create the chunks that are used to name the slots and
;; provide the visual prompts.
(define-chunks good bad value choose wrong correct)
;; Have any unattended visual chunk stuffed into the buffer.
;; This model doesn't need to actually attend to do this task.
(set-visloc-default :attended nil)
;; Create the tracker and set the initial chunks in the
;; goal and imagial buffers. The tracker will set the
;; value slot of the goal, and watch the good and bad
;; slots of the imaginal buffer, to determine the best
;; value among 1, 2, and 3.
(p start
?goal>
buffer empty
?imaginal>
state free
buffer empty
?tracker>
state free
==>
+tracker>
control-slot value
good-slot good
bad-slot bad
min 1
max 3
control-count 3
+imaginal>
+goal>)
;; When the choose prompt is provided press the key
;; for the value that the tracker has currently set.
(p guess
=goal>
value =val
=visual-location>
prompt choose
?manual>
state free
==>
+manual>
isa press-key
key =val)
;; If the feedback indicates a wrong answer modify the
;; bad slot of imaginal for the tracker to record.
(p wrong
=imaginal>
=visual-location>
prompt wrong
==>
=imaginal>
bad 1)
;; If the feedback indicates a correct answer modify the
;; good slot of imaginal for the tracker to record.
(p correct
=imaginal>
=visual-location>
prompt correct
==>
=imaginal>
good 1)
)
#|
When a tracker is created it will create an initial guess
for the value. That guess will be used until an update to
the result is made, at which time a new guess will be chosen
and used until the next update. Those updates are not
associated with the actions or feedback, and just occur
after a randomly chosen update period passes (by default
that is from an exponential distribution with a mean of 10s
bounded by 1s and 60s).
> (run-test 100)
0.000 VISION PROC-DISPLAY
0.000 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
0.000 VISION visicon-update
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.000 PROCEDURAL PRODUCTION-SELECTED START
0.000 PROCEDURAL QUERY-BUFFER-ACTION GOAL
0.000 PROCEDURAL QUERY-BUFFER-ACTION IMAGINAL
0.000 PROCEDURAL QUERY-BUFFER-ACTION TRACKER
0.050 PROCEDURAL PRODUCTION-FIRED START
0.050 PROCEDURAL MODULE-REQUEST TRACKER
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 1.0:
Choices: 1.000 2.000 3.000
Probs: 0.333 0.333 0.333
Chosen result is 1.0
0.050 PROCEDURAL MODULE-REQUEST IMAGINAL
0.050 PROCEDURAL MODULE-REQUEST GOAL
0.050 PROCEDURAL CLEAR-BUFFER TRACKER
0.050 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.050 PROCEDURAL CLEAR-BUFFER GOAL
0.050 GOAL CREATE-NEW-BUFFER-CHUNK GOAL
0.050 GOAL SET-BUFFER-CHUNK GOAL CHUNK2
0.050 TRACKER MOD-BUFFER-CHUNK GOAL
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-SELECTED GUESS
0.050 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.100 PROCEDURAL PRODUCTION-FIRED GUESS
0.100 PROCEDURAL MODULE-REQUEST MANUAL
0.100 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 PROCEDURAL CLEAR-BUFFER MANUAL
0.100 MOTOR PRESS-KEY KEY 1
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.250 IMAGINAL CREATE-NEW-BUFFER-CHUNK IMAGINAL
0.250 IMAGINAL SET-BUFFER-CHUNK IMAGINAL CHUNK3
0.250 PROCEDURAL CONFLICT-RESOLUTION
0.350 MOTOR PREPARATION-COMPLETE
0.350 PROCEDURAL CONFLICT-RESOLUTION
0.400 MOTOR INITIATION-COMPLETE
0.400 PROCEDURAL CONFLICT-RESOLUTION
0.500 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
0.500 VISION PROC-DISPLAY
0.500 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
0.500 VISION visicon-update
0.500 PROCEDURAL CONFLICT-RESOLUTION
0.500 PROCEDURAL PRODUCTION-SELECTED WRONG
0.500 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
0.500 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.550 PROCEDURAL PRODUCTION-FIRED WRONG
0.550 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
0.550 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.550 PROCEDURAL CONFLICT-RESOLUTION
0.650 MOTOR FINISH-MOVEMENT
0.650 PROCEDURAL CONFLICT-RESOLUTION
5.500 VISION PROC-DISPLAY
5.500 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
5.500 VISION visicon-update
5.500 PROCEDURAL CONFLICT-RESOLUTION
5.500 PROCEDURAL PRODUCTION-SELECTED GUESS
5.500 PROCEDURAL BUFFER-READ-ACTION GOAL
5.500 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
5.500 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
5.550 PROCEDURAL PRODUCTION-FIRED GUESS
5.550 PROCEDURAL MODULE-REQUEST MANUAL
5.550 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
5.550 PROCEDURAL CLEAR-BUFFER MANUAL
5.550 MOTOR PRESS-KEY KEY 1
5.550 MOTOR PREPARATION-COMPLETE
5.550 PROCEDURAL CONFLICT-RESOLUTION
5.600 MOTOR INITIATION-COMPLETE
5.600 PROCEDURAL CONFLICT-RESOLUTION
5.700 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
5.700 VISION PROC-DISPLAY
5.700 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
5.700 VISION visicon-update
5.700 PROCEDURAL CONFLICT-RESOLUTION
5.700 PROCEDURAL PRODUCTION-SELECTED WRONG
5.700 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
5.700 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
5.750 PROCEDURAL PRODUCTION-FIRED WRONG
5.750 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
5.750 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
5.750 PROCEDURAL CONFLICT-RESOLUTION
5.850 MOTOR FINISH-MOVEMENT
5.850 PROCEDURAL CONFLICT-RESOLUTION
10.700 VISION PROC-DISPLAY
10.700 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
10.700 VISION visicon-update
10.700 PROCEDURAL CONFLICT-RESOLUTION
10.700 PROCEDURAL PRODUCTION-SELECTED GUESS
10.700 PROCEDURAL BUFFER-READ-ACTION GOAL
10.700 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
10.700 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
10.750 PROCEDURAL PRODUCTION-FIRED GUESS
10.750 PROCEDURAL MODULE-REQUEST MANUAL
10.750 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
10.750 PROCEDURAL CLEAR-BUFFER MANUAL
10.750 MOTOR PRESS-KEY KEY 1
10.750 MOTOR PREPARATION-COMPLETE
10.750 PROCEDURAL CONFLICT-RESOLUTION
10.800 MOTOR INITIATION-COMPLETE
10.800 PROCEDURAL CONFLICT-RESOLUTION
10.900 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
10.900 VISION PROC-DISPLAY
10.900 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
10.900 VISION visicon-update
10.900 PROCEDURAL CONFLICT-RESOLUTION
10.900 PROCEDURAL PRODUCTION-SELECTED WRONG
10.900 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
10.900 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
10.950 PROCEDURAL PRODUCTION-FIRED WRONG
10.950 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
10.950 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
10.950 PROCEDURAL CONFLICT-RESOLUTION
11.050 MOTOR FINISH-MOVEMENT
11.050 PROCEDURAL CONFLICT-RESOLUTION
15.900 VISION PROC-DISPLAY
15.900 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
15.900 VISION visicon-update
15.900 PROCEDURAL CONFLICT-RESOLUTION
15.900 PROCEDURAL PRODUCTION-SELECTED GUESS
15.900 PROCEDURAL BUFFER-READ-ACTION GOAL
15.900 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
15.900 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
15.950 PROCEDURAL PRODUCTION-FIRED GUESS
15.950 PROCEDURAL MODULE-REQUEST MANUAL
15.950 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
15.950 PROCEDURAL CLEAR-BUFFER MANUAL
15.950 MOTOR PRESS-KEY KEY 1
15.950 MOTOR PREPARATION-COMPLETE
15.950 PROCEDURAL CONFLICT-RESOLUTION
16.000 MOTOR INITIATION-COMPLETE
16.000 PROCEDURAL CONFLICT-RESOLUTION
16.100 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
16.100 VISION PROC-DISPLAY
16.100 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
16.100 VISION visicon-update
16.100 PROCEDURAL CONFLICT-RESOLUTION
16.100 PROCEDURAL PRODUCTION-SELECTED WRONG
16.100 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
16.100 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
16.150 PROCEDURAL PRODUCTION-FIRED WRONG
16.150 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
16.150 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
16.150 PROCEDURAL CONFLICT-RESOLUTION
16.250 MOTOR FINISH-MOVEMENT
16.250 PROCEDURAL CONFLICT-RESOLUTION
21.100 VISION PROC-DISPLAY
21.100 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
21.100 VISION visicon-update
21.100 PROCEDURAL CONFLICT-RESOLUTION
21.100 PROCEDURAL PRODUCTION-SELECTED GUESS
21.100 PROCEDURAL BUFFER-READ-ACTION GOAL
21.100 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
21.100 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
21.150 PROCEDURAL PRODUCTION-FIRED GUESS
21.150 PROCEDURAL MODULE-REQUEST MANUAL
21.150 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
21.150 PROCEDURAL CLEAR-BUFFER MANUAL
21.150 MOTOR PRESS-KEY KEY 1
21.150 MOTOR PREPARATION-COMPLETE
21.150 PROCEDURAL CONFLICT-RESOLUTION
21.200 MOTOR INITIATION-COMPLETE
21.200 PROCEDURAL CONFLICT-RESOLUTION
21.300 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
21.300 VISION PROC-DISPLAY
21.300 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
21.300 VISION visicon-update
21.300 PROCEDURAL CONFLICT-RESOLUTION
21.300 PROCEDURAL PRODUCTION-SELECTED WRONG
21.300 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
21.300 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
21.350 PROCEDURAL PRODUCTION-FIRED WRONG
21.350 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
21.350 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
21.350 PROCEDURAL CONFLICT-RESOLUTION
21.450 MOTOR FINISH-MOVEMENT
21.450 PROCEDURAL CONFLICT-RESOLUTION
26.300 VISION PROC-DISPLAY
26.300 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
26.300 VISION visicon-update
26.300 PROCEDURAL CONFLICT-RESOLUTION
26.300 PROCEDURAL PRODUCTION-SELECTED GUESS
26.300 PROCEDURAL BUFFER-READ-ACTION GOAL
26.300 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
26.300 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
26.350 PROCEDURAL PRODUCTION-FIRED GUESS
26.350 PROCEDURAL MODULE-REQUEST MANUAL
26.350 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
26.350 PROCEDURAL CLEAR-BUFFER MANUAL
26.350 MOTOR PRESS-KEY KEY 1
26.350 MOTOR PREPARATION-COMPLETE
26.350 PROCEDURAL CONFLICT-RESOLUTION
26.400 MOTOR INITIATION-COMPLETE
26.400 PROCEDURAL CONFLICT-RESOLUTION
26.500 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
26.500 VISION PROC-DISPLAY
26.500 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
26.500 VISION visicon-update
26.500 PROCEDURAL CONFLICT-RESOLUTION
26.500 PROCEDURAL PRODUCTION-SELECTED WRONG
26.500 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
26.500 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
26.550 PROCEDURAL PRODUCTION-FIRED WRONG
26.550 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
26.550 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
26.550 PROCEDURAL CONFLICT-RESOLUTION
26.650 MOTOR FINISH-MOVEMENT
26.650 PROCEDURAL CONFLICT-RESOLUTION
31.500 VISION PROC-DISPLAY
31.500 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
31.500 VISION visicon-update
31.500 PROCEDURAL CONFLICT-RESOLUTION
31.500 PROCEDURAL PRODUCTION-SELECTED GUESS
31.500 PROCEDURAL BUFFER-READ-ACTION GOAL
31.500 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
31.500 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
31.550 PROCEDURAL PRODUCTION-FIRED GUESS
31.550 PROCEDURAL MODULE-REQUEST MANUAL
31.550 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
31.550 PROCEDURAL CLEAR-BUFFER MANUAL
31.550 MOTOR PRESS-KEY KEY 1
31.550 MOTOR PREPARATION-COMPLETE
31.550 PROCEDURAL CONFLICT-RESOLUTION
31.600 MOTOR INITIATION-COMPLETE
31.600 PROCEDURAL CONFLICT-RESOLUTION
31.700 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
31.700 VISION PROC-DISPLAY
31.700 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
31.700 VISION visicon-update
31.700 PROCEDURAL CONFLICT-RESOLUTION
31.700 PROCEDURAL PRODUCTION-SELECTED WRONG
31.700 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
31.700 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
31.750 PROCEDURAL PRODUCTION-FIRED WRONG
31.750 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
31.750 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
31.750 PROCEDURAL CONFLICT-RESOLUTION
31.850 MOTOR FINISH-MOVEMENT
31.850 PROCEDURAL CONFLICT-RESOLUTION
31.946 TRACKER update-tracker TRACKER0 VALUE
Tracker TRACKER0 for VALUE slot updating the equation
new equation is -0.6383563 + 0.5319536x + -0.10638899x^2
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 0.8494733:
Choices: 1.000 2.000 3.000
Probs: 0.280 0.360 0.360
Chosen result is 2.0
31.946 TRACKER MOD-BUFFER-CHUNK GOAL
31.946 PROCEDURAL CONFLICT-RESOLUTION
36.700 VISION PROC-DISPLAY
36.700 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
36.700 VISION visicon-update
36.700 PROCEDURAL CONFLICT-RESOLUTION
36.700 PROCEDURAL PRODUCTION-SELECTED GUESS
36.700 PROCEDURAL BUFFER-READ-ACTION GOAL
36.700 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
36.700 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
36.750 PROCEDURAL PRODUCTION-FIRED GUESS
36.750 PROCEDURAL MODULE-REQUEST MANUAL
36.750 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
36.750 PROCEDURAL CLEAR-BUFFER MANUAL
36.750 MOTOR PRESS-KEY KEY 2
36.750 PROCEDURAL CONFLICT-RESOLUTION
36.900 MOTOR PREPARATION-COMPLETE
36.900 PROCEDURAL CONFLICT-RESOLUTION
36.950 MOTOR INITIATION-COMPLETE
36.950 PROCEDURAL CONFLICT-RESOLUTION
37.050 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
37.050 VISION PROC-DISPLAY
37.050 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
37.050 VISION visicon-update
37.050 PROCEDURAL CONFLICT-RESOLUTION
37.050 PROCEDURAL PRODUCTION-SELECTED CORRECT
37.050 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
37.050 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
37.100 PROCEDURAL PRODUCTION-FIRED CORRECT
37.100 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
37.100 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
37.100 PROCEDURAL CONFLICT-RESOLUTION
37.200 MOTOR FINISH-MOVEMENT
37.200 PROCEDURAL CONFLICT-RESOLUTION
38.955 TRACKER update-tracker TRACKER0 VALUE
Tracker TRACKER0 for VALUE slot updating the equation
new equation is -1.0129573 + 1.0314226x + -0.2312571x^2
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 0.8222745:
Choices: 1.000 2.000 3.000
Probs: 0.263 0.396 0.341
Chosen result is 2.0
38.955 TRACKER MOD-BUFFER-CHUNK GOAL
38.955 PROCEDURAL CONFLICT-RESOLUTION
39.955 TRACKER update-tracker TRACKER0 VALUE
Tracker TRACKER0 for VALUE slot updating the equation
new equation is -0.97136295 + 0.97596157x + -0.21739036x^2
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 0.81853527:
Choices: 1.000 2.000 3.000
Probs: 0.264 0.393 0.343
Chosen result is 1.0
39.955 TRACKER MOD-BUFFER-CHUNK GOAL
39.955 PROCEDURAL CONFLICT-RESOLUTION
42.050 VISION PROC-DISPLAY
42.050 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
42.050 VISION visicon-update
42.050 PROCEDURAL CONFLICT-RESOLUTION
42.050 PROCEDURAL PRODUCTION-SELECTED GUESS
42.050 PROCEDURAL BUFFER-READ-ACTION GOAL
42.050 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
42.050 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
42.100 PROCEDURAL PRODUCTION-FIRED GUESS
42.100 PROCEDURAL MODULE-REQUEST MANUAL
42.100 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
42.100 PROCEDURAL CLEAR-BUFFER MANUAL
42.100 MOTOR PRESS-KEY KEY 1
42.100 PROCEDURAL CONFLICT-RESOLUTION
42.250 MOTOR PREPARATION-COMPLETE
42.250 PROCEDURAL CONFLICT-RESOLUTION
42.300 MOTOR INITIATION-COMPLETE
42.300 PROCEDURAL CONFLICT-RESOLUTION
42.400 KEYBOARD output-key SIMPLE-TRACKER-TEST 1
42.400 VISION PROC-DISPLAY
42.400 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
42.400 VISION visicon-update
42.400 PROCEDURAL CONFLICT-RESOLUTION
42.400 PROCEDURAL PRODUCTION-SELECTED WRONG
42.400 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
42.400 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
42.450 PROCEDURAL PRODUCTION-FIRED WRONG
42.450 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
42.450 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
42.450 PROCEDURAL CONFLICT-RESOLUTION
42.550 MOTOR FINISH-MOVEMENT
42.550 PROCEDURAL CONFLICT-RESOLUTION
43.291 TRACKER update-tracker TRACKER0 VALUE
Tracker TRACKER0 for VALUE slot updating the equation
new equation is -0.99539316 + 0.99599135x + -0.22139755x^2
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 0.8063035:
Choices: 1.000 2.000 3.000
Probs: 0.261 0.395 0.344
Chosen result is 2.0
43.291 TRACKER MOD-BUFFER-CHUNK GOAL
43.291 PROCEDURAL CONFLICT-RESOLUTION
47.400 VISION PROC-DISPLAY
47.400 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
47.400 VISION visicon-update
47.400 PROCEDURAL CONFLICT-RESOLUTION
47.400 PROCEDURAL PRODUCTION-SELECTED GUESS
47.400 PROCEDURAL BUFFER-READ-ACTION GOAL
47.400 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
47.400 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
47.450 PROCEDURAL PRODUCTION-FIRED GUESS
47.450 PROCEDURAL MODULE-REQUEST MANUAL
47.450 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
47.450 PROCEDURAL CLEAR-BUFFER MANUAL
47.450 MOTOR PRESS-KEY KEY 2
47.450 PROCEDURAL CONFLICT-RESOLUTION
47.600 MOTOR PREPARATION-COMPLETE
47.600 PROCEDURAL CONFLICT-RESOLUTION
47.650 MOTOR INITIATION-COMPLETE
47.650 PROCEDURAL CONFLICT-RESOLUTION
47.750 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
47.750 VISION PROC-DISPLAY
47.750 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
47.750 VISION visicon-update
47.750 PROCEDURAL CONFLICT-RESOLUTION
47.750 PROCEDURAL PRODUCTION-SELECTED CORRECT
47.750 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
47.750 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
47.800 PROCEDURAL PRODUCTION-FIRED CORRECT
47.800 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
47.800 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
47.800 PROCEDURAL CONFLICT-RESOLUTION
47.900 MOTOR FINISH-MOVEMENT
47.900 PROCEDURAL CONFLICT-RESOLUTION
52.750 VISION PROC-DISPLAY
52.750 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
52.750 VISION visicon-update
52.750 PROCEDURAL CONFLICT-RESOLUTION
52.750 PROCEDURAL PRODUCTION-SELECTED GUESS
52.750 PROCEDURAL BUFFER-READ-ACTION GOAL
52.750 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
52.750 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
52.800 PROCEDURAL PRODUCTION-FIRED GUESS
52.800 PROCEDURAL MODULE-REQUEST MANUAL
52.800 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
52.800 PROCEDURAL CLEAR-BUFFER MANUAL
52.800 MOTOR PRESS-KEY KEY 2
52.800 MOTOR PREPARATION-COMPLETE
52.800 PROCEDURAL CONFLICT-RESOLUTION
52.850 MOTOR INITIATION-COMPLETE
52.850 PROCEDURAL CONFLICT-RESOLUTION
52.950 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
52.950 VISION PROC-DISPLAY
52.950 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
52.950 VISION visicon-update
52.950 PROCEDURAL CONFLICT-RESOLUTION
52.950 PROCEDURAL PRODUCTION-SELECTED CORRECT
52.950 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
52.950 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
53.000 PROCEDURAL PRODUCTION-FIRED CORRECT
53.000 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
53.000 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
53.000 PROCEDURAL CONFLICT-RESOLUTION
53.100 MOTOR FINISH-MOVEMENT
53.100 PROCEDURAL CONFLICT-RESOLUTION
57.950 VISION PROC-DISPLAY
57.950 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
57.950 VISION visicon-update
57.950 PROCEDURAL CONFLICT-RESOLUTION
57.950 PROCEDURAL PRODUCTION-SELECTED GUESS
57.950 PROCEDURAL BUFFER-READ-ACTION GOAL
57.950 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
57.950 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
58.000 PROCEDURAL PRODUCTION-FIRED GUESS
58.000 PROCEDURAL MODULE-REQUEST MANUAL
58.000 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
58.000 PROCEDURAL CLEAR-BUFFER MANUAL
58.000 MOTOR PRESS-KEY KEY 2
58.000 MOTOR PREPARATION-COMPLETE
58.000 PROCEDURAL CONFLICT-RESOLUTION
58.050 MOTOR INITIATION-COMPLETE
58.050 PROCEDURAL CONFLICT-RESOLUTION
58.150 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
58.150 VISION PROC-DISPLAY
58.150 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
58.150 VISION visicon-update
58.150 PROCEDURAL CONFLICT-RESOLUTION
58.150 PROCEDURAL PRODUCTION-SELECTED CORRECT
58.150 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
58.150 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
58.200 PROCEDURAL PRODUCTION-FIRED CORRECT
58.200 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
58.200 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
58.200 PROCEDURAL CONFLICT-RESOLUTION
58.300 MOTOR FINISH-MOVEMENT
58.300 PROCEDURAL CONFLICT-RESOLUTION
63.150 VISION PROC-DISPLAY
63.150 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
63.150 VISION visicon-update
63.150 PROCEDURAL CONFLICT-RESOLUTION
63.150 PROCEDURAL PRODUCTION-SELECTED GUESS
63.150 PROCEDURAL BUFFER-READ-ACTION GOAL
63.150 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
63.150 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
63.200 PROCEDURAL PRODUCTION-FIRED GUESS
63.200 PROCEDURAL MODULE-REQUEST MANUAL
63.200 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
63.200 PROCEDURAL CLEAR-BUFFER MANUAL
63.200 MOTOR PRESS-KEY KEY 2
63.200 MOTOR PREPARATION-COMPLETE
63.200 PROCEDURAL CONFLICT-RESOLUTION
63.250 MOTOR INITIATION-COMPLETE
63.250 PROCEDURAL CONFLICT-RESOLUTION
63.350 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
63.350 VISION PROC-DISPLAY
63.350 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
63.350 VISION visicon-update
63.350 PROCEDURAL CONFLICT-RESOLUTION
63.350 PROCEDURAL PRODUCTION-SELECTED CORRECT
63.350 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
63.350 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
63.400 PROCEDURAL PRODUCTION-FIRED CORRECT
63.400 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
63.400 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
63.400 PROCEDURAL CONFLICT-RESOLUTION
63.500 MOTOR FINISH-MOVEMENT
63.500 PROCEDURAL CONFLICT-RESOLUTION
68.350 VISION PROC-DISPLAY
68.350 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
68.350 VISION visicon-update
68.350 PROCEDURAL CONFLICT-RESOLUTION
68.350 PROCEDURAL PRODUCTION-SELECTED GUESS
68.350 PROCEDURAL BUFFER-READ-ACTION GOAL
68.350 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
68.350 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
68.400 PROCEDURAL PRODUCTION-FIRED GUESS
68.400 PROCEDURAL MODULE-REQUEST MANUAL
68.400 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
68.400 PROCEDURAL CLEAR-BUFFER MANUAL
68.400 MOTOR PRESS-KEY KEY 2
68.400 MOTOR PREPARATION-COMPLETE
68.400 PROCEDURAL CONFLICT-RESOLUTION
68.450 MOTOR INITIATION-COMPLETE
68.450 PROCEDURAL CONFLICT-RESOLUTION
68.550 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
68.550 VISION PROC-DISPLAY
68.550 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
68.550 VISION visicon-update
68.550 PROCEDURAL CONFLICT-RESOLUTION
68.550 PROCEDURAL PRODUCTION-SELECTED CORRECT
68.550 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
68.550 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
68.600 PROCEDURAL PRODUCTION-FIRED CORRECT
68.600 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
68.600 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
68.600 PROCEDURAL CONFLICT-RESOLUTION
68.700 MOTOR FINISH-MOVEMENT
68.700 PROCEDURAL CONFLICT-RESOLUTION
73.550 VISION PROC-DISPLAY
73.550 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
73.550 VISION visicon-update
73.550 PROCEDURAL CONFLICT-RESOLUTION
73.550 PROCEDURAL PRODUCTION-SELECTED GUESS
73.550 PROCEDURAL BUFFER-READ-ACTION GOAL
73.550 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
73.550 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
73.600 PROCEDURAL PRODUCTION-FIRED GUESS
73.600 PROCEDURAL MODULE-REQUEST MANUAL
73.600 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
73.600 PROCEDURAL CLEAR-BUFFER MANUAL
73.600 MOTOR PRESS-KEY KEY 2
73.600 MOTOR PREPARATION-COMPLETE
73.600 PROCEDURAL CONFLICT-RESOLUTION
73.650 MOTOR INITIATION-COMPLETE
73.650 PROCEDURAL CONFLICT-RESOLUTION
73.750 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
73.750 VISION PROC-DISPLAY
73.750 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
73.750 VISION visicon-update
73.750 PROCEDURAL CONFLICT-RESOLUTION
73.750 PROCEDURAL PRODUCTION-SELECTED CORRECT
73.750 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
73.750 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
73.800 PROCEDURAL PRODUCTION-FIRED CORRECT
73.800 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
73.800 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
73.800 PROCEDURAL CONFLICT-RESOLUTION
73.900 MOTOR FINISH-MOVEMENT
73.900 PROCEDURAL CONFLICT-RESOLUTION
78.750 VISION PROC-DISPLAY
78.750 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
78.750 VISION visicon-update
78.750 PROCEDURAL CONFLICT-RESOLUTION
78.750 PROCEDURAL PRODUCTION-SELECTED GUESS
78.750 PROCEDURAL BUFFER-READ-ACTION GOAL
78.750 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
78.750 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
78.800 PROCEDURAL PRODUCTION-FIRED GUESS
78.800 PROCEDURAL MODULE-REQUEST MANUAL
78.800 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
78.800 PROCEDURAL CLEAR-BUFFER MANUAL
78.800 MOTOR PRESS-KEY KEY 2
78.800 MOTOR PREPARATION-COMPLETE
78.800 PROCEDURAL CONFLICT-RESOLUTION
78.850 MOTOR INITIATION-COMPLETE
78.850 PROCEDURAL CONFLICT-RESOLUTION
78.950 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
78.950 VISION PROC-DISPLAY
78.950 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
78.950 VISION visicon-update
78.950 PROCEDURAL CONFLICT-RESOLUTION
78.950 PROCEDURAL PRODUCTION-SELECTED CORRECT
78.950 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
78.950 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
79.000 PROCEDURAL PRODUCTION-FIRED CORRECT
79.000 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
79.000 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
79.000 PROCEDURAL CONFLICT-RESOLUTION
79.100 MOTOR FINISH-MOVEMENT
79.100 PROCEDURAL CONFLICT-RESOLUTION
83.950 VISION PROC-DISPLAY
83.950 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
83.950 VISION visicon-update
83.950 PROCEDURAL CONFLICT-RESOLUTION
83.950 PROCEDURAL PRODUCTION-SELECTED GUESS
83.950 PROCEDURAL BUFFER-READ-ACTION GOAL
83.950 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
83.950 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
84.000 PROCEDURAL PRODUCTION-FIRED GUESS
84.000 PROCEDURAL MODULE-REQUEST MANUAL
84.000 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
84.000 PROCEDURAL CLEAR-BUFFER MANUAL
84.000 MOTOR PRESS-KEY KEY 2
84.000 MOTOR PREPARATION-COMPLETE
84.000 PROCEDURAL CONFLICT-RESOLUTION
84.050 MOTOR INITIATION-COMPLETE
84.050 PROCEDURAL CONFLICT-RESOLUTION
84.150 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
84.150 VISION PROC-DISPLAY
84.150 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
84.150 VISION visicon-update
84.150 PROCEDURAL CONFLICT-RESOLUTION
84.150 PROCEDURAL PRODUCTION-SELECTED CORRECT
84.150 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
84.150 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
84.200 PROCEDURAL PRODUCTION-FIRED CORRECT
84.200 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
84.200 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
84.200 PROCEDURAL CONFLICT-RESOLUTION
84.300 MOTOR FINISH-MOVEMENT
84.300 PROCEDURAL CONFLICT-RESOLUTION
85.155 TRACKER update-tracker TRACKER0 VALUE
Tracker TRACKER0 for VALUE slot updating the equation
new equation is -1.193099 + 1.2595936x + -0.28729433x^2
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 0.67897624:
Choices: 1.000 2.000 3.000
Probs: 0.239 0.430 0.331
Chosen result is 2.0
85.155 TRACKER MOD-BUFFER-CHUNK GOAL
85.155 PROCEDURAL CONFLICT-RESOLUTION
89.150 VISION PROC-DISPLAY
89.150 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
89.150 VISION visicon-update
89.150 PROCEDURAL CONFLICT-RESOLUTION
89.150 PROCEDURAL PRODUCTION-SELECTED GUESS
89.150 PROCEDURAL BUFFER-READ-ACTION GOAL
89.150 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
89.150 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
89.200 PROCEDURAL PRODUCTION-FIRED GUESS
89.200 PROCEDURAL MODULE-REQUEST MANUAL
89.200 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
89.200 PROCEDURAL CLEAR-BUFFER MANUAL
89.200 MOTOR PRESS-KEY KEY 2
89.200 MOTOR PREPARATION-COMPLETE
89.200 PROCEDURAL CONFLICT-RESOLUTION
89.250 MOTOR INITIATION-COMPLETE
89.250 PROCEDURAL CONFLICT-RESOLUTION
89.350 KEYBOARD output-key SIMPLE-TRACKER-TEST 2
89.350 VISION PROC-DISPLAY
89.350 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
89.350 VISION visicon-update
89.350 PROCEDURAL CONFLICT-RESOLUTION
89.350 PROCEDURAL PRODUCTION-SELECTED CORRECT
89.350 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
89.350 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
89.400 PROCEDURAL PRODUCTION-FIRED CORRECT
89.400 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current GOOD value
Updating event occurred in the GOOD slot of the IMAGINAL buffer
updating with value 1.0
89.400 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
89.400 PROCEDURAL CONFLICT-RESOLUTION
89.500 MOTOR FINISH-MOVEMENT
89.500 PROCEDURAL CONFLICT-RESOLUTION
90.279 TRACKER update-tracker TRACKER0 VALUE
Tracker TRACKER0 for VALUE slot updating the equation
new equation is -1.1981206 + 1.2662959x + -0.28897288x^2
Tracker TRACKER0 generating value for buffer GOAL slot VALUE with temperature 0.6661017:
Choices: 1.000 2.000 3.000
Probs: 0.237 0.432 0.331
Chosen result is 3.0
90.279 TRACKER MOD-BUFFER-CHUNK GOAL
90.279 PROCEDURAL CONFLICT-RESOLUTION
94.350 VISION PROC-DISPLAY
94.350 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
94.350 VISION visicon-update
94.350 PROCEDURAL CONFLICT-RESOLUTION
94.350 PROCEDURAL PRODUCTION-SELECTED GUESS
94.350 PROCEDURAL BUFFER-READ-ACTION GOAL
94.350 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
94.350 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
94.400 PROCEDURAL PRODUCTION-FIRED GUESS
94.400 PROCEDURAL MODULE-REQUEST MANUAL
94.400 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
94.400 PROCEDURAL CLEAR-BUFFER MANUAL
94.400 MOTOR PRESS-KEY KEY 3
94.400 PROCEDURAL CONFLICT-RESOLUTION
94.550 MOTOR PREPARATION-COMPLETE
94.550 PROCEDURAL CONFLICT-RESOLUTION
94.600 MOTOR INITIATION-COMPLETE
94.600 PROCEDURAL CONFLICT-RESOLUTION
94.700 KEYBOARD output-key SIMPLE-TRACKER-TEST 3
94.700 VISION PROC-DISPLAY
94.700 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
94.700 VISION visicon-update
94.700 PROCEDURAL CONFLICT-RESOLUTION
94.700 PROCEDURAL PRODUCTION-SELECTED WRONG
94.700 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
94.700 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
94.750 PROCEDURAL PRODUCTION-FIRED WRONG
94.750 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
94.750 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
94.750 PROCEDURAL CONFLICT-RESOLUTION
94.850 MOTOR FINISH-MOVEMENT
94.850 PROCEDURAL CONFLICT-RESOLUTION
99.700 VISION PROC-DISPLAY
99.700 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
99.700 VISION visicon-update
99.700 PROCEDURAL CONFLICT-RESOLUTION
99.700 PROCEDURAL PRODUCTION-SELECTED GUESS
99.700 PROCEDURAL BUFFER-READ-ACTION GOAL
99.700 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
99.700 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
99.750 PROCEDURAL PRODUCTION-FIRED GUESS
99.750 PROCEDURAL MODULE-REQUEST MANUAL
99.750 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
99.750 PROCEDURAL CLEAR-BUFFER MANUAL
99.750 MOTOR PRESS-KEY KEY 3
99.750 MOTOR PREPARATION-COMPLETE
99.750 PROCEDURAL CONFLICT-RESOLUTION
99.800 MOTOR INITIATION-COMPLETE
99.800 PROCEDURAL CONFLICT-RESOLUTION
99.900 KEYBOARD output-key SIMPLE-TRACKER-TEST 3
99.900 VISION PROC-DISPLAY
99.900 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
99.900 VISION visicon-update
99.900 PROCEDURAL CONFLICT-RESOLUTION
99.900 PROCEDURAL PRODUCTION-SELECTED WRONG
99.900 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
99.900 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
99.950 PROCEDURAL PRODUCTION-FIRED WRONG
99.950 PROCEDURAL MOD-BUFFER-CHUNK IMAGINAL
Tracker TRACKER0 for VALUE updating the current BAD value
Updating event occurred in the BAD slot of the IMAGINAL buffer
updating with value 1.0
99.950 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
99.950 PROCEDURAL CONFLICT-RESOLUTION
100.000 ------ Stopped because time limit reached
|# | 50,177 | Common Lisp | .lisp | 887 | 50.829763 | 94 | 0.603235 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e7048b46359c5face7b8f02e87f620ed509b8908b315f93b41b548a9ae569dac | 14,257 | [
248508
] |
14,258 | suspend-resume.lisp | asmaloney_ACT-R/extras/tracker/suspend-resume.lisp | #|
This file contains the same experiment and basic model as the simple.lisp example.
However, in this model it is also going to suspend and resume the tracker, create
additional trackers, and also query the tracker information to demonstrate those
capabilities.
|#
(defvar *target* nil)
(defvar *feature* nil)
(defun response (model key)
(declare (ignore model))
(if (equal key *target*)
(modify-visicon-features (list *feature* 'prompt 'correct))
(modify-visicon-features (list *feature* 'prompt 'wrong)))
(schedule-event-relative 5 'choose :output nil :maintenance t))
(defun choose ()
(modify-visicon-features (list *feature* 'prompt 'choose)))
(defun run-test (time &optional (value 2))
(if (< 0 value 4)
(setf *target* (princ-to-string value))
(setf *target* "2"))
(reset)
(install-device (list "motor" "keyboard"))
(add-act-r-command "response" 'response "Process key response")
(monitor-act-r-command "output-key" "response")
(setf *feature* (car (add-visicon-features '(screen-x 100 screen-y 100 prompt choose))))
(run time)
(remove-act-r-command-monitor "output-key" "response")
(remove-act-r-command "response"))
(clear-all)
(require-extra "tracker")
(define-model simple-tracker-test
(sgp :v t :trace-tracker t :trace-detail high)
; Seed which generates the test
(sgp :seed (103 0))
;; create chunk-types for the goal, imaginal, and visual-location chunks
(chunk-type guess value state test name)
(chunk-type result good bad)
(chunk-type prompt screen-x screen-y prompt)
;; avoid warnings for the slots in productions that are modified and untested or vice-versa
(declare-buffer-usage goal guess value)
(declare-buffer-usage imaginal result :all)
;; Create the chunks that are used to name the slots and
;; provide the visual prompts.
(define-chunks good bad value choose wrong correct)
;; Have any unattended visual chunk stuffed into the buffer.
;; This model doesn't need to actually attend to do this task.
(set-visloc-default :attended nil)
;; Create the tracker and set the initial chunks in the
;; goal and imagial buffers. The tracker will set the
;; value slot of the goal, and watch the good and bad
;; slots of the imaginal buffer, to determine the best
;; value among 1, 2, and 3.
;; Also start a temporal timer to determine when to
;; interrupt and perform the additional features for this
;; demonstration.
(p start
?goal>
buffer empty
?imaginal>
state free
buffer empty
?tracker>
state free
==>
+tracker>
control-slot value
good-slot good
bad-slot bad
min 1
max 3
control-count 3
+imaginal>
+goal>
+temporal> isa time)
;; When the choose prompt is provided press the key
;; for the value that the tracker has currently set.
(p guess
=goal>
value =val
state nil
=visual-location>
prompt choose
?manual>
state free
==>
+manual>
isa press-key
key =val)
;; If the feedback indicates a wrong answer modify the
;; bad slot of imaginal for the tracker to record.
(p wrong
=goal>
=imaginal>
=visual-location>
prompt wrong
==>
=imaginal>
bad 1
=goal>
state t)
;; If the feedback indicates a correct answer modify the
;; good slot of imaginal for the tracker to record.
(p correct
=goal>
=imaginal>
=visual-location>
prompt correct
==>
=imaginal>
good 1
=goal>
state t)
(p continue
=goal>
state t
=temporal>
< ticks 60
==>
=goal>
state nil)
(p suspend-only-tracker
=goal>
state t
test nil
?tracker>
exists value
active value
=temporal>
>= ticks 60
=tracker>
control-slot value
==>
=goal>
state nil
test 1
+temporal> isa time
+tracker>
isa suspend-tracker
control-slot value
)
(p doesnt-match-1
=goal>
state t
test nil
?tracker>
- exists value
=temporal>
>= ticks 60
==>
)
(p doesnt-match-2
=goal>
state t
test nil
?tracker>
- active value
=temporal>
>= ticks 60
==>
)
(spp (doesnt-match-1 doesnt-match-2) :u 3)
(p resume-only-tracker
=goal>
state t
test 1
?tracker>
exists value
- active value
=temporal>
>= ticks 60
==>
=goal>
state nil
test 2
+temporal> isa time
+tracker>
isa resume-tracker
control-slot value
)
(p doesnt-match-3
=goal>
state t
test 1
?tracker>
- exists value
=temporal>
>= ticks 60
==>
)
(p doesnt-match-4
=goal>
state t
test 1
?tracker>
active value
=temporal>
>= ticks 60
==>
)
(spp (doesnt-match-3 doesnt-match-4) :u 3)
(p implicit-suspend-at-creation
=goal>
state t
test 2
?tracker>
exists value
active value
=tracker>
control-slot value
name =name
=temporal>
>= ticks 60
==>
=goal>
state nil
test 3
name =name
+temporal> isa time
+tracker>
control-slot value
good-slot good
bad-slot bad
min 0
max 5
control-count 6
name new-tracker
)
(p implicit-suspend-at-resume
=goal>
state t
test 3
name =name
=temporal>
>= ticks 60
==>
=goal>
state nil
test 4
+temporal> isa time
+tracker>
isa resume-tracker
name =name
)
(p explicit-suspend-by-name
=goal>
state t
test 4
name =name
=temporal>
>= ticks 60
==>
=goal>
state nil
test 5
+temporal> isa time
+tracker>
isa suspend-tracker
name =name
)
(p failed-suspend-by-name
=goal>
state t
test 5
name =name
=temporal>
>= ticks 20
==>
=goal>
state nil
test 6
+temporal> isa time
+tracker>
isa suspend-tracker
name =name
)
(p failed-suspend-by-slot
=goal>
state t
test 6
name =name
=temporal>
>= ticks 20
==>
=goal>
state nil
test 7
+temporal> isa time
+tracker>
isa suspend-tracker
control-slot value
)
(p failed-resume-1
=goal>
state t
test 7
name =name
=temporal>
>= ticks 20
==>
=goal>
state nil
test 9
+temporal> isa time
+tracker>
isa resume-tracker
)
(p failed-resume-2
=goal>
state t
test 9
name =name
=temporal>
>= ticks 20
==>
=goal>
state nil
test 10
+temporal> isa time
+tracker>
isa resume-tracker
name foo
)
(p failed-resume-3
=goal>
state t
test 10
name =name
=temporal>
>= ticks 20
==>
=goal>
state nil
test 11
+temporal> isa time
+tracker>
isa resume-tracker
control-slot color
)
(p failed-resume-4
=goal>
state t
test 11
name =name
=temporal>
>= ticks 20
==>
=goal>
state nil
test 12
+temporal> isa time
+tracker>
isa resume-tracker
control-slot value
)
)
| 8,139 | Common Lisp | .lisp | 355 | 15.487324 | 94 | 0.565379 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1804fba72f489dcf09d57f8b55554e27db7d119b293ea37a74ba8c4d2cbfa5eb | 14,258 | [
279824
] |
14,259 | example-demo2.lisp | asmaloney_ACT-R/extras/emma/example-demo2.lisp | ;; This file loads the demo2 model task and model from the tutorial.
;; The demo2-emma function will enable EMMA and run the task. The
;; comments at the end show the results of running the original task
;; without enabling EMMA and then with EMMA.
(clear-all)
(require-extra "emma")
(load-act-r-code "ACT-R:tutorial;lisp;demo2.lisp")
(defun demo2-emma ()
(let ((original (first (ssp :starting-parameters))))
(ssp-fct (list :starting-parameters (append '(:emma t) original)))
(demo2-experiment)
(ssp-fct (list :starting-parameters original))))
#|
CG-USER(12): (load "ACT-R:extras;emma;example-demo2.lisp")
T
CG-USER(13): (demo2-experiment)
#|Warning: No handler available for displaying a visible window. Using a virtual window instead. |#
0.000 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 VISION PROC-DISPLAY
0.000 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0 NIL
0.000 VISION visicon-update
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.000 PROCEDURAL PRODUCTION-SELECTED FIND-UNATTENDED-LETTER
0.000 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 PROCEDURAL PRODUCTION-FIRED FIND-UNATTENDED-LETTER
0.050 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.050 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.050 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 VISION Find-location
0.050 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-SELECTED ATTEND-LETTER
0.050 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
0.100 PROCEDURAL PRODUCTION-FIRED ATTEND-LETTER
0.100 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.100 PROCEDURAL MODULE-REQUEST VISUAL
0.100 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 PROCEDURAL CLEAR-BUFFER VISUAL
0.100 VISION Move-attention VISUAL-LOCATION0-1 NIL
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.185 VISION Encoding-complete VISUAL-LOCATION0-1 NIL
0.185 VISION SET-BUFFER-CHUNK VISUAL TEXT0
0.185 PROCEDURAL CONFLICT-RESOLUTION
0.185 PROCEDURAL PRODUCTION-SELECTED ENCODE-LETTER
0.185 PROCEDURAL BUFFER-READ-ACTION GOAL
0.185 PROCEDURAL BUFFER-READ-ACTION VISUAL
0.185 PROCEDURAL QUERY-BUFFER-ACTION IMAGINAL
0.235 PROCEDURAL PRODUCTION-FIRED ENCODE-LETTER
0.235 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.235 PROCEDURAL MODULE-REQUEST IMAGINAL
0.235 PROCEDURAL CLEAR-BUFFER VISUAL
0.235 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.235 PROCEDURAL CONFLICT-RESOLUTION
0.435 IMAGINAL CREATE-NEW-BUFFER-CHUNK IMAGINAL
0.435 IMAGINAL SET-BUFFER-CHUNK IMAGINAL CHUNK0
0.435 PROCEDURAL CONFLICT-RESOLUTION
0.435 PROCEDURAL PRODUCTION-SELECTED RESPOND
0.435 PROCEDURAL BUFFER-READ-ACTION GOAL
0.435 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
0.435 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.485 PROCEDURAL PRODUCTION-FIRED RESPOND
0.485 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.485 PROCEDURAL MODULE-REQUEST MANUAL
0.485 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.485 PROCEDURAL CLEAR-BUFFER MANUAL
0.485 MOTOR PRESS-KEY KEY V
0.485 PROCEDURAL CONFLICT-RESOLUTION
0.735 MOTOR PREPARATION-COMPLETE
0.735 PROCEDURAL CONFLICT-RESOLUTION
0.785 MOTOR INITIATION-COMPLETE
0.785 PROCEDURAL CONFLICT-RESOLUTION
0.885 KEYBOARD output-key DEMO2 v
0.885 VISION PROC-DISPLAY
0.885 VISION visicon-update
0.885 PROCEDURAL CONFLICT-RESOLUTION
0.970 VISION Encoding-complete VISUAL-LOCATION0-1 NIL
0.970 VISION No visual-object found
0.970 PROCEDURAL CONFLICT-RESOLUTION
1.035 MOTOR FINISH-MOVEMENT
1.035 PROCEDURAL CONFLICT-RESOLUTION
1.035 ------ Stopped because no events left to process
"v"
CG-USER(14): (demo2-emma)
#|Warning: No handler available for displaying a visible window. Using a virtual window instead. |#
0.000 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 VISION PROC-DISPLAY
0.000 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0 NIL
0.000 VISION visicon-update
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.000 PROCEDURAL PRODUCTION-SELECTED FIND-UNATTENDED-LETTER
0.000 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 PROCEDURAL PRODUCTION-FIRED FIND-UNATTENDED-LETTER
0.050 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.050 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.050 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 VISION Find-location
0.050 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-SELECTED ATTEND-LETTER
0.050 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
0.100 PROCEDURAL PRODUCTION-FIRED ATTEND-LETTER
0.100 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.100 PROCEDURAL MODULE-REQUEST VISUAL
0.100 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 PROCEDURAL CLEAR-BUFFER VISUAL
0.100 VISION Move-attention VISUAL-LOCATION0-1 NIL
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.250 EMMA Preparation-complete TEXT0
0.250 PROCEDURAL CONFLICT-RESOLUTION
0.300 EMMA INITIATION-COMPLETE
0.300 PROCEDURAL CONFLICT-RESOLUTION
0.379 EMMA Complete-eye-movement TEXT0 #(320 522 1080)
0.379 PROCEDURAL CONFLICT-RESOLUTION
0.479 EMMA Preparation-complete TEXT1
0.479 PROCEDURAL CONFLICT-RESOLUTION
0.529 EMMA INITIATION-COMPLETE
0.529 PROCEDURAL CONFLICT-RESOLUTION
0.553 VISION Encoding-complete VISUAL-LOCATION0-1 NIL
0.553 VISION SET-BUFFER-CHUNK VISUAL TEXT2
0.553 PROCEDURAL CONFLICT-RESOLUTION
0.553 PROCEDURAL PRODUCTION-SELECTED ENCODE-LETTER
0.553 PROCEDURAL BUFFER-READ-ACTION GOAL
0.553 PROCEDURAL BUFFER-READ-ACTION VISUAL
0.553 PROCEDURAL QUERY-BUFFER-ACTION IMAGINAL
0.562 EMMA Complete-eye-movement TEXT1 #(410 443 1080)
0.603 PROCEDURAL PRODUCTION-FIRED ENCODE-LETTER
0.603 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.603 PROCEDURAL MODULE-REQUEST IMAGINAL
0.603 PROCEDURAL CLEAR-BUFFER VISUAL
0.603 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.603 PROCEDURAL CONFLICT-RESOLUTION
0.803 IMAGINAL CREATE-NEW-BUFFER-CHUNK IMAGINAL
0.803 IMAGINAL SET-BUFFER-CHUNK IMAGINAL CHUNK0
0.803 PROCEDURAL CONFLICT-RESOLUTION
0.803 PROCEDURAL PRODUCTION-SELECTED RESPOND
0.803 PROCEDURAL BUFFER-READ-ACTION GOAL
0.803 PROCEDURAL BUFFER-READ-ACTION IMAGINAL
0.803 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.853 PROCEDURAL PRODUCTION-FIRED RESPOND
0.853 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.853 PROCEDURAL MODULE-REQUEST MANUAL
0.853 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.853 PROCEDURAL CLEAR-BUFFER MANUAL
0.853 MOTOR PRESS-KEY KEY V
0.853 PROCEDURAL CONFLICT-RESOLUTION
1.103 MOTOR PREPARATION-COMPLETE
1.103 PROCEDURAL CONFLICT-RESOLUTION
1.153 MOTOR INITIATION-COMPLETE
1.153 PROCEDURAL CONFLICT-RESOLUTION
1.253 KEYBOARD output-key DEMO2 v
1.253 VISION PROC-DISPLAY
1.253 VISION visicon-update
1.253 PROCEDURAL CONFLICT-RESOLUTION
1.276 VISION Encoding-complete VISUAL-LOCATION0-1 NIL
1.276 VISION No visual-object found
1.276 PROCEDURAL CONFLICT-RESOLUTION
1.353 EMMA Preparation-complete NIL
1.353 PROCEDURAL CONFLICT-RESOLUTION
1.403 MOTOR FINISH-MOVEMENT
1.403 EMMA INITIATION-COMPLETE
1.403 PROCEDURAL CONFLICT-RESOLUTION
1.426 EMMA Complete-eye-movement NIL #(431 454 1080)
1.426 PROCEDURAL CONFLICT-RESOLUTION
1.426 ------ Stopped because no events left to process
(NIL)
|# | 10,219 | Common Lisp | .lisp | 170 | 53.594118 | 101 | 0.573849 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e0f6737370a0136b04d40e5c64c9a98b2e35f125731e89103e1d67b9b1126f4e | 14,259 | [
236181
] |
14,260 | emma.lisp | asmaloney_ACT-R/extras/emma/emma.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Mike Byrne
;;; Copyright : (c)2000-3 Rice U./Mike Byrne, All Rights Reserved
;;; Availability: public domain
;;; Address : Rice University
;;; : Psychology Department
;;; : Houston,TX 77005-1892
;;; : [email protected]
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : emma.lisp
;;; Version : 8.2a1
;;;
;;; Description : Implementation of Dario Salvucci's EMMA system for eye
;;; : movements based on subclassing the Vision Module and making
;;; : eye movements based on movement styles.
;;;
;;; Bugs :
;;;
;;; Todo : [X] Solve "chunks created early" problem [requires some
;;; : rewriting of the Vision Module] - solved w/ACT-R 6.
;;; : [ ] Tracking.
;;; : [X] Fix the issue with the unrequested marking. - Not an issue
;;; : as of 8.0a1 since it's not replacing the current vision
;;; : functionality.
;;; : [X] Make sure it works properly with respect to the chunk
;;; : deletion code now in the main module. - Not an issue
;;; : as of 8.0a1 since it's not replacing the current vision
;;; : functionality.
;;; : [ ] Reevaluate the timing since it doesn't look like this
;;; : factored in the change from RPM to ACT-R 5 with an additional
;;; : 50ms production firing (the attention shift time was dropped
;;; : from 135ms to 85ms to account for that), but maybe that
;;; : doesn't matter.
;;;
;;; ----- History -----
;;; 00.07.12 Mike Byrne
;;; : Incept date.
;;; 01.05.09 mdb [r2]
;;; : Fixed vector bugs. Thanks, Dario.
;;; 01.05.?? Dario Salvucci [r3]
;;; : Noise added to both X and Y of movement.
;;; 01.05.28 mdb [r4]
;;; : Some minor tinkering with Dario's last changes.
;;; 01.07.02 mdb [r5]
;;; : Made eye movement relative to next landing spot.
;;; 01.09.21 mdb [r6]
;;; : Fixed bug in COMPLETE-EYE-MOVE.
;;; 01.10.01 mdb [r7]
;;; : Added PROC-S method that's actually correct.
;;; 01.11.10 mdb
;;; : Changed trace log to use CONS rather than LIST to save
;;; : a smidge of memory, and made tracing the eye path switchable.
;;; 2002.05.04 [r8]
;;; : Removed unnecessary PROC-STUB stuff.
;;; 2002.05.07
;;; : Fixed problem of FIND-LOCATION being clobbered by new preps.
;;; : Renamed FOCUS-ON to ENCODING-COMPLETE.
;;; 2003.05.07 mdb [r9]
;;; : Fixed MCL-specific checking.
;;; 2003.06.23 mdb [r10]
;;; : Made it easier and cleaner to hook into eye spot updating
;;; : for non-MCL Lisps by making a more generic function call
;;; : to which specific devices can be tailored, paralleling how
;;; : it's done for attended location.
;;; : Based the EYE-SPOT class on the new RPM-OVERLAY class from
;;; : the 2.1.3 version of "mcl-device.lisp".
;;; 2003.07.17 mdb [r11]
;;; : Added a CLEAR :after method to kill any in-progress shift
;;; : and stripped some dead code.
;;;
;;; 2005.08.10 mjs
;;; : Made numerous changes to create an ACT-R 6.0 version. Changes
;;; : are indicated by the initials mjs.deleted input-q references
;;; : changed scheduling to ACT-R 6 scheduling
;;; : delete preparation-complete from event queue if one is outstanding
;;; : when moving attention
;;; : uses ACT-R 6.0 noise
;;; : no pm- in top-level names
;;; : redefines Vision Module for EMMA
;;; 2006.07.27 Dan
;;; : * Added the code needed to draw the blue dot in ACL.
;;; : * Took the "chunks created early" problem off of to do and
;;; : bugs because I'm pretty sure that's not an issue in 6.
;;; : * Also added the package switches that are in all the other
;;; : module files for those that use them.
;;; 2006.09.08 Dan
;;; : * Changed parameter checks from posnum to nonneg.
;;; 2007.03.16 Dan
;;; : * Changed add-gaussian-noise to catch when there was 0
;;; : deviation because can't generate a noise of 0.
;;; 2007.04.02 Dan
;;; : * Minor tweak to the test in add-gaussian-noise because for
;;; : really small values of stdev (1*10^-23 for shorts) the old
;;; : fix still could have resulted in an error.
;;; 2007.06.25 Dan
;;; : * Added a test to all the schedule-event-relative calls so that
;;; : they are never negative - I don't know which one was actually
;;; : the problem so I put a check in all of them.
;;; 2007.06.26 Dan
;;; : * Modified the #+version> checks in the Allegro based code
;;; : because even though they're protected with a #+:allegro CLisp
;;; : still seems to break on reading them.
;;; 2007.11.05 Dan
;;; : * Fixed the #+ checks that were modified with the last
;;; : update because I broke them with respect to ACL.
;;; 2007.11.15 Dan
;;; : * Added a device-update-eye-loc method for the environment
;;; : visible-virtual windows.
;;; : To use that you need to have EMMA loaded after the environment
;;; : which means this file should go in other-files and not tools,
;;; : commands, or modules.
;;; 2007.11.20 Dan
;;; : * Fixed a bug in object-frequency because stringp doesn't
;;; : necessarily return the string itself for true.
;;; 2007.11.20 Dan [4.0a1]
;;; : * Started to rework for use with the new vision module.
;;; 2007.11.21 Dan
;;; : * Fixed a bug in the ACL display code that was still referring
;;; : to *mp*.
;;; 2007.11.21 Dan
;;; : * Added a parameter (:vis-obj-freq) to set the default frequency value.
;;; 2007.11.28 Dan
;;; : * Fixed a bug in move-attention so that when the target object
;;; : is no longer available there is still a scheduling of the
;;; : encoding complete to trigger the error and set the module back
;;; : to the free state.
;;; 2007.12.21 Dan
;;; : * Changed the LispWorks code for the eye-spot to make it a
;;; : subclass of focus-ring to avoid an error for not having an
;;; : appropriate update-me method, but it doesn't draw and I don't
;;; : really know enough capi code to make the necessary changes to
;;; : the device file...
;;; 2008.04.24 Dan
;;; : * Updated with the recent changes to the main vision module.
;;; : * Added the requested keyword parameter to encoding-complete
;;; : so it doesn't complain when loaded, but it doesn't work
;;; : right with the emma module - unrequested attention shifts
;;; : will not be marked as such in the buffer because emma uses
;;; : move-attention to do so. Will require modifying move-attention
;;; : both in emma and the core module.
;;; : * Added the :test-feats parameter to the module definition.
;;; : * Did not add :auto-attend because that doesn't seem like
;;; : the sort of thing that one would want when using emma and
;;; : it could lead to problems with the timing.
;;; 2008.07.08 Dan
;;; : * Updated update-attended-loc to work right now that the
;;; : visicon chunks get deleted. May need to fix other places
;;; : as well.
;;; 2008.07.15 Dan
;;; : * Fixed a cut-and-paste error introduced with the last fix.
;;; 2008.09.17 Dan
;;; : * Updated the LispWorks code for drawing the fixation spot
;;; : to match with the new device code from LispWorks.
;;; 2010.05.03 Dan
;;; : * Changed the :output of the "No visual-object found" event
;;; : from 'high to 'medium since that's how it has always printed
;;; : anyway because of a bug in filter-test.
;;; 2011.04.28 Dan
;;; : * Suppress warnings about extending chunks at initial load.
;;; 2011.05.16 Dan
;;; : * Replaced pm-warning calls with model-warning.
;;; 2011.05.19 Dan
;;; : * Changed mp-time calls to mp-time-ms calls and adjusted
;;; : as needed.
;;; 2011.06.17 Dan
;;; : * Took the ":exec 'free" out of encoding-complete's state change
;;; : since that shouldn't happen.
;;; 2012.07.02 Dan [4.0a2]
;;; : * Update to support one eye-spot per model in multiple window
;;; : and/or multiple model situations. Like the fixation marker
;;; : there is a function called eye-spot-marker which can be used
;;; : to store the current marker instead of the *eye-spot* variable.
;;; : Like device-update-attended-loc the device-update-eye-loc
;;; : method will now occasionally get called with nil to indicate
;;; : that the marker should be erased.
;;; : * Only show the eye spot when show-focus-p is true.
;;; : * Add a modified install-device so that it can call the
;;; : device-update-eye-loc method when the model switches devices
;;; : and always start eyes at location 0,0 when a device is installed.
;;; : * Also updating some other code that seems to have been neglected
;;; : along the way (particularly the :delete-visicon-chunks,
;;; : :scene-change-threshold, and :viewing-distance parameters).
;;; 2012.09.07 Dan
;;; : * Adding an eye spot for CCL since there's now a device for it.
;;; : * Fixed a bug in the environment version of the eye-spot code.
;;; 2013.01.09 Dan
;;; : * Replaced the #@ in the CCL code with make-point since that
;;; : causes problems in all other Lisps even inside the #+CCL...
;;; : * Removed the clearing of the eye-spot from the reset function
;;; : since install-device handles that and it's important that an
;;; : "old" spot persist to that it can be erased from the previous
;;; : device.
;;; 2013.09.26 Dan
;;; : * To keep the display code separate from the model actions
;;; : using an after method on update-device to draw the eye-loc
;;; : instead of calling it from set-eye-loc.
;;; 2014.02.14 Dan [4.1]
;;; : * Updated with the changes to the vision module to make
;;; : distance for visual locations be in pixels.
;;; 2014.03.17 Dan [5.0]
;;; : * Changed the query-buffer call to be consistent with the new
;;; : internal code.
;;; 2014.07.07 Dan [6.0]
;;; : * Updated for ACT-R 6.1.
;;; 2015.03.20 Dan
;;; : * Attend failure sets the buffer failure flag using set-buffer-failure.
;;; 2015.03.23 Dan
;;; : * The visual buffer failures are now marked as to whether it
;;; : was a requested encoding or an automatic one which failed.
;;; 2015.05.20 Dan
;;; : * Updated the calls to xy-loc to include the module to allow
;;; : for the use of device specific coordinate slots instead of just
;;; : screen-x, screen-y, and distance.
;;; 2015.06.05 Dan
;;; : * Schedule all events in ms now.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2015.07.30 Dan [6.1]
;;; : * Added the unstuffing/overwriting params and actions.
;;; 2015.08.13 Dan
;;; : * Changed all rand-time calls to randomize-time.
;;; 2015.09.23 Dan [7.0]
;;; : * Completing the requests to the visual buffer for the new utility
;;; : learning credit assignment mechanism.
;;; : One issue is that complete-eye-move gets called at multiple
;;; : points in the task so it can't be used to actually complete
;;; : the request even though it's a movement style and would do so
;;; : "automatically". Instead, just use encoding-complete like
;;; : the standard vision module to mark the request done since the
;;; : current module's request function is still called which sets
;;; : the last request slot of the module.
;;; 2016.03.14 Dan
;;; : * Added the provide at the bottom for use with require-extra.
;;; 2016.07.08 Dan [7.1]
;;; : * Added the new :tracking-clear parameter from the vision module.
;;; 2016.07.20 Dan
;;; : * Updated things to use set-current-marker and clof where it was
;;; : taking (xy-loc current-marker) to deal with potentially
;;; : deleted feature chunk issues.
;;; : * Update encoding-complete and all the calls to it because it
;;; : takes an extra parameter for location vector.
;;; : * Updated the calls to get-obj-at-location since it also takes
;;; : the vector now too.
;;; 2016.11.17 Dan
;;; : * Fix the redefinition of open-exp-window to use current-mp.
;;; 2018.09.06 Dan [8.0a1]
;;; : * Start of updates for 7.x.
;;; : * Making it its own module now, and going to implement it
;;; : through mechanisms that need to be added to vision module
;;; : (hooks, monitors, device?).
;;; 2018.09.18 Dan
;;; : * Using the attn-module as the parent class, and then using the
;;; : current-marker to hold the position, last-prep instead of prep-
;;; : event, and the param-lock for everything.
;;; 2018.09.19 Dan
;;; : * Add a parameter to control whether it is enabled or not.
;;; : * Set the default values for the factor and exponent to those
;;; : used in the paper.
;;; : * Set the default frequency to .1 as used for numbers and letters
;;; : in the paper. That means with the other default parameters a
;;; : saccade of 4.5 dva (about 85 pixels on the default AGI windows)
;;; : has an encoding that takes ~85ms (the default visual encoding
;;; : time):
;;; : > (* .006 (- (log .1)) (exp (* .4 4.5)))
;;; : 0.083578974
;;; 2018.09.21 Dan
;;; : * Added parameters for the slot to use in the visual objects
;;; : to determine frequency, to set the init time of the
;;; : saccades, and to set the feature prep cost of saccades.
;;; : * Set-eye-loc notifies the devices of the position -- there's
;;; : always an eye position even if attention is cleared.
;;; : * Can't use last-prep since that's part of the general pm
;;; : style handling code so need to put prep-event back in.
;;; : * Generate a signal for monitoring purposes when the eye
;;; : moves called "current-eye-location" passed the new x and y
;;; : values.
;;; 2018.09.24 Dan
;;; : * Don't need to distinguish whether there's an object there or
;;; : not -- absence of a target just means default frequency at
;;; : this point. May want a separate parameter for that in the
;;; : future.
;;; : * Need to handle state error queries since the generic method
;;; : doesn't.
;;; 2019.02.22 Dan [8.1a1]
;;; : * Don't throw out the z component in the current marker, and
;;; : just compute the angles instead of going to pixels for the
;;; : distances. Assuming no noise in z dimension and that there's
;;; : no additional cost for change in z -- the subtended angle is
;;; : all that matters.
;;; : * Sending all three values to the set-eye-loc command, and
;;; : assuming default distance when only two values provided to
;;; : set-eye-location.
;;; : * The eyeloc signal now also gets all three.
;;; : * Switched to using tertiary reset to get ppi and viewing
;;; : distance after model params set.
;;; : * Don't compute r-theta and saccade separately, just create
;;; : the saccade immediately and store the target point in it
;;; : (using a num-to-prepare to ingore the extra feature).
;;; 2020.01.10 Dan [8.1a2]
;;; : * Removed the #' and lambdas from the module interface
;;; : functions since that's not allowed in the general system
;;; : now.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled since it's not needed
;;; : and results in warnings in SBCL.
;;; 2022.03.24 Dan [8.2a1]
;;; : * Realized that there were two different current-eye-location
;;; : commands -- the signal it generates when the position
;;; : changes and one to get the current position. Because the
;;; : signal was added first the remote command for getting the
;;; : position didn't work.
;;; : Now, the signal is named new-eye-location and the command
;;; : for getting the position explicitly is current-eye-location
;;; : to match the function.
;;; : * Added a history recorder so one can get the fixation data
;;; : out fairly easily. The data stream is called
;;; : "emma-fixations" and the data it reports is a list of
;;; : three item lists. The first item is the time in ms of the
;;; : start of a fixation (when the eye stoped moving). The
;;; : second element is the time in ms when a saccade to move
;;; : from that fixation starts (determined by the end of
;;; : preparation/start of initiation). The third element is a
;;; : list of the x, y, and z position of the eye for the
;;; : fixation. The list is in order by time of fixation with
;;; : the first list being the fixation that was ongoing when
;;; : the data recording started and the last is for the current
;;; : fixation, which will have a second value of -1 if it is
;;; : "ongoing" i.e. no saccade has started to end it.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(require-compiled "GENERAL-PM")
;;; Note:
;;; This module's operation depends upon the get-obj-at-location method from the
;;; default vision module code which is not a documented command.
(defclass emma-vis-mod (attn-module)
((freq-ht :accessor freq-ht :initarg :freq-ht
:initform (make-hash-table :test 'equalp))
(enc-factor :accessor enc-factor :initarg :enc-factor )
(enc-exponent :accessor enc-exponent :initarg :enc-exponent)
(base-exe :accessor base-exe :initarg :base-exe)
(sacc-rate :accessor sacc-rate :initarg :sacc-rate)
(shift-start :accessor shift-start :initarg :shift-start :initform 0)
(shift-duration :accessor shift-duration :initarg :shift-duration :initform nil)
(shift-target :accessor shift-target :initarg :shift-target :initform nil)
(next-loc :accessor next-loc :initform nil) ;;holds the next landing loc
(show-focus-p :accessor show-focus-p :initform nil)
(default-freq :accessor default-freq)
(spot-color :accessor spot-color)
(freq-feature :accessor freq-feature)
(enabled :accessor enabled)
(encoded :accessor encoded)
(final-shift :accessor final-shift)
(current-feat :accessor current-feat)
(current-scale :accessor current-scale)
(prep-event :accessor prep-event)
(save-history :accessor save-history :initform nil)
(history-data :accessor history-data :initform nil))
(:default-initargs
:name :emma
:version-string "8.1a2"
:current-marker #(0 0 1)))
(defun emma-detect-device-install (device)
(let ((emma (get-module :emma)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(when (and (enabled emma) (show-focus-p emma) (spot-color emma))
(notify-device device (list "eyeloc" (px (current-marker emma)) (py (current-marker emma)) (pz (current-marker emma)) (color->name (spot-color emma) "blue"))))))))
(add-act-r-command "emma-detect-device-install" 'emma-detect-device-install "Monitor for installing-vision-device to send eye location from EMMA. Do not call.")
(monitor-act-r-command "installing-vision-device" "emma-detect-device-install")
(add-act-r-command "new-eye-location" nil "Signal indicating the EMMA module's eye position has changed. Params: x y z")
(defmethod set-eye-loc ((emma emma-vis-mod) (newloc vector))
(bt:with-recursive-lock-held ((param-lock emma))
(if (= (length newloc) 2)
(setf (current-marker emma)
(vector (px newloc) (py newloc)
(* (get-parameter-value :viewing-distance)
(get-parameter-value :pixels-per-inch))))
(if (= (length newloc) 3)
(setf (current-marker emma) newloc)
(progn
(print-warning "Invalid position ~s in call to set-eye-loc position not changed.")
(return-from set-eye-loc))))
(dispatch-apply "new-eye-location" (px (current-marker emma)) (py (current-marker emma)) (pz (current-marker emma)))
(when (show-focus-p emma)
(awhen (spot-color emma)
;; send window handler messages
;; There's always an eye position even when not an attended location
(let ((update-list
(list "eyeloc" (px (current-marker emma)) (py (current-marker emma)) (pz (current-marker emma)) (color->name it "blue"))))
(dolist (d (current-devices "vision"))
(notify-device d update-list)))))
(when (save-history emma)
(push-last (list (mp-time-ms) -1 (coerce (current-marker emma) 'list)) (history-data emma)))))
(defun emma-clear-action ()
(let ((emma (get-module :emma)))
(when emma ;; could check enabled, but that's probably about the same cost as the setf anyway...
(bt:with-recursive-lock-held ((param-lock emma))
;; can't stop current eye movement but clear the saved features
(setf (last-prep emma) nil)))))
(add-act-r-command "emma-clear-action" 'emma-clear-action "Monitor for visual-clear signal in EMMA. Do not call.")
(monitor-act-r-command "visual-clear" "emma-clear-action")
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Saccade movement style
(defStyle saccade () r theta trgt new-loc)
;;; Don't count the new-loc slot which is only for
;;; internal bookkeeping purposes.
(defmethod num-to-prepare ((sacc saccade))
3)
;;; COMPUTE-EXEC-TIME [Method]
;;; Date : 01.05.09
;;; Description : Execution time is the sum of the base execution time and
;;; : the distance times the rate.
(defmethod compute-exec-time ((emma emma-vis-mod) (mvmt saccade))
(randomize-time
(bt:with-recursive-lock-held ((param-lock emma))
(+ (init-time emma) (* (r mvmt) (sacc-rate emma))
(base-exe emma)))))
;;; COMPUTE-FINISH-TIME [Method]
;;; Date : 01.05.09
;;; Description : The finish time is the same as the execution time for
;;; : saccades.
(defmethod compute-finish-time ((emma emma-vis-mod) (mvmt saccade))
(exec-time mvmt))
;;; FEAT-DIFFERENCES [Method]
;;; Date : 01.05.09
;;; Description : How many features to prepare? One for direction and one for
;;; : distance, if they're different.
(defmethod feat-differences ((s1 saccade) (s2 saccade))
(let ((nfeats 0))
(unless (distance= (r s1) (r s2)) (incf nfeats))
(unless (direction= (theta s1) (theta s2)) (incf nfeats))
nfeats))
;;; TOTAL-TIME [Method]
;;; Date : 01.05.09
;;; Description : The total time for a saccade is the simple sum of the
;;; : prep time and the execution time.
(defmethod total-time ((sacc saccade))
(+ (fprep-time sacc) (exec-time sacc)))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Module-level stuff
(defun emma-attention-hook (current-loc new-loc feat-chunk scale)
(declare (ignore current-loc))
(let ((emma (get-module :emma))
(end-loc (coerce new-loc 'vector)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(when (enabled emma)
;; interrupt an ongoing preparation unless
;; it's also executing now as well.
(unless (eq 'BUSY (exec-s emma))
(awhen (prep-event emma)
(delete-event it))
(setf (prep-event emma) nil))
;; we need to know what's there to compute the encoding time
;; and for that we're going to rely on an undocumented function
;; in the vision module for getting that information.
(setf (current-feat emma) feat-chunk)
(setf (current-scale emma) scale)
(let ((return-obj (get-obj-at-location (get-module :vision) feat-chunk end-loc scale)))
;; doesn't matter anymore if there's something there or not
;; either case works the same
(let* ((start-loc (next-destination emma))
(sacc (compute-saccade-r-theta emma start-loc end-loc)))
(change-state emma :proc 'BUSY)
(schedule-event-now 'change-state :params (list emma :proc 'busy) :module :emma :output nil :priority :max)
(setf (shift-duration emma) (recog-time emma return-obj sacc))
;; don't need the old chunk anymore
(awhen (shift-target emma) (purge-chunk-fct it))
(setf (shift-target emma) return-obj)
(setf (final-shift emma) end-loc)
(initiate-eye-move emma (shift-duration emma) sacc))))))
t))
(defgeneric next-destination (emma)
(:documentation "Returns the next landing location for EMMA."))
(defmethod next-destination ((emma emma-vis-mod))
(if (eq 'FREE (exec-s emma))
(current-marker emma)
(next-loc emma) ;;; mjs since no more input-q, get from eye-mod, saved by complete-eye-move
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; INITIATE-EYE-MOVE [Method]
;;; Date : 01.05.09
;;; Description : First, build the actual saccade movement itself. This is a
;;; : CLOS object whose class is generated by the DEFSTYLE call in
;;; : this file. Do all the state changes and queue up the
;;; : preparation complete notice, which will then generate an
;;; : eye movement. Now, we only want to queue the FOCUS-ON when
;;; : the object will be recognized before the eye movement is
;;; : complete, so do that check and queue that event if necessary.
(defgeneric initiate-eye-move (emma recog-time sacc)
(:documentation "Given a recognition time and a movement spec, begin an eye movement."))
(defmethod initiate-eye-move ((emma emma-vis-mod) (recog-time number) (sacc saccade))
(bt:with-recursive-lock-held ((param-lock emma))
(let ()
(setf (trgt sacc) (shift-target emma))
;; always start the preparation of the eye move
(setf (shift-start emma) (mp-time-ms))
(change-state emma :prep 'BUSY)
(schedule-event-now 'change-state :params (list emma :prep 'busy) :module :emma :output nil :priority :max)
(setf (last-prep emma) sacc)
(setf (prep-event emma) ;;mjs
(schedule-event-relative (seconds->ms (max 0 (fprep-time sacc))) 'PREPARATION-COMPLETE
:time-in-ms t
:destination :emma
:module :emma
:output 'medium
:details (concatenate 'string "Preparation-complete " (write-to-string (trgt sacc)))))
;; only sometimes schedule the encoding complete
(if (<= recog-time (total-time sacc))
(progn
(schedule-encoding-complete (max 0 recog-time))
(setf (encoded emma) t))
(setf (encoded emma) nil)))))
;;;mjs after method to clear prep event
(defmethod preparation-complete :after ((emma emma-vis-mod))
(bt:with-recursive-lock-held ((param-lock emma))
(setf (prep-event emma) nil)
(when (save-history emma)
(awhen (history-data emma)
(setf (second (car (last it))) (mp-time-ms))))))
;;; COMPLETE-EYE-MOVE [Method]
;;; Date : 01.05.09
;;; Description : When an eye movement completes:
;;; : [1] Update the module's state.
;;; : [2] Compute the new recognition time for the target based
;;; : on the new distance.
;;; : [3] Initiate an eye move. Note that this movement should
;;; : die if recog time based on the eye's new location is
;;; : small.
(defgeneric complete-eye-move (emma marker xyloc)
(:documentation "Called when an eye movement completes to handle all the updating."))
(defmethod complete-eye-move ((emma emma-vis-mod) (trgt symbol) (xyloc vector))
;; handle the module-level stuff
(set-eye-loc emma xyloc)
;; when we're still moving attention to the same target, we might need
;; to generate another shift.
(bt:with-recursive-lock-held ((param-lock emma))
(when (null (encoded emma)) ;; don't care about the target anymore
;; (eq trgt (shift-target emma)))
(let* ((new-target (get-obj-at-location (get-module :vision) (current-feat emma) (final-shift emma) (current-scale emma)))
(start-loc (current-marker emma))
(end-loc (final-shift emma))
(sacc (compute-saccade-r-theta emma start-loc end-loc))
(new-duration
(* (recog-time emma new-target sacc)
(- 1 (/ (ms->seconds (- (mp-time-ms) (shift-start emma))) ;;mjs pm-time
(shift-duration emma))))))
;; don't need the old chunk anymore
(awhen (shift-target emma) (purge-chunk-fct it))
(setf (shift-target emma) new-target)
(setf (shift-start emma) (mp-time-ms))
(setf (shift-duration emma) new-duration)
(initiate-eye-move emma new-duration sacc))))
(finish-movement emma (last-prep emma)))
;;; PERFORM-MOVEMENT [Method]
;;; Date : 01.05.09
;;; Description : Performing the movement simply involves figuring out when
;;; : to call COMPLETE-EYE-MOVE and updating the eye location.
(defmethod perform-movement ((emma emma-vis-mod) (sacc saccade))
(change-state emma :exec 'BUSY)
(schedule-event-now 'change-state :params (list emma :exec 'busy) :module :emma :output nil :priority :max)
(bt:with-recursive-lock-held ((param-lock emma))
(let ()
(setf (next-loc emma) (new-loc sacc))
(schedule-event-relative (seconds->ms (min (max 0 (exec-time sacc)) (init-time emma))) 'initiation-complete
:time-in-ms t :destination :emma :module :emma)
(schedule-event-relative (seconds->ms (max 0 (exec-time sacc))) 'COMPLETE-EYE-MOVE ;;;mjs
:time-in-ms t
:destination :emma
:module :emma
:params `(,(trgt sacc) ,(new-loc sacc))
:output 'medium
:details (concatenate 'string "Complete-eye-movement " (write-to-string (trgt sacc)) " " (write-to-string (new-loc sacc)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defgeneric compute-saccade-r-theta (emma start-loc end-loc)
(:documentation "Adds gaussian noise to <end-loc> and returns r-theta vector for saccade destination."))
(defmethod compute-saccade-r-theta ((emma emma-vis-mod) (start-loc vector) (end-loc vector))
(let* ((stddev (* 0.1 (dist start-loc end-loc)))
(end-loc-noisy
(vector (round (add-gaussian-noise (px end-loc) stddev))
(round (add-gaussian-noise (py end-loc) stddev))
(pz end-loc)))
(sacc-mvmt (make-instance 'saccade
:r (angle-between-vectors start-loc end-loc-noisy)
:theta (atan (- (py start-loc) (py end-loc)) ;; y coords are reversed since - is up
(- (px end-loc) (px start-loc)))
:new-loc end-loc-noisy)))
(setf (fprep-time sacc-mvmt)
(randomize-time (compute-prep-time emma sacc-mvmt)))
(setf (exec-time sacc-mvmt)
(compute-exec-time emma sacc-mvmt))
sacc-mvmt))
(defgeneric recog-time (emma obj sacc)
(:documentation "Based on Dario's equation, compute the recognition
time for an object given the displacement from the current POR."))
(defmethod recog-time ((emma emma-vis-mod) obj (sacc saccade))
(let ((freq (object-frequency emma obj))
)
(bt:with-recursive-lock-held ((param-lock emma))
(randomize-time (* (enc-factor emma)
(- (log freq))
(exp (* (r sacc) (enc-exponent emma))))))))
;;; OBJECT-FREQUENCY [Method]
;;; Description : Use current default value if no entry.
(defgeneric object-frequency (emma obj)
(:documentation "Compute the frequency of ocurrence of a visual
object, which is used to compute the recognition time."))
(defmethod object-frequency ((emma emma-vis-mod) obj)
(bt:with-recursive-lock-held ((param-lock emma))
(aif (and obj
(gethash (fast-chunk-slot-value-fct obj (freq-feature emma)) (freq-ht emma)))
it
(default-freq emma))))
(defgeneric register-obj-freq (emma name freq)
(:documentation "Store a frequency for a particular symbol."))
(defmethod register-obj-freq ((emma emma-vis-mod) name freq)
(bt:with-recursive-lock-held ((param-lock emma))
(setf (gethash name (freq-ht emma)) freq)))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Utilities
(defun add-gaussian-noise (x stddev)
"Adds pseudo-Gaussian noise to mean x with a given stddev."
(let* ((v (* stddev stddev))
(s (/ (sqrt (* 3.0 v)) pi)))
(+ x (if (zerop s) 0 (act-r-noise s))))) ;;;mjs
;;;; ---------------------------------------------------------------------- ;;;;
;;;; toplevel stuff
(defun register-feature-frequency (feature frequency)
"Register the frequency of an arbitrary value."
(let ((emma (get-module :emma)))
(when emma
(if (and feature (numberp frequency) (<= 0 frequency 1))
(register-obj-freq emma feature frequency)
(print-warning "Register-feature-frequency requires a feature and a frequency between 0 and 1, but given ~s and ~s." feature frequency)))))
(defun set-eye-location (loc)
(let ((emma (get-module :emma)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(if (enabled emma)
(if (and (listp loc) (>= 3 (length loc) 2))
(progn
(set-eye-loc emma (coerce loc 'vector))
loc)
(print-warning "Location for set-eye-location must be a list with 2 or 3 values, but given ~s" loc))
(print-warning "EMMA module is not enabled when trying to set-eye-location."))))))
(defun current-eye-location ()
(let ((emma (get-module :emma)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(if (enabled emma)
(coerce (current-marker emma) 'list)
(print-warning "EMMA module is not enabled for current-eye-location."))))))
(add-act-r-command "register-feature-frequency" 'register-feature-frequency "Set the frequency of visual features which have the indicated value. Params: value frequency")
(add-act-r-command "set-eye-location" 'set-eye-location "Set the current position of the model's eye for EMMA. Params: location")
(add-act-r-command "current-eye-location" 'current-eye-location "Get the current position of the model's eye from EMMA. No params")
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Init stuff
;;;mjs create EMMA module
(defun create-emma-module (model-name)
(declare (ignore model-name))
(make-instance 'emma-vis-mod))
(defmethod reset-emma-module ((emma emma-vis-mod))
(reset-pm-module emma)
(bt:with-recursive-lock-held ((param-lock emma))
(setf (shift-start emma) 0)
(setf (shift-target emma) nil)
(setf (last-prep emma) nil)
(setf (prep-event emma) nil)
(setf (next-loc emma) nil)
(setf (encoded emma) nil)
(setf (final-shift emma) nil)
(setf (current-marker emma)
(vector 0 0 (* (get-parameter-value :viewing-distance)
(get-parameter-value :pixels-per-inch))))
(setf (history-data emma)
(if (save-history emma)
(list (list 0 -1 (coerce (current-marker emma) 'list)))
nil))
(clrhash (freq-ht emma))))
(defun emma-query (emma buffer slot value)
(cond ((and (eq slot 'state) (eq value 'error))
nil)
(t (generic-state-query emma buffer slot value))))
(defun params-emma-module (emma param)
(bt:with-recursive-lock-held ((param-lock emma))
(if (consp param)
(case (car param)
(:emma
(if (cdr param)
(unless (eq 'emma-attention-hook (get-parameter-value :visual-encoding-hook))
(set-parameter-value :visual-encoding-hook 'emma-attention-hook))
(when (eq 'emma-attention-hook (get-parameter-value :visual-encoding-hook))
(set-parameter-value :visual-encoding-hook nil)))
(setf (enabled emma) (cdr param)))
(:saccade-feat-time
(setf (feat-prep-time emma) (cdr param)))
(:SACCADE-INIT-TIME
(setf (init-time emma) (cdr param)))
(:VISUAL-ENCODING-FACTOR
(setf (enc-factor emma) (cdr param)))
(:VISUAL-ENCODING-EXPONENT
(setf (enc-exponent emma) (cdr param)))
(:EYE-SACCADE-RATE
(setf (sacc-rate emma) (cdr param)))
(:SACCADE-BASE-TIME
(setf (base-exe emma) (cdr param)))
(:vis-obj-freq
(setf (default-freq emma) (cdr param)))
(:show-focus
;; if it was on erase the spot
(when (and (show-focus-p emma) (null (cdr param)) (spot-color emma))
(dolist (d (current-devices "vision"))
(notify-device d (list "cleareyeloc"))))
(setf (show-focus-p emma) (cdr param)))
(:eye-spot-color
;; if it was on erase the spot
(when (and (show-focus-p emma) (null (cdr param)) (spot-color emma))
(dolist (d (current-devices "vision"))
(notify-device d (list "cleareyeloc"))))
(setf (spot-color emma) (cdr param)))
(:freq-feature
(setf (freq-feature emma)
(if (stringp (cdr param))
(string->name (cdr param))
(cdr param)))))
(case param
(:emma
(enabled emma))
(:saccade-feat-time
(feat-prep-time emma))
(:SACCADE-INIT-TIME
(init-time emma))
(:VISUAL-ENCODING-FACTOR
(enc-factor emma))
(:VISUAL-ENCODING-EXPONENT
(enc-exponent emma))
(:EYE-SACCADE-RATE
(sacc-rate emma))
(:SACCADE-BASE-TIME
(base-exe emma))
(:vis-obj-freq
(default-freq emma))
(:eye-spot-color
(spot-color emma))
(:freq-feature
(freq-feature emma))))))
(defun emma-buffer-status ()
(print-module-status (get-module :emma)))
(defun eye-spot-color-value-test (x)
(or (tornil x) (symbolp x) (stringp x)))
(defun freq-feature-value-test (x)
(or (symbolp x) (stringp x)))
(define-module-fct :emma
(list (define-buffer-fct 'emma ;; need a buffer for query and module state info
:queries '(modality preparation execution processor last-command)
:status-fn 'emma-buffer-status))
(list
(define-parameter :emma :valid-test 'tornil :warning "T or nil" :default-value nil :documentation "enable the EMMA extension for the vision module")
(define-parameter :show-focus :owner nil)
(define-parameter :VISUAL-ENCODING-FACTOR
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.006
:documentation "Visual encoding time factor (K)")
(define-parameter :VISUAL-ENCODING-EXPONENT
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.4
:documentation "Visual encoding time exponent (k)")
(define-parameter :EYE-SACCADE-RATE
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.002
:documentation "Saccade rate per degree of visual angle")
(define-parameter :SACCADE-BASE-TIME
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.020
:documentation "Base saccade time")
(define-parameter :SACCADE-INIT-TIME
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.050
:documentation "Non-labile saccade time")
(define-parameter :saccade-feat-time
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.050
:documentation "Cost to prepare each feature of a saccade")
(define-parameter :vis-obj-freq
:valid-test 'nonneg
:warning "a non-negative number"
:default-value 0.1
:documentation "Default visual object frequecny")
(define-parameter :eye-spot-color
:valid-test 'eye-spot-color-value-test
:default-value 'blue
:warning "T, NIL, a symbol, or string"
:documentation "Show the eye position in the GUI when vision shows the attention ring? T, a string, or symbol will enable, and some devices will use the value to indicate a color.")
(define-parameter :freq-feature
:valid-test 'freq-feature-value-test
:default-value 'value
:warning "a symbol or string"
:documentation "The slot of a feature's visual object which is used to determine the frequency.")
)
:version (version-string (make-instance 'emma-vis-mod))
:documentation "EMMA extension for the vision module"
:creation 'create-emma-module
:reset '(nil nil reset-emma-module)
:query 'emma-query
:params 'params-emma-module
)
;;; Functions to handle the history stream (assuming the data
;;; is recorded by the functions above).
(defun enable-emma-history ()
(let ((emma (get-module :emma)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(setf (save-history emma) t)
(push-last
(list (mp-time-ms) -1 (coerce (current-marker emma) 'list))
(history-data emma))))))
(defun disable-emma-history ()
(let ((emma (get-module :emma)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(setf (save-history emma) nil)
(awhen (history-data emma)
(setf (second (car (last it))) (mp-time-ms)))))))
(defun emma-history-status ()
(let ((emma (get-module :emma)))
(if emma
(bt:with-recursive-lock-held ((param-lock emma))
(values (save-history emma) (when (history-data emma) t) t))
(values nil nil nil))))
(defun emma-history-data ()
(let ((emma (get-module :emma)))
(when emma
(bt:with-recursive-lock-held ((param-lock emma))
(history-data emma)))))
(define-history "emma-fixations" enable-emma-history disable-emma-history emma-history-status emma-history-data)
(provide "emma")
| 45,313 | Common Lisp | .lisp | 848 | 47.698113 | 187 | 0.590886 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b0a396ab83100edf611cbd27dfad91e453bdb09a364b0dba23fe378c376d2cc6 | 14,260 | [
-1
] |
14,261 | parallel-computation.lisp | asmaloney_ACT-R/extras/parallel-computation/parallel-computation.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2013 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : parallel-computation.lisp
;;; Version : 2.0a1
;;;
;;; Description : Provides "mapcar like" functionality which can perform
;;; calculations in parallel using multiple threads using the
;;; ACT-R uni-files functions. The functions being used for
;;; mapping must be arity 1.
;;;
;;; Bugs :
;;;
;;; To do : [ ] More testing, both for performance and reliability.
;;;
;;; ----- History -----
;;; 2013.10.14 Dan
;;; : * Initial creation.
;;; 2013.10.29 Dan
;;; : * Update some of the docs after running some performance tests.
;;; : * Replaced the separate running functions with a single one that
;;; : takes parameters to setup the different situations.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2018.08.29 Dan [2.0a1]
;;; : * Updated to work with ACT-R 7.x using bordeaux-threads and
;;; : require-extra.
;;; 2018.08.30 Dan
;;; : * Eliminated the "out of order" options since the current
;;; : implementation always collects things in order.
;;; 2018.09.04 Dan
;;; : * Add the parallel mapcan back in since it's useful.
;;; 2018.09.06 Dan
;;; : * Instead of doing the subseq calls at the top level, just
;;; : set the indices and have the workers do it.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; This code only depends upon bordeaux-threads which means it could be use
;;; independently of ACT-R, but the assumption here is that it will be used with
;;; ACT-R 7.x which is also using bordeaux-threads.
;;;
;;; To use this the best option is to use require-extra:
;;;
;;; (require-extra "parallel-computation")
;;;
;;; in any file which uses the functions defined here.
;;;
;;; The basic procedure for using this is to create a "team" of workers. Then, that
;;; team, a function, and list of parameters can be passed to one of the parallel
;;; running functions. The parallel function will create a list of results based
;;; on the function and parameters provided by breaking the parameters into sublists
;;; and having the workers of the team process those sublists in parallel. The return
;;; values from the parallel function will then be a list of results and an indication
;;; of whether there was any error. When the team is no longer needed it should be
;;; released to end the worker processes that were created.
;;;
;;; An important thing to keep in mind is that the function passed to a parallel
;;; running command must be "thread safe". The most important aspect of that is
;;; that it can't modify non-local data without appropriate protection. It also
;;; shouldn't call any of the parallel running code, especially with the same team.
;;; Any input or output operations are also likely going to need to be locked if
;;; the same stream is being used (for example printing to *standard-output*).
;;;
;;; With respect to ACT-R commands, those which are published in the reference manual
;;; are thread-safe, but if you use non-documented ACT-R commands they may or may
;;; not be thread-safe and should be thoroughly investigated before using them in
;;; parallel operations. Note however that since the ACT-R commands are thread safe
;;; if you're using the same ACT-R command in parallel with itself it's possible that
;;; its locking to protect things could effectively force those parallel instance to
;;; work serially anyway which might eliminate any benefit from the parallelism.
;;;
;;; It is possible to use the same team for different tasks, and that is the easiest
;;; way to use this (similar to the parallel-models extra). However, if different
;;; tasks have different performance issues then different sized teams may be more
;;; efficient for handling those different tasks in parallel. Also, while it is
;;; technically possible to have a team of workers each of which uses a separate team
;;; of workers to further subdivide a task, using the system in that fashion was not
;;; how it was intended and recursively using the parallel commands has not been tested
;;; and is not recommended (recursively trying to use the same team of workers is not
;;; possible for what should be obvious reasons).
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;; create-parallel-team
;;;
;;; defun create-parallel-team (name size)
;;;
;;; name must be a string which is used to create the names for the worker processes
;;; and associated control items.
;;; size must be a positive integer indicating the number of workers to create.
;;;
;;; If the parameters provided are appropiate it creates and returns a team of workers
;;; which can be used for running the parallel-* functions. Size processes for the
;;; workers will be created and waiting until there is something for them to perform.
;;; Those processes will remain alive until the team is released or killed.
;;; If the parameters provided are not appropriate then it prints a warning and returns
;;; nil without creating any processes.
;;;
;;; When creating a team one should probably create fewer workers than there are
;;; processors/cores in the machine since there will be the main process and likely
;;; other Lisp processes (gc, GUI control, repl, etc) also running. That way
;;; workers aren't fighting for processor time, but there may be situations where
;;; more workers than processors may show an improvement (possibilities would be
;;; if memory accessing is a limiting factor or the function runs so fast that
;;; workers can finish while others are still being started or waiting to be
;;; collected).
;;;
;;; release-parallel-team
;;; kill-parallel-team
;;;
;;; defun release-parallel-team (team)
;;; defun kill-parallel-team (team)
;;;
;;; team must be a team that was returned from create-parallel-team.
;;;
;;; These functions end the worker threads which were created with the team
;;; provided and mark the team as unusable. Release-parallel-team is the
;;; recommended way to do so and should be called while the team is not
;;; actively being used first to have the team cleanly end the processes.
;;; However, if the worker processes for a team are not terminating because
;;; of an error in a parallel function which was not handled or for any other
;;; reason do not seem to exit cleanly, then kill-parallel-team can be used
;;; to attempt to explicitly kill the processes directly.
;;;
;;; If release-parallel-team is passed a team which has not yet been released
;;; then it will return t after releasing the worker processes, otherwise it
;;; will print a warning and return nil.
;;; If kill-parallel-team is passed a team it will try to kill the worker
;;; processes and return t, otherwise it will print a warning and return nil.
;;;
;;; parallel-mapcar
;;; parallel-mapcan
;;; parallel-funcall
;;;
;;; defun parallel-mapcar (team function params &rest more-params)
;;; defun parallel-mapcan (team function params &rest more-params)
;;; defun parallel-funcall (team function params &rest more-params)
;;;
;;; team must be a team that was returned from create-parallel-team.
;;; function must be a function or function name.
;;; params must be a list of parameters which will be passed to the function.
;;; more-params can be additional lists of parameters to pass to the function.
;;;
;;; The parallel-* functions are used to carry out the execution of the function
;;; provided with the params given, distributed across the workers of the team.
;;; How the params are passed to the function and what is returned depends on which
;;; of the parallel-* functions is called (the differences will be described below).
;;; All of the parallel-* functions return two values.
;;;
;;; If team is a team returned from create-parallel-team which has not yet been
;;; released or killed, function is a function or symbol which names a function,
;;; and params and more-params are lists of items all of the same length (a
;;; simplification requirement for now) then those lists of items will be split
;;; into m sublists, where m=min(workers in team, length(params)), of equal length
;;; (or as close to equal as possible). Each of those lists of sublists will be
;;; given to a worker to process with function. The results of the workers will be
;;; appended together and returned as the first value from a parallel-* function.
;;;
;;; The second value returned from a parallel-* function indicates whether or not
;;; there was an error either in the parameters provided or the execution of the
;;; workers. If there is an error then a warning will be printed and the second
;;; value will be t. If there are no errors then the second value will be nil.
;;; If the second value is t then the first value returned is likely not valid and
;;; should probably be discarded.
;;;
;;; Here are how the different parallel-* functions use the provided function
;;; and collect the results.
;;;
;;; Parallel-mapcar
;;;
;;; Each worker creates a list of results by using (mapcar function params(i) more-params[0][i] ...)
;;; where i is an index of the sublists by worker and all of the lists provided in more-params
;;; are included. Those resulting lists are appended together such that the overall order of
;;; the resulting list matches the order of the original params list, and that list is returned
;;; as the first value. Thus the result is the same as calling (mapcar function params more-params[0] ...)
;;; (assuming that function operating sequentially is the same as operating in parallel).
;;;
;;; Parallel-mapcan
;;;
;;; Each worker creates a list of results by using (mapcan function params(i) more-params[0][i] ...)
;;; where i is an index of the sublists by worker and all of the lists provided in more-params
;;; are included. Those resulting lists are appended together such that the overall order of
;;; the resulting list matches the order of the original params list, and that list is returned
;;; as the first value. Thus the result is the same as calling (mapcan function params more-params[0] ...)
;;; (assuming that function operating sequentially is the same as operating in parallel).
;;;
;;; Parallel-funcall
;;;
;;; Each worker creates a result using (funcall function params(i) more-params[0][i] ...)
;;; i.e. the function will be passed the entire sublists as its parameters. The
;;; results of those calls are appened together (in the order of the sublists) to
;;; produce the first result returned. Because the results are appended the
;;; function provided should always return a list.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Considered some existing libraries which do this sort of thing, but had problems
;;; with them in some Lisps and don't want to deal with issues like that so produced
;;; a simple mechanism using bordeaux-threads directly.
;;;
;;; It splits the list upfront so that it's divided across all of the
;;; workers initially instead of passing off one item at a time to the workers
;;; to handle since that seems to be more efficient in most situations because the
;;; locking/unlock for passing and returning values from a worker is costly.
;;;
;;; It uses ignore-errors to prevent errors in the functions from breaking
;;; the workers. If there are any errors in a worker it stops processing the
;;; remainder of its parameter list(s) and just signals an error result. That
;;; doesn't stop any other workers which are processing other parts of the
;;; parameter list(s).
;;;
;;; The workers have an unwind-protect which should signal the team controller
;;; when a worker thread has termiated unexpectedly, but if a worker thread is
;;; killed in a way that doesn't respect unwind-protect the whole team could be
;;; stuck if that happens during the processing of items.
;;;
;;; There's no protection in the workers to ensure the code they're using is
;;; itself thread safe. That's up to the user to ensure, and things like writing
;;; output to the REPL can certainly be problematic.
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defstruct p_team "A group of workers for parallel tasks"
name workers state target current lock cv size)
(defstruct p_worker "The parallel worker structure"
name process state function result input cv lock mechanism start end)
(defun p_worker-thread-function (worker team)
(setf (p_worker-state worker) :started)
(bt:with-lock-held ((p_team-lock team))
(pushnew worker (p_team-current team))
(bt:condition-notify (p_team-cv team)))
(unwind-protect
(progn
(bt:acquire-lock (p_worker-lock worker))
(loop
(bt:condition-wait (p_worker-cv worker) (p_worker-lock worker))
(setf (p_worker-state worker) :working)
(case (p_worker-mechanism worker)
(:exit
(setf (p_worker-state worker) :done)
(return))
(t
(multiple-value-bind (value condition)
; simply apply the indicated mechanism to the function and values provided
(ignore-errors (apply (p_worker-mechanism worker) (p_worker-function worker)
(mapcar
(lambda (x)
(subseq x (p_worker-start worker) (p_worker-end worker)))
(p_worker-input worker))
))
; if there's a problem send the condition back
; otherwise return the resulting list
(if (subtypep (type-of condition) 'condition)
(setf (p_worker-state worker) :fail
(p_worker-result worker) condition)
(setf (p_worker-state worker) :success
(p_worker-result worker) value)))
(bt:with-lock-held ((p_team-lock team))
(pushnew worker (p_team-current team))
(bt:condition-notify (p_team-cv team)))))))
;; just notify the team when exiting...
;; expected for a clean exit
(bt:with-lock-held ((p_team-lock team))
(pushnew worker (p_team-current team))
(bt:condition-notify (p_team-cv team)))))
(defun create-parallel-team (name size)
(if (and (stringp name) (integerp size) (plusp size))
(let ((team (make-p_team :name name :workers nil :state :creation :target size :current nil
:size size :lock (bt:make-lock name) :cv (bt:make-condition-variable :name name))))
(bt:acquire-lock (p_team-lock team))
(dotimes (i size)
(let* ((w-name (format nil "~a-~d" name i))
(worker (make-p_worker :name w-name :state :creating :cv (bt:make-condition-variable :name w-name)
:lock (bt:make-lock w-name)
)))
(setf (p_worker-process worker)
(bt:make-thread (lambda () (p_worker-thread-function worker team)) :name w-name))
(push-last worker (p_team-workers team))))
(loop
(bt:condition-wait (p_team-cv team) (p_team-lock team))
(when (= (length (p_team-current team)) (p_team-target team))
(return)))
(setf (p_team-state team) :ready)
(bt:release-lock (p_team-lock team))
team)
(if (stringp name)
(print-warning "Create-parallel-team requires a positive integer for the size, but given ~s" size)
(print-warning "Create-parallel-team requires a string for the name, but given ~s" name))))
(defun run-parallel-team (team function params mechanism)
(cond ((not (p_team-p team))
(values (print-warning "Must provide a team to run instead of ~s" team) t))
((not (or (functionp function) (fboundp function)))
(values (print-warning "Must provide a valid function instead of ~s" function) t))
(t
(let ((state (bt:with-lock-held ((p_team-lock team)) (p_team-state team))))
(cond ((not (eq state :ready))
(values (print-warning "Team ~s is not currently ready to run." (p_team-name team)) t))
((not (every (lambda (x)
(eq :started (p_worker-state x)))
(p_team-workers team)))
(values (print-warning "Some worker on team ~s is in an unexpected state and team cannot be used." (p_team-name team)) t))
((not (every (lambda (x)
(= (length x) (length (first params))))
params))
(values (print-warning "All parameter lists must be the same length but given ~s." params) t))
(t
(bt:with-lock-held ((p_team-lock team))
(setf (p_team-state team) :busy))
(unwind-protect
(let* ((n (length (first params)))
(m (min n (p_team-size team)))
(size (floor n m))
(sizes (make-list m :initial-element size)))
(unless (= n (* m size))
(dotimes (i (- n (* m size)))
(incf (nth i sizes))))
(bt:with-lock-held ((p_team-lock team))
(setf (p_team-current team) nil
(p_team-target team) m))
(let ((start 0))
(dotimes (i m)
(let ((worker (nth i (p_team-workers team))))
(bt:with-lock-held ((p_worker-lock worker))
(setf (p_worker-function worker) function)
(setf (p_worker-mechanism worker) mechanism)
(setf (p_worker-input worker) params)
(setf (p_worker-start worker) start)
(setf (p_worker-end worker) (+ start (nth i sizes)))
(incf start (nth i sizes))
(bt:condition-notify (p_worker-cv worker))))))
(bt:acquire-lock (p_team-lock team))
(while (< (length (p_team-current team)) m)
(bt:condition-wait (p_team-cv team) (p_team-lock team)))
(bt:release-lock (p_team-lock team))
(let ((used-workers (subseq (p_team-workers team) 0 m)))
(prog1
(cond ((not (every (lambda (x) (eq (p_worker-state x) :success)) used-workers))
(dolist (x used-workers)
(when (eq (p_worker-state x) :fail)
(print-warning "Worker ~s reports failure: ~/print-error-message/" (p_worker-name x) (p_worker-result x))))
(values nil t))
((not (every (lambda (x) (listp (p_worker-result x))) used-workers))
(print-warning "One or more workers returned a value which is not a list. Cannot append results.")
(values (mapcar 'p_worker-result used-workers) t))
(t (values (reduce 'append (mapcar 'p_worker-result (subseq (p_team-workers team) 0 m))) nil)))
(dolist (x used-workers)
(bt:with-lock-held ((p_worker-lock x))
(setf (p_worker-state x) :started))))))
(bt:with-lock-held ((p_team-lock team))
(setf (p_team-state team) :ready)))))))))
(defun parallel-mapcar (team function params &rest more-params)
(run-parallel-team team function (cons params more-params) 'mapcar))
(defun parallel-funcall (team function params &rest more-params)
(run-parallel-team team function (cons params more-params) 'funcall))
(defun parallel-mapcan (team function params &rest more-params)
(run-parallel-team team function (cons params more-params) 'mapcan))
(defun release-parallel-team (team)
;; Set the exit flag and then unlock workers so they terminate by
;; returning from the function in the process instead of killing them.
(if (p_team-p team)
(let ((state (bt:with-lock-held ((p_team-lock team))
(p_team-state team))))
(if (not (eq state :ready))
(print-warning "Team ~s is not currently in the ready state and cannot be released." (p_team-name team))
(progn
(dolist (x (p_team-workers team))
(when (bt:thread-alive-p (p_worker-process x))
(bt:with-lock-held ((p_worker-lock x))
(setf (p_worker-mechanism x) :exit))
(bt:condition-notify (p_worker-cv x))))
;; don't bother waiting or checking, just
;; consider it done
(bt:with-lock-held ((p_team-lock team))
(setf (p_team-state team) :done))
t)))
(print-warning "Release-parallel-team requires a team created by create-parallel-team, but was given ~s" team)))
;; If something goes wrong may need to kill the processes.
(defun kill-parallel-team (team)
(if (p_team-p team)
(progn
(dolist (x (p_team-workers team))
(when (bt:thread-alive-p (p_worker-process x))
(ignore-errors (bt:destroy-thread (p_worker-process x)))))
(bt:with-lock-held ((p_team-lock team))
(setf (p_team-state team) :done)
(setf (p_team-workers team) nil))
t)
(print-warning "Kill-parallel-team requires a team created by create-parallel-team, but was given ~s" team)))
#|
Here's a dummy example of computing fibonacci numbers in parallel
on a Windows machine with an i7-2600 (4 cores plus hyperthreads for
8 virtual cores) running ACL with a few different team sizes.
These results may not reflect the performance of any other task
split into parallel components with these tools.
CG-USER(16): (require-extra "parallel-computation")
;;; Compiling file C:\Users\db30\Desktop\actr7.x\extras\parallel-computation\parallel-computation.lisp
;;; Writing fasl file C:\Users\db30\Desktop\actr7.x\extras\parallel-computation\parallel-computation.fasl
;;; Fasl write complete
; Fast loading C:\Users\db30\Desktop\actr7.x\extras\parallel-computation\parallel-computation.fasl
T
CG-USER(17): (defun test-fib (x) (if (<= x 1) x (+ (test-fib (1- x)) (test-fib (- x 2)))))
TEST-FIB
CG-USER(18): (compile 'test-fib)
TEST-FIB
NIL
NIL
CG-USER(19): (time (mapcar 'test-fib (make-list 30 :initial-element 40)))
; cpu time (non-gc) 54.625000 sec user, 0.000000 sec system
; cpu time (gc) 0.000000 sec user, 0.000000 sec system
; cpu time (total) 54.625000 sec user, 0.000000 sec system
; cpu time (thread) 54.625000 sec user, 0.000000 sec system
; real time 54.614000 sec (100.0%)
; space allocation:
; 0 cons cells, 56 other bytes, 0 static bytes
; Page Faults: major: 0 (gc: 0), minor: 0 (gc: 0)
(102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 ...)
CG-USER(20): (defvar *team* (create-parallel-team "size-4" 4))
*TEAM*
CG-USER(21): (time (parallel-mapcar *team* 'test-fib (make-list 30 :initial-element 40)))
; cpu time (non-gc) 73.609375 sec (00:01:13.609375) user, 0.000000 sec system
; cpu time (gc) 0.000000 sec user, 0.000000 sec system
; cpu time (total) 73.609375 sec (00:01:13.609375) user, 0.000000 sec system
; cpu time (thread) 0.000000 sec user, 0.000000 sec system
; real time 19.878000 sec (370.3%)
; space allocation:
; 0 cons cells, 56 other bytes, 0 static bytes
; Page Faults: major: 0 (gc: 0), minor: 0 (gc: 0)
(102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 ...)
CG-USER(22): (release-parallel-team *team*)
T
CG-USER(23): (setf *team* (create-parallel-team "size-8" 8))
#S(P_TEAM ...)
CG-USER(24): (time (parallel-mapcar *team* 'test-fib (make-list 30 :initial-element 40)))
; cpu time (non-gc) 96.671875 sec (00:01:36.671875) user, 0.000000 sec system
; cpu time (gc) 0.000000 sec user, 0.000000 sec system
; cpu time (total) 96.671875 sec (00:01:36.671875) user, 0.000000 sec system
; cpu time (thread) 0.000000 sec user, 0.000000 sec system
; real time 13.067000 sec (739.8%)
; space allocation:
; 0 cons cells, 56 other bytes, 0 static bytes
; Page Faults: major: 0 (gc: 0), minor: 0 (gc: 0)
(102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 ...)
CG-USER(25): (release-parallel-team *team*)
T
CG-USER(26): (setf *team* (create-parallel-team "size-16" 16))
#S(P_TEAM ...)
CG-USER(27): (time (parallel-mapcar *team* 'test-fib (make-list 30 :initial-element 40)))
; cpu time (non-gc) 95.390625 sec (00:01:35.390625) user, 0.000000 sec system
; cpu time (gc) 0.000000 sec user, 0.000000 sec system
; cpu time (total) 95.390625 sec (00:01:35.390625) user, 0.000000 sec system
; cpu time (thread) 0.000000 sec user, 0.000000 sec system
; real time 14.360000 sec (664.3%)
; space allocation:
; 0 cons cells, 56 other bytes, 0 static bytes
; Page Faults: major: 0 (gc: 0), minor: 0 (gc: 0)
(102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 102334155 ...)
CG-USER(28): (release-parallel-team *team*)
T
|#
(provide "parallel-computation")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 28,154 | Common Lisp | .lisp | 498 | 48.676707 | 148 | 0.640611 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 8cf9c084ecdf73ab1e19cea9c6ab9ec12a891939f3993bb7cc5f506a1286398c | 14,261 | [
460838
] |
14,262 | example.lisp | asmaloney_ACT-R/extras/parallel-models/example.lisp | ;;; This example shows a combination of the save-model and
;;; parallel-models extras. It runs a model to generate a
;;; few chunks in declarative memory and then save the current
;;; state to a file. That file can then either be loaded and
;;; run sequentially or multiple times in parallel returning the
;;; value of the next retrieved chunk using the functions
;;; run-m-guesses-total or run-m-guesses-total-n-at-a-time
;;; respectively.
(clear-all)
(require-extra "save-model")
(require-extra "parallel-models")
(define-model create-and-guess
(sgp :esc t :er t :bll .5 :ans .5 :v nil :rt -10)
(chunk-type goal state)
(p start
?goal>
buffer empty
?imaginal>
state free
buffer empty
==>
+imaginal>
value 1)
(p generate-next
=imaginal>
value =v
< value 5
?imaginal>
state free
==>
!bind! =n (1+ =v)
+imaginal>
value =n)
(p stop
=imaginal>
value 5
==>
+goal>
state nil)
(p guess
=goal>
state guess
?retrieval>
state free
buffer empty
==>
+retrieval>))
(defun initial-run-and-save ()
(load-act-r-model "ACT-R:extras;parallel-models;example.lisp")
(run 10)
;; Save the model to a file along with a function to run it further.
(with-open-file (f "ACT-R:extras;parallel-models;guess-model.lisp" :direction :output :if-exists :supersede :if-does-not-exist :create)
(save-chunks-and-productions f)
;; Write out the function that'll run the model multiple times and return the result of
;; the value slot from the retrieval buffer on each run.
(format f "(defun make-guesses (i)~%")
(format f " (let (result)~%")
(format f " (dotimes (n i)~%")
(format f " (reset)~%")
(format f " (sgp :v nil)~%")
(format f " (mod-focus state guess)~%")
(format f " (run-until-condition (lambda (x)~%")
(format f " (declare (ignore x))~%")
(format f " (or (buffer-read 'retrieval)~%")
(format f " (query-buffer 'retrieval '(buffer failure)))))~%")
(format f " (push (chunk-slot-value-fct (buffer-read 'retrieval) 'value) result))~%")
(format f " result))")))
(defun run-m-guesses-total (m)
(initial-run-and-save)
;; load the saved model file
(load-act-r-model "ACT-R:extras;parallel-models;guess-model.lisp" t)
(make-guesses 1000))
(defun run-m-guesses-total-n-at-a-time (m n)
(initial-run-and-save)
;; create the parallel ACT-R threads
(create-parallel-instances n)
;; load the model file into each instance
(instantiate-parallel-models "ACT-R:extras;parallel-models;guess-model.lisp")
;; Have each instance run for no more than 10 seconds and
;; run one nth of the total guesses combining all the
;; returned lists into a single list.
(flatten (run-parallel-models "make-guesses" 10 (list (round m n)))))
| 3,176 | Common Lisp | .lisp | 82 | 31.987805 | 138 | 0.611316 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | f5d141683840fb31701a8bbf1fff9ef7a227b481544b6b45012c77818cce2cbd | 14,262 | [
331985
] |
14,263 | parallel-retrieval.lisp | asmaloney_ACT-R/extras/parallel-retrieval/parallel-retrieval.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2013 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : parallel-chunks.lisp
;;; Version : 2.0a1
;;;
;;; Description : Use the parallel-computation functions to perform the find-
;;; : matching-chunk operations, declarative retrieval actions
;;; : (finding matches and computing activation), and blending
;;; : computations (if the blending module is available) in parallel.
;;;
;;; Bugs :
;;;
;;; To do : [ ] More testing.
;;;
;;; ----- History -----
;;; 2013.10.30 Dan
;;; : * Initial creation.
;;; 2013.11.14 Dan
;;; : * Added (provide "PARALLEL-CHUNKS") so this can be put into
;;; : support for use as needed.
;;; 2014.06.16 Dan [1.0a2]
;;; : * Updated with the ACT-R 6.1 functions for find and retrieval.
;;; 2014.07.07 Dan
;;; : * Updated the blending code for 6.1.
;;; 2015.06.05 Dan
;;; : * Schedule events in ms and compute-activation-latency is now
;;; : returned in ms.
;;; 2015.06.08 Dan
;;; : * Record the saved trace at the time in ms not seconds.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2016.02.12 Dan
;;; : * Upated with some changes that happened in dm and blending
;;; : code.
;;; 2016.02.26 Dan
;;; : * Fixed a potential bug with the blending code.
;;; 2018.08.31 Dan [2.0a1]
;;; : * Updated for use with 7.x, and split it into its own extra
;;; : which requires the parallel-computation extra.
;;; 2018.09.06 Dan
;;; : * Unfortunately, thread safety on chunk parameters really
;;; : causes problems for trying to parallelize activations since
;;; : partial matching and spreading activation both have issues
;;; : with trying to access the same chunks (the source and the
;;; : requested values) and base-level needs the current time.
;;; : Those end up making it less efficient than the serial
;;; : mechanism without a complete rewrite of the activation code
;;; : (and likely the chunk parameter code as well).
;;; : * Find matching chunks also seems to have some sort of collision
;;; : in ACL even with some significant rewriting although it
;;; : doesn't in CCL which means there's something implicitly
;;; : locking/blocking in ACL and I'm guessing hashtables...
;;; : * For those reasons this is not going to be updated any further
;;; : at this time and is not recommended for use.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; DO NOT USE!
;;;
;;;
;;; Very speculative replacement functions for performing some potentially costly
;;; operations in parallel.
;;;
;;; To load this the best option is to put it into the ACT-R support directory
;;; and then either call this or put it into a file which will be using the
;;; provided capabilities:
;;;
;;; (require-extra "parallel-retrieval")
;;;
;;;
;;; When enabled, this will use multiple processes when searching for matching
;;; chunks with find-matching-chunks (used by the vision module for isa visual-
;;; location requests, the blending module for blending requests, and for parallel
;;; retrieval requests which bypasses the activation trace info), when
;;; performing the activation computation for chunks which match a retrieval
;;; request, and when performing the activation and blending computations in a
;;; blending request.
;;;
;;; This is not likely to improve performance for most users.
;;;
;;; Typically the model needs to have large sets of chunks to be searched over,
;;; have a large number of chunks for which the activation needs to be computed,
;;; or have complex activation computations for the chunks to see any benefit
;;; from this to overcome the overhead of running in parallel. For the performance
;;; testing models it looks like somewhere around 50 chunks in the set to be
;;; tested was the point where performance improvements started to show up, but
;;; if the model uses blending the benefits may show up for small sets of chunks
;;; being blended if there are multiple slots receiving a blended value in the
;;; majority of the blending requests.
;;;
;;; None of the tutorial models seem to show a benefit.
;;;
;;; Parallel operation should not be used if the activation or blending traces are
;;; enabled or being saved.
;;;
;;; Because the parallel operations will not always be executed in the same order as
;;; a sequentially run model the determinism provided by setting the seed parameter
;;; doesn't exist if it's run in parallel.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(require-extra "parallel-computation")
(defvar *actr-team* nil)
(defun enable-retrieval-team (n)
(if *actr-team*
(print-warning "Retrieval team is already enabled with a size of ~d." (p_team-size *actr-team*))
(progn
(setf *actr-team* (create-parallel-team "Retrieval-team" n))
t)))
(add-act-r-command "enable-retrieval-team" 'enable-retrieval-team "Enable the parallel retrieval capabilities with a team of the indicated size. Params: <size>" t)
(defun release-retrieval-team ()
(when *actr-team*
(release-parallel-team *actr-team*)
(setf *actr-team* nil)))
(add-act-r-command "release-retrieval-team" 'release-retrieval-team "Enable the parallel retrieval capabilities with a team of the indicated size. Params: <size>" t)
(defun unlocked-chunk-slot-equal (val1 val2)
(if (eq val1 val2)
t
(let (c1 c2)
(cond (;; The real definition of this test has to lock the chunk table to avoid
;; a potential merge or change between the get-chunk calls, but that lock
;; is held during the entire find for the parallel case otherwise each
;; worker blocks the others and it's worse than sequential...
(and (setf c1 (unlocked-get-chunk val1))
(setf c2 (unlocked-get-chunk val2)))
(eq c1 c2))
((stringp val1)
(and (stringp val2) (string-equal val1 val2)))
(t (equalp val1 val2))))))
(defun unlocked-chunk-slot-not-equal (arg1 arg2)
(not (unlocked-chunk-slot-equal arg1 arg2)))
(defun unlocked-get-chunk (name)
(let ((model (current-model-struct)))
(gethash name (act-r-model-chunks-table model))))
(defun unlocked-match-chunk-spec-p (chunk-name chunk-spec
&key (=test 'chunk-slot-equal)
(-test 'chunk-slot-not-equal)
(>test 'safe>) (>=test 'safe>=)
(<test 'safe<) (<=test 'safe<=)
(variable-char #\=))
(let ((chunk (unlocked-get-chunk chunk-name)))
(cond ((null chunk)
(print-warning "~s does not name a chunk in call to match-chunk-spec-p." chunk-name))
(t
(let ((s (cond ((act-r-chunk-spec-p chunk-spec) chunk-spec)
((numberp chunk-spec) (id-to-chunk-spec chunk-spec))
(t nil))))
(if (null s)
(print-warning "~s is not a valid chunk-spec or chunk-spec id in call to match-chunk-spec-p." chunk-spec)
(let ((var (cond ((characterp variable-char) variable-char)
((and (stringp variable-char) (= (length variable-char) 1)) (char variable-char 0))
(t nil))))
(if (null var)
(print-warning "~s is not a valid variable character in call to match-chunk-spec-p." variable-char)
(progn
;; check the variable character and reprocess the spec
;; if it's not = since that may mean different slotnames are "real"
(unless (char-equal var #\=)
(setf s (reprocess-chunk-spec s var)))
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(cond
;; if the filled slots are filled and the empty slots aren't then test further
((slots-vector-match-signature (act-r-chunk-filled-slots chunk)
(act-r-chunk-spec-filled-slots s)
(act-r-chunk-spec-empty-slots s))
(handler-case (test-chunk-slots (act-r-chunk-slot-value-lists chunk)
s =test -test >test >=test <test <=test)
(error (condition)
(print-warning "Error ~S encountered in matching chunk ~s." condition chunk-name))))
(t
nil))))))))))))
(defun find-matching-chunks (chunk-spec
&key
(chunks :all) =test -test
(>test 'safe>) (>=test 'safe>=)
(<test 'safe<) (<=test 'safe<=)
(variable-char #\=))
(verify-current-model
"Find-matching-chunks called with no current model."
(let ((model (current-model-struct))
(s (cond ((act-r-chunk-spec-p chunk-spec) chunk-spec)
((numberp chunk-spec) (id-to-chunk-spec chunk-spec))
(t nil))))
(if (null s)
(print-warning "~s is not a valid chunk-spec or chunk-spec id in call to find-matching-chunks." chunk-spec)
(let ((var (cond ((characterp variable-char) variable-char)
((and (stringp variable-char) (= (length variable-char) 1)) (char variable-char 0))
(t nil))))
(if (null var)
(print-warning "~s is not a valid variable character in call to find-matching-chunks." variable-char)
(cond ((eq :all chunks)
(if *actr-team*
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(parallel-mapcan *actr-team*
(lambda (z)
(when (unlocked-match-chunk-spec-p z s
:=test (aif =test it 'unlocked-chunk-slot-equal)
:-test (aif -test it 'unlocked-chunk-slot-not-equal)
:>test >test :>=test >=test
:<test <test :<=test <=test
:variable-char var)
(list z)))
(hash-table-keys (act-r-model-chunks-table model))))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(mapcan (lambda (z)
(when (unlocked-match-chunk-spec-p z s
:=test (aif =test it 'unlocked-chunk-slot-equal)
:-test (aif -test it 'unlocked-chunk-slot-not-equal)
:>test >test :>=test >=test
:<test <test :<=test <=test
:variable-char var)
(list z)))
(hash-table-keys (act-r-model-chunks-table model))))))
((listp chunks)
(if *actr-team*
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(parallel-mapcan *actr-team*
(lambda (z)
(when (unlocked-match-chunk-spec-p z s
:=test (aif =test it 'unlocked-chunk-slot-equal)
:-test (aif -test it 'unlocked-chunk-slot-not-equal)
:>test >test :>=test >=test
:<test <test :<=test <=test
:variable-char var)
(list z)))
chunks))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(mapcan (lambda (z)
(when (unlocked-match-chunk-spec-p z s
:=test (aif =test it 'unlocked-chunk-slot-equal)
:-test (aif -test it 'unlocked-chunk-slot-not-equal)
:>test >test :>=test >=test
:<test <test :<=test <=test
:variable-char var)
(list z)))
chunks))))
(t (print-warning "~S is not a valid value for the :chunks keyword parameter to find-matching-chunks." chunks)))))))))
#|
(defun start-retrieval (dm request)
(let (esc rt rrh sact act er set-hook
mp offsets blc bll ol act-scale
sa spreading-hook w-hook sji-hook mas nsji
pm-hook ms md sim-hook cache-sim-hook
noise-hook ans lf le bl-hook)
(bt:with-lock-held ((dm-state-lock dm))
(when (dm-stuff-event dm)
(delete-event (dm-stuff-event dm))
(setf (dm-stuff-event dm) nil)))
(bt:with-lock-held ((dm-param-lock dm))
(setf
act (dm-act dm)
rt (dm-rt dm)
sact (dm-sact dm)
mp (dm-mp dm)
esc (dm-esc dm)
offsets (dm-offsets dm)
blc (dm-blc dm)
bll (dm-bll dm)
ol (dm-ol dm)
act-scale (dm-act-scale dm)
sa (dm-sa dm)
spreading-hook (dm-spreading-hook dm)
w-hook (dm-w-hook dm)
sji-hook (dm-sji-hook dm)
mas (dm-mas dm)
nsji (dm-nsji dm)
pm-hook (dm-partial-matching-hook dm)
ms (dm-ms dm)
md (dm-md dm)
sim-hook (dm-sim-hook dm)
cache-sim-hook (dm-cache-sim-hook-results dm)
noise-hook (dm-noise-hook dm)
ans (dm-ans dm)
rrh (dm-retrieval-request-hook dm)
er (dm-er dm)
set-hook (dm-retrieval-set-hook dm)
lf (dm-lf dm)
le (dm-le dm)
bl-hook (dm-bl-hook dm)))
(when rrh
(let ((id (chunk-spec-to-id request)))
(dolist (x rrh)
(dispatch-apply x id))
(release-chunk-spec-id id)))
(when sact
(bt:with-lock-held ((dm-state-lock dm))
(setf (dm-current-trace dm) (make-sact-trace :esc esc))
(setf (gethash (mp-time-ms) (dm-trace-table dm)) (dm-current-trace dm))))
(let* ((last-request (make-last-request :time (mp-time-ms) :spec request :rt rt))
(filled (chunk-spec-filled-slots request))
(empty (chunk-spec-empty-slots request))
(chunk-list
;; Parallel unlikely to be useful at this point -- few types in mem...
(if *actr-team*
(parallel-mapcan *actr-team*
(lambda (x)
(when (slots-vector-match-signature (car x) filled empty)
(copy-list (cdr x))))
(bt:with-lock-held ((dm-chunk-lock dm)) (dm-chunks dm)))
(mapcan (lambda (x)
(when (slots-vector-match-signature (car x) filled empty)
(copy-list (cdr x))))
(bt:with-lock-held ((dm-chunk-lock dm)) (dm-chunks dm))))))
(flet ((invalid (reason warnings)
(bt:with-lock-held ((dm-state-lock dm))
(setf (dm-busy dm) nil)
(setf (last-request-invalid last-request) reason)
(setf (dm-last-request dm) last-request)
)
(dolist (x warnings)
(print-warning x))
(return-from start-retrieval)))
(when (member :recently-retrieved (chunk-spec-slots request))
(let ((recent (chunk-spec-slot-spec request :recently-retrieved)))
(cond ((> (length recent) 1)
(invalid :too-many '("Invalid retrieval request." ":recently-retrieved parameter used more than once.")))
((not (or (eq '- (caar recent)) (eq '= (caar recent))))
(invalid :bad-modifier '("Invalid retrieval request." ":recently-retrieved parameter's modifier can only be = or -.")))
((not (or (eq t (third (car recent)))
(eq nil (third (car recent)))
(and (eq 'reset (third (car recent)))
(eq '= (caar recent)))))
(invalid :bad-value '("Invalid retrieval request." ":recently-retrieved parameter's value can only be t, nil, or reset.")))
(t ;; it's a valid value for recently-retrieved
(if (eq 'reset (third (car recent)))
(bt:with-lock-held ((dm-state-lock dm))
(setf (dm-finsts dm) nil))
(let ((finsts (remove-old-dm-finsts dm)))
(cond ((or (and (eq t (third (car recent))) ;; = request t
(eq (caar recent) '=))
(and (null (third (car recent))) ;; - request nil
(eq (caar recent) '-)))
;; only those chunks marked are available
(setf chunk-list (intersection (mapcar 'car finsts) chunk-list))
;; save that info for whynot
(setf (last-request-finst last-request) :marked)
(setf (last-request-finst-chunks last-request) chunk-list)
(when sact
(bt:with-lock-held ((dm-state-lock dm))
(setf (sact-trace-only-recent (dm-current-trace dm)) t)
(setf (sact-trace-recents (dm-current-trace dm)) chunk-list)))
(when (dm-act-level act 'high)
(model-output "Only recently retrieved chunks: ~s" chunk-list)))
(t
;; simply remove the marked items
;; may be "faster" to do this later
;; once the set is trimed elsewise, but
;; for now keep things simple
(unwind-protect
(progn
(when sact
(bt:acquire-lock (dm-state-lock dm))
(setf (sact-trace-remove-recent (dm-current-trace dm)) t))
(when (dm-act-level act 'high)
(model-output "Removing recently retrieved chunks:"))
(setf (last-request-finst last-request) :unmarked)
(setf chunk-list
(remove-if (lambda (x)
(when (member x finsts :key 'car :test 'eq-chunks-fct)
(when sact
(push-last x (sact-trace-recents (dm-current-trace dm))))
(when (dm-act-level act 'high)
(model-output "~s" x))
(push x (last-request-finst-chunks last-request))
t))
chunk-list)))
(when sact
(bt:release-lock (dm-state-lock dm))))))))))))
(when (member :mp-value (chunk-spec-slots request))
(let ((mp-value (chunk-spec-slot-spec request :mp-value)))
(cond ((> (length mp-value) 1)
(invalid :mp-multi '("Invalid retrieval request." ":mp-value parameter used more than once.")))
((not (eq '= (caar mp-value)))
(invalid :mp-modifier '("Invalid retrieval request." ":mp-value parameter's modifier can only be =.")))
((not (numornil (third (car mp-value))))
(invalid :mp-not-num '("Invalid retrieval request." ":mp-value parameter's value can only be nil or a number.")))
(t ;; it's a valid request
(setf mp (third (car mp-value)))))))
(let ((best-val nil)
(best nil)
(return-val nil)
(chunk-set
(cond ((or (null esc) (null mp)) ;; exact matches only
;; normall would do them individually for tracing purposes
;; but when parallel just get them since tracing not possible
;; anyways -- should do that in both cases...
(if *actr-team*
(find-matching-chunks request :chunks chunk-list)
(unwind-protect
(let ((found nil))
(when sact
(bt:acquire-lock (dm-state-lock dm)))
(dolist (name chunk-list found)
(cond ((match-chunk-spec-p name request)
(when sact
(push-last name (sact-trace-matches (dm-current-trace dm))))
(when (dm-act-level act 'medium)
(model-output "Chunk ~s matches" name))
(push-last name found))
(t
(when sact
(push-last name (sact-trace-no-matches (dm-current-trace dm))))
(when (dm-act-level act 'high)
(model-output "Chunk ~s does not match" name))))))
(when sact
(bt:release-lock (dm-state-lock dm))))))
(t ;; partial matching
;; everything that fits the general pattern:
;; filled and empty slots (already handled)
;; also test the inequalities >, <, >=, and <=
(let* ((extra-spec (mapcan (lambda (x)
(unless (or (eq (car x) '=) (eq (car x) '-) (keywordp (second x)))
x))
(chunk-spec-slot-spec request)))
(matches (if extra-spec
(find-matching-chunks (define-chunk-spec-fct extra-spec) :chunks chunk-list)
;; reverse it to keep the ordering the same
;; relative to the older version and so that
;; things are consistent with different requests
(nreverse chunk-list)))
(non-matches (when (or act sact)
(set-difference chunk-list matches))))
(when (dm-act-level act 'high)
(dolist (c non-matches)
(model-output "Chunk ~s does not match" c)))
(when sact
(bt:with-lock-held ((dm-state-lock dm))
(setf (sact-trace-matches (dm-current-trace dm)) matches)
(setf (sact-trace-no-matches (dm-current-trace dm)) non-matches)))
matches)))))
(setf (last-request-matches last-request) chunk-set)
(if esc
(if *actr-team*
(let* ((current-time (mp-time-ms)) ;; probably also needed in the base-level calculation...
(bests (parallel-funcall *actr-team*
(lambda (set)
(let ((b nil)
(bv nil))
(dolist (x set)
(compute-activation dm x request :params-provided t
:act act :sact sact :mp mp :esc esc :offsets offsets
:blc blc :bll bll :ol ol :act-scale act-scale
:sa sa :spreading-hook spreading-hook :w-hook w-hook :sji-hook sji-hook
:mas mas :nsji nsji :pm-hook pm-hook :ms ms :md md :sim-hook sim-hook
:cache-sim-hook cache-sim-hook :noise-hook noise-hook :ans ans :bl-hook bl-hook)
(let ((a (setf (chunk-retrieval-activation x) (chunk-activation x))))
(setf (chunk-retrieval-time x) current-time)
(cond ((null bv)
(setf bv a)
(push x b))
((= a bv)
(push x b))
((> a bv)
(setf bv a)
(setf b (list x))))))
(list (cons bv b))))
chunk-set)))
(setf best-val (apply 'max (mapcar 'car bests)))
(setf best (mapcan (lambda (x) (if (= (car x) best-val) (cdr x) nil)) bests))
)
(dolist (x chunk-set)
(compute-activation dm x request :params-provided t
:act act :sact sact :mp mp :esc esc :offsets offsets
:blc blc :bll bll :ol ol :act-scale act-scale
:sa sa :spreading-hook spreading-hook :w-hook w-hook :sji-hook sji-hook
:mas mas :nsji nsji :pm-hook pm-hook :ms ms :md md :sim-hook sim-hook
:cache-sim-hook cache-sim-hook :noise-hook noise-hook :ans ans :bl-hook bl-hook)
(setf (chunk-retrieval-activation x) (chunk-activation x))
(setf (chunk-retrieval-time x) (mp-time-ms))
(cond ((null best-val)
(setf best-val (chunk-activation x))
(push x best)
(when (dm-act-level act 'medium)
(model-output "Chunk ~s has the current best activation ~f" x best-val)))
((= (chunk-activation x) best-val)
(push x best)
(when (dm-act-level act 'medium)
(model-output "Chunk ~s matches the current best activation ~f" x best-val)))
((> (chunk-activation x) best-val)
(setf best-val (chunk-activation x))
(setf best (list x))
(when (dm-act-level act 'medium)
(model-output "Chunk ~s is now the current best with activation ~f" x best-val))))))
(setf best chunk-set))
(when (> (length best) 1)
(if er
(let ((b (random-item best)))
(setf best (cons b (remove b best))))
(setf best (sort best 'string<)))) ;; deterministic but unspecified...
(setf (last-request-best last-request) best)
(when (car set-hook)
(let ((chunk-set-with-best (when best (cons (car best) (remove (car best) chunk-set)))))
(dolist (x set-hook)
(let ((val (dispatch-apply x chunk-set-with-best)))
(when val
(if return-val
(progn
(print-warning "multiple set-hook functions returned a value - none used")
(setf return-val :error))
(setf return-val val)))))))
(bt:with-lock-held ((dm-state-lock dm))
(setf (dm-last-request dm) last-request)
(cond ((and (listp return-val) (numberp (second return-val))
(chunk-p-fct (decode-string (first return-val))))
(let ((c (decode-string (first return-val))))
(setf (dm-busy dm) (schedule-event-relative (second return-val) 'retrieved-chunk
:module 'declarative
:destination 'declarative
:params (list c)
:details (concatenate 'string
(symbol-name 'retrieved-chunk)
" "
(symbol-name (car return-val)))
:output 'medium))
(when sact
(setf (sact-trace-result-type (dm-current-trace dm)) :force)
(setf (sact-trace-result (dm-current-trace dm)) c))
(when (dm-act-level (dm-act dm) 'low)
(model-output "Retrieval-set-hook function forced retrieval of chunk ~s" c))))
((numberp return-val)
(setf (dm-busy dm) (schedule-event-relative return-val 'retrieval-failure
:module 'declarative
:destination 'declarative
:output 'low))
(when sact
(setf (sact-trace-result-type (dm-current-trace dm)) :force-fail))
(when (dm-act-level (dm-act dm) 'low)
(model-output "Retrieval-set-hook function forced retrieval failure")))
((or (null best)
(and esc
(< best-val rt)))
(setf (dm-busy dm) (schedule-event-relative (if esc
(compute-activation-latency rt lf le)
0)
'retrieval-failure
:time-in-ms t
:module 'declarative
:destination 'declarative
:output 'low))
(when sact
(setf (sact-trace-result-type (dm-current-trace dm)) :fail)
(setf (sact-trace-result (dm-current-trace dm)) (when best rt)))
(when (dm-act-level act 'low)
(if best
(model-output "No chunk above the retrieval threshold: ~f" rt)
(model-output "No matching chunk found retrieval failure"))))
((= (length best) 1)
(setf (dm-busy dm) (schedule-event-relative (if esc
(compute-activation-latency (chunk-activation (car best)) lf le)
0)
'retrieved-chunk
:time-in-ms t
:module 'declarative
:destination 'declarative
:params best
:details
(concatenate 'string
(symbol-name 'retrieved-chunk)
" "
(symbol-name (car best)))
:output 'medium))
(when sact
(setf (sact-trace-result-type (dm-current-trace dm)) :single)
(setf (sact-trace-result (dm-current-trace dm)) (cons (car best) (chunk-activation (car best)))))
(when (dm-act-level act 'low)
(model-output "Chunk ~s with activation ~f is the best" (car best) (chunk-activation (car best)))))
(t
(let ((best1 (car best)))
(setf (dm-busy dm) (schedule-event-relative (if esc
(compute-activation-latency (chunk-activation best1) lf le)
0)
'retrieved-chunk
:time-in-ms t
:module 'declarative
:destination 'declarative
:params (list best1)
:details
(concatenate 'string
(symbol-name 'retrieved-chunk)
" "
(symbol-name best1))
:output 'medium))
(when sact
(setf (sact-trace-result-type (dm-current-trace dm)) :multi)
(setf (sact-trace-result (dm-current-trace dm)) (cons best1 (chunk-activation best1))))
(when (dm-act-level act 'low)
(model-output "Chunk ~s chosen among the chunks with activation ~f" best1 (chunk-activation best1))))))
(when sact
(setf (dm-current-trace dm) nil))))))))
(defun blend-slot (dm instance activation-list dont-generalize slot request)
(let* ((possible-values (mapcan (lambda (x)
(awhen (fast-chunk-slot-value-fct (third x) slot)
(list (make-blending-item :name (third x) :value it :prob (second x)
:mag (funcall (blending-module-v->m instance) it)))))
activation-list))
(slot-vals (mapcar 'blending-item-value possible-values))
(mags (mapcar 'blending-item-mag possible-values))
(true-mags (remove nil mags)))
(cond ((every 'null mags) ;; they're all nil
(cons slot nil))
((every 'numberp true-mags)
(let ((sum 0))
(dolist (mag possible-values)
(awhen (blending-item-mag mag)
(let ((increment (* it (blending-item-prob mag))))
(incf sum increment))))
(cond ((and (blending-module-m->v instance)
(not (equalp slot-vals mags)))
(let ((result (funcall (blending-module-m->v instance) sum request)))
(cons slot result)))
(t
(cons slot sum)))))
(t
(let ((which (if (every 'chunk-p-fct true-mags)
(if (not (find slot dont-generalize))
:chunks :not-generalized)
:other)))
(let* ((type (when (eq which :chunks) (common-chunk-type true-mags)))
(chunks (if (eq which :chunks)
(if (zerop type)
(all-dm-chunks dm)
(mapcan (lambda (x)
(if (slots-vector-match-signature (car x) type)
(copy-list (cdr x))
nil))
(dm-chunks dm)))
(remove-duplicates true-mags :test 'equalp)))
(best-val nil)
(best-mag nil))
(if (= 1 (length chunks))
(setf best-val (car chunks))
(dolist (val chunks)
(let ((sum 0.0))
(dolist (possible possible-values)
(let ((sim (chunks-similarity dm val (blending-item-mag possible))))
(incf sum (* (blending-item-prob possible) (expt sim 2)))))
(when (or (null best-mag)
(< sum best-mag))
(setf best-mag sum)
(setf best-val val)))))
(cond ((and (blending-module-m->v instance)
(not (equalp slot-vals mags)))
(let ((result (funcall (blending-module-m->v instance) best-val request)))
(cons slot result)))
(t
(cons slot best-val)))))))))
(defun start-blending (instance request)
(flet ((blending-terminated (&rest warnings)
(complete-request request)
(dolist (x warnings)
(print-warning x))
(return-from start-blending)))
(let ((ignore nil)
(dont-generalize nil)
(sblt nil))
;; set the currently pending request
(setf (blending-module-pending-request instance) request)
(when (blending-module-sblt instance)
(setf sblt (make-sblt-trace))
(setf (gethash (mp-time) (blending-module-trace-table instance)) sblt))
(when (member :ignore-slots (chunk-spec-slots request))
(let ((ignore-slots (chunk-spec-slot-spec request :ignore-slots)))
(cond ((> (length ignore-slots) 1)
(blending-terminated "Invalid blending request." ":ignore-slots parameter used more than once."))
((not (listp (spec-slot-value (first ignore-slots))))
(blending-terminated "Invalid blending request." ":ignore-slots parameter's value must be a list."))
(t
(setf ignore (spec-slot-value (first ignore-slots)))))))
(when (member :do-not-generalize (chunk-spec-slots request))
(let ((ignore-slots (chunk-spec-slot-spec request :do-not-generalize)))
(cond ((> (length ignore-slots) 1)
(blending-terminated "Invalid blending request." ":do-not-generalize parameter used more than once."))
((not (listp (spec-slot-value (first ignore-slots))))
(blending-terminated "Invalid blending request." ":do-not-generalize parameter's value must be a list."))
(t
(setf dont-generalize (spec-slot-value (first ignore-slots)))))))
(let* ((dm (get-module declarative)) ;; get that module since we're using some of its functions
(request-details (chunk-spec-slot-spec request))
(fixed-values (remove-if (lambda (x) (or (keywordp (spec-slot-name x)) (not (eq (spec-slot-op x) '=)))) request-details))
(fixed-slots (mapcar 'spec-slot-name fixed-values))
;; perform the chunk matching just like the declarative module does
(filled (chunk-spec-filled-slots request))
(empty (chunk-spec-empty-slots request))
(chunk-list (remove-if 'chunk-blending-suppressed
(mapcan (lambda (x)
(if (slots-vector-match-signature (car x) filled empty)
(copy-list (cdr x))
nil))
(dm-chunks dm))))
(matching-chunks (cond ((or (null (blending-module-esc instance))
(null (blending-module-mp instance)))
;; Perfect matching
(find-matching-chunks request :chunks chunk-list))
(t
;; everything that fits the general pattern:
;; filled and empty already done
;; so just test the inequalities
(let ((extra-spec (flatten (mapcan (lambda (x)
(unless (or (eq (spec-slot-op x) '=)
(eq (spec-slot-op x) '-)
(keywordp (spec-slot-name x)))
(list x)))
request-details))))
(if extra-spec
(find-matching-chunks (define-chunk-spec-fct extra-spec) :chunks chunk-list)
chunk-list)))))
(all-slots (slot-mask->names (reduce 'logior matching-chunks :key 'chunk-slots-vector)))
(blended-slots (remove-if (lambda (x)
(find x ignore))
(if (blending-module-blend-all instance)
all-slots
(set-difference all-slots fixed-slots))))
(temperature (aif (blending-module-tmp instance)
it
(if (null (blending-module-ans instance))
(progn
(print-warning "Blending requires :tmp or :ans to be set - assuming default of 1.")
1.0)
(* (sqrt 2) (blending-module-ans instance)))))
;; Have the declarative module compute the activations and record them here
(activation-list (if (and *use-actr-team* (<= *use-actr-team* (length matching-chunks)))
(parallel-mapcan *actr-team*
(lambda (chunk)
(compute-activation dm chunk request) ;; compute the activation
(setf (chunk-blended-activation chunk) (chunk-activation chunk))
(setf (chunk-blended-time chunk) (mp-time))
(if (and (blending-module-min-bl instance) (< (chunk-last-base-level chunk) (blending-module-min-bl instance)))
(progn (setf (chunk-blending-suppressed chunk) t)
nil)
(list (list (chunk-activation chunk)
nil
chunk))))
matching-chunks)
(mapcan (lambda (chunk)
(compute-activation dm chunk request) ;; compute the activation
(setf (chunk-blended-activation chunk) (chunk-activation chunk))
(setf (chunk-blended-time chunk) (mp-time))
(if (and (blending-module-min-bl instance) (< (chunk-last-base-level chunk) (blending-module-min-bl instance)))
(progn (setf (chunk-blending-suppressed chunk) t)
nil)
(list (list (chunk-activation chunk)
nil
chunk))))
matching-chunks)))
(max-ai (when activation-list (reduce 'max activation-list :key 'first))))
(if (and *use-actr-team* (<= *use-actr-team* (length matching-chunks)))
(parallel-run *actr-team* (lambda (x)
(setf (second x)
(handler-case (exp (/ (- (first x) max-ai) temperature))
(floating-point-underflow () 0)
(floating-point-overflow () ;; shouldn't actually happen...
(print-warning "Math overflow during blending. Chunk activation for ~s is ~s with temperature ~s" (third x) (first x) temperature)
(print-warning "Results of blending are not likely to be meaningful.")
;; just use something big and assume it's available for now...
(exp 50)))))
activation-list)
(dolist (x activation-list)
(setf (second x)
(handler-case (exp (/ (- (first x) max-ai) temperature))
(floating-point-underflow () 0)
(floating-point-overflow () ;; shouldn't actually happen...
(print-warning "Math overflow during blending. Chunk activation for ~s is ~s with temperature ~s" (third x) (first x) temperature)
(print-warning "Results of blending are not likely to be meaningful.")
;; just use something big and assume it's available for now...
(exp 50))))))
(when (and (blending-module-blend-all instance) (null (blending-module-mp instance)))
(print-warning "The :blend-all-slots parameter is set to t, but the :mp parameter is nil which means only perfect matches can occur."))
(when (blending-module-sblt instance)
(setf (sblt-trace-chunk-type sblt) (cons filled empty)))
(when (blending-module-trace instance)
(model-output "Blending request for chunks ~@[with slots ~a~] ~@[without slots ~a~]"
(slot-mask->names filled)
(slot-mask->names empty)))
(awhen (blending-module-request-hooks instance)
(dolist (x it)
(funcall x request)))
(awhen (blending-module-set-hooks instance)
(dolist (x it)
(funcall x matching-chunks)))
(when (null activation-list) ;; a complete failure
(when (blending-module-sblt instance)
(setf (sblt-trace-no-matches sblt) t))
(when (blending-module-trace instance)
(model-output "No matching chunks found.")
(model-output "Blending request fails."))
;; schedule the failure event to happen and record that as the busy flag
;; failure time same as for declarative - based on the retrieval threshold
(setf (blending-module-busy instance)
(schedule-event-relative (compute-activation-latency dm (blending-module-rt instance))
'blending-failure :time-in-ms t :module 'blending
:destination 'blending :output 'low))
(awhen (blending-module-result-hooks instance)
(dolist (x it)
(funcall x nil)))
(return-from start-blending nil))
(when (blending-module-sblt instance)
(setf (sblt-trace-tmp sblt) (blending-module-tmp instance))
(setf (sblt-trace-temperature sblt) temperature))
(when (blending-module-trace instance)
(if (blending-module-tmp instance)
(model-output "Blending temperature is: ~f" temperature)
(if (blending-module-ans instance)
(model-output "Blending temperature defaults to (* (sqrt 2) :ans): ~f" temperature)
(model-output "Blending temperature defaults to 1 when :ans and :tmp are both nil"))))
(let ((sum (reduce '+ activation-list :key 'second)) ;; parallelizing this probably isn't useful because tests seem to show those additions take
;; negligible time for lists of 10k elements...
(new-chunk nil)
(blended-results (mapcar (lambda (x) (cons x nil)) blended-slots))
(sblt-slot nil))
;; also probably not worth parallelizing unless lists are expected to be
;; really large...
;;(if (and *use-actr-team* (<= *use-actr-team* (length activation-list)))
;; (parallel-run *actr-team* (lambda (x) (setf (second x) (/ (second x) sum))) activation-list)
;;
(mapc (lambda (x) (setf (second x) (/ (second x) sum))) activation-list)
;)
(when (blending-module-sblt instance)
(setf (sblt-trace-activation-list sblt) activation-list)
(setf (sblt-trace-blended-slots sblt) blended-slots)
(setf (sblt-trace-ignore sblt) ignore))
(when (blending-module-trace instance)
(dolist (x activation-list)
(model-output "Chunk ~S matches blending request~% Activation ~f~% Probability of recall ~f~%"
(third x) (first x) (second x)))
(model-output "~%Slots to be blended: ~S" blended-slots)
(when ignore
(model-output "Slots being explicitly ignored: ~S~%" ignore)))
(if (and *use-actr-team* (second blended-slots)) ;; if there's more than one always do in parallel
(setf blended-results
(parallel-run *actr-team* (lambda (x) (blend-slot dm instance activation-list dont-generalize x request)) blended-slots))
(dolist (slot blended-slots)
(when (blending-module-sblt instance)
(setf sblt-slot (make-sblt-slot :name slot))
(push-last sblt-slot (sblt-trace-slot-list sblt)))
(when (blending-module-trace instance)
(model-output "Finding blended value for slot: ~s" slot))
(let* ((possible-values (mapcan (lambda (x)
(awhen (fast-chunk-slot-value-fct (third x) slot)
(list (make-blending-item :name (third x) :value it :prob (second x)
:mag (funcall (blending-module-v->m instance) it)))))
activation-list))
(slot-vals (mapcar 'blending-item-value possible-values))
(mags (mapcar 'blending-item-mag possible-values))
(true-mags (remove nil mags)))
(when (blending-module-sblt instance)
(setf (sblt-slot-slot-vals sblt-slot) slot-vals)
(setf (sblt-slot-magnitudes sblt-slot) possible-values))
(when (blending-module-trace instance)
(model-output "Matched chunks' slots contain: ~S" slot-vals)
(model-output "Magnitude values for those items: ~S" mags))
(cond ((every 'null mags) ;; they're all nil
(when (blending-module-sblt instance)
(setf (sblt-slot-condition sblt-slot) :null))
(when (blending-module-trace instance)
(model-output "When all magnitudes are nil there's nothing to blend and the slot is ignored"))
(setf blended-results (remove slot blended-results :key 'car)))
((every 'numberp true-mags)
(when (blending-module-sblt instance)
(setf (sblt-slot-condition sblt-slot) :numbers))
(let ((sum 0))
(when (blending-module-trace instance)
(model-output "With numeric magnitudes blending by weighted average"))
(dolist (mag possible-values)
(awhen (blending-item-mag mag)
(let ((increment (* it (blending-item-prob mag))))
(incf sum increment)
(when (blending-module-trace instance)
(model-output " Chunk ~s with probability ~f times magnitude ~f = ~f cumulative result: ~f"
(blending-item-name mag) (blending-item-prob mag) it increment sum)))))
(cond ((and (blending-module-m->v instance)
(not (equalp slot-vals mags)))
(let ((result (funcall (blending-module-m->v instance) sum request)))
(setf (cdr (assoc slot blended-results)) result)
(when (blending-module-sblt instance)
(setf (sblt-slot-mag-adjusted sblt-slot) t)
(setf (sblt-slot-adjusted-val sblt-slot) result))
(when (blending-module-trace instance)
(model-output " Final result: ~f Converted to value: ~s" sum result))))
(t
(setf (cdr (assoc slot blended-results)) sum)
(when (blending-module-trace instance)
(model-output " Final result: ~f" sum))))))
(t
(let ((which (if (every 'chunk-p-fct true-mags)
(if (not (find slot dont-generalize))
:chunks :not-generalized)
:other)))
(when (blending-module-sblt instance)
(setf (sblt-slot-condition sblt-slot) which))
(let* ((type (when (eq which :chunks) (common-chunk-type true-mags)))
(chunks (if (eq which :chunks)
(if (zerop type)
(all-dm-chunks dm)
(mapcan (lambda (x)
(if (slots-vector-match-signature (car x) type)
(copy-list (cdr x))
nil))
(dm-chunks dm)))
(remove-duplicates true-mags :test 'equalp))))
(when (blending-module-trace instance)
(case which
(:chunks
(model-output "When all magnitudes are chunks blending based on similarities to all related chunks"))
(:not-generalized
(model-output "When all magnitudes are chunks and the slot is not generalized blending based on similarities to only those chunks"))
(:other
(model-output "When not all magnitudes are numbers or chunks blending based on similarities using those unique values: ~s" chunks))))
(when (blending-module-sblt instance)
(setf (sblt-slot-ctype sblt-slot) type)
(setf (sblt-slot-chunks sblt-slot) chunks))
(when (and (eq which :chunks) (blending-module-trace instance))
(if (not (zerop type))
(model-output "Intersection of slots for values is: ~s" (slot-mask->names type))
(model-output "No intersecting slots found all chunks will be tested")))
(let ((best-val nil)
(best-mag nil))
(if (= 1 (length chunks))
(progn
(setf best-val (car chunks))
(when (blending-module-trace instance)
(model-output " Only one possible value ~S" (car chunks))))
(dolist (val chunks)
(when (blending-module-trace instance)
(model-output " Comparing value ~S" val))
(let ((sum 0.0))
(dolist (possible possible-values)
(let ((sim (chunks-similarity dm val (blending-item-mag possible))))
(when (blending-module-sblt instance)
(push-last (cons val (list possible sim))
(sblt-slot-possible-values sblt-slot)))
(incf sum (* (blending-item-prob possible) (expt sim 2)))
(when (blending-module-trace instance)
(model-output " Chunk ~s with probability ~f slot value ~s~@[ converted to magnitude ~s~] similarity: ~f cumulative result: ~f"
(blending-item-name possible) (blending-item-prob possible)
(blending-item-value possible)
(if (equalp (blending-item-value possible) (blending-item-mag possible))
nil
(blending-item-mag possible))
sim sum))))
(when (or (null best-mag)
(< sum best-mag))
(setf best-mag sum)
(setf best-val val)))))
(cond ((and (blending-module-m->v instance)
(not (equalp slot-vals mags)))
(let ((result (funcall (blending-module-m->v instance) best-val request)))
(setf (cdr (assoc slot blended-results)) result)
(when (blending-module-sblt instance)
(setf (sblt-slot-mag-adjusted sblt-slot) t)
(setf (sblt-slot-adjusted-val sblt-slot) result))
(when (blending-module-trace instance)
(model-output " Final result: ~s Converted to value: ~s" best-val result))))
(t
(setf (cdr (assoc slot blended-results)) best-val)
(when (blending-module-trace instance)
(model-output " Final result: ~s" best-val))))))))))))
;; put the fixed values into the chunk def.
(unless (blending-module-blend-all instance)
(dolist (slot fixed-values)
(push (spec-slot-name slot) new-chunk)
(push (spec-slot-value slot) new-chunk)))
;; put the blended values into the chunk def.
(dolist (slot blended-results)
(push (car slot) new-chunk)
(push (cdr slot) new-chunk))
(setf new-chunk (nreverse new-chunk))
(when (blending-module-sblt instance)
(setf (sblt-trace-new-chunk sblt) new-chunk))
(when (blending-module-trace instance)
(model-output "This is the definition of the blended chunk:~%~s" new-chunk)
(model-output "~%Computing activation and latency for the blended chunk"))
(let ((act 0))
(dolist (c activation-list)
(incf act (exp (first c)))
(when (blending-module-trace instance)
(model-output " Activation of chunk ~S is ~f" (third c) (first c))))
(setf act (log act))
(when (blending-module-trace instance)
(model-output "Activation for blended chunk is: ~f" act))
(when (blending-module-sblt instance)
(setf (sblt-trace-act sblt) act))
(cond ((>= act (blending-module-rt instance))
(setf (blending-module-busy instance)
(schedule-event-relative
(compute-activation-latency dm act)
'blending-complete
:time-in-ms t
:module 'blending
:destination 'blending
:params (list new-chunk)
:details (symbol-name 'blending-complete)
:output 'medium)))
(t
(when (blending-module-trace instance)
(model-output "Not above threshold so blending failed"))
(when (blending-module-sblt instance)
(setf (sblt-trace-fail sblt) t))
(setf (blending-module-busy instance)
(schedule-event-relative
(compute-activation-latency dm (blending-module-rt instance))
'blending-failure
:time-in-ms t
:module 'blending
:destination 'blending
:details (symbol-name 'blending-failure)
:output 'medium))))))))))
|#
(provide "parallel-retrieval")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 69,716 | Common Lisp | .lisp | 1,049 | 39.370829 | 198 | 0.448927 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | eec94e667af3064f76f10576dccd45b694f98bfcf95d06b8c12606dcef779ab7 | 14,263 | [
291627
] |
14,264 | al-fan-study.lisp | asmaloney_ACT-R/extras/associative-learning/al-fan-study.lisp | ;;; Example model showing the associative learning mechanims
;;; fitting the data from:
;;;
;;; Anderson, J. R. (1974). Retrieval of propositional information from long-term memory. Cognitive Psychology, 5, 451 - 474.
;;;
;;; which is avaliable from:
;;;
;;; http://act-r.psy.cmu.edu/?post_type=publications&p=13993
;;;
;;; It works similar to the model in the tutorial which uses
;;; the non-learning Sji mechanism.
;;;
;;; Here is the data from the experiment (as output by the
;;; tutorial code which includes whether the model responded
;;; correctly:
;;;
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.110 (T ) 1.170 (T ) 1.220 (T )
;;; 2 1.170 (T ) 1.200 (T ) 1.220 (T )
;;; 3 1.150 (T ) 1.230 (T ) 1.360 (T )
;;;
;;; FOILS:
;;; 1 1.200 (T ) 1.220 (T ) 1.260 (T )
;;; 2 1.250 (T ) 1.360 (T ) 1.290 (T )
;;; 3 1.260 (T ) 1.470 (T ) 1.470 (T )
;;;
;;; Here are the results from the tutorial model and the comparison
;;; to the experiment:
;;;
;;; CORRELATION: 0.864
;;; MEAN DEVIATION: 0.053
;;;
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.099 (T ) 1.157 (T ) 1.205 (T )
;;; 2 1.157 (T ) 1.227 (T ) 1.286 (T )
;;; 3 1.205 (T ) 1.286 (T ) 1.354 (T )
;;;
;;; FOILS:
;;; 1 1.245 (T ) 1.290 (T ) 1.328 (T )
;;; 2 1.290 (T ) 1.335 (T ) 1.373 (T )
;;; 3 1.328 (T ) 1.373 (T ) 1.411 (T )
;;;
;;;
;;; That model does not run the whole experiment. It starts with
;;; all of the test sentences encoded in memory and is then run
;;; through only one trial to generate a time. It generates
;;; a result for each cell to report the data (for the foil cells
;;; it averages the result from a request based on a person and
;;; a request based on the location).
;;;
;;; To use the associative learning mechanism this model will
;;; use an approach similar to the one used for the tutorial
;;; model, and for simplicity of testing the mechanism there
;;; won't be any productions for the model -- all of its actions
;;; will be explicitly generated in code.
;;;
;;;
;;; To create the history for learning, this model will use a
;;; random set of testing items as described in experiment 1
;;; of the paper. The model will start with an initial set of
;;; declarative chunks that represent the people and locations
;;; with no explicit histories provided (the prior history will
;;; be represented by the :al-prior-p and :al-prior-w parameter
;;; settings).
;;;
;;; It will be run through an initial presentation of a
;;; randomized ordering of the target sentences, spending
;;; 10 seconds on each. Then it will be run through two
;;; simulated drop-out passes where it sees each probe once
;;; (in a random ordering) and correclty retrieves all of
;;; the items for that probe spending 20 seconds per retrieval
;;; (for a total time of about 35 minutes in the study phase).
;;; Then, instead of actually performing the testing the
;;; activation of retrieving the appropriate chunk for each
;;; target and foil test item will be computed based on the
;;; associations which were learned during training. That
;;; will be done twice, once computing the activation for
;;; retrieving the item using the person and once using the
;;; location in the retrieval request (both items will be
;;; sources of activation in the imaginal buffer). Those
;;; activations will be converted to a time (adjusting the
;;; :lf parameter to scale appropriately) and added to
;;; an intercept time of .845 seconds which is the time the
;;; tutorial model takes to perform all of the actions that
;;; are not the critical retrieval. Because of the randomized
;;; items, that process will be performed multiple times and
;;; all the times averaged to create the results.
;;;
;;; Below are the results of some rough parameter fitting
;;; to get the model to perform similar to the one from the
;;; tutorial which doesn't use the learning mechanism (there
;;; may be better sets of parameters, but these are good
;;; enough for a demo).
;;;
;;; Here are the results after fitting the :lf, :prior-p, and
;;; :prior-w parameters with the optimized learning parameter
;;; set to it's default of t (assumes equally spaced
;;; presentation times across the history instead of recording
;;; explicit times).
;;;
;;; > (APPROACH-1-RESULTS 50 0.75 :PRIOR-P 0.08 :PRIOR-W 2.5)
;;; CORRELATION: 0.897
;;; MEAN DEVIATION: 0.044
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.108 1.156 1.192
;;; 2 1.156 1.212 1.255
;;; 3 1.192 1.255 1.303
;;;
;;; FOILS:
;;; 1 1.213 1.267 1.310
;;; 2 1.267 1.330 1.378
;;; 3 1.310 1.378 1.431
;;;
;;;
;;; Here are the results fit over 50 runs when :ol is
;;; is set to 1 (one prior reference recorded) which
;;; required changing the :prior-p slightly to get
;;; the "same" fit:
;;;
;;; > (APPROACH-1-RESULTS 50 0.75 :OL 1 :PRIOR-P 0.06 :PRIOR-W 2.5)
;;; CORRELATION: 0.898
;;; MEAN DEVIATION: 0.045
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.103 1.159 1.190
;;; 2 1.161 1.236 1.273
;;; 3 1.188 1.270 1.349
;;;
;;; FOILS:
;;; 1 1.220 1.275 1.310
;;; 2 1.275 1.337 1.375
;;; 3 1.311 1.377 1.420
;;;
;;; Here are the results fit over 50 runs when :ol is
;;; set to nil (all references recorded) which required
;;; changing the :lf slightly to get the "same" fit
;;; (because of the storage and computation costs :ol nil
;;; is not recommended in general when using this module
;;; but is ok for this task given the small number of
;;; chunks involved and the limited number of item
;;; presentations):
;;;
;;; > (APPROACH-1-RESULTS 50 0.7 :OL nil :PRIOR-P 0.06 :PRIOR-W 2.5)
;;; CORRELATION: 0.894
;;; MEAN DEVIATION: 0.045
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.105 1.155 1.188
;;; 2 1.154 1.208 1.251
;;; 3 1.191 1.253 1.296
;;;
;;; FOILS:
;;; 1 1.211 1.263 1.297
;;; 2 1.264 1.326 1.360
;;; 3 1.298 1.361 1.404
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Remove any existing models and make sure the associative
;;; learning extension is included:
(clear-all)
(require-extra "associative-learning")
;;; Here is the starting model.
;;; It enables the activation calculations, the associative
;;; learning mechanism with a decay parameter of .5, and sets
;;; the retrieval threshold low so that none of the simulated
;;; retrievals in the study/training sections will fail.
;;; It turns off the model output and display of the activation
;;; calculations (they could be turned on to see the details
;;; if desired). It also disables the use of negative Sji
;;; values (the default is to not use them and also print a
;;; warning so this just removes the warning). Then it just
;;; specifies the slots that will be used to represent the chunks
;;; for the words and the sentences.
(define-model fan
(sgp :esc t :eal .5 :rt -4)
(sgp :v nil :act nil)
(sgp :nsji nil)
(chunk-type comprehend-sentence relation arg1 arg2)
(chunk-type meaning word))
;;; This is the experimental data for comparison.
(defvar *person-location-data* '(1.11 1.17 1.22
1.17 1.20 1.22
1.15 1.23 1.36
1.20 1.22 1.26
1.25 1.36 1.29
1.26 1.47 1.47))
;;; These are the people and locations used to generate the stimuli
;;; for the experiment.
(defvar *people* '(hippie guard earl giant captain debutante fireman lawyer
wizard clerk writer doctor teacher boxer queen singer))
(defvar *places* '(beach castle dungeon forest park church cave bank store
tower lake stadium casino school diner office))
;;; Variables to hold the experiment stimuli
(defvar *targets* nil)
(defvar *foils* nil)
(defun *fillers* nil)
(defun *sentences* nil)
;;; Create a randomized set of stimuli for the
;;; studied sentences and the testing items as
;;; described in the paper: 26 study sentences
;;; with 3 in each block of the 3x3 fan matrix
;;; except the 2x2 cell which has only two items,
;;; nine target sentences from that set (one in
;;; each fan pairing) for testing, 18 foils
;;; (two different ones for each fan pairing),
;;; and 14 filler sentences which are random
;;; pairings of the previously unused people
;;; and places (thus could be true or false).
(defun create-stims ()
(let ((people (permute-list *people*))
(places (permute-list *places*)))
(setf *sentences*
(list
(list (nth 0 people) (nth 0 places) 1 1)
(list (nth 1 people) (nth 1 places) 1 1)
(list (nth 2 people) (nth 2 places) 1 1)
(list (nth 3 people) (nth 3 places) 2 1)
(list (nth 4 people) (nth 4 places) 2 1)
(list (nth 5 people) (nth 5 places) 2 1)
(list (nth 6 people) (nth 6 places) 3 1)
(list (nth 7 people) (nth 7 places) 3 1)
(list (nth 8 people) (nth 8 places) 3 1)
(list (nth 9 people) (nth 9 places) 1 2)
(list (nth 10 people) (nth 10 places) 1 2)
(list (nth 11 people) (nth 11 places) 1 2)
(list (nth 12 people) (nth 12 places) 1 3)
(list (nth 13 people) (nth 13 places) 1 3)
(list (nth 14 people) (nth 14 places) 1 3)
(list (nth 4 people) (nth 10 places) 2 2)
(list (nth 15 people) (nth 15 places) 2 2)
(list (nth 6 people) (nth 9 places) 3 2)
(list (nth 7 people) (nth 15 places) 3 2)
(list (nth 8 people) (nth 11 places) 3 2)
(list (nth 3 people) (nth 12 places) 2 3)
(list (nth 15 people) (nth 13 places) 2 3)
(list (nth 5 people) (nth 14 places) 2 3)
(list (nth 6 people) (nth 12 places) 3 3)
(list (nth 7 people) (nth 13 places) 3 3)
(list (nth 8 people) (nth 14 places) 3 3)))
(setf *targets*
(list
(list (nth 0 people) (nth 0 places) 1 1 t)
(list (nth 9 people) (nth 9 places) 1 2 t)
(list (nth 12 people) (nth 12 places) 1 3 t)
(list (nth 3 people) (nth 3 places) 2 1 t)
(list (nth 4 people) (nth 10 places) 2 2 t)
(list (nth 15 people) (nth 13 places) 2 3 t)
(list (nth 6 people) (nth 6 places) 3 1 t)
(list (nth 7 people) (nth 15 places) 3 2 t)
(list (nth 8 people) (nth 14 places) 3 3 t)))
(setf *foils*
(list
(list (nth 0 people) (nth 3 places) 1 1 nil)
(list (nth 9 people) (nth 10 places) 1 2 nil)
(list (nth 12 people) (nth 13 places) 1 3 nil)
(list (nth 3 people) (nth 0 places) 2 1 nil)
(list (nth 4 people) (nth 9 places) 2 2 nil)
(list (nth 15 people) (nth 12 places) 2 3 nil)
(list (nth 6 people) (nth 0 places) 3 1 nil)
(list (nth 7 people) (nth 9 places) 3 2 nil)
(list (nth 8 people) (nth 12 places) 3 3 nil)
(list (nth 0 people) (nth 6 places) 1 1 nil)
(list (nth 9 people) (nth 15 places) 1 2 nil)
(list (nth 12 people) (nth 14 places) 1 3 nil)
(list (nth 3 people) (nth 6 places) 2 1 nil)
(list (nth 4 people) (nth 15 places) 2 2 nil)
(list (nth 15 people) (nth 14 places) 2 3 nil)
(list (nth 6 people) (nth 3 places) 3 1 nil)
(list (nth 7 people) (nth 10 places) 3 2 nil)
(list (nth 8 people) (nth 13 places) 3 3 nil)))
(setf *fillers* nil)
(dotimes (i 6)
(let ((other-people (permute-list (list 1 2 5 10 11 13 14)))
(other-places (permute-list (list 1 2 4 5 7 8 11))))
(setf *fillers*
(append *fillers*
(mapcar (lambda (x y) (list (nth x people)
(nth y places)
-1 -1 :filler))
other-people
other-places)))))))
;;; Add chunks for the people, places, and word "in" to the model's
;;; declarative memory.
(defun create-initial-chunks ()
(dolist (x *people*)
(add-dm-fct (list (list x 'isa 'meaning 'word (symbol-name x)))))
(dolist (x *places*)
(add-dm-fct (list (list x 'isa 'meaning 'word (symbol-name x)))))
(add-dm (in isa meaning word "in")))
;;; Randomly present the model with each of the study sentences
;;; giving it 10 seconds between presentations.
(defun initial-presentation ()
(dolist (x (permute-list *sentences*))
(module-request 'imaginal (define-chunk-spec-fct (list 'relation 'in 'arg1 (first x) 'arg2 (second x))))
(schedule-clear-buffer 'imaginal 1.5)
(run 10)))
;;; Simulate the drop-out task by randomly presenting each of
;;; the possible probes and then having the model retrieve all
;;; of the correct responses for that probe with 20s between
;;; the retrievals.
(defun drop-out ()
(let ((lf (get-parameter-value :lf)))
(set-parameter-value :lf 0) ;; ignore actual retrieval time for simplicity
(dolist (x (permute-list (append (copy-list *people*) (copy-list *places*))))
;; don't want to create associations to the prompts or deposit
;; the prompts into DM for this example
(erase-buffer 'imaginal)
(module-request 'imaginal (define-chunk-spec-fct (list 'relation 'in 'arg1 x)))
(run .2)
(dolist (y (remove-if-not (lambda (z)
(or (eq (first z) x) (eq (second z) x)))
*sentences*))
(module-request 'retrieval (define-chunk-spec-fct (list 'relation 'in 'arg1 (first y) 'arg2 (second y))))
(run-full-time 20)))
(set-parameter-value :lf lf))) ;; restore the latency factor parameter value
;;; Compute the response times for each of the target items and
;;; the foils by determining the activation of the chunks that
;;; could be retrieved based on each of the person or location
;;; being used as the probe recording the maximum activation
;;; from each case (the activation of the chunk that would be
;;; retrieved). Convert those to times using the current :lf
;;; value and the intercept from the tutorial model (.845s).
;;; Average all the times in a cell and return a list of those
;;; values in the same ordering as the experimental data for
;;; comparison.
(defvar *task-intercept* .845)
(defun time-to-retrieve-at-start ()
(let ((data (make-array (list 3 3 2) :initial-element nil))
(lf (get-parameter-value :lf))
; put an empty context chunk into the imaginal buffer
(ic (set-buffer-chunk 'imaginal (car (define-chunks (isa comprehend-sentence relation in))))))
(dolist (x (append (copy-list *targets*) (copy-list *foils*)))
;set the person and location in the imaginal chunk
(set-chunk-slot-value-fct ic 'arg1 (first x))
(set-chunk-slot-value-fct ic 'arg2 (second x))
;; get the activations for chunks based on retrieval requests based on person and location
(let* ((activations-person (no-output (mapcar (lambda (x) (sdp-fct (list x :name :activation)))
(sdm-fct (list 'arg1 (first x) '- 'arg2 nil)))))
(activations-location (no-output (mapcar (lambda (x) (sdp-fct (list x :name :activation)))
(sdm-fct (list 'arg2 (second x) '- 'arg1 nil)))))
(activation-person (apply 'max (mapcar 'cadar activations-person)))
(activation-location (apply 'max (mapcar 'cadar activations-location))))
;; Record the response times using the ACT-R equation for
;; for retrieval time: F * e ^ -A
;; where F is the :lf value and A is the chunk's activation
(push (+ *task-intercept* (* lf (exp (- activation-person)))) (aref data (1- (third x)) (1- (fourth x)) (if (fifth x) 0 1)))
(push (+ *task-intercept* (* lf (exp (- activation-location)))) (aref data (1- (third x)) (1- (fourth x)) (if (fifth x) 0 1)))
;; as a safety check, make sure the correct chunk had the best activation
;; for target items.
(when (fifth x)
(let* ((m-person (mapcar 'cadar activations-person))
(m-location (mapcar 'cadar activations-location))
(retrieved-by-person (caar (find activation-person activations-person :key 'cadar)))
(retrieved-by-location (caar (find activation-location activations-location :key 'cadar))))
(unless (and (eq (chunk-slot-value-fct retrieved-by-person 'arg1) (first x))
(eq (chunk-slot-value-fct retrieved-by-person 'arg2) (second x)))
(format t "Retrieved incorrect chunk ~s for ~s ~s when probed with ~s~%"
retrieved-by-person (first x) (second x) (first x)))
(unless (and (eq (chunk-slot-value-fct retrieved-by-location 'arg1) (first x))
(eq (chunk-slot-value-fct retrieved-by-location 'arg2) (second x)))
(format t "Retrieved incorrect chunk ~s for ~s ~s when probed with ~s~%"
retrieved-by-location (first x) (second x) (second x)))))))
;; average the results recording into a list like *person-location-data*
(let ((d (make-list 18 :initial-element nil)))
(dotimes (pf 3)
(dotimes (lf 3)
(dotimes (t-f 2)
(setf (nth (+ pf (* 3 lf) (* 9 t-f)) d)
(/ (reduce '+ (aref data pf lf t-f))
(length (aref data pf lf t-f)))))))
d)))
;;; Run the model n times through the task setting the
;;; parameters :lf, :al-show, :ol, :al-prior-p, and :al-prior-w
;;; with the provided values, and report the average results
;;; and their comparison to the experiment data.
(defun approach-1-results (n lf &key (show nil) (ol t) (prior-p .01) (prior-w 10))
(let ((results nil))
(dotimes (i n)
(create-stims)
(reset)
(set-parameter-value :lf lf)
(set-parameter-value :al-show show)
(set-parameter-value :ol ol)
(set-parameter-value :al-prior-p prior-p)
(set-parameter-value :al-prior-w prior-w)
(create-initial-chunks)
(initial-presentation)
(drop-out)
(drop-out)
(push (time-to-retrieve-at-start) results))
(output-person-location
(mapcar (lambda (x) (/ x n))
(reduce (lambda (y z)
(mapcar '+ y z))
results)))))
;;; Print the table of data and the comparison stats
(defun output-person-location (data)
(correlation data *person-location-data*)
(mean-deviation data *person-location-data*)
(format t "TARGETS:~% Person fan~%")
(format t " Location 1 2 3~%")
(format t " fan")
(dotimes (i 3)
(format t "~% ~d " (1+ i))
(dotimes (j 3)
(format t "~8,3F " (nth (+ j (* i 3)) data))))
(format t "~%~%FOILS:")
(dotimes (i 3)
(format t "~% ~d " (1+ i))
(dotimes (j 3)
(format t "~8,3F " (nth (+ j (* (+ i 3) 3)) data)))))
| 20,572 | Common Lisp | .lisp | 425 | 41.369412 | 135 | 0.577516 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ab2658764980ce827d463d06ded4b3456f06b1210e2767e82da2315b4e9df060 | 14,264 | [
377587
] |
14,265 | al-fan-history.lisp | asmaloney_ACT-R/extras/associative-learning/al-fan-history.lisp | ;;; Example model showing the associative learning mechanims
;;; fitting the data from:
;;;
;;; Anderson, J. R. (1974). Retrieval of propositional information from long-term memory. Cognitive Psychology, 5, 451 - 474.
;;;
;;; which is avaliable from:
;;;
;;; http://act-r.psy.cmu.edu/?post_type=publications&p=13993
;;;
;;; It works similar to the model in the tutorial which uses
;;; the non-learning Sji mechanism.
;;;
;;; Here is the data from the experiment (as output by the
;;; tutorial code which includes whether the model responded
;;; correctly:
;;;
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.110 (T ) 1.170 (T ) 1.220 (T )
;;; 2 1.170 (T ) 1.200 (T ) 1.220 (T )
;;; 3 1.150 (T ) 1.230 (T ) 1.360 (T )
;;;
;;; FOILS:
;;; 1 1.200 (T ) 1.220 (T ) 1.260 (T )
;;; 2 1.250 (T ) 1.360 (T ) 1.290 (T )
;;; 3 1.260 (T ) 1.470 (T ) 1.470 (T )
;;;
;;; Here are the results from the tutorial model and the comparison
;;; to the experiment:
;;;
;;; CORRELATION: 0.864
;;; MEAN DEVIATION: 0.053
;;;
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.099 (T ) 1.157 (T ) 1.205 (T )
;;; 2 1.157 (T ) 1.227 (T ) 1.286 (T )
;;; 3 1.205 (T ) 1.286 (T ) 1.354 (T )
;;;
;;; FOILS:
;;; 1 1.245 (T ) 1.290 (T ) 1.328 (T )
;;; 2 1.290 (T ) 1.335 (T ) 1.373 (T )
;;; 3 1.328 (T ) 1.373 (T ) 1.411 (T )
;;;
;;;
;;; That model does not run the whole experiment. It starts with
;;; all of the test sentences encoded in memory and is then run
;;; through only one trial to generate a time. It generates
;;; a result for each cell to report the data (for the foil cells
;;; it averages the result from a request based on a person and
;;; a request based on the location).
;;;
;;; To use the associative learning mechanism this model will
;;; use an approach similar to the one used for the tutorial
;;; model, and for simplicity of testing the mechanims there
;;; won't be any productions for the model -- all of its actions
;;; will be explicitly generated in code.
;;;
;;;
;;; This model will set a history for all of the relevant chunks
;;; in the task from which the Sji values will be learned.
;;; The model will start with an initial set of declarative chunks
;;; that represent the people and locations. Those items will
;;; have a long history of having been in the context many times
;;; plus their time in the study phase (varies by fan). The
;;; target item chunks will be created at the start of the task
;;; with no explicit history. The total model history (for the F
;;; value in the associative learning equation) will be set to a
;;; very large count over a longer time.
;;;
;;; The optimized learning parameter will be left at its default
;;; value of t in the model (assumes equally spaced presentation
;;; times across the history), but can be specified as an
;;; integer value when running a test.
;;;
;;;
;;; If the history parameter are set like this it will correspond to
;;; the situation modeled in the al-fan-study.lisp file (without
;;; the randomness of the study period):
;;;
;;; (defparameter *probe-creation-time* -2131.8)
;;; (defparameter *probe-prior-context-count* 0)
;;; (defparameter *in-multiplier* 1)
;;; (defparameter *study-length* 2131.8)
;;; (defparameter *tries-per-drop-out* 1)
;;; (defparameter *global-history-count* 130)
;;; (defparameter *global-history-creation* -2131.8)
;;;
;;; and if the :lf, :al-prior-p and :al-prior-w parameters are
;;; then set to match that model the results are essentially the same:
;;;
;;; > (approach-2-results 0.75 :PRIOR-P 0.08 :PRIOR-W 2.5)
;;; CORRELATION: 0.898
;;; MEAN DEVIATION: 0.044
;;; TARGETS:
;;; Person fan
;;; Location 1 2 3
;;; fan
;;; 1 1.108 1.156 1.193
;;; 2 1.156 1.213 1.256
;;; 3 1.193 1.256 1.304
;;;
;;; FOILS:
;;; 1 1.213 1.268 1.310
;;; 2 1.268 1.330 1.379
;;; 3 1.310 1.379 1.432
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Here is the starting model.
;;; It enables the activation calculations, the associative
;;; learning mechanism with a decay parameter of .5, and sets
;;; the prior history parameter to very small value since a
;;; history is being provided.
;;; It turns off the model output and display of the activation
;;; calculations (they could be turned on to see the details
;;; if desired). For exploratory purposes, the :ol parameter
;;; is included, and set to t initially (though other values
;;; will be tested). Then it specifies the slots that will be used
;;; to represent the chunks for the words and the sentences.
(clear-all)
(require-extra "associative-learning")
(define-model fan
(sgp :esc t :eal .5)
(sgp :v nil :act nil)
(sgp :nsji nil) ;; turn off warning for treating negative Sji values as 0
(sgp :ol t)
(chunk-type comprehend-sentence relation arg1 arg2)
(chunk-type meaning word)
(add-dm (hippie isa meaning word "hippie")(guard isa meaning word "guard")
(earl isa meaning word "earl")(giant isa meaning word "giant")
(captain isa meaning word "captain")(debutante isa meaning word "debutante")
(fireman isa meaning word "fireman")(lawyer isa meaning word "lawyer")
(wizard isa meaning word "wizard")(clerk isa meaning word "clerk")
(writer isa meaning word "writer")(doctor isa meaning word "doctor")
(teacher isa meaning word "teacher")(boxer isa meaning word "boxer")
(queen isa meaning word "queen")(singer isa meaning word "singer")
(beach isa meaning word "beach")(castle isa meaning word "castle")
(dungeon isa meaning word "dungeon")(forest isa meaning word "forest")
(park isa meaning word "park")(church isa meaning word "church")
(cave isa meaning word "cave")(bank isa meaning word "bank")
(store isa meaning word "store")(tower isa meaning word "tower")
(lake isa meaning word "lake")(stadium isa meaning word "stadium")
(casino isa meaning word "casino")(school isa meaning word "school")
(diner isa meaning word "diner")(office isa meaning word "office")
(in isa meaning word "in")))
;;; This is the experimental data for comparison.
(defvar *person-location-data* '(1.11 1.17 1.22
1.17 1.20 1.22
1.15 1.23 1.36
1.20 1.22 1.26
1.25 1.36 1.29
1.26 1.47 1.47))
;;; These are the people and locations used to generate the stimuli
;;; for the experiment.
(defvar *people* '(hippie guard earl giant captain debutante fireman lawyer
wizard clerk writer doctor teacher boxer queen singer))
(defvar *places* '(beach castle dungeon forest park church cave bank store
tower lake stadium casino school diner office))
;;; Variables to hold the experiment stimuli
(defvar *targets* nil)
(defvar *foils* nil)
(defun *fillers* nil)
(defun *sentences* nil)
;;; Create a randomized set of stimuli for the
;;; studied sentences and the testing items as
;;; described in the paper: 26 study sentences
;;; with 3 in each block of the 3x3 fan matrix
;;; except the 2x2 cell which has only two items,
;;; nine target sentences from that set (one in
;;; each fan pairing) for testing, 18 foils
;;; (two different ones for each fan pairing),
;;; and 14 filler sentences which are random
;;; pairings of the previously unused people
;;; and places (thus could be true or false).
(defun create-stims ()
(let ((people (permute-list *people*))
(places (permute-list *places*)))
(setf *sentences*
(list
(list (nth 0 people) (nth 0 places) 1 1)
(list (nth 1 people) (nth 1 places) 1 1)
(list (nth 2 people) (nth 2 places) 1 1)
(list (nth 3 people) (nth 3 places) 2 1)
(list (nth 4 people) (nth 4 places) 2 1)
(list (nth 5 people) (nth 5 places) 2 1)
(list (nth 6 people) (nth 6 places) 3 1)
(list (nth 7 people) (nth 7 places) 3 1)
(list (nth 8 people) (nth 8 places) 3 1)
(list (nth 9 people) (nth 9 places) 1 2)
(list (nth 10 people) (nth 10 places) 1 2)
(list (nth 11 people) (nth 11 places) 1 2)
(list (nth 12 people) (nth 12 places) 1 3)
(list (nth 13 people) (nth 13 places) 1 3)
(list (nth 14 people) (nth 14 places) 1 3)
(list (nth 4 people) (nth 10 places) 2 2)
(list (nth 15 people) (nth 15 places) 2 2)
(list (nth 6 people) (nth 9 places) 3 2)
(list (nth 7 people) (nth 15 places) 3 2)
(list (nth 8 people) (nth 11 places) 3 2)
(list (nth 3 people) (nth 12 places) 2 3)
(list (nth 15 people) (nth 13 places) 2 3)
(list (nth 5 people) (nth 14 places) 2 3)
(list (nth 6 people) (nth 12 places) 3 3)
(list (nth 7 people) (nth 13 places) 3 3)
(list (nth 8 people) (nth 14 places) 3 3)))
(setf *targets*
(list
(list (nth 0 people) (nth 0 places) 1 1 t)
(list (nth 9 people) (nth 9 places) 1 2 t)
(list (nth 12 people) (nth 12 places) 1 3 t)
(list (nth 3 people) (nth 3 places) 2 1 t)
(list (nth 4 people) (nth 10 places) 2 2 t)
(list (nth 15 people) (nth 13 places) 2 3 t)
(list (nth 6 people) (nth 6 places) 3 1 t)
(list (nth 7 people) (nth 15 places) 3 2 t)
(list (nth 8 people) (nth 14 places) 3 3 t)))
(setf *foils*
(list
(list (nth 0 people) (nth 3 places) 1 1 nil)
(list (nth 9 people) (nth 10 places) 1 2 nil)
(list (nth 12 people) (nth 13 places) 1 3 nil)
(list (nth 3 people) (nth 0 places) 2 1 nil)
(list (nth 4 people) (nth 9 places) 2 2 nil)
(list (nth 15 people) (nth 12 places) 2 3 nil)
(list (nth 6 people) (nth 0 places) 3 1 nil)
(list (nth 7 people) (nth 9 places) 3 2 nil)
(list (nth 8 people) (nth 12 places) 3 3 nil)
(list (nth 0 people) (nth 6 places) 1 1 nil)
(list (nth 9 people) (nth 15 places) 1 2 nil)
(list (nth 12 people) (nth 14 places) 1 3 nil)
(list (nth 3 people) (nth 6 places) 2 1 nil)
(list (nth 4 people) (nth 15 places) 2 2 nil)
(list (nth 15 people) (nth 14 places) 2 3 nil)
(list (nth 6 people) (nth 3 places) 3 1 nil)
(list (nth 7 people) (nth 10 places) 3 2 nil)
(list (nth 8 people) (nth 13 places) 3 3 nil)))
(setf *fillers* nil)
(dotimes (i 6)
(let ((other-people (permute-list (list 1 2 5 10 11 13 14)))
(other-places (permute-list (list 1 2 4 5 7 8 11))))
(setf *fillers*
(append *fillers*
(mapcar (lambda (x y) (list (nth x people)
(nth y places)
-1 -1 :filler))
other-people
other-places)))))))
;;; Create a set of stims -- since the histories are being set
;;; explicitly don't need to randomize and run multiple times.
(create-stims)
;;; Add the chunks for the sentences to DM.
(defun create-sentence-chunks ()
(dolist (x *sentences*)
(add-dm-fct (list (list 'isa 'comprehend-sentence 'relation 'in 'arg1 (first x) 'arg2 (second x))))))
;;; Compute the response times for each of the target items and
;;; the foils by determining the activation of the chunks that
;;; could be retrieved based on each of the person or location
;;; being used as the probe recording the maximum activation
;;; from each case (the activation of the chunk that would be
;;; retrieved). Convert those to times using the current :lf
;;; value and the intercept from the tutorial model (.845s).
;;; Average all the times in a cell and return a list of those
;;; values in the same ordering as the experimental data for
;;; comparison.
(defvar *task-intercept* .845)
(defun time-to-retrieve-at-start ()
(let ((data (make-array (list 3 3 2) :initial-element nil))
(lf (get-parameter-value :lf))
; put an empty context chunk into the imaginal buffer
(ic (set-buffer-chunk 'imaginal (car (define-chunks (isa comprehend-sentence relation in))))))
(dolist (x (append (copy-list *targets*) (copy-list *foils*)))
;set the person and location in the imaginal chunk
(set-chunk-slot-value-fct ic 'arg1 (first x))
(set-chunk-slot-value-fct ic 'arg2 (second x))
;; get the activations for chunks based on retrieval requests based on person and location
(let* ((activations-person (no-output (mapcar (lambda (x) (sdp-fct (list x :name :activation)))
(sdm-fct (list 'arg1 (first x) '- 'arg2 nil)))))
(activations-location (no-output (mapcar (lambda (x) (sdp-fct (list x :name :activation)))
(sdm-fct (list 'arg2 (second x) '- 'arg1 nil)))))
(activation-person (apply 'max (mapcar 'cadar activations-person)))
(activation-location (apply 'max (mapcar 'cadar activations-location))))
;; Record the response times using the ACT-R equation for
;; for retrieval time: F * e ^ -A
;; where F is the :lf value and A is the chunk's activation
(push (+ *task-intercept* (* lf (exp (- activation-person)))) (aref data (1- (third x)) (1- (fourth x)) (if (fifth x) 0 1)))
(push (+ *task-intercept* (* lf (exp (- activation-location)))) (aref data (1- (third x)) (1- (fourth x)) (if (fifth x) 0 1)))
;; as a safety check, make sure the correct chunk had the best activation
;; for target items.
(when (fifth x)
(let* ((m-person (mapcar 'cadar activations-person))
(m-location (mapcar 'cadar activations-location))
(retrieved-by-person (caar (find activation-person activations-person :key 'cadar)))
(retrieved-by-location (caar (find activation-location activations-location :key 'cadar))))
(unless (and (eq (chunk-slot-value-fct retrieved-by-person 'arg1) (first x))
(eq (chunk-slot-value-fct retrieved-by-person 'arg2) (second x)))
(format t "Retrieved incorrect chunk ~s for ~s ~s when probed with ~s~%"
retrieved-by-person (first x) (second x) (first x)))
(unless (and (eq (chunk-slot-value-fct retrieved-by-location 'arg1) (first x))
(eq (chunk-slot-value-fct retrieved-by-location 'arg2) (second x)))
(format t "Retrieved incorrect chunk ~s for ~s ~s when probed with ~s~%"
retrieved-by-location (first x) (second x) (second x)))))))
;; average the results recording into a list like *person-location-data*
(let ((d (make-list 18 :initial-element nil)))
(dotimes (pf 3)
(dotimes (lf 3)
(dotimes (t-f 2)
(setf (nth (+ pf (* 3 lf) (* 9 t-f)) d)
(/ (reduce '+ (aref data pf lf t-f))
(length (aref data pf lf t-f)))))))
d)))
;;; These parameters indicate the values for the
;;; indicated components of the histories needed
;;; to compute Sji values.
;;;
;;; Times are in seconds, and the current time
;;; (when the retrievals will be performed) is 0.
;;;
;;; When optimizied learning with a history is enabled
;;; (an integer value) it will set the histories for
;;; the indicated number of items to be in steps of
;;; the *recent-history* value.
;;;
;;; The assumptions used for setting these parameters are:
;;; - the probe words were learned long ago and used occasionally
;;; - the word in was learned long ago and used more often than
;;; the probes
;;; - the target sentences are newly learned with a history
;;; based on the study period only and having equal study
;;; - the total history is significantly larger than just
;;; the probe words
;;;
;;; Only values that are needed will be set:
;;; - Creation time for probes
;;; - Length of the study period
;;; - the Cj values for when a probe was in the context
;;; - the Ni values for the target sentences
;;; - the Ni&Cj values for the target sentences
;;; - the global history F
;;;
(defparameter *probe-creation-time* -2131.8) ;; in seconds
(defparameter *probe-prior-context-count* 0)
(defparameter *in-multiplier* 1) ;; how many times more than probe prior
(defparameter *study-length* 2131.8) ;; in seconds
(defparameter *tries-per-drop-out* 1)
(defparameter *global-history-count* 130)
(defparameter *global-history-creation* -2131.8) ;; in seconds
;;; Search the study sentences to find the fan of
;;; a probe item
(defun find-item-fan (probe)
(aif (find probe *sentences* :key 'first)
(third it)
(fourth (find probe *sentences* :key 'second))))
;;; Internally times need to be ms but values given are
;;; in seconds
(defun sec->ms (x) (round x 1/1000))
(defun set-probe-histories ()
(let ((probes (append (copy-list *people*) (copy-list *places*)))
(ol (get-parameter-value :ol)))
;; Set creation-time as specified (gets set in seconds)
(dolist (x probes)
(sdp-fct (list x :creation-time *probe-creation-time*)))
(sdp-fct (list 'in :creation-time *probe-creation-time*))
;; The Cj value for probes is *probe-prior-context-count* plus the
;; fan of the item for initial presentation plus its fan for each
;; drop out attempt (there are two drop out passes with *tries-per-drop-out*
;; in each)
(dolist (x probes)
(setf (chunk-al-cj-count x) (+ *probe-prior-context-count* (* (find-item-fan x) (+ 1 (* 2 *tries-per-drop-out*)))))
;; Create any needed times for ol as equally spaced
;; during the study period.
(when (numberp ol)
(do ((delay (/ *study-length* ol))
(time (- *study-length*) (+ time delay))
(count ol (1- count))
(times nil (cons time times)))
((zerop count)
(setf (chunk-al-cj-refs x) (mapcar 'sec->ms times))))))
;; for in it's *in-multiplier* * *probe-prior-context-count*
;; plus 26 (every target's initial presentation) plus
;; 26 times 2 * 2 * *tries-per-drop-out*
;; since each target is retrieved twice per drop try (once by person
;; and once by location) in each drop out session
(setf (chunk-al-cj-count 'in) (+ (* *in-multiplier* *probe-prior-context-count*)
(* 26 (+ 1 (* 2 2 *tries-per-drop-out*)))))
;; for simplicity, just use the same time values for in
;; as with the probes
(when (numberp ol)
(do ((delay (/ *study-length* ol))
(time (- *study-length*) (+ time delay))
(count ol (1- count))
(times nil (cons time times)))
((zerop count)
(setf (chunk-al-cj-refs 'in) (mapcar 'sec->ms times)))))))
(defun set-target-histories ()
(let ((ol (get-parameter-value :ol)))
(dolist (x *sentences*)
;; find the chunk
(let ((chunk (car (no-output (sdm-fct (list 'arg1 (first x) 'arg2 (second x)))))))
;; creation time of targets is the start of study period
(sdp-fct (list chunk :creation-time (- *study-length*)))
;; history is 1 + 2 * 2 * *tries-per-drop-out*
;; initial presentation plus two retrievals per try per drop-out
(setf (chunk-al-ni-count chunk) (+ 1 (* 2 2 *tries-per-drop-out*)))
;; use the same time steps as with the probes
(when (numberp ol)
(do ((delay (/ *study-length* ol))
(time (- *study-length*) (+ time delay))
(count ol (1- count))
(times nil (cons time times)))
((zerop count)
(setf (chunk-al-ni-refs chunk) (mapcar 'sec->ms times)))))))))
(defun set-relational-histories ()
(let ((ol (get-parameter-value :ol)))
(dolist (x *sentences*)
;; find the chunk
(let ((chunk (car (no-output (sdm-fct (list 'arg1 (first x) 'arg2 (second x)))))))
;; history is 1 + 2 * *tries-per-drop-out* for each probe
;; initial presentation (both) one try per retrieval (each) per drop-out
;; and 1 + 2 * 2 * tries-per-drop-out* for in
(push (cons chunk (+ 1 (* 2 *tries-per-drop-out*))) (chunk-al-ni+cj-count (first x)))
(push (cons chunk (+ 1 (* 2 *tries-per-drop-out*))) (chunk-al-ni+cj-count (second x)))
(push (cons chunk (+ 1 (* 2 2 *tries-per-drop-out*))) (chunk-al-ni+cj-count 'in))
;; use the same time steps as with the probes
(when (numberp ol)
(do ((delay (/ *study-length* ol))
(time (- *study-length*) (+ time delay))
(count ol (1- count))
(times nil (cons time times)))
((zerop count)
(progn
(push (cons chunk (mapcar 'sec->ms times)) (chunk-al-ni+cj-refs (first x)))
(push (cons chunk (mapcar 'sec->ms times)) (chunk-al-ni+cj-refs (second x)))
(push (cons chunk (mapcar 'sec->ms times)) (chunk-al-ni+cj-refs 'in))))))))))
;; Need to set these directly in the module since
;; they aren't associated with a chunk and don't
;; have global parameters to hold them.
(defun set-total-history ()
(let ((al (get-module associative-learning)))
(setf (al-module-total-count al) *global-history-count*)
(setf (al-module-total-creation-time al) (sec->ms *global-history-creation*))
;; use same time steps as everything else
(when (numberp (al-module-ol al))
(do ((delay (/ *study-length* (al-module-ol al)))
(time (- *study-length*) (+ time delay))
(count (al-module-ol al) (1- count))
(times nil (cons time times)))
((zerop count)
(setf (al-module-total-refs al) (mapcar 'sec->ms times)))))))
;;; Set the underlying associative learning parameters based on the
;;; values specified in the variables above, set the ACT-R parameters
;;; based on the provided values, and then compute the time for the retrieval
;;; of the sentences.
;;;
;;; Make sure a valid :ol value is provided. Then reset
;;; the model, set the :lf and :ol values, add the chunks
;;; for the study items to DM, set the initial histories,
;;; and report the results.
(defun approach-2-results (lf &key (ol t) (prior-p .01) (prior-w 10))
;; safety checks
(when (null ol)
(print-warning "Can't run if :ol is nil because of the history lengths. Using t instead.")
(setf ol t))
(unless (or (eq ol t) (and (integerp ol) (plusp ol)))
(print-warning ":ol parameter must be t or a positive integer but given ~s. Using t instead." ol)
(setf ol t))
(reset)
(suppress-warnings ;; changing declarative parameters
;; with chunks in DM triggers a warning
;; but since we're setting all the history
;; this isn't really a problem.
(set-parameter-value :lf lf)
(set-parameter-value :ol ol))
(set-parameter-value :al-prior-p prior-p)
(set-parameter-value :al-prior-w prior-w)
(create-sentence-chunks)
(set-probe-histories)
(set-target-histories)
(set-relational-histories)
(set-total-history)
(output-person-location
(time-to-retrieve-at-start)))
;;; Print the table of data and the comparison stats
(defun output-person-location (data)
(correlation data *person-location-data*)
(mean-deviation data *person-location-data*)
(format t "TARGETS:~% Person fan~%")
(format t " Location 1 2 3~%")
(format t " fan")
(dotimes (i 3)
(format t "~% ~d " (1+ i))
(dotimes (j 3)
(format t "~8,3F " (nth (+ j (* i 3)) data))))
(format t "~%~%FOILS:")
(dotimes (i 3)
(format t "~% ~d " (1+ i))
(dotimes (j 3)
(format t "~8,3F " (nth (+ j (* (+ i 3) 3)) data)))))
| 25,403 | Common Lisp | .lisp | 502 | 42.531873 | 135 | 0.592286 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 42e00c586a5f50d304d2d06627983bdf307fc40d55d88cc5fdf0008e5086c43b | 14,265 | [
312429
] |
14,266 | associative-learning.lisp | asmaloney_ACT-R/extras/associative-learning/associative-learning.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2020 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : associative-learning.lisp
;;; Version : 0.6
;;;
;;; Description : Reintroduce learning of Sji values with a new approach.
;;;
;;; Bugs :
;;;
;;; To do : [ ] Should it use Sji values that are set explicitly with
;;; add-sji to override the learned value?
;;; : [ ] Should sdp report ALL "non-default" Sji values for a
;;; chunk instead of just those that were sources -- any
;;; chunk with some history is going to have an Sji that's
;;; different from the default but is that useful?
;;;
;;; ----- History -----
;;; 2020.09.02 Dan [0.1]
;;; : * First pass at implementation.
;;; 2020.09.22 Dan [0.2]
;;; : * Fixed a bug in the activation trace output for the Sji
;;; : calculation -- was showing Nj data instead of the Ni values.
;;; : * Fixed an issue with merging time references when :ol is a
;;; : number.
;;; : * Added the :opa parameter to provide an option in how the F
;;; : value is computed.
;;; : * Only updated for a cleared buffer if it's enabled.
;;; : * Added a slot to store a creation time for F (which could
;;; : be computed as the min of all chunks' creation times, but
;;; : for now just storing one).
;;; 2020.09.28 Dan [0.3]
;;; : * Monitor :nsji and warn or force to 0 as indicated.
;;; 2020.10.30 Dan [0.4]
;;; : * Add a replacement for get-all-chunk-sjis so that sdp will
;;; : show all the associations that aren't the default value for
;;; : the items with their current value.
;;; : * Replace all instances of true-chunk-name as a key with the
;;; : version since it's being called as a function -- not sure
;;; : why those didn't error out...
;;; : [0.5]
;;; : * Now sdp also reports the Sji for the chunk to itself as well
;;; : even if it hasn't been a source.
;;; : [0.6]
;;; : * This is a significant change. Replacing the parameters for
;;; : setting the priors. Now there's :al-prior-p and
;;; : :al-prior-w. In addition to that instead of using the
;;; : approximation for P(Cj|Ni)/P(Cj|~Ni) use that directly and
;;; : compute the needed quantites by removing the relevant items
;;; : from the total history that's recorded (or partial in the
;;; : case of :ol being set).
;;; : * Also added the parameter :al-show which shows the details
;;; : of computing the Sji values even if :act is off.
;;; 2020.11.04 Dan
;;; : * Updated the documentation to appropriately describe the new
;;; : changes.
;;; 2021.10.18 Dan
;;; : * Changed call to buffers to model-buffers instead.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Implement the mechanism described in the Anderson_ACT-R-2020-workshop slides
;;; with these changes/clarifications:
;;;
;;; - Using P(Cj|Ni)/P(Cj|~Ni) instead of the approximation P(Ni|Cj)/P(Ni).
;;; That makes the Sji = log [(F(Ni&Cj)/F(Ni))/(F(~Ni&Cj)/F(~Ni))] not
;;; counting the new parameters for priors described below.
;;;
;;; - The decay will use the optimized learning formulas when they are enabled.
;;;
;;; - Instead of only the imaginal buffer, it applies to all buffers that have
;;; a non-zero activation spread at model definition time. Any changes to the
;;; buffer spread paramters after the model is defined will not affect how this
;;; module operates with respect to those buffers i.e. if it was on but set to
;;; zero it's still going to be considered a source and if it was zero but set
;;; to non-zero it isn't going to be considered a source.
;;;
;;; - With respect to handling multiple source buffers, if multiple source
;;; buffers are simultaneously cleared it will result in them not being
;;; associated with each others' contents. This is done for ease of
;;; implementation at this point because without significant additional code
;;; there would be ordering issues in such a situation (and that order isn't
;;; completely in the modeler's control or guaranteed to be consistent). If
;;; associating the contents of multiple simultaneously cleared source buffers
;;; is found to be needed, the module can be updated to handle that.
;;;
;;; - Instead of a single parameter for a prior value that gets added to all
;;; of the F values, use a prior probability and a weight, which if they are
;;; called p and w respectively results in this equation for Sji:
;;;
;;; Sji = log [((F(Ni&Cj) + pw)/(F(Ni) + w)) /((F(~Ni&Cj) + pw)/(F(~Ni) + w))]
;;;
;;;
;;; If the :act parameter is set then this module will display the details of
;;; all the Sji calculations.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; Parameters:
;;; :eal - enable associative learning
;;; Set to the decay exponent to enable (.5 recomended)
;;; Will automatically set :mas to a number to enable the
;;; spreading activation calculation.
;;; :al-prior-p - associate learning prior probability
;;; the initial probability given to an association
;;; :al-prior-w - associative learning prior weight
;;; how much weight given to that prior value
;;; :al-show
;;; whether to display the details of the Sji calculations regardless
;;; of the settings of :act (:v must also be true for the output to
;;; actually be displayed)
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Create a separate module for it instead of trying to modify the normal
;;; module. Tie it in through the hook functions when enabled. Use chunk
;;; parameters to store the needed values where possible.
;;;
;;; The contents of the source buffers that are upated when a retrieval request
;;; happens are the same ones that are used to compute the spreading activation.
;;; That means any changes the production with the request makes occur before
;;; the sources are determined i.e. modifications and buffer clearing.
;;;
;;; Setting :mas to pi when :eal is set so that there's an easy check to see if
;;; it was automatically enabled so it can be turned off if :eal is set to nil
;;; (although turning things like :mas and :eal on/off after a model has been
;;; running isn't recommended).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(require-compiled "CENTRAL-PARAMETERS")
(defstruct al-module eal prior-p prior-w total-count total-refs (total-creation-time 0) ol buffers mas act
(lock (bt:make-recursive-lock)) scale last-retrieval-contexts dm-entry-method nsji show)
;; chunk i was needed -- either enters DM from a spreading buffer or gets retrieved
;; module does all of the updating (happens after the merge if there was one)
;; don't copy the value to new chunk
;; merge retains the c1 value
(suppress-extension-warnings)
(extend-chunks al-ni-count :default-value 0)
(extend-chunks al-ni-refs :default-value nil)
;; chunk j (this chunk) was in the context when a chunk either enters DM from a spreading buffer or gets retrieved
;; module updates new occurrences (happens after the merge if there was one)
;; don't copy the value to new chunk
;; merge needs to:
;; add the counts
;; interleave the times
(defun merge-time-lists (chunk1 chunk2)
(let* ((al (get-module associative-learning))
(ol (and (al-module-p al) (bt:with-recursive-lock-held ((al-module-lock al)) (al-module-ol al))))
(times (unless (eq ol t)
(do ((l1 chunk1)
(l2 chunk2)
(r nil))
((or (null l1) (null l2))
(if l1
(append r l1)
(append r l2)))
(cond ((< (car l1) (car l2))
(push-last (car l2) r)
(setf l2 (cdr l2)))
(t ;; same times or l2 smaller
(push-last (car l1) r)
(setf l1 (cdr l1))))))))
(if (and (numberp ol) times)
(subseq times
0 (min ol (1+ (length times))))
;; either it's nil or everything
times)))
(extend-chunks al-cj-count :default-value 0 :merge-value-function +)
(extend-chunks al-cj-refs :default-value nil :merge-value-function merge-time-lists)
;; chunk j (this chunk) was in the context when a chunk i either enters DM from a spreading buffer or gets retrieved
;; module updates new occurrences (happens after the merge if there was one so i should be the true-chunk name)
;; don't copy the value to new chunk
;; merge needs to:
;; add the counts for all matching i's
;; interleave the times for all matching i's
;;
;; the values are alists with i being the car
;; Use true-chunk-name for safety, even though that should already be the
;; case based on how things are updated.
(defun merge-ni+cj-counts (c1 c2)
(mapcar (lambda (i)
(cons i (+ (aif (assoc i c1 :key 'true-chunk-name-fct)
(cdr it)
0)
(aif (assoc i c2 :key 'true-chunk-name-fct)
(cdr it)
0))))
(remove-duplicates (append (mapcar 'car c1) (mapcar 'car c2)) :key 'true-chunk-name-fct)))
(defun merge-ni+cj-times (c1 c2)
(mapcar (lambda (i)
(cons i (merge-time-lists (aif (assoc i c1 :key 'true-chunk-name-fct)
(cdr it)
nil)
(aif (assoc i c2 :key 'true-chunk-name-fct)
(cdr it)
nil))))
(remove-duplicates (append (mapcar 'car c1) (mapcar 'car c2)) :key 'true-chunk-name-fct)))
(extend-chunks al-ni+cj-count :default-value nil :merge-value-function merge-ni+cj-counts)
(extend-chunks al-ni+cj-refs :default-value nil :merge-value-function merge-ni+cj-times)
;; Record the associated items with a chunk so that sdp can show
;; the sjis for those that have been learned and itself.
(defun default-associated-js (c)
(list c))
;; They haven't merged yet so need to remove c2's name from it's list, and
;; that will always be the last one since it pushes new js on the list.
(defun merge-associated-js (c1 c2)
(remove-duplicates (append c1 (butlast c2)) :key 'true-chunk-name-fct))
(extend-chunks associated-js :default-function default-associated-js :merge-value-function merge-associated-js)
(unsuppress-extension-warnings)
;;; Need to replace get-all-chunk-sjis to report all the values which
;;; have been learned for a chunk instead of the default set which are
;;; just itself, its chunk-filled-slots' values, and any set with add-sji.
;;; Since this module doesn't acknowledge the add-sji values in reporting
;;; an Sji we'll ignore those for now too.
(let ((original-sji-function #'get-all-chunk-sjis))
(defun get-all-chunk-sjis (dm chunk)
(let ((al (get-module associative-learning)))
(bt:with-recursive-lock-held ((al-module-lock al))
(if (null (al-module-eal al))
(funcall original-sji-function dm chunk)
(mapcar (lambda (x)
(list x (compute-learned-sji x chunk)))
(chunk-associated-js chunk)))))))
;;; Given chunks j and i return the learned Sji value
;;; using the declarative module's compute-references function
;;; that's used to compute the base-level learning from
;;; the references since it's the same equation and already
;;; handles all the :ol options.
(defun compute-learned-sji (j i)
(let ((al (get-module associative-learning)))
(when (and (chunk-p-fct i) (chunk-p-fct j))
(bt:with-recursive-lock-held ((al-module-lock al))
(let* ((p (al-module-prior-p al))
(w (al-module-prior-w al))
(ol (al-module-ol al))
(decay (- (al-module-eal al)))
(scale (al-module-scale al))
(nicj-count (aif (cdr (assoc i (chunk-al-ni+cj-count j))) it 0))
(nicj-refs (cdr (assoc i (chunk-al-ni+cj-refs j))))
(ni-count (aif (chunk-al-ni-count i) it 0))
(ni-refs (chunk-al-ni-refs i))
(~ni-refs (set-difference (al-module-total-refs al) ni-refs :test '=))
(~nicj-refs (set-difference (chunk-al-cj-refs j) nicj-refs :test '=))
(f~ni ;; Those items in the total not in ni
(if (zerop (- (al-module-total-count al) ni-count))
0
(exp (compute-references nil (- (al-module-total-count al) ni-count)
~ni-refs
(al-module-total-creation-time al)
decay nil (if (null ~ni-refs) t ol) (al-module-scale al) nil))))
(fni (if (zerop ni-count)
0
(exp (compute-references nil ni-count ni-refs (chunk-creation-time i)
decay nil ol scale nil))))
(f~nicj ;; remove those items from cj which are in nicj
(if (zerop (- (chunk-al-cj-count j) nicj-count))
0
(exp (compute-references nil (- (chunk-al-cj-count j) nicj-count)
~nicj-refs
(chunk-creation-time j)
decay nil (if (null ~nicj-refs) t ol) scale nil))))
(fnicj (if (zerop nicj-count) ;; shouldn't happen but just to be safe
0
(exp (compute-references nil nicj-count nicj-refs (chunk-creation-time i)
decay nil ol scale nil))))
(pcjni (/ (+ (* p w) fnicj) (+ w fni)))
(pcj~ni (/ (+ (* p w) f~nicj) (+ w f~ni)))
(sji (log (/ pcjni pcj~ni))))
(when (or (al-module-show al) (al-module-act al))
(model-output " Computing Sji from ~s to ~s with the decay set to ~f prior probability ~f and prior weight ~f" j i (- decay) p w)
(model-output " F(Ni&Cj) = ~f" fnicj)
(if nicj-count
(model-output " ~s was needed while ~s was in the context ~d times with history ~s" i j nicj-count nicj-refs)
(model-output " ~s was needed while ~s was in the context 0 times with history nil" i j))
(model-output " F(Ni) = ~f" fni)
(model-output " ~s was needed ~d times with history ~s" i ni-count ni-refs)
(model-output " F(~~Ni&Cj) = ~f" f~nicj)
(model-output " Retrieval of something other than ~s while ~s was in the context ~d times with history ~s"
i j (- (chunk-al-cj-count j) nicj-count) ~nicj-refs)
(model-output " F(~~Ni) = ~f" f~ni)
(model-output " Retrieval of something other than ~s happened ~d times with history ~s"
i (- (al-module-total-count al) ni-count) ~ni-refs)
(model-output " P(Cj|Ni) = ~f" pcjni)
(model-output " P(Cj|~~Ni) = ~f" pcj~ni)
(model-output " Sji = ~f" sji))
(when (minusp sji)
(cond ((eq (al-module-nsji al) 'warn)
(print-warning "Learned Sji value between ~s and ~s is negative, but using a value of 0." j i)
(setf sji 0))
((null (al-module-nsji al))
(setf sji 0))))
sji)))))
;;; Module interface functions
(defun create-al-module (name)
(declare (ignore name))
(make-al-module))
(defun primary-al-reset (al)
(bt:with-recursive-lock-held ((al-module-lock al))
(setf (al-module-eal al) nil) ;; normally just let sgp set it
;; but because it's used in other
;; parameter tests need to clear
;; it because order isn't guaranteed
(setf (al-module-total-count al) 0)
(setf (al-module-total-creation-time al) 0)
(setf (al-module-total-refs al) nil)
(setf (al-module-last-retrieval-contexts al) nil)
(setf (al-module-dm-entry-method al) nil)))
(defun finish-al-reset (al)
;; Record the buffers with non-zero source spread
;; at model definition time. Only those buffers
;; will be considered for associative learning
;; purposes.
(bt:with-recursive-lock-held ((al-module-lock al))
(setf (al-module-buffers al) nil)
(dolist (buffer (model-buffers))
(unless (zerop (buffer-spread buffer))
(if (eq buffer 'retrieval)
(print-warning "Associative learning will not consider the retrieval buffer as a source of activation.")
(push buffer (al-module-buffers al)))))))
(defun al-params (al param)
(bt:with-recursive-lock-held ((al-module-lock al))
(cond ((consp param)
(case (car param)
(:ol (setf (al-module-ol al) (cdr param)))
(:al-show (setf (al-module-show al) (cdr param)))
(:eal
;; Warn about decay values that create complex numbers
(when (and (al-module-ol al) (cdr param) (>= (cdr param) 1.0))
(print-warning "Setting :eal to a value >= 1 when optimized learning is enabled can result in complex numbers for Sjis and probably errors."))
;; Set the scale used by compute-references to handle ms->sec conversion
(when (cdr param) (setf (al-module-scale al) (log (expt 1/1000 (- (cdr param))))))
;; Set the value given so monitored hooks have the value
(setf (al-module-eal al) (cdr param))
(if (cdr param)
(set-parameter-value :mas pi)
(if (and (al-module-mas al)
(= (al-module-mas al) pi))
(set-parameter-value :mas nil)))
;; Set the Sji hook if being enabled or remove it if being
;; disabled and it's set
(if (cdr param)
(sgp :sji-hook compute-learned-sji)
(when (eq (get-parameter-value :sji-hook) 'compute-learned-sji)
(sgp :sji-hook nil)))
;; For the hook functions, add them if enabled and not there or
;; remove them if they are there and it's being disabled
#| Don't need these two currently but may change that
(if (cdr param)
(unless (find 'al-chunk-added (get-parameter-value :chunk-add-hook))
(sgp :chunk-add-hook al-chunk-added))
(when (find 'al-chunk-added (get-parameter-value :chunk-add-hook))
(sgp :chunk-add-hook (:remove al-chunk-added))))
(if (cdr param)
(unless (find 'al-chunk-merged (get-parameter-value :chunk-merge-hook))
(sgp :chunk-merge-hook al-chunk-merged))
(when (find 'al-chunk-merged (get-parameter-value :chunk-merge-hook))
(sgp :chunk-merge-hook (:remove al-chunk-merged))))
|#
(if (cdr param)
(unless (find 'al-chunk-retrieval-request (get-parameter-value :retrieval-request-hook))
(sgp :retrieval-request-hook al-chunk-retrieval-request))
(when (find 'al-chunk-retrieval-request (get-parameter-value :retrieval-request-hook))
(sgp :retrieval-request-hook (:remove al-chunk-retrieval-request))))
(if (cdr param)
(unless (find 'al-chunk-retrieved (get-parameter-value :retrieved-chunk-hook))
(sgp :retrieved-chunk-hook al-chunk-retrieved))
(when (find 'al-chunk-retrieved (get-parameter-value :retrieved-chunk-hook))
(sgp :retrieved-chunk-hook (:remove al-chunk-retrieved))))
;; return the value
(cdr param))
(:al-prior-p
(setf (al-module-prior-p al) (cdr param)))
(:al-prior-w
(setf (al-module-prior-w al) (cdr param)))
(:act
(setf (al-module-act al) (cdr param)))
(:nsji
(setf (al-module-nsji al) (cdr param)))
(:mas
(when (and (null (cdr param)) (al-module-eal al))
(print-warning "Turning off :mas will disable associative learning."))
(setf (al-module-mas al) (cdr param)))
;; For the hook function parameters check if the functions
;; are still there if enabled and they're changed.
;; If not, just print a warning -- don't try to "fix" it.
(:sji-hook
(when (al-module-eal al)
(unless (eq (cdr param) 'compute-learned-sji)
(print-warning "Setting the sji-hook while associative learning is enabled will prevent the learned Sji values from being used."))))
#| Not currently needed
(:chunk-add-hook
(when (al-module-eal al)
(cond ((null (cdr param))
(print-warning "Chunk-add-hook parameter cleared. This will affect the learning of Sji values."))
((and (listp (cdr param))
(eq (first param) :remove)
(eq (second param) 'al-chunk-added))
(print-warning "Associative learning's function was removed from the chunk-add-hook. This will affect the learning of Sji values.")))))
(:chunk-merge-hook
(when (al-module-eal al)
(cond ((null (cdr param))
(print-warning "Chunk-merge-hook parameter cleared. This will affect the learning of Sji values."))
((and (listp (cdr param))
(eq (first param) :remove)
(eq (second param) 'al-chunk-merged))
(print-warning "Associative learning's function was removed from the chunk-merge-hook. This will affect the learning of Sji values.")))))
|#
(:retrieval-request-hook
(when (al-module-eal al)
(cond ((null (cdr param))
(print-warning "Retrieval-request-hook parameter cleared. This will affect the learning of Sji values."))
((and (listp (cdr param))
(eq (first param) :remove)
(eq (second param) 'al-chunk-retrieval-request))
(print-warning "Associative learning's function was removed from the retrieval-request-hook This will affect the learning of Sji values.")))))
(:retrieved-chunk-hook
(when (al-module-eal al)
(cond ((null (cdr param))
(print-warning "Retrieved-chunk-hook parameter cleared. This will affect the learning of Sji values."))
((and (listp (cdr param))
(eq (first param) :remove)
(eq (second param) 'al-chunk-retrieved))
(print-warning "Associative learning's function was removed from the retrieved-chunk-hook This will affect the learning of Sji values.")))))))
(t
(case param
(:al-show
(al-module-show al))
(:eal
(al-module-eal al))
(:al-prior-p
(al-module-prior-p al))
(:al-prior-w
(al-module-prior-w al)))))))
;;; When a chunk clears from a buffer schedule an event to update the
;;; parameters if it was a source buffer.
;;;
;;; The event is scheduled so that it happens after all the buffers
;;; that are clearing have been cleared but before the retrieval
;;; request starts (since DM schedules that with a negative priority
;;; even though the request happens prior to buffers being cleared).
;;;
;;; Will consider its own slots as being in the context, and any
;;; other source buffers with chunks in them when the update occurs.
;;;
;;; NOTE: clearing multiple source buffers simultaneously will result
;;; in them not being associated with each others' contents.
;;; This is done for ease of implementation at this point, but if
;;; those associations are needed it could be updated to handle that.
(defun al-check-cleared-chunks (al buffer chunk)
(bt:with-recursive-lock-held ((al-module-lock al))
(when (and (al-module-eal al) (find buffer (al-module-buffers al)))
(schedule-event-now 'al-buffer-cleared :module 'associative-learning :params (list al chunk) :output nil :priority 5))))
(define-module-fct 'associative-learning nil
(list (define-parameter :eal :valid-test 'posnumornil :default-value nil
:warning "a positive number or nil"
:documentation "enable associative learning by setting a decay parameter")
(define-parameter :al-prior-p :valid-test 'posnum :default-value .01
:warning "a positive number"
:documentation "associative learning prior probability")
(define-parameter :al-prior-w :valid-test 'posnum :default-value 10
:warning "a positive number"
:documentation "associative learning prior weight")
(define-parameter :al-show :valid-test 'tornil :default-value t
:warning "T or nil"
:documentation "whether to show the Sji calculations even when :act is off")
(define-parameter :ol :owner nil)
(define-parameter :mas :owner nil)
(define-parameter :act :owner nil)
(define-parameter :nsji :owner nil)
(define-parameter :retrieval-request-hook :owner nil)
(define-parameter :retrieved-chunk-hook :owner nil)
(define-parameter :chunk-add-hook :owner nil)
(define-parameter :chunk-merge-hook :owner nil)
(define-parameter :sji-hook :owner nil))
:version "0.6"
:documentation "When enabled, compute Sji values from past experiences."
:creation 'create-al-module
:reset (list 'primary-al-reset nil 'finish-al-reset)
:notify-on-clear 'al-check-cleared-chunks
:params 'al-params)
;;; Functions to detect the necessary situations and record or
;;; update the information as necessary.
;; Just note which situation occurred for the buffer being cleared
;; Don't need this, but if it is needed in the future it's a little
;; tricky because we don't know which buffer so end up recording
;; ones that aren't important for learning and need to be removed
;; later some how...
(defun al-chunk-added (c)
(declare (ignore c))
;(let ((al (get-module associative-learning)))
; (bt:with-recursive-lock-held ((al-module-lock al))
; (push (cons c :added) (al-module-dm-entry-method al))))
)
;; the original name is passed and it hasn't actually merged yet...
;; same as above
(defun al-chunk-merged (c)
(declare (ignore c))
;(let ((al (get-module associative-learning)))
; (bt:with-recursive-lock-held ((al-module-lock al))
; (push (cons c :merged) (al-module-dm-entry-method al))))
)
;;; Return a list of the chunks that are in slots of the source buffers.
(defun source-buffer-chunks (al)
(let ((r nil))
(dolist (buffer (al-module-buffers al) r)
(awhen (buffer-read buffer)
(dolist (slot (chunk-filled-slots-list-fct it))
(let ((val (fast-chunk-slot-value-fct it slot)))
(when (chunk-p-fct val)
(push val r))))))))
;;; Just record the chunks that are in slots of source buffers.
(defun al-chunk-retrieval-request (spec)
(declare (ignore spec))
(let ((al (get-module associative-learning)))
(bt:with-recursive-lock-held ((al-module-lock al))
(setf (al-module-last-retrieval-contexts al) (source-buffer-chunks al)))))
;;; When the retrieval happens update the parameters where the
;;; DM chunk is i, and the js are the chunks that were in the
;;; context at the retrieval time.
(defun al-chunk-retrieved (chunk)
(when chunk ;; failure passes nil
(let ((al (get-module associative-learning)))
(bt:with-recursive-lock-held ((al-module-lock al))
(update-al-parameters al chunk (al-module-last-retrieval-contexts al))))))
;;; This is called when a buffer clears. Update the parameters
;;; where i is the cleared chunk if it was added into DM or the
;;; DM chunk if the chunk was merged into DM and the js are
;;; the current sources plus the chunk filled slots of chunk i.
(defun al-buffer-cleared (al chunk)
(bt:with-recursive-lock-held ((al-module-lock al))
(when (al-module-eal al)
(let (;not needed because added and merged are treated the same
;(check (assoc chunk (al-module-dm-entry-method al)))
(self-sources (mapcan (lambda (slot)
(let ((val (fast-chunk-slot-value-fct chunk slot)))
(when (chunk-p-fct val)
(list val))))
(chunk-filled-slots-list-fct chunk))))
; not needed
;(setf (al-module-dm-entry-method al) (remove check (al-module-dm-entry-method al)))
;; Don't need this distinction, but putting this here for now incase a need to treat
;; those two separately is found. That will require restoring the code for the
;; hook functions and determining how to deal with chunks from other buffers in those
;; functions.
;(case (cdr check)
; (:added
; (update-al-parameters al chunk (append self-sources (source-buffer-chunks al))))
; (:merged
; (update-al-parameters al (true-chunk-name-fct chunk) (append self-sources (source-buffer-chunks al)))))
(update-al-parameters al (true-chunk-name-fct chunk) (append self-sources (source-buffer-chunks al)))))))
;;; Given a needed chunk i and the context chunk js update
;;; all the chunk parameters.
;;;
;;; Only called while the lock is held, so don't need to
;;; grab that again here.
(defun needed-times (ol ct times)
(unless (eq ol t) ;; don't need the times when t
(push ct times)
(if (numberp ol)
(subseq times
0 (min ol (1+ (length times))))
times)))
(defun update-al-parameters (al i js)
(let ((ct (mp-time-ms))
(ol (al-module-ol al)))
;; Update the global values in the module
(incf (al-module-total-count al))
(setf (al-module-total-refs al)
(needed-times ol ct (al-module-total-refs al)))
;; Update the needs i values
(incf (chunk-al-ni-count i))
(setf (chunk-al-ni-refs i)
(needed-times ol ct (chunk-al-ni-refs i)))
;; For all chunks j in the context
(dolist (j js)
;; record that there's now an association between j and i
(pushnew j (chunk-associated-js i) :key 'true-chunk-name-fct)
;; Update the j in context values
(incf (chunk-al-cj-count j))
(setf (chunk-al-cj-refs j)
(needed-times ol ct (chunk-al-cj-refs j)))
;; Update the needs i with j in context values
(aif (assoc i (chunk-al-ni+cj-count j))
(incf (cdr it))
(push (cons i 1) (chunk-al-ni+cj-count j)))
(aif (assoc i (chunk-al-ni+cj-refs j))
(setf (cdr it) (needed-times ol ct (cdr it)))
(push (cons i (needed-times ol ct nil)) (chunk-al-ni+cj-refs j))))))
;; So it gets recorded as available when required
(provide "associative-learning")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 34,364 | Common Lisp | .lisp | 625 | 45.1536 | 165 | 0.591168 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | dd8a82e09ab71f56a68c9970f41a16a9ff30b65946c4842343f125a7694c94ea | 14,266 | [
-1
] |
14,267 | WNLexical_3-0-2.lisp | asmaloney_ACT-R/extras/WNLexicalModule/WNLexical_3-0-2.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : WNLexical_3-0-2.lisp
;;; Version : 3.0.2
;;;
;;; Description : ACT-R/WNLexical
;;;
;;; WNLexical is an implementation of WordNet for the Act-r
;;; cognitive architecture. WNLexical is an Act-r module and
;;; was developped from the prolog files distributed with
;;; WordNet Release 3.0.
;;; The first digits of the version number match the WordNet version number.
;;; The last digit distinguishes WNLexical versions.
;;;
;;; License : **** WNLexical license ****
;;;
;;; Copyright : (C) 2005, Bruno Emond,
;;; Institute for Information Technology,
;;; National Research Council Canada.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the Preamble to the GNU Lesser
;;; General Public License as published by Franz Incorporated,
;;; Berkeley, CA 94704, and the GNU Lesser General Public License
;;; as published by the Free Software Foundation; either
;;; version 2.1 of the License.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the Preamble to the GNU Lesser
;;; General Public License and the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;;
;;; The Preamble to the GNU Lesser General Public License and the
;;; GNU Lesser General Public License is located in the following
;;; directory relative to the location of this file:
;;; ../WNLexicalData/LLGPL.txt
;;; ../WNLexicalData/LGPL.txt
;;;
;;;
;;; License : **** WordNet Release 3.0 license ****
;;;
;;; WordNet Release 3.0
;;;
;;; This software and database is being provided to you, the LICENSEE, by
;;; Princeton University under the following license. By obtaining, using
;;; and/or copying this software and database, you agree that you have
;;; read, understood, and will comply with these terms and conditions.:
;;;
;;; Permission to use, copy, modify and distribute this software and
;;; database and its documentation for any purpose and without fee or
;;; royalty is hereby granted, provided that you agree to comply with
;;; the following copyright notice and statements, including the disclaimer,
;;; and that the same appear on ALL copies of the software, database and
;;; documentation, including modifications that you make for internal
;;; use or for distribution.
;;;
;;; WordNet 3.0 Copyright 2006 by Princeton University. All rights reserved.
;;;
;;; THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON
;;; UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
;;; IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON
;;; UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-
;;; ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE
;;; OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT
;;; INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR
;;; OTHER RIGHTS.
;;;
;;; The name of Princeton University or Princeton may not be used in
;;; advertising or publicity pertaining to distribution of the software
;;; and/or database. Title to copyright in this software, database and
;;; any associated documentation shall at all times remain with
;;; Princeton University and LICENSEE agrees to preserve same.
;;;
;;;
;;; The Wordnet License is located in the following directory relative to
;;; the location of this file:
;;; ../WNLexicalData/WordNet-License.txt
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; History
;;;
;;; BE - Bruno Emond
;;; DB - Dan Bothell
;;;
;;; 2005.11.15 BE - Version 0.1 of WNLexical for Act-r 6.0
;;; 2006.05.17 BE - Version 1.0 for first SourceForge distribution.
;;; 2006.05.22 DB - Add packaged-actr compiling instructions.
;;; - Change location of the 'WNLexixalData' directory and use of the
;;; logical pathname "ACT-R6:".
;;; - Remove buffer case in method 'wnl-module-and-buffer-query',
;;; which handles module queries.
;;; - Move the call that loads WNChunks into declarative memory
;;; from the module reset method to the one that handles the
;;; module parameters.
;;; 2006.05.26 BE - Replace the function (use-wnl-lexical) by a general parameter, :wnl.
;;; - Add a warning message when a model makes a WNLexical module or buffer
;;; queriy and wnl-chunks are not loaded in the module.
;;;
;;; 2007.08.22 BE - WNLexical version 3.0.1 : Upgrade to WordNet 3.0
;;;
;;; 2008.06.16 BE - Add the condition that if the synset context is empty, select a chunk
;;; at random. Otherwise use the set-difference or intersection operators.
;;; Set difference applies to chunk id, while intersection applies to
;;; synset-ids.
;;; 2014.07.07 DB - Changed the chunk-type and request functions to work with the ACT-R 6.1
;;; mechanism by just adding default slots for the request types and testing
;;; for the existence of those slots.
;;; 2015.07.28 DB - Changed the logicals to ACT-R.
;;; 2018.08.24 DB - Removed *wnl-code-pathname-directory* because it's unused and not where
;;; the file should be found now anyway.
;;; - Added a lock for parameters and queries.
;;; 2020.01.10 DB - Removed the #' from module interface functions because that's not
;;; allowed now for the general system.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; To do
;;;
;;; 2005.05.26 BE - Loading in declarative memory is very slow.
;;; - Add word frequency information.
;;;
;;; 2007.08.22 BE - Proper integration sense key operator (sk).
;;;
;;; 2018.08.24 DB - Does it need more locks?
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; actr package
;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; parameters
;;;
(defparameter *wordnet-lexical-version* "3.0.2")
(defparameter *wordnet-lexical-documentation* "WN-Lexical: An ACT-R module implementing the Wordnet lexical database." )
(defparameter *wnl-data-pathname-directory*
(pathname-directory
(translate-logical-pathname (logical-pathname "ACT-R:WNLexicalData;"))))
(defparameter *wordnet-lexical-modules* nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; wn-htable
;;;
(defclass wn-htable ()
((htable :initform (make-hash-table :test #'equal) :accessor htable)
(data-directory :initform *wnl-data-pathname-directory* :accessor data-directory)
(data-source :initarg :data-source :accessor data-source)))
(defmethod empty-htable ((wn-htable wn-htable))
(if (equal 0 (hash-table-count (htable wn-htable)))
t nil))
(defclass wn-chunks (wn-htable)
((data-source :initform "WNChunks")))
(defmethod get-index-value ((wn-htable wn-chunks) (key symbol))
(gethash key (htable wn-htable)))
(defclass wn-indexes (wn-htable)
((data-source :initform "WNChunksIndexes")))
(defmethod get-index-value ((wn-htable wn-indexes) (key number))
(gethash key (htable wn-htable)))
(defmethod get-index-value ((wn-htable wn-indexes) (key string))
(gethash key (htable wn-htable)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; indexes
;;;
(defclass word-senses-index ()
((word :initform nil :initarg :key :accessor key)
(senses :initform nil :accessor senses)))
(defclass synset-wn-operators-index ()
((synset-id :initform nil :initarg :key :accessor key)
(s :initform nil)
(sk :initform nil)
(g :initform nil)
(syntax :initform nil)
(hyp :initform nil)
(ins :initform nil)
(ent :initform nil)
(sim :initform nil)
(mm :initform nil)
(ms :initform nil)
(mp :initform nil)
(der :initform nil)
(cls :initform nil)
(cs :initform nil)
(vgp :initform nil)
(at :initform nil)
(ant :initform nil)
(sa :initform nil)
(ppl :initform nil)
(per :initform nil)
(fr :initform nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; wordnet-lexical-module
;;;
(defclass wordnet-lexical-module ()
((load-wnl-chunks :initform nil
:accessor load-wnl-chunks
:documentation "Parameter for determining if WN-CHUNKS are loaded in the module. Save time and memory resources when actr does not use WNLexical.")
(wnl-dm :initform nil
:accessor wnl-dm
:documentation "Parameter for determining if WN-CHUNKS are also loaded in declarative memory")
(wnl-chunks :initform (make-instance 'wn-chunks)
:accessor wnl-chunks
:documentation "WordNet-Lexical chunks.")
(wnl-indexes :initform (make-instance 'wn-indexes)
:accessor wnl-indexes
:documentation "Indexes for the WordNet-Lexical chunks.")
(synset-context :initform nil
:accessor synset-context
:documentation "A list of recent wordnet chunks retrieved.")
(busy-state :initarg :busy-state
:initform nil
:accessor busy-state
:documentation "Hold the state of the module. Request on the state returns either busy or free")
(failed-state :initarg :failed-state
:initform nil
:accessor failed-state
:documentation "Hold the state of the module it a process failled. Request on the state returns either error or t.")
(wn-lock :initform (bt:make-lock "WNLexical")
:accessor wn-lock
:documentation "Lock to protect parameter and state access.")
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; wordnet-lexical-modules
;;;
(defclass wordnet-lexical-modules ()
((model-names :initarg :model-names :initform nil :accessor model-names)
(shared-module :initarg :shared-module
:initform (make-instance 'wordnet-lexical-module)
:accessor shared-module)))
(defun reset-wordnet-lexical-modules ()
(setf *wordnet-lexical-modules*
(make-instance 'wordnet-lexical-modules)))
(reset-wordnet-lexical-modules)
(defmethod loaded-wnl-for-model ((wordnet-lexical-modules wordnet-lexical-modules) model-name)
(member model-name (model-names wordnet-lexical-modules)))
(defmethod set-wnl-for-model ((wordnet-lexical-modules wordnet-lexical-modules) model-name)
(push model-name (model-names wordnet-lexical-modules))
(setf *wordnet-lexical-modules* wordnet-lexical-modules))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; wordnet-lexical-module
;;; Methods
;;;
(defmethod wnl-ready ((wnl wordnet-lexical-module))
(if (and (load-wnl-chunks wnl)
(not (empty-htable (wnl-chunks wnl)))
(not (empty-htable (wnl-indexes wnl))))
t nil))
(defmethod clear-synset-context ((wnl wordnet-lexical-module))
(setf (synset-context wnl) nil)
(setf (busy-state wnl) nil))
;;; wn-chunks methods
;;;
(defmethod get-chunk-spec ((wnl wordnet-lexical-module) (wn-chunk-name symbol))
(get-index-value (wnl-chunks wnl) wn-chunk-name))
(defmethod get-synset-id ((wnl wordnet-lexical-module) (wn-chunk-name symbol))
(if (chunk-p-fct wn-chunk-name)
(chunk-slot-value-fct wn-chunk-name 'synset-id)
(nth 4 (get-chunk-spec wnl wn-chunk-name))))
(defmethod define-wn-chunk ((wnl wordnet-lexical-module) (wn-chunk-name symbol))
(if (chunk-p-fct wn-chunk-name)
wn-chunk-name
(car (define-chunks-fct (list (get-chunk-spec wnl wn-chunk-name))))))
;;; indexes methods
;;;
(defmethod get-synset-operator-chunk-names ((wnl wordnet-lexical-module) (synset-id number) (operator symbol))
(slot-value (get-index-value (wnl-indexes wnl) synset-id) operator))
(defmethod get-synset-operator-chunk-specs ((wnl wordnet-lexical-module) (synset-id number) (operator symbol))
(let (wn-chunk-specs)
(dolist (wn-chunk-name (get-synset-operator-chunk-names wnl synset-id operator))
(push (get-chunk-spec wnl wn-chunk-name) wn-chunk-specs))
wn-chunk-specs))
(defmethod get-word-sense-names ((wnl wordnet-lexical-module) (word string))
(let ((word-senses-index (get-index-value (wnl-indexes wnl) word)))
(when word-senses-index
(senses word-senses-index))))
(defmethod get-word-senses ((wnl wordnet-lexical-module) (word string))
(let (wn-chunk-specs)
(dolist (wn-chunk-name (get-word-sense-names wnl word))
(push (get-chunk-spec wnl wn-chunk-name) wn-chunk-specs))
wn-chunk-specs))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; act-r interface
;;;
;;;
;;; Module creation
;;;
(defmethod wnl-module-creation ((model-name symbol))
(unless (loaded-wnl-for-model *wordnet-lexical-modules* model-name)
(set-wnl-for-model *wordnet-lexical-modules* model-name))
(shared-module *wordnet-lexical-modules*))
;;;
;;; Module reset
;;;
(defmethod wnl-module-reset ((wnl (eql nil)))
nil)
(defmethod wnl-module-reset ((wnl wordnet-lexical-module))
(make-actr-wnl-chunk-types)
(bt:with-lock-held ((wn-lock wnl))
(setf (synset-context wnl) nil
(busy-state wnl) nil
(failed-state wnl) nil))
wnl)
;;;
;;; Module query
;;;
(defmethod wnl-module-and-buffer-query ((wnl wordnet-lexical-module)
(buffer-name symbol) (slot-name symbol) (slot-value symbol))
(bt:with-lock-held ((wn-lock wnl))
(if (wnl-ready wnl)
(case slot-name
(state
(case slot-value
(busy
(busy-state wnl))
(free
(not (busy-state wnl)))
(success
(not (failed-state wnl)))
(error
(failed-state wnl))
(empty-context
(not (synset-context wnl)))
(t (print-warning
"Invalid module-state query for buffer ~S with value ~S (must be either busy, free, success, error, or empty-context)."
buffer-name slot-value))))
(t (print-warning
"Invalid module query for buffer ~S with slot ~S (must be either state, or buffer)."
buffer-name slot-name)))
(model-warning "WNL-CHUNKS are not loaded. Use (sgp :wnl-chunks wnl) at the top of your model."))))
;;;
;;; Module request
;;;
(defmethod get-wn-chunks ((wnl wordnet-lexical-module) wn-operator word synset-id)
(let (chunk-specs)
(cond ((and word synset-id)
(if (member synset-id (get-word-senses wnl word) :key #'get-synset-id)
(setf chunk-specs (get-synset-operator-chunk-specs wnl synset-id wn-operator))
(model-warning "The request with word ~S and synset-id ~S is inconsistent. Word senses are: ~S." word synset-id (get-word-senses wnl word))))
(word
(if (equal 's wn-operator)
(setf chunk-specs (get-word-senses wnl word))
(model-warning "An initial request with word ~S and wn-operator S must be done prior to a request with wn-operator ~S." word wn-operator)))
(synset-id
(setf chunk-specs (get-synset-operator-chunk-specs wnl synset-id wn-operator))))
chunk-specs))
(defmethod apply-selection-criterion ((wnl wordnet-lexical-module) (retrieved-wn-chunks list) (criterion symbol))
(flet ((pick (lst)
(when lst
(nth (random (length lst)) lst))))
(case criterion
(set-intersection
(if (synset-context wnl)
(pick (intersection (synset-context wnl) retrieved-wn-chunks
:key #'(lambda (x) (get-synset-id wnl (car x)))
))
(pick retrieved-wn-chunks)))
(set-difference
(if (synset-context wnl)
(pick (set-difference retrieved-wn-chunks (synset-context wnl)
:key #'car ;#'(lambda (x) (get-synset-id wnl (car x)))
))
(pick retrieved-wn-chunks)))
(otherwise
(pick retrieved-wn-chunks)))))
(defmethod select-from-retrieved-wn-chunks ((wnl wordnet-lexical-module) (retrieved-wn-chunks list) (criterion symbol))
(let ((wn-chunk-spec (apply-selection-criterion wnl retrieved-wn-chunks criterion)))
(format nil "~S" wn-chunk-spec)
(dolist (event (busy-state wnl))
(delete-event event))
(setf (busy-state wnl) nil
(synset-context wnl) (union (synset-context wnl)
(when wn-chunk-spec (list wn-chunk-spec)) :key #'car))
(if wn-chunk-spec
(schedule-set-buffer-chunk 'wn-lexical (define-wn-chunk wnl (car wn-chunk-spec)) 0
:module 'wn-lexical
:priority :max)
(setf (failed-state wnl) t))))
(defmethod retrieve-wn-chunks ((wnl wordnet-lexical-module) (request t))
(if (and (slot-in-chunk-spec-p request 'wnl-request)
(slot-in-chunk-spec-p request 'wn-operator)
(or (slot-in-chunk-spec-p request 'word)
(slot-in-chunk-spec-p request 'synset-id)))
(let* ((wn-operator (third (car (chunk-spec-slot-spec request 'wn-operator))))
(word (when (slot-in-chunk-spec-p request 'word)
(third (car (chunk-spec-slot-spec request 'word)))))
(synset-id (when (slot-in-chunk-spec-p request 'synset-id)
(third (car (chunk-spec-slot-spec request 'synset-id)))))
(context-criterion (when (slot-in-chunk-spec-p request 'context-criterion)
(third (car (chunk-spec-slot-spec request 'context-criterion)))))
(retrieved-wn-chunks (get-wn-chunks wnl wn-operator word synset-id)))
(if retrieved-wn-chunks
(push (schedule-event-relative 0 'select-from-retrieved-wn-chunks
:module 'wn-lexical
:destination 'wn-lexical
:details (if context-criterion
(format nil "SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE ~S CRITERION IS ~S BETWEEN RETRIEVED-CHUNKS ~S AND CONTEXT ~S"
(length retrieved-wn-chunks) context-criterion
(mapcar #'(lambda (x) (nth 0 x)) retrieved-wn-chunks) (mapcar #'(lambda (x) (nth 0 x)) (synset-context wnl)))
(format nil "SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE ~S CRITERION IS RANDOM FROM RETRIEVED-CHUNKS ~S"
(length retrieved-wn-chunks)
(mapcar #'(lambda (x) (nth 0 x)) retrieved-wn-chunks)))
:priority -2000
:params (list retrieved-wn-chunks context-criterion)
:output 'medium)
(busy-state wnl))
(progn
(dolist (event (busy-state wnl))
(delete-event event))
(setf (busy-state wnl) nil
(failed-state wnl) t))))
(model-warning "A request to the wn-lexical module must be a chunk of type WNL-REQUEST, and have a value for the slot WN-OPERATOR, and have values for either WORD or SYNSET-ID, or both. Processing stopped.")))
(defmethod wnl-module-request ((wnl wordnet-lexical-module) (buffer-name symbol) (request t))
(declare (ignore buffer-name))
(if (wnl-ready wnl)
(bt:with-lock-held ((wn-lock wnl))
(when (busy-state wnl)
(model-warning "A lexical access event has been aborted by a new request")
(dolist (event (busy-state wnl))
(delete-event event)))
(setf (failed-state wnl) nil)
(setf (busy-state wnl)
(cond
((slot-in-chunk-spec-p request 'wnl-request)
(list (schedule-event-relative 0 'retrieve-wn-chunks
:module 'wn-lexical
:destination 'wn-lexical
:details (symbol-name 'retrieve-wn-chunks)
:priority -1000
:params (list request)
:output 'medium)))
((slot-in-chunk-spec-p request 'wnl-clear)
(list (schedule-event-relative 0 'clear-synset-context
:module 'wn-lexical
:destination 'wn-lexical
:details (symbol-name 'clear-wn-lexical-synset-context)
:priority -1000
:params nil
:output 'medium))))))
(model-warning "WNL-CHUNKS are not loaded. Use (sgp :wnl-chunks wnl) at the top of your model.")))
; (case (chunk-spec-chunk-type chunk-spec)
; (clear ;; replaces the implicit clear from -manual
; (schedule-event-relative 0 'clear :module :motor :destination :motor
; :output 'medium)
; )
; (execute
; (schedule-event-relative 0 'execute :module :motor :destination :motor
; :output 'medium)
;;;
;;; Module parameters
;;;
(defmethod get-wn-slot-names ((wn-operator symbol))
(case wn-operator
;;;;;; s(synset_id,w_num,'word',ss_type,sense_number,tag_count).
;;; A s operator is present for every word sense in WordNet.
;;; In wn_s.pl , w_num specifies the word number for word in the synset.
(s '(synset-id w-num word ss-type sense-number tag-count))
;;;;;; sk(synset_id,w_num,'sense_key').
;;; A sk operator is present for every word sense in WordNet.
;;; This gives the WordNet sense key for each word sense.
(sk '(synset_id w_num sense_key))
;;;;;; g(synset_id,'(gloss)').
;;; The g operator specifies the gloss for a synset.
(g '(synset-id gloss))
;;;;;; syntax(synset_id,w_num,syntax).
;;; The syntax operator specifies the syntactic marker for a given
;;; word sense if one is specified.
(syntax '(synset_id w_num syntax))
;;;;;; hyp(synset_id,synset_id).
;;; The hyp operator specifies that the second synset is a hypernym
;;; of the first synset. This relation holds for nouns and verbs.
;;; The reflexive operator, hyponym, implies that the first synset
;;; is a hyponym of the second synset.
(hyp '(synset-id synset-id2))
;;;;;; ins(synset_id,synset_id).
;;; The ins operator specifies that the first synset is an instance
;;; of the second synset. This relation holds for nouns. The reflexive
;;; operator, has_instance, implies that the second synset is an
;;; instance of the first synset.
(ins '(synset_id synset_id2))
;;;;;; ent(synset_id,synset_id).
;;; The ent operator specifies that the second synset is an
;;; entailment of first synset. This relation only holds for verbs.
(ent '(synset-id synset-id2))
;;;;;; sim(synset_id,synset_id).
;;; The sim woperator specifies that the second synset is similar
;;; in meaning to the first synset. This means that the second synset
;;; is a satellite the first synset, which is the cluster head.
;;; This relation only holds for adjective senses contained in
;;; adjective clusters.
(sim '(synset-id synset-id2))
;;;;;; mm(synset_id,synset_id).
;;; The mm operator specifies that the second synset is a member
;;; meronym of the first synset. This relation only holds for nouns.
;;; The reflexive wn-operator, member holonym, can be implied.
(mm '(synset-id synset-id2))
;;;;;; ms(synset_id,synset_id).
;;; The ms operator specifies that the second synset is a substance
;;; meronym of the first synset. This relation only holds for nouns.
;;; The reflexive operator, substance holonym, can be implied.
(ms '(synset-id synset-id2))
;;;;;; mp(synset_id,synset_id).
;;; The mp operator specifies that the second synset is a part
;;; meronym of the first synset. This relation only holds for nouns.
;;; The reflexive operator, part holonym, can be implied.
(mp '(synset-id synset-id2))
;;;;;; der(synset_id,synset_id).
;;; The der operator specifies that there exists a reflexive
;;; lexical morphosemantic relation between the first and second
;;; synset terms representing derivational morphology.
(der '(synset-id w-num1 synset-id2 w-num2))
;;;;;; cls(synset_id,synset_id,class_type).
;;; The cls operator specifies that the first synset has been
;;; classified as a member of the class represented by the
;;; second synset.
(cls '(synset-id synset-id2 class-type))
;;;;;; cs(synset_id,synset_id).
;;; The cs operator specifies that the second synset is a
;;; cause of the first synset. This relation only holds for verbs.
(cs '(synset-id synset-id2))
;;;;;; vgp(synset_id,synset_id).
;;; The vgp operator specifies verb senses that are similar in
;;; meaning and should be grouped together when displayed in response
;;; to a grouped synset search.
(vgp '(synset-id w-num1 synset-id2 w-num2))
;;;;;; at(synset_id,synset_id).
;;; The at operator defines the attribute relation between noun and
;;; adjective synset pairs in which the adjective is a value of the noun.
;;; For each pair, both relations are listed (ie. each synset_id is both
;;; a source and target).
(at '(synset-id synset-id2))
;;;;;; ant(synset_id,w_num,synset_id,w_num).
;;; The ant operator specifies antonymous word s. This is a lexical
;;; relation that holds for all syntactic categories. For each antonymous
;;; pair, both relations are listed (ie. each synset_id,w_num pair is both
;;; a source and target word.)
(ant '(synset-id w-num1 synset-id2 w-num2))
;;;;;; sa(synset_id,w_num,synset_id,w_num).
;;; The sa operator specifies that additional information about the first
;;; word can be obtained by seeing the second word. This wn-operator is only
;;; defined for verbs and adjectives. There is no reflexive relation
;;; (ie. it cannot be inferred that the additional information about the
;;; second word can be obtained from the first word).
(sa '(synset-id w-num1 synset-id2 w-num2))
;;;;;; ppl(synset_id,w_num,synset_id,w_num).
;;; The ppl operator specifies that the adjective first word is a participle
;;; of the verb second word. The reflexive wn-operator can be implied.
(ppl '(synset-id w-num1 synset-id2 w-num2))
;;;;;; per(synset_id,w_num,synset_id,w_num).
;;; The per operator specifies two different relations based on the parts
;;; of speech involved. If the first word is in an adjective synset, that
;;; word pertains to either the noun or adjective second word. If the first
;;; word is in an adverb synset, that word is derived from the adjective
;;; second word.
(per '(synset-id w-num1 synset-id2 w-num2))
;;;;;; fr(synset_id,f_num,w_num).
;;; The fr operator specifies a generic sentence frame for one or all
;;; words in a synset. The wn-operator is defined only for verbs.
(fr '(synset-id f-num w-num))))
(defun make-actr-wnl-chunk-types ()
(unless (chunk-type-p wnl-request)
(chunk-type wnl-request word synset-id wn-operator context-criterion (wnl-request t)))
(unless (chunk-type-p wnl-clear-context)
(chunk-type wnl-clear-context (wnl-clear t)))
(unless (chunk-p success)
(define-chunks (success isa chunk)))
(dolist (wn-operator '(s g hyp ent sim mm ms mp der cls cs vgp at ant sa ppl per fr))
(unless (chunk-type-p-fct wn-operator)
(eval `(chunk-type ,wn-operator ,@(get-wn-slot-names wn-operator))))))
(defmethod load-chunks-from-data-source ((wn-htable wn-htable) &optional (nb-lines nil))
(clrhash (htable wn-htable))
(format t "~%Loading ~S for the WN-Lexical module...~%" (data-source wn-htable))
(with-open-file (stream (make-pathname :directory (data-directory wn-htable)
:name (data-source wn-htable)
:type "data")
:direction :input
:if-does-not-exist :error)
(format t " 00%")
(do* ((nb-line 0 (incf nb-line))
(line (read-line stream nil 'eof)
(read-line stream nil 'eof))
(filelength (file-length stream))
(fileposition (file-position stream)
(file-position stream))
(proportion 10))
((or (equal nb-line nb-lines)
(eql line 'eof))
(format t " 100%~%"))
(when (> fileposition (* (/ proportion 100) filelength))
(format t " ~S%" proportion)
(setf proportion (+ 10 proportion)))
(let* ((index-spec (read-from-string line))
(index (gethash (first index-spec) (htable wn-htable))))
(unless index
(cond ((stringp (first index-spec))
(setf index (make-instance 'word-senses-index :key (first index-spec))))
((numberp (first index-spec))
(setf index (make-instance 'synset-wn-operators-index :key (first index-spec))))
((symbolp (first index-spec))
(setf index index-spec))))
(unless (listp index)
(setf (slot-value index (second index-spec)) (third index-spec)))
(setf (gethash (first index-spec) (htable wn-htable)) index))))
wn-htable)
(defmethod load-wn-lexical-in-declarative-memory ((wnl wordnet-lexical-module))
(let ((proportion 10)
(loaded-chunks 0)
(tot-chunks (hash-table-count (htable (wnl-chunks wnl)))))
(format t "~%Loading a total of ~S WN-Lexical chunks in declarative memory ...~%" tot-chunks)
(format t " 00%")
(maphash #'(lambda (key chunk-spec)
(declare (ignore key))
(add-dm-fct (list chunk-spec))
(incf loaded-chunks)
(when (> loaded-chunks (* (/ proportion 100) tot-chunks))
(format t " ~S%" proportion)
(setf proportion (+ 10 proportion))))
(htable (wnl-chunks wnl)))
(format t " 100%~%")))
(defmethod print-number-of-chunks ((wnl wordnet-lexical-module))
(format t "~%~S WNL-Chunks loaded in module WNLexical." (hash-table-count (htable (wnl-chunks wnl)))))
(defmethod load-all-data-sources-in-wn-lexical ((wnl wordnet-lexical-module))
(setf (wnl-chunks wnl)
(load-chunks-from-data-source (wnl-chunks wnl)))
(setf (wnl-indexes wnl)
(load-chunks-from-data-source (wnl-indexes wnl)))
wnl)
(defmethod wn-lexical-parameters ((wnl wordnet-lexical-module) (parameter list))
(bt:with-lock-held ((wn-lock wnl))
(case (car parameter)
(:wnl-chunks
(setf (load-wnl-chunks wnl) (cdr parameter))
(case (load-wnl-chunks wnl)
(wnl (make-actr-wnl-chunk-types)
(when (not (wnl-ready wnl))
(load-all-data-sources-in-wn-lexical wnl))
(print-number-of-chunks wnl))
(dm (make-actr-wnl-chunk-types)
(when (not (wnl-ready wnl))
(load-all-data-sources-in-wn-lexical wnl))
(print-number-of-chunks wnl)
(load-wn-lexical-in-declarative-memory wnl))
(nil (reset-wordnet-lexical-modules))))
(otherwise (print-warning "Unknown parameter ~S for module WNLexical." (car parameter))))))
(defmethod wn-lexical-parameters ((wnl wordnet-lexical-module) (parameter symbol))
(bt:with-lock-held ((wn-lock wnl))
(case parameter
(:wnl-chunks
(load-wnl-chunks wnl))
(otherwise (print-warning "Unknown parameter ~S for module WNLexical." parameter)))))
;;;
;;; Module definition
;;;
(defmethod valid-wnl-chunks-param-value ((value symbol))
(member value '(wnl dm nil)))
(define-module-fct 'wn-lexical
'(wn-lexical)
(list (define-parameter :wnl-chunks :valid-test 'valid-wnl-chunks-param-value :default-value nil
:warning "Possible values are wnl, dm or nil" :documentation "To load WN-CHUNKS in WNLexical use WNL, to load WN-CHUNKS in declarative memory (and WNLexical) use DM."))
:version *wordnet-lexical-version*
:documentation *wordnet-lexical-documentation*
:creation 'wnl-module-creation
:reset 'wnl-module-reset
:query 'wnl-module-and-buffer-query
:request 'wnl-module-request
:buffer-mod nil
:params 'wn-lexical-parameters
:delete nil
:notify-on-clear nil
:update nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
:eof
| 35,659 | Common Lisp | .lisp | 686 | 43.864431 | 213 | 0.583558 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ab2a7f8b17ffa554b653ecdf08d32806bc17e16d810cd6e83e6f3db22e486a36 | 14,267 | [
-1
] |
14,268 | WNLexicalModule.lisp | asmaloney_ACT-R/extras/WNLexicalModule/WNLexicalModule.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2018 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : WNLexicalModule.lisp
;;; Version : 1.0
;;;
;;; Description : A file to load the WNLexical module file with require-extra.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2018.08.24 Dan
;;; : * Creation.
;;; : * ACL doesn't like something about this logical:
;;; : "ACT-R:extras;WNLexicalModule;WNLexical_3-0-2.lisp"
;;; : so using merge-pathnames to put it together...
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(when (requiring-extra)
(compile-and-load (merge-pathnames "WNLexical_3-0-2.lisp" (translate-logical-pathname "ACT-R:extras;WNLexicalModule;"))))
(provide "WNLexicalModule")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 2,236 | Common Lisp | .lisp | 52 | 40.519231 | 124 | 0.531308 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e8558bdcce1f4167b4d7716bf42505983f09a7129ea5c8d4c8113eca62f34879 | 14,268 | [
-1
] |
14,269 | wnl-find-synonyms.lisp | asmaloney_ACT-R/extras/WNLexicalModule/Models/wnl-find-synonyms.lisp | (clear-all)
(require-extra "WNLexicalModule")
(define-model find-synonyms
(sgp :wnl-chunks wnl)
(chunk-type goal word-str synset-id state)
(define-chunks
(find-word-definition isa chunk)
(find-word-gloss isa chunk)
(find-synonyms isa chunk)
(say-definition isa chunk)
(g1 isa goal word-str "wiener" state find-word-definition)
(g2 isa goal word-str "dog" state find-word-definition))
(p find-word-definition
=goal>
isa goal
state find-word-definition
word-str =word
?wn-lexical>
state free
state success
==>
+wn-lexical>
isa wnl-request
wn-operator s
word =word
!output! (Looking for sense of =word)
=goal>
state find-word-gloss
)
(p do-not-know-word
=goal>
isa goal
state find-word-gloss
word-str =word
?wn-lexical>
state free
state error
==>
!output! (I know nothing about =word)
-goal>
)
(p find-word-gloss
=goal>
isa goal
state find-word-gloss
word-str =word
?wn-lexical>
state free
state success
=wn-lexical>
isa s
word =word
synset-id =synset-id
==>
+wn-lexical>
isa wnl-request
wn-operator g
synset-id =synset-id
!output! (Looking for definition of =word)
=goal>
state say-definition
)
(p say-definition
=goal>
isa goal
state say-definition
word-str =word
?wn-lexical>
state free
state success
=wn-lexical>
isa g
gloss =gloss
synset-id =synset-id
==>
!output! (the definition of =word is =gloss)
=goal>
state find-synonyms
synset-id =synset-id
+wn-lexical>
isa wnl-request
wn-operator s
synset-id =synset-id
)
(p find-synonyms
=goal>
isa goal
state find-synonyms
synset-id =synset-id
?wn-lexical>
state free
state success
=wn-lexical>
isa s
word =word
synset-id =synset-id
==>
!output! (=word is a synonyms)
+wn-lexical>
isa wnl-request
wn-operator s
synset-id =synset-id
context-criterion set-difference
)
(goal-focus g2)
)
#| Sample run
? (run 1)
0.000 GOAL SET-BUFFER-CHUNK GOAL G2 NIL
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
LOOKING FOR SENSE OF "dog"
0.050 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.050 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.050 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1)
0.050 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-110114209-2
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.100 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
LOOKING FOR DEFINITION OF "dog"
0.100 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.100 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.100 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-110114209-1)
0.100 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-110114209-1
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.150 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
THE DEFINITION OF "dog" IS "a dull unattractive unpleasant girl or woman; \"she got a reputation as a frump\"; \"she''s a real dog\""
0.150 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.150 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.150 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 2 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (S-110114209-2 S-110114209-1)
0.150 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-110114209-1
0.150 PROCEDURAL CONFLICT-RESOLUTION
0.200 PROCEDURAL PRODUCTION-FIRED FIND-SYNONYMS
"frump" IS A SYNONYMS
0.200 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.200 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.200 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 2 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-110114209-2 S-110114209-1) AND CONTEXT (G-110114209-1 S-110114209-2 S-110114209-1)
0.200 PROCEDURAL CONFLICT-RESOLUTION
0.200 ------ Stopped because no events left to process
0.2
57
NIL
|#
| 4,813 | Common Lisp | .lisp | 142 | 27.197183 | 237 | 0.626258 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 45f1c7615cf2fc4496068c82e6a5b7567da6cc78d65a212d2aa031e9c383069e | 14,269 | [
-1
] |
14,270 | wnl-find-definition.lisp | asmaloney_ACT-R/extras/WNLexicalModule/Models/wnl-find-definition.lisp | (clear-all)
(require-extra "WNLexicalModule")
(define-model find-definition
(sgp :wnl-chunks wnl)
(chunk-type goal word-str state)
(define-chunks
(find-word-definition isa chunk)
(find-word-gloss isa chunk)
(say-definition isa chunk)
(g1 isa goal word-str "wordnet" state find-word-definition))
(p find-word-definition
=goal>
isa goal
state find-word-definition
word-str =word
?wn-lexical>
state free
state success
==>
+wn-lexical>
isa wnl-request
wn-operator s
word =word
!output! (Looking for sense of =word)
=goal>
state find-word-gloss
)
(p do-not-know-word
=goal>
isa goal
state find-word-gloss
word-str =word
?wn-lexical>
state free
state error
==>
!output! (I know nothing about =word)
-goal>
)
(p find-word-gloss
=goal>
isa goal
state find-word-gloss
word-str =word
?wn-lexical>
state free
state success
=wn-lexical>
isa s
word =word
synset-id =synset-id
==>
+wn-lexical>
isa wnl-request
wn-operator g
synset-id =synset-id
!output! (Looking for definition of =word)
=goal>
state say-definition
)
(p say-definition
=goal>
isa goal
state say-definition
word-str =word
?wn-lexical>
state free
state success
=wn-lexical>
isa g
gloss =gloss
==>
!output! (the definition of =word is =gloss)
-goal>
)
(goal-focus g1)
)
#| Sample run
? (run 5)
0.000 GOAL SET-BUFFER-CHUNK GOAL G1 NIL
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
LOOKING FOR SENSE OF "wordnet"
0.050 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.050 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.050 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (S-106639428-1)
0.050 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-106639428-1
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.100 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
LOOKING FOR DEFINITION OF "wordnet"
0.100 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.100 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.100 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-106639428-1)
0.100 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-106639428-1
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.150 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
THE DEFINITION OF "wordnet" IS "any of the machine-readable lexical databases modeled after the Princeton WordNet"
0.150 PROCEDURAL CLEAR-BUFFER GOAL
0.150 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.150 PROCEDURAL CONFLICT-RESOLUTION
0.150 ------ Stopped because no events left to process
0.15
41
NIL
|#
| 3,290 | Common Lisp | .lisp | 105 | 24.761905 | 139 | 0.617792 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b2c4ffebb76fd9af7a00a41b823ded0c2b9b9943b38f73bf80027330ab38a41d | 14,270 | [
-1
] |
14,271 | wnl-find-all-definitions.lisp | asmaloney_ACT-R/extras/WNLexicalModule/Models/wnl-find-all-definitions.lisp | (clear-all)
(require-extra "WNLexicalModule")
(define-model find-all-definition
(sgp :wnl-chunks wnl)
(chunk-type goal word-str state)
(define-chunks
(find-word-definition isa chunk)
(find-word-gloss isa chunk)
(say-definition isa chunk)
(g1 isa goal word-str "wordnet" state find-word-definition)
(g2 isa goal word-str "act-r" state find-word-definition)
(g3 isa goal word-str "dog" state find-word-definition)
(g4 isa goal word-str "cat" state find-word-definition)
)
(p find-word-definition
=goal>
isa goal
state find-word-definition
word-str =word
?wn-lexical>
state free
==>
+wn-lexical>
isa wnl-request
wn-operator s
word =word
context-criterion set-difference
=goal>
state find-word-gloss
)
(p find-word-gloss
=goal>
isa goal
state find-word-gloss
word-str =word
?wn-lexical>
state free
state success
=wn-lexical>
isa s
word =word
synset-id =synset-id
==>
+wn-lexical>
isa wnl-request
wn-operator g
synset-id =synset-id
=goal>
state say-definition
)
(p no-more-word-senses
=goal>
isa goal
state find-word-gloss
word-str =word
?wn-lexical>
state free
state error
==>
!output! (no more word senses for =word)
+wn-lexical>
isa wnl-clear-context
-goal>
)
(p say-definition
=goal>
isa goal
state say-definition
word-str =word
?wn-lexical>
state free
state success
=wn-lexical>
isa g
gloss =gloss
==>
!output! (A definition of =word is =gloss)
=goal>
state find-word-definition
)
(goal-focus g1)
)
#| Sample run
(run 10)
(goal-focus g2)
(run 10)
(goal-focus g3)
(run 10)
(goal-focus g4)
(run 10)
? (run 10)
0.000 GOAL SET-BUFFER-CHUNK GOAL G1 NIL
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.050 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.050 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.050 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-106639428-1) AND CONTEXT NIL
0.050 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-106639428-1
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.100 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
0.100 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.100 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.100 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-106639428-1)
0.100 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-106639428-1
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.150 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "wordnet" IS "any of the machine-readable lexical databases modeled after the Princeton WordNet"
0.150 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.150 PROCEDURAL CONFLICT-RESOLUTION
0.200 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.200 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.200 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.200 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-106639428-1) AND CONTEXT (S-106639428-1 G-106639428-1)
0.200 PROCEDURAL CONFLICT-RESOLUTION
0.250 PROCEDURAL PRODUCTION-FIRED NO-MORE-WORD-SENSES
NO MORE WORD SENSES FOR "wordnet"
0.250 PROCEDURAL CLEAR-BUFFER GOAL
0.250 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.250 WN-LEXICAL CLEAR-WN-LEXICAL-SYNSET-CONTEXT
0.250 PROCEDURAL CONFLICT-RESOLUTION
0.250 ------ Stopped because no events left to process
0.25
61
NIL
? (goal-focus g2)
G2
? (run 10)
0.250 GOAL SET-BUFFER-CHUNK GOAL G2 NIL
0.250 PROCEDURAL CONFLICT-RESOLUTION
0.300 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.300 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.300 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.300 PROCEDURAL CONFLICT-RESOLUTION
0.350 PROCEDURAL PRODUCTION-FIRED NO-MORE-WORD-SENSES
NO MORE WORD SENSES FOR "act-r"
0.350 PROCEDURAL CLEAR-BUFFER GOAL
0.350 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.350 WN-LEXICAL CLEAR-WN-LEXICAL-SYNSET-CONTEXT
0.350 PROCEDURAL CONFLICT-RESOLUTION
0.350 ------ Stopped because no events left to process
0.1
24
NIL
? (goal-focus g3)
G3
? (run 10)
0.350 GOAL SET-BUFFER-CHUNK GOAL G3 NIL
0.350 PROCEDURAL CONFLICT-RESOLUTION
0.400 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.400 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.400 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.400 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT NIL
0.400 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-202001858-7
0.400 PROCEDURAL CONFLICT-RESOLUTION
0.450 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
0.450 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.450 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.450 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-202001858-1)
0.450 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-202001858-1
0.450 PROCEDURAL CONFLICT-RESOLUTION
0.500 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "go after with the intent to catch; \"The policeman chased the mugger down the alley\"; \"the dog chased the rabbit\""
0.500 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.500 PROCEDURAL CONFLICT-RESOLUTION
0.550 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.550 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.550 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.550 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-202001858-7 G-202001858-1)
0.550 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-107676602-5
0.550 PROCEDURAL CONFLICT-RESOLUTION
0.600 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
0.600 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.600 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.600 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-107676602-1)
0.600 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-107676602-1
0.600 PROCEDURAL CONFLICT-RESOLUTION
0.650 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "a smooth-textured sausage of minced beef or pork usually smoked; often served on a bread roll"
0.650 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.650 PROCEDURAL CONFLICT-RESOLUTION
0.700 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.700 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.700 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.700 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1)
0.700 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-102710044-3
0.700 PROCEDURAL CONFLICT-RESOLUTION
0.750 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
0.750 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.750 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.750 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-102710044-1)
0.750 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-102710044-1
0.750 PROCEDURAL CONFLICT-RESOLUTION
0.800 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "metal supports for logs in a fireplace; \"the andirons were too hot to touch\""
0.800 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.800 PROCEDURAL CONFLICT-RESOLUTION
0.850 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
0.850 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.850 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.850 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-102710044-3 S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1 G-102710044-1)
0.850 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-110023039-1
0.850 PROCEDURAL CONFLICT-RESOLUTION
0.900 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
0.900 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.900 WN-LEXICAL RETRIEVE-WN-CHUNKS
0.900 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-110023039-1)
0.900 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-110023039-1
0.900 PROCEDURAL CONFLICT-RESOLUTION
0.950 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "informal term for a man; \"you lucky dog\""
0.950 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
0.950 PROCEDURAL CONFLICT-RESOLUTION
1.000 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.000 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.000 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.000 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-110023039-1 S-102710044-3 S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1 G-102710044-1 G-110023039-1)
1.000 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-102084071-1
1.000 PROCEDURAL CONFLICT-RESOLUTION
1.050 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
1.050 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.050 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.050 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-102084071-1)
1.050 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-102084071-1
1.050 PROCEDURAL CONFLICT-RESOLUTION
1.100 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "a member of the genus Canis (probably descended from the common wolf) that has been domesticated by man since prehistoric times; occurs in many breeds; \"the dog barked all night\""
1.100 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.100 PROCEDURAL CONFLICT-RESOLUTION
1.150 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.150 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.150 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.150 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-102084071-1 S-110023039-1 S-102710044-3 S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1 G-102710044-1 G-110023039-1 G-102084071-1)
1.150 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-110114209-2
1.150 PROCEDURAL CONFLICT-RESOLUTION
1.200 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
1.200 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.200 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.200 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-110114209-1)
1.200 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-110114209-1
1.200 PROCEDURAL CONFLICT-RESOLUTION
1.250 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "a dull unattractive unpleasant girl or woman; \"she got a reputation as a frump\"; \"she''s a real dog\""
1.250 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.250 PROCEDURAL CONFLICT-RESOLUTION
1.300 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.300 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.300 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.300 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-110114209-2 S-102084071-1 S-110023039-1 S-102710044-3 S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1 G-102710044-1 G-110023039-1 G-102084071-1 G-110114209-1)
1.300 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-109886220-4
1.300 PROCEDURAL CONFLICT-RESOLUTION
1.350 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
1.350 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.350 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.350 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-109886220-1)
1.350 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-109886220-1
1.350 PROCEDURAL CONFLICT-RESOLUTION
1.400 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "someone who is morally reprehensible; \"you dirty dog\""
1.400 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.400 PROCEDURAL CONFLICT-RESOLUTION
1.450 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.450 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.450 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.450 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-109886220-4 S-110114209-2 S-102084071-1 S-110023039-1 S-102710044-3 S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1 G-102710044-1 G-110023039-1 G-102084071-1 G-110114209-1 G-109886220-1)
1.450 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-103901548-4
1.450 PROCEDURAL CONFLICT-RESOLUTION
1.500 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
1.500 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.500 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.500 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-103901548-1)
1.500 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-103901548-1
1.500 PROCEDURAL CONFLICT-RESOLUTION
1.550 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "dog" IS "a hinged catch that fits into a notch of a ratchet to move a wheel forward or prevent it from moving backward"
1.550 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.550 PROCEDURAL CONFLICT-RESOLUTION
1.600 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.600 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.600 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.600 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 8 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-202001858-7 S-110114209-2 S-110023039-1 S-109886220-4 S-107676602-5 S-103901548-4 S-102710044-3 S-102084071-1) AND CONTEXT (S-103901548-4 S-109886220-4 S-110114209-2 S-102084071-1 S-110023039-1 S-102710044-3 S-107676602-5 S-202001858-7 G-202001858-1 G-107676602-1 G-102710044-1 G-110023039-1 G-102084071-1 G-110114209-1 G-109886220-1 G-103901548-1)
1.600 PROCEDURAL CONFLICT-RESOLUTION
1.650 PROCEDURAL PRODUCTION-FIRED NO-MORE-WORD-SENSES
NO MORE WORD SENSES FOR "dog"
1.650 PROCEDURAL CLEAR-BUFFER GOAL
1.650 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.650 WN-LEXICAL CLEAR-WN-LEXICAL-SYNSET-CONTEXT
1.650 PROCEDURAL CONFLICT-RESOLUTION
1.650 ------ Stopped because no events left to process
1.3
305
NIL
? (goal-focus g4)
G4
? (run 10)
1.650 GOAL SET-BUFFER-CHUNK GOAL G4 NIL
1.650 PROCEDURAL CONFLICT-RESOLUTION
1.700 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.700 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.700 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.700 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT NIL
1.700 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-102985606-2
1.700 PROCEDURAL CONFLICT-RESOLUTION
1.750 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
1.750 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.750 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.750 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-102985606-1)
1.750 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-102985606-1
1.750 PROCEDURAL CONFLICT-RESOLUTION
1.800 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "a whip with nine knotted cords; \"British sailors feared the cat\""
1.800 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.800 PROCEDURAL CONFLICT-RESOLUTION
1.850 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
1.850 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.850 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.850 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-102985606-2 G-102985606-1)
1.850 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-102121620-1
1.850 PROCEDURAL CONFLICT-RESOLUTION
1.900 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
1.900 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.900 WN-LEXICAL RETRIEVE-WN-CHUNKS
1.900 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-102121620-1)
1.900 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-102121620-1
1.900 PROCEDURAL CONFLICT-RESOLUTION
1.950 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "feline mammal usually having thick soft fur and no ability to roar: domestic cats; wildcats"
1.950 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
1.950 PROCEDURAL CONFLICT-RESOLUTION
2.000 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.000 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.000 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.000 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1)
2.000 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-102127808-2
2.000 PROCEDURAL CONFLICT-RESOLUTION
2.050 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.050 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.050 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.050 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-102127808-1)
2.050 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-102127808-1
2.050 PROCEDURAL CONFLICT-RESOLUTION
2.100 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "any of several large cats typically able to roar and living in the wild"
2.100 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.100 PROCEDURAL CONFLICT-RESOLUTION
2.150 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.150 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.150 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.150 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1)
2.150 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-102983507-2
2.150 PROCEDURAL CONFLICT-RESOLUTION
2.200 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.200 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.200 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.200 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-102983507-1)
2.200 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-102983507-1
2.200 PROCEDURAL CONFLICT-RESOLUTION
2.250 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "a large tracked vehicle that is propelled by two endless metal belts; frequently used for moving earth in construction and farm work"
2.250 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.250 PROCEDURAL CONFLICT-RESOLUTION
2.300 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.300 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.300 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.300 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-102983507-2 S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1 G-102983507-1)
2.300 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-201411870-1
2.300 PROCEDURAL CONFLICT-RESOLUTION
2.350 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.350 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.350 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.350 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-201411870-1)
2.350 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-201411870-1
2.350 PROCEDURAL CONFLICT-RESOLUTION
2.400 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "beat with a cat-o''-nine-tails"
2.400 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.400 PROCEDURAL CONFLICT-RESOLUTION
2.450 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.450 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.450 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.450 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-201411870-1 S-102983507-2 S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1 G-102983507-1 G-201411870-1)
2.450 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-200076400-6
2.450 PROCEDURAL CONFLICT-RESOLUTION
2.500 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.500 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.500 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.500 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-200076400-1)
2.500 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-200076400-1
2.500 PROCEDURAL CONFLICT-RESOLUTION
2.550 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "eject the contents of the stomach through the mouth; \"After drinking too much, the students vomited\"; \"He purged continuously\"; \"The patient regurgitated the food we gave him last night\""
2.550 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.550 PROCEDURAL CONFLICT-RESOLUTION
2.600 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.600 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.600 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.600 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-200076400-6 S-201411870-1 S-102983507-2 S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1 G-102983507-1 G-201411870-1 G-200076400-1)
2.600 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-103608870-5
2.600 PROCEDURAL CONFLICT-RESOLUTION
2.650 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.650 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.650 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.650 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-103608870-1)
2.650 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-103608870-1
2.650 PROCEDURAL CONFLICT-RESOLUTION
2.700 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "the leaves of the shrub Catha edulis which are chewed like tobacco or used to make tea; has the effect of a euphoric stimulant; \"in Yemen kat is used daily by 85% of adults\""
2.700 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.700 PROCEDURAL CONFLICT-RESOLUTION
2.750 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.750 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.750 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.750 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-103608870-5 S-200076400-6 S-201411870-1 S-102983507-2 S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1 G-102983507-1 G-201411870-1 G-200076400-1 G-103608870-1)
2.750 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-109900153-1
2.750 PROCEDURAL CONFLICT-RESOLUTION
2.800 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.800 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.800 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.800 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-109900153-1)
2.800 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-109900153-1
2.800 PROCEDURAL CONFLICT-RESOLUTION
2.850 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "a spiteful woman gossip; \"what a cat she is!\""
2.850 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.850 PROCEDURAL CONFLICT-RESOLUTION
2.900 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
2.900 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.900 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.900 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-109900153-1 S-103608870-5 S-200076400-6 S-201411870-1 S-102983507-2 S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1 G-102983507-1 G-201411870-1 G-200076400-1 G-103608870-1 G-109900153-1)
2.900 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL S-110153414-2
2.900 PROCEDURAL CONFLICT-RESOLUTION
2.950 PROCEDURAL PRODUCTION-FIRED FIND-WORD-GLOSS
2.950 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
2.950 WN-LEXICAL RETRIEVE-WN-CHUNKS
2.950 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 1 CRITERION IS RANDOM FROM RETRIEVED-CHUNKS (G-110153414-1)
2.950 WN-LEXICAL SET-BUFFER-CHUNK WN-LEXICAL G-110153414-1
2.950 PROCEDURAL CONFLICT-RESOLUTION
3.000 PROCEDURAL PRODUCTION-FIRED SAY-DEFINITION
A DEFINITION OF "cat" IS "an informal term for a youth or man; \"a nice guy\"; \"the guy''s only doing it for some doll\""
3.000 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
3.000 PROCEDURAL CONFLICT-RESOLUTION
3.050 PROCEDURAL PRODUCTION-FIRED FIND-WORD-DEFINITION
3.050 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
3.050 WN-LEXICAL RETRIEVE-WN-CHUNKS
3.050 WN-LEXICAL SELECT-FROM-RETRIEVED-WN-CHUNKS SET OF SIZE 9 CRITERION IS SET-DIFFERENCE BETWEEN RETRIEVED-CHUNKS (S-201411870-1 S-200076400-6 S-110153414-2 S-109900153-1 S-103608870-5 S-102985606-2 S-102983507-2 S-102127808-2 S-102121620-1) AND CONTEXT (S-110153414-2 S-109900153-1 S-103608870-5 S-200076400-6 S-201411870-1 S-102983507-2 S-102127808-2 S-102121620-1 S-102985606-2 G-102985606-1 G-102121620-1 G-102127808-1 G-102983507-1 G-201411870-1 G-200076400-1 G-103608870-1 G-109900153-1 G-110153414-1)
3.050 PROCEDURAL CONFLICT-RESOLUTION
3.100 PROCEDURAL PRODUCTION-FIRED NO-MORE-WORD-SENSES
NO MORE WORD SENSES FOR "cat"
3.100 PROCEDURAL CLEAR-BUFFER GOAL
3.100 PROCEDURAL CLEAR-BUFFER WN-LEXICAL
3.100 WN-LEXICAL CLEAR-WN-LEXICAL-SYNSET-CONTEXT
3.100 PROCEDURAL CONFLICT-RESOLUTION
3.100 ------ Stopped because no events left to process
1.45
340
NIL
|#
| 32,704 | Common Lisp | .lisp | 456 | 66.105263 | 528 | 0.651902 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0337f09654de9031d378fb420e5975bbcd538b8cc32b71a648bd837d069be089 | 14,271 | [
-1
] |
14,272 | base-level-inhibition.lisp | asmaloney_ACT-R/extras/base-level-inhibition/base-level-inhibition.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2016 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : base-level-inhibition.lisp
;;; Version : 1.0
;;;
;;; Description : A file to load bl-inhibition.lisp automatically with require-extra.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2016.03.14 Dan
;;; : * Creation.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(when (requiring-extra)
(compile-and-load (translate-logical-pathname "ACT-R:extras;base-level-inhibition;bl-inhibition.lisp")))
(provide "base-level-inhibition")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 1,974 | Common Lisp | .lisp | 49 | 38.897959 | 106 | 0.544033 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1063978d4ea67ea386b6b7c1caa684a2d48e81f390f3b9b8d792d5263864cc66 | 14,272 | [
258536
] |
14,273 | bl-inhibition.lisp | asmaloney_ACT-R/extras/base-level-inhibition/bl-inhibition.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2009 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : bl-inhibition.lisp
;;; Version : 2.0a2
;;;
;;; Description : A module to add the short term base-level activation inhibition
;;; : component described in:
;;;
;;; Lebiere, C., & Best, B. J. (2009). Balancing Long-Term Reinforcement and
;;; Short-Term Inhibition. Proceedings of the 31st Annual Conference of the
;;; Cognitive Science Society (pp. 2378-2383). Austin, TX: Cognitive Science
;;; Society.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2009.08.05 Dan [1.0a1]
;;; : * Initial creation.
;;; 2011.04.25 Dan
;;; : * Updated because of the change to millisecond times being
;;; : recorded in DM parameters.
;;; 2016.03.14 Dan
;;; : * Added the note about require-extra.
;;; 2016.09.20 Dan
;;; : * Fixed a bug with how the monitoring of :activation-offsets
;;; : checked whether the parameter was already set.
;;; 2018.08.21 Dan [2.0a1]
;;; : * Added a lock for protection to work well with 7.6+.
;;; 2020.01.10 Dan [2.0a2]
;;; : * Removed the #' from the parameter valid functions since
;;; : that's not allowed in the general system now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; To use this extension call (require-extra "base-level-inhibition"), or to
;;; always have the extension available put this file into the modules directory
;;; before loading the main ACT-R load file. You can also explicitly load it
;;; once after loading ACT-R and before defining any models.
;;;
;;; With this module added to the system chunk activations now have an additional
;;; term added to the equation when the :enable-inhibition parameter is set to t
;;; (its default value) and base-level learning is enabled with at least one
;;; past reference being included (either :ol nil or a number):
;;;
;;; - log [1 + (Tn/ts)^-ds]
;;;
;;; Tn is the time since the most recent reference of the chunk
;;; ds is the value of the inhibition-decay parameter
;;; ts is the value of the inhibition-scale parameter
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; New parameters :enable-inhibition, :inhibition-scale and :inhibition-decay.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Relies on the new activation offsets hook to add a component to the
;;; activation calculation.
;;;
;;; Would like to use sdp to get the reference time instead of pulling it from
;;; the chunk parameter directly to be safe with respect to possible future changes
;;; in declarative parameter representations, but can't because sdp forces a
;;; recomputation of the activation which would call this again and recurse
;;; infinitely (or until the stack/heap exhausts).
;;;
;;; The default values for the parameters are suggestions from Christian, but
;;; are not necessarily good values for all situations.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defstruct bl-inhibition enabled scale decay (lock (bt:make-recursive-lock "bl-inhibition")))
(defun bl-inhibition-term (chunk)
(let ((bl (get-module base-level-inhibition))
(reference (car (chunk-reference-list chunk))))
(when (and bl (numberp reference))
(bt:with-recursive-lock-held ((bl-inhibition-lock bl))
(when (bl-inhibition-enabled bl)
(- (log-coerced (+ 1.0 (expt-coerced (/ (max .05 (ms->seconds (- (mp-time-ms) reference))) (bl-inhibition-scale bl))
(- (bl-inhibition-decay bl)))))))))))
(defun bl-inhibition-params (module param)
(bt:with-recursive-lock-held ((bl-inhibition-lock module))
(cond ((consp param)
(case (car param)
(:enable-inhibition (setf (bl-inhibition-enabled module) (cdr param)))
(:inhibition-scale (setf (bl-inhibition-scale module) (cdr param)))
(:inhibition-decay (setf (bl-inhibition-decay module) (cdr param)))
;; force our function onto the offset list whenever
;; it's changed and we're not on it
(:activation-offsets
(unless (or (find 'bl-inhibition-term (cdr param))
(find 'bl-inhibition-term (no-output (car (sgp :activation-offsets)))))
(sgp :activation-offsets bl-inhibition-term)))))
(t
(case param
(:enable-inhibition (bl-inhibition-enabled module))
(:inhibition-scale (bl-inhibition-scale module))
(:inhibition-decay (bl-inhibition-decay module)))))))
(defun create-bl-inhibition-module (name)
(declare (ignore name))
(make-bl-inhibition))
(define-module-fct 'base-level-inhibition
nil
(list (define-parameter :enable-inhibition :owner t :default-value t :valid-test 'tornil
:documentation "Enable base-level inhibition calculation"
:warning "T or nil")
(define-parameter :inhibition-scale :owner t :default-value 5 :valid-test 'plusp
:warning "a positive number"
:documentation "Base-level inhibition scale (ts)")
(define-parameter :inhibition-decay :owner t :default-value 1.0 :valid-test 'plusp
:warning "a positive number"
:documentation "Base-level inhibition decay (ds)")
(define-parameter :activation-offsets :owner nil))
:creation 'create-bl-inhibition-module
:params 'bl-inhibition-params
:version "2.0a2"
:documentation
"Module to add the option of the Lebiere & Best base-level inhibition component to activation calculations"
)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 7,493 | Common Lisp | .lisp | 156 | 43.878205 | 126 | 0.603823 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 665c7c22c1b2100b6ccce9fb5a32234bb546b8803affe20eb70edcfc940ba14e | 14,273 | [
63492
] |
14,274 | sample.lisp | asmaloney_ACT-R/extras/threads/sample.lisp | ;;;--------------------------------------------------------------------------
;;;
;;; Threaded Cognition
;;; Sample Model
;;; Dario Salvucci & Niels Taatgen
;;;
;;; This file contains a sample threaded model that performs two simple
;;; concurrent tasks: repeatedly typing a letter and repeatedly speaking
;;; a word. Enter (m) to run a 2.0 sec trace of the model.
;;;
;;; For more information please see:
;;; Salvucci, D. D., & Taatgen, N. A. (2008). Threaded cognition: An integrated
;;; theory of concurrent multitasking. Psychological Review, 115, 101-130.
;;;
;;; Copyright © 2008 Dario Salvucci and Niels Taatgen
;;;
;;;--------------------------------------------------------------------------
(defun m ()
(reset)
(let ((window (open-exp-window "window" :visible nil)))
(install-device window)
(run 2.0)))
(clear-all)
(require-extra "threads")
(define-model sample
(sgp :v t :esc t)
(chunk-type type key)
(chunk-type speak-word word)
(p start-concurrent-tasks
?goal>
buffer empty
==>
+goal>
isa type
key "a"
+goal>
isa speak-word
word "hello"
)
(p type-letter
=goal>
isa type
key =key
?manual>
state free
==>
+manual>
isa press-key
key =key
)
(p speak-word
=goal>
isa speak-word
word =word
?vocal>
state free
==>
+vocal>
isa speak
string =word
))
| 1,402 | Common Lisp | .lisp | 61 | 19.770492 | 81 | 0.573042 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2b30d7a4007f25af36e22f4b124a2d64157dbb0f5cf7b5f3f2b66f02621ec60c | 14,274 | [
258299
] |
14,275 | threads.lisp | asmaloney_ACT-R/extras/threads/threads.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2016 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : threads.lisp
;;; Version : 1.0
;;;
;;; Description : A file to load new-threads.lisp automatically with require-extra.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2016.03.14 Dan
;;; : * Creation.
;;; 2016.07.19 Dan
;;; : * Actually provide the right thing instead of the copy and
;;; : paste from a different extra.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(when (requiring-extra)
(compile-and-load (translate-logical-pathname "ACT-R:extras;threads;new-threads.lisp")))
(provide "threads")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 2,074 | Common Lisp | .lisp | 52 | 38.519231 | 90 | 0.53869 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 92ddd3a946f599af295f4c8cfb7c5f35e0f0a55b01f5ddbb9d439ab8e556e5a7 | 14,275 | [
454404
] |
14,276 | new-threads.lisp | asmaloney_ACT-R/extras/threads/new-threads.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2010 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : new-threads.lisp
;;; Version : 2.5
;;;
;;; Description : Reimplementation of the threaded cognition module using
;;; : the new searchable multi-buffer capability.
;;;
;;; Bugs :
;;;
;;; To do : [ ] Consider making the low priority offset a parameter or
;;; : perhaps using some way to scale it on the fly.
;;;
;;; ----- History -----
;;; 2010.01.13 Dan [2.0a]
;;; : * Initial creation.
;;; 2011.04.28 Dan
;;; : * Suppress warnings about extending chunks at initial load.
;;; 2014.06.17 Dan [2.1]
;;; : * Fix a bug with thread-request for 6.1 since there isn't an
;;; : 'isa <type>' in the chunk description.
;;; 2015.06.05 Dan
;;; : * Schedule events in ms now.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2015.08.12 Dan [2.2]
;;; : * Fixed a bug that got introduced with either the 2.1 or next
;;; : update in the request function.
;;; 2018.08.24 Dan [2.3]
;;; : * Use the goal module's lock to protect the internals so it's
;;; : safe to use with 7.6+.
;;; 2020.01.10 Dan [2.4]
;;; : * Removed the #' from a scheduled function sincethat's not
;;; : allowed in the general system now.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled since it's not needed
;;; : and results in warnings in SBCL.
;;; 2021.10.20 Dan [2.5]
;;; : * Check whether there is a procedural module before trying to
;;; : set the :do-not-harvest parameter.
;;; : * Also set the :do-not-query parameter now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; An implementation of the threaded cognition theory of Salvucci and Taatgen.
;;; This code uses a searchable multi-buffer in a module which is a complete
;;; replacement for the standard goal module. By using a multi-buffer to
;;; hold the potential goals and relying on the ability of the procedural
;;; module to search over a multi-buffer's chunks this new implementation
;;; does not require changing any of the standard procedural or buffer based
;;; code. Thus, this module should not interfere with any other modules or
;;; updates. Another advantage of this new implementation is that it works
;;; with the standard tracing and testing functions (like whynot).
;;;
;;; For the most part, this should work just like the previous implementation
;;; of threaded cognition, but there is a limitation built into the new
;;; procedural searching which the previous version of threaded cognition did
;;; not have. The limitation occurs in dynamic (p*) style productions. The
;;; chunk in the searched multi-buffer cannot be used to bind a variable that
;;; names a slot. Dynamically named slots can be tested in the searched buffer's
;;; conditions, but those variables must be bound in non-searched buffers. That
;;; shouldn't cause too much of an issue for modeling because problem
;;; representation (where those dynamic names would likely come from) should be
;;; done in the imaginal buffer now and not the goal anyway. The reason for
;;; that restriciton is to avoid the need to do full NP-hard searches in the
;;; procedural module while matching productions.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; threads-pprint
;;;
;;; Takes no parameters. Prints out the chunks currently in the thread
;;; set in order of their current priority and returns the list of those
;;; chunks.
;;;
;;; goal-focus
;;;
;;; Works like the default module's goal focus, except that it adds all of the
;;; goals created to the set of potential goals. The one exception to that is
;;; if the same goal is added more than once. It will only have one instance
;;; of a particular goal chunk in the set, and the newly focused version will
;;; replace an older one.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; By using a searchable multi-buffer the work required for the search is now
;;; done by the procedural system itself. So, all that's necessary here is to
;;; maintain the set of goal chunks in the appropriate order to pass back to
;;; procedural when asked and to report which one to prefer if more than one
;;; match. Right now, that's done with a fixed offset to the utility of -999
;;; for the low priority matches, but that may need to be adjusted.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Rely on the general functions in the goal-style-module
(require-compiled "GOAL-STYLE-MODULE")
;;; Remove the default goal module because we are going to replace it.
(undefine-module goal)
;;; Extend the structure which implements the standard goal module
;;; with some new slots.
(defstruct (threaded-goal-module (:include goal-module) (:conc-name tgm-))
chunk-set update)
;;; A simple module creation function which just makes a new structure.
(defun create-threaded-goal-module (model-name)
(declare (ignore model-name))
(make-threaded-goal-module))
;;; The reset function clears all of the slots and sets the goal buffer to
;;; not be harvested.
(defun threaded-goal-reset (instance)
(bt:with-lock-held ((tgm-lock instance))
(setf (tgm-delayed instance) nil)
(setf (tgm-chunk-set instance) nil)
(setf (tgm-update instance) nil))
; Do NOT strict harvest or query the goal buffer by default
(when (get-module procedural t)
(sgp :do-not-harvest goal :do-not-query goal))
)
;;; If a chunk is cleared from the goal buffer then it needs to be removed
;;; from the set of potential goals if it is still one of them.
(defun thread-clear (instance buffer chunk)
(bt:with-lock-held ((tgm-lock instance))
(when (and (eq buffer 'goal) (find chunk (tgm-chunk-set instance)))
(setf (tgm-chunk-set instance) (remove chunk (tgm-chunk-set instance))))))
;;; The goal requests need to store the new chunk in the set of potential
;;; goals and use overwrite to put it into the buffer to avoid clearing the
;;; old one.
(defun thread-request (instance buffer-name chunk-spec &optional (delay 0))
(let ((chunk-description (chunk-spec-to-chunk-def chunk-spec)))
(if chunk-description
(let ((chunk-name (car (define-chunks-fct (list chunk-description)))))
(store-m-buffer-chunk buffer-name chunk-name)
(bt:with-lock-held ((tgm-lock instance))
(push-last chunk-name (tgm-chunk-set instance)))
(schedule-event-relative (seconds->ms delay) 'create-new-thread-chunk
:module 'goal
:priority -100
:details (concatenate 'string (symbol-name 'create-new-buffer-chunk) " " (symbol-name buffer-name))
:params (list chunk-name)))
(print-warning "Invalid request made of the ~A buffer." buffer-name))))
(defun create-new-thread-chunk (chunk)
(schedule-overwrite-buffer-chunk 'goal chunk 0 :time-in-ms t :module 'goal :priority -1000 :requested t))
;;; These two module functions are responsible for the search interface provided
;;; by procedural now.
;;; Thread-search will be called at the start of conflict resolution and is
;;; responsible for returning the list of chunks to search in the order which
;;; they should be searched. The searching terminates when it finds a match.
;;; Here we just move the last used goal to the end if it's still on the
;;; list and then return that list.
(defun thread-search (instance buffer)
(declare (ignore buffer))
(bt:with-lock-held ((tgm-lock instance))
(when (tgm-update instance)
(when (find (tgm-update instance) (tgm-chunk-set instance))
(setf (tgm-chunk-set instance) (append (remove (tgm-update instance) (tgm-chunk-set instance)) (list (tgm-update instance)))))
(setf (tgm-update instance) nil))
(tgm-chunk-set instance)))
;;; Thread-offset is called after production matching has occurred to determine
;;; if there is a preference for which of the chunks from the multi-buffer to
;;; use. All chunks from the multi-buffer which were found to match to some
;;; production are given in chunks and it needs to return the list of offsets
;;; to apply to the utility of the productions using those chunks (in order).
;;; Right now all it does is specify 0 (no change) for the productions which
;;; match the highest priority goal (closest to the head of the queue) and
;;; -999 for all the others which should suppress them. This may need to be
;;; adapted to be more flexible at some point...
;;;
;;; That "best" chunk is recorded so that it can be moved to the end of the
;;; queue for the next matching phase.
(defun thread-offset (instance buffer chunks)
(declare (ignore buffer))
(bt:with-lock-held ((tgm-lock instance))
(let* ((positions (mapcar (lambda (x) (cons (position x (tgm-chunk-set instance)) x)) chunks))
(m (reduce 'min positions :key 'car)))
(setf (tgm-update instance) (cdr (assoc m positions)))
(mapcar (lambda (x) (if (= (car x) m) 0 -999)) positions))))
;;; Define the new module with the same name and buffer as the old
;;; goal module but now mark the buffer as searchable.
(define-module-fct 'goal '((goal (:ga 1.0) nil nil nil :search))
nil
:version "2.5"
:documentation "Threaded cognition version of the goal module"
:creation 'create-threaded-goal-module
:reset (list nil 'threaded-goal-reset)
:query 'goal-query
:buffer-mod 'goal-style-mod-request
:notify-on-clear 'thread-clear
:search 'thread-search
:offset 'thread-offset
:request 'thread-request
)
;;; The module's user commands.
;;; threads-pprint updates the list of chunks if necessary and then prints them out.
(defun threads-pprint ()
(let ((module (get-module goal)))
(pprint-chunks-fct (thread-search module 'goal))))
;;; Goal-focus works essentially the same as it does for the standard goal module,
;;; but now all the goals created are added to the set of potential goals instead
;;; of being directly set in the buffer. To avoid creating multiple instances of
;;; a single goal a new chunk parameter is added to keep track of goals which have
;;; been used in the past.
(suppress-extension-warnings)
(extend-chunks parent-goal)
(unsuppress-extension-warnings)
(defun goal-focus-fct (&optional (chunk-name nil))
"Place a chunk into the goal buffer or return either the chunk that is there
now or the one that will be placed there by a pending goal-focus"
(let ((g-module (get-module goal)))
(if g-module
(bt:with-lock-held ((tgm-lock g-module))
(if chunk-name
(if (chunk-p-fct chunk-name)
;;; always copy the user chunks for goals
(let ((n-chunk (copy-chunk-fct chunk-name))
(clear-old-chunk nil))
;; first remove an "old" instance of this same goal
;; if there is one
(awhen (find chunk-name (tgm-chunk-set g-module) :key 'chunk-parent-goal)
;; if it happens to be in the buffer then we will just let it clear
;; and that will take care of the removal details
(if (eq it (buffer-read 'goal))
(setf clear-old-chunk t)
(progn
;; otherwise just take it out of the current set of goals
;; and have it replaced with the new version
;; ??? should the old one get to DM ???
;; I don't think so since it'd only happen in a
;; threaded model, but I don't know
(setf (tgm-chunk-set g-module) (remove it (tgm-chunk-set g-module)))
(remove-m-buffer-chunk 'goal it))))
(setf (chunk-parent-goal n-chunk) chunk-name)
(when (null (tgm-chunk-set g-module))
;; if there aren't any goals then use
;; set-buffer-chunk instead of overwrite
;; to be more consistent with existing
;; single threaded models
(setf clear-old-chunk t))
(store-m-buffer-chunk 'goal n-chunk)
(setf (tgm-chunk-set g-module) (append (tgm-chunk-set g-module) (list n-chunk)))
(if clear-old-chunk
(schedule-set-buffer-chunk 'goal n-chunk 0 :time-in-ms t :module 'goal :priority :max :requested nil)
(schedule-overwrite-buffer-chunk 'goal n-chunk 0 :time-in-ms t :module 'goal :priority :max :requested nil))
(setf (tgm-delayed g-module) n-chunk)
(schedule-event-after-module 'goal 'clear-delayed-goal :module 'goal
:output nil :destination 'goal :maintenance t)
chunk-name)
(print-warning "~S is not the name of a chunk in the current model - goal-focus failed" chunk-name))
(let ((chunk (buffer-read 'goal))
(delayed (goal-module-delayed g-module)))
(cond ((and (null chunk) (null delayed))
(command-output "Goal buffer is empty")
nil)
((null chunk)
(command-output "Will be ~a when the model runs" delayed)
(pprint-chunks-fct (list delayed))
delayed)
((null delayed)
(pprint-chunks-fct (list chunk))
chunk)
(t
(if (or (eq delayed chunk) ;; it shouldn't be a copy with a multi-buffer
(eq delayed (chunk-copied-from-fct chunk))) ;; but if it was a DM chunk it was copied
;; caught it before the delayed chunk was cleared
(progn
(pprint-chunks-fct (list chunk))
chunk)
(progn
(command-output "Will be ~a when the model runs" delayed)
(command-output "Currently holds:")
(pprint-chunks-fct (list chunk))
delayed)))))))
(print-warning "No goal module available for goal-focus"))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 16,670 | Common Lisp | .lisp | 307 | 46.596091 | 134 | 0.612907 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6e971547b0f81753829262e5b6a19059146ae26d410003d730d3ba8ceedcbdb8 | 14,276 | [
-1
] |
14,277 | spacing-effect.lisp | asmaloney_ACT-R/extras/spacing-effect/spacing-effect.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : spacing-effect.lisp
;;; Version : 2.1
;;;
;;; Description : A module to allow one to toggle the base-level learning
;;; : equation from the default to the one proposed by
;;; : Pavlik and Anderson in Cognitive Science 29 (2005) 559-586.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2005.08.31 Dan
;;; : * Creation for David Peebles.
;;; 2010.11.15 Dan
;;; : * Took out the :bll setting since it's no longer necessary
;;; : and now generates a warning.
;;; : * Except, it is still necessary... So, now it's set to a
;;; : large positive value instead.
;;; : * Also added a reset function to turn off eblse before the
;;; : default parameters get set since declarative could go first
;;; : which would cause warnings from those default settings.
;;; 2011.04.25 Dan
;;; : * Updated since DM uses millisecond times internally now.
;;; 2011.04.28 Dan
;;; : * Suppress warnings about extending chunks at initial load.
;;; 2016.03.14 Dan
;;; : * Added the provide so that it works well with require-extra.
;;; 2018.08.21 Dan [2.0]
;;; : * Updated for 7.6+ with a lock to protect the internals.
;;; 2020.01.10 Dan [2.1]
;;; : * Removed the #' from the module interface functions since
;;; : that's not allowed in the general system now.
;;; 2022.05.09 Dan
;;; : * Changed the "flag" value for :bll from 91923.12 to 12.34
;;; : to avoid potential overflow issues in DM's setting of some
;;; : other values in response.
;;; 2022.05.23 Dan
;;; : * Set :ol to nil before setting the flag value of :bll when
;;; : setting :eblse to avoid the warning about complex numbers.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; When the :eblse (enable base level spacing effect) paramter is set to t
;;; base level activation is computed using the new equation.
;;;
;;; To do so, :ol (optimized learning) must be set to nil and the model
;;; must not be using the :bl-hook functionality (warnings will be printed if
;;; violations of either of those conditions are noticed). In addition,
;;; the setting of :bll by the model will be ignored and it will be set to
;;; the value 12.34 to enable the computation of base levels (since that
;;; parameter is both the switch and the parameter value) and provide a value
;;; that I can check against for saftey testing (since it's very unlikely that
;;; a user will every set that specific value).
;;;
;;; The new equation for base level activation is similar to the old one:
;;;
;;; n
;;; B[n] = ln( sum t[i]^-d[i])
;;; i=1
;;;
;;; The only difference being that the decay exponent value is no longer
;;; a constant, but is now based on the previous base level values by this
;;; equation:
;;;
;;; d[i] = c*e^m[i-1] + a
;;;
;;; whre m[i] = B[i] + (permanant noise of the chunk)
;;;
;;; The paramters :se-intercept (spacing effect intercept) and :se-scale
;;; (spacing effect scale) control the new computation for a and c respectively.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; New parameters :eblse, :se-intercept, and :se-scale only.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Because this was never actually implemented in ACT-R before, I asked Phil
;;; which activation to use for m in the general case. His thoughts were that
;;; it should only be based on the history of use of the chunk. That suggests
;;; using only the base level computation plus any permanent noise present.
;;; Thus, spreading activation, partial matching, and transient noise should
;;; not be considered for this.
;;;
;;; It does not support changing the c and a parameters "on the fly". Once
;;; the model has created a reference those decay values are cached and it
;;; does not recompute them - thus changing c and a other than at the start
;;; of the model will produce "wrong" results (at least what I would consider
;;; to be wrong values because the decays wouldn't all be generated from the
;;; current settings).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defstruct spacing-effect
enabled
scale
intercept
(lock (bt:make-recursive-lock "spacing-effect")))
(defun add-decay-value (chunk1 chunk2)
"Add another d to the list based on the last m of the pre-existing chunk
and put the initial value there if there wasn't one already."
(declare (ignore chunk2))
(let ((module (get-module spacing-effect)))
(bt:with-recursive-lock-held ((spacing-effect-lock module))
(let ((res (if (null (chunk-decays chunk1))
(list (spacing-effect-intercept module))
(chunk-decays chunk1))))
(aif (chunk-last-m chunk1)
(append (list (+ (* (spacing-effect-scale module)
(exp it))
(spacing-effect-intercept module)))
res)
nil ; If it doesn't have a last-m then punt and
; rely on a complete recomputation next time it's needed
)))))
(suppress-extension-warnings)
(extend-chunks decays :default-value nil
:copy-function copy-list
:merge-function add-decay-value)
(extend-chunks last-m :default-value nil
:copy-function identity)
(unsuppress-extension-warnings)
(defun compute-spacing-effect-activation (chunk)
(let ((module (get-module spacing-effect))
(ct (mp-time-ms))
(value 0.0))
(bt:with-recursive-lock-held ((spacing-effect-lock module))
(if (= (length (chunk-reference-list chunk))
(length (chunk-decays chunk)))
(progn
(mapcar (lambda (reference decay)
(incf value
(expt-coerced (max .05 (ms->seconds (- ct reference)))
(- decay))))
(chunk-reference-list chunk)
(chunk-decays chunk))
(setf value (log-coerced value))
(setf (chunk-last-m chunk) (+ value (chunk-permanent-noise chunk)))
value)
;; Compute the decay list and try again
;; painfully slow, but it shouldn't have to do this
;; since the merging should maintain the list
;; correctly - it's just here as a saftey net
;; in the event someone sets references directly.
(let* ((decays (list (spacing-effect-intercept module)))
(references (reverse (chunk-reference-list chunk)))
(new-references (list (pop references))))
(dolist (reference references)
(let ((value 0.0)
(ct reference)
)
(mapcar (lambda (reference decay)
(incf value
(expt-coerced (max .05 (ms->seconds (- ct reference)))
(- decay))))
new-references
decays)
(push (+ (* (spacing-effect-scale module)
(exp (+ (log-coerced value) (chunk-permanent-noise chunk))))
(spacing-effect-intercept module))
decays)
(push reference new-references)))
(setf (chunk-decays chunk) decays)
(compute-spacing-effect-activation chunk))))))
(defun spacing-effect-params (module param)
(bt:with-recursive-lock-held ((spacing-effect-lock module))
(cond ((consp param)
(case (car param)
(:ol
(when (and (cdr param)
(spacing-effect-enabled module))
(model-warning "Cannot turn on :ol when :eblse enabled")
(no-output (sgp :ol nil))))
(:bll
(when (spacing-effect-enabled module)
(cond ((and (numberp (cdr param)) (not (= (cdr param) 12.34)))
(model-warning "Changing :bll has no effect when :eblse is enabled")
(no-output (sgp :bll 12.34)))
((not (numberp (cdr param)))
(model-warning "Cannot turn off :bll while :eblse is enabled")
(no-output (sgp :bll 12.34))))
))
(:bl-hook
(when (and (spacing-effect-enabled module)
(not (equal (cdr param) 'compute-spacing-effect-activation)))
(model-warning "Cannot change the :bll-hook when :eblse enabled")
(no-output (sgp :bl-hook compute-spacing-effect-activation)))
)
(:eblse (setf (spacing-effect-enabled module) (cdr param))
(no-output
(when (cdr param)
(sgp :ol nil)
(sgp :bll 12.34)
(sgp :bl-hook compute-spacing-effect-activation)))
(cdr param))
(:se-intercept (setf (spacing-effect-intercept module) (cdr param)))
(:se-scale (setf (spacing-effect-scale module) (cdr param)))))
(t
(case param
(:eblse (spacing-effect-enabled module))
(:se-intercept (spacing-effect-intercept module))
(:se-scale (spacing-effect-scale module)))))))
(defun reset-spacing-effect-module (module)
(bt:with-recursive-lock-held ((spacing-effect-lock module))
(setf (spacing-effect-enabled module) nil)))
(defun create-spacing-module (name)
(declare (ignore name))
(make-spacing-effect))
(define-module-fct 'spacing-effect
nil
(list (define-parameter :eblse :owner t :default-value nil :valid-test 'tornil
:documentation "Enable base level spacing effect - turning this on replaces the base level equation with one sensitive to spacing effects"
:warning "T or nil")
(define-parameter :se-intercept :owner t :default-value .5 :valid-test 'numberp
:warning "a number"
:documentation "Spacing effect intercept parameter (a)")
(define-parameter :se-scale :owner t :default-value 0 :valid-test 'numberp
:warning "a number"
:documentation "Spacing effect scale parameter (c)")
(define-parameter :ol :owner nil)
(define-parameter :bl-hook :owner nil)
(define-parameter :bll :owner nil))
:creation 'create-spacing-module
:reset 'reset-spacing-effect-module
:params 'spacing-effect-params
:version "2.1"
:documentation
"Module to add the option of the Pavlik & Anderson spacing effect equation for base level activation"
)
(defun test-spacing-effect-1 ()
"Test the equation against the example in the paper for a sequence of retrievals"
(clear-all)
(define-model foo)
(sgp :esc t :eblse t :v t :act t :se-intercept 0.177 :se-scale .217)
(add-dm (g isa chunk))
(run-until-time 126)
;; fake a retrieval to get the times specific for the reference
(compute-activation (get-module declarative) 'g nil)
(set-buffer-chunk 'retrieval 'g)
(clear-buffer 'retrieval)
(run-until-time 252)
;; fake a retrieval to get the times specific for the reference
(compute-activation (get-module declarative) 'g nil)
(set-buffer-chunk 'retrieval 'g)
(clear-buffer 'retrieval)
(run-until-time 4844)
;; fake a retrieval to get the times specific for the reference
(compute-activation (get-module declarative) 'g nil)
(set-buffer-chunk 'retrieval 'g)
(clear-buffer 'retrieval)
(run-until-time 5877)
;; fake a retrieval to get the times specific for the reference
(compute-activation (get-module declarative) 'g nil)
(pprint (chunk-decays 'g))
)
(defun test-spacing-effect-2 ()
"Test the equation using a pre-specified reference list for a chunk"
(clear-all)
(define-model foo)
(sgp :esc t :eblse t :v t :act t :se-intercept 0.177 :se-scale .217)
(add-dm (g isa chunk))
(sdp g :references (4844 252 126 0))
(run-until-time 5877)
(compute-activation (get-module declarative) 'g nil)
(pprint (chunk-decays 'g))
)
(defun test-spacing-effect-3 ()
"Compare the default with the spacing to the original equation - should match"
(clear-all)
(define-model foo)
(sgp :esc t :v t :act t :bll .5 :ol nil)
(add-dm (g isa chunk))
(sdp g :references (4844 252 126 0))
(run-until-time 5877)
(compute-activation (get-module declarative) 'g nil)
(clear-all)
(define-model foo)
(sgp :esc t :eblse t :v t :act t)
(add-dm (g isa chunk))
(sdp g :references (4844 252 126 0))
(run-until-time 5877)
(compute-activation (get-module declarative) 'g nil)
(pprint (chunk-decays 'g))
)
#|
CG-USER(130): (test-spacing-effect-1 )
0.000 PROCEDURAL CONFLICT-RESOLUTION
126.000 PROCEDURAL CONFLICT-RESOLUTION
126.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
base-level hook returns: -0.8560219
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -0.8560219
252.000 PROCEDURAL CONFLICT-RESOLUTION
252.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
base-level hook returns: -0.43415272
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -0.43415272
4844.000 PROCEDURAL CONFLICT-RESOLUTION
4844.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
base-level hook returns: -0.9314301
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -0.9314301
5877.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
base-level hook returns: -0.61873615
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -0.61873615
(0.26249582 0.31757548 0.2691922 0.177)
CG-USER(131): (test-spacing-effect-2)
0.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
base-level hook returns: -0.61873615
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -0.61873615
(0.26249582 0.31757548 0.2691922 0.177)
CG-USER(140): (test-spacing-effect-3)
0.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
Starting with blc: 0.0
Computing base-level from 4 references (4844 252 126 0)
creation time: 0.0 decay: 0.5 Optimized-learning: NIL
base-level value: -2.649625
Total base-level: -2.649625
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -2.649625
0.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 PROCEDURAL CONFLICT-RESOLUTION
5877.000 ------ Stopped because time limit reached
Computing activation for chunk G
Computing base-level
base-level hook returns: -2.649625
Adding transient noise 0.0
Adding permanent noise 0.0
Chunk G has an activation of: -2.649625
(0.5 0.5 0.5 0.5)
|#
(provide "spacing-effect")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 17,623 | Common Lisp | .lisp | 393 | 38.638677 | 148 | 0.614462 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b3fccd32a7019f7654c0b6f7eaedc3c7e7131e8fd788ad3ae93deae10d3a48f1 | 14,277 | [
-1
] |
14,278 | blending-test-7.lisp | asmaloney_ACT-R/extras/blending/blending-test-7.lisp | ;; Simple model to show blending in action
;; while using inequality constraints to
;; limit the set of chunks retrieved and
;; that when the values to be blended
;; don't have common slots every chunk
;; in dm is a potential candidate.
;; Load the model and call run to see the
;; trace of a blended retrieval.
;;
(clear-all)
(require-extra "blending")
(define-model test-blending
(sgp :seed (1 1) :v t :blt t :esc t :ans .25 :rt 4)
(chunk-type target key value size)
(chunk-type size (size-type t))
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 value 1 size large)
(b isa target key key-1 value 2 size x-large)
(c isa target key key-1 value 3 size tiny)
(d isa target key key-2 value 1 size nil)
(e isa target key key-2 value 3 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Provide the similarities between the sizes
;; because blending will use that even though
;; partial matching is not enabled.
(set-similarities (tiny small -.1)
(small medium -.1)
(medium large -.1)
(large x-large -.1)
(tiny medium -.3)
(small large -.3)
(medium x-large -.3)
(tiny large -.6)
(small x-large -.6)
(tiny x-large -.9))
;; Very simple model.
;; Make a blending request for a target chunk
;; with any value in the key slot and a value
;; slot which is in the range (1,3].
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
- key nil
<= value 3
> value 1)
(p p2
=blending>
isa target
value =val
size =size
key =key
?blending>
state free
==>
!output! (blended value is =val size is =size and key is =key)
=blending>
value nil
)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY VALUE)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk B matches blending request
Activation 2.5325232
Probability of recall 0.0018145373
Chunk C matches blending request
Activation 4.763482
Probability of recall 0.9981818
Chunk E matches blending request
Activation 0.34333676
Probability of recall 3.7122225e-6
Slots to be blended: (KEY VALUE SIZE)
Finding blended value for slot: KEY
Matched chunks' slots contain: (KEY-1 KEY-1 KEY-2)
Magnitude values for those items: (KEY-1 KEY-1 KEY-2)
When all magnitudes are chunks blending based on similarities to all related chunks
No intersecting slots found all chunks will be tested
Comparing value D
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value E
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value C
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value B
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value A
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value X-LARGE
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value LARGE
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value MEDIUM
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value SMALL
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Comparing value TINY
Chunk B with probability 0.0018145373 slot value KEY-1 similarity: -1.0 cumulative result: 0.0018145373
Chunk C with probability 0.9981818 slot value KEY-1 similarity: -1.0 cumulative result: 0.99999636
Chunk E with probability 3.7122225e-6 slot value KEY-2 similarity: -1.0 cumulative result: 1.0000001
Final result: D
Finding blended value for slot: VALUE
Matched chunks' slots contain: (2 3 3)
Magnitude values for those items: (2 3 3)
With numeric magnitudes blending by weighted average
Chunk B with probability 0.0018145373 times magnitude 2.0 = 0.0036290747 cumulative result: 0.0036290747
Chunk C with probability 0.9981818 times magnitude 3.0 = 2.9945455 cumulative result: 2.9981744
Chunk E with probability 3.7122225e-6 times magnitude 3.0 = 1.1136667e-5 cumulative result: 2.9981856
Final result: 2.9981856
Finding blended value for slot: SIZE
Matched chunks' slots contain: (X-LARGE TINY SMALL)
Magnitude values for those items: (X-LARGE TINY SMALL)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk B with probability 0.0018145373 slot value X-LARGE similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.9981818 slot value TINY similarity: -0.9 cumulative result: 0.80852723
Chunk E with probability 3.7122225e-6 slot value SMALL similarity: -0.6 cumulative result: 0.80852854
Comparing value LARGE
Chunk B with probability 0.0018145373 slot value X-LARGE similarity: -0.1 cumulative result: 1.8145374e-5
Chunk C with probability 0.9981818 slot value TINY similarity: -0.6 cumulative result: 0.35936362
Chunk E with probability 3.7122225e-6 slot value SMALL similarity: -0.3 cumulative result: 0.35936394
Comparing value MEDIUM
Chunk B with probability 0.0018145373 slot value X-LARGE similarity: -0.3 cumulative result: 1.6330836e-4
Chunk C with probability 0.9981818 slot value TINY similarity: -0.3 cumulative result: 0.089999676
Chunk E with probability 3.7122225e-6 slot value SMALL similarity: -0.1 cumulative result: 0.08999971
Comparing value SMALL
Chunk B with probability 0.0018145373 slot value X-LARGE similarity: -0.6 cumulative result: 6.5323344e-4
Chunk C with probability 0.9981818 slot value TINY similarity: -0.1 cumulative result: 0.010635052
Chunk E with probability 3.7122225e-6 slot value SMALL similarity: 0.0 cumulative result: 0.010635052
Comparing value TINY
Chunk B with probability 0.0018145373 slot value X-LARGE similarity: -0.9 cumulative result: 0.0014697751
Chunk C with probability 0.9981818 slot value TINY similarity: 0.0 cumulative result: 0.0014697751
Chunk E with probability 3.7122225e-6 slot value SMALL similarity: -0.1 cumulative result: 0.0014698122
Final result: TINY
This is the definition of the blended chunk:
(KEY D VALUE 2.9981856 SIZE TINY)
Computing activation and latency for the blended chunk
Activation of chunk B is 2.5325232
Activation of chunk C is 4.763482
Activation of chunk E is 0.34333676
Activation for blended chunk is: 4.8763266
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.058 BLENDING BLENDING-COMPLETE
0.058 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.058 PROCEDURAL CONFLICT-RESOLUTION
0.108 PROCEDURAL PRODUCTION-FIRED P2
BLENDED VALUE IS 2.9981856 SIZE IS TINY AND KEY IS D
0.108 PROCEDURAL CONFLICT-RESOLUTION
0.108 ------ Stopped because no events left to process
0.108
22
NIL
|#
| 10,040 | Common Lisp | .lisp | 195 | 47.117949 | 107 | 0.736891 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4c33b6ec0d826938067f59ae831f74d70cde8ac4447e815dae74dc541d89dcb9 | 14,278 | [
-1
] |
14,279 | blending-test-1.lisp | asmaloney_ACT-R/extras/blending/blending-test-1.lisp | ;; Simple model to show blending in action.
;; Load the model and call run to see the
;; trace of two blended retrievals. The
;; second one will usually fail because
;; it will be below the retrieval threshold.
;;
;; This is a simple case without partial
;; matching enabled and demonstrating both
;; a numeric value blending and a chunk based
;; blending.
(clear-all)
(require-extra "blending")
(define-model test-blending
(sgp :seed (1 1) :v t :blt t :esc t :ans .25 :rt 4)
(chunk-type target key value size)
(chunk-type size (size-type t))
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 value 1 size large)
(b isa target key key-1 value 2 size x-large)
(c isa target key key-1 value 3 size tiny)
(d isa target key key-2 value 1 size nil)
(e isa target key key-2 value 3 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Provide the similarities between the sizes
;; because blending will use that even though
;; partial matching is not enabled.
(set-similarities (tiny small -.1)
(small medium -.1)
(medium large -.1)
(large x-large -.1)
(tiny medium -.3)
(small large -.3)
(medium x-large -.3)
(tiny large -.6)
(small x-large -.6)
(tiny x-large -.9))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
key key-1)
(p p2
=blending>
isa target
value =val
size =size
?blending>
state free
==>
!output! (blended value is =val and size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
key key-2)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk A matches blending request
Activation 2.5325232
Probability of recall 0.00497158
Chunk B matches blending request
Activation 3.763482
Probability of recall 0.16164705
Chunk C matches blending request
Activation 4.3433366
Probability of recall 0.8333814
Slots to be blended: (SIZE VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (LARGE X-LARGE TINY)
Magnitude values for those items: (LARGE X-LARGE TINY)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.1 cumulative result: 4.9715803e-5
Chunk B with probability 0.16164705 slot value X-LARGE similarity: 0.0 cumulative result: 4.9715803e-5
Chunk C with probability 0.8333814 slot value TINY similarity: -0.9 cumulative result: 0.6750886
Comparing value LARGE
Chunk A with probability 0.00497158 slot value LARGE similarity: 0.0 cumulative result: 0.0
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.1 cumulative result: 0.0016164706
Chunk C with probability 0.8333814 slot value TINY similarity: -0.6 cumulative result: 0.3016338
Comparing value MEDIUM
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.1 cumulative result: 4.9715803e-5
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.3 cumulative result: 0.014597951
Chunk C with probability 0.8333814 slot value TINY similarity: -0.3 cumulative result: 0.089602284
Comparing value SMALL
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.3 cumulative result: 4.4744223e-4
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.6 cumulative result: 0.058640383
Chunk C with probability 0.8333814 slot value TINY similarity: -0.1 cumulative result: 0.0669742
Comparing value TINY
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.6 cumulative result: 0.0017897689
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.9 cumulative result: 0.13272387
Chunk C with probability 0.8333814 slot value TINY similarity: 0.0 cumulative result: 0.13272387
Final result: SMALL
Finding blended value for slot: VALUE
Matched chunks' slots contain: (1 2 3)
Magnitude values for those items: (1 2 3)
With numeric magnitudes blending by weighted average
Chunk A with probability 0.00497158 times magnitude 1.0 = 0.00497158 cumulative result: 0.00497158
Chunk B with probability 0.16164705 times magnitude 2.0 = 0.3232941 cumulative result: 0.3282657
Chunk C with probability 0.8333814 times magnitude 3.0 = 2.5001442 cumulative result: 2.82841
Final result: 2.82841
This is the definition of the blended chunk:
(KEY KEY-1 SIZE SMALL VALUE 2.82841)
Computing activation and latency for the blended chunk
Activation of chunk A is 2.5325232
Activation of chunk B is 3.763482
Activation of chunk C is 4.3433366
Activation for blended chunk is: 4.8876944
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.058 BLENDING BLENDING-COMPLETE
0.058 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.058 PROCEDURAL CONFLICT-RESOLUTION
0.108 PROCEDURAL PRODUCTION-FIRED P2
BLENDED VALUE IS 2.82841 AND SIZE IS SMALL
0.108 PROCEDURAL CLEAR-BUFFER BLENDING
0.108 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk E matches blending request
Activation 3.2689652
Probability of recall 0.9031912
Chunk D matches blending request
Activation 2.4794111
Probability of recall 0.09680881
Slots to be blended: (SIZE VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL)
Magnitude values for those items: (SMALL)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.6 cumulative result: 0.32514885
Comparing value LARGE
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.3 cumulative result: 0.08128721
Comparing value MEDIUM
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.1 cumulative result: 0.009031912
Comparing value SMALL
Chunk E with probability 0.9031912 slot value SMALL similarity: 0.0 cumulative result: 0.0
Comparing value TINY
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.1 cumulative result: 0.009031912
Final result: SMALL
Finding blended value for slot: VALUE
Matched chunks' slots contain: (3 1)
Magnitude values for those items: (3 1)
With numeric magnitudes blending by weighted average
Chunk E with probability 0.9031912 times magnitude 3.0 = 2.7095737 cumulative result: 2.7095737
Chunk D with probability 0.09680881 times magnitude 1.0 = 0.09680881 cumulative result: 2.8063827
Final result: 2.8063827
This is the definition of the blended chunk:
(KEY KEY-2 SIZE SMALL VALUE 2.8063827)
Computing activation and latency for the blended chunk
Activation of chunk E is 3.2689652
Activation of chunk D is 2.4794111
Activation for blended chunk is: 3.643316
Not above threshold so blending failed
0.108 PROCEDURAL CONFLICT-RESOLUTION
0.126 BLENDING BLENDING-FAILURE
0.126 PROCEDURAL CONFLICT-RESOLUTION
0.126 ------ Stopped because no events left to process
0.126
27
NIL
|#
| 8,713 | Common Lisp | .lisp | 195 | 40.235897 | 105 | 0.724212 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 46faec60c3687e113fbe26c2737c1f3588d0fde5957cb14231b22c4e30dd7d2c | 14,279 | [
-1
] |
14,280 | blending-test-2.lisp | asmaloney_ACT-R/extras/blending/blending-test-2.lisp | ;; Simple model to show blending in action.
;; Load the model and call run to see the
;; trace of two blended retrievals. The
;; second one will usually fail because
;; it will be below the retrieval threshold.
;;
;; Same model as test-1 except now partial
;; matching is enabled and the temperature
;; parameter is set explicitly.
(clear-all)
(require-extra "blending")
(define-model test-blending
(sgp :seed (2 1) :v t :blt t :esc t :ans .25 :rt 5 :mp 1 :tmp 1.5)
(chunk-type target key value size)
(chunk-type size (size-type t))
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 value 1 size large)
(b isa target key key-1 value 2 size x-large)
(c isa target key key-1 value 3 size tiny)
(d isa target key key-2 value 1 size nil)
(e isa target key key-2 value 3 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Provide the similarities between the sizes
;; because blending will use that even though
;; partial matching is not enabled.
(set-similarities (tiny small -.1)
(small medium -.1)
(medium large -.1)
(large x-large -.1)
(tiny medium -.3)
(small large -.3)
(medium x-large -.3)
(tiny large -.6)
(small x-large -.6)
(tiny x-large -.9))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
key key-1)
(p p2
=blending>
isa target
value =val
size =size
?blending>
state free
==>
!output! (blended value is =val and size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
key key-2)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature is: 1.5
Chunk D matches blending request
Activation 1.370572
Probability of recall 0.055086102
Chunk E matches blending request
Activation 0.906558
Probability of recall 0.040429305
Chunk C matches blending request
Activation 4.347349
Probability of recall 0.40078118
Chunk B matches blending request
Activation 3.9501731
Probability of recall 0.3075481
Chunk A matches blending request
Activation 3.2755852
Probability of recall 0.19615522
Slots to be blended: (SIZE VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL TINY X-LARGE LARGE)
Magnitude values for those items: (SMALL TINY X-LARGE LARGE)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk E with probability 0.040429305 slot value SMALL similarity: -0.6 cumulative result: 0.014554551
Chunk C with probability 0.40078118 slot value TINY similarity: -0.9 cumulative result: 0.3391873
Chunk B with probability 0.3075481 slot value X-LARGE similarity: 0.0 cumulative result: 0.3391873
Chunk A with probability 0.19615522 slot value LARGE similarity: -0.1 cumulative result: 0.34114885
Comparing value LARGE
Chunk E with probability 0.040429305 slot value SMALL similarity: -0.3 cumulative result: 0.0036386377
Chunk C with probability 0.40078118 slot value TINY similarity: -0.6 cumulative result: 0.14791988
Chunk B with probability 0.3075481 slot value X-LARGE similarity: -0.1 cumulative result: 0.15099536
Chunk A with probability 0.19615522 slot value LARGE similarity: 0.0 cumulative result: 0.15099536
Comparing value MEDIUM
Chunk E with probability 0.040429305 slot value SMALL similarity: -0.1 cumulative result: 4.042931e-4
Chunk C with probability 0.40078118 slot value TINY similarity: -0.3 cumulative result: 0.036474604
Chunk B with probability 0.3075481 slot value X-LARGE similarity: -0.3 cumulative result: 0.06415393
Chunk A with probability 0.19615522 slot value LARGE similarity: -0.1 cumulative result: 0.06611548
Comparing value SMALL
Chunk E with probability 0.040429305 slot value SMALL similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.40078118 slot value TINY similarity: -0.1 cumulative result: 0.004007812
Chunk B with probability 0.3075481 slot value X-LARGE similarity: -0.6 cumulative result: 0.11472513
Chunk A with probability 0.19615522 slot value LARGE similarity: -0.3 cumulative result: 0.1323791
Comparing value TINY
Chunk E with probability 0.040429305 slot value SMALL similarity: -0.1 cumulative result: 4.042931e-4
Chunk C with probability 0.40078118 slot value TINY similarity: 0.0 cumulative result: 4.042931e-4
Chunk B with probability 0.3075481 slot value X-LARGE similarity: -0.9 cumulative result: 0.24951825
Chunk A with probability 0.19615522 slot value LARGE similarity: -0.6 cumulative result: 0.32013413
Final result: MEDIUM
Finding blended value for slot: VALUE
Matched chunks' slots contain: (1 3 3 2 1)
Magnitude values for those items: (1 3 3 2 1)
With numeric magnitudes blending by weighted average
Chunk D with probability 0.055086102 times magnitude 1.0 = 0.055086102 cumulative result: 0.055086102
Chunk E with probability 0.040429305 times magnitude 3.0 = 0.12128791 cumulative result: 0.17637402
Chunk C with probability 0.40078118 times magnitude 3.0 = 1.2023436 cumulative result: 1.3787177
Chunk B with probability 0.3075481 times magnitude 2.0 = 0.6150962 cumulative result: 1.9938139
Chunk A with probability 0.19615522 times magnitude 1.0 = 0.19615522 cumulative result: 2.189969
Final result: 2.189969
This is the definition of the blended chunk:
(KEY KEY-1 SIZE MEDIUM VALUE 2.189969)
Computing activation and latency for the blended chunk
Activation of chunk D is 1.370572
Activation of chunk E is 0.906558
Activation of chunk C is 4.347349
Activation of chunk B is 3.9501731
Activation of chunk A is 3.2755852
Activation for blended chunk is: 5.0881505
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.056 BLENDING BLENDING-COMPLETE
0.056 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.056 PROCEDURAL CONFLICT-RESOLUTION
0.106 PROCEDURAL PRODUCTION-FIRED P2
BLENDED VALUE IS 2.189969 AND SIZE IS MEDIUM
0.106 PROCEDURAL CLEAR-BUFFER BLENDING
0.106 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature is: 1.5
Chunk D matches blending request
Activation 2.065042
Probability of recall 0.10480824
Chunk E matches blending request
Activation 1.0152556
Probability of recall 0.05205363
Chunk C matches blending request
Activation 4.080316
Probability of recall 0.40167704
Chunk B matches blending request
Activation 3.1878269
Probability of recall 0.22155161
Chunk A matches blending request
Activation 3.1766677
Probability of recall 0.21990952
Slots to be blended: (SIZE VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL TINY X-LARGE LARGE)
Magnitude values for those items: (SMALL TINY X-LARGE LARGE)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk E with probability 0.05205363 slot value SMALL similarity: -0.6 cumulative result: 0.018739307
Chunk C with probability 0.40167704 slot value TINY similarity: -0.9 cumulative result: 0.3440977
Chunk B with probability 0.22155161 slot value X-LARGE similarity: 0.0 cumulative result: 0.3440977
Chunk A with probability 0.21990952 slot value LARGE similarity: -0.1 cumulative result: 0.3462968
Comparing value LARGE
Chunk E with probability 0.05205363 slot value SMALL similarity: -0.3 cumulative result: 0.004684827
Chunk C with probability 0.40167704 slot value TINY similarity: -0.6 cumulative result: 0.14928856
Chunk B with probability 0.22155161 slot value X-LARGE similarity: -0.1 cumulative result: 0.15150408
Chunk A with probability 0.21990952 slot value LARGE similarity: 0.0 cumulative result: 0.15150408
Comparing value MEDIUM
Chunk E with probability 0.05205363 slot value SMALL similarity: -0.1 cumulative result: 5.205363e-4
Chunk C with probability 0.40167704 slot value TINY similarity: -0.3 cumulative result: 0.03667147
Chunk B with probability 0.22155161 slot value X-LARGE similarity: -0.3 cumulative result: 0.056611117
Chunk A with probability 0.21990952 slot value LARGE similarity: -0.1 cumulative result: 0.05881021
Comparing value SMALL
Chunk E with probability 0.05205363 slot value SMALL similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.40167704 slot value TINY similarity: -0.1 cumulative result: 0.0040167705
Chunk B with probability 0.22155161 slot value X-LARGE similarity: -0.6 cumulative result: 0.08377536
Chunk A with probability 0.21990952 slot value LARGE similarity: -0.3 cumulative result: 0.10356721
Comparing value TINY
Chunk E with probability 0.05205363 slot value SMALL similarity: -0.1 cumulative result: 5.205363e-4
Chunk C with probability 0.40167704 slot value TINY similarity: 0.0 cumulative result: 5.205363e-4
Chunk B with probability 0.22155161 slot value X-LARGE similarity: -0.9 cumulative result: 0.17997734
Chunk A with probability 0.21990952 slot value LARGE similarity: -0.6 cumulative result: 0.25914478
Final result: MEDIUM
Finding blended value for slot: VALUE
Matched chunks' slots contain: (1 3 3 2 1)
Magnitude values for those items: (1 3 3 2 1)
With numeric magnitudes blending by weighted average
Chunk D with probability 0.10480824 times magnitude 1.0 = 0.10480824 cumulative result: 0.10480824
Chunk E with probability 0.05205363 times magnitude 3.0 = 0.15616089 cumulative result: 0.26096913
Chunk C with probability 0.40167704 times magnitude 3.0 = 1.2050312 cumulative result: 1.4660003
Chunk B with probability 0.22155161 times magnitude 2.0 = 0.44310322 cumulative result: 1.9091035
Chunk A with probability 0.21990952 times magnitude 1.0 = 0.21990952 cumulative result: 2.129013
Final result: 2.129013
This is the definition of the blended chunk:
(KEY KEY-2 SIZE MEDIUM VALUE 2.129013)
Computing activation and latency for the blended chunk
Activation of chunk D is 2.065042
Activation of chunk E is 1.0152556
Activation of chunk C is 4.080316
Activation of chunk B is 3.1878269
Activation of chunk A is 3.1766677
Activation for blended chunk is: 4.770789
Not above threshold so blending failed
0.106 PROCEDURAL CONFLICT-RESOLUTION
0.113 BLENDING BLENDING-FAILURE
0.113 PROCEDURAL CONFLICT-RESOLUTION
0.113 ------ Stopped because no events left to process
0.113
27
NIL
|#
| 11,892 | Common Lisp | .lisp | 239 | 45.648536 | 104 | 0.74706 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4b1671d0a81d4589d85f7c1cfa7a3b560cb29b8365b5b53b6ba59939f5b2dd5e | 14,280 | [
-1
] |
14,281 | blending-test-5.lisp | asmaloney_ACT-R/extras/blending/blending-test-5.lisp | ;; Simple model to show blending in action.
;; Load the model and call run to see the
;; trace of two blended retrievals.
;;
;; This example is similar to the others, except that
;; it sets the :blend-all-slots parameter to t and
;; makes a couple of other changes to show that in
;; action:
;; - the keys are created using a specific type and added
;; to DM (the specific type is used because otherwise
;; all chunks of type chunk would be considered valid
;; values)
;; - the value slot is used in the second request instead
;; of the key.
(clear-all)
(require-extra "blending")
(define-model test-blending
(sgp :seed (2 1) :v t :blt t :esc t :ans .25 :rt 4 :mp 1 :tmp 1.5 :blend-all-slots t)
(chunk-type target key value size)
(chunk-type size (size-type t))
(chunk-type key (key-type t))
;; Here are the chunks for the blending test
(add-dm
;; the keys
(key-1 isa key)
(key-2 isa key)
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 value 1 size large)
(b isa target key key-1 value 2 size x-large)
(c isa target key key-1 value 3 size tiny)
(d isa target key key-2 value 1 size nil)
(e isa target key key-2 value 3 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Provide the similarities between the sizes
;; because blending will use that even though
;; partial matching is not enabled.
(set-similarities (tiny small -.1)
(small medium -.1)
(medium large -.1)
(large x-large -.1)
(tiny medium -.3)
(small large -.3)
(medium x-large -.3)
(tiny large -.6)
(small x-large -.6)
(tiny x-large -.9))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
key key-2)
(p p2
=blending>
isa target
value =val
size =size
?goal>
buffer empty
?blending>
state free
==>
!output! (blended value is =val and size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
value 2
;; just set some goal to prevent repeat firing
+goal> isa chunk
)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature is: 1.5
Chunk D matches blending request
Activation 2.370572
Probability of recall 0.1649606
Chunk E matches blending request
Activation 1.906558
Probability of recall 0.1210694
Chunk C matches blending request
Activation 3.3473492
Probability of recall 0.31636333
Chunk B matches blending request
Activation 2.9501731
Probability of recall 0.24276826
Chunk A matches blending request
Activation 2.2755852
Probability of recall 0.15483841
Slots to be blended: (KEY VALUE SIZE)
Finding blended value for slot: KEY
Matched chunks' slots contain: (KEY-2 KEY-2 KEY-1 KEY-1 KEY-1)
Magnitude values for those items: (KEY-2 KEY-2 KEY-1 KEY-1 KEY-1)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (KEY-TYPE)
Comparing value KEY-2
Chunk D with probability 0.1649606 slot value KEY-2 similarity: 0.0 cumulative result: 0.0
Chunk E with probability 0.1210694 slot value KEY-2 similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.31636333 slot value KEY-1 similarity: -1.0 cumulative result: 0.31636333
Chunk B with probability 0.24276826 slot value KEY-1 similarity: -1.0 cumulative result: 0.5591316
Chunk A with probability 0.15483841 slot value KEY-1 similarity: -1.0 cumulative result: 0.71397007
Comparing value KEY-1
Chunk D with probability 0.1649606 slot value KEY-2 similarity: -1.0 cumulative result: 0.1649606
Chunk E with probability 0.1210694 slot value KEY-2 similarity: -1.0 cumulative result: 0.28603
Chunk C with probability 0.31636333 slot value KEY-1 similarity: 0.0 cumulative result: 0.28603
Chunk B with probability 0.24276826 slot value KEY-1 similarity: 0.0 cumulative result: 0.28603
Chunk A with probability 0.15483841 slot value KEY-1 similarity: 0.0 cumulative result: 0.28603
Final result: KEY-1
Finding blended value for slot: VALUE
Matched chunks' slots contain: (1 3 3 2 1)
Magnitude values for those items: (1 3 3 2 1)
With numeric magnitudes blending by weighted average
Chunk D with probability 0.1649606 times magnitude 1.0 = 0.1649606 cumulative result: 0.1649606
Chunk E with probability 0.1210694 times magnitude 3.0 = 0.3632082 cumulative result: 0.5281688
Chunk C with probability 0.31636333 times magnitude 3.0 = 0.94909 cumulative result: 1.4772588
Chunk B with probability 0.24276826 times magnitude 2.0 = 0.48553652 cumulative result: 1.9627953
Chunk A with probability 0.15483841 times magnitude 1.0 = 0.15483841 cumulative result: 2.1176336
Final result: 2.1176336
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL TINY X-LARGE LARGE)
Magnitude values for those items: (SMALL TINY X-LARGE LARGE)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk E with probability 0.1210694 slot value SMALL similarity: -0.6 cumulative result: 0.043584988
Chunk C with probability 0.31636333 slot value TINY similarity: -0.9 cumulative result: 0.29983926
Chunk B with probability 0.24276826 slot value X-LARGE similarity: 0.0 cumulative result: 0.29983926
Chunk A with probability 0.15483841 slot value LARGE similarity: -0.1 cumulative result: 0.30138764
Comparing value LARGE
Chunk E with probability 0.1210694 slot value SMALL similarity: -0.3 cumulative result: 0.010896247
Chunk C with probability 0.31636333 slot value TINY similarity: -0.6 cumulative result: 0.12478705
Chunk B with probability 0.24276826 slot value X-LARGE similarity: -0.1 cumulative result: 0.12721473
Chunk A with probability 0.15483841 slot value LARGE similarity: 0.0 cumulative result: 0.12721473
Comparing value MEDIUM
Chunk E with probability 0.1210694 slot value SMALL similarity: -0.1 cumulative result: 0.0012106941
Chunk C with probability 0.31636333 slot value TINY similarity: -0.3 cumulative result: 0.029683394
Chunk B with probability 0.24276826 slot value X-LARGE similarity: -0.3 cumulative result: 0.051532537
Chunk A with probability 0.15483841 slot value LARGE similarity: -0.1 cumulative result: 0.05308092
Comparing value SMALL
Chunk E with probability 0.1210694 slot value SMALL similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.31636333 slot value TINY similarity: -0.1 cumulative result: 0.0031636336
Chunk B with probability 0.24276826 slot value X-LARGE similarity: -0.6 cumulative result: 0.09056021
Chunk A with probability 0.15483841 slot value LARGE similarity: -0.3 cumulative result: 0.104495674
Comparing value TINY
Chunk E with probability 0.1210694 slot value SMALL similarity: -0.1 cumulative result: 0.0012106941
Chunk C with probability 0.31636333 slot value TINY similarity: 0.0 cumulative result: 0.0012106941
Chunk B with probability 0.24276826 slot value X-LARGE similarity: -0.9 cumulative result: 0.19785297
Chunk A with probability 0.15483841 slot value LARGE similarity: -0.6 cumulative result: 0.25359482
Final result: MEDIUM
This is the definition of the blended chunk:
(KEY KEY-1 VALUE 2.1176336 SIZE MEDIUM)
Computing activation and latency for the blended chunk
Activation of chunk D is 2.370572
Activation of chunk E is 1.906558
Activation of chunk C is 3.3473492
Activation of chunk B is 2.9501731
Activation of chunk A is 2.2755852
Activation for blended chunk is: 4.3135276
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.063 BLENDING BLENDING-COMPLETE
0.063 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.063 PROCEDURAL CONFLICT-RESOLUTION
0.113 PROCEDURAL PRODUCTION-FIRED P2
BLENDED VALUE IS 2.1176336 AND SIZE IS MEDIUM
0.113 PROCEDURAL CLEAR-BUFFER BLENDING
0.113 PROCEDURAL CLEAR-BUFFER GOAL
0.113 GOAL SET-BUFFER-CHUNK-FROM-SPEC GOAL
0.113 BLENDING START-BLENDING
Blending request for chunks with slots (VALUE)
Blending temperature is: 1.5
Chunk D matches blending request
Activation 1.065042
Probability of recall 0.04746663
Chunk E matches blending request
Activation 0.015255626
Probability of recall 0.023574583
Chunk C matches blending request
Activation 4.080316
Probability of recall 0.35432324
Chunk B matches blending request
Activation 4.187827
Probability of recall 0.38065124
Chunk A matches blending request
Activation 3.1766677
Probability of recall 0.19398431
Slots to be blended: (KEY VALUE SIZE)
Finding blended value for slot: KEY
Matched chunks' slots contain: (KEY-2 KEY-2 KEY-1 KEY-1 KEY-1)
Magnitude values for those items: (KEY-2 KEY-2 KEY-1 KEY-1 KEY-1)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (KEY-TYPE)
Comparing value KEY-2
Chunk D with probability 0.04746663 slot value KEY-2 similarity: 0.0 cumulative result: 0.0
Chunk E with probability 0.023574583 slot value KEY-2 similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.35432324 slot value KEY-1 similarity: -1.0 cumulative result: 0.35432324
Chunk B with probability 0.38065124 slot value KEY-1 similarity: -1.0 cumulative result: 0.7349745
Chunk A with probability 0.19398431 slot value KEY-1 similarity: -1.0 cumulative result: 0.92895883
Comparing value KEY-1
Chunk D with probability 0.04746663 slot value KEY-2 similarity: -1.0 cumulative result: 0.04746663
Chunk E with probability 0.023574583 slot value KEY-2 similarity: -1.0 cumulative result: 0.07104121
Chunk C with probability 0.35432324 slot value KEY-1 similarity: 0.0 cumulative result: 0.07104121
Chunk B with probability 0.38065124 slot value KEY-1 similarity: 0.0 cumulative result: 0.07104121
Chunk A with probability 0.19398431 slot value KEY-1 similarity: 0.0 cumulative result: 0.07104121
Final result: KEY-1
Finding blended value for slot: VALUE
Matched chunks' slots contain: (1 3 3 2 1)
Magnitude values for those items: (1 3 3 2 1)
With numeric magnitudes blending by weighted average
Chunk D with probability 0.04746663 times magnitude 1.0 = 0.04746663 cumulative result: 0.04746663
Chunk E with probability 0.023574583 times magnitude 3.0 = 0.07072375 cumulative result: 0.11819038
Chunk C with probability 0.35432324 times magnitude 3.0 = 1.0629697 cumulative result: 1.1811601
Chunk B with probability 0.38065124 times magnitude 2.0 = 0.7613025 cumulative result: 1.9424626
Chunk A with probability 0.19398431 times magnitude 1.0 = 0.19398431 cumulative result: 2.136447
Final result: 2.136447
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL TINY X-LARGE LARGE)
Magnitude values for those items: (SMALL TINY X-LARGE LARGE)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk E with probability 0.023574583 slot value SMALL similarity: -0.6 cumulative result: 0.00848685
Chunk C with probability 0.35432324 slot value TINY similarity: -0.9 cumulative result: 0.29548863
Chunk B with probability 0.38065124 slot value X-LARGE similarity: 0.0 cumulative result: 0.29548863
Chunk A with probability 0.19398431 slot value LARGE similarity: -0.1 cumulative result: 0.29742846
Comparing value LARGE
Chunk E with probability 0.023574583 slot value SMALL similarity: -0.3 cumulative result: 0.0021217125
Chunk C with probability 0.35432324 slot value TINY similarity: -0.6 cumulative result: 0.12967809
Chunk B with probability 0.38065124 slot value X-LARGE similarity: -0.1 cumulative result: 0.1334846
Chunk A with probability 0.19398431 slot value LARGE similarity: 0.0 cumulative result: 0.1334846
Comparing value MEDIUM
Chunk E with probability 0.023574583 slot value SMALL similarity: -0.1 cumulative result: 2.3574584e-4
Chunk C with probability 0.35432324 slot value TINY similarity: -0.3 cumulative result: 0.03212484
Chunk B with probability 0.38065124 slot value X-LARGE similarity: -0.3 cumulative result: 0.06638345
Chunk A with probability 0.19398431 slot value LARGE similarity: -0.1 cumulative result: 0.06832329
Comparing value SMALL
Chunk E with probability 0.023574583 slot value SMALL similarity: 0.0 cumulative result: 0.0
Chunk C with probability 0.35432324 slot value TINY similarity: -0.1 cumulative result: 0.0035432326
Chunk B with probability 0.38065124 slot value X-LARGE similarity: -0.6 cumulative result: 0.14057767
Chunk A with probability 0.19398431 slot value LARGE similarity: -0.3 cumulative result: 0.15803626
Comparing value TINY
Chunk E with probability 0.023574583 slot value SMALL similarity: -0.1 cumulative result: 2.3574584e-4
Chunk C with probability 0.35432324 slot value TINY similarity: 0.0 cumulative result: 2.3574584e-4
Chunk B with probability 0.38065124 slot value X-LARGE similarity: -0.9 cumulative result: 0.3085632
Chunk A with probability 0.19398431 slot value LARGE similarity: -0.6 cumulative result: 0.37839755
Final result: MEDIUM
This is the definition of the blended chunk:
(KEY KEY-1 VALUE 2.136447 SIZE MEDIUM)
Computing activation and latency for the blended chunk
Activation of chunk D is 1.065042
Activation of chunk E is 0.015255626
Activation of chunk C is 4.080316
Activation of chunk B is 4.187827
Activation of chunk A is 3.1766677
Activation for blended chunk is: 5.029959
0.113 PROCEDURAL CONFLICT-RESOLUTION
0.120 BLENDING BLENDING-COMPLETE
0.120 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.120 PROCEDURAL CONFLICT-RESOLUTION
0.120 ------ Stopped because no events left to process
0.12
33
NIL
|#
| 15,122 | Common Lisp | .lisp | 287 | 48.738676 | 104 | 0.749729 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | f8e185b6dc4511adc19574da04b8b5e91a85308f74776a5111f3e7f819c4bf39 | 14,281 | [
-1
] |
14,282 | blending-test-8.lisp | asmaloney_ACT-R/extras/blending/blending-test-8.lisp | ;; Simple model to show blending in action.
;; Load the model and call run to see the
;; trace of two blended retrievals.
;;
;; This is the same model as blending-test-1
;; except this one uses the :do-not-generalize
;; request parameter in the first request now
;; for the size slot. Thus, instead of considering
;; all chunks which have the same slots as those
;; in the possible values only those specific values
;; are tested.
(clear-all)
(require-extra "blending")
(define-model test-blending
(sgp :seed (1 1) :v t :blt t :esc t :ans .25 :rt 4)
(chunk-type target key value size)
(chunk-type size (size-type t))
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 value 1 size large)
(b isa target key key-1 value 2 size x-large)
(c isa target key key-1 value 3 size tiny)
(d isa target key key-2 value 1 size nil)
(e isa target key key-2 value 3 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Provide the similarities between the sizes
;; because blending will use that even though
;; partial matching is not enabled.
(set-similarities (tiny small -.1)
(small medium -.1)
(medium large -.1)
(large x-large -.1)
(tiny medium -.3)
(small large -.3)
(medium x-large -.3)
(tiny large -.6)
(small x-large -.6)
(tiny x-large -.9))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
key key-1
; Do not allow the size slot be blended with
; blending method c as described in the readme
:do-not-generalize (size)
)
(p p2
=blending>
isa target
value =val
size =size
?blending>
state free
==>
!output! (blended value is =val and size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
key key-2)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk A matches blending request
Activation 2.5325232
Probability of recall 0.00497158
Chunk B matches blending request
Activation 3.763482
Probability of recall 0.16164705
Chunk C matches blending request
Activation 4.3433366
Probability of recall 0.8333814
Slots to be blended: (SIZE VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (LARGE X-LARGE TINY)
Magnitude values for those items: (LARGE X-LARGE TINY)
When all magnitudes are chunks and the slot is not generalized blending based on similarities to only those chunks
Comparing value LARGE
Chunk A with probability 0.00497158 slot value LARGE similarity: 0.0 cumulative result: 0.0
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.1 cumulative result: 0.0016164706
Chunk C with probability 0.8333814 slot value TINY similarity: -0.6 cumulative result: 0.3016338
Comparing value X-LARGE
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.1 cumulative result: 4.9715803e-5
Chunk B with probability 0.16164705 slot value X-LARGE similarity: 0.0 cumulative result: 4.9715803e-5
Chunk C with probability 0.8333814 slot value TINY similarity: -0.9 cumulative result: 0.6750886
Comparing value TINY
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.6 cumulative result: 0.0017897689
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.9 cumulative result: 0.13272387
Chunk C with probability 0.8333814 slot value TINY similarity: 0.0 cumulative result: 0.13272387
Final result: TINY
Finding blended value for slot: VALUE
Matched chunks' slots contain: (1 2 3)
Magnitude values for those items: (1 2 3)
With numeric magnitudes blending by weighted average
Chunk A with probability 0.00497158 times magnitude 1.0 = 0.00497158 cumulative result: 0.00497158
Chunk B with probability 0.16164705 times magnitude 2.0 = 0.3232941 cumulative result: 0.3282657
Chunk C with probability 0.8333814 times magnitude 3.0 = 2.5001442 cumulative result: 2.82841
Final result: 2.82841
This is the definition of the blended chunk:
(KEY KEY-1 SIZE TINY VALUE 2.82841)
Computing activation and latency for the blended chunk
Activation of chunk A is 2.5325232
Activation of chunk B is 3.763482
Activation of chunk C is 4.3433366
Activation for blended chunk is: 4.8876944
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.058 BLENDING BLENDING-COMPLETE
0.058 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.058 PROCEDURAL CONFLICT-RESOLUTION
0.108 PROCEDURAL PRODUCTION-FIRED P2
BLENDED VALUE IS 2.82841 AND SIZE IS TINY
0.108 PROCEDURAL CLEAR-BUFFER BLENDING
0.108 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk E matches blending request
Activation 3.2689652
Probability of recall 0.9031912
Chunk D matches blending request
Activation 2.4794111
Probability of recall 0.09680881
Slots to be blended: (SIZE VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL)
Magnitude values for those items: (SMALL)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.6 cumulative result: 0.32514885
Comparing value LARGE
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.3 cumulative result: 0.08128721
Comparing value MEDIUM
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.1 cumulative result: 0.009031912
Comparing value SMALL
Chunk E with probability 0.9031912 slot value SMALL similarity: 0.0 cumulative result: 0.0
Comparing value TINY
Chunk E with probability 0.9031912 slot value SMALL similarity: -0.1 cumulative result: 0.009031912
Final result: SMALL
Finding blended value for slot: VALUE
Matched chunks' slots contain: (3 1)
Magnitude values for those items: (3 1)
With numeric magnitudes blending by weighted average
Chunk E with probability 0.9031912 times magnitude 3.0 = 2.7095737 cumulative result: 2.7095737
Chunk D with probability 0.09680881 times magnitude 1.0 = 0.09680881 cumulative result: 2.8063827
Final result: 2.8063827
This is the definition of the blended chunk:
(KEY KEY-2 SIZE SMALL VALUE 2.8063827)
Computing activation and latency for the blended chunk
Activation of chunk E is 3.2689652
Activation of chunk D is 2.4794111
Activation for blended chunk is: 3.643316
Not above threshold so blending failed
0.108 PROCEDURAL CONFLICT-RESOLUTION
0.126 BLENDING BLENDING-FAILURE
0.126 PROCEDURAL CONFLICT-RESOLUTION
0.126 ------ Stopped because no events left to process
0.126
27
NIL
|#
| 8,242 | Common Lisp | .lisp | 191 | 38.591623 | 114 | 0.716365 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 638966d83877cfd2b26917ce4b2c00e85a476ed11a03c6d7a667fe705899d3e4 | 14,282 | [
-1
] |
14,283 | blending-test-3.lisp | asmaloney_ACT-R/extras/blending/blending-test-3.lisp | ;; Simple model to show blending in action.
;; Load the model and call run to see the
;; trace of two blended retrievals. The
;; second one will usually fail because
;; it will be below the retrieval threshold.
;;
;; This test does not use partial matching
;; and does the blending over the third case -
;; non-number and non-chunk values in the slots.
;; That requires a similarity hook function to
;; be defined as one would if using partial
;; matching to provide the similarities for those
;; non-chunk values.
(clear-all)
(require-extra "blending")
(defun string-similarities (s1 s2)
(when (and (stringp s1) (stringp s2))
(case (read-from-string s1)
(tiny
(case (read-from-string s2)
(tiny 0)
(small -.1)
(medium -.3)
(large -.6)
(x-large -.9)))
(small
(case (read-from-string s2)
(tiny -.1)
(small 0)
(medium -.1)
(large -.3)
(x-large -.6)))
(medium
(case (read-from-string s2)
(tiny -.3)
(small -.1)
(medium 0)
(large -.1)
(x-large -.3)))
(large
(case (read-from-string s2)
(tiny -.6)
(small -.3)
(medium -.1)
(large 0)
(x-large -.1)))
(x-large
(case (read-from-string s2)
(tiny -.9)
(small -.6)
(medium -.3)
(large -.1)
(x-large 0))))))
(define-model test-blending
(sgp :seed (1 1) :v t :blt t :esc t :ans .25 :rt 4 :sim-hook string-similarities)
(chunk-type target key size)
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 size "large")
(b isa target key key-1 size "x-large")
(c isa target key key-1 size "tiny")
(d isa target key key-2 size nil)
(e isa target key key-2 size "small"))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
key key-1)
(p p2
=blending>
isa target
size =size
?blending>
state free
==>
!output! (blended size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
key key-2)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk A matches blending request
Activation 2.5325232
Probability of recall 0.00497158
Chunk B matches blending request
Activation 3.763482
Probability of recall 0.16164705
Chunk C matches blending request
Activation 4.3433366
Probability of recall 0.8333814
Slots to be blended: (SIZE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: ("large" "x-large" "tiny")
Magnitude values for those items: ("large" "x-large" "tiny")
When not all magnitudes are numbers or chunks blending based on similarities using those unique values: ("large" "x-large" "tiny")
Comparing value "large"
Chunk A with probability 0.00497158 slot value "large" similarity: 0.0 cumulative result: 0.0
Chunk B with probability 0.16164705 slot value "x-large" similarity: -0.1 cumulative result: 0.0016164706
Chunk C with probability 0.8333814 slot value "tiny" similarity: -0.6 cumulative result: 0.3016338
Comparing value "x-large"
Chunk A with probability 0.00497158 slot value "large" similarity: -0.1 cumulative result: 4.9715803e-5
Chunk B with probability 0.16164705 slot value "x-large" similarity: 0.0 cumulative result: 4.9715803e-5
Chunk C with probability 0.8333814 slot value "tiny" similarity: -0.9 cumulative result: 0.6750886
Comparing value "tiny"
Chunk A with probability 0.00497158 slot value "large" similarity: -0.6 cumulative result: 0.0017897689
Chunk B with probability 0.16164705 slot value "x-large" similarity: -0.9 cumulative result: 0.13272387
Chunk C with probability 0.8333814 slot value "tiny" similarity: 0.0 cumulative result: 0.13272387
Final result: "tiny"
This is the definition of the blended chunk:
(KEY KEY-1 SIZE "tiny")
Computing activation and latency for the blended chunk
Activation of chunk A is 2.5325232
Activation of chunk B is 3.763482
Activation of chunk C is 4.3433366
Activation for blended chunk is: 4.8876944
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.058 BLENDING BLENDING-COMPLETE
0.058 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.058 PROCEDURAL CONFLICT-RESOLUTION
0.108 PROCEDURAL PRODUCTION-FIRED P2
BLENDED SIZE IS "tiny"
0.108 PROCEDURAL CLEAR-BUFFER BLENDING
0.108 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk E matches blending request
Activation 3.2689652
Probability of recall 0.9031912
Chunk D matches blending request
Activation 2.4794111
Probability of recall 0.09680881
Slots to be blended: (SIZE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: ("small")
Magnitude values for those items: ("small")
When not all magnitudes are numbers or chunks blending based on similarities using those unique values: ("small")
Only one possible value "small"
Final result: "small"
This is the definition of the blended chunk:
(KEY KEY-2 SIZE "small")
Computing activation and latency for the blended chunk
Activation of chunk E is 3.2689652
Activation of chunk D is 2.4794111
Activation for blended chunk is: 3.643316
Not above threshold so blending failed
0.108 PROCEDURAL CONFLICT-RESOLUTION
0.126 BLENDING BLENDING-FAILURE
0.126 PROCEDURAL CONFLICT-RESOLUTION
0.126 ------ Stopped because no events left to process
0.126
27
NIL
|#
| 6,856 | Common Lisp | .lisp | 181 | 32.966851 | 130 | 0.675102 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | cf7869a78e6756aa82050aa67e1fd630c0a62882be79c47a503a4b4ddb74b1ab | 14,283 | [
-1
] |
14,284 | blending-test-4.lisp | asmaloney_ACT-R/extras/blending/blending-test-4.lisp | ;; Simple model to show blending in action.
;; Load the model and call run to see the
;; trace of two blended retrievals. The
;; second one will usually fail because
;; it will be below the retrieval threshold.
;;
;; This example uses the magnitude to value and
;; value to magnitude functions for the
;; blending module to map the values in the
;; slots to numbers and then back.
;;
;; This model demonstrates a potential issue one
;; should be careful about: chunks which match
;; the blending request but don't have a value
;; for a slot which is blended do not get considered
;; for that slot. However the probabilities are
;; only calculated once over all the chunks which
;; matched the request. That means that if a blended
;; slot value is computed via the weighted average
;; it's possible that the weights will not total 1.0
;; because of missing values.
;;
;; To be safe, one probably wants to ensure that
;; only chunks which have values for all of the
;; important slots match the request.
(clear-all)
(require-extra "blending")
;; A simple linear mapping of the
;; size chunks onto numbers.
(defun map-chunks-to-numbers (value)
(case value
(tiny 1)
(small 2)
(medium 3)
(large 4)
(x-large 5)
(t ;assume medium for an empty slot
3)))
;; return the closest chunk to the
;; number based on the above mapping
(defun map-numbers-to-sizes (value chunk-type)
(declare (ignore chunk-type)) ;; don't need it for this example
(if (numberp value)
(cond ((< value 1.5)
'tiny)
((< value 2.5)
'small)
((< value 3.5)
'medium)
((< value 4.5)
'large)
(t 'x-large))))
(define-model test-blending
(sgp :seed (1 1) :v t :blt t :esc t :ans .25 :rt 4
:value->mag map-chunks-to-numbers
:mag->value map-numbers-to-sizes)
(chunk-type target key size)
(chunk-type size (size-type t))
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 size large)
(b isa target key key-1 size x-large)
(c isa target key key-1 size tiny)
(d isa target key key-2 size nil)
(e isa target key key-2 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
key key-1)
(p p2
=blending>
isa target
size =size
?blending>
state free
==>
!output! (blended size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
key key-2)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk A matches blending request
Activation 2.5325232
Probability of recall 0.00497158
Chunk B matches blending request
Activation 3.763482
Probability of recall 0.16164705
Chunk C matches blending request
Activation 4.3433366
Probability of recall 0.8333814
Slots to be blended: (SIZE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (LARGE X-LARGE TINY)
Magnitude values for those items: (4 5 1)
With numeric magnitudes blending by weighted average
Chunk A with probability 0.00497158 times magnitude 4.0 = 0.01988632 cumulative result: 0.01988632
Chunk B with probability 0.16164705 times magnitude 5.0 = 0.8082353 cumulative result: 0.8281216
Chunk C with probability 0.8333814 times magnitude 1.0 = 0.8333814 cumulative result: 1.6615031
Final result: 1.6615031 Converted to value: SMALL
This is the definition of the blended chunk:
(KEY KEY-1 SIZE SMALL)
Computing activation and latency for the blended chunk
Activation of chunk A is 2.5325232
Activation of chunk B is 3.763482
Activation of chunk C is 4.3433366
Activation for blended chunk is: 4.8876944
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.058 BLENDING BLENDING-COMPLETE
0.058 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.058 PROCEDURAL CONFLICT-RESOLUTION
0.108 PROCEDURAL PRODUCTION-FIRED P2
BLENDED SIZE IS SMALL
0.108 PROCEDURAL CLEAR-BUFFER BLENDING
0.108 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk E matches blending request
Activation 3.2689652
Probability of recall 0.9031912
Chunk D matches blending request
Activation 2.4794111
Probability of recall 0.09680881
Slots to be blended: (SIZE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (SMALL)
Magnitude values for those items: (2)
With numeric magnitudes blending by weighted average
Chunk E with probability 0.9031912 times magnitude 2.0 = 1.8063824 cumulative result: 1.8063824
Final result: 1.8063824 Converted to value: SMALL
This is the definition of the blended chunk:
(KEY KEY-2 SIZE SMALL)
Computing activation and latency for the blended chunk
Activation of chunk E is 3.2689652
Activation of chunk D is 2.4794111
Activation for blended chunk is: 3.643316
Not above threshold so blending failed
0.108 PROCEDURAL CONFLICT-RESOLUTION
0.126 BLENDING BLENDING-FAILURE
0.126 PROCEDURAL CONFLICT-RESOLUTION
0.126 ------ Stopped because no events left to process
0.126
27
NIL
|#
| 6,579 | Common Lisp | .lisp | 180 | 32.294444 | 99 | 0.695039 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 16748dbd188d4eb22800937da3b3cfcd611c95bad036496634fab0ce18c853cb | 14,284 | [
-1
] |
14,285 | blending-test-6.lisp | asmaloney_ACT-R/extras/blending/blending-test-6.lisp | ;; This model is essentially the same as blending-test-1
;; except now it uses the :ignore-slots request parameter
;; so that not all of the slots get a blended result.
(clear-all)
(require-extra "blending")
(define-model test-blending
(sgp :seed (1 1) :v t :blt t :esc t :ans .25 :rt 4)
(chunk-type target key value size)
(chunk-type size (size-type t))
;; some chunks which don't need to be in DM
(define-chunks
(key-1 isa chunk)
(key-2 isa chunk))
;; Here are the chunks for the blending test
(add-dm
;; A set of size chunks
(tiny isa size)
(small isa size)
(medium isa size)
(large isa size)
(x-large isa size)
;; A set of target chunks which will be
;; the items for the blended retrieval.
(a isa target key key-1 value 1 size large)
(b isa target key key-1 value 2 size x-large)
(c isa target key key-1 value 3 size tiny)
(d isa target key key-2 value 1 size nil)
(e isa target key key-2 value 3 size small))
;; Set some arbitrary base-level activations for the target
;; chunks to provide some systematic variability in the values.
(set-base-levels (a 4 -10) (b 4 -10) (c 5 -10) (d 2 -10) (e 1 -10))
;; Provide the similarities between the sizes
;; because blending will use that even though
;; partial matching is not enabled.
(set-similarities (tiny small -.1)
(small medium -.1)
(medium large -.1)
(large x-large -.1)
(tiny medium -.3)
(small large -.3)
(medium x-large -.3)
(tiny large -.6)
(small x-large -.6)
(tiny x-large -.9))
;; Very simple model
;; Make a blending request for a target chunk
;; with key value key-1 and if such a chunk
;; is found make a blending request for a
;; target chunk with a key value of key-2
(p p1
?blending>
state free
buffer empty
error nil
==>
+blending>
isa target
:ignore-slots (value)
key key-1)
(p p2
=blending>
isa target
size =size
?blending>
state free
==>
!output! (blended size is =size)
; Overwrite the blended chunk to erase it and keep it
; from being added to dm. Not necessary, but keeps the
; examples simpler.
@blending>
+blending>
isa target
:ignore-slots (value size)
key key-2)
)
#| Here's a trace of the run
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL CLEAR-BUFFER BLENDING
0.050 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk A matches blending request
Activation 2.5325232
Probability of recall 0.00497158
Chunk B matches blending request
Activation 3.763482
Probability of recall 0.16164705
Chunk C matches blending request
Activation 4.3433366
Probability of recall 0.8333814
Slots to be blended: (SIZE)
Slots being explicitly ignored: (VALUE)
Finding blended value for slot: SIZE
Matched chunks' slots contain: (LARGE X-LARGE TINY)
Magnitude values for those items: (LARGE X-LARGE TINY)
When all magnitudes are chunks blending based on similarities to all related chunks
Intersection of slots for values is: (SIZE-TYPE)
Comparing value X-LARGE
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.1 cumulative result: 4.9715803e-5
Chunk B with probability 0.16164705 slot value X-LARGE similarity: 0.0 cumulative result: 4.9715803e-5
Chunk C with probability 0.8333814 slot value TINY similarity: -0.9 cumulative result: 0.6750886
Comparing value LARGE
Chunk A with probability 0.00497158 slot value LARGE similarity: 0.0 cumulative result: 0.0
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.1 cumulative result: 0.0016164706
Chunk C with probability 0.8333814 slot value TINY similarity: -0.6 cumulative result: 0.3016338
Comparing value MEDIUM
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.1 cumulative result: 4.9715803e-5
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.3 cumulative result: 0.014597951
Chunk C with probability 0.8333814 slot value TINY similarity: -0.3 cumulative result: 0.089602284
Comparing value SMALL
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.3 cumulative result: 4.4744223e-4
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.6 cumulative result: 0.058640383
Chunk C with probability 0.8333814 slot value TINY similarity: -0.1 cumulative result: 0.0669742
Comparing value TINY
Chunk A with probability 0.00497158 slot value LARGE similarity: -0.6 cumulative result: 0.0017897689
Chunk B with probability 0.16164705 slot value X-LARGE similarity: -0.9 cumulative result: 0.13272387
Chunk C with probability 0.8333814 slot value TINY similarity: 0.0 cumulative result: 0.13272387
Final result: SMALL
This is the definition of the blended chunk:
(KEY KEY-1 SIZE SMALL)
Computing activation and latency for the blended chunk
Activation of chunk A is 2.5325232
Activation of chunk B is 3.763482
Activation of chunk C is 4.3433366
Activation for blended chunk is: 4.8876944
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.058 BLENDING BLENDING-COMPLETE
0.058 BLENDING SET-BUFFER-CHUNK-FROM-SPEC BLENDING
0.058 PROCEDURAL CONFLICT-RESOLUTION
0.108 PROCEDURAL PRODUCTION-FIRED P2
BLENDED SIZE IS SMALL
0.108 PROCEDURAL CLEAR-BUFFER BLENDING
0.108 BLENDING START-BLENDING
Blending request for chunks with slots (KEY)
Blending temperature defaults to (* (sqrt 2) :ans): 0.35355338
Chunk E matches blending request
Activation 3.2689652
Probability of recall 0.9031912
Chunk D matches blending request
Activation 2.4794111
Probability of recall 0.09680881
Slots to be blended: NIL
Slots being explicitly ignored: (VALUE SIZE)
This is the definition of the blended chunk:
(KEY KEY-2)
Computing activation and latency for the blended chunk
Activation of chunk E is 3.2689652
Activation of chunk D is 2.4794111
Activation for blended chunk is: 3.643316
Not above threshold so blending failed
0.108 PROCEDURAL CONFLICT-RESOLUTION
0.126 BLENDING BLENDING-FAILURE
0.126 PROCEDURAL CONFLICT-RESOLUTION
0.126 ------ Stopped because no events left to process
0.126
27
NIL
|#
| 6,791 | Common Lisp | .lisp | 160 | 37.3625 | 105 | 0.700993 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 9f593adc281cd124945a4e4eb645dd7c116bea4939e5f1b4a26e651ff86d8ed1 | 14,285 | [
-1
] |
14,286 | extended-motor-actions.lisp | asmaloney_ACT-R/extras/extended-motor-actions/extended-motor-actions.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2016 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : extended-motor-actions.lisp
;;; Version : 1.0
;;;
;;; Description : A file to load motor-extension.lisp automatically with require-extra.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2016.03.14 Dan
;;; : * Creation.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(when (requiring-extra)
(compile-and-load (translate-logical-pathname "ACT-R:extras;extended-motor-actions;motor-extension.lisp")))
(provide "extended-motor-actions")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 1,981 | Common Lisp | .lisp | 49 | 39.040816 | 109 | 0.545691 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | dcdaa9ee958cbb341de7c45d746c1f12b81358b7185f3287f5bcc71aa6682377 | 14,286 | [
321958
] |
14,287 | motor-extension.lisp | asmaloney_ACT-R/extras/extended-motor-actions/motor-extension.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2014 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : motor-extension.lisp
;;; Version : 6.1
;;;
;;; Description : Collection of extensions for the motor module which include:
;;; : separate processor and/or execution stages for each hand, buffers
;;; : to track the separate hand usage, actions for holding keys,
;;; : and "press-key like" actions for holding keys and for hitting
;;; : a key without recoiling to the home row.
;;;
;;; Bugs :
;;;
;;; To do : [ ] Should a point-finger action send a notification?
;;; : Currently the normal point-hand actions don't so not
;;; : doing that here either, but if that changes need to make
;;; : the change here as well.
;;; :
;;;
;;; ----- History -----
;;; 2014.04.24 Dan [1.0a1]
;;; : * Initial creation. Combining the separate extensions that
;;; : were used for modeling Space Fortress, cleaning them up so
;;; : that the "regular" motor actions work correctly with them,
;;; : and adding the new "typing" actions.
;;; 2014.05.16 Dan [1.1a1]
;;; : * This version is for ACT-R 6.1.
;;; : * Fixed all the calls to check-specs to pass the name.
;;; : * Commented out the handle-extended-style method and use
;;; : handle-style-request for the actions instead.
;;; : * Changed the verify-single-explicit-value calls because of
;;; : the different way it works now.
;;; 2014.06.16 Dan [2.0a1]
;;; : * Fix prepare-movement for typeless chunk mechanism so that
;;; : setting of the hands' last command values still works.
;;; 2015.06.05 Dan
;;; : * Change all the scheduling to ms.
;;; 2015.08.06 Dan [2.0a2]
;;; : * Adding a release-all-fingers action which is special in that
;;; : it doesn't jam the module because it will reschedule itself
;;; : if the preparation is busy repeatedly until it becomes free
;;; : and then after the init cost it will call the release action
;;; : for each finger which is down.
;;; 2015.08.07 Dan
;;; : * Cleaning up the distinction between up/down and busy/free
;;; : for a finger -- those were conflated before because it
;;; : said set-finger-up but what it really meant was set finger
;;; : free. There wasn't a real indication of being down and one
;;; : could mistake a busy finger for down.
;;; : Since busy/free is measured at the "hand" level the fingers
;;; : don't need to really indicate busy/free, just up or down,
;;; : but it may be necessary to detect intermediate states at the
;;; : finger level i.e. that a finger is making an action even
;;; : though the key isn't up or down yet. So actually tracking
;;; : both separately for the fingers. A query for a finger of
;;; : busy means that it's between the initiation and finish
;;; : stages of an action (like the hand would indicate) whereas
;;; : a query of up or down indicates where the finger is with
;;; : respect to the key it's over.
;;; : * Actually implementing device-handle-keyrelease and device-
;;; : handle-click-release methods instead of only calling the
;;; : event handler functions directly so that a new device can
;;; : receive that info appropriately.
;;; : * The replacement motor module now has a slot for the extension
;;; : module.
;;; : * Instead of a style directly scheduling the output-key and
;;; : release-key methods it needs to call the key-up and key-down
;;; : methods which will then call output-key and release-key.
;;; 2015.08.10 Dan
;;; : * Fixing bugs with the previous updates.
;;; 2015.08.13 Dan
;;; : * The device-handle-click-release method only has one parameter
;;; : now, the device, like device-handle-click.
;;; : * The finger up/down queries are now available.
;;; : * Changed rand-time calls to randomize-time.
;;; 2015.08.19 Dan
;;; : * Only generate the press or release if the finger isn't in
;;; : that state i.e. can't have two presses without a release
;;; : between them.
;;; 2015.09.23 Dan [3.0]
;;; : * Make the necessary updates to be compatible with the new
;;; : request completion changes to the movement styles and
;;; : change the new action functions to work with those updates.
;;; 2015.09.25 Dan
;;; : * Release-all-fingers wasn't recording the request for completion.
;;; 2018.02.19 Dan [3.1]
;;; : * Delay checking that the finger is down for the release actions
;;; : until execution time because it could prepare it while the
;;; : finger was still executing the down stroke.
;;; 2018.10.09 Dan [4.0]
;;; : * Updating this for 7.x. Lots of changes necessary.
;;; : * Adding the delayed-punch extension in as well.
;;; 2018.10.11 Dan [4.1]
;;; : * Added another parameter: :cursor-drag-delay which slows down
;;; : cursor movement when a finger on the same hand is also held
;;; : down. Defaults to nil (off), can be set to t (.8) or a #
;;; : which is added to the control order for the Fitts coefficient
;;; : calculation. The .8 value seems to be a reasonable value
;;; : for fitting data from the paper below with other defaults:
;;; : I. Scott MacKenzie, Abigail Sellen, and William A. S. Buxton. 1991.
;;; : A comparison of input devices in element pointing and dragging tasks.
;;; : In Proceedings of the SIGCHI Conference on Human Factors in
;;; : Computing Systems (CHI '91), Scott P. Robertson, Gary M. Olson,
;;; : and Judith S. Olson (Eds.). ACM, New York, NY, USA, 161-166.
;;; : DOI: http://dx.doi.org/10.1145/108844.108868
;;; 2018.10.12 Dan
;;; : * Fixed the status functions since they need to return a string
;;; : now.
;;; : * Fixed the cursor-ply class because it needs a cursor slot.
;;; : * Changed all the 'old' style methods to be on motor-mod class
;;; : instead of the new class to avoid oddities in finding the
;;; : right method.
;;; : * It's much worse than that... Basically, I can't fall back to
;;; : a general dual queue-output-events because the 'old' specific
;;; : queue-output-events get in the way. So I have to define
;;; : every method which was defined for the old version here too
;;; : (or go through some ugly remove-method hoops to get rid of
;;; : what I don't want, or start from scratch and ignore the
;;; : movement-style class at the top, or probably some other
;;; : ugly thing I haven't considered).
;;; 2018.10.15 Dan
;;; : * Fixed an issue with the mouse drag timing (it was checking
;;; : for busy instead of down).
;;; 2018.10.16 Dan
;;; : * All-home needs to just move the fingers because if it uses
;;; : point-finger it will jam if there're multiple fingers to
;;; : move, and it has to do it at the finish time so that any
;;; : fingers which are down are released first.
;;; : * Fixed a bug in queue-output events for a peck-recoil.
;;; : * The style name for all peck and peck-recoil type actions is
;;; : just peck (as is true for the normal actions).
;;; : * Renamed key-up and key-down set-finger-up and set-finger-down.
;;; 2018.10.17 Dan
;;; : * Adjust how I handle the :peck-strike-distance calculation
;;; : to not assume linear motion and fix a bug in the calculation.
;;; : Now it uses the minimum jerk trajectory profile to find the
;;; : appropriate time to get to the striking distance, and it's
;;; : using a simple search using minjerk-dist to find that time
;;; : since it's a 5th order polynomial so there's no closed form
;;; : solution for time and a "fancy" solution is going to be at
;;; : least as costly as a few calls (typically all that's needed
;;; : to get close enough: +/- .01 key width).
;;; 2019.08.08 Dan
;;; : * Fixed a typo in a parameter doc string.
;;; 2020.01.10 Dan [4.2]
;;; : * Removed the #' and lambdas from param valid functions since
;;; : that's not allowed in the general system now.
;;; 2020.04.06 Dan [5.0]
;;; : * Updated with the changes necessary to track the separation
;;; : of current position and next starting position as well as
;;; : add the request time to the standard events as the normal
;;; : motor module does now.
;;; : * Changed point-finger to use an exec-time that matches when
;;; : the finger is "at" the key (init + fitts time). That means
;;; : there's an extra chance for a conflict-resolution at that
;;; : time relative to before, which seems reasonable -- when the
;;; : finger gets there maybe something else could happen.
;;; : * Changed all-fingers-to-home to both mark all the fingers as
;;; : busy during the action and to have a time that's the max of
;;; : 200ms and the times for each hand to do a hand-ply back to
;;; : home position.
;;; : * The release on a punch doesn't include the extra burst cost
;;; : now to be consistent with the timing of peck and peck-recoil
;;; : actions (a 90ms down time was too long).
;;; : * The timing of the release-all-fingers event now matches
;;; : when the release happens instead of a burst time later.
;;; : * Go back to a single exec queue which now is searched for
;;; : an available action, possibly for each hand, since the two
;;; : queue approach had issues with skipping over a both when
;;; : one of the hands was free.
;;; 2020.04.20 Dan
;;; : * Updated to work with the new location information in the
;;; : keyboard.
;;; 2020.05.21 Dan [5.1]
;;; : * Added a new parameter, :relay-hand-requests which if set to
;;; : t will pass requests to manual-left and manual-right on to
;;; : the manual buffer. The requests must still include a hand
;;; : feature when required because they can't just add one in
;;; : since it isn't possible to know when that is required in
;;; : advance. If a hand feature is included in the request, it
;;; : must match the buffer to be relayed. Enabling this switch
;;; : will affect the buffer trace information because the request
;;; : for an action will only be recorded for the specific buffer
;;; : which makes the request and not the buffer which corresponds
;;; : to the hand that is used (for example a press-key request
;;; : which only generates the hand after preparing the features
;;; : could be attributed to the wrong buffer).
;;; 2020.06.24 Dan [6.0]
;;; : * Updated the create-motor-module function because now it must
;;; : also specify the types.
;;; 2020.10.12 Dan [6.1]
;;; : * Adjust the actions that are scheduling the prepare-movement
;;; : so it displays in the low detail trace. Prior to the fix
;;; : for preparation free they were all just calling it and had
;;; : the event shown automatically in the low detail trace.
;;; 2021.01.08 Dan
;;; : * Didn't update the module version with the last change.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Combining a lot of updates to the motor module together in one place which
;;; should be useable as a replacement for the default module without breaking
;;; any existing models which use motor actions.
;;;
;;; The big changes with the update:
;;;
;;; The model can now generate actions for pressing and releasing keys which can
;;; be detected by the modeler. The actions from the existing module (punch,
;;; peck, peck-recall, and press-key) all now result in both a press and release
;;; of the key/button.
;;;
;;; With the addition of keys being able to be held down the previous motor module
;;; actions (the styles punch, peck, peck-recoil, and point-hand and all the
;;; higher-level actions which use them press-key, click-mouse, hand-to-home,
;;; hand-to-mouse, and point-hand-at-key) have been modified so that if the finger(s)
;;; used to perform the action is currently holding a key down there's an extra
;;; burst-time cost to execute the release of that key before performing the
;;; specified action.
;;;
;;; The trace of the motor actions for preparing, initiating, and finishing an
;;; action now indicate which action and hand it corresponds to since there may
;;; be parallel actions on going. (The old module also could have some overlapping
;;; actions which occasionally lead to confusion in the trace, but it didn't
;;; happen very often).
;;;
;;; The new motor module now has the option of using separate execution and/or
;;; processor stages for the two hands which allows motor actions on different
;;; hands to potentially operate in parallel. There is still only one preparation
;;; stage however. The default operation of the new module is for one execution
;;; stages and one processor stage, like the standard motor module, but that can
;;; be changed with parameters described below.
;;;
;;; There are two new sets of motor actions which can be used. The first set
;;; provides separate low-level actions for holding and releasing keys. The other
;;; set is more high-level actions like press-key which perform touch typing
;;; operations with holding keys and without always recoiling to the home row.
;;; Details on the new actions are found below.
;;;
;;; There is a new module created, named motor-extension, which adds two new
;;; buffers, manual-left and manual-right. These can be used for tracking the
;;; operation of the model's hands separately and also allows for querying
;;; whether individual fingers are currently busy i.e. holding down a key.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; release-key (model key)
;;;
;;; the signal that can be monitored to detect the release of a key just like
;;; output-key notes the pressing. Generated by the new default keyboard device
;;; included with this extension.
;;;
;;; release-mouse (model position finger)
;;;
;;; The signal that can be monitored to detect the release of a button on
;;; the mouse like click-mouse notes the press. Generated by the new default
;;; mouse cursor device included with this extension.
;;;
;;;
;;; New model parameters:
;;;
;;; :key-closure-time (default value .01)
;;;
;;; The time in seconds between when a key is contacted (the corresponding movement
;;; action has started pressing it) and when it registers as being hit. By default
;;; only used for the timing of punch actions, but see the :peck-strike-distance
;;; parameter below for how it may affect peck/peck-recoil actions as well. Note,
;;; this value has always existed within the device interface, but was not previously
;;; made directly available to the modeler.
;;;
;;; :key-release-time (default value .04)
;;;
;;; The time in seconds between when the action which is releasing a key is started
;;; and when that key actually registers as being released. Used in the timing of
;;; all the actions which include a releasing of a key. The assumption is that there
;;; is some distance over which the finger must be moved before the key stops being
;;; pressed. All of the release actions are based on a burst-time cost, thus this
;;; parameter should be set to a value no greater than the value of the :MOTOR-BURST-TIME
;;; parameter.
;;;
;;; NOTE: Those two parameters should really be modeled as a distance instead of a time
;;; cost, but since the motor movement code isn't modeled at that fine grain of detail
;;; (exact finger positions in 3-space) a simple cost assumption is used.
;;;
;;; :dual-processor-stages (default value nil)
;;;
;;; A boolean indicating whether the motor module should use separate processor
;;; stages for each hand.
;;;
;;; :dual-execution-stages (default value nil)
;;;
;;; A boolean indicating whether the motor module should use separate execution
;;; stages for each hand.
;;;
;;; :peck-strike-distance (default 0.0)
;;;
;;; The distance from the center of a key at which a peck action is considered
;;; to make contact with the key and start depressing it. The value can be
;;; from 0 to .5 (the width of a key is 1.0 and movement is computed from
;;; center of key to center of key thus the finger movement crosses at least
;;; half of the target key when striking it). This affects when the output-key
;;; action occurs. The default motor module assumes that the action occurs
;;; after the entire movement completes and ignores the key closure time which
;;; is what will still happen if the value is set to nil.
;;;
;;; If it is set to a non-nil value then the peck and peck-recoil actions
;;; will generate the output-key action at the time: ct + t(d - psd) where
;;; ct is the key-closure-time, t(x) is the time along a minimum jerk velocity
;;; profile for the whole movement at which the distance is x, d is the
;;; length of the whole movement and psd is the value of :peck-strike-distance.
;;;
;;; :default-punch-delay (.075s default)
;;;
;;; This is the delay time for a delayed-punch action when the model doesn't
;;; specify a delay.
;;;
;;; :fast-punch-delay (.05s default)
;;;
;;; This is the delay time for a delayed-punch action when the model specifies
;;; a delay of fast.
;;;
;;; :slow-punch-delay (.1s default)
;;;
;;; This is the delay time for a delayed-punch action when the model specifies
;;; a delay of slow.
;;;
;;;
;;; :cursor-drag-delay (nil default)
;;;
;;; Indicates whether to slow down cursor drag actions, and if so by how much.
;;; If set to t or a number then that number is added to the control order
;;; value of the cursor before calculating the time with Fitts' Law. A value
;;; of t sets it to .8 which provides a reasonable match to data from this paper:
;;;
;;; I. Scott MacKenzie, Abigail Sellen, and William A. S. Buxton. 1991.
;;; A comparison of input devices in element pointing and dragging tasks.
;;; In Proceedings of the SIGCHI Conference on Human Factors in
;;; Computing Systems (CHI '91), Scott P. Robertson, Gary M. Olson,
;;; and Judith S. Olson (Eds.). ACM, New York, NY, USA, 161-166.
;;; DOI: http://dx.doi.org/10.1145/108844.108868
;;;
;;; New Buffers for tracking hands:
;;;
;;; manual-left and manual-right
;;;
;;; Each buffer allows for the same queries as the manual buffer except for
;;; the preparation query which it does not track. The processor and execution
;;; queries of these buffers are busy if the corresponding hand is performing an
;;; action (or if either hand is when there aren't separate stages). The state
;;; is busy if there is an action being prepared or if the processor or execution
;;; for this hand is busy.
;;; Each also adds additional queries for the fingers on that hand. A finger
;;; query of busy is true if the finger is currently involved in an action which
;;; is occurring (actions which affect the whole hand do not involve the individual
;;; fingers) otherwise busy is false and free is true.
;;; A query of the finger for up will be true if the finger is not currently holding
;;; down a key and false if it is not.
;;; A query of the finger for down will be true if the finger is currently holding
;;; down a key and false if it is not.
;;; Down and up are mutually exclusive, eventhough there is potentially a non-zero
;;; time period during which the key and finger is transitioning from up to down or
;;; vice-versa the state changes at the same time as the corresponding output method
;;; gets called i.e. at the "real" make/break point of the press.
;;;
;;; Here is the output of the buffer-status call for the manual-left buffer for
;;; reference:
;;;
;;; MANUAL-LEFT:
;;; buffer empty : T
;;; buffer full : NIL
;;; buffer failure : NIL
;;; buffer requested : NIL
;;; buffer unrequested : NIL
;;; state free : T
;;; state busy : NIL
;;; state error : NIL
;;; processor free : T
;;; processor busy : NIL
;;; execution free : T
;;; execution busy : NIL
;;; last-command : ALL-HOME
;;; index free : T
;;; index down : NIL
;;; middle free : T
;;; middle down : NIL
;;; ring free : T
;;; ring down : NIL
;;; pinkie free : T
;;; pinkie down : NIL
;;; thumb free : T
;;; thumb down : NIL
;;;
;;;
;;; Neither buffer does anything with requests which it receives nor are there any
;;; chunks placed into either one.
;;;
;;;
;;;
;;; New request actions for the manual buffer.
;;;
;;; Here are low-level actions for directly manipulating the fingers:
;;;
;;; cmd hold-punch
;;; hand [left | right]
;;; finger [index | middle | ring | pinkie | thumb]
;;;
;;; Press and hold down the indicated finger. If the finger
;;; is already being held release it and press down again.
;;;
;;;
;;; cmd hold-peck
;;; hand [left | right]
;;; finger [index | middle | ring | pinkie | thumb]
;;; r distance
;;; theta direction
;;;
;;; Move the finger based on the distance and direction and hold it down
;;; at that location. If the finger is currently being held release it
;;; before performing this movement.
;;;
;;;
;;; cmd release
;;; hand [left | right]
;;; finger [index | middle | ring | pinkie | thumb]
;;;
;;; Stop holding down the indicated finger and leave it where it
;;; currently is. If the finger is not being held down do nothing and
;;; output a warning.
;;;
;;;
;;; cmd release-recoil
;;; hand [left | right]
;;; finger [index | middle | ring | pinkie | thumb]
;;; r distance
;;; theta direction
;;;
;;; Stop holding down the indicated finger and then move it based on the
;;; distance and direction given without performing a press when it
;;; completes the movement. If the finger is not being held down do nothing and
;;; output a warning.
;;;
;;; cmd delayed-punch
;;; hand [ left | right ]
;;; finger [ index | middle | ring | pinkie | thumb ]
;;; {delay [ fast | slow | # ] }
;;;
;;; Press down and then release the indicated finger in its current
;;; location. The release will occur delay seconds after the press
;;; if delay is provided as a number. If delay is not provided then
;;; the default delay time is used. If delay is either fast or slow,
;;; then the value is taken from the corresponding parameter. If
;;; :randomize-time is enabled then the delay will be randomized
;;; regardless of how it was indicated. If the finger is currently being
;;; held release it before performing this movement.
;;;
;;; cmd point-finger
;;; hand [left | right]
;;; finger [index | middle | ring | pinkie | thumb]
;;; r distance
;;; theta direction
;;;
;;; Move the finger based on the distance and direction without performing a
;;; press at that location. If the finger is currently being held down release
;;; it before performing this movement.
;;;
;;;
;;; Here are the new high-level actions for the updated keyboard and mouse
;;; devices which generate the corresponding low-level movements as necessary.
;;;
;;;
;;; isa type-key
;;; key key
;;;
;;; Move the appropriate finger to the key and press and release it. The
;;; finger is moved from where it currently is (unlike press-key which assumes
;;; it's on the home position) and returns to where it was after striking the key
;;; (which may not be the home row position). If the finger is currently being
;;; held release it before performing this movement.
;;;
;;;
;;; isa hit-key
;;; key key
;;;
;;; Move the appropriate finger to the key and press and release it. The
;;; finger is moved from where it currently is (unlike press-key which assumes
;;; it's on the home position) and stays over the key which is hit. If the finger
;;; is currently being held release it before performing this movement.
;;;
;;;
;;; isa hold-key
;;; key key
;;;
;;; Move the appropriate finger to the key and press it keeping it held down. The
;;; finger is moved from where it currently is (unlike press-key which assumes
;;; it's on the home position). If the finger is currently being held release it
;;; before performing this movement.
;;;
;;;
;;; isa release-key
;;; key key
;;;
;;; If the appropriate finger for that key is currently holding it down release it
;;; and leave the finger at that position. If the finger is not holding down that
;;; key print a warning and do nothing.
;;;
;;;
;;; isa release-key-to-home
;;; key key
;;;
;;; If the appropriate finger for that key is currently holding it down release it
;;; and move the finger back to its home position without striking the corresponding
;;; home key. If the finger is not holding down that key print a warning and do nothing.
;;;
;;;
;;; isa move-to-key
;;; key key
;;;
;;; Move the appropriate finger to that key without pressing it. The finger is moved
;;; from where it currently is (unlike press-key which assumes it's on the home position).
;;; If the finger is currently being held release it before performing this movement.
;;;
;;; isa move-finger-to-home
;;; hand [left | right]
;;; finger [index | middle | ring | pinkie | thumb]
;;;
;;; Move the specified finger to its home position without pressing it. If the finger
;;; is currently holding a key down release it before moving. If the finger is already
;;; at the home position do nothing and print a warning.
;;;
;;;
;;; isa all-fingers-to-home
;;; {hand [left | right]}
;;;
;;; Move all fingers on the specified hand, or both hands if no hand specified,
;;; to their home positions. Like move-finger-to-home any finger which is holding
;;; a key will be released first. If all the fingers are on the home positions
;;; do nothing and print a warning. This action has a fixed cost of 200ms. It
;;; does not move the hand(s) only the fingers.
;;;
;;;
;;; isa hold-mouse
;;;
;;; Execute a hold-punch with the right index finger to depress the primary mouse button.
;;; If the hand is not located on the mouse print a warning and do nothing.
;;;
;;;
;;; isa release-mouse
;;;
;;; Release the right index finger to release the primary mouse button. If the
;;; finger is not holding the button down or the hand is not located on the
;;; mouse do nothing and print a warning.
;;;
;;; isa release-all-fingers
;;;
;;; Causes all fingers which are currently being held down to release. The
;;; action doesn't jam and will wait until preparation is free to start the
;;; action. After the init time passes all fingers which are held will be
;;; released after the key-release-time and then an additional burst cost will
;;; be applied before it is finished.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Define a new keyboard and make it the default. This keyboard extends the
;;; available notifications to handle the releases and generates a release-key
;;; signal.
(defclass keyboard-with-release (virtual-keyboard)
nil)
(set-default-keyboard 'keyboard-with-release)
(defmethod other-notifications ((k keyboard-with-release) device features)
(let ((m (second (find 'model features :key 'first)))
(l (second (find 'loc features :key 'first)))
(s (second (find 'style features :key 'first))))
(if (and m l s (find s '(release)))
(aif (loc->key k l)
(with-model-eval m
(schedule-event-now "release-key" :params (list m it) :output t :module 'keyboard :maintenance t))
(print-warning "Keyboard device did not get signaled with a valid keyboard location for release action: ~s" features))
(print-warning "keyboard device can not process notification from device ~s with features ~s." device features))))
(add-act-r-command "release-key" nil "Command called when a key on the virtual keyboard is released by the model which can be monitored. It is passed 2 parameters: model-name and key-name. Should not be called directly.")
;;; Define a new mouse cursor and make it the default.
(defclass mouse-with-release (mouse)
nil)
(set-default-mouse 'mouse-with-release)
(defmethod other-notifications ((mouse mouse-with-release) device features)
(let ((m (second (find 'model features :key 'first)))
(s (second (find 'style features :key 'first)))
(h (second (find 'hand features :key 'first)))
(l (second (or (find 'loc features :key 'first)
(find 'new-loc features :key 'first)))))
(if (and m s h l (find s '(release))) ;; the only valid notification that should get here
(let (mx my xyz)
(bt:with-lock-held ((cursor-lock mouse))
(setf mx (px (cursor-pos mouse))
my (py (cursor-pos mouse))
xyz (cursor-loc mouse)))
(let* ((x (px l)) (y (py l))
(direction (if (eq h 'left) -1 1))
(f (cond ((and (= x mx) (= y my))
'index)
((and (= x (+ mx direction)) (= y my))
'middle)
((and (= x (+ mx (* direction 2))) (= y my))
'ring)
((and (= x (+ mx (* direction 3))) (= y my))
'pinkie)
((and (= x (- mx direction)) (= y (+ my 2)))
'thumb)
(t
(print-warning "Invalid mouse release finger position ~s." l)))))
(when f
(with-model-eval m
(schedule-event-now "release-mouse" :params (list m xyz f) :maintenance t :module 'mouse)))))
(print-warning "mouse device can not process notification from device ~s with features ~s." device features))))
(add-act-r-command "release-mouse" nil "Command called when a button on the virtual mouse is released by the model which can be monitored. It is passed 3 parameters: model-name mouse-position finger. Should not be called directly.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Code to implement a replacement for the standard motor module
;;; which tracks the processor and execution stages separately for
;;; left and right hand actions. There is still only one preparation
;;; stage for the whole module.
;;;
;;; There isn't an easy way to "extend" the default module without
;;; replacing it since this changes some fundamental operations which
;;; can't just be provided through some new hooks into the default
;;; module.
;;;
;;; Instead of undefining and creating a new one however, this is
;;; going to be based on how it's actually defined (which means that
;;; changes to the module will still likely require changes here too).
;;; Do this by subclassing the motor-module class, redefine the creation
;;; function for the motor module to instantiate this class instead,
;;; and then define the new and updated methods on that new class.
;;;
;;; The only functional difference is that now the proc-s and exec-s slots
;;; hold a list of two items (left and right) respectively instead of just one
;;; and actions for the exec-queue must have a hand specified (either left,
;;; right, or both).
;;;
;;; Also adding slots for holding the new parameters that are available
;;; for configuring the operation and adjusting the timing of the
;;; keypress actions as well as for holding the instance of the companion
;;; module for tracking the hands for convenience.
(defclass dual-execution-motor-module (motor-module)
((key-closure-time :accessor key-closure-time)
(key-release-time :accessor key-release-time)
(two-exec :accessor two-exec)
(two-proc :accessor two-proc)
(peck-strike :accessor peck-strike :initform nil)
(extension :accessor extension)
(d-punch-default :accessor d-punch-default)
(d-punch-fast :accessor d-punch-fast)
(d-punch-slow :accessor d-punch-slow)
(drag-delay :accessor drag-delay)
(relay-hand-requests :accessor relay-hand-requests))
(:default-initargs
:version-string "6.1-dual"))
;;; Redefine the creation function for the motor module to create the new class.
(defun create-motor-module (model-name)
(declare (ignore model-name))
(chunk-type motor-command (cmd "motor action"))
(chunk-type (prepare (:include motor-command)) (cmd prepare) style hand finger r theta)
(unless (chunk-p prepare)
(define-chunks (prepare isa prepare)))
(dolist (c '(left right index middle ring pinkie thumb))
(unless (chunk-p-fct c)
(define-chunks-fct (list (list c 'name c)))))
(let ((instance (make-instance 'dual-execution-motor-module)))
;; Define the chunk-types for the specified extensions
;; Note this means that for new extensions to be applied the
;; model must be redefined/reloaded not just reset
(maphash (lambda (name value)
(let ((type (chunk-type-fct (car value))))
(if type
(unless (chunk-p-fct name)
(define-chunks-fct (list (list name 'isa name))))
(print-warning "Failed to extend motor capabilities with chunk-type definition: ~s" (car value)))))
(bt:with-lock-held ((requests-table-lock instance)) (new-requests-table instance)))
instance))
;;; Set necessary slots to lists after the regular methods happen
(defmethod clear :after ((module dual-execution-motor-module))
(bt:with-recursive-lock-held ((state-lock module))
(setf (exec-queue module) nil)))
(defmethod reset-pm-module :after ((module dual-execution-motor-module))
(bt:with-recursive-lock-held ((state-lock module))
(setf (proc-s module) (list 'free 'free))
(setf (exec-s module) (list 'free 'free))
(setf (exec-queue module) nil))
;; store it for convenience in the style methods
;; don't need to lock protect it since it's internal,
;; only set here, and constant
(setf (extension module) (get-module motor-extension)))
;;; When changing state consider which hand the action is using
(defmethod change-state ((module dual-execution-motor-module) &key proc exec prep last)
(bt:with-recursive-lock-held ((state-lock module))
(bt:with-recursive-lock-held ((param-lock module))
(when proc
(if (listp proc)
(cond ((or (null (two-proc module)) (eq (car proc) 'both))
(setf (first (proc-s module)) (second proc))
(setf (second (proc-s module)) (second proc)))
((eq (car proc) 'left)
(setf (first (proc-s module)) (second proc)))
((eq (car proc) 'right)
(setf (second (proc-s module)) (second proc)))
(t
(print-warning "Invalid proc setting for the dual execution motor module: ~S" proc)))
(print-warning "Invalid proc setting for the dual execution motor module: ~S" proc)))
(when exec
(if (listp exec)
(cond ((or (null (two-exec module)) (eq (car exec) 'both))
(setf (first (exec-s module)) (second exec))
(setf (second (exec-s module)) (second exec)))
((eq (car exec) 'left)
(setf (first (exec-s module)) (second exec)))
((eq (car exec) 'right)
(setf (second (exec-s module)) (second exec)))
(t
(print-warning "Invalid exec setting for the dual execution motor module: ~S" exec)))
(print-warning "Invalid exec setting for the dual execution motor module: ~S" exec))))
(when prep (setf (prep-s module) prep))
(when last (setf (last-cmd module) last))
(if (or (eq (first (proc-s module)) 'busy)
(eq (second (proc-s module)) 'busy)
(eq (first (exec-s module)) 'busy)
(eq (second (exec-s module)) 'busy)
(eq (prep-s module) 'busy))
(setf (mode-s module) 'busy)
(setf (mode-s module) 'free))
(setf (state-change module) t)))
;;; For testing state the processor and execution are busy if either
;;; hand's stage is busy and free only if both hands' stages are free.
;;; Can't check based on hand with the manual buffer, but there are
;;; two additional buffers (manual-left and manual-right) which allow
;;; for testing that if desired, and those buffers also work for
;;; tracking BOLD data by hand.
(defmethod print-module-status ((mod dual-execution-motor-module))
(bt:with-recursive-lock-held ((state-lock mod))
(concatenate 'string
(format nil " preparation free : ~S~%" (eq (prep-s mod) 'free))
(format nil " preparation busy : ~S~%" (eq (prep-s mod) 'busy))
(format nil " processor free : ~S~%" (and (eq (first (proc-s mod)) 'free)
(eq (second (proc-s mod)) 'free)))
(format nil " processor busy : ~S~%" (or (eq (first (proc-s mod)) 'busy)
(eq (second (proc-s mod)) 'busy)))
(format nil " execution free : ~S~%" (and (eq (first (exec-s mod)) 'free)
(eq (second (exec-s mod)) 'free)))
(format nil " execution busy : ~S~%" (or (eq (first (exec-s mod)) 'busy)
(eq (second (exec-s mod)) 'busy)))
(format nil " last-command : ~S~%" (last-cmd mod)))))
(defmethod generic-state-query ((module dual-execution-motor-module) buffer slot value)
(bt:with-recursive-lock-held ((state-lock module))
(case slot
((state modality)
(case value
(busy
(eq (mode-s module) 'busy))
(free
(eq (mode-s module) 'free))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(execution
(case value
(busy
(or (eq (first (exec-s module)) 'busy)
(eq (second (exec-s module)) 'busy)))
(free
(and (eq (first (exec-s module)) 'free)
(eq (second (exec-s module)) 'free)))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(preparation
(case value
(busy
(eq (prep-s module) 'busy))
(free
(eq (prep-s module) 'free))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(processor
(case value
(busy
(or (eq (first (proc-s module)) 'busy)
(eq (second (proc-s module)) 'busy)))
(free
(and (eq (first (proc-s module)) 'free)
(eq (second (proc-s module)) 'free)))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(last-command
(eql (last-cmd module) value)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Change the style mechanisms:
;;;
;;; Give the movement style the slots for indicating whether or not
;;; the movement requires two "executions" (a press and release) and
;;; to indicate if it is a finger based action i.e. it has a finger
;;; attribute and should set that finger busy and free.
;;;
;;; A finger based action will mark the finger as busy when the
;;; initiation starts (preparation completes) and free when it
;;; finishes the movement.
;;;
;;; Whether the finger is up or down is handled by the set-finger-up
;;; and set-finger-down methods which should be called to send the
;;; actual notification to the device.
;;;
;;; Add a method for computing the second execution time.
;;;
;;; Send the hand information to change-state.
;;;
;;; Make dummy requests to the manual-left and manual-right buffers
;;; as appropriate so that an action is recorded for the buffer trace.
;;;
;;; Indicate style and hand in the motor action events' output.
;;;
;;; The new slots are used as follows:
;;;
;;; two-exec-p defaults to nil, but if set to t indicates that the
;;; compute-second-exec-time method should be called.
;;;
;;; exec2-time stores the result of calling compute-second-exec-time.
;;;
;;; release-if-down indicates whether or not the finger used for
;;; the action should produce a release event if it is down when the
;;; execution of this action starts. The possible values are:
;;; nil which means do not generate a release event.
;;; :free (the default) which means to generate the release event and
;;; not charge a time cost for it.
;;; :penalty generates the release event and adds a burst-time cost
;;; to each of the exec, exec2, and finish times of the action.
;;;
;;; Subclass movement-style for
(defclass dual-hand-movement-style (movement-style)
((two-exec-p :accessor two-exec-p :initform nil :initarg :two-exec-p)
(exec2-time :accessor exec2-time :initform 0 :initarg :exec2-time)
(finger-based-style :accessor finger-based-style :initarg :finger-based-style :initform t)
(release-if-down :accessor release-if-down :initarg :release-if-down :initform :free)))
(defgeneric compute-second-exec-time (module movement)
(:documentation "Return the release time of <movement>."))
(defmethod compute-second-exec-time ((module pm-module) (mvmt dual-hand-movement-style))
(error "No method defined for COMPUTE-SECOND-EXEC-TIME."))
(defmethod prepare-movement ((module dual-execution-motor-module) (mvmt dual-hand-movement-style))
(bt:with-recursive-lock-held ((state-lock module))
(change-state module :prep 'BUSY :proc (list (hand mvmt) 'BUSY))
(prepare-features module mvmt)
(setf (fprep-time mvmt)
(randomize-time (compute-prep-time module mvmt)))
(setf (last-prep module) mvmt)
(schedule-event-relative (seconds->ms (fprep-time mvmt)) 'preparation-complete :time-in-ms t
:destination (my-name module) :module (my-name module)
:details (concatenate 'string (symbol-name 'preparation-complete) " " (princ-to-string (request-time mvmt))
" style " (symbol-name (type-of mvmt)) " hand " (symbol-name (hand mvmt))))
;; send dummy requests so that the buffer trace records things appropriately by hand
(unless (relay-hand-requests module) ;; if the buffers sent them to manual don't send them back
(when (or (eq (hand mvmt) 'left) (eq (hand mvmt) 'both))
(schedule-event-now 'module-request
:module (my-name module)
:params (list 'manual-left
(define-chunk-spec-fct (list 'cmd (type-of mvmt))))
:details (concatenate 'string (symbol-name 'module-request) " " (symbol-name 'manual-left))
:output nil
:maintenance t))
(when (or (eq (hand mvmt) 'right) (eq (hand mvmt) 'both))
(schedule-event-now 'module-request
:module (my-name module)
:params (list 'manual-right
(define-chunk-spec-fct (list 'cmd (type-of mvmt))))
:details (concatenate 'string (symbol-name 'module-request) " " (symbol-name 'manual-right))
:output nil
:maintenance t)))))
(defmethod initiation-complete ((module dual-execution-motor-module))
(bt:with-recursive-lock-held ((state-lock module))
(when (last-prep module)
(case (hand (last-prep module))
(left
(change-state module :proc '(left FREE)))
(right
(change-state module :proc '(right FREE)))
(both
(change-state module :proc '(left FREE))
(change-state module :proc '(right FREE)))
(t
(print-warning "Non-handed action taken with the two-handed motor module: ~s" (last-prep module)))))))
(defmethod preparation-complete ((module dual-execution-motor-module))
(bt:with-recursive-lock-held ((state-lock module))
(bt:with-recursive-lock-held ((param-lock module))
(change-state module :prep 'free)
(when (last-prep module)
(if (exec-immediate-p (last-prep module))
(let ((hand (hand (last-prep module))))
(cond ((or (null (two-exec module))
(eq hand 'left)
(eq hand 'right)
(eq hand 'both))
(push-last (last-prep module) (exec-queue module)))
(t
(print-warning "Non-handed action taken with the dual-execution motor module: ~s ~s" (last-prep module) (hand (last-prep module)))))
(when (updated-pos (last-prep module))
(update-prepared module)))
(progn
(when (or (minusp (init-stamp module))
(and (plusp (init-stamp module))
(>= (mp-time-ms) (+ (init-stamp module) (seconds->ms (init-time module))))))
(change-state module :proc (list (hand (last-prep module)) 'FREE))))))
(maybe-execute-movement module))))
#| don't need to redefine this since there's only one
exec queue again
(defmethod execute ((module dual-execution-motor-module) request)
(bt:with-recursive-lock-held ((state-lock module))
(cond ((not (last-prep module))
(model-warning "Motor Module has no movement to EXECUTE."))
((eq (prep-s module) 'BUSY)
(model-warning "Motor Module cannot EXECUTE features being prepared."))
(t
(setf (request-spec (last-prep module)) request)
(setf (exec-queue module)
(append (exec-queue module) (mklist (last-prep module))))
(when (updated-pos (last-prep module))
(update-prepared module))
(maybe-execute-movement module)))))
|#
(defmethod update-prepared ((mtr-mod dual-execution-motor-module))
(when (find 'hand (feature-slots (last-prep mtr-mod)))
(case (hand (last-prep mtr-mod))
(left (set-hand-position mtr-mod 'left (updated-pos (last-prep mtr-mod)) :current nil))
(right (set-hand-position mtr-mod 'right (updated-pos (last-prep mtr-mod)) :current nil))
(both (set-hand-position mtr-mod 'left (first (updated-pos (last-prep mtr-mod))) :current nil)
(set-hand-position mtr-mod 'right (second (updated-pos (last-prep mtr-mod))) :current nil)))))
(defmethod maybe-execute-movement ((module dual-execution-motor-module))
;; If only one exec system just pop the next one like normal.
;; Otherwise, if there's an execution stage available check actions to
;; perform starting from the front until one can be executed for each
;; available stage or a both is found (regardless of whether it can
;; be executed because if it can't be executed then you can't skip
;; over it).
;;
(bt:with-recursive-lock-held ((state-lock module))
(bt:with-recursive-lock-held ((param-lock module))
(when (exec-queue module)
(if (null (two-exec module))
(when (eq (first (exec-s module)) 'FREE)
(perform-movement module (pop (exec-queue module))))
(when (or (eq (first (exec-s module)) 'FREE)
(eq (second (exec-s module)) 'FREE))
(do* ((left-available (eq (first (exec-s module)) 'FREE))
(right-available (eq (second (exec-s module)) 'FREE))
(queue (exec-queue module) (cdr queue))
(evt (car queue) (car queue)))
((or (null evt)
(and (null left-available)
(null right-available))))
(case (hand evt)
(left
(when left-available
(setf left-available nil)
(setf (exec-queue module) (remove evt (exec-queue module)))
(perform-movement module evt)))
(right
(when right-available
(setf right-available nil)
(setf (exec-queue module) (remove evt (exec-queue module)))
(perform-movement module evt)))
(both
(when (and left-available right-available)
(setf (exec-queue module) (remove evt (exec-queue module)))
(perform-movement module evt))
;; whether a both executes or not it blocks any
;; further actions because you can't reorder the
;; actions for a hand
(setf left-available nil)
(setf right-available nil))))))))))
(defmethod perform-movement ((module dual-execution-motor-module) (mvmt movement-style))
(bt:with-recursive-lock-held ((state-lock module)) ; don't need the lock the whole time but more efficient than grabbing twice
(bt:with-recursive-lock-held ((param-lock module))
(let ((extension (extension module))
(last (last-prep module)))
;; Check releases now because they could have been going down while this was being
;; prepared but if it's not down now just stop.
;; Shouldn't happen now because of the preparation checks, but just to be safe
;; leaving it here.
(when (and (or (typep last 'release)
(typep last 'release-recoil))
(not (finger-down extension (hand last) (finger last))))
(print-warning "RELEASE action ignored because the ~s ~s finger is not held down." (hand (last-prep module)) (finger (last-prep module)))
(return-from perform-movement))
(let ((hands (if (eq (hand mvmt) 'both) (list 'left 'right) (list (hand mvmt))))
(fingers (let ((f (when (find 'finger (feature-slots mvmt))
(finger mvmt))))
(if (and f (not (eq f :dummy)))
(list f)
'(index middle ring pinkie thumb)))))
(schedule-event-relative (seconds->ms (init-time module)) 'INITIATION-COMPLETE :destination (my-name module)
:time-in-ms t :module (my-name module)
:details (concatenate 'string (symbol-name 'INITIATION-COMPLETE) " " (princ-to-string (request-time mvmt))
" style " (symbol-name (type-of mvmt)) " hand " (symbol-name (hand mvmt))))
(change-state module :proc (list (hand mvmt) 'BUSY) :exec (list (hand mvmt) 'BUSY))
(setf (init-stamp module) (mp-time-ms))
(setf (exec-time mvmt) (compute-exec-time module mvmt))
(setf (finish-time mvmt) (compute-finish-time module mvmt))
(when (two-exec-p mvmt)
(setf (exec2-time mvmt) (compute-second-exec-time module mvmt)))
;;; Automatically release the fingers involved in an action
;;; and charge a burst-time cost if they're down at the start
;;; of the action and the style says they need to be released.
(when (release-if-down mvmt)
(let ((adjust nil))
(dolist (hand hands)
(dolist (finger fingers)
(when (finger-down extension hand finger)
(setf adjust t)
(schedule-event-relative (seconds->ms (+ (init-time module) (key-release-time module)))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list 'release hand finger (finger-loc-m module hand finger))))))
(when (and adjust (eq (release-if-down mvmt) :penalty))
(incf (exec-time mvmt) (burst-time module))
(incf (finish-time mvmt) (burst-time module))
(when (two-exec-p mvmt)
(incf (exec2-time mvmt) (burst-time module))))))
(queue-output-events module mvmt)
(queue-finish-event module mvmt)
;; indicate that the fingers are busy
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(when (finger-based-style mvmt)
(dolist (hand hands)
(dolist (finger fingers)
(setf (gethash (list hand finger) (hand-tracker-finger-busy extension)) t))))))))))
(defmethod queue-finish-event ((module dual-execution-motor-module) (mvmt movement-style))
(schedule-event-relative (seconds->ms (finish-time mvmt)) 'finish-movement-dual :destination (my-name module)
:time-in-ms t :params (list mvmt) :module (my-name module)
:details (concatenate 'string (symbol-name 'finish-movement) " " (princ-to-string (request-time mvmt))
" style " (symbol-name (type-of mvmt)) " hand " (symbol-name (hand mvmt)))))
(defmethod finish-movement-dual ((module dual-execution-motor-module) (mvmt movement-style))
(change-state module :exec (list (hand mvmt) 'free))
;;; If the style says it's finger based then set the fingers back to free
(when (finger-based-style mvmt)
(let ((extension (extension module))
(hands (if (eq (hand mvmt) 'both) (list 'left 'right) (list (hand mvmt))))
(fingers (let ((f (when (find 'finger (feature-slots mvmt))
(finger mvmt))))
(if (and f (not (eq f :dummy)))
(list f)
'(index middle ring pinkie thumb)))))
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(dolist (hand hands)
(dolist (finger fingers)
(remhash (list hand finger) (hand-tracker-finger-busy extension)))))))
(maybe-execute-movement module))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code for recording and testing hand execution with separate buffers.
;;;
;;; With the new buffers the fingers can also be tested to determine if
;;; they're currently "holding" a key. If the finger is up it is
;;; not holding a key and if it is down then it is holding a key. That
;;; is independent of free/busy which indicates that it is performing
;;; an action, and holding a key does not make it busy once the finger
;;; is down.
(defstruct hand-tracker
manual left-cmd right-cmd relay
(lock (bt:make-recursive-lock "hand-tracker"))
(finger-busy (make-hash-table :size 10 :test 'equalp))
(finger-down (make-hash-table :size 10 :test 'equalp)))
(defun track-hand-requests (module buffer spec)
(let (relay)
(bt:with-recursive-lock-held ((hand-tracker-lock module))
(setf relay (hand-tracker-relay module))
(if (eq buffer 'manual-left)
(setf (hand-tracker-left-cmd module) (spec-slot-value (car (chunk-spec-slot-spec spec 'cmd))))
(setf (hand-tracker-right-cmd module) (spec-slot-value (car (chunk-spec-slot-spec spec 'cmd))))))
(when relay
(let ((includes-hand (chunk-spec-slot-spec spec 'hand)))
(if (or (null includes-hand)
(and includes-hand
(= (length includes-hand) 1)
(eq (spec-slot-op (car includes-hand)) '=)
(or (and (eq buffer 'manual-left) (eq (spec-slot-value (car includes-hand)) 'left))
(and (eq buffer 'manual-right) (eq (spec-slot-value (car includes-hand)) 'right)))))
(module-request 'manual spec)
(print-warning "Request to ~s buffer has an invalid hand slot ~s." buffer includes-hand))))))
(defun reset-hand-tracker (module)
(bt:with-recursive-lock-held ((hand-tracker-lock module))
(setf (hand-tracker-manual module) (get-module :motor))
(setf (hand-tracker-left-cmd module) 'none)
(setf (hand-tracker-right-cmd module) 'none)
(clrhash (hand-tracker-finger-busy module))
(clrhash (hand-tracker-finger-down module))))
(defun finger-down (extension hand finger &key (current t))
(if current
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(gethash (list hand finger) (hand-tracker-finger-down extension)))
(let* ((hand-pos (hand-position hand :current nil))
(fingers (find 'extended-fingers (hand-pos-other hand-pos) :key 'first))
(f (find finger (rest fingers) :key 'first)))
(if f
(second f)
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(gethash (list hand finger) (hand-tracker-finger-down extension)))))))
(defun any-finger-down (extension hand &key (current t))
(if current
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(some (lambda (x) (gethash (list hand x) (hand-tracker-finger-down extension)))
'(index middle ring pinkie thumb)))
(let* ((hand-pos (hand-position hand :current nil))
(fingers (find 'extended-fingers (hand-pos-other hand-pos) :key 'first))
(states (rest fingers)))
(if states
(progn
(unless (= 5 (length states))
(print-warning "Invalid extended-fingers information stored in hand position for any-finger-down."))
(some 'second states))
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(some (lambda (x) (gethash (list hand x) (hand-tracker-finger-down extension)))
'(index middle ring pinkie thumb)))))))
(defun finger-busy (extension hand finger)
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(gethash (list hand finger) (hand-tracker-finger-busy extension))))
(defmethod print-hand-buffer-status ((mod hand-tracker) hand)
(let ((manual (hand-tracker-manual mod)))
(bt:with-recursive-lock-held ((state-lock manual))
(with-output-to-string (s)
(format s " processor free : ~S~%"
(if (eq hand 'manual-left)
(eq (first (proc-s manual)) 'free)
(eq (second (proc-s manual)) 'free)))
(format s " processor busy : ~S~%"
(if (eq hand 'manual-left)
(eq (first (proc-s manual)) 'busy)
(eq (second (proc-s manual)) 'busy)))
(format s " execution free : ~S~%"
(if (eq hand 'manual-left)
(eq (first (exec-s manual)) 'free)
(eq (second (exec-s manual)) 'free)))
(format s " execution busy : ~S~%"
(if (eq hand 'manual-left)
(eq (first (exec-s manual)) 'busy)
(eq (second (exec-s manual)) 'busy)))
(format s " last-command : ~S~%"
(if (eq hand 'manual-left)
(hand-tracker-left-cmd mod)
(hand-tracker-right-cmd mod)))
(dolist (x '(index middle ring pinkie thumb))
(format s " ~(~6a~) free : ~s~%" x
(null (finger-busy mod (if (eq hand 'manual-left) 'left 'right) x)))
(format s " ~(~6a~) down : ~s~%" x
(finger-down mod (if (eq hand 'manual-left) 'left 'right) x)))))))
(defmethod generic-state-query ((module hand-tracker) buffer slot value)
(let ((manual (hand-tracker-manual module)))
(bt:with-recursive-lock-held ((state-lock manual))
(case slot
(preparation ;; same for both hands
(case value
(busy
(eq (prep-s module) 'busy))
(free
(eq (prep-s module) 'free))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(state
(case value
(busy (case buffer
(manual-left
(or (eq (first (exec-s manual)) 'busy) (eq (first (proc-s manual)) 'busy)))
(manual-right
(or (eq (second (exec-s manual)) 'busy) (eq (second (proc-s manual)) 'busy)))))
(free (case buffer
(manual-left
(and (eq (first (exec-s manual)) 'free) (eq (first (proc-s manual)) 'free)))
(manual-right
(and (eq (second (exec-s manual)) 'free) (eq (second (proc-s manual)) 'free)))))
(error nil)
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(execution
(case value
(busy (case buffer
(manual-left
(eq (first (exec-s manual)) 'busy))
(manual-right
(eq (second (exec-s manual)) 'busy))))
(free (case buffer
(manual-left
(eq (first (exec-s manual)) 'free))
(manual-right
(eq (second (exec-s manual)) 'free))))
(error nil)
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(processor
(case value
(busy (case buffer
(manual-left
(eq (first (proc-s manual)) 'busy))
(manual-right
(eq (second (proc-s manual)) 'busy))))
(free (case buffer
(manual-left
(eq (first (proc-s manual)) 'free))
(manual-right
(eq (second (proc-s manual)) 'free))))
(error nil)
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(last-command
(case buffer
(manual-left
(eql (hand-tracker-left-cmd module) value))
(manual-right
(eql (hand-tracker-right-cmd module) value))))
((index middle ring pinkie thumb)
(bt:with-recursive-lock-held ((hand-tracker-lock module))
(case value
(busy
(gethash (list (if (eq buffer 'manual-left) 'left 'right) slot) (hand-tracker-finger-busy module)))
(free
(null (gethash (list (if (eq buffer 'manual-left) 'left 'right) slot) (hand-tracker-finger-busy module))))
(down
(gethash (list (if (eq buffer 'manual-left) 'left 'right) slot) (hand-tracker-finger-down module)))
(up
(null (gethash (list (if (eq buffer 'manual-left) 'left 'right) slot) (hand-tracker-finger-down module))))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value)))))))))
(defun track-hand-params (instance param)
;; The parameter values are actually stored in the motor module
;; and not the extension module.
(let ((manual (aif (hand-tracker-manual instance) it (get-module :motor))))
(bt:with-recursive-lock-held ((param-lock manual))
(cond ((consp param)
(case (car param)
(:key-closure-time
(setf (key-closure-time manual) (cdr param)))
(:key-release-time
(setf (key-release-time manual) (cdr param)))
(:dual-processor-stages
(setf (two-proc manual) (cdr param)))
(:dual-execution-stages
(setf (two-exec manual) (cdr param)))
(:peck-strike-distance
(setf (peck-strike manual) (cdr param)))
(:default-punch-delay
(setf (d-punch-default manual) (cdr param)))
(:fast-punch-delay
(setf (d-punch-fast manual) (cdr param)))
(:slow-punch-delay
(setf (d-punch-slow manual) (cdr param)))
(:cursor-drag-delay
(setf (drag-delay manual) (cdr param)))
(:relay-hand-requests
(setf (relay-hand-requests manual) (cdr param))
(bt:with-recursive-lock-held ((hand-tracker-lock instance))
(setf (hand-tracker-relay instance) (cdr param))))))
(t
(case param
(:key-release-time
(key-release-time manual))
(:dual-processor-stages
(two-proc manual))
(:dual-execution-stages
(two-exec manual))
(:peck-strike-distance
(peck-strike manual))
(:default-punch-delay
(d-punch-default manual))
(:fast-punch-delay
(d-punch-fast manual))
(:slow-punch-delay
(d-punch-slow manual))
(:cursor-drag-delay
(drag-delay manual))
(:relay-hand-requests
(bt:with-recursive-lock-held ((hand-tracker-lock instance))
(hand-tracker-relay instance)))))))))
(defun left-hand-buffer-status ()
(print-hand-buffer-status (get-module motor-extension) 'manual-left))
(defun right-hand-buffer-status ()
(print-hand-buffer-status (get-module motor-extension) 'manual-right))
(defun peck-strike-value-test (x)
(or (null x) (and (numberp x) (<= 0 x .5))))
(defun create-motor-extension-module (x)
(declare (ignore x))
(make-hand-tracker))
(define-module-fct 'motor-extension
(list (list 'manual-left nil nil '(execution processor last-command index middle ring pinkie thumb)
'left-hand-buffer-status)
(list 'manual-right nil nil '(execution processor last-command index middle ring pinkie thumb)
'right-hand-buffer-status))
(list
(define-parameter :default-punch-delay
:valid-test 'posnum
:warning "a number"
:default-value 0.075
:documentation "Default time for a delayed-punch request.")
(define-parameter :fast-punch-delay
:valid-test 'posnum
:warning "a number"
:default-value 0.050
:documentation "Time for a delayed-punch request with a delay of fast.")
(define-parameter :slow-punch-delay
:valid-test 'posnum
:warning "a number"
:default-value 0.1
:documentation "Time for a delayed-punch request with a delay of slow.")
(define-parameter :cursor-drag-delay
:valid-test 'posnumorbool
:warning "T, nil, or a positive number"
:default-value nil
:documentation "Control order increment for cursor drag actions.")
(define-parameter :key-release-time
:valid-test 'nonneg
:warning "a number"
:default-value 0.04
:documentation "Time between when a key that is held down is released and when it registers as being released.")
(define-parameter :key-closure-time
:owner nil)
(define-parameter :dual-processor-stages
:valid-test 'tornil
:warning "T or nil"
:default-value nil
:documentation "Whether the motor module has separate processor stages for the hands.")
(define-parameter :dual-execution-stages
:valid-test 'tornil
:warning "T or nil"
:default-value nil
:documentation "Whether the motor module has separate execution stages for the hands.")
(define-parameter :peck-strike-distance
:valid-test 'peck-strike-value-test
:warning "Nil or a number between 0 and .5"
:default-value nil
:documentation "Distance from center of the key at which time a peck starts to depress the key.")
(define-parameter :relay-hand-requests
:valid-test 'tornil
:warning "T or nil"
:default-value nil
:documentation "Whether manual-left and manual-right pass requests to manual"))
:params 'track-hand-params
:request 'track-hand-requests
:query 'generic-state-query
:creation 'create-motor-extension-module
:reset (list nil nil 'reset-hand-tracker)
:version "6.1"
:documentation "Extends motor module with dual processor and/or execution states and finger holding actions.")
;;; Compute when a peck or peck-recoil indicates that the key is hit
;;; based on the peck-strike-distance paramter.
;;;
;;; For the peck and peck-recoil compute the timing a little differently
;;; now because I want to consider the time between striking and releasing
;;; the key. So, send the output-key before the movement time is "done"
;;; to simulate the key-closure-time as punch does i.e. the key gets
;;; detected before the motion is complete. To do that I'm assuming that
;;; the key starts to move once the finger gets within the peck-strike-distance
;;; of the target (center of the key). Just using a simple binary serach to find
;;; the adjusted target time at this point instead of a complicated numerical
;;; method.
;;;
(defun movement-strike-time (mtr-mod tt r)
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(cond ((null (peck-strike mtr-mod))
tt)
((zerop (peck-strike mtr-mod))
(+ tt (key-closure-time mtr-mod)))
(t
(ms-round (+ (key-closure-time mtr-mod)
(do* ((target (- r (peck-strike mtr-mod)))
(width (* .25 tt) (/ width 2))
(guess (* tt .75) (+ (* dir width) guess))
(value (minjerk-dist guess r tt)
(minjerk-dist guess r tt))
(dir (if (< value target) 1 -1)
(if (< value target) 1 -1)))
((< (abs (- target value)) .01) guess))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Create methods to handle the finger movement, the notifications are
;;; generated by these instead of directly in the output event.
(defmethod set-finger-up ((module dual-execution-motor-module) style hand finger position)
(declare (ignore style))
(let ((extension (extension module)))
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(when (gethash (list hand finger) (hand-tracker-finger-down extension))
(remhash (list hand finger) (hand-tracker-finger-down extension))
(notify-motor-device (let ((h (case hand
(left (left-hand module))
(right (right-hand module)))))
(bt:with-lock-held ((hand-lock h))
(device h)))
`((model ,(current-model)) (style release) (hand ,hand) (loc ,(coerce position 'list))))))))
(defmethod set-finger-down ((module dual-execution-motor-module) style hand finger position)
(let ((extension (extension module)))
(bt:with-recursive-lock-held ((hand-tracker-lock extension))
(unless (gethash (list hand finger) (hand-tracker-finger-down extension))
(setf (gethash (list hand finger) (hand-tracker-finger-down extension)) t)
(notify-motor-device (let ((h (case hand
(left (left-hand module))
(right (right-hand module)))))
(bt:with-lock-held ((hand-lock h))
(device h)))
`((model ,(current-model)) (style ,style) (hand ,hand) (loc ,(coerce position 'list))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Redefine the standard motor actions: punch, peck, and peck-recoil
;;; to deal with calling the release event and indicate that they
;;; should automatically release the key (paying a burst-time cost) and
;;; indicate the actions are finger based (the default so don't really set).
;;;
;;; The release time is determined to be key-release-time after the
;;; "striking" action is over i.e. the burst or movement time. So it
;;; happens somewhere during the final burst-time.
;;;
;;; Only redefine the methods needed -- most exec and finish time
;;; methods for original actions are still fine.
;;;
;;; Using a symbol for style-name instead of a keyword so it can
;;; be passed to the notification directly.
;;;
;;; Create a base class for hand and finger movements since there are
;;; other related styles now instead of only punches, and that allows
;;; for a general queue-output-events!
;;;
;;; A big NOPE to that ability to have a general queue-output-events
;;; since the old specific methods get in the way...
;;; Leaving it here, but also cut-and-pasting it for specific
;;; methods.
(defstyle hf-movement dual-hand-movement-style hand finger)
(defStyle hfrt-movement hf-movement hand finger r theta)
(defmethod queue-output-events ((mtr-mod motor-module) (self hf-movement))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc-m mtr-mod (hand self) (finger self))))
(schedule-event-relative (seconds->ms (exec2-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc-m mtr-mod (hand self) (finger self)))))
;;; Method to adjust the state of a finger given a starting position
(defgeneric adjust-finger-position (mtr-mod self starting-point finger-state)
)
(defmethod adjust-finger-position ((mtr-mod dual-execution-motor-module) (self dual-hand-movement-style) starting-point finger-state)
(let* ((hand (hand self))
(others (copy-seq (hand-pos-other starting-point)))
(extension (extension mtr-mod))
(current (find 'extended-fingers (hand-pos-other starting-point) :key 'first))
(current-fingers (rest current)))
(when current
(setf others (remove current others)))
(let ((updated-fingers (list 'extended-fingers)))
;; don't really need to set all of them, but
;; for consistency always going to do so
(dolist (finger '(index middle ring pinkie thumb))
(push-last (if (eq finger (finger self))
(list finger finger-state)
(let ((previous (find finger current-fingers :key 'first)))
(if previous
(list finger (second previous))
(list finger (finger-down extension hand finger))))) ;; know it's not in :current nil
updated-fingers))
(push updated-fingers others))
(setf (hand-pos-other starting-point) others)
(setf (updated-pos self) starting-point)))
;;; Updated punch
(defclass punch (hf-movement)
nil
(:default-initargs
:style-name 'punch
:two-exec-p t
:release-if-down :penalty))
(defmethod prepare-features ((mtr-mod motor-module) (self punch))
(adjust-finger-position mtr-mod self (copy-hand-pos (hand-position (hand self) :current nil)) nil))
(defmethod compute-second-exec-time ((mtr-mod motor-module) (self punch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
; don't add this to be consistent with peck and peck-recoil actions (burst-time mtr-mod)
(key-release-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod motor-module) (self punch))
;; don't need to schedule a setting of the new hand position
;; since the "current" finger info isn't stored in there but do it
;; for consistency and use exec2 since that's when the finger is really up.
(schedule-event-relative (seconds->ms (exec2-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self))))
(schedule-event-relative (seconds->ms (exec2-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self)))))
;;; Updated peck
;;; add a move-time slot to pecks to save the calculation
(defclass peck (hfrt-movement)
((move-time :accessor move-time))
(:default-initargs
:style-name 'peck
:two-exec-p t
:release-if-down :penalty))
(defmethod prepare-features ((mtr-mod motor-module) (self peck))
(adjust-finger-position mtr-mod self (move-a-finger mtr-mod (hand self) (finger self) (r self) (theta self) :current nil) nil))
(defmethod compute-exec-time ((mtr-mod motor-module) (self peck))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(randomize-time (fitts mtr-mod (peck-fitts-coeff mtr-mod) (r self)))))
(+ (init-time mtr-mod)
(movement-strike-time mtr-mod (move-time self) (r self)))))
(defmethod compute-finish-time ((mtr-mod motor-module) (self peck))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(move-time self)
(burst-time mtr-mod))))
(defmethod compute-second-exec-time ((mtr-mod motor-module) (self peck))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(move-time self)
(key-release-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod motor-module) (self peck))
(schedule-event-relative (seconds->ms (exec2-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self))))
(schedule-event-relative (seconds->ms (exec2-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self)))))
;;; Updated peck-recoil
;;; for a peck-recoil record the base movement time and the specific (noisy) first movement times
(defclass peck-recoil (hfrt-movement)
((move-time :accessor move-time)
(first-move-time :accessor first-move-time))
(:default-initargs
:style-name 'peck
:two-exec-p t
:release-if-down :penalty))
(defmethod prepare-features ((mtr-mod motor-module) (self peck-recoil))
(adjust-finger-position mtr-mod self (copy-hand-pos (hand-position (hand self) :current nil)) nil))
(defmethod compute-exec-time ((mtr-mod motor-module) (self peck-recoil))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(fitts mtr-mod (peck-fitts-coeff mtr-mod) (r self))))
(setf (first-move-time self)
(max (burst-time mtr-mod)
(randomize-time (move-time self))))
(+ (init-time mtr-mod)
(movement-strike-time mtr-mod (first-move-time self) (r self)))))
(defmethod compute-finish-time ((mtr-mod motor-module) (self peck-recoil))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(first-move-time self)
(burst-time mtr-mod)
(max (burst-time mtr-mod) (randomize-time (move-time self))))))
(defmethod compute-second-exec-time ((mtr-mod motor-module) (self peck-recoil))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(first-move-time self)
(key-release-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod motor-module) (self peck-recoil))
(schedule-event-relative (seconds->ms (exec2-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(let ((target-loc (polar-move-xy (finger-loc (updated-pos self) (finger self))
(vector (r self) (theta self)))))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) target-loc))
(schedule-event-relative (seconds->ms (exec2-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) target-loc))))
;;; Make sure that mouse movement doesn't change the state of the
;;; mouse button
(defclass cursor-ply (ply)
((target-coords :accessor target-coords :initarg :target-coords)
(control-order :accessor control-order :initarg :control-order :initform 0)
(cursor :accessor cursor :initarg :cursor :initform nil))
(:default-initargs
:hand 'RIGHT
:fitts-coeff
(let ((mtr-mod (get-module :motor)))
(when mtr-mod
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(mouse-fitts-coeff mtr-mod))))
:release-if-down nil
:finger-based-style nil))
;; Since it doesn't adjust the extended custom features for the hand-position
;; (doesn't change finger states) the original methods will still work.
;; However, to account for the drag-delay need to change the :before
;; method on the exec-time.
(defmethod compute-exec-time :before ((mtr-mod motor-module) (self cursor-ply))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(let ((offset 0)
(extension (extension mtr-mod))
(hand (hand self)))
(when (drag-delay mtr-mod)
(when (any-finger-down extension hand :current nil) ;; down when move will happen
(setf offset (if (eq (drag-delay mtr-mod) t) .8 (drag-delay mtr-mod)))))
(setf (fitts-coeff self)
(* (expt-coerced 2 (+ offset (control-order self))) (fitts-coeff self))))))
;;; New styles for actions which hold a finger down or release a held finger
(defclass hold-punch (punch)
nil
(:default-initargs
:style-name 'punch
:two-exec-p nil
:release-if-down :penalty))
(defmethod prepare-features ((mtr-mod motor-module) (self hold-punch))
(adjust-finger-position mtr-mod self (copy-hand-pos (hand-position (hand self) :current nil)) t))
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self hold-punch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(key-closure-time mtr-mod))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self hold-punch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(burst-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self hold-punch))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self)))))
(defmethod hold-punch ((mtr-mod dual-execution-motor-module) &key hand finger request-spec)
(unless (or (check-jam mtr-mod) (check-specs 'hold-punch hand finger))
(prepare-movement mtr-mod (make-instance 'hold-punch :hand hand :finger finger :request-spec request-spec))))
(extend-manual-requests (hold-punch hand finger) handle-style-request)
(defclass hold-peck (peck)
nil
(:default-initargs
:style-name 'peck
:two-exec-p nil
:release-if-down :penalty))
(defmethod prepare-features ((mtr-mod motor-module) (self hold-peck))
(adjust-finger-position mtr-mod self (move-a-finger mtr-mod (hand self) (finger self) (r self) (theta self) :current nil) t))
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self hold-peck))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(randomize-time (fitts mtr-mod (peck-fitts-coeff mtr-mod) (r self)))))
(+ (init-time mtr-mod)
(movement-strike-time mtr-mod (move-time self) (r self)))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self hold-peck))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(move-time self))))
(defmethod queue-output-events ((mtr-mod motor-module) (self hold-peck))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self)))))
(defmethod hold-peck ((mtr-mod motor-module) &key hand finger r theta request-spec)
(unless (or (check-jam mtr-mod) (check-specs 'hold-peck hand finger r theta))
(when (symbolp theta)
(setf theta (symbol-value theta)))
(prepare-movement mtr-mod (make-instance 'hold-peck :hand hand :finger finger :r r :theta theta :request-spec request-spec))))
(extend-manual-requests (hold-peck hand finger r theta) handle-style-request)
(defclass release (punch)
nil
(:default-initargs
:style-name 'punch
:two-exec-p nil
:release-if-down nil))
(defmethod prepare-features ((mtr-mod motor-module) (self release))
(adjust-finger-position mtr-mod self (copy-hand-pos (hand-position (hand self) :current nil)) nil))
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self release))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(key-release-time mtr-mod))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self release))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(burst-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self release))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self)))))
(defmethod release ((mtr-mod dual-execution-motor-module) &key hand finger request-spec)
(unless (or (check-jam mtr-mod) (check-specs 'release hand finger))
(if (not (finger-down (extension mtr-mod) hand finger :current nil))
(print-warning "RELEASE action ignored because the ~s ~s finger is not held down or already being released." hand finger)
(prepare-movement mtr-mod (make-instance 'release :hand hand :finger finger :request-spec request-spec)))))
(extend-manual-requests (release hand finger) handle-style-request)
(defclass release-recoil (peck)
nil
(:default-initargs
:style-name 'peck
:two-exec-p nil
:release-if-down nil))
;; the same prepare as peck is fine
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self release-recoil))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(key-release-time mtr-mod))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self release-recoil))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(randomize-time (fitts mtr-mod (peck-fitts-coeff mtr-mod) (r self)))))
(+ (init-time mtr-mod)
(move-time self)
(burst-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self release-recoil))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(let ((current-position (finger-loc (hand self) (finger self))))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) current-position))))
(defmethod release-recoil ((mtr-mod dual-execution-motor-module) &key hand finger r theta request-spec)
(unless (or (check-jam mtr-mod) (check-specs 'release-recoil hand finger r theta))
(when (symbolp theta)
(setf theta (symbol-value theta)))
(prepare-movement mtr-mod (make-instance 'release-recoil :hand hand :finger finger :r r :theta theta :request-spec request-spec))))
(extend-manual-requests (release-recoil hand finger r theta) handle-style-request)
;; Style for moving a finger without striking the key
(defclass point-finger (peck)
nil
(:default-initargs
:style-name 'peck
:two-exec-p nil
:release-if-down :penalty))
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self point-finger))
;; compute a real exec time now to send the change in hand position
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(randomize-time (fitts mtr-mod (peck-fitts-coeff mtr-mod) (r self)))))
(max (init-time mtr-mod)
(move-time self))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self point-finger))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(move-time self))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self point-finger))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self))))
(defmethod point-finger ((mtr-mod motor-module) &key hand finger r theta request-spec)
(unless (or (check-jam mtr-mod) (check-specs 'point-finger hand finger r theta))
(when (symbolp theta)
(setf theta (symbol-value theta)))
(prepare-movement mtr-mod (make-instance 'point-finger :hand hand :finger finger :r r :theta theta :request-spec request-spec))))
(extend-manual-requests (point-finger hand finger r theta) handle-style-request)
;;; These are the new "macro" actions which take a key name and then generate
;;; the appropriate low-level style as needed based on current finger position and
;;; spcified target.
;;; Start with some functions that return useful keyboard information.
;;; Determine which hand and finger is used to strike the key based on the
;;; touch typing commands predefined for the keyboad.
(defun key->hand&finger (keyboard key)
(unless (stringp key)
(setf key (princ-to-string key)))
(let ((command (key->cmd keyboard key)))
(if (null (first command))
(print-warning "No hand and finger mapping available for key ~s" key)
(let* ((hand-index (position :hand command))
(hand-name (nth (1+ hand-index) command))
(finger-index (position :finger command))
(finger-name (nth (1+ finger-index) command)))
(values hand-name finger-name)))))
;;; Get a finger's home position.
(defun home-position (keyboard hand finger)
(let* ((positions
(case hand
(left (keyboard-hand-location keyboard 'left-home))
(right (keyboard-hand-location keyboard 'right-home))))
(h-pos (find 'hand positions :key 'first))
(f-pos (find finger positions :key 'first)))
(if (and f-pos h-pos)
(coerce (mapcar '+ (rest f-pos) (rest h-pos)) 'vector)
(print-warning "No home-position available for hand ~s and finger ~s." hand finger))))
;;; Here's the general pattern for many of the new finger-based keyboard actions
(defmethod extended-finger-keyboard ((mtr-mod dual-execution-motor-module) spec name
&key (same-loc-action 'punch) (move-loc-action 'peck-recoil)
(same-loc-key-only nil) (move-loc-key-only nil))
(if (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(aif (current-keyboard)
(let ((key (verify-single-explicit-value spec 'key :motor name)))
(if key
(progn
(unless (stringp key)
(setf key (princ-to-string key)))
(multiple-value-bind (hand finger) (key->hand&finger it key)
(if (and hand finger)
(let ((device (device-for-hand hand :current nil)))
(if (string-equal (second device) "keyboard")
(let ((key-loc (key->loc it key))
(finger-loc (finger-loc-m mtr-mod hand finger :current nil)))
(if (vpt= key-loc finger-loc)
(if same-loc-key-only
(funcall same-loc-action key)
(funcall same-loc-action mtr-mod :hand hand :finger finger :request-spec spec))
(let ((vector (xy-to-polar finger-loc key-loc)))
(if move-loc-key-only
(funcall move-loc-action key)
(funcall move-loc-action mtr-mod :hand hand :finger finger :r (vr vector) :theta (vtheta vector) :request-spec spec)))))
(print-warning "The ~s hand is not (or will not be) on the keyboard device for ~s request." hand name)))
(print-warning "Could not determine a hand and finger for key ~s in ~s request." key name))))
(print-warning "No valid key value found in ~s request." name)))
(print-warning "No keyboard device available for ~s request." name))
(print-warning "Keyboard device not installed for motor interface in ~s request." name)))
;; type-key
;; Similar to the press-key command except that it doesn't assume the finger
;; starts from the home row. It uses the appropriate finger's starting position
;; to determine the movement necessary to strike the key and return to where it
;; started (which may or may not be the home row).
(defmethod type-key ((mtr-mod dual-execution-motor-module) spec)
(extended-finger-keyboard mtr-mod spec 'type-key))
(extend-manual-requests (type-key key) type-key)
;; hit-key
;; Similar to the press-key command except that it doesn't assume the finger
;; starts from the home row (it uses the current position) and it stays at the
;; key which was hit instead of returning to the home position.
(defmethod hit-key ((mtr-mod dual-execution-motor-module) spec)
(extended-finger-keyboard mtr-mod spec 'type-key :move-loc-action 'peck))
(extend-manual-requests (hit-key key) hit-key)
;; hold-key
;; Like the hit-key action except that it continues to hold the key that is struck.
(defmethod hold-key ((mtr-mod dual-execution-motor-module) spec)
(extended-finger-keyboard mtr-mod spec 'type-key :same-loc-action 'hold-punch :move-loc-action 'hold-peck))
(extend-manual-requests (hold-key key) hold-key)
;; release-key
;; If the designated key is being held down release it and leave the finger over it.
(defmethod release-key ((mtr-mod dual-execution-motor-module) spec)
(extended-finger-keyboard mtr-mod spec 'release-key :same-loc-action 'release
:move-loc-key-only t
:move-loc-action (lambda (key)
(print-warning "Cannot release the ~s key because the appropriate finger is not on that key in release-key request." key))))
(extend-manual-requests (release-key key) release-key)
;; release-key-to-home
;; If the designated key is being held down release it and return the finger to the
;; home position.
(defmethod release-key-to-home ((mtr-mod dual-execution-motor-module) spec)
(extended-finger-keyboard mtr-mod spec 'release-key-to-home
:same-loc-action (lambda (m-mod &key hand finger request-spec)
(let* ((home-pos (home-position (current-keyboard) hand finger))
(finger-loc (finger-loc-m m-mod hand finger :current nil))
(vector (xy-to-polar finger-loc home-pos)))
(if (zerop (vr vector))
(release m-mod :hand hand :finger finger :request-spec request-spec)
(release-recoil m-mod :hand hand :finger finger :r (vr vector) :theta (vtheta vector) :request-spec request-spec)))
)
:move-loc-key-only t
:move-loc-action (lambda (key)
(print-warning "Cannot release the ~s key because the appropriate finger is not on that key in release-key-to-home request." key))))
(extend-manual-requests (release-key-to-home key) release-key-to-home)
;; move-to-key
;; Position the appropriate finger over the designated key without striking it.
(defmethod move-to-key ((mtr-mod dual-execution-motor-module) spec)
(extended-finger-keyboard mtr-mod spec 'move-to-key
:same-loc-key-only t
:same-loc-action (lambda (key)
(print-warning "Move-to-key request for key ~s ignored because appropriate finger is already at that key." key))
:move-loc-action 'point-finger))
(extend-manual-requests (move-to-key key) move-to-key)
;; move-finger-to-home
;; Return a specified finger to the home position without striking that key.
;; could probably get tricky and add the home-key for the given finger to the spec
;; and use the extended-finger-keyboard request, but don't want to mess around with
;; altering specs.
(defmethod move-finger-to-home ((mtr-mod dual-execution-motor-module) spec)
(if (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(aif (current-keyboard)
(let ((hand (verify-single-explicit-value spec 'hand :motor 'move-finger-to-home))
(finger (verify-single-explicit-value spec 'finger :motor 'move-finger-to-home)))
(if (and hand finger)
(let ((device (device-for-hand hand :current nil)))
(if (string-equal (second device) "keyboard")
(let ((home-pos (home-position it hand finger))
(finger-loc (finger-loc-m mtr-mod hand finger :current nil)))
(if (vpt= home-pos finger-loc)
(print-warning "Cannot move the ~s ~s finger to home position because it is already there in move-finger-to-home request." hand finger)
(let ((vector (xy-to-polar finger-loc home-pos)))
(point-finger mtr-mod :hand hand :finger finger :r (vr vector) :theta (vtheta vector) :request-spec spec))))
(print-warning "The ~s hand is not (or will not be) on the keyboard device for move-finger-to-home request." hand)))
(print-warning "Hand and finger not provided for move-finger-to-home request.")))
(print-warning "No keyboard device available for move-finger-to-home request."))
(print-warning "Keyboard device not installed for motor interface in move-finger-to-home request.")))
(extend-manual-requests (move-finger-to-home hand finger) move-finger-to-home)
;;; all-fingers-to-home
;;; A style to move all of the fingers on one or both hands to the home row.
;;; The cost for the action is the max of 200ms, the minimum time set for a
;;; fitts action, and the times for each hand to perform a hand-ply to the home location.
;;; The init-time is not added to the exec time, only to the finish time.
;;;
;;;
;;; Does mark the fingers as busy in the process. (prior to version 5.0 it did not).
;;;
(defclass all-fingers-to-home (hfrt-movement)
nil
(:default-initargs
:style-name :all-home
:hand 'both
:finger-based-style t ; so the fingers are marked busy and released
:finger :dummy))
(defmethod num-to-prepare :around ((self all-fingers-to-home))
;; don't want to count the direction as a possible feature
;; to match previous version
(- (call-next-method) 1))
(defmethod prepare-features ((mtr-mod motor-module) (self all-fingers-to-home))
;; Assuming that the need for a movement has already been determined
;; and the hand is set appropriately (only one even if both specified
;; but one is already there) as well as the installation of a keyboard.
(let ((hand (hand self))
(keyboard-device (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal))
(k (current-keyboard))
l-pos r-pos)
(when (or (eq hand 'both)
(eq hand 'left))
(let* ((keyboard-hand (keyboard-hand-location k 'left-home))
(home-pos (coerce (rest (find 'hand keyboard-hand :key 'first)) 'vector))
(home-offsets (mapcar (lambda (x)
(list (first x) (vector (second x) (third x))))
(remove 'hand keyboard-hand :key 'first)))
(hand-pos (hand-position 'left :current nil))
(vector (xy-to-polar (hand-pos-loc hand-pos) home-pos))
(device (device-for-hand 'left :current nil)))
(setf l-pos (list (make-hand-pos :loc home-pos
:fingers home-offsets
;; none are down so just set that
:other (let ((start (remove 'extended-fingers (hand-pos-other hand-pos) :key 'first)))
(push (list 'extended-fingers
(list 'index nil)
(list 'middle nil)
(list 'ring nil)
(list 'pinkie nil)
(list 'thumb nil))
start)
start)
:device (if (equalp device keyboard-device)
nil
device))
(vr vector)))))
(when (or (eq hand 'both)
(eq hand 'right))
(let* ((keyboard-hand (keyboard-hand-location k 'right-home))
(home-pos (coerce (rest (find 'hand keyboard-hand :key 'first)) 'vector))
(home-offsets (mapcar (lambda (x)
(list (first x) (vector (second x) (third x))))
(remove 'hand keyboard-hand :key 'first)))
(hand-pos (hand-position 'right :current nil))
(vector (xy-to-polar (hand-pos-loc hand-pos) home-pos))
(device (device-for-hand 'right :current nil)))
(setf r-pos (list (make-hand-pos :loc home-pos
:fingers home-offsets
;; none are down so just set that
:other (let ((start (remove 'extended-fingers (hand-pos-other hand-pos) :key 'first)))
(push (list 'extended-fingers
(list 'index nil)
(list 'middle nil)
(list 'ring nil)
(list 'pinkie nil)
(list 'thumb nil))
start)
start)
:device (if (equalp device keyboard-device)
nil
device))
(vr vector)))))
(case hand
(left
(setf (updated-pos self) (first l-pos))
(setf (r self) (second l-pos)))
(right
(setf (updated-pos self) (first r-pos))
(setf (r self) (second r-pos)))
(both
(setf (updated-pos self) (list (first l-pos) (first r-pos)))
(setf (r self) (max (second l-pos) (second r-pos)))))))
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self all-fingers-to-home))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(max
(init-time mtr-mod) ;; to be safe since not adding it here
(randomize-time
(max .2 (fitts mtr-mod (mouse-fitts-coeff mtr-mod) (r self) 4.0))))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self all-fingers-to-home))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(exec-time self))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self all-fingers-to-home))
;; just need to set the hand-position and the device when needed
;; any release events are automatically generated now
(when (or (eq (hand self) 'left) (eq (hand self) 'both))
(let ((new-pos (if (eq (hand self) 'both)
(first (updated-pos self))
(updated-pos self))))
(when (hand-pos-device new-pos)
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-device :time-in-ms t
:module :motor :params (list 'left (hand-pos-device new-pos)) :priority 1 :output nil))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list 'left new-pos)
;; Show an action now
:details (concatenate 'string (symbol-name 'all-fingers-to-home) " " (symbol-name 'left)))))
(when (or (eq (hand self) 'both) (eq (hand self) 'right))
(let ((new-pos (if (eq (hand self) 'both)
(second (updated-pos self))
(updated-pos self))))
(when (hand-pos-device new-pos)
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-device :time-in-ms t
:module :motor :params (list 'right (hand-pos-device new-pos)) :priority 1 :output nil))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list 'right new-pos)
;; Show an action now
:details (concatenate 'string (symbol-name 'all-fingers-to-home) " " (symbol-name 'right))))))
;; all-fingers-to-home
;; Return all the fingers on the specified hand (or both) to the home positions
;; without striking any keys.
(defmethod all-fingers-to-home ((mtr-mod dual-execution-motor-module) spec)
(let ((key (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)))
(if key
(aif (current-keyboard)
(let* ((slot-specs (and (slot-in-chunk-spec-p spec 'hand) (chunk-spec-slot-spec spec 'hand)))
(hands (cond ((zerop (length slot-specs)) '(left right))
((and (= (length slot-specs) 1)
(eql '= (caar slot-specs))
(or (eq (third (car slot-specs)) 'left)
(eq (third (car slot-specs)) 'right)
(eq (third (car slot-specs)) 'both)))
(if (eq (third (car slot-specs)) 'both)
'(left right)
(list (third (car slot-specs)))))
(t (print-warning "Invalid hand specified in all-fingers-to-home request. No action taken."))))
(any-to-move nil))
(when hands
(dolist (hand hands)
;; need to check the hand position before all of the fingers
;; because it could be in an odd state of the hand in the
;; wrong place but with finger offsets to put them in the
;; home positions...
(let* ((hand-pos (hand-position hand :current nil))
(keyboard-hand (if (eq hand 'left)
(keyboard-hand-location it 'left-home)
(keyboard-hand-location it 'right-home)))
(home-pos (coerce (rest (find 'hand keyboard-hand :key 'first)) 'vector))
(vector (xy-to-polar (hand-pos-loc hand-pos) home-pos))
(device (device-for-hand 'left :current nil)))
(if (or (not (equalp device key))
(not (zerop (vr vector)))
(any-finger-down (extension mtr-mod) hand :current nil))
;; hand not on device, not in start position, or some finger down
;; it needs to be moved
(push hand any-to-move)
;; otherwise check all the fingers for matching position
;; know hand is in home position so easiest to check position
(dolist (finger '(index middle ring pinkie thumb))
(let ((home-pos (home-position it hand finger))
(finger-loc (finger-loc hand-pos finger)))
(unless (vpt= home-pos finger-loc)
(pushnew hand any-to-move))))))))
(if any-to-move
(unless (check-jam mtr-mod)
(prepare-movement mtr-mod (make-instance 'all-fingers-to-home
:hand (if (= (length any-to-move) 2)
'both
(first any-to-move))
:request-spec spec)))
(print-warning "All-fingers-to-home request ignored because fingers are already at home positions.")))
(print-warning "No keyboard device available for all-fingers-to-home request."))
(print-warning "Keyboard device not installed for motor interface in all-fingers-to-home request."))))
(extend-manual-requests (all-fingers-to-home hand) all-fingers-to-home)
;; hold-mouse
;; Like click-mouse except that it does not release the button.
;; Just use hold-punch with the right index finger.
(defmethod hold-mouse ((mtr-mod dual-execution-motor-module) spec)
(let* ((model (current-model))
(mouse (find-model-cursor (list model 'mouse))))
(if mouse
(if (equalp (device-for-hand 'right :current nil)
(list "motor" "cursor" "mouse"))
(hold-punch mtr-mod :hand 'right :finger 'index :request-spec spec)
(model-warning "Hold-mouse requested when right hand not at mouse."))
(model-warning "Hold-mouse requested but no mouse device available."))))
(extend-manual-requests (hold-mouse) hold-mouse)
;; release-mouse
;; If the mouse button is being held release it (release does
;; the check for whether the finger is down or not).
(defmethod release-mouse-button ((mtr-mod dual-execution-motor-module) spec)
(let* ((model (current-model))
(mouse (find-model-cursor (list model 'mouse))))
(if mouse
(if (equalp (device-for-hand 'right :current nil)
(list "motor" "cursor" "mouse"))
(release mtr-mod :hand 'right :finger 'index :request-spec spec)
(model-warning "Release-mouse requested when right hand not at mouse."))
(model-warning "Release-mouse requested but no mouse device available."))))
(extend-manual-requests (release-mouse) release-mouse-button)
;; release-all-fingers
;;
;; Will delay if preparation not free.
;; Checks whether either hand requires lifting fingers:
;; - if neither do then it's a no-op
;; - if only one does then only that hand requires execution
;; - if both do then requires execution of both
;;
;; Let the default release mechanism handle the actual releasing.
;; So only need to schedule the update the position.
(defclass release-all-fingers (punch)
nil
(:default-initargs
:style-name :release-all-fingers
:hand 'both
:two-exec-p nil
:feature-slots '(hand)
:release-if-down :free
:finger-based-style t
:finger :dummy
))
(defmethod num-to-prepare :around ((self release-all-fingers))
;; don't want to count the hand to match previous version
(- (call-next-method) 1))
(defmethod prepare-features ((mtr-mod motor-module) (self release-all-fingers))
;; Assuming that the need for a release has already been determined
;; and the hand is set appropriately (only one or both if needed).
(let ((hand (hand self))
left
right)
(when (or (eq hand 'both)
(eq hand 'left))
(setf left (copy-hand-pos (hand-position 'left :current nil)))
;; just note that all fingers are up
(let ((start (remove 'extended-fingers (hand-pos-other left) :key 'first)))
(push (list 'extended-fingers
(list 'index nil)
(list 'middle nil)
(list 'ring nil)
(list 'pinkie nil)
(list 'thumb nil))
start)
(setf (hand-pos-other left) start)))
(when (or (eq hand 'both)
(eq hand 'right))
(setf right (copy-hand-pos (hand-position 'right :current nil)))
;; just note that all fingers are up
(let ((start (remove 'extended-fingers (hand-pos-other right) :key 'first)))
(push (list 'extended-fingers
(list 'index nil)
(list 'middle nil)
(list 'ring nil)
(list 'pinkie nil)
(list 'thumb nil))
start)
(setf (hand-pos-other right) start)))
(case hand
(left
(setf (updated-pos self) left))
(right
(setf (updated-pos self) right))
(both
(setf (updated-pos self) (list left right))))))
(defmethod compute-exec-time ((mtr-mod dual-execution-motor-module) (self release-all-fingers))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(key-release-time mtr-mod))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self release-all-fingers))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(* 2 (burst-time mtr-mod)))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self release-all-fingers))
(when (or (eq (hand self) 'left) (eq (hand self) 'both))
(let ((new-pos (if (eq (hand self) 'both)
(first (updated-pos self))
(updated-pos self))))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list 'left new-pos)
:output nil)))
(when (or (eq (hand self) 'both) (eq (hand self) 'right))
(let ((new-pos (if (eq (hand self) 'both)
(second (updated-pos self))
(updated-pos self))))
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list 'right new-pos)
:output nil)))
;; for backward compatibility keep the same notice in the trace instead of adding it to
;; the set-hand-position actions even though this function doesn't need to do anything now.
(schedule-event-relative (seconds->ms (exec-time self))
'releasing-all-fingers :time-in-ms t :module :motor :output 'medium
:params nil))
(defun releasing-all-fingers ())
(defmethod release-all-fingers ((mtr-mod dual-execution-motor-module) request-spec)
(if (eq (bt:with-lock-held ((state-lock mtr-mod)) (prep-s mtr-mod)) 'busy)
(schedule-event-after-module :motor 'release-all-fingers :maintenance t :output 'medium
:destination :motor :module :motor
:params (list request-spec)
:details "delayed-release-all-fingers")
(let (left right)
(when (any-finger-down (extension mtr-mod) 'left :current nil)
(setf left t))
(when (any-finger-down (extension mtr-mod) 'right :current nil)
(setf right t))
(if (or left right)
(schedule-event-now 'prepare-movement :module :motor
:destination :motor
:params (list (make-instance 'release-all-fingers
:hand (cond ((and left right) 'both)
(left 'left)
(t 'right))
:request-spec request-spec))
:output 'low
:details "release-all-fingers")
(print-warning "Release-all-fingers action called when no fingers need to be released.")))))
(extend-manual-requests (release-all-fingers) release-all-fingers)
;;; A punch with a release based on given time
;;; doesn't use the key-release-time and assumes
;;; that is accounted for in the delay.
(defclass delayed-punch (punch)
((delay :accessor delay :initarg :delay :initform .050))
(:default-initargs
:finger-based-style t
:release-if-down :penalty))
;; the prepare for a punch works fine
;; as does the initial execution time
(defmethod compute-second-exec-time ((mtr-mod dual-execution-motor-module) (self delayed-punch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (delay self) (randomize-time (delay self)))
(+ (init-time mtr-mod)
(key-closure-time mtr-mod)
(delay self))))
(defmethod compute-finish-time ((mtr-mod dual-execution-motor-module) (self delayed-punch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(key-closure-time mtr-mod)
(delay self)
(burst-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod dual-execution-motor-module) (self delayed-punch))
(schedule-event-relative (seconds->ms (exec2-time self)) 'set-hand-position :time-in-ms t :module :motor :output nil
:destination :motor :params (list (hand self) (updated-pos self)))
(schedule-event-relative (seconds->ms (exec-time self))
'set-finger-down :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self))))
(schedule-event-relative (seconds->ms (exec2-time self))
'set-finger-up :time-in-ms t :destination :motor :module :motor :output nil
:params (list (style-name self) (hand self) (finger self) (finger-loc (updated-pos self) (finger self)))))
(defun parse-delay-time (module delay)
(bt:with-recursive-lock-held ((param-lock module))
(cond ((or (null delay) (eq delay 'default)) (d-punch-default module))
((and (numberp delay) (posnum delay))
delay)
((numberp delay)
(model-warning "Non-positive delays not allowed in a delayed-punch. Using default instead.")
(d-punch-default module))
((eq delay 'slow) (d-punch-slow module))
((eq delay 'fast) (d-punch-fast module))
(t (model-warning "Invalid delay value ~s to a delayed-punch. Using default instead" delay)
(d-punch-default module)))))
(defmethod handle-delayed-punch-request ((mtr-mod dual-execution-motor-module) chunk-spec)
(let* ((hand (verify-single-explicit-value
chunk-spec 'hand
:motor 'delayed-punch))
(finger (verify-single-explicit-value
chunk-spec 'finger
:motor 'delayed-punch))
(given-delay (when (slot-in-chunk-spec-p chunk-spec 'delay)
(verify-single-explicit-value
chunk-spec 'delay
:motor 'delayed-punch)))
(delay (parse-delay-time mtr-mod given-delay)))
(if (and hand finger delay)
(unless (check-jam mtr-mod)
(schedule-event-now 'prepare-movement
:destination :motor :module :motor
:params (list (make-instance 'delayed-punch :hand hand :finger finger :delay delay :request-spec chunk-spec))
:output 'low
:details (format nil "~s ~s ~s ~s ~s ~s ~f" 'delayed-punch 'hand hand 'finger finger 'delay delay)))
(print-warning "Invalid delayed-punch request with chunk-spec ~S" chunk-spec))))
(extend-manual-requests (delayed-punch hand finger delay) handle-delayed-punch-request)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 127,442 | Common Lisp | .lisp | 2,286 | 46.384077 | 233 | 0.608697 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 48c9648c15841a9d529031b80f0ea8f2e2e22cfe676fd78755f465885e2fcd96 | 14,287 | [
-1
] |
14,288 | act-touch.lisp | asmaloney_ACT-R/extras/act-touch/act-touch.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Frank Tamborello
;;; Copyright : (c) 2012-4 Cogscent, LLC
;;; Availability: GNU LGPL, see LGPL.txt
;;; Address : Cogscent, LLC
;;; : PMB 7431
;;; : 2711 Centerville Rd, Ste 120
;;; : Wilmington DE, USA 19808-1676
;;; : [email protected]
;;;
;;; Disclaimer : This library is free software; you can redistribute it and/or
;;; : modify it under the terms of the GNU Lesser General Public
;;; : License as published by the Free Software Foundation; either
;;; : version 2.1 of the License, or (at your option) any later version.
;;; : This library 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
;;; : Lesser General Public License for more details.
;;; : You should have received a copy of the GNU Lesser General Public
;;; : License along with this library; if not, write to the Free Software
;;; : Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;; :
;;;
;;; Acknowledgements
;;; : This research is sponsored by Measurement Science and
;;; Engineering grant 60NANB12D134 from the
;;; National Institute of Standards and Technology (NIST).
;;; Special acknowledgements are due to Dr. Ross Micheals and
;;; Dr. Kristen K. Greene of NIST's Information Technology
;;; Laboratory.
;;; Thanks also to Dr. Michael D. Byrne, upon whose experiment
;;; library code I based the device code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : act-touch.lisp
;;; Revision : 16
;;;
;;; Description : Add a new device called "touch" which represents a touch screen/pad
;;; : and defines new motor actions for using that device.
;;;
;;;
;;; Usage : Call (require-extra "act-touch") in the model file which needs it.
;;;
;;; Bugs : None known
;;;
;;; To do : [ ] Add checks to tap-hold and tap-release for current finger state
;;; : and warn when inconsistent.
;;;
;;;
;;; Issues :
;;; 2014.10.05 fpt
;;; : 1. Long-term, it'd probably make more sense to add a z-dimension to hand locations.
;;; For now movement time methods use "z-index", a slot of the device object.
;;;
;;; 2012.06.14 fpt
;;; : 1. What's the target of a swipe? Is it the entire side of the
;;; device?
;;; 2012.06.14 fpt
;;; : 2. There's something funny about using Fitts' Law to compute
;;; pinch execution time. How wide should the target be? That's sort
;;; of a nonsensical question to ask in the context of a pinch, but
;;; Fitts' Law requires a width and on the surface the pinch movement
;;; seems fairly corrected-ballistic like other pointing movements.
;;; For now let's assume that the thumb is the target-yes, even for
;;; reverse-pinches-and that the typical human thumb is 1 inch (72px
;;; @ 72ppi) wide. So the pinch class has a slot for thumb-width
;;; initializing to 72, which gets passed to the fitts function for
;;; calculating pinch execution time.
;;; 2012.08.18 fpt
;;; : 3. Does it make more sense to construct two-, three-, and
;;; four-fingered swipes as different movement styles instead of
;;; one movement style with a feature specifying the number of
;;; fingers?
;;; 2012.08.18 fpt
;;; : 4. What about qualitatively different swipes used for
;;; scrolling precisely starting and ending within one page
;;; vs page turning?
;;;
;;; ----- History -----
;;; 2012.06.01 fpt 1
;;; : Inception: Extend the motor module with a movement style that
;;; allows ACT-R to respond to that style's request and produce some
;;; model output: swipe.
;;; 2012.06.02 fpt 2
;;; : Implement other movement styles: tap, pinch (also works for
;;; reverse-pinch), and rotate.
;;; 2012.06.07 fpt 3
;;; : Gave tap its real execution time computation, removed the r &
;;; theta features since it taps in place, and gave it a stub device
;;; method.
;;; 2012.06.14 fpt 4
;;; : Defined additional multitouch movement styles with assumed-to-
;;; be-sensible time computations: peck-tap, peck-tap-recoil, tap-
;;; hold, tap-release, tap-drag-release, swipe, pinch, rotate.
;;; 2012.06.19 fpt 5
;;; : The Device is now instrumented to record things like time and
;;; location of taps. It uses the virtual-experiment-window library,
;;; adapted by me from Mike Byrne's experiment-window4 library.
;;;
;;; 2012.06.29 fpt 6
;;; Demo task is now a procedure-window rather than a timed-exp-window so that the
;;; scope of one "trial" is one performance of one multi-action task rather than
;;; one performance of one action.
;;;
;;; 2012.07.13 fpt 7
;;; Move-hand-touch allows the model to move its hand to a visual-location or
;;; a visual-object, just like move-cursor. ...except that noisy movement
;;; is not yet implemented.
;;;
;;; 2012.08.18 fpt 8
;;; Wrote a feat-differences method for tap since it didn't inherit it from a parent
;;; movement-style.
;;;
;;; 2012.08.26 fpt 9
;;; Increased the length of the procedure from 1 to 8 steps & made some of the steps
;;; require other gestures besides tap, namely swipe, rotate, & pinch.
;;;
;;; 2012.09.29 fpt 10
;;; 1. Changed license from public domain to LGPL.
;;; 2. Forked the virtual multitouch display device and
;;;demonstration model into their own files.
;;;
;;; 2013.04.03 fpt 11
;;; Quickly hacked move-hand-touch so it could generate some noisy movements
;;; probability of a miss considering index finger tip area and target area
;;;
;;; 2013.11.21 fpt 12
;;; 1. Incorporate Melissa Gallagher's dual-distribution noisy movement mechanism,
;;; based on May & Byrne.
;;; 2. Push ':virtual-multitouch-device onto *features* to ease checking for &
;;; loading
;;;
;;; 2014.10.04 fpt 13
;;; Update to make compatible with ACT-R 6.1:
;;; 1. Move-hand-touch conforms to the new argument list of verify-single-explicit-
;;; value introduced with ACT-R 6.1.
;;;
;;; 2. A new abstraction became available in ACT-R 6.1, handle-style-request,
;;; to schedule the event for a defined movement style. Now all ACT-Touch's
;;; defined movement styles, such as tap, use that instead of their own
;;; request methods.
;;;
;;; 2014.12.01 Dan Bothell
;;; Added an (unless (fboundp 'aif) ...) around the macro definition since it
;;; should already be defined in the main ACT-R code.
;;;
;;; 2015.05.20 Dan Bothell
;;; * Use the device specific coordinate names (even though this has its own
;;; device) and make sure that xy-loc calls pass the vision module in as well.
;;;
;;; * The approach-width call in move-hand-touch needs to pass the vision module now.
;;;
;;; 2015.06.05 Dan Bothell
;;; * Changed all scheduling calls to use milliseconds instead of seconds to
;;; avoid the scheduler doing the conversion which requires all the safety checks.
;;;
;;; 2015.08.14 Dan Bothell
;;; * Changed rand-time calls to randomize-time since rand-time was depricated
;;; a while ago and I've finally decided to remove it.
;;; 2015.09.23 Dan Bothell
;;; * Updated the actions which don't use the "default" style mechanisms to
;;; complete the request for use with the new utility learning credit assignment
;;; approach.
;;; 2016.03.14 Dan Bothell
;;; * Added the provide and a compile-and-load for the multi-touch device so that
;;; require-extra gets both.
;;;
;;; 2018.10.24 Dan Bothell
;;; * First step before updating for 7.x is to apply some changes which were made
;;; to the 7.0 version as noted in these comments:
;;;
;;; 2017.11.04 fpt 15
;;; I deleted index-z so that act-touch now works with devices other than objects
;;; with an index-z slot, such as ACT-Droid.
;;;
;;; 2018.02.06 fpt 16
;;; Implement a new feature to allow the model to "consciously" control swiping
;;; swipe-speed: an integer from the set [1,5], where 1 is slowest and 5 is fastest.
;;;
;;; Note that this update breaks old code calling the swipe movement command
;;; without specifying a swipe-speed feature: ACT-R simply won't execute the swipe
;;; command, instead proceeding otherwise.
;;;
;;; Note: I lack a principled way to map user intention of swiping speed to
;;; computing its execution time, so I'll just do what's expedient and otherwise
;;; seems at least not stupidly unreasonable: I give the Fitts function a
;;; coefficient of difficulty that decreases with swipe-speed:
;;; (/ 1 (expt (swipe-speed self) 2))
;;;
;;; Note: I think swipe should allow for a nice, wide target parameter for the
;;; Fitts function, like the entire side of the device to which the model is
;;; swiping. For when you run with a NIL device, EG for testing, I gave it a
;;; value of 500. Replace that in compute-exec-time with a call to the width
;;; of your target.
;;;
;;; 2018.10.25 Dan Bothell
;;; * To better support some of those changes, also added a module so that one
;;; can specify parameters for finger height, thumb width, default swipe speed,
;;; and swipe target width and so that the user setting of :pixels-per-inch is
;;; used instead of assuming 72.
;;; * Removed *index-finger-tip-size* since it's not used anywhere.
;;; * Added a hand slot to move-hand-touch since all the other commands allow for
;;; either hand to perform the action, but there's no way for the model to move
;;; its left hand to do them.
;;; * Added the width for Fitts law to the index-thumb movements, using a thumb
;;; width for all of them as noted in issue 2.
;;; * Use the indicated hand and finger for the exec-time of a rotate, but why
;;; is the distance for Fitts law the distance between finger and thumb and
;;; not the distance traveled to rotate by the indicated angle?
;;; Changed that so the distance is the distance traveled and the target width
;;; is 5 degrees of the movement (target angle +/- 2.5 degrees which could
;;; be made noisy and parameterized but keeping it simple for now).
;;; * Finger offsets need to be adjusted when initially moving the hand because
;;; the default is a distance of 1 from each other (which is pixels for this
;;; interface). Added another parameter, finger-spacing which is the distance
;;; in inches between adjacent fingers, and the thumb is two down and one
;;; over from the index finger (same as the default offsets for the keyboard
;;; but now in finger spaces). Those are then converted to pixels for the
;;; offsets. Using 3/4" as the default based on the default keyboard spacing
;;; and adding a start-hand-at-touch command to handle setting things
;;; appropriately.
;;; 2018.10.26 Dan Bothell [2.0]
;;; * Track the module version for my updates.
;;; * Start the actual 7.x changes.
;;; * Add the ACT-R package checks.
;;; * Don't load the virtual-multitouch-device file anymore.
;;; * Don't bother checking for aif because it's always available with ACT-R.
;;; * Use the module to hold the device's info as well -- only one touch device
;;; per model and each model has its own.
;;; * Add a lock to the module and protect everything with that lock.
;;; * Keep track of finger positions directly in the module/device because the
;;; location of the device needs to be in the standard coordinates (keyspaces)
;;; so that moving the hands to/from the device is timed appropriately. Could
;;; still use the motor module's finger offsets for positions, but this is a
;;; simpler approach. Make the position for a touch device 6,9 (below the
;;; space bar roughly where a touch pad on a laptop would be).
;;; * Use undocumented internal AGI functionality to access window info to both
;;; check that something is an existing window and get its shape info.
;;; 2018.10.29 Dan Bothell
;;; * Add the signals that are generated by the device.
;;; * !! Currently using the same width of 4 as other devices for moving the
;;; hand to it, but should that be determined from an associated window and/or
;;; be configurable?
;;; * !! No way to know if the hand moves away from the device -- general issue
;; that will need to be fixed and then updated here!
;;; * Added the hand-to-touch request.
;;; 2018.10.30 Dan Bothell
;;; * Added the touch-drag-delay parameter to slow down move-hand-touch actions
;;; if any finger on that hand is down with a value of .8 being the default for
;;; t which works well for mouse moves to match the data from:
;;;
;;; I. Scott MacKenzie, Abigail Sellen, and William A. S. Buxton. 1991.
;;; A comparison of input devices in element pointing and dragging tasks.
;;; In Proceedings of the SIGCHI Conference on Human Factors in
;;; Computing Systems (CHI '91), Scott P. Robertson, Gary M. Olson,
;;; and Judith S. Olson (Eds.). ACM, New York, NY, USA, 161-166.
;;; DOI: http://dx.doi.org/10.1145/108844.108868
;;;
;;; * Record the peck and cursor fitts-coeff params in touch so don't need to
;;; grab two locks in exec-time computations.
;;; * Added a rotation target-width parameter.
;;; * Added all the finger position changes to the output events with some
;;; simple assumptions.
;;; 2018.10.31 Dan Bothell
;;; * Cleaned up the device and motor action code so that the motor actions
;;; work for other installed devices.
;;; * Start-hand-at-touch notifies motor of the change instead of calling the
;;; motor functions directly.
;;; 2018.11.01 Dan Bothell
;;; * Finished the separation of the device from the motor commands.
;;; * Only notify the device of finger positions/moves if there is a device.
;;; 2018.11.02 Dan Bothell
;;; * Need to not hold the module's lock when notifying since the device's
;;; interface function also needs it and just splitting it into separate
;;; device and parameter locks won't work since the interface function needs
;;; access to both types of info.
;;; * Changed the AGI window notifications to be showfinger and removefinger
;;; to make it easier for the Environment visible virtuals to handle them.
;;; * Extra safety check required because exp window needs to be installed
;;; to be usable with touch device.
;;; 2018.11.05 Dan Bothell
;;; * A release shouldn't be charged for the Fitts' time since it's not a
;;; targeted action. Instead, it's now just assessed a burst cost.
;;; * Similarly, the tap/tap-hold should really have a target so that there's
;;; a real width for the motion instead of the default which is actually
;;; a single pixel since the distance in pixels is used. To adjsut for that,
;;; using the distance in DVA instead.
;;; * Remove-touch tests that the window is still installed because there are
;;; possible ordering issues on how they're removed (but could that leave
;;; the images unnecessarily?).
;;; * Always round the x and y coords when setting them.
;;; 2018.11.06 Dan Bothell
;;; * Fixed a bug with specifying the hand in move-hand-touch-request.
;;; * Only apply the drag-delay if the hand is using a touch device which
;;; reports that there is a finger down.
;;; 2018.11.08 Dan Bothell
;;; * Provide an external command for start-hand-at-touch.
;;; 2020.01.13 Dan Bothell [2.1]
;;; * Remove lambda from module interface functions.
;;; 2020.03.30 Dan Bothell [3.0]
;;; * Apply the fixes needed to address the preparation/processor free issues.
;;; * Requires using the hand-pos struct instead of just being able to interact
;;; with the interface.
;;; * Start-hand-at-touch actually moves the hand to the appropriate position.
;;; * Index-thumb uses any finger and passes that to the interface (basically
;;; a one finger swipe).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;; Feature check if someone wants it, but require-extra is the recommended
;; way to load it which will only load if needed from the default location.
(pushnew :act-touch *features*)
;;; Module to support parameters and device internals.
(defstruct touch-module installed window right-start left-start left-start-default right-start-default
(fingers (make-array '(2 5))) ; hand left=0 right=1,finger index=0 -- thumb=4 value is list x,y,z (z is 0 (down) or 1 (up))
(hands (make-array 2)) ; t/nil is hand on device?
show-fingers
(position #(6 9))
height swipe-speed swipe-width ppi thumb-width finger-spacing
noise drag-delay
cursor-coeff
peck-coeff
rotate-width
(lock (bt:make-recursive-lock "touch")))
;;; support code and name to index functions
(defgeneric noisy-loc-em? (xy-loc w theta)
(:documentation "If the Motor Module is set up for it, make the output location noisy."))
;;; NOISY-LOC-em? [Method]
;;; Description : Adds noise to the output location if noise is on.
;;; : Rather than adding the same amount of error on both axis, more is on axis than
;;; : off axis. uses weighted-error to determine how much it is
;;;
(defmethod noisy-loc-em? ((xy-loc vector) (w number) (theta number))
(if (zerop w)
xy-loc
(weighted-error xy-loc w theta)))
;;; WEIGHTED-ERROR [Method]
;;; Description : samples from the normal distribution with different error on axis and off axis
;;; : based on work by may and byrne (see eq 6)
;;; : Treats the error area as a circle with a diameter of pixw
(defmethod weighted-error ((xy-loc vector) (pixw number) (theta number))
;(model-output "pixw: ~a theta: ~a~%" pixw theta)
(let ((on-noise (act-r-noise (* (/ pixw 4.133) (/ (sqrt 3) pi))))
(off-noise (act-r-noise (* 0.75 (/ pixw 4.133) (/ (sqrt 3) pi)))))
(polar-move-xy
xy-loc
(vector
(sqrt
(+ (* on-noise on-noise) (* off-noise off-noise)))
(+ theta (atan (/ off-noise on-noise)))))))
(defun valid-hand (h)
(case h
(left 0)
(right 1)))
(defun valid-finger (f)
(case f
(index 0)
(middle 1)
(ring 2)
(pinkie 3)
(thumb 4)))
;;; Module code
(defun touch-params (module param)
(bt:with-recursive-lock-held ((touch-module-lock module))
(if (consp param)
(case (car param)
(:finger-height
(setf (touch-module-height module) (cdr param)))
(:swipe-speed
(setf (touch-module-swipe-speed module) (cdr param)))
(:swipe-width
(setf (touch-module-swipe-width module) (cdr param)))
(:thumb-width
(setf (touch-module-thumb-width module) (cdr param)))
(:finger-spacing
(setf (touch-module-finger-spacing module) (cdr param)))
(:pixels-per-inch
(setf (touch-module-ppi module) (cdr param)))
(:left-start
(setf (touch-module-left-start-default module) (cdr param)))
(:right-start
(setf (touch-module-right-start-default module) (cdr param)))
(:show-fingers
(setf (touch-module-show-fingers module) (cdr param)))
(:touch-noise
(setf (touch-module-noise module) (cdr param)))
(:touch-drag-delay
(setf (touch-module-drag-delay module) (cdr param)))
(:cursor-fitts-coeff
(setf (touch-module-cursor-coeff module) (cdr param)))
(:peck-fitts-coeff
(setf (touch-module-peck-coeff module) (cdr param)))
(:touch-rotate-width
(setf (touch-module-rotate-width module) (cdr param))))
(case param
(:finger-height
(touch-module-height module))
(:swipe-speed
(touch-module-swipe-speed module))
(:swipe-width
(touch-module-swipe-width module))
(:finger-spacing
(touch-module-finger-spacing module))
(:thumb-width
(touch-module-thumb-width module))
(:left-start
(touch-module-left-start-default module))
(:right-start
(touch-module-right-start-default module))
(:show-fingers
(touch-module-show-fingers module))
(:touch-noise
(touch-module-noise module))
(:touch-drag-delay
(touch-module-drag-delay module))
(:touch-rotate-width
(touch-module-rotate-width module))))))
(defun create-touch-module (x)
(declare (ignore x))
(make-touch-module))
(defun touch-hand-start-value-test (x)
(and (listp x)
(= (length x) 2)
(every 'integerp x)))
(defun swipe-speed-value-test (x)
(and (integerp x) (<= 1 x 5)))
(define-module-fct :touch-interface nil
(list
(define-parameter :finger-height :default-value 1 :valid-test 'posnum :warning "A positive number" :documentation "Default height of the finger above the screen in inches.")
(define-parameter :swipe-speed :default-value 3 :valid-test 'swipe-speed-value-test :warning "An integer from 1-5" :documentation "Default speed for a swipe action.")
(define-parameter :swipe-width :default-value 500 :valid-test 'posnum :warning "A positive number" :documentation "Default width of the target for computing the cost with Fitts law in pixels.")
(define-parameter :thumb-width :default-value 1 :valid-test 'posnum :warning "A positive number" :documentation "Width of the model's thumb in inches used for computing the cost with Fitts law in pinch and rotate actions.")
(define-parameter :finger-spacing :default-value .75 :valid-test 'posnum :warning "A positive number" :documentation "Distance between finger tips measured in inches.")
(define-parameter :left-start :default-value (list 0 300) :valid-test 'touch-hand-start-value-test
:warning "A list of two integers" :documentation "Default starting location for left index finger.")
(define-parameter :right-start :default-value (list 1024 300) :valid-test 'touch-hand-start-value-test
:warning "A list of two integers" :documentation "Default starting location for right index finger.")
(define-parameter :show-fingers :default-value nil :valid-test 'tornil :warning "t or nil" :documentation "Whether to send finger information to the associated experiment window for possible display.")
(define-parameter :touch-noise :default-value nil :valid-test 'tornil :warning "t or nil" :documentation "Whether to add noise to move-hand-touch target location.")
(define-parameter :touch-drag-delay
:valid-test 'posnumorbool
:warning "T, nil, or a positive number"
:default-value nil
:documentation "Control order increment for touch drag actions.")
(define-parameter :touch-rotate-width
:valid-test 'posnum
:warning "positive number"
:default-value 5
:documentation "Size of the target width for a rotate action measured in degrees of the rotation.")
(define-parameter :pixels-per-inch :owner nil)
(define-parameter :cursor-fitts-coeff :owner nil)
(define-parameter :peck-fitts-coeff :owner nil))
:creation 'create-touch-module
:params 'touch-params
:version "3.0"
:documentation "Module to support the Touch device and corresponding motor extensions.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; User commands
;;; Use this to position the hand before running the model on a touch device
(defun start-hand-at-touch (&optional (hand 'right))
(verify-current-model
"No current model when trying to use start-hand-at-touch."
(let ((installed-touch (find "touch" (current-devices "motor") :test 'string-equal :key 'second)))
(unless installed-touch
(print-warning "Installing a default touch device for start-hand-at-touch.")
(setf installed-touch (install-device '("motor" "touch"))))
(let ((module (get-module :touch-interface)))
(if module
(if (valid-hand hand)
(let ((pos (bt:with-lock-held ((touch-module-lock module)) (touch-module-position module))))
(notify-interface "motor" (list 'set-hand-device hand installed-touch))
(notify-interface "motor" (list 'set-hand-position hand (px pos) (py pos)))
)
(print-warning "Invalid hand ~s in call to start-hand-at-touch." hand))
(print-warning "Touch interface not available. Could not start hands there."))))))
(defun external-start-hand-at-touch (&optional (hand 'right))
(start-hand-at-touch (decode-string-names hand)))
(add-act-r-command "start-hand-at-touch" 'external-start-hand-at-touch "Move a model's hand to the 'touch' device before running it. Params: { [ right | left ]}")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The actual device
(defun install-touch (device-list)
(let ((interface-name (first device-list))
(details (third device-list)))
(if (string-equal interface-name "motor")
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(if (touch-module-installed touch)
(print-warning "A touch device is already installed and only one can be installed at a time.")
(cond ((null details)
(setf (touch-module-window touch) nil)
(setf (touch-module-left-start touch)
(touch-module-left-start-default touch))
(setf (touch-module-right-start touch)
(touch-module-right-start-default touch))
(setf (aref (touch-module-hands touch) 0) nil)
(setf (aref (touch-module-hands touch) 1) nil)
(setf (touch-module-installed touch) device-list))
((and (listp details)
(= (length details) 2)
(every (lambda (x)
(listp x)
(= (length x) 2)
(every 'integerp x))
details))
(setf (touch-module-window touch) nil)
(setf (touch-module-left-start touch)
(first details))
(setf (touch-module-right-start touch)
(second details))
(setf (aref (touch-module-hands touch) 0) nil)
(setf (aref (touch-module-hands touch) 1) nil)
(setf (touch-module-installed touch) device-list))
(t
(aif (determine-exp-window (agi-component) details)
(if (find details (current-devices "vision") :test 'equalp)
(progn
(setf (touch-module-window touch) details)
(setf (touch-module-left-start touch)
(list (x-pos it) (+ (y-pos it) (round (height it) 2))))
(setf (touch-module-right-start touch)
(list (+ (x-pos it) (width it)) (+ (y-pos it) (round (height it) 2))))
(setf (aref (touch-module-hands touch) 0) nil)
(setf (aref (touch-module-hands touch) 1) nil)
(setf (touch-module-installed touch) device-list))
(print-warning "Experiment window for touch device must be installed before the touch device. Touch device not installed."))
(print-warning "Invalid details ~s provided when installing a touch device. No device installed." details)))))))
(print-warning "Touch device can only be installed for the motor interface, but given ~s." interface-name))))
(add-act-r-command "install-touch-device" 'install-touch "Internal command for installing a touch device. Do not call.")
(defun remove-touch (device-list)
(declare (ignore device-list))
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(setf (touch-module-installed touch) nil)
(awhen (and (touch-module-show-fingers touch) (touch-module-window touch)
(find (touch-module-window touch) (current-devices "vision") :test 'equalp))
(dolist (h '(left right))
(when (aref (touch-module-hands touch) (valid-hand h))
(dolist (x '(index middle ring pinkie thumb))
(notify-device it (list "removefinger" (string-downcase (symbol-name h)) (string-downcase (symbol-name x))))))))
(setf (aref (touch-module-hands touch) 0) nil)
(setf (aref (touch-module-hands touch) 1) nil))
t))
(add-act-r-command "remove-touch-device" 'remove-touch "Internal command for uninstalling a touch device. Do not call.")
;; The device calls the actions which can be monitored, and records the finger positions.
;; In this way the extensions operate completely through notifications which means it's
;; possible for a different device to respond to those actions and you don't
;; have to install a touch device to actually use the new motor actions.
;;
;; The touch device also sends these notifications to an associated experiment window:
;; (showfinger <hand> <finger> x y z) for any move or up/down change
;; (removefinger <hand> <finger>) when hand moves away from device
(defun touch-device-interface (device-list features)
;; possible notifications
;; (finger-position hand finger)
;; (set-finger-position hand finger x y)
;; (set-finger-up hand finger)
;; (set-finger-down hand finger)
;; (finger-down hand finger)
;; (any-finger-down hand)
;; Rest will be a list with all of these:
;; ( (style { tap | tap-hold | tap-release | swipe | move-hand-touch | index-thumb | pinch | rotate} (hand {left | right})
;; and some of these as appropriate for the style:
;; (finger { index | middle | ring | pinkie | thumb}) (loc <> <>) (distance <>) (speed <>) (direction <>) (count <>)) (range <> <>))
;;
(let ((touch (get-module :touch-interface))) ; since only one per model makes it easy
(bt:with-recursive-lock-held ((touch-module-lock touch))
(if (null (touch-module-installed touch))
(print-warning "Notification ~s sent to touch device ~s but it is not currently installed." features device-list)
(cond ((and (eq (first features) 'finger-position)
(= (length features) 3)
(valid-hand (second features))
(valid-finger (third features)))
(subseq (aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features))) 0 2))
((and (eq (first features) 'finger-down)
(= (length features) 3)
(valid-hand (second features))
(valid-finger (third features)))
(zerop (third (aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features))))))
((and (eq (first features) 'any-finger-down)
(= (length features) 2)
(valid-hand (second features)))
(some (lambda (x) (zerop (third x)))
(mapcar (lambda (x) (aref (touch-module-fingers touch) (valid-hand (second features)) x)) '(0 1 2 3 4))))
((and (eq (first features) 'set-finger-down)
(= (length features) 3)
(valid-hand (second features))
(valid-finger (third features))
(aref (touch-module-hands touch) (valid-hand (second features))))
(setf (third (aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))) 0)
(awhen (and (touch-module-show-fingers touch) (touch-module-window touch))
(notify-device it (append (list "showfinger" (string-downcase (symbol-name (second features))) (string-downcase (symbol-name (third features))))
(aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))))))
((and (eq (first features) 'set-finger-up)
(= (length features) 3)
(valid-hand (second features))
(valid-finger (third features))
(aref (touch-module-hands touch) (valid-hand (second features))))
(setf (third (aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))) 1)
(awhen (and (touch-module-show-fingers touch) (touch-module-window touch))
(notify-device it (append (list "showfinger" (string-downcase (symbol-name (second features))) (string-downcase (symbol-name (third features))))
(aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))))))
((and (eq (first features) 'set-finger-position)
(= (length features) 5)
(valid-hand (second features))
(valid-finger (third features))
(aref (touch-module-hands touch) (valid-hand (second features)))
(integerp (fourth features))
(integerp (fifth features)))
(setf (first (aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))) (round (fourth features)))
(setf (second (aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))) (round (fifth features)))
(awhen (and (touch-module-show-fingers touch) (touch-module-window touch))
(notify-device it (append (list "showfinger" (string-downcase (symbol-name (second features))) (string-downcase (symbol-name (third features))))
(aref (touch-module-fingers touch) (valid-hand (second features)) (valid-finger (third features)))))))
((and (every 'listp features)
(second (find 'style features :key 'first))
(find (second (find 'style features :key 'first)) '(tap tap-hold tap-release swipe index-thumb move-hand-touch pinch rotate)))
(case (second (find 'style features :key 'first))
(tap
(let* ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first))))
(if (and m (valid-hand h) (valid-finger f))
(let* ((loc (aref (touch-module-fingers touch) (valid-hand h) (valid-finger f)))
(x (first loc))
(y (second loc)))
(with-model-eval m
(schedule-event-now "touch-tap" :params (list m h f x y) :output t :module :touch-interface :maintenance t)
(awhen (touch-module-window touch) ;; if associated with an experiment window generate a mouse-click
;; signal -- any experiment window or other monitor will detect it
(schedule-event-now "click-mouse" :params (list m (list x y) f) :output t :module :touch-interface :maintenance t))))
(print-warning "Touch device received invalid tap action having features ~s." features))))
(tap-hold
(let* ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first))))
(if (and m (valid-hand h) (valid-finger f))
(let* ((loc (aref (touch-module-fingers touch) (valid-hand h) (valid-finger f)))
(x (first loc))
(y (second loc)))
(with-model-eval m
(schedule-event-now "touch-tap-hold" :params (list m h f x y) :output t :module :touch-interface :maintenance t)))
(print-warning "Touch device received invalid tap-hold action having features ~s." features))))
(tap-release ;; assume that the motor actions determine the validity of the release action i.e. the finger is already down
(let* ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first))))
(if (and m (valid-hand h) (valid-finger f))
(let* ((loc (aref (touch-module-fingers touch) (valid-hand h) (valid-finger f)))
(x (first loc))
(y (second loc)))
(with-model-eval m
(schedule-event-now "touch-tap-release" :params (list m h f x y) :output t :module :touch-interface :maintenance t)))
(print-warning "Touch device received invalid tap-release action having features ~s." features))))
(swipe
(let ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first)))
(dist (second (find 'distance features :key 'first)))
(dir (second (find 'direction features :key 'first)))
(c (second (find 'count features :key 'first)))
(s (second (find 'speed features :key 'first)))
)
(if (and m (valid-hand h) (valid-finger f) (numberp dist) (numberp dir) (numberp c) (numberp s))
(with-model-eval m
(schedule-event-now "touch-swipe" :params (list m h f dist dir c s) :output t :module :touch-interface :maintenance t))
(print-warning "Touch device received invalid swipe action having features ~s." features))))
(index-thumb
(let ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first)))
(dist (second (find 'distance features :key 'first)))
(dir (second (find 'direction features :key 'first))))
(if (and m (valid-hand h) (valid-finger f) (numberp dist) (numberp dir))
(with-model-eval m
(schedule-event-now "touch-index-thumb" :params (list m h f dist dir) :output t :module :touch-interface :maintenance t))
(print-warning "Touch device received invalid index-thumb action having features ~s." features))))
(move-hand-touch
(let* ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(loc (rest (find 'loc features :key 'first)))
(x (first loc))
(y (second loc)))
(if (and m (valid-hand h) (numberp x) (numberp y))
(with-model-eval m
(schedule-event-now "touch-point" :params (list m h x y) :output t :module :touch-interface :maintenance t))
(print-warning "Touch device received invalid move-hand-touch action having features ~s." features))))
(pinch
(let* ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first)))
(r (rest (find 'range features :key 'first)))
(start (first r))
(end (second r)))
(if (and m (valid-hand h) (valid-finger f) (numberp start) (numberp end))
(with-model-eval m
(schedule-event-now "touch-pinch" :params (list m h f start end) :output t :module :touch-interface :maintenance t))
(print-warning "Touch device received invalid pinch action having features ~s." features))))
(rotate
(let ((m (second (find 'model features :key 'first)))
(h (second (find 'hand features :key 'first)))
(f (second (find 'finger features :key 'first)))
(dir (second (find 'direction features :key 'first))))
(if (and m (valid-hand h) (valid-finger f) (numberp dir))
(with-model-eval m
(schedule-event-now "touch-rotate" :params (list m h f dir) :output t :module :touch-interface :maintenance t))
(print-warning "Touch device received invalid rotate action having features ~s." features))))))
(t
(print-warning "Invalid notification ~s sent to touch device ~s" features device-list)))))))
(add-act-r-command "touch-device-interface" 'touch-device-interface "Internal command for the touch device notifications. Do not call.")
(defun hand-moved-to-touch (device hand)
(declare (ignore device))
(let ((touch (get-module :touch-interface)))
(when touch
(bt:with-recursive-lock-held ((touch-module-lock touch))
(let* ((dist (* (touch-module-ppi touch) (touch-module-finger-spacing touch)))
(start (if (eq hand 'right)
(touch-module-right-start touch)
(touch-module-left-start touch)))
(sx (round (first start)))
(sy (round (second start)))
(window (and (touch-module-show-fingers touch)
(touch-module-window touch)))
(finger-offsets (if (eq hand 'right)
(right-standard-offsets)
(left-standard-offsets))))
;; indicate the hand is on the device
(setf (aref (touch-module-hands touch) (valid-hand hand)) t)
(dolist (f finger-offsets)
(let ((p (list (round (+ (* (px (second f)) dist) sx)) (round (+ (* (py (second f)) dist) sy)) 1)))
(setf (aref (touch-module-fingers touch) (valid-hand hand) (valid-finger (first f))) p)
(when window
(notify-device window (list "showfinger"
(string-downcase (symbol-name hand))
(string-downcase (symbol-name (first f)))
(first p)
(second p)
1))))))))))
(add-act-r-command "touch-set-hand" 'hand-moved-to-touch "Internal command for the touch device. Do not call.")
(defun hand-moved-away-from-touch (device hand)
(declare (ignore device))
(let ((touch (get-module :touch-interface)))
(when touch
(bt:with-recursive-lock-held ((touch-module-lock touch))
(awhen (and (aref (touch-module-hands touch) (valid-hand hand)) ;; should always be true since hand was there
(touch-module-show-fingers touch)
(touch-module-window touch))
(dolist (x '(index middle ring pinkie thumb))
(notify-device it (list "removefinger" (string-downcase (symbol-name hand)) (string-downcase (symbol-name x))))))
;; indicate the hand is no longer on device
(setf (aref (touch-module-hands touch) (valid-hand hand)) nil)))))
(add-act-r-command "touch-unset-hand" 'hand-moved-away-from-touch "Internal command for the touch device. Do not call.")
(define-device "touch" "install-touch-device" "remove-touch-device" "touch-device-interface" "touch-set-hand" "touch-unset-hand")
(add-act-r-command "touch-index-thumb" nil "Signal that an index-thumb action has been performed on the touch device. Params: model hand finger distance direction")
(add-act-r-command "touch-point" nil "Signal that a hand has moved to a new locaiton on the touch device. Params: model hand x y")
(add-act-r-command "touch-swipe" nil "Signal that a swipe action has been performed on the touch device. Params: model hand initial-finger distance direction finger-count speed")
(add-act-r-command "touch-tap" nil "Signal that a finger tap has been performed on the touch device. Params: model hand finger x y")
(add-act-r-command "touch-tap-hold" nil "Signal that a finger tap-hold has been performed on the touch device. Params: model hand finger x y")
(add-act-r-command "touch-tap-release" nil "Signal that a finger tap-release has been performed on the touch device. Params: model hand finger x y")
(add-act-r-command "touch-pinch" nil "Signal that a pinch has been performed on the touch device. Params: model hand finger start-width end-width")
(add-act-r-command "touch-rotate" nil "Signal that a rotate has been performed on the touch device. Params: model hand finger rotate-angle")
;;;; ---------------------------------------------------------------------- ;;;;
;;;; ACT-R Motor Module Extension
;;;; ---------------------------------------------------------------------- ;;;;
;;; These are general actions which could be used with other devices.
;;;
;;; First create a function which will get the finger positions from
;;; the device, or if it doesn't return any use the default motor-module
;;; position.
(defun touch-finger-position (hand finger &key (current t))
(let ((device (device-for-hand hand :current current)))
(if (and device (string-equal (second device) "touch"))
(progn
(if current
(coerce (notify-device device (list 'finger-position hand finger)) 'vector)
(let* ((hand-pos (hand-position hand :current nil))
(touch-pos (find 'touch-positions (hand-pos-other hand-pos) :key 'first))
(f (find finger (rest touch-pos) :key 'first)))
(if f
(vector (second f) (third f))
(coerce (notify-device device (list 'finger-position hand finger)) 'vector)))))
(print-warning "Touch-finger-position called for ~s ~s but hand not on touch device." hand finger))))
(defun touch-finger-down (hand finger &key (current t))
(let ((device (device-for-hand hand :current current)))
(if (and device (string-equal (second device) "touch"))
(progn
(if current
(notify-device device (list 'finger-down hand finger))
(let* ((hand-pos (hand-position hand :current nil))
(touch-pos (find 'touch-positions (hand-pos-other hand-pos) :key 'first))
(f (find finger (rest touch-pos) :key 'first)))
(if f
(zerop (fourth f))
(notify-device device (list 'finger-down hand finger))))))
(print-warning "Touch-finger-down called for ~s ~s but hand not on touch device." hand finger))))
(defun touch-any-finger-down (hand &key (current t))
(let ((device (device-for-hand hand :current current)))
(if (and device (string-equal (second device) "touch"))
(progn
(if current
(notify-device device (list 'any-finger-down hand))
(let* ((hand-pos (hand-position hand :current nil))
(touch-pos (find 'touch-positions (hand-pos-other hand-pos) :key 'first))
)
(dolist (finger '(thumb index middle ring pinkie) nil)
(let* ((f (find finger (rest touch-pos) :key 'first))
(val (if f
(zerop (fourth f))
(notify-device device (list 'finger-down hand finger)))))
(when val
(return-from touch-any-finger-down t)))))))
(print-warning "Touch-any-finger-down called for ~s but hand not on touch device." hand))))
;;; This is touch device specific
(defmethod hand-to-touch ((mtr-mod motor-module) request)
(let ((installed-touch (find "touch" (current-devices "motor") :test 'string-equal :key 'second)))
(cond (installed-touch
(let* ((touch (get-module :touch-interface))
(hand-spec (chunk-spec-slot-spec request 'hand))
(hand (if (null hand-spec) 'right
(verify-single-explicit-value request 'hand :touch-interface "hand-to-touch"))))
(if (and touch (valid-hand hand))
(let* ((touch-pos (bt:with-recursive-lock-held ((touch-module-lock touch)) (touch-module-position touch)))
(hand-pos (hand-position hand :current nil))
(hand-loc (hand-pos-loc hand-pos))
(polar (xy-to-polar hand-loc touch-pos))
(device (device-for-hand hand :current nil)))
(if (and (= (vr polar) 0)
device
(string-equal (second device) "touch"))
(model-warning "HAND-TO-TOUCH requested but hand already is (or will be) at the touch position.")
(point-hand mtr-mod :hand hand :r (vr polar) :theta (vtheta polar) :twidth 4.0
:device installed-touch :offsets 'standard :request-spec request
:style 'to-touch-ply)))
(model-warning "Hand-to-touch request received invalid hand information ~s" hand-spec))))
(t
(model-warning "Hand-to-touch requested but no touch device available.")))))
(defclass to-touch-ply (hand-ply)
())
(defmethod prepare-features ((mtr-mod motor-module) (self to-touch-ply))
(let ((new-pos (move-a-hand mtr-mod (hand self) (r self) (theta self) :current nil)))
(unless (eq (offsets self) 'standard)
(model-warning "Hand-to-touch action specified non-standard finger offsets but that is not currently supported."))
(setf (hand-pos-fingers new-pos) (ecase (hand self)
(right (right-standard-offsets))
(left (left-standard-offsets))))
;; Since the device won't set the positions
;; until the hand moves to it we need to set the
;; updated positions here as well because we
;; can't assume that falling through to current
;; will be valid if a subsequent action wants the "next" ones
(let ((touch (get-module :touch-interface)))
(when touch
(bt:with-recursive-lock-held ((touch-module-lock touch))
(let* ((dist (* (touch-module-ppi touch) (touch-module-finger-spacing touch)))
(start (if (eq (hand self) 'right)
(touch-module-right-start touch)
(touch-module-left-start touch)))
(sx (round (first start)))
(sy (round (second start)))
(finger-offsets (hand-pos-fingers new-pos))
(positions (list 'touch-positions))
(others (hand-pos-other new-pos)))
(dolist (f finger-offsets)
(push-last (list (first f)
(round (+ (* (px (second f)) dist) sx))
(round (+ (* (py (second f)) dist) sy))
1)
positions))
(awhen (find 'touch-positions others :key 'first)
(setf others (remove it others)))
(push positions others)
(setf (hand-pos-other new-pos) others)))))
(setf (hand-pos-device new-pos) (device self))
(setf (updated-pos self) new-pos)))
;;; move-hand-touch
;;; Allows the model to move its hand (referenced by index finger position) to what it sees.
;;; Also moves all of the other fingers along with it.
(defstyle touch-ply hand-ply hand finger r theta)
(defmethod prepare-features ((mtr-mod motor-module) (self touch-ply))
(let* ((starting-point (copy-hand-pos (hand-position (hand self) :current nil)))
(others (copy-seq (hand-pos-other starting-point))))
(awhen (find 'touch-positions (hand-pos-other starting-point) :key 'first)
(setf others (remove it others)))
(let ((updated-fingers (list 'touch-positions)))
(dolist (finger '(index middle ring pinkie thumb))
(let ((new-pos (polar-move-xy (touch-finger-position (hand self) finger :current nil)
(vector (r self) (theta self)))))
(push-last (list finger (px new-pos) (py new-pos)
(if (touch-finger-down (hand self) finger :current nil)
0 1))
updated-fingers)))
(push updated-fingers others))
(setf (hand-pos-other starting-point) others)
(setf (updated-pos self) starting-point)))
(defmethod queue-output-events ((mtr-mod motor-module) (self touch-ply))
(let* ((device (device-for-hand (hand self)))
(action-time (seconds->ms (exec-time self)))
(finger-positions (rest (find 'touch-positions (hand-pos-other (updated-pos self)) :key 'first)))
(hand-position (find 'index finger-positions :key 'first)))
;; Send the move-hand-touch action to the device
(schedule-event-relative action-time 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
((model ,(current-model))
(style move-hand-touch) (hand ,(hand self))
(loc ,(second hand-position) ,(third hand-position)))))
;; update the hand-position
(schedule-event-relative action-time 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list (hand self) (updated-pos self))
:output nil)
;; schedule calls to move all of the fingers
(dolist (finger finger-positions)
(let ((f finger))
(schedule-event-relative action-time 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,(hand self) ,(first f) ,(second f) ,(third f))))))))
(defmethod move-hand-touch ((mtr-mod motor-module) &key loc object hand request-spec)
(let ((real-device (device-for-hand hand :current nil)))
(when (or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to move-hand-touch.")
(return-from move-hand-touch nil))
(unless (or (check-jam mtr-mod) (check-specs 'move-hand-touch (or loc object)))
(let ((target (or (and (chunk-p-fct object) object) (and (chunk-p-fct loc) loc)))
(target-loc (or (and object (chunk-to-visual-position object))
(and loc (chunk-to-visual-position loc)))))
(unless (and target target-loc)
(print-warning "No valid location could be generated from ~s or ~s when trying to move hand on touch device." object loc)
(return-from move-hand-touch nil))
;; need parameters from the module
(let ((touch (get-module :touch-interface))
drag-delay coeff noise)
(bt:with-recursive-lock-held ((touch-module-lock touch))
(setf drag-delay (touch-module-drag-delay touch)
coeff (touch-module-cursor-coeff touch)
noise (touch-module-noise touch)))
;; hand position is index finger position
(let* ((current-loc (touch-finger-position hand 'index :current nil))
(r-theta (xy-to-polar current-loc (coerce target-loc 'vector))))
(if (= 0 (vr r-theta)) ; r=0 is a no-op
(model-warning "Move-hand-touch action aborted because hand is at requested target ~S" (if object object loc)))
(let* ((w (pm-angle-to-pixels (approach-width target (vtheta r-theta) (px current-loc) (py current-loc)))) ;;approach-width returns DVA but we're working in pixels
(r-theta-new (if noise
(noisy-loc-em? target-loc w (vtheta r-theta))
r-theta)))
(prepare-movement mtr-mod
(make-instance 'touch-ply
:request-spec request-spec
:hand hand
:r (vr r-theta-new)
:theta (vtheta r-theta-new)
:target-width w
:fitts-coeff (if (and drag-delay (touch-any-finger-down hand :current nil))
;; because control order is 0
;; just use drag-delay directly
;; and don't need 2^0 in normal
(* (expt-coerced 2 (if (eq drag-delay t) .8 drag-delay)) coeff)
coeff))))))))))
(defmethod move-hand-touch-request ((mtr-mod motor-module) chunk-spec)
(let ((object (if (slot-in-chunk-spec-p chunk-spec 'object)
(verify-single-explicit-value
chunk-spec
'object
:motor
'move-hand-touch)
nil))
(location (if (slot-in-chunk-spec-p chunk-spec 'loc)
(verify-single-explicit-value
chunk-spec
'loc
:motor
'move-hand-touch)
nil))
(hand (if (slot-in-chunk-spec-p chunk-spec 'hand)
(verify-single-explicit-value
chunk-spec
'hand
:motor
'move-hand-touch)
;; defaults to right hand if not given
'right)))
(cond ((not (or (eq hand 'right) (eq hand 'left)))
(print-warning "Move-hand-touch action failed because ~s is not a valid hand." hand))
((null (or location object))
(print-warning "Move-hand-touch action failed because no object or location provided."))
(t
(schedule-event-now
'move-hand-touch
:destination :motor
:params (list :object object
:loc location
:hand hand
:request-spec chunk-spec)
:module :motor
:output 'high
:details (format nil "~a ~a ~a ~a ~a ~a ~a" 'move-hand-touch :object object :loc location :hand hand))))))
;;; tap movement style
;;; analogous to punch movement style, the indicated finger strikes the surface
;;; of the display at the finger's current position and returns the finger
;;; to a z-position where it is ready to act again
;;; Actually executed like a peck-recoil since it must move to the display and
;;; back based on the distance parameter.
(defstyle tap () hand finger)
(defmethod tap :around ((mtr-mod motor-module) &key hand finger request-spec)
(declare (ignore request-spec))
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to tap."))
((null (valid-hand hand))
(print-warning "Tap request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Tap request has invalid finger ~s." finger))
((touch-finger-down hand finger :current nil)
(print-warning "Tap requested for ~a ~a but that finger is (or will be) down." hand finger))
(t
(call-next-method)))))
(defmethod compute-exec-time ((mtr-mod motor-module) (self tap))
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
(max (burst-time mtr-mod)
(randomize-time (fitts mtr-mod
;; peck's "b" coefficient
(touch-module-peck-coeff touch)
;; Use the user defined settings for height and ppi
;; also, convert that to degrees of visual angle
;; because since there is no target width the default
;; is 1 which would mean 1 pixel and that results in
;; a time which seems too long for the default distance
;; ~.45 seconds to tap
(pixels->angle-mth (current-device-interface) (* (touch-module-ppi touch) (touch-module-height touch)))))))))))
(defmethod feat-differences ((t1 tap) (t2 tap))
(cond ((not (eq (hand t1) (hand t2))) 2)
((not (eq (finger t1) (finger t2))) 1)
(t 0)))
(defmethod queue-output-events ((mtr-mod motor-module) (self tap))
;; Send the tap action at execution time to whatever device is current for the hand
(let ((device (device-for-hand (hand self))))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
((model ,(current-model))
(style tap) (hand ,(hand self))
(finger ,(finger self)))))
;; also set the finger-down at execution time
;; and finger-up at burst time after exec time
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device (set-finger-down ,(hand self) ,(finger self))))
(schedule-event-relative (seconds->ms (+ (exec-time self) (burst-time mtr-mod))) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device (set-finger-up ,(hand self) ,(finger self)))))))
;;; tap-hold movement style
;;; Performs a tap movement, but holds the finger to the multitouch display surface.
(defstyle tap-hold tap hand finger)
(defmethod tap-hold :around ((mtr-mod motor-module) &key hand finger request-spec)
(declare (ignore request-spec))
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to tap-hold."))
((null (valid-hand hand))
(print-warning "Tap-hold request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Tap-hold request has invalid finger ~s." finger))
((touch-finger-down hand finger :current nil)
(print-warning "Tap-hold requested for ~a ~a but that finger is (or will be) down." hand finger))
(t
(call-next-method)))))
(defmethod prepare-features ((mtr-mod motor-module) (self tap-hold))
(let* ((starting-point (copy-hand-pos (hand-position (hand self) :current nil)))
(others (copy-seq (hand-pos-other starting-point))))
(awhen (find 'touch-positions (hand-pos-other starting-point) :key 'first)
(setf others (remove it others)))
(let ((updated-fingers (list 'touch-positions)))
(dolist (finger '(index middle ring pinkie thumb))
(let ((pos (touch-finger-position (hand self) finger :current nil)))
(push-last (list finger (px pos) (py pos)
(if (eq finger (finger self))
0
(if (touch-finger-down (hand self) finger :current nil)
0 1)))
updated-fingers)))
(push updated-fingers others))
(setf (hand-pos-other starting-point) others)
(setf (updated-pos self) starting-point)))
(defmethod queue-output-events ((mtr-mod motor-module) (self tap-hold))
;; Send the tap-hold action at execution time to whatever device is current for the hand
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,(device-for-hand (hand self))
((model ,(current-model))
(style tap-hold) (hand ,(hand self))
(finger ,(finger self)))))
;; update the hand-position information
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list (hand self) (updated-pos self))
:output nil)
;; also send the finger-down notice
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,(device-for-hand (hand self))
(set-finger-down ,(hand self) ,(finger self)))))
;;; tap-release movement style
;;; If the finger is held against the surface of the multitouch display,
;;; as in a tap-hold movement, then tap-release moves the finger away from
;;; the multitouch display surface.
(defstyle tap-release tap hand finger)
(defmethod tap-release :around ((mtr-mod motor-module) &key hand finger request-spec)
(declare (ignore request-spec))
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to tap-release."))
((null (valid-hand hand))
(print-warning "Tap-release request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Tap-release request has invalid finger ~s." finger))
((not (touch-finger-down hand finger :current nil))
(print-warning "Tap-release requested for ~a ~a but that finger is (or will be) up." hand finger))
(t
(call-next-method)))))
(defmethod prepare-features ((mtr-mod motor-module) (self tap-release))
(let* ((starting-point (copy-hand-pos (hand-position (hand self) :current nil)))
(others (copy-seq (hand-pos-other starting-point))))
(awhen (find 'touch-positions (hand-pos-other starting-point) :key 'first)
(setf others (remove it others)))
(let ((updated-fingers (list 'touch-positions)))
(dolist (finger '(index middle ring pinkie thumb))
(let ((pos (touch-finger-position (hand self) finger :current nil)))
(push-last (list finger (px pos) (py pos)
(if (eq finger (finger self))
1
(if (touch-finger-down (hand self) finger :current nil)
0 1)))
updated-fingers)))
(push updated-fingers others))
(setf (hand-pos-other starting-point) others)
(setf (updated-pos self) starting-point)))
(defmethod compute-exec-time ((mtr-mod motor-module) (self tap-release))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (init-time mtr-mod)
;; just costs a burst-time since it's not a targeted
;; motion -- just lifting a finger
(burst-time mtr-mod))))
(defmethod queue-output-events ((mtr-mod motor-module) (self tap-release))
;; Send the tap-release action at execution time to whatever device is current for the hand
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,(device-for-hand (hand self))
((model ,(current-model))
(style tap-release) (hand ,(hand self))
(finger ,(finger self)))))
;; update the hand-position information
(schedule-event-relative (seconds->ms (exec-time self)) 'set-hand-position :time-in-ms t :module :motor
:destination :motor :params (list (hand self) (updated-pos self))
:output nil)
;; also send the finger-up notice
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,(device-for-hand (hand self))
(set-finger-up ,(hand self) ,(finger self)))))
;;; Index-Thumb
;;; Subclass this for pinch and rotate
;;; on its own basically a thumb swipe
;; want an extra slot so skip defstyle to avoid complications
(defclass index-thumb (hfrt-movement)
((move-time :accessor move-time))
(:default-initargs
:style-name :index-thumb))
(defmethod compute-exec-time ((mtr-mod motor-module) (self index-thumb))
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(fitts mtr-mod (peck-fitts-coeff mtr-mod)
(r self)
;; the width of the thumb
(* (touch-module-ppi touch) (touch-module-thumb-width touch)))))
(+ (init-time mtr-mod)
(max (burst-time mtr-mod)
(randomize-time (move-time self))))))))
(defmethod compute-finish-time ((mtr-mod motor-module) (self index-thumb))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(+ (exec-time self)
(burst-time mtr-mod)
(max (burst-time mtr-mod)
(randomize-time (move-time self))))))
(defmethod queue-output-events ((mtr-mod motor-module) (self index-thumb))
(let* ((finger (finger self))
(hand (hand self))
(start-pos (touch-finger-position hand finger))
(move-vector (vector (r self) (theta self)))
(end-pos (polar-move-xy start-pos move-vector))
(device (device-for-hand hand)))
;; Send the index-thumb action at execution time to whatever device is current for the hand
;; with the distance and direction
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
((model ,(current-model))
(style index-thumb) (hand ,hand) (finger ,finger)
(distance ,(vr move-vector)) (direction ,(vtheta move-vector)))))
;; schedule the finger to go down after init-time
;; move to the target point at exec-time
;; lift up after exec-time + burst-time
;; move back to start at finish-time
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-down ,hand ,finger)))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px end-pos) ,(py end-pos))))
(schedule-event-relative (seconds->ms (+ (exec-time self) (bt:with-recursive-lock-held ((param-lock mtr-mod)) (burst-time mtr-mod))))
'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-up ,hand ,finger)))
(schedule-event-relative (seconds->ms (finish-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px start-pos) ,(py start-pos)))))))
(defmethod index-thumb ((mtr-mod motor-module) &key hand finger r theta request-spec)
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to index-thumb."))
((check-jam mtr-mod) ; prints own warning
)
((null (valid-hand hand))
(print-warning "Index-thumb request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Index-thumb request has invalid finger ~s." finger))
((touch-finger-down hand finger :current nil)
(print-warning "Index-thumb requested for ~a ~a but that finger is (or will be) down." hand finger))
(t
(when (symbolp theta)
(setf theta (symbol-value theta)))
(prepare-movement mtr-mod (make-instance 'index-thumb :hand hand :finger finger :r r :theta theta :request-spec request-spec))))))
;; Pinch is finger and thumb down start-width apart then move to end-width apart lift and return to starting
(defStyle pinch index-thumb hand finger start-width end-width)
(defmethod compute-exec-time ((mtr-mod motor-module) (self pinch))
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(fitts mtr-mod (peck-fitts-coeff mtr-mod)
(abs (- (start-width self) (end-width self)))
;; the width of the thumb
(* (touch-module-ppi touch) (touch-module-thumb-width touch)))))
(+ (init-time mtr-mod)
(max (burst-time mtr-mod)
(randomize-time (move-time self))))))))
(defmethod queue-output-events ((mtr-mod motor-module) (self pinch))
;; Send the pinch action at execution time to whatever device is current for the hand
;; with the distances
(let* ((hand (hand self))
(finger (finger self))
(device (device-for-hand hand)))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
((model ,(current-model))
(style pinch) (hand ,hand) (finger ,finger)
(range ,(start-width self) ,(end-width self)))))
;; move the finger and thumb to be start-width apart and put them
;; down at init-time
;; move to end-width distance at exec-time
;; lift up a burst-time after exec-time
;; move back to start at finish-time
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(let* ((thumb-start-pos (touch-finger-position hand 'thumb))
(finger-start-pos (touch-finger-position hand finger))
(theta (atan (- (py finger-start-pos) (py thumb-start-pos)) (- (px finger-start-pos) (px thumb-start-pos))))
(r (round (- (dist thumb-start-pos finger-start-pos) (start-width self))))
(thumb-init-pos (if (zerop r) thumb-start-pos
(polar-move-xy thumb-start-pos
(vector (/ r 2)
(if (> r (start-width self))
theta
(+ pi theta))))))
(finger-init-pos (if (zerop r) finger-start-pos
(polar-move-xy finger-start-pos
(vector (/ r 2)
(if (> r (start-width self))
(+ pi theta)
theta)))))
(travel-dist (round (- (start-width self) (end-width self))))
(thumb-end-pos (if (zerop travel-dist) thumb-init-pos
(polar-move-xy thumb-init-pos
(vector (/ travel-dist 2) theta))))
(finger-end-pos (if (zerop travel-dist) finger-init-pos
(polar-move-xy finger-init-pos
(vector (/ travel-dist 2) (+ theta pi)))))
(bt (burst-time mtr-mod)))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand thumb ,(px thumb-init-pos) ,(py thumb-init-pos))))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px finger-init-pos) ,(py finger-init-pos))))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-down ,hand thumb)))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-down ,hand ,finger)))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand thumb ,(px thumb-end-pos) ,(py thumb-end-pos))))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px finger-end-pos) ,(py finger-end-pos))))
(schedule-event-relative (seconds->ms (+ (exec-time self) bt)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-up ,hand thumb)))
(schedule-event-relative (seconds->ms (+ (exec-time self) bt)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-up ,hand ,finger)))
(schedule-event-relative (seconds->ms (finish-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand thumb ,(px thumb-start-pos) ,(py thumb-start-pos))))
(schedule-event-relative (seconds->ms (finish-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px finger-start-pos) ,(py finger-start-pos))))))))
(defmethod pinch :around ((mtr-mod motor-module) &key hand finger start-width end-width request-spec)
(declare (ignore start-width end-width request-spec))
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to pinch."))
((null (valid-hand hand))
(print-warning "Pinch request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Pinch request has invalid finger ~s." finger))
((touch-finger-down hand finger :current nil)
(print-warning "Pinch requested for ~a ~a but that finger is (or will be) down." hand finger))
((touch-finger-down hand 'thumb :current nil)
(print-warning "Pinch requested for ~a hand but that thumb is (or will be) down." hand))
(t
(call-next-method)))))
;; Rotate is thumb and finger down and then moved along a circular path
;; the indicated number of radians (positive is clockwise negative counter-clockwise).
(defStyle rotate index-thumb hand finger rotation)
(defmethod compute-exec-time ((mtr-mod motor-module) (self rotate))
(let ((touch (get-module :touch-interface))
width)
(bt:with-recursive-lock-held ((touch-module-lock touch))
(setf width (touch-module-rotate-width touch)))
(let ((diameter (dist (touch-finger-position (hand self) 'thumb)
(touch-finger-position (hand self) (finger self)))))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(fitts mtr-mod (peck-fitts-coeff mtr-mod)
;; Was this but that doesn't make sense to me
;; (dist
;; (finger-loc-m mtr-mod (hand self) 'thumb)
;; (finger-loc-m mtr-mod (hand self) 'index))
;; So instead use the actual distance traveled to
;; perform the indicated rotation assuming a circle
;; with the thumb and indicated finger rotated around
;; the midpoint of their connecting line segment.
;; That's simply the angle in radians times half the
;; distance between them because s = r * theta
(* .5 diameter (abs (rotation self)))
;; target size is rotate-width degrees of the circle
(* .5 diameter pi 1/180 width))))
(+ (init-time mtr-mod)
(max (burst-time mtr-mod)
(randomize-time (move-time self))))))))
(defmethod queue-output-events ((mtr-mod motor-module) (self rotate))
(let* ((hand (hand self))
(finger (finger self))
(device (device-for-hand hand)))
;; Send the rotate action at execution time to whatever device is current for the hand
;; with the rotation angle
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
((model ,(current-model))
(style rotate) (hand ,hand) (finger ,finger)
(direction ,(rotation self)))))
;; move the finger and thumb down at init-time
;; move by rotation angle at exec-time (positive is clockwise)
;; lift up a burst-time after exec-time
;; move back to start at finish-time
;; just compute the final location -- not doing incremental movement along the arc
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(let* ((thumb-start-pos (touch-finger-position hand 'thumb))
(finger-start-pos (touch-finger-position hand finger))
(center (vector (+ (px thumb-start-pos) (/ (- (px finger-start-pos) (px thumb-start-pos)) 2))
(+ (py thumb-start-pos) (/ (- (py finger-start-pos) (py thumb-start-pos)) 2))))
(tx1 (- (px thumb-start-pos) (px center)))
(ty1 (- (py thumb-start-pos) (py center)))
(fx1 (- (px finger-start-pos) (px center)))
(fy1 (- (py finger-start-pos) (py center)))
(s (sin (rotation self)))
(c (cos (rotation self)))
(tx (round (+ (- (* tx1 c) (* ty1 s)) (px center))))
(ty (round (+ (+ (* ty1 c) (* tx1 s)) (py center))))
(fx (round (+ (- (* fx1 c) (* fy1 s)) (px center))))
(fy (round (+ (+ (* fy1 c) (* fx1 s)) (py center))))
(bt (burst-time mtr-mod)))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-down ,hand thumb)))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-down ,hand ,finger )))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand thumb ,tx ,ty)))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,fx ,fy)))
(schedule-event-relative (seconds->ms (+ (exec-time self) bt)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-up ,hand thumb)))
(schedule-event-relative (seconds->ms (+ (exec-time self) bt)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-up ,hand ,finger)))
(schedule-event-relative (seconds->ms (finish-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand thumb ,(px thumb-start-pos) ,(py thumb-start-pos))))
(schedule-event-relative (seconds->ms (finish-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px finger-start-pos) ,(py finger-start-pos))))))))
(defmethod rotate :around ((mtr-mod motor-module) &key hand finger rotation request-spec)
(declare (ignore rotation request-spec))
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to rotate."))
((null (valid-hand hand))
(print-warning "Rotate request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Rotate request has invalid finger ~s." finger))
((touch-finger-down hand finger :current nil)
(print-warning "Rotate requested for ~a ~a but that finger is (or will be) down." hand finger))
((touch-finger-down hand 'thumb :current nil)
(print-warning "Rotate requested for ~a hand but that thumb is (or will be) down." hand))
(t
(call-next-method)))))
;; Swipe is multiple fingers down moved together for a given distance
;; and direction at a specified speed (where speed is 1-5 with 5 being fastest
;; and speed sets the Fitts law coefficient as (/ 1 (expt swipe-speed 2)) )
;; finger indicates the 'first' finger and the following (num-fingers - 1)
;; fingers are also used from the ordering: index, middle, ring, pinkie, thumb
(defStyle swipe index-thumb hand finger r theta num-fngrs swipe-speed)
(defmethod swipe :around ((mtr-mod motor-module) &key hand finger r theta num-fngrs swipe-speed request-spec)
(let ((real-device (device-for-hand hand :current nil)))
(cond ((or (null real-device) (not (string-equal (second real-device) "touch")))
(print-warning "Hand is not on a touch device in request to swipe."))
((null (valid-hand hand))
(print-warning "Swipe request has invalid hand ~s." hand))
((null (valid-finger finger))
(print-warning "Swipe request has invalid finger ~s." finger))
((touch-any-finger-down hand :current nil)
(print-warning "Swipe requested for ~a hand but there are (or will be) one or more fingers down." hand))
((< num-fngrs 1)
(print-warning "Swipe for ~a hand requested with less than 1 finger ~s." hand num-fngrs))
((> (+ num-fngrs (valid-finger finger)) 5)
(print-warning "Swipe for ~a hand requested with too many fingers (~s) starting with the ~a finger."
hand num-fngrs finger))
((not (or (numberp swipe-speed) (null swipe-speed)))
(print-warning "Swipe for ~a hand requested with invalid swipe-speed ~s." hand swipe-speed))
((and swipe-speed (or (< swipe-speed 1) (> swipe-speed 5)))
(print-warning "Swipe for ~a hand requested with invalid swipe-speed ~s." hand swipe-speed))
(t
;; fill in the default speed if not provided
(when (null swipe-speed)
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(setf swipe-speed (touch-module-swipe-speed touch)))))
(call-next-method mtr-mod :hand hand :finger finger :r r :theta theta
:num-fngrs num-fngrs :swipe-speed swipe-speed :request-spec request-spec)))))
(defmethod compute-exec-time ((mtr-mod motor-module) (self swipe))
(let ((touch (get-module :touch-interface)))
(bt:with-recursive-lock-held ((touch-module-lock touch))
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(setf (move-time self)
(max (burst-time mtr-mod)
(fitts mtr-mod
(/ 1 (expt (aif (swipe-speed self) it (touch-module-swipe-speed touch)) 2))
(r self)
;; the width of a target of a swipe should be wide, ie the edge of the device
(touch-module-swipe-width touch))))
(+ (init-time mtr-mod)
(max (burst-time mtr-mod)
(randomize-time (move-time self))))))))
(defmethod queue-output-events ((mtr-mod motor-module) (self swipe))
;; Send the swipe action at execution time to whatever device is current for the hand
;; with the distance, direction, and number
(let* ((hand (hand self))
(device (device-for-hand hand)))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
((model ,(current-model))
(style swipe) (hand ,hand) (finger ,(finger self))
(distance ,(r self)) (direction ,(theta self))
(count ,(num-fngrs self))
(speed ,(swipe-speed self)))))
;; move the fingers down at init-time
;; move to end-points at exec-time
;; lift up a burst-time after exec-time
;; move back to start at finish-time
(bt:with-recursive-lock-held ((param-lock mtr-mod))
(let* ((move-vector (vector (r self) (theta self)))
(bt (burst-time mtr-mod))
(start-finger (valid-finger (finger self)))
(count (num-fngrs self))
(fingers '(index middle ring pinkie thumb)))
(dotimes (i count)
(let* ((finger (nth (+ i start-finger) fingers))
(start (touch-finger-position hand finger))
(end (polar-move-xy start move-vector)))
(schedule-event-relative (seconds->ms (init-time mtr-mod)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-down ,hand ,finger)))
(schedule-event-relative (seconds->ms (exec-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px end) ,(py end))))
(schedule-event-relative (seconds->ms (+ (exec-time self) bt)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-up ,hand ,finger)))
(schedule-event-relative (seconds->ms (finish-time self)) 'notify-motor-device
:time-in-ms t :module :motor :output nil
:params `(,device
(set-finger-position ,hand ,finger ,(px start) ,(py start))))))))))
(extend-manual-requests ((hand-to-touch (:include motor-command)) (hand right)) handle-simple-command-request)
(extend-manual-requests-fct '((tap (:include motor-command)) (hand right) (finger index)) 'handle-style-request)
(extend-manual-requests-fct '((tap-hold (:include motor-command)) (hand right) (finger index)) 'handle-style-request)
(extend-manual-requests-fct '((tap-release (:include motor-command)) (hand right) (finger index)) 'handle-style-request)
(extend-manual-requests-fct '((move-hand-touch (:include motor-command)) (hand right) loc object) 'move-hand-touch-request)
(extend-manual-requests-fct '((index-thumb (:include motor-command)) (hand right) (finger thumb) r theta) 'handle-style-request)
(extend-manual-requests-fct '((swipe (:include motor-command)) (hand right) (finger index) r theta (num-fngrs 1) swipe-speed) 'handle-partial-style-request)
(extend-manual-requests-fct '((pinch (:include motor-command)) (hand right) (finger index) start-width end-width) 'handle-style-request)
(extend-manual-requests-fct '((rotate (:include motor-command)) (hand right) (finger index) rotation) 'handle-style-request)
;; Record that it's loaded so require won't load it again.
(provide "act-touch")
| 98,210 | Common Lisp | .lisp | 1,567 | 48.848117 | 226 | 0.584021 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1a03b1db80298a610bbdfd5fe3bd883834933b4287620438e5e8c4828295de6e | 14,288 | [
-1
] |
14,289 | touch-demo-model.lisp | asmaloney_ACT-R/extras/act-touch/touch-demo-model.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Frank Tamborello
;;; Copyright : (c) 2012 Cogscent, LLC
;;; Availability: GNU LGPL, see LGPL.txt
;;; Address : Cogscent, LLC
;;; : PMB 7431
;;; : 2711 Centerville Rd, Ste 120
;;; : Wilmington DE, USA 19808-1676
;;; : [email protected]
;;;
;;; Disclaimer : This library is free software; you can redistribute it and/or
;;; : modify it under the terms of the GNU Lesser General Public
;;; : License as published by the Free Software Foundation; either
;;; : version 2.1 of the License, or (at your option) any later version.
;;; : This library 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
;;; : Lesser General Public License for more details.
;;; : You should have received a copy of the GNU Lesser General Public
;;; : License along with this library; if not, write to the Free Software
;;; : Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;; :
;;;
;;; Acknowledgements
;;; : This research is sponsored by Measurement Science and
;;; Engineering grant 60NANB12D134 from the
;;; National Institute of Standards and Technology (NIST).
;;; Special acknowledgements are due to Dr. Ross Micheals and
;;; Dr. Kristen K. Greene of NIST's Information Technology
;;; Laboratory.
;;; Thanks also to Dr. Michael D. Byrne, upon whose experiment
;;; library code I based the device code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : touch-demo-model.lisp
;;; Revision : 3
;;;
;;; Description : A demonstration of ACT-Touch
;;;
;;; Usage : Load this file and call run-touch-demo to run the demonstration
;;; : model (see below for options). Does not require loading act-touch separately.
;;;
;;;
;;; Bugs : None known
;;;
;;; To do : Nothing
;;;
;;; ----- History -----
;;; 2012.09.29 fpt 1
;;; : Inception: Forked from act-touch.lisp
;;; 2014.12.01 Dan Bothell
;;; : Added the run-touch-demo function which includes the code
;;; : from the after method that was previously defined in the
;;; : virtual-multitouch-device.lisp file.
;;; : Added a chunk-type named goal with a slot named op.
;;; : Added chunk definitions for all of the chunks in the model.
;;; 2016.03.14 Dan Bothell
;;; : Added the require-extra so that it automatically loads the
;;; : act-touch extension if it's not already available.
;;; 2018.10.25 Dan Bothell
;;; : Use the new start-hand-at-touch command to position the hands
;;; : so the offsets are set correctly.
;;; : Changed the productions so that it performs all of the actions
;;; : sequentially without having to change the op slot from code.
;;; : Added some different speed swipes.
;;; : Changed the queries to state free so it's easier to see
;;; : the individual actions.
;;; : Added another rotate to see the difference in time by angle now.
;;; 2018.11.01 Dan Bothell [2]
;;; : This version runs with ACT-R 7.6+ (7.12 when updated).
;;; : Renamed to demo2.
;;; : This demo installs a touch device and starts both hands at
;;; : that device before performing some actions.
;;; 2018.11.05 Dan Bothell [3]
;;; : Moved demo1 and 2 versions together and renamed touch-demo-model.
;;; : Added the visible window option, some left hand actions, and
;;; : adjusted the movements so they're on the actual window used.
;;; : Put an image on the window for the model to tap and drag when
;;; : it is a visible device.
;;; 2018.11.06 Dan Bothell
;;; : Set the touch-drag-delay parameter and move the hand between
;;; : the same places once with a finger down and once without.
;;; : Don't start both hands at the device and instead use the hand-
;;; : to-touch action to move one there.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(clear-all)
(require-extra "act-touch")
;;; Function to run the demo model.
;;;
;;; Has three possible modes run as follows:
;;;
;;; (run-touch-demo)
;;; Runs the model without a touch device installed to just demonstrate the
;;; actions being performed. No monitorable actions are generated, and the
;;; finger positions are not actually changed from the motor module's
;;; default locations (which affects the Fitts Law timing values) because
;;; the touch device is needed to track the finger positions in pixel space
;;; (in the same way that the mouse cursor moves in pixel space although the
;;; model's hand doesn't really move from the location of the cursor itself).
;;;
;;; (run-touch-demo t)
;;; Installs a touch device and then runs the model. The touch device
;;; will generate the signals which can be monitored, and some simple
;;; monitoring functions will just print out what happens.
;;;
;;; (run-touch-demo :window)
;;; Installs an experiment window (visible if possible) and then installs
;;; the touch device associating it with that window. Taps will result in
;;; click actions which the window can respond to in addition to the touch
;;; module generating the signals which can be monitored. The demo adds
;;; a button with a click action which will report the click and add two
;;; additional monitors which will move the button between the next tap-hold
;;; and tap-relase actions.
(defun run-touch-demo (&optional mode)
(reset)
(setup-action-monitors)
(cond ((null mode)
;; add a visual feature that corresponds to the button in the windowed
;; version and automatically move it as the model would on the window
(let ((feature (first (add-visicon-features '(screen-x 350 screen-y 175 width 100 height 50)))))
(schedule-event-relative 3 'modify-visicon-features :output nil :maintenance t :params (list (list feature 'screen-x 450 'screen-y 300))))
(run 20))
((eq mode t)
;; set the starting points to the same places as in the windowed version
(sgp :left-start (100 300) :right-start (600 300))
;; Start the right hand (the default) at the touch device and automatically install the device.
(start-hand-at-touch)
;; Indicate there is a device for the model to move its hand to
(mod-focus device t)
;; add a visual feature that corresponds to the button in the windowed
;; version and automatically move it as the model would on the window
(let ((feature (first (add-visicon-features '(screen-x 350 screen-y 175 width 100 height 50)))))
(schedule-event-relative 3 'modify-visicon-features :output nil :maintenance t :params (list (list feature 'screen-x 450 'screen-y 300))))
(run 20))
((eq mode :window)
;; display the finger locations in the window when it's visible
(sgp :show-fingers t)
;; create a window which is visible if possible
(let ((w (open-exp-window "test" :visible t :width 500 :height 400 :x 100 :y 100)))
;; install the window device
(install-device w)
;; add a button with a function to call when clicked
(setf *created-button* (add-button-to-exp-window w :text "" :color "blue" :x 200 :y 50 :width 100 :height 50 :action "demo-button-clicked"))
;; install the touch device and associate it with the window above
(install-device (list "motor" "touch" w))
;; start the right hand at the touch device
(start-hand-at-touch)
;; indicate there is a device for the model to move its hand to
(mod-focus device t)
(run 20)))
(t
(print-warning "Invalid mode ~s given to run-touch-demo. Possible options are nil, t, or :window." mode)))
(remove-action-monitors))
;;; Variables for handling the interaction with a window.
(defvar *created-button*)
(defvar *tapped-item*)
;; Clear the interaction variables and add the monitoring functions
;; to the associated actions.
(defun setup-action-monitors ()
(setf *created-button* nil)
(setf *tapped-item* nil)
;; All of the signals generated by the touch device
(monitor-act-r-command "touch-tap" "demo-tap")
(monitor-act-r-command "touch-point" "demo-point")
(monitor-act-r-command "touch-swipe" "demo-swipe")
(monitor-act-r-command "touch-tap-hold" "demo-tap-hold")
(monitor-act-r-command "touch-tap-release" "demo-tap-release")
(monitor-act-r-command "touch-pinch" "demo-pinch")
(monitor-act-r-command "touch-rotate" "demo-rotate"))
;; Remove the monitors to avoid any problems with other tasks
;; run after this one that also use the touch device.
(defun remove-action-monitors ()
(remove-act-r-command-monitor "touch-tap" "demo-tap")
(remove-act-r-command-monitor "touch-point" "demo-point")
(remove-act-r-command-monitor "touch-swipe" "demo-swipe")
(remove-act-r-command-monitor "touch-tap-hold" "demo-tap-hold")
(remove-act-r-command-monitor "touch-tap-release" "demo-tap-release")
(remove-act-r-command-monitor "touch-pinch" "demo-pinch")
(remove-act-r-command-monitor "touch-rotate" "demo-rotate"))
;; Simple functions which are monitoring for the touch devices
;; signals and print out the values provided.
(defun demo-tap (model hand finger x y)
(act-r-output "model ~s tapped the ~s finger on the ~s hand at point ~d , ~d" model finger hand x y))
(defun demo-point (model hand x y)
(act-r-output "model ~s moved the ~s hand to point ~d , ~d" model hand x y))
(defun demo-swipe (model hand finger distance direction count speed)
(act-r-output "model ~s swiped ~d fingers on the ~s hand starting with the ~s finger a distance of ~f in the ~f direction at speed ~f" model count hand finger distance direction speed))
(defun demo-tap-hold (model hand finger x y)
(act-r-output "model ~s tapped and held the ~s finger on the ~s hand at point ~d , ~d" model finger hand x y))
(defun demo-tap-release (model hand finger x y)
(act-r-output "model ~s released the ~s finger on the ~s hand at point ~d , ~d" model finger hand x y))
(defun demo-pinch (model hand finger start end)
(act-r-output "model ~s pinched with the ~s finger on the ~s hand from a width of ~f to ~f" model finger hand start end))
(defun demo-rotate (model hand finger angle)
(act-r-output "model ~s rotated with the ~s finger on the ~s hand ~f radians" model finger hand angle))
;; Create commands for those functions so they can be used
;; used to monitor the touch device's signals.
(add-act-r-command "demo-tap" 'demo-tap "Touch-demo-model example tap monitoring function.")
(add-act-r-command "demo-point" 'demo-point "Touch-demo-model example point monitoring function.")
(add-act-r-command "demo-swipe" 'demo-swipe "Touch-demo-model example swipe monitoring function.")
(add-act-r-command "demo-tap-hold" 'demo-tap-hold "Touch-demo-model example tap-hold monitoring function.")
(add-act-r-command "demo-tap-release" 'demo-tap-release "Touch-demo-model example tap-release monitoring function.")
(add-act-r-command "demo-pinch" 'demo-pinch "Touch-demo-model example pinch monitoring function.")
(add-act-r-command "demo-rotate" 'demo-rotate "Touch-demo-model example rotate monitoring function.")
;; Functions for the interaction with the experiment window.
;; When the button is clicked the next hold and release are going to cause
;; the button to be moved. This is a simple demo since the model is performing
;; a specific action sequence and it's easy to deal with since there is only one
;; item on the window, but a more general hold/drag/release would require more
;; work to determine the item when held (instead of an initial click being the
;; indication to drag a specific item).
(defun demo-button-clicked ()
(act-r-output "model clicked the button in the experiment window")
;; set the item and add additional monitors for the tap-hold and tap-release signals
(setf *tapped-item* *created-button*)
(monitor-act-r-command "touch-tap-hold" "start-drag-button")
(monitor-act-r-command "touch-tap-release" "stop-drag-button"))
(defun start-drag-button (model hand finger x y)
(when *tapped-item*
(act-r-output "model ~s starting to drag the example button with finger ~s" model finger)))
(defun stop-drag-button (model hand finger x y)
(when *tapped-item*
(act-r-output "model ~s stopping the drag of the example button with finger ~s" model finger)
(modify-button-for-exp-window *tapped-item* :x (- x 100 50) :y (- y 100 25)) ;; item coords are window referenced but fingers are global and reference point is upper left, but model clicked middle
(setf *tapped-item* nil)
(remove-act-r-command-monitor "touch-tap-hold" "start-drag-button")
(remove-act-r-command-monitor "touch-tap-release" "stop-drag-button")))
;; Create commands for those actions.
(add-act-r-command "demo-button-clicked" 'demo-button-clicked "Touch demo model command for detecting a click/tap on a button in an experiment window.")
(add-act-r-command "start-drag-button" 'start-drag-button "Touch demo model command for detecting tap-hold after clicking the experiment window button.")
(add-act-r-command "stop-drag-button" 'stop-drag-button "Touch demo model command for detecting tap-release after clicking the experiment window button.")
;;;; ---------------------------------------------------------------------- ;;;;
;;;; A Demonstration Model
;;;; ---------------------------------------------------------------------- ;;;;
;;;
;;; Just perform a series of actions covering all the ACT-Touch extensions.
;;; Starting with the right hand:
;;; - move the hand to the stuffed visual-location
;;; - tap the index finger
;;; - tap-hold the index finger
;;; - move the hand to location 450,300
;;; - tap-release the index finger
;;; - swipe index and middle finger right 75 pixels at default speed
;;; - swipe middle, ring, and pinkie fingers up 100 pixels at speed 1
;;; - swipe index and middle finger left 75 pixels at speed 5
;;; - pinch with the index and thumb from 60 pixels apart to 30 pixels apart
;;; - pinch with the ring and thumb from 30 pixels apart to 60 pixels apart
;;; - rotate with the index and thumb 45 deg (.785 radians) clockwise
;;; - rotate with the index and thumb 90 deg (1.57 radians) counter-clockwise
;;; - move the right hand back to where the button was originally
;;; - move the left hand to the touch device (if one indicated as available)
;;; - repeat the above actions for the left hand (except the first movement is to 250,200 instead of 450,300)
(define-model act-touch-demo
;; show all details, don't clear visual-loction automatically, and
;; take longer to move hand when a finger is down on the device
(sgp :v t :trace-detail high :unstuff-visual-location nil :touch-drag-delay t)
;; chunks used as markers in the task
(define-chunks start tapped tap-holding tap-releasing
tapped-dragging-release tapped-dragged-releasing
swiped-default swiped-slow swiped pinched anti-pinched
rotated-45 rotated-90 stop check)
;; Slots and initial goal chunk
(chunk-type goal op hand device)
(define-chunks
(goal op start hand right))
(goal-focus goal)
;; Normal constraint includes attended new, but
;; don't want that since the same item moves
;; without being a new object.
(set-visloc-default screen-x lowest)
(p move-hand
=goal>
op start
hand =hand
=visual-location>
?manual>
state free
==>
+manual>
cmd move-hand-touch
hand =hand
loc =visual-location
=goal>
op tap
loc =visual-location)
(p do-tap
=goal>
op tap
hand =hand
?manual>
state free
==>
+manual>
cmd tap
hand =hand
finger index
=goal>
op tapped)
(p do-tap-hold-right
=goal>
op tapped
hand right
?manual>
state free
?imaginal>
state free
buffer empty
==>
=goal>
op tap-holding
+manual>
cmd tap-hold
hand right
finger index
+imaginal>
screen-x 450
screen-y 300
distance 1080)
(p do-tap-hold-left
=goal>
op tapped
hand left
?manual>
state free
?imaginal>
state free
buffer empty
==>
=goal>
op tap-holding
+manual>
cmd tap-hold
hand left
finger index
+imaginal>
screen-x 250
screen-y 200
distance 1080)
(p do-tapped-dragging-release
=goal>
op tap-holding
hand =hand
?manual>
state free
=imaginal>
screen-x =x
screen-y =y
distance =d
==>
=goal>
op tapped-dragging-release
+manual>
cmd move-hand-touch
loc =imaginal
hand =hand)
(p do-tapped-dragged-releasing
=goal>
op tapped-dragging-release
hand =hand
?manual>
state free
==>
=goal>
op tapped-dragged-releasing
+manual>
cmd tap-release
hand =hand
finger index)
(p do-swipe-default-speed
=goal>
op tapped-dragged-releasing
hand =hand
?manual>
state free
==>
=goal>
op swiped-default
+manual>
cmd swipe
hand =hand
finger index
r 75
theta 0
num-fngrs 2)
(p do-swipe-slow-speed
=goal>
op swiped-default
hand =hand
?manual>
state free
==>
=goal>
op swiped-slow
+manual>
cmd swipe
hand =hand
finger middle
r 100
theta -1.57
num-fngrs 3
swipe-speed 1)
(p do-swipe-fast-speed
=goal>
op swiped-slow
hand =hand
?manual>
state free
==>
=goal>
op swiped
+manual>
cmd swipe
hand =hand
finger index
r 75
theta 3.14
num-fngrs 2
swipe-speed 5)
(p do-pinch
=goal>
op swiped
hand =hand
?manual>
state free
==>
=goal>
op pinched
+manual>
cmd pinch
hand =hand
finger index
start-width 60
end-width 30)
(p do-anti-pinch
=goal>
op pinched
hand =hand
?manual>
state free
==>
=goal>
op anti-pinched
+manual>
cmd pinch
hand =hand
finger ring
start-width 30
end-width 60)
(p do-rotate-45
=goal>
op anti-pinched
hand =hand
?manual>
state free
==>
=goal>
op rotated-45
+manual>
cmd rotate
hand =hand
finger index
rotation .785)
(p do-rotate-minus-90
=goal>
op rotated-45
hand =hand
?manual>
state free
==>
=goal>
op rotated-90
+manual>
cmd rotate
hand =hand
finger index
rotation -1.57)
(p move-right-hand-and-switch
=goal>
op rotated-90
hand right
loc =loc
?manual>
state free
==>
=goal>
op check
hand left
+manual>
cmd move-hand-touch
hand right
loc =loc)
(p move-left-hand-and-stop
=goal>
op rotated-90
hand left
loc =loc
?manual>
state free
==>
=goal>
op stop
+manual>
cmd move-hand-touch
hand left
loc =loc)
(p move-left-to-device
=goal>
op check
device t
?manual>
state free
==>
+manual>
cmd hand-to-touch
hand left
=goal>
op start
device nil)
(p skip-moving-left-to-device
=goal>
op check
device nil
==>
=goal>
op start))
| 20,587 | Common Lisp | .lisp | 527 | 33.550285 | 200 | 0.645181 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0dca0dd4aae6deba8fb82f7be755d6276a38c0c80ec2eba9ef30ba33f9b22ca4 | 14,289 | [
-1
] |
14,290 | virtual-multitouch-device.lisp | asmaloney_ACT-R/extras/act-touch/depricated/virtual-multitouch-device.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Frank Tamborello
;;; Copyright : (c) 2012 Cogscent, LLC
;;; Availability: GNU LGPL, see LGPL.txt
;;; Address : Cogscent, LLC
;;; : PMB 7431
;;; : 2711 Centerville Rd, Ste 120
;;; : Wilmington DE, USA 19808-1676
;;; : [email protected]
;;;
;;; Disclaimer : This library is free software; you can redistribute it and/or
;;; : modify it under the terms of the GNU Lesser General Public
;;; : License as published by the Free Software Foundation; either
;;; : version 2.1 of the License, or (at your option) any later version.
;;; : This library 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
;;; : Lesser General Public License for more details.
;;; : You should have received a copy of the GNU Lesser General Public
;;; : License along with this library; if not, write to the Free Software
;;; : Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
;;; : USA
;;;
;;; Acknowledgements
;;; : This research is sponsored by Measurement Science and
;;; Engineering grant 60NANB12D134 from the
;;; National Institute of Standards and Technology (NIST).
;;; Special acknowledgements are due to Dr. Ross Micheals and
;;; Dr. Kristen K. Greene of NIST's Information Technology
;;; Laboratory.
;;; Thanks also to Dr. Michael D. Byrne, upon whose experiment
;;; library code I based the device code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : virtual-multitouch-device.lisp
;;; Revision : 1
;;;
;;; Description : A virtual multi-touch display device for use with ACT-Touch
;;;
;;; Usage : Place in ACT-R folder "User Loads." This file will load
;;; automatically after ACT-R loads.
;;;
;;; Bugs : None known
;;;
;;; To do : Nothing
;;;
;;; ----- History -----
;;; 2012.09.29 fpt 1
;;; : Inception: Forked from act-touch.lisp
;;; 2014.12.01 Dan Bothell
;;; : Commented out the initialize-instance after method for the
;;; : multitouch-display class since it was specific code to setup
;;; : and run the example model, and moved the example run code from
;;; : the end into the comment with the initialize-instance method.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Multitouch Display Device
;;;; ---------------------------------------------------------------------- ;;;;
;;;; A slightly more sophisticated device than a list.
;;;; Let's start with the simplest case: The user is holding the device with the
;;;; left hand and using the right hand to input. The right hand defaults to being
;;;; at rest at the right edge of the display, centered vertically, with the index
;;;; finger hovering an inch above the display surface. There are some multitouch
;;;; interface widgets on-screen. The user interacts with each of them.
;;;; ---------------------------------------------------------------------- ;;;;
;;;; The window & trial management stuff
;;;; ---------------------------------------------------------------------- ;;;;
(defclass multitouch-display ()
((visual-world :accessor visual-world :initarg :visual-world :initform nil)
;; Distance of the index finger to the display surface, in pixels.
(index-z :accessor index-z :initarg :index-z :initform 72)
(widgets :accessor widgets :initarg :widgets :initform nil)))
#|
This method could be used to setup and run the example model found
in the act-touch-demo-model.lisp file by just using this call:
(progn
(reset)
(setf *experiment* (make-instance 'multitouch-display)))
However, there is a function in that file which can also be used
without having the after method defined for all instances of the
multitouch-display class.
; Visual-world & widgets
(defmethod initialize-instance :after ((wind multitouch-display) &key)
(let* ((vis-locs
(define-chunks-fct
;; Remember, the display is 1024 x 768 px
'((screen-x 500 screen-y 350 kind rectangle height 200 width 200 color red))))
(vis-objs
(define-chunks-fct
`((height ,(chunk-slot-value-fct (car vis-locs) 'height)
width ,(chunk-slot-value-fct (car vis-locs) 'width)
color ,(chunk-slot-value-fct (car vis-locs) 'color)
screen-pos ,(car vis-locs)))))
(wgts (list (make-instance 'test-widget :vwindow wind :vis-loc (car vis-locs)
:vis-obj (car vis-objs) :nick-name :TAP))))
(setf (visual-world wind) (pairlis vis-locs vis-objs)
(widgets wind) wgts))
(set-hand-location left 0 300)
(set-hand-location right 1024 300)
(install-device wind)
(goal-focus goal)
(proc-display)
; (start-timing (timer wind))
(run 20))
|#
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Multitouch Interface Widgets
;;;; ---------------------------------------------------------------------- ;;;;
(defclass virtual-widget ()
((nick-name :accessor nick-name :initarg :nick-name :initform nil)
(vwindow :accessor vwindow :initarg :vwindow :initform nil)
(vis-loc :accessor vis-loc :initarg :vis-loc :initform nil)
(vis-obj :accessor vis-obj :initarg :vis-obj :initform nil)
(action-type :accessor action-type :initarg :action-type :initform nil)))
(defgeneric vwidget-named (virtual-experiment-window name)
(:documentation "Vwidget-named returns the first virtual-widget of
virtual-experiment-window whose name is name."))
(defmethod vwidget-named ((vew multitouch-display) name)
(let ((vw (visual-world vew)))
(vwn-helper vw name)))
(defun vwn-helper (lst name)
(if (null lst) nil
(let* ((wgt (car lst))
(wnn (nick-name wgt)))
(if
(eq name wnn) wgt
(vwn-helper (cdr lst) name)))))
(defclass test-widget (virtual-widget)
()
(:default-initargs
:action-type 'test-widget))
(defgeneric current-widget (device finger-loc)
(:documentation "Given the device and the finger location, return a widget
containing the finger location."))
(defmethod current-widget ((device multitouch-display) (finger-loc vector))
(current-widget-helper (widgets device) finger-loc))
(defun current-widget-helper (widgets finger-loc)
(cond
((null widgets) nil)
((inside finger-loc (vis-loc (car widgets))) (car widgets))
(t (current-widget-helper (cdr widgets) finger-loc))))
(defun inside (loc vl)
"Takes a display coordinate as a vector and a visual-location chunk name,
returns t if the display coordinate
is inside the area of the named visual-location chunk."
(let* ((x1 (chunk-slot-value-fct vl 'screen-x))
(x2 (+ x1 (chunk-slot-value-fct vl 'width)))
(y1 (chunk-slot-value-fct vl 'screen-y))
(y2 (+ y1 (chunk-slot-value-fct vl 'height))))
(and (>= (svref loc 0) x1)
(<= (svref loc 0) x2)
(>= (svref loc 1) y1)
(<= (svref loc 1) y2))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; ACT-R Device Handler Methods
;;;; ---------------------------------------------------------------------- ;;;;
(defmethod cursor-to-vis-loc ((device list))
nil)
(defmethod build-vis-locs-for ((device list) vismod)
(declare (ignore vismod))
(mapcar 'car device))
(defmethod build-vis-locs-for ((device multitouch-display) vismod)
(declare (ignore vismod))
(mapcar 'car (visual-world device)))
(defmethod vis-loc-to-obj ((device list) vis-loc)
(cdr (assoc vis-loc device)))
(defmethod vis-loc-to-obj ((device multitouch-display) vis-loc)
(cdr (assoc vis-loc (visual-world device))))
(defvar *mouse-pos* (vector 0 0))
(defmethod device-move-cursor-to (device loc)
(declare (ignore device))
(model-output "Model moved mouse to ~A" loc)
(setf *mouse-pos* loc))
(defmethod get-mouse-coordinates (device)
(declare (ignore device))
*mouse-pos*)
(defmethod device-handle-click (device)
(declare (ignore device))
(model-output "Model clicked the mouse"))
(defmethod device-handle-keypress (device key)
(declare (ignore device))
(model-output "Model pressed key ~c" key))
(defgeneric device-handle-tap (device loc &rest params)
(:documentation "Handle the tap gesture."))
(defmethod device-handle-tap ((device multitouch-display) (loc list) &rest params)
(model-output "Model tapped ~A at ~A." params loc))
(defmethod device-handle-tap ((device multitouch-display) (loc vector) &rest params)
(awhen
(current-widget device loc)
(progn
(model-output "Model tapped ~A at ~A with ~A." (nick-name it) loc params))))
(defmethod device-handle-tap-hold ((device multitouch-display) &rest params)
(setf (index-z (current-device)) 0)
(model-output "Model tap-held ~A." params))
(defmethod device-handle-tap-release ((device multitouch-display) &rest params)
(setf (index-z (current-device)) 72)
(model-output "Model tap-released ~A." params))
(defmethod device-handle-tap-drag-release ((device multitouch-display) &rest params)
(model-output "Model tap-drag-released ~A." params))
(defmethod device-handle-pinch ((device multitouch-display) &rest params)
(model-output "Model pinched ~A." params))
(defmethod device-handle-rotate ((device multitouch-display) &rest params)
(model-output "Model rotated ~A." params))
(defgeneric device-handle-swipe (device loc &rest params)
(:documentation "Handle the swipe gesture."))
(defmethod device-handle-swipe ((device multitouch-display) (loc vector) &rest params)
(awhen
(current-widget device loc)
(progn
(model-output "Model swiped ~A at ~A with ~A." (nick-name it) loc params))))
| 10,114 | Common Lisp | .lisp | 212 | 44.028302 | 92 | 0.632148 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 83e1c5e62633bd8ed4b36db97083daf01a6f5413cb14f93069761ddc20b70135 | 14,290 | [
-1
] |
14,291 | act-touch-demo-model.lisp | asmaloney_ACT-R/extras/act-touch/depricated/act-touch-demo-model.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Frank Tamborello
;;; Copyright : (c) 2012 Cogscent, LLC
;;; Availability: GNU LGPL, see LGPL.txt
;;; Address : Cogscent, LLC
;;; : PMB 7431
;;; : 2711 Centerville Rd, Ste 120
;;; : Wilmington DE, USA 19808-1676
;;; : [email protected]
;;;
;;; Disclaimer : This library is free software; you can redistribute it and/or
;;; : modify it under the terms of the GNU Lesser General Public
;;; : License as published by the Free Software Foundation; either
;;; : version 2.1 of the License, or (at your option) any later version.
;;; : This library 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
;;; : Lesser General Public License for more details.
;;; : You should have received a copy of the GNU Lesser General Public
;;; : License along with this library; if not, write to the Free Software
;;; : Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
;;; :
;;;
;;; Acknowledgements
;;; : This research is sponsored by Measurement Science and
;;; Engineering grant 60NANB12D134 from the
;;; National Institute of Standards and Technology (NIST).
;;; Special acknowledgements are due to Dr. Ross Micheals and
;;; Dr. Kristen K. Greene of NIST's Information Technology
;;; Laboratory.
;;; Thanks also to Dr. Michael D. Byrne, upon whose experiment
;;; library code I based the device code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : act-touch-demo-model.lisp
;;; Revision : 1
;;;
;;; Description : A quickie demonstration of ACT-Touch
;;;
;;; Usage : Load this file and call run-touch-demo to run the demonstration
;;; : model. Does not require loading act-touch separately.
;;;
;;; Bugs : None known
;;;
;;; To do : Nothing
;;;
;;; ----- History -----
;;; 2012.09.29 fpt 1
;;; : Inception: Forked from act-touch.lisp
;;; 2014.12.01 Dan Bothell
;;; : Added the run-touch-demo function which includes the code
;;; : from the after method that was previously defined in the
;;; : virtual-multitouch-device.lisp file.
;;; : Added a chunk-type named goal with a slot named op.
;;; : Added chunk definitions for all of the chunks in the model.
;;; 2016.03.14 Dan Bothell
;;; : Added the require-extra so that it automatically loads the
;;; : act-touch extension if it's not already available.
;;; 2018.10.25 Dan Bothell
;;; : Use the new start-hand-at-touch command to position the hands
;;; : so the offsets are set correctly.
;;; : Changed the productions so that it performs all of the actions
;;; : sequentially without having to change the op slot from code.
;;; : Added some different speed swipes.
;;; : Changed the queries to state free so it's easier to see
;;; : the individual actions.
;;; : Added another rotate to see the difference in time by angle now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; ---------------------------------------------------------------------- ;;;;
;;;; A Demonstration Model
;;;; ---------------------------------------------------------------------- ;;;;
(clear-all)
(require-extra "act-touch")
(defun run-touch-demo ()
(reset)
(let* ((wind (make-instance 'multitouch-display))
(vis-locs
(define-chunks-fct
;; Remember, the display is 1024 x 768 px
'((screen-x 500 screen-y 350 kind rectangle height 200 width 200 color red))))
(vis-objs
(define-chunks-fct
`((height ,(chunk-slot-value-fct (car vis-locs) 'height)
width ,(chunk-slot-value-fct (car vis-locs) 'width)
color ,(chunk-slot-value-fct (car vis-locs) 'color)
screen-pos ,(car vis-locs)))))
(wgts (list (make-instance 'test-widget :vwindow wind :vis-loc (car vis-locs)
:vis-obj (car vis-objs) :nick-name :TAP))))
(setf (visual-world wind) (pairlis vis-locs vis-objs)
(widgets wind) wgts)
(start-hand-at-touch) ;; default right hand 1024,300
(start-hand-at-touch 'left 0 300)
(install-device wind)
(proc-display)
(run 20)))
(define-model act-touch-demo
(sgp :v t :trace-detail high)
(chunk-type goal op)
(define-chunks (rectangle) (start) (tapped) (tap-holding) (tap-releasing)
(tap-drag-release) (tapping-drag-release) (tapped-dragging-release)
(tapped-dragged-releasing) (swiped) (pinched) (rotated)(swiped-default)
(swiped-slow)(rotated-45) (rotated-90) (rotated-180))
(add-dm
(goal op start))
(goal-focus goal)
(p move-hand
=goal>
op start
=visual-location>
color red
?manual>
state free
==>
+manual>
cmd move-hand-touch
loc =visual-location
=goal>
op tap)
(p do-tap
=goal>
op tap
?manual>
state free
==>
+manual>
cmd tap
hand right
finger index
=goal>
op tapped)
(p do-tap-hold
=goal>
op tapped
?manual>
state free
==>
=goal>
op tap-holding
+manual>
cmd tap-hold
hand right
finger index)
(p do-tap-release
=goal>
op tap-holding
?manual>
state free
==>
=goal>
op tap-releasing
+manual>
cmd tap-release
hand right
finger index)
;; Here's an example of a composed movement: the tap-hold, drag, & release
(p do-tapping-drag-release
=goal>
op tap-releasing
?manual>
state free
?imaginal>
buffer empty
==>
=goal>
op tapping-drag-release
+manual>
cmd tap-hold
hand right
finger index
+imaginal>
screen-x 550
screen-y 400)
(p do-tapped-dragging-release
=goal>
op tapping-drag-release
?manual>
state free
=imaginal>
screen-x =x
screen-y =y
==>
=goal>
op tapped-dragging-release
+manual>
cmd move-hand-touch
loc =imaginal)
(p do-tapped-dragged-releasing
=goal>
op tapped-dragging-release
?manual>
state free
==>
=goal>
op tapped-dragged-releasing
+manual>
cmd tap-release
hand right
finger index)
(p do-swipe-default-speed
=goal>
op tapped-dragged-releasing
?manual>
state free
==>
=goal>
op swiped-default
+manual>
cmd swipe
hand right
finger index
r 50
theta 0
num-fngrs 2)
(p do-swipe-slow-speed
=goal>
op swiped-default
?manual>
state free
==>
=goal>
op swiped-slow
+manual>
cmd swipe
hand right
finger index
r 50
theta 0
num-fngrs 2
swipe-speed 1)
(p do-swipe-fast-speed
=goal>
op swiped-slow
?manual>
state free
==>
=goal>
op swiped
+manual>
cmd swipe
hand right
finger index
r 50
theta 0
num-fngrs 2
swipe-speed 5)
(p do-pinch
=goal>
op swiped
?manual>
state free
==>
=goal>
op pinched
+manual>
cmd pinch
hand right
finger index
start-width 20
end-width 50)
(p do-rotate-45
=goal>
op pinched
?manual>
state free
==>
=goal>
op rotated-45
+manual>
cmd rotate
hand right
finger index
rotation .785) ; it's in radians
(p do-rotate-90
=goal>
op rotated-45
?manual>
state free
==>
=goal>
op rotated-90
+manual>
cmd rotate
hand right
finger index
rotation 1.57)
(p do-rotate-180
=goal>
op rotated-90
?manual>
state free
==>
=goal>
op rotated-180
+manual>
cmd rotate
hand right
finger index
rotation 3.14)
)
| 8,003 | Common Lisp | .lisp | 301 | 22.528239 | 92 | 0.600811 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 43b743588c7a8742c1ad079db06e0c4fed39ab901c4e50c3e842b9da3aa6c7aa | 14,291 | [
-1
] |
14,292 | save-model.lisp | asmaloney_ACT-R/extras/save-model/save-model.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2016 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : save-model.lisp
;;; Version : 1.0
;;;
;;; Description : A file to load save-chunks-and-productions.lisp automatically with require-extra.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2016.03.14 Dan
;;; : * Creation.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(when (requiring-extra)
(compile-and-load (translate-logical-pathname "ACT-R:extras;save-model;save-chunks-and-productions.lisp")))
(provide "save-model")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 1,969 | Common Lisp | .lisp | 49 | 38.795918 | 109 | 0.54232 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 55eb4b69e0d8b3f1ab10d6dae033e30fd444032141ef30c6bebe8fc27113e281 | 14,292 | [
489234
] |
14,293 | audio.lisp | asmaloney_ACT-R/core-modules/audio.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Mike Byrne & Dan Bothell
;;; Address : Rice University, MS-25
;;; : Psychology Department
;;; : Houston,TX 77251-1892
;;; : [email protected]
;;;
;;; Copyright : (c)1998-2005 Mike Byrne/Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : audio.lisp
;;; Version : 7.0
;;;
;;; Description : Source for RPM's Audition Module
;;;
;;; Bugs : *
;;;
;;; Todo : * [x] Should there be audio buffer stuffing as well?
;;; : * [X] Add a set-audioloc-defaults command like the set-visloc-
;;; : default to give more control over stuffing so that
;;; : the :hear-newest-only parameter can go away.
;;; : * [X] Change the request function so that modifiers and ranges
;;; : are accepted and add pitch as an option (alternatively
;;; : convert the audicon over to holding chunks and use the
;;; : more general chunk matching tools...)
;;; : * [ ] Should it automatically stuff aural-location when there
;;; : are events in the audicon and the buffer is cleared
;;; : instead of waiting for a change before doing so?
;;; : * [X] Deal with possible long run timing issues due to
;;; : floating point imprecision since detection time involves
;;; : an addition of a "current" time which could be too big
;;; : to represent milliseconds with a delay that's likely to be
;;; : in the 50-200ms range.
;;; : * [ ] There's a problem with using the ID and EVENT slots to
;;; : point to the original chunk since that means it has to
;;; : stay around (can't just delete it when done). The right
;;; : solution is to work like vision where the object chunk
;;; : refers to the actual location chunk in the buffer and the
;;; : location chunk doesn't have a "self link" which will
;;; : require changing how things map back to the module chunks.
;;; ----- History -----
;;;
;;; 2005.01.07 mdb [act6a1]
;;; : Transition to ACT6 stuff.
;;; 2005.01.08 Dan
;;; : More updates to move to 6
;;; :
;;; : Changed aural-location to audio-event in request-audio-module
;;; : (alternatively audio-event could be changed to aural-location
;;; : in reset-audio-module but this way is backward compatible
;;; : to ACT-R 5)
;;; :
;;; : Removed the :offset parameter in the scheduling of find-sound
;;; : in request-audio-module because it isn't defined in find-sound
;;; :
;;; : Changed find-sound to put the chunk into the buffer
;;; :
;;; : Changed find-sound because the chunk that comes in doesn't
;;; : have the same name as the one in the audicon because it will
;;; : be a copy from the buffer.
;;; :
;;; : To get around that (for now at least) I've added an id slot
;;; : to the audio-event chunk-type which will always have the
;;; : original value.
;;; :
;;; : The event->dmo method was modified to set that value.
;;; :
;;; : Changed audio-encoding-complete so that it sets the chunk
;;; : in the aural buffer.
;;; :
;;; : Related to the issue above with sound event names - the
;;; : sound put into the buffer has its event set to the "original"
;;; : event name (the id slot of the audio-event) which doesn't
;;; : correspond to the name of a chunk in DM, but it will match
;;; : an audio-event with that value in its id slot (assuming the
;;; : aural-location buffer has cleared so that the chunk goes to
;;; : DM).
;;; :
;;; : That seems reasonable for now at least.
;;; :
;;; : Put the aural-location stuffing in:
;;; ; Added the :around method for new-sound-event
;;; : Added the stuff-sound-buffer function.
;;; :
;;; 2005.01.09 Dan
;;; : Added the clearing of the audicon to the reset-audio-module
;;; : function.
;;; : Added the word chunk to the audicon.
;;; 2005.01.10 Dan
;;; : Maintain the stuffed slot of the audio module now since
;;; : I added the buffer stuffing back in.
;;; 2005.01.11 mdb
;;; : Put in parameter doc strings.
;;; 2005.01.21 Dan
;;; : * Removed use of buffer-chunk and replaced with buffer-read.
;;; 2005.01.21 Dan
;;; : * Wrapped the proclaim in an eval-when because otherwise
;;; : it may not actually affect the compilation.
;;; 2005.02.03 Dan
;;; : * Added ":output 'medium" to some of the events that are
;;; : scheduled to play friendly with the new detail level.
;;; 2005.04.23 Dan
;;; : * Updated find-sound so that it indicates whether the chunk
;;; : being put into the buffer was stuffed or not.
;;; : * Changed stuff-sound-buffer to indicate that.
;;; : * Removed the check of stuffed from query-audio-module.
;;; : * Added attended as a possible query but I'm unsure if I've
;;; : got the testing quite right...
;;; 2005.04.29 Dan
;;; : * Added a print-audicon command that works basically like
;;; : print-visicon for visual - it prints a table of info for
;;; : the sound-events currently in the audicon.
;;; 2005.07.22 Dan
;;; : * Updated the module definition to use the pm-module-request
;;; : method and renamed the audio-module-request function
;;; : accordingly.
;;; 2005.08.03 Dan
;;; : * Added a find-sound-failure event to the trace when find-
;;; : sound fails. Also adjusted the find-sound event scheduling
;;; : so that it gets output in the medium level trace detail.
;;; 2005.08.10 Dan
;;; : * Commented out the offset value in the audio-event request
;;; : because it wasn't used.
;;; 2005.12.14 Dan
;;; : * Added :sound-decay-time parameter which seems to have been
;;; : lost in the move to 6.
;;; 2006.01.04 Dan
;;; : * Removed a duplicate instance of :tone-recode-delay in the
;;; : case of the parameter handling in params-audio-module and
;;; : replaced it with :tone-detect-delay (which is what it
;;; : should have been).
;;; 2006.03.24 Dan
;;; : * Added a new parameter called :hear-newest-only and changed
;;; : stuff-sound-buffer to include :onset :highest when that's
;;; : set because it seems like often one might want the newest
;;; : sound to be the one that gets stuffed into the buffer.
;;; : The default is nil to keep it compatible with the old
;;; : version for now, but should it default to t?
;;; 2006.05.03 Dan
;;; : * Fixed a bug in pm-module-request for aural-location requests
;;; : in specifying the location (it was testing the onset slot.)
;;; 2006.05.03 Dan
;;; : * Turns out that loc-failure and attend-failure weren't
;;; : really being set/cleared so add that in now.
;;; 2006.05.03 Dan
;;; : * Fixed attend-sound so that it checks the current-audicon
;;; : so that old sounds get purged as needed.
;;; 2006.09.08 Dan
;;; : * Changed several parameter tests from posnum to nonneg.
;;; 2006.11.20 Dan
;;; : * Fixed the bug in stuff-sound-buffer because it should be
;;; : :onset 'highest not :highest...
;;; : * Changed the version to 2.2 (dropped the a1) and updated the
;;; : doc string so that it doesn't say "first pass".
;;; 2006.12.20 Dan
;;; : * Changed the version in the class definition too...
;;; 2007.01.03 Dan
;;; : * Changed the scheduling of the stuff-sound-buffer event
;;; : to :output nil and :maintenance t because the set-buffer-chunk
;;; : ... requested nil shows that the stuffing occurs already -
;;; : no point in two events showing for the same thing.
;;; : * Also changed the test for the empty buffer slightly because
;;; : buffer-read is a bit of a hack for that purpose.
;;; : * Took attended out of the audio-event chunk-type and made it
;;; : a request parameter instead (actually just started using the
;;; : request parameter that was already there).
;;; 2007.01.04 Dan
;;; : * Took the string column out of the audicon printing because
;;; : its going to be the same as content when it's provided.
;;; : * Similarly, changed the content column to be printed with
;;; : ~s instead of ~a so that strings are differentiated from
;;; : symbols for content.
;;; : * Added a column for detectable to the audicon printing.
;;; : * Changed attend-sound to check exec-s instead of check-jam
;;; : because the attend-sound doesn't set the preparation state
;;; : to busy (which is what check-jam looks at).
;;; : * Use randomize-time in scheduling the attend-sound-failure
;;; : event.
;;; : * Removed the update function from the module definition
;;; : because it didn't do anything.
;;; : * Fixed new-sound-event to better check for model/mp/module
;;; : and report a warning if not available - also switched the
;;; : return value to t/nil instead of returning the stuff-sound
;;; : scheduler event.
;;; : * Converted the new-*-sound methods to functions so that
;;; : parameter validation is handled explicitly. So that
;;; : ACT-R warnings can be printed instead of Lisp errors being
;;; : generated when invalid values are used (yes there are more
;;; : "CLOS-y" ways of doing it, but call me old fashioned...).
;;; : * Took the optional instr parameter out of new-other-sound
;;; : because the string component of the sound-events doesn't
;;; : really have a purpose. [Or am I missing something?]
;;; 2007.01.10 Dan
;;; : * Added location and kind optional parameters to new-other-sound.
;;; : * Changed the call to get-articulation-time because the
;;; : speech module is no longer needed as a parameter (though the
;;; : module itself still needs to exist).
;;; 2007.01.18 Dan
;;; : * Turns out that stuff-sound-buffer can't be a maintenance
;;; : event because that event needs to be able to trigger
;;; : conflict-resolution because until the schedule-set-buffer-chunk
;;; : event gets scheduled other model events could have pushed
;;; : conflict-resolution into the future... (probably doesn't
;;; : make sense to anyone else, but I know what it means)
;;; 2007.03.29 Dan
;;; : * Incremented version to 2.3.
;;; : * Added the set-audloc-default command and depricated the
;;; : hear-newest-only parameter because of that.
;;; 2007.04.03 Dan
;;; : * Some cleanup of the set-audloc-default command - better
;;; : testing of params and validity (allowing none for example).
;;; 2008.06.03 Dan
;;; : * Added an after method for clear to clear the error states
;;; : as is done for vision, but maybe that needs to move up to
;;; : the attn-module class method.
;;; 2011.04.28 Dan
;;; : * Added a declaim to avoid a compiler warning about an
;;; : undefined function.
;;; 2011.05.16 Dan
;;; : * Replaced pm-warning calls with model-warning.
;;; 2011.05.17 Dan
;;; : * Replaced queue-command calls with schedule-event-relative.
;;; 2011.05.18 Dan
;;; : * Removed detectable-time since it was the same as detect-at-time
;;; : and there's no need for two methods that compute the same thing.
;;; : * Starting to convert over to using ms internally for the sound-
;;; : event components to avoid issues with math on seconds.
;;; 2011.11.09 Dan
;;; : * Commented out the *enable-package-locked-errors* line for ACL
;;; : because it no longer seems to be necessary and it sets up a
;;; : dangerous situation for users since that setting enables the
;;; : redefinition of CL functions without warning.
;;; 2012.05.14 Dan
;;; : * Fixed a bug with the offset time of the audio-event chunks
;;; : being in ms while the onset was in seconds.
;;; 2012.05.14 Dan [2.4]
;;; : * Added another request parameter to the aural-location buffer:
;;; : :finished. It can be requested as t or nil to determine if
;;; : a sound is already completed or not.
;;; : * A corresponding finished query is also available which works
;;; : like the attended query -- if there is a chunk in the buffer
;;; : then finished tests whether the property of that chunk matches
;;; : the queried value.
;;; : * Changed the finished-p method so it always returns t or nil
;;; : since >= only returns a generalized boolean and that matters
;;; : for testing in the query.
;;; : * Updated set-audloc-default so that it also accepts finished.
;;; : * Added a duration slot to the audio-event type so that one
;;; : doesn't have to do the math with offset and onset values.
;;; : * Added the audio-event-ended function which gets scheduled
;;; : by attend-sound to set the offset and duration of the chunk
;;; : in the aural-location buffer if it's still there when the
;;; : attended sound stops.
;;; 2013.10.02 Dan
;;; : * Commented out the optimize proclaim since that persists and
;;; : may or may not be useful anyway.
;;; 2014.03.17 Dan [3.0]
;;; : * Changed the query-buffer call to be consistent with the new
;;; : internal code.
;;; 2014.05.16 Dan
;;; : * Continue the conversion to type-less chunks.
;;; : * First step is to switch over to testing the chunks in the audicon!
;;; : * Print-audicon sorts the events by onset time (lowest first).
;;; 2014.05.19 Dan
;;; : * New-other-sound now allows for specifying additional slots and
;;; : values for the event and/or the sound chunks. They are provided
;;; : as 3 element lists after all the optional parameters. The first
;;; : item in the list is either :evt, :sound, or :both to indicate
;;; : which chunk gets the slot and value specified with the second
;;; : and third items respectively.
;;; : * Testing the chunks in the audicon instead of the sound-event
;;; : object allows for +aural-location to specify things more freely:
;;; : slots can be specified more than once, any operator is allowed,
;;; : user specified slots for an event can be provided, and higest and
;;; : lowest can be used for any slot.
;;; 2014.05.30 Dan
;;; : * Use the test-for-clear-request function in pm-module-request.
;;; : * Use an isa sound/audio-event when creating the chunks so that
;;; : the "backward" slots exist when needed.
;;; 2014.08.13 Dan
;;; : * Either I can't use the name of the audicon chunk in the ID
;;; : and EVENT slots or I can't delete that chunk when it leaves
;;; : the audicon! I think the right solution is to get rid of
;;; : the ID slot and have the EVENT refer to the actual audio-event
;;; : chunk that's in the buffer, but that requires a lot of reworking
;;; : things (like the internals of vision so that things can refer
;;; : to the original internal module chunk). So, for now
;;; 2014.10.30 Dan [3.1]
;;; : * I guess that should have said "for now leave it alone and
;;; : don't delete the chunks".
;;; : * Eliminating the previously depricated :hear-newest-only
;;; : parameter.
;;; : * Changed the last-command value for an aural-location request
;;; : from audio-event to find-sound.
;;; : * Added an event to the queue when a set-audloc-default request
;;; : is processed.
;;; : * Added some more chunks to those defined by the module.
;;; 2015.03.20 Dan
;;; : * Failures now set the buffer failure flags using set-buffer-failure.
;;; 2015.03.23 Dan
;;; : * Specify whether a find-sound-failure is requested or not i.e.
;;; : if it's stuffed then that's not requested.
;;; 2015.04.22 Dan [3.2]
;;; : * Add the unstuff-aural-location parameter which will cause
;;; : stuffed chunks to be removed either after a time indicated,
;;; : when the corresponding sound leaves the audicon if it is t,
;;; : or pushed out by a new stuffed chunk.
;;; 2015.06.02 Dan [3.3]
;;; : * Report onset and offset times in milliseconds now to avoid
;;; : potential issues with float conversions and also allow the
;;; : new-*-sound functions to specify onset in ms by providing a
;;; : new optional parameter to each which if given as t means
;;; : the onset time is ms instead of s.
;;; 2015.06.04 Dan
;;; : * Convert all the parameters that are seconds to ms when they're
;;; : set so it doesn't need to do so everywhere they are used.
;;; : * Use the ms return from get-articulation-time now too.
;;; : * All scheduled events specify time-in-ms.
;;; 2015.06.16 Dan
;;; : * Fixed a bug in one of the calls to schedule-event-now that
;;; : was replacing a relative 0.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; : * Changed default value of unstuff-aural-location to t.
;;; 2015.07.29 Dan [3.4]
;;; : * Changed the way the check-unstuff-buffer action is scheduled
;;; : because that's now the precondition and unstuff-buffer is the
;;; : actual action.
;;; : * Splitting the unstuff- parameter into two parameters:
;;; : :unstuff-aural-location can be nil, t, or # and indicates
;;; : whether to take a stuffed chunk out of the buffer and
;;; : defaults to t.
;;; : :overstuff-aural-location determines whether or not to
;;; : stuff a new chunk overtop of a previously stuffed chunk
;;; : and defaults to nil.
;;; : * When an unstuff is scheduled save it so that it can be
;;; : deleted if another gets scheduled.
;;; 2015.07.30 Dan
;;; : * Fixed a bug with the unstuffing time because it was computed
;;; : as an absolute time but scheduled as relative when set to t.
;;; 2015.07.31 Dan
;;; : * Changed the default values for unstuff and overstuff. They
;;; : are now nil and t respectively because that seems to work
;;; : better for the way audio gets used which is not as frequent
;;; : as speech output which triggers audio percepts so don't want
;;; : a potentially unused system affecting performance.
;;; 2015.08.17 Dan
;;; : * Changed the randomize-time calls which were used with times
;;; : in ms to randomize-time-ms.
;;; 2015.09.17 Dan [4.0]
;;; : * Making the aural buffer trackable and having it complete
;;; : requests.
;;; : * Adding the last-aural-request slot to audio-module to hold
;;; : the request for completion.
;;; 2015.09.22 Dan
;;; : * Fixed some syntax issues with the previous changes.
;;; 2016.01.11 Dan
;;; : * Changed how print-audicon displays the location, it uses
;;; : a ~s instead of ~a in the format string, so that a string
;;; : value for locations shows up correctly.
;;; 2016.06.29 Dan [4.1]
;;; : * Changing the default value for :overstuff-aural-location back
;;; : to nil for performance reasons. If a model is speaking or
;;; : subvocalizing and not using the aural information that constant
;;; : re-stuffing of the buffer is costly, and if a model is using the
;;; : aural info, then it probably doesn't need to be overstuffed
;;; : anyway.
;;; 2016.07.15 Dan
;;; : * The unstuff-buffer events didn't specify the module as audio
;;; : but do now.
;;; 2017.01.26 Dan [5.0]
;;; : * Added remote versions of the new-{word|digit|tone}-sound
;;; : commands. New-other-sound hasn't been added yet because I'm
;;; : not sure what the right way to provide that should be since
;;; : the values for content and other features are arbitrary.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Reworked the local versions of the remote commands to not
;;; : go out through the dispatcher.
;;; 2017.05.23 Dan [5.1]
;;; : * Instead of setting the offset and duration for the chunk in
;;; : the aural-location buffer if it's still there when a sound is
;;; : attended to (would require the model keep it around explicitly)
;;; : schedule that event when the chunk enters the aural-location
;;; : buffer because it's possible for the attention shift to occur
;;; : after the sound goes off which results in a warning that the
;;; : time has already passed. Alternatively, it could check for the
;;; : current time to avoid the warning and continue to only update
;;; : the chunk when it's attended to, but I think it's better to
;;; : update it with the info when available.
;;; : * The previous change breaks the current code for "overstuffing"
;;; : since when the sound ends it modifies the chunk in the buffer
;;; : which then prevents it from being replaced by a new stuffed
;;; : chunk. The fix is to not require that the chunk is unmodified,
;;; : but that it is still a match to the original event information.
;;; : * Do that test with a precondition and change the unstuffing
;;; : precondition to deal with the possibility of a modification.
;;; : * Audio-event-ended is now a maintenance event and only if there's
;;; : a change is a model event created -- this eliminates some
;;; : spurious conflict-resolution tests when there wasn't really
;;; : a update because of the sound ending.
;;; : * Actually use the version-string from the class to set the
;;; : version in the model.
;;; 2017.07.14 Dan
;;; : * Adding locks to protect the audicon and the parameters to
;;; : make things thread safe.
;;; 2017.08.03 Dan
;;; : * Have new-sound-event call the new-sound function through the
;;; : dispatcher for monitoring purposes.
;;; 2017.08.04 Dan
;;; : * Fixed the poor cut-and-paste job with the last update.
;;; 2017.08.09 Dan
;;; : * Update the buffer-status function to return the string.
;;; : * Added printed-audicon to return the output string.
;;; : * Update the reset and clear code to directly change slot values
;;; : instead of relying on the attn-module methods.
;;; : * Also don't use set/clear-attended methods.
;;; 2017.08.11 Dan
;;; : * Fixed a cut-and-paste error with the clear method.
;;; 2017.09.06 Dan
;;; : * Make print-audicon and printed-audicon available remotely.
;;; 2017.09.21 Dan
;;; : * Make new-sound a signal and schedule it to happen at the
;;; : onset time of the sound instead of calling it immediately
;;; : upon the sound's creation.
;;; : * Added a missing newline to the end of items in printed-audicon.
;;; 2018.01.26 Dan
;;; : * Changed the buffer-status function to omit the extra newline.
;;; 2018.05.24 Dan
;;; : * Added a details value to the scheduling of audio-encoding-
;;; : complete so that the trace shows the event instead of the
;;; : internal audicon structure.
;;; : * Cleaned up new-other-sound so that it converts strings to
;;; : symbols and added a remote version.
;;; 2018.05.25 Dan
;;; : * Added a remote set-audloc-default.
;;; 2018.06.01 Dan
;;; : * Param-lock was moved to the pm-module class.
;;; 2018.06.12 Dan
;;; : * Only external commands do the string conversion now.
;;; : * Removed some verify-current-mp calls while updating things.
;;; 2018.07.26 Dan [5.2]
;;; : * Removing the code to support request tracking.
;;; 2018.11.16 Dan [5.3]
;;; : * Start to Add new parameters :aural-encoding-hook :aural-loc-
;;; : encoding-hook which work like :visual-encoding-hook to allow
;;; : the user to override the default timing.
;;; 2018.11.19 Dan
;;; : * Changing the parameter to :aural-loc-hook because it's not
;;; : the encoding, and works more like :retrieval-set-hook than
;;; : :visual-encoding-hook.
;;; : * Grab the audicon-lock when setting an item as attended.
;;; : * Current-marker doesn't seem to do anything. So going to
;;; : use it for implementing the :aural-encoding-hook.
;;; : * Similarly, currently-attended isn't really used, but going
;;; : to keep setting it anyway.
;;; : * Adding a lock around those two things now (don't know why
;;; : they didn't but probably because they weren't used). The
;;; : new lock is the aural-attn-lock.
;;; : * Added the schedule-audio-encoding-complete function to go
;;; : along with the :aural-encoding-hook.
;;; 2018.11.20 Dan
;;; : * Added the remote schedule-audio-encoding-complete.
;;; 2020.01.10 Dan [5.4]
;;; : * Removed the #' and lambdas from the module interface
;;; : functions since that's not allowed in the general system
;;; : now.
;;; 2020.06.01 Dan [6.0]
;;; : * Moved the chunk-type and chunk definition to the creation
;;; : function instead of the reset function.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled since it's not needed
;;; : and results in warnings in SBCL.
;;; 2021.06.09 Dan [6.1]
;;; : * Make sure the aural-location buffer always gets a new
;;; : chunk when it's set with buffer-requires-copies.
;;; 2021.10.20 Dan [7.0]
;;; : * Audio is required if speech is required.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(require-compiled "GENERAL-PM")
(declaim (ftype (function (t &optional t) t) get-articulation-time))
(defclass audio-module (attn-module)
((audicon :accessor audicon :initarg :audicon :initform nil)
(audicon-lock :accessor audicon-lock :initform (bt:make-lock "audicon"))
(digit-detect-delay :accessor digit-detect-delay :initarg :digit-dtct-dly :initform 300)
(digit-recode-delay :accessor digit-recode-delay :initarg :digit-rec-dly :initform 500)
(digit-duration :accessor digit-duration :initarg :digit-duration :initform 600)
(tone-detect-delay :accessor tone-detect-delay :initarg :tone-dtct-dly :initform 50)
(tone-recode-delay :accessor tone-recode-delay :initarg :tone-rec-dly :initform 285)
(sound-decay-time :accessor decay-time :initarg :decay-time :initform 3000)
(default-spec :accessor default-spec :initform nil)
(aural-hook :accessor aural-hook :initform nil)
(aural-loc-hook :accessor aural-loc-hook :initform nil)
(aural-attn-lock :accessor aural-attn-lock :initform (bt:make-lock "aural-attn"))
(last-stuffed-event :accessor last-stuffed-event :initform nil))
(:default-initargs
:version-string "7.0"
:name :AUDIO))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Sound events.
;;;; ---------------------------------------------------------------------- ;;;;
(defclass sound-event ()
((onset :accessor onset :initarg :onset :initform (mp-time-ms))
(offset :accessor offset :initarg :offset :initform nil)
(string :accessor snd-string :initarg :string :initform nil)
(duration :accessor duration :initarg :duration :initform 0)
(content :accessor content :initarg :content :initform nil)
(content-delay :accessor delay :initarg :delay :initform nil)
(kind :accessor kind :initarg :kind :initform 'SPEECH)
(attended-p :accessor attended-p :initform nil :initarg :attended-p)
(location :accessor location :initarg :location :initform 'EXTERNAL)
(sname :accessor sname :initform (new-name-fct "SOUND") :initarg :sname)
(ename :accessor ename :initform (new-name-fct "AUDIO-EVENT"))
(recode :accessor recode :initarg :recode :initform nil)
(pitch :accessor pitch :initform 'middle :initarg :pitch)
(other-features :accessor other-features :initform nil :initarg :other-features)
))
(defmethod initialize-instance :after ((self sound-event) &key)
(unless (offset self)
(when (and (numberp (onset self)) (numberp (duration self)))
(setf (offset self) (+ (onset self) (duration self)))))
;; Create the chunks up front
(define-chunks-fct (list (list (sname self) 'isa 'sound)))
(define-chunks-fct (list (list (ename self) 'isa 'audio-event))))
(defgeneric detect-at-time (evt)
(:documentation "Returns the time at which an event becomes detectable."))
(defmethod detect-at-time ((evt sound-event))
(+ (onset evt) (delay evt)))
(defgeneric detectable-p (evt)
(:documentation "Returns T if the given sound event is detectable."))
(defmethod detectable-p ((evt sound-event))
(>= (mp-time-ms) (detect-at-time evt)))
(defgeneric finished-p (evt)
(:documentation "Returns T if the given sound-event is finished."))
(defmethod finished-p ((evt sound-event))
(when (>= (mp-time-ms) (offset evt)) t))
(defclass digit-sound-evt (sound-event)
()
(:default-initargs
:kind 'DIGIT
:sname (new-name-fct "DIGIT")))
(defmethod initialize-instance :after ((self digit-sound-evt) &key)
(let ((aud-mod (get-module :audio)))
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf (content self) (snd-string self))
(setf (duration self) (randomize-time-ms (digit-duration aud-mod)))
(setf (delay self) (randomize-time-ms (digit-detect-delay aud-mod)))
(setf (recode self) (digit-recode-delay aud-mod)))))
;;; TONE-SOUND-EVENT [Class]
;;; Date : 97.04.03
;;; Description : Class for tone events.
;;; : The CONTENT slot should be the tone frequency.
(defclass tone-sound-evt (sound-event)
()
(:default-initargs
:string ""
:kind 'TONE
:content 1000
:sname (new-name-fct "TONE")))
(defmethod initialize-instance :after ((self tone-sound-evt) &key)
(let ((aud-mod (get-module :audio)))
(bt:with-recursive-lock-held ((param-lock aud-mod))
(cond ((> (content self) 1500) (setf (pitch self) 'high))
((< (content self) 900) (setf (pitch self) 'low)))
(setf (delay self) (randomize-time-ms (tone-detect-delay aud-mod)))
(setf (recode self) (tone-recode-delay aud-mod)))))
(defclass word-sound-evt (sound-event)
()
(:default-initargs
:kind 'WORD
:sname (new-name-fct "WORD")
:duration 0
:recode nil
))
(defmethod initialize-instance :after ((self word-sound-evt) &key)
(when (or (null (duration self)) (zerop (duration self)))
(setf (duration self)
(get-articulation-time (snd-string self) t)))
(unless (recode self)
(setf (recode self)
;; change the value below to make "hearing" faster
(max
(/ (duration self) 2)
(- (duration self) 150))))
(setf (content self) (snd-string self))
(setf (offset self) (+ (onset self) (duration self)))
(let ((aud-mod (get-module :audio)))
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf (delay self) (randomize-time-ms (digit-detect-delay aud-mod))))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Toplevel commands.
;;;; ---------------------------------------------------------------------- ;;;;
(defgeneric new-sound-event (evt)
(:documentation "Handles the bookkeeping when a new sound event is created."))
;; handle the buffer stuffing
(defun aural-location-unstuff-check (module buffer chunk)
(let ((current (buffer-read buffer)))
(and
current
(multiple-value-bind (copy was-copy) (chunk-copied-from-fct current)
(declare (ignore copy))
(or ;; the copy of the chunk is still in the buffer unchanged
;; regardless of whether the original has changed
(eq was-copy chunk)
;; otherwise check if it was stuffed
;; and matches the last sound event (both of which may have been modified)
(and
(query-buffer buffer '(buffer unrequested))
(equal-chunks-fct current (ename (bt:with-recursive-lock-held ((param-lock module))
(last-stuffed-event module))))))))))
(defun stuff-sound-buffer (audio-mod)
(let ((chunk (buffer-read 'aural-location)))
(when (or (null chunk)
(bt:with-recursive-lock-held ((param-lock audio-mod))
(and (overstuff-loc audio-mod)
(query-buffer 'aural-location '(buffer unrequested))
;; overwrite the stuffed chunk if it's 'safe':
;; - unmodified
;; - it still matches all the features from the last stuffed chunk
(or (multiple-value-bind (x unmodified-copy) (chunk-copied-from-fct chunk) (declare (ignore x)) unmodified-copy)
(equal-chunks-fct chunk (ename (last-stuffed-event audio-mod)))))))
(find-sound audio-mod (bt:with-recursive-lock-held ((param-lock audio-mod)) (default-spec audio-mod)) :stuffed t))))
(add-act-r-command "new-sound" nil "Indicates when a new sound has been created for monitoring purposes. Do not call directly.")
(defmethod new-sound-event :around ((evt sound-event))
(let ((evt (call-next-method)))
(when evt
(schedule-event (detect-at-time evt) 'stuff-sound-buffer :module :audio
:destination :audio :output nil :time-in-ms t)
(schedule-event (onset evt) "new-sound" :module :audio :time-in-ms t :output 'medium)
t)
))
(defmethod new-sound-event ((evt sound-event))
(verify-current-mp
"No meta-process found. Cannot create a new sound."
(verify-current-model
"No current model found. Cannot create a new sound."
(aif (get-module :audio)
(bt:with-lock-held ((audicon-lock it))
(push-last evt (audicon it))
evt)
(print-warning "No Audio module found. Cannot create a new sound.")))))
(defun new-digit-sound (digit &optional onset time-in-ms)
"Creates and adds a digit sound <digit>, a number, starting optionally at <onset>."
(verify-current-model
"No current model found. Cannot create a new sound."
(cond ((not (numberp digit))
(print-warning "Digit must be a number. No new digit sound created."))
((not (or (null onset) (numberp onset)))
(print-warning "Onset must be a number. No new digit sound created."))
(t
(new-sound-event (make-instance 'digit-sound-evt
:onset (cond ((null onset) (mp-time-ms))
((null time-in-ms) (safe-seconds->ms onset 'new-digit-sound))
(t onset))
:string digit))))))
(add-act-r-command "new-digit-sound" 'new-digit-sound "Create a new digit sound event for the audio module. Params: digit {onset-time {onset-time-in-milliseconds}}.")
(defun new-tone-sound (freq duration &optional onset time-in-ms)
"Creates and adds a tone sound of <freq>, starting optionally at <onset>."
(verify-current-model
"No current model found. Cannot create a new sound."
(cond ((not (numberp freq))
(print-warning "Freq must be a number. No new tone sound created."))
((not (numberp duration))
(print-warning "Duration must be a number. No new tone sound created."))
((not (or (null onset) (numberp onset)))
(print-warning "Onset must be a number. No new tone sound created."))
(t
(new-sound-event (make-instance 'tone-sound-evt
:onset (cond ((null onset) (mp-time-ms))
((null time-in-ms) (safe-seconds->ms onset 'new-tone-sound))
(t onset))
:duration (safe-seconds->ms duration 'new-tone-sound)
:content freq))))))
(add-act-r-command "new-tone-sound" 'new-tone-sound "Create a new pure tone sound event for the audio module. Params: frequency duration {onset-time {onset-time-in-milliseconds}}.")
(defun new-other-sound (content duration delay recode
&optional onset (location 'external) (kind 'speech) time-in-ms &rest other-features)
"Creates and adds a sound <content>, lasting <duration>, with content delay <delay>, with recode time <recode>, starting optionally at <onset>."
(verify-current-model
"No current model found. Cannot create a new sound."
(setf other-features (decode-string-names other-features))
(cond ((not (numberp duration))
(print-warning "Duration must be a number. No new sound created."))
((not (numberp delay))
(print-warning "Delay must be a number. No new sound created."))
((not (numberp recode))
(print-warning "Recode must be a number. No new sound created."))
((not (or (null onset) (numberp onset)))
(print-warning "Onset must be a number. No new sound created."))
((not (every (lambda (x) (and (= (length x) 3) (or (eq (car x) :evt) (eq (car x) :sound) (eq (car x) :both)))) other-features))
(print-warning "Other features must be lists of length 3 starting with one of: :evt, :sound, or :both. No new sound created."))
(t
(dolist (o other-features)
(unless (valid-slot-name (second o))
(extend-possible-slots (second o))))
(new-sound-event (make-instance 'sound-event
:onset (cond ((null onset) (mp-time-ms))
((null time-in-ms) (safe-seconds->ms onset 'new-other-sound))
(t onset))
:duration (safe-seconds->ms duration 'new-other-sound)
:content content
:delay (safe-seconds->ms delay 'new-other-sound)
:recode (safe-seconds->ms recode 'new-other-sound)
:location location
:kind kind
:other-features other-features))))))
(defun external-new-other-sound (content duration delay recode
&optional onset (location 'external) (kind 'speech) time-in-ms &rest other-features)
(apply 'new-other-sound (decode-string content) duration delay recode onset (decode-string location) (decode-string kind) time-in-ms (decode-string-names other-features)))
(add-act-r-command "new-other-sound" 'external-new-other-sound "Create a new custom sound event for the audio module. Params: 'content' duration delay recode {onset-time {'location' {'kind' {onset-time-in-milliseconds {'extra-features'*}}}}}.")
(defun new-word-sound (word &optional onset (location 'external) time-in-ms)
"Creates and adds a word with optional onset time."
(verify-current-model
"No current model found. Cannot create a new sound."
(cond ((not (stringp word))
(print-warning "Word must be a string. No new word sound created."))
((not (or (null onset) (numberp onset)))
(print-warning "Onset must be a number. No new word sound created."))
(t
(new-sound-event (make-instance 'word-sound-evt
:onset (cond ((null onset) (mp-time-ms))
((null time-in-ms) (safe-seconds->ms onset 'new-word-sound))
(t onset))
:string word :location location))))))
(defun external-new-word-sound (word &optional onset (location 'external) time-in-ms)
(new-word-sound word onset (decode-string location) time-in-ms))
(add-act-r-command "new-word-sound" 'external-new-word-sound "Create a new word sound event for the audio module. Params: word {onset-time {'location' {onset-time-in-milliseconds}}}.")
(defun update-sound-evt (evt)
(mod-chunk-fct (ename evt)
(append `(onset ,(onset evt)
location ,(location evt)
kind ,(kind evt)
id ,(ename evt)
pitch ,(pitch evt))
(when (finished-p evt)
`(offset ,(offset evt)
duration ,(ms->seconds (- (offset evt) (onset evt)))))
(mapcan (lambda (x)
(when (or (eq (car x) :evt) (eq (car x) :both))
(copy-list (cdr x))))
(other-features evt)))))
;;; FIND-SOUND [Method]
;;; Date : 97.08.18, delta 99.08.30
;;; Description : Parallels the Vision Module's FIND-LOCATION, this one finds
;;; : audio events (not sounds).
(defgeneric find-sound (aud-mod spec &key stuffed)
(:documentation "Given a chunk-spec return a sound event which matches."))
(defmethod find-sound ((aud-mod audio-module) spec &key (stuffed nil))
(let* ((slots (chunk-spec-slot-spec spec))
(finished-spec (find :finished slots :key 'spec-slot-name))
(attended-spec (find :attended slots :key 'spec-slot-name))
(relative-slots nil)
(event-ls (detectable-audicon aud-mod)))
;; filter by attended - spec-slot-op must be =
(when attended-spec
(setf event-ls (remove-if-not (lambda (x)
(eq (attended-p x) (spec-slot-value attended-spec)))
event-ls)))
;; filter by finished - spec-slot-op must be =
(when finished-spec
(setf event-ls (remove-if-not (lambda (x)
(eq (finished-p x) (spec-slot-value finished-spec)))
event-ls)))
(dolist (x slots)
(when (or (eq (spec-slot-value x) 'lowest)
(eq (spec-slot-value x) 'highest))
(setf slots (remove x slots))
(push-last x relative-slots)))
(let ((matching-chunks (find-matching-chunks (slot-specs-to-chunk-spec slots)
:chunks (mapcar 'update-sound-evt event-ls)
:variable-char #\&)))
(dolist (x relative-slots)
(let ((value nil)
(op (spec-slot-op x))
(slot (spec-slot-name x))
(test (spec-slot-value x)))
(dolist (y matching-chunks)
(let ((cur-val (fast-chunk-slot-value-fct y slot)))
(unless (numberp cur-val)
(setf value :fail)
(print-warning "Cannot apply ~S constraint because not all chunks have a numerical value." x)
(return))
(when (or (null value)
(and (eq test 'lowest)
(< cur-val value))
(and (eq test 'highest)
(> cur-val value)))
(setf value cur-val))))
(unless (eq value :fail)
(setf matching-chunks (find-matching-chunks (define-chunk-spec-fct (list op slot value)) :chunks matching-chunks)))))
(let (hook override forced failed)
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf hook (aural-loc-hook aud-mod)))
(when hook
(let ((id (chunk-spec-to-id spec)))
(setf override (dispatch-apply hook matching-chunks id stuffed))
(release-chunk-spec-id id))
(cond ((numberp override)
(when (minusp override)
(print-warning "Negative time ~s returned from :aural-loc-hook command ~s. Using time of 0." override hook)
(setf override 0)))
((and (listp override)
(= (length override) 2)
(numberp (first override))
(or (null (second override))
(find (second override) matching-chunks)))
(aif (second override)
(setf forced it)
(setf failed t))
(setf override (first override))
(when (minusp override)
(print-warning "Negative time ~s returned from :aural-loc-hook command ~s. Using time of 0." override hook)
(setf override 0)))
(t
(print-warning "Invalid return value ~s from :aural-loc-hook commnad ~s using default operation." override hook)
(setf override nil))))
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf (loc-failure aud-mod) nil)
(if (and (or forced matching-chunks) (not failed))
(let* ((chunk (aif forced it (random-item matching-chunks)))
(event (find chunk (bt:with-lock-held ((audicon-lock aud-mod)) (audicon aud-mod)) :key 'ename))
(time (aif override (randomize-time-ms (safe-seconds->ms it 'find-sound)) 0)))
(if (and stuffed (buffer-read 'aural-location))
(schedule-overwrite-buffer-chunk 'aural-location chunk time :time-in-ms t :module :audio :requested nil :priority 10)
(schedule-set-buffer-chunk 'aural-location chunk time :time-in-ms t :module :audio :requested (not stuffed) :priority 10))
(when stuffed
(setf (last-stuffed-event aud-mod) event))
(unless (and (chunk-slot-value-fct chunk 'offset) (chunk-slot-value-fct chunk 'duration))
(schedule-event (offset event) 'audio-event-ended :module :audio :priority 9 :output 'high :params (list event)
:precondition 'aural-location-update-check :maintenance t :time-in-ms t :details (format nil "~s ~s" 'audio-event-ended chunk)))
(when (and stuffed (unstuff-loc aud-mod))
(awhen (unstuff-event aud-mod)
(delete-event it))
(setf (unstuff-event aud-mod)
(if (numberp (unstuff-loc aud-mod))
(schedule-event-relative (unstuff-loc aud-mod) 'unstuff-buffer :maintenance t :params (list 'aural-location chunk)
:destination :audio :module :audio :output nil :time-in-ms t :priority :min
:precondition 'aural-location-unstuff-check)
(schedule-event (+ (offset event) (decay-time aud-mod)) 'unstuff-buffer :maintenance t :params (list 'aural-location chunk)
:destination :audio :module :audio :output nil :time-in-ms t :priority :min
:precondition 'aural-location-unstuff-check)))))
(let* ((time (aif override (randomize-time-ms (safe-seconds->ms it 'find-sound)) 0)))
(schedule-event-relative time 'find-sound-failure :time-in-ms t :params (list stuffed) :module :audio :destination :audio :output 'medium :details "find-sound-failure"))))))))
(defun aural-location-update-check (evt)
(let ((buffer-chunk (buffer-read 'aural-location)))
(and buffer-chunk (eq (chunk-slot-value-fct buffer-chunk 'id) (ename evt)))))
(defun audio-event-ended (evt)
(update-sound-evt evt)
(schedule-mod-buffer-chunk 'aural-location (list 'offset (offset evt)
'duration (ms->seconds (- (offset evt) (onset evt))))
0 :module :audio :priority :max))
(defun find-sound-failure (audio stuffed)
"function to indicate a failure in the trace and set the error flag"
(bt:with-recursive-lock-held ((param-lock audio)) (setf (loc-failure audio) t))
(set-buffer-failure 'aural-location :ignore-if-full t :requested (not stuffed))
nil)
;;; ATTEND-SOUND [Method]
;;; Date : 97.08.18
;;; Description : Parallels the Vision Module's MOVE-ATTENTION, this one
;;; : attends an audio event, ultimately building a chunk based
;;; : on the content of the sound.
(defgeneric attend-sound (aud-mod &key event)
(:documentation "Shift auditory attention to the given sound event."))
(defmethod attend-sound ((aud-mod audio-module) &key event)
(cond ((eq (exec-s aud-mod) 'BUSY)
(model-warning "Auditory attention shift requested at ~S while one was already in progress." (mp-time))
)
(t ; Keep using an id slot in the audio-event to keep the connection
(let ((s-event (find (chunk-slot-value-fct event 'id) (current-audicon aud-mod)
:test (lambda (x y) (eq x (ename y))))))
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf (attend-failure aud-mod) nil))
(change-state aud-mod :exec 'busy)
(let (hook override)
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf hook (aural-hook aud-mod)))
(when hook
(setf override (dispatch-apply hook event (if s-event t nil))))
(cond ((or (null override) (numberp override))
(bt:with-lock-held ((aural-attn-lock aud-mod))
(setf (current-marker aud-mod) nil))
(when (numberp override)
(when (minusp override)
(print-warning "Aural encoding hook returned a negative encoding time ~f. Using 0 instead." override)
(setf override 0))
(setf override (safe-seconds->ms override 'attend-sound)))
(if s-event ;; add in a test to make sure - could have a failure
(schedule-event-relative (randomize-time-ms (aif override it (recode s-event)))
'audio-encoding-complete
:module :audio
:destination :audio
:params (list s-event)
:time-in-ms t
:details (format nil "AUDIO-ENCODING-COMPLETE ~s" (chunk-slot-value-fct event 'id)))
;; assume digit delay for a failure
(schedule-event-relative (randomize-time-ms (aif override it (bt:with-recursive-lock-held ((param-lock aud-mod)) (digit-recode-delay aud-mod))))
'attend-sound-failure
:time-in-ms t
:module :audio
:destination :audio
:output 'medium
:details "attend-sound-failure")))
(t ;; event must be scheduled by code
;; just set the marker to know which event
(bt:with-lock-held ((aural-attn-lock aud-mod))
(setf (current-marker aud-mod) (list s-event (chunk-slot-value-fct event 'id)))))))))))
(defun schedule-audio-encoding-complete (delay)
(let ((aud-mod (get-module :audio)))
(when aud-mod
(bt:with-lock-held ((aural-attn-lock aud-mod))
(if (current-marker aud-mod)
(progn
(unless (and (numberp delay) (not (minusp delay)))
(print-warning "Invalid delay time passed to schedule-audio-encoding-complete ~s. Using 0 instead." delay)
(setf delay 0))
(if (first (current-marker aud-mod))
(schedule-event-relative (randomize-time-ms (safe-seconds->ms delay 'schedule-audio-encoding-complete))
'audio-encoding-complete
:time-in-ms t
:module :audio
:destination :audio
:params (list (first (current-marker aud-mod)))
:details (format nil "AUDIO-ENCODING-COMPLETE ~s" (second (current-marker aud-mod))))
(schedule-event-relative (randomize-time-ms (safe-seconds->ms delay 'schedule-audio-encoding-complete))
'attend-sound-failure
:time-in-ms t
:module :audio
:destination :audio
:output 'medium
:details "attend-sound-failure"))
(setf (current-marker aud-mod) nil))
(print-warning "Schedule-audio-encoding-complete called but there is no pending attend-sound action."))))))
(add-act-r-command "schedule-audio-encoding-complete" 'schedule-audio-encoding-complete "Used to finish an attend-sound request which was suspended by the :aural-encoding-hook. Params: delay-time.")
(defun attend-sound-failure (audio)
"Flag that an error occured"
(bt:with-recursive-lock-held ((param-lock audio))
(setf (attend-failure audio) t))
(set-buffer-failure 'aural)
(change-state audio :exec 'free)
(bt:with-lock-held ((aural-attn-lock audio))
(setf (currently-attended audio) nil)))
(defgeneric audio-encoding-complete (aud-mod sevt)
(:documentation "Put the sound into the aural buffer."))
(defmethod audio-encoding-complete ((aud-mod audio-module) (sevt sound-event))
(change-state aud-mod :exec 'free)
(bt:with-lock-held ((audicon-lock aud-mod))
(setf (attended-p sevt) t))
(mod-chunk-fct (sname sevt)
(append `(content ,(content sevt)
kind ,(kind sevt)
event ,(ename sevt)) ;; use the ename since it's constant but won't match the "chunk" in the aural-loc buffer
(mapcan (lambda (x)
(when (or (eq (car x) :sound) (eq (car x) :both))
(copy-list (cdr x))))
(other-features sevt))))
(schedule-set-buffer-chunk 'aural (sname sevt) 0 :time-in-ms t :module :audio)
(bt:with-lock-held ((aural-attn-lock aud-mod))
(setf (currently-attended aud-mod) (sname sevt))))
(defmethod clear :after ((aud-mod audio-module))
(bt:with-lock-held ((aural-attn-lock aud-mod))
(setf (current-marker aud-mod) nil)
(setf (currently-attended aud-mod) nil))
(bt:with-recursive-lock-held ((param-lock aud-mod))
(setf (loc-failure aud-mod) nil)
(setf (attend-failure aud-mod) nil)))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Audio utilities
;;;; ---------------------------------------------------------------------- ;;;;
(defgeneric purge-old-sounds (aud-mod)
(:documentation "Removes sounds that have decayed from the audicon but can't delete corresponding event chunks"))
(defmethod purge-old-sounds ((aud-mod audio-module))
(let ((new-audicon nil))
(bt:with-lock-held ((audicon-lock aud-mod))
(setf (audicon aud-mod)
(dolist (e (audicon aud-mod) new-audicon)
(if (< (+ (offset e) (decay-time aud-mod)) (mp-time-ms))
(progn
;(when (chunk-p-fct (ename e))
; (delete-chunk-fct (ename e)))
(when (chunk-p-fct (sname e))
(delete-chunk-fct (sname e))))
(push-last e new-audicon)))))))
(defgeneric current-audicon (aud-mod)
(:documentation "Returns the audicon, assuming all events that currently exist are in there."))
(defmethod current-audicon ((aud-mod audio-module))
(purge-old-sounds aud-mod)
(remove-if (lambda (x) (> (onset x) (mp-time-ms))) (bt:with-lock-held ((audicon-lock aud-mod)) (audicon aud-mod))))
(defgeneric detectable-audicon (aud-mod)
(:documentation "Returns the audicon, but only those events that are currently detectable."))
(defmethod detectable-audicon ((aud-mod audio-module))
(purge-old-sounds aud-mod)
(remove-if (lambda (x) (not (detectable-p x))) (bt:with-lock-held ((audicon-lock aud-mod)) (audicon aud-mod))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; ACT6 integration stuff
;;;; ---------------------------------------------------------------------- ;;;;
(defun reset-audio-module (instance)
(reset-pm-module instance)
(bt:with-lock-held ((aural-attn-lock instance))
(setf (currently-attended instance) nil)
(setf (current-marker instance) nil))
(bt:with-lock-held ((audicon-lock instance))
(setf (audicon instance) nil))
(bt:with-recursive-lock-held ((param-lock instance))
(setf (loc-failure instance) nil)
(setf (attend-failure instance) nil)
(setf (last-stuffed-event instance) nil)
(setf (default-spec instance)
(define-chunk-spec :attended nil)))
(buffer-requires-copies 'aural-location)
)
(defun query-audio-module (aud-mod buffer slot value)
(bt:with-recursive-lock-held ((param-lock aud-mod))
(case buffer
(aural
(if (member slot '(preparation execution processor modality))
(generic-state-query aud-mod buffer slot value)
(case slot
(state
(case value
(busy
(eq (mode-s aud-mod) 'busy))
(free
(eq (mode-s aud-mod) 'free))
(error
(attend-failure aud-mod))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(t (print-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value)))))
(aural-location
(case slot
(state
(case value
(busy nil) ;; aural-location requests are always free
(free t)
(error (loc-failure aud-mod))
(t (model-warning "Invalid query made of the ~S buffer with slot ~S and value ~S" buffer slot value))))
(attended
(awhen (buffer-read 'aural-location)
(let ((s-event (find (chunk-slot-value-fct it 'id)
(bt:with-lock-held ((audicon-lock aud-mod)) (audicon aud-mod))
:test (lambda (x y) (eq x (ename y))))))
(when s-event
(eq value (attended-p s-event))))))
(finished
(awhen (buffer-read 'aural-location)
(let ((s-event (find (chunk-slot-value-fct it 'id)
(bt:with-lock-held ((audicon-lock aud-mod)) (audicon aud-mod))
:test (lambda (x y) (eq x (ename y))))))
(when s-event
(eq value (finished-p s-event)))))))))))
(defmethod pm-module-last-cmd-name ((aud-mod audio-module) buffer-name chunk-spec)
(case buffer-name
(aural-location (if (chunk-spec-slot-spec chunk-spec 'set-audloc-default)
'set-audloc-default
'find-sound))
(aural 'sound)))
(defmethod pm-module-request ((aud-mod audio-module) buffer-name chunk-spec)
(case buffer-name
(aural
(if (test-for-clear-request chunk-spec)
(schedule-event-now 'clear :module :audio :destination :audio :output 'medium)
(let ((event-spec (chunk-spec-slot-spec chunk-spec 'event)))
(cond ((and (= (length event-spec) 1)
(eq '= (spec-slot-op (first event-spec)))
(chunk-p-fct (spec-slot-value (first event-spec))))
(schedule-event-now 'attend-sound
:params (list :event (spec-slot-value (first event-spec)))
:module :audio :destination :audio
:details (mkstr 'attend-sound " " (spec-slot-value (first event-spec)))
:output 'medium))
(t
(print-warning "Invalid command to the aural buffer does not describe a valid action"))))))
(aural-location
(cond ((> (length (chunk-spec-slot-spec chunk-spec :attended)) 1)
(print-warning ":attended specification only allowed once in an aural-location request."))
((> (length (chunk-spec-slot-spec chunk-spec :finished)) 1)
(print-warning ":finished specification only allowed once in an aural-location request."))
((chunk-spec-slot-spec chunk-spec 'set-audloc-default)
(let* ((specs (chunk-spec-slot-spec chunk-spec 'set-audloc-default))
(spec (first specs)))
(cond ((> (length specs) 1)
(print-warning "set-audloc-default slot can only be specified once in an aural-location request."))
((not (eq '= (spec-slot-op spec)))
(print-warning "set-audloc-default slot must use the = test in an aural-location request."))
(t
(schedule-event-now 'set-audloc-default-fct
:params (list (apply 'append (remove-if (lambda (x) (eq (spec-slot-name x) 'set-audloc-default))
(chunk-spec-slot-spec chunk-spec))))
:output 'medium :module :audio :details (mkstr 'set-audloc-default))))))
(t
(schedule-event-now 'find-sound :module :audio
:output 'medium
:destination :audio
:details (mkstr 'find-sound)
:params (list chunk-spec)))))))
(defun params-audio-module (aud-mod param)
(bt:with-recursive-lock-held ((param-lock aud-mod))
(if (consp param)
(case (first param)
(:digit-detect-delay
(setf (digit-detect-delay aud-mod) (safe-seconds->ms (rest param) 'sgp))
(rest param))
(:digit-duration
(setf (digit-duration aud-mod) (safe-seconds->ms (rest param) 'sgp))
(rest param))
(:digit-recode-delay
(setf (digit-recode-delay aud-mod) (safe-seconds->ms (rest param) 'sgp))
(rest param))
(:sound-decay-time
(setf (decay-time aud-mod) (safe-seconds->ms (rest param) 'sgp))
(rest param))
(:tone-detect-delay
(setf (tone-detect-delay aud-mod) (safe-seconds->ms (rest param) 'sgp))
(rest param))
(:tone-recode-delay
(setf (tone-recode-delay aud-mod) (safe-seconds->ms (rest param) 'sgp))
(rest param))
(:unstuff-aural-location
(setf (unstuff-loc aud-mod)
(if (numberp (cdr param))
(safe-seconds->ms (cdr param))
(cdr param)))
(cdr param))
(:aural-loc-hook
(when (and (cdr param) (aural-loc-hook aud-mod))
(print-warning ":aural-loc-hook parameter being changed from ~s to ~s." (aural-loc-hook aud-mod) (cdr param)))
(setf (aural-loc-hook aud-mod) (cdr param)))
(:aural-encoding-hook
(when (and (cdr param) (aural-hook aud-mod))
(print-warning ":aural-encoding-hook parameter being changed from ~s to ~s." (aural-hook aud-mod) (cdr param)))
(setf (aural-hook aud-mod) (cdr param)))
(:overstuff-aural-location
(setf (overstuff-loc aud-mod) (cdr param))))
(case param
(:digit-detect-delay
(ms->seconds (digit-detect-delay aud-mod)))
(:digit-duration
(ms->seconds (digit-duration aud-mod)))
(:digit-recode-delay
(ms->seconds (digit-recode-delay aud-mod)))
(:sound-decay-time
(ms->seconds (decay-time aud-mod)))
(:tone-detect-delay
(ms->seconds (tone-detect-delay aud-mod)))
(:tone-recode-delay
(ms->seconds (tone-recode-delay aud-mod)))
(:unstuff-aural-location
(if (numberp (unstuff-loc aud-mod))
(ms->seconds (unstuff-loc aud-mod))
(unstuff-loc aud-mod)))
(:aural-loc-hook
(aural-loc-hook aud-mod))
(:aural-encoding-hook
(aural-hook aud-mod))
(:overstuff-aural-location
(overstuff-loc aud-mod))))))
(defun aural-location-status ()
(concatenate 'string
(format nil " attended nil : ~S~%" (query-buffer 'aural-location '(attended nil)))
(format nil " attended t : ~S~%" (query-buffer 'aural-location '(attended t)))
(format nil " finished nil : ~S~%" (query-buffer 'aural-location '(finished nil)))
(format nil " finished t : ~S" (query-buffer 'aural-location '(finished t)))))
(defun aural-status ()
(print-module-status (get-module :audio)))
(defun create-audio-module (name)
(declare (ignore name))
(chunk-type audio-event onset offset duration pitch kind location id)
(chunk-type (set-audloc-default (:include audio-event)) (set-audloc-default t))
(chunk-type sound kind content event)
(dolist (c '(digit speech tone word highest lowest sound find-sound set-audloc-default internal external self high middle low))
(unless (chunk-p-fct c)
(define-chunks-fct (list (list c 'name c)))))
(make-instance 'audio-module))
(define-module-fct :audio
(list (define-buffer-fct 'aural-location
:request-params '(:attended :finished)
:queries '(attended finished)
:status-fn 'aural-location-status)
(define-buffer-fct 'aural
:queries '(modality preparation execution processor)
:status-fn 'aural-status))
(list
(define-parameter :digit-detect-delay
:valid-test 'nonneg
:default-value 0.3
:warning "a non-negative number"
:documentation "Lag between onset and detectability for digits")
(define-parameter :digit-duration
:valid-test 'nonneg
:default-value 0.6
:warning "a non-negative number"
:documentation "Default duration for digit sounds.")
(define-parameter :digit-recode-delay
:valid-test 'nonneg
:default-value 0.5
:warning "a non-negative number"
:documentation "Recoding delay for digit sound content.")
(define-parameter :sound-decay-time
:valid-test 'nonneg
:default-value 3.0
:warning "a non-negative number"
:documentation "The amount of time after a sound has finished it takes for the sound to be deleted from the audicon")
(define-parameter :tone-detect-delay
:valid-test 'nonneg
:default-value 0.05
:warning "a non-negative number"
:documentation "Lag between sound onset and detectability for tones")
(define-parameter :tone-recode-delay
:valid-test 'nonneg
:default-value 0.285
:warning "a non-negative number"
:documentation "Recoding delay for tone sound content.")
(define-parameter :unstuff-aural-location
:valid-test 'numorbool
:default-value nil
:warning "T, NIL, or a number"
:documentation "Whether chunks stuffed into the aural-location buffer should be automatically cleared by the module if unused")
(define-parameter :overstuff-aural-location
:valid-test 'tornil
:default-value nil
:warning "T or nil"
:documentation "Whether a chunk previously stuffed into the aural-location buffer can be overwritten by a new chunk to be stuffed")
(define-parameter :aural-encoding-hook
:valid-test 'local-or-remote-function-or-nil
:default-value nil
:warning "Local or remote function or NIL"
:documentation "User hook for overriding the encoding time of an aural attention shift")
(define-parameter :aural-loc-hook
:valid-test 'local-or-remote-function-or-nil
:default-value nil
:warning "Local or remote function or NIL"
:documentation "User hook for overriding the timing and choice on an aural-location action"))
:version (version-string (make-instance 'audio-module))
:documentation "A module which gives the model an auditory attentional system"
:creation 'create-audio-module
:reset 'reset-audio-module
:query 'query-audio-module
:request 'pm-module-request
:params 'params-audio-module
:required :speech)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; User Commands
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun print-audicon ()
(let ((module (get-module :audio)))
(if module
(progn
(command-output "Sound event Att Detectable Kind Content location onset offset Sound ID")
(command-output "----------- --- ---------- ------------- ---------------- -------- ----- ------ --------")
(dolist (x (sort (copy-list (current-audicon module)) #'< :key 'onset))
(print-audio-feature x)))
(print-warning "No audio module found"))))
(add-act-r-command "print-audicon" 'print-audicon "Print all the attributes of the features in the model's audicon to command output. No params.")
(defgeneric print-audio-feature (feat)
(:documentation "Print out an ASCII representation of the audicon."))
(defmethod print-audio-feature ((feat sound-event))
(command-output "~15a~5A~12A~15A~18s~10s~8d ~8d ~a"
(ename feat)
(attended-p feat)
(detectable-p feat)
(kind feat)
(content feat)
(location feat)
(onset feat)
(offset feat)
(sname feat)))
(defun printed-audicon ()
(let ((module (get-module :audio)))
(if module
(let ((s (make-string-output-stream)))
(format s "Sound event Att Detectable Kind Content location onset offset Sound ID~%")
(format s "----------- --- ---------- ------------- ---------------- -------- ----- ------ --------~%")
(dolist (x (sort (copy-list (current-audicon module)) #'< :key 'onset))
(format s "~15a~5A~12A~15A~18s~10s~8d ~8d ~a~%"
(ename x)
(attended-p x)
(detectable-p x)
(kind x)
(content x)
(location x)
(onset x)
(offset x)
(sname x)))
(get-output-stream-string s))
"#|Warning: No audio module found|#")))
(add-act-r-command "printed-audicon" 'printed-audicon "Return the string containing all the printed attributes of the features in the model's audicon. No params.")
(defmacro set-audloc-default (&rest params)
"Macro to set the default specification for aural location buffer stuffing."
`(set-audloc-default-fct ',params))
(defun set-audloc-default-fct (params)
"Function to set the default specification for aural location buffer stuffing."
(verify-current-model
"No current model. Cannot set audloc defaults."
(aif (get-module :audio)
(let* ((spec (funcall 'define-chunk-spec-fct params))
(attended (when spec (chunk-spec-slot-spec spec :attended)))
(finished (when spec (chunk-spec-slot-spec spec :finished))))
(if (or (> (length attended) 1)
(> (length finished) 1))
(progn
(print-warning "The :attended and :finished specification for set-audloc-default can only be specified at most once.")
(print-warning "Audloc defaults not changed."))
(if spec
(bt:with-recursive-lock-held ((param-lock it))
(setf (default-spec it) spec)
t)
(print-warning "Invalid chunk specification. Default audloc not changed."))))
(print-warning "No audio module found. Cannot set audloc defaults."))))
(defun external-set-audloc-default (&rest params)
(set-audloc-default-fct (decode-string-names params)))
(add-act-r-command "set-audloc-default" 'external-set-audloc-default "Set the specification of how to pick the chunk to stuff into the aural-location buffer. Params: '{{modifier} slot value}'*")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 77,161 | Common Lisp | .lisp | 1,330 | 49.349624 | 244 | 0.576915 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0be0310eaabd0ecedc52860c609374320226fe62932f12fa5dd6a62876c7f487 | 14,293 | [
-1
] |
14,294 | speech.lisp | asmaloney_ACT-R/core-modules/speech.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Mike Byrne & Dan Bothell
;;; Address : Rice University, MS-25
;;; : Psychology Department
;;; : Houston,TX 77251-1892
;;; : [email protected]
;;;
;;; Copyright : (c)1998-2005 Mike Byrne/Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LICENSE.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : speech.lisp
;;; Version : 7.1
;;;
;;; Description : Source code for the ACT-R/PM Speech Module. This Module
;;; : is pretty brain-damaged but should get the job done
;;; : for short, simple strings.
;;;
;;; Bugs :
;;;
;;; Todo : [ ] Should a jam signal an error state?
;;;
;;; ----- History -----
;;; 2004.12.24 Dan [First pass at moving to ACT-R 6]
;;; : Changed name to speech and reset version to 1.0a1
;;; :
;;; : Moved *char-per-syllable into the module and made it a
;;; : real parameter :char-per-syllable.
;;; :
;;; : Removed the state chunk from the initialize-instance method.
;;; :
;;; : Added the :from :speech to the queue-command to the device
;;; :
;;; : Not flagging any errors at this point.
;;; :
;;; : Not placing a response chunk into the buffer at this point.
;;; :
;;; : Changed art-rate-ht in register-art-time to art-time-ht
;;; 2005.01.08 Dan
;;; : Removed the NEW-WORD-SOUND method since there's now
;;; : an audio module.
;;; 2005.01.11 mdb
;;; : * Added parameter doc strings.
;;; : * Added toplevel commands.
;;; : * Went to more generic methods on buffer interactions.
;;; 2005.01.12 Dan
;;; : * Moved the device interface parameters to the device module.
;;; 2005.02.03 Dan
;;; : * Added ":output 'medium" or ":output 'low" to some of the
;;; : events scheduled to play friendly with the new detail level.
;;; 2005.04.23 Dan
;;; : * Added the status printing function to the buffer definition.
;;; : * Noticed that the last-command query is unhandled...
;;; 2005.06.15 Dan
;;; : * Added a check and warning that the string parameter to speak
;;; : and subvocalize is actually a real string because it seems
;;; : to throw a hard error when passed a chunk-name...
;;; : * Updated version to 2.2a2.
;;; 2006.09.08 Dan
;;; : * Changed a parameter test from posnum to nonneg.
;;; 2007.01.10 Dan
;;; : * Changed the version to 2.2.
;;; : * Cleaned out most of the old (commented out) code.
;;; : * Added a new parameter :subvocalize-detect-delay
;;; : which is the time required for a subvocalized speech act
;;; : to be detecteable by the audio module. The reason for it
;;; : is because the default of .3 (the digit-detect-delay) seems
;;; : way off - the model can't keep up with hearing it's
;;; : own internal speech with that delay for short utterances
;;; : because it can generate them faster than it can hear them...
;;; : So, by making it a parameter people can adjust that as needed.
;;; : * Changed the subvocalize action to create the internal sound
;;; : using new-other-sound so that the delay can be set.
;;; : * Also changed the recode time on that to 0ms - because
;;; : it seems odd for a model to not immediately be able to understand
;;; : what it's saying in it's own head.
;;; : * Changed the get-articulation-time method to get-art-time
;;; : and made get-articulation-time a function which doesn't
;;; : require passing the module as a parameter.
;;; : * Made the set/get articulation check to make sure there is
;;; : a current mp/model/module.
;;; : * Removed the speech-utils from being loaded for now - does
;;; : that even still work or get used by anyone?
;;; 2007.03.15 Dan
;;; : * Changed the speak action so that a model's own voice
;;; : is tagged with a location of self for the audio system
;;; : so a model can differentiate its own speech from another
;;; : model's!
;;; 2008.07.22 Dan
;;; : * Why did this require central-parameters? Taking that out.
;;; 2011.04.28 Dan
;;; : * Changed a declare ignore to ignorable to supprress an ACL warning.
;;; 2011.05.17 Dan
;;; : * Replaced queue-command calls with schedule-event-relative.
;;; 2011.05.18 Dan
;;; : * Replaced calls to new-word-sound and new-other-sound with
;;; : the lower level sound creation code which has been changed
;;; : over to using ms internally to avoid having to do math on
;;; : times in seconds.
;;; 2014.02.12 Dan
;;; : * The request chunk-types are no longer subtypes of speech-command
;;; : since that wasn't actually used for anything.
;;; 2014.05.16 Dan [3.0]
;;; : * Start the conversion to type-less chunks.
;;; : * In addition to isa speak string <text> one can now just do
;;; : speak <text> as the request.
;;; 2014.05.30 Dan
;;; : * Use the test-for-clear-request function in pm-module-request.
;;; 2014.10.31 Dan
;;; : * Changed the speak and subvocalize chunks to be of the
;;; : corresponding type.
;;; 2015.06.04 Dan [3.1]
;;; : * Convert to using ms for internal math and convert user
;;; : times in seconds to ms with safe-seconds->ms.
;;; : * Added an optional parameter to get-articulation-time so
;;; : that it can be returned in ms if needed.
;;; : * Add :time-in-ms t to all scheduled events and explicitly
;;; : convert the exec-time to ms.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2015.09.22 Dan [4.0]
;;; : * Track and complete requests to the vocal buffer. Should mostly
;;; : just work since this is built upon movement-styles and that's
;;; : been generally updated.
;;; 2017.01.26 Dan [5.0]
;;; : * Instead of sending output-speech to the device interface it
;;; : now just calls that function directly with a model name and
;;; : the text spoken. That goes out through the dispatcher to
;;; : provide something that can be monitored.
;;; 2017.01.27 Dan
;;; : * Fixed a cut-and-paste bug because it was trying to add
;;; : output-key as a command instead of output-speech.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Changed the parameter names for output-speech.
;;; 2017.02.27 Dan
;;; : * Schedule "output-speech" directly and don't bother with the
;;; : stub function.
;;; 2017.08.03 Dan [5.1]
;;; : * Adding a lock to the module which will be used to protect
;;; : all of the slots.
;;; : * Removed pm-register-articulation-time.
;;; 2017.08.23 Dan
;;; : * Don't need the dummy function for output-speech now.
;;; 2018.03.05 Dan [6.0]
;;; : * For consistency actually providing an interface and having
;;; : a microphone device that gets signaled if installed.
;;; : * Don't acquire the lock in get-art-time -- assume it is held.
;;; : * Update calls to get-art-time to hold the lock.
;;; : * Signal-device was renamed to notify-device.
;;; : * Use notify-device to ask if subvocalize need to be sent.
;;; 2018.03.12 Dan
;;; : * Update to the new interface and device approach which uses
;;; : the whole device list everywhere.
;;; 2018.06.01 Dan
;;; : * Use the param-lock from pm-module instead of the speech-lock
;;; : which can be eliminated.
;;; 2018.06.04 Dan [6.1]
;;; : * Changed the feature test to use string-equal and the table
;;; : for storing articulation times to be equalp so that the
;;; : strings are case insensitive.
;;; : * Added remote get/set-articulation-time commands.
;;; 2018.07.26 Dan [6.2]
;;; : * No longer handle tracked requests.
;;; 2020.01.10 Dan [6.3]
;;; : * Removed the #' and lambdas from the module interface
;;; : functions since that's not allowed in the general system
;;; : now.
;;; 2020.06.01 Dan [7.0]
;;; : * Moved the chunk-type and chunk definitions to the creation
;;; : function instead of the reset function.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled since it's not needed
;;; : and results in warnings in SBCL.
;;; 2021.03.18 Dan [7.1]
;;; : * The minimum articulation time is now the syllable-rate
;;; : not a fraction of that for shorter strings. For longer
;;; : strings it is still computed at the sub-syllable level i.e.
;;; : syllable-rate * (length/char-per-syllable).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(require-compiled "GENERAL-PM")
(defclass speech-module (pm-module)
((syllable-rate :accessor s-rate :initform 150)
(subvocalize-delay :accessor subvocalize-delay :initform 300)
(char-per-syllable :accessor char-per-syllable :initform 3)
(art-time-ht :accessor art-time-ht :initarg :art-time-ht
:initform (make-hash-table :test 'equalp))
(device :accessor device :initform nil)
(notify-subvocalize :accessor notify-subvocalize :initform nil))
(:default-initargs
:version-string "7.1"
:name :SPEECH))
(defmethod register-art-time ((spch-mod speech-module) (text string) (time number))
(bt:with-recursive-lock-held ((param-lock spch-mod))
(setf (gethash text (art-time-ht spch-mod)) (safe-seconds->ms time 'register-articulation-time))))
(defmethod get-art-time ((spch-mod speech-module) (text string) &optional time-in-ms)
(let ((time
(aif (gethash text (art-time-ht spch-mod))
it
(round (max (s-rate spch-mod) (* (s-rate spch-mod) (/ (length text) (char-per-syllable spch-mod))))))))
(if time-in-ms time (ms->seconds time))))
;;;; Create an interface and send the actions as signals to
;;;; an installed device.
(defun install-speech-device (device-list)
(let ((speech (get-module :speech)))
(when speech
(bt:with-recursive-lock-held ((param-lock speech))
(setf (device speech) device-list)
(let ((val (notify-device device-list '(check-subvocalize))))
(if val
(setf (notify-subvocalize speech) t)
(setf (notify-subvocalize speech) nil)))))
t))
(defun remove-speech-device (device-list)
(declare (ignore device-list))
(let ((speech (get-module :speech)))
(when speech
(bt:with-recursive-lock-held ((param-lock speech))
(setf (device speech) nil)
(setf (notify-subvocalize speech) nil)))
t))
(add-act-r-command "install-speech-device" 'install-speech-device "Internal command for speech module to handle a new device. Do not call directly.")
(add-act-r-command "remove-speech-device" 'remove-speech-device "Internal command for speech module to handle a device being removed. Do not call directly.")
(define-interface "speech" "install-speech-device" "remove-speech-device" t)
(defun default-speech-action ())
(defun notify-speech-device (device action text state)
(if device
(notify-device device (list state action text))
(when (eq state 'start)
(schedule-event-now 'default-speech-action :module :speech :output 'medium :details (format nil "~a ~a" action text)))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; SPEAK movement style
(defStyle speak () text)
(defmethod num-to-prepare ((mvmt speak))
3)
(defmethod compute-exec-time ((spch-mod speech-module) (mvmt speak))
(bt:with-recursive-lock-held ((param-lock spch-mod))
(init-time spch-mod)))
(defmethod compute-finish-time ((spch-mod speech-module) (mvmt speak))
(+ (exec-time mvmt)
(bt:with-recursive-lock-held ((param-lock spch-mod))
(get-art-time spch-mod (text mvmt)))))
(defmethod feat-differences ((s1 speak) (s2 speak))
(if (string-equal (text s1) (text s2))
0
2))
(defmethod queue-output-events ((spch-mod speech-module) (mvmt speak))
(new-sound-event (make-instance 'word-sound-evt :onset (+ (mp-time-ms) (seconds->ms (exec-time mvmt)))
:string (text mvmt) :location 'self))
(bt:with-recursive-lock-held ((param-lock spch-mod))
(schedule-event-relative (seconds->ms (exec-time mvmt)) 'notify-speech-device :output nil :time-in-ms t :params (list (device spch-mod) 'speak (text mvmt) 'start) :module :speech)
(schedule-event-relative (seconds->ms (finish-time mvmt)) 'notify-speech-device :output nil :time-in-ms t :params (list (device spch-mod) 'speak (text mvmt) 'end) :module :speech)))
;;;; SUBVOCALIZE movement style
(defStyle subvocalize speak text)
(defmethod queue-output-events ((spch-mod speech-module) (mvmt subvocalize))
(bt:with-recursive-lock-held ((param-lock spch-mod))
(new-sound-event (make-instance 'sound-event :onset (+ (mp-time-ms) (seconds->ms (exec-time mvmt)))
:duration (get-art-time spch-mod (text mvmt) t) :content (text mvmt)
:delay (subvocalize-delay spch-mod) :recode 0 :location 'internal
:kind 'word))
(when (notify-subvocalize spch-mod)
(schedule-event-relative (seconds->ms (exec-time mvmt)) 'notify-speech-device :output nil :time-in-ms t :params (list (device spch-mod) 'subvocalize (text mvmt) 'start) :module :speech)
(schedule-event-relative (seconds->ms (finish-time mvmt)) 'notify-speech-device :output nil :time-in-ms t :params (list (device spch-mod) 'subvocalize (text mvmt) 'end) :module :speech))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Dan
;;; everything below here is additional stuff for the ACT-R 6 interface
(defun query-speech-module (speech buffer slot value)
(if (and (eq slot 'state) (eq value 'error))
nil
(generic-state-query speech buffer slot value)))
(defmethod pm-module-last-cmd-name ((speech speech-module) buffer-name chunk-spec)
(declare (ignorable speech buffer-name))
(let ((main-spec (chunk-spec-slot-spec chunk-spec)))
(and (= (length main-spec) 1)
(or (eq 'speak (spec-slot-name (first main-spec)))
(eq 'subvocalize (spec-slot-name (first main-spec))))
(spec-slot-name (first main-spec)))))
(defmethod pm-module-request ((speech speech-module) buffer-name chunk-spec)
(declare (ignorable speech buffer-name))
(cond ((test-for-clear-request chunk-spec)
(schedule-event-now 'clear :module :speech :destination :speech :output 'low))
((= (length (chunk-spec-slot-spec chunk-spec 'cmd)) 1)
(let ((cmd (spec-slot-value (first (chunk-spec-slot-spec chunk-spec 'cmd)))))
(case cmd
((speak subvocalize)
(let ((string (verify-single-explicit-value chunk-spec 'string :speech cmd)))
(if (stringp string)
(schedule-event-now cmd :destination :speech :params (list :text string :request-spec chunk-spec)
:module :speech :output 'low
:details (format nil "~a ~a ~a" cmd :text string))
(model-warning "String slot in a ~s request must be a string." cmd))))
(t
(print-warning "Invalid command ~a sent to the vocal buffer" cmd)))))
((chunk-spec-slot-spec chunk-spec 'cmd)
(print-warning "Invalid command to speech module specifies the cmd slot multiple times."))
;; allow a request of just speak <text> or subvocalize <text>
(t
(let ((speak-spec (chunk-spec-slot-spec chunk-spec 'speak))
(subv-spec (chunk-spec-slot-spec chunk-spec 'subvocalize)))
(if (and (= (length speak-spec) 1)
(stringp (spec-slot-value (first speak-spec))))
(schedule-event-now 'speak :destination :speech
:params (list :text (spec-slot-value (first speak-spec)) :request-spec chunk-spec)
:module :speech :output 'low
:details (format nil "~a ~a ~a" 'speak :text (spec-slot-value (first speak-spec))))
(if (and (= (length subv-spec) 1)
(stringp (spec-slot-value (first subv-spec))))
(schedule-event-now 'subvocalize :destination :speech
:params (list :text (spec-slot-value (first subv-spec)) :request-spec chunk-spec)
:module :speech :output 'low
:details (format nil "~a ~a ~a" 'subvocalize :text (spec-slot-value (first speak-spec))))
(print-warning "Invalid command to speech module does not specify a valid action.")))))))
(defun reset-speech-module (instance)
(reset-pm-module instance)
)
(defun params-speech-module (speech param)
(bt:with-recursive-lock-held ((param-lock speech))
(if (consp param)
(case (car param)
(:syllable-rate
(setf (s-rate speech) (safe-seconds->ms (cdr param) 'sgp))
(cdr param))
(:char-per-syllable
(setf (char-per-syllable speech) (cdr param)))
(:subvocalize-detect-delay
(setf (subvocalize-delay speech) (safe-seconds->ms (cdr param) 'sgp))
(cdr param))
)
(case param
(:syllable-rate
(ms->seconds (s-rate speech)))
(:char-per-syllable
(char-per-syllable speech))
(:subvocalize-detect-delay
(ms->seconds (subvocalize-delay speech)))))))
(defun vocal-buffer-status ()
(print-module-status (get-module :speech)))
(defun create-speech-module (x)
(declare (ignore x))
(chunk-type speech-command (cmd "speech command"))
(chunk-type (speak (:include speech-command)) (cmd speak) string speak)
(chunk-type (subvocalize (:include speech-command)) (cmd subvocalize) string subvocalize)
(dolist (c '(speak subvocalize))
(unless (chunk-p-fct c)
(define-chunks-fct `((,c isa ,c)))))
(dolist (c '(self internal))
(unless (chunk-p-fct c)
(define-chunks-fct `((,c name ,c)))))
(make-instance 'speech-module))
(define-module-fct :speech
(list (define-buffer-fct 'vocal :queries '(modality preparation execution processor last-command)
:status-fn 'vocal-buffer-status))
(list
(define-parameter :syllable-rate
:valid-test 'nonneg
:default-value 0.15
:warning "a non-negative number"
:documentation "Seconds per syllable.")
(define-parameter :subvocalize-detect-delay
:valid-test 'nonneg
:default-value 0.3
:warning "a non-negative number"
:documentation "Sound detect time for a subvocalized word.")
(define-parameter :char-per-syllable
:valid-test 'posnum
:default-value 3
:warning "a positive number"
:documentation "Characters per syllable."))
:version (version-string (make-instance 'speech-module))
:documentation "A module to provide a model with the ability to speak"
:creation 'create-speech-module
:reset 'reset-speech-module
:query 'query-speech-module
:request 'pm-module-request
:params 'params-speech-module
)
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Misc toplevel stuff
(defun register-articulation-time (string time)
"Register the articulation time of a string."
(verify-current-mp
"No current meta-process. Cannot set articulation time."
(verify-current-model
"No current model. Cannot set articulation time."
(aif (get-module :speech)
(cond ((or (not (numberp time)) (minusp time))
(print-warning "Articulation time must be a non-negative number."))
((not (stringp string))
(print-warning "Must specify a string for which the articulation time is to be set."))
(t
(register-art-time it string time)))
(print-warning "No Speech module found. Cannot set articulation time.")))))
(defun get-articulation-time (string &optional time-in-ms)
"Return the articulation time of a string."
(verify-current-mp
"No current meta-process. Cannot get articulation time."
(verify-current-model
"No current model. Cannot get articulation time."
(aif (get-module :speech)
(cond ((not (stringp string))
(print-warning "Must specify a string for which to get the articulation time."))
(t
(bt:with-recursive-lock-held ((param-lock it))
(get-art-time it string time-in-ms))))
(print-warning "No Speech module found. Cannot get articulation time.")))))
(add-act-r-command "register-articulation-time" 'register-articulation-time "Set the time required to speak a string of text in seconds. Params: string time.")
(add-act-r-command "get-articulation-time" 'get-articulation-time "Get the time required to speak a string of text in seconds or milliseconds. Params: string {milliseconds?}.")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 23,084 | Common Lisp | .lisp | 427 | 49.079625 | 194 | 0.60875 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 15ee7de2d929def35a614df427fbeb74ea574f5c576cf35d57b9da02f2d3e9a3 | 14,294 | [
-1
] |
14,295 | imaginal.lisp | asmaloney_ACT-R/core-modules/imaginal.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : imaginal.lisp
;;; Version : 6.0
;;;
;;; Description : An actual imaginal module.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2005.09.27 Dan
;;; : Creation.
;;; 2005.11.08 Dan
;;; : * Extended it with a second buffer to accept commands to
;;; : manipulate the chunk in the imaginal buffer.
;;; : * The imaginal-action buffer right now only takes one
;;; : request which is generic-action that results in a funcall
;;; : of the function named in the action slot.
;;; 2005.11.16 Dan
;;; : * Replaced all occurences of imaginal-free with the actual
;;; : function name set-imaginal-free.
;;; 2006.09.08 Dan
;;; : * Changed the posnum test on the delay param to nonneg.
;;; 2006.09.25 Dan
;;; : * The module now accepts modification requests which also
;;; : take the imaginal-delay time to occur. They act just
;;; : like a normal buffer modification in a production i.e.
;;; : it just changes the slots as specified.
;;; 2006.09.25 Dan
;;; : * Changed the behavior on a "jam". Now, it ignores any
;;; : request (regular or modification) to either buffer when
;;; : the state of the module is busy.
;;; 2006.09.26 Dan
;;; : * Cleaned up set-imaginal-free and set-imaginal-error so that
;;; : they don't throw an error when there is no current imaginal
;;; : module.
;;; 2006.11.07 Dan
;;; : * Changed the mod-request cleanup event to just be set-imaginal-free
;;; : instead of a lambda that called it (makes the event easier to
;;; : read/handle).
;;; : * Also removed the handle-imaginal-request function/event and
;;; : schedule the goal-style-request and set-imaginal-free events
;;; : directly in the request.
;;; : * Removed the modification requests for the imaginal-action
;;; : buffer.
;;; 2007.01.16 Dan
;;; : * Fixed a bug in a warning in imaginal-mod-request.
;;; 2011.05.16 Dan [1.2]
;;; : * Added a new request to the imaginal-action buffer:
;;; : simple-action which works like generic-action execept that
;;; : it clears the imaginal buffer immediatly and the action
;;; : function should return either a chunk-name or nil.
;;; : If a chunk is returned it is put into the imaginal buffer
;;; : at the current delay time and if nil is returned it sets
;;; : the imaginal module error state to t at that time instead.
;;; : In either case, the module is flagged as busy during that time.
;;; 2013.04.10 Dan
;;; : * Allow the modification requests to now also extend the chunk-
;;; : type when a dynamic request specifies new slots.
;;; 2013.05.01 Dan [1.3]
;;; : * Added a slot called slots to both the generic-action and
;;; : simple-action types. That slot can be used when making a
;;; : request to the imaginal-action buffer to provide a list of
;;; : symbols. If all of those symbols name slots of the chunk
;;; : in the imaginal buffer at the time of the request then
;;; : they will be passed to the action function. If they are not
;;; : valid slot names then the request will fail.
;;; 2013.05.07 Dan
;;; : * Test whether the slots slot is specified in the imaginal-action
;;; : requests to avoid a warning when getting its value when not
;;; : provided.
;;; 2014.05.14 Dan [2.0]
;;; : * Change to deal with the new type-less chunks. Since the
;;; : request function can't case off of type need to check the
;;; : slots of the spec and using a slot named simple to indicate
;;; : if the action should be treated as the simple. If the model
;;; : requests "isa simple-action ..." that slot will be set
;;; : automatically.
;;; 2015.02.11 Dan [2.1]
;;; : * Change the default value for :ga from 1 to 0. The imaginal
;;; : buffer is now the only one which spreads activation by default.
;;; : Should have made this change with the first version of 6.1.
;;; 2015.03.20 Dan
;;; : * Set-imaginal-error now sets the buffer failure flag in the
;;; : imaginal buffer using set-buffer-failure.
;;; 2015.04.01 Dan
;;; : * Set-imaginal-error now sets the buffer failure flag for both
;;; : the imaginal and imaginal-action buffers.
;;; 2015.06.04 Dan
;;; : * Change the :imaginal-delay to ms when it's set and then use
;;; : :time-in-ms t for scheduling events.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2015.08.17 Dan
;;; : * Changed the randomize-time calls which were used with times
;;; : in ms to randomize-time-ms.
;;; 2015.09.22 Dan [3.0]
;;; : * Make the buffers trackable. Completion will be tied to the
;;; : busy/free signal since the module can only handle one
;;; : request at a time regardless of buffer through which the
;;; : request is made.
;;; : * Since set-imaginal-free gets used for all the requests then
;;; : that's the easy place to put the completion and works for
;;; : the imaginal-action requests too (assuming the user calls it
;;; : for the generic requests).
;;; 2015.12.15 Dan
;;; : * Set-imaginal-error now also completes a request.
;;; 2017.02.15 Dan [4.0]
;;; : * The imaginal-action requests can now accept strings as the
;;; : action and those will be sent out through the dispatcher.
;;; : Set-imaginal-free and set-imaginal-error are now remotely
;;; : available for use with imaginal actions.
;;; 2017.02.17 Dan
;;; : * Use local-or-remote-function-p to test the imaginal actions.
;;; 2017.03.14 Dan
;;; : * Use dispatch-apply-list instead of dispatch-apply since a
;;; : slots value of nil means no parameters not one parameter of
;;; : nil.
;;; : * If the result is a string, convert that to a symbol when
;;; : calling chunk-p-fct since it doesn't do that automatically.
;;; 2017.08.08 Dan
;;; : * Make everything thread safe using a single lock instead of
;;; : separate param and state locks like other modules since it's
;;; : such a simple module.
;;; 2018.06.12 Dan
;;; : * Change the doc string on the external commands for consistency.
;;; 2018.07.26 Dan [4.1]
;;; : * Removing the support for competion of events.
;;; 2020.01.10 Dan [4.2]
;;; : * Removed the #' from the module interface functions since
;;; : that's not allowed in the general system now.
;;; 2020.06.01 Dan [5.0]
;;; : * Moved the chunk-type definitions to the creation
;;; : function instead of the reset function.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled since it's not needed
;;; : and results in warnings in SBCL.
;;; 2021.06.14 Dan [6.0]
;;; : * Allow the simple imaginal-action request to accept a chunk
;;; : description list as the return value and then use that to
;;; : set the buffer instead of creating a temp chunk.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; The imaginal module has two buffers one called imaginal which works just like
;;; the goal module (requests create new chunks) except there is a time delay
;;; before the new chunk shows up in the buffer. The delay is controlled by
;;; a parameter called :imaginal-delay.
;;; The other buffer is called imaginal-action and it takes requests to change
;;; the chunk currently in the imaginal buffer or to perform other actions
;;; that use that chunk (without having to clear the buffer).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; The new buffer imaginal is available.
;;;
;;; There is a new parameter called :imaginal-delay which must be a number.
;;; It defaults to .2 and is the time in seconds before an imaginal request
;;; completes.
;;;
;;; The imaginal-action buffer accepts two requests:
;;;
;;; a generic-action: the action slot is required, the slots slot is
;;; optional, and there should be no other slots.
;;;
;;; The function named in the action slot is called at the time of the request.
;;; All timing and state maintenance must be handled by that function except
;;; that the module is marked busy at the time of the call (thus the function
;;; or an event that it schedules, needs to set it back to free using the
;;; set-imaginal-free command). No chunks are placed into the imaginal-action
;;; buffer by default, but the generic-action chunk-type also has a slot
;;; called result which could be a meaningful thing to use - place a
;;; chunk of type generic-action with the action and result slots set
;;; in the imaginal-action buffer in response to a request. If the slots slot
;;; is specified with a list of symbols which name valid slots for a chunk then
;;; those slot names will be passed to the action function in the order provided
;;; i.e. this is what will effectively happen: (apply <action> <slots list>).
;;; If the slots list is provided but not valid then no action is taken and a warning
;;; is printed.
;;;
;;; a simple-action: the action slot is required, the slots slot is
;;; optional, and the simple slot should have a true value (default for
;;; the simple-action chunk-type).
;;;
;;; The function named in the action slot is called at the time of the request,
;;; the imaginal buffer is cleared, and the imaginal module is marked as busy.
;;; The action function should return either a chunk name, a list of slots and
;;; values that describe a chunk, or nil. If a chunk name or list of slots and
;;; values is returned then the named chunk will be copied into the imaginal
;;; buffer after the current delay time for the imaginal module passes and the
;;; module will then be marked as free. If a slots and values list is returned
;;; then that will be used to create a new chunk in the imaginal buffer after the
;;; current delay time passes and then the module will be marked as free. If the
;;; function returns nil then after the current imaginal delay time passes the
;;; module will be marked as free and the error state will be set to t. If the
;;; slots slot is specified with a list of symbols which name valid slots for a
;;; chunk then those slot names will be passed to the action function in the order
;;; provided i.e. this is what will effectively happen: (apply <action> <slots list>).
;;; If the slots list is provided but not valid then no action is taken and a warning
;;; is printed.
;;;
;;;
;;; Two new commands are provided for use in user defined actions:
;;;
;;; set-imaginal-free
;;; This command takes no parameters and sets the state of the imaginal
;;; module in the current model to free.
;;;
;;; set-imaginal-error
;;; This command takes no parameters and sets the error state of the
;;; imaginal module in the current model to t. The only way to clear
;;; the error is through a new request or resetting the model.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; There's a little more here than the goal-style-module code would seem to
;;; indicate is necessary because there's a paramter in the module and it needs
;;; to properly signal busy/free during the delay (which the goal-style-query
;;; doesn't do).
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(require-compiled "GOAL-STYLE-MODULE")
(defstruct imaginal-module delay busy error randomize last-request (lock (bt:make-lock "imaginal-module")))
(defun create-imaginal (model)
(declare (ignore model))
(chunk-type generic-action action slots result)
(chunk-type simple-action action slots (simple t))
(make-imaginal-module))
(defun imaginal-query (instance buffer-name slot value)
(declare (ignore slot)) ; the only slot is state
(bt:with-lock-held ((imaginal-module-lock instance))
(case value
(busy (imaginal-module-busy instance))
(free (not (imaginal-module-busy instance)))
(error (imaginal-module-error instance))
(t (print-warning "Unknown state query ~S to ~S module"
value buffer-name)
nil))))
(defun set-imaginal-free ()
(let ((im (get-module imaginal)))
(if im
(bt:with-lock-held ((imaginal-module-lock im))
(setf (imaginal-module-busy im) nil)
t)
(print-warning "Call to set-imaginal-free failed"))))
(add-act-r-command "set-imaginal-free" 'set-imaginal-free "Clear the busy flag for the imaginal module. No params.")
(defun set-imaginal-error ()
(let ((im (get-module imaginal)))
(if im
(progn
(bt:with-lock-held ((imaginal-module-lock im))
(setf (imaginal-module-error im) t))
(set-buffer-failure 'imaginal)
(set-buffer-failure 'imaginal-action)
t)
(print-warning "Call to set-imaginal-error failed"))))
(add-act-r-command "set-imaginal-error" 'set-imaginal-error "Clear the busy flag for the imaginal module, set the error state, and complete the request as needed for imagnal-action buffer requests. No params.")
(defun imaginal-request (instance buffer-name chunk-spec)
(bt:acquire-lock (imaginal-module-lock instance))
(cond ((imaginal-module-busy instance)
(bt:release-lock (imaginal-module-lock instance))
(model-warning "Imaginal request made to the ~S buffer while the imaginal module was busy. New request ignored." buffer-name))
(t
(setf (imaginal-module-busy instance) t)
(setf (imaginal-module-error instance) nil)
(case buffer-name
(imaginal
(let ((delay (if (imaginal-module-randomize instance)
(randomize-time-ms (imaginal-module-delay instance))
(imaginal-module-delay instance))))
(schedule-event-relative delay
'set-imaginal-free
:time-in-ms t
:module 'imaginal
:output nil
:priority -1010)
(schedule-event-relative delay
'goal-style-request
:time-in-ms t
:params (list 'imaginal chunk-spec)
:destination 'imaginal
:module 'imaginal
:output nil)
(bt:release-lock (imaginal-module-lock instance))))
(imaginal-action
(flet ((bad-action-exit (&rest strings)
(dolist (x strings)
(print-warning x))
(setf (imaginal-module-busy instance) nil)
(bt:release-lock (imaginal-module-lock instance))
(return-from imaginal-request nil)))
(let ((action-spec (chunk-spec-slot-spec chunk-spec 'action))
(slots-spec (chunk-spec-slot-spec chunk-spec 'slots))
(simple-spec (chunk-spec-slot-spec chunk-spec 'simple)))
(cond ((null action-spec)
(bad-action-exit "An imaginal-action request requires an action."))
((> (length action-spec) 1)
(bad-action-exit "An imaginal-action request requires a single action."))
((not (eq '= (spec-slot-op (first action-spec))))
(bad-action-exit "An imaginal-action request requires the = specifier for the action."))
((not (local-or-remote-function-p (spec-slot-value (first action-spec))))
(bad-action-exit "An imaginal-action request requires the action to name a valid function or a string naming a command."))
(t
(let ((slots nil))
(when slots-spec
(cond ((> (length slots-spec) 1)
(bad-action-exit "An imaginal-action request can only specify one slots list."))
((not (eq '= (spec-slot-op (first slots-spec))))
(bad-action-exit "An imaginal-action request requires the = specifier for the slots."))
((not (listp (spec-slot-value (first slots-spec))))
(bad-action-exit "An imaginal-action request slots value must be a list."))
((not (buffer-read 'imaginal))
(bad-action-exit "An imaginal-action request which specifies slots requires a chunk in the imaginal buffer."))
((not (every (lambda (x) (valid-slot-name x)) (spec-slot-value (first slots-spec))))
(bad-action-exit "An imaginal-action request which specifies slots requires valid slot names."))
(t
(setf slots (spec-slot-value (first slots-spec))))))
(if simple-spec
(cond ((> (length simple-spec) 1)
(bad-action-exit "An imaginal-action request can only specify the simple slot once."))
((not (eq '= (spec-slot-op (first simple-spec))))
(bad-action-exit "An imaginal-action request requires the = specifier for the simple slot"))
(t
(if (null (spec-slot-value (first simple-spec)))
(progn
(bt:release-lock (imaginal-module-lock instance))
(dispatch-apply-list (spec-slot-value (first action-spec)) slots))
(progn
(bt:release-lock (imaginal-module-lock instance))
(let ((c (dispatch-apply-list (spec-slot-value (first action-spec)) slots))
(delay (bt:with-lock-held ((imaginal-module-lock instance))
(if (imaginal-module-randomize instance)
(randomize-time-ms (imaginal-module-delay instance))
(imaginal-module-delay instance)))))
(schedule-clear-buffer 'imaginal 0 :time-in-ms t :module 'imaginal)
(cond ((null c) ;; set module free and error t
(schedule-event-relative delay 'set-imaginal-free :time-in-ms t :module 'imaginal :output nil)
(schedule-event-relative delay 'set-imaginal-error :time-in-ms t :module 'imaginal :output nil))
((chunk-p-fct (string->name c)) ;; set module free and buffer chunk
(schedule-set-buffer-chunk 'imaginal (string->name c) delay :time-in-ms t :module 'imaginal :priority -1000)
(schedule-event-relative delay 'set-imaginal-free :time-in-ms t :module 'imaginal :output nil :priority -1001 :maintenance t))
((listp c)
(aif (define-chunk-spec-fct (decode-string-names c))
(schedule-set-buffer-chunk 'imaginal it delay :time-in-ms t :module 'imaginal :priority -1000)
(progn
(bt:acquire-lock (imaginal-module-lock instance)) ;; since the bad exit releases it
(bad-action-exit "Invalid result from the action of an imaginal-action simple-action function."))))
(t
(bt:acquire-lock (imaginal-module-lock instance)) ;; since the bad exit releases it
(bad-action-exit "Invalid result from the action of an imaginal-action simple-action function."))))))))
(progn
(bt:release-lock (imaginal-module-lock instance))
(dispatch-apply-list (spec-slot-value (first action-spec)) slots)))))))))))))
(defun imaginal-mod-request (instance buffer mods)
(bt:with-lock-held ((imaginal-module-lock instance))
(cond ((imaginal-module-busy instance)
(model-warning "Imaginal modification request made to the ~S buffer while the imaginal module was busy. New request ignored." buffer))
((eq buffer 'imaginal)
(let ((delay (if (imaginal-module-randomize instance)
(randomize-time-ms (imaginal-module-delay instance))
(imaginal-module-delay instance))))
(setf (imaginal-module-busy instance) t)
(schedule-mod-buffer-chunk buffer mods delay :time-in-ms t :module 'imaginal)
(schedule-event-relative delay 'set-imaginal-free :time-in-ms t :module 'imaginal :priority -1 :output nil)))
(t
(model-warning "Modification requests not available for the imaginal-action buffer")))))
(defun imaginal-params (instance param)
(bt:with-lock-held ((imaginal-module-lock instance))
(if (consp param)
(case (car param)
(:imaginal-delay (setf (imaginal-module-delay instance) (safe-seconds->ms (cdr param))) (cdr param))
(:vidt (setf (imaginal-module-randomize instance) (cdr param))))
(case param
(:imaginal-delay (ms->seconds (imaginal-module-delay instance)))
(:vidt (imaginal-module-randomize instance))))))
(defun imaginal-reset (instance)
(bt:with-lock-held ((imaginal-module-lock instance))
(setf (imaginal-module-busy instance) nil)
(setf (imaginal-module-error instance) nil)))
(define-module-fct 'imaginal
(list (define-buffer imaginal :param-default 1.0)
(define-buffer imaginal-action))
(list
(define-parameter :imaginal-delay :valid-test 'nonneg
:default-value .2 :warning "non-negative number"
:documentation "Time in seconds to respond to an imaginal request")
(define-parameter :vidt :valid-test 'tornil :default-value nil
:warning "T or nil" :documentation "Variable Imaginal Delay Time"))
:version "6.0"
:documentation "The imaginal module provides a goal style buffer with a delay and an action buffer for manipulating the imaginal chunk"
:creation 'create-imaginal
:query 'imaginal-query
:request 'imaginal-request
:buffer-mod 'imaginal-mod-request
:params 'imaginal-params
:reset 'imaginal-reset)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 26,030 | Common Lisp | .lisp | 435 | 49.928736 | 210 | 0.57759 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | addacafe258dae0b20e8af4150d4cfa79f25d5c57c2d8331de156ec1f921d314 | 14,295 | [
-1
] |
14,296 | core-loader.lisp | asmaloney_ACT-R/core-modules/core-loader.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : core-loader.lisp
;;; Version : 1.0a1
;;;
;;; Description : Compiles (if necessary) and loads the files that implement
;;; the core modules.
;;;
;;; Bugs :
;;;
;;; To do : Possibly need special cases for "standalones" as was done
;;; with the ACT-R 5 loader.
;;;
;;; ----- History -----
;;;
;;; 2005.01.02 Dan
;;; : Creation
;;; 2005.01.29 Dan
;;; : * Changed core-load to use compile-and-load instead of doing
;;; : the the same things here.
;;; 2005.09.29 Dan
;;; : * Added imaginal to the list - I forgot that core-modules
;;; : wasn't searched, but loaded in a specific order.
;;; 2005.10.18 Dan
;;; : * Stripped this down to just the file list. It makes more
;;; : sense to have all the loading in the top-level load file.
;;; 2011.04.28 Dan
;;; : * Just setf the list instead of defining it.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; loaded by the top level loader so it's not really for general use, but
;;; may be needed when testing updates.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; Nothing for use here.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Just a list of files to be loaded in order from the core-modules directory.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Define the files to be loaded.
(setf *file-list* '("declarative-memory"
"goal"
"procedural"
"vision"
"motor"
"audio"
"speech"
"imaginal"))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 3,496 | Common Lisp | .lisp | 88 | 36.909091 | 80 | 0.501617 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 615980cf6736c9831575dd6445d8446b87a093f283a084cb55fe8c72c4c415d7 | 14,296 | [
-1
] |
14,297 | temporal.lisp | asmaloney_ACT-R/modules/temporal.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Niels Taatgen
;;; Copyright : (c) 2005 Niels Taatgen
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : temporal.lisp
;;; Version : 4.0
;;;
;;; Description : Implementation of the temporal module.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2005.04.26 Niels
;;; : Initial creation.
;;; 2010.02.05 Dan [1.0b2]
;;; : * Moved the noise added to t0 into the reset function and
;;; : made that a 3rd pass reset so that if the seed is set in
;;; : the model code the temporal module will perform the same
;;; : every time. However, if the model time isn't 0 (other than
;;; : during a reset) then it will still add the noise when the
;;; : :time-master-start-increment parameter is changed.
;;; : * Along with that I changed it from a fixed .075 multiplier
;;; : (which is 5 * the default b) to actually 5 times the current
;;; : b value (:time-noise).
;;; : * Also changed the return value for setting :time-master-start-increment
;;; : to always be the value set instead of the randomized value
;;; : since the non-setting sgp returns the non-randomized value.
;;; : * Needs a primary reset to create the chunk type.
;;; 2010.06.17 Dan
;;; : * Added a mod-request function which uses the goal-style-mod-request
;;; : and then use that to make the updates to the time tick. That
;;; : will then be recorded in the buffer trace history which will then
;;; : show in the tracing tools.
;;; : [1.0b3]
;;; : * Changed that to put it on a switch so that it can be turned
;;; : off for something like computing bold response where only
;;; : the "reseting" is what's important.
;;; : The :record-ticks parameter controls whether or not the
;;; : individual updates create an event to record. The default
;;; : value is t.
;;; 2010.08.09 Dan [1.0b4]
;;; : * Moved the setting of the t0 noise from reset/param. init.
;;; : time to the first request. That way it doesn't affect how
;;; : the existing test models operate. Also makes it easy if
;;; : we want to switch it to have a new random offset each time.
;;; : * Took out the temporal-mod-request function which isn't used
;;; : now since it uses the goal-style-mod-request.
;;; 2010.08.10 Dan
;;; : * Added code to make sure that there is a chunk-type called clear
;;; : defined and if not to define it.
;;; : * Actually generate an event for the clear request in the trace.
;;; : * Changed the update event's details from format to concatenate
;;; : which is typically significantly faster.
;;; : * Changed the test for :time-noise to be posnum since act-r-noise
;;; : only works for values >0.
;;; : * Changed all the parameters' warnings to indicate a positive
;;; : number is required.
;;; 2010.09.17 Dan
;;; : * Changed the 3rd reset function to a second reset function
;;; : because otherwise the :do-not-harvest setting doesn't apply
;;; : during production definition...
;;; 2011.05.17 Dan [1.0b5]
;;; : * Added some saftey checks so that there's always at least
;;; : a 1ms increment in time before the next tick to avoid bad
;;; : situations which could arrive with some parameter adjustments.
;;; 2011.07.04 Dan
;;; : * Set a 1ms minimum time for temporal-module-time-start-increment
;;; : to avoid negative calls to act-r-noise.
;;; 2013.01.17 Dan [1.0]
;;; : * Changed it so the timer ticks don't show in the low detail
;;; : trace.
;;; 2014.05.16 Dan [2.0]
;;; : * Updated to work with the type-less chunk mechanism.
;;; 2014.11.03 Dan
;;; : * Allow clear requests like PM modules by using the
;;; : test-for-clear-request function.
;;; 2015.06.05 Dan [2.1]
;;; : * Compute the tick lengths in ms by converting :time-master-start-increment
;;; : when provided and schedule everything in ms.
;;; 2018.06.04 Dan
;;; : * Don't require that the tick value be zero in the request to
;;; : start the module going.
;;; 2020.01.10 Dan [2.2]
;;; : * Removed the #' from the module interface functions
;;; : since that's not allowed in the general system now.
;;; 2020.06.01 Dan [3.0]
;;; : * Moved the chunk-type definition to the creation
;;; : function instead of the reset function.
;;; 2020.07.06 Dan [3.1]
;;; : * Got rid of the temporal-clear dummy function and just
;;; : schedule nil since the details are all that matters.
;;; 2021.03.10 Dan [3.2]
;;; : * Also put temporal on the do-not-query list.
;;; 2021.06.07 Dan [4.0]
;;; : * Instead of using create-new-buffer-chunk just schedule
;;; : set-buffer-chunk with a spec, and create that spec at reset
;;; : so it doesn't have to happen every time.
;;; 2021.10.20 Dan
;;; : * Check whether there is a procedural module before setting
;;; : the :do-not-* parameters.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; User Functions:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defstruct temporal-module
time-noise
time-mult
time-start-increment
time-master-start-increment
tick
ticks
next-increment
record-ticks
spec)
(defun create-temporal-module (model-name)
(declare (ignore model-name))
(chunk-type time (ticks 0))
(make-temporal-module))
(defun temporal-reset-1 (instance)
;; Create the chunk-type and clear the internal
;; marker for the next update.
(setf (temporal-module-next-increment instance) nil))
(defun temporal-reset-2 (instance)
(setf (temporal-module-spec instance) (define-chunk-spec isa time))
;; Do NOT strict harvest the temporal buffer by default
(when (get-module procedural t)
(sgp :do-not-harvest temporal :do-not-query temporal)))
(defun temporal-query (instance buffer-name slot value)
(declare (ignore instance buffer-name))
(case slot
(state
(case value
(busy nil)
(free t)
(error nil)
(t (print-warning "Unknown state query ~S to temporal module" value)
nil)))
(t (print-warning "Unknown query of the temporal module"))))
(defun temporal-request (instance buffer-name chunk-spec)
(declare (ignore buffer-name))
;; Don't want to perform the next increment if a new
;; request comes in or a bad value could get written.
(when (temporal-module-next-increment instance)
(delete-event (temporal-module-next-increment instance)))
;; Add the noise to the start tick (for now only happens
;; at the time of the first request).
(when (null (temporal-module-time-start-increment instance))
(setf (temporal-module-time-start-increment instance)
(max 1
(+ (temporal-module-time-master-start-increment instance)
(act-r-noise (* (temporal-module-time-master-start-increment instance)
5 (temporal-module-time-noise instance)))))))
(let ((ticks (chunk-spec-slot-spec chunk-spec 'ticks))
(clear (test-for-clear-request chunk-spec)))
(if (or ticks clear)
(if clear
(schedule-event-now nil :module 'temporal :details "Clear")
(if (not (verify-single-explicit-value chunk-spec 'ticks 'temporal 'time))
(print-warning "Invalid time request made to the temporal module.")
(progn
(schedule-set-buffer-chunk 'temporal (temporal-module-spec instance) 0
:module 'temporal :priority -1000)
(setf (temporal-module-tick instance)
(max 1 (+ (temporal-module-time-start-increment instance)
(act-r-noise
(* (temporal-module-time-noise instance)
(temporal-module-time-start-increment instance))))))
(setf (temporal-module-ticks instance) 0)
(setf (temporal-module-next-increment instance)
(schedule-event-relative (round (temporal-module-tick instance)) 'next-time-tick
:time-in-ms t
:module 'temporal :priority :min
:details "Incrementing time ticks to 1"
:destination 'temporal)))))
(print-warning "Invalid request made to the temporal module."))))
(defun next-time-tick (instance)
;; if the chunk in the temporal buffer has a slot named ticks which holds a number
(when (let ((c (buffer-read 'temporal)))
(and c (numberp (chunk-slot-value-fct c 'ticks))))
(incf (temporal-module-ticks instance))
(setf (temporal-module-tick instance)
(* (temporal-module-tick instance) (temporal-module-time-mult instance)))
(setf (temporal-module-tick instance)
(max 1 (+ (temporal-module-tick instance)
(act-r-noise (* (temporal-module-time-noise instance)
(temporal-module-tick instance))))))
;; using a mod-request to do it so that it shows up in the
;; tracing tools when desired otherwise just do the modification
;; directly on the buffer chunk
(if (temporal-module-record-ticks instance)
(schedule-module-mod-request 'temporal (list 'ticks (temporal-module-ticks instance)) 0 :time-in-ms t :module 'temporal)
(schedule-mod-buffer-chunk 'temporal (list 'ticks (temporal-module-ticks instance)) 0 :time-in-ms t :module 'temporal :output 'medium))
(setf (temporal-module-next-increment instance)
(schedule-event-relative (round (temporal-module-tick instance)) 'next-time-tick
:time-in-ms t :module 'temporal :priority :min :destination 'temporal
:details (concatenate 'string "Incrementing time ticks to "
(princ-to-string (1+ (temporal-module-ticks instance))))))))
(defun temporal-mod-request (instance buffer mods)
(declare (ignore instance))
(schedule-mod-buffer-chunk buffer mods 0 :time-in-ms t :module buffer :output 'medium))
(defun temporal-params (tmp param)
(cond ((consp param)
(case (car param)
(:time-noise (setf (temporal-module-time-noise tmp) (cdr param)))
(:time-mult (setf (temporal-module-time-mult tmp) (cdr param)))
(:record-ticks (setf (temporal-module-record-ticks tmp) (cdr param)))
(:time-master-start-increment (setf (temporal-module-time-start-increment tmp) nil)
(setf (temporal-module-time-master-start-increment tmp) (seconds->ms (cdr param)))
(cdr param))))
(t
(case param
(:time-noise (temporal-module-time-noise tmp))
(:time-mult (temporal-module-time-mult tmp))
(:record-ticks (temporal-module-record-ticks tmp))
(:time-master-start-increment (ms->seconds (temporal-module-time-master-start-increment tmp)))))))
;;; Actually define the module now
(define-module-fct 'temporal '(temporal)
(list (define-parameter :time-noise :valid-test 'posnum :default-value .015
:warning "a positive number" :documentation "Temporal noise")
(define-parameter :time-master-start-increment :valid-test 'posnum :default-value .011
:warning "a positive number" :documentation "Temporal start interval")
(define-parameter :time-mult :valid-test 'posnum :default-value 1.1
:warning "a positive number" :documentation "Temporal multiplier")
(define-parameter :record-ticks :valid-test 'tornil :default-value t
:warning "t or nil" :documentation "Record each time increment as a buffer event")
)
:version "4.0"
:documentation "The temporal module is used to estimate short time intervals"
:creation 'create-temporal-module
:query 'temporal-query
:request 'temporal-request
:buffer-mod 'temporal-mod-request
:params 'temporal-params
:reset (list 'temporal-reset-1 'temporal-reset-2))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 14,603 | Common Lisp | .lisp | 281 | 46.323843 | 141 | 0.592681 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | af0382d58f09981d8c33f2b0a5a2d55bfa508eddca792a8c95d9e64fd94cf73c | 14,297 | [
-1
] |
14,298 | act-gui-interface.lisp | asmaloney_ACT-R/modules/act-gui-interface.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Address : Carnegie Mellon University
;;; : Psychology Department
;;; : Pittsburgh,PA 15213-3890
;;; : [email protected]
;;;
;;; Copyright : (c)2002-2017 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : act-gui-interface.lisp
;;; Version : 6.0
;;;
;;; Description : Contains the functions that implement the abstract GUI
;;; : interface used by the tutorial units and the misc functions
;;; : that go with them (correlation and mean-deviation).
;;; : I'm calling it the ACT-R GUI interface (AGI) as suggested by Mike.
;;; : It relies on the old UWI to handle the "real" interface to any
;;; : particular windowing environment.
;;; Bugs :
;;; To Do : [x] Consider making it support multiple interfaces to go with
;;; : multiple models.
;;; --- History ---
;;; 2002.06.30 Dan
;;; : Added this header.
;;; : Renamed this file from uniform-interface-exp to
;;; : act-gui-interface.
;;; : Added comments.
;;; 2002.12.17 Dan
;;; : Modified correlation and mean-deviation so that
;;; : the output keyword parameter is "more useful" -
;;; : specifying a stream works right now (it doesn't try to
;;; : open a file for it) and specifying nil suppress
;;; : all output.
;;; 2002.12.19 Dan
;;; : Updated add-text-to-exp-window so that it now includes
;;; : a color option.
;;; 04.04.13 Dan [2.2] (previous two changes also "new" as of 2.2)
;;; : Changed the copyright notice and added the LGPL stuff.
;;;
;;; 04.10.19 Dan [Moved into ACT-R 6]
;;; : reset version to 1.0a1
;;; : added the packaging switches
;;; : changed permute-list to use act-r-random
;;;
;;; 04.12.17 Dan
;;; : Added get-time as a replacement for pm-get-time.
;;;
;;; 2005.02.25 Dan
;;; : * Removed the ~\newline usages because that causes problems
;;; : when a Lisp only wants to see native new lines there.
;;; 2006.09.07 Dan
;;; : * Changed permute-list so that it's safe when passed nil or
;;; : a non-list.
;;; 2007.07.13 Dan
;;; : * Added color as an option to add-button-to-exp-window.
;;; 2007.12.13 Dan
;;; : * Adding an add-items-to-exp-window function to compliment
;;; : the remove-... and to avoid the need to call the UWI
;;; : function when such an action is necessary.
;;; 2009.09.10 Dan
;;; : * Moved permute-list to the random module's file.
;;; 2010.03.08 Dan
;;; : * Changed close-exp-window so that it checks to see if the
;;; : window is still there before trying to close it. Avoids
;;; : a problem where a user has closed an environment side
;;; : window.
;;; 2010.07.31 Dan
;;; : * Changed add-line-to-exp-window to constrain the x,y positions
;;; : to be fixnums to avoid problems in ACL and LispWorks if
;;; : a float or rational is used instead.
;;; 2011.04.26 Dan
;;; : * Changed get-time to just return mp-time-ms.
;;; 2011.11.14 Dan
;;; : * Make open-exp-window set the visual center to the center of
;;; : the window.
;;; 2011.11.21 Dan
;;; : * Get-time changed to not use *actr-enabled-p*. Instead
;;; : it uses an optional parameter to determine whether or not
;;; : to use mp-time.
;;; : If the optional parameter is provided then a true value
;;; : means model time and nil means internal-real-time. If
;;; : no parameter is provided then model time will be returned.
;;; 2012.06.08 Dan [2.0a1]
;;; : * Use a module to maintain the information for the open
;;; : window(s) and allow multiple open windows for a model.
;;; : Multiple models may have the same titled window open and
;;; : that should make it "easy" to have multiple models use the
;;; : same code to provide separate interfaces. The real window's
;;; : title (which the model can't see anyway) will include the
;;; : model's name to make things easier for the modeler.
;;; : * The significant changes to the commands are:
;;; : - open-exp-window doesn't automatically close a window with
;;; : a different title when it creates a new one. It does
;;; : still clear and bring to the front a window by the same
;;; : title within the same model.
;;; : - Open-exp-window will only create a window if there is a
;;; : current model. The main reason for that is because it
;;; : avoids a lot of hassle of dealing with "unowned"
;;; : windows. It also makes things much easier with respect
;;; : to displaying multiple visible virtual windows through
;;; : the ACT-R Environment.
;;; : - All windows now automatically close when the owning model
;;; : is deleted (either explicitly or via clear-all) and if
;;; : the new system parameter :close-exp-windows-on-reset is set
;;; : it will also close them when the owning model is reset.
;;; : [I'd prefer the default for :close-exp-windows-on-reset
;;; : to be t, but unfortunately because of how the single
;;; : experiment window code worked doing so would likely break
;;; : lots of existing models (since some in the tutorial models
;;; : used it in a manner that assumed the window persists).]
;;; : - Most of the commands now have an additional keyword
;;; : parameter :window which can be used to indicate which
;;; : window to perform the action upon. If it is not provided
;;; : and there is only one window open in the current model
;;; : the command will be applied to that window, otherwise it
;;; : will result in a warning and no action performed.
;;; : The window value can be specified as either the window
;;; : object returned by open-exp-window or the title which
;;; : was specified for open-exp-window. When specifying a title
;;; : as the :window parameter that will be relative to the current
;;; : model since different models can have windows with the same
;;; : title.
;;; : - For add-line-to-exp-window the color is now a keyword
;;; : parameter instead of optional so that it isn't confusing
;;; : when also specifying a window. This change is the only one
;;; : that's not backward compatible with the previous "single
;;; : window" usage and will require changing existing models.
;;; 2012.07.02 Dan
;;; : * Open-exp-window now calls device-update-attended-loc with a
;;; : nil xy-loc when it reuses a window so that the attended marker
;;; : gets cleared.
;;; 2012.07.12 Dan
;;; : * Added the exp-window-owner function because there are times
;;; : when it would be useful to know that.
;;; 2012.12.12 Dan
;;; : * Adding a check to make sure that the text is a string in
;;; : add-text-to-exp-window.
;;; 2013.09.30 Dan [2.0]
;;; : * Time to remove the a1 from the version.
;;; 2015.05.26 Dan
;;; : * Added a :font-size parameter to add-text-to-exp-window.
;;; 2016.06.07 Dan [3.0]
;;; : * Starting work to add create and modify actions for each of
;;; : default item types. Create is already supported by the UWI,
;;; : and is being implemented first.
;;; : * Added a check of the text for a button to make sure it's a
;;; : string.
;;; 2016.06.08 Dan
;;; : * Adding a :class parameter to open-exp-window for passing off
;;; : to make-rpm-window to allow for easier extensions while I'm
;;; : in here.
;;; : * Added the front AGI modify functions which call out to UWI
;;; : modify functions.
;;; 2016.06.09 Dan
;;; : * Fixed a bug with the use of flatten and push.
;;; : * Fixed an issue with create-line actually adding it to the
;;; : display as well.
;;; 2016.11.17 Dan
;;; : * Use current-mp instead of current-meta-process when creating
;;; : the table key -- don't need that at all with this version
;;; : since only a single meta-process is supported, but for now
;;; : keeping the changes minimal.
;;; 2017.01.04 Dan [4.0]
;;; : * Only the virtual and visible-virtual windows are used now.
;;; : * Don't return the window object, but a list of module interface
;;; : items for use with the new install-device function.
;;; : * Make open-exp-window available through the dispatcher with
;;; : optional parameters instead of keywords.
;;; : * Make get-time available through dispatcher.
;;; 2017.01.05 Dan
;;; : * Added the call to create a device (under the new definition
;;; : of what a device is) and assuming now that it's building a
;;; : subtype of virtual window underneath.
;;; 2017.01.10 Dan
;;; : * BIG ISSUE -- right now this code is built around the notion
;;; : that the owning model is the only model which could install
;;; : the device. That needs to be corrected, but there isn't a
;;; : viable solution for "current-model" in the dispatch environment
;;; : yet since one can't just wrap a macro around a set of rpc calls...
;;; : The init and remove device functions would probably need to
;;; : have the model passed in I think, as well as other things.
;;; 2017.01.12 Dan
;;; : * Added a remote version of clear-exp-window.
;;; : * Removed the clear on reset parameter -- they will always be
;;; : closed upon reset.
;;; 2017.01.18 Dan
;;; : * Removed the echo-act-r-output from commands. The assumption
;;; : now is that echoing is handled by the user.
;;; : * Use handle-evaluate-results.
;;; 2017.01.20 Dan
;;; : * Automatically install a keyboard device for motor if there
;;; : isn't one when a window is opened.
;;; 2017.01.26 Dan
;;; : * Fix the call that adds the correlation function since it was
;;; : cut and pasted from mean-deviation and still said that.
;;; 2017.01.30 Dan
;;; : * Change the 'local' versions of the commands so that they have
;;; : the same signature as the remote ones.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Reworked the local versions of the remote commands to not
;;; : go out through the dispatcher.
;;; : * Fixed some bugs with the last update.
;;; 2017.02.09 Dan
;;; : * Add remote versions of create and add for lines.
;;; : * Convert strings for colors to symbols in text and line functions.
;;; 2017.02.24 Dan
;;; : * Test the parameters given to open-exp-window because this
;;; : (open-exp-window "" :visible t) construct from before causes
;;; : problems now.
;;; 2017.03.02 Dan
;;; : * Moved the installation of a keyboard and mouse from the
;;; : opening of the window to the installing.
;;; : * Updated and added the button create and add commands.
;;; 2017.03.03 Dan
;;; : * Creating a button checks the action function for a valid
;;; : value at creation time now.
;;; : * When an experiment window is installed it also installs
;;; : a mouse for itself (removing a previously installed mouse),
;;; : and it now provides a signal-interface so that the mouse
;;; : can send move and click notices directly instead of having
;;; : to catch them with a monitor.
;;; 2017.03.08 Dan
;;; : * Removing an exp-window needs to remove all the visual
;;; : features it has added because can't rely on vision doing so
;;; : since it doesn't know who 'owns' them and can't just kill
;;; : all of them when the device is removed.
;;; 2017.03.09 Dan
;;; : * Updated the modify-line-for-exp-window command and made it
;;; : available externally.
;;; 2017.03.10 Dan
;;; : * Convert a string color in modify-line-for-exp-window to a
;;; : symbol if possible, and check if the line is actually in the
;;; : window before asking vision to modify the visicon features.
;;; 2017.03.16 Dan
;;; : * Comment out most of modify-text-for-exp-window because it
;;; : doesn't work yet and want to avoid the compiler warnings.
;;; 2017.05.31 Dan [5.0]
;;; : * As a first step to dealing with the model issue this is now
;;; : being implemented as a component instead of a module -- that
;;; : removes the need for a current model and should provide a
;;; : path for multiple models to use the same device.
;;; 2017.06.08 Dan
;;; : * Fixed modify-line-for-exp-window so that it works right with
;;; : respect to updating all the models that have the window installed.
;;; 2017.06.13 Dan
;;; : * The agi module itself needs a lock to protect access to its
;;; : internal components.
;;; 2017.06.14 Dan
;;; : * The remove-exp-window function needs to return true for the
;;; : remove-device command to work.
;;; : * Reorganized some locking in open and close because open can
;;; : call close and close may call remove-exp-window which all
;;; : need the agi lock, but remove-exp-window will be in a
;;; : different thread since it is called through the dispatcher.
;;; 2017.06.16 Dan
;;; : * Make the agi-lock directly instead of using an act-r-lock.
;;; 2017.06.23 Dan
;;; : * Added a name for the lock.
;;; 2017.06.30 Dan
;;; : * Got rid of the data structure since it's not used anywhere.
;;; 2017.07.13 Dan
;;; : * Add some error detection to the file opening in mean-deviation
;;; : and correlation and pass output to act-r-output if there
;;; : isn't a current model.
;;; 2017.08.16 Dan
;;; : * Fixed an issue with modify-line-for-exp-window because
;;; : determine-exp-window doesn't really do what it's named if
;;; : a sub-view is passed to it.
;;; 2017.08.17 Dan
;;; : * Fixed an issue with close-exp-window because it held the
;;; : agi lock while remove-device was called but that can dispatch
;;; : things that might need that lock through the remove function
;;; : of the device.
;;; 2017.09.13 Dan
;;; : * Fixed close-all-exp-windows to use the the window list
;;; : instead of the global table since that contains more than
;;; : windows.
;;; 2017.11.01 Dan
;;; : * Removed the extra new-line in the correlation and mean-deviation
;;; : output when using command-output or act-r-output.
;;; 2017.11.16 Dan
;;; : * Fixed a bug with valid-button-action because it looped forever
;;; : with nil.
;;; 2018.02.08 Dan
;;; : * Fixed a bug with remove-items-from-exp-window and clear-exp-
;;; : window because they didn't remove the underlying visual features
;;; : from the dialog item. They just removed the chunk name for
;;; : the feature.
;;; : * Remove-exp-window doesn't need to inform the vision module
;;; : about features being removed if the window isn't actually
;;; : installed (which can happen because of a reset while it was
;;; : installed -- the reset still needs to clear the features from
;;; : the underlying window structures but not the visicon).
;;; 2018.03.05 Dan
;;; : * Install a microphone for the speech module if there isn't
;;; : already one installed.
;;; 2018.03.13 Dan
;;; : * All coordinates must be global now because multiple windows
;;; : are allowed and a single mouse is used for all of them which
;;; : has global coordinates.
;;; : * Because a model can have multiple windows the installed-windows
;;; : needs to be a table instead of just an alist.
;;; 2018.03.14 Dan
;;; : * Opening the window installs the monitors for the signals that
;;; : matter (click-mouse, move-cursor, delete-cursor, and update-
;;; : attended-loc) and closing the window removes the monitors.
;;; 2018.03.27 Dan
;;; : * Moved find-top-level-window to the uwi file.
;;; 2018.04.27 Dan
;;; : * Fixed modify-text-for-exp-window and added a remote version.
;;; : * Same for modify-button-for-exp-window.
;;; 2018.05.01 Dan
;;; : * Fixed a problem with the modify actions when the item hadn't
;;; : been added to a window or didn't have visicon features yet.
;;; 2018.05.02 Dan
;;; : * Fixed a bug with close-all-exp-windows since it held the
;;; : agi lock but that's needed to remove an installed window
;;; : when it's closed.
;;; 2018.05.03 Dan
;;; : * Updated the modify actions to be consistent with the new
;;; : modify-visicon-features definition.
;;; 2018.06.13 Dan
;;; : * Added a declaim to avoid a warning for set-cursor-position-fct.
;;; 2018.06.21 Dan
;;; : * Return to keyword params! Use options lists externally.
;;; : * Don't allow a symbol for window title.
;;; 2018.06.26 Dan
;;; : * Fixed a bug with adding the command for open-exp-window.
;;; 2018.09.13 Dan
;;; : * Now the device has a notification function which can be used
;;; : to send messages to the real window handlers. A notification
;;; : should be provided a list where the first item is a string
;;; : and the remaining items are additional parameters. It will
;;; : then send the handler a command with that string, the window
;;; : title, current model, and then the additional parameters.
;;; 2018.11.15 Dan
;;; : * Modify-button-for-exp-window command wasn't calling the
;;; : external version.
;;; : * Bug in check for whether a button modification was valid.
;;; 2018.11.19 Dan
;;; : * Really fixed the button modification tests now.
;;; 2019.06.19 Dan
;;; : * Adjust close-exp-window because LispWorks implicitly locks
;;; : hash-tables between threads which means a maphash can't
;;; : call something in another thread that accesses the table.
;;; 2019.10.01 Dan
;;; : * Fixed the typo in the monitor-move-cursor accessor.
;;; 2020.06.02 Dan
;;; : * Removed an unnecessary with-recursive-lock-held from
;;; : add-items-to-exp-window because it already had the lock.
;;; 2021.10.20 Dan [6.0]
;;; : * Have it check before installing devices to make sure that
;;; : the corresponding module is avaliable.
;;; 2022.02.18 Dan
;;; : * Fixed a bug with modify-button-for-exp-window in how it
;;; : handles the modifications for passing to the underlying
;;; : button object since the action could be a list of things.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function (t &optional t) t) set-cursor-position-fct))
;;; Class for the AGI component instance.
;;; Have central tables to hold windows and subcomponents, make the windows
;;; available as a device, and track which models have installed which
;;; window so when a window or item is changed or closed all the models can
;;; have their visicons updated.
;;; Assumes that it's an rpm virtual window (or the visible-virtual subclass).
;;; That assumption can also be satisfied by the subviews and window-lock methods
;;; being defined for the window object and all the items returned from subviews
;;; have x-pos, y-pos, and visual-features accessor/methods to return and store
;;; values and device-move-cursor-to and vv-handle-click method for responding
;;; to mouse actions.
;;; Also assumes that the window-lock protects all of the subviews too.
(defclass agi-component ()
;; the global table maps a window or item identifier to the underlying object
((global-agi-table :accessor global-agi-table :initform (make-hash-table :test 'equalp))
;; table of created objects for a window -- list of actual objects
(window-objects-table :accessor window-objects-table :initform (make-hash-table :test 'equalp))
;; table of objects added to a window -- list of actual objects
(window-added-objects-table :accessor window-added-objects-table :initform (make-hash-table :test 'equalp))
;; the list of window titles
(agi-window-list :accessor agi-window-list :initform nil)
;; table of installed windows by model
(installed-windows :accessor installed-windows :initform (make-hash-table))
;; protect the tables
(agi-lock :accessor agi-lock :initform (bt:make-recursive-lock "agi"))))
;;; Since there's only one component, for now keeping things simple and
;;; creating a clozure around a single agi-component object to use.
(declaim (ftype (function () t) agi-component))
(let ((agi (make-instance 'agi-component)))
(defun agi-component () agi))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Functions for defining the component itself.
;;;
;;; Assmumes that the interface functions are called from something that's
;;; thread safe.
;;; Here's all I need for the component -- creation, reset, and delete
;;; functions to initialize and close things as needed.
;;; Create just needs to return a new instance of the class.
(defun create-agi-module ()
(agi-component))
;;; Delete just closes all of the model's windows, but doesn't need to clear the
;;; module list since the module is going away.
(defun delete-agi-module (instance)
(dolist (x (bt:with-recursive-lock-held ((agi-lock instance)) (agi-window-list instance)))
(close-exp-window x)))
;;; clear-all may need to close the windows (like delete) and also needs to
;;; clean up the model's list by setting it to nil to make sure
;;; things are synchronized since the delete method doesn't need
;;; to do so.
(defun clear-all-agi-module (instance)
(reset-agi-module instance)
(delete-agi-module instance)
(bt:with-recursive-lock-held ((agi-lock instance))
(setf (agi-window-list instance) nil)))
(defun delete-model-agi-module (instance model-name)
(awhen (gethash model-name (bt:with-recursive-lock-held ((agi-lock instance)) (installed-windows instance)))
(with-model-eval model-name
(dolist (w it)
(remove-device (list "vision" "exp-window" w))))))
(defun reset-agi-module (instance)
(bt:with-recursive-lock-held ((agi-lock instance))
(clrhash (installed-windows instance))))
(define-component agi :version "6.0" :documentation "Manager for the AGI windows"
:creation create-agi-module
:clear-all clear-all-agi-module
:delete delete-agi-module
:delete-model delete-model-agi-module
:before-reset reset-agi-module
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Create a device called "exp-window".
;;; Interface functions are all dispatched and single instance.
;;; The window identifier is the value passed in from the device installation
;;; and removal. It's the third value of the list returned from open-exp-window
;;; and is just the window title string. This function maps that to the real
;;; window object from the table.
(defun window-identifier-to-window (agi id)
(bt:with-recursive-lock-held ((agi-lock agi))
(gethash id (global-agi-table agi))))
(defun init-exp-window (device-list)
(let* ((agi (agi-component))
(interface (first device-list))
(win-identifier (third device-list))
(w (window-identifier-to-window agi win-identifier)))
(if (not (string-equal interface "vision"))
(print-warning "Experiment windows can only be installed for the vision interface, but ~a given." interface)
(cond (w ;; must be a new install since install-device blocks dups.
;; Record the model as installed for the window
(bt:with-recursive-lock-held ((agi-lock agi))
(push win-identifier (gethash (current-model) (installed-windows agi))))
(when (get-module-fct :motor t)
(unless (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(install-device (list "motor" "keyboard"))))
(when (get-module-fct :speech t)
(unless (find "microphone" (current-devices "speech") :key 'second :test 'string-equal)
(install-device (list "speech" "microphone"))))
(when (get-parameter-value :needs-mouse)
(when (get-module-fct :motor t)
(unless (find-if (lambda (x) (string-equal (third x) "mouse") (string-equal (second x) "cursor")) (current-devices "motor"))
(install-device (list "motor" "cursor" "mouse"))
(set-cursor-position-fct (list (x-pos w) (y-pos w)) "mouse")))
(when (get-module-fct :vision t)
(when (get-parameter-value :process-cursor)
(unless (find-if (lambda (x) (string-equal (third x) "mouse") (string-equal (second x) "cursor")) (current-devices "vision"))
(install-device (list "vision" "cursor" "mouse"))))))
;; Create the features for all subviews, add them to the visicon, and record them in the
;; visual-features for the item. Assume that items aren't already in the visicon since
;; the window is just being installed now.
;; Probably want to change this since there's only one for vision in general...
(set-visual-center-point (+ (x-pos w) (round (width w) 2)) (+ (y-pos w) (round (height w) 2)))
(dolist (x (if (stable-names (current-device-interface))
(sort (subviews w) #'subview-sort)
(subviews w)))
(let ((feat-list nil))
(dolist (y (build-vis-locs-for x))
(push (cons (car (add-visicon-features y)) y) feat-list))
(push (cons (current-model) feat-list) (visual-features x))))
t)
(t
(print-warning "Window ~s could not be found when being installed." win-identifier))))))
(defun remove-exp-window (device-list)
(let* ((agi (agi-component))
(win-identifier (third device-list))
(w (window-identifier-to-window agi win-identifier)))
;; assume it's good since remove requires it was installed
(when w
(let ((installed (bt:with-recursive-lock-held ((agi-lock agi))
(find win-identifier (gethash (current-model) (installed-windows agi)) :test 'string-equal))))
;;; need to explicitly remove the visiual features
;;; since vision doesn't know who 'owns' features and
;;; can't just delete everything when a device is
;;; uninstalled.
;;;
;;; However, that's only necessary if the window is actually
;;; installed. Upon a reset we want to clear out the old features,
;;; but since the window isn't installed at that point we don't
;;; need to inform the vision module.
(bt:with-recursive-lock-held ((window-lock w))
(dolist (x (subviews w))
(when installed
(dolist (y (cdr (assoc (current-model) (visual-features x))))
(delete-visicon-features (car y))))
(setf (visual-features x) (remove (current-model) (visual-features x) :key 'car))))
(bt:with-recursive-lock-held ((agi-lock agi))
(setf (gethash (current-model) (installed-windows agi))
(remove win-identifier (gethash (current-model) (installed-windows agi)) :test 'string-equal)))))
t))
(defun notify-exp-window (device features)
(aif (determine-exp-window (agi-component) device)
(cond ((and (listp features) (stringp (first features)))
(send-update-to-handlers it (append (list (first features)) (list (window-title it) (current-model)) (rest features))))
((not (listp features))
(print-warning "Exp window notification for ~s must be a list but given ~s" device features))
(t
(print-warning "Exp window notification for ~s must be have a string as the first feature but given ~s" device features)))
(print-warning "Could not notify a window with device list ~s" device)))
(add-act-r-command "init-exp-window" 'init-exp-window "Internal command for experiment windows being installed. Do not call.")
(add-act-r-command "remove-exp-window" 'remove-exp-window "Internal command for experiment windows being uninstalled. Do not call.")
(add-act-r-command "notify-exp-window" 'notify-exp-window "Internal command for notifying an experiment window device. Do not call.")
(define-device "exp-window" "init-exp-window" "remove-exp-window" "notify-exp-window")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code to provide the AGI windowing functions.
;;;
;;; OPEN-EXP-WINDOW [Function]
;;; Description : This function opens a window with the properties specified and
;;; : returns a list of items which can be passed to install-device.
;;; :
;;; : If there's already a window with that title open close it first,
;;; : then create a new window with the provided details.
;;; : In either case the window is brough to the front (assuming that
;;; : the UWI select-rpm-window command works properly for the window
;;; : type).
;;; :
;;; : The return value is a device list suitable for install-device and can
;;; : also be use to reference the window.
(defun open-exp-window (title &key (visible t) (width 300) (height 300) (x 300) (y 300))
; don't allow any more
; (when (symbolp title)
; (setf title (symbol-name title)))
(if (stringp title)
(if (and (numberp width) (numberp height) (numberp x) (numberp y))
(let ((instance (agi-component))
(key title))
(let ((exists (bt:with-recursive-lock-held ((agi-lock instance))
(gethash key (global-agi-table instance)))))
(when exists
(close-exp-window key))
(bt:with-recursive-lock-held ((agi-lock instance))
(let ((win (make-rpm-window :visible visible
:title title
:width width
:height height
:x x
:y y)))
(pushnew title (agi-window-list instance) :test 'string-equal)
(setf (gethash key (global-agi-table instance)) win)
;; Add the monitors necessary for the window to
;; respond to mouse updates.
;; Attention updates only handled by visible and added in the
;; init for that class.
(bt:with-lock-held ((window-lock win))
(let ((name (get-new-command-name "agi-win-click-mouse-monitor")))
(add-act-r-command name (lambda (model pos finger)
(declare (ignore finger))
(exp-window-mouse-click-handler instance win key model pos))
"Experiment window command for monitoring click-mouse signals. Do not call directly." nil)
(setf (monitor-click-mouse win) name)
(monitor-act-r-command "click-mouse" name))
(let ((name (get-new-command-name "agi-win-move-cursor-monitor")))
(add-act-r-command name (lambda (model cursor loc)
(exp-window-move-cursor-handler instance win key model cursor loc))
"Experiment window command for monitoring move-cursor signals. Do not call directly." nil)
(setf (monitor-move-cursor win) name)
(monitor-act-r-command "move-cursor" name))
(let ((name (get-new-command-name "agi-win-delete-cursor-monitor")))
(add-act-r-command name (lambda (model cursor)
(exp-window-delete-cursor-handler instance win key model cursor))
"Experiment window command for monitoring delete-cursor signals. Do not call directly." nil)
(setf (monitor-delete-cursor win) name)
(monitor-act-r-command "delete-cursor" name))
)
(select-rpm-window win)
(list "vision" "exp-window" key)))))
(print-warning "Cannot create an experiment window with value ~s for the ~s parameter."
(cond ((not (numberp width)) width)
((not (numberp height)) height)
((not (numberp x)) x)
((not (numberp y)) y))
(cond ((not (numberp width)) 'width)
((not (numberp height)) 'height)
((not (numberp x)) 'x)
((not (numberp y)) 'y))))
(print-warning "Experiment window title must be a string, but ~s was specified." title)))
(defun exp-window-mouse-click-handler (instance win key model pos)
(if model
;; check if this window is currently installed
;; and only handle the click if it is
(when (find key (bt:with-recursive-lock-held ((agi-lock instance))
(gethash model (installed-windows instance)))
:test 'string-equal)
(vv-handle-click win (coerce pos 'vector)))
;; no model means a person which just has to be passed on
(vv-handle-click win (coerce pos 'vector))))
(defun exp-window-move-cursor-handler (instance win key model cursor loc)
(when (and (string-equal cursor "mouse")
(find key (bt:with-recursive-lock-held ((agi-lock instance))
(gethash model (installed-windows instance)))
:test 'string-equal))
;; a mouse and this model still has this window installed
(device-move-cursor-to win (coerce loc 'vector))))
(defun exp-window-delete-cursor-handler (instance win key model cursor)
(when (and (string-equal cursor "mouse")
(find key (bt:with-recursive-lock-held ((agi-lock instance))
(gethash model (installed-windows instance)))
:test 'string-equal))
;; a mouse and this model still has this window installed
(device-move-cursor-to win (vector))))
(defun external-open-exp-window (title &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'open-exp-window '(:visible :x :y :height :width))
(when valid
(apply 'open-exp-window title ol))))
(add-act-r-command "open-exp-window" 'external-open-exp-window "Create a window for a task. Params: title {< visible, width, height, x, y >}")
;;; Internal function for mapping a user provided window reference: device-list, title, or nil
;;; to some real window object if possible.
;;; Could also be a particular item --
(defun determine-exp-window (instance window)
;; if it's the device identifier list
(aif (and (listp window) (= (length window) 3)
(string-equal (first window) "vision")
(string-equal (second window) "exp-window")
(window-identifier-to-window instance (third window)))
(values it (third window))
(aif (window-identifier-to-window instance window)
(values it window)
(cond ((and window (stringp window) instance)
(print-warning "~s is not the title of an open window." window))
(window
(print-warning "~s is not a reference to an open window." window))
(t ;; window is nil
(if instance
(bt:with-recursive-lock-held ((agi-lock instance))
(if (= (length (agi-window-list instance)) 1)
(values (window-identifier-to-window instance (first (agi-window-list instance)))
(first (agi-window-list instance)))
(print-warning "There is ~:[no~;more than one~] window to use in the AGI so a nil reference will not work." (agi-window-list instance))))
(print-warning "There is no AGI component available to interact with experiment windows.")))))))
;;; CLOSE-EXP-WINDOW [Function]
;;; Description : Closes an experiment window. The window can be specified
;;; : by title or the install list.
;;; : If no valid window can be found it will print a warning and return nil.
(defun close-exp-window (&optional (window nil))
"Close the experiment window"
; don't allow symbols
; (when (and window (symbolp window))
; (setf window (symbol-name window)))
(let ((instance (agi-component)))
(multiple-value-bind (wind key) (determine-exp-window instance window)
(if wind
;; for every model in which it is installed it must be removed
(let (to-remove)
(maphash (lambda (model windows)
(when (find key windows :test 'string-equal)
(push (cons model windows) to-remove)))
(bt:with-recursive-lock-held ((agi-lock instance)) (installed-windows instance)))
(mapcar (lambda (x)
(let ((model (car x))
(windows (cdr x)))
(with-model-eval model
(remove-device (list "vision" "exp-window" key)))
(bt:with-recursive-lock-held ((agi-lock instance))
(setf (gethash model (installed-windows instance)) (remove key windows :test 'string-equal)))))
to-remove)
;; Close the window
(close-rpm-window wind)
;; remove all the monitors it created
(bt:with-lock-held ((window-lock wind))
(when (monitor-attended-loc wind)
(remove-act-r-command-monitor "update-attended-loc" (monitor-attended-loc wind))
(remove-act-r-command (monitor-attended-loc wind)))
(when (monitor-click-mouse wind)
(remove-act-r-command-monitor "click-mouse" (monitor-click-mouse wind))
(remove-act-r-command (monitor-click-mouse wind)))
(when (monitor-move-cursor wind)
(remove-act-r-command-monitor "move-cursor" (monitor-move-cursor wind))
(remove-act-r-command (monitor-move-cursor wind)))
(when (monitor-delete-cursor wind)
(remove-act-r-command-monitor "delete-cursor" (monitor-delete-cursor wind))
(remove-act-r-command (monitor-delete-cursor wind))))
;; remove it from the global table
(bt:with-recursive-lock-held ((agi-lock instance))
(remhash key (global-agi-table instance))
;; remove it from list of windows
(setf (agi-window-list instance) (remove key (agi-window-list instance) :test 'string-equal))
;; Remove all of its created items from the global table
(dolist (x (gethash key (window-objects-table instance)))
(remhash (list key (string (id x))) (global-agi-table instance)))
;; clear the created and added objects entries
(remhash key (window-objects-table instance))
(remhash key (window-added-objects-table instance))
t))
(print-warning "Could not close window ~s" window)))))
(add-act-r-command "close-exp-window" 'close-exp-window "Close the indicated experiment window or if none provided the only open one. Params: {window}")
(defun close-all-exp-windows ()
(let ((agi (agi-component)))
(mapcar (lambda (win)
(close-exp-window win))
(bt:with-recursive-lock-held ((agi-lock agi)) (agi-window-list agi)))))
(add-act-r-command "close-all-exp-windows" 'close-all-exp-windows "Close all the currently open experiment windows. No params.")
;;; SELECT-EXP-WINDOW [Function]
;;; Description : Brings a window to the front. The window can be specified
;;; : by title in current model or the install list.
;;; : If no window is provided then if there is only one window or only
;;; : one window in the current model that window will be brought to the
;;; : front, otherwise it will print a warning.
;;; : Returns t if a window was attempted to be brought to the front
;;; : (success depends on select-rpm-window working) and nil otherwise.
(defun select-exp-window (&optional (window nil))
"select the experiment window"
; don't allow anymore
;(when (and window (symbolp window))
; (setf window (symbol-name window)))
(aif (determine-exp-window (agi-component) window)
(progn
(select-rpm-window it)
t)
(print-warning "Select-exp-window failed.")))
(add-act-r-command "select-exp-window" 'select-exp-window "Bring an open experiment window to the front. Params: {window}.")
;;; ADD-ITEMS-TO-EXP-WINDOW [Function]
;;; Description : Returns t if the items were attempted to be added
;;; : (success depends on whether or not they were accepted by add-visual-
;;; : items-to-rpm-window), but if there is no window provided and no
;;; : current "default" window then a warning is printed and nil is
;;; : returned.
(defun add-items-to-exp-window (win &rest items)
"Add the specified items to the experiment window"
; don't allow any more
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(bt:with-recursive-lock-held ((agi-lock agi))
(let ((objects (mapcar (lambda (x) (gethash x (global-agi-table agi))) items))
(created (gethash key (window-objects-table agi)))
(added (gethash key (window-added-objects-table agi))))
(if (every 'identity objects)
(if (every (lambda (x) (and (find x created) (not (find x added)))) objects)
(progn
;; have the UWI do what it needs to do first
(apply 'add-visual-items-to-rpm-window window objects)
;; for every model that has this window installed
(maphash (lambda (model windows)
(when (find key windows :test 'string-equal)
(with-model-eval model
(let (feat-lis)
;; create the features for each item,
;; pass them off to vision module, and
;; record those features
(bt:with-recursive-lock-held ((window-lock window))
(dolist (item objects)
(setf feat-lis (assoc model (visual-features item)))
(unless feat-lis
(setf feat-lis (cons model nil))
(push-last feat-lis (visual-features item)))
(dolist (y (build-vis-locs-for item))
(push (cons (car (add-visicon-features y)) y) (cdr feat-lis)))))))))
(installed-windows agi))
;; put the items into the added table for the window
(setf (gethash key (window-added-objects-table agi))
(append added objects))
t)
(print-warning "One or more existing but invalid items in call to add-items-to-exp-window. No items added."))
(print-warning "One or more invalid items in call to add-items-to-exp-window. No items added."))))
(print-warning "No window available for add-items-to-exp-window.")))))
(add-act-r-command "add-items-to-exp-window" 'add-items-to-exp-window "Add the given items to the window provided. Params: window {item}*.")
;;; REMOVE-ITEMS-FROM-EXP-WINDOW [Function]
;;; Description : Removes the requested items from the window provided or the "default" window if
;;; : null. Returns t if the items were attempted to be removed
;;; : (success depends on whether or not they were accepted by remove-visual-
;;; : items-from-rpm-window), but if there is no window provided and no
;;; : current "default" window then a warning is printed and nil is
;;; : returned.
(defun remove-items-from-exp-window (win &rest items)
"Remove the specified items from the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(bt:with-recursive-lock-held ((agi-lock agi))
(let ((objects (mapcar (lambda (x) (gethash x (global-agi-table agi))) items))
(created (gethash key (window-objects-table agi)))
(added (gethash key (window-added-objects-table agi))))
(if (every 'identity objects)
(if (every (lambda (x) (and (find x created) (find x added))) objects)
(progn
;; for every model that has this window installed
(bt:with-recursive-lock-held ((window-lock window))
(bt:with-recursive-lock-held ((agi-lock agi))
(maphash (lambda (model windows)
(when (find key windows :test 'string-equal)
(with-model-eval model
(dolist (item objects)
(dolist (feat (cdr (assoc model (visual-features item))))
(delete-visicon-features (car feat)))
(setf (visual-features item) (remove model (visual-features item) :key 'car :count 1))))))
(installed-windows agi))))
;; remove the items from the added table
(setf (gethash key (window-added-objects-table agi))
(set-difference added objects))
;; have the UWI do what it needs to
(apply 'remove-visual-items-from-rpm-window window objects)
t)
(print-warning "One or more existing but invalid items in call to remove-items-from-exp-window. No items removed."))
(print-warning "One or more invalid items in call to remove-items-from-exp-window. No items removed."))
))
(print-warning "No window available for remove-items-from-exp-window.")))))
(add-act-r-command "remove-items-from-exp-window" 'remove-items-from-exp-window "Remove the given items from the window provided. Params: window {item}*.")
(defun clear-exp-window (&optional win)
"Erases everything in the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(bt:with-recursive-lock-held ((agi-lock agi))
(let ((added (gethash key (window-added-objects-table agi))))
(bt:with-recursive-lock-held ((window-lock window))
(bt:with-recursive-lock-held ((agi-lock agi))
(maphash (lambda (model windows)
(when (find key windows :test 'string-equal)
(with-model-eval model
(dolist (item added)
(dolist (feat (cdr (assoc model (visual-features item))))
(delete-visicon-features (car feat)))
(setf (visual-features item) (remove model (visual-features item) :key 'car :count 1))))))
(installed-windows agi))))
;; remove the added list
(remhash key (window-added-objects-table agi))
;; have the UWI do what it needs to
(apply 'remove-visual-items-from-rpm-window window added)
t))
(print-warning "No window available for clear-exp-window.")))))
(add-act-r-command "clear-exp-window" 'clear-exp-window "Remove all items from the window provided. Params: {window}.")
(defun create-text-for-exp-window (win text &key (x 0) (y 0) (color 'black) (height 20) (width 75) (font-size 12))
"Creates a text item for the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'black)))
(if (stringp text)
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(let* ((item (make-static-text-for-rpm-window window
:text text
:x x
:y y
:width width
:height height
:color color
:font-size font-size))
(item-key (list key (string (id item)))))
(if (and agi item)
(bt:with-recursive-lock-held ((agi-lock agi))
(setf (gethash item-key (global-agi-table agi)) item)
(push item (gethash key (window-objects-table agi)))
item-key)
(print-warning "Problem creating text item. No item created.")))
(print-warning "No window available for creating a text item."))))
(print-warning "Text must be a string in create-text-for-exp-window. Cannot create with ~s." text)))
(defun external-create-text-for-exp-window (window text &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'create-text-for-exp-window '(:x :y :height :width :color :font-size))
(when valid
(apply 'create-text-for-exp-window window text ol))))
(add-act-r-command "create-text-for-exp-window" 'external-create-text-for-exp-window "Create a text item for the provided experiment window with the features specified. Params: window text {<x, y, color, height, width, font-size>}.")
;;; ADD-TEXT-TO-EXP-WINDOW [Function]
;;; Description : Build a text item based on the parameters supplied and
;;; : add it to the specified window (or current default if
;;; : none povided).
(defun add-text-to-exp-window (win text &key (x 0) (y 0) (color 'black) (height 20) (width 75) (font-size 12))
"Create and display a text item in the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'black)))
(let ((item-key (create-text-for-exp-window win text :x x :y y :color color :height height :width width :font-size font-size)))
(if item-key
(if (add-items-to-exp-window win item-key)
item-key
nil)
nil)))
(defun external-add-text-to-exp-window (window text &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'add-text-to-exp-window '(:x :y :height :width :color :font-size))
(when valid
(apply 'add-text-to-exp-window window text ol))))
(add-act-r-command "add-text-to-exp-window" 'external-add-text-to-exp-window "Create a text item for the provided experiment window with the features specified and place it in the window. Params: window text {< x, y, color, height, width, font-size >}.")
(defun modify-text-for-exp-window (item &key text x y color height width font-size)
"Modify a text item for the experiment window"
(let ((agi (agi-component)))
(bt:with-recursive-lock-held ((agi-lock agi))
(aif (gethash item (global-agi-table agi))
(let* ((top-win (find-top-level-window (determine-exp-window agi (first item))))
(window-title (window-title top-win)) ;; probably always same as in the item, but maybe there'll be windows in windows at some point.
mods)
(when x
(if (numberp x)
(push (list :x x) mods)
(print-warning "X parameter in modify-text-for-exp-window must be a number but given ~s." x)))
(when y
(if (numberp y)
(push (list :y y) mods)
(print-warning "y parameter in modify-text-for-exp-window must be a number but given ~s." y)))
(when text
(if (stringp text)
(push (list :text text) mods)
(print-warning "Text parameter in modify-text-for-exp-window must be a string but given ~s." text)))
(when height
(if (numberp height)
(push (list :height height) mods)
(print-warning "Height parameter in modify-text-for-exp-window must be a number but given ~s." height)))
(when width
(if (numberp width)
(push (list :width width) mods)
(print-warning "Width parameter in modify-text-for-exp-window must be a number but given ~s." width)))
(when font-size
(if (numberp font-size)
(push (list :font-size font-size) mods)
(print-warning "Font-size parameter in modify-text-for-exp-window must be a number but given ~s." font-size)))
(when color
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'black)))
(push (list :color color) mods))
(cond ((null mods)
;; why even call it?
item
)
((null (visual-features it)) ;; not in visicon so just make the changes
(apply 'modify-text-for-rpm-window (cons it (flatten mods)))
item)
((or (not (= (length (first (visual-features it))) 2)) ;; don't try to match multiple features
(and text (or (> (length (string-to-lines text)) 1)
(> (length (chop-string (get-module :vision) text)) 1))))
(print-warning "Cannot modify a text item which has or will have multiple features."))
(t
(apply 'modify-text-for-rpm-window (cons it (flatten mods)))
(bt:with-recursive-lock-held ((window-lock top-win))
;; for every model that has this item's window installed
(maphash (lambda (model windows)
(when (find window-title windows :test 'string-equal)
(with-model-eval model
(let* ((current-features (cadr (assoc model (visual-features it))))
(new-feats (build-vis-locs-for it))
(id (first current-features)))
;; just pass all the features again to vision
;; except the ones that can't be changed assuming that
;; the first one is the isa!
(modify-visicon-features (cons id (cddar new-feats)))
(setf (cdr current-features) new-feats)))))
(installed-windows agi)))
item)))
(print-warning "Could not modify text ~s because it does not refer to an existing interface item." item)))))
(defun external-modify-text-for-exp-window (item &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'modify-text-for-exp-window '(:text :x :y :height :width :color :font-size))
(when valid
(apply 'modify-text-for-exp-window item ol))))
(add-act-r-command "modify-text-for-exp-window" 'external-modify-text-for-exp-window "Modify a text item created for an experiment window with the new features provided. Params: text-item {< text, x, y, color, height, width, font-size >}.")
(defun create-button-for-exp-window (win &key (text "") (x 0) (y 0) (action nil) (height 18) (width 60) (color 'gray))
"Creates a button item for the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'gray)))
(if (stringp text)
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(let* ((item (make-button-for-rpm-window window
:x x
:y y
:text text
:action (if (valid-button-action action) action "default-button-action")
:height height
:width width :color color))
(item-key (list key (string (id item)))))
(if (and agi item)
(bt:with-recursive-lock-held ((agi-lock agi))
(setf (gethash item-key (global-agi-table agi)) item)
(push item (gethash key (window-objects-table agi)))
item-key)
(print-warning "Problem creating button item. No button created.")))
(print-warning "No window available for creating a button."))))
(print-warning "Text must be a string in create-button-for-exp-window. Cannot create with ~s." text)))
(defun external-create-button-for-exp-window (win &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'create-button-for-exp-window '(:text :x :y :height :width :color :action))
(when valid
(apply 'create-button-for-exp-window win ol))))
(add-act-r-command "create-button-for-exp-window" 'external-create-button-for-exp-window "Create a button item for the provided experiment window with the features specified. Params: window {< text, x, y, action, height, width, color >}.")
;;; ADD-BUTTON-TO-EXP-WINDOW [Function]
;;; Description : Build a button item based on the parameters supplied and
;;; : add it to the specified window (or current default if
;;; : none povided).
(defun add-button-to-exp-window (win &key (text "") (x 0) (y 0) (action nil) (height 18) (width 60) (color 'gray))
"Create and display a button item in the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'gray)))
(let ((item-key (create-button-for-exp-window win :text text :x x :y y :action action :height height :width width :color color)))
(if item-key
(if (add-items-to-exp-window win item-key)
item-key
nil)
nil)))
(defun external-add-button-to-exp-window (win &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'add-button-to-exp-window '(:text :x :y :height :width :color :action))
(when valid
(apply 'add-button-to-exp-window win ol))))
(add-act-r-command "add-button-to-exp-window" 'external-add-button-to-exp-window "Create a button item for the provided experiment window with the features specified and place it in the window. Params: window {< text, x, y, action, height, width, color >}.")
(defun valid-button-action (action)
(and action
(or (and (stringp action)
(check-act-r-command action))
(functionp action)
(and (symbolp action)
(fboundp action)
(not (macro-function action)))
(and (listp action)
(atom (first action))
(valid-button-action (first action))))))
(defun modify-button-for-exp-window (item &key text x y action height width color)
"Modify a button item for the experiment window"
(let ((agi (agi-component)))
(bt:with-recursive-lock-held ((agi-lock agi))
(aif (gethash item (global-agi-table agi))
(let* ((top-win (find-top-level-window (determine-exp-window agi (first item))))
(window-title (window-title top-win))
mods)
(when x
(if (numberp x)
(progn
(push x mods)
(push :x mods))
(print-warning "X parameter in modify-button-for-exp-window must be a number but given ~s." x)))
(when y
(if (numberp y)
(progn
(push y mods)
(push :y mods))
(print-warning "y parameter in modify-button-for-exp-window must be a number but given ~s." y)))
(when text
(if (stringp text)
(progn
(push text mods)
(push :text mods))
(print-warning "Text parameter in modify-button-for-exp-window must be a string but given ~s." text)))
(when height
(if (numberp height)
(progn
(push height mods)
(push :height mods))
(print-warning "Height parameter in modify-button-for-exp-window must be a number but given ~s." height)))
(when width
(if (numberp width)
(progn
(push width mods)
(push :width mods))
(print-warning "Width parameter in modify-button-for-exp-window must be a number but given ~s." width)))
(when action
(if (valid-button-action action)
(progn
(push action mods)
(push :action mods))
(print-warning "Action parameter in modify-button-for-exp-window must be a valid command but given ~s." action)))
(when color
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'black)))
(push color mods)
(push :color mods))
(push it mods)
(cond ((null mods)
;; why even call it?
item
)
((null (visual-features it)) ;; not in visicon so just make the changes
(apply 'modify-button-for-rpm-window mods)
item)
((> (length (first (visual-features it))) 3)
(print-warning "Cannot modify a button item which has multi-word text."))
((and (= (length (first (visual-features it))) 3) ; button and text items
text
(not (= (length (chop-string (get-module :vision) text)) 1))) ;one item on a line
(print-warning "Cannot modify a button item which requires adding or removing features."))
((and (= (length (first (visual-features it))) 2) ; just the button
text
(not (zerop (length (chop-string (get-module :vision) text))))) ; any text
(print-warning "Cannot modify a button item which requires adding or removing features."))
(t
(apply 'modify-button-for-rpm-window mods)
(bt:with-recursive-lock-held ((window-lock top-win))
;; for every model that has this item's window installed
(maphash (lambda (model windows)
(when (find window-title windows :test 'string-equal)
(with-model-eval model
(let* ((current-features (cdr (assoc model (visual-features it))))
(new-feats (reverse (build-vis-locs-for it))))
(dotimes (i (length current-features))
(let ((id (first (nth i current-features))))
;; just pass all the features again to vision
;; except the ones that can't be changed which
;; we assume are only the isa which are first 2.
(modify-visicon-features (cons id (cddr (nth i new-feats))))
(setf (cdr (nth i current-features)) (nth i new-feats))))))))
(installed-windows agi)))
item)))
(print-warning "Could not modify button ~s because it does not refer to an existing interface item." item)))))
(defun external-modify-button-for-exp-window (item &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'modify-button-for-exp-window '(:text :x :y :height :width :color :action))
(when valid
(apply 'modify-button-for-exp-window item ol))))
(add-act-r-command "modify-button-for-exp-window" 'external-modify-button-for-exp-window "Modify a button item created for an experiment window with the new features provided. Params: button {< text, x, y, action, height, width, color >}.")
;;; ADD-LINE-TO-EXP-WINDOW [Function]
;;; Description : Build a line item based on the parameters supplied and
;;; : add it to the specified window (or current default if
;;; : none povided).
(defun create-line-for-exp-window (win start-pt end-pt &optional (color 'black))
"Creates a line item for the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'black)))
(if (and (listp start-pt) (listp end-pt) (= 2 (length start-pt) (length end-pt)))
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(let* ((item (make-line-for-rpm-window window (mapcar 'round start-pt) (mapcar 'round end-pt) color))
(item-key (list key (string (id item)))))
(if (and agi item)
(bt:with-recursive-lock-held ((agi-lock agi))
(setf (gethash item-key (global-agi-table agi)) item)
(push item (gethash key (window-objects-table agi)))
item-key)
(print-warning "Problem creating line item. No item created.")))
(print-warning "No window available for adding a line."))))
(print-warning "Start and end points for a line must be 2 element lists. Cannot create a line given ~s and ~s." start-pt end-pt)))
(add-act-r-command "create-line-for-exp-window" 'create-line-for-exp-window "Create a line for the provided experiment window with the features specified. Params: window (x1 y1) (x2 y2) {color}.")
(defun add-line-to-exp-window (win start-pt end-pt &optional (color 'black))
"Create and display a line item in the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
(when (stringp color)
(setf color (aif (ignore-errors (read-from-string color)) it 'black)))
(let ((item-key (create-line-for-exp-window win start-pt end-pt color)))
(if item-key
(if (add-items-to-exp-window win item-key)
item-key
nil)
nil)))
(add-act-r-command "add-line-to-exp-window" 'add-line-to-exp-window "Create a line for the provided experiment window with the features specified and then place it in that window. Params: window (x1 y1) (x2 y2) {color}.")
(defun modify-line-for-exp-window (item start-pt end-pt &optional color)
"Modify a line item for the experiment window"
(let ((agi (agi-component)))
(bt:with-recursive-lock-held ((agi-lock agi))
(aif (gethash item (global-agi-table agi))
(let* ((top-win (find-top-level-window (determine-exp-window agi (first item))))
(window-title (window-title top-win)) ;; probably always same as in the item, but maybe there'll be windows in windows at some point.
(c (when color
(if (stringp color)
(ignore-errors (read-from-string color))
color)))
(start (if (and start-pt (listp start-pt) (= (length start-pt) 2) (every 'numberp start-pt))
(mapcar 'round start-pt)
(when start-pt
(print-warning "Invalid start-point ~s specified for modify-line-for-exp-window."))))
(end (if (and end-pt (listp end-pt) (= (length end-pt) 2) (every 'numberp end-pt))
(mapcar 'round end-pt)
(when end-pt
(print-warning "Invalid end-point ~s specified for modify-line-for-exp-window.")))))
(cond ((and (null c) (null start) (null end))
;; why even call it?
item
)
((null (visual-features it)) ;; not in visicon so just make the changes
(if c
(modify-line-for-rpm-window it start end :color c)
(modify-line-for-rpm-window it start end))
item)
(t
(if c
(modify-line-for-rpm-window it start end :color c)
(modify-line-for-rpm-window it start end))
(bt:with-recursive-lock-held ((window-lock top-win))
;; for every model that has this item's window installed
(maphash (lambda (model windows)
(when (find window-title windows :test 'string-equal)
(with-model-eval model
(let* ((current-features (cadr (assoc model (visual-features it))))
(new-feats (build-vis-locs-for it))
(id (first current-features)))
;; just pass all the features again to vision
;; except the ones that can't be changed
;; assuming there's only one feature for a line item
(modify-visicon-features (cons id (cddr (first new-feats))))
(setf (cdr current-features) new-feats)))))
(installed-windows agi)))
item)))
(print-warning "Could not modify line ~s because it does not refer to an existing interface item." item)))))
(add-act-r-command "modify-line-for-exp-window" 'modify-line-for-exp-window "Change the attributes of a line that was created for an experiment window. Params: line (x1 y1) (x2 y2) {color}.")
;;;; ---------------------------------------------------------------------- ;;;;
;;;; The miscelaneous functions used in the tutorial.
;;;; ---------------------------------------------------------------------- ;;;;
;;; GET-TIME
;;; Return time in milliseconds
;;; If the optional parameter is specified as true then model time is returned
;;; and if it is nil then get-internal-real-time is used.
;;; If time is not based on the model it's only meaningful as a relative
;;; time.
(defun get-time (&optional (model-time t))
(if model-time
(mp-time-ms)
(round (* 1000 (/ (get-internal-real-time) internal-time-units-per-second)))))
(add-act-r-command "get-time" 'get-time "Get current absolute model time or relative real time in milliseconds. Params: {model}." nil)
;;; These are the correlation and deviation functions from the scripting
;;; extensions file and the necessary support. I figured since they are
;;; still used they should be put here because the scripting extensions
;;; aren't part of ACT-R 5, but making people load the scripting file
;;; separately is a pain... I also changed mean-deviation so that it
;;; actually returned the deviation.
(defmacro /-safe (number &rest dividers)
`(/ ,number ,@(let ((max nil))
(dolist (divider dividers max)
(push-last `(if (zerop ,divider) 1 ,divider) max)))))
(defun numbers-list (structure)
(let ((list nil))
(cond ((arrayp structure)
(dotimes (i (array-total-size structure))
(let ((data (row-major-aref structure i)))
(when (numberp data) (push data list)))))
((listp structure)
(dolist (data structure)
(cond ((listp data)
(setf list (append (nreverse (numbers-list data)) list)))
((numberp data)
(push data list)))))
((numberp structure)
(push structure list))
(t (format t "~&UNKNOWN DATA FORMAT ~S NOT COMPATIBLE WITH NUMBERS LIST.~%"
structure)))
(nreverse list)))
(defun square-data (x)
(* x x))
(defun sum-list (list)
(let ((sum 0.0))
(dolist (data list sum)
(incf sum data))))
(defun square-list (list)
(let ((sum 0.0))
(dolist (data list sum)
(incf sum (square-data data)))))
(defun product-list (list1 list2)
(let ((sum 0.0))
(loop
(when (or (null list1) (null list2)) (return sum))
(incf sum (* (pop list1) (pop list2))))))
(defun mean-deviation (results data &optional (output t))
(let* ((results-list (numbers-list results))
(data-list (numbers-list data))
(n (min (length results-list) (length data-list)))
(opened nil))
(cond ((or (stringp output) (pathnamep output))
(setf output (handler-case (open output :direction :output :if-exists :append :if-does-not-exist :create)
(error (x) (print-warning "Error ~/print-error-message/ occurred while trying to open file ~s for output from mean-deviation. Printing as if t provided."
x output))))
(if (null output)
(setf output t)
(setf opened t)))
((not (or (streamp output) (null output) (eq output t)))
(print-warning "Output argument ~s to mean-deviation is not valid. It must be a string, pathname, stream, t or nil. Printing as if t provided." output)
(setf output t)))
(unless (= (length results-list) (length data-list))
(print-warning "~s and ~s do not have the same number of numbers." results data))
(let ((result (sqrt (/ (+ (square-list results-list) (square-list data-list)
(* -2.0 (product-list results-list data-list)))
n))))
(if (and (eq output t) (current-model))
(command-output "MEAN DEVIATION: ~6,3F" result)
(if (eq output t)
(act-r-output "MEAN DEVIATION: ~6,3F" result)
(format output "~&MEAN DEVIATION: ~6,3F~%" result)))
(when opened (close output))
result)))
(add-act-r-command "mean-deviation" 'mean-deviation "Compute the RMSD between two lists of numbers. Params: (results) (data) {output}." nil)
(defun correlation (results data &optional (output t))
(let* ((results-list (numbers-list results))
(data-list (numbers-list data))
(n (min (length results-list) (length data-list)))
(average-results (/-safe (sum-list results-list) n))
(average-data (/-safe (sum-list data-list) n))
(opened nil))
(cond ((or (stringp output) (pathnamep output))
(setf output (handler-case (open output :direction :output :if-exists :append :if-does-not-exist :create)
(error (x) (print-warning "Error ~/print-error-message/ occurred while trying to open file ~s for output from correlation. Printing as if t provided."
x output))))
(if (null output)
(setf output t)
(setf opened t)))
((not (or (streamp output) (null output) (eq output t)))
(print-warning "Output argument ~s to correlation is not valid. It must be a string, pathname, stream, t or nil. Printing as if t provided." output)
(setf output t)))
(unless (= (length results-list) (length data-list))
(print-warning "~s and ~s do not have the same number of numbers .~%"
results data))
(let ((result (/-safe (- (/-safe (product-list results-list data-list) n)
(* average-results average-data))
(* (sqrt (- (/-safe (square-list results-list) n)
(square-data average-results)))
(sqrt (- (/-safe (square-list data-list) n)
(square-data average-data)))))))
(if (and (eq output t) (current-model))
(command-output "CORRELATION: ~6,3F" result)
(if (eq output t)
(act-r-output "CORRELATION: ~6,3F" result)
(format output "~&CORRELATION: ~6,3F~%" result)))
(when opened (close output))
result)))
(add-act-r-command "correlation" 'correlation "Compute the correlation between two lists of numbers. Params: (results) (data) {output}." nil)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 84,967 | Common Lisp | .lisp | 1,355 | 50.066421 | 258 | 0.57271 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | db8db0803d897d47994eb7615202b7850d8412c558fbbfe1d9d0a65cd4a634c6 | 14,298 | [
-1
] |
14,299 | utility-and-reward-1.lisp | asmaloney_ACT-R/modules/utility-and-reward-1.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell & John Anderson
;;; Copyright : (c) 2006 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : utility-and-reward-1.lisp
;;; Version : 6.0
;;;
;;; Description : The procedural utility computation functions and a module
;;; : for handling the "reward" given to a production.
;;; :
;;;
;;; Bugs :
;;;
;;; To do : [ ] Consider a new command or switch which allows one to
;;; : not clear the history after propigating a reward.
;;;
;;; ----- History -----
;;; 2006.05.22 Dan
;;; : * Initial creation.
;;; 2006.08.24 Dan
;;; : * Added the "null" learning event marker (the way setting
;;; : both success and failure worked in the old system) - if
;;; : trigger-reward is passed nil it just clears the history.
;;; 2006.09.08 Dan
;;; : * Changed the :at parameter check from posnum to nonneg.
;;; 2006.10.06 Dan
;;; : * Changed some print-warning calls to model-warning so that
;;; : they turn off with the model-warning parameter.
;;; 2006.11.15 Dan
;;; : * Changed trigger-reward so that it tests its parameter
;;; : before generating the event instead of waiting for the
;;; : propigate-reward function to catch problems.
;;; : * Changed the name of the module from utility-2 to utility
;;; : in preparation for making it the default module.
;;; : * Changed the doc string for the module and updated the
;;; : version to 2.0.
;;; 2007.10.26 Dan [2.1]
;;; : * Added the Utility threshold parameter back into the system.
;;; 2008.02.26 Dan
;;; : * Fixed a bug in propigate-reward which allowed utility
;;; : learning to go on even when :esc was set to nil.
;;; 2008.07.22 Dan
;;; : * Changed compute-utility so that it has an optional parameter
;;; : which indicates whether or not to store the computed value.
;;; 2008.07.23 Dan
;;; : * Added the require of "CENTRAL-PARAMETERS" since it does use
;;; : it - don't rely on procedural or declarative to load it first.
;;; : * Added call to the new register-subsymbolic-parameters to
;;; : note which parameters should trigger the warning.
;;; 2008.08.01 Dan
;;; : * Procedural now owns :dat.
;;; 2009.08.12 Dan
;;; : * Added a utility-offset hook which is called after the normal
;;; : utility for a production is computed and set (without noise).
;;; : If it returns a number that's added into the utility value.
;;; 2011.02.16 Dan [2.2]
;;; : * Added a utility learning trace parameter which prints out
;;; : the utility changes when a reward occurs.
;;; : * Also changed linear-update-utility to take the utility module
;;; : as a parameter.
;;; 2011.04.26 Dan
;;; : * Updated to use millisecond timer for production times.
;;; 2011.04.28 Dan
;;; : * Suppress warnings about extending productions at initial load.
;;; 2011.05.16 Dan
;;; : * Changed the formatting of the utility trace slightly.
;;; 2011.06.02 Dan
;;; : * Added a reward-hook parameter to allow one to override the
;;; : effective reward provided to a production.
;;; 2011.08.03 Dan
;;; : * Added a reward-notify-hook which can hold multiple functions
;;; : and gets called during propagate-reward with the reward value.
;;; 2012.03.14 Dan
;;; : * Added the ability to set :reward to t using spp to be the
;;; : equivalent of calling trigger-reward with nil (can't set the
;;; : :reward parameter to nil since that's the default and seems
;;; : like a bad idea to change that).
;;; : * That change requires making a change to how production
;;; : compilation determines whether or not there is a :reward
;;; : setting for the new production. The old rule still holds --
;;; : if they're both numbers then it's the max, and if only one is
;;; : a number then the new one gets that number (now that means
;;; : the other can be either t or nil). The new change is that now
;;; : if neither is a number but at least one is t then the new
;;; : production will get a value of t.
;;; 2012.06.18 Dan
;;; : * Fixed a bug with the test for warning about parameter changes
;;; : so that it warns if there are any productions defined.
;;; 2014.09.30 Dan
;;; : * If reward and utility aren't numbers don't try to print them
;;; : with ~f in spp.
;;; 2015.06.04 Dan
;;; : * Store production action time internally in ms.
;;; 2015.06.05 Dan
;;; : * Use schedule-event-now for propagate-reward.
;;; : * Get-default-action-time and get-default-u functions now take
;;; : values from the utility module instead of indirectly through
;;; : sgp, and the module records dat in ms.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2015.09.01 Dan
;;; : * Add an optional parameter to trigger-reward to allow the
;;; : propagate-reward event to be marked as maintenance.
;;; 2015.09.10 Dan [3.0]
;;; : * Start of the process of adding a new reward assignment
;;; : mechanism which only rewards productions that have "completed"
;;; : all of their actions instead of just having been selected.
;;; 2015.09.11 Dan
;;; : * Added the new option for :ul as complete to initiate the
;;; : new mechanism.
;;; : * Propagate-reward tests the switch and updates appropriately.
;;; 2015.09.14 Dan
;;; : * When a production specifies a reward now that leads to a
;;; : trigger-reward being scheduled instead of happening directly
;;; : during the "fired" action because when the complete setting
;;; : is in effect the actions of the production need to happen
;;; : before determining whether or not to reward this production
;;; : itself.
;;; : * The learn-parameters function now updates the requests
;;; : stored in the history since the production has executed its
;;; : actions at that point.
;;; 2015.10.14 Dan [3.1]
;;; : * Added a new production parameter available via spp :fixed-utility.
;;; : It defaults to nil, but if set to t then utility learning is
;;; : disabled for that production and its :u value will remain at
;;; : whatever value is set with spp (it can be changed by spp even
;;; : while marked as fixed).
;;; 2016.03.09 Dan
;;; : * Allow a production to have its reward status turned off via
;;; : spp, but track if that changes during a run and warn about
;;; : it during compilation updating since reward for a compiled
;;; : production is only set on inital creation.
;;; 2017.03.13 Dan
;;; : * Added a remote spp command and just have spp-fct always
;;; : decode the parameters passed to it.
;;; 2017.03.14 Dan
;;; : * Have the remote spp command 'collect' the parameters with a
;;; : &rest before passing them to spp-fct.
;;; 2017.08.15 Dan
;;; : * Added a lock to protect all the parameters.
;;; : * Changed linear-update-utility to take alpha directly instead
;;; : of getting it from the module.
;;; 2017.11.14 Dan
;;; : * Changed the decoding of the parameters to spp from the main
;;; : function to only do it through the remote one -- can't use
;;; : strings from the Lisp calls.
;;; 2017.11.16 Dan [4.0]
;;; : * Changed how trigger-reward/propagate-reward are signaled with
;;; : a dummy to clear the history. Instead of nil now any value
;;; : that isn't a number or nil will result in clearing the history.
;;; : This makes the reward setting for a production be consistent
;;; : with the underlying functions and allows for one to speicfy
;;; : meaningful 'dummy' rewards for the trace or other purposes.
;;; : * Added a remote version of trigger-reward.
;;; 2017.11.20 Dan
;;; : * Make trigger-reward go out through the dispatcher so it can
;;; : be monitored.
;;; 2018.04.16 Dan
;;; : * Allow :reward-hook, :reward-notify-hook, :utility-hook, and
;;; : :utility-offsets to be set to remote commands.
;;; : * Mark the reward-notify-hook as depricated.
;;; 2018.06.22 Dan
;;; : * Encode the spp results on the way out through remote.
;;; 2018.07.26 Dan [5.0]
;;; : * Don't need to track requested actions anymore.
;;; 2020.01.09 Dan [5.1]
;;; : * To make things safer for external access can't use the
;;; : function object for things like parameter tests or interface
;;; : actions.
;;; : * Add the ability to remove hook functions from the lists.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled since it's not needed
;;; : and results in warnings in SBCL.
;;; 2021.07.09 Dan
;;; : * Fixed a bug with spp setting :at because it was returning
;;; : the time in ms instead of seconds.
;;; 2021.10.19 Dan [6.0]
;;; : * Set the :required flag on the module to procedural.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; General:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Description:
;;;
;;; See the new-utility.doc file for all the details, but the general idea is
;;; that instead of tracking P and C and effectively boolean successes/failures
;;; we collapse things into one value called utility and have the successes and
;;; failures represented numerically as a single reward value.
;;; [Note the variable noise value discussed in the doc is not implemented at this
;;; time.]
;;;
;;; Thus, a production only has a utility value, U, which is adjusted over time based
;;; on the rewards received. The equation for the learning of production i is now:
;;;
;;; Ui(n) = Ui(n-1) + A[Ri(n) - Ui(n-1)]
;;;
;;; A := the learning rate set by a parameter (defaults to .2).
;;; Ri(n) := the effective reward value of production i at time n. Like the old
;;; mechanim, the learning only occurs when directly triggered and all productions
;;; that have been selected since the last "learning event" are updated (unless the
;;; special complete mode is in effect). The effective reward is the reward value
;;; at time n minus the time since the selection of production i.
;;; Ui(0) := set by a parameter (defaults to 0).
;;;
;;; The new meechanism only needs the following general parameters:
;;;
;;; dat := default action time, same as before - the default time to fire a
;;; production.
;;; egs := the expected gain s value, same as before.
;;;
;;; utility-hook := a function that can bypass the utility computation for
;;; productions, same as before.
;;;
;;; ul := utility learning, t or nil to indicate whether or not to
;;; apply the equation above. There is no decaying version as there is with
;;; the old parameter pl at this time.
;;; alpha := the learning rate for the equation above. Note this differs from
;;; the alpha parameter in the old system because that only applied to
;;; the production compilation mechanism.
;;; iu := the default U(0) value for an initial (user defined) production.
;;; nu := the default U(0) value for a newly learned (production compilation) production.
;;; reward-hook := a function to bypass the R(n) calculation.
;;;
;;; In addition, this parameter from the old system is now available again
;;;
;;; ut := the utility threshold. Productions with a utility less than this
;;; value will not be chosen during conflict resolution.
;;;
;;; ult := The utility learing trace parameter. When a reward occurs
;;; display the utility changes which occur.
;;;
;;; For a production, only the following parameters are needed for spp:
;;;
;;; at := The action time of the production, how long between the production's
;;; selection and when it fires. Can be set directly, defaults to :dat.
;;; name := returns the name of the production. Cannot be set directly.
;;; u := the current U(n) value for the production. Can be set directly.
;;; utility := the last computed utility value of the production during
;;; conflict resolution. Cannot be set directly.
;;; reward := a reward value to apply when this production fires if set to a
;;; non-nil value (the default is nil). Can be set directly.
;;;
;;; Note: in the old system there was a parameter called value which
;;; was used to order productions if :esc was nil, but now the u value is used
;;; regardless of the setting of esc. However learning cannot take palce if esc
;;; is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; since this module uses :esc make sure that module is available
(require-compiled "CENTRAL-PARAMETERS")
;;; similarly, require productions even though it will most certainly
;;; have been loaded by something else
(require-compiled "PRODUCTIONS")
;;; The structure that is the utility module
(defstruct utility
egs esc dat ul ut
iu nu alpha
utility-hook
reward-hook
history
offsets
trace
reward-notify-hooks
(param-lock (bt:make-lock "utility-module")))
;;; Functions necessary to support the production parameters
(defun get-default-action-time (p)
(declare (ignore p))
(verify-current-mp
"No meta-process available when trying to set production action time"
(verify-current-model
"No current model when trying to set production action time"
(let ((u (get-module utility)))
(if u
(bt:with-lock-held ((utility-param-lock u)) (utility-dat u))
(print-warning "No utility module available when trying to set production action time"))))))
(defun get-default-u (p)
(declare (ignore p))
(verify-current-mp
"No meta-process available when trying to set production u value"
(verify-current-model
"No current model when trying to set production u value"
(let ((u (get-module utility)))
(if u
(bt:with-lock-held ((utility-param-lock u)) (utility-iu u))
(print-warning "No utility module available when trying to set production u value"))))))
;;; The parameters added to productions for utility purposes
(suppress-extension-warnings)
(extend-productions utility)
(extend-productions u :default-function get-default-u)
(extend-productions at :default-function get-default-action-time)
(extend-productions reward)
(extend-productions fixed-utility)
(extend-productions reward-changed)
(unsuppress-extension-warnings)
;;; Instead of a simple cons for the history actually store
;;; structures now for ease of reading
(defstruct utility-history name time)
;;; The functions that are required by the procedural system
(defun note-production-selection (production)
(let ((u (get-module utility)))
(when u
(bt:with-lock-held ((utility-param-lock u))
(when (utility-ul u)
(push-last
(make-utility-history
:name production
:time (mp-time-ms))
(utility-history u)))))))
(defun productions-action-time (production)
(production-at production))
(defun compute-utility (production &optional (save nil))
(let ((u (get-module utility)))
(when u
(let (utility-hook esc egs offsets)
(bt:with-lock-held ((utility-param-lock u))
(setf utility-hook (utility-utility-hook u)
esc (utility-esc u)
egs (utility-egs u)
offsets (utility-offsets u)))
(let* ((over-ride (awhen utility-hook
(dispatch-apply it production)))
(utility (if (numberp over-ride)
over-ride
(+ (if (and esc egs (not (zerop egs)))
(act-r-noise egs)
0)
(production-u production)
(if offsets
(reduce #'+ (mapcar (lambda (x)
(let ((val (dispatch-apply x production)))
(if (numberp val)
val
0)))
offsets))
0)))))
(if save
(setf (production-utility production) utility)
utility))))))
(defun minimum-utility ()
(let ((u (get-module utility)))
(when u
(bt:with-lock-held ((utility-param-lock u))
(utility-ut u)))))
(defun linear-update-utility (alpha production reward)
(let ((old (production-u production)))
(setf (production-u production) (+ old (* alpha (- reward old))))))
(defun trigger-reward (value &optional (maintenance nil))
(evaluate-act-r-command "trigger-reward" value maintenance))
(defun trigger-reward-internal (value &optional (maintenance nil))
(cond ((null (current-model))
(print-warning "No current model. Trigger-reward has no effect."))
((numberp value)
(schedule-event-now 'propagate-reward :module 'utility
:priority :max :params (list value)
:output 'medium :maintenance maintenance)
t)
(value ;; want to differentiate the param to propagate in some way for this?
(schedule-event-now 'propagate-reward :module 'utility
:priority :max :params (list value)
:output 'medium :maintenance maintenance)
t)
(t
(print-warning "Trigger-reward must be called with a non-null value -- nil does not indicate a null reward anymore."))))
(add-act-r-command "trigger-reward" 'trigger-reward-internal "Provide a reward signal for utility learning. Params: reward-value {maintenance?}")
(defun propagate-reward (value)
(let* ((u (get-module utility))
ul reward-notify-hooks ult esc alpha reward-hook history)
(bt:with-lock-held ((utility-param-lock u))
(setf ul (utility-ul u)
reward-notify-hooks (utility-reward-notify-hooks u)
ult (utility-trace u)
esc (utility-esc u)
alpha (utility-alpha u)
reward-hook (utility-reward-hook u)
history (utility-history u)))
(dolist (hook reward-notify-hooks)
(dispatch-apply hook value))
(if (numberp value)
(if (and esc ul)
(let ((keep nil))
(when ult
(model-output " Utility updates with Reward = ~f alpha = ~f" value alpha))
(dolist (item history)
(let ((name (utility-history-name item)))
(if (production-fixed-utility name)
(when ult
(model-output " Updating of production ~S skipped because it has a fixed utility" name))
(let ((delta-t (ms->seconds (- (mp-time-ms) (utility-history-time item)))))
(let* ((override (and reward-hook
(dispatch-apply reward-hook name value delta-t)))
(r (if (numberp override) override (- value delta-t))))
(when ult
(model-output " Updating utility of production ~S" name)
(model-output " U(n-1) = ~f R(n) = ~f [~:[~f - ~f seconds since selection~;from reward-hook function~]]"
(production-u (utility-history-name item)) r override value delta-t))
(linear-update-utility alpha name r)
(when ult
(model-output " U(n) = ~f" (production-u name))))))))
(bt:with-lock-held ((utility-param-lock u)) (setf (utility-history u) keep)))
(print-warning "Trigger-reward can only be used if utility learning is enabled."))
(if value
(progn
(when ult
(model-output " Non-numeric reward clears utility learning history."))
(bt:with-lock-held ((utility-param-lock u)) (setf (utility-history u) nil)))
(print-warning "Trigger-reward called with nil has no effect at all now.")))))
(defun learn-parameters (production)
(awhen (production-reward production)
(schedule-event-now 'trigger-reward :module 'procedural :params (list it) :priority :min :output 'high)))
(defun initialize-utility-for-compiled-production (new-p p1 p2)
(let* ((at1 (production-at p1))
(at2 (production-at p2))
(at (max at1 at2))
(r1 (production-reward p1))
(r2 (production-reward p2))
(reward (or (and (numberp r1)
(numberp r2)
(max r1 r2))
(and (numberp r1) r1)
(and (numberp r2) r2)
r1 r2)))
(setf (production-at new-p) at)
(setf (production-reward new-p) reward)
(setf (production-u new-p) (car (no-output (sgp :nu))))))
(defun update-utility-for-compiled-production (p3 p1 p2)
(let ((u (get-module utility))
ult ul alpha)
(when (or (production-reward-changed p1) (production-reward-changed p2))
(model-warning "Parent productions for ~s may now provide different rewards than they did when it was created." p3))
(when u
(bt:with-lock-held ((utility-param-lock u))
(setf ult (utility-trace u)
ul (utility-ul u)
alpha (utility-alpha u)))
(when ul
(when ult
(model-output " Updating utility of production ~S from production compilation" p3)
(model-output " U(n-1) = ~f R(n) = ~f [U(n) for first parent] alpha = ~f" (production-u p3)
(production-u p1) alpha))
(linear-update-utility alpha p3 (production-u p1))
(when ult
(model-output " U(n) = ~f" (production-u p3)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Here's the actual module and associated support code
(defun utility-module-params (u param)
(bt:with-lock-held ((utility-param-lock u))
(cond ((consp param)
;; Changing utility parameters may lead to
;; to possibly trigger conflict-resolution if it were waiting
(un-delay-conflict-resolution)
(when (and (> (length (all-productions)) 0)
(member (car param) '(:esc :dat :ul :iu)))
(model-warning "Changing procedural parameters when productions exist unsupported.")
(model-warning "Results may not be what one expects."))
(case (car param)
(:esc (setf (utility-esc u) (cdr param)))
(:egs (setf (utility-egs u) (cdr param)))
(:ul (setf (utility-ul u) (cdr param)))
(:dat (setf (utility-dat u) (seconds->ms (cdr param))))
(:iu (setf (utility-iu u) (cdr param)))
(:nu (setf (utility-nu u) (cdr param)))
(:alpha (setf (utility-alpha u) (cdr param)))
(:ult (setf (utility-trace u) (cdr param)))
(:ut (setf (utility-ut u) (cdr param)))
(:utility-hook
(when (and (cdr param) (utility-utility-hook u))
(print-warning
"Utility-hook was set to ~S and is being overwritten"
(utility-utility-hook u)))
(setf (utility-utility-hook u) (cdr param)))
(:reward-hook
(when (and (cdr param) (utility-reward-hook u))
(print-warning
"Reward-hook was set to ~S and is being overwritten"
(utility-reward-hook u)))
(setf (utility-reward-hook u) (cdr param)))
(:utility-offsets
(setf (utility-offsets u)
(set-or-remove-hook-parameter :utility-offsets (utility-offsets u) (cdr param))))
(:reward-notify-hook
(setf (utility-reward-notify-hooks u)
(set-or-remove-hook-parameter :reward-notify-hook (utility-reward-notify-hooks u) (cdr param))))))
(t
(case param
(:egs (utility-egs u))
(:ul (utility-ul u))
(:iu (utility-iu u))
(:nu (utility-nu u))
(:ut (utility-ut u))
(:alpha (utility-alpha u))
(:ult (utility-trace u))
(:utility-hook (utility-utility-hook u))
(:reward-hook (utility-reward-hook u))
(:utility-offsets (utility-offsets u))
(:reward-notify-hook (utility-reward-notify-hooks u)))))))
(defun reset-utility-module (u)
(bt:with-lock-held ((utility-param-lock u))
(setf (utility-history u) nil)))
(defun create-utility-module (x)
(declare (ignore x))
(make-utility))
(define-module-fct 'utility nil
(list (define-parameter :esc :owner nil)
(define-parameter :egs :valid-test 'numberp :default-value 0.0
:warning "a number" :documentation "Expected Gain S")
(define-parameter :ul :valid-test 'tornil :default-value nil
:warning "T or nil" :documentation "Utility learning switch")
(define-parameter :dat :owner nil)
(define-parameter :iu :valid-test 'numberp :default-value 0
:warning "a number" :documentation "default U(0) value for an initial (user defined) production")
(define-parameter :nu :valid-test 'numberp :default-value 0
:warning "a number" :documentation "default U(0) value for a newly learned production")
(define-parameter :ut :valid-test 'numornil :default-value nil
:warning "a number or nil" :documentation "Utility Threshold")
(define-parameter :alpha :default-value .2
:valid-test 'numberp :warning "a number"
:documentation "Production learning rate")
(define-parameter :ult :valid-test 'tornil :default-value nil
:warning "T or nil" :documentation "Utility learning trace")
(define-parameter :utility-hook :valid-test 'local-or-remote-function-or-nil
:default-value nil
:warning "a function, string naming a command, or nil"
:documentation "Utility computation hook")
(define-parameter :reward-hook :valid-test 'local-or-remote-function-or-nil
:default-value nil
:warning "a function, string naming a command, or nil"
:documentation "Reward value hook")
(define-parameter :utility-offsets :valid-test 'local-or-remote-function-or-remove
:default-value nil
:warning "a function, string naming a command, nil, or (:remove <item>)"
:documentation "Add additional utility equation components")
(define-parameter :reward-notify-hook :valid-test 'local-or-remote-function-or-remove
:default-value nil
:warning "a function, string naming a command, nil, or (:remove <item>)"
:documentation "Depricated - monitor trigger-reward instead. Functions to call when there is a reward provided"))
:version "6.0"
:documentation "A module that computes production utilities"
:creation 'create-utility-module
:reset 'reset-utility-module
:params 'utility-module-params
:required 'procedural)
(register-subsymbolic-parameters :egs :ul :iu :nu :alpha)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This section is all support for spp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Taken and modified from ACT-R 5 code
(defun production-parameter-fct (production-name &optional parameters)
"Returns the value of the production parameter(s), or print all if none given."
(let ((esc (car (no-output (sgp :esc))))
(ul (car (no-output (sgp :ul))))
(value nil)
(values nil))
(cond (production-name
(command-output "Parameters for production ~S:" production-name)
(cond (parameters
(dolist (parameter parameters)
(setf value
(case parameter
(:name production-name)
(:utility (production-utility production-name))
(:u (production-u production-name))
(:at (ms->seconds (production-at production-name)))
(:reward (production-reward production-name))
(:fixed-utility (production-fixed-utility production-name))
(t (print-warning "NO PARAMETER ~A DEFINED FOR PRODUCTIONS." parameter)
:error)))
(push-last value values)
(if (numberp value)
(command-output " ~S ~6,3F" parameter value)
(command-output " ~S ~6@s" parameter value)))
values)
(t
(when esc
(if (numberp (production-utility production-name))
(command-output " :utility ~6,3F" (production-utility production-name))
(command-output " :utility ~6@s" (production-utility production-name))))
(command-output " :u ~6,3F" (production-u production-name))
(command-output " :at ~6,3F" (ms->seconds (production-at production-name)))
(when (and esc ul)
(if (numberp (production-reward production-name))
(command-output " :reward ~6,3F" (production-reward production-name))
(command-output " :reward ~6@s" (production-reward production-name)))
(command-output " :fixed-utility ~6@s" (production-fixed-utility production-name)))
production-name)))
(t :error))))
;;; This name is dangerously close to what I use in the sgp code, but
;;; for now I'll leave it as is.
(defmacro set-parameter (slot parameter test warning &rest housekeeping)
"Sets parameter of production p in slot if value passes test, otherwise issue warning."
`(cond (,test
(setf (,slot p) value)
,@housekeeping
value)
(t
(print-warning
"PARAMETER ~A CANNOT TAKE VALUE ~S BECAUSE IT MUST BE ~:@(~A~)."
,parameter value ,warning)
:error)))
(defun parameters-fct (p parameters)
"Sets the parameters of the production (internal - user should use spp)."
;; Changing procedural parameters reschedules conflict resolution
;; if it's waiting to happen
(un-delay-conflict-resolution)
;; Having the name of the production be p and the
;; value to be set called value are critical to
;; the functioning of the set-parameter macro...
(let ((values nil)
(ul (car (no-output (sgp :ul)))))
(if p
(loop
(unless parameters
(return values))
(let* ((parameter (pop parameters))
(value (pop parameters)))
;; not sure about this, but I'll leave it in for now
(when (and (listp value)
(eq (first value) 'quote))
(setf value (second value)))
(push-last
(case parameter
(:name
(print-warning "PARAMETER NAME CANNOT BE SET.")
:error)
(:utility
(print-warning "PARAMETER UTILITY CANNOT BE SET.")
:error)
(:u
(set-parameter production-u :u
(numberp value) "a number"))
(:at
(setf value (safe-seconds->ms value 'spp))
(let ((res (set-parameter production-at :at
(nonneg value)
"a positive number")))
(if (numberp res)
(ms->seconds res)
res)))
(:reward ;; can't use set-parameter because I need to test
;; the original value before setting it but the
;; housekeeping only occurs after
(if ul
(cond ((or (null value) (eq value t) (numberp value))
(unless (zerop (mp-time-ms))
(let ((old (production-reward p)))
(unless (eq value old)
(setf (production-reward-changed p) t))))
(setf (production-reward p) value)
value)
(t
(print-warning
"PARAMETER ~A CANNOT TAKE VALUE ~S BECAUSE IT MUST BE ~:@(~A~)."
:reward value "a number, t, or nil")
:error))
(print-warning "PARAMETER REWARD CAN ONLY BE SET WHEN UL IS T.")))
(:fixed-utility
(set-parameter production-fixed-utility :fixed-utility
(or (eq value t) (null value))
"T or nil"))
(t
(print-warning
"NO PARAMETER ~A DEFINED FOR PRODUCTIONS." parameter)
:error))
values)))
:error)))
(defmacro spp (&rest production-parameters)
"Inspects and sets production parameters."
`(spp-fct ',production-parameters))
(defun spp-fct (parameters)
"Inspects and sets production parameters."
(let ((results nil))
(if (null parameters) ; print all parameters for all productions
(dolist (production (all-productions))
(push-last (production-parameter-fct production) results))
(dolist (description (if (or (keywordp (first parameters))
(keywordp (second parameters))
(and (listp (first parameters))
(null (second parameters))
(not (keywordp
(second
(first parameters))))))
(list parameters) parameters))
(when (atom description) (setf description (list description)))
(if (keywordp (first description))
(dolist (production (all-productions))
(push-last
(if (and (cdr description)
(not (keywordp (second description))))
(parameters-fct production description)
(production-parameter-fct production description))
results))
(dolist (production (if (atom (first description))
(list (first description))
(first description)))
(if (get-production production)
(push-last
(if (and (cddr description)
(not (keywordp (third description))))
(parameters-fct production (rest description))
(production-parameter-fct production (rest description)))
results)
(progn
(model-warning "Spp cannot adjust parameters because production ~S does not exist" production)
(push-last :error results)))))))
results))
(defun spp-remote (&rest params)
(encode-string-names (spp-fct (decode-string-names params))))
(add-act-r-command "spp" 'spp-remote "Set or get production parameters. Params: see ACT-R manual." t)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|# | 39,577 | Common Lisp | .lisp | 737 | 43.056988 | 146 | 0.566004 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1ec29ca396b79de5f50232072e34f18dcf23b8a175e29b20fcdbaabdc7ca13f2 | 14,299 | [
-1
] |
14,300 | device.lisp | asmaloney_ACT-R/devices/virtual/device.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Mike Byrne & Dan Bothell
;;; Address : Rice University, MS-25
;;; : Psychology Department
;;; : Houston,TX 77251-1892
;;; : [email protected]
;;;
;;; Copyright : (c)2000-2004 Mike Byrne
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : virtual-view.lisp
;;; Version : 1.0
;;;
;;; Description : Instantiates "virtual views" so that RPM can act on things
;;; : other than MCL windows.
;;;
;;; Bugs :
;;;
;;; Todo :
;;;
;;; ----- History -----
;;; 00.06.08 Mike Byrne
;;; : Date for new header.
;;; 00.09.13 mdb
;;; : Updated for vectors.
;;; 00.11.15 mdb
;;; : Fixed minor compiler warnings, cleaned up some lingering
;;; : vector bugs.
;;; 01.07.03 mdb
;;; : Added defgenerics and doc strings.
;;; 02.01.15 Dan
;;; : Changed the declaration of ignore to
;;; : ignore-if-unused for the subviews method
;;; : to eliminate an ugly warning in ACL.
;;; 02.02.28 Dan
;;; : changed vv-click-event-handler because
;;; : functionp doesn't gurantee that the function is
;;; : returned as the true value.
;;; 02.06.21 Dan [b7]
;;; : Added the rpm-window class as part of the reorganization
;;; : of internal window classes.
;;; : Changed the #+:mcl to better work with openmcl.
;;; 02.06.30 Dan
;;; : Moved the view based line support in to here.
;;; : Moved the populate-loc-to-key-array from generic-interface
;;; : to here.
;;; : Took the UWI code out of here.
;;; 02.12.19 Dan
;;; : Added an around method for text items to handle color.
;;; 04.04.13 Dan [2.2] (the previous update is "new" as of 2.2 as well)
;;; : Changed the copyright notice and added the LGPL stuff.
;;;
;;; 04.10.19 Dan [Moved into ACT-R 6]
;;; : Reset the version to 1.0a1
;;; : added the packaging switches
;;; : Changed vw-output to show in the trace and not in the
;;; : a window specific stream
;;; :
;;; : depends on the vision module and dmi, but that seems
;;; : reasonable for now.
;;; 2005.05.11 Dan
;;; : * Added a check of :vwt to vw-output so that it can be
;;; : easily shut off (which is actually the default for now).
;;; 2006.01.16 Dan
;;; : * Discovered that the hash-table implementation of the
;;; : virtual-view subviews can lead to non-repeatable performance
;;; : of tutorial models (both between different Lisps or even
;;; : within a single Lisp!). So, for now at least, the
;;; : build-features-for method for a virtual-window will sort
;;; : the features based on xy coordinates. That way the tutorial
;;; : model results will remain consistent for all systems that
;;; : use the virtuals (any hooked up to the environment).
;;; 2006.09.07 Dan
;;; : * Modified the build-features-for method on the virtual-
;;; : windows so that it calls fill-default-dimensions.
;;; 2007.06.21 Dan
;;; : * Converted things over to use the new chunk based device
;;; : specification.
;;; 2007.07.05 Dan
;;; : * No need to sort the features being returned because the
;;; : hash-table inside vision will mess it up anyway...
;;; 2007.08.23 Dan
;;; : * Fixed build-vis-locs-for of buttons so that the text
;;; : is located at the same point as the oval (bug carried
;;; : over from the old stuff).
;;; 2008.01.08 Dan
;;; : * Put the sorting code back in build-vis-locs-for because
;;; : without it there's no consistency in the names of the
;;; : visual-location chunks for testing and verification purposes.
;;; 2008.01.09 Dan
;;; : * Adding a little more to the sorting method so that co-located
;;; : items of different types also get a specific ordering.
;;; 2008.04.11 Dan [1.0]
;;; : * Using the new parameter :stable-loc-names in the build-vis-
;;; : locs-for method on virtual-windows to check whether the
;;; : subview items should be sorted.
;;; : * Also took the package setting out of the mode line at the
;;; : top since there isn't a specific package for any of the
;;; : source files.
;;; 2008.04.14 Dan
;;; : * Modifying the objects and build-vis-locs-for methods to
;;; : only create 1 chunk per item across proc-display calls.
;;; : That makes it compatible with the :test-feats nil setting.
;;; : Doesn't hold when :optimize-visual is nil or text items
;;; : contain multiple "words" i.e. only compatible when each text
;;; : item produces only one feature.
;;; 2008.04.15 Dan
;;; : * Fixed a bug with the line views. Without a specific
;;; : point-in-vv-p the default misinterprets their size values
;;; : and could consider clicks which didn't overlap the line
;;; : to be over the line and not be passed on to the "real" item
;;; : which should be clicked. Now, lines are not clickable at
;;; : all.
;;; : * Took all the "the fixnum" declarations out of point-in-vv-p
;;; : because nothing forces the mouse position to be a fixnum and
;;; : when visual items have an odd dimension the mouse position
;;; : can get set to a rational. In LispWorks point-in-vv-p does
;;; : not work if the values are rationals declared as fixnums.
;;; 2008.07.01 Dan
;;; : * Added code to the build-vis-locs-for methods to purge any
;;; : old chunks when possible.
;;; : * Also purge them in remove-subviews so that when the item is
;;; : cleared from a window they're also removed.
;;; 2010.08.11 Dan
;;; : * Changed view-loc to round the divisions to of height and width
;;; : to make sure things stay fixnums since an odd width button
;;; : causes problems in build-string-feats for Lisps that care
;;; : about the fixnum delcaration.
;;; 2011.04.28 Dan
;;; : * Changed an ignore-if-unused declaration to ignorable.
;;; 2012.06.20 Dan
;;; : * Changed loc-chunks to be a hash-table referenced by a cons
;;; : of meta-process and model names since multiple models may
;;; : be viewing the same item and they need to keep their chunks
;;; : separate. Now the chunks are stored as the values of the
;;; : table for the appropriate mp and model and always in a list.
;;; 2014.01.24 Dan
;;; : * Updated the build-vis-locs-for methods for text and button
;;; : items so that they use the updated build-string-feats to
;;; : deal with newlines in the text.
;;; : * The spacing for lines in virtual items is the max of
;;; : (* (text-height item) 1.25) (1+ (text-height item)).
;;; 2014.02.07 Dan
;;; : * Why have virtual static text items always assumed a centered
;;; : y justification when all the other devices assume top? It
;;; : now assumes top justification like everything else for
;;; : consistency which will probably break lots of models...
;;; 2014.02.11 Dan
;;; : * Removed the lines variable from the text build-vis-locs-for
;;; : to avoid a warning since it's not needed.
;;; 2014.05.19 Dan
;;; : * Fixed the use of chunk-type-slot-names by using chunk-filled-
;;; : slots-list instead.
;;; 2014.08.29 Dan
;;; : * Changed vv-click-event-handler for buttons so that the action
;;; : can be either a function or a symbol naming a function.
;;; 2015.05.20 Dan
;;; : * The approach-width call in the buttons build-vis-locs-for
;;; : method needs to pass the vision module in too.
;;; 2015.12.17 Dan
;;; : * Changed the name of the key at 19,2 from esc to clear to
;;; : actually match the reference image since the model now has
;;; : keypad actions.
;;; 2016.06.16 Dan
;;; : * When a button or line changes the size of the location now
;;; : gets updated along with the other features.
;;; 2016.11.17 Dan
;;; : * The code for storing and removing the loc chunks was using
;;; : the meta-process name, but that's not needed (or available)
;;; : anymore.
;;; 2017.01.05 Dan
;;; : * Removed the loc-chunks slot altogether and removed some of
;;; : the old device methods.
;;; : * Also removed methods that weren't used anywhere else like
;;; : set-view-size and set-view-position.
;;; 2017.01.06 Dan
;;; : * Stripped some other unnecessary code like close and select.
;;; : * The build-vis-locs-for methods now just return the feature
;;; : lists as needed for the add-visicon-features command and it's
;;; : up to the agi to handle the actual adding and recording of
;;; : the chunk returned by vision.
;;; : * Add-subviews now warns if an item already has a container
;;; : and doesn't put it into the new window.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.09 Dan
;;; : * Updated the build-vis-locs-for for lines to specify isa
;;; : line-location since it needs the end* slots, and added that
;;; : chunk-type to vision module.
;;; 2017.03.02 Dan
;;; : * Changed device-handle-click to vv-handle-click to avoid
;;; : issues since it now gets passed the click point.
;;; : * Fixed a bug in the vv-click-event-handler.
;;; 2017.03.03 Dan
;;; : * Changed the way the button's action function is specified.
;;; : Now it can be:
;;; : - a function or dispatch command string
;;; : That function or command will be called with no parameters
;;; : - a list where the first is as above
;;; : That function or command will be called with the rest
;;; : of the list as its parameters
;;; : Also, the validity of that item is only tested when the
;;; : button is created and not before each execution, but if an error
;;; : is reported by the dispatch call it will report that.
;;; 2017.03.08 Dan
;;; : * Adding back the device-move-cursor-to method because I need
;;; : something to call to send the updates to the environment and
;;; : that's where it was before.
;;; 2017.05.31 Dan
;;; : * Use new-symbol instead of new-name so there doesn't need
;;; : to be a current model to create GUI elements.
;;; 2017.06.19 Dan
;;; : * Remove the unused optional parameter from subviews.
;;; : * Removed the build-vis-locs-for methods.
;;; 2018.03.14 Dan
;;; : * Just set :handles-click-p to nil for lines instead of having
;;; : a dummy point-in-vv-p method for them.
;;; 2020.01.10 Dan
;;; : * Removed #' from lambdas since not using it other places either.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Base Virtual View class.
(defclass virtual-view ()
((view-subviews :accessor view-subviews :initarg :subviews
:initform (make-hash-table))
(x-pos :accessor x-pos :initform nil :initarg :x-pos)
(y-pos :accessor y-pos :initform nil :initarg :y-pos)
(width :accessor width :initform nil :initarg :width)
(height :accessor height :initform nil :initarg :height)
(id :accessor id :initarg :id :initform (new-symbol-fct "VV"))
(handles-click-p :accessor handles-click-p :initform t
:initarg :handles-click-p)
(view-container :accessor view-container :initform nil)
(color :accessor color :initarg :color :initform 'black)
(visual-features :accessor visual-features :initform nil)))
#+(or (not :mcl) :openmcl)
(defgeneric subviews (view)
(:documentation "Returns a list of subviews of <view>."))
(defmethod subviews ((vv virtual-view))
(let (accum)
(maphash (lambda (x y) (declare (ignore x))
(push y accum))
(view-subviews vv))
accum))
(defmethod view-loc ((vv virtual-view))
(vector (+ (x-pos vv) (round (width vv) 2))
(+ (y-pos vv) (round (height vv) 2))))
#+(or (not :mcl) :openmcl)
(defgeneric add-subviews (view &rest subviews)
(:documentation "Add subviews to <view>."))
(defmethod add-subviews ((vv virtual-view) &rest subviews)
(dolist (sub subviews)
(if (view-container sub)
(print-warning "Item ~s is already in window ~s so it can't be added to window ~s" sub (view-container sub) vv)
(progn
(setf (gethash (id sub) (view-subviews vv)) sub)
(setf (view-container sub) vv)))))
#+(or (not :mcl) :openmcl)
(defgeneric remove-subviews (view &rest subviews)
(:documentation "Remove subviews from <view>."))
(defmethod remove-subviews ((vv virtual-view) &rest subviews)
(dolist (sub subviews)
(if (gethash (id sub) (view-subviews vv))
(progn
(remhash (id sub) (view-subviews vv))
(setf (view-container sub) nil)
)
(print-warning "Item ~s is not in window ~s so it can't be removed from it" sub vv))))
(defgeneric point-in-vv-p (vview point)
(:documentation "Determine if the supplied point is inside the supplied view."))
(defmethod point-in-vv-p ((vv virtual-view) point)
(let ((x (px point))
(y (py point)))
(and (>= x (x-pos vv))
(>= y (y-pos vv))
(<= x (+ (x-pos vv) (width vv)))
(<= y (+ (y-pos vv) (height vv))))))
(defgeneric vv-click-event-handler (vview point)
(:documentation "Handle a click in <vview> at point <point>."))
(defmethod vv-click-event-handler ((vv virtual-view) point)
(declare (ignore point))
nil)
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Virtual Window class and methods.
(defclass virtual-window (virtual-view)
((window-title :accessor window-title :initarg :window-title
:initform "Virtual Window")
)
(:default-initargs
:x-pos 0
:y-pos 0
:id (new-symbol-fct "VW")
))
(defmethod device-move-cursor-to ((vw virtual-window) (loc vector))
)
(defun subview-sort (i1 i2)
(and (numberp (x-pos i1))
(numberp (x-pos i2))
(numberp (y-pos i1))
(numberp (y-pos i2))
(or
(< (x-pos i1) (x-pos i2))
(and (= (x-pos i1) (x-pos i2))
(< (y-pos i1) (y-pos i2)))
(and (= (x-pos i1) (x-pos i2))
(= (y-pos i1) (y-pos i2))
(string< (symbol-name (type-of i1)) (symbol-name (type-of i2)))))))
(defmethod vv-handle-click ((vw virtual-window) (pos vector))
(dolist (sub (subviews vw))
(when (and (handles-click-p sub)
(point-in-vv-p sub pos))
(vv-click-event-handler sub pos)
(return-from vv-handle-click t))))
#+(or (not :mcl) :openmcl)
(defgeneric view-window (view)
(:documentation "Returns the window associated with <view> (if any), or <view> if <view> is a window."))
(defmethod view-window ((vw virtual-window))
vw)
;;;; ---------------------------------------------------------------------- ;;;;
;;;; View classes: static-text-vv, button-vv,
(defclass virtual-dialog-item (virtual-view)
((text :accessor dialog-item-text :initform "Untitled"
:initarg :dialog-item-text)
(action-function :accessor action-function :initarg :action :initform nil)
(text-height :accessor text-height :initarg :text-height :initform 10)
(str-width-fct :accessor str-width-fct :initarg :str-width-fct
:initform (lambda (str)
(* 7 (length str))))
(lock :initform nil :accessor dialog-item-lock :initarg :lock))
(:default-initargs
:height 18
:width 60
:subviews nil))
(defmethod subviews ((vdi virtual-dialog-item))
(declare (ignorable vdi))
nil)
(defmethod view-window ((vdi virtual-dialog-item))
(let ((vc (view-container vdi)))
(if (null vc)
nil
(if (typep vc 'virtual-window)
vc
(view-window vc)))))
(defclass static-text-vdi (virtual-dialog-item)
()
(:default-initargs
:id (new-symbol-fct "TEXT-VDI")
:handles-click-p nil))
(defclass button-vdi (virtual-dialog-item)
()
(:default-initargs
:id (new-symbol-fct "BUTTON-VDI")
:action "default-button-action"))
(defmethod vv-click-event-handler ((btn button-vdi) where)
(declare (ignore where))
(if (listp (action-function btn))
(cond ((stringp (first (action-function btn)))
(multiple-value-bind (success result)
(apply 'evaluate-act-r-command (first (action-function btn)) (rest (action-function btn)))
(unless success
(print-warning "Button click action ~s reported error ~s." (action-function btn) result))))
((or (functionp (first (action-function btn)))
(and (symbolp (first (action-function btn)))
(fboundp (first (action-function btn)))
(not (macro-function (first (action-function btn))))))
(apply (first (action-function btn)) (rest (action-function btn))))
(t
(default-button-action)))
(cond ((stringp (action-function btn))
(multiple-value-bind (success result)
(evaluate-act-r-command (action-function btn))
(unless success
(print-warning "Button click action ~s reported error ~s." (action-function btn) result))))
((or (functionp (action-function btn))
(and (symbolp (action-function btn))
(fboundp (action-function btn))
(not (macro-function (action-function btn)))))
(funcall (action-function btn)))
(t
(default-button-action)))))
(defun default-button-action ()
(print-warning "Button with no valid action clicked at time ~S." (mp-time)))
(add-act-r-command "default-button-action" 'default-button-action "Function called for a button with no action. Do not call directly." nil)
;;; The base class for the view based lines.
(defclass v-liner (virtual-dialog-item)
()
(:default-initargs
:handles-click-p nil))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 20,330 | Common Lisp | .lisp | 408 | 46.247549 | 139 | 0.587018 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | de172fbf97e256b7a24a3e981a2ef2f3fe3480e68b7031b287623534d44ecede | 14,300 | [
-1
] |
14,301 | uwi.lisp | asmaloney_ACT-R/devices/virtual/uwi.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Address : Carnegie Mellon University
;;; : Psychology Department
;;; : Pittsburgh,PA 15213-3890
;;; : [email protected]
;;;
;;; Copyright : (c)2002-2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : uniform-interface-virtual.lisp
;;; Version : 2.0
;;;
;;; Description : wirtual view functions to implement the UWI.
;;; : NOTE: The UWI is only still around to support the
;;; : ACT-R GUI interface. I don't advocate using it directly.
;;;
;;; Bugs :
;;; --- History ---
;;; 2002.06.30 Dan
;;; : Added this header.
;;; : Moved all of the UWI code from virtual-view
;;; : to this file where it belongs.
;;; : Added the visible-virtuals-avaialable? function.
;;; : Actually documented the code and added defgenerics with
;;; : documentation for the uwi.
;;; 2002.12.19 Dan
;;; : Modified make-static-text-for-rpm-window to take a
;;; : color parameter.
;;; 04.04.13 Dan [2.2] (previous change is "new" as of 2.2 as well)
;;; : Changed the copyright notice and added the LGPL stuff.
;;;
;;; 04.10.19 Dan [Moved into ACT-R 6]
;;; : Reset the version to 1.0a1
;;; : added the packaging switches
;;; 2007.07.13 Dan
;;; : * Adding color as an option for button items in make-
;;; button-for
;;; 2008.07.01 Dan
;;; : * Added code so that closing a virtual window will force all
;;; : the associated chunks to be purged:
;;; : - closing a virtual window will first remove all of its
;;; : objects.
;;; : - if it has a loc-chunk (a cursor) it is purged.
;;; 2012.06.20 Dan
;;; : * The loc-chunk slot now holds a hash-table since multiple
;;; : models could be sharing the window and each will have its
;;; : own cursor chunk.
;;; 2012.10.02 Dan
;;; : * Make-rpm-window now uses print warning to report when there
;;; : isn't a visible window available when one is requested and
;;; : returns a virtual on instead.
;;; 2013.01.10 Dan
;;; : * Visible-virtuals-available? now just calls check-with-environment-for-visible-virtuals
;;; : if it's defined to avoid having to redefine visible-virtuals-available?
;;; : it later.
;;; 2015.05.26 Dan
;;; : * Added a font-size parameter to make-static-text-for-rpm-window.
;;; : Should be a point size for the font, defaults to 12 and the
;;; : height and width are based on the ratios for the previous
;;; : defaults which were 10 high and 7 wide for 12 point.
;;; 2016.06.08 Dan
;;; : * Allow the class in make-rpm-window to override visible-
;;; : virtual-windows if it's a subtype of that class.
;;; : * Add the modify-*-for-rpm-window methods which just directly
;;; : change the slots of the object since that's all a virtual
;;; : item needs (the device code modifies the underlying feature
;;; : chunks as needed).
;;; 2016.06.09 Dan
;;; : * Properly change the action of a button in the modify.
;;; 2017.01.05 Dan
;;; : * Add the installed slot to rpm-window class.
;;; : * Removed device methods.
;;; 2017.01.06 Dan
;;; : * More adjustments with the assumption that virtual windows
;;; : are the only interface for the AGI and nobody will be trying
;;; : to treat them like MCL windows.
;;; 2017.06.01 Dan
;;; : * Remove the installed slot because that needs to be tracked by
;;; : the AGI since a window could be installed for more than 1 model.
;;; 2017.06.07 Dan
;;; : * Adding a lock to the window object and using that in the add,
;;; : remove, and modify actions (technically modify should probably
;;; : be a lock on the item itself, but just using the window lock
;;; : for now).
;;; 2017.06.08 Dan
;;; : * Removed the lock use from the items since the modify actions
;;; : don't change the window and are single-instance.
;;; : * Fixed the with-act-r-lock usage since it uses a simpler
;;; : syntax than the underlying with-lock.
;;; : * Have each window create a lock with a unique name.
;;; 2017.06.14 Dan
;;; : * Put the lock checks back into the modify actions since the
;;; : AGI commands can be called directly from Lisp which bypasses
;;; : the single instance tests.
;;; : * Added a lock test to close-rpm-window around the window-open?
;;; : setting.
;;; 2017.06.16 Dan
;;; : * Use a raw lock instead of an act-r lock for the window and
;;; : redefine some of the virtual-window methods on the rpm-
;;; : class so that the lock can be tested. Also make it recursive
;;; : because add-subviews should test it but that happens in the
;;; : context of other things too.
;;; : * Create new classes for the dialog items so that they can
;;; : have a lock slot which gets set when they are created to
;;; : be the parent window's lock.
;;; : * Moved the build-vis-locs-for methods here since they're
;;; : defined on the subclasses to be thread safe.
;;; 2017.06.23 Dan
;;; : * Added a name for the window's lock.
;;; 2017.08.16 Dan
;;; : * Need to release the window's lock in the vv-handle-click
;;; : method before calling vv-click-event-handler because that
;;; : might end up calling a dispatched function to modify the
;;; : window.
;;; 2017.09.08 Dan
;;; : * Updated the warning about visible virtuals not available.
;;; 2018.03.13 Dan [2.0]
;;; : * Build-vis-locs-for methods don't need vision module now!
;;; : * Vv-handle-click now needs to check the window and then
;;; : convert from global to local for testing subviews.
;;; 2018.03.15 Dan
;;; : * Simplifying the class hierarcy because the UWI doesn't
;;; : really need the rpm-dialog-item and rpm-window classes
;;; : at this point or the rpm-*-item classes.
;;; 2018.03.27 Dan
;;; : * Moved find-top-level-window here from the agi file.
;;; 2018.05.02 Dan
;;; : * Update the feature creation to match the new add-visicon-features
;;; : specification.
;;; 2018.05.04 Dan
;;; : * Updated the modify calls as well.
;;; 2018.06.13 Dan
;;; : * Button text doesn't need to double quote the value.
;;; 2018.08.06 Dan
;;; : * Line locations can just use visual-location instead of line-
;;; : location now.
;;; 2018.09.13 Dan
;;; : * Add the send-update-to-handlers method which does nothing
;;; : for virtual windows.
;;; 2019.10.01 Dan
;;; : * Fixed the typo in the monitor-move-cursor slot name.
;;; 2020.05.01 Dan (from Mike)
;;; : * Changed the line features to include the orientation in the
;;; : value slot of both chunks.
;;; 2020.12.10 Dan
;;; : * Added an external command for visible-virtuals-available?.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; RPM-VIRTUAL-WINDOW [Class]
;;; Description : This is the UWI's window class to produce a virtual window.
(defclass rpm-virtual-window (virtual-window)
((monitor-attended-loc :accessor monitor-attended-loc :initform nil)
(monitor-click-mouse :accessor monitor-click-mouse :initform nil)
(monitor-move-cursor :accessor monitor-move-cursor :initform nil)
(monitor-delete-cursor :accessor monitor-delete-cursor :initform nil)
(cursor-drawn :accessor cursor-drawn :initform nil)
(open :initform t :accessor window-open?)
(lock :initform (bt:make-recursive-lock "virtual-window-lock") :accessor window-lock :initarg :lock)))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; These are the UWI Methods.
;;;; ---------------------------------------------------------------------- ;;;;
(defun find-top-level-window (item)
(do ((w item (view-container w)))
((null (view-container w)) w)))
;;; OPEN-RPM-WINDOW? [Method]
;;; Description : Returns t if the window is open and nil if not.
(defgeneric open-rpm-window? (window)
(:documentation "Returns t if the window is currently open"))
(defmethod open-rpm-window? ((win rpm-virtual-window))
(bt:with-recursive-lock-held ((window-lock win))
(window-open? win)))
(defmethod open-rpm-window? ((win null))
nil)
(defgeneric send-update-to-handlers (window params)
(:documentation "Returns t if the window is visible"))
(defmethod send-update-to-handlers ((win rpm-virtual-window) params)
(declare (ignorable win params)))
;;; CLOSE-RPM-WINDOW [Method]
;;; Description : Closes the window.
(defgeneric close-rpm-window (window)
(:documentation "Close an rpm-window"))
(defmethod close-rpm-window ((win rpm-virtual-window))
(remove-all-items-from-rpm-window win)
(bt:with-recursive-lock-held ((window-lock win))
(setf (window-open? win) nil)))
;;; SELECT-RPM-WINDOW [Method]
;;; Description : Brings the specified window to the foreground.
(defgeneric select-rpm-window (window)
(:documentation "Bring an rpm-window to the front"))
(defmethod select-rpm-window ((win rpm-virtual-window))
nil)
;;; ADD-VISUAL-ITEMS-TO-RPM-WINDOW [Method]
;;; Description : Makes the specified items subviews of the window and
;;; : calls view-draw-contents and event-dispatch to make sure
;;; : that they show up.
(defgeneric add-visual-items-to-rpm-window (window &rest x)
(:documentation "Add items to the rpm-window for display"))
(defmethod add-visual-items-to-rpm-window ((win rpm-virtual-window) &rest items)
(bt:with-recursive-lock-held ((window-lock win))
(dolist (item items)
(add-subviews win item))))
;;; REMOVE-VISUAL-ITEMS-FROM-RPM-WINDOW [Method]
;;; Description : Take the specified items out of the subviews of the
;;; : window and make it redraw.
(defgeneric remove-visual-items-from-rpm-window (window &rest x)
(:documentation "Remove items from the display in the window"))
(defmethod remove-visual-items-from-rpm-window ((win rpm-virtual-window) &rest items)
(bt:with-recursive-lock-held ((window-lock win))
(dolist (item items)
(remove-subviews win item))))
;;; REMOVE-ALL-ITEMS-FROM-RPM-WINDOW [Method]
;;; Description : Remove all the subvies of the window and redisplay it.
(defgeneric remove-all-items-from-rpm-window (window)
(:documentation "Remove all items from the window"))
(defmethod remove-all-items-from-rpm-window ((win rpm-virtual-window))
(bt:with-recursive-lock-held ((window-lock win))
(apply 'remove-subviews win (subviews win))))
;;;;; redefine some virtual-view methods to be able to test the lock
(defmethod add-subviews ((vv rpm-virtual-window) &rest subviews)
(bt:with-recursive-lock-held ((window-lock vv))
(dolist (sub subviews)
(if (view-container sub)
(print-warning "Item ~s is already in window ~s so it can't be added to window ~s" sub (view-container sub) vv)
(progn
(setf (gethash (id sub) (view-subviews vv)) sub)
(setf (view-container sub) vv))))))
(defmethod remove-subviews ((vv rpm-virtual-window) &rest subviews)
(bt:with-recursive-lock-held ((window-lock vv))
(dolist (sub subviews)
(if (gethash (id sub) (view-subviews vv))
(progn
(remhash (id sub) (view-subviews vv))
(setf (view-container sub) nil)
)
(print-warning "Item ~s is not in window ~s so it can't be removed from it" sub vv)))))
(defmethod vv-handle-click ((vw rpm-virtual-window) (pos vector))
(bt:acquire-recursive-lock (window-lock vw))
(when (point-in-vv-p vw pos)
(let ((local-pos (map 'vector '- pos (vector (x-pos vw) (y-pos vw)))))
(dolist (sub (subviews vw))
(when (and (handles-click-p sub)
(point-in-vv-p sub local-pos))
(bt:release-recursive-lock (window-lock vw))
(vv-click-event-handler sub local-pos)
(return-from vv-handle-click t)))))
(bt:release-recursive-lock (window-lock vw))
nil)
;;; MAKE-RPM-WINDOW [Function]
;;; Description : Make and return a window based on the parameters supplied.
;;; : Visible determines wheter or not it should be a real or
;;; : virtual and if the environment is connected it will use a
;;; : visible-virtual for the real window unless the user explicitly
;;; : specifies the class to use.
(defun make-rpm-window (&key (visible nil) (title "RPM Window") (width 100) (height 100) (x 0 ) (y 0))
(if visible
(aif (visible-virtuals-available?)
(make-instance 'visible-virtual-window :window-title title :width width :height height :x-pos x :y-pos y :display-handlers it)
(progn
(print-warning "No handler available for displaying a visible window. Using a virtual window instead.")
(make-instance 'rpm-virtual-window :window-title title :width width :height height :x-pos x :y-pos y)))
(make-instance 'rpm-virtual-window :window-title title :width width :height height :x-pos x :y-pos y)))
;;; MAKE-BUTTON-FOR-RPM-WINDOW [Method]
;;; Description : Build and return a button-dialog-item based on the
;;; : parameters supplied.
(defgeneric make-button-for-rpm-window (window &key x y text action height width color)
(:documentation "Returns a button built with the parameters supplied"))
(defmethod make-button-for-rpm-window ((win rpm-virtual-window) &key (x 0) (y 0) (text "Ok") (action nil) (height 18) (width 60) (color 'gray))
(make-instance 'button-vdi
:x-pos x :y-pos y
:dialog-item-text text
:action action
:height height
:width width
:color color
:lock (window-lock win)))
(defmethod modify-button-for-rpm-window ((button-item button-vdi) &key (x nil xp) (y nil yp) (text nil textp) (height nil heightp) (width nil widthp) (color nil colorp) (action nil actionp))
"Modify a button item for the rpm window"
(bt:with-recursive-lock-held ((dialog-item-lock button-item))
(when xp
(setf (x-pos button-item) x))
(when yp
(setf (y-pos button-item) y))
(when textp
(setf (dialog-item-text button-item) text))
(when heightp
(setf (height button-item) height))
(when widthp
(setf (width button-item) width))
(when colorp
(setf (color button-item) color))
(when actionp
(setf (action-function button-item) action))
button-item))
(defmethod build-vis-locs-for ((self button-vdi))
(bt:with-recursive-lock-held ((dialog-item-lock self))
(let* ((line-height (max (round (text-height self) .8) (+ (text-height self) 1)))
(lines (1+ (count #\newline (dialog-item-text self))))
(view-loc (view-loc self))
(top (find-top-level-window self))
(top-xy (bt:with-recursive-lock-held ((window-lock top)) (vector (x-pos top) (y-pos top))))
(text-feats (build-string-feats :text (dialog-item-text self)
:start-x (px view-loc)
:x-fct (lambda (string startx obj)
(- startx
(round (dispatch-apply (str-width-fct obj) string) 2)))
:y-pos (round (- (py view-loc) (* 1/2 line-height (1- lines))))
:width-fct (str-width-fct self)
:height (text-height self)
:obj self
:line-height line-height
:x-off (px top-xy)
:y-off (py top-xy))))
;; set the text to be black
(dolist (f text-feats)
(push-last 'color f)
(push-last 'black f))
;; previously it set the approach width of the text chunks,
;; but can't do that since don't have a chunk here now.
;; Also, that was only actually correct if there was a single
;; text item co-located with the oval. Otherwise the angle was
;; off since the cursor was moving to the center of the text item.
#| (car feats was the oval chunk)
(let ((fun (lambda (x y) (declare (ignore x)) (approach-width (car feats) y vis-mod))))
(mapcar #'(lambda (f)
(setf (chunk-visual-approach-width-fn f) fun))
text-feats))
|#
;; return the oval which now has the text as its value if there is any
;; along with the text features
(append `((isa (visual-location oval)
screen-x ,(+ (px top-xy) (px view-loc))
screen-y ,(+ (py top-xy) (py view-loc))
width ,(width self)
height ,(height self)
value ,(if text-feats
`(oval ,(dialog-item-text self))
`(oval nil))
color ,(color self)))
text-feats))))
;;; MAKE-STATIC-TEXT-FOR-RPM-WINDOW [Method]
;;; Description : Build and return a static-text-dialog-item based on the
;;; : parameters supplied.
(defgeneric make-static-text-for-rpm-window (window &key x y text height width color)
(:documentation "Returns a text item built with the parameters supplied"))
(defmethod make-static-text-for-rpm-window ((win rpm-virtual-window) &key (x 0) (y 0) (text "")
(height 20) (width 80) (color 'black) font-size)
(unless (numberp font-size)
(setf font-size 12))
(make-instance 'static-text-vdi
:x-pos x :y-pos y
:dialog-item-text text
:height height
:width width
:color color
:text-height (round font-size 12/10)
:str-width-fct (let ((w (round font-size 12/7))) (lambda (str) (* (length str) w)))
:lock (window-lock win)))
(defmethod modify-text-for-rpm-window ((text-item static-text-vdi) &key (x nil xp) (y nil yp) (text nil textp) (height nil heightp) (width nil widthp) (color nil colorp) (font-size nil font-sizep))
"Modify a text item for the rpm window"
(bt:with-recursive-lock-held ((dialog-item-lock text-item))
(when xp
(setf (x-pos text-item) x))
(when yp
(setf (y-pos text-item) y))
(when textp
(setf (dialog-item-text text-item) text))
(when heightp
(setf (height text-item) height))
(when widthp
(setf (width text-item) width))
(when font-sizep
(setf (text-height text-item) (round font-size 12/10))
(setf (str-width-fct text-item) (let ((w (round font-size 12/7))) (lambda (str) (* (length str) w)))))
(when colorp
(setf (color text-item) color))
text-item))
(defmethod build-vis-locs-for ((self static-text-vdi))
(bt:with-recursive-lock-held ((dialog-item-lock self))
(let* ((line-height (max (round (text-height self) .8) (+ (text-height self) 1)))
(top (find-top-level-window self))
(top-xy (bt:with-recursive-lock-held ((window-lock top)) (vector (x-pos top) (y-pos top))))
(feats (build-string-feats :text (dialog-item-text self)
:start-x (1+ (x-pos self))
:y-pos (+ (y-pos self) (round line-height 2)) ;;(round (- (py (view-loc self)) (* 1/2 line-height (1- lines))))
:width-fct (str-width-fct self)
:height (text-height self)
:obj self
:line-height line-height
:x-off (px top-xy)
:y-off (py top-xy))))
(dolist (f feats)
(push-last 'color f)
(push-last (color self) f))
feats)))
;;; MAKE-LINE-FOR-RPM-WINDOW [Method]
;;; Description : Build and return the appropriate liner object for the
;;; : window based on the parameters supplied.
(defgeneric make-line-for-rpm-window (window start-pt end-pt &optional color)
(:documentation "returns a view which will draw a line with the parameters supplied"))
(defmethod make-line-for-rpm-window ((win rpm-virtual-window) start-pt end-pt &optional (color 'black))
(make-instance 'v-liner
:color color
:x-pos (first start-pt)
:y-pos (second start-pt)
:width (first end-pt)
:height (second end-pt)
:lock (window-lock win)))
(defmethod modify-line-for-rpm-window ((line v-liner) start-pt end-pt &key (color nil colorp))
(bt:with-recursive-lock-held ((dialog-item-lock line))
(when start-pt
(setf (x-pos line) (first start-pt))
(setf (y-pos line) (second start-pt)))
(when end-pt
(setf (width line) (first end-pt))
(setf (height line) (second end-pt)))
(when colorp
(setf (color line) color))
line))
(defun pts-to-orientation (pt1 pt2)
"Return the orientation of the line connecting two points, in degrees from -89 to +90. 0 is vertical."
(let ((angle (- (round (rad->deg (vtheta (xy-to-polar pt1 pt2)))) 90)))
(cond ((< angle -90) (+ angle 180))
((> angle 90) (- angle 180))
((= angle -90) 90)
(t angle))))
(defmethod build-vis-locs-for ((lnr v-liner))
"Convert the view to a feature to be placed into the visual icon"
(let* ((top (find-top-level-window lnr))
(top-xy (bt:with-recursive-lock-held ((window-lock top)) (vector (x-pos top) (y-pos top)))))
(bt:with-recursive-lock-held ((dialog-item-lock lnr))
`((isa (visual-location line)
color ,(color lnr)
value ,(pts-to-orientation
(vector (+ (px top-xy) (x-pos lnr))
(+ (py top-xy) (y-pos lnr)))
(vector (+ (px top-xy) (width lnr))
(+ (py top-xy) (height lnr))))
screen-x ,(+ (px top-xy) (floor (/ (+ (x-pos lnr) (width lnr)) 2)))
screen-y ,(+ (px top-xy) (floor (/ (+ (y-pos lnr) (height lnr)) 2)))
width ,(abs (- (x-pos lnr) (width lnr)))
height ,(abs (- (y-pos lnr) (height lnr)))
end1-x (nil ,(+ (px top-xy) (x-pos lnr)))
end1-y (nil ,(+ (py top-xy) (y-pos lnr)))
end2-x (nil ,(+ (px top-xy) (width lnr)))
end2-y (nil ,(+ (py top-xy) (height lnr))))))))
;;; VISIBLE-VIRTUALS-AVAILABLE? [Function]
;;; Description : Check with environment to determine if they're available.
(defun visible-virtuals-available? ()
"Return whether or not the visible-virtuals are available"
(and (fboundp 'check-with-environment-for-visible-virtuals)
(funcall 'check-with-environment-for-visible-virtuals)))
(add-act-r-command "visible-virtuals-available?" 'visible-virtuals-available? "Check whether there is a handler active for displaying visible virtual windows.")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 24,783 | Common Lisp | .lisp | 472 | 46.595339 | 197 | 0.600298 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2d7d9e4a83b7e7266bdf99022d0586e00ee852d2b16406232273d3089c559dbf | 14,301 | [
-1
] |
14,302 | random.lisp | asmaloney_ACT-R/framework/random.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : random.lisp
;;; Version : 2.0
;;;
;;; Description : Module that contains a pseudo-random number generator.
;;;
;;; Bugs :
;;;
;;; To do : Roll rand-time into the scheduling functions
;;; : Fill in the API details
;;;
;;; ----- History -----
;;;
;;; 2004.09.17 Dan
;;; : Creation
;;; 2005.01.04 Dan
;;; : Actually put a version of the Mersenne Twister in here.
;;; 2005.01.07 Dan
;;; : Restored rand-time and :randomize-time so it works the
;;; : way it used to in PM (for now).
;;; 2005.01.13 Dan
;;; : * Fixed an issue with how :seed set and reported values.
;;; : If one was set explicitly, it didn't always report that
;;; : same value back, but did properly reset the seed.
;;; : * Changed act-r-noise so it doesn't call random when s is
;;; : 0.
;;; 2005.02.10 Dan
;;; : * Changed log to log-coerced in act-r-noise.
;;; 2005.02.11 Dan
;;; : * Changed the declare in genrand_int32.
;;; 2005.10.19 Dan
;;; : * Slight change to genrand_int32 to give y an initial value
;;; : since the declare is a problem since y gets an initial
;;; : value of nil and CMUCL doesn't like that at all...
;;; 2006.01.17 Dan
;;; : * Updated the version to 1.0 since there haven't been any
;;; : problems it's time to drop the "a".
;;; 2006.08.11 Dan
;;; : * Adjusted randomize-time function and corresponding parameter
;;; : so that the param forces the value to be an integer thus
;;; : the check isn't needed in the function. Also doesn't
;;; : bother to do the rounding now since the scheduler does that
;;; : automatically, and simplified the number of math operation
;;; : necessary to get the time.
;;; 2006.09.11 Dan
;;; : * Take the unnecessary zerop test out of act-r-noise because
;;; : the plusp already rejects that case.
;;; 2009.09.10 Dan
;;; : * Moved permute-list here from the act-gui-interface.lisp file.
;;; 2011.09.02 Dan
;;; : * Wrapped an abs around the initial seed setting since some
;;; : Lisps (ACL 6.2 in the standalone in particular) were returning
;;; : a negative from get-internal-real-time for some reason.
;;; 2012.09.27 Dan
;;; : * Added a genrand_real2_L for internal use which specifies
;;; : the float as long for the division to avoid the situation
;;; : where the result is 1.0 due to the floating point size.
;;; : That's only used when the request is for an integer however
;;; : to avoid returning a different float type than asked for.
;;; : Thus, this only avoids (act-r-random INT) = INT errors not
;;; : (act-r-random FLOAT) = FLOAT if the default float size is
;;; : too small to represent 1 - 4294967295/4294967296.0. Of
;;; : course if the largest float size is too small to represent
;;; : that then errors are also still possible for integers too.
;;; 2015.08.13 Dan
;;; : * Basically eliminate rand-time and have it just print a warning
;;; : and return the time it was passed for now.
;;; 2015.08.17 Dan
;;; : * Added the randomize-time-ms function for randomizing times
;;; : that are in ms because they need to return integer results.
;;; : It's not quite the same as converting to seconds, randomizing
;;; : that, and then rounding back to milliseconds because that
;;; : is inefficient, but it's pretty close (the probability of
;;; : the extreme values in the range are uniform with this whereas
;;; : with the other method they aren't since they would be rounded
;;; : to milliseconds after the fact).
;;; 2017.01.11 Dan
;;; : * Adding dispatcher functions for act-r-random and permute-list.
;;; 2017.01.18 Dan
;;; : * Removed the echo-act-r-output from commands. The assumption
;;; : now is that echoing is handled by the user.
;;; : * Use handle-evaluate-results.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Reworked the local versions of the remote commands to not
;;; : go out through the dispatcher.
;;; 2017.06.01 Dan
;;; : * Changed how act-r-random checks for a current model and gets
;;; : the module to avoid the warnings when it has to default to
;;; : the default state.
;;; 2017.06.28 Dan
;;; : * Adding a lock on the module, make the global actually a
;;; : module and not just a mersenne-twister, and then add a
;;; : new global to serve as the default state.
;;; 2017.12.14 Dan
;;; : * Fix a typo in the doc string for permute-list.
;;; 2018.02.28 Dan
;;; : * Add remote commands for act-r-noise, randomize-time, and
;;; : randomize-time-ms.
;;; 2018.06.15 Dan
;;; : * Updated doc strings for consistency.
;;; 2018.08.27 Dan
;;; : * The incf in the constructor really should be protected by
;;; : a lock for safety so adding that.
;;; 2020.01.10 Dan [1.1]
;;; : * Removed the lambdas from the module interface functions
;;; : since that's not allowed in the general system now.
;;; 2020.08.25 Dan
;;; : * Replaced constants that had *...* with +...+ to avoid the
;;; : warnings in SBCL.
;;; : * Switch from defconstant to the define-constant macro to
;;; : avoid issues with SBCL (instead of redefining defconstant
;;; : for SBCL as was done previously).
;;; : * Specify an initial value and change the type for the array
;;; : to make SBCL happy...
;;; 2021.10.19 Dan [2.0]
;;; : * Set the :required flag on the module.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; act-r-random
;;;
;;; act-r-noise
;;;
;;; randomize-time
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; I chose to use the Mersenne Twister generator (as implemented in the C file
;;; mt19937ar.c) for the pseudorandom number generator. It is considered to
;;; be the best one available for Monte Carlo simulation and is currently the
;;; same one used already in ACL and CMUCL as well as being an option for
;;; LispWorks. So, putting it into the code for ACT-R in many cases doesn't
;;; even really change how the models will run since the same generator would
;;; have been used with random anyway.
;;;
;;; The big benefit is in being able to record the seed in a consistent cross-
;;; platform manner that is easy to work with instead of the Lisp specific
;;; *random-states*.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;(eval-when (:compile-toplevel :Load-toplevel :execute)
; (proclaim '(optimize (speed 3) (space 0) (saftey 0))))
;;; Start off with code for the pseudorandom number generator
(defvar *random-module-counter* -1)
(defvar *random-lock* (bt:make-lock "random-lock-count"))
(defstruct (mersenne-twister (:conc-name mt-))
(n 624 :type fixnum)
(m 397 :type fixnum)
(mti 625 :type fixnum)
(mt (make-array 624 :element-type '(or bignum integer) :initial-element 0) :type vector)
(count 0 :type integer)
(start (bt:with-lock-held (*random-lock*) (incf *random-module-counter*)) :type integer)
(initial-seed 5489 :type integer))
;; Some constants from the algorithm
(define-constant +matrix_a+ #x9908b0df)
(define-constant +upper_mask+ #x80000000)
(define-constant +lower_mask+ #x7fffffff)
;; Truncating numbers down to 32 bits with ldb so make this a constant
(define-constant +byte-32-0+ (byte 32 0))
;(defconstant *b1* (byte 1 31))
(defvar *default-random-state* (make-mersenne-twister))
;;; functions translated from the C code of mt19937ar.c and
;;; modified as necessary to take a state parameter.
(defun init_genrand (s &optional (state *default-random-state*))
(setf (svref (mt-mt state) 0) (ldb +byte-32-0+ s))
(setf (mt-mti state) 1)
(do ()
((= (mt-mti state) (mt-n state)))
(setf (svref (mt-mt state) (mt-mti state))
(ldb +byte-32-0+
(+ (* 1812433253
(logxor (svref (mt-mt state) (1- (mt-mti state)))
(ash (svref (mt-mt state) (1- (mt-mti state))) -30)))
(mt-mti state)))
)
(incf (mt-mti state))))
(defun init_by_array (init_key &optional (state *default-random-state*))
(init_genrand 19650218 state)
(let ((key_length (length init_key))
(i 1 )
(j 0 ))
(declare (fixnum i j))
(do ((k (if (> (mt-n state) key_length)
(mt-n state)
key_length)
(1- k)))
((zerop k))
(setf (svref (mt-mt state) i)
(ldb +byte-32-0+
(+ (logxor (svref (mt-mt state) i)
(* 1664525
(logxor (svref (mt-mt state) (1- i))
(ash (svref (mt-mt state) (1- i)) -30))))
(svref init_key j) j)))
(incf i)
(incf j)
(when (= j key_length)
(setf j 0))
(when (= i (mt-n state))
(setf (svref (mt-mt state) 0) (svref (mt-mt state) (1- (mt-n state))))
(setf i 1)))
(do ((k (1- (mt-n state))
(1- k)))
((zerop k))
(setf (svref (mt-mt state) i)
(ldb +byte-32-0+
(- (logxor (svref (mt-mt state) i)
(* 1566083941
(logxor (svref (mt-mt state) (1- i))
(ash (svref (mt-mt state) (1- i)) -30))))
i)))
(incf i)
(when (= i (mt-n state))
(setf (svref (mt-mt state) 0)
(svref (mt-mt state) (1- (mt-n state))))
(setf i 1)))
(setf (svref (mt-mt state) 0) #x80000000)))
;; Some different versions of the computation are included here
;; because I want to test them in different lisps/oss
(defun genrand_int32(&optional (state *default-random-state*))
(let ((y 0))
(declare (type integer y))
(when (>= (mt-mti state) (mt-n state))
(let ((kk 0))
(when (> (mt-mti state) (mt-n state))
(init_genrand 5489 state))
(do ()
((>= kk (- (mt-n state) (mt-m state))))
(setf y
;(logior (logand (svref mt kk) +upper_mask+)
; (ldb (byte 31 0) (svref mt (1+ kk))))
;(dpb (ldb *b1* (svref mt kk))
; *b1*
; (ldb (byte 31 0) (svref mt (1+ kk))))
(logior (logand (svref (mt-mt state) kk) +upper_mask+)
(logand (svref (mt-mt state) (1+ kk)) +lower_mask+))
)
(setf (svref (mt-mt state) kk)
(logxor (svref (mt-mt state) (+ kk (mt-m state)))
(ash y -1)
(if (zerop (logand y 1))
0
+matrix_a+)))
(incf kk))
(do ()
((>= kk (1- (mt-n state))))
(setf y
;(logior (logand (svref mt kk) +upper_mask+)
; (ldb (byte 31 0) (svref mt (1+ kk))))
;(dpb (ldb *b1* (svref mt kk))
; *b1*
; (ldb (byte 31 0) (svref mt (1+ kk))))
(logior (logand (svref (mt-mt state) kk) +upper_mask+)
(logand (svref (mt-mt state) (1+ kk)) +lower_mask+))
)
(setf (svref (mt-mt state) kk)
(logxor (svref (mt-mt state) (+ kk (- (mt-m state) (mt-n state))))
(ash y -1)
(if (zerop (logand y 1))
0
+matrix_a+)))
(incf kk))
(setf y
;(logior (logand (svref mt (1- *n*)) +upper_mask+)
; (ldb (byte 31 0) (svref mt 0)))
;(dpb (ldb *b1* (svref mt (1- *n*)))
; *b1*
; (ldb (byte 31 0) (svref mt 0)))
(logior (logand (svref (mt-mt state) (1- (mt-n state))) +upper_mask+)
(logand (svref (mt-mt state) 0) +lower_mask+))
)
(setf (svref (mt-mt state) (1- (mt-n state)))
(logxor (svref (mt-mt state) (1- (mt-m state)))
(ash y -1)
(if (zerop (logand y 1))
0
+matrix_a+)))
(setf (mt-mti state) 0)))
(setf y (svref (mt-mt state) (mt-mti state)))
(incf (mt-mti state))
(incf (mt-count state))
(setf y (logxor y (ash y -11)))
(setf y (logxor y (logand (ash y 7) #x9d2c5680)))
(setf y (logxor y (logand (ash y 15) #xefc60000)))
(setf y (logxor y (ash y -18)))
y))
(defun genrand_real2_L (&optional (state *default-random-state*))
(/ (genrand_int32 state) 4294967296.0L0))
(defun genrand_real2 (&optional (state *default-random-state*))
(/ (genrand_int32 state) 4294967296.0))
#|
This function should produce the same numbers as the 2000
in the test output file provided with mt19937ar.c -> mt19937ar.out.txt
(defun test-mt-generator ()
(let ((res1 nil)
(res2 nil)
(init (make-array 4 :initial-contents
'(#x123 #x234 #x345 #x456))))
(init_by_array init)
(dotimes (i 1000)
(push (genrand_int32) res1))
(dotimes (i 1000)
(push (genrand_real2) res2))
(list (reverse res1) (reverse res2))))
|#
;; Here's the actual module definition code
(defstruct act-r-random-module
state randomize-time (lock (bt:make-lock "random-lock")))
(defun create-random-module (ignore)
(declare (ignore ignore))
(let ((state (make-mersenne-twister)))
;; Here's where we initialize the thing - not in reset
;; since that defeats the purpose of having a good generator.
;; Use get-internal-real-time to randomly seed things.
;; However, get-internal-real-time may be > 32 bits and we also don't
;; want two modules having the same initial seed because they happened
;; to be created at the "same" time. So also add a count of modules
;; created so far to the time returned and if that is > 32 bits
;; build an array of numbers to do the initializing.
(setf (mt-initial-seed state)
(abs (+ (mt-start state)
(get-internal-real-time))))
(init-random-state-from-seed state (mt-initial-seed state))
(make-act-r-random-module :state state)))
(defun init-random-state-from-seed (state seed)
(if (<= (ceiling (log seed 2)) 32)
(init_genrand seed state)
(init_by_array (make-array
2 :initial-contents
(list (ldb (byte 32 0) seed)
(ldb (byte 32 32) seed)))
state)))
(defvar *default-random-module* (create-random-module nil))
(defun random-module-params (module param)
(bt:with-lock-held ((act-r-random-module-lock module))
(cond ((consp param)
(case (car param)
(:seed (unless (symbolp (cdr param))
;; ignore the case when it sends the "default"
(let ((seed (first (cdr param)))
(count (second (cdr param)))
(state (act-r-random-module-state module)))
(init-random-state-from-seed state seed)
(setf (mt-count state) 0)
(setf (mt-initial-seed state) seed)
(dotimes (i count)
(genrand_int32 state))
(list seed count))))
(:randomize-time (setf (act-r-random-module-randomize-time module)
(cdr param)))))
(t
(case param
(:seed (list (mt-initial-seed (act-r-random-module-state module))
(mt-count (act-r-random-module-state module))))
(:randomize-time (act-r-random-module-randomize-time module)))))))
(defun valid-random-module-seed (x)
(or (and (symbolp x) (eq x 'no-default))
(and (listp x)
(= (length x) 2)
(integerp (first x))
(not (minusp (first x)))
(integerp (second x))
(not (minusp (second x))))))
(defun valid-randomize-time-value (x)
(or (eq x t)
(null x)
(integerp x)))
(define-module-fct 'random-module nil
(list
(define-parameter :seed
:documentation "Current seed of the random number generator"
:valid-test 'valid-random-module-seed
:default-value 'no-default
:warning "a list of two non-negative integers"
)
(define-parameter :randomize-time
:valid-test 'valid-randomize-time-value
:default-value nil
:warning "T, nil, or an integer"
:documentation
"Allows the timing of certain actions to vary")
)
:version "2.0"
:documentation
"Provide a good and consistent source of pseudorandom numbers for all systems"
:creation 'create-random-module
; Don't need to do anything special on reset :reset ...
:params 'random-module-params
:required t)
(defun act-r-random (limit)
(if (and (numberp limit) (plusp limit))
(let ((module (if (current-model-struct)
(get-module random-module)
*default-random-module*)))
(bt:with-lock-held ((act-r-random-module-lock module))
(cond ((integerp limit)
(if (< limit #xffffffff)
(values (floor (* limit (genrand_real2_L (act-r-random-module-state module)))))
(let ((accum 0)
(nums (ceiling (/ (1+ (log limit 2)) 32))))
(dotimes (i nums)
(setf accum (+ (ash accum 32) (genrand_int32 (act-r-random-module-state module)))))
(mod accum limit))))
(t
(* limit (genrand_real2 (act-r-random-module-state module)))))))
(print-warning "Act-r-random called with an invalid value ~s" limit)))
(add-act-r-command "act-r-random" 'act-r-random "Return a random number up to limit using the current model's random stream. Params: limit." nil)
(defun act-r-noise (s)
"Approximates a sample from a normal distribution with mean zero and
the given s-value (/ (sqrt (* 3.0 variance)) 3.1416)."
;; Need to test bound because of short-float lack of precision
(if (and (numberp s) (plusp s))
(let ((p (max 0.0001 (min (act-r-random 1.0) 0.9999))))
(* s (log-coerced (/ (- 1.0 p) p))))
(print-warning "Act-r-noise called with an invalid s ~S" s)))
(add-act-r-command "act-r-noise" 'act-r-noise "Return a random sample from a logistic distribution with mean 0 and s value provided using the current model's random stream. Params: s-value." nil)
;;; Do it this way so that later it is easier
;;; to just disable rand-time and let the scheduler
;;; use randomize-time so that the modules don't have
;;; to be immediately cleaned up.
(defun randomize-time (time)
(if (numberp time)
(let ((rand-module (get-module random-module)))
(if rand-module
(let ((rand (bt:with-lock-held ((act-r-random-module-lock rand-module)) (act-r-random-module-randomize-time rand-module))))
(if (or (not rand) (zerop time))
time
(let* ((tscale (if (numberp rand) rand 3))) ;; default when t is 3
;; Old way
;(min (float (* time (/ (1- tscale) tscale))))
;(max (float (* time (/ (1+ tscale) tscale)))))
;(+ min (act-r-random (- max min))))
;; simplified
(* (/ time tscale) (+ tscale -1 (act-r-random 2.0))))))
time))
(progn
(print-warning "Invalid value passed to randomize-time: ~S" time)
time)))
(add-act-r-command "randomize-time" 'randomize-time "If :randomize-time is enabled return a random result from the uniform distribution from time - time/n to time + time/n where n is the :randomize-time value. Params: time." nil)
(defun randomize-time-ms (time)
(if (integerp time)
(let ((rand-module (get-module random-module)))
(if rand-module
(let ((rand (bt:with-lock-held ((act-r-random-module-lock rand-module)) (act-r-random-module-randomize-time rand-module))))
(if (or (not rand) (zerop time))
time
(let* ((tscale (if (numberp rand) rand 3)) ;; default w
(step (round time tscale)))
(+ time (- step) (act-r-random (+ 1 step step))))))
time))
(progn
(print-warning "Invalid value passed to randomize-time-ms: ~S. Value must be an integer." time)
time)))
(add-act-r-command "randomize-time-ms" 'randomize-time-ms "If :randomize-time is enabled return a random integer result from the uniform distribution from time - time/n to time + time/n where n is the :randomize-time value. Params: time." nil)
;;; PERMUTE-LIST [Function]
;;; Description : This function returns a randomly ordered copy of the passed
;;; : in list.
(defun permute-list (lis)
"Return a random permutation of the list"
(if (and (listp lis) lis)
(do* ((item (nth (act-r-random (length lis)) lis) (nth (act-r-random (length temp)) temp))
(temp (remove item lis :count 1) (remove item temp :count 1))
(result (list item) (cons item result)))
((null temp) result))
nil))
(add-act-r-command "permute-list" 'permute-list "Return a randomly ordered copy of the list provided using the current model's random stream. Params: list." nil)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 24,193 | Common Lisp | .lisp | 508 | 40.192913 | 243 | 0.558488 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | bb5a94481921bcc6a38a486d52b7336dd6a543ac1123ba5560803f48b3a4ccd6 | 14,302 | [
-1
] |
14,303 | model.lisp | asmaloney_ACT-R/framework/model.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : model.lisp
;;; Version : 4.1
;;;
;;; Description : Functions that support the abstraction of a model
;;;
;;; Bugs :
;;;
;;; To do : Finish the documentation.
;;;
;;; ----- History -----
;;;
;;; 2004.20.08 Dan
;;; : Creation
;;; 2005.01.12 Dan
;;; : Don't need to special case the device because it's now an
;;; : actual module.
;;; 2005.02.11 Dan
;;; : * Changed some reset-model to use clrhash instead of
;;; : creating new tables.
;;; 2005.02.28 Dan
;;; : * Made the with-model macro hygienic.
;;; 2005.03.23 Dan
;;; : * Update the model reset and creation to use the two reset
;;; : functions that are now part of the module definition - one
;;; : before the parameter are reset and one after.
;;; 2006.07.05 Dan
;;; : * Fixed a bug in the delete-model-fct function in the format
;;; : command for printing that there was no model.
;;; 2006.11.07 Dan
;;; : * Fixed a bug in delete-model which could result in the deleted
;;; : model being left as the current model after deletion.
;;; 2007.04.19 Dan
;;; : * Fixed another bug in delete-model which left the current-model
;;; : set even when the last model currently defined was deleted.
;;; 2008.08.21 Dan
;;; : * Added a new with-model-eval macro that sits half way between
;;; : the current macro and the -fct. This macro does evaluate the
;;; : first parameter to get the name, but splices in the body
;;; : to evaluate. Should be more convenient in many circumstances.
;;; 2008.10.22 Dan [1.0]
;;; : * Updated the reset function to handle the new chunk-ref table
;;; : and setting its flags to default values.
;;; : * Finally took the a1 off the version.
;;; 2008.12.01 Dan
;;; : * Added the code to call a third module reset function after
;;; : the user code has been evaled.
;;; 2008.12.08 Dan
;;; : * Added new-chunk-type-size and largest-chunk-type-size to
;;; : record and get the largest possible chunk size.
;;; 2008.12.15 Dan
;;; : * Added the code to call the third reset function when the
;;; : model is initially created too.
;;; 2009.09.09 Dan
;;; : * Updated reset-model to also clear the chunk-set from all of
;;; : the multi-buffers.
;;; 2009.10.08 Dan
;;; : * Updated define-model to clear the chunk-set as well since
;;; : reset doesn't happen at initial definition time.
;;; 2009.12.03 Dan
;;; : * Delete-model needs to take events out of the meta-process's
;;; : dynamics list as well.
;;; 2010.08.17 Dan
;;; : * Better cleanup in define-model when there's an error during
;;; : the definition code.
;;; 2010.11.16 Dan
;;; : * Added the :mcts and :mctrt system parameters for configuring
;;; : the model's chunk table because those can speed things up
;;; : significantly in some circumstances (for example ACL works
;;; : better with :mctrt of .6 and :mcts set large if there are
;;; : going to be a lot of chunks created).
;;; 2011.11.11 Dan
;;; : * Added a warning about model names that could cause problems
;;; : for the environment.
;;; 2012.02.06 Dan
;;; : * Added unsafe-define-model for my debugging purposes because
;;; : sometimes it's easier to fix things if the errors are unhandled.
;;; 2012.08.08 Dan
;;; : * Record the models as they are defined in meta-p-model-order
;;; : so things like reset can occur in the same order as when
;;; : initially created for consistency.
;;; 2013.01.04 Dan
;;; : * Added unwind-protect to reset- and delete- model so that the
;;; : current model always gets restored (define model doesn't need
;;; : it since it has other protection and doesn't just restore the
;;; : "last" model anyway).
;;; : * Added a check to define-model to prevent it from creating a
;;; : new model when it's not valid to do so based on meta-p-cannot-define-model
;;; : and added the cannot-define-model calls to places that need
;;; : to be protected.
;;; 2013.01.07 Dan
;;; : * Changed the test on cannot-define-model to be >0 instead of
;;; : just true.
;;; 2014.02.24 Dan [2.0]
;;; : * Don't bother creating the chunk-type chunk since it's
;;; : automatic now.
;;; : * Largest chunk-type size is total slot count (not the most
;;; : efficient method, but go with it for now).
;;; 2014.05.16 Dan
;;; : * Added more default chunk types: constant-chunk and clear.
;;; : constant-chunk specifies a name slot which can then be used
;;; : to prevent chunks from merging to avoid oddities like free
;;; : and busy merging! Clear has one slot named clear with a
;;; : default value of t and it can be used by modules that need
;;; : a "clear" request without having to define it in the module.
;;; : * All the default chunks now use the name slot to prevent
;;; : possible merging. The chunk-name is set in the slot to
;;; : avoid that. It does change the fan of those items relative
;;; : to the older ACT-R versions if they're used in slots of DM
;;; : chunks and spreading activation is on, but the fan of those
;;; : things shouldn't have been important anyway.
;;; 2014.06.25 Dan
;;; : * Change the definition for the type chunk since subtype info
;;; : isn't kept anymore.
;;; : * Set the act-r-chunk-type-info-types list to (chunks) on a
;;; : reset.
;;; 2014.09.26 Dan
;;; : * Instead of maphashing over global-modules-table dolist over
;;; : all-module-names because that guarantees ordering.
;;; 2014.11.07 Dan
;;; : * Adding another default chunk-type to specify the default
;;; : query slots as valid: (chunk-type query-slots state buffer error).
;;; 2015.03.19 Dan
;;; : * Resetting a model now needs to clear the buffer flags as well.
;;; : * Failure needs to be the name of a default chunk.
;;; 2015.09.09 Dan [3.0]
;;; : * Model now keeps track of requests made to modules when asked
;;; : and can report on whether or not a request has "completed".
;;; 2015.12.16 Dan
;;; : * All of the "completing" functions now return t as long as
;;; : there is a model and meta-process regardless of whether or
;;; : not the params matched something previously uncompleted.
;;; 2017.03.30 Dan
;;; : * Replaced meta-p-current-model usage with *current-act-r-model*.
;;; 2017.06.02 Dan
;;; : * Cleaned up some issues with the "current model" setting and
;;; : use.
;;; : * Delete-model needs to call the component delete hooks since
;;; : they may need access to the model's modules before they're
;;; : gone.
;;; 2017.06.15 Dan
;;; : * Lock access to the modules table.
;;; : * Only evaluate current-model-struct once in current-model.
;;; 2017.06.20 Dan
;;; : * Protect the chunk-type-info access with its lock.
;;; : * Protect the chunk tables with a lock.
;;; 2017.06.21 Dan
;;; : * Protect the 'chunk updateing" slots with a lock.
;;; 2017.06.22 Dan
;;; : * Protecting meta-p-models and meta-p-events with the lock.
;;; 2017.06.29 Dan
;;; : * Lock access to the global buffer-table and the model's buffers.
;;; : * Protect the access to the global parameters table.
;;; : * Changed valid-model-name to return the struct on success and
;;; : adjusted the with-model-* commands accordingly to avoid the
;;; : double lock and gethash.
;;; 2017.07.13 Dan
;;; : * Lock the buffer itself when modifying things during reset.
;;; 2017.07.14 Dan
;;; : * Protect access to the meta-p-component-list.
;;; 2017.08.24 Dan
;;; : * Add signals for the three model reset points.
;;; 2017.08.29 Dan
;;; : * Fixed copy and paste error with last update that only called
;;; : reset-step1 3 times...
;;; 2017.11.01 Dan
;;; : * Adding a switch for :standalone that doesn't invoke the
;;; : debugger when running the standalone version for an error
;;; : in the model definition because if that reload happens in
;;; : another thread (called from Tcl/Tk or Python) then CCL can
;;; : get stuck with the "type (:y #)" to switch to that process
;;; : message but not let you actually type it...
;;; 2017.11.03 Dan
;;; : * Still want to print the error message from the standalone
;;; : with the previous change.
;;; 2017.12.07 Dan
;;; : * Starting work needed to allow for remote modules.
;;; 2017.12.08 Dan
;;; : * Added remote versions of the complete request functions.
;;; : * Added a remote current-model, but not sure that it'll really
;;; : do the 'right' thing.
;;; 2018.02.05 Dan
;;; : * Don't directly access the meta-process events.
;;; 2018.04.13 Dan
;;; : * The buffer-lock is now recursive.
;;; 2018.04.24 Dan
;;; : * Use top-level-load? to check before invoking the debugger
;;; : since can't invoke it from a dispatched thread.
;;; 2018.06.08 Dan
;;; : * Tracking a request now returns an id instead of the chunk-spec
;;; : since that's safe to use through the dispatcher.
;;; 2018.06.13 Dan
;;; : * Updated the doc strings for remote commands and removed
;;; : a few verify-current-mp calls.
;;; 2018.07.26 Dan
;;; : * Added remote request-completed-p.
;;; 2019.02.05 Dan
;;; : * Adjustments because meta-p-models is now an alist.
;;; 2019.02.13 Dan
;;; : * The model now holds a bitvector indicating which buffers
;;; : currently have chunks in them.
;;; 2019.03.13 Dan
;;; : * The act-r-chunk-type-info-slot->mask table isn't used anymore.
;;; 2019.04.03 Dan
;;; : * Store the instance of the module in the buffer struct when
;;; : creating a model and also in a list to use upon reset (so
;;; : it doesn't need to pull them from the hash-table).
;;; 2019.11.08 Dan
;;; : * Moved the *define-model-lock* to the meta-process file and
;;; : added a global variable to go with it that indicates it's
;;; : currently inside a model manipulation function to allow the
;;; : running cmds to check and not run in the body of a model.
;;; 2019.11.20 Dan
;;; : * Need to clear the act-r-chunk-type-info-query-slots list
;;; : when resetting to maintain consistency since they're also
;;; : being added to the slot table too.
;;; 2020.06.01 Dan [4.0]
;;; : * Allow chunk-types and chunks to be defined during module
;;; : creation functions and then cache all the chunk-type and
;;; : chunk information after creation for reapplication during
;;; : reset (much faster than redefining every time).
;;; : * Any chunk defined at creation time is automatically marked
;;; : as immutable.
;;; 2021.06.03 Dan [4.1]
;;; : * Set the reuse? flag for the buffers at init and reset and
;;; : create the initial chunk for the buffer.
;;; 2021.06.09 Dan
;;; : * Don't actually create the initial chunk for the buffers
;;; : because that's a big performance hit for tasks that run a
;;; : non-learning short trial & reset approach (fan model in the
;;; : tutorial for example).
;;; 2021.07.16 Dan
;;; : * Only set the reuse? flag if it's not a multi buffer.
;;; : * Delete-model wasn't returning t on success.
;;; 2021.10.14 Dan [5.0]
;;; : * Only record the modules and buffers that are actually
;;; : instantiated.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Model structure is not for use outside of the framework.
;;;
;;; Note possible unsafe condition with respect to threading because a run could
;;; be started after the define-model call checks. Ignoring that for now because
;;; it's likely a low probability situation.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;; define-model
;;;
;;; (defmacro define-model (name &body model-code))
;;; (defun define-model-fct (name model-code-list))
;;;
;;; name a symbol that will be the name for the new model
;;; model-code any number of forms that will be evaluated for the model
;;; model-code-list a list of forms to evaluate for the model
;;;
;;; define-model is used to create a new model in the current meta-process.
;;;
;;; The name must not already be used for a model in the current meta-process. If the name is not a symbol or is already used to name a model in the current meta-process a warning will be displayed and the model will not be defined (the old model with that name will remain unchanged if one existed).
;;;
;;; When a model is first defined the following sequence of events will occur:
;;;
;;; - Create a new model with that name
;;; - with that new model as the current model
;;; - create the default chunk-types
;;; - create the default chunks
;;; - create a new instance of each module
;;; - call its create function if it exists
;;; - call its reset function if it exists
;;; - evaluate the forms of the model in the order provided
;;;
;;; If a model is successfully created then its name is returned otherwise define-model returns nil.
;;;
;;; Every model will need to have a call to define-model before issuing any of the model commands because there is no default model in a meta-process. However, if one is working with only a single model then all that is necessary is to provide a name - it is not necessary to enclose all of the model code.
;;;
;;; current-model
;;;
;;; (defun current-model ())
;;;
;;; current-model returns the name of the current model in the current meta-process or nil if there is no current model or no current meta-process.
;;;
;;; delete-model
;;;
;;; (defmacro delete-model (&optional model-name))
;;; (defun delete-model-fct (&optional model-name))
;;;
;;; model-name a symbol that names a model
;;;
;;; If model-name is not provided the name of the current-model is used.
;;;
;;; If model-name is the name of a model in the current meta-process then the following sequence of events will occur:
;;;
;;; - the model with that name is set to the current model
;;; - all events generated by that model are removed from the event queue
;;; - each module of the model is deleted
;;; - the model is removed from the set of models in the current meta-process
;;;
;;; If model-name is valid then t is returned.
;;;
;;; If model-name is not valid or there is no current meta-process then a warning is printed, nothing is done and nil is returned.
;;;
;;; with-model
;;;
;;; (defmacro with-model (model-name &body body))
;;; (defun with-model-fct (model-name forms-list))
;;;
;;; model-name a symbol that names a model in the current meta-process
;;; body any number of forms to execute
;;; forms-list a list of forms to execute
;;;
;;; If model-name is the name of a model in the current meta-process then the forms are evaluated in order with the current model set to the one named by model-name. The value of the last form evaluated is returned.
;;;
;;; If model-name does not name a model in the current meta-process, or there is no current meta-process then none of the forms are evaluated, a warning is printed and nil is returned.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function (t) t) id-to-chunk-spec))
(defun current-model ()
(awhen (current-model-struct)
(act-r-model-name it)))
(add-act-r-command "current-model" 'current-model "Get the name of the current model if there is one. No params.")
(defun largest-chunk-type-size ()
(let ((info (act-r-model-chunk-types-info (current-model-struct))))
(bt:with-recursive-lock-held ((act-r-chunk-type-info-lock info))
(act-r-chunk-type-info-size info))))
(defvar *model-chunk-table-size* nil)
(defvar *model-chunk-table-rehash-threshold* nil)
(create-system-parameter :mcts :valid-test 'posnumornil :default-value nil :warning "positive number or nil"
:documentation "initial size of a model's chunk table"
:handler (simple-system-param-handler *model-chunk-table-size*))
(create-system-parameter :mctrt :valid-test (lambda (x) (typep x '(or null (real 0 1)))) :default-value nil
:warning "a real number [0-1] or nil"
:documentation "rehash-threshold of a model's chunk table"
:handler (simple-system-param-handler *model-chunk-table-rehash-threshold*))
(defmacro define-model (name &body model-code)
`(define-model-fct ',name ',model-code))
(defun define-model-fct (name model-code-list)
(verify-current-mp
"define-model called with no current meta-process."
(bt:with-lock-held (*define-model-lock*)
(unwind-protect
(progn
(setf *defining-model* t)
(cond ((not (symbolp name))
(print-warning "Model name must be a symbol, ~S is not valid. No model defined." name))
((null name)
(print-warning "Nil is not a valid name for a model. No model defined."))
((valid-model-name name)
(print-warning "~S is already the name of a model in the current meta-process. Cannot be redefined." name))
((mp-running?)
(print-warning "Cannot define a model while the system is running."))
(t
(when (some (lambda (x) (find x (symbol-name name))) (list #\$ #\{ #\} #\[ #\]))
(print-warning "Model names that contain any of the characters $, {, }, [, or ] may not work correctly with the ACT-R Environment."))
(let ((new-model (make-act-r-model :name name))
(mp (current-mp)))
(let ((*current-act-r-model* new-model))
(when (or *model-chunk-table-size* *model-chunk-table-rehash-threshold*)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock new-model))
(if *model-chunk-table-size*
(if *model-chunk-table-rehash-threshold*
(progn
(setf (act-r-model-chunks-table new-model) (make-hash-table :size *model-chunk-table-size* :rehash-threshold *model-chunk-table-rehash-threshold*))
(setf (act-r-model-chunk-ref-table new-model) (make-hash-table :size *model-chunk-table-size* :rehash-threshold *model-chunk-table-rehash-threshold*)))
(progn
(setf (act-r-model-chunks-table new-model) (make-hash-table :size *model-chunk-table-size*))
(setf (act-r-model-chunk-ref-table new-model) (make-hash-table :size *model-chunk-table-size*))))
(progn
(setf (act-r-model-chunks-table new-model) (make-hash-table :rehash-threshold *model-chunk-table-rehash-threshold*))
(setf (act-r-model-chunk-ref-table new-model) (make-hash-table :rehash-threshold *model-chunk-table-rehash-threshold*))))))
(add-new-model name new-model)
(create-model-default-chunk-types new-model)
(create-model-default-chunks)
(bt:with-lock-held ((act-r-model-modules-lock new-model))
(dolist (module-name (all-module-names))
(let ((i (instantiate-module module-name name)))
(when i
(push-last i (act-r-model-module-instances new-model))
(setf (gethash module-name (act-r-model-modules-table new-model)) i))))
;; cache the starting chunk-type information
(let ((info (act-r-model-chunk-types-info new-model)))
(bt:with-recursive-lock-held ((act-r-chunk-type-info-lock info))
(setf (act-r-model-starting-slot-vector new-model)
(copy-seq (act-r-chunk-type-info-index->slot info)))
(setf (act-r-model-starting-ct-size new-model) (act-r-chunk-type-info-size info))
(setf (act-r-model-starting-slot-structs new-model)
(let ((r nil))
(maphash (lambda (k v)
(push-last (cons k v) r))
(act-r-chunk-type-info-slot->index info))
r))
(setf (act-r-model-starting-chunk-types new-model)
(mapcar (lambda (x)
(cons x (deep-copy-act-r-chunk-type (gethash x (act-r-chunk-type-info-table info)))))
(act-r-chunk-type-info-types info)))
(setf (act-r-model-starting-distinct-types new-model)
(maphash (lambda (k v)
(cons k (copy-list v)))
(act-r-chunk-type-info-distinct-types info)))))
;; cache the starting chunk information and make them all immutable
(setf (act-r-model-initial-chunks new-model)
(let ((chunks nil))
(maphash (lambda (c s)
(bt:with-recursive-lock-held ((act-r-chunk-lock s))
(push (list c (act-r-chunk-documentation s) (act-r-chunk-filled-slots s) (act-r-chunk-slot-value-lists s))
chunks)
(setf (act-r-chunk-immutable s) t)))
(act-r-model-chunks-table new-model))
chunks))
;; instantiate the buffers
(bt:with-lock-held (*buffers-table-lock*)
(bt:with-lock-held ((act-r-model-buffers-lock new-model))
(maphash (lambda (buffer-name buffer-struct)
(let ((module (gethash (act-r-buffer-module buffer-struct) (act-r-model-modules-table new-model))))
(when module
(let ((buffer (copy-act-r-buffer buffer-struct)))
(setf (act-r-buffer-module-instance buffer)
(gethash (act-r-buffer-module buffer) (act-r-model-modules-table new-model)))
(when (act-r-buffer-multi buffer)
(setf (act-r-buffer-chunk-set buffer) (make-hash-table :test 'eq :size 5)))
(dolist (x (act-r-buffer-requests buffer))
(add-request-parameter x)
(setf (act-r-buffer-requests-mask buffer) (logior (slot-name->mask x) (act-r-buffer-requests-mask buffer))))
(dolist (x (act-r-buffer-queries buffer))
(add-buffer-query x))
(unless (act-r-buffer-multi buffer)
(setf (act-r-buffer-reuse? buffer) t))
(setf (act-r-buffer-reuse-chunk buffer) nil)
(setf (gethash buffer-name (act-r-model-buffers new-model)) buffer)))))
*buffers-table*))))
(dolist (m (act-r-model-module-instances new-model))
(reset-module m))
#|;; Just set all the reusable slots to nil above instead of setting
them here (here because naming module needs to be reset) since
it's an added cost to do this for a buffer that doesn't get a chunk in the
model
(bt:with-lock-held ((act-r-model-buffers-lock new-model))
(maphash (lambda (buffer-name buffer-struct)
(let ((name (new-name-fct (format nil "~s-buffer-chunk" buffer-name))))
(define-chunks-fct (list name))
(make-chunk-reusable name)
(setf (act-r-buffer-reuse-chunk buffer-struct) name)))
(act-r-model-buffers new-model)))
|#
(maphash (lambda (parameter-name parameter)
(when (gethash (act-r-parameter-owner parameter) (act-r-model-modules-table new-model))
(push (list parameter-name (act-r-parameter-default parameter)) (act-r-model-params new-model))
(sgp-fct (list parameter-name (act-r-parameter-default parameter)))))
(bt:with-lock-held (*parameters-table-lock*) *act-r-parameters-table*))
(dolist (m (act-r-model-module-instances new-model))
(secondary-reset-module m))
(let ((errored nil))
(dolist (form model-code-list)
(unwind-protect
(handler-case (eval form)
(error (condition)
(setf errored t)
(print-warning "Error encountered in model form:~%~S~%" form)
#-:standalone (let ((sub-load (not (top-level-load?))))
(if sub-load
(print-warning "~/print-error-message/" condition)
(progn
(print-warning "Invoking the debugger.")
(print-warning "You must exit the error state to continue.")
(invoke-debugger condition))))
#+:standalone (print-warning "~/print-error-message/" condition)
))
(when errored
(remove-model name)
(print-warning "Model ~s not defined." name)
;; delete any events that may have been scheduled by modules
;; or code prior to the error
(delete-all-model-events mp name)
;; remove the modules which were created
(dolist (module-name (hash-table-keys (act-r-model-modules-table new-model)))
(delete-module module-name))
(return-from define-model-fct nil)))))
(setf (act-r-model-code new-model) model-code-list)
(dolist (m (act-r-model-module-instances new-model))
(tertiary-reset-module m)))
name))))
(setf *defining-model* nil)))))
(defmacro unsafe-define-model (name &body model-code)
`(unsafe-define-model-fct ',name ',model-code))
(defun unsafe-define-model-fct (name model-code-list)
(verify-current-mp
"define-model called with no current meta-process."
(bt:with-lock-held (*define-model-lock*)
(unwind-protect
(progn
(setf *defining-model* t)
(cond ((not (symbolp name))
(print-warning "Model name must be a symbol, ~S is not valid. No model defined." name))
((null name)
(print-warning "Nil is not a valid name for a model. No model defined."))
((valid-model-name name)
(print-warning "~S is already the name of a model in the current meta-process. Cannot be redefined." name))
((mp-running?)
(print-warning "Cannot define a model while the system is running."))
(t
(when (some (lambda (x) (find x (symbol-name name))) (list #\$ #\{ #\} #\[ #\]))
(print-warning "Model names that contain any of the characters $, {, }, [, or ] may not work correctly with the ACT-R Environment."))
(let ((new-model (make-act-r-model :name name)))
(let ((*current-act-r-model* new-model))
(when (or *model-chunk-table-size* *model-chunk-table-rehash-threshold*)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock new-model))
(if *model-chunk-table-size*
(if *model-chunk-table-rehash-threshold*
(progn
(setf (act-r-model-chunks-table new-model) (make-hash-table :size *model-chunk-table-size* :rehash-threshold *model-chunk-table-rehash-threshold*))
(setf (act-r-model-chunk-ref-table new-model) (make-hash-table :size *model-chunk-table-size* :rehash-threshold *model-chunk-table-rehash-threshold*)))
(progn
(setf (act-r-model-chunks-table new-model) (make-hash-table :size *model-chunk-table-size*))
(setf (act-r-model-chunk-ref-table new-model) (make-hash-table :size *model-chunk-table-size*))))
(progn
(setf (act-r-model-chunks-table new-model) (make-hash-table :rehash-threshold *model-chunk-table-rehash-threshold*))
(setf (act-r-model-chunk-ref-table new-model) (make-hash-table :rehash-threshold *model-chunk-table-rehash-threshold*))))))
(add-new-model name new-model)
(create-model-default-chunk-types new-model)
(create-model-default-chunks)
(bt:with-lock-held ((act-r-model-modules-lock new-model))
(dolist (module-name (all-module-names))
(let ((i (instantiate-module module-name name)))
(when i
(push-last i (act-r-model-module-instances new-model))
(setf (gethash module-name (act-r-model-modules-table new-model)) i))))
;; cache the starting chunk-type information
(let ((info (act-r-model-chunk-types-info new-model)))
(bt:with-recursive-lock-held ((act-r-chunk-type-info-lock info))
(setf (act-r-model-starting-slot-vector new-model)
(copy-seq (act-r-chunk-type-info-index->slot info)))
(setf (act-r-model-starting-ct-size new-model) (act-r-chunk-type-info-size info))
(setf (act-r-model-starting-slot-structs new-model)
(let ((r nil))
(maphash (lambda (k v)
(push-last (cons k v) r))
(act-r-chunk-type-info-slot->index info))
r))
(setf (act-r-model-starting-chunk-types new-model)
(mapcar (lambda (x)
(cons x (deep-copy-act-r-chunk-type (gethash x (act-r-chunk-type-info-table info)))))
(act-r-chunk-type-info-types info)))
(setf (act-r-model-starting-distinct-types new-model)
(maphash (lambda (k v)
(cons k (copy-list v)))
(act-r-chunk-type-info-distinct-types info)))))
;; cache the starting chunk information and make them all immutable
(setf (act-r-model-initial-chunks new-model)
(let ((chunks nil))
(maphash (lambda (c s)
(bt:with-recursive-lock-held ((act-r-chunk-lock s))
(push (list c (act-r-chunk-documentation s) (act-r-chunk-filled-slots s) (act-r-chunk-slot-value-lists s))
chunks)
(setf (act-r-chunk-immutable s) t)))
(act-r-model-chunks-table new-model))
chunks))
;; instantiate the buffers
(bt:with-lock-held (*buffers-table-lock*)
(bt:with-lock-held ((act-r-model-buffers-lock new-model))
(maphash (lambda (buffer-name buffer-struct)
(let ((module (gethash (act-r-buffer-module buffer-struct) (act-r-model-modules-table new-model))))
(when module
(let ((buffer (copy-act-r-buffer buffer-struct)))
(setf (act-r-buffer-module-instance buffer)
module)
(when (act-r-buffer-multi buffer)
(setf (act-r-buffer-chunk-set buffer) (make-hash-table :test 'eq :size 5)))
(dolist (x (act-r-buffer-requests buffer))
(add-request-parameter x)
(setf (act-r-buffer-requests-mask buffer) (logior (slot-name->mask x) (act-r-buffer-requests-mask buffer))))
(dolist (x (act-r-buffer-queries buffer))
(add-buffer-query x))
(unless (act-r-buffer-multi buffer)
(setf (act-r-buffer-reuse? buffer) t))
(setf (act-r-buffer-reuse-chunk buffer) nil)
(setf (gethash buffer-name (act-r-model-buffers new-model)) buffer)))))
*buffers-table*))))
(dolist (m (act-r-model-module-instances new-model))
(reset-module m))
#| ;; Create the reusable chunks for the buffers (needs to happen after naming module reset)
(bt:with-lock-held ((act-r-model-buffers-lock new-model))
(maphash (lambda (buffer-name buffer-struct)
(let ((name (new-name-fct (format nil "~s-buffer-chunk" buffer-name))))
(define-chunks-fct (list name))
(make-chunk-reusable name)
(setf (act-r-buffer-reuse-chunk buffer-struct) name)))
(act-r-model-buffers new-model)))
|#
(maphash (lambda (parameter-name parameter)
(when (gethash (act-r-parameter-owner parameter) (act-r-model-modules-table new-model))
(push (list parameter-name (act-r-parameter-default parameter)) (act-r-model-params new-model))
(sgp-fct (list parameter-name (act-r-parameter-default parameter)))))
(bt:with-lock-held (*parameters-table-lock*) *act-r-parameters-table*))
(dolist (m (act-r-model-module-instances new-model))
(secondary-reset-module m))
(dolist (form model-code-list)
(eval form))
(setf (act-r-model-code new-model) model-code-list)
(dolist (m (act-r-model-module-instances new-model))
(tertiary-reset-module m)))
name))))
(setf *defining-model* nil)))))
(defun create-model-default-chunk-types (model)
(let ((info (act-r-model-chunk-types-info model))
(c (make-act-r-chunk-type :name 'chunk :super-types (list 'chunk))))
(bt:with-recursive-lock-held ((act-r-chunk-type-info-lock info))
(setf (gethash 'chunk (act-r-chunk-type-info-table info)) c)
(setf (gethash 0 (act-r-chunk-type-info-distinct-types info)) (list (cons nil (list 'chunk))))
(setf (act-r-chunk-type-info-types info) (list 'chunk))))
(chunk-type constant-chunks name)
(chunk-type clear (clear t))
(chunk-type query-slots state buffer error))
(defun create-model-default-chunks ()
(dolist (x '(free busy error empty full failure requested unrequested))
(define-chunks-fct `((,x name ,x))))
(define-chunks (clear isa clear)))
(defmacro delete-model (&optional (model-name nil provided))
`(if ,provided
(delete-model-fct ',model-name)
(delete-model-fct (current-model))))
(defun delete-model-fct (model-name)
(verify-current-mp
"delete-model called with no current meta-process.~%No model deleted."
(let ((mp (current-mp)))
(if model-name
(aif (cdr (assoc model-name (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-models mp))))
(progn
(bt:with-lock-held (*define-model-lock*)
(unwind-protect
(let ((*current-act-r-model* it))
(setf *defining-model* t)
(delete-all-model-events mp model-name)
(dolist (c (bt:with-lock-held ((meta-p-component-lock (current-mp))) (meta-p-component-list (current-mp))))
(when (act-r-component-model-destroy (cdr c))
(funcall (act-r-component-model-destroy (cdr c)) (act-r-component-instance (cdr c)) model-name)))
(unwind-protect
(dolist (module-name (hash-table-keys (act-r-model-modules-table it)))
(delete-module module-name))
(remove-model model-name)))
t)
(setf *defining-model* nil))
t)
(print-warning "No model named ~S in current meta-process." model-name))
(print-warning "No current model to delete.")))))
(defmacro with-model (model-name &body body)
(let ((mp (gensym))
(model (gensym)))
`(let ((,mp (current-mp)))
(if ,mp
(let ((,model (valid-model-name ',model-name)))
(if ,model
(let ((*current-act-r-model* ,model))
,@body)
(print-warning "~S does not name a model in the current meta-process" ',model-name)))
(print-warning "No actions taken in with-model because there is no current meta-process")))))
(defmacro with-model-eval (model-name &body body)
(let ((mp (gensym))
(model (gensym)))
`(let ((,mp (current-mp)))
(if ,mp
(let ((,model (valid-model-name ,model-name)))
(if ,model
(let ((*current-act-r-model* ,model))
,@body)
(print-warning "~S does not name a model in the current meta-process" ,model)))
(print-warning "No actions taken in with-model because there is no current meta-process")))))
(defun with-model-fct (model-name forms-list)
(let ((mp (current-mp)))
(if mp
(let ((model (valid-model-name model-name)))
(if model
(let ((*current-act-r-model* model)
(val nil))
(dolist (x forms-list val)
(setf val (eval x))))
(print-warning "~S does not name a model in the current meta-process" model-name)))
(print-warning "No actions taken in with-model because there is no current meta-process"))))
(defun valid-model-name (name)
"Returns struct if name is the name of a model in the current meta-process - there must be a current mp"
(cdr (assoc name (bt:with-lock-held ((meta-p-models-lock (current-mp))) (meta-p-models (current-mp))))))
(add-act-r-command "reset-step1" nil "Signal for the primary model reset point (before default parameters are set, modules primary resets, and code evaluated) for monitoring purposes. No params." nil)
(add-act-r-command "reset-step2" nil "Signal for the secondary model reset point (after default parameters are set but before modules secondary resets and code evaluated) for monitoring purposes. No params." nil)
(add-act-r-command "reset-step3" nil "Signal for the tertiary model reset point (after code evaluated but before model tertiary resets) for monitoring purposes. No params." nil)
(defun reset-model (mp model)
(declare (ignore mp))
(let ((*current-act-r-model* model))
(bt:with-lock-held (*define-model-lock*)
(unwind-protect
(let ((info (act-r-model-chunk-types-info model)))
(setf *defining-model* t)
;; erase chunk-type info
(bt:with-recursive-lock-held ((act-r-chunk-type-info-lock info))
(clrhash (act-r-chunk-type-info-slot->index info))
(mapcar (lambda (x)
(setf (gethash (car x) (act-r-chunk-type-info-slot->index info))
(cdr x)))
(act-r-model-starting-slot-structs model))
(setf (act-r-chunk-type-info-index->slot info) (make-array (list 0) :adjustable t :fill-pointer t))
(map nil (lambda (x) (vector-push-extend x (act-r-chunk-type-info-index->slot info)))
(act-r-model-starting-slot-vector model))
(setf (act-r-chunk-type-info-size info) (act-r-model-starting-ct-size model))
(clrhash (act-r-chunk-type-info-distinct-types info))
(dolist (x (act-r-model-starting-distinct-types model))
(setf (gethash (car x) (act-r-chunk-type-info-distinct-types info))
(copy-list (cdr x))))
(setf (act-r-chunk-type-info-extended-slots info) nil)
(setf (act-r-chunk-type-info-query-slots info) nil)
(clrhash (act-r-chunk-type-info-table info))
(setf (act-r-chunk-type-info-types info) nil)
(dolist (x (act-r-model-starting-chunk-types model))
(push-last (car x) (act-r-chunk-type-info-types info))
(setf (gethash (car x) (act-r-chunk-type-info-table info))
(deep-copy-act-r-chunk-type (cdr x)))))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(setf (act-r-model-chunk-update model) t)
(setf (act-r-model-dynamic-update model) t)
(setf (act-r-model-delete-chunks model) nil))
;; initialize the tables and recreate the starting chunk structs
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(clrhash (act-r-model-chunks-table model))
(clrhash (act-r-model-chunk-ref-table model))
(bt:with-lock-held (*chunk-parameters-lock*)
(dolist (c (act-r-model-initial-chunks model))
(setf (gethash (first c) (act-r-model-chunks-table model))
(make-act-r-chunk
:name (first c)
:merged-chunks (list (first c))
:documentation (second c)
:filled-slots (third c)
:slot-value-lists (fourth c)
:immutable t
:parameter-values (make-array *chunk-parameters-count*
:initial-element *chunk-parameter-undefined*)))))
;; update the back-links data
(dolist (c (act-r-model-initial-chunks model))
(dolist (s (fourth c))
(when (gethash (cdr s) (act-r-model-chunks-table model))
(let ((bl (gethash (cdr s) (act-r-model-chunk-ref-table model))))
(if (hash-table-p bl)
(push (act-r-slot-name (car s)) (gethash (first c) bl))
(let ((ht (make-hash-table)))
(setf (gethash (first c) ht) (list (act-r-slot-name (car s))))
(setf (gethash (cdr s) (act-r-model-chunk-ref-table model)) ht))))))))
(bt:with-lock-held ((act-r-model-buffers-lock model))
(setf (act-r-model-buffer-state model) 0)
(maphash (lambda (buffer-name buffer)
(declare (ignore buffer-name))
(bt:with-recursive-lock-held ((act-r-buffer-lock buffer))
(setf (act-r-buffer-chunk buffer) nil)
(when (act-r-buffer-multi buffer)
(setf (act-r-buffer-chunk-set buffer) (make-hash-table :test 'eq :size 5)))
(dolist (x (act-r-buffer-requests buffer))
(add-request-parameter x)
(setf (act-r-buffer-requests-mask buffer) (logior (slot-name->mask x) (act-r-buffer-requests-mask buffer))))
(dolist (x (act-r-buffer-queries buffer))
(add-buffer-query x))
;; clear any flags
(setf (act-r-buffer-flags buffer) nil)
(unless (act-r-buffer-multi buffer)
(setf (act-r-buffer-reuse? buffer) t))
;; Clear any previous name (will be created as needed)
(setf (act-r-buffer-reuse-chunk buffer) nil)
))
(act-r-model-buffers model)))
(dispatch-apply "reset-step1")
(dolist (module-name (act-r-model-module-instances model))
(reset-module module-name))
#| ;; Create the reusable chunks for the buffers (needs to happen after naming module reset)
(bt:with-lock-held ((act-r-model-buffers-lock model))
(maphash (lambda (buffer-name buffer-struct)
(let ((name (new-name-fct (format nil "~s-buffer-chunk" buffer-name))))
(define-chunks-fct (list name))
(make-chunk-reusable name)
(setf (act-r-buffer-reuse-chunk buffer-struct) name)))
(act-r-model-buffers model)))
|#
;; These are the default values
(mapcar 'sgp-fct (act-r-model-params model))
#|(maphash (lambda (parameter-name parameter)
(sgp-fct (list parameter-name (act-r-parameter-default parameter))))
(bt:with-lock-held (*parameters-table-lock*) *act-r-parameters-table*))
|#
(dispatch-apply "reset-step2")
(dolist (module-name (act-r-model-module-instances model))
(secondary-reset-module module-name))
(dolist (form (act-r-model-code model))
(eval form))
(dispatch-apply "reset-step3")
(dolist (module-name (act-r-model-module-instances model))
(tertiary-reset-module module-name)))
(setf *defining-model* nil)))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 54,504 | Common Lisp | .lisp | 833 | 47.752701 | 307 | 0.532275 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ab0652ad535ea075fa110990d9d3744c210e8d2b0e64e51cfa4e1af39cd93ca2 | 14,303 | [
-1
] |
14,304 | top-level.lisp | asmaloney_ACT-R/framework/top-level.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : top-level.lisp
;;; Version : 3.0
;;;
;;; Description : The framework's top level user commands that aren't
;;; part of another section.
;;;
;;; Bugs :
;;;
;;; To do : * Documentation.
;;; : * Make reload/clear-all smart about compiled files so that
;;; : it knows to check the .lisp if the current file is a
;;; : compiled one.
;;; : [X] Why doesn't clear-all use the reset-mp command?
;;; : [ ] Deal with clear-all not checking the top-level-lock.
;;;
;;; ----- History -----
;;;
;;; 2004.09.02 Dan
;;; : Creation
;;; 2005.01.29 Dan
;;; : * Added an optional parameter to reload that if specified as
;;; : non-nil will use compile-and-load to load the file.
;;; 2005.02.11 Dan
;;; : * Changed clear-all to use clrhash instead of building new
;;; : tables.
;;; 2005.02.22 Dan
;;; : * Modified reset so it better reports what's happening in
;;; : other than normal circumstances.
;;; 2009.10.27 Dan
;;; : * Fixed clear-all so that it also restores the meta-process
;;; : timing code to the default if it has been changed by mp-
;;; : real-time-management.
;;; 2009.12.03 Dan
;;; : * Clear the meta-process dynamics and in-slack on a clear-all too.
;;; 2009.12.04 Dan
;;; : * Use reset-mp in clear-all to avoid duplicate code.
;;; 2012.01.11 Dan
;;; : * Added a safety check to clear-all which throws an error if
;;; : it's called while there's a meta-process running. This
;;; : should avoid situations which can be very problematic when
;;; : model files get loaded while things are running.
;;; 2012.08.08 Dan
;;; : * Change reset so that it uses meta-p-model-order so that
;;; : things work the same at reset and reload times and between
;;; : Lisps.
;;; 2016.09.28 Dan
;;; : * Removed code relating to multiple meta-processes.
;;; : * Reset now returns t instead of a meta-process name.
;;; 2016.11.16 Dan [2.0]
;;; : * Making the commands available through the central dispatcher
;;; : and having the user commands execute them that way. Only
;;; : doing reset and reload through the dispatcher right now
;;; : because I'm not sure about top-level model file commands
;;; : at this point.
;;; 2016.11.17 Dan
;;; : * Changed execute-act-r-command to evaluate-act-r-command.
;;; 2016.12.07 Dan
;;; : * Updated the reload internal function so that it captures
;;; : the non-ACT-R output during the load the same way load does.
;;; 2017.01.18 Dan
;;; : * Removed the echo-act-r-output from commands. The assumption
;;; : now is that echoing is handled by the user.
;;; : * Only return the actual result of evaluating reset and reload
;;; : printing errors using handle-evaluate-results.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.03.30 Dan
;;; : * Don't need meta-p-current-model in clear-all.
;;; 2017.05.30 Dan
;;; : * Adding the call to component functions into clear-all.
;;; 2017.06.22 Dan
;;; : * Protect meta-p-model-order and meta-p-models with lock.
;;; 2017.06.30 Dan
;;; : * Protect the meta-p event-hook related slots.
;;; 2017.07.14 Dan
;;; : * Reset and reload check the top-level-lock. Clear-all DOES NOT.
;;; : That's because it can't be a recursive lock and clear-all
;;; : gets called during reload, but since clear-all isn't remotely
;;; : available that isn't a serious issue at this point.
;;; : * Protect access to meta-p-component-list.
;;; 2017.08.25 Dan
;;; : * If reload is provided the optional compile flag and the
;;; : last loaded file was compiled now it will recompile the source
;;; : file if it exists and should be.
;;; : * Reset and reload return t upon success.
;;; 2017.08.28 Dan
;;; : * Adding a signal for clear-all (clear-all-start).
;;; : * Added a reset-start signal with the last update but didn't
;;; : note that above.
;;; 2017.12.14 Dan [3.0]
;;; : * Eliminated the special case of not resetting a single empty
;;; : model because that usage should be discouraged and this seems
;;; : like a good time to eliminate a 5.0 backwards compatibility
;;; : feature!
;;; : * Why does reload generate errors? Just print the warnings
;;; : now instead. Should probably do the same for clear-all,
;;; : but holding off on that for now.
;;; 2017.12.18 Dan
;;; : * Fixed a bug with changing the errors to print-warnings in
;;; : reload.
;;; 2019.02.05 Dan
;;; : * Adjustments because meta-p-models is now an alist.
;;; 2019.05.24 Dan
;;; : * At clear-all make sure all remote modules are still connected.
;;; : Would be nice to check at other times, but can't undefine
;;; : when there are models so this is really the only safe spot
;;; : right now.
;;; 2019.09.09 Dan
;;; : * Adjusted calls to with-top-level lock to pass the string
;;; : that indicates why the lock is being held.
;;; 2021.10.15 Dan [4.0]
;;; : * Added the call to clear-used-modules during clear-all.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defvar *recorded-load-file* nil)
(defun clear-all ()
(when (mp-running?)
(error "Clear-all cannot be used while ACT-R is running.~%If you are loading a model file you must stop the current run first.~%If the Stepper is open you must close it or hit the stop button.~%"))
;; There is only one mp in this system
(let ((mp (current-mp)))
(dispatch-apply "clear-all-start")
(mapcar (lambda (x)
(delete-model-fct (car x)))
(bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-models mp)))
;; Make sure all the remote modules are still available
(verify-remote-modules)
;; update the componenets
(dolist (c (bt:with-lock-held ((meta-p-component-lock mp)) (meta-p-component-list mp)))
(when (act-r-component-clear-all (cdr c))
(funcall (act-r-component-clear-all (cdr c)) (act-r-component-instance (cdr c)))))
;; This resets the scheduler and real-time management
(reset-mp mp)
(bt:with-lock-held ((meta-p-event-hook-lock mp))
(setf (meta-p-pre-events mp) nil)
(setf (meta-p-post-events mp) nil)
(setf (meta-p-next-hook-id mp) 0)
(clrhash (meta-p-hook-table mp)))
(bt:with-lock-held ((meta-p-models-lock mp))
(setf (meta-p-models mp) nil)
(setf (meta-p-model-order mp) nil)
(setf (meta-p-model-count mp) 0)
(setf (meta-p-model-name-len mp) 0))
)
(clear-used-modules)
(setf *recorded-load-file* *load-truename*)
nil)
(add-act-r-command "clear-all-start" nil "Signal that a clear-all has begun for monitoring. No params." nil)
(add-act-r-command "reset-start" nil "Signal that a reset has begun for monitoring. No params." nil)
(defun internal-reset ()
(with-top-level-lock "Reset cannot be used." "reset"
(let ((mp (current-mp)))
(dispatch-apply "reset-start")
(reset-mp mp)
(dolist (c (bt:with-lock-held ((meta-p-component-lock mp)) (meta-p-component-list mp)))
(awhen (act-r-component-before-reset (cdr c))
(funcall it (act-r-component-instance (cdr c)))))
(dolist (model-name (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-model-order mp)))
(awhen (bt:with-lock-held ((meta-p-models-lock mp)) (cdr (assoc model-name (meta-p-models mp))))
(reset-model mp it)))
(dolist (c (bt:with-lock-held ((meta-p-component-lock mp)) (meta-p-component-list mp)))
(awhen (act-r-component-after-reset (cdr c))
(funcall it (act-r-component-instance (cdr c)))))
t)))
(add-act-r-command "reset" 'internal-reset "Reset the ACT-R scheduler and all models. No params." "Reset already in progress")
(defun reset ()
(handle-evaluate-results (evaluate-act-r-command "reset")))
(defun internal-reload (&optional (compile nil))
(if *recorded-load-file*
(if (probe-file *recorded-load-file*)
(with-top-level-lock "Reload cannot be used." "reload"
(let ((no-errors t))
(cond ((and compile
(string= (pathname-type *recorded-load-file*)
(pathname-type *.lisp-pathname*)))
(let* ((save-stream (make-string-output-stream))
(display-stream (make-broadcast-stream *standard-output* save-stream))
(error-stream (make-broadcast-stream *error-output* save-stream))
(*standard-output* display-stream)
(*error-output* error-stream))
(handler-case
(compile-and-load *recorded-load-file*)
(error (x)
(print-warning "Error ~/print-error-message/ while trying to reload file ~s" x *recorded-load-file*)
(setf no-errors nil)))
(let ((s (get-output-stream-string save-stream)))
(unless (zerop (length s))
(print-warning "Non-ACT-R messages during load of ~s:~%~a~%" *recorded-load-file* s)))))
((and compile
(string= (pathname-type *recorded-load-file*)
(pathname-type *.fasl-pathname*))
(probe-file (merge-pathnames *.lisp-pathname* *recorded-load-file*)))
(print-warning "Since the last loaded file was compiled and the source file exists, recompiling the source file if necessary.")
(let* ((save-stream (make-string-output-stream))
(display-stream (make-broadcast-stream *standard-output* save-stream))
(error-stream (make-broadcast-stream *error-output* save-stream))
(*standard-output* display-stream)
(*error-output* error-stream))
(handler-case
(compile-and-load (merge-pathnames *.lisp-pathname* *recorded-load-file*))
(error (x)
(print-warning "Error ~/print-error-message/ while trying to reload file ~s" x *recorded-load-file*)
(setf no-errors nil)))
(let ((s (get-output-stream-string save-stream)))
(unless (zerop (length s))
(print-warning "Non-ACT-R messages during load of ~s:~%~a~%" *recorded-load-file* s)))))
(t
(let* ((save-stream (make-string-output-stream))
(display-stream (make-broadcast-stream *standard-output* save-stream))
(error-stream (make-broadcast-stream *error-output* save-stream))
(*standard-output* display-stream)
(*error-output* error-stream))
(handler-case
(load *recorded-load-file*)
(error (x)
(print-warning "Error ~/print-error-message/ while trying to reload file ~s" x *recorded-load-file*)
(setf no-errors nil)))
(let ((s (get-output-stream-string save-stream)))
(unless (zerop (length s))
(print-warning "Non-ACT-R messages during load of ~s:~%~a~%" *recorded-load-file* s))))))
no-errors))
(print-warning "File ~s does not exist." *recorded-load-file*))
(progn
(print-warning "No model file recorded to reload.")
:none)))
(add-act-r-command "reload" 'internal-reload "Reload the last ACT-R model file which was loaded. Params: {compile}." "Reload already in progress")
(defun reload (&optional (compile nil))
(handle-evaluate-results (evaluate-act-r-command "reload" compile)))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 14,794 | Common Lisp | .lisp | 275 | 46.378182 | 201 | 0.554183 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 569b1b5314c2f59fa42f90a7d910ddac82cf590fdd3ae043ee5cc7294e67a998 | 14,304 | [
-1
] |
14,305 | framework-loader.lisp | asmaloney_ACT-R/framework/framework-loader.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : framework-loader.lisp
;;; Version : 2.0
;;;
;;; Description : Compiles (if necessary) and loads the files that implement
;;; the framework core.
;;;
;;; Bugs :
;;;
;;; To do : Possibly need special cases for "standalones" as was done
;;; with the ACT-R 5 loader.
;;; : Get rid of smart-load and use the main loader's
;;; compile and load instead.
;;;
;;; ----- History -----
;;;
;;; 2004.09.27 Dan
;;; : Creation
;;; 2005.01.29 Dan
;;; : * Removed the setting of *.lisp-pathname* and *.bin-pathname*
;;; : since that happens in the top loader (load-act-r-6.lisp).
;;; : * Changed smart-load to use compile-and-load instead of doing
;;; : the same checks.
;;; 2005.08.11 Dan
;;; : * Took act-gui-interface off of the list because it has been
;;; : moved to tools.
;;; : * Changed version to 1.0.
;;; : * Removed everything but the file list...
;;; 2007.01.15 Dan
;;; : * Added version-string as the first file in the list now.
;;; 2010.11.15 Dan
;;; : * Added system-parameters to the list.
;;; 2011.04.28 Dan
;;; : * Just setf the list instead of defining it.
;;; : * Take generic-interface.lisp out since it's always
;;; : overridden by the virtual interface and possibly a Lisp
;;; : specific one too.
;;; 2016.11.16 Dan [2.0]
;;; : * Added the dispatcher for the command interface.
;;; 2017.03.30 Dan
;;; : * Added the system-locks file because there's a lock needed
;;; : in the internal-macros code.
;;; 2017.03.31 Dan
;;; : * The internal-macros file is no longer necessary.
;;; 2017.09.19 Dan
;;; : * Added the history-recorder file.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Compiles and loads only the framework pieces but not the general modules
;;; or the specific device interfaces.
;;; Called by the top level loader so it's not really for general use, but
;;; may be needed when testing updates.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; Nothing for use here.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Based on the loader from ACT-R/PM and ACT-R 5. Supports the same Lisps
;;; as was done there.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Define the files to be loaded.
;;; this is always the generic list
(setf *file-list* '("version-string"
"internal-structures"
"system-locks"
; "internal-macros"
"misc-utils"
"dispatcher"
"system-parameters"
"meta-process"
"chunk-types"
"chunks"
"modules"
"parameters"
"buffers"
"model"
"events"
"scheduling"
"chunk-spec"
"top-level"
"device-interface"
"vision-categorization"
"random"
"printing"
"naming-module"
"history-recorder"))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 5,173 | Common Lisp | .lisp | 128 | 35.625 | 80 | 0.499702 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ec79c34922b96f2eee67239afff0ba74c724ef83e540c1d86b4a1aba2dbf9fd7 | 14,305 | [
-1
] |
14,306 | modules.lisp | asmaloney_ACT-R/framework/modules.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : modules.lisp
;;; Version : 4.1
;;;
;;; Description : Code for defining and using the modules.
;;;
;;; Bugs :
;;;
;;; To do : X Finish the documentation.
;;; : X Write an undefine function.
;;; : X Test better so that a module can't be created with models
;;; : already defined otherwise bad things happen.
;;; : * Look into an undefine "on the fly" for when a remotely
;;; : defined module goes away.
;;;
;;; ----- History -----
;;;
;;; 2004.08.13 Dan
;;; : Creation.
;;;
;;; 2004.12.23 Dan
;;; : Modified get-module and get-module-fct so that :device
;;; : returns the current device interface.
;;; 2005.01.12 Dan
;;; : * Since the device is now a true module don't need to
;;; : do the hack listed above - the :device module is the current
;;; : device-interface.
;;; : * Changed the update function so that it gets the old and
;;; : new times as well as the module instance.
;;; 2005.02.22 Dan
;;; : * Updated the to do list with a new issue.
;;; 2005.02.25 Dan
;;; : * Removed the ~\newline usages because that causes problems
;;; : when a Lisp only wants to see native new lines there.
;;; 2005.03.23 Dan
;;; : * Changed how the reset parameter to define-module is
;;; : interpreted to allow for different reset possibilities.
;;; : There are two possible reset functions now - one before
;;; : and one after the parameters take the default values.
;;; : * Added the secondary-reset-module function to support
;;; : the additional reset function.
;;; 2005.03.24 Dan
;;; : * Patched define-module relative to the reset change so
;;; : that it doesn't break on fboundp in Lispworks.
;;; 2005.04.19 Dan
;;; : * Added all-module-names function to make some things easy.
;;; 2005.05.03 Dan
;;; : * Added some more warnings to define-module-fct.
;;; 2005.08.09 Dan
;;; : * Modified define-module so that you can't add a module while
;;; : there are any models defined or any meta-processes other
;;; : than the default.
;;; : * Made undefine-module work now so that one can remove a
;;; : module to redefine it - don't want to make that automatic
;;; : to prevent any module collision issues.
;;; : * Update the version to 1.0.
;;; 2005.08.16 Dan
;;; : * Update query-module so that one can now query "error t"
;;; : or "error nil" but the module writer doesn't have to do
;;; : anything else - just reporting "state error" queries is
;;; : sufficient because the mapping occurs automatically i.e.
;;; : if "state error" returns t then "error t" is t and "error
;;; : nil" is nil or if "state error" is returns nil then "error
;;; : t" is nil and "error nil" is t.
;;; 2006.11.15 Dan
;;; : * Changed the warnings in the buffer-mod-module function to
;;; : be a little clearer.
;;; 2006.11.20 Dan
;;; : * Added the warn-module and warn-module? commands so that
;;; : a module can receive an advance warning of an approaching
;;; : action if it needs to do something. That warning gets
;;; : called when a production which will make a request to the
;;; : module is selected (during the conflict resolution process).
;;; : Right now it's only needed by vision to lock-out the proc-
;;; : display, but other modules may need such functionality too.
;;; : * The warning keyword parameter has been added to define-module
;;; : for setting the warning function.
;;; 2007.06.19 Dan
;;; : * Removed a duplicate definition of warn-module.
;;; 2008.08.28 Dan
;;; : * Fixed get-module so that it always returns two values - even
;;; : when there is no current model or meta-process.
;;; 2008.08.29 Dan
;;; : * Fixed a bug with the test for multiple meta-processes in
;;; : undefine-module-fct.
;;; : * Fixed a typo in a warning of undefine-module-fct.
;;; 2008.09.03 Dan
;;; : * Changed the define-module macro to only splice in the
;;; : version and docs if provided so that the warning displays
;;; : the same as it does for define-module-fct in that respect.
;;; 2008.12.01 Dan
;;; : * Added the option of specifying a third reset function when
;;; : defining a module. The third reset function gets called
;;; : after the user code is evaled.
;;; 2009.09.09 Dan
;;; : * Define-module updated to allow the specification of the
;;; : new multi-buffers. An entry for the buffers-list can now
;;; : have an optional 6th element. If a buffer's definition
;;; : list has a non-nil 6th element then it will be created as
;;; : a multi-buffer. If that 6th element is the keyword :search
;;; : then it will be a searchable buffer.
;;; : The module definition can also now provide two additional
;;; : functions which may be used in conjunction with a searchable
;;; : buffer. They are specified with the :search and :offset
;;; : keywords. The search function will be called at the start
;;; : of a conflict-resolution event for each searchable buffer.
;;; : It will be passed the module instance and a buffer name.
;;; : It should return a list of the chunk names from the buffer's
;;; : chunk set in the order in which they should be searched (car
;;; : of the list will be first searched). If no such function is
;;; : provided then the chunks will be searched in an arbitrary
;;; : order.
;;; : The offset function will be called near the end of the conflict-
;;; : resolution event (after production matching but before the
;;; : final choice). It will be passed the module instance, the
;;; : name of the buffer and a list of the chunks which were matched
;;; : in productions that may be fired. It should return a list of
;;; : numbers that represent the offsets to the utilities for the
;;; : productions which matched those chunks i.e. the first element
;;; : in the list returned will be the offset for productions which
;;; : matched the first chunk in the list provided and so on. If no
;;; : offset function is specified or no list returned by it then no
;;; : offset will be applied and the standard utility will be used
;;; : to choose the production to fire.
;;; 2009.09.11 Dan
;;; : * Added functions to call the search and offset hooks of the
;;; : module given only the buffer name.
;;; 2010.01.15 Dan
;;; : * Added the :search and :offset keywords to the define-module
;;; : macro too.
;;; 2010.12.22 Dan
;;; : * Added the run-notify option to a module to allow it to provide
;;; : a hook for when the scheduler starts running.
;;; 2011.01.11 Dan
;;; : * Added the run-over-notify option to go along with the run-notify
;;; : which gets called at the completion of a run.
;;; : * Changing the define-module keywords to :run-start and :run-end.
;;; 2011.04.27 Dan
;;; : * Added some declaims to avoid compiler warnings about
;;; : undefined functions.
;;; 2014.03.17 Dan [2.0]
;;; : * Changed warn-module because now it's called with a chunk-spec
;;; : instead of just the type.
;;; 2014.09.26 Dan
;;; : * All-module-names now returns a list sorted by module name
;;; : which should be used anywhere the current maphashing is done.
;;; 2014.11.11 Dan
;;; : * Fixed a bug in define-module with the check for multiple
;;; : meta-processes.
;;; 2016.09.28 Dan
;;; : * Removed calls to meta-process-name and checks for more than
;;; : one meta-process from define and undefine module.
;;; 2017.06.15 Dan
;;; : * Making get-module-fct and max-module-name-length thread safe.
;;; 2017.06.29 Dan
;;; : * Making everything here thread safe.
;;; 2017.12.07 Dan
;;; : * Adding remote module commands for add and undefine, and also
;;; : adjusting everything to actually work with a remotely defined
;;; : module (calling dispatch fn's and converting results as needed).
;;; 2017.12.18 Dan
;;; : * Getting the declaim right for define-parameter so that it
;;; : doesn't result in warnings/errors in ACL and CCL.
;;; 2018.02.23 Dan
;;; : * Allow an external module to specify its own instance instead
;;; : of forcing it to be the model name.
;;; 2018.06.14 Dan
;;; : * Rework the parameters for the remote define module so that
;;; : it uses the options list functionality and looks a lot more
;;; : like define-module, and then just pass the parameters to the
;;; : internal command instead of having a parallel remote version.
;;; 2018.07.27 Dan
;;; : * Added a test for buffer-list actually being a list in define-
;;; : module.
;;; : * Process-parameters should pass the param name or a list of two
;;; : values to a remote command not a list of 1 or two items.
;;; : * Get-module always returns two values now.
;;; 2018.08.01 Dan
;;; : * Process-parameters should always pass a list to the remote
;;; : command because testing for 1 or 2 elements in a list is
;;; : something that should be easy in any language, but testing
;;; : for the difference between a string and a list of two items
;;; : is likely more complicated.
;;; 2019.01.17 Dan
;;; : * Fixed a bug in a warning with m-buffer-offset.
;;; 2019.03.15 Dan
;;; : * Getting rid of most get-abstract-module calls by storing the
;;; : abstract-module in the table with the instance so that get-
;;; : module returns both -- the exists is the abstract!
;;; 2019.04.03 Dan
;;; : * The functions called from internal code (like reset-module)
;;; : are now passed the module instance and abstract module.
;;; 2019.04.15 Dan
;;; : * Replace splice-into-list with splice-into-position-des and
;;; : don't setf with the returned value since it's destructive.
;;; 2019.05.24 Dan [3.0]
;;; : * Add code to check that a remote module still has valid
;;; : interface functions and undefine it if it doesn't. Can only
;;; : be called at clear-all time, and clear-all now does so.
;;; 2019.07.02 Dan
;;; : * Actually set the external flag on the remote modules.
;;; 2020.01.31 Dan [3.1]
;;; : * Added a remote all-module-names.
;;; 2020.08.25 Dan
;;; : * Changed the declaim for buffers to avoid warning in SBCL.
;;; 2020.09.10 Dan [3.2]
;;; : * Added the check-module-version command for testing the
;;; : version string of a module against a provided version.
;;; 2020.09.11 Dan
;;; : * Deleted a needed function for check-module-version before
;;; : I committed the last one.
;;; 2021.10.15 Dan [4.0]
;;; : * Added the use-modules command that when called without a
;;; : model defined limits the modules that will be used until the
;;; : next clear-all call, and clear-used-modules for use in
;;; : clear-all to keep from needing to use the global elsewhere.
;;; : * Added the required parameter to define-module which if set
;;; : means the module will be used even if not specified in a
;;; : call to use-modules.
;;; 2021.10.18 Dan
;;; : * Change process-parameters because it's always called with a
;;; : current model so don't use the general get-module code and
;;; : don't print warnings if the module doesn't exist when the
;;; : third parameter is nil.
;;; 2021.10.19 Dan
;;; : * Test the :required value of a module for being t, module, or
;;; : a list of modules so that a module can be required when any
;;; : of the indicated modules are also required (saves having to
;;; : specify all modules explicitly for something like procedural
;;; : but the cost is that it always uses the related modules).
;;; : * Added an optional parameter to get-module that suppresses
;;; : the warning if provided, and use that in the notify
;;; : functions which only warn if both the instance and abstract
;;; : are unavailable.
;;; : * Fixed the external get-module since the abstract module
;;; : can't be encoded, but presumably the module that one wants
;;; : to get can be...
;;; 2021.10.22 Dan
;;; : * Get-module should return only t/nil as the second parameter
;;; : to indicate existence. Use a different version in this code
;;; : to get both the instance and the abstract module.
;;; 2022.03.09 Dan [4.1]
;;; : * Adding a :requires parameter to define-module because it
;;; : makes more sense for a module to specify the other modules
;;; : that it requires instead of the other module knowing which
;;; : modules need it. Leaving :required however because setting
;;; : that to t is useful and no need to break things that are
;;; : already in place.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; The globals and structures are not for general use.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;; define-module
;;;
;;; define-module creates a new module for the system along with its buffers.
;;;
;;; See reference manual for details.
;;;
;;; get-module
;;;
;;; (defmacro get-module (module-name &optional suppress-warning))
;;; (defun get-module-fct (module-name &optional suppress-warning))
;;;
;;; module-name a symbol which is the name of a module
;;; suppress-warning a generalized boolean
;;;
;;; If module-name is the name of a module in the current model then the
;;; instantiation of that module in the current model is returned.
;;;
;;; If module-name does not name a module in the current model or there is
;;; no current model then a warning is printed, unless suppress-warning is
;;; true, and nil is returned
;;;
;;; This exists so that if a module provides functions that are called other
;;; than through the buffer it can get the correct instantiation of itself to
;;; use. It is not really for general purpose use because the instantiations
;;; of a module are really only meaningful within the code of the module.
;;;
;;; use-modules
;;;
;;; (defmacro use-modules (&rest names))
;;; (defun use-modules-fct (names))
;;;
;;; If called when there are no models defined it will limit the set of modules
;;; that will be instantiated for models to only those indicated, those which
;;; are marked as always required, and any that are required by the modules that
;;; are specified.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Redefinition requires explicit removal of the existing module first.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function (t) t) buffers-module-name))
(declaim (ftype (function (t) t) remove-modules-parameters))
(declaim (ftype (function (t) t) uninstall-buffers))
(declaim (ftype (function (t) t) buffer-exists))
(declaim (ftype (function (t t) t) install-parameters))
(declaim (ftype (function (t t) t) install-buffers))
(declaim (ftype (function (t) t) parse-parameters))
(declaim (ftype (function (t) t) parse-buffers))
(declaim (ftype (function (&optional t) t) buffers))
(declaim (ftype (function (t) t) chunk-spec-to-id))
(declaim (ftype (function (t &key (:owner t) (:valid-test t) (:default-value t) (:warning t) (:documentation t)) t) define-parameter))
;;; The top level tabel that holds all the modules and details.
;;; Holds all the modules that have been defined.
(defvar *modules-lookup* (make-act-r-modules)
"The table of all defined modules")
;;; For safety reasons need to know which modules are defined
;;; remotely so that they can be verified at clear-all time.
(defvar *remote-act-r-modules* nil)
;;; Allow for a limted set of modules to be instantiated
;;; by the model.
(defvar *limited-modules* nil)
(defun clear-used-modules ()
(setf *limited-modules* nil))
(defmacro use-modules (&rest names)
`(use-modules-fct ',names))
(defun use-modules-fct (names)
(if (mp-models)
(print-warning "Use-modules can only be used when there are no models defined.")
(let ((l (bt:acquire-lock *define-model-lock* nil)))
(if (null l)
(print-warning "Cannot call use-modules while a model is being defined or deleted.")
(unwind-protect
(if *defining-model*
(print-warning "Cannot call use-modules while a model is being defined or deleted.")
(dolist (n names)
(if (get-abstract-module n)
(pushnew n *limited-modules*)
(print-warning "~s is not a valid module name in call to use-modules" n))))
(bt:release-lock *define-model-lock*))))))
(defun required-module (abstract-module)
(or (null *limited-modules*)
(aif (act-r-module-required abstract-module)
(or
(eq t it)
(intersection *limited-modules* it))
(find (act-r-module-name abstract-module) *limited-modules*))))
;;; Some macros to hide the global from direct use in other files
(defun max-module-name-length ()
"Length of the longest module's name"
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-name-len *modules-lookup*)))
(defun global-modules-table ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-table *modules-lookup*)))
(defun all-module-names ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-sorted-names *modules-lookup*)))
(add-act-r-command "all-module-names" 'all-module-names "Returns a list of the names of all currently defined modules. No params.")
(defun notified-modules ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-notify *modules-lookup*)))
(defun run-notify-modules ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-run-notify *modules-lookup*)))
(defun run-over-notify-modules ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-run-over-notify *modules-lookup*)))
(defun updating-modules ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(act-r-modules-update *modules-lookup*)))
(defmacro define-module (module-name buffer-list params-list
&key (version nil)
(documentation nil)
(creation nil) (reset nil) (query nil)
(request nil) (buffer-mod nil) (params nil)
(delete nil)
(notify-on-clear nil)
(update nil)
(warning nil)
(search nil)
(offset nil)
(run-start nil)
(run-end nil)
(required nil)
(requires nil))
`(define-module-fct ',module-name ',buffer-list ',params-list ,@(when version `(:version ,version))
,@(when documentation `(:documentation ,documentation))
:creation ',creation :reset ',reset :query ',query :request ',request
:buffer-mod ',buffer-mod :params ',params
:delete ',delete :notify-on-clear ',notify-on-clear :update ',update :warning ',warning
:search ',search :offset ',offset :run-start ',run-start :run-end ',run-end
:required ',required :requires ',requires))
(defun define-module-fct (module-name buffer-list params-list
&key (version "" version?)
(documentation "" docs?)
creation reset query
request buffer-mod params
delete notify-on-clear update warning
search offset run-start run-end required requires)
(unless (and version? docs?)
(print-warning "Modules should always provide a version and documentation string."))
(cond ((mp-models)
(print-warning "Cannot create a new module when there are models defined."))
((null module-name)
(print-warning "Nil is not a valid module-name. No module defined."))
((not (symbolp module-name))
(print-warning "~s is not a valid module name.~%No module defined." module-name))
((valid-module-name module-name)
(print-warning "Module ~S already exists and cannot be redefined. Delete it with undefine-module first if you want to redefine it." module-name))
((not (listp buffer-list))
(print-warning "Buffer-list must be a list of buffer names or buffer description lists, but given ~s. Module ~s not defined." buffer-list module-name))
((and buffer-list (null query))
(print-warning "A module with a buffer must support queries.~%Module ~s not defined." module-name))
((and buffer-list (some #'(lambda (x)
(buffer-exists (cond ((listp x) (car x))
(t x))))
buffer-list))
(print-warning "A buffer name requested when defining module ~s is already used by another module." module-name)
(print-warning "Existing buffer names are: ~s" (buffers))
(print-warning "Module attempted to create buffers: ~s" buffer-list)
(print-warning "Module ~s not defined" module-name))
((not (or (and (not (listp reset)) (local-or-remote-function-or-nil reset))
(and (listp reset)
(<= (length reset) 3)
(every 'local-or-remote-function-or-nil reset))))
(print-warning
"Reset parameter is not a function, functon name, nil or a list of one, two, or three such items."))
((not (and (local-or-remote-function-or-nil creation) (local-or-remote-function-or-nil query)
(local-or-remote-function-or-nil request) (local-or-remote-function-or-nil buffer-mod) (local-or-remote-function-or-nil params)
(local-or-remote-function-or-nil delete) (local-or-remote-function-or-nil search) (local-or-remote-function-or-nil offset)
(local-or-remote-function-or-nil notify-on-clear) (local-or-remote-function-or-nil update) (local-or-remote-function-or-nil run-start)
(local-or-remote-function-or-nil run-end)))
(print-warning "Invalid parameter for a module call-back function")
(do ((items (list creation query request buffer-mod params delete notify-on-clear update warning search offset run-start run-end)
(cdr items))
(names '(creation query request buffer-mod params delete notify-on-clear update warning search offset run-start run-end)
(cdr names)))
((null items))
(unless (local-or-remote-function-or-nil (car items))
(print-warning "Parameter: ~s is not a function, function name, or nil" (car names))))
(print-warning "Module ~s not defined" module-name))
((notevery 'act-r-parameter-p params-list)
(print-warning "Invalid params-list ~s.~%Module ~s not defined." params-list module-name))
((and params-list (null params))
(print-warning "Must specify a param function because parameters are used.~%Module ~s not defined." module-name))
(t
(let ((buffers (parse-buffers buffer-list))
(parameters (parse-parameters params-list)))
(cond ((eq :error buffers)
(print-warning "Error in module buffer definitions.~%Module ~s not defined." module-name))
((eq :error parameters)
(print-warning "Error in module parameter definitions.~%Module ~s not defined." module-name))
(t
(let ((new-mod (make-act-r-module :name module-name
:buffers buffers
:version version
:documentation documentation
:creation creation
:reset (if (listp reset)
(first reset)
reset)
:secondary-reset (if (listp reset)
(second reset)
nil)
:tertiary-reset (if (listp reset)
(third reset)
nil)
:query query
:request request
:buffer-mod buffer-mod
:params params
:delete delete
:notify-on-clear notify-on-clear
:update update
:warn warning
:search search
:offset offset
:run-notify run-start
:run-over-notify run-end
:required (if (listp required) required (if (eq required t) t (list required))))))
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(setf (gethash module-name (act-r-modules-table *modules-lookup*)) new-mod)
(if (null (act-r-modules-sorted-names *modules-lookup*))
(push module-name (act-r-modules-sorted-names *modules-lookup*))
(splice-into-position-des (act-r-modules-sorted-names *modules-lookup*)
(aif (position-if (lambda (x)
(string< (symbol-name module-name) (symbol-name x)))
(act-r-modules-sorted-names *modules-lookup*))
it
(length (act-r-modules-sorted-names *modules-lookup*)))
module-name))
(incf (act-r-modules-count *modules-lookup*))
(when (> (length (format nil "~S" module-name)) (act-r-modules-name-len *modules-lookup*))
(setf (act-r-modules-name-len *modules-lookup*) (length (format nil "~S" module-name))))
(when notify-on-clear
(push module-name (act-r-modules-notify *modules-lookup*)))
(when update
(push module-name (act-r-modules-update *modules-lookup*)))
(when run-start
(push module-name (act-r-modules-run-notify *modules-lookup*)))
(when run-end
(push module-name (act-r-modules-run-over-notify *modules-lookup*)))
(if (listp requires)
(dolist (r requires)
(aif (gethash r (act-r-modules-table *modules-lookup*))
(when (listp (act-r-module-required it))
(push module-name (act-r-module-required it)))
(print-warning "Module ~s indicates it requires module ~s but that module does not exist."
module-name r)))
(print-warning "Ignoring invalid :requires value when defining module ~s" module-name))
)
(install-buffers module-name buffers)
(install-parameters module-name parameters)
module-name)))))))
(defun parse-remote-params (params-list)
(mapcar (lambda (x)
(multiple-value-bind (valid params)
(process-options-list (second x) "parse-remote-params" '(:owner :valid-test :default-value :warning :documentation))
(when valid
(apply 'define-parameter (string->name (first x)) (convert-options-list-items params '(:default-value :valid-test) nil)))))
params-list))
(defun parse-remote-buffers (buffer-list)
(if (listp buffer-list)
(mapcar (lambda (x)
(if (atom x)
(string->name x)
(cond ((< (length x) 5)
(string->name-recursive x))
((= (length x) 5)
(append (string->name-recursive (subseq x 0 4)) (list (fifth x))))
(t
(append (string->name-recursive (subseq x 0 4)) (list (fifth x)) (string->name-recursive (nthcdr 5 x)))))))
buffer-list)
buffer-list))
(defun remote-define-module (name buffer-list param-list &optional interface-list)
(multiple-value-bind (valid interface)
(process-options-list interface-list "define-module" '(:version :documentation :creation :reset :query :request :buffer-mod :params :delete :notify-on-clear :update :warning :search :offset :run-start :run-end :required :requires))
(if valid
(let ((success (apply 'define-module-fct (string->name name) (parse-remote-buffers buffer-list) (parse-remote-params param-list) interface)))
(when success
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(let ((m (gethash success (act-r-modules-table *modules-lookup*))))
(setf (act-r-module-external m) t))
(push success *remote-act-r-modules*)))
success)
nil)))
(add-act-r-command "define-module" 'remote-define-module "Create a new module. Params: name (buffer-spec*) (param-spec*) {< version, documentation, creation , reset, query, request, buffer-mod, params, delete, notify-on-clear, update, warning, search, offset, run-start, run-end, required, requires >}")
(defun verify-remote-modules ()
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(dolist (module *remote-act-r-modules*)
(let ((m (gethash module (act-r-modules-table *modules-lookup*))))
(when (some (lambda (fn)
(and (stringp fn) (not (check-act-r-command fn))))
(list (act-r-module-creation m)
(act-r-module-reset m)
(act-r-module-secondary-reset m)
(act-r-module-tertiary-reset m)
(act-r-module-query m)
(act-r-module-request m)
(act-r-module-buffer-mod m)
(act-r-module-params m)
(act-r-module-delete m)
(act-r-module-notify-on-clear m)
(act-r-module-update m)
(act-r-module-warn m)
(act-r-module-search m)
(act-r-module-offset m)
(act-r-module-run-notify m)
(act-r-module-run-over-notify m)))
(undefine-module-fct module)
(print-warning "Module ~s undefined because remote commands no longer available." module)
(setf *remote-act-r-modules* (remove module *remote-act-r-modules*)))))))
;;; Since a module can't be redefined interactive creation of new
;;; modules requires a way to get rid of one on the fly
(defmacro undefine-module (module-name)
`(undefine-module-fct ',module-name))
(defun undefine-module-fct (module-name)
(cond ((mp-models)
(print-warning "Cannot delete a module when there are models defined."))
((not (valid-module-name module-name))
(print-warning "~S is not the name of a currently defined module." module-name))
(t
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(uninstall-buffers (act-r-module-buffers
(gethash module-name (act-r-modules-table *modules-lookup*))))
(remove-modules-parameters module-name)
;; take it out of the table
(remhash module-name (act-r-modules-table *modules-lookup*))
(setf (act-r-modules-sorted-names *modules-lookup*) (remove module-name (act-r-modules-sorted-names *modules-lookup*)))
(decf (act-r-modules-count *modules-lookup*))
;;; if it was the longest name remeasure the rest
(when (= (length (format nil "~S" module-name))
(act-r-modules-name-len *modules-lookup*))
(setf (act-r-modules-name-len *modules-lookup*)
(apply #'max (mapcar #'(lambda (x)
(length (format nil "~S" x)))
(all-module-names)))))
(setf (act-r-modules-notify *modules-lookup*)
(remove module-name (act-r-modules-notify *modules-lookup*)))
(setf (act-r-modules-run-notify *modules-lookup*)
(remove module-name (act-r-modules-run-notify *modules-lookup*)))
(setf (act-r-modules-run-over-notify *modules-lookup*)
(remove module-name (act-r-modules-run-over-notify *modules-lookup*)))
(setf (act-r-modules-update *modules-lookup*)
(remove module-name (act-r-modules-update *modules-lookup*))))
t)))
(defun remote-undefine-module (name)
(undefine-module-fct (string->name name)))
(add-act-r-command "undefine-module" 'remote-undefine-module "Remove the named module from the system. Params: module-name." t)
(defmacro get-module (module-name &optional no-warning)
`(get-module-fct ',module-name ',no-warning))
(defun get-module&abstract (module-name &optional no-warning)
(let (abstract)
(values (verify-current-model
"get-module called with no current model."
(multiple-value-bind (mod present)
(gethash module-name (let ((model (current-model-struct))) (bt:with-lock-held ((act-r-model-modules-lock model)) (act-r-model-modules-table model))))
(if present
(progn
(setf abstract (cdr mod))
(car mod))
(unless no-warning (print-warning "~s is not the name of a module in the current model." module-name)))))
abstract)))
(defun get-module-fct (module-name &optional no-warning)
(let (exists)
(values (verify-current-model
"get-module called with no current model."
(multiple-value-bind (mod present)
(gethash module-name (let ((model (current-model-struct))) (bt:with-lock-held ((act-r-model-modules-lock model)) (act-r-model-modules-table model))))
(if present
(progn
(setf exists t)
(car mod))
(unless no-warning (print-warning "~s is not the name of a module in the current model." module-name)))))
exists)))
(defun external-get-module (module-name &optional no-warning)
(get-module-fct (string->name module-name) no-warning))
(add-act-r-command "get-module" 'external-get-module "Return the instance of the named module in the current model. Params: module-name {no-warning}")
(defun get-abstract-module (module-name)
(bt:with-recursive-lock-held ((act-r-modules-lock *modules-lookup*))
(gethash module-name (act-r-modules-table *modules-lookup*))))
(defun valid-module-name (name)
(if (get-abstract-module name)
t
nil))
(defun process-parameters (module-name param ignore)
(multiple-value-bind (mod present)
(gethash module-name
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-modules-lock model))
(act-r-model-modules-table model))))
(if present
(let ((module (cdr mod))
(instance (car mod)))
(awhen (act-r-module-params module) ;; should be guranteed
(if (act-r-module-external module)
(if (consp param)
(dispatch-apply it instance (list (car param) (cdr param)))
(dispatch-apply it instance (list param)))
(funcall it instance param))))
(unless ignore
(print-warning "There is no module named ~S. Cannot process parameters for it." module-name)))))
(defun instantiate-module (module-name model-name)
(let ((module (get-abstract-module module-name)))
(if module
(when (required-module module)
(let ((instance (when (act-r-module-creation module)
(dispatch-apply (act-r-module-creation module) model-name))))
;; store the abstract in the table with the instance!
(cons instance module)))
(print-warning "There is no module named ~S. Cannot instantiate it." module-name))))
(defun reset-module (module-alist)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(awhen (act-r-module-reset module)
(dispatch-apply it instance))))
(defun secondary-reset-module (module-alist)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(awhen (act-r-module-secondary-reset module)
(dispatch-apply it instance))))
(defun tertiary-reset-module (module-alist)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(awhen (act-r-module-tertiary-reset module)
(dispatch-apply it instance))))
(defun query-module (module-alist buffer-name query value)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(aif (act-r-module-query module)
(cond ((eq query 'error)
(if value
(dispatch-apply it instance buffer-name 'state 'error)
(not (dispatch-apply it instance buffer-name 'state 'error))))
(t
(dispatch-apply it instance buffer-name query value)))
(print-warning "Module ~s does not support queries." (act-r-module-name module)))))
(defun warn-module? (module-alist)
(if (act-r-module-warn (cdr module-alist)) t nil))
(defun warn-module (module-alist buffer-name chunk-spec)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(aif (act-r-module-warn module)
(if (act-r-module-external module)
(dispatch-apply it instance buffer-name (chunk-spec-to-id chunk-spec))
(funcall it instance buffer-name chunk-spec))
(print-warning "Module ~s does not require warnings." (act-r-module-name module)))))
(defun request-module (module-alist buffer-name chunk-spec)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(aif (act-r-module-request module)
(progn
(if (act-r-module-external module)
(dispatch-apply it instance buffer-name (chunk-spec-to-id chunk-spec))
(funcall it instance buffer-name chunk-spec))
t)
(print-warning "Module ~s does not handle requests." (act-r-module-name module)))))
(defun buffer-mod-module (module-alist buffer-name chunk-mods)
(let ((module (cdr module-alist))
(instance (car module-alist)))
(aif (act-r-module-buffer-mod module)
(progn
(if (act-r-module-external module)
(dispatch-apply it instance buffer-name (chunk-spec-to-id chunk-mods))
(funcall it instance buffer-name chunk-mods))
t)
(print-warning "Module ~s does not support buffer modification requests." (act-r-module-name module)))))
(defun delete-module (module-name)
(multiple-value-bind (instance module)
(get-module&abstract module-name)
(if module
(awhen (act-r-module-delete module)
(dispatch-apply it instance))
(print-warning "There is no module named ~S in the current model. Cannot delete an instance of it." module-name))))
(defun notify-module (module-name buffer-name chunk-name)
(multiple-value-bind (instance module)
(get-module&abstract module-name t)
(if module
;; this only gets called if there is such a function
;; so no need to double check it
(dispatch-apply (act-r-module-notify-on-clear module) instance buffer-name chunk-name)
(unless *limited-modules*
(print-warning "There is no module named ~S in the current model. Cannot notify it of a buffer's clearing." module-name)))))
(defun update-the-module (module-name old-time new-time)
(multiple-value-bind (instance module)
(get-module&abstract module-name t)
(if module
;; this only gets called if there is such a function
;; so no need to double check it
(dispatch-apply (act-r-module-update module) instance old-time new-time)
(unless *limited-modules*
(print-warning "There is no module named ~S in the current model. Cannot update it." module-name)))))
(defun run-notify-module (module-name)
(multiple-value-bind (instance module)
(get-module&abstract module-name t)
(if module
;; this only gets called if there is such a function
;; so no need to double check it
(dispatch-apply (act-r-module-run-notify module) instance)
(unless *limited-modules*
(print-warning "There is no module named ~S in the current model. Cannot notify it of a run start." module-name)))))
(defun run-over-notify-module (module-name)
(multiple-value-bind (instance module)
(get-module&abstract module-name t)
(if module
;; this only gets called if there is such a function
;; so no need to double check it
(dispatch-apply (act-r-module-run-over-notify module) instance)
(unless *limited-modules*
(print-warning "There is no module named ~S in the current model. Cannot notify it of a run ending." module-name)))))
(defun m-buffer-search (buffer-name)
(aif (buffers-module-name buffer-name)
(module-m-buffer-search it buffer-name)
(print-warning "m-buffer-search cannot search ~s because it does not name a valid buffer.")))
(defun module-m-buffer-search (module-name buffer-name)
(multiple-value-bind (instance module)
(get-module&abstract module-name)
(if module
(aif (act-r-module-search module)
(values t (dispatch-apply it instance buffer-name))
(values nil nil))
(print-warning "There is no module named ~S in the current model. Cannot perform buffer search." module-name))))
(defun m-buffer-offset (buffer-name c-list)
(aif (buffers-module-name buffer-name)
(module-m-buffer-offset it buffer-name c-list)
(print-warning "m-buffer-offset cannot get values for ~s because it does not name a valid buffer." buffer-name)))
(defun module-m-buffer-offset (module-name buffer-name c-list)
(multiple-value-bind (instance module)
(get-module&abstract module-name)
(if module
(aif (act-r-module-offset module)
(values t (dispatch-apply it instance buffer-name c-list))
(values nil nil))
(print-warning "There is no module named ~S in the current model. Cannot get buffer offsets." module-name))))
;;; Add a way to test against a module's version number assuming that it's set as a sequence of numbers
;;; separated by periods. Useful for things in extras or user added extensions since those won't
;;; correspond to an ACT-R version change.
(defun valid-module-version-string (val)
(and (stringp val)
(every (lambda (x) (find x '(#\. #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))) val)))
(defun module-version-numbers (s)
(read-from-string (format nil "(~a)" (substitute #\space #\. s))))
(defun check-module-version (module version &optional warn-if-newer)
(let ((m (get-abstract-module module)))
(if m
(if (valid-module-version-string (act-r-module-version m))
(if (valid-module-version-string version)
(let ((check-version (module-version-numbers version))
(module-version (module-version-numbers (act-r-module-version m))))
(mapcar (lambda (m-v t-v)
(if (< m-v t-v)
(return-from check-module-version
(print-warning "Module ~s with version ~s does not meet the version test for ~s"
module (act-r-module-version m) version))
(when (> m-v t-v)
(if warn-if-newer
(return-from check-module-version
(print-warning "Module ~s with version ~s is newer than the version test for ~s"
module (act-r-module-version m) version))
(return-from check-module-version t)))))
module-version check-version)
(if (> (length check-version) (length module-version))
(print-warning "Module ~s with version ~s does not meet the version test for ~s"
module (act-r-module-version m) version)
t))
(print-warning "Version number ~s given to check module ~s is not a string of numbers" version module))
(print-warning "Cannot check version because module ~s has version ~s which is not a string of numbers" module (act-r-module-version m)))
(print-warning "Cannot check version because no module with name ~s" module))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 50,597 | Common Lisp | .lisp | 862 | 48.140371 | 303 | 0.576428 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | f7a535c11fc24d14ec9f742129b9b32acc5e68cc1a1661749084c8d56ad3cd46 | 14,306 | [
-1
] |
14,307 | internal-macros.lisp | asmaloney_ACT-R/framework/internal-macros.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : internal-macros.lisp
;;; Version : 1.0a1
;;;
;;; Description : All of the defmacros for the internal code.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2004.10.07 Dan
;;; : Created.
;;; 2013.01.04 Dan
;;; : * Added the cannot-define-model macro here.
;;; 2013.01.07 Dan
;;; : * Changed cannot-define-model to use a count instead of t/nil.
;;; 2016.09.27 Dan
;;; : * Moved current-mp here since it's just a simple closure now.
;;; 2016.09.28 Dan
;;; : * Moved verify-current-mp here but it's just a dummy to avoid
;;; : having to fix that everywhere else for now.
;;; 2017.03.29 Dan
;;; : * Replaced the current-model slot in the meta-process and just
;;; : using a global since there's only one meta-process and this
;;; : lets me rebind it in a let on a per-thread basis.
;;; 2017.03.30 Dan
;;; : * Moved current-mp and current-mp-fct to the structures file
;;; : because they're needed for the locks code.
;;; : * Also moved the model related code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; These are not for general use!
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; NONE!
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; I had some odd compiling order issues with the defstructs and defmacros
;;; so for now the easy (only?) fix was to make sure that they are all
;;; available from the start.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defmacro cannot-define-model (&body body)
`(progn
(incf (meta-p-cannot-define-model (current-mp)))
(unwind-protect
(progn ,@body)
(decf (meta-p-cannot-define-model (current-mp))))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 3,627 | Common Lisp | .lisp | 91 | 38.318681 | 80 | 0.524795 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5a882d68586a3369a63b3f216c480a1e204c4b973f52515533b4683f9afaf11b | 14,307 | [
-1
] |
14,308 | internal-structures.lisp | asmaloney_ACT-R/framework/internal-structures.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : internal-structures.lisp
;;; Version : 5.0
;;;
;;; Description : All of the defstructs for the internal code.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2004.10.07 Dan
;;; : Created.
;;; 2005.01.05 Dan
;;; : Changed the version on the meta-process so that it indicates
;;; : the svn revision because it's going to be used to create a
;;; : snapshot for the website.
;;; 2005.01.10 Dan
;;; : Same as above - added r20 and this time it's actually going
;;; : out to the site!
;;; 2005.01.12 Dan
;;; : Because device is becoming a module it doesn't need to be
;;; : a slot in the model.
;;; 2005.01.15 Dan
;;; : * Taking the r20 out of the meta-process version and uping
;;; : it to 1.0a2.
;;; : * Moving to 80 charater width.
;;; : * Adding the copied-from slot to chunks.
;;; 2005.01.16 Dan
;;; : * Removed the print-functions for chunks and chunk-types
;;; : because users shouldn't be seeing those and there's no
;;; : need to hide the details.
;;; 2005.01.21 Dan
;;; : * Added the merge-list slot to chunks to help speed up the
;;; : merging action.
;;; 2005.01.27 Dan
;;; : * Added the filter slot to the printing module structure.
;;; 2005.01.29 Dan
;;; : * Added r33 to the meta-process version for distribution
;;; : on the ACT-R website.
;;; 2005.01.31 Dan
;;; : * Removed the r33 from the version and updated it to 1.0a3.
;;; 2005.02.02 Dan
;;; : * Added the detail slot to the printing module.
;;; : * Changed the default output for break events to be low
;;; : for use wth the detail level.
;;; 2005.02.11 Dan
;;; : * Changed the make-hash-tables in the chunk structure to
;;; : limit the size to just a little bigger than needed and
;;; : in the meta-process to 5 for models.
;;; 2005.03.23 Dan
;;; : * Added the secondary-reset slot to the module structure.
;;; 2005.04.08 Dan
;;; : * Added r67 to meta-process version for distribution on
;;; : the website.
;;; 2005.04.14 Dan
;;; : * Added the suppress-cmds slot to the printing module to get
;;; : around a problem with no-output and trying to read the :cmdt
;;; : parameter...
;;; 2005.04.20 Dan
;;; : * Took the r67 off of the meta-process version.
;;; 2005.05.11 Dan
;;; : * Changed the version to 1.0b1 [r79].
;;; 2005.05.12 Dan
;;; : * Removed the [r79] from the version.
;;; 2005.06.10 Dan
;;; : * Changed the version to 1.0b2 [r120].
;;; 2005.06.11 Dan
;;; : * Changed version to 1.0b2
;;; 2005.07.12 Dan
;;; : * Changed the framework version to 1.0 [r130].
;;; 2005.07.13 Dan
;;; : * Removed the r130 from the version number.
;;; 2005.08.30 Dan
;;; : * Changed the framework version to 1.0 [r144].
;;; 2005.08.30 Dan
;;; : * Oops, mis-encoded the file with mac line endings, so
;;; : now changing to [r145].
;;; 2005.09.01 Dan
;;; : * Taking the [r145] off.
;;; 2005.09.08 Dan
;;; : * Added the model-warnings slot to the printing module
;;; : struct to support suppression of all model warnings.
;;; 2005.11.16 Dan
;;; : * Changing framework version to 1.0 [r168].
;;; 2005.11.17 Dan
;;; : * Changing framework version to back to 1.0.
;;; 2006.01.16 Dan
;;; : * Changed the version to [r187] for release.
;;; 2006.01.17 Dan
;;; : * Changing framework version to 1.1.
;;; 2006.01.18 Dan
;;; : * Added the extended-slots slot to the chunk-type structure
;;; : so that one can differentiate between the original slots
;;; : and any that are added on the fly.
;;; : * Added the show-all-slots slot to the printing module to hold
;;; : the new parameter.
;;; 2006.01.30 Dan
;;; : * Adding the maintenance event type for use in things like
;;; : terminating events and periodic events. The schedule-event-
;;; : after functions will have a keyword that specifies whether
;;; : or not to consider maintenance events that defaults to nil.
;;; 2006.02.27 Dan
;;; : * Added slots to the meta-process to handle the configuration
;;; : of the real time management.
;;; 2006.03.03 Dan
;;; : * Added the max-time-delta slot to the meta-process.
;;; 2006.03.06 Dan
;;; : * Changed the version to [r204] for release.
;;; 2006.03.06 Dan
;;; : * Removed the [r204] from the version.
;;; 2006.03.14 Dan
;;; : * Changed version to [r212] for web release.
;;; 2006.03.14 Dan
;;; : * Removed the [r212].
;;; 2006.03.15 Dan
;;; : * Changed version to [r216] for web release.
;;; 2006.03.15 Dan
;;; : * Removed the [r216].
;;; 2006.03.21 Dan
;;; : * Changed version to [r219] for web release.
;;; 2006.03.21 Dan
;;; : * Changed version to [r220] for web release.
;;; 2006.03.28 Dan
;;; : * Changed version to [r222] for web release.
;;; 2006.03.28 Dan
;;; : * Removed the [r222].
;;; 2006.07.10 Dan
;;; : * Changed version to [r248] for web release.
;;; 2006.07.10 Dan
;;; : * Removed the [r248].
;;; 2006.11.20 Dan
;;; : * Added the warn slot to the act-r-module structure.
;;; 2007.01.15 Dan
;;; : * Changed the version setting in the meta-process structure
;;; : to be the value of *actr-version-string* so that I don't
;;; : have to touch this file to mark the version changes.
;;; 2007.04.13 Dan
;;; : * Added a new slot to the printing module struct to hold
;;; : the cbct parameter.
;;; 2008.10.20 Dan
;;; : * Added new slots to the model structure to hold the flags
;;; : for normalizing.
;;; 2008.11.03 Dan
;;; : * Updated the chunk and chunk parameter structures to work
;;; : with the new array representation of the parameters.
;;; 2008.11.13 Dan
;;; : * Added the dynamic-update-hooks slot to the model struct.
;;; 2008.12.01 Dan
;;; : * Added the tertiary-reset slot to the module structure.
;;; 2008.12.08 Dan
;;; : * Added the the largest-chunk-type slot to the model struct
;;; : to keep track of the largest possible chunk size.
;;; 2008.12.10 Dan
;;; : * Added the copy-from-chunk slot to the chunk parameter
;;; : struct.
;;; 2009.02.13 Dan
;;; : * Added the base-name slot to chunks to support the new
;;; : short copy names.
;;; : * Added the short-copy-names slot to the model structure too.
;;; 2009.04.29 Dan
;;; : * Adding a slot to the meta-process so I can detect recursive
;;; : calls to run and signal a warning.
;;; 2009.09.09 Dan
;;; : * Added the multi, searchable and chunk-set slots to the buffer
;;; : struct.
;;; 2009.12.03 Dan
;;; : * Adding the dynamics, allow-dynamics, and in-slack to the meta-process
;;; : to provide more flexibility with real-time when a slack-hook
;;; : is used and add the dynamic tag to events.
;;; 2010.01.14 Dan
;;; : * Adding the copy slot to the buffer struct.
;;; 2010.09.02 Dan
;;; : * Added a slot to the meta-process to record whether or not the
;;; : time overflow warning has been displayed or not.
;;; 2010.11.03 Dan
;;; : * Changed the event structure's time slot to be mstime because
;;; : that's what will be used elsewhere. To go with that have
;;; : added an evt-time function which makes the conversion to
;;; : keep the API right.
;;; 2010.12.22 Dan
;;; : * Added a run-notify slot to the module structures to support
;;; : the new run-notify option for modules.
;;; 2011.01.11 Dan
;;; : * Added a run-over-notify slot to the module structures since
;;; : a module may want to know about both situations.
;;; 2011.03.25 Dan
;;; : * Added a safety check to evt-time so that if there's not a
;;; : time it doesn't throw an error.
;;; 2011.04.01 Dan
;;; : * Changed the initial value for the meta-process time to be 0
;;; : instead of 0.0.
;;; 2012.08.08 Dan
;;; : * Adding another slot to the meta-process so that it can
;;; : record the order in which models are defined so that they
;;; : can be reset in that same order for consistency.
;;; 2013.01.03 Dan
;;; : * Adding a max-time-maintenance slot to the meta-process.
;;; 2013.01.04 Dan
;;; : * Added the cannot-define-model slot to the meta-process to
;;; : provide a way of avoiding a nasty situation that can occur
;;; : if something tries to create a model while the "current"
;;; : model is being changed for other reasons. Now, anytime there's
;;; : a (setf (meta-p-current-model ...)) it should be wrapped in
;;; : a (cannot-define-model ...) construct since that macro sets
;;; : and clears this slot.
;;; 2013.01.07 Dan
;;; : * Changed cannot-define-model to be a count since t/nil doesn't
;;; : work since cannot-define-model macros could be nested.
;;; 2013.01.24 Dan
;;; : * Adding a new slot to the chunk-type structure to keep track
;;; : of an index for slots because the production matching code
;;; : builds an array of bufferXslot values but chunk extension
;;; : mixed with subtyping can cause issues with that.
;;; 2013.01.28 Dan
;;; : * Adding another new slot to the chunk-type structure: possible-slots.
;;; : That will hold the names of slots in subtypes of a type but
;;; : not members of the type itself. Needed to allow for the
;;; : ability to specify subtype slots in conditions as constants
;;; : which seems to follow as a logical conclusion, but which hasn't
;;; : been implemented previously.
;;; 2013.05.17 Dan [1.2]
;;; : * Added new slots to the chunk-type structure to indicate
;;; : and manage the new static chunk-types which create
;;; : subtypes instead of growing the base type when extended.
;;; 2013.10.02 Dan
;;; : * Took the # off of the setting for the default break event
;;; : action since that function isn't defined at this point.
;;; 2014.02.12 Dan
;;; : * Added the user-defined slot to chunk-types for use with
;;; : printing 'cannonical' names of types based on the added
;;; : option of defined for the :show-static-subtype-names param.
;;; 2014.02.17 Dan
;;; : * Added the creation-type slot to chunks to allow things like
;;; : this to still work with static chunks:
;;; : (chunk-type foo)
;;; : (chunk-type (bar (:include foo)) slot)
;;; : (define-chunks (a isa bar))
;;; : (set-chunk-slot-value a slot t)
;;; 2014.02.24 Dan [2.0]
;;; : * Chunks no longer maintain a chunk-type, just a vector of filled
;;; : slots and now an immutable tag since changing DM chunks
;;; : will really be a problem without types to organize things.
;;; : * Chunk-types don't have a static specifier since they aren't
;;; : really used at run time and don't need to maintain a lot
;;; : of info.
;;; : * Instead there's a structure for the model which holds the
;;; : chunk-type info instead of just a table of types.
;;; : * Chunk-specs now have filled slot and empty slot vectors
;;; : instead of a type.
;;; 2014.03.13 Dan
;;; : * Chunk-specs now hold more details directly:
;;; : - which slots have multiple specifications
;;; : - which slots have inequality tests
;;; : - which slots have equality tests
;;; : - which slots have negation tests
;;; : - any potential variable markers in slot tests (non alphanumericp
;;; : initial characters)
;;; 2014.03.14 Dan
;;; : * Request parameters get treated just like slots in a chunk-spec
;;; : which means that they will need to be added as slots when
;;; : defined with modules. Keep track of them in the spec for
;;; : comparing a chunk-spec to a chunk-type signature.
;;; 2014.05.14 Dan
;;; : * Maintain query info separately in the chunk-type-info struct.
;;; 2014.06.24 Dan
;;; : * Chunk-types don't need to record subtypes info now.
;;; : * Do want to record the specific parent types given, if any.
;;; 2014.06.25 Dan
;;; : * Record the chunk-type names as they're created in the chunk-
;;; : type-info struct so that printing them out is consistent
;;; : among Lisps and so they don't need to be ordered by inheritance
;;; : when saving a model.
;;; 2014.08.14 Dan
;;; : * Printing module no longer needs the show-all-slots slot.
;;; 2014.09.26 Dan
;;; : * Maintain a sorted list of module names so that things like
;;; : resetting can always be applied in the same order unlike
;;; : maphash which varies from Lisp to Lisp.
;;; 2014.11.04 Dan
;;; : * Added a slot to indicate a request-param to the slot-spec
;;; : structure.
;;; 2015.03.19 Dan
;;; : * Added the flags slot to the buffer struct to handle the
;;; : new failure option and provide a way for implementing other
;;; : such markers in the future.
;;; 2015.06.01 Dan
;;; : * Added the one-time-tags slot to the printing module struct
;;; : to support the new one-time-model-warning command.
;;; 2015.07.29 Dan [2.1]
;;; : * Changed the version number set in the meta-process to be
;;; : the concatenation of the two version strings.
;;; : * Added a precondition slot to events which will be used to
;;; : allow ignoring "unneeded" events.
;;; 2015.08.03 Dan
;;; : * Going back to *actr-version-string* being the whole thing
;;; : and changing that in the version-string file.
;;; 2015.08.25 Dan
;;; : * Adding the real-time-scale slot to the meta-process to make
;;; : it easier to control the scaling in real-time mode.
;;; 2015.09.09 Dan [3.0]
;;; : * Slot added to buffers to indicate whether its module will
;;; : report on completion of requests i.e. trackable.
;;; : * Slot added to model struct for tracking requests.
;;; 2016.04.11 Dan
;;; : * Converted the printing module to a class because then
;;; : supporting the :save-trace parameter and show-model-trace
;;; : command can be done with a class allocated slot to hold
;;; : the event hook ids. Keep the accessors for the slots the
;;; : same as they were for the struct to avoid having to change
;;; : lots of other code too.
;;; 2016.09.27 Dan [4.0]
;;; : * Removed the meta-processes structure.
;;; 2016.09.28 Dan
;;; : * The printing module's event-hook doesn't need to be a hash-table
;;; : since there's only one meta-process.
;;; 2017.02.27 Dan
;;; : * Added class allocated slots to the printing-module to allow
;;; : warnings to be captured cleanly since *error-output* can't
;;; : just be monitored now.
;;; 2017.03.29 Dan
;;; : * Added slots for lock tables in the meta-process and model
;;; : along with a lock in the buffer struct and a class lock in
;;; : the printing-module.
;;; : * Removed the current-model and cannot-define-model slots.
;;; 2017.03.30 Dan
;;; : * Moved the current-mp and current-mp-fct code here.
;;; : * Also moved the model code from internal-macros here.
;;; : * Added with-current-model which works like verify-current-model
;;; : except that it binds current-model to the current model struct
;;; : for use in the body.
;;; : * Moved print-warning here too.
;;; 2017.04.27 Dan
;;; : * Added a lock to the buffer structure to protect access.
;;; 2017.05.30 Dan
;;; : * Adding a new piece to the internal organization -- a "component".
;;; : A component is installed at the meta-process level not the
;;; : model level. It is not directly affected by resets, only
;;; : clear-alls. It has 5 interface functions:
;;; : - creation (called once at define-component time)
;;; : - destroy (called once at undefine-component time)
;;; : - clear-all (called at every clear-all)
;;; : - model-creation (called for every model that's defined)
;;; : - model-destruction (called for every model that's undefined)
;;; : Like a module its returned creation is the 'instance' and
;;; : there will be a get-component command, but since there is
;;; : only 1 instance of a component it may not be necessary.
;;; 2017.06.02 Dan
;;; : * Cleaned up some issues with the "current model" setting and
;;; : use. Now nothing ever setfs *current-act-r-model* and
;;; : current-model-struct is an or of that and the meta-p-default-
;;; : model.
;;; 2017.06.05 Dan
;;; : * Adding slots for reset functions to components.
;;; 2017.06.15 Dan
;;; : * Make the 'current model' macros thread safe by locking the
;;; : read of the meta-process default model slot.
;;; : * Added a lock to the model struct to protect the modules table.
;;; : * Added another lock to the printing module for checking/setting
;;; : parameters within a model (the other lock is class allocated).
;;; : * Add the schedule-lock to the meta-process for locking all of
;;; : the time and event queue access.
;;; : * Add a lock to the modules struct.
;;; 2017.06.16 Dan
;;; : * Added another lock to printing module for the saved trace.
;;; : * Make the printing module param lock recursive.
;;; : * Added a component-lock to the meta-process.
;;; 2017.06.20 Dan
;;; : * Added a lock to the act-r-chunk-type-info struct to protect
;;; : all access. Since chunk-types are only modifided in the
;;; : chunk-type functions the info lock is used to protect the
;;; : underlying structs too.
;;; 2017.06.21 Dan
;;; : * Added a lock for the chunk 'updating' slots to the model.
;;; 2017.06.23 Dan
;;; : * Added names for all the locks.
;;; 2017.06.28 Dan
;;; : * Removed the in-slack slot of the meta-process because it
;;; : isn't used anymore.
;;; 2017.06.29 Dan
;;; : * Add a lock to the model struct for the buffers table.
;;; 2017.05.30 Dan
;;; : * Add a lock for the meta-process event hook slots.
;;; 2017.07.14 Dan
;;; : * Add a lock to the model for tracked-requests.
;;; 2017.09.19 Dan
;;; : * Remove all the slots needed for the printing module to
;;; : support the :save-trace parameter.
;;; 2017.12.07 Dan
;;; : * Added an external slot to modules sturcture.
;;; 2018.02.05 Dan
;;; : * Removed the evt- :conc-name from the event structure and
;;; : added a num slot for use as an id.
;;; : * Added event-id slot to meta-process for creating them.
;;; 2018.02.07 Dan
;;; : * Remove the unnecessary real-time params from the meta-process
;;; : and added the mode.
;;; 2018.04.13 Dan
;;; : * The buffer-lock needs to be a recursive lock because buffer-
;;; : chunk locks it but get-m-buffer-chunks also does for a multi-
;;; : buffer.
;;; 2018.04.17 Dan
;;; : * The modules lock also needs to be recursive.
;;; 2018.06.08 Dan
;;; : * Add a tracked-requests id counter which is what the 'tracker'
;;; : uses to check things.
;;; 2019.01.30 Dan
;;; : * Updating the chunk-spec related structs to eliminate some
;;; : unused slots and add some others to help with how they're used.
;;; 2019.02.05 Dan
;;; : * Adjust meta-p-models to be an alist instead of hashtable.
;;; 2019.02.13 Dan
;;; : * Add a slot to the model to hold a bitvector of buffers with
;;; : chunks in them and slots to the buffer to hold their index
;;; : and a mask.
;;; 2019.03.13 Dan
;;; : * Change the chunk-type-info to get rid of slot->mask and to
;;; : specify tests for the hash tables.
;;; 2019.03.14 Dan
;;; : * Can't use = as the test for a hash-table outside of ACL.
;;; : * Just removing all the tests now.
;;; 2019.03.19 Dan
;;; : * Added a slot to chunk-types for a possible-slots vector.
;;; 2019.04.03 Dan
;;; : * Store a module instance in the buffer struct of a model
;;; : and a list of instances in the model.
;;; 2019.04.03 Dan
;;; : * Added a slot to store the unique slot names in a chunk-spec
;;; : to avoid having to recompute them.
;;; 2019.04.09 Dan
;;; : * Have the event priorities default to 0 and add slots for min
;;; : and max so priority values are always numbers.
;;; 2020.02.12 Dan
;;; : * Added the merge-value slot to chunk parameters.
;;; 2020.05.29 Dan
;;; : * Removed the name from the chunks' locks.
;;; : * Added some slots to the model struct to store chunk-type
;;; : information after module creation to reapply at reset time
;;; : instead of repeatedly calling chunk-type i.e. if a module
;;; : calls it in the creation function it doesn't have to be done
;;; : in the reset function every time.
;;; 2020.06.01 Dan
;;; : * Added some more slots to the model struct for caching the
;;; : creation time chunks as well.
;;; 2020.07.23 Dan
;;; : * Added slots to the act-r-output struct to indicate
;;; : whether the :v and :cmdt are using the same stream to fix
;;; : a problem when they're set to the same file.
;;; 2021.06.03 Dan [5.0]
;;; : * Buffer struct has a slot to store the name of the reusable
;;; : chunk that it will use, and a flag to indicate if it should
;;; : use it.
;;; : * Chunk struct has a slot to indicate not storable.
;;; 2021.10.14 Dan [6.0]
;;; : * Added a new slot to modules to indicate whether they are
;;; : required to exist or not.
;;; : * Also added a slot to models for the parameters it has since
;;; : it will only have parameters for the used modules.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; These are not for general use!
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; NONE!
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; I had some odd compiling order issues with the defstructs and defmacros
;;; so for now the easy fix was to make sure that they are all
;;; available from the start.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function (t &rest t) t) evaluate-act-r-command))
(declaim (ftype (function () t) current-model))
(declaim (ftype (function () t) mp-models))
(defstruct act-r-buffer
"The internal structure for a buffer"
name
chunk ;; holds the chunk name not struct - copy issues and such...
flags
module
spread
queries
requests
(requests-mask 0)
parameter-name
requested
status-printing
multi
searchable
chunk-set
copy
trackable
(lock (bt:make-recursive-lock "buffer-lock"))
index
mask
module-instance
reuse-chunk
reuse?)
(defstruct act-r-chunk-spec
"The internal structure of a chunk-spec"
(filled-slots 0)
(empty-slots 0)
(request-param-slots 0)
(duplicate-slots 0)
(equal-slots 0)
(negated-slots 0)
(relative-slots 0)
variables
slot-vars
dependencies
slots
testable-slots
slot-names)
(defstruct act-r-slot-spec
"The internal structure of a chunk-spec's slot specification"
(modifier '=) name value variable)
(defstruct act-r-chunk-type
"The internal structure of a chunk-type"
name documentation super-types parents
;; don't need this any more: subtypes
slots ;; your slots (direct and inherited) including possible default values
possible-slots ;; slot names only of all the slots of self and children
slot-vector ;; a mask of the direct slots
(possible-slot-vector 0) ;; a mask of the possible-slots
(initial-spec (make-act-r-chunk-spec)))
(defstruct act-r-chunk-type-info
"The structure to hold chunk-type information for a model"
(slot->index (make-hash-table))
(index->slot (make-array (list 0) :adjustable t :fill-pointer t))
(size 0)
(distinct-types (make-hash-table))
extended-slots
query-slots
(table (make-hash-table))
(types (list 'chunk))
(lock (bt:make-recursive-lock "chunk-type")))
(defstruct act-r-chunk
"The internal structure of a chunk"
name base-name
documentation
(filled-slots 0)
slot-value-lists
copied-from
merged-chunks
parameter-values
immutable
not-storable
(lock (bt:make-recursive-lock)))
(defstruct act-r-chunk-parameter
"The internal structure of a chunk parameter"
name index default-value default-function merge merge-value copy copy-from-chunk accessor)
(defstruct act-r-event
"Internal ACT-R event"
mstime (priority 0) action model mp module destination params details (output t)
wait-condition dynamic precondition num min max)
(defstruct (act-r-maintenance-event (:include act-r-event (output 'low)))
"Events for system maintenance")
(defstruct (act-r-break-event
(:include act-r-maintenance-event (action 'act-r-event-break-action)))
"The ACT-R break events"
)
(defstruct (act-r-periodic-event (:include act-r-maintenance-event))
"special event that repeatedly schedules a user's event"
id)
(defstruct (meta-process (:conc-name meta-p-))
"The internal representation of the meta-process"
(time 0)
start-time
start-real-time
(models nil)
(model-count 0)
(model-name-len 0)
events
delayed
dynamics
break
pre-events
post-events
(time-function 'get-internal-real-time)
(units-per-second internal-time-units-per-second)
(slack-function 'real-time-slack)
(time-mode 'interval)
(next-hook-id 0)
(hook-table (make-hash-table))
(event-hook-lock (bt:make-lock "mp-event-hooks"))
(version *actr-version-string*)
(documentation "")
(running nil)
(run-lock (bt:make-lock "run-lock"))
model-order
(models-lock (bt:make-lock "models-lock"))
default-model
(schedule-lock (bt:make-recursive-lock "schedule-lock"))
(event-id 0)
temp-event
(lock-table (make-hash-table :test 'equal))
(component-lock (bt:make-lock "component"))
component-list
(component-length 0)
)
(let ((mp (make-meta-process)))
(defun current-mp ()
mp)
(defun current-mp-fct ()
mp))
(defstruct act-r-component
name
instance
destroy
clear-all
model-create
model-destroy
version
documentation
before-reset
after-reset)
(defmacro verify-current-mp (warning &body body)
(declare (ignore warning))
`(progn ,@body))
(defstruct act-r-output
"The internal structure of an output stream for the printing module"
stream file shared name)
(defclass printing-module ()
((v :accessor printing-module-v :initform (make-act-r-output :stream t))
(c :accessor printing-module-c :initform (make-act-r-output :stream t))
(suppress-cmds :accessor printing-module-suppress-cmds :initform nil)
(filter :accessor printing-module-filter :initform nil)
(detail :accessor printing-module-detail :initform 'high)
(model-warnings :accessor printing-module-model-warnings :initform t)
(cbct :accessor printing-module-cbct :initform nil)
(one-time-tags :accessor printing-module-one-time-tags :initform nil)
(param-lock :accessor printing-module-param-lock :initform (bt:make-recursive-lock "printing-param"))
(capture-warnings :accessor printing-module-capture-warnings :initform nil :allocation :class)
(captured-warnings :accessor printing-module-captured-warnings :initform nil :allocation :class)
(printing-lock :accessor printing-module-lock :initform (bt:make-recursive-lock "printing-lock") :allocation :class)))
;;; print-warning
;;;
;;; (defmacro print-warning (control-string &rest args))
;;;
;;; control-string is a control-string as would be passed to the format function
;;; args are the arguments to use in that control string
;;;
;;; control-string and args are passed to format on the stream *error-output*
;;; with the text "#|Warning: " proceeding it and "|#" after it so that it would
;;; appear as a comment if the stream were to be read.
;;;
;;; nil is returned.
;;; variable for use in suppressing warnings
;;;
(defvar *act-r-warning-capture* (make-instance 'printing-module))
(defmacro print-warning (message &rest arguments)
"Outputs a warning of message and arguments."
`(progn
(evaluate-act-r-command "print-warning" (format nil "~@?" ,message ,@arguments))
nil))
(defstruct act-r-model
"The internal structure of a model"
(modules-table (make-hash-table))
(modules-lock (bt:make-lock "model-modules"))
(buffers-lock (bt:make-lock "model-buffers"))
(buffers (make-hash-table))
(chunk-lock (bt:make-recursive-lock "model-chunk"))
(chunks-table (make-hash-table))
(chunk-ref-table (make-hash-table))
(chunk-types-info (make-act-r-chunk-type-info))
name
code
(chunk-updating-lock (bt:make-lock "model-chunk-updating"))
(chunk-update t)
(dynamic-update t)
delete-chunks
dynamic-update-hooks
short-copy-names
(tracked-requests-lock (bt:make-lock "tracked-requests"))
tracked-requests
(tracked-requests-id 0)
(lock-table (make-hash-table :test 'equal))
(buffer-state 0)
module-instances
starting-slot-vector
starting-ct-size
starting-slot-structs
starting-chunk-types
starting-distinct-types
initial-chunks
params
)
(defvar *current-act-r-model* nil)
(defmacro current-model-struct ()
`(or *current-act-r-model* (let ((mp (current-mp))) (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-default-model mp)))))
(defmacro verify-current-model (warning &body body)
`(if (or *current-act-r-model* (let ((mp (current-mp))) (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-default-model mp))))
(progn ,@body)
(print-warning ,warning)))
(defmacro with-current-model (warning &body body)
`(let ((current-model (or *current-act-r-model* (let ((mp (current-mp))) (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-default-model mp))))))
(if current-model
(progn ,@body)
(print-warning ,warning))))
(defstruct act-r-modules
"The internal structure that holds the modules"
(table (make-hash-table))
(count 0)
(name-len 0)
notify
update
run-notify
run-over-notify
sorted-names
(lock (bt:make-recursive-lock "modules")))
(defstruct act-r-module
"The internal structure of a module"
name buffers version documentation creation reset query
request buffer-mod params delete notify-on-clear update
secondary-reset tertiary-reset warn search offset run-notify run-over-notify
external required)
(defstruct act-r-parameter
"The internal structure of a parameter"
param-name
default
test
warning
details
owner
users)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 34,718 | Common Lisp | .lisp | 767 | 43.432855 | 150 | 0.60469 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d08612aec42f6c269953d7fdab59ffd1ce56bfd722da7709a101795affab6b12 | 14,308 | [
-1
] |
14,309 | meta-process.lisp | asmaloney_ACT-R/framework/meta-process.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : meta-process.lisp
;;; Version : 3.0
;;;
;;; Description : The meta-process handling functions as defined in the
;;; ACT-R 6 software framework API.
;;;
;;;
;;; Bugs :
;;;
;;; To do : [ ] Improve on the max-time-delta situation for multiple models.
;;;
;;; ----- History -----
;;;
;;; 2004.08.11 Dan
;;; : Creation.
;;; 2005.02.28 Dan
;;; : * Made the with-meta-process macro hygienic.
;;; 2006.02.27 Dan
;;; : * Added the mp-real-time-management function to allow one to
;;; : configure external time sources.
;;; 2006.03.03 Dan
;;; : * Updated mp-real-time-management to add the max-time-delta
;;; : parameter. This provides a solution for a problem that can
;;; : occur when hooking a model up to an asynchronous system.
;;; : The problem is that if there aren't any model events to
;;; : process at some point the model just jumps right to its end
;;; : time and waits for real time to catch up and asynchronous
;;; : events that come in effectively get pushed off until then.
;;; : This effectively provides the maximum amount of time that
;;; : the model will "skip ahead" without some event occuring.
;;; : This still isn't perfect for a multi-model situation because
;;; : it only works at the meta-process level and thus one model
;;; : could still end up skipping way ahead if other models were
;;; : still doing things, but it's better than nothing right now.
;;; 2007.08.03 Dan
;;; : * Moved the *meta-processes* definition before the macros
;;; : that use it to avoid a warning at compile time.
;;; 2008.05.05 Dan
;;; : * Fixed a bug with a missing parameter to format in
;;; : delete-meta-process-fct.
;;; 2009.11.30 Dan
;;; : * Make sure to set meta-p-running back to nil on reset because
;;; : some abnormal situations could leave that set.
;;; 2009.12.03 Dan
;;; : * Clear the dynamics and in-slack slots of the meta-process on
;;; : reset and adding an allow-dynamics keyword to mp-real-time-management
;;; : to enable dynamic event testing.
;;; 2010.03.03 Dan
;;; : * Added a with-meta-process-eval like with-model has.
;;; 2010.03.05 Dan
;;; : * Fixed a bug in define-meta-process-fct with the printing of
;;; : the warning when the name is invalid.
;;; 2010.09.02 Dan
;;; : * Added code to allow the coercion of the mp-time variable to
;;; : a different float type.
;;; : * Added commands for checking the accuracy of the mp-time float
;;; : type and allow changing it on the fly.
;;; 2010.11.03 Dan
;;; : * Changing the internal time to be ms and converting it for
;;; : what's sent out (mp-time) which means the accuracy checks
;;; : and conversion code can go away once this is settled.
;;; : * Removed the coercion code, but left the size tests in for
;;; : now just in case that may be useful in the future since
;;; : specifying large event in seconds would still be represented as
;;; : floats that would lose precision.
;;; 2010.12.22 Dan
;;; : * Added mp-modules-events to return a list of all events that
;;; : are scheduled for a module - both active and waiting.
;;; 2011.03.25 Dan
;;; : * Added mp-time-ms as a first step to transitioning everything
;;; : internal to milliseconds to fix the last few lingering issues.
;;; 2011.04.27 Dan
;;; : * Added some declaims to avoid compiler warnings about
;;; : undefined functions.
;;; 2011.06.08 Dan
;;; : * Changed reset-mp and mp-configure-real-time since the latter
;;; : is now documented as a user function so it's got more safety
;;; : checks in it.
;;; 2013.01.03 Dan
;;; : * Added the :delta-maintenance parameter to mp-real-time-management
;;; : to allow setting meta-p-max-time-maintenance.
;;; 2013.01.07 Dan
;;; : * Added the clearing of the cannot-define-model slot to reset-mp.
;;; : * Added a safety check to define-meta-process to prevent the
;;; : creation of new meta-processes while there's some meta-process
;;; : running (basically same issue as defining new models on the fly).
;;; 2014.02.18 Dan
;;; : * Mp-models now returns the models in a deterministic, but
;;; : unspecified order.
;;; 2014.07.17 Dan
;;; : * Mp-print-versions now includes the *actr-major-version-string*
;;; : in the header.
;;; 2014.09.29 Dan
;;; : * Mp-print-versions now uses all-module-names so that they are
;;; : always printed in order.
;;; 2014.09.22 Dan
;;; : * Added mp-queue-count to be able to check if there are any
;;; : active events without having to print them or do some trick
;;; : with aborting a scheduled "after" event.
;;; 2014.11.13 Dan
;;; : * Don't allow mp-real-time-management to adjust things if the
;;; : model is currently running.
;;; 2014.12.17 Dan
;;; : * Changed the declaim for some get-abstract-module because it
;;; : didn't indicate multiple return values and some Lisps care
;;; : about that.
;;; 2015.05.19 Dan
;;; : * Added an optional parameter to mp-show-queue which if true
;;; : indicates events that are in the trace with a *.
;;; 2015.05.20 Dan
;;; : * Added the declaim for event-displayed-p.
;;; 2015.06.03 Dan
;;; : * Commented out the time "accuracy" code since it's not used
;;; : and the variables it is using are being set and used differently
;;; : for other reasons now.
;;; 2015.06.04 Dan
;;; : * Use safe-seconds->ms in mp-real-time-management.
;;; 2015.07.29 Dan
;;; : * Changed how mp-print-versions outputs info for the software
;;; : itself (previously called the framework).
;;; 2015.08.25 Dan
;;; : * Adding a separate scale keyword to mp-real-time-management
;;; : because just adjusting the units-per-second doesn't quite
;;; : work for going faster than real time with the default slack
;;; : hook.
;;; 2016.03.04 Dan
;;; : * mp-print-versions now uses *actr-architecture-version* to
;;; : get the main version info.
;;; 2016.09.27 Dan [2.0]
;;; : * There can be only one! Or maybe, one meta-process to rule
;;; : them all!
;;; : The objective here is to have one central system through
;;; : which everything must communicate and given that the meta-
;;; : process is a discrete-event simulation system it makes sense
;;; : to use that as the central system since much of the existing
;;; : activity progresses through it already. This does remove
;;; : the possibility of asynchronously running models, but given
;;; : how infrequent I suspect that is I think it's an acceptable
;;; : loss given the end objective of opening this up with an
;;; : interface to other systems/languages.
;;; : * Lots of code removed -- basically everything that dealt with
;;; : additional meta-processes.
;;; 2017.02.23 Dan
;;; : * Added a dispatch function for mp-show-queue and now use
;;; : command-output to display the info so remote connections
;;; : can see the output.
;;; 2017.03.31 Dan
;;; : * Added the accessors for testing/setting the running slot
;;; : because it's protected by a lock now.
;;; 2017.05.30 Dan
;;; : * Adding the code to support the use of components.
;;; 2017.06.02 Dan
;;; : * Cleaned up some issues with the "current model" setting and
;;; : don't reset the default in reset-mp.
;;; : * Component model-delete functions can't be called in remove-
;;; : model because it needs to happen before the modules are gone.
;;; 2017.06.05 Dan
;;; : * Adding a reset functions to components. A before and after
;;; : are available based on when the models get reset.
;;; 2017.06.07 Dan
;;; : * Changed mp-show-queue to use meta-p-output since command-
;;; : output depends on current model which prevents it from working
;;; : in a multiple model situation.
;;; 2017.06.15 Dan
;;; : * Making things thread safe: mp-models.
;;; 2017.06.22 Dan
;;; : * Protected meta-p-time with the schedule-lock.
;;; 2017.06.23 Dan
;;; : * Protecting meta-p-delayed.
;;; 2017.06.28 Dan
;;; : * Removed the in-slack slot of the meta-process because it
;;; : isn't used anymore.
;;; : * Protect all the scheduling slots with the schedule-lock.
;;; 2017.07.14 Dan
;;; : * Protect all the meta-p-component-list access.
;;; 2017.08.24 Dan
;;; : * Added the creating-model and deleting-model signals.
;;; : * Added the mp-models command.
;;; 2017.08.28 Dan
;;; : * Added the act-r-running-p command as a remote version of
;;; : mp-running?.
;;; 2017.08.31 Dan
;;; : * Adding a remote version of mp-show-queue which returns the
;;; : text instead of outputing it.
;;; 2017.10.04 Dan
;;; : * Fixed a bug in get-component when the name is invalid.
;;; 2018.01.24 Dan
;;; : * Mp-show-queue now uses act-r-output instead of meta-p-output.
;;; : * Added a remote mp-queue-count.
;;; : * Mp-show-waiting now uses act-r-output.
;;; : * Added a remote mp-show-waiting.
;;; 2018.01.25 Dan
;;; : * Added remote mp-print-versions and adjusted it to use the
;;; : act-r-output command instead of just format t.
;;; 2018.02.05 Dan [3.0]
;;; : * Abstracting the access to event lists and access the event
;;; : internals with act-r-event-... and maintain the count for
;;; : when events are created.
;;; : * Adjusting how real-time management works since it can't just
;;; : spin now and may also want to have a 'real' external clock
;;; : instead of an interval one.
;;; 2018.02.07 Dan
;;; : * Have mp-show-waiting include the wait condition since the
;;; : general event formatter doesn't now.
;;; : * Add a 'user' version of mp-scheduled-events for use in some
;;; : module code (like procedural) which doesn't require actual
;;; : event access.
;;; 2018.02.23 Dan
;;; : * Add a remote delete-event.
;;; 2018.02.26 Dan
;;; : * Fixed a bug in the output of mp-show-waiting.
;;; 2018.06.13 Dan
;;; : * Updated command doc strings to the current spec.
;;; 2018.07.30 Dan
;;; : * Updated some of the comments and changed mp-real-time-management
;;; : back to keyword parameters. When the external version is
;;; : eventually added it can use the options list for them.
;;; 2019.02.05 Dan
;;; : * Adjustments because meta-p-models is now an alist.
;;; 2019.03.22 Dan
;;; : * Next-scheduled-event is only called when the lock is held
;;; : so make that assumption and skip the lock.
;;; 2019.04.09 Dan
;;; : * Adjust compare-events and the scheduling of waiting and
;;; : after events to use the new min and max slots for priority.
;;; 2019.04.15 Dan
;;; : * Replace splice-into-list with splice-into-position-des and
;;; : don't setf with the returned value since it's destructive.
;;; 2019.11.08 Dan
;;; : * Moved the *define-model-lock* definition here from model
;;; : and updated set-mp-running to check that lock and the
;;; : corresponding variable so that it can prevent a run that's
;;; : in the body of a model definition. The lock alone isn't
;;; : sufficient because some Lisps create recursive locks even
;;; : for make-lock.
;;; 2020.05.20 Dan
;;; : * Added a :count 1 to most places that remove an event
;;; : (tried using delete instead of remove but didn't seem to
;;; : make a difference and actually looked like it made things
;;; : worse in some cases).
;;; 2020.08.25 Dan
;;; : * Changed the declaim for format-event to avoid SBCL warning.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;; mp-time
;;; mp-time returns the current time of the current meta-process in seconds.
;;;
;;; mp-models
;;; mp-models returns a list of the names of all the models defined in the current meta-process.
;;;
;;; mp-show-queue
;;; mp-show-queue prints the events that are on the event queue of the current meta-process
;;; to *standard-output* in the order that they would be executed.
;;;
;;; mp-show-waiting
;;; mp-show-waiting prints the events that are in the waiting queue of the current meta-process
;;; along with a description of the condition for which each needs to be added to the event queue to *standard-output*.
;;;
;;; mp-print-versions
;;; mp-print-versions prints the version number of the framework and the name,
;;; version number, and documentation of each module which is currently defined to *standard-output*.
;;;
;;; (defun mp-real-time-management (&key (mode 'interval)
;;; (time-function 'get-internal-real-time)
;;; (units-per-second internal-time-units-per-second)
;;; (slack-function 'real-time-slack))
;;;
;;; mp-real-time-management sets the function and divisor used to determine the
;;; current time in seconds when then real-time flag is specified to run the
;;; meta-process. The slack function is called while the model is waiting for
;;; the time to advance when there is a discrepancy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Using structs for now because I don't need the flexibility of CLOS classes.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype function format-event))
(declaim (ftype (function () t) global-modules-table))
(declaim (ftype (function () t) max-module-name-length))
(declaim (ftype (function (t) t) delete-model-fct))
(declaim (ftype (function (t) (values t t)) get-abstract-module))
(declaim (ftype (function () t) all-module-names))
(declaim (ftype (function (t) t) event-displayed-p))
(defun reset-mp (meta-process)
"Set a meta-process to time 0 and clear the events"
(clear-mp-running)
(bt:with-recursive-lock-held ((meta-p-schedule-lock meta-process))
(setf (meta-p-time meta-process) 0)
(setf (meta-p-start-time meta-process) nil)
(setf (meta-p-start-real-time meta-process) nil)
(setf (meta-p-events meta-process) nil)
(setf (meta-p-delayed meta-process) nil)
(setf (meta-p-dynamics meta-process) nil)
(setf (meta-p-temp-event meta-process) nil)
(setf (meta-p-time-mode meta-process) 'interval)
(setf (meta-p-time-function meta-process) 'get-internal-real-time)
(setf (meta-p-units-per-second meta-process) internal-time-units-per-second)
(setf (meta-p-slack-function meta-process) 'real-time-slack)
(setf (meta-p-event-id meta-process) 0)))
(defun mp-running? ()
(awhen (current-mp)
(bt:with-lock-held ((meta-p-run-lock it))
(meta-p-running it))))
(add-act-r-command "act-r-running-p" 'mp-running? "Predicate to check whether or not the system is currently running. No params.")
(defvar *define-model-lock* (bt:make-lock "define-model"))
(defvar *defining-model* nil)
(defun set-mp-running (warning)
(awhen (current-mp)
(let ((l (bt:acquire-lock *define-model-lock* nil)))
(if (null l)
(print-warning "Cannot run the system while a model is being defined or deleted.")
(unwind-protect
(if *defining-model*
(print-warning "Cannot run the system while a model is being defined or deleted.")
(bt:with-lock-held ((meta-p-run-lock it))
(if (meta-p-running it)
(print-warning warning)
(setf (meta-p-running it) t))))
(bt:release-lock *define-model-lock*))))))
(defun clear-mp-running ()
(awhen (current-mp)
(bt:with-lock-held ((meta-p-run-lock it))
(setf (meta-p-running it) nil))))
(add-act-r-command "creating-model" nil "Signal for a model being created for monitoring purposes. Params: model-name." nil)
(defun add-new-model (name model-struct)
(awhen (current-mp)
(dispatch-apply "creating-model" name)
(bt:with-lock-held ((meta-p-models-lock it))
(push (cons name model-struct) (meta-p-models it))
(push-last name (meta-p-model-order it))
(incf (meta-p-model-count it))
(when (> (length (symbol-name name)) (meta-p-model-name-len it))
(setf (meta-p-model-name-len it) (length (symbol-name name))))
(dolist (c (bt:with-lock-held ((meta-p-component-lock it)) (meta-p-component-list it)))
(when (act-r-component-model-create (cdr c))
(funcall (act-r-component-model-create (cdr c)) (act-r-component-instance (cdr c)) name)))
(if (= 1 (meta-p-model-count it))
(setf (meta-p-default-model it) model-struct)
(setf (meta-p-default-model it) nil)))))
(add-act-r-command "deleting-model" nil "Signal for a model being deleted for monitoring purposes. Params: model-name." nil)
(defun remove-model (name)
(awhen (current-mp)
(dispatch-apply "deleting-model" name)
(bt:with-lock-held ((meta-p-models-lock it))
(setf (meta-p-models it) (remove name (meta-p-models it) :key 'car))
(setf (meta-p-model-order it) (remove name (meta-p-model-order it)))
(decf (meta-p-model-count it))
(when (= (length (symbol-name name)) (meta-p-model-name-len it))
(setf (meta-p-model-name-len it)
(apply 'max (cons 0 (mapcar (lambda (x) (length (symbol-name x))) (meta-p-model-order it))))))
(if (= 1 (meta-p-model-count it))
(setf (meta-p-default-model it) (cdr (assoc (first (meta-p-model-order it)) (meta-p-models it))))
(setf (meta-p-default-model it) nil)))))
(defun mp-time ()
"returns the current time of the current meta-process in seconds"
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(ms->seconds (meta-p-time mp)))))
(add-act-r-command "mp-time" 'mp-time "Return the current simulation time in seconds. No params.")
(defun mp-time-ms ()
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(meta-p-time mp))))
(add-act-r-command "mp-time-ms" 'mp-time-ms "Return the current simulation time in milliseconds. No params.")
(defun real-time-slack (current-time next-time)
(declare (ignore current-time next-time))
(bt:thread-yield))
(defun mp-real-time-management (&key (mode 'interval)
(time-function 'get-internal-real-time)
(units-per-second internal-time-units-per-second)
(slack-function 'real-time-slack))
(verify-current-mp
"mp-real-time-management called with no current meta-process."
(cond ((not (or (eq mode 'interval) (eq mode 'absolute)))
(print-warning "Mode ~s not a valid value for mp-real-time-management. Must be absolute or interval." mode))
((not (and time-function (local-or-remote-function-or-nil time-function)))
(print-warning "Time-function ~s not a valid function for mp-real-time-management" time-function))
((not (posnum units-per-second))
(print-warning "Units-per-second ~s must be a positive number" units-per-second))
((not (and slack-function (local-or-remote-function-or-nil slack-function)))
(print-warning "Slack-function ~s not a valid function for mp-real-time-management" slack-function))
((mp-running?)
(print-warning "Mp-real-time-management cannot adjust real-time operation while the model is running."))
(t
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(setf (meta-p-time-mode mp) mode)
(setf (meta-p-time-function mp) time-function)
(setf (meta-p-units-per-second mp) units-per-second)
(setf (meta-p-slack-function mp) slack-function)
))
t))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Abstracting the access to the meta-process events because
;;; I may want to change internal rep. at some point, and since
;;; I need to update all the event accessors for remote access
;;; might as well handle that now too.
(defun mp-scheduled-events (mp) ;; Returns a list of events
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(copy-list (meta-p-events mp))))
;; A "user" version where user is really me but in code that's
;; outside of the framework, like procedural.
(defun scheduled-events ()
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(mapcar 'act-r-event-num (meta-p-events mp)))))
(defun mp-delayed-events (mp) ;; Returns a list of events
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(copy-list (meta-p-delayed mp))))
(defun mp-all-events (mp)
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(append (meta-p-events mp) (meta-p-delayed mp))))
(defun get-event-by-id (id)
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(or (find id (meta-p-events mp) :key 'act-r-event-num :test '=)
(find id (meta-p-delayed mp) :key 'act-r-event-num :test '=)
(and (meta-p-temp-event mp) (= id (act-r-event-num (meta-p-temp-event mp)))
(meta-p-temp-event mp))))))
(defun delete-all-model-events (mp name)
(let ((model (get-model name)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(setf (meta-p-events mp)
(remove model (meta-p-events mp) :key #'act-r-event-model))
(setf (meta-p-delayed mp)
(remove model (meta-p-delayed mp) :key #'act-r-event-model))
(setf (meta-p-dynamics mp)
(remove model (meta-p-dynamics mp) :key #'(lambda (x) (act-r-event-model (car x))))))))
(defun next-scheduled-event (mp)
;; assume this is true! (bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(first (meta-p-events mp)))
(defun remove-scheduled-event (mp event)
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(setf (meta-p-events mp) (remove event (meta-p-events mp) :test 'eq :count 1))
(when (act-r-event-dynamic event)
(setf (meta-p-dynamics mp) (remove event (meta-p-dynamics mp) :key 'car :test 'eq :count 1)))
(setf (meta-p-temp-event mp) event)))
(defun remove-tagged-events (mp tag &key (key 'act-r-event-num) (test '=) (count 1))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(setf (meta-p-events mp)
(remove tag (meta-p-events mp) :key key :test test :count count))))
;;; insert-queue-event
;;;
;;; This function takes two parameter which are a meta-process and an
;;; event. The event is added to the list of scheduled events for the
;;; meta-process in order based on its time and priority.
;;;
;;; Items are ordered by time first, lower times occuring before higher
;;; times. If two events have the same time then:
;;;
;;; An event with priority :max occurs before any event in the queue with
;;; the same time except existing events of :max
;;; priority
;;; An event with a numeric priority occurs before an event with a lesser
;;; numbered priority or a priority of :min
;;; An event with priority :min occurs after any events at that time
;;;
(defun insert-queue-event (mp event &key now delta)
"Place an event into the scheduled-events list maintaning the ordering"
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(unless (act-r-event-num event)
(setf (act-r-event-num event) (incf (meta-p-event-id mp))))
(when (or now delta)
(setf (act-r-event-mstime event)
(if now
(meta-p-time mp)
(+ (meta-p-time mp) delta))))
(when (< (act-r-event-mstime event) (meta-p-time mp))
(print-warning "Event with action ~s and time ~s specifies a time that's already past. Scheduling for current time ~s."
(act-r-event-action event) (act-r-event-mstime event) (mp-time))
(setf (act-r-event-mstime event) (meta-p-time mp)))
(if (null (meta-p-events mp))
(push event (meta-p-events mp))
(do* ((pos 0 (1+ pos))
(queue (meta-p-events mp) (cdr queue)))
((or (null queue)
(compare-events event (car queue)))
(splice-into-position-des (meta-p-events mp) pos event))))
(when (or (meta-p-delayed mp) (meta-p-dynamics mp))
(update-waiting-events mp event))))
(defun insert-final-queue-event (mp event)
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(unless (act-r-event-num event)
(setf (act-r-event-num event) (incf (meta-p-event-id mp))))
(setf (act-r-event-mstime event)
(if (meta-p-events mp)
(act-r-event-mstime (car (last (meta-p-events mp))))
(meta-p-time mp)))
(push-last event (meta-p-events mp))))
;;; This comparison rule is now the specified operation!
;;; If this is changed for some reason the same ordering needs
;;; to be maintained -- always schedule the new event after
;;; existing events with the same priority.
(defun compare-events (new-event old-event)
(or (< (act-r-event-mstime new-event) (act-r-event-mstime old-event))
(and (= (act-r-event-mstime new-event) (act-r-event-mstime old-event))
(null (act-r-event-max old-event))
(null (act-r-event-min new-event))
(or (act-r-event-max new-event)
(act-r-event-min old-event)
(and (> (act-r-event-priority new-event)
(act-r-event-priority old-event)))))))
;;; update-waiting-events
;;;
;;; This function takes two parameters, a meta-process and an event. The
;;; list of waiting events for the meta-process is checked to see if the
;;; event specified allows any of them to be added to the scheduled events.
;;; If an event can be moved to the scheduled events list it is removed
;;; from the waiting events list and it is added to the scheduled events
;;; list (which will call update-waiting-events to test whether that event
;;; frees others from the waiting list).
;;; The list of dynamic events is also tested in the same way as the
;;; waiting events.
(defun update-waiting-events (mp new-event)
"Check the list of waiting events to see if a new event allows any to run"
(let ((moved-events nil))
; assumed since it's only called from insert-queue-event (bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(dolist (event (meta-p-delayed mp))
(when (conditions-met event new-event)
(setf (meta-p-delayed mp) (remove event (meta-p-delayed mp) :count 1))
(unless (act-r-event-dynamic event)
(setf (act-r-event-wait-condition event) nil))
(push event moved-events)))
(dolist (event-check (meta-p-dynamics mp))
(let ((event (car event-check))
(cur-time (cdr event-check)))
(when (and (< (act-r-event-mstime new-event) cur-time)
(conditions-met event new-event))
(setf (meta-p-events mp) (remove event (meta-p-events mp) :count 1))
(setf (meta-p-dynamics mp) (remove event-check (meta-p-dynamics mp) :count 1))
(push event moved-events))))
(dolist (event moved-events)
(setf (act-r-event-mstime event) (act-r-event-mstime new-event))
(setf (act-r-event-min event) :min)
(insert-queue-event mp event))
(dolist (event moved-events)
(when (act-r-event-dynamic event)
(push (cons event (act-r-event-mstime new-event)) (meta-p-dynamics mp))))))
;;; conditions-met
;;;
;;; This function takes two parameters which are a waiting-event and a
;;; new-event.
(defun conditions-met (w-event new-event)
"Test whether a waiting event's wait-for reason is met by a new event"
(case (car (act-r-event-wait-condition w-event))
(:any (and (eq (act-r-event-model w-event) (act-r-event-model new-event))
(or (second (act-r-event-wait-condition w-event))
(not (act-r-maintenance-event-p new-event)))))
(:module (and (or (eq (act-r-event-model w-event) (act-r-event-model new-event))
(null (act-r-event-model w-event)))
(eq (second (act-r-event-wait-condition w-event))
(act-r-event-module new-event))
(or (third (act-r-event-wait-condition w-event))
(not (act-r-maintenance-event-p new-event)))))
(t nil)))
(defun insert-waiting-event (mp new-event delay)
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(let ((matching-event (find-if (lambda (x)
(conditions-met new-event x))
(meta-p-events mp))))
(cond (matching-event
(setf (act-r-event-mstime new-event)
(act-r-event-mstime matching-event))
(unless (act-r-event-dynamic new-event)
(setf (act-r-event-wait-condition new-event) nil))
(insert-queue-event mp new-event)
(when (act-r-event-dynamic new-event)
(push (cons new-event (act-r-event-mstime new-event)) (meta-p-dynamics mp)))
(values (act-r-event-num new-event) (if (act-r-event-wait-condition new-event) t nil)))
((null delay)
(setf (act-r-event-mstime new-event) (meta-p-time mp))
(setf (act-r-event-max new-event) :max)
(setf (act-r-event-wait-condition new-event) nil)
(setf (act-r-event-dynamic new-event) nil)
(insert-queue-event mp new-event)
(values (act-r-event-num new-event) nil))
((eq delay :abort)
(values nil :abort))
(t
(setf (act-r-event-num new-event) (incf (meta-p-event-id mp)))
(push new-event (meta-p-delayed mp))
(values (act-r-event-num new-event) t))))))
(defun delete-event (event-num)
(cond ((not (numberp event-num)) (print-warning "~S is not a valid event identifier." event-num))
(t
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(let ((l (+ (length (meta-p-events mp)) (length (meta-p-dynamics mp)) (length (meta-p-delayed mp)))))
(setf (meta-p-events mp) (remove event-num (meta-p-events mp) :key 'act-r-event-num :test '= :count 1))
(setf (meta-p-dynamics mp) (remove event-num (meta-p-dynamics mp) :key (lambda (x) (act-r-event-num (car x))) :test '= :count 1))
(setf (meta-p-delayed mp) (remove event-num (meta-p-delayed mp) :key 'act-r-event-num :test '= :count 1))
(not (= l (+ (length (meta-p-events mp)) (length (meta-p-dynamics mp)) (length (meta-p-delayed mp)))))))))))
(add-act-r-command "delete-event" 'delete-event "Remove an event which has been scheduled. Params: event-id")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mp-models ()
"returns a list of the names of all the models in the current meta-process"
(let ((mp (current-mp)))
(bt:with-lock-held ((meta-p-models-lock mp))
(meta-p-model-order mp))))
(add-act-r-command "mp-models" 'mp-models "Return a list of all existing model names. No params." nil)
(defun mp-show-queue (&optional indicate-traced)
(let ((events (mp-scheduled-events (current-mp))))
(act-r-output "Events in the queue:")
(dolist (evt events (length events))
(act-r-output "~:[~*~;~:[ ~;*~]~]~A" indicate-traced (event-displayed-p evt) (format-event evt)))))
(add-act-r-command "mp-show-queue" 'mp-show-queue "Print out a description of the events currently scheduled to occur optionally indicating which will show in the trace. Params: {mark-traced?}")
(defun mp-queue-text (&optional indicate-traced)
(let ((s (make-string-output-stream))
(events (mp-scheduled-events (current-mp))))
(dolist (evt events)
(format s "~:[~*~;~:[ ~;*~]~]~A~%" indicate-traced (event-displayed-p evt) (format-event evt)))
(prog1
(get-output-stream-string s)
(close s))))
(add-act-r-command "mp-queue-text" 'mp-queue-text "Return the text contianing a description of the events currently scheduled to occur optionally indicating which will show in the trace. Params: {mark-traced?}")
(defun mp-queue-count ()
(let ((events (mp-scheduled-events (current-mp))))
(length events)))
(add-act-r-command "mp-queue-count" 'mp-queue-count "Return the number of the events currently scheduled to occur. No params.")
(defun mp-show-waiting ()
(let ((events (mp-delayed-events (current-mp))))
(act-r-output "Events waiting to be scheduled:~%")
(dolist (evt events (length events))
(act-r-output "~A Waiting for: ~s~%" (format-event evt) (act-r-event-wait-condition evt)))))
(add-act-r-command "mp-show-waiting" 'mp-show-waiting "Print out a description of the events which are currently waiting to be scheduled. No params.")
(defun mp-modules-events (module)
(let ((events (mp-all-events (current-mp)))
(results nil))
(dolist (e events results)
(when (eq module (act-r-event-module e))
(push (act-r-event-num e) results)))))
(defun mp-print-versions ()
(let ((mp (current-mp)))
(act-r-output "ACT-R ~a Version Information:~%~va: ~10a ~a" *actr-architecture-version*
(max (max-module-name-length) 10)
"Software"
(meta-p-version mp)
(meta-p-documentation mp))
(act-r-output "=================================================")
(bt:with-lock-held ((meta-p-component-lock mp))
(when (meta-p-component-list mp)
(act-r-output "Components")
(act-r-output "-------------------------------------------------")
(dolist (c (meta-p-component-list mp))
(act-r-output "~va: ~10a ~a"
(max (meta-p-component-length mp) 10)
(car c)
(act-r-component-version (cdr c))
(act-r-component-documentation (cdr c))))
(act-r-output "=================================================")))
(act-r-output "Modules")
(act-r-output "-------------------------------------------------")
(dolist (name (all-module-names))
(let ((module (get-abstract-module name)))
(act-r-output "~va: ~10a ~a"
(max (max-module-name-length) 10)
name
(act-r-module-version module)
(act-r-module-documentation module))))))
(add-act-r-command "mp-print-versions" 'mp-print-versions "Print out the version information for the overall software and all the components and modules. No params.")
;;;;;; Support for components
;;;;;; Since they're defined at the meta-process level putting
;;;;;; them in this file instead of a separate one.
(defmacro define-component (name &key (version nil) (documentation nil)
(creation nil) (delete nil)
(clear-all nil) (create-model nil) (delete-model nil)
(before-reset nil) (after-reset nil))
`(define-component-fct ',name ,@(when version `(:version ,version))
,@(when documentation `(:documentation ,documentation))
:creation ',creation :delete ',delete :clear-all ',clear-all
:create-model ',create-model :delete-model ',delete-model
:before-reset ',before-reset :after-reset ',after-reset))
(defun define-component-fct (name &key (version "" version?) (documentation "" docs?)
creation delete clear-all create-model delete-model
before-reset after-reset)
(let ((mp (current-mp)))
(unless (and version? docs?)
(print-warning "Components should always provide a version and documentation string."))
(cond ((mp-models)
(print-warning "Cannot create a new component when there are models defined."))
((null name)
(print-warning "Nil is not a valid component name. No component defined."))
((not (symbolp name))
(print-warning "~s is not a symbol and thus not a valid component name.~%No component defined." name))
((assoc name (bt:with-lock-held ((meta-p-component-lock mp))
(meta-p-component-list mp)))
(print-warning "Componenet named ~S already exists. Delete it with undefine-component if you want to redefine it." name))
((not (and (fctornil creation) (fctornil delete) (fctornil clear-all)
(fctornil create-model) (fctornil delete-model)
(fctornil before-reset) (fctornil after-reset)))
(print-warning "Invalid parameter for a component call-back function")
(do ((items (list creation delete clear-all create-model delete-model before-reset after-reset)
(cdr items))
(names '(creation delete clear-all create-model delete-model before-reset after-reset)
(cdr names)))
((null items))
(unless (fctornil (car items))
(print-warning "Parameter: ~s is not a function, function name, or nil" (car names))))
(print-warning "Component ~s not defined" name))
(t
(let* ((instance (when creation
(funcall creation)))
(component (make-act-r-component :name name
:instance instance
:destroy delete
:clear-all clear-all
:model-create create-model
:model-destroy delete-model
:before-reset before-reset
:after-reset after-reset
:version version
:documentation documentation)))
(bt:with-lock-held ((meta-p-component-lock mp))
(setf (meta-p-component-list mp) (sort (push (cons name component) (meta-p-component-list mp)) 'string< :key (lambda (x) (symbol-name (car x)))))
(when (> (length (format nil "~S" name)) (meta-p-component-length mp))
(setf (meta-p-component-length mp) (length (format nil "~S" name)))))
name)))))
(defmacro undefine-component (name)
`(undefine-component-fct ',name))
(defun undefine-component-fct (name)
(let ((mp (current-mp)))
(cond ((mp-models)
(print-warning "Cannot delete a component when there are models defined."))
((not (assoc name (bt:with-lock-held ((meta-p-component-lock mp)) (meta-p-component-list mp))))
(print-warning "~S is not the name of a currently defined component." name))
(t
(bt:with-lock-held ((meta-p-component-lock mp))
(let ((c (cdr (assoc name (meta-p-component-list mp)))))
(when (act-r-component-destroy c)
(funcall (act-r-component-destroy c) (act-r-component-instance c)))
(setf (meta-p-component-list mp) (remove name (meta-p-component-list mp) :key 'car))
(when (= (length (format nil "~S" name)) (meta-p-component-length mp))
(setf (meta-p-component-length mp)
(if (meta-p-component-list mp)
(apply #'max (mapcar #'(lambda (x)
(length (format nil "~S" (car x))))
(meta-p-component-list mp)))
0)))))
t))))
(defmacro get-component (name)
`(get-component-fct ',name))
(defun get-component-fct (name)
(let ((mp (current-mp)))
(aif (assoc name (bt:with-lock-held ((meta-p-component-lock mp))
(meta-p-component-list mp)))
(values (act-r-component-instance (cdr it)) t)
(values (print-warning "~s does not name a current component." name) nil))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 44,142 | Common Lisp | .lisp | 792 | 48.811869 | 211 | 0.594769 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d206d981246fb00ef46bc5bf83cb542d953990eff2fa43a11f92d220a55a74b1 | 14,309 | [
-1
] |
14,310 | chunks.lisp | asmaloney_ACT-R/framework/chunks.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : chunks.lisp
;;; Version : 6.0
;;;
;;; Description : Definition of chunks and the function that manipulate them.
;;;
;;; Bugs :
;;;
;;; To do : * Finish the documentation.
;;; : * This one is a big target for benchmarking and optimizing.
;;; : * Should merge-chunks impact chunk-copied-from?
;;; ----- History -----
;;;
;;; 2004.09.02 Dan
;;; : Creation
;;; 2005.01.16 Dan
;;; : * Added chunk-copied-from.
;;; : * Reduced most things to 80 columns (I don't want to split
;;; : the format string because I've had problems with the ~
;;; : new-line breaking with "non-native" line endings).
;;; : * Added doc strings.
;;; : * Modified pprint-a-chunk so it can print with or without
;;; : the parameters.
;;; : * Removed the print-chunk-type function since I don't want to
;;; : hide the structure since users shouldn't see them anyway.
;;; 2005.01.17 Dan
;;; : * Switched to using command-output for printing.
;;; : * Renamed pprint-chunk pprint-chunkS and took away its
;;; : printing of chunk parameters and added pprint-chunks-plus
;;; : to display chunks with chunk parameters.
;;; 2005.01.21 Dan
;;; : * Updated merge-chunks-fct to work more efficiently.
;;; 2005.01.24 Dan
;;; : * Fixed some bugs I introduced with the changes to pprint-
;;; : chunks and pprint-chunks-plus - I changed their return
;;; : value which broke other things...
;;; 2005.02.04 Dan
;;; : * Added the fast-* chunk accessors to eliminate the
;;; : excessive calling of valid-slot-name.
;;; 2005.02.09 Dan
;;; : * Fixed a bug that the fast-* stuff introduced with respect
;;; : to printing chunks.
;;; 2005.02.11 Dan
;;; : * Some general clean up in define-chunks-fct.
;;; 2005.03.24 Dan
;;; : * Changed the pprint-a-chunk function because it turns out
;;; : that some Lisps don't like using the pre-formatted format
;;; : string with the ~? directive.
;;; 2005.03.25 Dan
;;; : * Changed pprint-a-chunk so that the slots print in the
;;; : same order as the chunk-type.
;;; 2005.04.01 Dan
;;; : * Added true-chunk-name to help with an issue in merging
;;; : and may want to use it in printing and elsewhere...
;;; 2005.04.07 Dan
;;; : * Fixed a minor issue with define-chunks and how it creates
;;; : the name for a chunk without one specified.
;;; 2005.05.07 Dan
;;; : * Changed copy-chunk-fct so that instead of naming the new
;;; : chunk based on the chunk-type it bases it on the actual
;;; : name of the chunk being copied. I think this is easier
;;; : to follow in the traces, but maybe it's more confusing.
;;; : We'll find out from experience I guess and then determine
;;; : which is better...
;;; 2005.06.11 Dan
;;; : * DOH! I remember again why I used the chunktype for the
;;; : name of the copy - because vision for example uses things
;;; : like loc1 which now when copied ends up as loc10 which
;;; : of course looks like "loc"+"10" instead of "loc1"+"0".
;;; : So, I've changed it so that it adds a - between the
;;; : chunk's name and the number so that would be loc1-0.
;;; 2005.08.10 Dan
;;; : * Minor clean-up in define-chunks to remove unused variables
;;; : in the let.
;;; : * Updated version to 1.0.
;;; 2005.09.14 Dan
;;; : * Fixed a bug in the output of a warning in define-chunks-fct
;;; : because invalid slot names weren't printed.
;;; 2005.11.17 Dan
;;; : * Fixed some bugs in define-chunks-fct and pprint-a-chunk
;;; : related to default slot values in the chunk-type.
;;; 2006.01.03 Dan
;;; : * Modified extend-chunks to remove the explicit compile call
;;; : (but still result in a compiled function at all times) to
;;; : hopefully get around the CMUCL issue.
;;; 2006.01.18 Dan
;;; : * Modified the chunk printing function so that it can suppress
;;; : the "unfilled" extended slots of a chunk if desired.
;;; 2006.02.20 Dan
;;; : * Fixed a bug in extend-chunks that causes problems with chunk
;;; : parameters when merged when the ACT-R is both compiled and
;;; : loaded in the same session i.e. if one loads a previously
;;; : compiled version there's no problem so it shouldn't have
;;; : caused too many problems.
;;; 2006.07.06 Dan
;;; : * Fixed a bug in define-chunks-fct. When a chunk-type
;;; : specified a default value for a slot which was a symbol (thus
;;; : interepreted as a chunk name) nothing ever created such a
;;; : chunk if it wasn't defined. It doesn't make sense to do it
;;; : at the time of the chunk-type definition (because you may not
;;; : be able to create the chunk you want first) so it now happens
;;; : when such a slot value gets set (just like it does for any
;;; : non-chunk name symbols in the specified chunk slots).
;;; 2006.07.10 Dan
;;; : * Added get-chunk-warn for use in several of the "user" functions
;;; : because they don't provide a warning if the chunk-name is
;;; : invalid, but since get-chunk is used for other purposes,
;;; : I don't want to change it directly.
;;; : * Added changed true-chunk-name to true-chunk-name-fct and
;;; : added a macro for true-chunk-name to make it user accessible.
;;; 2006.07.11 Dan
;;; : * Made merge-chunks "safe" because previously it would merge
;;; : un-equal chunks as long as both items were really chunks.
;;; : Didn't cause problems since DM did the check first anyway,
;;; : but may be an issue if other modules were to use it.
;;; 2006.08.08 Dan
;;; : * Put a test into define-chunks-fct so that it doesn't result
;;; : in errors for malformed add-dm/define-chunks calls, but just
;;; : prints a warning.
;;; 2006.10.10 Dan
;;; : * Added the normalize-chunk-names command which goes through
;;; : all of the model's chunks and replaces any refrence to a
;;; : chunk name in a slot with the chunk's "true" name and then
;;; : optionally releases any non-true name i.e. the name that
;;; : was "merged away". Generally, this probably won't see
;;; : much use, but cleaning up the references may be useful at
;;; : times, and if a model creates so many names that the symbol
;;; : table becomes a memory limiter clearing those out maybe
;;; : necessary.
;;; 2006.10.17 Dan
;;; : * Minor bug fix in normalize-chunk-names for the unintern
;;; : clause.
;;; 2006.10.20 Dan
;;; : * More clean-up added to normalize-chunk-names - should free
;;; : up more memory in the unintern case now.
;;; 2007.01.04 Dan
;;; : * Minor tweak to chunk-copied-from-fct to make sure that the
;;; : "copied-from" chunk still exists - which may not be the case
;;; : for something like a goal or imaginal requests which delete
;;; : the original.
;;; 2007.01.15 Dan
;;; : * Bug from that last update fixed - use chunk-p-fct instead
;;; : of chunk-p...
;;; 2007.07.13 Dan
;;; : * Performance enhancement for normalize-chunk-names - it
;;; : can skip checking the chunks for which the name change is
;;; : being done. Duh!
;;; 2008.04.15 Dan
;;; : * Performance improvement for delete-chunk-fct. Assume that
;;; : the only way to get "eq" chunks in the table is through
;;; : merging so don't need to search the whole table to find
;;; : them for deletion - just use the merge-list from the chunk's
;;; : truename as the set of chunks to delete.
;;; 2008.04.16 Dan
;;; : * Minor tweaks to normalize-chunk-names: if there aren't any
;;; : merged chunks it terminates early (unlikely situation) and
;;; : it now uses the fast- chunk component accessors.
;;; 2008.07.01 Dan
;;; : * Added purge-chunk command to both delete and release the
;;; : name of the chunk.
;;; 2008.07.30 Dan
;;; : * Changed an append to an nconc in merge-chunks-fct because
;;; : there's no need to copy the lists and performance wise it
;;; : makes a difference in the long run.
;;; 2008.07.31 Dan
;;; : * Moved chunk-slot-equal from chunk-spec to here and removed
;;; : the equivalent equal-compare-slot-values function since
;;; : there don't need to be two such functions.
;;; : * Also improved chunk-slot-equal so that it doesn't need to
;;; : use eq-chunks-fct which may save 10% or more time wise for
;;; : models becuase it removes duplicate lookups.
;;; : * Added the testing of val1 and val2 back into the chunk
;;; : case of chunk-slot-equal since a nil can short-circuit the
;;; : chunk lookup - slows down the chunk only cases but speeds
;;; : up the nil tests which is probably more common in the
;;; : average model.
;;; 2008.10.08 Dan
;;; : * Improvement to normalize-chunk-names so it doesn't have to
;;; : look up non-chunks.
;;; 2008.10.20 Dan [1.1]
;;; : * Made changes to add the option of having chunk merging
;;; : work like the older ACT-R versions where it essentially
;;; : normalizes as it goes. It can be enabled via the :dcnn
;;; : parameter and is on by default.
;;; 2008.10.30 Dan
;;; : * Tweaked chunk-slot-equal to make it a little more efficient.
;;; 2008.11.03 Dan [1.2]
;;; : * Changed the internals of how chunk parameters get stored
;;; : from a hash-table to an array and added extra lists so that
;;; : copying and merging don't need to loop over all the parameters.
;;; 2008.11.04 Dan
;;; : * Fixed a minor bug with how the parameter copy list gets
;;; : created because compiling and loading the chunks file would
;;; : lead to calling the copy functions twice.
;;; 2008.11.11 Dan
;;; : * Fixed a bug in the chunk copy code.
;;; 2008.11.13 Dan
;;; : * Modified chunk normalizing so that it calls the hook fn's
;;; : when it changes chunk slot values.
;;; 2008.12.10 Dan
;;; : * Added the :copy-from-chunk-function keyword to extend
;;; : chunks because sometimes having access to the original
;;; : chunk may be useful when copying a parameter.
;;; 2009.02.13 Dan
;;; : * Modified chunk-copy-fct to better control for size since
;;; : the ANSI CL spec doesn't require this to be true:
;;; :
;;; : (let* ((ht1 (make-hash-table))
;;; : (s1 (hash-table-size ht1))
;;; : (ht2 (make-hash-table :size s1))
;;; : (s2 (hash-table-size ht2)))
;;; : (= s1 s2))
;;; :
;;; : which can result in runaway memory usage if a chunk gets
;;; : copied, then the copy gets copied, and so on, in a Lisp which
;;; : "rounds up" the size (ACL and possibly others).
;;; 2009.02.13 Dan
;;; : * Modified chunk-copy-fct to use the new option of "short
;;; : chunk copy names". So, instead of A-0-0-0-0 one would have
;;; : A-3 instead.
;;; 2009.04.23 Dan
;;; : * Fixed a bug introduced in chunk-slot-equal the last time it
;;; : was updated which caused t to match any non-chunk value if
;;; : t was also not explicitly defined as a chunk.
;;; 2010.04.30 Dan
;;; : * Updated delete-chunk-fct so that it doesn't print a double
;;; : warning for deleting a chunk which is still used and also
;;; : fixed an unnecessary ' in the warning.
;;; 2010.08.16 Dan
;;; : * Fixed a bug in delete-chunk-fct that would throw an error
;;; : if a non-chunk were passed in.
;;; 2010.08.17 Dan
;;; : * Changed the extend-chunk macro so that the accessor and setf
;;; : funtions for a parameter include the parameter in the warning
;;; : when there's a bad chunk name provided.
;;; 2011.04.27 Dan
;;; : * Added some declaims to avoid compiler warnings about
;;; : undefined functions.
;;; 2011.04.28 Dan
;;; : * Added a mechanism for suppressing the warnings that get
;;; : printed when chunks are extended during compile and load.
;;; 2011.05.19 Dan
;;; : * Added the create-chunk-alias command that allows one to
;;; : add new chunk names that refer to existing chunks.
;;; 2012.05.30 Dan
;;; : * Fixed a bug in the create-chunk-alias macro.
;;; 2012.10.15 Dan
;;; : * Changed chunk-back-links to use a hash-table instead of a
;;; : list of lists to improve performance. Significant reduction
;;; : in time and memory usage when :ncnar is t found in test
;;; : cases.
;;; 2013.03.13 Dan [1.3]
;;; : * Changed chunk creation so that all slots which exist for
;;; : the chunk get set in the table, even if they are empty,
;;; : because that's important for matching chunk-specs now since
;;; : a non-existent slot needs to be diferentiated from an empty
;;; : slot.
;;; 2013.04.05 Dan
;;; : * Fixed a bug with creating chunks that have default values in
;;; : slots which are themselves chunks.
;;; : * Re-fixed because I undid the previous change which is still
;;; : important.
;;; 2013.05.20 Dan
;;; : * Added the resolve-a-static-chunks-type function to handle
;;; : converting a chunk to the minimal type needed for holding
;;; : its contents.
;;; 2013.05.21 Dan
;;; : * Fast-mod-chunk and define-chunk now resolves static chunks so
;;; : that they are always of the most appropriate type.
;;; 2013.05.22 Dan
;;; : * Changed pprint-a-chunk so that static chunks show the root
;;; : type or current type based on the setting of the :show-static-
;;; : subtype-names parameter.
;;; 2013.05.23 Dan
;;; : * Changed define-chunks to now allow one to specify any possible
;;; : slots when creating static chunks even if only the parent type
;;; : is provided, but won't allow creating as yet undefined type
;;; : combinations e.g. if the root type is x and you've extended
;;; : x with a slot1 and extended x with a slot2 but haven't extended
;;; : either of those (x+slot1 or x+slot2) with the other to create
;;; : x+slot1&slot2 a definition for a chunk like this:
;;; : (isa x slot1 "a" slot2 "b") will fail, but either of these:
;;; : (isa x slot1 "a") (isa x slot2 "b") would be fine.
;;; : * Fixed resolve-chunks-type so that it doesn't remove the
;;; : static slots of the root type from the chunks i.e. those are
;;; : allowed to have a value of nil and still exist.
;;; 2014.02.12 Dan
;;; : * Changed pprint-a-chunk to use canonical-chunk-type-name
;;; : instead of directly testing the type and static printing
;;; : state.
;;; 2014.02.17 Dan
;;; : * Changed set-chk-slot-value so that it resolves a static
;;; : chunk's type after the change.
;;; : * Set the creation-type slot when creating a chunk and check
;;; : that when resolving a chunk's type. If it moves up the
;;; : hierarchy allow the slots of the creation type to still be
;;; : used in set and mod operations for verification of valid
;;; : slots until it either has the same type as its creation
;;; : type or becomes a type which isn't a supertype of the
;;; : creation type. What this allows is the following sequence
;;; : of operations which are used by some of the device code to
;;; : create visual features 'incrementally':
;;; : (chunk-type foo)
;;; : (chunk-type (bar (:include foo)) slot)
;;; : (define-chunk (a isa bar)) ;; falls back to foo at this point
;;; : (set-chunk-slot-value a slot t) ;; want to set that slot later
;;; 2014.02.24 Dan [2.0]
;;; : * Move to chunks not maintaining type information at runtime.
;;; : * Instead it just keeps a bitvector of slots which have values
;;; : in them based on a global slot mapping.
;;; : * Setting and modifying slot values will automatically extend
;;; : the chunk. Automatic extension however will print a model
;;; : warning.
;;; : * Chunks can be marked as immutable now and trying to change
;;; : such a chunk doesn't work and prints a warning.
;;; : * Don't print an ISA when printing a chunk.
;;; 2014.02.25 Dan
;;; : * Switch slot-value-lists back to a list of cons from a hashtable.
;;; : * Chunk-slot-value doesn't warn for missing slots, just returns nil.
;;; 2014.03.05 Dan
;;; : * Go all out and make the isa optional in chunk definition.
;;; : Print warnings for any slots that aren't already defined and
;;; : then extend things to compensate (basically the same as with
;;; : undefined chunks).
;;; 2014.03.13 Dan
;;; : * Require chunk names to start with an alphanumeric. That
;;; : prevents a lot of potential weirdness in production compilation
;;; : because imagine what happens if a chunk named =goal or worse
;;; : =goal> were instantiated into a compiled production not to
;;; : mention things like just =val, +retrieval>, or ==>.
;;; 2014.03.18 Dan
;;; : * Added the mod-chunk-with-spec-fct function.
;;; 2014.03.26 Dan
;;; : * Added chunk-filled-slots-vector for accessing the info from
;;; : a chunk-name.
;;; 2014.03.27 Dan
;;; : * Changed the warning for create-undefined-chunk to say no
;;; : slots instead of default type chunk.
;;; 2014.04.01 Dan
;;; : * Already had chunk-slots-vector so no need for chunk-filled-slots-
;;; : vector...
;;; 2014.05.21 Dan
;;; : * Allow the :merge-function for extend-chunks to take the value
;;; : :second instead of a function to just set the value based on
;;; : that of the second chunk instead of having to write a function
;;; : to do so for each parameter.
;;; 2014.06.17 Dan
;;; : * Fixed define-chunks-fct to disambiguate what a definition
;;; : like this means: (name "doc") since that could be a chunk
;;; : name and documentation string or it could be an unnamed
;;; : chunk with a slot named name with a value of "doc". The
;;; : second interpretation is how it works now and the only way
;;; : to specify a doc string is to also name the chunk and specify
;;; : an isa.
;;; : Here are the valid options:
;;; : {slot value}+
;;; : <name> {slot value}+
;;; : isa <type> {slot value}+
;;; : <name> isa <type> {slot value}+
;;; : <name> <"doc"> isa <type> {slot value}+
;;; 2014.06.19 Dan
;;; : * Fixed a bug that allowed a chunk to have more than one
;;; : instance of a slot.
;;; 2014.06.20 Dan
;;; : * Only create undefined chunks if the name is valid for a
;;; : chunk i.e. starts with an alphanumeric.
;;; : * Also test that when extending slots.
;;; 2014.06.24 Dan
;;; : * Allow all chunk definitions to extend the slots, even if it's
;;; : got a type specified, but do a hard warning when there's a
;;; : type specified.
;;; 2014.10.15 Dan
;;; : * When merging chunks need to make sure that if either is
;;; : immutable then the resulting chunk is also.
;;; 2014.10.17 Dan
;;; : * Fixed a bug with recording the documentation string for a
;;; : chunk that didn't have a name -- this makes it possible
;;; : to also specify things as:
;;; : <"doc"> isa <type> {slot value}*
;;; : Note that for all those listed above the + should be a * as
;;; : well since not slot vlaue pairs are required.
;;; 2014.10.20 Dan
;;; : * Modify mod-chunk-fct so that it returns nil for all of the
;;; : "bad" situations instead of letting set-chk-slot-value fail
;;; : and then returning the chunk-name.
;;; 2014.11.10 Dan
;;; : * Tweak pprint-a-chunk to avoid the issue with ~ and the output
;;; : macros.
;;; 2014.11.11 Dan
;;; : * Add a check to extend-chunks to make sure the parameter
;;; : name is a symbol and not a keyword.
;;; : * Add tests to make sure the functions provided are actually
;;; : functions.
;;; 2014.11.13 Dan
;;; : * Remove the checking of the extend-chunks functions because
;;; : of potential issues with compile time vs load time checking.
;;; 2014.12.17 Dan
;;; : * Changed the declaim for some functions because they didn't
;;; : indicate multiple return values and some Lisps care
;;; : about that.
;;; 2015.03.13 Dan
;;; : * Don't try to create a chunk for a keyword used in a slot
;;; : value. Treat it like a number or string and leave it alone.
;;; 2015.04.22 Dan
;;; : * Chunk-copied-from now has a second return value when the
;;; : parameter is a valid chunk name. The second return value
;;; : is the act-r-chunk-copied-from value for the chunk which
;;; : could be the name of a chunk which is no longer equal to the
;;; : copy because it had been changed, a symbol which doesn't
;;; : name a chunk anymore because it has been deleted, or nil if
;;; : the chunk itself has been modified or wasn't a copy to begin
;;; : with. If the second value is non-nil then that means that
;;; : the chunk was created as a copy and hasn't been itself
;;; : modified since then.
;;; 2016.06.27 Dan
;;; : * Removed some duplicate testing when using mod-chunk or mod-
;;; : chunk-with-spec since set-chk-slot-value retested the
;;; : immutability of the chunk and the validity of the slot name.
;;; : Now there's a set-slot-value below set-chk-slot-value which
;;; : can be used if the chunk is immutable and the slot name is
;;; : valid -- calling that otherwise will lead to problems and
;;; : it's not intended for user code.
;;; : * Reverse the order of the initial tests in convert-slot-value-
;;; : to-true since get-chunk is costly and unnecessary if the
;;; : renaming is off anyway.
;;; 2016.06.28 Dan
;;; : * Changed set-slot-value to set-c-slot-value.
;;; : * Compressed create-slot-value-chunk-if-needed and convert-slot-
;;; : value-to-true into get-true-slot-value-name to save some
;;; : overhead.
;;; 2016.12.19 Dan [3.0]
;;; : * Added define-chunks as a command through the dispatcher and
;;; : define-chunks-fct now uses that.
;;; 2017.01.04 Dan
;;; : * Because define-chunks can recursively call itself through
;;; : create-undefined-chunk I've hacked that for now so that it
;;; : directly calls the internal function instead of going out
;;; : through the dispatcher again since that would deadlock
;;; : because define-chunks is set to be single instance -- which
;;; : it must be! That means monitoring define-chunks will not be
;;; : sufficient to track all of the model's chunks, but since this
;;; : situation generates a warning it is an "unusual" circumstance
;;; : and for now I'm considering that reasonable behavior.
;;; 2017.01.18 Dan
;;; : * Removed the echo-act-r-output from define-chunks. The assumption
;;; : now is that echoing is handled by the user.
;;; : * Use handle-evaluate-results.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Define-chunks now handles string based (remote) calls.
;;; : * Added external pprint-chunks, chunk-slot-value, mod-chunk,
;;; : set-chunk-slot-value commands.
;;; 2017.02.15 Dan
;;; : * Chunk-p-fct now accepts strings as names.
;;; : * If chunk-slot-value-fct gets a string for the chunk name
;;; : and the slot value is a string then it encodes that result
;;; : into the special quoted string for returning.
;;; : * Don't allow chunk-p-fct to take a string for a name! Instead,
;;; : have remote calls routed to a special chunk-p-fct which does
;;; : the string to name decoding.
;;; : * Added the remote chunk-p function.
;;; 2017.02.27 Dan
;;; : * Changed the test in define-chunks-internal for decoding the
;;; : chunk-def list to include null items.
;;; 2017.03.13 Dan
;;; : * Added a remote copy-chunk and have that one convert
;;; : the name if it's a string but don't change the internal
;;; : for the same efficiency reasons that chunk-p doesn't.
;;; 2017.06.20 Dan
;;; : * Protecting access to the model chunk table and ref-table with
;;; : the model's lock.
;;; : * Added a lock to protect the parameter table.
;;; 2017.06.21 Dan
;;; : * Adding the individual chunk locking to everything.
;;; 2017.06.22 Dan
;;; : * Define-chunks and copy-chunk don't need to be single instance.
;;; 2017.06.23 Dan
;;; : * Added a name to the lock.
;;; 2017.08.09 Dan
;;; : * Added printed-chunk to use as a replacement for capture-output
;;; : on pprint-chunks.
;;; 2017.12.06 Dan
;;; : * Added remote versions of delete and purge chunk.
;;; 2017.12.08 Dan
;;; : * Added a remote chunk-copied-from.
;;; 2018.01.09 Dan
;;; : * Allow define-chunks to get just symbols/strings for the
;;; : items and create those as chunks with no slots or values.
;;; : For safety reasons at this point only do that if all the items
;;; : are atoms instead of allowing a mixture, but may want to
;;; : relax that in the future.
;;; 2018.02.27 Dan
;;; : * The notify-on-the-fly hooks might be dispatch commands so
;;; : need to use dispatch-apply instead of funcall.
;;; 2018.04.13 Dan
;;; : * Fixed a bug in a warning from internal-define-chunks.
;;; 2018.06.12 Dan
;;; : * Starting to have only remote commands allow strings for names
;;; : (not true for define-chunks yet because having it go through
;;; : the dispatcher for protection needs to change).
;;; 2018.06.13 Dan
;;; : * Don't require define-chunks-fct to go through the dispatcher.
;;; : I think I did that so it could be monitored for any chunk
;;; : creation, but I don't see that being useful and since it's
;;; : not single instance it doesn't provide any extra protection.
;;; : * Finish the transition to only remote commands using the
;;; : string names and extra quoting for stings as slot values.
;;; 2018.06.14 Dan
;;; : * Adding an additional option for the merge function in a new
;;; : chunk parameter :second-if which sets it to the value of the
;;; : second chunk only if that value is non-nil otherwise it stays
;;; : as the c1 value.
;;; 2018.07.27 Dan [4.0]
;;; : * Make extend-chunks available remotely as well as create the
;;; : external commands to use it - the accessor is the same as
;;; : the Lisp accessor and the setter is called set-<accessor>.
;;; : Also allow the functions to be remote commands. Note, the
;;; : external version uses the string double-quoting mechanism
;;; : for all the keyword parameters so that one can specify a
;;; : Lisp function or value instead of a remote command as the
;;; : value (in particular setting identity for the copy function
;;; : or one of the keyword options for merging).
;;; 2018.08.23 Dan
;;; : * Added remote chunk-filled-slots-list and chunks.
;;; 2019.01.30 Dan
;;; : * Don't need to repeatedly grab the lock for param size.
;;; 2019.03.06 Dan
;;; : * Tried storing the slot struct in the chunks, but not a
;;; : noticeable difference in performance.
;;; : * Now trying the index instead.
;;; 2019.03.14 Dan
;;; : * Undoing the change to indexes, since it actually hurt the
;;; : overall performance on the zbrodoff test model, but keeping
;;; : some of the minor cleanups that went along with it.
;;; 2019.04.04 Dan
;;; : * valid-ct-slot now returns the slot-struct so save a test
;;; : by using that.
;;; 2019.06.06 Dan
;;; : * Add an external printed-chunk command.
;;; 2020.02.05 Dan [4.1]
;;; : * Adding remote versions for most of the commands.
;;; 2020.02.11 Dan
;;; : * Added a remote make-chunk-immutable.
;;; 2020.02.12 Dan [5.0]
;;; : * Fixed an issue with external extend-chunks because it needs
;;; : to do the string decoding on all the functions so that they
;;; : can be set to external commands.
;;; : * Because merging holds the locks on the chunks you can't
;;; : access a parameter's value in an external command for
;;; : merging or copying thus need to add a merge-values-fn
;;; : hook that passes the values as a work around (basically
;;; : parallel the copy and copy-from-chunk functions).
;;; 2020.08.24 Dan
;;; : * Replaced constants that had *...* with +...+ to avoid the
;;; : warnings in SBCL.
;;; 2020.08.25 Dan
;;; : * Switch from defconstant to the define-constant macro to
;;; : avoid issues with SBCL (instead of redefining defconstant
;;; : for SBCL as was done previously).
;;; 2020.09.09 Dan
;;; : * If either parameter hasn't had a value set for a parameter,
;;; : then the merge-value-function needs to get the default value
;;; : instead of the undefined value. (Can happen if there isn't
;;; : a copy function because it only sets the default when needed
;;; : if there isn't one.)
;;; 2021.06.03 Dan [6.0]
;;; : * Add the option of a "reusable" chunk -- something that is
;;; : safe for a buffer to use repeatedly. They will still be
;;; : safe to merge as c2 (it will update the params of c1 but not
;;; : link it to c2), but must be copied if needed to store.
;;; : The make-chunk-reusable command sets it to be such a chunk.
;;; : * There's a new command that should be checked by something
;;; : that wants to "store" a chunk that was cleared from a buffer
;;; : or was specified in a request slot: chunk-not-storable. If
;;; : that is true then a copy should be made and stored instead.
;;; 2021.10.19 Dan
;;; : * Changed the declaim for get-module-fct since it has an
;;; : optional now.
;;; 2022.03.04 Dan
;;; : * Fixed a problem with how the :second and :second-if merging
;;; : mechanisms apply because they would copy the "undefined"
;;; : status of c2 into c1 when c1 already had a value, but should
;;; : use the default value of c2 instead for :second and not
;;; : change it in the case of :second-if.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Globals and underlying chunk structures are not for general use.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function (t &optional t) (values t t)) get-module-fct))
(declaim (ftype (function (&optional t) t) sgp-fct))
(declaim (ftype (function () t) current-model))
(declaim (ftype (function () t) use-short-copy-names))
(declaim (ftype (function (&optional t) (values t t t)) new-name-fct))
(declaim (ftype (function () t) update-chunks-on-the-fly))
(declaim (ftype (function (t) t) release-name-fct))
(declaim (ftype (function () t) notify-on-the-fly-hooks))
(declaim (ftype (function (t) t) id-to-chunk-spec))
(declaim (ftype (function (t) t) chunk-spec-to-chunk-def))
(defvar *chunk-parameters-count* 0)
(defvar *chunk-parameter-undefined* (gentemp "Unused-Param"))
(defvar *chunk-parameters-list* nil
"Internal list of parameters that have been added to chunks")
(defvar *chunk-parameters-copy-list* nil
"Internal list of parameters that have a copy function")
(defvar *chunk-parameters-merge-list* nil
"Internal list of parameters that have a merge function")
(defvar *chunk-parameters-merge-value-list* nil
"Internal list of parameters that have a merge value function")
(defvar *chunk-parameters-lock* (bt:make-lock "chunk-parameters"))
(defun chunk-parameter-default (param chunk-name)
"Return a default value for a parameter in a chunk"
(if (act-r-chunk-parameter-default-function param)
(dispatch-apply (act-r-chunk-parameter-default-function param) chunk-name)
(act-r-chunk-parameter-default-value param)))
(define-constant +pprint-chunk-string+ (formatter "~S~:[ (~s)~;~*~]~%~@[~S~%~]~:{ ~s ~s~%~}")
"compiled format string for printing chunks")
(define-constant +pprint-chunk-parameters-string+ (formatter "~@[ --chunk parameters--~%~:{ ~s ~s~%~}~]~%")
"compiled format string for printing chunk parameters")
(defun pprint-a-chunk (name &optional (w-params t))
"Internal function for printing a chunk"
(let ((chunk (get-chunk name)))
(if chunk
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(command-output "~a"
(format nil
+pprint-chunk-string+
name
(eql name (act-r-chunk-name chunk))
(act-r-chunk-name chunk)
(act-r-chunk-documentation chunk)
(mapcar (lambda (slot)
(list (act-r-slot-name (car slot)) (cdr slot)))
(sort (copy-tree (act-r-chunk-slot-value-lists chunk)) #'< :key (lambda (x) (act-r-slot-index (car x)))))))
(when w-params
(command-output "~a"
(format nil +pprint-chunk-parameters-string+
(mapcar (lambda (param)
(list (act-r-chunk-parameter-name param)
(funcall (act-r-chunk-parameter-accessor param)
name)))
(bt:with-lock-held (*chunk-parameters-lock*)
*chunk-parameters-list*)))))
name)
:error)))
(defun printed-chunk (name &optional w-params)
(let ((chunk (get-chunk name)))
(if chunk
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(let ((s (make-string-output-stream)))
(format s +pprint-chunk-string+
name
(eql name (act-r-chunk-name chunk))
(act-r-chunk-name chunk)
(act-r-chunk-documentation chunk)
(mapcar (lambda (slot)
(list (act-r-slot-name (car slot)) (cdr slot)))
(sort (copy-tree (act-r-chunk-slot-value-lists chunk)) #'< :key (lambda (x) (act-r-slot-index (car x))))))
(when w-params
(format s "~%")
(format s +pprint-chunk-parameters-string+
(mapcar (lambda (param)
(list (act-r-chunk-parameter-name param)
(funcall (act-r-chunk-parameter-accessor param)
name)))
(bt:with-lock-held (*chunk-parameters-lock*)
*chunk-parameters-list*))))
(get-output-stream-string s)))
"")))
(defun external-printed-chunk (name &optional w-params)
(printed-chunk (string->name name) w-params))
(add-act-r-command "printed-chunk" 'external-printed-chunk "Return the text output of printing a chunk optionally with the parameter values. Params: chunk-name {show-parameters?}." nil)
(defmacro pprint-chunks (&rest chunk-names)
"Print the chunks"
`(pprint-chunks-fct ',chunk-names))
(defun pprint-chunks-fct (chunk-names-list)
"Print the chunks"
(verify-current-model
"pprint-chunks called with no current model."
(let ((res nil))
(dolist (chunk (if (null chunk-names-list) (chunks) chunk-names-list) res)
(push-last (pprint-a-chunk chunk nil) res)))))
(defun pprint-chunks-external (&rest chunk-names-list)
(pprint-chunks-fct (string->name-recursive chunk-names-list)))
(add-act-r-command "pprint-chunks" 'pprint-chunks-external "Print the indicated chunks. Params: chunk-name*." nil)
(defun chunk-back-links (chunk-name)
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(gethash chunk-name (act-r-model-chunk-ref-table model)))))
(defun set-chunk-back-links (chunk-name val)
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(setf (gethash chunk-name (act-r-model-chunk-ref-table model)) val))))
(defsetf chunk-back-links set-chunk-back-links)
(defmacro pprint-chunks-plus (&rest chunk-names)
"Print the chunks and their chunk parameters"
`(pprint-chunks-plus-fct ',chunk-names))
(defun pprint-chunks-plus-fct (&optional chunk-names-list)
"Print the chunks and their parameters"
(verify-current-model
"pprint-chunks-plus called with no current model."
(let ((res nil))
(dolist (chunk (if (null chunk-names-list) (chunks) chunk-names-list) res)
(push-last (pprint-a-chunk chunk t) res)))))
(defun pprint-chunks-plus-external (&rest chunk-names-list)
(pprint-chunks-plus-fct (string->name-recursive chunk-names-list)))
(add-act-r-command "pprint-chunks-plus" 'pprint-chunks-plus-external "Print the indicated chunks along with chunk parameters. Params: chunk-name*." nil)
(defun chunks ()
"Returns a list of the names of all currently defined chunks"
(verify-current-mp
"chunks called with no current meta-process."
(verify-current-model
"chunks called with no current model."
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(hash-table-keys (act-r-model-chunks-table model)))))))
(add-act-r-command "chunks" 'chunks "Returns a list of all the currently defined chunks. No params." nil)
(defun get-chunk (name)
"Internal function for getting the chunk structure from its name"
(verify-current-model
"get-chunk called with no current model."
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(gethash name (act-r-model-chunks-table model))))))
(defun get-chunk-warn (name)
"Internal function for getting the chunk structure from its name"
(verify-current-model
"get-chunk called with no current model."
(let ((c (let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(gethash name (act-r-model-chunks-table model))))))
(if c c
(print-warning "~s does not name a chunk in the current model." name)))))
(defmacro chunk-p (chunk-name?)
"Check a name to see if it names a chunk"
`(chunk-p-fct ',chunk-name?))
(defun chunk-p-fct (chunk-name?)
"Check a name to see if it names a chunk"
(if (get-chunk chunk-name?) t nil))
(defun external-chunk-p-fct (chunk-name?)
(chunk-p-fct (string->name chunk-name?)))
(add-act-r-command "chunk-p" 'external-chunk-p-fct "Returns whether the given name is the name of a chunk in the model. Params: chunk-name." nil)
(defun chunk-slots-vector (chunk-name)
"Return the bitvector of slots with values for a chunk"
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(act-r-chunk-filled-slots c)))))
(defmacro chunk-documentation (chunk-name)
"Return the documentation string for a chunk"
`(chunk-documentation-fct ',chunk-name))
(defun chunk-documentation-fct (chunk-name)
"Return the documentation string for a chunk"
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(act-r-chunk-documentation c)))))
(defun external-chunk-documentation-fct (name)
(chunk-documentation-fct (string->name name)))
(add-act-r-command "chunk-documentation" 'external-chunk-documentation-fct "Return the documentation string of the specified chunk if it has one. Params: chunk-name." nil)
(defun create-undefined-chunk (name)
"Create a new chunk with the given name of chunk-type chunk with a warning"
(model-warning "Creating chunk ~S with no slots" name)
(define-chunks-fct `((,name isa chunk))))
(defmacro copy-chunk (chunk-name)
"Create a new chunk which is a copy of the given chunk"
`(copy-chunk-fct ',chunk-name))
(defun copy-chunk-fct (chunk-name)
"Create a new chunk which is a copy of the given chunk"
(let ((chunk (get-chunk-warn chunk-name)))
(when chunk
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(when (use-short-copy-names)
(unless (act-r-chunk-base-name chunk)
(setf (act-r-chunk-base-name chunk) (concatenate 'string (symbol-name chunk-name) "-"))))
(let* ((new-name (new-name-fct (if (use-short-copy-names)
(act-r-chunk-base-name chunk)
(concatenate 'string (symbol-name chunk-name) "-"))))
(new-chunk (make-act-r-chunk
:name new-name
:base-name (act-r-chunk-base-name chunk)
:merged-chunks (list new-name)
:filled-slots (act-r-chunk-filled-slots chunk)
:parameter-values (bt:with-lock-held (*chunk-parameters-lock*)
(make-array *chunk-parameters-count*
:initial-element *chunk-parameter-undefined*))
:slot-value-lists (copy-tree (act-r-chunk-slot-value-lists chunk)))))
;; Create the back links as needed
(when (update-chunks-on-the-fly)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(dolist (slot (act-r-chunk-slot-value-lists chunk))
(let ((slot-name (act-r-slot-name (car slot)))
(old (cdr slot)))
(when (chunk-p-fct old)
(let ((bl (chunk-back-links old)))
(if (hash-table-p bl)
(push slot-name (gethash new-name bl))
(let ((ht (make-hash-table)))
(setf (gethash new-name ht) (list slot-name))
(setf (chunk-back-links old) ht)))))))))
;; update its parameters for only those that need it
(let (copy-list undefined)
(bt:with-lock-held (*chunk-parameters-lock*)
(setf copy-list *chunk-parameters-copy-list*)
(setf undefined *chunk-parameter-undefined*))
(dolist (param copy-list)
(if (act-r-chunk-parameter-copy param)
(let ((current (aref (act-r-chunk-parameter-values chunk) (act-r-chunk-parameter-index param))))
(setf (aref (act-r-chunk-parameter-values new-chunk) (act-r-chunk-parameter-index param))
(dispatch-apply (act-r-chunk-parameter-copy param)
(if (eq current undefined)
(chunk-parameter-default param chunk-name)
current))))
(setf (aref (act-r-chunk-parameter-values new-chunk) (act-r-chunk-parameter-index param))
(dispatch-apply (act-r-chunk-parameter-copy-from-chunk param) chunk-name)))))
;; note the original
(setf (act-r-chunk-copied-from new-chunk) chunk-name)
;; Put it into the main table
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(setf (gethash new-name (act-r-model-chunks-table model)) new-chunk)))
new-name)))))
(defun external-copy-chunk-fct (chunk-name?)
(copy-chunk-fct (string->name chunk-name?)))
(add-act-r-command "copy-chunk" 'external-copy-chunk-fct "Returns the name of a chunk which is a copy of the chunk name provided. Params: chunk-name." nil)
(defun copy-chunk-to-chunk-fct (from-chunk to-chunk)
"Copy the from-chunk into the reusable chunk to-chunk"
(let ((f-chunk (get-chunk-warn from-chunk))
(t-chunk (get-chunk-warn to-chunk)))
(when (and f-chunk t-chunk)
(bt:with-recursive-lock-held ((act-r-chunk-lock f-chunk))
(bt:with-recursive-lock-held ((act-r-chunk-lock t-chunk))
(when (act-r-chunk-not-storable t-chunk) ;; it's reusable
(let (param-count undefined copy-list)
(bt:with-lock-held (*chunk-parameters-lock*)
(setf param-count *chunk-parameters-count*)
(setf copy-list *chunk-parameters-copy-list*)
(setf undefined *chunk-parameter-undefined*))
;; clear the back links from current values of t-chunk
(when (update-chunks-on-the-fly)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(dolist (current (act-r-chunk-slot-value-lists t-chunk))
(let ((old (cdr current)))
(when (chunk-p-fct old)
(let* ((bl (chunk-back-links old))
(new-links (remove (act-r-slot-name (car current)) (gethash to-chunk bl))))
(if new-links
(setf (gethash to-chunk bl) new-links)
(remhash to-chunk bl))))))))
;; copy the values from the other chunk
(setf (act-r-chunk-base-name t-chunk) (act-r-chunk-base-name f-chunk))
(setf (act-r-chunk-filled-slots t-chunk) (act-r-chunk-filled-slots f-chunk))
(setf (act-r-chunk-slot-value-lists t-chunk) (copy-tree (act-r-chunk-slot-value-lists f-chunk)))
(setf (act-r-chunk-parameter-values t-chunk)
(make-array param-count :initial-element undefined))
;; Create the back links as needed
(when (update-chunks-on-the-fly)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(dolist (slot (act-r-chunk-slot-value-lists t-chunk))
(let ((slot-name (act-r-slot-name (car slot)))
(old (cdr slot)))
(when (chunk-p-fct old)
(let ((bl (chunk-back-links old)))
(if (hash-table-p bl)
(push slot-name (gethash to-chunk bl))
(let ((ht (make-hash-table)))
(setf (gethash to-chunk ht) (list slot-name))
(setf (chunk-back-links old) ht)))))))))
;; update its parameters for only those that need it
(dolist (param copy-list)
(if (act-r-chunk-parameter-copy param)
(let ((current (aref (act-r-chunk-parameter-values f-chunk) (act-r-chunk-parameter-index param))))
(setf (aref (act-r-chunk-parameter-values t-chunk) (act-r-chunk-parameter-index param))
(dispatch-apply (act-r-chunk-parameter-copy param)
(if (eq current undefined)
(chunk-parameter-default param t-chunk)
current))))
(setf (aref (act-r-chunk-parameter-values t-chunk) (act-r-chunk-parameter-index param))
(dispatch-apply (act-r-chunk-parameter-copy-from-chunk param) from-chunk)))))
;; note the original
(setf (act-r-chunk-copied-from t-chunk) from-chunk)
to-chunk))))))
(defun external-copy-chunk-to-chunk-fct (from-chunk to-chunk)
(copy-chunk-to-chunk-fct (string->name from-chunk) (string->name to-chunk)))
(add-act-r-command "copy-chunk-to-chunk-fct" 'external-copy-chunk-to-chunk-fct "Copy the from-chunk into the reusable chunk to-chunk and returns to-chunk if successful. Params: from-chunk to-chunk." nil)
(defun buffer-chunk-spec-to-chunk-list (chunk-spec)
"Convert a chunk-spec to a list of slot-value conses"
(if (act-r-chunk-spec-p chunk-spec)
(unless (or (not (zerop (act-r-chunk-spec-request-param-slots chunk-spec))) ; don't allow request params
(act-r-chunk-spec-slot-vars chunk-spec)
(act-r-chunk-spec-variables chunk-spec)
(not (zerop (act-r-chunk-spec-duplicate-slots chunk-spec)))
(not (zerop (act-r-chunk-spec-negated-slots chunk-spec)))
(not (zerop (act-r-chunk-spec-relative-slots chunk-spec))))
(values t
(mapcar (lambda (x)
(unless (keywordp (act-r-slot-spec-name x))
(cons (act-r-slot-spec-name x) (act-r-slot-spec-value x))))
(act-r-chunk-spec-slots chunk-spec))))
(awhen (id-to-chunk-spec chunk-spec)
(chunk-spec-to-chunk-def it))))
(defun copy-chunk-spec-to-chunk-fct (chunk-spec to-chunk)
"Copy the info from the chunk-spec into the reusable chunk to-chunk"
(multiple-value-bind (valid slots) (buffer-chunk-spec-to-chunk-list chunk-spec)
(when valid
(let ((t-chunk (get-chunk-warn to-chunk)))
(when t-chunk
(bt:with-recursive-lock-held ((act-r-chunk-lock t-chunk))
(when (act-r-chunk-not-storable t-chunk) ;; it's reusable
(let (param-count undefined)
(bt:with-lock-held (*chunk-parameters-lock*)
(setf param-count *chunk-parameters-count*)
(setf undefined *chunk-parameter-undefined*))
;; clear the back links from current values of t-chunk
(when (update-chunks-on-the-fly)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(dolist (current (act-r-chunk-slot-value-lists t-chunk))
(let ((old (cdr current)))
(when (chunk-p-fct old)
(let* ((bl (chunk-back-links old))
(new-links (remove (act-r-slot-name (car current)) (gethash to-chunk bl))))
(if new-links
(setf (gethash to-chunk bl) new-links)
(remhash to-chunk bl))))))))
;; set initial-values in the copy
(setf (act-r-chunk-base-name t-chunk) nil)
(setf (act-r-chunk-filled-slots t-chunk) 0)
(setf (act-r-chunk-slot-value-lists t-chunk) nil)
(setf (act-r-chunk-parameter-values t-chunk)
(make-array param-count :initial-element undefined))
;; don't need to call copy parameters since there's no chunk to
;; actually copy from...
(dolist (s slots)
(awhen (valid-slot-name (car s)) ;; should be valid since was in a spec
(set-c-slot-value t-chunk it (car s) (cdr s)))) ;; handles all the details
to-chunk))))))))
(defmacro chunk-copied-from (chunk-name)
"Return the name of the chunk from which the provided chunk was copied"
`(chunk-copied-from-fct ',chunk-name))
(defun chunk-copied-from-fct (chunk-name)
"Return the name of the chunk from which the provided chunk was copied"
(let ((chunk (get-chunk-warn chunk-name)))
(when chunk
(let ((copied-from (bt:with-recursive-lock-held ((act-r-chunk-lock chunk)) (act-r-chunk-copied-from chunk))))
(values
(when (and copied-from (chunk-p-fct copied-from) (equal-chunks-fct chunk-name copied-from))
copied-from)
copied-from)))))
(defun external-chunk-copied-from (chunk-name)
(chunk-copied-from-fct (string->name chunk-name)))
(add-act-r-command "chunk-copied-from" 'external-chunk-copied-from "Returns the name of the chunk from which the given chunk was copied. Params: chunk-name.")
(defmacro define-chunks (&rest chunk-defs)
"Create chunks in the current model"
`(define-chunks-fct ',chunk-defs))
(defun get-true-slot-value-name (chunk slot-name value)
(let ((chunkp nil))
(when (and value
(symbolp value)
(not (keywordp value))
(not (numberp value))
(not (eq t value))
(alphanumericp (char (symbol-name value) 0)))
(unless (chunk-p-fct value)
(create-undefined-chunk value))
(setf chunkp t))
(when (and chunkp (update-chunks-on-the-fly))
(setf value (true-chunk-name-fct value))
;; If it's a chunk save the back link to this chunk
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(let ((bl (chunk-back-links value)))
(if (hash-table-p bl)
(push slot-name (gethash (act-r-chunk-name chunk) bl))
(let ((ht (make-hash-table)))
(setf (gethash (act-r-chunk-name chunk) ht) (list slot-name))
(setf (chunk-back-links value) ht))))))
value))
(defun define-chunks-fct (chunk-def-list)
"Create chunks in the current model"
;; Do it in 2 passes like the old add-dm because there could be
;; circular references which should be allowed
(verify-current-model
"define-chunks called with no current model."
(let ((model (current-model-struct))
(chunk-list nil)
)
;; lock it early to avoid conflicting attempts to create chunks
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
;; first pass just create the chunks
(cond ((every (lambda (x) (symbolp x)) chunk-def-list)
(dolist (name chunk-def-list)
(cond ((not (alphanumericp (char (symbol-name name) 0)))
(print-warning "Invalid chunk definition: ~S chunk name must be a symbol starting with an alphanumeric character." name))
((chunk-p-fct name)
(print-warning "Invalid chunk definition: ~S names a chunk which already exists." name))
(t
(let ((c (make-act-r-chunk
:name name
:merged-chunks (list name)
:documentation nil
:parameter-values (bt:with-lock-held (*chunk-parameters-lock*)
(make-array *chunk-parameters-count*
:initial-element *chunk-parameter-undefined*))
:slot-value-lists nil)))
(push-last c chunk-list)
;; enter it into the main chunk table
(setf (gethash name (act-r-model-chunks-table model)) c))))))
((every 'listp chunk-def-list)
(dolist (chunk-def chunk-def-list)
(let (name doc type slots slots-and-values
(type-pos (position 'isa chunk-def))
(doc-pos (position-if 'stringp (subseq chunk-def 0 (min (length chunk-def) 2))))
(parity (if (oddp (length chunk-def)) 'odd 'even)))
(cond ((and type-pos (> (count 'isa chunk-def) 1))
(print-warning "Invalid chunk definition: ~S has more than one ISA." chunk-def))
((and type-pos (> type-pos 2))
(print-warning "Invalid chunk definition: ~S too many specifiers before ISA." chunk-def))
((and type-pos (= (1+ type-pos) (length chunk-def)))
(print-warning "Invalid chunk definition: ~S no chunk-type specified after ISA." chunk-def))
((and type-pos (not (get-chunk-type (nth (1+ type-pos) chunk-def))))
(print-warning "Invalid chunk definition: ~S chunk-type specified does not exist." chunk-def))
((and type-pos (= type-pos 1) (eq parity 'even))
(print-warning "Invalid chunk definition: ~S odd number of items after type specification." chunk-def))
((and type-pos (zerop type-pos) (eq parity 'odd))
(print-warning "Invalid chunk definition: ~s odd number of items after type specification." chunk-def))
((and type-pos (null doc-pos) (= type-pos 2))
(print-warning "Invalid chunk definition: ~s non-string between name and isa." chunk-def))
(t
(when type-pos
(setf type (get-chunk-type (nth (1+ type-pos) chunk-def))))
(if (or (and (eq parity 'odd) (null type-pos))
(and (eq parity 'odd) (null doc-pos))
(and type-pos (= type-pos 2) doc-pos (= doc-pos 1)))
(setf name (first chunk-def))
(setf name (new-name-fct (if type
(symbol-name (act-r-chunk-type-name type))
"CHUNK"))))
(when (and doc-pos type-pos)
(setf doc (nth doc-pos chunk-def)))
(setf slots-and-values
(cond (type-pos
(subseq chunk-def (+ 2 type-pos)))
((eq parity 'even)
chunk-def)
(t
(subseq chunk-def 1))))
(cond ((and type-pos (null type))
(print-warning "Invalid chunk definition: ~S ISA does not specify a valid type." chunk-def))
((or (null name) (not (symbolp name)) (keywordp name))
(print-warning "Invalid chunk definition: ~S chunk name is not a valid symbol." chunk-def))
((not (alphanumericp (char (symbol-name name) 0)))
(print-warning "Invalid chunk definition: ~S chunk name must be a symbol starting with an alphanumeric character." chunk-def))
((chunk-p-fct name)
(print-warning "Invalid chunk definition: ~S names a chunk which already exists." chunk-def))
(t
(do* ((s slots-and-values (cddr s))
(s-name (first s) (first s))
(s-val (second s) (second s)))
((null s))
(let ((slot-struct (if type (valid-ct-slot type s-name) (valid-slot-name s-name))))
(if (and slot-struct (not (keywordp s-name)))
(aif (assoc slot-struct slots)
(setf (cdr it) s-val)
(push (cons slot-struct s-val) slots))
(if (and (symbolp s-name) (not (keywordp s-name)) (alphanumericp (char (symbol-name s-name) 0)))
(if type
(if slot-struct
(progn
(print-warning "Invalid slot ~s specified when creating chunk with type ~s, but creating chunk ~s anyway." s-name (act-r-chunk-type-name type) name)
(aif (assoc slot-struct slots)
(setf (cdr it) s-val)
(push (cons slot-struct s-val) slots)))
(progn
(print-warning "Invalid slot ~s specified when creating chunk ~s with type ~s. Extending chunks with slot named ~s." s-name name (act-r-chunk-type-name type) s-name)
(extend-possible-slots s-name)
(push (cons (valid-slot-name s-name) s-val) slots)))
(progn
(model-warning "Extending chunks with slot named ~s because of chunk definition ~s" s-name chunk-def)
(extend-possible-slots s-name)
(push (cons (valid-slot-name s-name) s-val) slots)))
(progn
(print-warning "Invalid chunk definition: ~S invalid slot name ~s." chunk-def s-name)
(setf s nil)
(setf slots :error))))))
(unless (eq slots :error)
(let ((c (make-act-r-chunk
:name name
:merged-chunks (list name)
:documentation doc
:parameter-values (bt:with-lock-held (*chunk-parameters-lock*)
(make-array *chunk-parameters-count*
:initial-element *chunk-parameter-undefined*))
:slot-value-lists (cons slots (if type
(act-r-chunk-type-initial-spec type)
nil)))))
(push-last c chunk-list)
;; enter it into the main chunk table
(setf (gethash name (act-r-model-chunks-table model)) c))))))))))
(t
(print-warning "Invalid chunk definitions list provided to define-chunks ~s. Must be all lists or all names." chunk-def-list)))
;; second pass create slot-value list and define parameters
(dolist (chunk chunk-list)
(bt:with-lock-held ((act-r-chunk-lock chunk))
(let* ((slots-list nil)
(specified-slots (car (act-r-chunk-slot-value-lists chunk)))
(default-slots (mapcar (lambda (x)
(cons (act-r-slot-spec-name x) (act-r-slot-spec-value x)))
(awhen (cdr (act-r-chunk-slot-value-lists chunk))
(act-r-chunk-spec-slots it)))))
;; add any unspecified default slots to the set to add
(dolist (default default-slots)
(unless (assoc (car default) specified-slots :key 'act-r-slot-name)
(push (cons (valid-slot-name (car default)) (cdr default)) specified-slots)))
(dolist (slot specified-slots)
(let* ((slot-struct (car slot))
(slot-name (act-r-slot-name slot-struct))
(slot-value (cdr slot)))
(when slot-value
;; Create the slot-value chunk if it is needed
;; and if updates are happening on the fly map the value to
;; the "true" name
(setf slot-value (get-true-slot-value-name chunk slot-name slot-value))
(push (cons slot-struct slot-value) slots-list)
(setf (act-r-chunk-filled-slots chunk)
(logior (act-r-chunk-filled-slots chunk) (act-r-slot-mask slot-struct))))))
(setf (act-r-chunk-slot-value-lists chunk) slots-list)))))
(mapcar 'act-r-chunk-name chunk-list))))
(defun external-define-chunks (&rest chunks)
(define-chunks-fct (decode-string-names chunks)))
(add-act-r-command "define-chunks" 'external-define-chunks "Create chunks in the current model. Params: [ 'chunk-description'* | chunk-name* ]." nil)
(defun chk-slot-value (chunk slot-name) ;; only call when the chunk's lock is held
"Internal function for getting the value of a slot in a chunk structure"
(cdr (assoc slot-name (act-r-chunk-slot-value-lists chunk) :key 'act-r-slot-name)))
(defmacro chunk-slot-value (chunk-name slot-name)
"Return the value of a slot for the named chunk"
`(chunk-slot-value-fct ',chunk-name ',slot-name))
(defun chunk-slot-value-fct (chunk-name slot-name)
"Return the value of a slot for the named chunk"
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(chk-slot-value c slot-name)))))
(defun external-chunk-slot-value (chunk slot)
(encode-string (chunk-slot-value-fct (string->name chunk) (string->name slot))))
(add-act-r-command "chunk-slot-value" 'external-chunk-slot-value "Return the value of a slot in a chunk. Params: chunk-name slot-name" nil)
(defmacro chunk-filled-slots-list (chunk-name &optional sorted)
"Return a sorted list of slots that exist in the named chunk"
`(chunk-filled-slots-list-fct ',chunk-name ,sorted))
(defun chunk-filled-slots-list-fct (chunk-name &optional sorted)
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(if sorted
(mapcar (lambda (x) (act-r-slot-name (car x)))
(setf (act-r-chunk-slot-value-lists c)
(sort (act-r-chunk-slot-value-lists c) #'< :key (lambda (x) (act-r-slot-index (car x))))))
(mapcar (lambda (x) (act-r-slot-name (car x))) (act-r-chunk-slot-value-lists c)))))))
(defun external-chunk-filled-slots-list-fct (chunk-name &optional sorted)
(chunk-filled-slots-list-fct (string->name chunk-name) sorted))
(add-act-r-command "chunk-filled-slots-list" 'external-chunk-filled-slots-list-fct "Returns the list of slot names for the chunk provided which can be in an arbitrary or cannonical ordering. Params: chunk-name {cannonical-order?}." nil)
(defmacro set-chunk-slot-value (chunk-name slot-name value)
"Set the value of a chunk's slot"
`(set-chunk-slot-value-fct ',chunk-name ',slot-name ',value))
(defun set-chunk-slot-value-fct (chunk-name slot-name value)
"Set the value of a chunk's slot"
#| shouldn't happen, should it?
(when (stringp chunk-name)
(setf chunk-name (string->name chunk-name))
(setf slot-name (string->name slot-name))
(setf value (decode-string-names value)))
|#
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(set-chk-slot-value c slot-name value)))))
(defun external-set-chunk-slot-value (chunk slot value)
(encode-string (set-chunk-slot-value-fct (string->name chunk) (string->name slot) (decode-string value))))
(add-act-r-command "set-chunk-slot-value" 'external-set-chunk-slot-value "Change the value of a slot in a chunk. Params: chunk-name slot-name 'new-value'" nil)
(defun make-chunk-immutable (chunk-name)
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(setf (act-r-chunk-immutable c) t)))))
(defun external-make-chunk-immutable (chunk)
(make-chunk-immutable (string->name chunk)))
(add-act-r-command "make-chunk-immutable" 'external-make-chunk-immutable "Prevent any changes to a chunk's contents. Params: chunk-name")
(defun make-chunk-reusable (chunk-name)
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(if (and (null (act-r-chunk-not-storable c))
(= (length (act-r-chunk-merged-chunks c)) 1)
(eq chunk-name (car (act-r-chunk-merged-chunks c))))
(progn
(setf (act-r-chunk-merged-chunks c) nil)
(setf (act-r-chunk-not-storable c) t)
t)
nil)))))
(defun external-make-chunk-reusable (chunk)
(make-chunk-reusable (string->name chunk)))
(add-act-r-command "make-chunk-reusable" 'external-make-chunk-reusable "Mark a chunk so that it can be used with copy-to-chunk and not be deletable. Params: chunk-name")
(defun chunk-not-storable (chunk-name)
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(act-r-chunk-not-storable c)))))
(defun external-chunk-not-storable (chunk)
(chunk-not-storable (string->name chunk)))
(add-act-r-command "chunk-not-storable" 'external-chunk-not-storable "Check if a chunk has been marked as not storable (a reusable chunk). Params: chunk-name")
(defun set-chk-slot-value (c slot-name value) ;; only call when the lock is held
"internal chunk slot setting function"
(when (act-r-chunk-immutable c)
(unless (chunk-slot-equal value (chk-slot-value c slot-name))
(print-warning "Cannot change contents of chunk ~s." (act-r-chunk-name c))
(return-from set-chk-slot-value nil)))
(aif (valid-slot-name slot-name) ;; any slot name available can be set
(set-c-slot-value c it slot-name value)
(print-warning "~s is not a valid slot name. You can use extend-possible-slots to add it first if needed." slot-name)))
(defun set-c-slot-value (c slot-struct slot-name value) ;; only call when the lock is held
"Set the chunk's slot value assuming the chunk is not immutable and the slot name is valid"
;; changing the chunk automatically breaks it as a copy
;; even if the change were to set a slot to the same
;; value it has currently.
(setf (act-r-chunk-copied-from c) nil)
(let ((current (assoc slot-struct (act-r-chunk-slot-value-lists c))))
;; If the value in the slot now is a chunk then
;; remove this chunk from the back links of that chunk
(when (and current (update-chunks-on-the-fly))
(let ((old (cdr current)))
(when (chunk-p-fct old)
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(let* ((bl (chunk-back-links old))
(new-links (remove slot-name (gethash (act-r-chunk-name c) bl))))
(if new-links
(setf (gethash (act-r-chunk-name c) bl) new-links)
(remhash (act-r-chunk-name c) bl)))))))
;; If the new value should be a chunk but isn't
;; create one for it and if it is get its true name
;; when necessary
(setf value (get-true-slot-value-name c slot-name value))
;; Set the new slot value
(let ((mask (act-r-slot-mask slot-struct)))
(if value
(if current
;; already there so just replace the value
(setf (cdr current) value)
;; add the slot to the list and set the filled slot bit
(progn
(push (cons slot-struct value) (act-r-chunk-slot-value-lists c))
(setf (act-r-chunk-filled-slots c) (logior mask (act-r-chunk-filled-slots c)))))
;; if it's on the list remove it and clear the filled bit
(when (logtest mask (act-r-chunk-filled-slots c))
(setf (act-r-chunk-slot-value-lists c) (delete slot-struct (act-r-chunk-slot-value-lists c) :key 'car))
(setf (act-r-chunk-filled-slots c) (logandc1 mask (act-r-chunk-filled-slots c))))))
value))
(defmacro mod-chunk (chunk-name &rest modifications)
"Modify the slot values of a chunk"
`(mod-chunk-fct ',chunk-name ',modifications))
(defun mod-chunk-fct (chunk-name modifications-list)
"Modify the slot values of a chunk"
#| shouldn't happen...
(when (stringp chunk-name)
(setf chunk-name (string->name chunk-name))
(setf modifications-list (decode-string-names modifications-list)))
|#
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(cond ((act-r-chunk-immutable c)
(print-warning "Cannot modify chunk ~s because it is immutable." chunk-name))
((oddp (length modifications-list))
(print-warning "Odd length modifications list in call to mod-chunk."))
(t
(let ((slots-and-values nil)
(slots nil))
(do ((s modifications-list (cddr s)))
((null s))
(pushnew (car s) slots)
(push (cons (car s) (second s)) slots-and-values))
(cond ((not (= (length slots) (length slots-and-values)))
(print-warning "Slot name used more than once in modifications list."))
(t
(setf slots nil)
(dolist (x slots-and-values)
(let* ((name (car x))
(slot-struct (valid-slot-name name)))
(if slot-struct
(push-last (list slot-struct name (cdr x)) slots)
(progn
(print-warning "Invalid slot name ~s specified for mod-chunk." name)
(return-from mod-chunk-fct)))))
(dolist (slot-value slots chunk-name)
(set-c-slot-value c (first slot-value) (second slot-value) (third slot-value))))))))))))
(defun mod-chunk-external (name &rest modifications)
(mod-chunk-fct (string->name name) (decode-string-names modifications)))
(add-act-r-command "mod-chunk" 'mod-chunk-external "Modify the contents of the specified chunk with the list of slots and values provided. Params: chunk-name '{slot-name new-slot-value}'*" nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; to potentially speed things way up provide un-checked but fast accessors
;;; to the chunk info...
(defun fast-chunk-slot-value-fct (chunk-name slot-name)
"Return the value of a slot for the named chunk without testing validity"
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(chk-slot-value c slot-name)))))
(defun fast-set-chunk-slot-value-fct (chunk-name slot-name value)
"Set the value of a chunk's slot without testing validity"
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(set-chk-slot-value c slot-name value)))))
(defun fast-mod-chunk-fct (chunk-name modifications-list)
"Modify the slot values of a chunk without testing validity"
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(unless (oddp (length modifications-list))
(loop
(when (null modifications-list) (return))
(set-chk-slot-value
c
(pop modifications-list)
(pop modifications-list)))
chunk-name)))))
(defun mod-chunk-with-spec-fct (chunk-name mod-spec)
"Modify the slot values without testing except to skip request parameters and variables"
(let ((c (get-chunk chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(if (act-r-chunk-immutable c)
(print-warning "Cannot modify chunk ~s because it is immutable." chunk-name)
(dolist (x (act-r-chunk-spec-slots mod-spec) chunk-name)
(let ((name (act-r-slot-spec-name x)))
(unless (or (keywordp name) (chunk-spec-variable-p name))
(set-c-slot-value c (valid-slot-name name) name (act-r-slot-spec-value x))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro delete-chunk (chunk-name)
"Delete a chunk from a model"
`(delete-chunk-fct ',chunk-name))
(defun delete-chunk-fct (chunk-name)
"Delete a chunk from a model"
(let ((c (get-chunk-warn chunk-name)))
(when c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(if (act-r-chunk-immutable c)
(print-warning "Cannot delete chunk ~s because it is marked as immutable." chunk-name)
(if (act-r-chunk-not-storable c)
(print-warning "Cannot delete chunk ~s because it is marked as reusable." chunk-name)
(let ((tn (act-r-chunk-name c))
(model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
;; If this chunk has back-links from others to it then warn because
;; that's likely a problem
(when (update-chunks-on-the-fly)
(let ((bl (chunk-back-links chunk-name)))
(when (and (hash-table-p bl) (not (zerop (hash-table-count bl))))
(model-warning "Chunk ~s is being deleted but it is still used as a slot value in other chunks." chunk-name))
(when (not (eq tn chunk-name))
(let ((t-bl (chunk-back-links tn)))
(when (and (hash-table-p t-bl) (not (zerop (hash-table-count t-bl))))
(model-warning "Chunk ~s is being deleted but its true name ~s is still used as a slot value in other chunks." chunk-name tn)))))
;; Delete all of the back-links to this chunk
(dolist (slots (act-r-chunk-slot-value-lists c))
(let ((slot-name (act-r-slot-name (car slots)))
(old (cdr slots)))
(when (chunk-p-fct old)
(let* ((bl (chunk-back-links old))
(new-links (remove slot-name (gethash tn bl))))
(if new-links
(setf (gethash tn bl) new-links)
(remhash tn bl)))))))
;; Take all the related chunks out of the main hash-table
(dolist (x (act-r-chunk-merged-chunks c))
(remhash x (act-r-model-chunks-table model))
;; Take them out of the meta-data table too
(when (update-chunks-on-the-fly)
(remhash x (act-r-model-chunk-ref-table model)))))
chunk-name)))))))
(defmacro purge-chunk (chunk-name)
"delete a chunk and release its name"
`(purge-chunk-fct ',chunk-name))
(defun purge-chunk-fct (chunk-name)
(let ((name (delete-chunk-fct chunk-name)))
(when name
(release-name-fct name))))
(defun remote-delete-chunk (chunk-name)
(delete-chunk-fct (string->name chunk-name)))
(add-act-r-command "delete-chunk" 'remote-delete-chunk "Delete a chunk from the model. Params: chunk-name.")
(defun remote-purge-chunk (chunk-name)
(purge-chunk-fct (string->name chunk-name)))
(add-act-r-command "purge-chunk" 'remote-purge-chunk "Delete a chunk from the model and release the name. Params: chunk-name.")
(defmacro merge-chunks (chunk-name1 chunk-name2)
"Merge two chunks into a single representation"
`(merge-chunks-fct ',chunk-name1 ',chunk-name2))
(defun merge-chunks-fct (chunk-name1 chunk-name2)
"Merge two chunks into a single representation"
(let ((c1 (get-chunk-warn chunk-name1))
(c2 (get-chunk-warn chunk-name2)))
(when (and c1 c2)
(unless (chunk-equal-test c1 c2)
(return-from merge-chunks-fct nil))
(unless (eq c1 c2)
(bt:with-recursive-lock-held ((act-r-chunk-lock c1))
(bt:with-recursive-lock-held ((act-r-chunk-lock c2))
;; update the parameters for c1
(dolist (param (bt:with-lock-held (*chunk-parameters-lock*)
*chunk-parameters-merge-list*))
(setf (aref (act-r-chunk-parameter-values c1) (act-r-chunk-parameter-index param))
(case (act-r-chunk-parameter-merge param)
(:second
(let ((v (aref (act-r-chunk-parameter-values c2) (act-r-chunk-parameter-index param))))
(if (eq v *chunk-parameter-undefined*)
(chunk-parameter-default param chunk-name2)
v)))
(:second-if
(let ((v (aref (act-r-chunk-parameter-values c2) (act-r-chunk-parameter-index param))))
(when (eq v *chunk-parameter-undefined*)
(setf v (chunk-parameter-default param chunk-name2)))
(if v
v
(aref (act-r-chunk-parameter-values c1) (act-r-chunk-parameter-index param)))))
(t
(dispatch-apply (act-r-chunk-parameter-merge param) chunk-name1 chunk-name2)))))
(dolist (param (bt:with-lock-held (*chunk-parameters-lock*)
*chunk-parameters-merge-value-list*))
(setf (aref (act-r-chunk-parameter-values c1) (act-r-chunk-parameter-index param))
(let ((c1-val (aref (act-r-chunk-parameter-values c1) (act-r-chunk-parameter-index param)))
(c2-val (aref (act-r-chunk-parameter-values c2) (act-r-chunk-parameter-index param))))
(dispatch-apply (act-r-chunk-parameter-merge-value param)
(if (eq c1-val *chunk-parameter-undefined*)
(chunk-parameter-default param chunk-name1)
c1-val)
(if (eq c2-val *chunk-parameter-undefined*)
(chunk-parameter-default param chunk-name2)
c2-val)))))
;; If either is immutable then the result should be as well.
;; Since c1 will maintain its immutability need to check if c2
;; is immutable and then make c1 immutable if c2 is.
(when (act-r-chunk-immutable c2)
(setf (act-r-chunk-immutable c1) t))
;; For any chunks which had been merged with c2 also remap them
;; and indicate them in c1
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(dolist (x (act-r-chunk-merged-chunks c2))
(setf (gethash x (act-r-model-chunks-table model)) c1)
(push x (act-r-chunk-merged-chunks c1)))
;; When name-remapping is on
(when (update-chunks-on-the-fly)
;; delete all back-links to the c2 chunk
(dolist (slots (act-r-chunk-slot-value-lists c2))
(let ((slot-name (act-r-slot-name (car slots)))
(old (cdr slots)))
(when (chunk-p-fct old)
(let* ((bl (chunk-back-links old))
(new-links (remove slot-name (gethash chunk-name2 bl))))
(if new-links
(setf (gethash chunk-name2 bl) new-links)
(remhash chunk-name2 bl))))))
;; replace all the slot values which hold chunk-name2 with chunk-name1
(when (hash-table-p (chunk-back-links chunk-name2))
(maphash (lambda (chunk slots)
(dolist (x slots)
(fast-set-chunk-slot-value-fct chunk x chunk-name1)
(dolist (notify (notify-on-the-fly-hooks))
(dispatch-apply notify chunk))))
(chunk-back-links chunk-name2))
(clrhash (chunk-back-links chunk-name2)))))))))
chunk-name1)))
(defun external-merge-chunks-fct (c1 c2)
(merge-chunks-fct (string->name c1) (string->name c2)))
(add-act-r-command "merge-chunks" 'external-merge-chunks-fct "Merge the two named chunks into one chunk if they are equivalent. Params: chunk-name-1 chunk-name-2")
(defmacro create-chunk-alias (chunk alias)
`(create-chunk-alias-fct ',chunk ',alias))
(defun create-chunk-alias-fct (chunk alias)
(verify-current-model
"create-chunk-alias called with no current model."
(cond ((not (chunk-p-fct chunk))
(model-warning "~s is not the name of a chunk in the current model." chunk))
((chunk-p-fct alias)
(model-warning "~s is already the name of a chunk in the current model and cannot be used as an alias." alias))
((not (symbolp alias))
(model-warning "~s is not a symbol and thus cannot be used as a chunk alias." alias))
(t
(let ((model (current-model-struct)))
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(let ((c (get-chunk chunk)))
(setf (gethash alias (act-r-model-chunks-table model)) c)
(push alias (act-r-chunk-merged-chunks c))
alias)))))))
(defun external-create-chunk-alias-fct (c a)
(create-chunk-alias-fct (string->name c) (string->name a)))
(add-act-r-command "create-chunk-alias" 'external-create-chunk-alias-fct "Create an alternate name by which the named chunk can be referenced. Params: chunk-name alternate-name")
(defmacro eq-chunks (chunk-name1 chunk-name2)
"Return t if two chunks have the same underlying representation"
`(eq-chunks-fct ',chunk-name1 ',chunk-name2))
(defun eq-chunks-fct (chunk-name1 chunk-name2)
"Return t if two chunks have the same underlying representation"
(bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct)))
(let ((c1 (get-chunk-warn chunk-name1))
(c2 (get-chunk-warn chunk-name2)))
(and c1 c2 (eq c1 c2)))))
(defun external-eq-chunks-fct (c1 c2)
(eq-chunks-fct (string->name c1) (string->name c2)))
(add-act-r-command "eq-chunks" 'external-eq-chunks-fct "Return whether the two named chunks are the same chunk. Params: chunk-name-1 chunk-name-2" nil)
(defmacro true-chunk-name (chunk-name)
"Return the prototypical name of a chunk in the event of merging"
`(true-chunk-name-fct ',chunk-name))
(defun true-chunk-name-fct (chunk-name)
"Return the prototypical name of a chunk in the event of merging"
(let ((c (get-chunk chunk-name)))
(if c
(act-r-chunk-name c)
chunk-name)))
(defun external-true-chunk-name-fct (c)
(true-chunk-name-fct (string->name c)))
(add-act-r-command "true-chunk-name" 'external-true-chunk-name-fct "Return the true name of a chunk. Params: chunk-name")
(defmacro equal-chunks (chunk-name1 chunk-name2)
"Return t if two chunks are of the same chunk-type and have equal slot values"
`(equal-chunks-fct ',chunk-name1 ',chunk-name2))
(defun equal-chunks-fct (chunk-name1 chunk-name2)
"Return t if two chunks are of the same chunk-type and have equal slot values"
(let ((c1 (get-chunk-warn chunk-name1))
(c2 (get-chunk-warn chunk-name2)))
(chunk-equal-test c1 c2)))
(defun external-equal-chunks-fct (c1 c2)
(equal-chunks-fct (string->name c1) (string->name c2)))
(add-act-r-command "equal-chunks" 'external-equal-chunks-fct "Return whether the two named chunks are equivalent. Params: chunk-name-1 chunk-name-2" nil)
(defun chunk-equal-test (c1 c2)
"Internal function for comparing the equality of two chunks"
(and c1 c2 (or (eq c1 c2)
(bt:with-recursive-lock-held ((act-r-chunk-lock c1))
(bt:with-recursive-lock-held ((act-r-chunk-lock c2))
(and (= (act-r-chunk-filled-slots c1)
(act-r-chunk-filled-slots c2))
(every (lambda (slot)
(chunk-slot-equal
(cdr slot)
(chk-slot-value c2 (act-r-slot-name (car slot)))))
(act-r-chunk-slot-value-lists c1))))))))
(defun chunk-slot-equal (val1 val2)
(if (eq val1 val2)
t
(let (c1 c2)
(cond ((bt:with-recursive-lock-held ((act-r-model-chunk-lock (current-model-struct))) ;; possible for them to merge between the get-chunk calls...
(and (setf c1 (get-chunk val1))
(setf c2 (get-chunk val2))))
(eq c1 c2))
((stringp val1)
(and (stringp val2) (string-equal val1 val2)))
(t (equalp val1 val2))))))
(defun external-chunk-slot-equal (val1 val2)
(chunk-slot-equal (decode-string-names val1) (decode-string-names val2)))
(add-act-r-command "chunk-slot-equal" 'external-chunk-slot-equal "Returns whether the provided items are considered equal values for chunk slots. Params: 'val1' 'val2'.")
(defvar *suppress-extend-item-warning* nil)
(defun suppress-extension-warnings ()
(setf *suppress-extend-item-warning* t))
(defun unsuppress-extension-warnings ()
(setf *suppress-extend-item-warning* nil))
(defmacro extend-chunks (parameter-name &key (default-value nil)
(default-function nil)
(merge-function nil)
(merge-value-function nil)
(copy-function nil)
(copy-from-chunk-function nil))
"Add new parameters to all chunks"
(if (or (not (symbolp parameter-name)) (keywordp parameter-name))
(print-warning "~s is not a valid name for specifying a chunk parameter." parameter-name)
(let* ((accessor (concatenate 'string "chunk-" (string-downcase parameter-name)))
(remote-setter (concatenate 'string "set-chunk-" (string-downcase parameter-name)))
(accessor-name (intern (string-upcase accessor)))
(setf-name (intern (concatenate 'string "CHUNK-" (string-upcase parameter-name) "-SETF")))
(external-name (intern (concatenate 'string "EXTERNAL-CHUNK-" (string-upcase parameter-name))))
(external-setf-name (intern (concatenate 'string "EXTERNAL-CHUNK-" (string-upcase parameter-name) "-SETF")))
(index (gensym))
(exists (gensym))
(param (gensym)))
(if (find parameter-name (bt:with-lock-held (*chunk-parameters-lock*)
*chunk-parameters-list*)
:key #'act-r-chunk-parameter-name)
(progn
(print-warning "Parameter ~s already defined for chunks." parameter-name)
:duplicate-parameter)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(unless *suppress-extend-item-warning*
(when (fboundp ',accessor-name)
(print-warning "Function ~s already exists and is being redefined." ',accessor-name))
(when (fboundp ',setf-name)
(print-warning "Function ~s already exists and is being redefined." ',setf-name))
(when (fboundp ',external-name)
(print-warning "Function ~s already exists and is being redefined." ',external-name))
(when (fboundp ',external-setf-name)
(print-warning "Function ~s already exists and is being redefined." ',external-setf-name)))
(bt:with-lock-held (*chunk-parameters-lock*)
(let* ((,index *chunk-parameters-count*)
(,exists (find ',parameter-name *chunk-parameters-list* :key #'act-r-chunk-parameter-name))
(,param (make-act-r-chunk-parameter :name ',parameter-name
:index ,index
:default-value ',default-value
:default-function ',default-function
:merge ',merge-function
:merge-value ',merge-value-function
:copy ',copy-function
:copy-from-chunk ',copy-from-chunk-function
:accessor ',accessor-name)))
(if ,exists
(progn
(setf ,index (act-r-chunk-parameter-index ,exists))
(setf *chunk-parameters-list* (remove ,exists *chunk-parameters-list*))
(setf *chunk-parameters-copy-list* (remove ,exists *chunk-parameters-copy-list*))
(setf *chunk-parameters-merge-list* (remove ,exists *chunk-parameters-merge-list*))
(setf *chunk-parameters-merge-value-list* (remove ,exists *chunk-parameters-merge-value-list*))
(setf (act-r-chunk-parameter-index ,param) (act-r-chunk-parameter-index ,exists)))
(incf *chunk-parameters-count*))
(push ,param *chunk-parameters-list*)
(if ',copy-function
(push ,param *chunk-parameters-copy-list*)
(when ',copy-from-chunk-function
(push ,param *chunk-parameters-copy-list*)))
(when ',merge-function
(push ,param *chunk-parameters-merge-list*))
(when ',merge-value-function
(push ,param *chunk-parameters-merge-value-list*))
(defun ,accessor-name (chunk-name)
(let ((c (get-chunk chunk-name)))
(if c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(let ((v (aref (act-r-chunk-parameter-values c) ,index)))
(if (eq v *chunk-parameter-undefined*)
(setf (aref (act-r-chunk-parameter-values c) ,index)
(chunk-parameter-default ,param chunk-name))
v)))
(print-warning "Chunk ~s does not exist in attempt to access ~a." chunk-name ',accessor-name))))
(defun ,setf-name (chunk-name new-value)
(let ((c (get-chunk chunk-name)))
(if c
(bt:with-recursive-lock-held ((act-r-chunk-lock c))
(setf (aref (act-r-chunk-parameter-values c) ,index) new-value))
(print-warning "Chunk ~s does not exist in attempt to set ~a." chunk-name ',accessor-name))))
(defsetf ,accessor-name ,setf-name)
(defun ,external-name (chunk-name)
(encode-string-names (,accessor-name (string->name chunk-name))))
(defun ,external-setf-name (chunk-name new-value)
(encode-string-names (,setf-name (string->name chunk-name) (decode-string-names new-value))))
(when (check-act-r-command ,accessor)
(unless *suppress-extend-item-warning*
(print-warning "Remote command ~s already exists and will attempt to be removed to create chunk accessor." ,accessor))
(remove-act-r-command ,accessor))
(when (check-act-r-command ,remote-setter)
(unless *suppress-extend-item-warning*
(print-warning "Remote command ~s already exists and will attempt to be removed to create chunk accessor." ,remote-setter))
(remove-act-r-command ,remote-setter))
(add-act-r-command ,accessor ',external-name (format nil "Command to get the chunk parameter named ~s. Params: chunk-name" ',parameter-name))
(add-act-r-command ,remote-setter ',external-setf-name (format nil "Command to set the chunk parameter named ~s. Params: chunk-name 'value'" ',parameter-name))
',accessor-name)))))))
(defun external-extend-chunks (parameter-name &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'extend-chunks '(:default-value :default-function :merge-function :merge-value-function :copy-function :copy-from-chunk-function))
(when valid
(eval `(extend-chunks ,(string->name parameter-name) ,@(convert-options-list-items ol nil '(:default-function :merge-function :merge-value-function :copy-function :copy-from-chunk-function :default-value)))))))
(add-act-r-command "extend-chunks" 'external-extend-chunks
"Create a new parameter for chunks. Params: parameter-name { < 'default-value', 'default-function', 'merge-function', 'merge-value-function', 'copy-function', 'copy-from-chunk-function' > }."
nil)
(defun normalize-chunk-names (&optional (unintern? nil))
(let ((model (current-model-struct)))
(if model
(bt:with-recursive-lock-held ((act-r-model-chunk-lock model))
(if (update-chunks-on-the-fly)
;; Use the meta-data table to do the work
(maphash (lambda (key value)
(when (not (eq key (act-r-chunk-name value))) ;; not a used chunk
;; Square up all names for unused chunks
(let ((bl (chunk-back-links key)))
(when (hash-table-p bl)
(let ((tn (true-chunk-name-fct key)))
(maphash (lambda (c ss)
(dolist (s ss)
(fast-set-chunk-slot-value-fct c s tn)
(dolist (notify (notify-on-the-fly-hooks))
(dispatch-apply notify c))))
bl))
(clrhash bl)))
;; release names of unused chunks
(when unintern?
;; Take it out of the main hash-table
(remhash key (act-r-model-chunks-table model))
;; Take it out of the meta-data table too
(remhash key (act-r-model-chunk-ref-table model))
;; unintern the name
(release-name-fct key))))
(act-r-model-chunks-table model))
;; Without the meta-data do it the hard way
(let ((possible-removals nil))
(maphash (lambda (key value)
(when (not (eq key (act-r-chunk-name value)))
(push key possible-removals)))
(act-r-model-chunks-table model))
;; clean up the chunk references
;; this could take a while
(when possible-removals
(maphash (lambda (chunk val)
(when (eq chunk (act-r-chunk-name val))
(dolist (slot-val (act-r-chunk-slot-value-lists (get-chunk chunk)))
(let ((slot (act-r-slot-name (car slot-val)))
(value (cdr slot-val)))
(when (and (chunk-p-fct value) (member value possible-removals))
(fast-set-chunk-slot-value-fct chunk slot (true-chunk-name-fct value))
(dolist (notify (notify-on-the-fly-hooks))
(dispatch-apply notify chunk)))))))
(act-r-model-chunks-table model)))
(when unintern?
(dolist (x possible-removals)
(remhash x (act-r-model-chunks-table model))
(release-name-fct x))))))
(print-warning "No current model in which to normalize chunk names."))))
(add-act-r-command "normalize-chunk-names" 'normalize-chunk-names "Replace all chunk slot values that are chunk names with the true name of that chunk, and delete the other names if indicated. Params: {delete}")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 107,764 | Common Lisp | .lisp | 1,762 | 49.602724 | 236 | 0.563269 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 199764a6f57b654488279bb2f8c4f8f9a3a03cfa3ee8dea07caf592cb2ceae44 | 14,310 | [
-1
] |
14,311 | system-locks.lisp | asmaloney_ACT-R/framework/system-locks.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2017 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : system-locks.lisp
;;; Version : 1.0
;;;
;;; Description : Code for creating and using locks at the meta-process and model
;;; : levels.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2017.03.30 Dan [1.0]
;;; : * Initial creation.
;;; 2020.07.29 Dan
;;; : * Fixed a bug with make-act-r-model-lock even though it's not
;;; : currently being used.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; In order for things to be thread safe need locks around lots of things...
;;; So, this code provides the mechanism for creating and using locks that exist
;;; at the meta-process and the model level. A lock gets named with a string and
;;; the with-... and acquire-.../release-... macros are used to protect the code
;;; as needed.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; The meta-process table is not cleared upon clear-all and the model table is
;;; not cleared upon reset.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defun make-act-r-lock (name &optional recursive)
(if (gethash name (meta-p-lock-table (current-mp)))
(print-warning "A lock named ~s already exists." name)
(progn
(setf (gethash name (meta-p-lock-table (current-mp)))
(if recursive
(cons (bt:make-recursive-lock name) t)
(cons (bt:make-lock name) nil)))
name)))
(defun make-act-r-model-lock (name &optional recursive)
(with-current-model
"No current model available to create a model lock"
(if (gethash name (act-r-model-lock-table current-model))
(print-warning "A lock named ~s already exists in the current model." name)
(progn
(setf (gethash name (act-r-model-lock-table current-model))
(if recursive
(cons (bt:make-recursive-lock name) t)
(cons (bt:make-lock name) nil)))
name))))
(defmacro with-act-r-lock (name &body body)
(let ((lock (gensym)))
`(let* ((,lock (gethash ,name (meta-p-lock-table (current-mp)))))
(if ,lock
(if (cdr ,lock)
(bt:with-recursive-lock-held ((car ,lock))
(progn ,@body))
(bt:with-lock-held ((car ,lock))
(progn ,@body)))
(print-warning "No actions taken in with-act-r-lock because there is no lock named ~s" ,name)))))
(defun acquire-act-r-lock (name &optional (wait t))
(let ((lock (gethash name (meta-p-lock-table (current-mp)))))
(if lock
(if (cdr lock)
(bt:acquire-recursive-lock (car lock))
(bt:acquire-lock (car lock) wait))
(print-warning "Cannot acquire act-r-lock because there is no lock named ~s" name))))
(defun release-act-r-lock (name)
(let ((lock (gethash name (meta-p-lock-table (current-mp)))))
(if lock
(if (cdr lock)
(bt:release-recursive-lock (car lock))
(bt:release-lock (car lock)))
(print-warning "Cannot release act-r-lock because there is no lock named ~s" name))))
(defmacro with-act-r-model-lock (name &body body)
(let ((lock (gensym)))
`(with-current-model
(let* ((,lock (gethash ,name (act-r-model-lock-table current-model))))
(if ,lock
(if (cdr ,lock)
(bt:with-recursive-lock-held ((car ,lock))
(progn ,@body))
(bt:with-lock-held ((car ,lock))
(progn ,@body)))
(print-warning "No actions taken in with-act-r-model-lock because there is no lock named ~s in the current model: ~s" ,name current-model))))))
(defun acquire-act-r-model-lock (name &optional (wait t))
(with-current-model
"Cannot acquire a lock because there is no current model."
(let ((lock (gethash name (act-r-model-lock-table current-model))))
(if lock
(if (cdr lock)
(bt:acquire-recursive-lock (car lock))
(bt:acquire-lock (car lock) wait))
(print-warning "Cannot acquire act-r-lock because there is no lock named ~s" name)))))
(defun release-act-r-model-lock (name)
(with-current-model
"Cannot acquire a lock because there is no current model."
(let ((lock (gethash name (act-r-model-lock-table current-model))))
(if lock
(if (cdr lock)
(bt:release-recursive-lock (car lock))
(bt:release-lock (car lock)))
(print-warning "Cannot release act-r-lock because there is no lock named ~s" name)))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 6,378 | Common Lisp | .lisp | 144 | 39.069444 | 156 | 0.562098 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c733ee8b6646bf2eb8747122c79620ff335b4749e072d44b45dffb29d6d0518c | 14,311 | [
-1
] |
14,312 | chunk-spec.lisp | asmaloney_ACT-R/framework/chunk-spec.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : chunk-spec.lisp
;;; Version : 3.0
;;;
;;; Description : Definition of chunk specifications and corresponding functions
;;;
;;; Bugs :
;;;
;;; To do : * Finish the documentation.
;;; : * Investigate optimizations after there's some use.
;;; : * Add a function to check chunk-specs to make module writing
;;; : easier.
;;; ----- History -----
;;;
;;; 2004.09.02 Dan
;;; : Creation.
;;; 2004.12.29 Dan
;;; : Realized that the comparitors are backwards with respect
;;; : to productions in test-chunk-slots.
;;; 2005.02.03 Dan
;;; : * Changing the internal slot-value-lists of a chunk to be a
;;; : hash-table instead of an alist...
;;; 2005.02.09 Dan
;;; : * Some minor cleanup - changing member to find where possible.
;;; 2005.04.19 Dan
;;; : * Added pprint-chunk-spec.
;;; 2005.05.16 Dan
;;; : * Modified chunk-spec-variable-p to test that the name has
;;; : a length > 1 to reject the symbol itself as a variable.
;;; : That fixes a minor problem in production parsing and I
;;; : don't think it breaks anything else.
;;; 2005.09.09 Dan
;;; : * Renamed chunk-to-chunk-spec chunk-name-to-chunk-spec to
;;; : clarify its use because I introduced a bug somewhere
;;; : along the line with its usage that didn't actually affect
;;; : any existing modules, but may cause problems for other
;;; : module writers.
;;; : * Also fixed chunk-name-to-chunk-spec because it didn't
;;; : include nil slots in the spec, but it probably should (it
;;; : did prior to my "fixing" it when I changed over to hash
;;; : tables).
;;; 2005.11.17 Dan
;;; : * Fixed chunk-name-to-chunk-spec because it incorrectly
;;; : referenced the internal chunk-type slot list instead of
;;; : using ct-slot-names.
;;; 2006.09.11 Dan
;;; : * Changed chunk-slot-equal so that it uses equalp instead of
;;; : equal when the string and chunk checks fall through because
;;; : numbers (which is the typical value that'd fall through)
;;; : don't test well with equal...
;;; 2007.06.18 Dan
;;; : * Added slot-specs-to-chunk-spec-list and chunk-spec-to-chunk-def
;;; : as "official" commands now and also added slot-specs-to-chunk-spec
;;; : which removes the need to call define-chunk-spec after slot-specs-
;;; : to-chunk-spec-list.
;;; 2007.07.02 Dan
;;; : * Changed PROCESS-SLOTS-SPECS so that it keeps the slot-spec
;;; : in the order provided during definition.
;;; 2007.08.07 Dan
;;; : * Fixed pprint-chunk-spec so that it actually has the : on the
;;; : front of the request parameters.
;;; 2008.06.16 Dan
;;; : * Changed test-chunk-slots so that it always fails if there
;;; : are unbound variables even when they're used in other
;;; : tests. Doesn't change the normal operation, just shuts
;;; : down the possibility of "odd" chunk-specs doing unusual
;;; : matches that result in a true result.
;;; 2008.06.17 Dan
;;; : * Changed test-chunk-slots so that it ignores request parameters
;;; : in the chunk-spec for matching purposes.
;;; : * Added tests for current model and mp to match-chunk-spec-p.
;;; 2008.06.18 Dan
;;; : * Added a test to find-matching-chunks to verify that the
;;; : chunks parameter is a list when it's not :all.
;;; : * Fixed the warning in chunk-spec-slot-spec to name the right
;;; : function.
;;; 2008.06.20 Dan
;;; : * Changed chunk-spec-to-chunk-def so that tests to make sure
;;; : the parameter is a chunk-spec.
;;; : * Changed chunk-spec-to-chunk-def so that it also rejects a
;;; : spec with request parameters.
;;; : * Removed the macros of slot-specs-to-chunk-spec-list and
;;; : slot-specs-to-chunk-spec and renamed the functions to not
;;; : have the -fct since none of the other chunk-spec manipulation
;;; : commands use that convention and they aren't the types of
;;; : things that would be entered 'directly' and need a macro
;;; : form.
;;; 2008.07.31 Dan
;;; : * Took chunk-slot-equal out of here and put it into the chunks
;;; : file.
;;; 2008.10.30 Dan
;;; : * Performance improvement for test-chunk-slots - fewer loops
;;; : over the spec/slots.
;;; 2013.01.28 Dan
;;; : * Changed the internal storing of the chunk-type to the name
;;; : since that's what got used anyway and changed process-slots-specs
;;; : to call valid-chunk-type-slot instead (which is the command
;;; : it really should have been using anyway) and similarly don't
;;; : use the internal chunk/chunk-type accessors in chunk-name-to-chunk-spec.
;;; 2013.02.14 Dan
;;; : * Changed strip-request-parameters-from-chunk-spec so that it
;;; : maintains the ordering of the slots and removed an unneeded
;;; : cond from chunk-spec-slot-spec.
;;; 2013.03.13 Dan [1.1]
;;; : * Changed process-slots-specs so that it allows a parent type
;;; : to specify slots of child types in chunk-specs.
;;; : * Changed test-chunk-slots so that it requires that a chunk
;;; : have the specified slot as well as matching its value --
;;; : not having the slot is not the same as having the slot with
;;; : a value of nil.
;;; 2013.03.18 Dan
;;; : * Fixed some order dependence issues in test-chunk-slots.
;;; 2013.06.07 Dan
;;; : * Changed test-chunk-slots so that it now requires a parameter
;;; : indicating whether the chunk is static or not because now a
;;; : static chunk which doesn't have a particular slot will match
;;; : to a spec which says "= <that slot> nil" because for statics
;;; : not having a slot is the same as having a slot with an explict
;;; : value of nil.
;;; 2014.02.14 Dan
;;; : * Fixed a bug in test-chunk-slots with how it tests variables
;;; : between slots that was broken with the 13/3/13 change.
;;; 2014.03.03 Dan [2.0]
;;; : * Conversion to the no chunk-types at run time mechanism. A
;;; : chunk-spec now holds two vectors of slot info (filled and empty)
;;; : instead of a type symbol.
;;; : * Chunk-spec-chunk-type returns nil and prints a warning.
;;; : * Chunk-spec-filled-slots and chunk-spec-empty-slots return
;;; : the corresponding vectors for comparison purposes.
;;; : * The isa is optional when defining a chunk-spec but if provided
;;; : starts with the default spec for the type, but overwrites
;;; : any default values with those provided in the spec.
;;; 2014.03.14 Dan
;;; : * Treat request parameters like slots in a chunk-spec, but not
;;; : in chunks.
;;; 2014.03.19 Dan
;;; : * Allow a chunk-spec to have variablized slot names, add an
;;; : instantiate-chunk-spec command, and require that matching a
;;; : chunk-spec only uses the "instantiated" slot specs.
;;; : * Remove the warning when a chunk-spec-slot-spec gets a slot
;;; : that's not specified to avoid the need for pre-checking the
;;; : slots everywhere that's used, and do the same for the
;;; : slot-in-chunk-spec-p function as well.
;;; 2014.03.20 Dan
;;; : * Let define-chunk-spec-fct extend chunks automatically with
;;; : optional parameters that indicate if it can and if it should
;;; : print a warning when it does.
;;; : * Now returns 2 values: the spec and a list of slots that were
;;; : added by extension.
;;; 2014.03.26 Dan
;;; : * Don't allow modifiers for request parameters i.e. they must
;;; : have an = modifier.
;;; 2014.03.27 Dan
;;; : * Added merge-chunk-specs command.
;;; 2014.03.28 Dan
;;; : * Instantiate-chunk-spec now returns two values like define-
;;; : chunk-spec.
;;; 2014.04.01 Dan
;;; : * Added the functions for comparing a chunk/slot-vector to
;;; : the filled and empty specs so I don't need to do the bit
;;; : tests directly everywhere.
;;; 2014.04.07 Dan
;;; : * Moved chunk-spec-variable-p to misc-utils.
;;; 2014.05.08 Dan
;;; : * Adding the structure spec-slot to allow for more cleanly
;;; : accessing the components of a slot specification. However,
;;; : they are still represented as lists this just provides
;;; : accessors to treat the list as a struct.
;;; 2014.05.19 Dan
;;; : * Putting slot-specs-to-chunk-spec back in because vision and
;;; : audio can use such a function.
;;; 2014.06.09 Dan
;;; : * Changed a warning so that it matches the older version.
;;; 2014.06.11 Dan
;;; : * Fixed some logic in add-slot-spec-to-chunk-spec so that the
;;; : backward compatibility flag properly indicates how to deal
;;; : with a - slot <val> condition in a chunk-spec.
;;; 2014.06.12 Dan
;;; : * Reevaluated the logic in how matching nil slots should work
;;; : under various conditions and decided that it should be the
;;; : same with or without the backward compat. flag because we
;;; : don't want to capture the "odd" behavior of 6.0 rejecting
;;; : a non-existant slot.
;;; 2014.06.24 Dan
;;; : * Allow the definition of a chunk-spec which uses an isa and
;;; : slots which don't belong to that type, but print a hard
;;; : warning.
;;; 2014.09.05 Dan
;;; : * Add extra tests to process-slots-specs when trying to extend
;;; : with a new slot because with allowing 'bad' slots as above
;;; : it has to be sure bad values are at least valid as a slot
;;; : name first.
;;; 2014.11.04 Dan
;;; : * Added model and meta-process checks to pprint-chunk-spec.
;;; : * Starting to fix issues with the match and find code to deal
;;; : with the fact that variables are now allowed in the slot name
;;; : positions of chunk-specs. Isn't a problem for the current
;;; : code that uses chunk-specs since conflict resolution doesn't
;;; : rely on it and things like visicon searches which use vars
;;; : only do so in the value spot, but it should do the "right"
;;; : thing for all usage.
;;; 2014.11.05 Dan
;;; : * Match-chunk-spec-p now works for arbitrary depth slot name
;;; : bindings when using the default variable character.
;;; 2014.11.06 Dan
;;; : * Match-chunk-spec-p works fully with other variable characters
;;; : though it can be tough to take advantage of that since slot
;;; : names need to be valid during the definition of the chunk-spec.
;;; : * Changed slot-in-chunk-spec-p to return t when it's a varaible
;;; : now too.
;;; : * Added the slot-spec-* accessors to go along with spec-slot
;;; : since they better match the description in the manual and are
;;; : safer since they don't throw an error if non-list provided.
;;; : * Fixed chunk-spec-to-chunk-def to fail if there are variablized
;;; : slots in the chunk-spec.
;;; : * Safety check added to verify-single-explicit-value.
;;; 2014.12.16 Dan
;;; : * Don't use the list structure trick to define the spec-slot-*
;;; : accessors since not all Lisps like that when passed nil.
;;; : Instead just make it functions calling first, second, and
;;; : third with no error checking (also was true for the struct
;;; : accessors) along with corresponding setf forms.
;;; 2015.08.19 Dan
;;; : * Added the chunk-difference-to-chunk-spec function which
;;; : returns a chunk-spec with the modifications necessary to
;;; : turn the second chunk into a copy of the first. Needed by
;;; : visual tracking because with nil slots not being part of a
;;; : chunk now chunk-name-to-chunk-spec isn't sufficient if the
;;; : first chunk doesn't have a slot the second. May be useful
;;; : in other places as well.
;;; 2017.06.20 Dan
;;; : * Locking access to the model's chunk table for find-matching-
;;; : chunks.
;;; 2017.06.21 Dan
;;; : * Lock a chunk when accessing its internal slots.
;;; 2017.08.09 Dan
;;; : * Added the printed-chunk-spec command to provide an alternative
;;; : for capture-model-output which doesn't work in an RPC world.
;;; 2017.09.28 Dan
;;; : * Added an optional parameter to printed-chunk-spec to have it
;;; : printed to a 'flat' string instead of embedding the new lines
;;; : and production spacing.
;;; 2017.12.06 Dan [3.0]
;;; : * Adding a component to hold a table of chunk-specs since a
;;; : remote call can't use the internal struct. Instead cache
;;; : the struct in the table and return a # as the chunk-spec-id
;;; : instead. Need to provide a 'release' mechanism too since
;;; : otherwise the table could get large before a reset/clearall
;;; : can flush it.
;;; 2018.06.06 Dan
;;; : * Added a remote define-chunk-spec-fct.
;;; : * Chunk-spec-to-id tests that it's actually given a chunk-spec.
;;; : * Don't throw an error for bad remote define-chunk-spec calls.
;;; : Just return nil since there'll already be a warning.
;;; : * Added a remote chunk-name-to-chunk-spec and pprint-chunk-spec.
;;; 2018.06.07 Dan
;;; : * Added a remote match-chunk-spec-p, allow commands for the
;;; : test functions, and do a little more parameter checking.
;;; : * Added remote find-matching-chunks, chunk-spec-slots, slot-in-
;;; : chunk-spec-p, chunk-spec-slot-spec, slot-spec-modifier,
;;; : slot-spec-slot, slot-spec-value.
;;; 2018.06.08 Dan
;;; : * Added a remote chunk-spec-variable-p here since the
;;; : original is in misc-utils which gets loaded before the
;;; : dispatcher.
;;; : * Verify-single-explicit-value now always returns 2 values
;;; : since that's safer for use remotely, and added a remote
;;; : command for it.
;;; : * Added remote chunk-difference-to-chunk-spec and printed-
;;; : chunk-spec.
;;; 2018.06.11 Dan
;;; : * Fixed a bug with chunk-spec-slots introduced with that last
;;; : update.
;;; 2018.06.12 Dan
;;; : * Work to make sure things are consistent with respect to when
;;; : special string handling is used.
;;; : * Use the new process-options-list function from the dispatcher
;;; : to handle remote 'keyword-like' parameters and update the doc
;;; : strings accordingly.
;;; 2018.06.14 Dan
;;; : * Fixed a bug when there's an alternate variable char to match-
;;; : chunk-spec-p.
;;; 2019.01.30 Dan
;;; : * Fixed some copy and paste issues with warnings and removed
;;; : all the verify-current-meta-process checks.
;;; : * Use a separate list of testable chunk-specs instead of doing
;;; : a check on a testable flag.
;;; 2019.02.13 Dan
;;; : * Add a comment with an alternate test for slots-vector-match-
;;; : signature.
;;; 2019.03.06 Dan
;;; : * Adjust how act-r-chunk-slot-value-lists is used since its
;;; : first elements are slot structs.
;;; 2019.04.04 Dan
;;; : * Take advantage of slot-struct being returned by tests to
;;; : simplify some code.
;;; : * Instantiating a chunk-spec always calls replace-variables
;;; : on the value because it could be a list which wouldn't have
;;; : been flagged as a variable.
;;; : * Put slot names into a slot of the struct so for chunk-spec-
;;; : slots to use instead of recomputing.
;;; 2019.04.18 Dan
;;; : * Fix a bug with creating a chunk-spec where nil is used in a
;;; : slot name position.
;;; 2020.08.25 Dan
;;; : * Fixed a bug with chunk-spec-slots when it was given an id
;;; : instead of an actual chunk-spec.
;;; 2021.07.15 Dan
;;; : * Fixed a typo in a warning in verify-single-explicit-value.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; The structures are not for external use.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Find-matching-chunks automatically ignores request parameters now so they
;;; don't have to be stripped out first.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Create a component to provide a way to map a number (id) to a chunk-spec
;;; since the structure can't be passed out through the remote interface.
(defstruct chunk-spec-component (table (make-hash-table)) (number 0) (lock (bt:make-lock "chunk-spec-component")))
(defun clear-chunk-spec-table (cs-component)
(bt:with-lock-held ((chunk-spec-component-lock cs-component))
(clrhash (chunk-spec-component-table cs-component))))
(define-component :chunk-spec :version "3.0" :documentation "Maintains a table of chunk-specs for remote use"
:creation make-chunk-spec-component :clear-all clear-chunk-spec-table :after-reset clear-chunk-spec-table)
;;; Commands for working with the chunk-spec ids
(defun chunk-spec-to-id (chunk-spec)
(when (act-r-chunk-spec-p chunk-spec)
(let ((c (get-component :chunk-spec)))
(bt:with-lock-held ((chunk-spec-component-lock c))
(let ((n (incf (chunk-spec-component-number c))))
(setf (gethash n (chunk-spec-component-table c)) chunk-spec)
n)))))
(defun id-to-chunk-spec (chunk-spec-id)
(let ((c (get-component :chunk-spec)))
(bt:with-lock-held ((chunk-spec-component-lock c))
(gethash chunk-spec-id (chunk-spec-component-table c)))))
(defun release-chunk-spec-id (chunk-spec-id)
(let ((c (get-component :chunk-spec)))
(bt:with-lock-held ((chunk-spec-component-lock c))
(remhash chunk-spec-id (chunk-spec-component-table c)))))
(add-act-r-command "release-chunk-spec-id" 'release-chunk-spec-id "Release the chunk-spec associated with the provided id. Params: chunk-spec-id." nil)
;;; Internal accessors for the parts of a chunk-spec slot specification.
;;;
;;; Can't do this (defstruct (spec-slot (:type list)) op name value)
;;; safely in all Lisps. So just make them simple macros instead.
(defun spec-slot-op (spec) (first spec))
(defun set-spec-slot-op (spec value) (setf (first spec) value))
(defsetf spec-slot-op set-spec-slot-op)
(defun spec-slot-name (spec) (second spec))
(defun set-spec-slot-name (spec value) (setf (second spec) value))
(defsetf spec-slot-name set-spec-slot-name)
(defun spec-slot-value (spec) (third spec))
(defun set-spec-slot-value (spec value) (setf (third spec) value))
(defsetf spec-slot-value set-spec-slot-value)
;;; User level accessors.
(defun slot-spec-modifier (slot-spec-list)
(if (and (listp slot-spec-list) (= 3 (length slot-spec-list)))
(first slot-spec-list)
(print-warning "Invalid slot-spec list ~s passed to slot-spec-modifier." slot-spec-list)))
(defun slot-spec-slot (slot-spec-list)
(if (and (listp slot-spec-list) (= 3 (length slot-spec-list)))
(second slot-spec-list)
(print-warning "Invalid slot-spec list ~s passed to slot-spec-slot." slot-spec-list)))
(defun slot-spec-value (slot-spec-list)
(if (and (listp slot-spec-list) (= 3 (length slot-spec-list)))
(third slot-spec-list)
(print-warning "Invalid slot-spec list ~s passed to slot-spec-value." slot-spec-list)))
(add-act-r-command "slot-spec-modifier" 'slot-spec-modifier "Return the modifier from a slot-spec list (the first item). Params: slot-spec-list.")
(add-act-r-command "slot-spec-slot" 'slot-spec-slot "Return the slot name from a slot-spec list (the second item). Params: slot-spec-list.")
(add-act-r-command "slot-spec-value" 'slot-spec-value "Return the value from a slot-spec list (the third item). Params: slot-spec-list.")
;;; The rest of the real commands
(defmacro define-chunk-spec (&rest specifications)
`(define-chunk-spec-fct ',specifications))
(defun define-chunk-spec-fct (specifications-list &optional (extend t) (warn t))
(verify-current-model
"define-chunk-spec-fct called with no current model."
(cond ((= (length specifications-list) 1)
(if (get-chunk (car specifications-list))
(chunk-name-to-chunk-spec (car specifications-list))
(print-warning "define-chunk-spec's 1 parameter doesn't name a chunk: ~S" specifications-list)))
((eq (car specifications-list) 'isa)
(let ((chunk-type (get-chunk-type (second specifications-list))))
(if chunk-type
(process-slots-specs chunk-type (cddr specifications-list) extend warn)
(print-warning "Element after isa in define-chunk-spec isn't a chunk-type. ~S" specifications-list))))
(t
(process-slots-specs nil specifications-list extend warn)))))
(defun remote-define-chunk-spec (&rest spec)
(let ((cs (define-chunk-spec-fct (decode-string-names spec))))
(when cs
(chunk-spec-to-id cs))))
(defun remote-define-chunk-spec-fct (spec &optional (extend t) (warn t))
(let ((cs (define-chunk-spec-fct (decode-string-names spec) extend warn)))
(when cs
(chunk-spec-to-id cs))))
(add-act-r-command "define-chunk-spec" 'remote-define-chunk-spec "Create a chunk-spec and return its id. Params: '{{mod} slot value}'*." nil)
(add-act-r-command "define-chunk-spec-fct" 'remote-define-chunk-spec-fct "Create a chunk-spec and return its id. Params: '({{mod} slot value}*)' {extend {warn}}." nil)
(defmacro define-query-spec (&rest specifications)
`(define-query-spec-fct ',specifications))
(defun define-query-spec-fct (specifications-list)
(verify-current-model
"define-query-spec-fct called with no current model."
(process-query-specs specifications-list)))
(defun chunk-name-to-chunk-spec (chunk-name)
(let ((spec (make-act-r-chunk-spec))
(chunk (get-chunk chunk-name)))
(if chunk
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(let ((slot-vector (act-r-chunk-filled-slots chunk)))
(setf (act-r-chunk-spec-filled-slots spec) slot-vector)
(setf (act-r-chunk-spec-equal-slots spec) slot-vector)
(dolist (slot (act-r-chunk-slot-value-lists chunk) spec)
(let ((s (make-act-r-slot-spec :name (act-r-slot-name (car slot)) :value (cdr slot))))
(pushnew (act-r-slot-name (car slot)) (act-r-chunk-spec-slot-names spec))
(push s (act-r-chunk-spec-slots spec))
(push s (act-r-chunk-spec-testable-slots spec))))))
(print-warning "Chunk-name-to-chunk-spec called with a non-chunk ~s." chunk-name))))
(defun remote-chunk-name-to-chunk-spec (chunk-name)
(let ((cs (chunk-name-to-chunk-spec (string->name chunk-name))))
(when cs
(chunk-spec-to-id cs))))
(add-act-r-command "chunk-name-to-chunk-spec" 'remote-chunk-name-to-chunk-spec "Given the name of a chunk return a chunk-spec id of a chunk-spec that contains a specification of all the slots and values of that chunk. Params: chunk-name.")
(defun chunk-difference-to-chunk-spec (chunk-name1 chunk-name2)
(let ((spec (make-act-r-chunk-spec))
(chunk1 (get-chunk chunk-name1))
(chunk2 (get-chunk chunk-name2)))
(if (and chunk1 chunk2)
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk1))
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk2))
(let* ((slot-vector (act-r-chunk-filled-slots chunk1))
(slots-in-c2 (act-r-chunk-filled-slots chunk2))
(slots-to-remove-from-c2 (logandc2 slots-in-c2 slot-vector)))
(setf (act-r-chunk-spec-filled-slots spec) slot-vector)
(setf (act-r-chunk-spec-empty-slots spec) slots-to-remove-from-c2)
(setf (act-r-chunk-spec-equal-slots spec) (logior slot-vector slots-to-remove-from-c2))
(dolist (slot (act-r-chunk-slot-value-lists chunk1))
(let ((s (make-act-r-slot-spec :name (act-r-slot-name (car slot)) :value (cdr slot))))
(pushnew (act-r-slot-name (car slot)) (act-r-chunk-spec-slot-names spec))
(push s (act-r-chunk-spec-slots spec))
(push s (act-r-chunk-spec-testable-slots spec))))
(dolist (slot (slot-mask->names slots-to-remove-from-c2))
(let ((s (make-act-r-slot-spec :name slot :value nil)))
(pushnew slot (act-r-chunk-spec-slot-names spec))
(push s (act-r-chunk-spec-slots spec))
(push s (act-r-chunk-spec-testable-slots spec))))
spec)))
(print-warning "Chunk-difference-to-chunk-spec called with ~s and ~s which are not both chunks." chunk-name1 chunk-name2))))
(defun remote-chunk-difference-to-chunk-spec (c1 c2)
(aif (chunk-difference-to-chunk-spec (string->name c1) (string->name c2))
(chunk-spec-to-id it)))
(add-act-r-command "chunk-difference-to-chunk-spec" 'remote-chunk-difference-to-chunk-spec "Create a chunk-spec that could be used to modify chunk-2 to be identical to chunk-1. Params: chunk-1 chunk-2")
(defun chunk-spec-filled-slots (chunk-spec)
(if (act-r-chunk-spec-p chunk-spec)
(act-r-chunk-spec-filled-slots chunk-spec)
(print-warning "Chunk-spec-filled-slots called with a non-chunk-spec")))
(defun chunk-spec-empty-slots (chunk-spec)
(if (act-r-chunk-spec-p chunk-spec)
(act-r-chunk-spec-empty-slots chunk-spec)
(print-warning "Chunk-spec-empty-slots called with a non-chunk-spec")))
(defun chunk-spec-slots (chunk-spec)
(if (act-r-chunk-spec-p chunk-spec)
(act-r-chunk-spec-slot-names chunk-spec) ;(remove-duplicates (mapcar 'act-r-slot-spec-name (act-r-chunk-spec-slots chunk-spec)))
(aif (id-to-chunk-spec chunk-spec)
(act-r-chunk-spec-slot-names it) ;(remove-duplicates (mapcar 'act-r-slot-spec-name (act-r-chunk-spec-slots it)))
(print-warning "Chunk-spec-slots called with something other than a chunk-spec or chunk-spec-id"))))
(add-act-r-command "chunk-spec-slots" 'chunk-spec-slots "Return a list of slots and request-parameters that are found in the given chunk-spec. Params: chunk-spec.")
(defun chunk-spec-slot-spec (chunk-spec &optional slot)
(if (act-r-chunk-spec-p chunk-spec)
(let ((result nil))
(dolist (x (act-r-chunk-spec-slots chunk-spec) result)
(when (or (null slot) (eq slot (act-r-slot-spec-name x)))
(push-last (slot-spec-to-list x) result))))
(aif (id-to-chunk-spec chunk-spec)
(chunk-spec-slot-spec it slot)
(print-warning "Chunk-spec-slot-spec was not passed a valid chunk-spec or chunk-spec id"))))
(defun remote-chunk-spec-slot-spec (chunk-spec &optional slot)
(encode-string-names (chunk-spec-slot-spec chunk-spec (string->name slot))))
(add-act-r-command "chunk-spec-slot-spec" 'remote-chunk-spec-slot-spec "Return a list of the slot spec lists from a chunk-spec for the indicated slot or all slots if none provided. Params: chunk-spec {slot}.")
(defun slot-in-chunk-spec-p (chunk-spec slot)
(if (act-r-chunk-spec-p chunk-spec)
(aif (valid-slot-name slot)
(let ((index (act-r-slot-index it)))
(and (or (logbitp index (act-r-chunk-spec-filled-slots chunk-spec))
(logbitp index (act-r-chunk-spec-empty-slots chunk-spec)))
t))
(when (find slot (act-r-chunk-spec-slots chunk-spec) :key 'act-r-slot-spec-name)
t))
(aif (id-to-chunk-spec chunk-spec)
(slot-in-chunk-spec-p it slot)
(print-warning "Slot-in-chunk-spec-p called with something other than a chunk-spec or chunk-spec-id"))))
(defun external-slot-in-chunk-spec-p (chunk-spec slot)
(slot-in-chunk-spec-p chunk-spec (string->name slot)))
(add-act-r-command "slot-in-chunk-spec-p" 'external-slot-in-chunk-spec-p "Test whether a given slot is used in the indicated chunk-spec. Params: chunk-spec slot.")
(defun slot-spec-to-list (slot-spec)
(list (act-r-slot-spec-modifier slot-spec)
(act-r-slot-spec-name slot-spec)
(act-r-slot-spec-value slot-spec)))
(defun process-slots-specs (chunk-type specs extend warn)
(let ((spec (make-act-r-chunk-spec))
(defaults nil)
(extended? nil))
(when chunk-type
(let ((default-spec (act-r-chunk-type-initial-spec chunk-type)))
(setf defaults (act-r-chunk-spec-slots default-spec))))
(loop
(when (null specs)
(dolist (x defaults)
(let ((index (slot-name->index (act-r-slot-spec-name x))))
;; If the default slot is already tested for full or empty
;; skip the default value
(unless (or (logbitp index (act-r-chunk-spec-filled-slots spec))
(logbitp index (act-r-chunk-spec-empty-slots spec)))
(add-slot-spec-to-chunk-spec x spec))))
(return (values spec extended?)))
(let ((slot-spec (make-act-r-slot-spec))
(slot-struct nil))
(when (find (car specs) '(= - > < >= <=))
(setf (act-r-slot-spec-modifier slot-spec) (pop specs)))
(when (null specs)
(print-warning "Invalid specs in call to define-chunk-spec - not enough arguments")
(return nil))
(let ((slot? (car specs)))
(when (null slot?)
(print-warning "Cannot use nil as a slot name.")
(return nil))
(when (and (keywordp slot?) (not (eq (act-r-slot-spec-modifier slot-spec) '=)))
(print-warning "Request parameters may not use a modifier other than =.")
(return nil))
(setf slot-struct (if chunk-type (valid-ct-slot chunk-type slot?) (valid-slot-name slot?)))
(unless (or slot-struct (chunk-spec-variable-p slot?))
(if (and extend (not (keywordp slot?)) ;; unnecessary since the alphanumericp catches this too (not (chunk-spec-variable-p slot?))
(symbolp slot?) (alphanumericp (char (symbol-name slot?) 0)))
(let ((extended (extend-possible-slots slot? nil)))
(if extended
(progn
(push extended extended?)
(setf slot-struct (valid-slot-name slot?))
(when warn
(model-warning "Chunks extended with slot ~s during a chunk-spec definition." slot?)))
(if chunk-type
(progn
(print-warning "Slot ~s invalid for type ~s but chunk-spec definition still created." slot? (act-r-chunk-type-name chunk-type))
(push (list :mismatch (act-r-chunk-type-name chunk-type) slot?) extended?))
(progn
(print-warning "Invalid slot-name ~s in call to define-chunk-spec." slot?)
(return nil)))))
(progn
(print-warning "Invalid slot-name ~S in call to define-chunk-spec." slot?)
(return nil)))))
(let ((slot (pop specs)))
(setf (act-r-slot-spec-name slot-spec) slot)
(when (chunk-spec-variable-p slot)
(setf (act-r-slot-spec-variable slot-spec) :slot)))
(when (null specs)
(print-warning "Invalid specs in call to define-chunk-spec - not enough arguments")
(return nil))
(let ((value (pop specs)))
(setf (act-r-slot-spec-value slot-spec) value)
(when (chunk-spec-variable-p value)
(if (act-r-slot-spec-variable slot-spec)
(setf (act-r-slot-spec-variable slot-spec) :both)
(setf (act-r-slot-spec-variable slot-spec) :value))))
(unless (add-slot-spec-to-chunk-spec slot-spec spec slot-struct)
(return nil))))))
(defun process-query-specs (specs)
(let ((spec (make-act-r-chunk-spec)))
(loop
(when (null specs)
(return (values spec nil)))
(let ((slot-spec (make-act-r-slot-spec)))
(if (find (car specs) '(= -))
(setf (act-r-slot-spec-modifier slot-spec) (pop specs))
(if (find (car specs) '(> < >= <=))
(progn
(print-warning "Query specs only allow = or - modifiers.")
(return nil))))
(when (null specs)
(print-warning "Invalid specs in call to define-query-spec - not enough arguments")
(return nil))
(unless (valid-query-name (car specs))
(print-warning "Invalid query name ~S in call to define-query-spec." (car specs))
(return nil))
(setf (act-r-slot-spec-name slot-spec) (pop specs))
(pushnew (act-r-slot-spec-name slot-spec) (act-r-chunk-spec-slot-names spec))
(when (null specs)
(print-warning "Invalid specs in call to define-query-spec - not enough arguments")
(return nil))
(setf (act-r-slot-spec-value slot-spec) (pop specs))
(when (chunk-spec-variable-p (act-r-slot-spec-value slot-spec))
(setf (act-r-slot-spec-variable slot-spec) :value)
(pushnew (act-r-slot-spec-value slot-spec) (act-r-chunk-spec-variables spec)))
(push-last slot-spec (act-r-chunk-spec-slots spec))))))
(defun add-slot-spec-to-chunk-spec (slot-spec spec &optional slot-struct)
(push-last slot-spec (act-r-chunk-spec-slots spec))
(pushnew (act-r-slot-spec-name slot-spec) (act-r-chunk-spec-slot-names spec))
(case (act-r-slot-spec-variable slot-spec)
(:slot
(pushnew (act-r-slot-spec-name slot-spec) (act-r-chunk-spec-variables spec))
(pushnew (act-r-slot-spec-name slot-spec) (act-r-chunk-spec-slot-vars spec))
(push slot-spec (act-r-chunk-spec-testable-slots spec))
(return-from add-slot-spec-to-chunk-spec t))
(:both
(pushnew (act-r-slot-spec-value slot-spec) (act-r-chunk-spec-variables spec))
(pushnew (act-r-slot-spec-name slot-spec) (act-r-chunk-spec-variables spec))
(pushnew (act-r-slot-spec-name slot-spec) (act-r-chunk-spec-slot-vars spec))
(push slot-spec (act-r-chunk-spec-testable-slots spec))
(aif (assoc (act-r-slot-spec-value slot-spec) (act-r-chunk-spec-dependencies spec))
(pushnew (act-r-slot-spec-name slot-spec) (cdr it))
(push (list (act-r-slot-spec-value slot-spec) (act-r-slot-spec-name slot-spec)) (act-r-chunk-spec-dependencies spec)))
(return-from add-slot-spec-to-chunk-spec t))
(:value
(pushnew (act-r-slot-spec-value slot-spec) (act-r-chunk-spec-variables spec))))
(let* ((mod (act-r-slot-spec-modifier slot-spec))
(slot-name (act-r-slot-spec-name slot-spec))
(val (act-r-slot-spec-value slot-spec))
(struct (aif slot-struct it (valid-slot-name slot-name)))
(mask (act-r-slot-mask struct))
(index (act-r-slot-index struct)))
(when (keywordp slot-name)
(setf (act-r-chunk-spec-request-param-slots spec) (logior mask (act-r-chunk-spec-request-param-slots spec))))
(when (or (logbitp index (act-r-chunk-spec-filled-slots spec))
(logbitp index (act-r-chunk-spec-empty-slots spec)))
(setf (act-r-chunk-spec-duplicate-slots spec) (logior mask (act-r-chunk-spec-duplicate-slots spec))))
(case mod
(= (setf (act-r-chunk-spec-equal-slots spec) (logior mask (act-r-chunk-spec-equal-slots spec))))
(- (setf (act-r-chunk-spec-negated-slots spec) (logior mask (act-r-chunk-spec-negated-slots spec))))
(t (setf (act-r-chunk-spec-relative-slots spec) (logior mask (act-r-chunk-spec-relative-slots spec)))))
(unless (keywordp slot-name)
(if val
;; anything that's not nil means the slot filled bit gets set
;; and we need the test
(progn
(push slot-spec (act-r-chunk-spec-testable-slots spec))
(unless (eq mod '-)
(setf (act-r-chunk-spec-filled-slots spec) (logior mask (act-r-chunk-spec-filled-slots spec)))))
;; for nil things are a little more interesting and we don't need the tests
(cond ((eq mod '=)
(setf (act-r-chunk-spec-empty-slots spec) (logior mask (act-r-chunk-spec-empty-slots spec))))
((eq mod '-)
(setf (act-r-chunk-spec-filled-slots spec) (logior mask (act-r-chunk-spec-filled-slots spec))))
(t
(return-from add-slot-spec-to-chunk-spec
(print-warning "A ~s test for slot ~s with a value of nil not allowed in chunk-spec." mod slot-name))))))
t))
(defun instantiate-chunk-spec (chunk-spec bindings &optional (extend t))
(let ((extended-slots nil))
(cond ((not (act-r-chunk-spec-p chunk-spec))
(print-warning "instantiate-chunk-spec called with something other than a chunk-spec: ~s" chunk-spec))
((not (and (listp bindings) (every (lambda (x)
(and (consp x) (chunk-spec-variable-p (car x)) (cdr x)))
bindings)))
(print-warning "Instantiate-chunk-spec called with an invalid bindings alist: ~s" bindings))
(t
(let ((new-spec (make-act-r-chunk-spec)))
(dolist (x (act-r-chunk-spec-slots chunk-spec))
(let ((it (act-r-slot-spec-variable x)))
(let* ((slot (if (eq it :value)
(act-r-slot-spec-name x)
(aif (assoc (act-r-slot-spec-name x) bindings)
(cdr it)
(act-r-slot-spec-name x))))
(value (replace-variables (act-r-slot-spec-value x) bindings)))
(unless (or (chunk-spec-variable-p slot)
(valid-slot-name slot))
(if extend
(let ((extended (if (keywordp slot) nil (extend-possible-slots slot))))
(if extended
(push slot extended-slots)
(progn
(print-warning "Invalid slot-name ~s in instantiation of chunk spec for variable ~s" slot (act-r-slot-spec-name x))
(return-from instantiate-chunk-spec nil))))
(progn
(print-warning "Invalid slot-name ~s in instantiation of chunk spec for variable ~s" slot (act-r-slot-spec-name x))
(return-from instantiate-chunk-spec nil))))
(add-slot-spec-to-chunk-spec (make-act-r-slot-spec :modifier (act-r-slot-spec-modifier x)
:name slot
:value value
:variable (cond ((and (chunk-spec-variable-p slot)
(chunk-spec-variable-p value))
:both)
((chunk-spec-variable-p slot)
:slot)
((chunk-spec-variable-p value)
:value)
(t nil)))
new-spec))))
(values new-spec extended-slots))))))
(defun instantiate-query-spec (chunk-spec bindings)
(cond ((not (act-r-chunk-spec-p chunk-spec))
(print-warning "instantiate-query-spec called with something other than a chunk-spec: ~s" chunk-spec))
((not (and (listp bindings) (every (lambda (x)
(and (consp x) (chunk-spec-variable-p (car x)) (cdr x)))
bindings)))
(print-warning "Instantiate-query-spec called with an invalid bindings alist: ~s" bindings))
(t
(let ((new-spec (make-act-r-chunk-spec)))
(dolist (x (act-r-chunk-spec-slots chunk-spec))
(let ((value (replace-variables (act-r-slot-spec-value x) bindings)))
(pushnew (act-r-slot-spec-name x) (act-r-chunk-spec-slot-names new-spec))
(push-last (make-act-r-slot-spec :modifier (act-r-slot-spec-modifier x)
:name (act-r-slot-spec-name x)
:value value
:variable (if (chunk-spec-variable-p value) :value nil))
(act-r-chunk-spec-slots new-spec))))
(values new-spec nil)))))
;;; A specific value of nil may be important to some things, so that's why it
;;; returns a second value of t on success.
(defun verify-single-explicit-value (chunk-spec slot module cmd &optional (var-char #\=))
(if (act-r-chunk-spec-p chunk-spec)
(let ((index (slot-name->index slot)))
(cond ((null index)
(values nil nil))
((not (or (logbitp index (act-r-chunk-spec-filled-slots chunk-spec))
(logbitp index (act-r-chunk-spec-empty-slots chunk-spec))
(logbitp index (act-r-chunk-spec-request-param-slots chunk-spec))))
(print-warning "~a command to ~s module requires a value for the ~a slot." cmd module slot)
(values nil nil))
((logbitp index (act-r-chunk-spec-duplicate-slots chunk-spec))
(print-warning "~a slot may only be specified once in a ~a command to the ~s module." slot cmd module)
(values nil nil))
((not (logbitp index (act-r-chunk-spec-equal-slots chunk-spec)))
(print-warning "~a slot may only have the = modifier in a ~a command to the ~s module." slot cmd module)
(values nil nil))
(t
(let* ((slot-spec (find slot (act-r-chunk-spec-slots chunk-spec) :key 'act-r-slot-spec-name))
(value (when slot-spec
(act-r-slot-spec-value slot-spec)))
(var (if (and (stringp var-char) (> (length var-char) 0)) (char var-char 0) var-char)))
(if (and value (characterp var) (symbolp value) (char-equal var (char (symbol-name value) 0)))
(values nil (print-warning "~a slot must be explicit - not a variable in a ~a command to the ~s module." slot cmd module))
(values value t))))))
(aif (id-to-chunk-spec chunk-spec)
(verify-single-explicit-value it slot module cmd var-char)
(values nil (print-warning "~a is not a chunk-spec in ~a command to the ~s module." chunk-spec cmd module)))))
(defun remote-verify-single-explicit-value (chunk-spec slot module cmd &optional (var-char #\=))
(multiple-value-bind (val exist)
(verify-single-explicit-value chunk-spec (string->name slot) module cmd var-char)
(values (encode-string-names val) exist)))
(add-act-r-command "verify-single-explicit-value" 'remote-verify-single-explicit-value "Determine if a slot in a chunk-spec has exactly one value specified and if so return it. Params: chunk-spec slot module-name command-name {variable-indicator}.")
(defun chunk-match-signature (chunk-name filled &optional empty)
(let ((chunk (get-chunk chunk-name)))
(cond ((not chunk)
(print-warning "~s does not name a chunk in call to chunk-match-signature." chunk-name))
((not (integerp filled))
(print-warning "~s is not an appropriate filled signature in call to chunk-match-signature." filled))
((not (or (null empty) (integerp empty)))
(print-warning "~s is not an appropriate empty signature in call to chunk-match-signature." empty))
(t
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(slots-vector-match-signature (act-r-chunk-filled-slots chunk) filled empty))))))
(defun slots-vector-match-signature (slots-vector filled &optional empty)
;; if empty defaults to 0 could do this instead but doesn't seem to matter time wise
;; (zerop (logior (logandc1 slots-vector filled) (logand slots-vector empty)))
(and (= filled (logand filled slots-vector))
(or (null empty)
(= empty (logandc2 empty slots-vector)))))
(defun compare-chunk-to-signature (chunk-name filled &optional empty)
(let ((chunk (get-chunk chunk-name)))
(cond ((not chunk)
(print-warning "~s does not name a chunk in call to compare-chunk-to-signature." chunk-name))
((not (integerp filled))
(print-warning "~s is not an appropriate filled signature in call to compare-chunk-to-signature." filled))
((not (or (null empty) (integerp empty)))
(print-warning "~s is not an appropriate empty signature in call to compare-chunk-to-signature." empty))
(t
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(compare-slots-vector-to-signature (act-r-chunk-filled-slots chunk) filled empty))))))
(defun compare-slots-vector-to-signature (slots-vector filled &optional empty)
"Returns match, extra slots with values, slots which were missing values, and slots which shouldn't have had values"
(let ((filled? (= filled (logand filled slots-vector)))
(empty? (or (null empty)
(= empty (logandc2 empty slots-vector)))))
(values (and filled? empty?)
(slot-mask->names (logandc2 slots-vector filled))
(slot-mask->names (logandc1 slots-vector filled))
(and empty (slot-mask->names (logand slots-vector empty))))))
(defun reprocess-chunk-spec (spec var-char)
(let ((new-spec (make-act-r-chunk-spec)))
(dolist (x (act-r-chunk-spec-slots spec))
(let ((slot-spec (copy-act-r-slot-spec x)))
(setf (act-r-slot-spec-variable slot-spec)
(cond ((and (chunk-spec-variable-p (act-r-slot-spec-name slot-spec) var-char)
(chunk-spec-variable-p (act-r-slot-spec-value slot-spec) var-char))
:both)
((chunk-spec-variable-p (act-r-slot-spec-name slot-spec) var-char)
:slot)
((chunk-spec-variable-p (act-r-slot-spec-value slot-spec) var-char)
:value)
(t nil)))
(add-slot-spec-to-chunk-spec slot-spec new-spec)))
new-spec))
(defun match-chunk-spec-p (chunk-name chunk-spec
&key (=test 'chunk-slot-equal)
(-test 'chunk-slot-not-equal)
(>test 'safe>) (>=test 'safe>=)
(<test 'safe<) (<=test 'safe<=)
(variable-char #\=))
(verify-current-model
"Match-chunk-spec-p called with no current model."
(let ((chunk (get-chunk chunk-name)))
(cond ((null chunk)
(print-warning "~s does not name a chunk in call to match-chunk-spec-p." chunk-name))
(t
(let ((s (cond ((act-r-chunk-spec-p chunk-spec) chunk-spec)
((numberp chunk-spec) (id-to-chunk-spec chunk-spec))
(t nil))))
(if (null s)
(print-warning "~s is not a valid chunk-spec or chunk-spec id in call to match-chunk-spec-p." chunk-spec)
(let ((var (cond ((characterp variable-char) variable-char)
((and (stringp variable-char) (= (length variable-char) 1)) (char variable-char 0))
(t nil))))
(if (null var)
(print-warning "~s is not a valid variable character in call to match-chunk-spec-p." variable-char)
(progn
;; check the variable character and reprocess the spec
;; if it's not = since that may mean different slotnames are "real"
(unless (char-equal var #\=)
(setf s (reprocess-chunk-spec s var)))
(bt:with-recursive-lock-held ((act-r-chunk-lock chunk))
(cond
;; if the filled slots are filled and the empty slots aren't then test further
((slots-vector-match-signature (act-r-chunk-filled-slots chunk)
(act-r-chunk-spec-filled-slots s)
(act-r-chunk-spec-empty-slots s))
(handler-case (test-chunk-slots (act-r-chunk-slot-value-lists chunk)
s =test -test >test >=test <test <=test)
(error (condition)
(print-warning "Error ~S encountered in matching chunk ~s." condition chunk-name))))
(t
nil)))))))))))))
(defun remote-match-chunk-spec-p (chunk spec &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'remote-match-chunk-spec-p '(:=test :-test :<test :>test :<=test :>=test :variable-char))
(when valid
(apply 'match-chunk-spec-p (string->name chunk) spec ol))))
(add-act-r-command "match-chunk-spec-p" 'remote-match-chunk-spec-p "Test whether a chunk matches the pattern in a chunk-spec. Params: chunk-name chunk-spec {< =test, -test, <test, <=test, >test, >=test, variable-char >}.")
(defun chunk-slot-not-equal (arg1 arg2)
(not (chunk-slot-equal arg1 arg2)))
(defun test-chunk-slots (slots spec =test -test >test >=test <test <=test)
(let ((bindings nil)
(get-bindings nil)
(others nil))
(flet ((test-slot (modifier chunks-slot-value spec-value)
(dispatch-apply (case modifier
(= =test)
(- -test)
(> >test)
(>= >=test)
(< <test)
(<= <=test))
chunks-slot-value spec-value))
(chunks-slot-value (slot)
(cdr (assoc slot slots :key 'act-r-slot-name))))
;; First pass to get all the constant bindings and test the constants
(dolist (x (act-r-chunk-spec-testable-slots spec))
(let ((value (act-r-slot-spec-value x))
(modifier (act-r-slot-spec-modifier x))
(slot (act-r-slot-spec-name x))
(variable (act-r-slot-spec-variable x)))
(cond (;; it's a constant test
(null variable)
(unless (test-slot modifier (chunks-slot-value slot) value)
(return-from test-chunk-slots nil)))
(;; variables in constant slots
(eq (act-r-slot-spec-variable x) :value)
(cond (;; it has been bound and can be tested
(assoc value bindings)
(unless (test-slot modifier (chunks-slot-value slot) (cdr (assoc value bindings)))
(return-from test-chunk-slots nil)))
(;; it's an equal test so create the binding
(eq modifier '=)
(push (cons value (chunks-slot-value slot)) bindings))
(;; some other test required so save it
t
(push x others))))
(;; other potential bindings save for pass 2
(and (eq modifier '=)
(eq variable :both))
(push x get-bindings))
(t ;; everything else goes at the end
(push x others)))))
;; Second pass if all variables bound then check things
;; that needed the bindings.
(when get-bindings
;; just do this in repeated loops instead of trying to sort
;; things up front
(do ((conds get-bindings)
(changed t))
((or (null conds) (null changed))
(unless (null conds)
(return-from test-chunk-slots nil)))
(setf changed nil)
(dolist (x conds)
(let ((value (act-r-slot-spec-value x))
(slot (act-r-slot-spec-name x)))
(cond (;; slot name not bound so skip it
(null (assoc slot bindings)))
(;; value variable is bound already
;; so just test it
(assoc value bindings)
(unless (test-slot '= (chunks-slot-value (cdr (assoc slot bindings))) (cdr (assoc value bindings)))
(return-from test-chunk-slots nil))
(setf conds (remove x conds))
(setf changed t))
(;; variable not bound yet so create binding if slot actually exists
;; and remove this from the set
t
(let ((slot-value (chunks-slot-value (cdr (assoc slot bindings)))))
(unless slot-value
(return-from test-chunk-slots nil))
(push (cons value slot-value) bindings)
(setf conds (remove x conds))
(setf changed t))))))))
;; third pass - test all the others since bindings done
(dolist (x others t)
(let ((value (act-r-slot-spec-value x))
(modifier (act-r-slot-spec-modifier x))
(slot (act-r-slot-spec-name x))
(variable (act-r-slot-spec-variable x)))
(case variable
(:value
(unless (test-slot modifier (chunks-slot-value slot) (cdr (assoc value bindings)))
(return-from test-chunk-slots nil)))
(:slot
(unless (test-slot modifier (chunks-slot-value (cdr (assoc slot bindings))) value)
(return-from test-chunk-slots nil)))
(:both
(unless (test-slot modifier (chunks-slot-value (cdr (assoc slot bindings))) (cdr (assoc value bindings)))
(return-from test-chunk-slots nil)))
(t
(unless (test-slot modifier (chunks-slot-value slot) value)
(return-from test-chunk-slots nil)))))))))
(defun find-matching-chunks (chunk-spec
&key
(chunks :all) (=test 'chunk-slot-equal)
(-test 'chunk-slot-not-equal)
(>test 'safe>) (>=test 'safe>=)
(<test 'safe<) (<=test 'safe<=)
(variable-char #\=))
(verify-current-model
"Find-matching-chunks called with no current model."
(let ((found nil)
(model (current-model-struct))
(s (cond ((act-r-chunk-spec-p chunk-spec) chunk-spec)
((numberp chunk-spec) (id-to-chunk-spec chunk-spec))
(t nil))))
(if (null s)
(print-warning "~s is not a valid chunk-spec or chunk-spec id in call to find-matching-chunks." chunk-spec)
(let ((var (cond ((characterp variable-char) variable-char)
((and (stringp variable-char) (= (length variable-char) 1)) (char variable-char 0))
(t nil))))
(if (null var)
(print-warning "~s is not a valid variable character in call to find-matching-chunks." variable-char)
(cond ((eq :all chunks)
(dolist (name (bt:with-recursive-lock-held ((act-r-model-chunk-lock model)) (hash-table-keys (act-r-model-chunks-table model))) found)
(when (match-chunk-spec-p name s
:=test =test :-test -test
:>test >test :>=test >=test
:<test <test :<=test <=test
:variable-char var)
(push name found))))
((listp chunks)
(dolist (name chunks found)
(when (match-chunk-spec-p name s
:=test =test :-test -test
:>test >test :>=test >=test
:<test <test :<=test <=test
:variable-char var)
(push name found))))
(t (print-warning "~S is not a valid value for the :chunks keyword parameter to find-matching-chunks." chunks)))))))))
(defun remote-find-matching-chunks (chunk-spec &optional (chunks "all" chunksp) params)
(if (null chunksp)
(find-matching-chunks chunk-spec)
(multiple-value-bind (valid params)
(process-options-list params 'find-matching-chunks '(:=test :-test :<test :>test :<=test :>=test :variable-char))
(when valid
(if (and (stringp chunks) (string-equal chunks "all"))
(apply 'find-matching-chunks chunk-spec params)
(if (listp chunks)
(apply 'find-matching-chunks chunk-spec :chunks (string->name-recursive chunks) params)
(print-warning "Chunks parameter to find-matching-chunks must be a list of chunk names, but given ~s" chunks)))))))
(add-act-r-command "find-matching-chunks" 'remote-find-matching-chunks "Return all chunks which match the pattern in a chunk-spec. Params: chunk-spec {list-of-chunks {< =test, -test, <test, <=test, >test, >=test, variable-char >}}.")
(defun pprint-chunk-spec (chunk-spec)
"Print a chunk specification in a 'production like' way to command output"
(verify-current-model
"Pprint-chunk-spec called with no current model."
(let ((spec (if (act-r-chunk-spec-p chunk-spec) chunk-spec (id-to-chunk-spec chunk-spec))))
(when spec
(dolist (slot (act-r-chunk-spec-slots spec))
(if (eql '= (act-r-slot-spec-modifier slot))
(command-output " ~s ~s" (act-r-slot-spec-name slot) (act-r-slot-spec-value slot))
(command-output " ~2a ~s ~s" (act-r-slot-spec-modifier slot) (act-r-slot-spec-name slot) (act-r-slot-spec-value slot))))))))
(add-act-r-command "pprint-chunk-spec" 'pprint-chunk-spec "Print a chunk-spec representation to the command trace. Params: chunk-spec.")
(defun printed-chunk-spec (chunk-spec &optional (flat nil))
"Return a string with the print of a chunk specification in a 'production like' way"
(verify-current-model
"Printed-chunk-spec called with no current model."
(if (act-r-chunk-spec-p chunk-spec)
(let ((s (make-string-output-stream)))
(dolist (slot (act-r-chunk-spec-slots chunk-spec))
(if (eql '= (act-r-slot-spec-modifier slot))
(if flat
(format s " ~s ~s" (act-r-slot-spec-name slot) (act-r-slot-spec-value slot))
(format s " ~s ~s~%" (act-r-slot-spec-name slot) (act-r-slot-spec-value slot)))
(if flat
(format s " ~a ~s ~s" (act-r-slot-spec-modifier slot) (act-r-slot-spec-name slot) (act-r-slot-spec-value slot))
(format s " ~2a ~s ~s~%" (act-r-slot-spec-modifier slot) (act-r-slot-spec-name slot) (act-r-slot-spec-value slot)))))
(if flat
(string-left-trim '(#\space) (get-output-stream-string s))
(get-output-stream-string s)))
(awhen (id-to-chunk-spec chunk-spec)
(printed-chunk-spec it flat)))))
(add-act-r-command "printed-chunk-spec" 'printed-chunk-spec "Return a string with the representation of a chunk-spec. Params: chunk-spec {flat}.")
(defun slot-specs-to-chunk-spec-list (slot-specs)
(apply 'append slot-specs))
(defun slot-specs-to-chunk-spec (slot-specs)
(define-chunk-spec-fct (slot-specs-to-chunk-spec-list slot-specs)))
(defun chunk-spec-to-chunk-def (chunk-spec)
"Convert a chunk-spec to a chunk definition list ignoring request parameters"
(if (act-r-chunk-spec-p chunk-spec)
(let ((requests (lognot (act-r-chunk-spec-request-param-slots chunk-spec)))) ;; don't consider request parameters
(cond ((act-r-chunk-spec-slot-vars chunk-spec)
(print-warning "Chunk-spec has variablized slots in a call to chunk-spec-to-chunk-def."))
((act-r-chunk-spec-variables chunk-spec)
(print-warning "Chunk-spec has variables in the values in a call to chunk-spec-to-chunk-def."))
((not (zerop (logand requests (act-r-chunk-spec-duplicate-slots chunk-spec))))
(print-warning "Chunk-spec may only specify a slot once in a call to chunk-spec-to-chunk-def."))
((or (not (zerop (logand requests (act-r-chunk-spec-negated-slots chunk-spec))))
(not (zerop (logand requests (act-r-chunk-spec-relative-slots chunk-spec)))))
(print-warning "Chunk-spec may only use the = modifier in a call to chunk-spec-to-chunk-def."))
(t
(aif (mapcan (lambda (x)
(unless (keywordp (act-r-slot-spec-name x))
(list (act-r-slot-spec-name x) (act-r-slot-spec-value x))))
(act-r-chunk-spec-slots chunk-spec))
it
(list 'isa 'chunk)))))
(aif (id-to-chunk-spec chunk-spec)
(chunk-spec-to-chunk-def it)
(print-warning "Chunk-spec-to-chunk-def called with something other than a chunk-spec."))))
(defun remote-chunk-spec-to-chunk-def (chunk-spec-id)
(let ((cs (id-to-chunk-spec chunk-spec-id)))
(when cs
(encode-string-names (chunk-spec-to-chunk-def cs)))))
(add-act-r-command "chunk-spec-to-chunk-def" 'remote-chunk-spec-to-chunk-def "Convert a chunk-spec id to a list of slot value pairs. Params: chunk-spec." nil)
(defun merge-chunk-specs (spec1 spec2)
(if (and (act-r-chunk-spec-p spec1) (act-r-chunk-spec-p spec2))
(let ((new-spec (make-act-r-chunk-spec)))
(dolist (slot (act-r-chunk-spec-slots spec1))
(add-slot-spec-to-chunk-spec slot new-spec))
(dolist (slot (act-r-chunk-spec-slots spec2))
(add-slot-spec-to-chunk-spec slot new-spec))
new-spec)
(print-warning "merge-chunk-specs requires two valid chunk-specs")))
(defun remote-chunk-spec-variable-p (chunk-spec-slot-value &optional (char "="))
(chunk-spec-variable-p (string->name chunk-spec-slot-value) (when (stringp char) (char char 0))))
(add-act-r-command "chunk-spec-variable-p" 'remote-chunk-spec-variable-p "Test a value to determine if it would be considered a variable in a chunk-spec. Params: value {var-character}.")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 67,383 | Common Lisp | .lisp | 1,102 | 50.77314 | 250 | 0.57782 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | fc91159485538f97ea1fe99d3b8d59cd89df75a8e1fb22a83c26ca95988de801 | 14,312 | [
-1
] |
14,313 | version-string.lisp | asmaloney_ACT-R/framework/version-string.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2007 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : version-string.lisp
;;; Version : 2.0
;;;
;;; Description : Sets a global variable with the current version of the ACT-R
;;; : sources so that this is all I need to touch to update that.
;;;
;;; Bugs :
;;;
;;; To do : * When the repository number isn't set (it's not a released
;;; : version) it could try to get the version info from subversion
;;; : since that's probably how one got an unreleased version. In
;;; : ACL that'd look more or less like this:
;;; :
;;; : CG-USER(194): (when (null *actr-repository-number*)
;;; : (let ((result (ignore-errors (run-shell-command "svnversion" :wait nil :output :stream :directory (translate-logical-pathname "ACT-R:")))))
;;; : (when result
;;; : (read-line result))))
;;; : "1924:1946M"
;;; :
;;; : Would need to be Lisp specific (like run-environment) and
;;; : require the appropriate Lisp modules. When to do that
;;; : is a potential issue because it may cause a terminal window
;;; : to open which could be confusing/annoying to some.
;;;
;;; ----- History -----
;;; 2007.01.15 Dan
;;; : * Initial creation.
;;; 2014.07.17 Dan
;;; : * Split it into a major and minor version now. Report the
;;; : major version with the "ACT-R ..." part of mp-print-versions
;;; : and the minor version as the Framework number.
;;; 2015.07.29 Dan
;;; : * The version strings are now going to be combined to create
;;; : the "version" of the software instead of being separate
;;; : and the ".0" is dropped from the major version info.
;;; : When I build a release it will now append the repository #
;;; : as an additional .# on the end and add the date in place of
;;; : the <internal> tag which will be after the number e.g. if
;;; : I were to build it today it would be .0.1842-<07/29/2015>
;;; : instead of ".0-<internal>".
;;; 2015.08.03 Dan
;;; : * Actually separate out all the pieces of the version string
;;; : and then combine them to set *actr-version-string*.
;;; 2016.03.03 Dan [2.0]
;;; : * Don't consider 7 as the major version number but the architecture
;;; : and move the repository number into the angle brackets.
;;; : * Push features for the architecture, architecture.major, and
;;; : architecture.major.minor (if it exists) onto *features*.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Just sets a string which will be used as the framework version number.
;;;
;;; Will not be indicating changes to version numbers in the history section
;;; when they are made - only changes to the code and how the version numbers
;;; are constructed will be noted.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defvar *actr-architecture-version* "7")
(defvar *actr-major-version-string* "27")
(defvar *actr-minor-version-string* "7")
(defvar *actr-repository-number* "3260")
(defvar *actr-release-tag* "2022-07-19")
(defvar *actr-version-string* (format nil "~a.~a~@[.~a~]-<~@[~a:~]~a>"
*actr-architecture-version*
*actr-major-version-string*
*actr-minor-version-string*
*actr-repository-number*
*actr-release-tag*))
(pushnew (read-from-string (format nil ":act-r-~a" *actr-architecture-version*)) *features*)
(pushnew (read-from-string (format nil ":act-r-~a.~a" *actr-architecture-version* *actr-major-version-string*)) *features*)
(when *actr-minor-version-string*
(pushnew (read-from-string (format nil ":act-r-~a.~a.~a" *actr-architecture-version* *actr-major-version-string* *actr-minor-version-string*)) *features*))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 5,734 | Common Lisp | .lisp | 107 | 50.794393 | 177 | 0.563801 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 7beaf80f11d45661ace31ce2cb8960a042b73175ab563e115c6daa2a78171cc2 | 14,313 | [
-1
] |
14,314 | naming-module.lisp | asmaloney_ACT-R/framework/naming-module.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : naming-module.lisp
;;; Version : 3.0
;;;
;;; Description : Module that supports model-specific and "safe" gentemping for
;;; name creation.
;;;
;;; Bugs :
;;;
;;; To do : Documentation.
;;;
;;; ----- History -----
;;;
;;; 2004.09.17 Dan
;;; : Creation
;;; 2005.02.22 Dan
;;; : * Changed reset-naming-module to work around an issue in
;;; : Lispworks 4.4.
;;; : * Fixed a bug in new-name-fct - it wasn't catching the
;;; : existing symbol info correctly.
;;; : * Updated the version number.
;;; 2006.01.17 Dan
;;; : * Updated the version to 1.0 since there haven't been any
;;; : problems it's time to drop the "a".
;;; 2006.08.10 Dan
;;; : * Modified new-symbol so that it only returns one value
;;; : instead of two from intern.
;;; 2006.10.10 Dan
;;; : * Changed the representation of what's stored in the *global-
;;; : names-table* so that I can add the release-name command.
;;; : That way it's possible for a model to clear out all of the
;;; : temp chunk names that were used for the buffer chunks which
;;; : got merged away if the symbol table size becomes an issue.
;;; : (There's another command called normalize-chunk-names in
;;; : the chunks file that uses release-name because it should
;;; : be rare for a user to call release-name directly.)
;;; 2006.10.23 Dan
;;; : * Complete overhaul of how the symbol creation/deletion is
;;; : managed. Should be better overall, but performance testing
;;; : is still underway - this might need some more tweaks...
;;; 2007.04.16 Dan
;;; : * Changed the version number to 1.1.
;;; : * Added the :ncnar parameter to the module. If it is set to
;;; : t then normalize-chunk-names will be called at the end of
;;; : every run.
;;; 2007.07.03 Dan
;;; : * Changed the :ncnar default value to t.
;;; : That means that like :v one should always disable :ncnar
;;; : when performing long runs or when debugging is not necessary.
;;; 2007.07.13 Dan
;;; : * Added a new value for :ncnar - delete. When it's set to
;;; : delete it not only normalizes the names but uninterns the
;;; : and deletes the other chunks (it passes t to normalize-chunk
;;; : names). NOT a recommended setting, but does provide a
;;; : direct way to handle the issue raised by Bill Kennedy and
;;; : Greg Trafton about long term memory usage of the system.
;;; : Setting it to delete for a model that's run incrementally
;;; : (multiple calls to run) will almost certainly cause errors
;;; : with the vision module if there's a device installed.
;;; 2007.07.24 Dan
;;; : * The quote in front of the lambda in the valid-test of the
;;; : :ncnar parameter causes problems for some Lisps (it shouldn't
;;; : really be there and it's just that some Lisps are more
;;; : forgiving).
;;; 2007.11.21 Dan
;;; : * Fixed a bug with new-symbol-fct that was introduced when
;;; : the :ncnar parameter got added...
;;; 2008.04.17 Dan
;;; : * Performance improvement for the new-name and new-symbol
;;; : functions (at least in ACL, LispWorks, and MCL others
;;; : untested at this point).
;;; : Instead of using princ-to-string created a custom function
;;; : for converting numbers into strings which takes about half
;;; : the time in the tested systems which adds up because of how
;;; : often new-name gets used (creating copies of chunks being
;;; : a big part of model running).
;;; 2008.10.23 Dan [1.3]
;;; : * Added the new parameter :dcnn and modified how :ncnar sets
;;; : the flags for the model since they're in the model struct
;;; : now.
;;; : * Added the functions to check the normalizing conditions
;;; : which bypass getting at the specific parameter values:
;;; : update-chunks-at-all, update-chunks-on-the-fly and
;;; : delete-chunks-after-run.
;;; 2008.11.13 Dan
;;; : * Added the :dcsc-hook parameter to provide a hook for functions
;;; : to be called when chunk name normalizing modifies chunks.
;;; 2009.02.13 Dan
;;; : * Added the :short-copy-names parameter to determine how the
;;; : chunk-name for a copied chunk gets created.
;;; 2009.03.24 Dan
;;; : * Changed update-chunks-on-the-fly to actually check update-
;;; : chunks-at-all as well since :dcnn is supposed to be turned
;;; : off with :ncnar but wasn't completely off unless it was also
;;; : explicitly disabled.
;;; 2012.06.27 Dan
;;; : * Fixed a bug in new-symbol because it would throw an error
;;; : if there isn't a current model instead of printing the warning.
;;; 2017.05.31 Dan [2.0]
;;; : * Also adding a naming component which can generate symbols
;;; : outside of any model and move new-symbol to use the component
;;; : instead of the module.
;;; 2017.06.16 Dan
;;; : * Add locks for the global tables and actually protect the
;;; : symbols table (the name table is not protected yet).
;;; 2017.06.21 Dan
;;; : * Protect everything else with locks (parameters, global
;;; : symbol table, local table, and model level 'updating' slots).
;;; 2017.06.23 Dan
;;; : * Added names for all the locks.
;;; 2018.02.27 Dan
;;; : * Allow the :dcsc-hook function to accept command strings.
;;; : * Provide remote versions of new-name, release-name, and new-symbol.
;;; 2020.01.10 Dan [2.1]
;;; : * Removed the #' and lambdas from the module interface functions
;;; : since that's not allowed in the general system now.
;;; : * Also allow hook function parameters to remove items with
;;; : a setting of (:remove <item>).
;;; 2020.08.25 Dan
;;; : * Replaced constants that had *...* with +...+ to avoid the
;;; : warnings in SBCL.
;;; : * Switch from defconstant to the define-constant macro to
;;; : avoid issues with SBCL (instead of redefining defconstant
;;; : for SBCL as was done previously).
;;; 2021.10.19 Dan [3.0]
;;; : * Set the :required flag on the module.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defvar *global-names-table* (make-hash-table :test #'equal))
(defvar *global-symbols-table* (make-hash-table :test #'equal))
(defvar *symbols-table-lock* (bt:make-lock "symbols-table"))
(defvar *names-table-lock* (bt:make-lock "names-table"))
(define-constant +naming-module-num-vector+ (vector #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))
(defun fast-num->string (n)
(if (< n 4) ;; catch the common/easy cases fast
(if (< n 2)
(if (zerop n) "0" "1")
(if (= n 2) "2" "3"))
(let (rem
(s nil))
(while (> n 0)
(multiple-value-setq (n rem) (floor n 10))
(push rem s))
(let ((s2 (make-string (length s))))
(dotimes (i (length s))
(setf (aref s2 i)
(aref +naming-module-num-vector+ (pop s))))
s2))))
(defstruct act-r-name (next-name 0) used-symbols)
(defstruct naming-module model ncnar dcnn hook (table (make-hash-table :test #'equal)) (table-lock (bt:make-lock "naming-table")) (param-lock (bt:make-lock "naming-param")))
(defun create-naming-module (model-name)
(make-naming-module :model model-name))
(defun reset-naming-module (name-module)
(bt:with-lock-held ((naming-module-table-lock name-module))
(bt:with-lock-held (*names-table-lock*)
(let ((m-name (naming-module-model name-module))
(table (naming-module-table name-module)))
(maphash (lambda (base val)
(dotimes (i (act-r-name-next-name val))
(let* ((symbol-name (concatenate 'string base (fast-num->string i)))
(val (gethash symbol-name *global-names-table*)))
(when (and val
(not (eq val t))
(find m-name val))
(setf val (remove m-name val))
(if (null val)
(let ((symbol (intern symbol-name)))
(unintern symbol)
(remhash symbol-name *global-names-table*))
(setf (gethash symbol-name *global-names-table*) val)))))
(remhash base table))
table)))))
(defun reset-naming-component (name-module)
(bt:with-lock-held ((naming-module-table-lock name-module))
(let ((table (naming-module-table name-module)))
(maphash (lambda (base val)
(dolist (x (act-r-name-used-symbols val))
(let ((symbol (intern (concatenate 'string base "-" (fast-num->string x)))))
(unintern symbol)))
(remhash base table))
table))))
(defun params-naming-module (module param)
(bt:with-lock-held ((naming-module-param-lock module))
(if (consp param)
(case (car param)
(:ncnar
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(cond ((null (cdr param))
(setf (act-r-model-chunk-update model) nil)
(setf (act-r-model-delete-chunks model) nil))
((eq (cdr param) 'delete)
(setf (act-r-model-chunk-update model) t)
(setf (act-r-model-delete-chunks model) t))
(t
(setf (act-r-model-chunk-update model) t)
(setf (act-r-model-delete-chunks model) nil)))))
(setf (naming-module-ncnar module) (cdr param)))
(:dcnn (let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(setf (act-r-model-dynamic-update model) (cdr param))))
(setf (naming-module-dcnn module) (cdr param)))
(:dcsc-hook
(if (cdr param)
(let ((l (length (naming-module-hook module)))
(v (setf (naming-module-hook module)
(set-or-remove-hook-parameter :dcsc-hook (naming-module-hook module) (cdr param)))))
(cond ((< l (length v)) ;; added one
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(push (cdr param) (act-r-model-dynamic-update-hooks model)))))
((> l (length v)) ;; removed one
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(setf (act-r-model-dynamic-update-hooks model)
(remove (cddr param) (act-r-model-dynamic-update-hooks model)))))))
v)
(progn
(setf (naming-module-hook module) nil)
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(setf (act-r-model-dynamic-update-hooks model) nil))))))
(:short-copy-names
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(setf (act-r-model-short-copy-names model) (cdr param))))))
(case param
(:ncnar (naming-module-ncnar module))
(:dcnn (naming-module-dcnn module))
(:dcsc-hook (naming-module-hook module))
(:short-copy-names
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(act-r-model-short-copy-names model))))))))
(defun ncnar-value-test (x)
(or (tornil x) (eq x 'delete)))
(define-module-fct 'naming-module nil
(list
(define-parameter :ncnar
:documentation "Normalize chunk names after run"
:default-value t
:warning "must be t, nil, or delete"
:valid-test 'ncnar-value-test)
(define-parameter :dcnn
:documentation "Dynamic chunk name normalizing"
:default-value t
:warning "must be t or nil"
:valid-test 'tornil)
(define-parameter :dcsc-hook :valid-test 'local-or-remote-function-or-remove
:default-value nil
:warning "a function, string naming a command, nil, or (:remove <item>)"
:documentation "Hook called when a chunk is changed due to normalizing")
(define-parameter :short-copy-names :valid-test 'tornil
:default-value nil
:warning "T or nil"
:documentation "Flag to signal how copied chunks are named"))
:version "3.0"
:documentation "Provides safe and repeatable new name generation for models."
:params 'params-naming-module
:creation 'create-naming-module
:reset 'reset-naming-module
:delete 'reset-naming-module
:required t)
(define-component naming :version "2.0" :documentation "Provides new symbol generation for the system."
:creation make-naming-module
:delete reset-naming-component
:clear-all reset-naming-component)
(defmacro new-name (&optional (prefix "CHUNK"))
`(new-name-fct ',prefix))
(defun new-name-fct (&optional (prefix "CHUNK"))
(if (or (stringp prefix) (symbolp prefix))
(let ((name-module (get-module naming-module)))
(if name-module
(bt:with-lock-held ((naming-module-table-lock name-module))
(let* ((name-table (naming-module-table name-module))
(m-name (naming-module-model name-module))
(base (string-upcase prefix))
(element (gethash base name-table)))
(unless element
(setf element
(setf (gethash base name-table) (make-act-r-name))))
(multiple-value-bind (symbol-name symbol previous)
(do* ((count (act-r-name-next-name element) (1+ count))
(symbol-name (concatenate 'string base (fast-num->string count))
(concatenate 'string base (fast-num->string count)))
(existed (find-symbol symbol-name)
(find-symbol symbol-name))
(symbol (intern symbol-name)
(intern symbol-name)))
((not (get-chunk symbol))
(progn
(setf (act-r-name-next-name element) (1+ count)))
(values symbol-name symbol existed)))
(bt:with-lock-held (*names-table-lock*)
(multiple-value-bind (val exists)
(gethash symbol-name *global-names-table*)
(if exists
(unless (or (eq val t)
(find m-name val))
(setf (gethash symbol-name *global-names-table*)
(push m-name val)))
(if previous
(setf (gethash symbol-name *global-names-table*) t)
(setf (gethash symbol-name *global-names-table*) (list m-name))))))
symbol)))
(print-warning "No naming module available cannot create new name.")))
(print-warning "Invalid parameter passed to new-name. Must be a string or symbol.")))
(add-act-r-command "new-name" 'new-name-fct "Create new item names within a model. Params: {name-prefix}")
(defmacro release-name (symbol)
`(release-name-fct ',symbol))
(defun release-name-fct (symbol)
(bt:with-lock-held (*names-table-lock*)
(multiple-value-bind (val exists) (gethash (symbol-name symbol) *global-names-table*)
(when (and exists
(not (eq t val)))
(let ((name-module (get-module naming-module)))
(if name-module
(let ((m-name (naming-module-model name-module)))
(when (find m-name val)
(setf val (remove m-name val))
(if (null val)
(progn
(remhash (symbol-name symbol) *global-names-table*)
(unintern symbol)
t)
(progn
(setf (gethash (symbol-name symbol) *global-names-table*) val)
nil))))
(print-warning "No naming module available cannot release name ~s." symbol)))))))
(defun release-name-external (name-string)
(release-name-fct (string->name name-string)))
(add-act-r-command "release-name" 'release-name-external "Unintern a name generated by new-name. Params: {name-string}")
(defmacro new-symbol (&optional (prefix "CHUNK"))
`(new-symbol-fct ',prefix))
(defun new-symbol-fct (&optional (prefix "CHUNK"))
(if (or (stringp prefix) (symbolp prefix))
(let* ((component (get-component naming))
(name-table (when component (naming-module-table component))))
(if name-table
(bt:with-lock-held ((naming-module-table-lock component))
(let* ((base (string-upcase prefix))
(element (gethash base name-table)))
(unless element
(setf element
(setf (gethash base name-table) (make-act-r-name))))
(bt:with-lock-held (*symbols-table-lock*)
(unless (gethash base *global-symbols-table*)
(setf (gethash base *global-symbols-table*) 0))
(do* ((count (gethash base *global-symbols-table*)
(incf (gethash base *global-symbols-table*)))
(symbol-name (concatenate 'string base "-" (fast-num->string count))
(concatenate 'string base "-" (fast-num->string count)))
(existed (find-symbol symbol-name)
(find-symbol symbol-name)))
((not existed)
(progn
(push count (act-r-name-used-symbols element))
(incf (gethash base *global-symbols-table*))
(values (intern symbol-name))))))))
(print-warning "No naming component available cannot create new symbol.")))
(print-warning "Invalid parameter passed to new-symbol. Must be a string or symbol.")))
(add-act-r-command "new-symbol" 'new-symbol-fct "Create new names outside of a model. Params: {name-prefix}")
(defun update-chunks-at-all ()
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(act-r-model-chunk-update model))))
(defun update-chunks-on-the-fly ()
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(and (act-r-model-chunk-update model)
(act-r-model-dynamic-update model)))))
(defun notify-on-the-fly-hooks ()
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(act-r-model-dynamic-update-hooks model))))
(defun delete-chunks-after-run ()
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(act-r-model-delete-chunks model))))
(defun use-short-copy-names ()
(let ((model (current-model-struct)))
(bt:with-lock-held ((act-r-model-chunk-updating-lock model))
(act-r-model-short-copy-names model))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 22,703 | Common Lisp | .lisp | 430 | 43.411628 | 173 | 0.551283 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 252a13b0cfef776ecc712687bbe3c79103f380e08368a7f8e5e478cc4ae2b270 | 14,314 | [
-1
] |
14,315 | scheduling.lisp | asmaloney_ACT-R/framework/scheduling.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : scheduling.lisp
;;; Version : 5.2
;;;
;;; Description : Event creation and scheduling and schedule running functions.
;;;
;;; Bugs : [X] Need to fix/remove the update functions from the modules
;;; : because how they get called prevents one from scheduleing
;;; : events correctly during one (in particular the device
;;; : device-update-attended-loc doesn't accept the time parameters
;;; : but just adding that is really just a hack).
;;; : [ ] There isn't a way to delete an "after" event that was waiting
;;; : but then got scheduled since it's no longer the same event
;;; : in the queue.
;;;
;;; To do : [ ] Finish documentation.
;;; : [x] Add an equivalent to the real-time-slack-hook-fn in rpm.
;;; : [ ] Consider a global randomize time flag and/or parameter to the
;;; : scheduling functions.
;;; : [x] The break events and "stopping reason" trace don't go to
;;; : the output of all models but probably should so that if
;;; : the traces are split at the model level they all show it.
;;; : [x] Run-full-time and run-until-time both still rely on the
;;; : time count in seconds to determine the "end" but that's
;;; : still got potential problems.
;;;
;;; ----- History -----
;;;
;;; 2004.08.16 Dan
;;; : Creation
;;; 2004.12.06 Dan
;;; : Updated a warning message because I found it uninformative.
;;; : Tried to fit things to 80 char line width.
;;; 2005.01.12 Dan
;;; : Because the device is now a module it doesn't need to
;;; : be handled specially in set-mp-clock.
;;; 2005.01.27 Dan
;;; : * Modified run-one-event to use filter-output-events which
;;; : is now part of the printing module to determine if the
;;; : trace should be displayed.
;;; 2005.02.03 Dan
;;; : * Removed the format call from the periodic action's details.
;;; 2005.02.14 Dan
;;; : * Added the run-until-condition function.
;;; 2005.02.16 Dan
;;; : * Some general cleanup and added the "stopping reason" output
;;; : to the run functions.
;;; 2005.02.22 Dan
;;; : * Cleaned up the stopping reason output.
;;; : * Fixed a bug in run-full-time by just making it use
;;; : run-until-time.
;;; 2005.02.25 Dan
;;; : * Made run work more like pm-run in that if there are future
;;; : events it will work like run-full-time instead of just
;;; : stopping.
;;; 2005.02.28 Dan
;;; : * Switched the stopping reason output from model-output to
;;; : meta-p-output (which I've put back into things) because
;;; : model-output doesn't work in a multi-model situation.
;;; 2005.04.20 Dan
;;; : * Changed add-pre/post-event-hook so that fboundp doesn't
;;; : cause problems for Lispworks with lambdas.
;;; 2005.05.20 Dan
;;; : * Fixed a bug in run-until-time (caused primarily when
;;; : run-full-time used) where a non-rounded time could cause
;;; : the system to get stuck.
;;; 2005.12.08 Dan
;;; : * Fixed a bug in the output of the events generated by
;;; : schedule-periodic-event and periodic-action.
;;; 2006.01.25 Dan
;;; : * Modifying all the "run" functions so that when they end
;;; : a "run-terminated" event is passed to all the models if
;;; : it terminates other than due to a break. This way, the
;;; : event hooks can detect when a run ends (either a break
;;; : event or an event with the run-terminated action) which
;;; : makes adding additional tracing and other tools easier.
;;; 2006.01.26 Dan
;;; : * Added an optional parameter to the add-pre/post-event-hook
;;; : functions to suppress the warning if one adds a hook that's
;;; : already on the list. It just returns nil in that case now.
;;; : This helps because the hook is at the meta-process level,
;;; : but one may have a module (at the model level) that needs
;;; : to add such a hook and not want to see the warning if there
;;; : are multiple models loaded and using it.
;;; 2006.01.30 Dan
;;; : * Changed the run-terminated event to a maintenance event.
;;; : * Added the keyword param :include-maintenance to the schedule-
;;; : after-* functions which indicates whether or not to include
;;; : maintenance events in those that can trigger it (it defaults
;;; : to nil). This keeps things from getting scheduled after
;;; : events that don't do anything for the model.
;;; : * Added the schedule-maintenance-event-relative function to
;;; : be able to schedule maintenance events. Could make it a
;;; : switch on the existing functions, but for now at least
;;; : I've decided to use a different function.
;;; 2006.02.24 Dan
;;; : * Fixed a bug in run-until-time that caused it to not work
;;; : if there was more than one model defined.
;;; 2006.02.27 Dan [1.2]
;;; : * Modified run-schd-queue and set-mp-clock so that they
;;; : now use the "real time" control functions that can be set
;;; : for the meta-process using mp-real-time-management.
;;; 2006.02.28 Dan
;;; : * Added a schedule-maintenance-event function and changed
;;; : run-until-time to actually use it.
;;; 2006.03.03 Dan
;;; : * Modified run-sched-queue to use the max-delta-time
;;; : property set with mp-real-time-management.
;;; : New (non-maintenance) "dummy" events will be automatically
;;; : generated to occur in any time slice that needs them.
;;; 2006.03.08 Dan
;;; : * Fixed a bug with schedule-break-after-module because it
;;; : didn't set the model for the event, so never matched up
;;; : with a new event to get scheduled.
;;;
;;; 2006.05.02 Dan
;;; : * Noted an issue with the update function of modules and put
;;; : it under bugs above.
;;; 2006.07.13 Dan
;;; : * Fixed a bug with run-until-time that caused it to jump
;;; : back in time if the end-time had already passed.
;;; 2006.07.14 Dan
;;; : * Added another output to run-n-events to make it clearer
;;; : in the trace why it stopped - differentiate hitting the
;;; : event-count from just running out of events.
;;; 2006.07.18 Dan
;;; : * Removed the schedule-maintenance-* functions and
;;; : replaced them with a keyword :maintenance t/nil
;;; : in the regular schedule-* functions.
;;; : * Updated all references to schedule-maintenance-* with
;;; : the correct schedule-* function.
;;; : * As a saftey check those maintenance functions now just
;;; : print a warning to let people know there was a change.
;;; 2006.07.20 Dan
;;; : * Fixed a bug in schedule-periodic-event because it tried
;;; : to take the symbol-name of an interpreted function if that
;;; : was passed as the action.
;;; : * Updated conditions-met because a break event doesn't have
;;; : a model so if it's waiting it'll never match to any specific
;;; : model so should instead match to any model.
;;; : * Fixed update waiting-events because it didn't distinguish
;;; : between break events and normal events which caused a
;;; : problem for schedule-break-after-module.
;;; 2006.07.28 Dan
;;; : * Fixed the warning in delete-event-hook.
;;; 2007.01.19 Dan
;;; : * Fixed a bug in periodic-action because it had the same
;;; : symbol-name issue as schedule-periodic-event did...
;;; 2007.04.16 Dan
;;; : * Updated the version to 1.3.
;;; : * Made the run-terminated action actually do something. It
;;; : checks the :ncnar parameter and if true calls normalize-
;;; : chunk-names.
;;; 2007.05.04 Dan
;;; : * Added a general method for delete-event (specified the class
;;; : t) so that it doesn't throw an error if a bad value is
;;; : provided.
;;; 2007.07.13 Dan
;;; : * Changed run-terminated so that when :ncnar is set to delete
;;; : it actually forces the chunk deletion and name uninterning.
;;; 2007.08.28 Dan
;;; : * Added s and w options to run-step to show the event queue and
;;; : the waiting events during the stepping.
;;; 2007.10.31 Dan
;;; : * Fixed a bug with the printing of break events in run-one-event -
;;; : if there was more than one model the event wasn't being output.
;;; : Now check for break events and use meta-p-output instead of
;;; : model-output since a break doesn't have a model.
;;; : * Changed the model name used for the terminating event output
;;; : to just '- so that it will always line up even if the longest
;;; : model name is only 1 character.
;;; 2007.11.30 Dan
;;; : * Changed run-terminated to use awhen so it doesn't have to
;;; : call sgp twice (an expensive call).
;;; 2007.12.13 Dan
;;; : * Fixed a bug in schedule-periodic-event because if it was
;;; : passed an action that wasn't a symbol the call to fboundp
;;; : for the details would break.
;;; 2008.05.02 Dan
;;; : * Added another option to run-step (b) for showing the buffer
;;; : contents.
;;; 2008.10.23 Dan
;;; : * Updated run-terminated to use the new flags for normalizing.
;;; 2008.10.28 Dan
;;; : * Changed the model-output in run-one-event so that the
;;; : event string isn't directly used as the format string to
;;; : avoid issues with tildes in the output.
;;; 2009.03.10 Dan [1.4]
;;; : * Moved the code to check for sending module "updates" from
;;; : set-mp-clock to run-sched-queue. This has two effects:
;;; : - Updates occur at the end of a time step now and not the
;;; : "top of the next one".
;;; : - It's safe to schedule events during an "update" (fixes
;;; : the bug listed under bugs).
;;; 2009.04.29 Dan
;;; : * Added checks for recursive calls to run and now signal a
;;; : warning and just abort the later calls.
;;; 2009.12.04 Dan [1.5]
;;; : * Updated the real-time running code to allow for a little
;;; : more responsiveness when a slack-hook is provided. Events
;;; : can be scheduled during the slack-hook and they can jump
;;; : "back" in time if desired (which would require explicitly
;;; : scheduling them for that time since "now" has still already
;;; : moved) which likely requires a custom clock as well (to
;;; : know when "now" is relative to where the event queue is).
;;; : * In addition to that, if the allow-dynamics is also provided
;;; : then events which were scheduled using one of the after
;;; : scheduling functions and are flagged as dynamic will be
;;; : sensitive to those new events (or events that they schedule)
;;; : and may be moved back in time if appropriate (conflict-resolution
;;; : is now scheduled as dynamic so it could move back).
;;; : * It is important to note however that the scheduling code is
;;; : still not thread safe -- any asynchronous event scheduling
;;; : should occur in the slack-hook (or some other safe place) and
;;; : be protected appropriately.
;;; 2010.09.02 Dan
;;; : * Added a test to run-sched-queue to check if the end time is
;;; : greater than what can be represented accurately with the
;;; : current floating point size of the time and warn if it should
;;; : be changed or there's nothing that can be done.
;;; : * Changed the calls that set the time so that they go through
;;; : the proper coercion when things are changed.
;;; 2010.11.03 Dan
;;; : * Changed all of the code to use time in milliseconds internally
;;; : and convert to/from seconds where there's an interface with the
;;; : user since the API is for seconds.
;;; : * Removed the floating point time check code since it's not
;;; : necessary now, but may still be useful to know if the time
;;; : is "too big" in the future so still leaving it in comments
;;; : for potentially enabling again in the future.
;;; 2010.12.22 Dan
;;; : * Took the toggle out of the run-sched-queue since the integer
;;; : time values won't have the same issues as floating point
;;; : math and comparisons.
;;; : * Added code to notify modules at the start of a run for all
;;; : the modules which have a run-notify function.
;;; 2011.01.11 Dan
;;; : * Added code to notify modules at the end of a run too, and
;;; : reorganized run-sched-queue a little to make sure the
;;; : unwind-protect covers everything.
;;; 2011.01.14 Dan
;;; : * Added the new command mp-running? to query whether the current
;;; : meta-process is currently running.
;;; 2011.02.04 Dan
;;; : * Added visicon and buffer-status options to run-step.
;;; 2011.03.25 Dan
;;; : * Took the API section out since it's out of date and I don't
;;; : want to update it with the new changes either...
;;; : * Adjusted run-one-event so that dynamics clear their dynamic
;;; : flag before being output in the trace.
;;; 2011.03.29 Dan
;;; : * Added the option of specifying time in milliseconds for all
;;; : of the scheduling commmands by specifying :time-in-ms t.
;;; 2011.04.25 Dan
;;; : * Fixed a bug in schedule-event-relative introduced with the
;;; : :time-in-ms option.
;;; : * Schedule-periodic-event and schedule-ee had the
;;; : same issue.
;;; 2011.04.28 Dan
;;; : * Changed the schedule-maintenance-event* functions which aren't
;;; : used to avoid warnings at compile time.
;;; : * Added some declaims to avoid compiler warnings about
;;; : undefined functions.
;;; 2011.05.18 Dan
;;; : * Changed set-mp-clock and insert-queue-event to prevent time
;;; : from moving backwards. The slack-hook for real time now
;;; : gets called with a second parameter which is the "next"
;;; : time in milliseconds.
;;; 2011.05.19 Dan
;;; : * Added a declare to ignore next-time in real-time-slack.
;;; 2011.06.06 Dan
;;; : * Changed the second parameter for the slack-hook to time in
;;; : seconds since all the "user" code should be working in seconds.
;;; 2011.06.07 Dan
;;; : * Changed the real-time clock setting so that the real-time
;;; : clock function is called before the model time is checked
;;; : so that a custom clock could schedule events that are "ahead"
;;; : of the next model event.
;;; 2012.01.27 Dan
;;; : * Added an additional test to the scheduling functions so that
;;; : they reject actions which are macros since those will throw
;;; : an error at run time.
;;; 2012.08.08 Dan
;;; : * Send all the notifications (start, stop, update, terminate)
;;; : to the models in order using meta-p-model-order instead of
;;; : maphashing over the model table for consistency.
;;; 2012.12.06 Dan
;;; : * Changed run-sched-queue so that it returns the time in ms
;;; : and then convert that as needed in the "run" functions to
;;; : try and avoid other float issues with math on times.
;;; 2013.01.03 Dan
;;; : * Use the meta-p-max-time-maintenance value when scheduling a
;;; : necessary time-delta event.
;;; 2013.01.04 Dan
;;; : * Add cannot-define-model to run-sched-queue and send-run-terminated-events
;;; : to avoid problems.
;;; 2014.02.21 Dan
;;; : * Add a warning to the top of every run.
;;; 2014.07.17 Dan
;;; : * Removed the warning.
;;; 2015.06.04 Dan
;;; : * Use safe-seconds->ms for all the run and schedule time
;;; : conversions.
;;; 2015.06.05 Dan
;;; : * Finally adding a schedule-event-now function that does what
;;; : the name suggests to replace all the ...-relative 0 calls.
;;; 2015.06.09 Dan
;;; : * The "clean up" run-full-time at the end of run now computes
;;; : the difference in ms and creates a rational to avoid floats.
;;; 2015.07.29 Dan [2.0]
;;; : * Add the option of a precondition to an event. It must be a
;;; : function and will be passed the same parameters as the action.
;;; : If an event has a precondition when it is the "next" event
;;; : which could occur the precondition is first tested. If that
;;; : returns nil then the event is removed from the queue without
;;; : performing its action. No output will be generated for the
;;; : trace for an event with a failed precondition at this point,
;;; : and only maintenance events will be allowed to have preconditions
;;; : for now. This is being added because the "unstuff" actions
;;; : for perceptual modules shouldn't advance the clock if there
;;; : isn't a chunk that needs to be unstuffed, but the module
;;; : can't remove the scheduled event because the buffer can be
;;; : modified by "anything" and thus it can't know until it needs
;;; : to try.
;;; 2015.08.25 Dan
;;; : * Use the real-time-scale when updating the clock so that both
;;; : the clock and slack get the appropriate shift in time.
;;; : * New system parameter :real-time-sleep-threshold which sets
;;; : the min time for sleeping in the default real time slack hook.
;;; : * Run function's real-time parameter can be specified as a number
;;; : in addition to t. If it is a number then that over rides
;;; : the current real-time-scale parameter.
;;; 2015.09.14 [3.0]
;;; : * Not really a change to the code, but making the current
;;; : process of scheduling equal priority items after any existing
;;; : items of that priority the specified mechanism i.e. that's
;;; : what the docs say now so it shouldn't be changed in the
;;; : future.
;;; 2016.09.28 Dan
;;; : * Removed all the setting of the :mp slot in the events.
;;; 2016.11.16 Dan [4.0]
;;; : * Start to convert to using the central dispatcher for all
;;; : user commands. At this point, the only one added is run,
;;; : and it still needs work because the trace/output situation
;;; : hasn't been worked out yet.
;;; 2016.11.17 Dan
;;; : * Changed execute-act-r-command to evaluate-act-r-command.
;;; 2017.01.18 Dan
;;; : * Removed the echo-act-r-output from run. The assumption
;;; : now is that echoing is handled by the user.
;;; : * Use handle-evaluate-results.
;;; 2017.01.27 Dan
;;; : * Start to think about taking dispatch function names for
;;; : scheduling. Right now just allow strings as the function
;;; : value, but don't actually dispatch them correctly because
;;; : there are a bunch of issues to work out...
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.02 Dan
;;; : * Changed the real-time parameter for the run function from a
;;; : keyword parameter to an optional so it matches the signature
;;; : of the dispatchers function.
;;; : * Added the run-full-time command as a dispatched command.
;;; 2017.02.09 Dan
;;; : * Updated the call to run-full-time inside of run since real-time
;;; : is now optional not keyword.
;;; 2017.02.15 Dan
;;; : * Allow all the scheduling commands to accept remote commands
;;; : for the actions and preconditions.
;;; 2017.02.20 Dan
;;; : * Fixed a bug introduced with the last update.
;;; 2017.02.22 Dan
;;; : * Adding a suite of "simple" scheduling commands which will
;;; : be available through the dispatcher. The simple versions
;;; : will use optional parameters to match with the underlying
;;; : RPC protocol, not make available :destination since it can't
;;; : practically be sent remotely, always have medium output,
;;; : always use milliseconds (since that's what gettime returns),
;;; : no alternate details, and no precondition.
;;; : For now, the simple event functions only return t or nil to
;;; : indicate success and thus can't be deleted, but there could
;;; : be an internal reference kept that maps something returnable,
;;; : like an int, to the actual event to allow that eventually.
;;; 2017.02.24 Dan
;;; : * Allowing run-until-condition to accept a string that will call
;;; : a dispatch function. That seems like an extremely bad way
;;; : to run things since it gets called for each event, but there's
;;; : a tutorial task that uses it so making it available...
;;; 2017.03.30 Dan
;;; : * Replace meta-p-current-model usage with *current-act-r-model*.
;;; 2017.03.31 Dan
;;; : * Mp-running? has been moved to the meta-process file and the
;;; : code which was setting the running slot now calls the function
;;; : set-mp-running and clear-mp-running in a macro that's used
;;; : in the run functions directly instead of run-sched-queue.
;;; : * Also, run doesn't call run-full-time now because that would
;;; : be a problem with setting the running flag.
;;; 2017.06.02 Dan
;;; : * Cleaned up some issues with the "current model" setting and
;;; : use current-model-struct instead of *current-act-r-model*
;;; : directly.
;;; 2017.06.22 Dan
;;; : * Protected all access to meta-p-time, meta-p-model-order, and
;;; : meta-p-models.
;;; 2017.06.23 Dan
;;; : * Protected meta-p-delayed and added the need-to-check-updates
;;; : function to avoid the need for that same or occurring in lots
;;; : of places. Also protected meta-p-dynamics.
;;; 2017.06.28 Dan
;;; : * Protecting the rest of the meta-p-* schedule slot access.
;;; 2017.06.30 Dan
;;; : * Protecting the meta-p event hook slots.
;;; : * Why did run and run-full-time go through the dispatcher but
;;; : run-until-condition didn't? For now not dispatching any, but
;;; : may need to revisit that.
;;; : * Modified run-until-time and run-n-events to work remotely
;;; : and added the commands.
;;; : * Added a schedule-simple-event-now local and remote.
;;; : * Everything is thread safe except run-step (read and format
;;; : not feasible) and real-time-slack since the system parameter
;;; : :real-time-sleep-threshold isn't safe.
;;; 2017.06.14 Dan
;;; : * Real-time-slack is now safe since system parameters are now
;;; : safe.
;;; : * Check the top-level-lock before running.
;;; 2017.08.24 Dan
;;; : * Added signals for run-start and run-stop that can be monitored.
;;; : Should modules just monitor for those now instead of specifying
;;; : hook functions for those situations?
;;; 2017.08.28 Dan
;;; : * Added a remote version of schedule-break-relative and updated
;;; : the doc string for the remote schedule-simple-event-relative.
;;; : * Allow a pre-event-hook to force a break before executing the
;;; : event by returning the string "break".
;;; 2017.08.29 Dan
;;; : * When the pre-event causes a break it needs to put the event
;;; : back on the queue!
;;; 2017.11.14 Dan
;;; : * Fix an issue with run not printing the end reason when it
;;; : stopped because the time limit was reached due to the need
;;; : for a dummy event because the next real event was beyond the
;;; : run time.
;;; 2017.11.20 Dan
;;; : * Another fix for the previous issue because it printed the wrong
;;; : time with that fix. It should all be right now.
;;; 2017.12.06 Dan
;;; : * Changed some of the doc strings for remote commands.
;;; : * Added the schedule-simple-event-after-module remote command.
;;; 2017.12.08 Dan
;;; : * Convert priorities from strings in the simple- functions.
;;; 2017.12.11 Dan
;;; : * Also need to convert the module names in the simple functions.
;;; 2018.02.07 Dan [5.0]
;;; : * Reworked all the event access to use the full struct since
;;; : the conc-name of evt- isn't used any more.
;;; : * Simplified a lot of the scheduling code because the things
;;; : that touch the event queues have been abstracted and put
;;; : into functions in the meta-process code.
;;; : * Return an id# for the events instead of the struct itself
;;; : so that it's more feasible to "use" them remotely.
;;; : * Reworked the "running" code because as it was there were
;;; : some nasty race conditions now that events can come in
;;; : asynchronously -- in particular that it kept referring to
;;; : the first item in the event queue but gave up the lock
;;; : between accesses to that value.
;;; : * Also reworking how real-time works because it can't just
;;; : spin when the current next-event has to wait since another
;;; : event that should happen during that wait time could show
;;; : up while it's waiting.
;;; : * Real-time-slack now just yields instead of sleeping.
;;; : * The real time slack fn is now passed current time and next
;;; : time and it can compute the delta if needed.
;;; : * For the run-terminated-events don't actually put it on the
;;; : queue just run the created event directly.
;;; : * Actually store the model structure in the event instead of
;;; : just the name.
;;; : * Protect all access to event times and priorities with the
;;; : meta-p-schedule-lock.
;;; 2018.02.23 Dan
;;; : * Depricate the "simple" scheduling functions and provide all
;;; : the parameters as optionals for external versions of all the
;;; : scheduling functions.
;;; 2018.02.28 Dan
;;; : * Fixed some cut-and-paste bugs with the new external fcts.
;;; 2018.03.26 Dan
;;; : * Pass the time to the run-until-condition condition function
;;; : since it's not safe to get the time at that point -- the lock
;;; : is held.
;;; 2018.05.10 Dan
;;; : * Fixed run-sched-queue because it needed to use dispatch-
;;; : apply when running the time-function.
;;; 2018.05.11 Dan
;;; : * Use the time-units-per-second value with an absolute clock.
;;; 2018.06.15 Dan
;;; : * Remove the simple scheduling functions and use an options
;;; : list to handle all keyword params.
;;; : * Schedule-break-after-all changed from having one keyword
;;; : parameter to an optional.
;;; 2018.06.28 Dan
;;; : * Moved the run-stop signal so it's always sent even if the
;;; : run terminates due to an error.
;;; 2018.07.11 Dan
;;; : * Fix a typo with :priority being misspelled in the calls
;;; : which process the external params for some actions.
;;; 2019.02.05 Dan
;;; : * Adjustments because meta-p-models is now an alist.
;;; 2019.02.15 Dan
;;; : * Added a switch that kills the trace output without having to
;;; : access the printing module or output filtering and it's
;;; : associated with the system parameter - :high-performance.
;;; 2019.04.09 Dan
;;; : * When creating events set the min and max slots instead of
;;; : priority when needed since priority is now always a number.
;;; 2019.05.22 Dan [5.1]
;;; : * Added a run-until-action function that runs the system
;;; : until after an event that has the provided action occurs.
;;; 2019.09.09 Dan
;;; : * Adjusted calls to with-top-level lock to pass the string
;;; : that indicates why the lock is being held.
;;; 2020.06.02 Dan
;;; : * Since run-one-event already sets the current model it can
;;; : skip filter-output-events and call the test directly now
;;; : that it always sets a current model if possible, and filter-
;;; : test returns the current value of :v so that can be tested
;;; : to avoid the model-output call that needs to get the
;;; : printing-module again.
;;; 2020.07.06 Dan [5.2]
;;; : * Allow scheduling nil to just display the details. However,
;;; : if details aren't provided for a nil event it's going to
;;; : show an event called internal-dummy-event-fn.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;; See reference-manual...
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Keep the system as simple as I can.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function () t) print-visicon))
(declaim (ftype (function () t) delete-chunks-after-run))
(declaim (ftype (function () t) update-chunks-at-all))
(declaim (ftype (function (t) t) filter-test))
(defvar *periodic-event-id-counter* 0)
(defvar *periodic-event-lock* (bt:make-lock "periodic-event"))
(defvar *allow-event-output* t)
(defun skip-unnecessary-events (mp)
; assume it's called with the lock held (bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(do* ((cm (current-model-struct))
(next-event (next-scheduled-event mp) (next-scheduled-event mp))
(unnecessary (and next-event
(act-r-event-precondition next-event)
(let ((*current-act-r-model* (if (act-r-event-model next-event)
(act-r-event-model next-event)
cm)))
(null (if (act-r-event-destination next-event)
(dispatch-apply-list (act-r-event-precondition next-event)
(append (list (get-module-fct (act-r-event-destination next-event)))
(act-r-event-params next-event)))
(dispatch-apply-list (act-r-event-precondition next-event) (act-r-event-params next-event))))))
(and next-event
(act-r-event-precondition next-event)
(let ((*current-act-r-model* (if (act-r-event-model next-event)
(act-r-event-model next-event)
cm)))
(null (if (act-r-event-destination next-event)
(dispatch-apply-list (act-r-event-precondition next-event)
(append (list (get-module-fct (act-r-event-destination next-event)))
(act-r-event-params next-event)))
(dispatch-apply-list (act-r-event-precondition next-event) (act-r-event-params next-event))))))))
((not unnecessary) nil)
(remove-scheduled-event mp next-event)))
(add-act-r-command "run-start" nil "Signal that the system is starting to run for monitoring. Params: run-start-time." nil)
(add-act-r-command "run-stop" nil "Signal that the system has stopped running for monitoring. Params: run-end-time." nil)
(defun run-sched-queue (mp stop-condition &key (real-time nil))
"The internal function that steps through events sending them to be
executed until a condtion is met"
(unwind-protect
(let ((event-count 0)
next-event
evaluate
next-time)
;; Notify any modules which care that a new run has begun
(dolist (model-name (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-model-order mp)))
(let ((*current-act-r-model* (bt:with-lock-held ((meta-p-models-lock mp)) (cdr (assoc model-name (meta-p-models mp))))))
(dolist (module (run-notify-modules))
(run-notify-module module))))
;; Send the start signal and set the initial clock info
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(dispatch-apply "run-start" (meta-p-time mp))
(setf (meta-p-break mp) nil)
(setf (meta-p-start-time mp) (meta-p-time mp))
(when real-time
(setf (meta-p-start-real-time mp)
(dispatch-apply (meta-p-time-function mp)))
(unless (numberp real-time)
(setf real-time 1.0))))
(loop
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(when (or (meta-p-break mp)
(skip-unnecessary-events mp) ;; always returns nil but need to do that now
(not (setf next-event (next-scheduled-event mp)))
(funcall stop-condition
mp
(act-r-event-mstime next-event)
event-count))
(return))
(set-mp-clock mp (act-r-event-mstime next-event) real-time)
(setf evaluate (<= (act-r-event-mstime next-event) (meta-p-time mp)))
(setf next-time (act-r-event-mstime next-event)))
(if evaluate
(let ((result (run-one-event mp next-event)))
(if result
(incf event-count)
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(setf (meta-p-break mp) t))))
(when real-time
(dispatch-apply (meta-p-slack-function mp) (meta-p-time mp) next-time))))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(remove-tagged-events mp 'dummy-event-function :key 'act-r-event-action :count nil :test 'eq)
;(dispatch-apply "run-stop" (meta-p-time mp))
(values (- (meta-p-time mp) (meta-p-start-time mp)) event-count (meta-p-break mp))))
(progn
;; generate a run-stop signal
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(dispatch-apply "run-stop" (meta-p-time mp)))
;; Notify any modules which care that a run has ended
(dolist (model-name (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-model-order mp)))
(let ((*current-act-r-model* (bt:with-lock-held ((meta-p-models-lock mp)) (cdr (assoc model-name (meta-p-models mp))))))
(dolist (module (run-over-notify-modules))
(run-over-notify-module module))))
;; instead of relying on the run functions to do this,
;; always do it here (even if there is a break) directly
;; instead of through an event.
(dolist (model-name (bt:with-lock-held ((meta-p-models-lock mp)) (meta-p-model-order mp)))
(let ((*current-act-r-model* (bt:with-lock-held ((meta-p-models-lock mp)) (cdr (assoc model-name (meta-p-models mp))))))
(when (update-chunks-at-all)
(normalize-chunk-names (delete-chunks-after-run))))))))
;;; run-one-event
;;;
(defun run-one-event (mp next-event)
(let ((*current-act-r-model* (act-r-event-model next-event))
(break nil))
(dolist (hook (bt:with-lock-held ((meta-p-event-hook-lock mp)) (meta-p-pre-events mp)))
(let ((r (dispatch-apply hook (act-r-event-num next-event))))
(when (and r (stringp r) (string-equal r "break"))
(setf break t))))
(when break ;; don't remove the event and just return
(meta-p-output (format-event (make-act-r-break-event :mp nil
:mstime (mp-time-ms)
:params nil
:details "forced by a pre-event hook")))
(return-from run-one-event nil))
;; print the trace if needed
(when (and *allow-event-output*
(act-r-event-output next-event))
(if *current-act-r-model*
(multiple-value-bind (o v) (filter-test next-event)
(when o
(if (act-r-break-event-p next-event)
(meta-p-output (format-event next-event))
(when v
(model-output "~a" (format-event next-event))))))
;; if we don't have a current-model just set it to the first one
;; in the meta-process to get parameter values (which would be
;; the same as default because default is only set when there's
;; one model defined...
(let ((*current-act-r-model* (bt:with-lock-held ((meta-p-models-lock mp))
(cdar (meta-p-models (current-mp))))))
(multiple-value-bind (o v) (filter-test next-event)
(when o
(if (act-r-break-event-p next-event)
(meta-p-output (format-event next-event))
(when v
(model-output "~a" (format-event next-event)))))))))
;; remove the event now so that it doesn't interfere with
;; events being scheduled while it's evaluated
(remove-scheduled-event mp next-event)
;; evaluate the event
(if (act-r-event-destination next-event)
(dispatch-apply-list (act-r-event-action next-event)
(append (list (get-module-fct
(act-r-event-destination next-event)))
(act-r-event-params next-event)))
(dispatch-apply-list (act-r-event-action next-event) (act-r-event-params next-event)))
;; call the post hooks -- the event is still available viay the id because it's temporarily
;; stored by the meta-process with remove-scheduled-event
(dolist (hook (bt:with-lock-held ((meta-p-event-hook-lock mp)) (meta-p-post-events mp)))
(dispatch-apply hook (act-r-event-num next-event)))
;; return success
t))
;;; set-mp-clock
;;;
;;; This function takes three parameters which are a meta-process, the next
;;; time as it stands now, and whether or not it's to run in real-time.
;;;
(defun set-mp-clock (mp time real-time)
"Update the time of a meta-process"
;; assume this (bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(if real-time
(let ((actual-time (cond ((eq (meta-p-time-mode mp) 'absolute)
(seconds->ms (/ (dispatch-apply (meta-p-time-function mp)) (meta-p-units-per-second mp))))
(t ;; interval
(+ (meta-p-start-time mp)
(seconds->ms (* real-time (/ (- (dispatch-apply (meta-p-time-function mp)) (meta-p-start-real-time mp))
(meta-p-units-per-second mp)))))))))
(setf (meta-p-time mp) (min time actual-time)))
(setf (meta-p-time mp) time)))
(defmacro indicate-running (&body body)
`(when (set-mp-running "Recursive call to a running function not allowed. Must wait for a 'run' to complete before 'running' again.")
(unwind-protect
(with-top-level-lock "Unable to run the system." "a running command"
,@body)
(clear-mp-running))))
(defun run (run-time &optional (real-time nil))
(indicate-running
(if (not (and (numberp run-time) (> run-time 0)))
(print-warning "run-time must be a number greater than zero.")
(let ((ms-time (safe-seconds->ms run-time 'run)))
(flet ((test (mp next-time count)
(declare (ignore count))
(> (- next-time (meta-p-start-time mp)) ms-time)))
(multiple-value-bind (time events break)
(run-sched-queue (current-mp) #'test :real-time real-time)
(unless break
(let ((mp (current-mp)))
(let ((mp-time (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))))
(if (< time ms-time)
(if (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (null (meta-p-events mp)))
(meta-p-output (format-event (make-act-r-event
:mstime mp-time
:module "------"
:model '-
:details
"Stopped because no events left to process"
:output t
:mp nil)))
(progn
(let ((msend-time (+ (- ms-time time) mp-time)))
(flet ((test (mp next-time count)
(declare (ignore count) (ignore mp))
(> next-time msend-time)))
(if (current-model)
(schedule-event msend-time 'dummy-event-function
:maintenance t :priority :min
:details "A dummy event to guarantee a run until time"
:time-in-ms t
:output nil)
(with-model-eval (first (mp-models)) ;; just pick the first one
(schedule-event msend-time 'dummy-event-function
:maintenance t
:priority :min
:details "A dummy event to guarantee a run until time"
:time-in-ms t
:output nil)))
(run-sched-queue (current-mp) #'test :real-time real-time)))
(setf time ms-time)
(meta-p-output (format-event (make-act-r-event
:mstime (mp-time-ms)
:module "------"
:model '-
:details "Stopped because time limit reached"
:output t
:mp nil)))))
(meta-p-output (format-event (make-act-r-event
:mstime mp-time
:module "------"
:model '-
:details "Stopped because time limit reached"
:output t
:mp nil)))))))
(values (ms->seconds time) events break)))))))
(add-act-r-command "run" 'run "Run the ACT-R scheduler for up to a specified amount of time. Params: time {real-time}." "Only one run allowed at a time")
(defun run-until-condition (condition &optional (real-time nil))
(indicate-running
(if (not (local-or-remote-function-p condition))
(print-warning "condition must be a function or valid dispatch command string.")
(multiple-value-bind (time events break)
(run-sched-queue (current-mp)
(if (stringp condition)
(lambda (mp next-time count)
(declare (ignore mp count))
(multiple-value-bind (success result) (evaluate-act-r-command condition next-time)
(if success
result
(progn
(print-warning "Run terminated because of Error:< ~s > evaluating condition." result)
t))))
(lambda (mp next-time count)
(declare (ignore mp count))
(funcall condition next-time)))
:real-time real-time)
(unless break
(let* ((mp (current-mp))
(mp-time (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))))
(if (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (null (meta-p-events mp)))
(meta-p-output (format-event (make-act-r-event
:mstime mp-time
:module "------"
:model '-
:details "Stopped because no events to process"
:output t
:mp nil)))
(meta-p-output (format-event (make-act-r-event
:mstime mp-time
:module "------"
:model '-
:details "Stopped because condition is true"
:output t
:mp nil))))))
(values (ms->seconds time) events break)))))
(add-act-r-command "run-until-condition" 'run-until-condition "Run the ACT-R scheduler until the provided function returns a non-nil value. Params: fct-or-cmd-string {real-time?}." "Only one run allowed at a time")
(defun run-until-action (action &optional (real-time nil))
(indicate-running
(if (not (or (symbolp action) (stringp action)))
(print-warning "run-until-action must be given a name(symbol) or a string, but given ~s which is a ~s." action (type-of action))
(let ((stop nil)
(name (when (symbolp action) (symbol-name action))))
(flet ((test-symbol (mp next-time count)
(declare (ignore next-time count))
(let* ((e (next-scheduled-event mp))
(a (act-r-event-action e)))
(prog1
stop
(unless stop
(cond ((symbolp a)
(setf stop (eq action a)))
((stringp a)
(setf stop (string-equal name a))))))))
(test-string (mp next-time count)
(declare (ignore next-time count))
(let* ((e (next-scheduled-event mp))
(a (act-r-event-action e)))
(prog1
stop
(unless stop
(cond ((symbolp a)
(setf stop (string-equal action (symbol-name a))))
((stringp a)
(setf stop (string= action a)))))))))
(multiple-value-bind (time events break)
(run-sched-queue (current-mp) (if (symbolp action) #'test-symbol #'test-string) :real-time real-time)
(unless break
(if stop
(meta-p-output (format-event (make-act-r-event
:mstime (mp-time-ms)
:module "------"
:model '-
:details (format nil "Stopped because ~a action occurred" action)
:output t
:mp nil)))
(meta-p-output (format-event (make-act-r-event
:mstime (mp-time-ms)
:module "------"
:model '-
:details
"Stopped because no events left to process"
:output t
:mp nil)))))
(values (ms->seconds time) events break)))))))
(defun run-until-action-external (action &optional (real-time nil))
(run-until-action (decode-string action) real-time))
(add-act-r-command "run-until-action" 'run-until-action-external "Run the ACT-R scheduler stopping after an event with the given action occurs. Params: 'action' {real-time}." "Only one run allowed at a time")
(defun run-full-time (run-time &optional (real-time nil))
(indicate-running
(if (not (and (numberp run-time) (> run-time 0)))
(print-warning "run-time must be a number greater than zero.")
(let* ((mp (current-mp))
(msend-time (+ (safe-seconds->ms run-time 'run-full-time) (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp)))))
(flet ((test (mp next-time count)
(declare (ignore count) (ignore mp))
(> next-time msend-time)))
(if (current-model)
(schedule-event msend-time 'dummy-event-function
:maintenance t :priority :min
:details "A dummy event to guarantee a run until time"
:time-in-ms t
:output nil)
(with-model-eval (first (mp-models)) ;; just pick the first one
(schedule-event msend-time 'dummy-event-function
:maintenance t
:priority :min
:details "A dummy event to guarantee a run until time"
:time-in-ms t
:output nil)))
(multiple-value-bind (time events break)
(run-sched-queue mp #'test :real-time real-time)
(unless break
(meta-p-output (format-event (make-act-r-event
:mstime (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))
:module "------"
:model '-
:details "Stopped because time limit reached"
:output t
:mp nil))))
(values (ms->seconds time) events break)))))))
(add-act-r-command "run-full-time" 'run-full-time "Run the ACT-R scheduler for the specified amount of time. Params: time {real-time}." "Only one run allowed at a time")
(defun dummy-event-function ())
(defun run-until-time (end-time &optional (real-time nil))
(indicate-running
(if (not (and (numberp end-time) (> end-time 0)))
(print-warning "end-time must be a number greater than zero.")
(let ((mp (current-mp))
(ms-end-time (safe-seconds->ms end-time 'run-until-time)))
(if (<= ms-end-time (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp)))
(progn
(meta-p-output (format-event (make-act-r-event
:mstime (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))
:module "------"
:model '-
:details "Stopped because end time already passed"
:output t
:mp nil)))
(values 0 0 nil))
(flet ((test (mp next-time count)
(declare (ignore count) (ignore mp))
(> next-time ms-end-time)))
(if (current-model)
(schedule-event ms-end-time 'dummy-event-function
:maintenance t :priority :min
:details "A dummy event to guarantee a run until time"
:time-in-ms t
:output nil)
(with-model-eval (first (mp-models)) ;; just pick the first one
(schedule-event ms-end-time 'dummy-event-function
:maintenance t
:priority :min
:details "A dummy event to guarantee a run until time"
:time-in-ms t
:output nil)))
(multiple-value-bind (time events break)
(run-sched-queue mp #'test :real-time real-time)
(unless break
(meta-p-output (format-event (make-act-r-event
:mstime (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))
:module "------"
:model '-
:details "Stopped because time limit reached"
:output t
:mp nil))))
(values (ms->seconds time) events break))))))))
(add-act-r-command "run-until-time" 'run-until-time "Run the ACT-R scheduler up to the indicated time. Params: end-time {real-time}." "Only one run allowed at a time")
(defun run-n-events (event-count &optional (real-time nil))
(indicate-running
(if (not (and (numberp event-count) (> event-count 0)))
(print-warning "event-count must be a number greater than zero.")
(flet ((test (mp next-time count)
(declare (ignore next-time) (ignore mp))
(= count event-count)))
(let ((mp (current-mp)))
(multiple-value-bind (time events break)
(run-sched-queue (current-mp) #'test :real-time real-time)
(unless break
(if (< events event-count)
(meta-p-output (format-event (make-act-r-event
:mstime (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))
:module "------"
:model '-
:details "Stopped because no events to process"
:output t
:mp nil)))
(meta-p-output (format-event (make-act-r-event
:mstime (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))
:module "------"
:model '-
:details "Stopped because event limit reached"
:output t
:mp nil)))))
(values (ms->seconds time) events break)))))))
(add-act-r-command "run-n-events" 'run-n-events "Run the indicated number of events from the ACT-R scheduler. Params: event-count {real-time}." "Only one run allowed at a time")
(defun run-step ()
(indicate-running
(flet ((test (mp next-time count)
;; the schedule-lock is held already while test is evaluated
(declare (ignore next-time count))
(loop
(when (null (meta-p-events mp))
(format t "No more events to process")
(return t))
(format t "Next Event: ~A~%"
(let ((next (car (meta-p-events mp))))
(format-event next)))
(format t "[A]bort (or [q]uit)~%")
(format t "[D]elete~%")
(format t "[S]how event queue~%")
(format t "[W]aiting events~%")
(format t "[B]uffer contents~%")
(format t "[V]isicon~%")
(format t "[R]eport buffer status~%")
(format t "[E]xecute~%")
(let ((response (read )))
(case response
((a q) (return t))
(e (return nil))
(s (mp-show-queue))
(w (mp-show-waiting))
(b (show-buffer-chunks))
(v (print-visicon))
(r (buffer-status))
(d (pop (meta-p-events mp))))))))
(let ((mp (current-mp)))
(multiple-value-bind (time events break)
(run-sched-queue mp #'test :real-time nil)
(unless break
(meta-p-output (format-event (make-act-r-event
:mstime (bt:with-recursive-lock-held ((meta-p-schedule-lock mp)) (meta-p-time mp))
:module "------"
:model '-
:details "Stepping stopped"
:output t
:mp nil))))
(values (ms->seconds time) events break))))))
(defun internal-dummy-event-fn (&rest r)
(declare (ignore r)))
(defun schedule-event (time action
&key (maintenance nil)
(module :none) (destination nil)
(priority 0) (params nil)
(details nil) (output t)
(time-in-ms nil)
(precondition nil))
(verify-current-model
"schedule-event called with no current model."
(let ((mp (current-mp)))
(cond ((not (and (numberp time) (>= time 0)))
(print-warning "Time must be non-negative number."))
((not (local-or-remote-function-or-nil action))
(print-warning "Can't schedule ~S because it is not a valid command identifier." action))
((and (symbolp action) (macro-function action))
(print-warning "Can't schedule ~S because it is a macro and not a function." action))
((not (or (numberp priority) (eq priority :min) (eq priority :max)))
(print-warning "Priority must be a number or :min or :max."))
((not (listp params))
(print-warning "params must be a list."))
((and time-in-ms (not (integerp time)))
(print-warning "When time-in-ms is true the time must be an integer."))
((and precondition (not maintenance))
(print-warning "Only maintenance events may have a precondition."))
((or (and precondition (not (local-or-remote-function-p precondition)))
(and (symbolp precondition) (macro-function precondition)))
(print-warning "Precondition must be a function, but ~s provided." precondition))
(t
(let ((new-event (funcall (if maintenance
#'make-act-r-maintenance-event
#'make-act-r-event)
:mp nil
:model (current-model-struct)
:module module
:mstime (if time-in-ms time (safe-seconds->ms time 'sechedule-event))
:priority (if (numberp priority) priority 0)
:min (and (eq priority :min) priority)
:max (and (eq priority :max) priority)
:action (if action action 'internal-dummy-event-fn)
:params params
:details details
:output output
:precondition precondition
:destination destination)))
(insert-queue-event mp new-event)
(act-r-event-num new-event)))))))
(defun external-schedule-event (time action &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-event '(:params :module :destination :priority :maintenance :output :time-in-ms :details :precondition))
(when valid
(apply 'schedule-event time action (convert-options-list-items ol '(:module :destination :priority :output) nil)))))
(add-act-r-command "schedule-event" 'external-schedule-event
"Create an event to occur at the specified time. Params: time action { < params, module, destination, priority, maintenance, output, time-in-ms, details, precondition > }."
nil)
(defun schedule-event-relative (time-delay action
&key (maintenance nil)
(module :none) (destination nil)
(priority 0) (params nil)
(details nil) (output t)
(time-in-ms nil)
(precondition nil))
(verify-current-model
"schedule-event-relative called with no current model."
(let ((mp (current-mp)))
(cond ((not (and (numberp time-delay) (>= time-delay 0)))
(print-warning "Time-delay must be non-negative number."))
((not (local-or-remote-function-or-nil action))
(print-warning "Can't schedule ~S because it is not a valid command identifier." action))
((and (symbolp action) (macro-function action))
(print-warning "Can't schedule ~S because it is a macro and not a function." action))
((not (or (numberp priority) (eq priority :min) (eq priority :max)))
(print-warning "Priority must be a number or :min or :max."))
((not (listp params))
(print-warning "params must be a list."))
((and time-in-ms (not (integerp time-delay)))
(print-warning "When time-in-ms is true the time-delay must be an integer."))
((and precondition (not maintenance))
(print-warning "Only maintenance events may have a precondition."))
((or (and precondition (not (local-or-remote-function-p precondition)))
(and (symbolp precondition) (macro-function precondition)))
(print-warning "Precondition must be a function, but ~s provided." precondition))
(t
(let ((new-event
(funcall (if maintenance
#'make-act-r-maintenance-event
#'make-act-r-event)
:mp nil
:model (current-model-struct)
:module module
:priority (if (numberp priority) priority 0)
:min (and (eq priority :min) priority)
:max (and (eq priority :max) priority)
:action (if action action 'internal-dummy-event-fn)
:params params
:details details
:output output
:precondition precondition
:destination destination)))
(insert-queue-event mp new-event :delta (if time-in-ms time-delay (safe-seconds->ms time-delay 'schedule-event-relative)))
(act-r-event-num new-event)))))))
(defun external-schedule-event-relative (delta-time action &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-event-relative '(:params :module :destination :priority :maintenance :output :time-in-ms :details :precondition))
(when valid
(apply 'schedule-event-relative delta-time action (convert-options-list-items ol '(:module :destination :priority :output) nil)))))
(add-act-r-command "schedule-event-relative" 'external-schedule-event-relative
"Create an event to occur at the specified amount of time from now. Params: time-delay action { < params, module, destination, priority, maintenance, output, time-in-ms, details, precondition > }."
nil)
(defun schedule-event-now (action &key (maintenance nil)
(module :none) (destination nil)
(priority 0) (params nil)
(details nil) (output t)
(precondition nil))
(verify-current-model
"schedule-event-now called with no current model."
(let ((mp (current-mp)))
(cond ((not (local-or-remote-function-or-nil action))
(print-warning "Can't schedule ~S because it is not a valid command identifier." action))
((and (symbolp action) (macro-function action))
(print-warning "Can't schedule ~S because it is a macro and not a function." action))
((not (or (numberp priority) (eq priority :min) (eq priority :max)))
(print-warning "Priority must be a number or :min or :max."))
((not (listp params))
(print-warning "params must be a list."))
((and precondition (not maintenance))
(print-warning "Only maintenance events may have a precondition."))
((or (and precondition (not (local-or-remote-function-p precondition)))
(and (symbolp precondition) (macro-function precondition)))
(print-warning "Precondition must be a function, but ~s provided." precondition))
(t
(let ((new-event
(funcall (if maintenance
#'make-act-r-maintenance-event
#'make-act-r-event)
:mp nil
:model (current-model-struct)
:module module
:priority (if (numberp priority) priority 0)
:min (and (eq priority :min) priority)
:max (and (eq priority :max) priority)
:action (if action action 'internal-dummy-event-fn)
:params params
:details details
:output output
:precondition precondition
:destination destination)))
(insert-queue-event mp new-event :now t)
(act-r-event-num new-event)))))))
(defun external-schedule-event-now (action &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-event-now '(:params :module :destination :priority :maintenance :output :details :precondition))
(when valid
(apply 'schedule-event-now action (convert-options-list-items ol '(:module :destination :priority :output) nil)))))
(add-act-r-command "schedule-event-now" 'external-schedule-event-now
"Create an event to occur at the current time. Params: time-delay action { < params, module, destination, priority, maintenance, output, details, precondition > }."
nil)
(defun schedule-event-after-module (after-module action
&key (maintenance nil)
(module :none) (destination nil)
(params nil) (details nil)
(output t) (delay t)
(include-maintenance nil)
(dynamic nil)
(precondition nil))
(verify-current-model
"schedule-event-after-module called with no current model."
(let ((mp (current-mp)))
(cond ((not (valid-module-name after-module))
(print-warning "after-module must name a module."))
((not (local-or-remote-function-or-nil action))
(print-warning "Can't schedule ~S because it is not a valid command identifier." action))
((and (symbolp action) (macro-function action))
(print-warning "Can't schedule ~S because it is a macro and not a function." action))
((not (listp params))
(print-warning "params must be a list."))
((and precondition (not maintenance))
(print-warning "Only maintenance events may have a precondition."))
((or (and precondition (not (local-or-remote-function-p precondition)))
(and (symbolp precondition) (macro-function precondition)))
(print-warning "Precondition must be a function, but ~s provided." precondition))
(t
(let* ((new-event
(funcall (if maintenance
#'make-act-r-maintenance-event
#'make-act-r-event)
:mp nil
:model (current-model-struct)
:module module
:min :min
:action (if action action 'internal-dummy-event-fn)
:params params
:details details
:output output
:precondition precondition
:destination destination
:dynamic dynamic
:wait-condition
(list :module after-module
include-maintenance))))
(insert-waiting-event mp new-event delay)
(act-r-event-num new-event)))))))
(defun external-schedule-event-after-module (after-module action &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-event-after-module '(:params :module :destination :maintenance :output :details :precondition :delay :include-maintenance :dynamic))
(when valid
(apply 'schedule-event-after-module (string->name after-module) action (convert-options-list-items ol '(:module :destination :output :delay) nil)))))
(add-act-r-command "schedule-event-after-module" 'external-schedule-event-after-module
"Create an event to occur after the next event for the named module. Params: after-module action {< params, module, destination, maintenance, output, details, precondition, delay, include-maintenance, dynamic > }"
nil)
(defun schedule-event-after-change (action
&key (maintenance nil)
(module :none) (destination nil)
(params nil) (details nil)
(output t) (delay t)
(include-maintenance nil)
(dynamic nil)
(precondition nil))
(verify-current-model
"schedule-event-after-change called with no current model."
(let ((mp (current-mp)))
(cond ((not (local-or-remote-function-or-nil action))
(print-warning "Can't schedule ~S because it is not a valid command identifier." action))
((and (symbolp action) (macro-function action))
(print-warning "Can't schedule ~S because it is a macro and not a function." action))
((not (listp params))
(print-warning "params must be a list."))
((and precondition (not maintenance))
(print-warning "Only maintenance events may have a precondition."))
((or (and precondition (not (local-or-remote-function-p precondition)))
(and (symbolp precondition) (macro-function precondition)))
(print-warning "Precondition must be a function, but ~s provided." precondition))
(t
(let* ((new-event
(funcall (if maintenance
#'make-act-r-maintenance-event
#'make-act-r-event)
:mp nil
:model (current-model-struct)
:module module
:min :min
:action (if action action 'internal-dummy-event-fn)
:params params
:details details
:output output
:precondition precondition
:destination destination
:dynamic dynamic
:wait-condition (list :any include-maintenance))))
(insert-waiting-event mp new-event delay)
(act-r-event-num new-event)))))))
(defun external-schedule-event-after-change (action &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-event-after-change '(:params :module :destination :maintenance :output :details :precondition :delay :include-maintenance :dynamic))
(when valid
(apply 'schedule-event-after-change action (convert-options-list-items ol '(:module :destination :output :delay) nil)))))
(add-act-r-command "schedule-event-after-change" 'external-schedule-event-after-change
"Create an event to occur after the next event. Params: action {< params, module, destination, maintenance, output, details, precondition, delay, include-maintenance, dynamic > }"
nil)
(defun schedule-periodic-event (period action
&key (maintenance nil)
(module :none) (destination nil)
(priority 0) (params nil)
(details nil) (output t)
(initial-delay 0)
(time-in-ms nil))
(verify-current-model
"schedule-event called with no current model."
(let ((mp (current-mp)))
(cond ((not (and (numberp period) (> period 0)))
(print-warning "period must be greater than 0."))
((not (and (numberp initial-delay) (>= initial-delay 0)))
(print-warning "initial-dealy must be a non-negative number."))
((not (local-or-remote-function-or-nil action))
(print-warning "Can't schedule ~S because it is not a valid command identifier." action))
((and (symbolp action) (macro-function action))
(print-warning "Can't schedule ~S because it is a macro and not a function." action))
((not (or (numberp priority) (eq priority :min) (eq priority :max)))
(print-warning "Priority must be a number or :min or :max."))
((not (listp params))
(print-warning "params must be a list."))
((and time-in-ms (or (not (integerp period)) (not (integerp initial-delay))))
(print-warning "When time-in-ms is true the period and initial-delay must be integers."))
(t
(let* ((real-event (funcall (if maintenance
#'make-act-r-maintenance-event
#'make-act-r-event)
:mp nil
:model (current-model-struct)
:module module
:max :max
:action (if action action 'internal-dummy-event-fn)
:params params
:details details
:output output
:destination destination))
(id (bt:with-lock-held (*periodic-event-lock*)
(incf *periodic-event-id-counter*)))
(periodic-event
(make-act-r-periodic-event
:id id
:mp nil
:module :none
:model (current-model-struct)
:priority (if (numberp priority) priority 0)
:min (and (eq priority :min) priority)
:max (and (eq priority :max) priority)
:action 'periodic-action
:output nil
:details
;(format nil
; "Periodic Action: ~A Period: ~A" action period)
(concatenate 'string
"Periodic-Action "
(if (and (symbolp action) (fboundp action)) (symbol-name action) (if (stringp action) action "Unnamed function"))
" "
(princ-to-string period)))))
(insert-queue-event mp periodic-event :delta (if time-in-ms initial-delay (safe-seconds->ms initial-delay 'schedule-periodic-event)))
(setf (act-r-event-params periodic-event)
(list periodic-event real-event (if time-in-ms period (safe-seconds->ms period 'schedule-periodic-event))))
(setf (act-r-event-num real-event) (act-r-event-num periodic-event))
(act-r-event-num periodic-event)))))))
(defun periodic-action (periodic-event real-event period)
(let ((mp (current-mp)))
(bt:with-recursive-lock-held ((meta-p-schedule-lock mp))
(setf (act-r-event-mstime real-event) (act-r-event-mstime periodic-event))
(insert-queue-event mp real-event)
(setf (act-r-event-mstime periodic-event) (+ (act-r-event-mstime periodic-event) period))
(insert-queue-event mp periodic-event))))
(defun external-schedule-periodic-event (period action &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-periodic-event '(:params :module :destination :maintenance :output :details :priority :time-in-ms :initial-delay))
(when valid
(apply 'schedule-periodic-event period action (convert-options-list-items ol '(:module :destination :output :priority) nil)))))
(add-act-r-command "schedule-periodic-event" 'external-schedule-periodic-event
"Create an event to occur repeatedly with the given period. Params: period action {< params, module, destination, maintenance, output, details, priority, time-in-ms, initial-delay > }"
nil)
(defun schedule-break (time &key (priority :max) (details nil)(time-in-ms nil))
(let ((mp (current-mp)))
(cond ((not (and (numberp time) (>= time 0)))
(print-warning "Time must be non-negative number."))
((not (or (numberp priority) (eq priority :min) (eq priority :max)))
(print-warning "Priority must be a number or :min or :max."))
((and time-in-ms (not (integerp time)))
(print-warning "When time-in-ms is true the time must be an integer."))
(t
(let ((new-event (make-act-r-break-event :mp nil
:mstime (if time-in-ms time (safe-seconds->ms time 'schedule-break))
:params (list mp)
:priority (if (numberp priority) priority 0)
:min (and (eq priority :min) priority)
:max (and (eq priority :max) priority)
:details details)))
(insert-queue-event mp new-event)
(act-r-event-num new-event))))))
(defun external-schedule-break (time &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-break '(:priority :time-in-ms :details))
(when valid
(apply 'schedule-break time (convert-options-list-items ol '(:priority) nil)))))
(add-act-r-command "schedule-break" 'external-schedule-break
"Create a break event to force the current run to stop at the time indicated. Params: time {< details, priority, time-in-ms > }"
nil)
(defun schedule-break-relative (time-delay &key (priority :max) (details nil)(time-in-ms nil))
(let ((mp (current-mp)))
(cond ((not (and (numberp time-delay) (>= time-delay 0)))
(print-warning "Time-delay must be non-negative number."))
((not (or (numberp priority) (eq priority :min) (eq priority :max)))
(print-warning "Priority must be a number or :min or :max."))
((and time-in-ms (not (integerp time-delay)))
(print-warning "When time-in-ms is true the time-delay must be an integer."))
(t
(let ((new-event (make-act-r-break-event
:mp nil
:params (list mp)
:priority (if (numberp priority) priority 0)
:min (and (eq priority :min) priority)
:max (and (eq priority :max) priority)
:details details)))
(insert-queue-event mp new-event :delta (if time-in-ms time-delay (safe-seconds->ms time-delay 'schedule-break-relative)))
(act-r-event-num new-event))))))
(defun external-schedule-break-relative (time-delay &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-break-relative '(:priority :time-in-ms :details))
(when valid
(apply 'schedule-break-relative time-delay (convert-options-list-items ol '(:priority) nil)))))
(add-act-r-command "schedule-break-relative" 'external-schedule-break-relative
"Create a break event to force the current run to stop after the specified amount of time. Params: time-delay {< details, priority, time-in-ms > }"
nil)
(defun schedule-break-after-module (after-module &key (details nil) (delay t)(dynamic nil))
(verify-current-model
"schedule-break-after-module called with no current model."
(let ((mp (current-mp)))
(cond ((not (valid-module-name after-module))
(print-warning "after-module must name a module."))
(t
(let* ((new-event (make-act-r-break-event
:mp nil
:model (current-model-struct)
:min :min
:params (list mp)
:details details
:dynamic dynamic
:wait-condition
(list :module after-module t))))
(insert-waiting-event mp new-event delay)
(act-r-event-num new-event)))))))
(defun external-schedule-break-after-module (after-module &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'schedule-break-after-module '(:delay :dynamic :details))
(when valid
(apply 'schedule-break-after-module after-module ol))))
(add-act-r-command "schedule-break-after-module" 'external-schedule-break-after-module
"Create a break event to force the current run to stop after the specified module's next action. Params: after-module {< details, delay, dynamic > }"
nil)
(defun schedule-break-after-all (&optional (details nil))
(let* ((mp (current-mp))
(new-event (make-act-r-break-event :mp nil
:params (list mp)
:min :min
:details details)))
(insert-final-queue-event mp new-event)
(act-r-event-num new-event)))
(add-act-r-command "schedule-break-after-all" 'schedule-break-after-all
"Create a break event to force the current run to stop after the last event currently scheduled. Params: {details}"
nil)
(defun add-pre-event-hook (hook-fn &optional (warn t))
(verify-current-mp
"add-pre-event-hook called with no current meta-process"
(let ((mp (current-mp)))
(bt:with-lock-held ((meta-p-event-hook-lock mp))
(cond ((not (local-or-remote-function-p hook-fn))
(print-warning
"parameter ~s to add-pre-event-hook is not a function" hook-fn))
((member hook-fn (meta-p-pre-events mp))
(when warn
(print-warning
"~s is already on the pre-event-hook list not added again"
hook-fn)))
(t (push hook-fn (meta-p-pre-events mp))
(setf (gethash (meta-p-next-hook-id mp) (meta-p-hook-table mp))
(cons :pre hook-fn))
(1- (incf (meta-p-next-hook-id mp)))))))))
(add-act-r-command "add-pre-event-hook" 'add-pre-event-hook "Add a command to be called before each event is evaluated. Params: command {warn}")
(defun add-post-event-hook (hook-fn &optional (warn t))
(verify-current-mp
"add-post-event-hook called with no current meta-process"
(let ((mp (current-mp)))
(bt:with-lock-held ((meta-p-event-hook-lock mp))
(cond ((not (local-or-remote-function-p hook-fn))
(print-warning
"parameter ~s to add-post-event-hook is not a function" hook-fn))
((member hook-fn (meta-p-post-events mp))
(when warn
(print-warning
"~s is already on the post-event-hook list not added again"
hook-fn)))
(t (push hook-fn (meta-p-post-events mp))
(setf (gethash (meta-p-next-hook-id mp) (meta-p-hook-table mp))
(cons :post hook-fn))
(1- (incf (meta-p-next-hook-id mp)))))))))
(add-act-r-command "add-post-event-hook" 'add-post-event-hook "Add a command to be called after each event is evaluated. Params: command {warn}")
(defun delete-event-hook (hook-fn-id)
(verify-current-mp
"delete-event-hook called with no current meta-process"
(let ((mp (current-mp)))
(bt:with-lock-held ((meta-p-event-hook-lock mp))
(let ((event (gethash hook-fn-id (meta-p-hook-table mp))))
(when event
(remhash hook-fn-id (meta-p-hook-table mp))
(if (eq :pre (car event))
(setf (meta-p-pre-events mp)
(remove (cdr event) (meta-p-pre-events mp)))
(setf (meta-p-post-events mp)
(remove (cdr event) (meta-p-post-events mp))))
(cdr event)))))))
(add-act-r-command "delete-event-hook" 'delete-event-hook "Remove a previously added event hook command. Params: event-hook-id")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 93,326 | Common Lisp | .lisp | 1,532 | 46.934073 | 232 | 0.528633 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 3acc28a9fcf07b0a1966a9c3f233c811135189704bf7e258512e2b9ec7b82c95 | 14,315 | [
-1
] |
14,316 | generic-interface.lisp | asmaloney_ACT-R/framework/generic-interface.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Address : Carnegie Mellon University
;;; : Psychology Department
;;; : Pittsburgh,PA 15213-3890
;;; : [email protected]
;;;
;;; Copyright : (c)2001-2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : generic-interface.lisp
;;; Version : 1.0a1
;;;
;;; Description : Functions for RPM other than with MCL or ACL.
;;;
;;; Bugs :
;;; --- History ---
;;; 01.05.31 Dan Bothell
;;; : Created for use with LispWorks and hopefully other lisps.
;;; 02.06.21 Dan
;;; : Removed the rmp-window class because it's now in the
;;; : virtual-view file.
;;; 04.04.13 Dan [2.2]
;;; : Changed the copyright notice and added the LGPL stuff.
;;;
;;; 04.10.19 Dan [Moved into ACT-R 6]
;;; : Reset the version to 1.0a1
;;; : added the packaging switches
;;; 2015.12.17 Dan
;;; : * Changed the name of the key at 19,2 from esc to clear to
;;; : actually match the reference image since the model now has
;;; : keypad actions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Even though LispWorks allows things like #\f1 I'm using symbols
;;; for everything that's not "normal" so as to hopefully make
;;; it general enough.
(defmethod populate-loc-to-key-array ((ar array))
"Sets all the keys in the array that need to be set"
;; function key row
(setf (aref ar 0 0) 'ESC)
(setf (aref ar 2 0) 'f1)
(setf (aref ar 3 0) 'f2)
(setf (aref ar 4 0) 'f3)
(setf (aref ar 5 0) 'f4)
(setf (aref ar 7 0) 'f5)
(setf (aref ar 8 0) 'f6)
(setf (aref ar 9 0) 'f7)
(setf (aref ar 10 0) 'f8)
(setf (aref ar 12 0) 'f9)
(setf (aref ar 13 0) 'f10)
(setf (aref ar 14 0) 'f11)
(setf (aref ar 15 0) 'f12)
(setf (aref ar 17 0) 'print-screen)
(setf (aref ar 18 0) 'scroll-lock)
(setf (aref ar 19 0) 'pause)
;; numeric key row
(setf (aref ar 0 2) #\tab)
(setf (aref ar 1 2) #\1)
(setf (aref ar 2 2) #\2)
(setf (aref ar 3 2) #\3)
(setf (aref ar 4 2) #\4)
(setf (aref ar 5 2) #\5)
(setf (aref ar 6 2) #\6)
(setf (aref ar 7 2) #\7)
(setf (aref ar 8 2) #\8)
(setf (aref ar 9 2) #\9)
(setf (aref ar 10 2) #\0)
(setf (aref ar 11 2) #\-)
(setf (aref ar 12 2) #\=)
(setf (aref ar 13 2) 'Delete)
(setf (aref ar 15 2) 'help)
(setf (aref ar 16 2) 'home)
(setf (aref ar 17 2) 'pageup)
(setf (aref ar 19 2) 'clear)
(setf (aref ar 20 2) #\=)
(setf (aref ar 21 2) #\/)
(setf (aref ar 22 2) #\*)
;; qwerty row
(setf (aref ar 0 3) #\Tab)
(setf (aref ar 1 3) #\q)
(setf (aref ar 2 3) #\w)
(setf (aref ar 3 3) #\e)
(setf (aref ar 4 3) #\r)
(setf (aref ar 5 3) #\t)
(setf (aref ar 6 3) #\y)
(setf (aref ar 7 3) #\u)
(setf (aref ar 8 3) #\i)
(setf (aref ar 9 3) #\o)
(setf (aref ar 10 3) #\p)
(setf (aref ar 11 3) #\[)
(setf (aref ar 12 3) #\])
(setf (aref ar 13 3) #\\)
(setf (aref ar 15 3) 'DEL)
(setf (aref ar 16 3) 'End)
(setf (aref ar 17 3) 'Page)
(setf (aref ar 19 3) #\7)
(setf (aref ar 20 3) #\8)
(setf (aref ar 21 3) #\9)
(setf (aref ar 22 3) #\-)
;; ASDF row
(setf (aref ar 0 4) 'caps-lock)
(setf (aref ar 1 4) #\a)
(setf (aref ar 2 4) #\s)
(setf (aref ar 3 4) #\d)
(setf (aref ar 4 4) #\f)
(setf (aref ar 5 4) #\g)
(setf (aref ar 6 4) #\h)
(setf (aref ar 7 4) #\j)
(setf (aref ar 8 4) #\k)
(setf (aref ar 9 4) #\l)
(setf (aref ar 10 4) #\;)
(setf (aref ar 11 4) #\')
(setf (aref ar 12 4) #\Newline)
(setf (aref ar 13 4) #\Newline)
(setf (aref ar 19 4) #\4)
(setf (aref ar 20 4) #\5)
(setf (aref ar 21 4) #\6)
(setf (aref ar 22 4) #\+)
;; Z row
(setf (aref ar 0 5) 'shift)
(setf (aref ar 1 5) #\z)
(setf (aref ar 2 5) #\x)
(setf (aref ar 3 5) #\c)
(setf (aref ar 4 5) #\v)
(setf (aref ar 5 5) #\b)
(setf (aref ar 6 5) #\n)
(setf (aref ar 7 5) #\m)
(setf (aref ar 8 5) #\,)
(setf (aref ar 9 5) #\.)
(setf (aref ar 10 5) #\/)
(setf (aref ar 11 5) 'shift)
(setf (aref ar 12 5) 'shift)
(setf (aref ar 16 5) 'UpArrow)
(setf (aref ar 19 5) #\1)
(setf (aref ar 20 5) #\2)
(setf (aref ar 21 5) #\3)
(setf (aref ar 22 5) 'enter)
;; space bar row
(setf (aref ar 0 6) 'control)
(setf (aref ar 1 6) 'option)
(setf (aref ar 2 6) 'command)
(setf (aref ar 3 6) #\Space)
(setf (aref ar 4 6) #\Space)
(setf (aref ar 5 6) #\Space)
(setf (aref ar 6 6) #\Space)
(setf (aref ar 7 6) #\Space)
(setf (aref ar 8 6) #\Space)
(setf (aref ar 9 6) #\Space)
(setf (aref ar 10 6) #\Space)
(setf (aref ar 11 6) 'command)
(setf (aref ar 12 6) 'option)
(setf (aref ar 13 6) 'control)
(setf (aref ar 15 6) 'BackArrow)
(setf (aref ar 16 6) 'DownArrow)
(setf (aref ar 17 6) 'ForwardArrow)
(setf (aref ar 19 6) #\0)
(setf (aref ar 20 6) #\0)
(setf (aref ar 21 6) #\.)
(setf (aref ar 22 6) 'enter)
ar)
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 6,063 | Common Lisp | .lisp | 180 | 31.222222 | 80 | 0.570043 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d88e287cbe13ca2dce43cff1e99f8bb2033bed05475c7ada2e8a7d3bb8ff1167 | 14,316 | [
-1
] |
14,317 | printing.lisp | asmaloney_ACT-R/framework/printing.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : printing.lisp
;;; Version : 2.0
;;;
;;; Description : Module that provides model output control.
;;;
;;; Bugs :
;;;
;;; To do : [ ] * Add a warning level parameter and handling.
;;; : [ ] * Consider using the ACT-R logical host as the default for
;;; : when a string of name only is used for a trace instead of
;;; : just letting the system defaults kick in.
;;;
;;; ----- History -----
;;;
;;; 2004.09.17 Dan
;;; : Creation
;;; 2005.01.17 Dan
;;; : * Added the :cmdt parameter to handle outputting of commands
;;; : independently of other model output.
;;; 2005.01.18 Dan
;;; : * Moved the printing-module structure to internal-structures.
;;; 2005.01.27 Dan
;;; : * Updated the version to 1.0a3.
;;; : * Added the :trace-filter parameter and the function
;;; : production-firing-only as a possible filter.
;;; : * Added the function filter-output-events which uses the
;;; : trace-filter to determine whether to output info or not.
;;; 2005.02.02 Dan
;;; : * Added the :trace-detail parameter to control how much
;;; : gets printed in the trace - depends on the new specification
;;; : of the event's output parameter.
;;; 2005.02.03 Dan
;;; : * Moved production-firing-only to the procedural-cmds file.
;;; 2005.02.21 Dan
;;; : * Cleared the to do that was completed and added a new one.
;;; 2005.02.28 Dan
;;; : * Fixed a bug in the reseting when an output stream was a
;;; : file.
;;; 2005.04.19 Dan
;;; : * Added event-displayed-p as a user function for events.
;;; 2005.05.11 Dan
;;; : * Changed the default for trace-detail to medium because
;;; : it's been bulked up and may be more reasonable as the
;;; : general trace.
;;; 2005.09.08 Dan
;;; : * Added the :model-warnings parameter to suppress all "model-
;;; : warning" calls.
;;; 2006.01.17 Dan
;;; : * Updated the version to 1.0 since there haven't been any
;;; : recent problems it's time to drop the "a".
;;; 2006.01.18 Dan
;;; : * Adding a new paramter :show-all-slots to allow one to hide
;;; : "unset" extended slots in chunks if desired (the default
;;; : is to hide them).
;;; 2006.07.17 Dan
;;; : * Added a with-model-fct to filter-output-events so that the
;;; : printing module of the model in which the event was
;;; : generated is used to make the determination instead of the
;;; : current model's.
;;; 2006.07.20 Dan
;;; : * Realized that the change above isn't quite right because
;;; : break events don't have a model, so in that case it just
;;; : uses the "first" model.
;;; 2006.10.11 Dan
;;; : * Realized while doing some profiling on a different change
;;; : that the backqouted code in filter-output-events was really
;;; : slow (in ACL 20+% of the model's time was spent evaluating
;;; : that). I've replaced that with a call to a separate
;;; : function and things seem to be back to better performance.
;;; 2006.10.16 Dan
;;; : * Bug in the last change doesn't work in all Lisps - fixed
;;; : that now (difference between #' and ' for a function name
;;; : that gets passed to eval).
;;; 2007.04.13 Dan
;;; : * Added the :cbct parameter which determines whether or not
;;; : an extra event shows in the trace indicating when a buffer
;;; : copies a chunk to give the old and new names.
;;; 2008.10.30 Dan
;;; : * Added the show-copy-buffer-trace function to avoid needing
;;; : an sgp in the buffer code.
;;; 2010.05.03 Dan
;;; : * Changed filter-test so that it doesn't display ":output 'high"
;;; : events in the medium trace detail level.
;;; 2012.09.21 Dan
;;; : * Set suppress-cmds back to nil upon a reset because apparently
;;; : even with an unwind-protect it's possible for it to get stuck
;;; : somehow.
;;; 2013.08.16 Dan
;;; : * Fix a problem with CCL and the environment which seems like
;;; : it can only be dealt with here (I don't like implementation
;;; : hacks in the main code). By default an opened stream is
;;; : only available to the thread which opens it, but if one sets
;;; : :v or :cmdt to a pathname and then Loads the file through
;;; : the environment in CCL that stream is unavailable to the
;;; : thread which "runs" the model and an error results. The
;;; : fix is to specify :sharing :lock in the open command and
;;; : that has to happen here.
;;; 2014.06.26 Dan
;;; : * More error protection around the setting of :v and :cmdt
;;; : when files/streams are used.
;;; 2014.08.14 Dan
;;; : * The :show-all-slots parameter is unnecessary now.
;;; 2015.06.01 Dan [1.1]
;;; : * Adding a one-time-model-warning command (it's in misc-utils
;;; : with the other output commands) which allows one to specify
;;; : a "tag" for the warning and it will only print a warning
;;; : with a given tag (equal test) the first time it occurs after
;;; : a reset.
;;; 2016.04.11 Dan [1.2]
;;; : * Adding a parameter to have the module save the trace info
;;; : whether or not it's being printed and a command to print
;;; : out a saved trace at any detail level for an optionally
;;; : specified subsegment. For now this is going to be crude and
;;; : just store a list of the formatted output for each event
;;; : since that's easy but costly in terms of space. Some sort
;;; : of caching would probably be better for space (since something
;;; : like conflict-resolution is going to show up a lot) but has
;;; : a bigger time cost since a lookup would have to happen for
;;; : every event.
;;; 2016.04.12 Dan
;;; : * Added a get-saved-trace function to allow access to the data
;;; : without having to print it out or wrap it in a no-output, and
;;; : include the time and output level with that.
;;; 2016.04.13 Dan
;;; : * Fixed a copy-and-paste error in get-saved-trace.
;;; 2016.04.14 Dan
;;; : * Might as well save the event itself and recreate the trace
;;; : after the fact if needed.
;;; : * Don't return the trace items from show-saved-trace since
;;; : get-saved-trace can be used for that -- have each do its
;;; : own thing.
;;; 2016.04.21 Dan
;;; : * Minor improvement to internals of show and get saved-trace.
;;; 2016.09.28 Dan
;;; : * Changed printing-module-event-hook to just be nil or cons since
;;; : there's only one meta-process.
;;; 2017.02.27 Dan
;;; : * Clear the capture warnings flag and any recorded warnings
;;; : when the module is reset. [Clears all of them since it's a
;;; : class allocated slot, but since there's only one mp a reset
;;; : affects all models anyway.]
;;; 2017.06.15 Dan
;;; : * Wrapped the lock around the warning capture clearing for
;;; : thread safety.
;;; : * Make event-displayed-p, filter-events, and filter-output-events
;;; : thread safe.
;;; 2017.06.16 Dan
;;; : * Use the trace lock for access to the saved trace info.
;;; 2017.07.13 Dan
;;; : * Protect the cbct parameter through show-copy-buffer-trace.
;;; 2017.09.19 Dan [1.3]
;;; : * Remove the :save-trace parameter because that functionality
;;; : is being handled by a history stream now outside of the
;;; : module.
;;; 2018.02.05 Dan
;;; : * Allow the :trace-filter parameter to accept a command name
;;; : string.
;;; : * Update event-displayed-p to accept a real event or id, and
;;; : always pass the id to the trace-filter fn.
;;; 2018.02.07 Dan
;;; : * The trace filter needs to get the model name.
;;; 2018.02.22 Dan
;;; : * Add a remote version of event-displayed-p.
;;; 2018.06.14 Dan
;;; : * Updated doc string for event-displayed-p command.
;;; 2019.01.16 Dan
;;; : * Adjust filter-event so it only needs to grab the lock once.
;;; 2019.06.18 Dan
;;; : * Change the ccl hack from :sharing :lock to :sharing :external.
;;; 2020.01.13 Dan [1.4]
;;; : * Removed the #' and lambdas from the module interface.
;;; 2020.06.03 Dan
;;; : * Have the filter-test return the value of v as well so that
;;; : scheduling can skip the model-output immediately if it's
;;; : off.
;;; 2020.07.24 Dan
;;; : * Fixed the problem when :v and :cmdt were both set to files
;;; : because they used separate streams and thus were both
;;; : writing to different positions in the file. Now, if they're
;;; : set to a file/pathname it uses one stream for both.
;;; 2021.10.19 Dan [2.0]
;;; : * Set the required flag on the module.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defun create-printing-module (model-name)
(declare (ignore model-name))
(make-instance 'printing-module))
(defun verify-printing-param (param)
(or (null param) (eq param t) (streamp param) (pathnamep param)
(and (stringp param) (parse-namestring param))))
(defun safe-close-printing-stream (target other cmd)
(if (act-r-output-shared target)
(setf (act-r-output-shared other) nil (act-r-output-shared target) nil)
(multiple-value-bind (result err)
(ignore-errors (close (act-r-output-stream target)))
(when (and err (subtypep (type-of err) 'condition))
(print-warning "Error encountered when trying to close the file associated with the ~s parameter:~% ~s" cmd err))
result)))
(defun safe-open-printing-stream (name target other cmd)
(if (and (act-r-output-file other)
(equalp name (act-r-output-name other)))
;; if it's the same name as the other one
;; indicate they're shared and return the other's stream
(progn
(setf (act-r-output-shared target) t)
(setf (act-r-output-shared other) t)
(setf (act-r-output-name target) name)
(act-r-output-stream other))
(multiple-value-bind (result err)
(ignore-errors (open (parse-namestring name)
:direction :output :if-exists :append
:if-does-not-exist :create
#+:ccl :sharing #+:ccl :external))
(if (and err (subtypep (type-of err) 'condition))
(progn
(setf (act-r-output-name target) nil)
(setf (act-r-output-file target) nil)
(print-warning "Error encountered when trying to open the file associated with the ~s parameter:~% ~s" cmd err)
(print-warning "The ~s parameter is being set to t instead." cmd))
(progn
(setf (act-r-output-name target) name)
))
result)))
(defun printing-module-param (module param)
(bt:with-recursive-lock-held ((printing-module-param-lock module))
(if (consp param)
(case (car param)
(:v
(when (act-r-output-file (printing-module-v module))
(safe-close-printing-stream (printing-module-v module) (printing-module-c module) :v)
(setf (act-r-output-file (printing-module-v module)) nil)
(setf (act-r-output-name (printing-module-v module)) nil))
(setf (act-r-output-stream (printing-module-v module))
(cond ((or (pathnamep (cdr param)) (stringp (cdr param)))
(aif (safe-open-printing-stream (cdr param) (printing-module-v module) (printing-module-c module) :v)
(progn
(setf (act-r-output-file (printing-module-v module)) t)
it)
t))
(t
(setf (act-r-output-file (printing-module-v module)) nil)
(setf (act-r-output-name (printing-module-v module)) nil)
(cdr param)))))
(:cmdt
(when (act-r-output-file (printing-module-c module))
(safe-close-printing-stream (printing-module-c module) (printing-module-v module) :cmdt)
(setf (act-r-output-file (printing-module-c module)) nil)
(setf (act-r-output-name (printing-module-c module)) nil))
(setf (act-r-output-stream (printing-module-c module))
(cond ((or (pathnamep (cdr param)) (stringp (cdr param)))
(aif (safe-open-printing-stream (cdr param) (printing-module-c module) (printing-module-v module) :cmdt)
(progn
(setf (act-r-output-file (printing-module-c module)) t)
it)
t))
(t
(setf (act-r-output-file (printing-module-c module)) nil)
(setf (act-r-output-name (printing-module-c module)) nil)
(cdr param)))))
(:trace-filter
(setf (printing-module-filter module) (cdr param)))
(:trace-detail
(setf (printing-module-detail module) (cdr param)))
(:model-warnings
(setf (printing-module-model-warnings module) (cdr param)))
(:cbct
(setf (printing-module-cbct module) (cdr param)))
)
(case param
(:v (act-r-output-stream (printing-module-v module)))
(:cmdt (act-r-output-stream (printing-module-c module)))
(:trace-filter (printing-module-filter module))
(:trace-detail (printing-module-detail module))
(:model-warnings (printing-module-model-warnings module))
(:cbct (printing-module-cbct module))
))))
(defun reset-printing-module (module)
(bt:with-recursive-lock-held ((printing-module-param-lock module))
(when (act-r-output-file (printing-module-v module))
(close (act-r-output-stream (printing-module-v module)))
(setf (act-r-output-file (printing-module-v module)) nil))
(setf (act-r-output-stream (printing-module-v module)) t)
(when (act-r-output-file (printing-module-c module))
(close (act-r-output-stream (printing-module-c module)))
(setf (act-r-output-file (printing-module-c module)) nil))
(setf (act-r-output-stream (printing-module-c module)) t)
(setf (printing-module-one-time-tags module) nil)
(setf (printing-module-filter module) nil)
(setf (printing-module-detail module) 'high)
(setf (printing-module-suppress-cmds module) nil))
(bt:with-recursive-lock-held ((printing-module-lock module))
(setf (printing-module-capture-warnings module) nil)
(setf (printing-module-captured-warnings module) nil)))
(defun delete-printing-module (module)
(reset-printing-module module))
(defun trace-detail-value-test (x)
(or (eq x 'high)
(eq x 'medium)
(eq x 'low)))
(define-module-fct 'printing-module nil
(list
(define-parameter :v :documentation "Verbose controls model output"
:default-value t
:warning "must be t, nil, a stream, pathname or namestring"
:valid-test 'verify-printing-param)
(define-parameter :cmdt :documentation "Commands trace controls output of commands"
:default-value t
:warning "must be t, nil, a stream, pathname or namestring"
:valid-test 'verify-printing-param)
(define-parameter :trace-filter :documentation "Function to limit output shown in the trace"
:default-value nil
:warning "must be a function, string naming a command, or nil"
:valid-test 'local-or-remote-function-or-nil)
(define-parameter :trace-detail :documentation "Determines which events show in the trace"
:default-value 'medium
:warning "Must be one of high, medium, or low"
:valid-test 'trace-detail-value-test)
(define-parameter :model-warnings :documentation "Whether to output model warnings"
:default-value t
:warning "must be t or nil"
:valid-test 'tornil)
(define-parameter :cbct :documentation "Whether or not to show an event in the trace when a buffer copies a chunk"
:default-value nil
:warning "must be t or nil"
:valid-test 'tornil)
)
:version "2.0"
:documentation "Coordinates output of the model."
:creation 'create-printing-module
:reset 'reset-printing-module
:delete 'delete-printing-module
:params 'printing-module-param
:required t)
(defun filter-output-events (event)
(with-model-eval (if (act-r-event-model event) (act-r-model-name (act-r-event-model event)) (first (mp-models))) ;; just use the first if there isn't one (a break event)
(filter-test event)))
(defun filter-test (event)
(let ((module (get-module printing-module)))
(when module
(let (d f v)
(bt:with-recursive-lock-held ((printing-module-param-lock module))
(setf d (printing-module-detail module))
(setf f (printing-module-filter module))
(setf v (printing-module-v module)))
(values
(and (case d
(low (eq (act-r-event-output event) 'low))
(medium (or (eq (act-r-event-output event) 'low)
(eq (act-r-event-output event) 'medium)))
(high t))
(or (null f)
(dispatch-apply f (act-r-event-num event))))
v)))))
(defun event-displayed-p (evt)
(let ((event (if (act-r-event-p evt) evt (get-event-by-id evt))))
(and event
(act-r-event-output event)
(filter-output-events event))))
(add-act-r-command "event-displayed-p" 'event-displayed-p "Return whether the specified event will be shown in the trace based on its output value, the current trace detail, and the current trace filter. Params: event-id")
(defun show-copy-buffer-trace ()
(let ((module (get-module printing-module)))
(bt:with-recursive-lock-held ((printing-module-param-lock module))
(printing-module-cbct module))))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 20,885 | Common Lisp | .lisp | 411 | 45.793187 | 222 | 0.584488 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6abcba9801fae14d49404cb759803bfaa9baa2800fd8230ebb9d04c19044ca0b | 14,317 | [
-1
] |
14,318 | vision-categorization.lisp | asmaloney_ACT-R/framework/vision-categorization.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author Mike Byrne
;;; Address : Rice University, MS-25
;;; : Psychology Department
;;; : Houston,TX 77251-1892
;;; : [email protected]
;;;
;;; Copyright : (c)1998-2001 Mike Byrne
;;; Availability: Covered by the GNU LGPL, see LICENSE.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename vision-categorization.lisp
;;; Version 1.0
;;;
;;; Description Class and constants for different feature sets.
;;;
;;; Bugs
;;;
;;; Todo
;;;
;;; ----- History -----
;;; 99.06.10 Mike Byrne
;;; Header date.
;;; 99.07.30 mdb
;;; Added GETFEATS.
;;; 99.08.08 mdb
;;; : Removed keywords from feature lists, added PROB-BEST-CHAR.
;;; 99.09.08 mdb
;;; : Corrected RM set from Mike Matessa's comments.
;;; 00.06.09 mdb
;;; : Conversion of "new-feats.lisp" file to
;;; : "vision-categorization" for inclusion in RPM 2.0.
;;; 01.06.29 mdb
;;; : Added defgenerics and doc strings.
;;;
;;; 04.10.19 Dan [Moved into ACT-R 6]
;;; : Reset the version to 1.0a1
;;; : added the packaging switches
;;; 2006.01.03 Dan
;;; : * Removed the package from the mode line at the top.
;;; 2007.12.07 Dan [1.0]
;;; : * Fixed a bug in cliplast because it didn't specify the
;;; : optional parameters before the keywords in read-from-string.
;;; : Which didn't really matter since it was just :start 0
;;; : but it doesn't hurt to be safe and it avoids a warning in LW.
;;; : * Put the :'s in the mode line at the top to avoid a warning
;;; : with LW.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(defclass char-feats ()
((feature-ls :accessor feature-ls :initarg :feat-ls)
(fhash :accessor fhash :initform (make-hash-table :test #'equal))
(letters :accessor letters :allocation :class
:initform '("A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M"
"N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"))
(digits :accessor digits :allocation :class
:initform '("1" "2" "3" "4" "5" "6" "7" "8" "9" "0"))
(average-match-prob :accessor average-match-prob :initform nil)
(name :accessor name :initarg :name :initform nil)
(number-of-features :accessor number-of-features :initform nil)
(true->icon :accessor true->icon :initarg :true->icon :initform #'identity)
))
(defmethod print-object ((self char-feats) stream)
(print-unreadable-object (self stream :type t)
(format stream "~S" (name self))))
(defgeneric numfeats (chr-feat-set)
(:documentation "Return the number of features in the feature set."))
(defmethod numfeats ((self char-feats))
(aif (number-of-features self) it (length (feature-ls self))))
(defgeneric has-match-p (chr-feat-set str1 str2)
(:documentation "Given two letters, return the list of features that appear in both."))
(defmethod has-match-p ((self char-feats) (s1 string) (s2 string))
(intersection (gethash s1 (fhash self)) (gethash s2 (fhash self))))
(defgeneric prob-match (chr-feat-set str1 str2)
(:documentation "Return the probabily that a random feature in s1 will appear in s2."))
(defmethod prob-match ((self char-feats) (s1 string) (s2 string))
(if (string= s1 s2)
-1
(float (/ (length (remove-duplicates (has-match-p self s1 s2)))
(length (gethash s1 (fhash self)))))))
(defgeneric setfeats (chr-feat-set str feat-lst)
(:documentation "Set the feature list for a string (character)."))
(defmethod setfeats ((self char-feats) (s1 string) (feat-ls list))
(setf (gethash s1 (fhash self)) feat-ls))
(defgeneric getfeats (chr-feat-set chr)
(:documentation "Returns the feature list for a character."))
(defmethod getfeats ((self char-feats) (s string))
(gethash s (fhash self)))
(defmethod getfeats ((self char-feats) (c character))
(gethash (mkstr c) (fhash self)))
(defgeneric get-icon-feats (chr-feat-set char)
(:documentation "Return the icon feature list for a given character."))
(defmethod get-icon-feats ((self char-feats) char)
(let ((ti (true->icon self)))
(cond ((functionp ti) (mapcar ti (getfeats self char)))
((listp ti) (mapcar #'(lambda (feat)
(second (assoc feat ti)))
(getfeats self char)))
(t (getfeats self char)))))
(defgeneric exact-character (char-feat-set feat-lst)
(:documentation "Return the character exactly matching a feature set."))
(defmethod exact-character ((self char-feats) (feat-ls list))
(setf feat-ls (mapcar #'sym->key feat-ls))
(let (realfeats)
(dolist (char (chars self))
(setf realfeats (getfeats self char))
(when (= (length realfeats) (length feat-ls)
(length (intersection feat-ls realfeats)))
(return-from exact-character char)))))
(defgeneric prob-best-character (char-feat-set feat-lst)
(:documentation "Return the character with the best probability of match to a feature list."))
(defmethod prob-best-character ((self char-feats) (feat-ls list))
(let ((bestval 0) (bestchar nil) cur-val)
(dolist (char (chars self))
(setf cur-val (feat-ls-prob-match self feat-ls (getfeats self char)))
(when (= cur-val bestval)
(push char bestchar))
(when (> cur-val bestval)
(setf bestval cur-val)
(setf bestchar (mklist char))))
(values (random-item bestchar) (* 100. bestval))))
(defgeneric feat-ls-prob-match (char-feat-set lst1 lst2)
(:documentation "Return the probability that two feature lists represent a match."))
(defmethod feat-ls-prob-match ((self char-feats) (l1 list) (l2 list))
(let* ((overlap (length (remove-duplicates (intersection l1 l2))))
(num-miss (+ (- (length l1) overlap)
(- (length l2) overlap))))
(float (* (expt 2/3 (- (numfeats self) num-miss))
(expt 1/3 num-miss)))))
(defmethod chars ((char-feat-set char-feats))
(append (letters char-feat-set) (digits char-feat-set)))
(defgeneric avg-match-prob (char-feat-set)
(:documentation "Returns the average match probability for an entire feature set."))
(defmethod avg-match-prob ((self char-feats))
(aif (average-match-prob self)
it
(let ((accum))
(dolist (targ (chars self))
(dolist (item (chars self))
(when (not (string= targ item))
(push (prob-match self targ item) accum))))
(setf (average-match-prob self)
(/ (reduce #'+ accum) (length accum))))))
(defgeneric print-match-table (char-feat-set)
(:documentation "Print out a table of matc probabilities."))
(defmethod print-match-table ((self char-feats))
(dolist (targ (append (letters self) (digits self)))
(format t "~%~A " targ)
(dolist (char (append (letters self) (digits self)))
(format t "~3,2F " (prob-match self targ char)))))
(defgeneric print-num-feats (char-feat-set)
(:documentation "Print the number of features for each character."))
(defmethod print-num-feats ((self char-feats))
(dolist (targ (append (letters self) (digits self)))
(format t "~%~A has ~S" targ (length (gethash targ (fhash self))))))
(defgeneric check-integrity (thing)
(:documentation "Check the internal integrity of <thing>."))
(defmethod check-integrity ((self char-feats))
(let ((feat-ls))
(dolist (char (append (letters self) (digits self)))
(setf feat-ls (gethash char (fhash self)))
(awhen (set-difference feat-ls (feature-ls self))
(format t "~&~A has a feature not in the set ~S" char it))
(dolist (item (append (letters self) (digits self)))
(when (and (not (string= char item))
(equal feat-ls (gethash item (fhash self))))
(format t "~&~A and ~A have identical features" char item)))
(let ((bestchar (prob-best-character self feat-ls)))
(when (not (string= char bestchar))
(format t "~&~A has ~A as its best char." char bestchar)))
)))
(defgeneric feature-freq (char-feat-set)
(:documentation "Print the frequency of occurrence for each feature in the set."))
(defmethod feature-freq ((self char-feats))
(let ((counter))
(dolist (feat (feature-ls self))
(setf counter 0)
(dolist (char (chars self))
(when (member feat (gethash char (fhash self)))
(incf counter)))
(format t "~&Feature ~S occurs in ~S chars" feat counter))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; The Gibson (1969) feature set
(defun build-gibson-set ()
"Returns the Gibson (1969) character feature set."
(let ((tmp (make-instance 'char-feats :name :GIBSON :feat-ls
'(HORIZONTAL VERTICAL DIAGONAL-SLASH
DIAGONAL-BACK DIAGONAL-SLASH CLOSED-CURVE
OPEN-V-CURVE OPEN-H-CURVE INTERSECTION
CYCLIC-CHANGE SYMMETRY VERTICAL-DISCONT
HORIZONTAL-DISCONT))))
(setfeats tmp "A" '(SYMMETRY HORIZONTAL DIAGONAL-SLASH DIAGONAL-BACK INTERSECTION VERTICAL-DISCONT))
(setfeats tmp "B" '(SYMMETRY CYCLIC-CHANGE INTERSECTION HORIZONTAL VERTICAL CLOSED-CURVE ))
(setfeats tmp "C" '(SYMMETRY OPEN-H-CURVE ))
(setfeats tmp "D" '(SYMMETRY VERTICAL CLOSED-CURVE ))
(setfeats tmp "E" '(HORIZONTAL-DISCONT SYMMETRY CYCLIC-CHANGE HORIZONTAL VERTICAL INTERSECTION ))
(setfeats tmp "F" '(HORIZONTAL-DISCONT VERTICAL-DISCONT HORIZONTAL VERTICAL INTERSECTION ))
(setfeats tmp "G" '(HORIZONTAL OPEN-H-CURVE ))
(setfeats tmp "H" '(VERTICAL-DISCONT SYMMETRY HORIZONTAL VERTICAL INTERSECTION ))
(setfeats tmp "I" '(VERTICAL-DISCONT SYMMETRY VERTICAL ))
(setfeats tmp "J" '(OPEN-V-CURVE OPEN-H-CURVE ))
(setfeats tmp "K" '(VERTICAL-DISCONT SYMMETRY CYCLIC-CHANGE VERTICAL DIAGONAL-SLASH DIAGONAL-BACK INTERSECTION ))
(setfeats tmp "L" '(HORIZONTAL-DISCONT HORIZONTAL VERTICAL ))
(setfeats tmp "M" '(CYCLIC-CHANGE VERTICAL-DISCONT SYMMETRY VERTICAL DIAGONAL-SLASH DIAGONAL-BACK ))
(setfeats tmp "N" '(VERTICAL-DISCONT VERTICAL DIAGONAL-BACK ))
(setfeats tmp "O" '(SYMMETRY CLOSED-CURVE ))
(setfeats tmp "P" '(VERTICAL-DISCONT INTERSECTION VERTICAL CLOSED-CURVE ))
(setfeats tmp "Q" '(intersection DIAGONAL-BACK CLOSED-CURVE ))
(setfeats tmp "R" '(VERTICAL-DISCONT INTERSECTION VERTICAL DIAGONAL-BACK CLOSED-CURVE ))
(setfeats tmp "S" '(CYCLIC-CHANGE OPEN-H-CURVE ))
(setfeats tmp "T" '(HORIZONTAL-DISCONT VERTICAL-DISCONT SYMMETRY HORIZONTAL VERTICAL INTERSECTION ))
(setfeats tmp "U" '(SYMMETRY OPEN-V-CURVE ))
(setfeats tmp "V" '(SYMMETRY DIAGONAL-SLASH DIAGONAL-BACK ))
(setfeats tmp "W" '(SYMMETRY CYCLIC-CHANGE DIAGONAL-SLASH DIAGONAL-BACK ))
(setfeats tmp "X" '(SYMMETRY INTERSECTION DIAGONAL-SLASH DIAGONAL-BACK ))
(setfeats tmp "Y" '(VERTICAL-DISCONT SYMMETRY VERTICAL DIAGONAL-SLASH DIAGONAL-BACK ))
(setfeats tmp "Z" '(HORIZONTAL-DISCONT HORIZONTAL DIAGONAL-SLASH ))
(setfeats tmp "1" '(HORIZONTAL-DISCONT HORIZONTAL VERTICAL INTERSECTION))
(setfeats tmp "2" '(HORIZONTAL-DISCONT HORIZONTAL OPEN-H-CURVE))
(setfeats tmp "3" '(SYMMETRY OPEN-H-CURVE CYCLIC-CHANGE))
(setfeats tmp "4" '(VERTICAL-DISCONT HORIZONTAL-DISCONT HORIZONTAL VERTICAL DIAGONAL-SLASH INTERSECTION))
(setfeats tmp "5" '(HORIZONTAL-DISCONT HORIZONTAL OPEN-H-CURVE CYCLIC-CHANGE))
(setfeats tmp "6" '(HORIZONTAL-DISCONT CLOSED-CURVE OPEN-H-CURVE))
(setfeats tmp "7" '(VERTICAL-DISCONT HORIZONTAL DIAGONAL-SLASH))
(setfeats tmp "8" '(SYMMETRY CLOSED-CURVE INTERSECTION))
(setfeats tmp "9" '(VERTICAL-DISCONT CLOSED-CURVE OPEN-H-CURVE))
(setfeats tmp "0" '(SYMMETRY CLOSED-CURVE DIAGONAL-SLASH))
tmp))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; The Briggs & Hocevar (1975) feature set
(defun build-bh-set ()
"Returns the Briggs & Hocevar (1975) character feature set."
(let ((tmp (make-instance 'char-feats :name :BRIGGS-HOCEVAR :feat-ls
'(H-TOP H-CENTER H-BOTTOM SINGLE-V DOUBLE-V
ANG-OPEN-TOP ANG-OPEN-DOWN ANG-OPEN-HORIZ
SM-CURVE-CONVEX-RIGHT SM-CURVE-CONVEX-BOTTOM
LARGE-CURVE CONTINUOUS-CURVE CLOSED-CURVE
SM-CURVE-CONVEX-LEFT))))
(setfeats tmp "A" '(H-CENTER ANG-OPEN-DOWN))
(setfeats tmp "B" '(H-TOP H-CENTER H-BOTTOM SINGLE-V SM-CURVE-CONVEX-RIGHT CLOSED-CURVE))
(setfeats tmp "C" '(LARGE-CURVE CONTINUOUS-CURVE ))
(setfeats tmp "D" '(SINGLE-V LARGE-CURVE CLOSED-CURVE))
(setfeats tmp "E" '(H-TOP H-CENTER H-BOTTOM SINGLE-V ))
(setfeats tmp "F" '(H-TOP H-CENTER SINGLE-V ))
(setfeats tmp "G" '(SM-CURVE-CONVEX-RIGHT LARGE-CURVE ))
(setfeats tmp "H" '(H-CENTER DOUBLE-V ))
(setfeats tmp "I" '(SINGLE-V ))
(setfeats tmp "J" '(SINGLE-V SM-CURVE-CONVEX-BOTTOM ))
(setfeats tmp "K" '(SINGLE-V ANG-OPEN-TOP ANG-OPEN-DOWN ANG-OPEN-HORIZ ))
(setfeats tmp "L" '(H-BOTTOM SINGLE-V ))
(setfeats tmp "M" '(DOUBLE-V ANG-OPEN-DOWN ))
(setfeats tmp "N" '(DOUBLE-V ANG-OPEN-TOP ANG-OPEN-DOWN ))
(setfeats tmp "O" '(LARGE-CURVE CONTINUOUS-CURVE CLOSED-CURVE))
(setfeats tmp "P" '(H-TOP H-CENTER SINGLE-V SM-CURVE-CONVEX-RIGHT CLOSED-CURVE))
(setfeats tmp "Q" '(LARGE-CURVE CLOSED-CURVE))
(setfeats tmp "R" '(H-TOP H-CENTER SINGLE-V ANG-OPEN-DOWN SM-CURVE-CONVEX-RIGHT CLOSED-CURVE))
(setfeats tmp "S" '(SM-CURVE-CONVEX-RIGHT CONTINUOUS-CURVE))
(setfeats tmp "T" '(H-TOP SINGLE-V ))
(setfeats tmp "U" '(DOUBLE-V SM-CURVE-CONVEX-BOTTOM ))
(setfeats tmp "V" '(ANG-OPEN-TOP ))
(setfeats tmp "W" '(ANG-OPEN-TOP ANG-OPEN-DOWN ))
(setfeats tmp "X" '(ANG-OPEN-TOP ANG-OPEN-DOWN ANG-OPEN-HORIZ ))
(setfeats tmp "Y" '(SINGLE-V ANG-OPEN-TOP ANG-OPEN-HORIZ ))
(setfeats tmp "Z" '(H-TOP H-BOTTOM ANG-OPEN-HORIZ ))
(setfeats tmp "1" '(H-BOTTOM SINGLE-V ANG-OPEN-DOWN))
(setfeats tmp "2" '(H-BOTTOM SM-CURVE-CONVEX-LEFT))
(setfeats tmp "3" '(SM-CURVE-CONVEX-LEFT))
(setfeats tmp "4" '(SINGLE-V CLOSED-CURVE H-CENTER))
(setfeats tmp "5" '(SM-CURVE-CONVEX-LEFT H-TOP))
(setfeats tmp "6" '(CLOSED-CURVE SM-CURVE-CONVEX-RIGHT))
(setfeats tmp "7" '(H-TOP ANG-OPEN-HORIZ))
(setfeats tmp "8" '(CLOSED-CURVE CONTINUOUS-CURVE))
(setfeats tmp "9" '(CLOSED-CURVE SM-CURVE-CONVEX-LEFT))
(setfeats tmp "0" '(CLOSED-CURVE CONTINUOUS-CURVE LARGE-CURVE ANG-OPEN-HORIZ))
tmp))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Original Rumelhart and McClelland feature set
(defun build-rm-orig-set ()
"Returns the Rumelhart & McClelland (1981) character feature set."
(let ((tmp (make-instance 'char-feats :name :RM-ORIG
:feat-ls
'(horizontal-t0 vertical-l1
back-diagonal-u1 vertical-c1 front-diagonal-u1
vertical-r1 horizontal-c1 horizontal-c2
vertical-l2 front-diagonal-l2 vertical-c2
back-diagonal-l2 vertical-r2 horizontal-l0
left-facing symmetric right-facing))))
(setfeats tmp "A" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 VERTICAL-R2 SYMMETRIC))
(setfeats tmp "B" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-R1 HORIZONTAL-C2
VERTICAL-C2 VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "C" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-L2 HORIZONTAL-L0
RIGHT-FACING))
(setfeats tmp "D" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-R1 VERTICAL-C2
VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "E" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 VERTICAL-L2
HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "F" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 VERTICAL-L2
RIGHT-FACING))
(setfeats tmp "G" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C2 VERTICAL-L2
VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "H" '(VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-L2 VERTICAL-R2 SYMMETRIC))
(setfeats tmp "I" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-C2 HORIZONTAL-L0
SYMMETRIC))
(setfeats tmp "J" '(VERTICAL-R1 VERTICAL-L2 VERTICAL-R2 HORIZONTAL-L0
LEFT-FACING))
(setfeats tmp "K" '(VERTICAL-L1 FRONT-DIAGONAL-U1 HORIZONTAL-C1
VERTICAL-L2 BACK-DIAGONAL-L2 RIGHT-FACING))
(setfeats tmp "L" '(VERTICAL-L1 VERTICAL-L2 HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "M" '(VERTICAL-L1 BACK-DIAGONAL-U1 FRONT-DIAGONAL-U1
VERTICAL-R1 VERTICAL-L2 VERTICAL-R2 SYMMETRIC))
(setfeats tmp "N" '(VERTICAL-L1 BACK-DIAGONAL-U1 VERTICAL-R1 VERTICAL-L2
BACK-DIAGONAL-L2 VERTICAL-R2 SYMMETRIC))
(setfeats tmp "O" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 VERTICAL-L2
VERTICAL-R2 HORIZONTAL-L0 SYMMETRIC))
(setfeats tmp "P" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 RIGHT-FACING))
(setfeats tmp "Q" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 VERTICAL-L2
BACK-DIAGONAL-L2 VERTICAL-R2 HORIZONTAL-L0
RIGHT-FACING))
(setfeats tmp "R" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 BACK-DIAGONAL-L2
RIGHT-FACING))
(setfeats tmp "S" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-R2 HORIZONTAL-L0 SYMMETRIC))
(setfeats tmp "T" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-C2 SYMMETRIC))
(setfeats tmp "U" '(VERTICAL-L1 VERTICAL-R1 VERTICAL-L2 VERTICAL-R2
HORIZONTAL-L0 SYMMETRIC))
(setfeats tmp "V" '(VERTICAL-L1 FRONT-DIAGONAL-U1 VERTICAL-L2
FRONT-DIAGONAL-L2 SYMMETRIC))
(setfeats tmp "W" '(VERTICAL-L1 VERTICAL-R1 VERTICAL-L2 FRONT-DIAGONAL-L2
BACK-DIAGONAL-L2 VERTICAL-R2 SYMMETRIC))
(setfeats tmp "X" '(BACK-DIAGONAL-U1 FRONT-DIAGONAL-U1 FRONT-DIAGONAL-L2
BACK-DIAGONAL-L2 SYMMETRIC))
(setfeats tmp "Y" '(BACK-DIAGONAL-U1 FRONT-DIAGONAL-U1 VERTICAL-C2
SYMMETRIC))
(setfeats tmp "Z" '(HORIZONTAL-T0 FRONT-DIAGONAL-U1 FRONT-DIAGONAL-L2
HORIZONTAL-L0 SYMMETRIC))
(setfeats tmp "1" '(VERTICAL-R1 VERTICAL-R2 LEFT-FACING))
(setfeats tmp "2" '(HORIZONTAL-T0 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-L2 HORIZONTAL-L0 LEFT-FACING))
(setfeats tmp "3" '(HORIZONTAL-T0 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-R2 HORIZONTAL-L0 LEFT-FACING))
(setfeats tmp "4" '(VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-R2 LEFT-FACING))
(setfeats tmp "5" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1
BACK-DIAGONAL-L2 HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "6" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-L2 VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING))
(setfeats tmp "7" '(HORIZONTAL-T0 VERTICAL-R1 VERTICAL-R2 LEFT-FACING))
(setfeats tmp "8" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 VERTICAL-R2 HORIZONTAL-L0
SYMMETRIC))
(setfeats tmp "9" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-R2 HORIZONTAL-L0 LEFT-FACING))
(setfeats tmp "0" '(HORIZONTAL-T0 VERTICAL-L1 BACK-DIAGONAL-U1 VERTICAL-R1
VERTICAL-L2 BACK-DIAGONAL-L2 VERTICAL-R2 HORIZONTAL-L0
SYMMETRIC))
tmp))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; "Clean" Rumelhart and McClelland (??) feature set
(defun cliplast (sym)
"Removes the last character from a symbol."
(let ((str (mkstr sym)))
(read-from-string str nil nil :start 0 :end (- (length str) 1))))
(defun build-rm-clean-set ()
(let ((tmp (make-instance 'char-feats :name :RM-CLEAN :true->icon #'cliplast
:feat-ls
'(horizontal-t0 vertical-l1
back-diagonal-u1 vertical-c1 front-diagonal-u1
vertical-r1 horizontal-c1 horizontal-c2
vertical-l2 front-diagonal-l2 vertical-c2
back-diagonal-l2 vertical-r2 horizontal-l0
left-facing+ symmetric+ right-facing+))))
(setfeats tmp "A" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 VERTICAL-R2 SYMMETRIC+))
(setfeats tmp "B" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-R1 HORIZONTAL-C2
VERTICAL-C2 VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "C" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-L2 HORIZONTAL-L0
RIGHT-FACING+))
(setfeats tmp "D" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-R1 VERTICAL-C2
VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "E" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 VERTICAL-L2
HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "F" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 VERTICAL-L2
RIGHT-FACING+))
(setfeats tmp "G" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C2 VERTICAL-L2
VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "H" '(VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-L2 VERTICAL-R2 SYMMETRIC+))
(setfeats tmp "I" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-C2 HORIZONTAL-L0
SYMMETRIC+))
(setfeats tmp "J" '(VERTICAL-R1 VERTICAL-L2 VERTICAL-R2 HORIZONTAL-L0
LEFT-FACING+))
(setfeats tmp "K" '(VERTICAL-L1 FRONT-DIAGONAL-U1 HORIZONTAL-C1
VERTICAL-L2 BACK-DIAGONAL-L2 RIGHT-FACING+))
(setfeats tmp "L" '(VERTICAL-L1 VERTICAL-L2 HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "M" '(VERTICAL-L1 BACK-DIAGONAL-U1 FRONT-DIAGONAL-U1
VERTICAL-R1 VERTICAL-L2 VERTICAL-R2 SYMMETRIC+))
(setfeats tmp "N" '(VERTICAL-L1 BACK-DIAGONAL-U1 VERTICAL-R1 VERTICAL-L2
BACK-DIAGONAL-L2 VERTICAL-R2 SYMMETRIC+))
(setfeats tmp "O" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 VERTICAL-L2
VERTICAL-R2 HORIZONTAL-L0 SYMMETRIC+))
(setfeats tmp "P" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 RIGHT-FACING+))
(setfeats tmp "Q" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 VERTICAL-L2
BACK-DIAGONAL-L2 VERTICAL-R2 HORIZONTAL-L0
RIGHT-FACING+))
(setfeats tmp "R" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 BACK-DIAGONAL-L2
RIGHT-FACING+))
(setfeats tmp "S" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-R2 HORIZONTAL-L0 SYMMETRIC+))
(setfeats tmp "T" '(HORIZONTAL-T0 VERTICAL-C1 VERTICAL-C2 SYMMETRIC+))
(setfeats tmp "U" '(VERTICAL-L1 VERTICAL-R1 VERTICAL-L2 VERTICAL-R2
HORIZONTAL-L0 SYMMETRIC+))
(setfeats tmp "V" '(VERTICAL-L1 FRONT-DIAGONAL-U1 VERTICAL-L2
FRONT-DIAGONAL-L2 SYMMETRIC+))
(setfeats tmp "W" '(VERTICAL-L1 VERTICAL-R1 VERTICAL-L2 FRONT-DIAGONAL-L2
BACK-DIAGONAL-L2 VERTICAL-R2 SYMMETRIC+))
(setfeats tmp "X" '(BACK-DIAGONAL-U1 FRONT-DIAGONAL-U1 FRONT-DIAGONAL-L2
BACK-DIAGONAL-L2 SYMMETRIC+))
(setfeats tmp "Y" '(BACK-DIAGONAL-U1 FRONT-DIAGONAL-U1 VERTICAL-C2
SYMMETRIC+))
(setfeats tmp "Z" '(HORIZONTAL-T0 FRONT-DIAGONAL-U1 FRONT-DIAGONAL-L2
HORIZONTAL-L0 SYMMETRIC+))
(setfeats tmp "1" '(VERTICAL-R1 VERTICAL-R2 LEFT-FACING+))
(setfeats tmp "2" '(HORIZONTAL-T0 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-L2 HORIZONTAL-L0 LEFT-FACING+))
(setfeats tmp "3" '(HORIZONTAL-T0 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-R2 HORIZONTAL-L0 LEFT-FACING+))
(setfeats tmp "4" '(VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-R2 LEFT-FACING+))
(setfeats tmp "5" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1
BACK-DIAGONAL-L2 HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "6" '(HORIZONTAL-T0 VERTICAL-L1 HORIZONTAL-C1 HORIZONTAL-C2
VERTICAL-L2 VERTICAL-R2 HORIZONTAL-L0 RIGHT-FACING+))
(setfeats tmp "7" '(HORIZONTAL-T0 VERTICAL-R1 VERTICAL-R2 LEFT-FACING+))
(setfeats tmp "8" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-L2 VERTICAL-R2 HORIZONTAL-L0
SYMMETRIC+))
(setfeats tmp "9" '(HORIZONTAL-T0 VERTICAL-L1 VERTICAL-R1 HORIZONTAL-C1
HORIZONTAL-C2 VERTICAL-R2 HORIZONTAL-L0 LEFT-FACING+))
(setfeats tmp "0" '(HORIZONTAL-T0 VERTICAL-L1 BACK-DIAGONAL-U1 VERTICAL-R1
VERTICAL-L2 BACK-DIAGONAL-L2 VERTICAL-R2 HORIZONTAL-L0
SYMMETRIC+))
tmp))
#|
;;;; ---------------------------------------------------------------------- ;;;;
;;;; XXXX () feature set
(defun build-XX-set ()
(let ((tmp (make-instance 'char-feats feat-ls
'())))
(setfeats tmp "A" '())
(setfeats tmp "B" '())
(setfeats tmp "C" '())
(setfeats tmp "D" '())
(setfeats tmp "E" '())
(setfeats tmp "F" '())
(setfeats tmp "G" '())
(setfeats tmp "H" '())
(setfeats tmp "I" '())
(setfeats tmp "J" '())
(setfeats tmp "K" '())
(setfeats tmp "L" '())
(setfeats tmp "M" '())
(setfeats tmp "N" '())
(setfeats tmp "O" '())
(setfeats tmp "P" '())
(setfeats tmp "Q" '())
(setfeats tmp "R" '())
(setfeats tmp "S" '())
(setfeats tmp "T" '())
(setfeats tmp "U" '())
(setfeats tmp "V" '())
(setfeats tmp "W" '())
(setfeats tmp "X" '())
(setfeats tmp "Y" '())
(setfeats tmp "Z" '())
(setfeats tmp "1" '())
(setfeats tmp "2" '())
(setfeats tmp "3" '())
(setfeats tmp "4" '())
(setfeats tmp "5" '())
(setfeats tmp "6" '())
(setfeats tmp "7" '())
(setfeats tmp "8" '())
(setfeats tmp "9" '())
(setfeats tmp "0" '())
tmp))
|#
;;;; ---------------------------------------------------------------------- ;;;;
(defun all-feature-sets ()
(list (build-gibson-set) (build-bh-set) (build-rm-orig-set)
(build-rm-clean-set)))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 28,472 | Common Lisp | .lisp | 514 | 46.529183 | 117 | 0.614422 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ab62c15ad255cd66bb0f55728b3e271b16bf1c48d83d2fed720f55c9875b40a0 | 14,318 | [
-1
] |
14,319 | parameters.lisp | asmaloney_ACT-R/framework/parameters.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2004 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : parameters.lisp
;;; Version : 1.0
;;;
;;; Description : Functions for defining and accessing parameters.
;;;
;;; Bugs :
;;;
;;; To do : Finish the documentation.
;;;
;;; ----- History -----
;;;
;;; 2004.08.18 Dan
;;; : Creation.
;;;
;;; 2005.01.04 Dan
;;; : Took some of the newlines out of show-all-parameters.
;;; : Shrunk down to max width of 80 chars.
;;; 2005.01.17 Dan
;;; : * Changed model-output to command-output so that one can
;;; : see sgp printing when :v is nil.
;;; : * Changed the order of sgp's printing so that it's easier
;;; : to see the parameter values.
;;; 2005.02.11 Dan
;;; : * Replaced a reverse with push-last in set-parameters.
;;; 2005.08.10 Dan
;;; : * Added the remove-modules-parameters and remove-parameter
;;; : to support the undefine-module function.
;;; : * Updated the version to 1.0.
;;; 2006.07.12 Dan
;;; : * Modified TEST-AND-SET-PARAMETER-VALUE so that when a value
;;; : failed the validity test :invalid-value is returned for the
;;; : list of parameter values (could return the current setting
;;; : instead, but I think an error marker works better).
;;; : * Also did some reformatting because I find it difficult to
;;; : read some of the code if I keep it to only 80 columns.
;;; 2008.07.23 Dan
;;; : * Added a get-parameter-default-value function so that that
;;; : value can be retrieved through a function in the API.
;;; 2008.08.29 Dan
;;; : * Updated define-parameter to check the valid-test parameter
;;; : for validity like the rest.
;;; 2012.03.20 Dan
;;; : * Added the with-parameters and with-parameters-fct commands
;;; : which can be used to temporarily set parameter values while
;;; : evaluating some code.
;;; 2012.08.06 Dan
;;; : * Sgp now prints the paramter table sorted by module name
;;; : and then by parameter name within a module when it prints
;;; : all parameters.
;;; 2017.03.08 Dan
;;; : * Because (no-output (car (sgp :xxx))) is a frequently needed
;;; : construct adding a function to do just that and making it
;;; : available remotely: get-parameter-value.
;;; 2017.06.29 Dan
;;; : * Protecting the parameters table with a lock.
;;; 2017.07.14 Dan
;;; : * Make sure sgp is thread safe.
;;; 2017.11.07 Dan
;;; : * Changed the warning in test-and-set-parameter-value to use
;;; : ~s instead of ~a when printing an invalid value.
;;; 2017.11.14 Dan
;;; : * Added the external command set-parameter-value.
;;; 2018.01.26 Dan
;;; : * Renamed the things so that get-paraemter-value and set-
;;; : parameter-value are valid user commands associated with the
;;; : corresponding remote commands and don't error out for get.
;;; 2018.06.14 Dan
;;; : * Set- and get- parameter-value need to encode/decode strings
;;; : for remote calls only.
;;; 2020.09.04 Dan
;;; : * Get-parameters simplified to avoid the need to get the
;;; : struct from the table twice (once to check valid and once to
;;; : actually get the struct).
;;; 2021.10.18 Dan
;;; : * Don't warn about a missing module when trying to set a
;;; : parameter for a module that's not the owner by using the
;;; : new third parameter to process-parameters (which ignores
;;; : warnings when t).
;;; 2021.10.20 Dan
;;; : * Fixed show-all-parameters and the set/get functions so that
;;; : they handle missing modules well.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Internal structures not for external use.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Holds all the parameters that have been "registered" with a module.
(defvar *act-r-parameters-table* (make-hash-table :test #'eq)
"The table of all used parameters")
(defvar *parameters-table-lock* (bt:make-lock "parameters-table"))
(defun define-parameter (param-name
&key (owner t) (valid-test nil)
(default-value nil) (warning "")
(documentation ""))
(cond ((not (keywordp param-name))
(print-warning "Parameter name must be a keyword."))
((keywordp default-value)
(print-warning "default-value cannot be a keyword."))
((not (fctornil valid-test))
(print-warning "valid-test must be a function, the name of a function, or nil."))
((not (stringp documentation))
(print-warning "documentation must be a string."))
((not (stringp warning))
(print-warning "warning must be a string."))
(t
(make-act-r-parameter :owner owner
:param-name param-name
:default default-value
:test valid-test
:warning warning
:details documentation))))
(defun parse-parameters (parameters-list)
"Make sure that they are parameters and not already owned if ownership
requested or that it exists if not owned"
(if (every (lambda (x)
(and (act-r-parameter-p x)
(or (and (act-r-parameter-owner x)
(not (valid-parameter-name
(act-r-parameter-param-name x))))
(and (not (act-r-parameter-owner x))
(valid-parameter-name
(act-r-parameter-param-name x))))))
parameters-list)
parameters-list
:error))
(defun install-parameters (module-name parameters)
(bt:with-lock-held (*parameters-table-lock*)
(dolist (x parameters)
(if (act-r-parameter-owner x)
(let ((param-copy (copy-act-r-parameter x)))
(setf (act-r-parameter-owner param-copy) module-name)
(setf (gethash (act-r-parameter-param-name param-copy)
*act-r-parameters-table*)
param-copy))
(push module-name (act-r-parameter-users
(gethash (act-r-parameter-param-name x) *act-r-parameters-table*)))))))
(defun remove-modules-parameters (module-name)
"Remove all parameters of the module both owned and watched"
(bt:with-lock-held (*parameters-table-lock*)
(maphash (lambda (name param)
(when (eq module-name
(act-r-parameter-owner param))
(remhash name *act-r-parameters-table*))
(setf (act-r-parameter-users param)
(remove module-name (act-r-parameter-users param))))
*act-r-parameters-table*)))
(defun remove-parameter (param-name)
"Remove a specific parameter from the table"
(bt:with-lock-held (*parameters-table-lock*)
(remhash param-name *act-r-parameters-table*)))
(defmacro sgp (&rest parameters)
`(sgp-fct ',parameters))
(defun sgp-fct (&optional (parameters-list nil))
(verify-current-mp
"sgp called with no current meta-process."
(verify-current-model
"sgp called with no current model."
(set-or-get-parameters parameters-list))))
(defun set-or-get-parameters (params)
(if (null params)
(show-all-parameters)
(if (every 'keywordp params)
(get-parameters params)
(set-parameters params))))
(defun internal-get-parameter-value (parameter)
(first (get-parameters (list parameter) nil)))
(defun get-parameter-value (parameter)
(let ((m (current-model)))
(cond ((null m)
(print-warning "get-parameter-value called with no current model.")
:no-model)
(t
(let ((p (internal-get-parameter-value parameter)))
(when (eq p :bad-parameter-name)
(print-warning "Invalid parameter name ~s in call to get-parameter-value." parameter))
p)))))
(defun remote-get-parameter-value (parameter)
(encode-string-names (get-parameter-value (string->name parameter))))
(add-act-r-command "get-parameter-value" 'remote-get-parameter-value "Return the current value of a parameter in the current model. Params: parameter-name." nil)
(defun get-parameters (params &optional (output t))
(let ((res nil))
(dolist (p-name params (reverse res))
(aif (get-parameter-struct p-name)
(let* ((owner (act-r-parameter-owner it))
(val (process-parameters owner p-name nil)))
(if (get-module-fct owner t)
(progn
(push val res)
(when output
(command-output "~S ~S (default ~S) : ~A"
p-name
val
(act-r-parameter-default it)
(act-r-parameter-details it))))
(push :bad-parameter-name res)))
(push :bad-parameter-name res)))))
(defun get-parameter-struct (p-name)
(bt:with-lock-held (*parameters-table-lock*)
(gethash p-name *act-r-parameters-table*)))
(defun valid-parameter-name (p-name)
(bt:with-lock-held (*parameters-table-lock*)
(gethash p-name *act-r-parameters-table*)))
(defun set-parameters (params)
(if (evenp (length params))
(let ((res nil))
(while params
(let ((p-name (pop params))
(p-val (pop params)))
(push-last (test-and-set-parameter-value p-name p-val) res)))
res)
(print-warning "Odd number of parameters and values passed to sgp.")))
(defun test-and-set-parameter-value (p-name value)
(let ((param (bt:with-lock-held (*parameters-table-lock*) (gethash p-name *act-r-parameters-table*))))
(if param
(if (or (null (act-r-parameter-test param))
(funcall (act-r-parameter-test param) value))
(internal-set-parameter-value param value)
(progn
(print-warning "Parameter ~S cannot take value ~s because it must be ~A."
p-name value (act-r-parameter-warning param))
:invalid-value))
(progn
(print-warning "Parameter ~s is not the name of an available parameter" p-name)
:bad-parameter-name))))
(defun internal-set-parameter-value (param value)
(let* ((current-value (process-parameters (act-r-parameter-owner param)
(cons (act-r-parameter-param-name param) value)
nil)))
(if (get-module-fct (act-r-parameter-owner param) t)
(dolist (s (bt:with-lock-held (*parameters-table-lock*) (act-r-parameter-users param)) current-value)
(process-parameters s (cons (act-r-parameter-param-name param) current-value) t))
:bad-parameter-name)))
(defun set-parameter-value (param value)
(let ((m (current-model)))
(cond ((null m)
(print-warning "set-parameter-value called with no current model.")
:no-model)
(t
(test-and-set-parameter-value param value)))))
(defun remote-set-parameter-value (param val)
(encode-string-names (set-parameter-value (string->name param) (decode-string-names val))))
(add-act-r-command "set-parameter-value" 'remote-set-parameter-value "Sets the current value of a parameter in the current model. Params: parameter-name 'new-value'." nil)
(defmacro with-parameters (temp-params &body body)
(let ((params (gensym))
(current-vals (gensym))
(new-vals (gensym))
(p-name (gensym))
(p-val (gensym))
(val (gensym)))
`(let ((,params ',temp-params))
(block with-parameters
(verify-current-mp
"with-parameters called with no current meta-process."
(verify-current-model
"with-parameters called with no current model."
(if (oddp (length ,params))
(print-warning "Odd length parameters list in call to with-parameters. The body is ignored.")
(let ((,current-vals nil)
(,new-vals nil))
(while ,params
(let ((,p-name (pop ,params))
(,p-val (pop ,params)))
(unless (valid-parameter-name ,p-name)
(print-warning "~s is not the name of a parameter. with-parameters body ignored." ,p-name)
(return-from with-parameters nil))
(push (cons ,p-name (car (get-parameters (list ,p-name) nil))) ,current-vals)
(push-last (cons ,p-name ,p-val) ,new-vals)))
(unwind-protect
(progn
(dolist (,val ,new-vals)
(test-and-set-parameter-value (car ,val) (cdr ,val)))
,@body)
(dolist (,val ,current-vals)
(test-and-set-parameter-value (car ,val) (cdr ,val))))))))))))
(defmacro with-parameters-fct (temp-params &body body)
(let ((params (gensym))
(current-vals (gensym))
(new-vals (gensym))
(p-name (gensym))
(p-val (gensym))
(val (gensym)))
`(let ((,params (list ,@temp-params)))
(block with-parameters
(verify-current-mp
"with-parameters called with no current meta-process."
(verify-current-model
"with-parameters called with no current model."
(if (oddp (length ,params))
(print-warning "Odd length parameters list in call to with-parameters. The body is ignored.")
(let ((,current-vals nil)
(,new-vals nil))
(while ,params
(let ((,p-name (pop ,params))
(,p-val (pop ,params)))
(unless (valid-parameter-name ,p-name)
(print-warning "~s is not the name of a parameter. with-parameters body ignored." ,p-name)
(return-from with-parameters nil))
(push (cons ,p-name (car (get-parameters (list ,p-name) nil))) ,current-vals)
(push-last (cons ,p-name ,p-val) ,new-vals)))
(unwind-protect
(progn
(dolist (,val ,new-vals)
(test-and-set-parameter-value (car ,val) (cdr ,val)))
,@body)
(dolist (,val ,current-vals)
(test-and-set-parameter-value (car ,val) (cdr ,val))))))))))))
(defun show-all-parameters ()
(let ((current-val-table (make-hash-table)))
(maphash (lambda (p-name param)
(when (get-module-fct (act-r-parameter-owner param) t)
(push
(cons param (process-parameters (act-r-parameter-owner param) p-name nil))
(gethash (act-r-parameter-owner param) current-val-table))))
(bt:with-lock-held (*parameters-table-lock*) *act-r-parameters-table*))
(let ((name-len (1+ (apply #'max
(mapcar (lambda (x)
(length (string x)))
(hash-table-keys (bt:with-lock-held (*parameters-table-lock*) *act-r-parameters-table*))))))
(default-len (apply #'max
(with-hash-table-iterator (generator-fn (bt:with-lock-held (*parameters-table-lock*) *act-r-parameters-table*))
(let ((items nil))
(loop
(multiple-value-bind (more? key value) (generator-fn)
(declare (ignore key))
(unless more? (return items))
(push (length (format nil "~s" (act-r-parameter-default value)))
items)))))))
(value-len (apply #'max
(with-hash-table-iterator (generator-fn current-val-table)
(let ((items nil))
(loop
(multiple-value-bind (more? key value) (generator-fn)
(declare (ignore key))
(unless more? (return items))
(dolist (param value)
(push (length (format nil "~S" (cdr param)))
items)))))))))
(dolist (module-name (sort (hash-table-keys current-val-table) #'string< :key 'symbol-name))
(when (get-module-fct module-name t)
(command-output "--------------------------------~%~S module" module-name)
(command-output "--------------------------------")
(dolist (param (sort (gethash module-name current-val-table) #'string< :key (lambda (x) (symbol-name (act-r-parameter-param-name (car x))))))
(command-output "~vS ~vS default: ~vS : ~A"
name-len
(act-r-parameter-param-name (car param))
value-len
(cdr param)
default-len
(act-r-parameter-default (car param))
(act-r-parameter-details (car param)))))))))
(defun get-parameter-default-value (param)
(aif (get-parameter-struct param)
(act-r-parameter-default it)
(progn
(print-warning "Invalid parameter name ~S in call to get-parameter-default-value." param)
:bad-parameter-name)))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 20,191 | Common Lisp | .lisp | 402 | 39.460199 | 171 | 0.541387 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5a187cb0aa064f3ac3042c742f8ae331cfca40477a96b39ea0a70bf5686a1f76 | 14,319 | [
-1
] |
14,320 | history-recorder.lisp | asmaloney_ACT-R/framework/history-recorder.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2016 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : history-recorder.lisp
;;; Version : 2.2
;;;
;;; Description : General history data recording mechanisms based on those which
;;; : were used for the Environment tools previously.
;;;
;;; Bugs :
;;;
;;; To do : [x] Need some way to break up large histories because the
;;; : Environment currently dies when handling things like a
;;; : production grid that's a 3M+ json string...
;;;
;;; ----- History -----
;;; 2016.04.15 Dan [1.0a1]
;;; : * Initial creation.
;;; 2016.04.21 Dan
;;; : * Updates to make this actually usable...
;;; 2016.04.22 Dan
;;; : * Adding the support for saving/loading data for the history
;;; : tools. The approach is that a tool needs to specify a function
;;; : to "get" the data and should always call the get-history-information
;;; : function to access the data for display because that will
;;; : return the current or saved data as needed.
;;; : * Adding code to support the text trace here since it doesn't
;;; : have its own file.
;;; 2016.05.03 Dan [1.0a2]
;;; : * Adding support for removing the saved traces from the global
;;; : hash table to conserve memory. The table now holds a count
;;; : of windows using it and it will decrement that when the window
;;; : closes (needs the signals from the environment) and can
;;; : remhash it at 0.
;;; 2016.05.05 Dan
;;; : * Allow get-history-information to work without a current model
;;; : when it's tabled data being accessed.
;;; 2016.05.12 Dan
;;; : * Updated the save-history-information to better deal with
;;; : errors and report them back to the Environment.
;;; 2016.05.13 Dan
;;; : * Similar update to load-history-information.
;;; : * The text history output function can't use command-output
;;; : since there may not be a model when looking at saved data.
;;; 2016.05.17 Dan
;;; : * Fixed a bug with load-history-information that didn't catch
;;; : bad data at the start of the loaded file.
;;; 2016.05.18 Dan
;;; : * Fixed some issues with unused variables.
;;; 2016.05.19 Dan
;;; : * Fixed an issue with loading a model while the previous model
;;; : had a select data window open already -- the new model ended
;;; : up with invalid settings sometimes because of the asynchrony
;;; : in closing the old window and defining the new model. Now
;;; : the module's handler code checks to make sure it's the right
;;; : model before initializing the data from the window's handler.
;;; : * Better fix for that now since reload also had an issue if it
;;; : was the same model...
;;; 2016.06.01 Dan
;;; : * When saving the history information also save the current
;;; : ACT-R version and then check that when loading.
;;; 2016.06.09 Dan
;;; : * Added the clear-history-cache function which the environment
;;; : code can use to make sure everything is released when the
;;; : environment isn't connected anymore.
;;; 2017.08.11 Dan
;;; : * Protect access to procedural-buffer-indices.
;;; 2017.09.15 Dan [2.0a1]
;;; : * Moved this into the framework, and it doesn't need to
;;; : be a module now because it's just a bunch of functions.
;;; : The objective is to generalize this mechanism so that it
;;; : isn't just something tied to the Tcl/Tk Environment.
;;; : * Don't worry about cacheing the data anymore, and basically
;;; : just act as an intermediary for dealing with the data streams
;;; : and processors recorded.
;;; 2017.09.19 Dan
;;; : * Removed the trace history stuff, added the standard macro/fct
;;; : split, and changed the top-level names to include history
;;; : instead of stream.
;;; : * Added remote commands to access it.
;;; 2017.09.20 Dan
;;; : * Make a component for the main recorder instead of a global
;;; : because it needs to be cleaned-up when a clear-all happens.
;;; 2017.09.21 Dan
;;; : * Have the get and available check to see if there's a current
;;; : model when it's a model based data stream.
;;; : * Status needs to return three things enabled, data, and alive.
;;; : The alive check is for when a model gets deleted because a
;;; : module may need to clear things itself upon deletion for
;;; : consistency (instead of assuming all starts will be stopped)
;;; : but doing so can result in warnings for 'external' changes
;;; : if the module cleans itself up and then the stops come in
;;; : (perhaps also driven by the delete model call). If the
;;; : stream source is no longer available then it needs to say
;;; : it's no longer alive so the history code can skip the warnings
;;; : for disabling after that point.
;;; 2017.09.22 Dan
;;; : * Fixed a bug with process-history-data because it needed to
;;; : pass the name of the stream to get-history-data.
;;; 2017.09.26 Dan
;;; : * Make sure process-history-data returns the comment as a
;;; : second value when data is loaded from a file.
;;; 2017.10.04 Dan
;;; : * Allow names to be symbols or strings and convert to symbol
;;; : using string->symbol for storage.
;;; : * Split all into a macro and function.
;;; : * Allow record-history and stop-recording-history to take an
;;; : arbitrary number of items.
;;; : * Allow get, available, record, and stop to take a processor name.
;;; : Because of that, just switch to one table and always check
;;; : the type of the retrieved thing.
;;; : * Change process-history-data to take two lists of params: one
;;; : for the history stream and one for the processor. If get-
;;; : history is used for a processor then the parameters are only
;;; : passed to the stream and the processor is assumed to only take
;;; : the data as a parameter.
;;; 2017.11.14 Dan
;;; : * Fixed a bug in stop-recording-history when an invalid name
;;; : is given.
;;; 2017.11.21 Dan
;;; : * Save-history-data was defined as a function instead of a
;;; : macro.
;;; 2017.11.27 Dan
;;; : * Added a first pass at an incremental data system since the
;;; : Environment chokes on "big" packets, like those for the
;;; : production graphs and graphic traces which can be several
;;; : MB for a run of something like past-tense or zbrodoff
;;; : respectively.
;;; 2018.02.28 Dan [2.0]
;;; : * Changed the ordering of the parameters for -processor so that
;;; : the history is first and the processor's name second to be
;;; : the same as -component.
;;; : * Make remote versions of all the commands.
;;; : * Require that the names be strings.
;;; : * Pass the rest parameters from get-history-data to the status
;;; : command now.
;;; 2018.03.01 Dan
;;; : * Fix a bug with passing the get-history-data params to the
;;; : status command.
;;; : * Force everthing to require names be strings.
;;; : * Return multiple values from record and stop-recording with
;;; : each value indicating the result of the corresponding param.
;;; 2018.03.02 Dan
;;; : * Renamed history-component to history-constituent because
;;; : component is already used to describe something...
;;; : * NOPE! Don't require names to be strings because stuff that
;;; : comes in remotely could get converted from string to symbol
;;; : automatically and don't want to 'fix' all the Environment
;;; : code.
;;; 2018.06.13 Dan
;;; : * Updated the command doc strings to match current spec.
;;; : * Histories must be named with strings now.
;;; 2018.08.08 Dan
;;; : * Fixed a bug with save-history-data in how it creates the
;;; : call to get data when parameters are given.
;;; 2018.08.22 Dan
;;; : * Process-history-data should also return the comment from a
;;; : file of history data as the second result.
;;; 2019.05.29 Dan
;;; : * Turn off file access in single threaded mode because there
;;; : isn't a JSON parser loaded so data will be in the original
;;; : Lisp format and don't want to generate incompatible files.
;;; 2020.01.13 Dan [2.1]
;;; : * Removed the #' and lambdas from the module interface.
;;; 2022.03.10 Dan [2.2]
;;; : * Make this a required module.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Provide a common mechanism for recording and saving history information.
;;; Originally designed around the needs of the Environment tools, but then
;;; generalized into something that's useful for all of the underlying data
;;; recording capabilities.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; See reference manual.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Use JSON as the underlying data format because that's what the RPC system
;;; uses, so the processing of that is already available.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
(declaim (ftype (function (t &optional t) t) written-for-act-r-version))
(defstruct history-module
(state-table (make-hash-table)) ; nil, :enabled, :disabled
(requests-table (make-hash-table))) ; nil or #
(defstruct history-recorder
(lock (bt:make-recursive-lock "history recorder"))
(module (make-history-module))
(streams-table (make-hash-table))
(current-id 0)
(incremental-table (make-hash-table)))
(defun create-history-recorder () (make-history-recorder))
(defun clear-all-history-state (component)
(bt:with-recursive-lock-held ((history-recorder-lock component))
(setf (history-recorder-module component) (make-history-module))
(clrhash (history-recorder-incremental-table component))))
(define-component history-recorder :version "2.0" :documentation "Maintain the tables of defined history recorders and state of non-model based history streams."
:creation create-history-recorder :clear-all clear-all-history-state)
(defstruct data-stream
parent
sub-streams
internal-name
external-name
enable
disable
status
get
model-based)
(defstruct data-processor
internal-name
external-name
stream
get)
(defmacro define-history (name enable disable status get &optional (model-based t))
`(define-history-fct ',name ',enable ',disable ',status ',get ',model-based))
(defun define-history-fct (name enable disable status get &optional (model-based t))
(cond ((not (stringp name))
(print-warning "Name for a history source must be a string, but given ~s." name))
((not (local-or-remote-function-p enable))
(print-warning "Enable function for a history source must be a valid command, but given ~s." enable))
((not (local-or-remote-function-p disable))
(print-warning "Disable function for a history source must be a valid command, but given ~s." disable))
((not (local-or-remote-function-p status))
(print-warning "Status function for a history source must be a valid command, but given ~s." status))
((not (local-or-remote-function-p get))
(print-warning "Get data function for a history source must be a valid command, but given ~s." get))
(t
(let ((i-name (string->name name)) ;; use a symbol internally
(history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(if (gethash i-name (history-recorder-streams-table history-recorder))
(print-warning "Cannot create a history source with name ~s because it is already used." name)
(progn
(setf (gethash i-name (history-recorder-streams-table history-recorder))
(make-data-stream
:internal-name i-name
:external-name name
:enable enable
:disable disable
:status status
:get get
:model-based model-based))
t)))))))
(add-act-r-command "define-history" 'define-history-fct "Create a new history source recorder. Params: name enable-cmd disable-cmd status-cmd get-cmd {model-based}")
(defmacro define-history-constituent (history name enable disable status)
`(define-history-constituent-fct ',history ',name ',enable ',disable ',status))
(defun define-history-constituent-fct (history name enable disable status)
(cond ((not (stringp name))
(print-warning "Name for a history stream constituent must be a string, but given ~s." name))
((not (stringp history))
(print-warning "Name for a history stream must be a string, but given ~s." history))
((not (local-or-remote-function-p enable))
(print-warning "Enable function for a history stream constituent must be a valid command, but given ~s." enable))
((not (local-or-remote-function-p disable))
(print-warning "Disable function for a history stream constituent must be a valid command, but given ~s." disable))
((not (local-or-remote-function-p status))
(print-warning "Status function for a history stream constituent must be a valid command, but given ~s." status))
(t
(let ((i-name (string->name name))
(i-history (string->name history))
(history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(if (gethash i-name (history-recorder-streams-table history-recorder))
(print-warning "Cannot create a history stream constituent with name ~s because it is already used." name)
(let ((s (gethash i-history (history-recorder-streams-table history-recorder))))
(if (and s (null (data-stream-parent s)))
(let ((sub (make-data-stream
:internal-name i-name
:external-name name
:enable enable
:disable disable
:status status
:parent s
:model-based (data-stream-model-based s))))
(setf (gethash i-name (history-recorder-streams-table history-recorder)) sub)
(push sub (data-stream-sub-streams s))
t)
(print-warning "Cannot create a history source constituent with name ~s for history source ~s because that source does not exist." name history)))))))))
(add-act-r-command "define-history-constituent" 'define-history-fct "Create a new constituent part for a history source. Params: history name enable-cmd disable-cmd status-cmd")
(defmacro define-history-processor (history name get)
`(define-history-processor-fct ',history ',name ',get))
(defun define-history-processor-fct (history name get)
(cond ((not (stringp name))
(print-warning "Name for a history source processor must be a string, but given ~s." name))
((not (stringp history))
(print-warning "Name for a history source must be a string, but given ~s." history))
((not (local-or-remote-function-p get))
(print-warning "Processor function for a history source processor must be a valid command, but given ~s." get))
(t
(let ((i-name (string->name name))
(i-history (string->name history))
(history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(let ((s (gethash i-history (history-recorder-streams-table history-recorder))))
(if (and s (data-stream-p s) (null (data-stream-parent s)))
(if (gethash i-name (history-recorder-streams-table history-recorder))
(print-warning "Cannot create a history source processor with name ~s because that is already the name of a history source item." name)
(progn
(setf (gethash i-name (history-recorder-streams-table history-recorder))
(make-data-processor
:internal-name i-name
:external-name name
:stream s
:get get))
t))
(print-warning "Cannot create a history source processor named ~s for source ~s because that source is ~:[not defined~;a component of another stream or a processor~]."
name history s))))))))
(add-act-r-command "define-history-processor" 'define-history-processor-fct "Create a new data processor for a history source. Params: history processor-name process-cmd")
(defmacro history-data-available (name &rest rest)
`(apply 'history-data-available-fct ',name ',rest))
(defun history-data-available-fct (name &rest rest)
(if (not (stringp name))
(print-warning "History-data-available given name ~s but names must be strings." name)
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(setf name (string->name name))
(let* ((start (gethash name (history-recorder-streams-table history-recorder)))
(s (cond ((data-stream-p start)
(aif (data-stream-parent start) it start))
((data-processor-p start)
(data-processor-stream start)))))
(if s
(if (and (data-stream-model-based s) (null (current-model)))
(print-warning "Model based history ~a requires a current model to check for available data." name)
(multiple-value-bind (enabled data)
(dispatch-apply-list (data-stream-status s) rest)
(declare (ignore enabled))
(when data t)))
(print-warning "~s does not name a history data item in call to history-data-available." name)))))))
(add-act-r-command "history-data-available" 'history-data-available-fct "Return whether there is any data available for the indicated history stream. Params: history-name {param*}")
(defmacro get-history-data (name &optional file &rest rest)
`(apply 'get-history-data-fct ',name ',file ',rest))
(defun get-history-data-fct (name &optional file &rest rest)
#+:single-threaded-act-r (when file
(print-warning "History file access unavailable in single-threaded model.")
(return-from get-history-data-fct))
(if (not (stringp name))
(print-warning "Get-history-data given name ~s but names must be strings." name)
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(setf name (string->name name))
(let ((s (gethash name (history-recorder-streams-table history-recorder))))
(cond ((and (data-stream-p s) (data-stream-parent s))
(apply 'get-history-data-fct (data-stream-external-name (data-stream-parent s)) file rest))
((data-processor-p s)
(process-history-data-fct (data-processor-external-name s) file rest nil))
((data-stream-p s)
(if file
(multiple-value-bind (result err) (ignore-errors (probe-file file))
(if (subtypep (type-of err) 'condition)
(print-warning "Error ~/print-error-message/ encountered while trying to open file ~s for get-history-data." err file)
(if result
(multiple-value-bind (d c) (parse-saved-history-data (data-stream-internal-name s) result)
(if d
(if c
(values d c)
d)
(print-warning "File ~s does not contain valid data for history data source ~s in attempt get-history-data." file name)))
(print-warning "File ~s could not be found in attempt to get-history-data for ~s." file name))))
(if (and (data-stream-model-based s) (null (current-model)))
(print-warning "Model based history ~a requires a current model to get data." name)
(multiple-value-bind (enabled data alive)
(dispatch-apply-list (data-stream-status s) rest)
(if data
(let ((d (dispatch-apply-list (data-stream-get s) rest)))
(if (and d (listp d)
(every (lambda (x)
(and (listp x)
(numberp (first x))))
d))
(multiple-value-bind (result err)
(ignore-errors (json:encode-json-to-string d))
(if (subtypep (type-of err) 'condition)
(print-warning "Error ~/print-error-message/ encountered converting data from ~s to JSON." err d)
result))
(print-warning "Get-history-data for history data source ~s with parameters ~s returned invalid data ~s." name rest d)))
(let ((m (if (data-stream-model-based s)
(suppress-warnings (get-module :history-recorder))
(history-recorder-module history-recorder))))
(if m
(let ((state (gethash (data-stream-internal-name s) (history-module-state-table m))))
(cond ((null alive)
(print-warning "There is no data available for history data source ~s because the source is no longer available." name))
((and (null enabled) (null state))
(print-warning "There is no data available for history data source ~s because recording was never started." name))
((and (null enabled) (eq state :enabled))
(print-warning "There is no data available for history data source ~s and although recording was started it has since been disabled through other means." name))
((and (null enabled) (eq state :was-enabled))
(print-warning "There is no data available for history data source ~s and it appears that recording was not started because it had been enabled through other means and has since been disabled through other means." name))
((and (null enabled) (eq state :disabled))
(print-warning "There is no data available for history data source ~s and recording was already stopped." name))
(enabled
(print-warning "There is no data available for history data source ~s but the recording is currently enabled." name))
(t
(print-warning "There is no data available for history data source ~s and no indication as to why." name))))
(print-warning "There is no data available for history data source ~s and there is no current model to determine the reason why." name))))))))
(t
(print-warning "~s does not name a history data source in call to get-history-data." name))))))))
(add-act-r-command "get-history-data" 'get-history-data-fct "Return the indicated history stream data from the specfied file or current data using indicated parameters if no file given. Params: history-name {file-name-or-nil} {additional-parameters}*")
(defmacro process-history-data (name &optional file data-params processor-params)
`(process-history-data-fct ',name ',file ',data-params ',processor-params))
(defun process-history-data-fct (name &optional file data-params processor-params)
#+:single-threaded-act-r (when file
(print-warning "History file access unavailable in single-threaded model.")
(return-from process-history-data-fct))
(if (not (stringp name))
(print-warning "Process-history-data given name ~s but names must be strings." name)
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(setf name (string->name name))
(let ((p (gethash name (history-recorder-streams-table history-recorder))))
(if (data-processor-p p)
(multiple-value-bind (data comment) (apply 'get-history-data-fct (data-stream-external-name (data-processor-stream p)) file data-params)
(if data
(let ((d (dispatch-apply-list (data-processor-get p) (append (list data) processor-params))))
(multiple-value-bind (result err)
(ignore-errors (json:encode-json-to-string d))
(if (subtypep (type-of err) 'condition)
(print-warning "Error ~/print-error-message/ encountered converting data from ~s to JSON." err d)
(values result comment))))
(print-warning "No history data available from the source for processor ~a" name)))
(print-warning "~a does not name a history data processor in call to process-history-data" name)))))))
(add-act-r-command "process-history-data" 'process-history-data-fct "Return the result of applying the named processor to the history data from the specfied file or current data using indicated parameters if no file given. Params: processor-name {file-name-or-nil} {additional-parameters}*")
(defun start-incremental-history-data-fct (name size &optional file &rest rest)
#+:single-threaded-act-r (when file
(print-warning "History file access unavailable in single-threaded model.")
(return-from start-incremental-history-data-fct))
(if (not (stringp name))
(print-warning "Start-incremental-history-data given name ~s but names must be strings." name)
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(if file
(multiple-value-bind (results comment) (apply 'get-history-data-fct (append (list name) (list (if file file nil)) rest))
(if results
(let* ((id (incf (history-recorder-current-id history-recorder)))
(data (json:decode-json-from-string results))
(segments (ceiling (length results) size))
(step-size (max 1 (floor (length data) segments))))
(setf (gethash id (history-recorder-incremental-table history-recorder))
(list :file step-size (if comment comment "") data))
id)
nil))
(let ((results (apply 'get-history-data-fct name file rest)))
(if results
(let* ((id (incf (history-recorder-current-id history-recorder)))
(data (json:decode-json-from-string results))
(segments (ceiling (length results) size))
(step-size (max 1 (floor (length data) segments))))
(setf (gethash id (history-recorder-incremental-table history-recorder))
(list :data step-size data))
id)
nil)))))))
(add-act-r-command "start-incremental-history-data" 'start-incremental-history-data-fct "Returns an id for incrementally acquiring the history data from the specfied file or current data using the indicated parameters if no file given in segements roughly the length specified. Params: processor-name byte-size-suggestion {file-name-or-nil} {additional-parameters}*")
(defun get-incremental-history-data-fct (id)
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(multiple-value-bind (item exists) (gethash id (history-recorder-incremental-table history-recorder))
(if exists
(if (eq (car item) :file)
(let* ((step (second item))
(comment (third item))
(data (fourth item))
(send (json:encode-json-to-string comment)))
(setf (gethash id (history-recorder-incremental-table history-recorder)) (list :data step data))
send)
(let* ((step (second item))
(data (third item))
(end (min step (length data)))
(sub (subseq data 0 end))
(send (json:encode-json-to-string sub))
(remain (when (<= end (length data)) (subseq data end))))
(if data
(setf (gethash id (history-recorder-incremental-table history-recorder)) (list :data step remain))
(remhash id (history-recorder-incremental-table history-recorder))
)
send))
(print-warning "Invalid id ~s given for get-incremental-history-data." id))))))
(add-act-r-command "get-incremental-history-data" 'get-incremental-history-data-fct "Return the next segment from the history data associated with the given id or an empty list if there is no more data. Params: id")
(defmacro save-history-data (name file &optional comment &rest rest)
`(save-history-data-fct ',name ',file ',comment ',@rest))
(defun save-history-data-fct (name file &optional comment &rest rest)
#+:single-threaded-act-r (when file
(print-warning "History file access unavailable in single-threaded model.")
(return-from save-history-data-fct))
(if (not (stringp name))
(print-warning "Save-history-data given name ~s but names must be strings." name)
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(setf name (string->name name))
(let* ((start (gethash name (history-recorder-streams-table history-recorder)))
(s (cond ((data-stream-p start)
(aif (data-stream-parent start) it start))
((data-processor-p start)
(data-processor-stream start)))))
(if s
(let ((data (apply 'get-history-data-fct (append (list (data-stream-external-name s) nil) rest))))
(if data
(handler-case
(progn
(with-open-file (f file :direction :output :if-does-not-exist :create :if-exists :supersede)
(format f "{\"name\": \"~a\",~%" (data-stream-internal-name s))
(multiple-value-bind (second minute hour date month year) (get-decoded-time)
(format f "\"date\": \"~d/~2,'0d/~2,'0d ~2,'0d:~2,'0d:~2,'0d\",~%" year month date hour minute second))
(format f "\"version\": ~s,~%" (act-r-version-string))
(if (stringp comment)
(format f "\"comment\": ~s,~%" comment)
(print-warning "A comment for save-history-data must be a string but given ~s which will be ignored." comment))
(format f "\"data\": ~s~%}" data))
t)
(error (x)
(print-warning "Error ~/print-error-message/ occurred while trying to save history ~s to file ~s." x name file)))
(print-warning "No history data available for ~a in call to save-history-data." name)))
(print-warning "~a does not name a history data source item in call to save-history-data." name)))))))
(add-act-r-command "save-history-data" 'save-history-data-fct "Save the current history data from the indicated history stream and parameters to the specifed file. Params: history-name file-name {additional-parameters}*")
(defun parse-saved-history-data (requested file)
#+:single-threaded-act-r (when file
(print-warning "History file access unavailable in single-threaded model.")
(return-from parse-saved-history-data))
(handler-case
(let* ((d (json:decode-json-from-source file))
(name (cdr (assoc :name d)))
(version (cdr (assoc :version d)))
(data (cdr (assoc :data d)))
(comment (cdr (assoc :comment d))))
(if (eq (string->name name) requested)
(progn
(written-for-act-r-version version (format nil "Saved history data stream ~s in file ~s" requested file))
(if comment
(values data comment)
data))
(print-warning "File ~s contains data for history ~s instead of desired history ~s." file name requested)))
(error (x)
(print-warning "Error ~/print-error-message/ occurred while trying to read history ~s from file ~s." x requested file))))
(defmacro record-history (&rest names)
`(apply 'record-history-fct ',names))
(defun record-history-fct (&rest names)
(let ((history-recorder (get-component history-recorder))
(results (make-list (length names) :initial-element nil)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(dotimes (i (length names) (values-list results))
(let ((n (nth i names)))
(if (not (stringp n))
(print-warning "Record-history given name ~s but names must be strings." n)
(let* ((o-name (string->name n))
(start (gethash o-name (history-recorder-streams-table history-recorder)))
(s (cond ((data-stream-p start)
start)
((data-processor-p start)
(data-processor-stream start))))
(name (when s (data-stream-internal-name s))))
(if s
(let ((m (if (data-stream-model-based s)
(suppress-warnings (get-module :history-recorder))
(history-recorder-module history-recorder))))
(if m
(multiple-value-bind (enabled data alive)
(dispatch-apply (data-stream-status s))
(declare (ignore data))
(if alive
(let ((state (gethash name (history-module-state-table m))))
(cond ((and enabled (or (eq state :disabled) (null state)))
(setf (gethash name (history-module-state-table m))
:was-enabled))
(enabled
;; do nothing - either was-enabled or enabled so what expected
)
((and (null enabled) (eq state :enabled))
(print-warning "History data source ~s should have already been recording, but was off and is being re-enabled." name)
(dispatch-apply (data-stream-enable s)))
((and (null enabled) (eq state :was-enabled))
(print-warning "History data source ~s had been enabled for recording by other means and is now off, but is being re-enabled." name)
(dispatch-apply (data-stream-enable s)))
((null enabled)
(dispatch-apply (data-stream-enable s))
(setf (gethash name (history-module-state-table m)) :enabled)))
(if (gethash name (history-module-requests-table m))
(incf (gethash name (history-module-requests-table m)))
(setf (gethash name (history-module-requests-table m)) 1))
(when (data-stream-parent s)
(unless (dispatch-apply (data-stream-status (data-stream-parent s)))
(print-warning "Data source constituent ~s enabled but parent source ~s is not." name (data-stream-external-name (data-stream-parent s)))))
(setf (nth i results) t))
(print-warning "Cannot enable history data source ~s because the current source is no longer available." name)))
(print-warning "Cannot enable model-based history data source ~s when no model is available." name)))
(print-warning "~s does not name a history data source in call to record-history." n)))))))))
(add-act-r-command "record-history" 'record-history-fct "Start recording the named history information if not already being recorded. Params: history-name*")
(defmacro stop-recording-history (&rest names)
`(apply 'stop-recording-history-fct ',names))
(defun stop-recording-history-fct (&rest names)
(let ((history-recorder (get-component history-recorder))
(results (make-list (length names) :initial-element nil)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(dotimes (i (length names) (values-list results))
(let ((n (nth i names)))
(if (not (stringp n))
(print-warning "Stop-recording-history given name ~s but names must be strings." n)
(let* ((o-name (string->name n))
(start (gethash o-name (history-recorder-streams-table history-recorder)))
(s (cond ((data-stream-p start)
start)
((data-processor-p start)
(data-processor-stream start))))
(name (when s (data-stream-internal-name s))))
(if s
(let ((m (if (data-stream-model-based s)
(suppress-warnings (get-module :history-recorder))
(history-recorder-module history-recorder))))
(if m
(multiple-value-bind (enabled data alive)
(dispatch-apply (data-stream-status s))
(declare (ignore data))
(when alive ;; if it's not alive don't care about disabling and no need to warn
(let ((state (gethash name (history-module-state-table m)))
(val (gethash name (history-module-requests-table m))))
(cond ((and val (numberp val) (plusp val))
(setf val (decf (gethash name (history-module-requests-table m)))))
((and val (not (and (numberp val) (zerop val))))
(print-warning "Clearing unexpected value in recording table when attempting to stop recording of history source ~s." name)
(setf (gethash name (history-module-requests-table m)) 0
val 0))
(t
(print-warning "Attempting to stop recording history source ~s but it hasn't explicitly been started." name)))
(setf (nth i results)
(cond ((and enabled (eq state :enabled) (zerop val))
(dispatch-apply (data-stream-disable s))
(setf (gethash name (history-module-state-table m))
:disabled)
t)
((and enabled (eq state :enabled))
; do nothing already decremented
nil)
((and enabled (null state))
(setf (gethash name (history-module-state-table m))
:was-enabled)
(print-warning "Cannot disable recording for history source ~s because it was enabled by other means." name))
(enabled
(print-warning "Cannot disable recording for history source ~s because it was enabled by other means." name))
((and (eq state :enabled) (zerop val))
(setf (gethash name (history-module-state-table m)) :disabled)
(print-warning "History recording for history source ~s was disabled by other means." name)
t)
((eq state :enabled)
(print-warning "History recording for history source ~s was disabled externally but there are still pending requests to start it." name))
((null state)
t)
(t
(print-warning "History recording for history source ~s encounterd unexpected state because it toggled from enabled to disabled through other means." name)))))))
(print-warning "Cannot disable model-based history data source ~s when no model is available." name)))
(print-warning "~s does not name a history data source in call to stop-recording-history." n)))))))))
(add-act-r-command "stop-recording-history" 'stop-recording-history-fct "Stop recording the named history information if all requested starts have stopped. Params: history-name*")
(defun reset-history-recorder (module)
;; If there are any unstopped starts (>0 value in requests)
;; make sure it's turned on
(let ((history-recorder (get-component history-recorder)))
(bt:with-recursive-lock-held ((history-recorder-lock history-recorder))
(maphash (lambda (name val)
(when (and (numberp val) (> val 0))
(let ((s (gethash name (history-recorder-streams-table history-recorder))))
(when s
(unless (dispatch-apply (data-stream-status s))
(dispatch-apply (data-stream-enable s)))))))
(history-module-requests-table module)))))
(defun create-history-recorder-module (x)
(declare (ignore x))
(make-history-module))
(define-module-fct :history-recorder nil nil
:creation 'create-history-recorder-module
:reset '(nil nil reset-history-recorder)
:required t
:version "2.2"
:documentation "Module to support the saving and accessing of information as a model runs.")
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 47,052 | Common Lisp | .lisp | 708 | 52.70904 | 367 | 0.568716 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 661d9d3fa5bce8d3f36ca619a320c781760c0478aabb29e9d81f8f96c69e4383 | 14,320 | [
-1
] |
14,321 | device-interface.lisp | asmaloney_ACT-R/framework/device-interface.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Authors : Mike Byrne & Dan Bothell
;;; Address : Rice University, MS-25
;;; : Psychology Department
;;; : Houston,TX 77251-1892
;;; : [email protected]
;;;
;;; Copyright : (c)1998-2005 Mike Byrne & Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LICENSE.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : device-interface.lisp
;;; Version : 7.3
;;;
;;; Description : File for managing the device interface.
;;;
;;; Bugs : None known.
;;;
;;; Todo : Nothing pending.
;;;
;;; ----- History -----
;;; 2004.10.19 Dan [Moved into ACT-R 6]
;;; : Lots of changes - first being a reset of version to 1.0a1
;;;
;;; : Added the package switches for the act-r package and
;;; : the "clean" packaging
;;;
;;; : Removed the following:
;;; pm-get-time, pm-timed-event, pm-delayed-event
;;; new functions replace these: mp-time and all of the
;;; new scheduling functions
;;; may want to put back as depricated to ease transition
;;;
;;; reset-module
;;; because a model reset calls reset-device directly
;;;
;;; run-events, new-message
;;; everything goes through the central scheduler
;;; instead of separate event queues
;;;
;;; pm-install-module, update-module, silent-events
;;; master-process functionality replaced
;;;
;;; process-display and update-cursor-feat
;;; moved specific methods to the vision module since
;;; that's really more the critical class and the
;;; device preceeds the specific modules now
;;;
;;; : Added:
;;; current-device-interface, install-device,
;;; current-device, proc-display
;;;
;;; : Moved these from elsewhere to here
;;; pm-angle-to-pixels, pm-pixels-to-angle
;;; 2005.01.11 mdb
;;; : Added a couple toplevel functions for backward compatibility.
;;;
;;; 2005.01.12 Dan
;;; : Made the device an actual module so that it can have its
;;; : own parameters.
;;; :
;;; : Moved the newly added backward compatibility functions to the
;;; : backward file in support.
;;; 2005.01.13 Dan
;;; : * Added the the two new methods lock-device and unlock-device
;;; : along with the appropriate slots and changes to reset-device
;;; : to allow other modules to block and unblock proc-display
;;; : from actually going. [Right now, that's a problem with
;;; : productions potentially jamming vision if a proc-display
;;; : happens between the time of the query for free and the
;;; : time that the +visual command is actually sent.]
;;; 2005.02.17 Dan
;;; : * Fixed the references in the *pixels-per-inch-* settings
;;; : so that ACL gets the packaging correct.
;;; 2005.05.11 Dan
;;; : * Added the :vwt paramter and corresponding virtual-trace
;;; : slot to the device interface to control the output of the
;;; : << ... >> printing from the vw-output command used by the
;;; : virtual window device.
;;; 2005.08.10 Dan
;;; : * Removed a duplicate definition of prod-display.
;;; 2005.11.02 Dan
;;; : * Updated unlock-device so that tracking updates can be
;;; : recognized and handled as well as full proc-displays.
;;; 2006.03.07 Dan
;;; : * Fixed an old bug which I don't know how it got back in...
;;; : the theta for hyphen in the key mapping should be -1.11.
;;; 2006.03.08 Dan
;;; : * Made the key-to-loc and key-to-command tables consistent
;;; : with respect to - and hyphen. Both tables now have entries
;;; : for both symbols mapped to the same things.
;;; 2006.09.11 Dan
;;; : * Changed valid test for :mouse-fitts-coeff from posnum to nonneg.
;;; 2006.12.14 Dan
;;; : * Changed current-device-interface so that it only returns
;;; : one value.
;;; : * Reset all the versions to 1.1...
;;; 2006.12.18 Dan
;;; : * Removed the :speech-hook parameter since it was depricated
;;; : long ago.
;;; : * Also removed the :output-speech parameter because it doesn't
;;; : really have a purpose now - the default devices all have a
;;; : device-speak-string method even if it doesn't do anything.
;;; 2006.12.28 Dan
;;; : * Made proc-display better check for current mp/model/device.
;;; 2007.01.09 Dan
;;; : * Make output-key check the keyboard array boundaries to avoid
;;; : errors when bad key-locations come in.
;;; 2007.05.24 Dan
;;; : * Removed the device-hook slot and call from the update-device
;;; : method since it was depricated long ago.
;;; 2007.06.20 Dan
;;; : * Changed dmo-to-xy to xy-loc for use with the new vision
;;; : module.
;;; : * Replaced the generic build-features-for and cursor-to-feature
;;; : with build-vis-loc-for and cursor-to-vis-loc.
;;; 2007.07.16 Dan
;;; : * Fixed a bug in the default device-speak-string method that
;;; : would cause it to throw the "wrong" error.
;;; 2008.08.11 Dan [1.2]
;;; : * Added a new parameter :stable-loc-names which controls
;;; : whether or not the virtual device sorts the subviews to
;;; : guarantee the same names on different runs. The default is
;;; : t which means it still does the sorting. Setting it to nil
;;; : should improve performance when using the virtual devices.
;;; : * Also took the package setting out of the mode line at the
;;; : top since there isn't a specific package for any of the
;;; : source files.
;;; 2009.09.08 Dan
;;; : * Fixed the key-to-command mapping for the period.
;;; 2010.08.26 Dan
;;; : * Why is the space bar represented as space in the the
;;; : key->command table but spc in the key->loc table, and
;;; : why is it entered multiple times when they're all just
;;; : overwriting the same entry? Adding an entry for space
;;; : into the key->loc table at 6,6 so there's at least a
;;; : way to relate things.
;;; 2011.01.19 Dan
;;; : * Changed unlock-device to use unlock-tracking instead of
;;; : update-tracking since that has been depricated.
;;; 2011.04.28 Dan
;;; : * Added some declaims to avoid compiler warnings about
;;; : undefined functions.
;;; 2011.05.16 Dan
;;; : * Added a parameter to allow enabling trace-mouse-p and added
;;; : a function, get-mouse-trace, to return the list of postions
;;; : and times that have been recorded.
;;; 2011.11.21 Dan
;;; : * Removing *actr-enabled-p* since it doesn't really do much
;;; : of anything important, but its use in the tutorial models
;;; : makes it seem like it's something "special" and that requires
;;; : edit/save/reloads which aren't really needed.
;;; : Instead, replacing it with a command model-generated-action
;;; : which returns true during the handling of the device methods
;;; : that get called as a result of the model performing the
;;; : action so that they can be distinguished from a person if
;;; : needed. However, this can't really be used at the "user"
;;; : level in general because it may or may not be valid during
;;; : the rpm-window- handler or the button action functions
;;; : when "real windows" are being used.
;;; 2012.06.26 Dan [1.3]
;;; : * An installed device no longer persists across a reset.
;;; : * Update-attended-loc now only gets called when the attention
;;; : actually changes or when the device changes.
;;; : * Update-attended-loc can now get called with nil for the location
;;; : when the vision module "stops" attending to something which
;;; : can happen when there's an explicit visual clear request or
;;; : when the device changes, and it also gets called with nil
;;; : when the window gets initially installed.
;;; : * There is a slot in the device interface for holding the
;;; : attention marker which can be used so that each model has
;;; : its own: it can be accessed via the visual-fixation-marker
;;; : function which takes no parameters and there is a setf function
;;; : defined for it. It returns the value for that slot from the
;;; : current model's device interface. It defaults to nil when
;;; : the model is initialized, but isn't changed at reset time
;;; : since the device itself could persist.
;;; 2012.08.27 Dan
;;; : * Changed the indicate-model-generated macro to actually setf
;;; : the variable instead of using a let so that it "works" when
;;; : different processes may need to check the value since
;;; : the rpm-window-key-event-handler may be called from an event
;;; : thread instead of in the "ACT-R" thread.
;;; 2012.09.07 Dan
;;; : * Removed the test for :actr-env-alone in the pixels-per-inch
;;; : setting for ACL.
;;; 2014.04.24 Dan
;;; : * Added commands to the press-key table so that all the keys
;;; : in the "primary area" have a mapping, but it does assume that
;;; : the model has a long right pinkie and can hit things 3+ keys
;;; : away without moving the hand...
;;; : * Renamed some of the keys in the loc table because there were
;;; : duplicates between the "primary area" and the keypad. Now
;;; : all of the keypad keys which appear in both areas are
;;; : prefixed with "keypad-".
;;; 2014.05.21 Dan [2.0]
;;; : * Just now noticed that the pixels-to-angle code isn't quite
;;; : right given that we compute the location of something as
;;; : it's center point. It should be 2*(atan (/ (w/2) d) not
;;; : just (atan (/ w d)) because that assumes a view from one
;;; : end. Of course, it's even odder than that because we also
;;; : consider everything on the screen as the same distance, but
;;; : really that's only true if the display is a spherical
;;; : surface centered on the viewing position...
;;; : The difference in values between those 2 calculations is
;;; : generally negligible for the typical sizes and default
;;; : viewing distance. However, since I'm adding in code to
;;; : allow for distances other than the default I'm going to
;;; : switch to the "better" calculation.
;;; 2014.10.31 Dan
;;; : * Changed synch-mouse so that it has an optional parameter
;;; : for indicating whether the action was "model generated"
;;; : instead of treating all usage like it was.
;;; 2015.05.20 Dan
;;; : * Adding a new method for devices: vis-loc-coordinate-slots.
;;; : It needs to return a list of three values which indicate the
;;; : names of the slots used to hold the x, y, and z coordinates
;;; : respectively for the visual location chunks created by the
;;; : device. The default is '(screen-x screen-y distance), but
;;; : now one can use something else instead.
;;; : It is only called when the device is installed thus it can't
;;; : change dynamically and must be consistent for all features
;;; : in the device.
;;; 2015.05.21 Dan
;;; : * Fixed the decalim for xy-loc.
;;; 2015.09.01 Dan
;;; : * Added press-key shortcuts for the keypad assuming that the
;;; : hand has been moved to it with hand-to-keypad or start-hand-
;;; : at-keypad.
;;; 2016.04.04 Dan [2.1]
;;; : * Allow :show-focus to also take string and symbol values for
;;; : true. Those values MAY be used by the device to indicate
;;; : a color for the fixation ring.
;;; 2016.07.20 Dan
;;; : * Update-device now sends the clof value to device-update-attended-loc
;;; : since the current-marker value may not be a chunk anymore.
;;; 2016.12.15 Dan [3.0]
;;; : * Start of the work to basically eliminate the device approach
;;; : to PM interfacing to better support remote modeling. For now
;;; : all I've done is remove proc-display and the lock/unlock-device
;;; : commands since those really belong to vision.
;;; 2016.12.16 Dan
;;; : * Removed the declaim for unlock-tracking and the pending-procs
;;; : slot.
;;; 2016.12.19 Dan
;;; : * Remove the generic process-display method.
;;; 2017.01.05 Dan
;;; : * Complete overhaul. This is no longer tied to any particular
;;; : modules by default. A module must register as an interface
;;; : if it needs access to "devices". Devices must be registered
;;; : as well. Both the interface and the device indicate init
;;; : and remove commands (if needed) when registered. Install-
;;; : device takes a list of 2 or 3 items: module device {details}.
;;; : When installing a device:
;;; : - if that device and details are already installed for
;;; : indicated module then do nothing
;;; : - else
;;; : - if the indicated module only allows a single device and
;;; : there is one already installed
;;; : call the remove commands for the module then device
;;; : - call the init commands for the module and device
;;; : - store the record for this device being installed
;;; 2017.01.11 Dan
;;; : * Removed the show-focus parameter and moved it to vision.
;;; 2017.01.13 Dan
;;; : * Added the interface function to a device definition and the
;;; : signal-device command for communicating with it through that
;;; : function.
;;; : * Removed the keyboard related code.
;;; 2017.01.18 Dan
;;; : * Removed the echo-act-r-output from commands. The assumption
;;; : now is that echoing is handled by the user.
;;; : * Use handle-evaluate-results.
;;; 2017.01.26 Dan
;;; : * Removed output-speech. That happens directly from speech
;;; : module now.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Reworked the local versions of most remote commands to not
;;; : go out through the dispatcher.
;;; : * Fixed bugs with the last change.
;;; 2017.03.02 Dan
;;; : * Removed all the mouse code.
;;; 2017.03.03 Dan
;;; : * Remove-device now returns t when remove is successful.
;;; 2017.03.07 Dan [4.0]
;;; : * Signal-device command can't be single instance because it
;;; : may be possible for a device being signaled to signal another
;;; : which would cause a deadlock (the mouse signaling the exp-window
;;; : is where it occurred).
;;; : * Reset and delete need to remove any installed devices.
;;; : * Adding a delete function to handle that now.
;;; : * When installing a device put it on the list before calling
;;; : the init functions so that it can be referenced from there.
;;; : Not certain that's the best way to handle things yet, but it
;;; : fixes an issue with a window installing a mouse that then
;;; : needs to tell the window to draw the mouse...
;;; 2017.06.02 Dan
;;; : * Wrapped some handle-evaluate-results around the evaluate
;;; : calls to catch errors.
;;; 2017.06.16 Dan
;;; : * Adding a lock for protecting the device slot of the interface,
;;; : a lock for the device-table and interface-table, a lock for the
;;; : visual-fixation-marker, and a lock for the params.
;;; : * Removed the mouse tracing param and slots.
;;; 2017.06.20 Dan
;;; : * Rewored install-, remove-, and signal- device to only lock as
;;; : needed to avoid issues with devices that install devices (like
;;; : experiment windows) and a recursive lock won't help because
;;; : since the interface/device actions themselves could be dispatched.
;;; : * Also marking them as not single instance.
;;; 2017.06.23 Dan
;;; : * Added names for all the locks.
;;; 2017.08.03 Dan
;;; : * Actually store the name of the interface in the structure.
;;; 2017.08.09 Dan
;;; : * Remove all the declaims since they're unnecessary now.
;;; 2017.08.17 Dan
;;; : * Fixed a potential deadlock with respect to delete-device
;;; : because it called the remove functions for devices and
;;; : interfaces while it held the device module's locks.
;;; 2017.10.11 Dan
;;; : * Eliminate the vwt parameter and virtual-trace slot.
;;; 2018.01.29 Dan
;;; : * Reformating the remove-device code since I was trying to
;;; : figure out a problem with removing a mouse and realized that
;;; : the indentation was off for remove-device eventhough it did
;;; : work correctly.
;;; 2018.02.08 Dan
;;; : * Don't abort from delete-device just because some device fails.
;;; : Print a warning about that and continue with the rest.
;;; 2018.03.05 Dan
;;; : * Rename signal-device notify-device since I call commands
;;; : with no function signals...
;;; : * Why does notify-device have to go through dispatcher? Is
;;; : that necessary -- should it be monitorable?
;;; 2018.03.12 Dan [5.0]
;;; : * Added available-devices and available-interfaces functions.
;;; : * Reworking it so that it's possible to install more than
;;; : one of the same device -- that simplifies things with
;;; : respect to a mouse because the device can be a cursor and
;;; : the details can then specify mouse, joystick1, or joystick2
;;; : and the same move-cursor command can just use whichever
;;; : cursor device the hand is on. It also allows more than
;;; : one exp-window to be installed which means the cursor
;;; : can be in global coordinates and if the windows translate
;;; : things appropriately multiple windows could be available
;;; : to vision at the same time.
;;; : * Interface fns all get whole device-list.
;;; 2018.03.14 Dan
;;; : * Needs-mouse param can now be a symbol or string and will be
;;; : converted to a color for the outline like show-focus does
;;; : since each model has its own mouse now. It also defaults to
;;; : nil instead of t to avoid having to deal with it unless it's
;;; : actually needed.
;;; 2018.04.25 Dan [6.0]
;;; : * Eliminate the *pixels-per-inch-?* variables and just default
;;; : to 72.
;;; : * Removed the visual-fixation-marker support and the cursor-loc.
;;; : * Renamed :mouse-fitts-coeff to :cursor-fitts-coeff.
;;; 2018.04.26 Dan
;;; : * Current-devices now prints a warning if an invalid interface
;;; : is provided.
;;; : * Added a remote current-devices.
;;; : * Defined-devices and defined-interfaces don't require a current
;;; : model to operate.
;;; 2018.05.21 Dan
;;; : * Renamed the slot from act-r-device-interface to -notification
;;; : since it's called from notify-device to keep the terminology
;;; : consistent.
;;; 2018.05.30 Dan
;;; : * Put the key-closure-time param here instead of it being a
;;; : fixed value (it was being added in the motor extensions).
;;; 2018.06.13 Dan
;;; : * Updated the doc strings for remote commands to match the
;;; : current spec style.
;;; 2018.10.04 Dan [7.0]
;;; : * An interface can now also provide a notification function
;;; : and there's a notify-interface command. That allows for
;;; : a better separation of device from module (for example
;;; : keyboard and cursor device implementations currently access
;;; : the motor module directly).
;;; : * Create a global variable with a default device interface to
;;; : avoid having to create one for the non-model based commands.
;;; : * Notify-device and notify-interface decode the features provided
;;; : from external calls with the embedded string mechanism, but
;;; : don't decode the device or interface names.
;;; 2018.11.01 Dan [7.1]
;;; : * A device now has two additional optional functions it can
;;; : specify which are called by the motor module when a hand is
;;; : set to the device and when the hand is unset from the device.
;;; : They are called with two parameters: the device-list and the
;;; : hand (left or right).
;;; : * Moved the default-target-width parameter here from motor.
;;; 2020.01.10 Dan [7.2]
;;; : * Removed the #' and lambdas from the module interface functions
;;; : since that's not allowed in the general system now.
;;; 2021.10.19 Dan [7.3]
;;; : * Set the required flag for the module to a list of :motor,
;;; : :vision, and :speech, but it may be needed at other times
;;; : since it handles all devices.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Class for the device-interface and a default one for convenience.
(defclass device-interface ()
((pixels-per-inch :accessor ppi :initarg :ppi :initform 72)
(viewing-distance :accessor viewing-distance :initform 15.0)
(device :accessor device :initform nil)
(device-lock :accessor device-lock :initform (bt:make-lock "device-lock"))
(key-closure-time :accessor key-closure-time :initform 0.010)
(with-cursor-p :accessor with-cursor-p :initform nil)
(mouse-fitts-coeff :accessor mouse-fitts-coeff :initform 0.1)
(show-focus-p :accessor show-focus-p :initarg :show-focus-p :initform nil)
(needs-mouse-p :accessor needs-mouse-p :initarg :needs-mouse-p :initform t)
(version-string :accessor version-string :initarg :version-string :initform "7.3")
(stable-names :accessor stable-names :initarg :stable-names :initform t)
(param-lock :accessor device-param-lock :initform (bt:make-lock "device-param"))
(device-tables-lock :accessor device-tables-lock :initform (bt:make-lock "device-tables") :allocation :class)
(interface-table :accessor interface-table :initform (make-hash-table :test 'equalp) :allocation :class)
(default-target-width :accessor default-target-width :initarg :default-target-width :initform 1.0)
(device-table :accessor device-table :initform (make-hash-table :test 'equalp) :allocation :class)))
(defvar *default-device-interface* (make-instance 'device-interface))
(defstruct interface name init remove single-device notification)
(defstruct act-r-device init remove notification set unset)
(defun define-interface (name &optional init remove single? notification)
(let ((di *default-device-interface*))
(bt:with-lock-held ((device-tables-lock di))
(if (gethash name (interface-table di))
(print-warning "Interface ~s already exists and cannot be created." name)
(progn
(when init
(unless (check-act-r-command init)
(print-warning "Init function ~s specified for interface ~s is not available. Cannot create interface." init name)
(return-from define-interface)))
(when remove
(unless (check-act-r-command remove)
(print-warning "Remove function ~s specified for interface ~s is not available. Cannot create interface." remove name)
(return-from define-interface)))
(when notification
(unless (check-act-r-command notification)
(print-warning "Notification function ~s specified for interface ~s is not available. Cannot create interface." notification name)
(return-from define-interface)))
(setf (gethash name (interface-table di)) (make-interface :name name :init init :remove remove :single-device single? :notification notification))
t)))))
(add-act-r-command "define-interface" 'define-interface "Command to add a new interface. Params: name {init-command {remove-command {single-device {notification}}}}")
(defun undefine-interface (name)
(let ((di *default-device-interface*))
(bt:with-lock-held ((device-tables-lock di))
(when (gethash name (interface-table di))
(remhash name (interface-table di))
t))))
(add-act-r-command "undefine-interface" 'undefine-interface "Command to remove an interface. Params: name")
(defun notify-interface (name features)
"Send the provided features to the named interface"
(let* ((di *default-device-interface*)
(interface (bt:with-lock-held ((device-tables-lock di)) (gethash name (interface-table di)))))
(if interface
(aif (interface-notification interface)
(dispatch-apply it features)
(print-warning "Interface ~s does not accept notifications. Ignoring notification features ~s." name features))
(print-warning "Interface ~s could not be found when calling notify-interface with features ~s." name features))))
(defun external-notify-interface (name features)
(notify-interface name (decode-string-names features)))
(add-act-r-command "notify-interface" 'external-notify-interface "Send features to the indicated interface. Params: interface 'features'" nil)
(defun define-device (name &optional init remove notification set-hand unset-hand)
(let ((di *default-device-interface*))
(bt:with-lock-held ((device-tables-lock di))
(if (gethash name (device-table di))
(print-warning "Device ~s already exists and cannot be created." name)
(progn
(when init
(unless (check-act-r-command init)
(print-warning "Init function ~s specified for device ~s is not available. Cannot define device."
init name)
(return-from define-device)))
(when remove
(unless (check-act-r-command remove)
(print-warning "Remove function ~s specified for device ~s is not available. Cannot define device."
remove name)
(return-from define-device)))
(when notification
(unless (check-act-r-command notification)
(print-warning "Notification function ~s specified for device ~s is not available. Cannot define device."
notification name)
(return-from define-device)))
(when set-hand
(unless (check-act-r-command set-hand)
(print-warning "Set-hand function ~s specified for device ~s is not available. Cannot define device."
set-hand name)
(return-from define-device)))
(when unset-hand
(unless (check-act-r-command unset-hand)
(print-warning "Unset-hand function ~s specified for device ~s is not available. Cannot define device."
unset-hand name)
(return-from define-device)))
(setf (gethash name (device-table di)) (make-act-r-device :init init :remove remove :notification notification :set set-hand :unset unset-hand))
t)))))
(add-act-r-command "define-device" 'define-device "Command to add a new device. Params: name {init-command {remove-command {notification-command {hand-set {hand-unset}}}}")
(defun undefine-device (name)
(let ((di *default-device-interface*))
(bt:with-lock-held ((device-tables-lock di))
(when (gethash name (device-table di))
(remhash name (device-table di))
t))))
(add-act-r-command "undefine-device" 'undefine-device "Command to remove a device. Params: name")
(defun install-device (device-list)
"Set a device with which a model will interact"
(verify-current-model
"install-device called with no current model."
(if (and (listp device-list)
(<= 2 (length device-list) 3))
(let ((interface-name (first device-list))
(device-name (second device-list))
(devin (current-device-interface))
interface device)
(bt:with-lock-held ((device-tables-lock devin))
(setf interface (gethash interface-name (interface-table devin)))
(setf device (gethash device-name (device-table devin))))
(cond ((null interface)
(print-warning "Invalid interface ~s in call to install-device with ~s. No device installed."
interface-name device-list))
((null device)
(print-warning "Invalid device ~s in call to install-device with ~s. No device installed."
device-name device-list))
(t
(let ((d (bt:with-lock-held ((device-lock devin))
(device devin))))
(if (find device-list d :test 'equalp)
(print-warning "The device ~s is already installed. No device installed." device-list)
(progn
(awhen (and (interface-single-device interface)
(find interface-name d :key 'first :test 'string-equal))
(when (interface-remove interface)
(unless (handle-evaluate-results (evaluate-act-r-command (interface-remove interface) it))
(return-from install-device nil)))
(when (act-r-device-remove device)
(unless (handle-evaluate-results (evaluate-act-r-command (act-r-device-remove device) it))
(return-from install-device nil)))
(bt:with-lock-held ((device-lock devin))
(setf d (setf (device devin) (remove it (device devin))))))
;; should be there before trying to init
;; but needs to be removed if errors occur
(bt:with-lock-held ((device-lock devin))
(push device-list (device devin)))
(when (interface-init interface)
(unless (handle-evaluate-results (evaluate-act-r-command (interface-init interface) device-list))
(bt:with-lock-held ((device-lock devin))
(setf (device devin) (remove device-list (device devin))))
(return-from install-device nil)))
(when (act-r-device-init device)
(unless (handle-evaluate-results (evaluate-act-r-command (act-r-device-init device) device-list))
(bt:with-lock-held ((device-lock devin))
(setf (device devin) (remove device-list (device devin))))
(return-from install-device nil)))
device-list))))))
(print-warning "Invalid device-list provided ~s. No device installed." device-list))))
(add-act-r-command "install-device" 'install-device "Command to install a device for an interface. Params: (interface device {device-detail})" nil)
(defun remove-device (device-list)
"Remove a device with which a model is interacting"
(verify-current-model
"remove-device called with no current model."
(let* ((devin (current-device-interface))
(device (bt:with-lock-held ((device-lock devin)) (device devin)))
(exists (find device-list device :test 'equalp)))
(if exists
(let ((interface-name (first device-list))
(device-name (second device-list))
interface device)
(bt:with-lock-held ((device-tables-lock devin))
(setf interface (gethash interface-name (interface-table devin)))
(setf device (gethash device-name (device-table devin))))
;; The warning cases shouldn't happen since it was installed
;; but it's possible that one was undefined after the install
;; which doesn't get caught currently.
(cond ((null interface)
(print-warning "Invalid interface ~s in call to remove-device with ~s. No device removed."
interface-name device-list))
((null device)
(print-warning "Invalid device ~s in call to remove-device with ~s. No device removed."
device-name device-list))
(t
(when (interface-remove interface)
(unless (handle-evaluate-results (evaluate-act-r-command (interface-remove interface) device-list))
(return-from remove-device nil)))
(when (act-r-device-remove device)
(unless (handle-evaluate-results (evaluate-act-r-command (act-r-device-remove device) device-list))
(return-from remove-device nil)))
(bt:with-lock-held ((device-lock devin))
(setf (device devin) (remove exists (device devin))))
t)))
(print-warning "Device ~s is not currently installed and cannot be removed." device-list)))))
(add-act-r-command "remove-device" 'remove-device "Command to remove a device for an interface. Params: (interface device {device-detail})" nil)
(defun current-devices (interface)
"Return the devices for the named interface in the current model"
(verify-current-model
"current-devices called with no current model."
(let ((devin (current-device-interface)))
(bt:with-lock-held ((device-lock devin))
(if (gethash interface (interface-table devin))
(remove-if-not (lambda (x) (string-equal interface (first x))) (device devin))
(print-warning "~s does not name a valid interface in call to current-devices." interface))))))
(add-act-r-command "current-devices" 'current-devices "Get the list of all devices installed for an interface. Params: interface" nil)
(defun current-device-interface ()
"Return the device-interface for current model"
(values (get-module :device)))
(defun defined-devices ()
(let ((di *default-device-interface*))
(bt:with-lock-held ((device-tables-lock di))
(hash-table-keys (device-table di)))))
(defun defined-interfaces ()
(let ((di *default-device-interface*))
(bt:with-lock-held ((device-tables-lock di))
(hash-table-keys (interface-table di)))))
(add-act-r-command "defined-devices" 'defined-devices "Command to get the list of all defined devices. No params" nil)
(add-act-r-command "defined-interfaces" 'defined-interfaces "Command to get the list of all defined interfaces. No params" nil)
(defun notify-device (device-list features)
"Send the provided features to the named device for the specified interface in the current model in the current meta-process if such a function was provided"
(verify-current-model
"notify-device called with no current model."
(let ((di (current-device-interface)))
(if di
(let ((d (bt:with-lock-held ((device-lock di)) (device di))))
(if (find device-list d :test 'equalp)
(let ((device (gethash (second device-list) (bt:with-lock-held ((device-tables-lock di)) (device-table di)))))
(when (and device (act-r-device-notification device))
(let ((res (multiple-value-list (evaluate-act-r-command (act-r-device-notification device) device-list features))))
(if (first res)
(values-list (rest res))
(values-list res))))
;; don't warn if there isn't a device-function just fall through and return nil
)
(print-warning "Device ~s is not installed when trying to notify with features ~s." device-list features)))
(print-warning "Device-interface could not be found when trying notify device ~s." device-list)))))
(defun external-notify-device (device-list features)
(notify-device device-list (decode-string-names features)))
(add-act-r-command "notify-device" 'external-notify-device "Send features to the given device. Params: device-list 'features'" nil)
(defun notify-device-hand-set (device-list hand)
"Call the set-hand command for the device if it has one"
(verify-current-model
"notify-device-hand-set called with no current model."
(let ((di (current-device-interface)))
(if di
(let ((d (bt:with-lock-held ((device-lock di)) (device di))))
(if (find device-list d :test 'equalp)
(let ((device (gethash (second device-list) (bt:with-lock-held ((device-tables-lock di)) (device-table di)))))
(awhen (and device (act-r-device-set device))
(dispatch-apply it device-list hand)))
(print-warning "Device ~s is not installed when trying to notify for hand being set." device-list)))
(print-warning "Device-interface could not be found when trying notify device ~s for hand being set." device-list)))))
(defun notify-device-hand-unset (device-list hand)
"Call the unset-hand command for the device if it has one"
(verify-current-model
"notify-device-hand-set called with no current model."
(let ((di (current-device-interface)))
(if di
(let ((d (bt:with-lock-held ((device-lock di)) (device di))))
(if (find device-list d :test 'equalp)
(let ((device (gethash (second device-list) (bt:with-lock-held ((device-tables-lock di)) (device-table di)))))
(awhen (and device (act-r-device-unset device))
(dispatch-apply it device-list hand)))
(print-warning "Device ~s is not installed when trying to notify for hand being unset." device-list)))
(print-warning "Device-interface could not be found when trying notify device ~s for hand being unset." device-list)))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; some simple device-interface methods.
(defmethod my-name ((mod device-interface))
:DEVICE)
(defgeneric angle->pixels-mth (devin angle &optional dist)
(:documentation "Determine the number of pixels subtending a visual angle."))
(defmethod angle->pixels-mth ((devin device-interface) (angle number) &optional dist)
(bt:with-lock-held ((device-param-lock devin))
(if (numberp dist)
(round (* 2 dist (tan (deg->rad (/ angle 2)))))
(round (* 2 (viewing-distance devin) (ppi devin) (tan (deg->rad (/ angle 2))))))))
(defgeneric pixels->angle-mth (devin pixels &optional dist)
(:documentation "Determine the amount of visual angle subtended by <pixels>."))
(defmethod pixels->angle-mth ((devin device-interface) (pixels number) &optional dist)
(bt:with-lock-held ((device-param-lock devin))
(if (numberp dist)
(rad->deg (* 2 (atan (/ pixels 2) dist)))
(rad->deg (* 2 (atan (/ pixels 2) (* (ppi devin) (viewing-distance devin))))))))
(defgeneric find-viewing-dist-mth (devin angle pixels &optional in-pixels)
(:documentation "Given the number of pixels an angle subtends, what's the viewing distance?"))
(defmethod find-viewing-dist-mth ((devin device-interface) angle pixels &optional in-pixels)
(bt:with-lock-held ((device-param-lock devin))
(if in-pixels
(floor (/ pixels 2) (tan (deg->rad (/ angle 2))))
(floor (/ pixels 2) (* (tan (deg->rad (/ angle 2))) (ppi devin))))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; some simple user commands
(defun pm-pixels-to-angle (pixels &optional dist)
"Convert <pixels> to degress of visual angle."
(pixels->angle-mth (current-device-interface) pixels dist))
(defun pm-angle-to-pixels (angle &optional dist)
"Convert visual <angle> in degress to pixels."
(angle->pixels-mth (current-device-interface) angle dist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The actual module interface code.
(defmethod reset-device ((devin device-interface))
(delete-device devin)
;; Clear the installed devices now
(bt:with-lock-held ((device-lock devin))
(setf (device devin) nil)))
(defmethod delete-device ((devin device-interface))
(let (interface device)
(dolist (device-list (bt:with-lock-held ((device-lock devin)) (device devin)))
(bt:with-lock-held ((device-tables-lock devin))
(setf interface (gethash (first device-list) (interface-table devin))
device (gethash (second device-list) (device-table devin))))
;; The warning cases shouldn't happen since it was installed
;; but it's possible that one was undefined after the install
;; which doesn't get caught currently.
(cond ((null interface)
(print-warning "Invalid interface ~s while trying to remove-device with ~s. No device removed."
(first device-list) device-list))
((null device)
(print-warning "Invalid device ~s while trying to remove-device with ~s. No device removed."
(second device-list) device-list))
(t
(when (interface-remove interface)
(unless (handle-evaluate-results (evaluate-act-r-command (interface-remove interface) device-list))
(print-warning "Interface-remove failed for ~S" device-list)))
(when (act-r-device-remove device)
(unless (handle-evaluate-results (evaluate-act-r-command (act-r-device-remove device) device-list))
(print-warning "Device-remove failed for ~S ~S" (act-r-device-remove device) device-list)))
t)))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Module interface functions
(defun params-device-module (device param)
(bt:with-lock-held ((device-param-lock device))
(if (consp param)
(case (car param)
(:pixels-per-inch
(setf (ppi device) (cdr param)))
(:process-cursor
(setf (with-cursor-p device) (cdr param)))
(:viewing-distance
(setf (viewing-distance device) (cdr param)))
(:cursor-fitts-coeff
(setf (mouse-fitts-coeff device) (cdr param)))
(:needs-mouse
(setf (needs-mouse-p device) (cdr param)))
(:default-target-width
(setf (default-target-width device) (cdr param)))
(:stable-loc-names
(setf (stable-names device) (cdr param)))
(:key-closure-time
(setf (key-closure-time device) (cdr param)))
)
(case param
(:pixels-per-inch
(ppi device))
(:process-cursor
(with-cursor-p device))
(:viewing-distance
(viewing-distance device))
(:cursor-fitts-coeff
(mouse-fitts-coeff device))
(:needs-mouse
(needs-mouse-p device))
(:key-closure-time
(key-closure-time device))
(:stable-loc-names
(stable-names device))
(:default-target-width
(default-target-width device))))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Interface functions
(defun tornilorsymbolorstring (x) (or (tornil x) (symbolp x) (stringp x)))
(defun create-device-module (x)
(declare (ignore x))
(make-instance 'device-interface))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Module definition
(define-module-fct :device
nil
(list
;; From vision
(define-parameter :pixels-per-inch
:valid-test 'posnum
:default-value 72.0
:warning "a non-negative number"
:documentation "Pixels per inch of display")
(define-parameter :process-cursor
:valid-test 'tornil
:default-value nil
:warning "T or NIL"
:documentation "Should the AGI create a visicon feature for the mouse cursor?")
(define-parameter :viewing-distance
:valid-test 'posnum
:default-value 15.0
:warning "a non-negative number"
:documentation "Distance of the eyes from the display, in inches.")
;; From motor
(define-parameter :key-closure-time
:valid-test 'nonneg
:warning "a number"
:default-value 0.01
:documentation "Time between when a key is contacted and it registers as being hit.")
(define-parameter :cursor-fitts-coeff
:valid-test 'nonneg
:default-value 0.1
:warning "a non-negative number"
:documentation "b coefficient in Fitts's equation for aimed movements.")
(define-parameter :needs-mouse
:valid-test 'tornilorsymbolorstring
:default-value nil
:warning "T, NIL, a symbol, or string"
:documentation "Should the AGI install a mouse device?")
(define-parameter :stable-loc-names
:valid-test 'tornil
:default-value t
:warning "T or NIL"
:documentation "Whether or not to sort the virtual window's subviews to guarantee the names always line up")
(define-parameter :default-target-width
:valid-test 'nonneg
:default-value 1.0
:warning "a non-negative number"
:documentation
"Width of targets with unspecified widths for approach-width calculations and ply motor actions (no units)."))
:version (version-string (make-instance 'device-interface))
:documentation "The device interface for a model"
:creation 'create-device-module
:reset 'reset-device
:delete 'delete-device
:params 'params-device-module
:required (list :motor :vision :speech))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 49,341 | Common Lisp | .lisp | 845 | 52.198817 | 172 | 0.601217 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b82328ef2c6c6525482c78a8dd2dba14793c534255b3b62ec89361661c563a95 | 14,321 | [
-1
] |
14,322 | p-star-cmd.lisp | asmaloney_ACT-R/commands/p-star-cmd.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : p-star-cmd.lisp
;;; Version : 2.0
;;;
;;; Description : Functions that work with the procedural module to allow
;;; : definition of productions with bound-variable slot names.
;;;
;;; Bugs :
;;;
;;; To do : [ ] Modifiy the ordering of conditions so that one can
;;; : use an explicit bind for a variablized slot as long as
;;; : there aren't circularities. Not quite as easy as I
;;; : inititial thought because you need to differentiate
;;; : explicit binds based on whether they should occur before
;;; : or after the variablized slot tests.
;;;
;;; ----- History -----
;;; 2005.02.05 Dan
;;; : * Creation - no 80 column limit because it really makes it
;;; hard for me to work with this!
;;; 2005.02.28 Dan
;;; : * Made the replace-variables-for-eval fix in p* as well.
;;; 2005.04.26 Dan
;;; : * Restored the setting of lhs and rhs of the production to
;;; : the parsed code for use by compilation.
;;; 2005.05.03 Dan
;;; : * Added the production-?hs-buffers setting for compilation.
;;; 2005.05.04 Dan
;;; : * Fixed the issue with direct requests not clearing the
;;; : buffer.
;;; 2005.05.11 Dan
;;; : * Changed the output parameter for buffer clearing so that
;;; : it prints in the medium traces as well.
;;; 2005.06.19 Dan
;;; : * Seems to be a bug wrt condition ordering if there are
;;; : "cross buffer" conditions.
;;; 2005.06.21 Dan
;;; : * Fixed the issue noted above. What happened is that a
;;; : variablized slot with a variablized value was being allowed
;;; : to rebind the variable even if it had a different value.
;;; : Doesn't do that now.
;;; 2005.09.01 Dan
;;; : * Making the changes necessary to allow a RHS = in a p* to
;;; : extend the chunk-type definition.
;;; : * Had to add a flag to the procedural module (can't use a
;;; : global and p*'s don't have their own module) called
;;; : check-p*-mods to let compilation generate correctly in
;;; : all cases.
;;; ; * Adding a test of the above to valid-variable-chunk-mod-spec
;;; : to allow production compilation to create instantiated
;;; : p*'s for slots that don't exist yet.
;;; : * Adding the extend-buffer-chunk function and putting it into
;;; : the RHS = action function before the mod.
;;; 2005.09.09 Dan
;;; : * Changed references of chunk-to-chunk-spec to chunk-name-to-
;;; : chunk-spec and made sure to call it appropriately.
;;; 2005.09.14 Dan
;;; : * Change to the priority of RHS actions. = is now set to a
;;; : higher priority than +. See log in procedural.lisp for
;;; : the detailed rational.
;;; 2005.12.05 Dan
;;; : * Fixed an issue with ordering when a variablized slot needs
;;; : to create a binding, but the buffer that binds the slot
;;; : name occurs in a buffer test after the buffer with the
;;; : variablized slot. Added replace-slot-variables to handle
;;; : that and modified p*-fct appropriately.
;;; : - Should probably just fix replace-variables, but don't
;;; : want to deal with the possible issues that could cause.
;;; 2005.12.06 Dan
;;; : * Previous fix is not quite sufficient because there's
;;; : still an issue with the binding of that variablized slot's
;;; : value. Changing the matching process slightly so that
;;; : it's a more explicit 2 steps of binding and now it rejects
;;; : p*'s that violate the two step rule.
;;; 2005.12.07 Dan
;;; : * Following the changes to the p command, p*'s are now
;;; : more restrictive with respect to !bind! and most problem
;;; : conditions (circular references, unbound vars, etc) should
;;; : now be flagged. The biggest change is that a !bind! cannot
;;; : be used to set a variable for a slot name anymore - all
;;; : explicit binds take place after all the buffer bindings.
;;; 2005.12.12 Dan
;;; : * The last update caused some problems for production
;;; : compilation because it modified the order of the lhs data
;;; : in the p* relative to p. That's been corrected now.
;;; 2006.01.18 Dan
;;; : * Eliminated some warnings that occured during conflict
;;; : resolution because a variablized slot didn't name a valid
;;; : slot in the chunk-type at that point. Now, it does a
;;; : round of slot validation first.
;;; 2006.01.31 Dan
;;; : * Fixed a bug that was introduced with the elimination of
;;; : the warnings that really broke the p* mechanism...
;;; 2006.03.21 Dan
;;; : * Fixed a bug that slipped through when I update the
;;; : utility mechanisms.
;;; 2006.10.11 Dan
;;; : * Changed the priority of the buffer-overwrite action to be
;;; : 90 instead of 100 (the priority of the buffer mod action)
;;; : because the modifications must occur first, but if they
;;; : have the same priority then they could be reversed which
;;; : can lead to run-time issues and isn't right with respect
;;; : to how productions should work.
;;; 2006.11.09 Dan
;;; : * Added the define-p* and define-p*-fct commands for consistency.
;;; : * Added the setting of the dynamic slot in the production
;;; : structure of a p*.
;;; : * Modified the call to print-production-output in the parsing
;;; : of an !output! command so that the "old style" format string
;;; : usage doesn't get triggered implicitly.
;;; : * Fixed a bug in production parsing that would lead to run time
;;; : errors if a buffer overwrite action didn't specify a chunk
;;; : or at least a variable (the variable could still bind to a
;;; : non-chunk at run time).
;;; 2006.11.10 Dan
;;; : * Additional update to the parsing like the last one - now
;;; : direct requests must be a variable or chunk.
;;; : * Fixed a cut and paste error related to the last change.
;;; 2006.11.20 Dan
;;; : * Removed the special case implicit action for visual requests in
;;; : the production definition and replaced it with the new
;;; : (generic) module-warning mechanims.
;;; 2007.06.18 Dan
;;; : * Changed calls to slot-specs-to-chunk-spec-list to add the -fct
;;; : since it's now an "official" command.
;;; 2008.03.24 Dan
;;; : * Start of the work to add the !mv-bind! to productions.
;;; : * Added the failure reason for !bind! so whynot shows that it
;;; : fails for a binding to nil.
;;; : * Sort the conditions of the productions now so that explicit
;;; : binds always precede buffer bindings (thought I did that
;;; : already).
;;; 2008.03.25 Dan
;;; : * Added the new !mv-bind! option for productions. It works
;;; : like !bind! except that it can bind multiple values in one
;;; : call. Here is an example:
;;; : !mv-bind! (=var1 =var2) (some-function)
;;; : that would bind the variables =var1 and =var2 to the first
;;; : and second values returned by some-function. If there are
;;; : not as many return values as variables to be bound the extra
;;; : are bound to nil which means the production will not match
;;; : if it's a LHS !mv-bind!.
;;; : * Fixed a bug that would let one rebind a variable with an
;;; : explicit !bind! on the RHS of a production.
;;; 2008.03.28 Dan
;;; : * Changed the order of the conditions so that the slot tests
;;; : actually precede the variablized slot bindings. Doesn't
;;; : affect the matching but it does clean up the whynot info.
;;; : * Fixed !mv-bind! for the RHS.
;;; 2008.06.20 Dan
;;; : * Removed the -fct from slot-specs-to-chunk-spec-list since
;;; : the macro was removed from the chunk-spec code.
;;; 2008.07.09 Dan
;;; : * Patched the p*-fct to not error when there are bad lhs
;;; : conditions.
;;; 2008.11.03 Dan
;;; : * Updated the parsing of a p* so that the LHS code uses
;;; : the new cr-buffer-read option in the conflict resolution
;;; : code.
;;; 2008.11.10 Dan
;;; : * Fixed the bug introduced on 08/07/09 that was fixed for
;;; : the p command a while ago.
;;; 2008.11.25 Dan
;;; : * Changed p*-fct to use add-production and remove-production
;;; : to better abstract away from the internals of the module.
;;; : * Changed calls to get-production to use get-production-internal
;;; : to avoid the unnecessary hash-table look-up when possible.
;;; 2008.12.08 Dan [1.1]
;;; : * Significant overhaul of the internal representation of
;;; : productions. No longer create lambdas for the conditions.
;;; : Instead, create more specific single condition tests.
;;; 2009.02.10 Dan
;;; : * Changed the module modification requests so that they don't
;;; : verify things before passing it along to the module. That
;;; : allows a module to perform chunk-type extensions in the
;;; : requests.
;;; 2009.05.04 Dan
;;; : * Fixed an issue with symbols in variablized slots on the LHS
;;; : not being defined as chunks when necessary.
;;; 2009.05.05 Dan
;;; : * Changed the inequality tests so that they all use the "right"
;;; : test instead of only testing > and negating and then add the
;;; : opposite test to the implicit ones for the tree.
;;; 2009.05.22 Dan
;;; : * Fixed a bug in production parsing which would allow something
;;; : like this to "work" (p* name =goal> free ==> ...).
;;; 2009.06.03 Dan
;;; : * Added explicit conditions for the inequality tests to check
;;; : if a value is a number and an implicit check if a slot has
;;; : a constant to possibly help in building the conflict tree.
;;; 2009.09.10 Dan
;;; : * Added the require-compiled for the code that's now in production-
;;; : parsing-support.lisp and clipped out some old code that's not
;;; : used anymore.
;;; 2009.09.18 Dan
;;; : * P and p* have been combined into a single system now, but
;;; : leaving this here to keep the p* particular stuff still
;;; : separate and for the history info.
;;; 2013.01.28 Dan
;;; : * Replaced calls to internal chunk-type functions with the
;;; : appropriate command.
;;; 2013.03.13 Dan [1.2]
;;; : * Changed process-variable-slots-specs so that it allows the
;;; : slots of a child type to be provided in a parent type specification.
;;; 2013.03.19 Dan
;;; : * Allow the modifications to also specify child slots as long
;;; : as they are in the conditions as well with a change to
;;; : valid-variable-chunk-mod-spec.
;;; 2013.04.10 Dan
;;; : * Removing the extend-buffer-chunk function since the schedule-
;;; : mod-buffer-chunk command is now getting that option built in.
;;; 2013.06.04 Dan
;;; : * Fixed valid-variable-chunk-mod-spec to allow static chunks
;;; : to modify any of the possible slots for the type given.
;;; 2014.03.19 Dan [2.0]
;;; : * Start of conversion to chunks without types.
;;; : * Remove define-varaible-chunk-spec-fct and associated functions
;;; : because chunk-specs are now allowed to have variable slot names.
;;; 2014.03.20 Dan
;;; : * Don't really do anything here now, and just keep this around
;;; : mostly for the commnets because p and p* are now the same.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2018.04.13 Dan
;;; : * No point in keeping the p* commands around anymore...
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; p* and p*-fct which work just like p and p-fct since those are allowed to
;;; have variables in slot positions now too.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; There is only allowed to be one level of indirection, either within or
;;; across buffers.
;;;
;;; Thus, this is acceptable:
;;;
;;; =goal>
;;; isa goal
;;; slot1 =slot-name
;;; =slot-name =next-slot
;;; =next-slot =some-value
;;;
;;; as is this:
;;;
;;; =goal>
;;; isa goal
;;; slot1 =slot-name
;;; =slot2-name =slot-val
;;; =retrieval>
;;; isa memory
;;; =slot-name =val2
;;; slot =slot2-name
;;;
;;; but this is NOT allowed:
;;;
;;; =goal>
;;; isa goal
;;; slot1 =slot-name
;;; =slot-name =next-slot
;;; =next-slot =some-value
;;; =some-value =value
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 15,508 | Common Lisp | .lisp | 303 | 50.069307 | 88 | 0.565423 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | fdac01438cd7c59aaeb5155cda4e70296dc85a5899aff93ed7b918402e227ce0 | 14,322 | [
-1
] |
14,323 | conflict-tree.lisp | asmaloney_ACT-R/commands/conflict-tree.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2008 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;; Address : Department of Psychology
;;; : Carnegie Mellon University
;;; : Pittsburgh, PA 15213-3890
;;; : [email protected]
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : conflict-tree.lisp
;;; Version : 3.0
;;;
;;; Description : Code for creating and searching a simple decision tree of
;;; production conditions.
;;;
;;; Bugs :
;;;
;;; To do : [2.0] Consider handling conditions other than constants.
;;; : [2.0] See if it can infer other things about non-equal or
;;; : numeric values in creating the tree.
;;; : [-] Consider extending the tree when adding new productions
;;; : on the fly - track the used tests and call build-...
;;; : Seems like a bad idea for performance which is the
;;; : objective of using the tree.
;;; : [3.0] Make the negative limit a parameter somewhere.
;;;
;;; ----- History -----
;;; 2008.12.23 Dan [1.0]
;;; : * First complete version of the tree building/searching code
;;; : for use in production selection.
;;; 2008.01.07 Dan
;;; : * Fixed print-conflict-tree.
;;; 2009.06.03 Dan
;;; : * Added a hard limit to how many negative splits can occur
;;; : sequentially when building the tree (3). If it gets that
;;; : far it just gives up on the branch and creates a leaf.
;;; 2010.04.26 Dan
;;; : * Tree-condition-equal now uses eql for the value tests to
;;; : make sure numerical slot conditions can be considered
;;; : the same (doesn't affect the matching itself).
;;; 2011.04.28 Dan
;;; : * Added some declares to quite compliation warnings.
;;; 2013.10.18 Dan
;;; : * Added a few more stats to conflict-tree-stats.
;;; 2014.03.17 Dan [2.0]
;;; : * Changed the query-buffer call to be consistent with the new
;;; : internal code.
;;; 2014.04.03 Dan
;;; : * Ignore the isa tests for now and instead use all the implicit
;;; : tests which were being ignored previously...
;;; 2014.05.19 Dan
;;; : * To avoid warnings at load time commenting out the code from
;;; : the isa-node processing methods.
;;; 2014.05.30 Dan
;;; : * Also commented out the isa condition in split-productions-with-condition.
;;; 2016.07.05 Dan [2.1]
;;; : * Add-production-to-tree removes the isa conditions before
;;; : passing things to add-to-tree.
;;; : * When adding a new node for a new production being added check
;;; : the condition added at the leaf with the current productions
;;; : at that leaf since previously it just pushed them to all
;;; : branches.
;;; 2020.08.25 Dan
;;; : * Moved the defstructs to the procedural module file.
;;; 2021.03.31 Dan [3.0]
;;; : * Something broke this at some point. Instead of just fixing
;;; : it, doing some significant updating. Just remove all the isa
;;; : conditions beforehand instead of no-oping them everywhere.
;;; : Also switching to the info gain for deciding which to use
;;; : which eliminates the need for the repeated 0 tests, but
;;; : that requires the real calculations and to improve that it
;;; : groups the productions by the conditions they have so that
;;; : the calcualtions better measure how well a condition does at
;;; : splitting things (treating each production as its own class
;;; : as was done previously doesn't really produce a good metric
;;; : resulting in bigger trees than necessary and all the extra
;;; : checks to decide when to stop). The downside is the added
;;; : computation for this calcuation...
;;; : * Switched from the 'doesn't test' branch being marked with
;;; : :other to '=other since it's possible for someone to put the
;;; : keyword value into the productions but something which starts
;;; : with an = would never be a specific value since it's a
;;; : variable.
;;; : * Don't try to extend the tree when new productions are added
;;; : for now (previously it just picked some remaining condition
;;; : and used that to split things). May want to try using the
;;; : gain to decide to split a leaf, but would require keeping
;;; : some of the class grouping info to be efficient.
;;; 2021.04.15 Dan
;;; : * Changed print-conflict-tree to output to the command trace.
;;; 2021.04.21 Dan
;;; : * Fixed a place where :other hadn't been changed to '=other.
;;; 2021.05.10 Dan
;;; : * Allow use with ppm by just dropping the slot tests - it's
;;; : just the query and test-slot cases.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Builds a tree from production conditions. Initially uses all the productions
;;; in the model definition using the info. gain calculation to try and create a
;;; small tree. Originally used the ID3 algorithm ofr that but switched to info.
;;; gain to alleviate some issues with detecting terminating conditions. Not
;;; using the normalized info. gain from the C4.5 algorithm (the updated version
;;; of ID3) since that biases away from creating many specific classes which is
;;; something we want here -- if a single test uniquely splits things that's what
;;; we want instead of something that generalizes to more cases.
;;; If productions get added after the model is defined (through compilation or
;;; otherwise) currently they just end up in an existing leaf.
;;;
;;; One assumption in the matching is that chunk names used in constant slot
;;; tests (those hard coded into the productions) will always have thier true
;;; name. It's not likely people have models where that's not the case, but
;;; it is technically possible to build such a model and it would not work
;;; correctly with the tree based matching.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; print-conflict-tree
;;;
;;; Has no parameters. Can be called to print out the tree in the current
;;; model's procedural module. The tree is printed one node per line with
;;; indenting and numbering indicating depth within a branch.
;;;
;;; conflict-tree-stats
;;;
;;; Takes no parameters. Will return a list of cons cells with some info
;;; about the tree in the current procedural module. The cons cells have
;;; a description of the stat as the car and the value as the cdr. The
;;; current stats computed are:
;;; :depth - deepest node in the tree
;;; :min-depth - shortest branch in the tree
;;; :total-nodes - count of all nodes (internal and terminal) in the tree
;;; :terminal - count of only terminal nodes (leaves)
;;; :non-empty - number of leaf nodes with 1 or more productions that
;;; are valid
;;; :sets - the number of different sets of productions found in the
;;; non-empty leaf nodes
;;; :average-set - the mean size of non-empty sets
;;; :largest-set - the size of the largest set
;;;
;;; > (conflict-tree-stats )
;;; ((:DEPTH . 24) (:MIN-DEPTH . 3) (:TOTAL-NODES . 4670) (:TERMINAL . 3422) (:NON-EMPTY . 3373) (:SETS . 1073)
;;; (:AVERAGE-SET . 4.746098) (:LARGEST-SET . 187))
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Using the info gain from C4.5 now because the simple entropy from ID3 and
;;; assuming each production was its own classification had some problems with
;;; building a "good" tree.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (in-package :act-r)
#+(and :clean-actr (not :packaged-actr) :ALLEGRO-IDE) (in-package :cg-user)
#-(or (not :clean-actr) :packaged-actr :ALLEGRO-IDE) (in-package :cl-user)
;;; Find the valid productions given the tree and the procedural module
;;; returns the list of valid productions and a table with the conditions tested
(defmethod get-valid ((node conflict-node) prod )
(get-valid (select-child node prod) prod ))
(defmethod get-valid ((node test-node) prod )
(get-valid (select-child node prod) prod ))
(defmethod get-valid ((node leaf-node) prod )
(declare (ignore prod))
(conflict-node-valid node))
(defmethod get-valid ((node null) prod)
(declare (ignore prod))
node)
;;; pick the next node to check
(defmethod select-child ((node root-node) prod)
(declare (ignore prod))
(root-node-child node))
(defmethod select-child ((node test-slot-node) prod)
(let ((buffer-val (cr-buffer-slot-read prod (test-slot-node-buffer node) (test-slot-node-buffer-index node) (test-slot-node-slot-index node) (test-slot-node-slot node))))
(if (funcall (test-slot-node-test node) buffer-val (test-slot-node-value node))
(test-slot-node-true node)
(test-slot-node-false node))))
(defmethod select-child ((node query-node) prod)
(declare (ignore prod))
(if (query-buffer (query-node-buffer node) (list (query-node-query node) (query-node-value node)))
(binary-test-node-true node)
(binary-test-node-false node)))
(defmethod select-child ((node slot-node) prod)
(let ((buffer-val (cr-buffer-slot-read prod (slot-node-buffer node) (slot-node-buffer-index node) (slot-node-slot-index node) (slot-node-slot node))))
(aif (gethash buffer-val (slot-node-children node))
it
(gethash '=other (slot-node-children node)))))
;;; Print out the tree for debugging purposes
(defun print-conflict-tree ()
(walk-tree (procedural-conflict-tree (get-module procedural))))
(defun walk-tree (node)
(print-tree node nil 0 ))
(defun print-tree (node branch depth)
(cond ((root-node-p node)
(command-output "---->[root ~s]" (conflict-node-valid node))
(awhen (root-node-child node)
(print-tree it t (+ depth 2))))
((leaf-node-p node)
(command-output "~vt-~d- ~s ->[leaf ~s]" depth (/ depth 2) branch (conflict-node-valid node))
)
((binary-test-node-p node)
(command-output "~vt-~d- ~s ->[~s ~a ~s ~@[~s ~]~s]" depth (/ depth 2) branch (cr-condition-type (test-node-condition node))
(test-node-buffer node)
(if (eq (cr-condition-type (test-node-condition node)) 'query)
(query-node-query node)
(test-slot-node-slot node))
(if (eq (cr-condition-type (test-node-condition node)) 'query)
nil
(test-slot-node-test node))
(test-node-value node))
(awhen (binary-test-node-true node)
(print-tree it t (+ depth 2)))
(awhen (binary-test-node-false node)
(print-tree it nil (+ depth 2))))
((wide-test-node-p node)
(command-output "~vt-~d- ~s ->[~s ~a ~s]" depth (/ depth 2) branch (cr-condition-type (test-node-condition node)) (test-node-buffer node) (slot-node-slot node))
(maphash (lambda (branch node)
(print-tree node branch (+ depth 2)))
(wide-test-node-children node)))))
;;; Compute tree statistics for comparison and analysis
(defvar *tree-data* nil)
(defun conflict-tree-stats ()
(setf *tree-data* nil)
(mapcar #'cons '(:depth :min-depth :total-nodes :terminal :non-empty :sets :average-set :largest-set)
(append (multiple-value-list (get-tree-stats (procedural-conflict-tree (get-module procedural))))
(list (length *tree-data*)) (list (length (remove nil *tree-data*)))
(list (length (remove-duplicates *tree-data* :test 'equalp)))
(list (let ((nodes (remove nil *tree-data*)))
(unless (null nodes)
(* 1.0 (/ (reduce '+ (mapcar 'length nodes)) (length nodes))))))
(list (reduce 'max (mapcar 'length *tree-data*))))))
(defmethod get-tree-stats ((node binary-test-node))
(let ((max-depth 0)
(min-depths nil)
(nodes 1))
(awhen (binary-test-node-true node)
(multiple-value-bind (d md n)
(get-tree-stats it)
(incf nodes n)
(setf min-depths md)
(when (> d max-depth)
(setf max-depth d))
))
(awhen (binary-test-node-false node)
(multiple-value-bind (d md n)
(get-tree-stats it)
(incf nodes n)
(when (or (null min-depths) (< md min-depths))
(setf min-depths md))
(when (> d max-depth)
(setf max-depth d))
))
(values (1+ max-depth) (if min-depths (1+ min-depths) 1) nodes)))
(defmethod get-tree-stats ((node wide-test-node))
(let ((max-depth 0)
(min-depths nil)
(nodes 1))
(maphash (lambda (branch node)
(declare (ignore branch))
(multiple-value-bind (d md n)
(get-tree-stats node)
(incf nodes n)
(setf min-depths md)
(when (> d max-depth)
(setf max-depth d))))
(wide-test-node-children node))
(values (1+ max-depth) (if min-depths (1+ min-depths) 1) nodes)))
(defmethod get-tree-stats ((node root-node))
(let ((max-depth 0)
(min-depths nil)
(nodes 1))
(awhen (root-node-child node)
(multiple-value-bind (d md n)
(get-tree-stats it)
(incf nodes n)
(setf min-depths md)
(when (> d max-depth)
(setf max-depth d))
))
(values (1+ max-depth) (if min-depths (1+ min-depths) 1) nodes)))
(defmethod get-tree-stats ((node leaf-node))
(push (leaf-node-valid node) *tree-data*)
(values 1 1 1))
#| don't generally build incrementally now so not updating this for the current representations
unless something changes to make it useful
(defun get-production-stats ()
(let ((c nil))
(dolist (p (productions-list (get-module procedural)))
(setf c (append c (production-constants p))))
(list (cons :total-constants (length c))
(cons :unique-constants (length (remove-duplicates c :test 'equalp)))
(cons :unique-tests (length (remove-duplicates c :test (lambda (x y) (equal (butlast x) (butlast y)))))))))
(defun detail-adding-ps (ps)
(dolist (x ps)
(eval x)
(format t "~s: ~s ~s~%" (second x) (get-production-stats) (conflict-tree-stats))))
|#
;;; Build the tree incrementally when a production is added.
;;;
;;; only happens after the initial tree creation - which should only be production compilation
;;; for most models.
;;;
;;; Don't add any more nodes than necessary i.e. if it gets to a leaf add the first condition and stop
;;;
;;; Input: - current-tree
;;; - list of cr-condition structs valid for constants
;;; so the type is one of: query, slot, or test-slot
;;; - production name
(defmethod add-to-tree ((node leaf-node) conditions production)
; just storing in leaves for now
;(if conditions
;(create-branch node (list (car conditions)) production)
(declare (ignore conditions))
(push-last production (leaf-node-valid node)))
(defmethod add-to-tree ((node root-node) conditions production)
(push-last production (conflict-node-valid node))
(aif (root-node-child node)
(add-to-tree it conditions production)
nil
; Don't make a tree if there isn't one
;(let ((new-node (make-leaf-node :parent node :branch t :valid nil)))
; (setf (root-node-child node) new-node)
; (add-to-tree new-node conditions production))))
))
(defmethod add-to-tree ((node binary-test-node) conditions production) ;; query and test-slot
(aif (find (binary-test-node-condition node) conditions :test 'cr-condition-equal)
;; this test matches so progress down the proper branch
(add-to-tree (if (cr-condition-result it)
(binary-test-node-true node)
(binary-test-node-false node))
(remove it conditions) production)
;; otherwise add it to both branches
(progn
(add-to-tree (binary-test-node-true node) conditions production)
(add-to-tree (binary-test-node-false node) conditions production))))
(defmethod add-to-tree ((node slot-node) conditions production)
(aif (find (slot-node-condition node) conditions :test 'cr-condition-equal)
(if (gethash (cr-condition-value it) (slot-node-children node))
;; push it down the existing branch
(add-to-tree (gethash (cr-condition-value it) (slot-node-children node)) (remove it conditions) production)
;; doesn't have a branch so create one then add it
;; copy the default node if there is once since those may have
;; a subtree already otherwise just create a leaf
(let* ((default (gethash '=other (slot-node-children node)))
(new-node (if default
(copy-conflict-tree default node)
(make-leaf-node :parent node))))
(setf (gethash (cr-condition-value it) (slot-node-children node)) new-node)
(setf (conflict-node-branch new-node) (cr-condition-value it))
(add-to-tree new-node (remove it conditions) production)))
;; need to add it to every branch and if there's not a default
;; create one
(let ((default nil))
(maphash (lambda (key value)
(when (eq key '=other) (setf default t))
(add-to-tree value conditions production))
(slot-node-children node))
(unless default
(setf (gethash '=other (slot-node-children node))
(make-leaf-node :parent node :branch '=other :valid (list production)))))))
#| Not going to extend the tree for now -- but may come back to this, and if so
should use info gain to determine whether to branch or not but that may
require keeping some more info in the leaves (the production class info with
remaining conditions) to make it easy to do the calculations
(defmethod create-branch ((node leaf-node) conditions production)
;(format t "create-branch ~20s from ~20s~%" branch (type-of node))
(let* ((condition (car conditions))
(new-node (case (cr-condition-type condition)
(query
(make-query-node :parent (conflict-node-parent node)
:branch (conflict-node-branch node)
:buffer (cr-condition-buffer condition)
:query (cr-condition-slot condition)
:value (cr-condition-value condition)
:condition condition))
(test-slot
(make-test-slot-node :parent (conflict-node-parent node)
:branch (conflict-node-branch node)
:buffer (cr-condition-buffer condition)
:buffer-index (cr-condition-bi condition)
:slot (cr-condition-slot condition)
:slot-index (cr-condition-si condition)
:value (cr-condition-value condition)
:test (cr-condition-test condition)
:condition condition))
(slot
(make-slot-node :parent (conflict-node-parent node)
:branch (conflict-node-branch node)
:buffer (cr-condition-buffer condition)
:buffer-index (cr-condition-bi condition)
:slot (cr-condition-slot condition)
:slot-index (cr-condition-si condition)
:condition condition)))))
(if (binary-test-node-p new-node)
(progn
(setf (binary-test-node-true new-node) (make-leaf-node :parent new-node :branch t ))
(setf (binary-test-node-false new-node) (make-leaf-node :parent new-node :branch nil ))
)
(progn
(let ((other-tree (make-leaf-node :parent new-node :branch '=other)))
(setf (gethash '=other (wide-test-node-children new-node)) other-tree))))
;; splice this in as the child of the leaf's parent
(cond ((binary-test-node-p (conflict-node-parent node))
(if (conflict-node-branch node)
(setf (binary-test-node-true (conflict-node-parent node)) new-node)
(setf (binary-test-node-false (conflict-node-parent node)) new-node)))
((root-node-p (conflict-node-parent node))
(setf (root-node-child (conflict-node-parent node)) new-node))
((wide-test-node-p (conflict-node-parent node))
(setf (gethash (conflict-node-branch new-node) (wide-test-node-children (conflict-node-parent node))) new-node)))
;; now call the add code for this new-node
(add-to-tree new-node conditions production)
;; then add the current node's valid productions based on whether they have the
;; same condition or not
(dolist (p-name (conflict-node-valid node))
(let* ((p (get-production p-name))
(c (or (find (car conditions) (production-constants p) :test 'tree-condition-equal)
(find (car conditions) (production-implicit p) :test 'tree-condition-equal))))
(add-to-tree new-node (when c (list c)) p-name)))))
|#
;;; Code to copy a tree making sure not to save things that shouldn't be saved
(defmethod copy-conflict-tree ((node leaf-node) parent)
(let ((new-node (copy-conflict-node node)))
(setf (conflict-node-parent new-node) parent)
(setf (conflict-node-valid new-node) (copy-list (conflict-node-valid node)))
new-node))
(defmethod copy-conflict-tree ((node root-node) parent)
(let ((new-node (copy-conflict-node node)))
(setf (conflict-node-parent new-node) parent)
(setf (conflict-node-valid new-node) (copy-list (conflict-node-valid node)))
(awhen (root-node-child node)
(setf (root-node-child new-node) (copy-conflict-tree it new-node)))
new-node))
(defmethod copy-conflict-tree ((node binary-test-node) parent)
(let ((new-node (copy-conflict-node node)))
(setf (conflict-node-parent new-node) parent)
(setf (conflict-node-valid new-node) (copy-list (conflict-node-valid node)))
(awhen (binary-test-node-true node)
(setf (binary-test-node-true new-node) (copy-conflict-tree it new-node)))
(awhen (binary-test-node-false node)
(setf (binary-test-node-false new-node) (copy-conflict-tree it new-node)))
new-node))
(defmethod copy-conflict-tree ((node wide-test-node) parent)
(let ((new-node (copy-conflict-node node)))
(setf (conflict-node-parent new-node) parent)
(setf (conflict-node-valid new-node) (copy-list (conflict-node-valid node)))
(setf (wide-test-node-children new-node) (make-hash-table :test 'equalp :size (hash-table-size (wide-test-node-children node))))
(maphash (lambda (key value)
(setf (gethash key (wide-test-node-children new-node)) (copy-conflict-tree value new-node)))
(wide-test-node-children node))
new-node))
;;;
(defun tree-condition-equal (a b)
(and (eq (cr-condition-type a) (cr-condition-type b))
(eq (cr-condition-buffer a) (cr-condition-buffer b))
(case (cr-condition-type a)
(slot (= (cr-condition-si a) (cr-condition-si b)))
(query (and (eq (cr-condition-slot a) (cr-condition-slot b))
(eql (cr-condition-value a) (cr-condition-value b))))
(test-slot (and (eq (cr-condition-test a) (cr-condition-test b))
(= (cr-condition-si a) (cr-condition-si b))
(eql (cr-condition-value a) (cr-condition-value b))))
(t nil))))
;;; Sort the root nodes based on the cannonical production order so that
;;; using the tree should result in identical choices for 'tie' situations
;;; and can't just build them that way now with the class based grouping
(defun production-ordering (productions procedural)
(sort (copy-list productions) #'< :key (lambda (x) (position x (productions-list procedural) :key 'production-name))))
;;; Updated the scoring to use the info gain. Also, now group the productions
;;; by their sets of conditions instead of treating each as a separate class
;;; which should allow for a more efficient tree (at the cost of more initial
;;; calculations).
(defun tree-entropy (classes)
;; s is a list of lists where each list is a 'class' of items and the car of the
;; list holds the items in that class.
(let ((N (reduce '+ (mapcar (lambda (x) (length (car x))) classes) :initial-value 0)))
(if (zerop N)
0
(reduce '+ (mapcar (lambda (x)
(if (zerop (length (car x)))
0
(- (* (/ (length (car x)) N) (log (/ (length (car x)) N) 2)))))
classes)))))
(defun tree-gain (base-entropy sub-groupings)
;; the sub-groupings are based on
;; the repartitioning of the sets based on a condition.
;; It's a list of lists of lists where the toplevel lists
;; are the possible values for the condition, the lists
;; within that are the classes, and the first list in those
;; are the items.
(let ((N (reduce '+ (mapcar (lambda (x) (reduce '+ (mapcar (lambda (y) (length (car y))) x) :initial-value 0)) sub-groupings) :initial-value 0)))
(if (zerop N)
0
(- base-entropy
(reduce '+ (mapcar (lambda (x)
(* (/ (reduce '+ (mapcar (lambda (y) (length (car y))) x)) N)
(tree-entropy x)))
sub-groupings))))))
(defun split-productions-with-condition (condition n classes)
;; Need to compute the entropy for the condition
;; which means ignore the items without the condition
(let (haves have-nots entropy)
(dolist (x classes)
(if (assoc n (second x))
(push x haves)
(push x have-nots)))
(setf entropy (tree-entropy haves))
;(pprint classes)
(if (eq 'slot (cr-condition-type condition))
(let* ((vals (remove-duplicates (mapcar (lambda (x) (cdr (assoc n (second x)))) haves)))
(results (mapcar (lambda (x)
(cons x nil))
vals)))
;; split the items that have it to determine the gain
(dolist (x haves)
(let ((val (cdr (assoc n (second x))))
(without (list (first x) (remove n (second x) :key 'car))))
(push without
(cdr (assoc val results)))))
;; update their classes
(dolist (x results)
(setf (cdr x)
(group-by-condition-class (cdr x))))
(let* ((new-classes (mapcar 'cdr results))
(gain (tree-gain entropy new-classes)))
(when have-nots
(dolist (y results)
(setf (cdr y)
(append have-nots (cdr y))))
(push (cons '=other have-nots) results)
;; update the classes again with the have-nots included
(setf results (mapcar (lambda (x)
(cons (car x)
(group-by-condition-class (cdr x))))
results)))
;(pprint results)
(values gain results)))
; test-slot and queries only have two options t or nil
(let ((results (list (cons t nil) (cons nil nil))))
;; split the items that have it to determine the gain
(dolist (x haves)
(let ((val (cdr (assoc n (second x))))
(without (list (first x) (remove n (second x) :key 'car))))
(push without
(cdr (if val
(first results)
(second results))))))
;; update their classes
(dolist (x results)
(setf (cdr x)
(group-by-condition-class (cdr x))))
(let* ((new-classes (mapcar 'cdr results))
(gain (tree-gain entropy new-classes)))
(when have-nots
(dolist (y results)
(setf (cdr y)
(append have-nots (cdr y))))
;; update the classes again with the have-nots included
(setf results (mapcar (lambda (x)
(cons (car x)
(group-by-condition-class (cdr x))))
results)))
;(pprint results)
(values gain results))))))
(defun build-tree-from-productions (branch parent conditions classes procedural)
(if (= (length classes) 1) ;; nothing to decide
(make-leaf-node :parent parent :branch branch :valid (production-ordering (first (first classes)) procedural))
;; only consider the conditions that are actually used.
;; I thought limiting that to only those where every class has it
;; or there are classes with different values for the condition
;; would be useful, but it can find shorter trees if all of the
;; used conditions are tested though that's potentially a lot of
;; extra computation...
(let ((used-conditions (remove-duplicates (mapcar 'car (reduce 'append (mapcar 'second classes))))))
;(used-conditions (reduce 'append (mapcar 'second classes)))
;(all-contain nil)
;(diff-vals nil)
;(n (length conditions))
;(class-count (length classes)))
;; find the interesting cases
#|(dotimes (i n)
(let ((match (remove-if-not (lambda (x) (= x i)) used-conditions :key 'car)))
(when (= (length match) class-count)
(push i all-contain))
(when (> (length (remove-duplicates match :test 'equalp)) 1)
(push i diff-vals))))
(setf used-conditions (remove-duplicates (append diff-vals all-contain)))
|#
(if (null used-conditions) ;; nothing useful to split with
(make-leaf-node :parent parent :branch branch :valid (production-ordering (apply 'append (mapcar 'first classes)) procedural))
;; Find the condition with the best info gain ration
(let ((best nil)
(val nil)
(sub-nodes nil))
(dolist (x used-conditions)
(let ((condition (svref conditions x)))
(multiple-value-bind (gain subs) (split-productions-with-condition condition x classes)
;(format t "splitting ~S~% with ~s~% scores ~S~%" classes condition gain)
(when (or (null val)
(> gain val))
(setf val gain)
(setf sub-nodes subs)
(setf best condition)))))
;(format t "Best: ~S ~S ~%~%" val sub-nodes)
;(break)
;; No relevant conditions left to split them
(if (or (null val) (<= val 0.0)) ;;; should it always stop if zero or negative now?
(make-leaf-node :parent parent :branch branch :valid (production-ordering (flatten (mapcar 'first classes)) procedural))
(let* (
(new-node (case (cr-condition-type best)
(query
(make-query-node :parent parent
:branch branch
:buffer (cr-condition-buffer best)
:query (cr-condition-slot best)
:value (cr-condition-value best)
:condition best))
(test-slot
(make-test-slot-node :parent parent
:branch branch
:buffer (cr-condition-buffer best)
:buffer-index (cr-condition-bi best)
:slot (cr-condition-slot best)
:slot-index (cr-condition-si best)
:value (cr-condition-value best)
:test (cr-condition-test best)
:condition best))
(slot
(make-slot-node :parent parent
:branch branch
:buffer (cr-condition-buffer best)
:buffer-index (cr-condition-bi best)
:slot (cr-condition-slot best)
:slot-index (cr-condition-si best)
:condition best))))
)
(if (binary-test-node-p new-node)
(progn
(setf (binary-test-node-true new-node)
(build-tree-from-productions t new-node conditions (cdr (assoc t sub-nodes)) procedural))
(setf (binary-test-node-false new-node)
(build-tree-from-productions nil new-node conditions (cdr (assoc nil sub-nodes)) procedural)))
(progn
(dolist (x sub-nodes)
(setf (gethash (car x) (wide-test-node-children new-node))
(build-tree-from-productions (car x) new-node conditions (cdr x) procedural)))))
new-node)))))))
(defun group-by-condition-class (productions)
(let ((classes nil))
(dolist (p productions classes)
(aif (find (second p) classes :test 'equalp :key 'second)
(setf (first it) (append (first p) (first it)))
(push (list (first p) (second p)) classes)))))
;;; Interface to the procedural module
(defun build-conflict-tree (procedural)
(let* ((productions-with-conditions (mapcar (lambda (x)
(list (list (production-name x))
(append (remove-if (lambda (x)
(or (eq (cr-condition-type x) 'isa)
(and
(procedural-ppm procedural) ;; param lock held by calling fn
(eq (cr-condition-type x) 'slot))))
(copy-list (production-constants x)))
(copy-list (production-implicit x)))))
(productions-list procedural)))
(conditions (remove-duplicates (mapcan (lambda (x) (copy-list (second x))) productions-with-conditions) :test 'tree-condition-equal)))
(setf conditions (coerce conditions 'vector))
;(pprint productions-with-conditions)
(dolist (p productions-with-conditions)
(setf (second p)
(sort (mapcar (lambda (x)
(let ((n (position x conditions :test 'tree-condition-equal))
(val (if (eq 'slot (cr-condition-type x))
(cr-condition-value x)
(cr-condition-result x))))
(cons n val)))
(second p))
#'< :key 'car)))
;(pprint conditions))
;(pprint productions-with-conditions))
(setf (root-node-conditions (procedural-conflict-tree procedural)) conditions)
(setf (root-node-valid (procedural-conflict-tree procedural)) (mapcar 'production-name (productions-list procedural)))
(setf (root-node-child (procedural-conflict-tree procedural))
(build-tree-from-productions t
(procedural-conflict-tree procedural)
conditions
(group-by-condition-class productions-with-conditions)
procedural))))
(defun add-production-to-tree (p procedural)
(add-to-tree (procedural-conflict-tree procedural)
(remove-if (lambda (x)
(or (eq (cr-condition-type x) 'isa)
(and
(procedural-ppm procedural) ;; param lock held by calling fn
(eq (cr-condition-type x) 'slot))))
(remove-duplicates (append (production-constants p) (production-implicit p)) :test 'cr-condition-equal))
(production-name p)))
(defun remove-production-from-tree (p procedural)
(declare (ignore p procedural))
(model-warning "Removing productions not supported when :use-tree is set to t - tree removal not implemented."))
(defun get-valid-productions (procedural)
(get-valid (procedural-conflict-tree procedural) procedural))
#|
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|#
| 39,836 | Common Lisp | .lisp | 727 | 43.200825 | 172 | 0.569493 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e44bb21de51ad9ce5f2416e8f416356ba9bc172e8276cd8fd4995c96d52965f8 | 14,323 | [
-1
] |
14,324 | new-server.tcl | asmaloney_ACT-R/environment/GUI/new-server.tcl |
source "json.tcl"
set environment_socket ""
set incomplete_cmd ""
set end_of_cmd [format "%c" 4]
set id_num 0
set cmd_table [dict create]
proc replace_quotes {i} {
set start 0
set index [string first "\"" $i $start]
while {$index != -1} {
set i [string replace $i $index $index "'"]
set start $index
set index [string first "\"" $i $start]
}
return $i
}
proc item2json {i} {
if {[string is double -strict $i]} {
if {[string index [string trimleft $i] 0] == "."} {
return "0[string trimleft $i]"
} else {
return $i
}
} elseif {[regexp {^(?:true|false|null)$} $i]} {
return "$i"
} else {
return "\"[replace_quotes $i]\""
}
}
proc list2json {l} {
set json ""
if {$l == "null"} {
return "null"
} else {
foreach i $l {
if {[string is double -strict $i]} {
if {[string index [string trimleft $i] 0] == "."} {
append json "0[string trimleft $i],"
} else {
append json "$i,"
}
} elseif {[regexp {^(?:true|false|null)$} $i]} {
append json "$i,"
} else {
append json "\"[replace_quotes $i]\","
}
}
if {$json == ""} {
return "null"
} else {
return [format "\[%s\]" [string trimright $json ","]]
}
}
}
proc list2json_strings {l} {
set json ""
if {$l == "null"} {
return "null"
} else {
foreach i $l {
if {[regexp {^(?:true|false|null)$} $i]} {
append json "$i,"
} else {
append json "\"[replace_quotes $i]\","
}
}
if {$json == ""} {
return "null"
} else {
return [format "\[%s\]" [string trimright $json ","]]
}
}
}
proc collect_incoming {s} {
global incomplete_cmd
global end_of_cmd
global up_and_running
if [eof $s] {
close $s
global environment_socket
set environment_socket ""
if {$up_and_running == 1} {
tk_messageBox -title "ACT-R connection lost" -message "The environment has lost contact with ACT-R and will quit." -icon warning -type ok
} else {
tk_messageBox -title "ACT-R connection error" -message "There was a problem starting the environment and it must exit." -icon warning -type ok
}
clean_exit
} else {
set d [read $s]
set end [string first $end_of_cmd $d]
while { $end != -1 } {
set previous [string range $d 0 [expr $end - 1]]
set d [string range $d [expr $end + 1] end]
set complete "$incomplete_cmd$previous"
set incomplete_cmd ""
process_cmd $complete
set end [string first $end_of_cmd $d]
}
set incomplete_cmd "$incomplete_cmd$d"
}
}
proc process_cmd {cmd} {
set d [::json::json2dict $cmd]
if [dict exists $d "result"] {
set id [dict get $d "id"]
set error [dict get $d "error"]
set result [dict get $d "result"]
global $id
if {$error == "" || $error == "null" || $error == "false"} {
set $id [list 1 $result]
} else {
set $id [list 0 [dict get $error "message"]]
}
} elseif {[dict exists $d "method"] && [dict get $d "method"] == "evaluate"} {
# assume that it's a valid cmd on this side since it had to be added...
set params [dict get $d "params"]
set res [catch $params ret]
if {$res == 0} {
transmit_success $ret [dict get $d "id"]
} else {
transmit_error $ret [dict get $d "id"]
}
} else {
puts "Invalid message received from server: $cmd"
}
}
proc add_cmd {cmd_name proc_name {documentation "null"} {single "null"}} {
global cmd_table
if [dict exists $cmd_table $cmd_name] {
send_cmd "remove" [list $cmd_name]
}
dict set cmd_table $cmd_name $proc_name
send_cmd "add" [list $cmd_name $proc_name $documentation $single]
}
proc add_new_cmd {base_name proc_name {documentation "null"} {single "null"}} {
set n [new_variable_name $base_name]
while {[send_cmd "check" $n] != "null"} {
set n [new_variable_name $base_name]
}
add_cmd $n $proc_name $documentation $single
return $n
}
proc remove_cmd {cmd_name} {
global cmd_table
if [dict exists $cmd_table $cmd_name] {
send_cmd "remove" [list $cmd_name]
dict unset cmd_table $cmd_name
}
}
proc transmit_success {value id} {
global environment_socket
global end_of_cmd
if {[string trimleft $value] == ""} {
puts $environment_socket [format "\{\"result\": \[true\], \"error\": null, \"id\": %s\}$end_of_cmd" [item2json $id]]
} else {
puts $environment_socket [format "\{\"result\": %s, \"error\": null, \"id\": %s\}$end_of_cmd" [list2json $value] [item2json $id]]
}
}
proc transmit_error {error id} {
global environment_socket
global end_of_cmd
if {$error == ""} {
puts $environment_socket [format "\{\"result\": null, \"error\": \{\"message\": \"Unknown error.\"\}, \"id\": %s\}$end_of_cmd" [item2json $id]]
} else {
puts $environment_socket [format "\{\"result\": null, \"error\": \{\"message\": %s\}, \"id\": %s\}$end_of_cmd" [item2json $error] [item2json $id]]
}
}
proc transmit_cmd {cmd params var} {
global environment_socket
global end_of_cmd
set sent [catch {puts $environment_socket [format "\{\"method\": \"$cmd\", \"params\": %s, \"id\": \"$var\"\}$end_of_cmd" [list2json $params]]}]
if {$sent != 0} {
global $var
set $var "null"
}
}
proc transmit_cmd_strings {cmd params var} {
global environment_socket
global end_of_cmd
set sent [catch {puts $environment_socket [format "\{\"method\": \"$cmd\", \"params\": %s, \"id\": \"$var\"\}$end_of_cmd" [list2json_strings $params]]}]
if {$sent != 0} {
global $var
set $var "null"
}
}
proc send_cmd {cmd params {only 0}} {
global id_num
set var "var_$id_num"
global $var
set $var ""
incr id_num
if {$only == 0} {
after 1 "transmit_cmd $cmd \"$params\" $var"
} else {
after 1 "transmit_cmd_strings $cmd \"$params\" $var"
}
tkwait variable $var
set res [subst $$var]
if {[lindex $res 0] == 1} {
return [lindex $res 1]
} else {
report_status "communication error result: [lindex $res 1]"
return ""
}
}
proc call_act_r_command {cmd {model "nil"} {params ""}} {
set result [send_cmd {evaluate} [concat [list $cmd $model] $params]]
if {$result == "null"} {
return ""
} else {
return $result
}
}
proc call_act_r_command_string_only {cmd {model "nil"} {params ""}} {
set result [send_cmd {evaluate} [concat [list $cmd $model] $params] 1]
if {$result == "null"} {
return ""
} else {
return $result
}
}
proc send_cmd_with_result {cmd params} {
global id_num
set var "var_$id_num"
global $var
set $var ""
incr id_num
after 1 "transmit_cmd $cmd \"$params\" $var"
tkwait variable $var
set res [subst $$var]
return $res
}
proc call_act_r_command_with_error_messages {cmd {model "nil"} {params ""}} {
return [send_cmd_with_result {evaluate} [concat [list $cmd $model] $params]]
}
# code from wiki.tcl.tk/3015
proc ip:address {} {
# find out localhost's IP address
# courtesy David Gravereaux, Heribert Dahms
set TheServer [socket -server none -myaddr [info hostname] 0]
set MyIP [lindex [fconfigure $TheServer -sockname] 0]
close $TheServer
return $MyIP
}
proc ip:address_local {} {
# find out localhost's IP address
# courtesy David Gravereaux, Heribert Dahms
catch {
set TheServer [socket -server none -myaddr "localhost" 0]
set MyIP [lindex [fconfigure $TheServer -sockname] 0]
close $TheServer
}
return $MyIP
}
proc start_connection {{address ""} {port ""}} {
global environment_socket
global local_connection
global actr_address
global actr_port
global options_array
if {$address == ""} {
if {[file readable "~/act-r-address.txt"]} {
set fileid [open "~/act-r-address.txt" "r"]
set address [read $fileid]
close $fileid
} else {
set address $actr_address
}
}
if {$port == ""} {
if {[file readable "~/act-r-port-num.txt"]} {
set fileid [open "~/act-r-port-num.txt" "r"]
set port [read $fileid]
close $fileid
} else {
set port $actr_port
}
}
if {$options_array(use_localhost) == 1 && $address == "127.0.0.1"} {
set address "localhost"
}
set actr_address $address
set actr_port $port
set environment_socket [socket $address $port]
fconfigure $environment_socket -blocking no -buffering none
fileevent $environment_socket readable "collect_incoming $environment_socket"
send_cmd {set-name} [list "ACT-R Environment"]
if {$address == "localhost" || $address == [ip:address] || $address == [ip:address_local]} {
set local_connection 1
} else {
set local_connection 0
}
}
proc update_text_pane {pane text} {
$pane configure -state normal
$pane delete 1.0 end
if {[string trimleft $text] == ""} {
$pane configure -state disabled
} else {
$pane insert 1.0 $text
}
}
# assume that the list var is $box.var
proc update_list_box {box vals {select 1} {generate 0}} {
global $box.var
if {[string trimleft $vals] == ""} {
set $box.var ""
$box selection set 0
} else {
set $box.var $vals
$box selection clear 0 end
if {$select == 1} {
$box selection set 0
}
}
if {$generate == 1} {
event generate $box <<ListboxSelect>>
}
}
# want things to update when 'selected' which
# seems to be a tricky thing to do efficiently
# because a focusin on the toplevel window triggers
# for all the subwindows and setting it for a subwindow
# might not result in it getting called if a different
# subwindow is how it comes into focus.
# My current approach is to add a special tag to the
# toplevel window and call the event during that.
# There's still a gotcha however because at least
# on windows one can close a window that doesn't
# currently have the focus which creates a race
# condition between the focus event and the destroy
# event. If the destroy completes before all of
# the focus happens it can often lead to errors so
# I'm just going to wrap a catch around it and
# hope it all works out for now.
proc set_update_script {win script} {
set new_tags [concat [list [new_variable_name "focus_tag"]] [bindtags $win]]
bindtags $win $new_tags
bind [lindex $new_tags 0] <FocusIn> "catch {eval {$script}}"
}
| 10,836 | Common Lisp | .cl | 340 | 26.323529 | 155 | 0.605449 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 80f0c5d80e2d904aad302c09d0cb010bfce196a201d7ed0c155793af74462ac3 | 14,324 | [
-1
] |
14,325 | starter.tcl | asmaloney_ACT-R/environment/GUI/starter.tcl | #!/bin/sh
# start with wish instead \
exec wish "$0"
# This was formerly in the splash-screen.tcl init file
# This script opens a window with the Powered by ONR Logo in it
# centered on the screen for 3 seconds or until it's clicked
# read the image from the file
image create photo onr_logo -file [file join [pwd] "logo.gif"]
#create a window for it with no border and hide it
toplevel .splash
if {$tcl_platform(os) != "Darwin"} {
wm overrideredirect .splash 1
}
wm withdraw .splash
# make a label to hold the image and put it in the window
label .splash.image -image onr_logo
pack .splash.image
# create a variable that will trigger the destruction of the window
# after 3 seconds or when the window is clicked
set clear_splash 0
global clear_splash
# compute the window position given that the
# logo is 579x288 and set it
set x [expr ([winfo screenwidth .]/2) - 290]
set y [expr ([winfo screenheight .]/2) - 144]
wm geometry .splash +$x+$y
# show the window
wm deiconify .splash
focus -force .splash
# set the variable that triggers destruction after 3 seconds
# or as soon as a button is pressed on the window
after 3000 {set clear_splash 1}
bind .splash <ButtonPress> {set clear_splash 1}
# wait for one of the triggering events to happen
tkwait variable clear_splash
# close the window
destroy .splash
# Here's where the real work takes place...
set quit_now ""
proc set_quit_now {val} {
global quit_now
set quit_now $val
}
# close the console window if it's open
if {$tcl_platform(platform) != "unix"} {console hide}
# Start by hiding .
wm withdraw .
file delete [file join [pwd] "error.log"]
interp create env_instance
load {} Tk env_instance
env_instance alias set_return_result set_quit_now
env_instance alias console console
env_instance eval {source "server.tcl"}
if {$quit_now == ""} {tkwait variable quit_now}
interp delete env_instance
exit
# when debugging through the console need to
# make sure that I deal with the sub interpreter:
#
# 4 % env_instance eval {winfo children .}
# .control_panel .copyright
| 2,066 | Common Lisp | .cl | 61 | 32.196721 | 67 | 0.762918 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2e43767a3203575b70e51ea928684d94c715415e4273696c5cd4a01a7b812455 | 14,325 | [
-1
] |
14,326 | server.tcl | asmaloney_ACT-R/environment/GUI/server.tcl | #
# This is the main environment file.
# It contains the procedures and variables for the network
# communication, sources all of the other files, creates the
# control panel window as .control_panel, and opens the listening socket.
# This variable is used to conditionalize code that
# operates differently when the environment is being
# built into a standalone application.
global standalone_mode
# Use 0 for not standalone
# Use 1 for Windows standalone
# Use 2 for Mac standalone
# Use 3 for Android app
set standalone_mode 0
# This variable is an array that will be used to hold the
# table of Lisp handler names indexed by Tcl window name.
# These get entered by the register command coming from Lisp.
global handler_names
# valid_handler_name
# Given a tcl window (w) return true if there is
# currently an entry in the table of that window's
# Lisp handler and 0 if there is not.
proc valid_handler_name {w} {
global handler_names
return [llength [array names handler_names $w]]
}
# get_handler_name
# Given a tcl window (w) return the name of the Lisp handler
# associated with that window. There is no check to see if
# that window has a handler - that must be done prior to calling
# this procedure.
proc get_handler_name {w} {
global handler_names
return $handler_names($w)
}
# set_handler_name
# Given a tcl window (w) and the name of a Lisp handler (h)
# set the handler entry of w to be h in the global lookup table.
proc set_handler_name {w h} {
global handler_names
set handler_names($w) $h
}
# This variable and the next procedure are used to implement
# basically a gentemp in Tcl. The reason I need it is because every
# dialog that comunicates with Lisp needs a unique name and
# probably a variable to be set to return values. This allows
# me to easily create multiple instances of the "standard"
# environment dialogs.
global variable_count_array
# new_variable_name
# Given any variable name prefix (prefix) return that
# prefix with the next number appended to it. Doesn't
# gurantee uniqueness though because if you use name#
# variables elswhere this could end up generating that
# same name.
proc new_variable_name {prefix} {
global variable_count_array
if [llength [array names variable_count_array $prefix]] {
return "$prefix[incr variable_count_array($prefix)]"
} else {
return "$prefix[set variable_count_array($prefix) 1]"
}
}
# record the Environment's directory
global top_dir
global tcl_env_dir
set tcl_env_dir [pwd]
if {$standalone_mode != 3} {cd ..}
if {$standalone_mode == 0} {cd ..}
if {$standalone_mode == 2} {cd ..}
set top_dir [pwd]
if {$standalone_mode == 2} {cd applications}
if {$standalone_mode == 0} {cd "environment"}
if {$standalone_mode != 3} {cd "gui"}
# Define some general file handling procedures.
# Taken pretty much right from the Tcl/Tk book I've got
proc read_file { filename } {
set data ""
if {[file readable $filename]} {
set fileid [open $filename "r"]
set data [read $fileid]
close $fileid
}
return $data
}
proc save_text {textwidget filename} {
set data [$textwidget get 1.0 {end -1c}]
write_data $data $filename
}
proc write_data {data filename} {
set fileid [open $filename "w"]
puts -nonewline $fileid $data
# I know I shouldn't have to flush before closing, but I've
# got a weird synchronization problem that seems to be caused
# by just this type of thing
flush $fileid
close $fileid
}
proc append_data {data filename} {
set fileid [open $filename "a"]
puts -nonewline $fileid $data
# I know I shouldn't have to flush before closing, but I've
# got a weird synchronization problem that seems to be caused
# by just this type of thing
flush $fileid
close $fileid
}
# Start by hiding .
wm withdraw .
# source all the init folder .tcl files.
# They're sourced in sorted order, so prepending a # to the
# beginning of the name helps enforce an order on them.
#cd [file join $tcl_env_dir init]
global init_error_msg
set init_error 0
foreach f [lsort [glob -nocomplain -directory [file join $tcl_env_dir init] *.tcl]] {
if {[catch {source $f} init_error_msg] } {
append_data "Error during init of $f: $init_error_msg\n" [file join $tcl_env_dir "error.log"]
set init_error 1
}
}
# Create the Control Panel here...
toplevel .control_panel
wm title .control_panel "Control Panel"
wm geometry .control_panel [get_configuration .control_panel]
# for now just have a label to report errors.
global global_status
label .control_panel.status -textvariable global_status -text "" -borderwidth 1 -font intro_s_font
pack .control_panel.status
# Then it needs a "scrollable frame" for the controls since the window is
# getting too big for small (laptop) displays. Because of issues with
# including the libraries in the executables I'm not going to use the BWidgets or
# iwidgets extensions and just use a simple hack which is based on code
# found at http://www.tek-tips.com/viewthread.cfm?qid=372792 by
# Ken Jones of Avia Training and Consulting, www.avia-training.com
# Create a "hull" frame to contain all other widgets
# composing the scrollable frame.
frame .control_panel.frame
canvas .control_panel.frame.c -height 100 -width 50 -yscrollcommand ".control_panel.frame.ybar set"
scrollbar .control_panel.frame.ybar -orient vertical -command ".control_panel.frame.c yview"
# Create the frame that will actually
# hold all children of the scrollable
# frame. All children should be packed
# or gridded into this frame, *not* the
# hull frame or the canvas!
frame .control_panel.frame.c.contents
# Tell the canvas to display the frame,
# anchoring the upper-left hand corner
# of the frame in the upper-left hand
# corner of the canvas
set .control_panel.window.tag [.control_panel.frame.c create window 0 0 -anchor nw -window .control_panel.frame.c.contents -tag win]
# Use grid to display the canvas and its
# scrollbars. Handle resizing properly.
grid .control_panel.frame.c -row 0 -column 0 -sticky nsew -pady 4 -padx 2
grid .control_panel.frame.ybar -row 0 -column 1 -sticky ns -pady 4 -padx 2
grid columnconfigure .control_panel.frame 0 -weight 1
grid rowconfigure .control_panel.frame 0 -weight 1
# Detect <Configure> events on the frame
# to detect when it is first displayed
# and any time is is resized. In either
# case, recompute the visible bounds of
# the canvas and update its -scrollregion
# attribute.
# Not sure why I need to handle both, but need the first one
# to adjust it when the control panel window resizes and the
# second is needed so that the initial display is drawn correctly.
#
bind .control_panel.frame <Configure> {
.control_panel.frame.c configure -scrollregion [.control_panel.frame.c bbox all]
.control_panel.frame.c itemconfigure win -width [winfo width .control_panel.frame.c]
}
bind .control_panel.frame.c.contents <Configure> {
.control_panel.frame.c configure -scrollregion [.control_panel.frame.c bbox all]
.control_panel.frame.c itemconfigure win -width [winfo width .control_panel.frame.c]
}
pack .control_panel.frame -expand yes -fill both
# Now instead of packing the buttons directly on the control panel one has
# to get the name of the correct parent window with the control_panel_name
# procedure something like this:
# button [control_panel_name].tool ...
# pack [control_panel_name].tool ...
proc control_panel_name {} {return ".control_panel.frame.c.contents"}
proc report_status {s} {
global global_status
global tcl_env_dir
set global_status "ERROR Logged"
append_data $s [file join $tcl_env_dir "error.log"]
}
# For debugging I need access to the console window, so
# here's how to get it -> shift-control-L
bind .control_panel <Shift-Control-Key-L> {console show}
proc clean_exit {} {
save_window_positions
# foreach w [winfo children .] {
# if {$w != ".control_panel"} {
# catch {destroy $w}
# }
# }
destroy .
set_return_result 1
}
wm protocol .control_panel WM_DELETE_WINDOW {
global current_open_model
global standalone_mode
global environment_socket
set destroy 1
if {$standalone_mode == 1} { # Windows version needs to kill the Lisp explicitly
set answer [tk_messageBox -icon warning -title "Exit the Environment?" \
-message "Closing this window stops ACT-R. Do you want to quit now?" \
-type yesno]
switch -- $answer {
no {
set destroy 0
}
yes {
if {$current_open_model != ""} {
set answer [tk_messageBox -icon warning -title "Model still open" \
-message "There is a model open. Should the environment \
close the model before quitting (all unsaved\
changes will be lost if it is not closed)?" \
-type yesno]
switch -- $answer {
yes {
close_model
}
}
}
}
}
} elseif {$current_open_model != ""} {
set answer [tk_messageBox -icon warning -title "Model still open" \
-message "There is a model open. Should the environment \
close the model before quitting (all unsaved\
changes will be lost if it is not closed)?" \
-type yesno]
switch -- $answer {
yes {
close_model
}
}
}
if $destroy {
clean_exit
}
}
# start the lisp side running if necessary
if {$standalone_mode == 1} {
set cur_dir [pwd]
global top_dir
cd [file join $top_dir apps]
if [catch {exec "actr-s-64.exe" -V}] {
if [catch {exec "actr-s-32.exe" -V}] {
tk_messageBox -icon warning -title "No ACT-R available" \
-message "Cannot run the ACT-R application. Contact Dan for help." -type ok
clean_exit
} else {
exec "./run-32.bat" &
}
} else {
exec "./run-64.bat" &
}
cd $cur_dir
}
# Source the new-server file which actually impements the
# client code for connecting to the ACT-R DES server.
source "new-server.tcl"
# Connect to the Lisp server
set not_connected 1
set connect_addr ""
while {$not_connected} {
if {[catch {start_connection $connect_addr} init_error_msg] } {
set try_again [tk_messageBox -icon warning -title "Connection Problem" -type yesnocancel -message "Error occurred trying to connect to ACT-R\n$actr_address : $actr_port \nError: $init_error_msg \nYes to try again using the ACT-R address file.\nNo to try again using localhost.\nCancel to quit."]
if {$try_again == "cancel"} {
set not_connected 0
tk_messageBox -icon warning -title "Environment terminated" -type ok -message "ACT-R Environment GUI components not started."
clean_exit
} else {
if {$try_again == "no"} {
set connect_addr [ip:address_local]
if {$connect_addr == $actr_address} {
set connect_addr "localhost"
}
} else {
set connect_addr ""
}
}
} else {
set not_connected 0
}
}
set up_and_running 0
# source all the dialog folder .tcl files.
# They're sourced in sorted order, so prepending a number to the
# beginning of the name helps enforce an order on them.
foreach f [lsort [glob -nocomplain -directory [file join $tcl_env_dir dialogs] *.tcl]] {
if { [catch {source $f} init_error_msg] } {
append_data "Error during dialog loading of $f: $init_error_msg\n" [file join $tcl_env_dir "error.log"]
set global_status "dialog error"
}
}
set up_and_running 1
# Below is a modified version of the tk_dilog command which I've
# named my_tk_dialog. It uses my text and button fonts to build
# the display. I've included all the original copyrights and
# license info along with it (instead of including the license
# file separately).
#
# dialog.tcl --
#
# This file defines the procedure tk_dialog, which creates a dialog
# box containing a bitmap, a message, and one or more buttons.
#
# RCS: @(#) $Id: dialog.tcl,v 1.14.2.3 2006/01/25 18:21:41 dgp Exp $
#
# Copyright (c) 1992-1993 The Regents of the University of California.
# Copyright (c) 1994-1997 Sun Microsystems, Inc.
#
# This software is copyrighted by the Regents of the University of
# California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
# Corporation and other parties. The following terms apply to all files
# associated with the software unless explicitly disclaimed in
# individual files.
#
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors
# and need not follow the licensing terms described here, provided that
# the new terms are clearly indicated on the first page of each file where
# they apply.
#
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
# FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
# ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
# DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
# MODIFICATIONS.
#
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
# are acquiring the software on behalf of the Department of Defense, the
# software shall be classified as "Commercial Computer Software" and the
# Government shall have only "Restricted Rights" as defined in Clause
# 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
# authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
#
#
# ::tk_dialog:
#
# This procedure displays a dialog box, waits for a button in the dialog
# to be invoked, then returns the index of the selected button. If the
# dialog somehow gets destroyed, -1 is returned.
#
# Arguments:
# w - Window to use for dialog top-level.
# title - Title to display in dialog's decorative frame.
# text - Message to display in dialog.
# bitmap - Bitmap to display in dialog (empty string means none).
# default - Index of button that is to display the default ring
# (-1 means none).
# args - One or more strings to display in buttons across the
# bottom of the dialog box.
proc ::my_tk_dialog {w title text bitmap default args} {
global tcl_platform
variable ::tk::Priv
# Check that $default was properly given
if {[string is integer -strict $default]} {
if {$default >= [llength $args]} {
return -code error "default button index greater than number of\
buttons specified for tk_dialog"
}
# Never call if -strict option is omitted in previous test !
} elseif {"" eq $default} {
set default -1
} else {
set default [lsearch -exact $args $default]
}
# 1. Create the top-level window and divide it into top
# and bottom parts.
destroy $w
toplevel $w -class Dialog
wm title $w $title
wm iconname $w Dialog
wm protocol $w WM_DELETE_WINDOW { }
# Dialog boxes should be transient with respect to their parent,
# so that they will always stay on top of their parent window. However,
# some window managers will create the window as withdrawn if the parent
# window is withdrawn or iconified. Combined with the grab we put on the
# window, this can hang the entire application. Therefore we only make
# the dialog transient if the parent is viewable.
#
if {[winfo viewable [winfo toplevel [winfo parent $w]]] } {
wm transient $w [winfo toplevel [winfo parent $w]]
}
set windowingsystem [tk windowingsystem]
if {$tcl_platform(platform) eq "macintosh" || $windowingsystem eq "aqua"} {
::tk::unsupported::MacWindowStyle style $w dBoxProc
}
frame $w.bot
frame $w.top
if {$windowingsystem eq "x11"} {
$w.bot configure -relief raised -bd 1
$w.top configure -relief raised -bd 1
}
pack $w.bot -side bottom -fill both
pack $w.top -side top -fill both -expand 1
# 2. Fill the top part with bitmap and message (use the option
# database for -wraplength and -font so that they can be
# overridden by the caller).
option add *Dialog.msg.wrapLength 3i widgetDefault
if {$tcl_platform(platform) eq "macintosh" || $windowingsystem eq "aqua"} {
option add *Dialog.msg.font system widgetDefault
} else {
option add *Dialog.msg.font {Times 12} widgetDefault
}
label $w.msg -justify left -text $text -font label_font
pack $w.msg -in $w.top -side right -expand 1 -fill both -padx 3m -pady 3m
if {$bitmap ne ""} {
if {($tcl_platform(platform) eq "macintosh"
|| $windowingsystem eq "aqua") && ($bitmap eq "error")} {
set bitmap "stop"
}
label $w.bitmap -bitmap $bitmap
pack $w.bitmap -in $w.top -side left -padx 3m -pady 3m
}
# 3. Create a row of buttons at the bottom of the dialog.
set i 0
foreach but $args {
button $w.button$i -text $but -font button_font -command [list set ::tk::Priv(button) $i]
if {$i == $default} {
$w.button$i configure -default active
} else {
$w.button$i configure -default normal
}
grid $w.button$i -in $w.bot -column $i -row 0 -sticky ew \
-padx 10 -pady 4
grid columnconfigure $w.bot $i
# We boost the size of some Mac buttons for l&f
if {$tcl_platform(platform) eq "macintosh" || $windowingsystem eq "aqua"} {
set tmp [string tolower $but]
if {$tmp eq "ok" || $tmp eq "cancel"} {
grid columnconfigure $w.bot $i -minsize [expr {59 + 20}]
}
}
incr i
}
# 4. Create a binding for <Return> on the dialog if there is a
# default button.
if {$default >= 0} {
bind $w <Return> "
[list $w.button$default] configure -state active -relief sunken
update idletasks
after 100
set ::tk::Priv(button) $default
"
}
# 5. Create a <Destroy> binding for the window that sets the
# button variable to -1; this is needed in case something happens
# that destroys the window, such as its parent window being destroyed.
bind $w <Destroy> {set ::tk::Priv(button) -1}
# 6. Withdraw the window, then update all the geometry information
# so we know how big it wants to be, then center the window in the
# display and de-iconify it.
wm withdraw $w
update idletasks
set x [expr {[winfo screenwidth $w]/2 - [winfo reqwidth $w]/2 \
- [winfo vrootx [winfo parent $w]]}]
set y [expr {[winfo screenheight $w]/2 - [winfo reqheight $w]/2 \
- [winfo vrooty [winfo parent $w]]}]
# Make sure that the window is on the screen and set the maximum
# size of the window is the size of the screen. That'll let things
# fail fairly gracefully when very large messages are used. [Bug 827535]
if {$x < 0} {
set x 0
}
if {$y < 0} {
set y 0
}
wm maxsize $w [winfo screenwidth $w] [winfo screenheight $w]
wm geometry $w +$x+$y
wm deiconify $w
tkwait visibility $w
# 7. Set a grab and claim the focus too.
set oldFocus [focus]
set oldGrab [grab current $w]
if {$oldGrab ne ""} {
set grabStatus [grab status $oldGrab]
}
grab $w
if {$default >= 0} {
focus $w.button$default
} else {
focus $w
}
# 8. Wait for the user to respond, then restore the focus and
# return the index of the selected button. Restore the focus
# before deleting the window, since otherwise the window manager
# may take the focus away so we can't redirect it. Finally,
# restore any grab that was in effect.
vwait ::tk::Priv(button)
catch {focus $oldFocus}
catch {
# It's possible that the window has already been destroyed,
# hence this "catch". Delete the Destroy handler so that
# Priv(button) doesn't get reset by it.
bind $w <Destroy> {}
destroy $w
}
if {$oldGrab ne ""} {
if {$grabStatus ne "global"} {
grab $oldGrab
} else {
grab -global $oldGrab
}
}
return $Priv(button)
}
| 20,860 | Common Lisp | .cl | 529 | 35.780718 | 299 | 0.709519 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 8b1df2f49a24f79b10cf0391a71caee6174553889a9fa2d1e31b70afe6f2a4cb | 14,326 | [
-1
] |
14,327 | pstarter.tcl | asmaloney_ACT-R/environment/GUI/pstarter.tcl | # This is a custom starter for use with Python evaluating
# the Tcl/Tk instead of a specific Tcl/Tk or wish app.
# That makes it possible to start one from within a Jupyter
# notebook, and also provides a backup way to start it if
# the application doesn't work.
# The main differences are that it doesn't need to close
# a console window and it doesn't need to start a new
# interpreter instance to run things.
# This was formerly in the splash-screen.tcl init file
# This script opens a window with the Powered by ONR Logo in it
# centered on the screen for 3 seconds or until it's clicked
# read the image from the file
image create photo onr_logo -file [file join [pwd] "logo.gif"]
#create a window for it with no border and hide it
toplevel .splash
if {$tcl_platform(os) != "Darwin"} {
wm overrideredirect .splash 1
}
wm withdraw .splash
# make a label to hold the image and put it in the window
label .splash.image -image onr_logo
pack .splash.image
# create a variable that will trigger the destruction of the window
# after 3 seconds or when the window is clicked
set clear_splash 0
global clear_splash
# compute the window position given that the
# logo is 579x288 and set it
set x [expr ([winfo screenwidth .]/2) - 290]
set y [expr ([winfo screenheight .]/2) - 144]
wm geometry .splash +$x+$y
# show the window
wm deiconify .splash
focus -force .splash
# set the variable that triggers destruction after 3 seconds
# or as soon as a button is pressed on the window
after 3000 {set clear_splash 1}
bind .splash <ButtonPress> {set clear_splash 1}
# wait for one of the triggering events to happen
tkwait variable clear_splash
# close the window
destroy .splash
wm withdraw .
file delete [file join [pwd] "error.log"]
proc set_return_result {x} {
}
source "server.tcl"
| 1,872 | Common Lisp | .cl | 47 | 36.765957 | 68 | 0.751546 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d18aa01ec245d4fd9598bed327c8ba200903b52caeeb85d8c2f6b417fd34851a | 14,327 | [
-1
] |
14,328 | json.tcl | asmaloney_ACT-R/environment/GUI/json.tcl | #
# JSON parser for Tcl.
#
# See http://www.json.org/ && http://www.ietf.org/rfc/rfc4627.txt
#
# Copyright 2006 ActiveState Software Inc.
#
# $Id: json.tcl,v 1.2 2006/08/25 23:19:53 hobbs Exp $
#
if {$::tcl_version < 8.5} {
package require dict
}
package provide json 1.0
namespace eval json {}
proc json::getc {{txtvar txt}} {
# pop single char off the front of the text
upvar 1 $txtvar txt
if {$txt eq ""} {
return -code error "unexpected end of text"
}
set c [string index $txt 0]
set txt [string range $txt 1 end]
return $c
}
proc json::json2dict {txt} {
return [_json2dict]
}
proc json::_json2dict {{txtvar txt}} {
upvar 1 $txtvar txt
set state TOP
set txt [string trimleft $txt]
while {$txt ne ""} {
set c [string index $txt 0]
# skip whitespace
while {[string is space $c]} {
getc
set c [string index $txt 0]
}
if {$c eq "\{"} {
# object
switch -- $state {
TOP {
# we are dealing with an Object
getc
set state OBJECT
set dictVal [dict create]
}
VALUE {
# this object element's value is an Object
dict set dictVal $name [_json2dict]
set state COMMA
}
LIST {
# next element of list is an Object
lappend listVal [_json2dict]
set state COMMA
}
default {
return -code error "unexpected open brace in $state mode"
}
}
} elseif {$c eq "\}"} {
getc
if {$state ne "OBJECT" && $state ne "COMMA"} {
return -code error "unexpected close brace in $state mode"
}
return $dictVal
} elseif {$c eq ":"} {
# name separator
getc
if {$state eq "COLON"} {
set state VALUE
} else {
return -code error "unexpected colon in $state mode"
}
} elseif {$c eq ","} {
# element separator
if {$state eq "COMMA"} {
getc
if {[info exists listVal]} {
set state LIST
} elseif {[info exists dictVal]} {
set state OBJECT
}
} else {
return -code error "unexpected comma in $state mode"
}
} elseif {$c eq "\""} {
# string
# capture quoted string with backslash sequences
set reStr {(?:(?:\")(?:[^\\\"]*(?:\\.[^\\\"]*)*)(?:\"))}
set string ""
if {![regexp $reStr $txt string]} {
set txt [string replace $txt 32 end ...]
return -code error "invalid formatted string in $txt"
}
set txt [string range $txt [string length $string] end]
# chop off outer ""s and substitute backslashes
# This does more than the RFC-specified backslash sequences,
# but it does cover them all
set string [subst -nocommand -novariable \
[string range $string 1 end-1]]
switch -- $state {
TOP {
return $string
}
OBJECT {
set name $string
set state COLON
}
LIST {
lappend listVal $string
set state COMMA
}
VALUE {
dict set dictVal $name $string
unset name
set state COMMA
}
}
} elseif {$c eq "\["} {
# JSON array == Tcl list
switch -- $state {
TOP {
getc
set state LIST
}
LIST {
lappend listVal [_json2dict]
set state COMMA
}
VALUE {
dict set dictVal $name [_json2dict]
set state COMMA
}
default {
return -code error "unexpected open bracket in $state mode"
}
}
} elseif {$c eq "\]"} {
# end of list
getc
if {![info exists listVal]} {
#return -code error "unexpected close bracket in $state mode"
# must be an empty list
return ""
}
return $listVal
} elseif {0 && $c eq "/"} {
# comment
# XXX: Not in RFC 4627
getc
set c [getc]
switch -- $c {
/ {
# // comment form
set i [string first "\n" $txt]
if {$i == -1} {
set txt ""
} else {
set txt [string range $txt [incr i] end]
}
}
* {
# /* comment */ form
getc
set i [string first "*/" $txt]
if {$i == -1} {
return -code error "incomplete /* comment"
} else {
set txt [string range $txt [incr i] end]
}
}
default {
return -code error "unexpected slash in $state mode"
}
}
} elseif {[string match {[-0-9]} $c]} {
# one last check for a number, no leading zeros allowed,
# but it may be 0.xxx
string is double -failindex last $txt
if {$last > 0} {
set num [string range $txt 0 [expr {$last - 1}]]
set txt [string range $txt $last end]
switch -- $state {
TOP {
return $num
}
LIST {
lappend listVal $num
set state COMMA
}
VALUE {
dict set dictVal $name $num
set state COMMA
}
default {
getc
return -code error "unexpected number '$c' in $state mode"
}
}
} else {
getc
return -code error "unexpected '$c' in $state mode"
}
} elseif {[string match {[ftn]} $c]
&& [regexp {^(true|false|null)} $txt val]} {
# bare word value: true | false | null
set txt [string range $txt [string length $val] end]
switch -- $state {
TOP {
return $val
}
LIST {
lappend listVal $val
set state COMMA
}
VALUE {
dict set dictVal $name $val
set state COMMA
}
default {
getc
return -code error "unexpected '$c' in $state mode"
}
}
} else {
# error, incorrect format or unexpected end of text
return -code error "unexpected '$c' in $state mode"
}
}
}
proc json::dict2json {dictVal} {
# XXX: Currently this API isn't symmetrical, as to create proper
# XXX: JSON text requires type knowledge of the input data
set json ""
dict for {key val} $dictVal {
# key must always be a string, val may be a number, string or
# bare word (true|false|null)
if {0 && ![string is double -strict $val]
&& ![regexp {^(?:true|false|null)$} $val]} {
set val "\"$val\""
}
append json "\"$key\": $val," \n
}
return "\{${json}\}"
}
proc json::list2json {listVal} {
return "\[$[join $listVal ,]\]"
}
proc json::string2json {str} {
return "\"$str\""
}
| 6,036 | Common Lisp | .cl | 253 | 19.118577 | 68 | 0.583999 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e50c8f71878de16f7b5459ca02defa156ef9f7efe56867c76d74a377a1e9aaee | 14,328 | [
-1
] |
14,329 | 03-fonts.tcl | asmaloney_ACT-R/environment/GUI/init/03-fonts.tcl |
# This file contains all of the font settings that I will use for createing
# the dialogs. By setting things this way I hope to accomplish 2 things.
# First, it should make the dialogs look very similar on all platforms, and
# second it should allow easy configuration by end users through a dialog
# because it could just write a 'font configure X' line to the config file.
# These are fixed sizes in pixels to maintain uniformity
font create intro_s_font -family helvetica -size -12 -weight bold -slant roman -underline 0 -overstrike 0
font create intro_l_font -family helvetica -size -18 -weight bold -slant roman -underline 0 -overstrike 0
font create button_font -family helvetica -size -12 -weight normal -slant roman -underline 0 -overstrike 0
font create label_font -family times -size -14 -weight bold -slant roman -underline 0 -overstrike 0
font create list_font -family times -size -14 -weight normal -slant roman -underline 0 -overstrike 0
font create text_font -family courier -size -14 -weight normal -slant roman -underline 0 -overstrike 0
font create checkbox_font -family times -size -12 -weight normal -slant roman -underline 0 -overstrike 0
font create menu_font -family helvetica -size -10 -weight normal -slant roman -underline 0 -overstrike 0
font create graphic_trace_font -family courier -size -12 -weight bold -slant roman -underline 0 -overstrike 0
font create dm_tree_slot_name -family courier -size -11 -weight normal -slant italic -underline 0 -overstrike 0
# These two are using point sizes because they're not tied into gui elements
font create env_window_font -family courier -size 12 -weight normal -slant roman -underline 0 -overstrike 0
font create edit_font -family courier -size 14 -weight normal -slant roman -underline 0 -overstrike 0
| 1,792 | Common Lisp | .cl | 19 | 92.421053 | 111 | 0.787706 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 3efe7441775b3baaef0d5e5ad24d2a30b7dea23bba2c999f3d6855b2c4016c74 | 14,329 | [
-1
] |
14,330 | 02-configurations.tcl | asmaloney_ACT-R/environment/GUI/init/02-configurations.tcl | # These strings set the default positions and sizes to use for the
# dialogs so named. They are formatted such that they can be passed to
# wm geometry. The plan is to actually change them when the window
# is moved or resized, so that the next one appears where the last one was
# (could be an option setting) and then it gets written to the config file
# on exit so that next time things "are as they were the last time".
set screen_width [winfo screenwidth .]
set screen_height [winfo screenheight .]
set screen_center_x [expr $screen_width / 2]
set screen_center_y [expr $screen_height / 2]
global window_config
set window_config(.copyright) \
"400x466+[expr $screen_center_x - 200]+[expr $screen_center_y - 233]"
set window_config(.control_panel) \
"235x700+[expr $screen_width - 255]+[expr $screen_center_y - 350]"
set window_config(.reload_response) \
"500x230+[expr $screen_center_x - 250]+[expr $screen_center_y - 115]"
set window_config(.stepper) \
"500x550+[expr $screen_center_x - 250]+[expr $screen_center_y - 275]"
set window_config(.event_queue) \
"800x180+[expr $screen_center_x - 400]+[expr $screen_center_y - 90]"
set window_config(.tutor_response) \
"480x130+[expr $screen_center_x - 240]+[expr $screen_center_y - 65]"
set window_config(.declarative) \
"420x300+[expr $screen_center_x - 210]+[expr $screen_center_y - 150]"
set window_config(.whynotdm) \
"200x300+[expr $screen_center_x - 100]+[expr $screen_center_y - 150]"
set window_config(.procedural) \
"500x400+[expr $screen_center_x - 250]+[expr $screen_center_y - 200]"
set window_config(.whynot) \
"200x300+[expr $screen_center_x - 100]+[expr $screen_center_y - 150]"
set window_config(.buffers) \
"470x240+[expr $screen_center_x - 235]+[expr $screen_center_y - 120]"
set window_config(.bufferstatus) \
"450x240+[expr $screen_center_x - 225]+[expr $screen_center_y - 120]"
set window_config(.visicon) \
"700x150+[expr $screen_center_x - 350]+[expr $screen_center_y - 100]"
set window_config(.audicon) \
"870x150+[expr $screen_center_x - 435]+[expr $screen_center_y - 100]"
set window_config(.param_viewer) \
"400x330+[expr $screen_center_x - 200]+[expr $screen_center_y - 150]"
set window_config(.graphic_trace) \
"870x500+[expr $screen_center_x - 435]+[expr $screen_center_y - 250]"
set window_config(.vert_graphic_trace) \
"870x500+[expr $screen_center_x - 435]+[expr $screen_center_y - 250]"
set window_config(.pgraph) \
"700x400+[expr $screen_center_x - 350]+[expr $screen_center_y - 200]"
set window_config(.ptrace) \
"410x370+[expr $screen_center_x - 205]+[expr $screen_center_y - 150]"
set window_config(.retrieval_history) \
"670x380+[expr $screen_center_x - 335]+[expr $screen_center_y - 150]"
set window_config(.buffer_history) \
"530x290+[expr $screen_center_x - 265]+[expr $screen_center_y - 100]"
set window_config(.audicon_history) \
"734x300+[expr $screen_center_x - 367]+[expr $screen_center_y - 150]"
set window_config(.visicon_history) \
"810x340+[expr $screen_center_x - 405]+[expr $screen_center_y - 170]"
set window_config(.text_trace_history) \
"714x340+[expr $screen_center_x - 387]+[expr $screen_center_y - 170]"
set window_config(.history_recorder) \
"360x390+[expr $screen_center_x - 180]+[expr $screen_center_y - 195]"
set window_config(.history_playback) \
"512x370+[expr $screen_center_x - 256]+[expr $screen_center_y - 185]"
set window_config(.save_history_response) \
"630x150+[expr $screen_center_x - 315]+[expr $screen_center_y - 75]"
set window_config(.bold_graphs) \
"660x250+[expr $screen_center_x - 330]+[expr $screen_center_y - 120]"
set window_config(.bold_slices) \
"766x388+[expr $screen_center_x - 383]+[expr $screen_center_y - 150]"
set window_config(.bold_brain_3d) \
"658x586+[expr $screen_center_x - 329]+[expr $screen_center_y - 260]"
set window_config(.bold_brain_3d_real) \
"658x508+[expr $screen_center_x - 329]+[expr $screen_center_y - 250]"
set window_config(.pick_buffers) \
"200x340+[expr $screen_center_x - 100]+[expr $screen_center_y - 170]"
set window_config(.options) \
"450x274+[expr $screen_center_x - 225]+[expr $screen_center_y - 137]"
set window_config(.dispatcher) \
"700x274+[expr $screen_center_x - 350]+[expr $screen_center_y - 137]"
set window_config(.tutor_r) \
"496x636+[expr $screen_center_x - 248]+[expr $screen_center_y - 318]"
set window_config(.tutor_cr) \
"554x646+[expr $screen_center_x - 277]+[expr $screen_center_y - 323]"
set window_config(.model) \
"400x500+0+20"
proc check_for_configuration {w} {
global window_config
return [llength [array names window_config $w]]
}
proc get_configuration {w args} {
global window_config
global screen_center_x
global screen_center_y
if [llength $args] {
set_window_config_name [lindex $args 0] $w
}
if {[check_for_configuration $w] == 0} {
set window_config($w) "200x200+[expr $screen_center_x - 100]+[expr $screen_center_y - 100]"
}
return $window_config($w)
}
global window_crossreference
global changed_window_list
proc set_window_config_name {w v} {
global window_crossreference
set window_crossreference($w) $v
}
proc check_for_crossreference {w} {
global window_crossreference
return [llength [array names window_crossreference $w]]
}
bind all <Configure> {
global window_config
global window_crossreference
global changed_window_list
if [check_for_crossreference %W] {
set name $window_crossreference(%W)
} else {
set name %W
}
if [check_for_configuration $name] {
set window_config($name) [wm geometry %W]
set changed_window_list($name) 1
}
}
global gui_options
set gui_options(p_selected) #44DA22
set gui_options(p_matched) #FCA31D
set gui_options(p_mismatched) #E1031E
proc save_window_positions {} {
global tcl_env_dir
global changed_window_list
global window_config
global gui_options
set file [file join $tcl_env_dir init "10-userguisettings.tcl"]
write_data "# this file generated when environment is closed\n# refresh . to make sure sizes are right\n\nwm deiconify .\nupdate\nwm withdraw .\n" $file
append_data "if {\[winfo screenwidth .\] != [winfo screenwidth .] || \[winfo screenheight .\] != [winfo screenheight .] || \[lindex \[wm maxsize .\] 0\] != [lindex [wm maxsize .] 0] || \[lindex \[wm maxsize .\] 1\] != [lindex [wm maxsize .] 1]} {\n" $file
append_data " set size_mismatch 1\n} else {\n set size_mismatch 0\n}\n\n" $file
append_data "if \$size_mismatch {\n" $file
append_data " set reset_window_sizes \[tk_messageBox -icon warning -title \"Screen resolution changed\" -type yesno \\\n" $file
append_data " -message \"The screen resolution is not the same as it was the last time the Environment was used. Should the window positions reset to the defaults?\"\]\n" $file
append_data "} else { set reset_window_sizes 0}\n" $file
append_data "if {\$reset_window_sizes != \"yes\"} {\n" $file
foreach name [array names changed_window_list] {
append_data " set window_config($name) $window_config($name)\n" $file
append_data " set changed_window_list($name) 1\n" $file
}
append_data "}\n" $file
foreach name [array names gui_options] {
append_data "set gui_options($name) $gui_options($name)\n" $file
}
}
| 7,431 | Common Lisp | .cl | 152 | 45.513158 | 257 | 0.693835 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 8f9678aae97feab2af0dafac082a648446568ff8f795939f60677ee04dfd85e2 | 14,330 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.