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,039 | 实用编程第3章.lisp | zhlisp_zhlisp/ZHLISP中文编程示例代码/实用编程第3章.lisp | ;;3.1 音乐和记录
(列表 1 2 3)
(列表 :a 1 :b 2 :c 3)
(读符号值 (列表 :a 1 :b 2 :c 3) :a)
(读符号值 (列表 :a 1 :b 2 :c 3) :c)
(函数 录入音乐 (标题 艺术家 评分 转格式)
(列表 :标题 标题 :艺术家 艺术家 :评分 评分 :转格式 转格式))
(录入音乐 "卡路里" "火箭少女101" 7 t)
;;3.2 录入音乐
(空值全局变量 *音乐数据* nil)
(函数 添加记录 (音乐) (添加 音乐 *音乐数据*))
(添加记录 (录入音乐 "卡路里" "火箭少女101" 7 t))
(添加记录 (录入音乐 "三生三世" "张杰" 8 t))
(添加记录 (录入音乐 "明天过后" "张杰" 9 t))
;;3.3 查看数据库的内容
*音乐数据*
;标题: 明天过后
;艺术家: 张杰
;评分: 9
;转格式: T
;标题: 三生三世
;艺术家: 张杰
;评分: 8
;转格式: T
;标题: 卡路里
;艺术家: 火箭少女101
;评分: 7
;转格式: T
(函数 转储数据库 ()
(列表循环 (音乐 *音乐数据*)
(格式 t "~{~a:~10t~a~%~}~%" 音乐)))
(格式 t "~a" "张杰")
(格式 t "~a" :艺术家)
(格式 t "~a:~10t~a" :艺术家 "张杰")
(函数 转储数据库 ()
(格式 t "~{~{~a:~10t~a~%~}~%~}" *音乐数据*))
(转储数据库)
;;3.4 改进用户交互
(函数 提示输入 (提示)
(格式 *输入流* "~a: " 提示)
(强制输出 *输入流*)
(读行 *输入流*))
(函数 提示输入音乐 ()
(录入音乐
(提示输入 "标题")
(提示输入 "艺术家")
(提示输入 "评分")
(提示输入 "转格式 [y/n]")))
;;(解析整数 (提示输入 "评分"))
;;(解析整数 (提示输入 "评分") :junk-allowed t)
;;(或 (解析整数 (提示输入 "评分") :junk-allowed t) 0)
;;(是否 "转格式 [y/n]: ")
(函数 提示输入音乐 ()
(录入音乐
(提示输入 "标题")
(提示输入 "艺术家")
(或 (解析整数 (提示输入 "评分") :junk-allowed t) 0)
(是否 "转格式 [y/n]: ")))
(函数 添加音乐组 ()
(循环 (添加记录 (提示输入音乐))
(判断 (非 (是否 "需要添加下一条信息吗? [y/n]: ")) (返回))))
(添加音乐组)
;标题: 最美的期待
;艺术家: 周笔畅
;评分: 6
;转格式 [y/n]: (y or n) y
;需要添加下一条信息吗? [y/n]: (y or n) y
;标题: 微微一笑很倾城
;艺术家: 杨洋
;评分: 10
;转格式 [y/n]: (y or n) y
;需要添加下一条信息吗? [y/n]: (y or n) y
;标题: 我们不一样
;艺术家: 大壮
;评分: 9
;转格式 [y/n]: (y or n) y
;需要添加下一条信息吗? [y/n]: (y or n) n
;NIL
;;3.5 保存和加载数据库
(函数 保存数据库 (文件名字)
(打开文件 (out 文件名字
:direction :output
:if-exists :supersede)
(读写标准
(打印 *音乐数据* out))))
(保存数据库 "D:\\GitHub\\my-cds.db")
(函数 加载数据库 (文件名字)
(打开文件 (in 文件名字)
(读写标准
(赋值 *音乐数据* (读 in)))))
(加载数据库 "D:\\GitHub\\my-cds.db")
;;(搜索 :艺术家 "张杰")
(不匹配删除 #'偶数 '(1 2 3 4 5 6 7 8 9 10))
(不匹配删除 #'(lambda (x) (= 0 (模 x 2))) '(1 2 3 4 5 6 7 8 9 10))
;;(lambda (x) (= 0 (模 x 2)))
(不匹配删除 #'(lambda (x) (= 1 (模 x 2))) '(1 2 3 4 5 6 7 8 9 10))
(不匹配删除 #'(lambda (音乐) (内同 (读符号值 音乐 :艺术家) "张杰")) *音乐数据*)
(函数 搜索艺术家 (艺术家)
(不匹配删除
#'(lambda (音乐) (内同 (读符号值 音乐 :艺术家) 艺术家))
*音乐数据*))
(函数 搜索 (搜索内容)
(不匹配删除 搜索内容 *音乐数据*))
(搜索 #'(lambda (音乐) (内同 (读符号值 音乐 :艺术家) "张杰")))
(函数 搜索艺术家名 (艺术家名)
#'(lambda (音乐) (内同 (读符号值 音乐 :艺术家) 艺术家名)))
(搜索 (搜索艺术家名 "张杰"))
(函数 临时 (a b c) (列表 a b c))
(临时 1 2 4)
(函数 临时 (&key a b c) (列表 a b c))
(临时 :a 1 :b 2 :c 3) ;==> (1 2 3)
(临时 :c 3 :b 2 :a 1) ;==> (1 2 3)
(临时 :a 1 :c 3) ;==> (1 NIL 3)
(临时) ;==> (NIL NIL NIL)
(函数 临时
(&key a (b 20) (c 30 c-p))
(列表 a b c c-p))
(临时 :a 1 :b 2 :c 3) ;==> (1 2 3 T)
(临时 :c 3 :b 2 :a 1) ;==> (1 2 3 T)
(临时 :a 1 :c 3) ;==> (1 20 3 T)
(临时) ;==> (NIL 20 30 NIL)
;;(搜索 (哪里有 :艺术家 "张杰"))
;;(搜索 (哪里有 :评分 10 :转格式 T))
(函数 哪里有 (&key 标题 艺术家 评分 (转格式 nil 转格式-p))
#'(lambda (音乐)
(与
(判断 标题 (内同 (读符号值 音乐 :标题) 标题) t)
(判断 艺术家 (内同 (读符号值 音乐 :艺术家) 艺术家) t)
(判断 评分 (内同 (读符号值 音乐 :评分) 评分) t)
(判断 转格式-p (内同 (读符号值 音乐 :转格式) 转格式) t))))
;;3.7 更新已有的记录——哪里有再战江湖,读符号值报错,改回为getf,错误原因未知。
(函数 更新 (搜索内容 &key 标题 艺术家 评分 (转格式 nil 转格式-p))
(赋值 *音乐数据*
(映射函数
#'(lambda (行)
(如果真 (函数调用 搜索内容 行)
(判断 标题 (赋值 (getf 行 :标题) 标题))
(判断 艺术家 (赋值 (getf 行 :艺术家) 艺术家))
(判断 评分 (赋值 (getf 行 :评分) 评分))
(判断 转格式-p (赋值 (getf 行 :转格式) 转格式)))
行) *音乐数据*)))
(更新 (哪里有 :艺术家 "张杰") :评分 11)
(搜索 (哪里有 :艺术家 "张杰"))
(函数 删除行 (搜索内容)
(赋值 *音乐数据* (匹配删除 搜索内容 *音乐数据*)))
(删除行 (哪里有 :标题 "最美的期待"))
;;3.8 消除重复,获益良多
(判断 标题 (内同 (读符号值 音乐 :标题) 标题) t)
(搜索 (哪里有 :标题 "三生三世" :转格式 t))
(搜索 #'(lambda (音乐)
(与 (内同 (读符号值 音乐 :标题) "三生三世")
(内同 (读符号值 音乐 :转格式) t))))
(宏 向后 (反向列表) (倒序 反向列表))
(向后 ("你好,世界" t 格式))
;(内同 (读符号值 音乐 区域) 值)
;(函数 比较反向列表 (区域 值) ; 错误
; (列表 内同 (列表 读符号值 音乐 区域) 值))
(函数 比较反向列表 (区域 值)
(列表 '内同 (列表 '读符号值 '音乐 区域) 值))
(比较反向列表 :评分 10)
;(内同
; (读符号值
; 音乐
; :评分)
; 10)
(比较反向列表 :标题 "三生三世")
;(内同
; (读符号值
; 音乐
; :标题)
; "三生三世")
`(1 2 3)
;(1 2 3)
'(1 2 3)
;(1 2 3)
`(1 2 (+ 1 2)) ;==> (1 2 (+ 1 2))
`(1 2 ,(+ 1 2)) ;==> (1 2 3)
(函数 比较反向列表 (区域 值)
`(内同 (读符号值 音乐 ,区域) ,值))
(函数 用列表比较 (区域)
(循环 while 区域
collecting (比较反向列表 (移除前 区域) (移除前 区域))))
(宏 哪里有 (&rest 子列表)
`#'(lambda (音乐) (与 ,@(用列表比较 子列表))))
`(与 ,(列表 1 2 3)) ;==> (与 (1 2 3))
`(与 ,@(列表 1 2 3)) ;==> (与 1 2 3)
`(与 ,@(列表 1 2 3) 4) ;==> (与 1 2 3 4)
(哪里有 :标题 "三生三世" :转格式 t)
;(:标题 "三生三世" :转格式 t)
(展开宏 '(哪里有 :标题 "三生三世" :转格式 t))
;#'(lambda (音乐)
; (与
; (内同
; (读符号值
; 音乐
; :标题)
; "三生三世")
; (内同
; (读符号值
; 音乐
; :转格式)
; T)))
(搜索 (哪里有 :标题 "三生三世" :转格式 t))
| 7,712 | Common Lisp | .lisp | 203 | 20.477833 | 60 | 0.463469 | zhlisp/zhlisp | 6 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 243a74960330347d62a7b8fc9793337bd4207d1c012b6ee7299dcc245fdb7376 | 14,039 | [
-1
] |
14,040 | 中文lisp猜数字游戏.LISP | zhlisp_zhlisp/ZHLISP中文编程示例代码/中文lisp猜数字游戏.LISP | ;;;;使用LispWorks加载本文件,便可以使用中文的函数名、操作符、宏名,可自函数或添加名称。
;;;;只汉化了一小部分,英文和中文字称可同时使用,因为只是新建了一些中文宏。
;;;;所有的符号还必须使用英文符号,中文的不可以使用。
;;;;学习交流www.lisp.vip
;;;;作者:陆志广
;;;;如果你已经加载基本宏和扩展宏,可以从下面的代码直接执行。
(全局变量 *小* 1)
(全局变量 *大* 100)
(函数 猜数字 ()
(移位 (+ *小* *大*) -1))
(函数 小()
(赋值 *大* (1- (猜数字)))
(猜数字))
(函数 大 ()
(赋值 *小* (1+ (猜数字)))
(猜数字))
(函数 开始()
(全局变量 *小* 1)
(全局变量 *大* 100)
(猜数字)) | 886 | Common Lisp | .lisp | 20 | 17 | 51 | 0.447983 | zhlisp/zhlisp | 6 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 72d9c21313d2b0cd576d9366225621df86421b807269d160b092566fccec6c00 | 14,040 | [
-1
] |
14,041 | zhlisp代码转换.bas | zhlisp_zhlisp/zhlisp代码转换/zhlisp代码转换.bas | Attribute VB_Name = "NewMacros"
Sub 用Excel替换()
'Excel文件中的替换(Ctrl+Alt+Z)(HongTiHuan.xls在e盘根目录下)
Dim Bth As String, Thw As String, Xh As Integer
Dim excel_App As Object
Dim excel_Book As Object
Dim excel_sheet As Object
'启动Excel
Set excel_App = CreateObject("Excel.Application") '引用程序对象实例
'设置Excel为不可见
excel_App.Visible = False
'打开文件
Set excel_Book = excel_App.Workbooks.Open(ActiveDocument.Path & "\HongTiHuan.xlsx") '工作簿实例
Set excel_sheet = excel_Book.Worksheets("替换") '数据表实例
Xh = 1
Bth = excel_sheet.Range("A" & Xh).Value
Thw = excel_sheet.Range("B" & Xh).Value
While Bth <> ""
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = Bth '可以使用通配符了
.Replacement.Text = Thw
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Xh = Xh + 1
Bth = excel_sheet.Range("A" & Xh).Value
Thw = excel_sheet.Range("B" & Xh).Value
Wend
'关闭Excel文件
Set excel_sheet = Nothing
excel_App.ActiveWorkbook.Close savechanges:=True '保存对EXCELL进行更改。
Set excel_Book = Nothing
excel_App.Quit
Set excel_App = Nothing
End Sub
| 1,392 | Common Lisp | .lisp | 45 | 26.444444 | 90 | 0.789916 | zhlisp/zhlisp | 6 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4ebc8c3fc18b511480b8de22de4bcd1ffe57564c46e06079da25041416b9f347 | 14,041 | [
-1
] |
14,117 | package.lisp | mabragor_cl-larval/package.lisp | ;;;; package.lisp
(defpackage #:cl-larval
(:use #:cl #:iterate)
(:shadowing-import-from #:named-readtables #:parse-body)
(:shadowing-import-from #:alexandria #:symbolicate)
(:shadow #:! #:~ #:- #:* #:/ #:+ #:<< #:>> #:< #:> #:<= #:>= #:== #:!= #:& #:^ #:\| #:&& #:||
#:sleep #:set #:push #:pop
#:and #:or)
(:export #:with-larval))
| 352 | Common Lisp | .lisp | 9 | 35.777778 | 95 | 0.488235 | mabragor/cl-larval | 6 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c04cf92695bab66c0f7cbb17db0b18bb798434e060c9fc9284ec0371653713d0 | 14,117 | [
-1
] |
14,118 | cl-larval.asd | mabragor_cl-larval/cl-larval.asd | ;;;; cl-larval.asd
(asdf:defsystem #:cl-larval
:serial t
:description "Lisp syntax for assembler for AVR microcontrollers"
:author "Alexander Popolitov <[email protected]>"
:license "GPL"
:depends-on (#:iterate #:cl-interpol #:rutils #:cl-curlex #:named-readtables
#:alexandria #:cl-package-locks #:swank)
:components ((:file "package")
(:file "cl-larval")))
| 392 | Common Lisp | .asd | 10 | 34.9 | 78 | 0.684211 | mabragor/cl-larval | 6 | 0 | 1 | GPL-3.0 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 81cfc9345af8b92132f7a77ec5bb9c3b3dc7197df8b146e2ed793f3ca02c9875 | 14,118 | [
-1
] |
14,136 | load-act-r.lisp | asmaloney_ACT-R/load-act-r.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2015 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 : load-act-r.lisp
;;; Version : 3.1
;;;
;;; Description : Top level loader for the whole ACT-R system.
;;;
;;; Bugs : ???
;;;
;;; To do : [-] Test in a variety of Lisps for issues with the
;;; : logical hostname stuff.
;;; : [ ] Now, look into using the clisp version in other
;;; : lisps because it seems cleaner/more generic than
;;; : the ones I put toghether...
;;; : [x] Use compile-file-pathname instead of always adding a new
;;; : entry for *.fasl-pathname*.
;;;
;;; ----- History -----
;;;
;;; 2004.10.26 Dan
;;; : Creation.
;;; :
;;; : Realized that require doesn't compile things automatically
;;; : in all cases, so added my own require-compiled that does.
;;; 2004.12.10 Dan
;;; : Fixed the make-package for the packaged version (for use
;;; : with ACL at least).
;;; : Reduced the lines to max of 80 chars.
;;; 2005.01.02 Dan
;;; : Changed it so that it loads the "core modules" in a specific
;;; : order and then all other modules.
;;; 2005.01.12 Dan
;;; : * Added the tools directory to the set.
;;; 2005.01.23 Dan
;;; : * Fixed the Lispworks binary extension check. Don't think it
;;; : still needs the old one...
;;; 2005.01.29 Dan
;;; : * Added a feature check into compile-and-load to force it
;;; : to recompile if :actr-recompile is on the features list.
;;; 2005.02.01 Dan
;;; : * This time, the Lispworks feature checks should be set
;;; : properly for OSX (thanks to Chris Sims).
;;; 2005.02.25 Dan
;;; : * Removed the ~\newline usages because that causes problems
;;; : when a Lisp only wants to see native new lines there.
;;; 2005.04.14 Dan
;;; : * Changed compile-and-load so that it throws an error if the
;;; : file it is passed has a non-"lisp" extension. - need to
;;; : verify that in other Lisps to make sure it works right.
;;; 2005.07.07 Dan
;;; : * Fixed the packaged loading for Lispworks now too.
;;; 2005.08.10 Dan
;;; : * Added a new directory to the set (commands) in place of
;;; : where modules was and then moved modules to after the
;;; : devices.
;;; : * Now, there's basically a directory to auto-load in all
;;; : resonable locations, and I can better distribute files
;;; : that were all jammed into tools.
;;; : * Updated the version to 1.0.
;;; 2005.08.16 Dan
;;; : * Added a flag to indicate whether things have been loaded
;;; : previously or not and actually throw an error if this
;;; : file is attempted to be loaded more than once.
;;; 2005.09.16 Dan
;;; : * Added the appropriate feature checks to work "right" with
;;; : ACL 7's IDE i.e. load the devices and package things in
;;; : cg-user when necessary.
;;; 2005.10.18 Dan
;;; : * Added the logical host setup for CMUCL.
;;; : * Moved the smart-load function here and generalized it so
;;; : that framework and core-modules don't need to have
;;; : their own special versions.
;;; : * Also converted those specific loaders to essentially just
;;; : file lists now.
;;; 2005.11.01 Dan
;;; : * Added a new compile-and-load so that things can be loaded
;;; : into MCL 5/5.1 (the versions that have the split open/load
;;; : Mac/Unix file menu options) without having to convert all
;;; : the files first. This file needs to be loaded as a Unix
;;; : file and the rest should take care of itself.
;;; 2005.11.07 Dan
;;; : * Realized that since the environment is loaded from tools
;;; : that there's no way to add patches to the environment
;;; : in an "auto load" directory because things in tools may
;;; : be loaded before the environment. So, I've added yet
;;; : another directory from which files are loaded automatically.
;;; : The other-files directory is now scanned and .lisp files
;;; : are loaded as the last step of the load process.
;;; 2005.12.13 Dan
;;; : * Changed the logical host setup for ACL because it turns
;;; : out that the host-namestring always ends up nil and doesn't
;;; : actually capture the drive info which causes problems if
;;; : the ACT-R sources are on a different drive than the ACL
;;; : assumed default.
;;; 2006.01.04 Dan
;;; : * Added the switches so that it'll load under CMUCL in OS X
;;; : (with ppc).
;;; 2006.06.29 Dan
;;; : * Added components provided by Don Morrison to allow it to be
;;; : loaded into CLisp v2.38 - the CLisp logical host, tighter
;;; : handling of the logical pathnames in general (other Lisps
;;; : didn't mind logical namestrings in places where a pathname
;;; : designator was required), and a shadowing of the CLisp
;;; : execute function.
;;; 2006.08.31 Dan
;;; : * Replaced the *already-loaded-act-r-6-files* variable as
;;; : the reloading test with a feeature check for :act-r-6.0
;;; : which is now placed on the *features* list.
;;; 2007.01.17 Dan
;;; : * Added the support necessary to load into SBCL.
;;; : * Required changing all calls to logical-pathname in the
;;; : directory calls to translate-logical-pathname which should
;;; : work for all Lisps (SHOULD!).
;;; : * NOTE that this doesn't work with SBCL 1.0 under Windows
;;; : because a bug in their directory command doesn't
;;; : recognize the wildcards but they've addressed that so future
;;; : versions of SBCL for Windows should work.
;;; 2007.02.02 Dan
;;; : * Changed the uses for the packaged-actr so that all Lisps
;;; : use "COMMON-LISP" - should work, but this is still an
;;; : an experimental feature.
;;; 2007.02.05 Dan
;;; : * Added the hack for the broken directory command in SBCL for
;;; : Windows so that it can load all of the files now.
;;; 2007.02.26 Dan
;;; : * Added an appropriate fasl extension for LispWorks 5 on
;;; : x86 Macs.
;;; 2007.07.24 Dan
;;; : * Finally added the right extension for LispWorks 5 for
;;; : Windows.
;;; 2007.08.03 Dan
;;; : * Fixed the feature checks so that LispWorks 5 gets the
;;; : right value for Windows...
;;; 2007.09.10 Dan
;;; : * Putting the LispWorks device file pointers in to allow use
;;; : of the beta device interface.
;;; 2008.06.09 Dan
;;; : * Added yet another LispWorks entry for compiled file types
;;; : to cover the LW 5 unix names. Probably about time to try
;;; : getting something that's robust using compile-file-pathname
;;; : instead...
;;; 2008.06.10 Dan
;;; : * Trying a version that uses compile-file-pathname to try
;;; : to set the fasl name "automatically".
;;; 2010.03.09 Dan
;;; : * Changed the openmcl logical setting to the 'generic' one
;;; : to fix problems with different "drives" under Windows.
;;; 2010.03.11 mdb
;;; : * Changed MCL-specific code to not load CFBundle when running
;;; : under MCL 5.2.
;;; 2010.11.02 Dan
;;; : * Added ABCL to the list for logical translation.
;;; 2011.04.28 Dan
;;; : * Define *file-list* here and just set it in the other loaders.
;;; 2012.01.04 Dan
;;; : * Added another directory to the tree: user-loads. That will
;;; : always go last and there will never be any distributed files
;;; : in it. The .lisp files in it will be loaded in order based
;;; : on file name and is for users to add initialization or model
;;; : files to as needed.
;;; : * Removed the old info under general docs.
;;; 2012.05.07 Dan
;;; : * Make the ACL device support dependent on the Windows version
;;; : only and print a warning for the others.
;;; 2012.08.24 Dan
;;; : * Added the switches to load the new ccl-cocoa device and
;;; : removed the mcl device.
;;; 2013.08.09 Dan
;;; : * Fixed a problem with the shadowing of functions in SBCL and
;;; : CLisp when the current package wasn't :cg-user.
;;; 2013.10.07 Dan
;;; : * Added another feature switch to be tested :actr-fast. When
;;; : it's on the features list set the optimize settings for faster
;;; : compiled code.
;;; 2013.12.19 Dan
;;; : * Added an :ecl switch to the logical path definitions.
;;; 2014.02.21 Dan
;;; : * Big warnings that this shouldn't be used!
;;; 2014.05.29 Dan
;;; : * Define the variable used to test for applying the hacks to
;;; : work more like ACT-R 6.0.
;;; 2014.06.16 Dan
;;; : * Added a use :ccl to the :act-r package for CCL.
;;; 2014.07.14 Dan
;;; : * Changed the feature switch from :ACT-R-6.0 to :ACT-R-6.1
;;; : and added a separate :ACT-R switch which can be used in
;;; : the future for testing that "some" ACT-R is loaded.
;;; 2014.08.28 Dan
;;; : * Changed the warning from don't use to pre-release and let me
;;; : know about issues.
;;; 2014.08.29 Dan
;;; : * Double check for the :act-r being on *features* because
;;; : the compiler switch isn't sufficient if the file gets
;;; : compiled when the switch isn't set.
;;; : * Removed the second "do not use" warning as well.
;;; 2014.09.11 Dan
;;; : * Changed the final load print out to say 6.1.
;;; 2014.09.29 Dan
;;; : * Added the actr-load function which does a translate on the
;;; : parameter it's passed so that I can use that in the test
;;; : models and have them work with SBCL and any others which
;;; : don't accept logical to load.
;;; 2014.09.30 Dan
;;; : * Changed the warning to beta instead of pre-release.
;;; 2014.12.01 Dan
;;; : * Removed the beta warning at load time.
;;; 2014.12.02 Dan
;;; : * Added a translate-logical-pathname to the directory passed
;;; : to smart-load so it can be used with logicals in Lisps that
;;; : don't like logicals as pathnames.
;;; 2015.07.28 Dan
;;; : * Renamed it to load-act-r-7.lisp.
;;; : * Changed the logical from "ACT-R6" to "ACT-R" and use the
;;; : general form for all Lisps.
;;; : * Removed all the special code for MCL.
;;; : * Get rid of the 6.0 compatibility hack variable.
;;; : * Changed the feature to :act-r-7.
;;; : * Changed the output to say ACT-R 7.
;;; : * Added an "ACT-R-support" logical for use in other places.
;;; 2015.08.03 Dan
;;; : * Change the package shadowing for CLisp because it seems to
;;; : need the nicknames now.
;;; 2015.08.05 Dan
;;; : * Changed the name again to load-act-r.lisp because I might as
;;; : well do so now while I'm changing everything else...
;;; 2015.10.26 Dan
;;; : * The hack for defconstant in SBCL doesn't work for the newer
;;; : versions so replaced that with something that doesn't depend
;;; : on the internals and just ignores any error in the "rebinding"
;;; : situation. This works for both the old and new versions and
;;; : should continue to work with future versions as well.
;;; 2016.03.03 Dan
;;; : * Only push :act-r onto features here and do specific version
;;; : tags in the version-string file.
;;; : * Use the *actr-architecture-version* value where appropriate.
;;; 2016.03.07 Dan
;;; : * Added system parameters for version info and version checking,
;;; : and also a function for indicating the version a model was
;;; : written for to provide warnings when it is loaded in a
;;; : possibly incompatible version.
;;; 2016.03.09 Dan
;;; : * Added an optional parameter to written-for-act-r-version to
;;; : provide a description for use in the warning.
;;; 2016.03.14 Dan
;;; : * Added the require-extra macro to make it easier to use the
;;; : extras and the requiring-extra function to test in the main
;;; : extra file so it can load more files when needed.
;;; 2016.03.30 Dan
;;; : * Changed written-for-act-r-version to provide more details
;;; : when there is a mismatch and change the system parameter
;;; : :act-r-minor-version to return 0 instead of nil when there
;;; : isn't currently a minor version.
;;; 2016.05.31 Dan
;;; : * Added the finish-format macro which can be used to do a format
;;; : followed by a finish-output on the stream because *error-output*
;;; : is buffered in some Lisps (Windows CCL 1.10+ at least) and
;;; : need to make sure warnings/errors get output immediately.
;;; 2016.06.01 Dan
;;; : * Fixed the :check-act-r-version parameter so that it could
;;; : actually check the versions returned by the :act-r-version
;;; : parameter which includes the -<...> tag at the end.
;;; 2017.03.28 Dan
;;; : * Moved the code for loading the quicklisp libraries here.
;;; 2017.12.04 Dan
;;; : * Editted the warning about Quicklisp to captialize it correctly.
;;; 2018.01.09 Dan
;;; : * Fix the require-extra macro since it was checking the count
;;; : of meta-processes which isn't recorded now.
;;; 2018.03.29 Dan
;;; : * Can't print the version info when building the standalone
;;; : since mp-print-versions now goes through the dispatcher.
;;; 2018.08.27 Dan
;;; : * Keep track separately of the things which were loaded with
;;; : require-extra and require-compiled in case they need to be
;;; : removed from *modules* for some reason (reloading ACT-R in
;;; : a separate package for example). The variable *act-r-modules*
;;; : holds the things that were loaded with those.
;;; 2019.04.09 Dan
;;; : * Added support for the :single-threaded-act-r flag which
;;; : results in the dispatcher not starting any threads (thus no
;;; : external connections possible) and all the locks being
;;; : ignored.
;;; 2019.04.10 Dan
;;; : * Print a notice that it's single threaded after the version
;;; : information.
;;; 2019.05.29 Dan [3.0]
;;; : * Don't need QuickLisp if loading in single-threaded mode.
;;; : Instead just load the support/single-threaded.lisp file
;;; : that now defines the packages and stubs for all the things
;;; : that are referenced from the Quicklisp libraries.
;;; : * Record which mode was last used in support/mode.txt so that
;;; : it can automatically force a recompile when switching
;;; : between full and single-threaded.
;;; 2019.05.30 Dan
;;; : * Reverting from using jsown since it doesn't differentiate
;;; : 1.0 from 1, but that distinction is important.
;;; 2019.11.18 Dan
;;; : * Wasn't using translate-logical-pathname in the writing of
;;; : the load-mode.lisp file which meant sbcl would always
;;; : have to recompile.
;;; 2020.05.19 Dan [3.1]
;;; : * Because support and extra files aren't always being loaded,
;;; : they need their own record of which mode was last used to
;;; : compile them so they can be recompiled when necessary. [The
;;; : problematic case was when they are loaded under one mode,
;;; : the mode changes but that file isn't, and then that same
;;; : mode is used again and the file is required.] Now alists
;;; : are written into files extra-mode.lisp and required-mode.lisp
;;; : in the support directory to record which mode was last used
;;; : to compile files loaded with require-extra and require-compiled.
;;; : * To go along with that, compile-and-load now takes an optional
;;; : parameter that if true will force the file to be recompiled
;;; : regardless of the other tests.
;;; 2020.07.17 Dan [3.2]
;;; : * Added another switch :dont-compile-actr which means just use
;;; : whatever fasl file is there and don't read/write the extra
;;; : marker files. This overrides the :recompile-actr switch.
;;; 2020.08.04 Dan
;;; : * To fix an issue with SBCL tacking a .NEWEST onto the end of
;;; : pathnames with compile-and-load which results in an error
;;; : if a string is provided, use translate-logical-pathname on
;;; : it before doing anything else.
;;; 2020.08.11 Dan
;;; : * Made the pathname for require-compiled optional and use the
;;; : ACT-R-support directory with the code-module for the file
;;; : name if not provided.
;;; 2020.08.25 Dan
;;; : * Switching out the special defconstant macro for SBCL and
;;; : using thier define-constant instead for all systems.
;;; : * Added a string-downcase to require-compiled when the path
;;; : is not provived since the module strings are upper case but
;;; : the file names are lower case.
;;; 2021.10.01 Dan
;;; : * Added the remote written-for-act-r-version here.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Using logical pathnames a directory structure for ACT-R 7 can be created
;;; that allows users to add or remove files from a specific directory within
;;; the system, and through the use of require and provide also remove the
;;; need to edit a "load order" file.
;;;
;;; See the reference manual for details about the directories provided.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; The logical hostname "ACT-R" can be used as a relative reference for the
;;; directory where the ACT-R 7 folders are located.
;;;
;;;
;;; require-compiled (code-module &optional pathname)
;;;
;;; code-module is a string that designates some code that needs to be loaded
;;; which should have a corresponding (provide code-module)
;;; pathname is the pathname to where code-module can be found.
;;;
;;; Similar to the function require this will determine if the requested
;;; code-module has been loaded and if not will compile and load the file
;;; specified by pathname. If the pathname is not provided the it will
;;; try to load the file from the ACT-R-support directory with a name that
;;; matches the code-module given. Like the normal require function, it
;;; does depend on a provide call existing in the code-module file so that
;;; it only loads the necessary file the first time it is required.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; The idea is for a system where people can just drop in new modules without
;;; having to edit or change any of the existing code. In practice, that
;;; may not work all the time (with things like name conflicts) but should
;;; be useable. Name conflicts could probably be eliminated through some
;;; sort of module packaging scheme, but that seems to complicate module
;;; creation and could lead to some potentially nasty debugging issues.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+:packaged-actr (make-package :act-r
:use '("COMMON-LISP-USER"
"COMMON-LISP"
#+:ccl "CCL"
#+:allegro "EXCL"
#+:allegro-ide "COMMON-GRAPHICS-USER"
#+:common-graphics "COMMON-GRAPHICS-USER"))
;;; Basically a hack for ACL 7 so that I don't have to touch every file!
(eval-when (:compile-toplevel :load-toplevel :execute)
#+(and :allegro :ide (not :allegro-ide))
(push :allegro-ide *features*))
#+: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)
#+:act-r (error "Only one version of ACT-R should be loaded at a time.")
#-:act-r (if (find :act-r *features*)
(error "Only one version of ACT-R should be loaded at a time.")
(progn
(pushnew :act-r *features*)))
;; Clisp has an implementation-specific function execute that conflicts with
;; the generic function execute in ACT-R, so shadow it
#+:clisp (eval `(defpackage ,(package-name *package*) (:nicknames "CL-USER" "USER") (:shadow "EXECUTE")))
;; SBCL has a function called reset we need to shadow.
#+(and :sbcl (not :win32))
(eval `(defpackage ,(package-name *package*) (:shadow "RESET" )))
#+(and :sbcl :win32)
(eval `(defpackage ,(package-name *package*) (:shadow "RESET" "DIRECTORY")))
;;; The Windows version of SBCL doesn't properly handle wild cards in the
;;; directory command so this hacks around that for now sufficiently to load
;;; the ACT-R files...
#+(and :sbcl :win32)
(eval-when (:load-toplevel :execute)
(defun directory (pathname &key)
;(format t "Calling the new directory for ~S~%" pathname)
(if (not (string= (pathname-type pathname) "*"))
(let* ((new-path (make-pathname :host (pathname-host pathname)
:device (pathname-device pathname)
:directory (pathname-directory pathname)
:defaults "*.*"))
(new-val (cl::directory new-path))
(res (remove-if-not (lambda (x)
(string-equal (pathname-type x) (pathname-type pathname)))
new-val)))
;(format t "Returning ~S from directory of new-path: ~s which returns ~s.~%" res new-path new-val)
res)
(cl::directory pathname))))
;;; To avoid the strict interpretation of defconstant that SBCL takes, use their
;;; recommended define-constant macro instead in all cases instead of special
;;; casing for SBCL
(defmacro define-constant (name value &optional doc)
`(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value)
,@(when doc (list doc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Create the logical host "ACT-R" relative to the current location
(setf (logical-pathname-translations "ACT-R")
`(("**;*.*" ,(namestring (merge-pathnames "**/*.*" *load-truename*)))))
(setf (logical-pathname-translations "ACT-R-support")
`(("**;*.*" ,(namestring (merge-pathnames "**/*.*" (translate-logical-pathname "ACT-R:support;"))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; define the file extension (the pathname type) for compiled and source files
;;; in the currently supported systems
(unless (boundp '*.lisp-pathname*)
(defvar *.lisp-pathname*
(make-pathname :type "lisp")))
(unless (boundp '*.fasl-pathname*)
(defvar *.fasl-pathname*
(let ((type (pathname-type (compile-file-pathname "dummy.lisp"))))
(if (and type (not (string-equal type "lisp")))
(make-pathname :type type)
;; If it can't figure it out automatically resort to predefined value
#+:allegro (make-pathname :type "fasl")
#+:sbcl (make-pathname :type "fasl")
#+:clisp (make-pathname :type "fas")
#+(and :linux :cmu) (make-pathname :type "x86f")
#+(and :ppc :cmu) (make-pathname :type "ppcf")
#+(and :lispworks :win32 (not :lispworks5)) (make-pathname :type "fsl")
#+(and :lispworks :win32 :lispworks5) (make-pathname :type "ofasl")
#+(and :lispworks :unix (not :macosx) (not :lispworks5)) (make-pathname :type "ufsl")
#+(and :lispworks :unix (not :macosx) :lispworks5) (make-pathname :type "ufasl")
#+(and :lispworks :macosx (not :x86)) (make-pathname :type "nfasl")
#+(and :lispworks :macosx :x86) (make-pathname :type "xfasl")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; When :actr-fast is on the features list then set the switches for fastest
;;; compiled code.
#+:actr-fast (eval-when (:compile-toplevel :load-toplevel :execute)
(proclaim '(optimize (speed 3) (safety 1) (space 0) (debug 0))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Flag that forces recompiling to not happen.
#+:dont-compile-actr (defvar *skip-recompiling* t)
#-:dont-compile-actr (defvar *skip-recompiling* nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Define some functions for compiling and loading files
;;; compile-and-load (pathname &optional force)
;;;
;;; pathname a file pathname (or pathname string) if the file already
;;; has a type specified, then it is ignored and the defaults
;;; of lisp for source and system-dependent binary types are
;;; used.
;;; force a generalized boolean which indicates whether the file should
;;; be compiled regardless of the state of a previously compiled
;;; version.
;;;
;;; If a source file (.lisp) exists for the specified pathname then if there
;;; is no binary file (determined by *.fasl-pathname*), the binary is
;;; older than the source file, the feature :act-r-recompile is set, or force
;;; is true then compile the source file into a binary and load it.
;;;
;;; Based on the smart-load function from the ACT-R loader.
(defun compile-and-load (pathname &optional force)
(when (stringp pathname)
(setf pathname (translate-logical-pathname pathname)))
(when (pathname-type pathname) ;; throw away the type to allow for
;; the merging with a binary type
(if (string-equal (pathname-type pathname) "lisp")
(setf pathname (make-pathname :host (pathname-host pathname)
:directory (pathname-directory pathname)
:device (pathname-device pathname)
:name (pathname-name pathname)))
(error "To compile a file it must have a .lisp extension")))
(let* ((srcpath (merge-pathnames pathname *.lisp-pathname*))
(binpath (merge-pathnames pathname *.fasl-pathname*)))
(unless (probe-file srcpath)
(error "File ~S does not exist" srcpath))
(if *skip-recompiling*
(unless (probe-file binpath)
(error "File ~s does not exist but the :dont-compile-actr flag is set." binpath))
(when (or force
(member :actr-recompile *features*)
(not (probe-file binpath))
(> (file-write-date srcpath) (file-write-date binpath)))
(compile-file srcpath :output-file binpath)))
(load binpath)))
;;; Going to use this in a few places to make sure output to *error-output*
;;; happens since it could be buffered.
(defmacro finish-format (stream string &rest args)
`(prog1
(format ,stream ,string ,@args)
(finish-output ,stream)))
;;; SMART-LOAD [Function]
;;; Date : 99.12.21
;;; Description : Loads binary version of a specified file. Of course, the
;;; : said binary version might not exist or be older than the
;;; : source version, in which case the source file is compiled
;;; : before loading.
;;; : Updated to add an option parameter to determine whether
;;; : to just warn of a missing file or to throw an error.
(defun smart-load (this-files-dir file &optional (error? nil))
"Loads binary <file> in directory <this-files-dir> or compiles and loads
source version"
(let* ((true-dir (translate-logical-pathname this-files-dir))
(srcpath (merge-pathnames
(merge-pathnames file *.lisp-pathname*)
true-dir)))
(if (not (probe-file srcpath))
(if error?
(error "File ~S does not exist" srcpath)
(finish-format *error-output* "File ~S does not exist" srcpath)))
(compile-and-load srcpath)))
(defun actr-load (file)
"Loads the file specified after translating the pathname"
(let ((path (translate-logical-pathname file)))
(if (not (probe-file path))
(finish-format *error-output* "#|Warning: File ~S does not exist.|#~%" path)
(load path))))
(defvar *act-r-modules* nil)
;;; require-compiled (code-module &optional pathname)
;;;
;;; code-module is a string that designates some code that needs to be loaded
;;; which should have a corresponding (provide code-module) in it
;;; pathname is the pathname to where that code-module can be found (including
;;; the file's name).
;;;
;;; Similar to the function require this will determine if the requested
;;; code-module has been loaded and if not will compile and load the file
;;; specified by pathname. If the pathname is not provided the it will
;;; try to load the file from the ACT-R-support directory with a name that
;;; matches the code-module given. Like the normal require function, it
;;; does depend on a provide call existing in the code-module file so that
;;; it only loads the necessary file the first time it is required.
(defmacro require-compiled (code-module &optional pathname)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member ,code-module *modules* :test #'string=)
(push ,code-module *act-r-modules*)
(let ((pn (if (null ,pathname) (concatenate 'string "ACT-R-SUPPORT:" (string-downcase ,code-module) ".lisp") ,pathname)))
(if *skip-recompiling*
(compile-and-load (translate-logical-pathname pn))
(let* ((previous (ignore-errors
(with-open-file (f (translate-logical-pathname "ACT-R-support:require-mode.lisp") :direction :input)
(read f))))
(previous-mode (cdr (assoc ,code-module previous :test 'string=)))
(need-to-compile (not (eq previous-mode *current-load-mode*)))
(result (compile-and-load (translate-logical-pathname pn) need-to-compile)))
(when result
(if previous-mode
(setf (cdr (assoc ,code-module previous :test 'string=)) *current-load-mode*)
(push (cons ,code-module *current-load-mode*) previous))
(ignore-errors (with-open-file (f (translate-logical-pathname "ACT-R-support:require-mode.lisp") :direction :output :if-does-not-exist :create :if-exists :supersede)
(write previous :stream f))))
result))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; load any special system support files here
;; Warn about the case sensitive mode in ACL because things like t vs T shouldn't
;; matter (and both probably occur in the code), and won't work in the case sensitive
;; versions of ACL.
#+:allegro (when (or (eq :case-sensitive-lower *current-case-mode*)
(eq :case-sensitive-upper *current-case-mode*))
(unless
(yes-or-no-p
"WARNING: you are using a case sensitive Lisp. ACT-R may not load or run correctly. Continue anyway?")
(break)))
;; Load the quicklisp libraries for threads, sockets, and JSON parsing.
;; For now, assume quicklisp is available, but eventually want to include local
;; versions with the sources so it can be loaded without them too.
#+(and (not :QUICKLISP) (not :single-threaded-act-r)) (eval-when (:compile-toplevel :load-toplevel :execute)
(when (probe-file "~/quicklisp/setup.lisp")
(load "~/quicklisp/setup.lisp"))
(unless (find :quicklisp *features*)
(error "This version of ACT-R requires Quicklisp to load the components necessary for the remote connection.")))
;;; Load the libraries
#-:single-threaded-act-r (eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload :bordeaux-threads)
(ql:quickload :usocket)
(ql:quickload :cl-json))
;;; Check which mode the last load used to determine if it should
;;; force a recompile.
(defvar *current-load-mode* nil)
(let ((current (if (find :single-threaded-act-r *features*)
:single
:normal))
(previous (unless *skip-recompiling*
(ignore-errors (with-open-file (f (translate-logical-pathname "ACT-R-support:load-mode.lisp") :direction :input)
(read f))))))
(unless (or *skip-recompiling* (eq current previous))
(pushnew :actr-recompile *features*))
(setf *current-load-mode* current))
#+:single-threaded-act-r (smart-load (translate-logical-pathname "ACT-R:support;") "single-threaded.lisp")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Load the framework's loader file (it is order dependent)
(defvar *file-list*)
(smart-load (translate-logical-pathname "ACT-R:framework;") "framework-loader.lisp")
(dolist (the-file *file-list*)
(smart-load (translate-logical-pathname "ACT-R:framework;") the-file t))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Define system parameters for version information before anything could
;;; change the global variables.
(let ((set-version-info 4))
(defun version-info-ignored (val)
(declare (ignore val))
(if (zerop set-version-info)
nil
(decf set-version-info))))
(defun fixed-version-parameter-value (val)
(lambda (a b)
(declare (ignore a b))
val))
(create-system-parameter :act-r-version :valid-test 'version-info-ignored
:default-value *actr-version-string* :warning "unmodified"
:documentation "The full software version"
:handler (fixed-version-parameter-value *actr-version-string*))
(create-system-parameter :act-r-architecture-version :valid-test 'version-info-ignored
:default-value (read-from-string *actr-architecture-version*) :warning "unmodified"
:documentation "The ACT-R architecture version"
:handler (fixed-version-parameter-value (read-from-string *actr-architecture-version*)))
(create-system-parameter :act-r-major-version :valid-test 'version-info-ignored
:default-value (read-from-string *actr-major-version-string*) :warning "unmodified"
:documentation "The major software version"
:handler (fixed-version-parameter-value (read-from-string *actr-major-version-string*)))
(create-system-parameter :act-r-minor-version :valid-test 'version-info-ignored
:default-value (if *actr-minor-version-string* (read-from-string *actr-minor-version-string*) 0) :warning "unmodified"
:documentation "The minor software version"
:handler (fixed-version-parameter-value (if *actr-minor-version-string* (read-from-string *actr-minor-version-string*) 0)))
(defun valid-version-test-string (val)
(if (eq val t)
t
(when (stringp val)
(awhen (position #\- val)
(setf val (subseq val 0 it)))
(and
(every (lambda (x) (find x '(#\. #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))) val)
(<= (count #\. val) 2)
(> (length val) 0)))))
(let ((last-result t))
(defun check-act-r-version-string (set-or-get val)
(if set-or-get
(setf last-result (if (stringp val)
(let* ((ver (subseq val 0 (position #\- val)))
(version-numbers (read-from-string (format nil "(~a)" (substitute #\space #\. ver)))))
(case (length version-numbers)
(1 (= (first version-numbers) (car (ssp :act-r-architecture-version))))
(2 (and (= (first version-numbers) (car (ssp :act-r-architecture-version)))
(= (second version-numbers) (car (ssp :act-r-major-version)))))
(3 (and (= (first version-numbers) (car (ssp :act-r-architecture-version)))
(= (second version-numbers) (car (ssp :act-r-major-version)))
(<= (third version-numbers) (car (ssp :act-r-minor-version)))))
(t nil))) ;; just to be safe, but the valid test should avoid this...
val))
last-result)))
(create-system-parameter :check-act-r-version :valid-test 'valid-version-test-string
:default-value t :warning "a valid version string of the form A{.B{.C}} where A, B, and C are integers followed by optional data after a dash"
:documentation "Test a version string against the current version for t or nil result"
:handler 'check-act-r-version-string)
(defun written-for-act-r-version (version &optional description)
(if (stringp version)
(let ((strip-tag (subseq version 0 (position #\- version))))
(if (valid-version-test-string strip-tag)
(let ((given-version-numbers (read-from-string (format nil "(~a)" (substitute #\space #\. strip-tag))))
(current-version-numbers (mapcar (lambda (x) (car (ssp-fct (list x))))
(list :act-r-architecture-version
:act-r-major-version
:act-r-minor-version))))
(cond ((not (= (first given-version-numbers) (first current-version-numbers)))
(print-warning "Current ACT-R architecture ~d is not the same as ~d specified in ~a~@[ for ~a~]."
(first current-version-numbers) (first given-version-numbers) version description))
((and (second given-version-numbers)
(not (= (second given-version-numbers) (second current-version-numbers))))
(if (> (second given-version-numbers) (second current-version-numbers))
(print-warning "Current ACT-R major version ~d is older than major version ~d specified in ~a~@[ for ~a~].~% Some features may not be implemented."
(second current-version-numbers) (second given-version-numbers) version description)
(print-warning "Current ACT-R major version ~d is newer than major version ~d specified in ~a~@[ for ~a~].~% It may not be backward compatible."
(second current-version-numbers) (second given-version-numbers) version description)))
((and (third given-version-numbers)
(> (third given-version-numbers) (third current-version-numbers)))
(print-warning "Current ACT-R minor version ~d is older than minor version ~d specified in ~a~@[ for ~a~].~% Some features may not be implemented."
(third current-version-numbers) (third given-version-numbers) version description))
(t t)))
(progn
(print-warning "Invalid version specified in written-for-act-r-version: ~s. Version must be an ACT-R version string." version)
:invalid-value)))
(progn
(print-warning "Invalid version specified in written-for-act-r-version: ~s. Version must be an ACT-R version string." version)
:invalid-value)))
(add-act-r-command "written-for-act-r-version" 'written-for-act-r-version "Check a given version number against the current version for compatibility. Params: version-string {checking-info}")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Define a macro to make loading extras easier
(defvar *requiring-extra* nil)
(defun requiring-extra ()
*requiring-extra*)
(defmacro require-extra (name)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (member ,name *modules* :test #'string=)
(cond
((mp-models)
(print-warning "Cannot require an extra when there is a current model."))
((not (probe-file (translate-logical-pathname (format nil "ACT-R:extras;~a;" ,name))))
(print-warning "Directory ~a for specified extra ~a not found."
(translate-logical-pathname (format nil "ACT-R:extras;~a;" ,name))
,name))
((not (probe-file (translate-logical-pathname (format nil "ACT-R:extras;~a;~a.lisp" ,name ,name))))
(print-warning "Load file for extra ~a at location ~a not found." ,name
(translate-logical-pathname (format nil "ACT-R:extras;~a;~a.lisp" ,name ,name))))
(t
(unwind-protect
(progn
(setf *requiring-extra* t)
(if *skip-recompiling*
(compile-and-load (translate-logical-pathname (format nil "ACT-R:extras;~a;~a.lisp" ,name ,name)))
(let* ((previous (ignore-errors
(with-open-file (f (translate-logical-pathname "ACT-R-support:extra-mode.lisp") :direction :input)
(read f))))
(previous-mode (cdr (assoc ,name previous :test 'string=)))
(need-to-compile (not (eq previous-mode *current-load-mode*)))
(result (compile-and-load (translate-logical-pathname (format nil "ACT-R:extras;~a;~a.lisp" ,name ,name)) need-to-compile)))
(when result
(if previous-mode
(setf (cdr (assoc ,name previous :test 'string=)) *current-load-mode*)
(push (cons ,name *current-load-mode*) previous))
(ignore-errors (with-open-file (f (translate-logical-pathname "ACT-R-support:extra-mode.lisp") :direction :output :if-does-not-exist :create :if-exists :supersede)
(write previous :stream f))))
result)))
(progn
(pushnew ,name *act-r-modules*)
(setf *requiring-extra* nil)))
(if (member ,name *modules* :test #'string=)
t
(print-warning "Extra ~a was loaded, but did not have a provide to prevent it from being loaded again." ,name)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Load the core modules
(smart-load (translate-logical-pathname "ACT-R:core-modules;") "core-loader.lisp")
(dolist (the-file *file-list*)
(smart-load (translate-logical-pathname "ACT-R:core-modules;") the-file))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; First, load any additional extensions.
(dolist (file (directory (translate-logical-pathname "ACT-R:commands;*.lisp")))
(compile-and-load file))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; When a new device is added it should be included with a switch below so that it can be loaded
(defvar *device-interface-pathname* nil)
;;; Here are the devices that are defined
#+(and :allegro-ide :mswindows) (setf *device-interface-pathname* "ACT-R:devices;acl;")
#+(and :allegro-ide (not :mswindows)) (print-warning "Native ACL device not available for Mac or Linux versions because~%they lack the commands for controlling the mouse and keyboard as described here~%http://www.franz.com/support/documentation/6.2/doc/cggtk-relnotes.html#2.3~%")
#+:lispworks (setf *device-interface-pathname* "ACT-R:devices;lw;")
#+(and :clozure :darwin :apple-objc :ccl-1.8) (setf *device-interface-pathname* "ACT-R:devices;ccl-cocoa;")
;;; Load the virtual device
(compile-and-load (translate-logical-pathname "ACT-R:devices;virtual;device.lisp"))
(compile-and-load (translate-logical-pathname "ACT-R:devices;virtual;uwi.lisp"))
;;; Load any Lisp specific device that's defined
(when *device-interface-pathname*
(if (probe-file (merge-pathnames *device-interface-pathname* "device.lisp"))
(compile-and-load (merge-pathnames *device-interface-pathname*
"device.lisp"))
(format t
"################~%#### No Device file found in ~S ####~%##############"
*device-interface-pathname*))
(if (probe-file (merge-pathnames *device-interface-pathname* "uwi.lisp"))
(compile-and-load (merge-pathnames *device-interface-pathname*
"uwi.lisp"))
(format t
"#################~%#### No uwi file found in ~S ####~%################"
*device-interface-pathname*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; After the modules and devices files are done load any files in the
;;; modules, tools and then finally the other-files drectories.
(dolist (file (directory (translate-logical-pathname "ACT-R:modules;*.lisp")))
(compile-and-load file))
(dolist (file (directory (translate-logical-pathname "ACT-R:tools;*.lisp")))
(compile-and-load file))
(dolist (file (directory (translate-logical-pathname "ACT-R:other-files;*.lisp")))
(compile-and-load file))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Print a confirmation message to let the user know ACT-R has been loaded
;;; along with the version numbers of all the modules.
(format t "~%##################################~%")
#-:standalone (mp-print-versions)
#+:single-threaded-act-r (mp-print-versions)
(format t "~%######### Loading of ACT-R ~d is complete #########~%" *actr-architecture-version*)
#+:single-threaded-act-r (format t "~%######### This is a single threaded build #########~%")
(unless *skip-recompiling*
(ignore-errors (with-open-file (f (translate-logical-pathname "ACT-R-support:load-mode.lisp") :direction :output :if-does-not-exist :create :if-exists :overwrite)
(write *current-load-mode* :stream f))))
(let ((d (directory (translate-logical-pathname "ACT-R:user-loads;*.lisp"))))
(when d
(format t "~%######### Loading user files #########~%")
(dolist (file (sort d 'string< :key (lambda (x) (string (pathname-name x)))))
(compile-and-load file))
(format t "~%######### User files loaded #########~%")))
#|
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,101 | Common Lisp | .lisp | 845 | 52.846154 | 280 | 0.580354 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | fc3a381c360ea60257a3b293ff4c6ef27d7599e0442255a69b6256c25b699e4f | 14,136 | [
-1
] |
14,137 | recompile-act-r.lisp | asmaloney_ACT-R/recompile-act-r.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 : recompile-act-r.lisp
;;; Version : 1.0
;;;
;;; Description : Load main ACT-R loader forcing it to recompile everything.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2020.01.30 Dan [1.0]
;;; : * Pretty simple setup -- push the actr-recompile feature and
;;; : then load the main load file.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(push :actr-recompile *features*)
(load (merge-pathnames "load-act-r.lisp" *load-truename*))
#|
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,790 | Common Lisp | .lisp | 43 | 40.255814 | 80 | 0.583238 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 41c295cf1e653e3891fdd8a789895db752a2d82b0aa464319244f5181d912c29 | 14,137 | [
-1
] |
14,138 | load-single-threaded-act-r.lisp | asmaloney_ACT-R/load-single-threaded-act-r.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2019 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 : load-single-threaded-act-r.lisp
;;; Version : 2.0
;;;
;;; Description : Top level loader for the whole ACT-R system.
;;;
;;; Bugs :
;;;
;;; To do : [-] Test in a variety of Lisps for issues with the
;;; : logical hostname stuff.
;;; : [ ] Now, look into using the clisp version in other
;;; : lisps because it seems cleaner/more generic than
;;; : the ones I put toghether...
;;; : [x] Use compile-file-pathname instead of always adding a new
;;; : entry for *.fasl-pathname*.
;;;
;;; ----- History -----
;;;
;;; 2019.04.19 Dan
;;; : * Custom loader that sets the flag to disable locking and
;;; : suppress any threaded operation.
;;; 2019.05.29 Dan [2.0]
;;; : * Just set the switch and then load the main load file so
;;; : that I don't need to maintain two versions of basically the
;;; : same code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
(pushnew :single-threaded-act-r *features*)
(setf (logical-pathname-translations "SINGLE-STUB")
`(("**;*.*" ,(namestring (merge-pathnames "**/*.*" *load-truename*)))))
(load (translate-logical-pathname "SINGLE-STUB:load-act-r.lisp"))
#|
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,562 | Common Lisp | .lisp | 57 | 43.614035 | 80 | 0.578062 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | cefd995c5abd517c0b24d780f5c2544298c64eeb729538dcf5505eece9fe4753 | 14,138 | [
-1
] |
14,139 | server.lisp | asmaloney_ACT-R/environment/server.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-2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : server.lisp
;;; Version : 3.0
;;;
;;; Description : Contains no system dependent code because it relies on the
;;; : definitions in uni-files.
;;; : Holds the Environment global variables and the
;;; : code to open and manage an environment socket connection.
;;; Bugs :
;;;
;;; Todo : [ ] Currently stopping the environment doesn't cause the
;;; : Tk side to cleanly destroy all windows and remove the
;;; : handlers. That could be an issue for something that
;;; : needs to do some cleanup (like the history tools table).
;;; : For now, special casing that table in the closing,
;;; : but should look into having the close message be more
;;; : thorough (some quick fix attempts ran into ugly issues
;;; : with timing/waiting issues).
;;;
;;; ----- History -----
;;;
;;; 05/10/2002 Dan
;;; : Added this header
;;; 05/20/2002 Dan
;;; : Think I've finally got it working on Macs w/ OS < 10 and MCL
;;; : and for now w/OSX it's got to be OpenMcl which also seems
;;; : to work (though it's not in here yet...)
;;; 05/21/2002 Dan
;;; : Serious reorganization took place with the files...
;;; 05/22/2002 Dan
;;; : Fixed some more MCL problems. At this point it's working
;;; : mostly, so I'm not wasting any more time 'fixing' it there
;;; : since MacOS < 10 is "dead"...
;;; : Changed close-connection so that killing the process was
;;; : optional and altered the message-process and process-
;;; : connection functions so that they don't kill their own
;;; : process (doesn't seem to change things, but seemed like a
;;; : good idea and I thought it'd fix a closeing bug I had
;;; : in MCL, but it didn't).
;;; 05/23/2002 Dan
;;; : Made a very subtle change, that may have a big impact
;;; : later on. When a handler is created it preforms an initial
;;; : update - that's as it was, but now that first time the
;;; : handler itself is passed as the parameter to the updater.
;;; : Thus if an updater needs to use its parameter it had better
;;; : check its type because that first time it'll be something
;;; : other than it normally expects.
;;; 08/23/2002 Dan
;;; : Updated the version number to 6.0b3, which doesn't
;;; : correspond to the versions in the headers, so I
;;; : need to fix that at some point for consistency...
;;; 09/17/2002 Dan
;;; : Updated the environment and ACT-R version numbers...
;;; 10/01/2002 Dan
;;; : Updated version to 1.1 and fixed the packaging
;;; : for building a standalone in ACL.
;;; : Added the conditionalized in-package to message-process
;;; : to make building a standalone easier.
;;; : Changed the environment version to correspond to the
;;; : file version numbers and add a -S if it's the standalone.
;;; 01/20/2003 Dan
;;; : Updated version number again for the env because
;;; : of a quick change for the class.
;;; 07/07/2003 Dan
;;; : Updated version because I rolled in most of Mike's newest
;;; : RPM (my UWI and ACL device files were newer).
;;; 08/15/2003 Dan
;;; : Updated version to 1.3 because I've added the support for
;;; : CMUCL from Ethan Glasser-Camp at RPI.
;;; 12/19/2003 Dan
;;; : Updated version to 1.4 for this file because I've fixed
;;; : a bug in the uni-files and moved the ACT-R version
;;; : variable to the actr5.lisp file itself.
;;; 4/22/2004 Dan [1.5]
;;; : Added the license info, updated the version to 1.5
;;; : and removed the ACT-R version variable since that's
;;; : in the main ACT-R file now.
;;; -----------------------------------------------------------------------
;;; 2005.04.11 Dan [2.0]
;;; : Start of the move to ACT-R 6.0.
;;; 2007.08.03 Dan
;;; : * Moved the *environment-sockets* defvar to env-module
;;; : to avoid a compiler warning.
;;; 2007.08.13 Dan
;;; : * Adding reset as a possible update condtion for handlers.
;;; 2007.08.17 Dan
;;; : * Added a without-interrupts call to close-connection to
;;; : fix a problem in stopping things under LispWorks.
;;; 2008.01.15 Dan
;;; : * Changed close-connection because SBCL doesn't have
;;; : without-interrupts in the default package...
;;; 2008.04.08 Dan
;;; : * Refixed that last update using uni-without-interrupts.
;;; : Also added the require-compiled of uni-files just to be
;;; : safe.
;;; 2008.05.16 Dan
;;; : * Added the conflict-nil option for when to update the
;;; : handler. That's the same as conflict except that it
;;; : doesn't pass the return value back to the conflict-set-
;;; : hook.
;;; 2009.01.08 Dan
;;; : * Fixed an issue with message-process which could cause
;;; : problems with some Lisps (CCLx86 in particular).
;;; 2009.04.13 Dan
;;; : * Uni-send-string doesn't have an automatic newline now,
;;; : so need to put one in the string to be sent.
;;; 2009.04.14 Dan
;;; : * Seems that adding the newline here breaks the stopping
;;; : of the connection. However, since it doesn't seem to be
;;; : necessary I'm just dropping it again.
;;; 2009.06.08 Dan
;;; : * Adding the run-environment command which spawns the
;;; : environment app and then makes the connection.
;;; : Only available for LispWorks under MacOSX or Windows and
;;; : ACL under MacOSX or Windows at this time.
;;; 2009.06.09 Dan
;;; : * Upped the default delay on run-environment to 12 seconds
;;; : to be safer.
;;; 2009.07.17 Dan
;;; : * Added a test to the remove handler code so that it
;;; : shouldn't throw an error on initial connection anymore
;;; : like it would occasionally for some Lisps.
;;; 2011.01.07 Dan
;;; : * Lock all the background processes from the environment
;;; : for now until I come up with a better way to protect the
;;; : ACT-R code.
;;; 2011.01.14 Dan
;;; : * Fixed the name of the application to run for the Mac
;;; : environment in the ACL run-environment command.
;;; 2011.01.14 Dan
;;; : * Added a return reply for the keep alive message to
;;; : possibly avoid some time out issues in Windows 7.
;;; 2011.02.21 Dan
;;; : * Added the ability to specify the new run-start and run-end hooks.
;;; -------------------------------------------------------------------------
;;; 2011.05.20 Dan [3.0]
;;; : * Start of a complete overhaul to eliminate most of the
;;; : global variable usage and better encapsulate things so
;;; : that multiple model support can be added.
;;; 2011.05.25 Dan
;;; : * Updated create message parsing to set the use-model
;;; : slot. The semantics now are that if there are only 6
;;; : items in the create no model is used, if there are 7 then
;;; : the 7th is either a model name to use when evaluating the
;;; : update or nil which means use the current-model explicitly
;;; : (which is not the same as not using a model).
;;; : * Added the which-hook slot to the control structure and
;;; : set that in the hook updating functions.
;;; 2011.05.26 Dan
;;; : * Fixed a cut-and-paste error in delete-post-hook-if-necessary.
;;; 2011.06.01 Dan
;;; : * Changed the remove message handling to only evaluate it in
;;; : a model if that's a valid model now.
;;; 2011.09.02 Dan
;;; : * Added a background option to connect-to-environment so
;;; : that it's possible to have the environment message handling
;;; : thread be the main one (for use with standalone versions that
;;; : have a slave Lisp running headless).
;;; 2011.09.07 Dan
;;; : * Fixed some format strings that were missing '~'s.
;;; 2011.09.13 Dan
;;; : * Readjust how the default run-environment gets defined to
;;; : avoid a warning for multiple definitions.
;;; 2011.11.07 Dan
;;; : * Added a check for LW 6 to the windows version of run-
;;; : environment so it'll work there too.
;;; 2011.12.19 Dan
;;; : * Added some checks to start-environment so it better warns
;;; : when the Lisp isn't able to use the Environment.
;;; 2012.02.01 Dan
;;; : * Added some more declaims to avoid undefined function warnings
;;; : at load time.
;;; 2012.02.07 Dan
;;; : * Fixed the declaim for update-handler.
;;; 2012.03.21 Dan
;;; : * Fixed a bug with stopping the environment while the stepper
;;; : was open that prevented one from using the stepper if a
;;; : new environment connection was made.
;;; 2012.09.07 Dan
;;; : * Removed the in-package from message-process based on the
;;; : :actr-env-alone feature.
;;; 2012.09.21 Dan
;;; : * Trying to eliminate an intermittent environment error
;;; : with multiple models in CCL (perhaps elsewhere too just
;;; : unreported). So adding additional lock-outs so that
;;; : updates can't occur while the model is running by locking
;;; : during the pre-event-hook and unlocking during the post as
;;; : well as during anything else which calls update handlers.
;;; : * The problem with that is if someone breaks the system
;;; : between pre and post it leaves the lock set and basically
;;; : kills the environment -- need a better alternative.
;;; 2013.02.22 Dan
;;; : * Added the wait-for-environment command to provide a way
;;; : to check that it has processed all outstanding actions.
;;; : Primary intended use is with creating complex visible
;;; : virtual displays, especially those that update faster than
;;; : real time, because if the "drawing" falls behind things
;;; : can be difficult to use or display errors could result.
;;; 2013.02.25 Dan
;;; : * Adding run-environment commands for CCL in Win, Mac, and
;;; : linux.
;;; : * Changed how the delay parameter works for run-environment.
;;; : It still waits that long before the first try to connect,
;;; : but it will now continue to try to connect after every
;;; : delay seconds pass.
;;; 2013.02.26 Dan
;;; : * Fixed a bug with the CCL Mac run-environment.
;;; 2013.12.18 Dan
;;; : * Changed close-connection so that there's a parameter which
;;; : indcates whether or not to send the close message.
;;; : * Changed the reception of a goodbye message so that it
;;; : completely closes down the connection by killing the
;;; : process as well.
;;; 2014.09.10 Dan
;;; : * Changed the flag on run-environment for LispWorks to
;;; : :lispworks6 instead of 6.0 so that 6.1 also works (and
;;; : presumably any other 6.x they create).
;;; 2014.09.30 Dan
;;; : * Changed safe-evaluation from a defmethod to defun since
;;; : it wasn't specifying types in the params list anyway.
;;; 2015.02.20 Dan
;;; : * Connect-to-environment now passes the optional parameter
;;; : for capturing the current stream as t to uni-run-process
;;; : to avoid issues with the "AltConsole" in CCL.
;;; 2015.07.28 Dan
;;; : * Changed the ACT-R6 logicals to ACT-R in the environment
;;; : directory pathing.
;;; : * Changed ACT-R6;support to ACT-R-support in require compiled.
;;; 2015.08.03 Dan
;;; : * Fix a bug with run-environment in CCL because with versions
;;; : 1.9 or newer it doesn't properly create the command line to
;;; : evaluate when there are spaces in the path.
;;; 2015.08.10 Dan
;;; : * Adjust the feature test for run-environment for Lispworks
;;; : because v7 is available and assuming it works the same as
;;; : the previous 2 so just removing the version check since
;;; : I doubt that anyone is using v4 at this point.
;;; 2016.01.14 Dan
;;; : * Added a run-environment for ACL+Linux.
;;; 2016.04.14 Dan
;;; : * Added a dummy-env-handler function which does nothing so
;;; : that I don't have to put the empty lambda in all the
;;; : environment tools...
;;; 2016.06.02 Dan
;;; : * Added the Todo about fixing the close problem.
;;; : * Removed the old Todo because it seems like it's a non-
;;; : issue now.
;;; : * The connection closing now clears the table of history
;;; : data in *history-recorder-data-cache* when all connections
;;; : are gone (fixing the close issue would eliminate the need
;;; : for this).
;;; 2016.06.09 Dan
;;; : * To avoid an undefined variable warning using a function
;;; : to clear the history data cache which can be declaimed
;;; : and defined in the history code.
;;; 2017.08.08 Dan
;;; : * Uni-without-interrupts isn't needed since uni-send-string
;;; : already has a lock around it...
;;; 2017.08.28 Dan
;;; : * Removed everything except the run-environment functions
;;; : since that's all that's needed.
;;; 2017.10.13 Dan
;;; : * Updated the linux version in anticipation of a real
;;; : application being there instead of assuming wish is
;;; : available.
;;; 2018.03.30 Dan
;;; : * Run-environment for Mac and Linux CCL restores the
;;; : current directory -- why didn't it before?
;;; 2019.11.01 Dan
;;; : * Change run-environment for the Macs to run the application
;;; : directly because it's not in an app bundle anymore.
;;; 2021.05.11 Dan
;;; : * Changed reference to GUI directory to gui to avoid issues
;;; : with logical pathnames (particularlly in SBCL).
;;; 2021.09.15 Dan
;;; : * The Linux environment application now has dashes instead
;;; : of spaces in its name.
;;; : * Also fixed the Linux and macOS versions of ACL to run
;;; : the correct program.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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)
;;; Adding a hack for a problem with how run-program creates the string that it
;;; sends to Windows to execute because it doesn't properly escape spaces as of
;;; CCL 1.9.
;;; The fix was found here: http://comments.gmane.org/gmane.lisp.openmcl.devel/9030
#+(and :ccl :windows :ccl-1.9)
(let ((*WARN-IF-REDEFINE-KERNEL* nil))
(defun ccl::make-windows-command-line (strings)
(setf strings (mapcar 'prin1-to-string strings))
(reduce (lambda (s1 s2) (concatenate 'string s1 " " s2))
(cdr strings) :initial-value (car strings))))
#+(and :ccl :windows)
(defun run-environment ()
(run-program (namestring (translate-logical-pathname "ACT-R:environment;start environment.exe")) nil :wait nil))
#+(and :ccl :linux)
(defun run-environment ()
(let ((c (ccl::cd ".")))
(ccl::cd "ACT-R:environment")
(run-program "./start-environment-Linux" nil :wait nil)
(ccl::cd c)))
#+(and :ccl :darwin)
(defun run-environment ()
(let ((c (ccl::cd ".")))
(ccl::cd "ACT-R:environment")
(run-program "./start-environment-osx" nil :wait nil)
(ccl::cd c)))
#+(and :lispworks (or :win32 :win64))
(defun run-environment ()
(sys:call-system "\"Start Environment.exe\"" :current-directory (translate-logical-pathname "ACT-R:environment") :wait nil))
#+(and :lispworks :macosx)
(defun run-environment ()
(sys:call-system (format nil "'~a/Start Environment OSX.app/Contents/MacOS/start-environment-osx'"
(namestring (translate-logical-pathname "ACT-R:environment")))
:wait nil))
#+(and :allegro :mswindows)
(defun run-environment ()
(let ((c (current-directory)))
(chdir "ACT-R:environment")
(run-shell-command "\"Start Environment.exe\"" :wait nil)
(chdir c)))
#+(and :allegro :macosx)
(defun run-environment ()
(let ((c (current-directory)))
(chdir "ACT-R:environment")
(run-shell-command "./start-environment-osx" :wait nil)
(chdir c)))
#+(and :allegro :linux)
(defun run-environment ()
(let ((c (current-directory)))
(chdir "ACT-R:environment")
(run-shell-command "./start-environment-Linux" :wait nil)
(chdir c)))
(unless (fboundp 'run-environment)
(defun run-environment ()
(print-warning "The run-environment command is not available for your current Lisp & OS combination.")))
#|
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
|#
| 19,196 | Common Lisp | .lisp | 363 | 51.352617 | 126 | 0.588338 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 20e1b98a948c989ac62608885c1a6181a0713e82483abbd88650d7f826a5001c | 14,139 | [
-1
] |
14,140 | environment-cmds.lisp | asmaloney_ACT-R/environment/environment-cmds.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 : environment-cmds.lisp
;;; Version : 3.0
;;;
;;; Description : No system dependent code.
;;; : Defines stuff that is needed to handle "environment"
;;; : things.
;;; Bugs :
;;;
;;; Todo : Clean up what goes here and what's passed literally
;;; : from the Tcl side - it's an odd mix at this point
;;; : and I should have some consistency.
;;;
;;; ----- History -----
;;;
;;; 05/22/2002 Dan
;;; : File creation
;;; 10/01/2002 Dan
;;; : Updated version to 1.1 and fixed the packaging
;;; : for building a standalone in ACL.
;;; 01/20/2003 Dan
;;; : Added the show-module-state-chunk function and
;;; : hacked buffer-contents so that the module-state
;;; : chunks shown by the environment match internal
;;; : module states even though the "real" chunks
;;; : don't seem to be updated anymore. WHY and WHEN?!
;;; 4/22/2004 Dan [1.5]
;;; : Added the license info.
;;; ----------------------------------------------------------------------
;;; 2005.04.13 Dan [2.0]
;;; : * Moved to ACT-R 6.
;;; 2007.08.03 Dan
;;; : * Moved the *stepper-open* defvar here to avoid a warning
;;; : at compile time.
;;; : * Deleted the commented out in-package calls.
;;; -------------------------------------------------------------------------
;;; 2011.05.20 Dan [3.0]
;;; : * Start of a complete overhaul to eliminate most of the
;;; : global variable usage and better encapsulate things so
;;; : that multiple model support can be added.
;;; 2011.05.25 Dan
;;; : * Modified reload-model and safe-load so that warnings aren't
;;; : double printed in most cases.
;;; : * Added a finishing of the output streams to those because
;;; : it seems to lag sometimes in ACL...
;;; : * The open button uses a function called smart-loader which
;;; : isn't defined anymore, so adding that.
;;; 2012.02.09 Dan
;;; : * Explicitly close streams made with make-string-output-stream
;;; : to be safe.
;;; 2012.12.18 Dan
;;; : * Changed reload-model and safe-load so that they can signal
;;; : an error without opening the interactive debugger because
;;; : that's an issue in the environment particularly with the
;;; : standalones since the error would have to be cleared before
;;; : the environment notice can be displayed, but with CCL that's
;;; : very difficult becuase the background process doesn't have
;;; : access to the terminal...
;;; 2013.02.19 Dan
;;; : * Haven't been able to reconstruct why the loaders "ignore"
;;; : unbound-variable errors, but since it can lead to very bad
;;; : situations for users I'm taking that out. There are two
;;; : guesses so far as to where it comes from. Christian thinks
;;; : it may go all the way back to the old environment's split
;;; : edit files because code may have been loaded out of order.
;;; : It might also have been a "fix" for a problem with the early
;;; : OpenMCL versions of the standalone environment based on an
;;; : error report I found in an email from 9/12/02:
;;; :
;;; : ... whenever I try to load a model (I get that far without
;;; : problem), OpenMCL complains:
;;; : ? (start-environment)
;;; : ((#<TCP-STREAM (SOCKET/4) #x54A8926> #<PROCESS Environment-Connection(2) [Enabled] #x54A8DEE> ("127.0.0.1" . 2621)))
;;; : <try to load a model>
;;; : ? Error in update of Handler: HANDLER5
;;; : message: #<Anonymous Function #x54C3E9E>
;;; :
;;; : Error:Unbound variable: \?
;;; :
;;; : and then hangs.
;;; 2014.07.30 Dan
;;; : * Added the all-dm-slot-lists and filter-dm-chunks functions
;;; : to use for the filter in the declarative viewer since
;;; : chunk-type won't work now.
;;; 2015.05.18 Dan
;;; : * Filter-dm-chunks now verifies that all the items are valid
;;; : slot names first because there are potential issues across
;;; : reset and loading where a slot name from a previous run
;;; : doesn't exist anymore.
;;; 2017.08.25 Dan
;;; : * Remove the functions that aren't needed as I go.
;;; 2017.09.01 Dan
;;; : * Updated the declarative cmds: dm-slot-filters and filter-
;;; : dm-chunks.
;;; : * To get around an issue in how the cmds come over from
;;; : Tcl with respect to the encoding of lists just make it
;;; : work 'right' here when necessary using convert-tcl-list-to-list.
;;; 2017.09.05 Dan
;;; : * Added dm-whynot-text to capture the whynot-dm output.
;;; : * Added production-details for capturing spp+pp output.
;;; 2017.09.06 Dan
;;; : * Added the sorted-module-names, printed-parameter-details,
;;; : and modules-parameters commands.
;;; 2017.09.07 Dan
;;; : * Fixed printed-parameter-details so that it decodes the
;;; : parameter from the string.
;;; : * Added modules-with-parameters for the parameters dialog.
;;; 2018.06.12 Dan
;;; : * Changed some external doc strings for consistency.
;;; 2019.07.30 Dan
;;; : * Adjusted filter-dm-chunks so that it doesn't assume a tcl
;;; : encoded list of slots.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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)
;; This is a hack to get around an issue in the encoding
;; of things on the Tcl side when generating the commands.
;; The right fix would be to have it better parse things
;; and create a list in JSON instead of sending the string
;; directly, but that's more work than just dealing with the
;; occasional issues in values sent.
(defun convert-tcl-list-to-list (string)
(handler-case (read-from-string (format nil "(~a)" string))
(error () nil)))
(defun dm-slot-filters ()
(cons '_none_ (all-dm-chunk-types (get-module declarative))))
(add-act-r-command "dm-slot-filters" 'dm-slot-filters "Returns a list of the possible filters (lists of slot names) for chunks in DM for the Environment to use. No params.")
(defun filter-dm-chunks (slot-list)
(let ((dm (get-module declarative)))
(if (and (stringp slot-list) (or (string-equal slot-list "_none_") (string-equal slot-list "null")))
(setf slot-list nil)
(setf slot-list (if (stringp slot-list) (convert-tcl-list-to-list slot-list) (decode-string-names slot-list))))
(when (and dm (every 'valid-slot-name slot-list))
(let ((mask (reduce 'logior slot-list :key 'slot-name->mask)))
(mapcan (lambda (x)
(if (slots-vector-match-signature (car x) mask)
(copy-list (cdr x))
nil))
(bt:with-lock-held ((dm-chunk-lock dm))(dm-chunks dm)))))))
(add-act-r-command "filter-dm-chunks" 'filter-dm-chunks "Returns a list of chunks in DM which match the specified slot list filter. Params: list-of-slots.")
(defun dm-chunk-details (name)
(let ((cname (string->name name)))
(if (chunk-p-fct cname)
(with-parameters (:ans nil)
(format nil "~a~%~a" (capture-command-output (sdp-fct (list cname)))
(printed-chunk cname)))
"")))
(add-act-r-command "dm-chunk-details" 'dm-chunk-details "Returns the text of the declarative parameters and printed representaion of a chunk for the Environment. Params: chunk-name.")
(defun dm-whynot-text (name)
(let ((cname (string->name name)))
(if (chunk-p-fct cname)
(capture-command-output (whynot-dm-fct (list cname)))
"")))
(add-act-r-command "dm-whynot-text" 'dm-whynot-text "Returns the text of the whynot-dm information for a chunk for use in the Environment. Params: chunk-name.")
(defun production-details (name)
(let ((pname (string->name name)))
(if (find pname (all-productions))
(format nil "~a~%~a" (capture-command-output (spp-fct (list pname)))
(printed-production-text pname))
"")))
(add-act-r-command "production-details" 'production-details "Returns the text of the procedural parameters and printed representaion of a production for the Environment. Params: production-name.")
(defun whynot-text (name)
(let ((pname (string->name name)))
(if (find pname (all-productions))
(format nil "Time: ~/print-time-in-seconds/~%~a" (mp-time-ms)
(capture-command-output (whynot-fct (list pname))))
"")))
(add-act-r-command "whynot-text" 'whynot-text "Returns the text of the whynot information for a production for use in the Environment. Params: production-name.")
(defun sorted-module-names ()
(sort (all-module-names) #'string< :key 'symbol-name))
(add-act-r-command "sorted-module-names" 'sorted-module-names "Returns a list of the names of all current modules sorted alphabetically. No params.")
(defun modules-with-parameters ()
(remove-if-not 'modules-parameters (sorted-module-names)))
(add-act-r-command "modules-with-parameters" 'modules-with-parameters "Returns a list of the names of all current modules which provided parameters sorted alphabetically. No params.")
(defun printed-parameter-details (param)
(capture-command-output (sgp-fct (list (string->name param)))))
(add-act-r-command "printed-parameter-details" 'printed-parameter-details "Returns a string of the parameter output for the given parameter's value and details. Params: parameter-name.")
(defun modules-parameters (module-name)
(let (params
(name (string->name module-name)))
(bt:with-lock-held (*parameters-table-lock*)
(maphash (lambda (key value)
(when (eq (act-r-parameter-owner value) name)
(push key params)))
*act-r-parameters-table*))
(sort params 'string< :key 'symbol-name)))
(add-act-r-command "modules-parameters" 'modules-parameters "Returns a list of the names of all the parameters for the named module sorted alphabetically. Params: module-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
|#
| 11,940 | Common Lisp | .lisp | 214 | 53.028037 | 196 | 0.609183 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 806976043b13a839dd7d1e73f81931b0147f29c4626450281f6e9477137c60ab | 14,140 | [
-1
] |
14,141 | stepper-control.lisp | asmaloney_ACT-R/environment/stepper-control.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-2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : stepper-control.lisp
;;; Version : 7.0
;;;
;;; Description : No system dependent code.
;;; : This file contains the Lisp to support the stepper window.
;;; :
;;; Bugs : [ ] Display more info in the cases when data wasn't recorded
;;; : 2021.01.27 fix at least stopped the warning
;;;
;;; Todo : [ ] Extend the possible information which can be recorded
;;; : with some sort of action triggers and data hooks.
;;;
;;; ----- History -----
;;;
;;; 05/24/2002 Dan
;;; : File creation
;;; 10/01/2002 Dan
;;; : Updated version to 1.1 and fixed the packaging
;;; : for building a standalone in ACL.
;;; : Modified the stepper-control-function to use the
;;; : new uni-wait-for function.
;;; 10/14/2002 Dan
;;; : Made the changes to implement the tutor mode
;;; : in the instantiation window instead of the bindings
;;; : window of the stepper.
;;; 11/11/2002 Dan
;;; : Modified stepper-instan-info and stepper-control-function
;;; : so that instantiation picking was possible. It works
;;; : off of the step buttons value and the *last-stepper-instantiation*
;;; : variable. Requires that the option be set in the
;;; : environment before it's enabled.
;;; 4/22/2004 Dan [1.5]
;;; : Added the license info.
;;; : Updated run-master-process with the RPM 2.2 version.
;;; -----------------------------------------------------------------------
;;; 2005.04.13 Dan
;;; : * Moved to ACT-R 6.
;;; : * LOTS of things to change - not included yet.
;;; 2005.04.20 Dan
;;; : * Updated and added - should work with the tutorial mode.
;;; 2005.05.14 Dan
;;; : * Fixed a typo in the stepper window - it was printing
;;; : +retreval> for retrieval requests...
;;; 2005.08.10 Dan
;;; : * Minor clean-up to declare event unused in stepper-test.
;;; 2006.03.10 Dan
;;; : * Calls to get-production no longer need the procedural
;;; : module so took that out of stepper-instan-binding.
;;; 2007.07.13 Dan
;;; : * Added the stepper-stop-button function because the
;;; : stop button is being put back on the stepper.
;;; 2007.08.03 Dan
;;; : * Moved the *stepper-open* defvar to environment-cmds
;;; : because it's used there and that's loaded first...
;;; 2007.08.07 Dan
;;; : * When :esc is set to t the stepper now shows the
;;; : declarative or procedural parameters for the
;;; : item in a new window in the lower left.
;;; 2007.08.08 Dan
;;; : * Put the "run until" button back into the stepper and
;;; : added module as an option now too.
;;; 2007.08.15 Dan
;;; : * The chunk list shown in the stepper is now sorted
;;; : by activation with the chunk being retrieved at the top.
;;; 2011.04.20 Dan
;;; : * Changed the evt-time call to an evt-mstime one and
;;; : converted the user time to ms.
;;; -------------------------------------------------------------------------
;;; 2011.05.20 Dan [3.0]
;;; : * Start of a complete overhaul to eliminate most of the
;;; : global variable usage and better encapsulate things so
;;; : that multiple model support can be added.
;;; 2011.05.25 Dan
;;; : * Fixed a bug in the tutor-completed function.
;;; 2011.05.26 Dan
;;; : * Protected some code that assumed there was a model for
;;; : eventual use with multiple models.
;;; 2011.05.31 Dan
;;; : * Removed a declaration from tutor-completed.
;;; : * Changed stepper-test so that when it's "until" a production
;;; : that name can be from any of the defined models.
;;; 2012.03.01 Dan
;;; : * Added the macro suppress-declarative-noise which will
;;; : temporarily set :ans to nil so that when sdp gets called
;;; : from the stepper it doesn't affect the current random
;;; : stream because otherwise it changes the results for a
;;; : fixed seed model when stepping through it and that makes
;;; : debugging more difficult.
;;; 2012.03.21 Dan
;;; : * Instead of suppress-declarative-noise I can just use
;;; : with-parameters to temporarily set :ans to nil.
;;; 2012.10.25 Dan
;;; : * Fixed the stepper so it doesn't step when :v is nil, which
;;; : is what it's documented as doing i.e. only stepping on
;;; : events that show in the trace.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2017.08.11 Dan
;;; : * Protect access to production-bindings.
;;; 2017.08.28 Dan [4.0]
;;; : * Complete reworking to not use the hander mechanism and
;;; : instead provide functions for the stepper to call and
;;; : call stepper side functions as needed.
;;; 2017.08.29 Dan
;;; : * Continuing the rewrite to complete the stepper tool.
;;; : * Using a module for it now to more easily handle the
;;; : information necessary when multiple models are defined.
;;; 2017.08.31 Dan
;;; : * Simplified this from all the cross-talk that the old
;;; : handler interface had and basically just need the hook
;;; : functions, stuff for parsing the events, and things to
;;; : deal with multiple models on the Lisp side now.
;;; 2017.10.06 Dan
;;; : * Need to know if tutor mode is off or on because when it's
;;; : on it needs to stop on production-selection events even if
;;; : they aren't displayed in the trace.
;;; 2018.08.08 Dan
;;; : * Have to print the retrieval chunk-spec during the hook
;;; : because declaritive frees it when its done.
;;; 2018.12.03 Dan
;;; : * Need to add a check for whether a varaible is the name of
;;; : a buffer for the update when in tutor mode and add extra
;;; : quotes around a binding which is a string.
;;; 2019.05.31 Dan [5.0]
;;; : * Add the ability to step on all events regardless of :v
;;; : setting. Goes along with the ability to open the stepper
;;; : while ACT-R is running now.
;;; 2019.08.02 Dan [6.0]
;;; : * Reworking this so that it's a general interface instead
;;; : of tied to the current Stepper tool.
;;; : - use a component so clear-all handled nicely
;;; : - can be started from anywhere
;;; : - only one ever allowed
;;; : - only the starter can manipulate it (given an id)
;;; : - there is always a waiting loop on the ACT-R side, but
;;; : one could wait on the other side too by not responding
;;; : - removed the tutor info slots since tutoring is all on
;;; : the other side
;;; 2019.08.12 Dan
;;; : * Check if there is an event for the update-stepper action.
;;; 2019.08.14 Dan
;;; : * Need to clear the skip type and value when a new stepper
;;; : is started.
;;; 2019.08.15 Dan
;;; : * Also need to clear the current-event and the stepped-event-
;;; : details when reset occurs.
;;; 2019.08.19 Dan
;;; : * Added a declare to update-stepper-info to avoid warnings.
;;; 2020.01.14 Dan [6.1]
;;; : * Use the new (:remove <>) option for hook functions.
;;; 2020.08.19 Dan
;;; : * Added a handler-case to start-stepper so that if there is
;;; : an error it doesn't leave the stepper open but unusable, and
;;; : then a bunch of ignore-errors in the remove-stepper-controls
;;; : so it can clean things up safely despite whatever caused the
;;; : error.
;;; 2020.10.29 Dan [6.2]
;;; : * Use suppress-undelay-cr and unsuppress-undelay-cr so that
;;; : opening and closing the stepper doesn't potentially lead to
;;; : scheduling a new conflict-resolution.
;;; 2021.01.27 Dan
;;; : * Added a safety check to displaying the production-fired
;;; : details since it's possible that the stepper wasn't open
;;; : when the production was selected and thus there's no info
;;; : recorded. In that case it will just print the name in the
;;; : list, but none of the details.
;;; 2021.11.01 Dan [7.0]
;;; : * Allow for other tutoring possibilities. The update function
;;; : is passed the name of the tutored event if it is one instead
;;; : of just t as was the case before when there was only one
;;; : possible tutoring event.
;;; : * If "update-stepper" is passed nil then it returns one item
;;; : which is any additional information recorded for tutoring
;;; : purposes at the time of the event.
;;; : * Now saves the production conditions text and whynot info
;;; : for conflict-resolution tutoring and the printed DM chunk
;;; : info for start-retrieval (the retrieval request is already
;;; : saved for display purposes). When asked for the tutor data
;;; : c-r sends a list of two element lists where the first item
;;; : in a list is a production's condition text and the second
;;; : is the whynot reason for that production or an empty string
;;; : if it does match, and s-r sends a list of two items where
;;; : the first item is the text of the retrieval request and the
;;; : second is a list of two element lists for each chunk in DM
;;; : with the first item being the printed chunk string and the
;;; : second being t if the chunk matches and nil if it does not.
;;; 2021.11.05 Dan
;;; : * Always step on start-retrieval and conflict-resolution when
;;; : tutoring is enabled, just like production-selected.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Provide a set of commands that can be used to provide an interactive
;;; stepper through the remote interface that will provide the retrieval and
;;; procedural details. Only one stepper can be active at a time.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; "start-stepper"
;;;
;;; Ask to start an interactive stepper session. Requires 4 parameters:
;;; step-all? - a boolean indicating whether it should stop on all events
;;; or only those displayed in the trace (can be changed later)
;;; tutor-mode? - a boolean indicating whether it should stop on production-
;;; selected events even if they aren't shown in the trace (can
;;; be changed later)
;;; next-event-cmd - a command which will be called to indicate that there is
;;; an event step. It will be passed one parameter which is
;;; the format-string of the event. This is called before the
;;; event has occurred.
;;;
;;; update-cmd - a command which will be called after a stepped event has been
;;; executed. It will be passed seven parameters:
;;; event - format-event string of the event
;;; items - a list of items for which there may be additional
;;; details available (currently retrieved chunks and
;;; selected or fired productions)
;;; tutorable - a generalized boolean indicating whether or not
;;; this is a tutorable item with a true value
;;; indicating the event type
;;; item-label - a string naming the type of items provided
;;; features-1 - a string indicating the information provided
;;; in the first value of an update
;;; features-2 - a string indicating the information provided
;;; in the second value of an update
;;; features-3 - a string indicating the information provided
;;; in the third value of an update
;;;
;;; It returns two values. The first is a boolean indicating whether a new
;;; stepper could be started (only one stepper allowed at a time) and the second
;;; is a string. If the stepper was started, the string is an id which must be
;;; provided to interact with that stepper, and if the stepper was not started
;;; it indicates the reason why not.
;;;
;;; Once started, the stepper will remain active until stopped or a clear-all
;;; occurs (it will persist across a reset).
;;;
;;; "set-stepper-ready"
;;;
;;; Indicate that an open stepper should start pausing the run. Requires one
;;; parameter which is the id of a started stepper. The stepper interface does
;;; not pause on any events until this command is called. If the id matches the
;;; currently open stepper, then it will now pause on the events which occur.
;;; If the stepper was successfully readied then it returns t otherwise it
;;; returns nil. The reason for the extra step is because one may need to
;;; perform some additional setup after opening a stepper before being able to
;;; actually process the information e.g. opening a window to display the
;;; information and get user input which wouldn't happen if opening the stepper
;;; failed.
;;;
;;;
;;; "stop-stepper"
;;;
;;; Stop using a stepper that was started. Requires one parameter which is the
;;; id string returned by start-stepper. If that id matches the currently open
;;; stepper interface then it is removed and the run is allowed to continue as
;;; normal. Returns a boolean indicating whether the stepper was stopped or not.
;;;
;;; "step-stepper"
;;;
;;; Advance the stepper control interface when it is waiting. It requires one
;;; parameter, and accepts three optional parameters. The required parameter is
;;; the id string returned by start-stepper. If the id string matches the
;;; currently open stepper it may stop waiting on the current event, depending
;;; upon the optional parameter values. If none of the optional parameters are
;;; given, then the current event will be allowed to occur and the run will
;;; continue until the next stepped event or it completes. The first optional
;;; parameter is a boolean indicating whether or not the current run should be
;;; termianted instead of allowing the event to occur. If it is provided as
;;; a true value, then the run will be terminated before executing the current
;;; event. If the value is false, then a normal step will occur. The other
;;; two optional parameters can be used to specify a condition for the next
;;; event at which to step instead of the next valid event. The third must
;;; be one of the strings: "production", "time", or "module", to indicate the
;;; constraint used to test for the next step and the fourth must indicate a
;;; valid value for the specified constraint step. If the constraint is
;;; production, then the value must be a string which names a production in
;;; a current model and the stepper will allow the system to run until a
;;; production with that name is selected or fired. If the constraint is
;;; time, then the value must be a number indicating a time in seconds and
;;; the stepper will allow the run to occur until an event with the given
;;; time (or greater) occurs. If the constraint is module, then the value
;;; must be a string naming a module in the system and the stepper will allow
;;; the run to occur until an event which has that module designation.
;;;
;;; The command returns two values. The first is a boolean indicating whether
;;; or not the provided parameters were valid (the id and constraint and value
;;; if specified). If they were valid the second will be an empty string,
;;; but if an invalid value is given the second will be a string indicating
;;; why something was invalid.
;;;
;;; "update-stepper"
;;;
;;; This command provides additional details for the items given to the update
;;; command provided when the stepper was started. It requires one parameter
;;; which should be one of the items in the list passed to the update command.
;;;
;;; If it is passed an item from the list (which is either a chunk name or
;;; production name since those are the only lists provided at this time),
;;; then it returns four values. The first two are strings with information
;;; for that item corresponding to the first two labels provided to the update.
;;; Currently, for production items those are the parameters and variable
;;; bindings, and for chunk items they are the chunk parameters and the
;;; retrieval request. The third item provides a string for the third label.
;;; For a production item it is the printed production if it is a production-
;;; selected event or the tutor mode is enabled otherwise it is the printed
;;; instantiatiation of that production, and for a chunk item it is a string
;;; of the printed chunk. The fourth value is additional information about
;;; the item. For chunk items it is nil, and for production items it is a
;;; list of lists related to the variable bindings. There will be one list
;;; for each variable with three items: the first is a string of the variable
;;; itself, the second is the value that variable has in the production
;;; instantiation (which will be an encoded string i.e. if the value itself
;;; is a string it will have a set of single quote characters around it) and
;;; the third is a boolean indicating whether or not the variable is the name
;;; of a buffer in the production.
;;;
;;; If it is passed a value of nil then it will return one value which is
;;; any additional tutoring information for the current situation.
;;;
;;; "set-stepper-tutoring"
;;;
;;; This command can be used to update whether the stepper is set to tutoring
;;; mode or not (in tutoring model it stops on production-selected actions
;;; even if they are not shown in the trace). It requires two parameters.
;;; The first is the id of the stepper and the second is a boolean indicating
;;; whether tutoring mode should be enabled or not. If the id is valid then
;;; the tutoring mode is set as indicated and t is returned, otherwise it
;;; returns nil.
;;;
;;; "set-stepper-step-all"
;;;
;;; This command can be used to update whether the stepper is set to step on
;;; all events (regardless of their output mode) or not. It requires two
;;; parameters. The first is the id of the stepper and the second is a boolean
;;; indicating whether the stepper should step all events or not. If the id is
;;; valid then the stepping mode is set as indicated and t is returned,
;;; otherwise it returns nil.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Since there are a lot of hooks needed to record the information and interact
;;; with the event queue that should probably all be on the "inside". The early
;;; versions of this were tied directly to the Tcl/Tk Environment and had a lot
;;; of odd interdependencies and representation choices.
;;;
;;; Now things are cleaned up to use the normal remote interface.
;;; It also depends upon the remote interface to keep track of whether a stepper
;;; is still needed. If the commands provided when starting the stepper are no
;;; longer available then it will terminate the stepper. That's handled by a
;;; thread that just checks every 1/4 second and stops stepping if they aren't
;;; there (since run time performance isn't an issue when stepping that doesn't
;;; seem like a problem).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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 stepper-control
(lock (bt:make-recursive-lock "stepper-lock"))
open pre-hook post-hook skip-type skip-val tutoring current-event stepped-event-details step-all next-cmd update-cmd waiting step-val
(step-lock (bt:make-lock)) (step-cv (bt:make-condition-variable))
safety-thread
ready)
(defvar *stepper* (make-stepper-control))
(defun stepper-cleared (stepper)
(bt:with-recursive-lock-held ((stepper-control-lock stepper))
(setf (stepper-control-open stepper) nil)))
(define-component-fct :stepper
:version "7.0"
:documentation "Stepper interface global information"
:creation (lambda () *stepper*)
:clear-all 'stepper-cleared)
(defstruct stepper-module rr rs cs)
(defun reset-stepper-module (instance)
(setf (stepper-module-rr instance) nil)
(setf (stepper-module-rs instance) nil)
(setf (stepper-module-cs instance) nil)
(let (open)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(setf open (stepper-control-open *stepper*))
(setf (stepper-control-stepped-event-details *stepper*) nil)
(setf (stepper-control-current-event *stepper*) nil))
(when open
(no-output
(unless (find 'stepper-rr-hook (car (sgp :retrieval-request-hook)))
(sgp :retrieval-request-hook stepper-rr-hook))
(unless (find 'stepper-rs-hook (car (sgp :retrieval-set-hook)))
(sgp :retrieval-set-hook stepper-rs-hook))
(unwind-protect
(progn
(suppress-undelay-cr)
(unless (find 'stepper-cs-hook (car (sgp :conflict-set-hook)))
(sgp :conflict-set-hook stepper-cs-hook)))
(unsuppress-undelay-cr))))))
(defun create-stepper-module (name)
(declare (ignore name))
(make-stepper-module))
(define-module stepper nil nil
:creation create-stepper-module
:reset (nil reset-stepper-module)
:version 7.0
:documentation "Store the model specific information for the stepper interface.")
(defun start-stepper (step-all tutor-mode next-event-fn update-fn)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(if (stepper-control-open *stepper*)
(values nil "There is already a stepper open")
(cond ((not (check-act-r-command next-event-fn))
(values nil (format nil "The next-event-fn given ~s did not name a valid command." next-event-fn)))
((not (check-act-r-command update-fn))
(values nil (format nil "The update-fn given ~s did not name a valid command." update-fn)))
((and (null step-all) (every (lambda (x) (with-model-eval x (null (car (no-output (sgp :v)))))) (mp-models)))
(values nil "Step-all not enabled and all models have :v set to nil."))
(t
(handler-case
(progn
(setf (stepper-control-step-all *stepper*) step-all)
(setf (stepper-control-tutoring *stepper*) tutor-mode)
(setf (stepper-control-next-cmd *stepper*) next-event-fn)
(setf (stepper-control-update-cmd *stepper*) update-fn)
(setf (stepper-control-current-event *stepper*) nil)
(setf (stepper-control-stepped-event-details *stepper*) nil)
(setf (stepper-control-ready *stepper*) nil)
(setf (stepper-control-skip-type *stepper*) nil)
(setf (stepper-control-skip-val *stepper*) nil)
(setf (stepper-control-open *stepper*) (symbol-name (new-symbol "stepper")))
(setf (stepper-control-safety-thread *stepper*)
(let ((id (stepper-control-open *stepper*))
(next next-event-fn)
(update update-fn))
(bt:make-thread (lambda ()
(loop
(sleep .25)
(unless (check-act-r-command next)
(return))
(unless (check-act-r-command update)
(return)))
(stop-stepper id nil)))))
(setf (stepper-control-pre-hook *stepper*)
(add-pre-event-hook 'stepper-pre-hook))
(setf (stepper-control-post-hook *stepper*)
(add-post-event-hook 'stepper-post-hook))
(dolist (m (mp-models))
(with-model-eval m
(let ((s (get-module stepper)))
(reset-stepper-module s))))
(values t (stepper-control-open *stepper*)))
(error (x)
(remove-stepper-controls *stepper* t)
(return-from start-stepper
(values nil
(let ((*print-circle* t))
(format nil "Error ~/print-error-message/ occurred while trying to start a stepper" x)))
))))))))
(add-act-r-command "start-stepper" 'start-stepper "Start the stepper control interface if possible. Returns t and an id or nil and a failure string. Params: step-all? tutor-mode? next-event-cmd update-cmd")
(defun stop-stepper (id &optional (kill t))
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(when (and (stringp id) (stepper-control-open *stepper*)
(string-equal id (stepper-control-open *stepper*)))
(remove-stepper-controls *stepper* kill)
(terminate-waiting *stepper*)
t)))
(defun remove-stepper-controls (stepper kill)
(ignore-errors (when kill (bt:destroy-thread (stepper-control-safety-thread stepper))))
(ignore-errors
(setf (stepper-control-open stepper) nil)
(setf (stepper-control-current-event stepper) nil)
(setf (stepper-control-stepped-event-details stepper) nil)
(when (stepper-control-pre-hook stepper)
(delete-event-hook (stepper-control-pre-hook stepper))
(setf (stepper-control-pre-hook stepper) nil))
(when (stepper-control-post-hook stepper)
(delete-event-hook (stepper-control-post-hook stepper))
(setf (stepper-control-post-hook stepper) nil)))
(dolist (m (mp-models))
(with-model-eval m
(no-output
(ignore-errors
(when (find 'stepper-rr-hook (car (sgp :retrieval-request-hook)))
(sgp :retrieval-request-hook (:remove stepper-rr-hook))))
(ignore-errors
(when (find 'stepper-rs-hook (car (sgp :retrieval-set-hook)))
(sgp :retrieval-set-hook (:remove stepper-rs-hook))))
(ignore-errors
(when (find 'stepper-cs-hook (car (sgp :conflict-set-hook)))
(unwind-protect
(progn
(suppress-undelay-cr)
(sgp :conflict-set-hook (:remove stepper-cs-hook)))
(unsuppress-undelay-cr))))))))
(add-act-r-command "stop-stepper" 'stop-stepper "Stop the stepper control interface. Params: stepper-id.")
(defun terminate-waiting (stepper)
(bt:acquire-lock (stepper-control-step-lock stepper) t)
(when (stepper-control-waiting stepper)
(setf (stepper-control-step-val stepper) t)
(bt:condition-notify (stepper-control-step-cv stepper)))
(bt:release-lock (stepper-control-step-lock stepper)))
(defun check-step-type (type val)
(if (stringp type)
(let* ((*read-eval* nil)
(real-val (if (stringp val) (read-from-string val nil :stepper-string-read-error) val)))
(if (eq real-val :stepper-string-read-error)
(if (zerop (length val))
(values nil "No step value provided.")
(values nil "Could not parse step value provided."))
(cond ((string-equal type "production")
(cond ((or (not (symbolp real-val))
(notany (lambda (model)
(with-model-eval model
(find real-val (all-productions))))
(mp-models)))
(values nil "Step type Production requires a valid production name."))
(t
(values 'production real-val))))
((string-equal type "time")
(cond ((not (numberp real-val))
(values nil "Step type Time requires a number in seconds."))
((>= (mp-time) real-val)
(values nil "Steo type Time given a time that has already occurred."))
(t
(values 'time (seconds->ms real-val)))))
((string-equal type "module")
(if (not (find val (mapcar 'symbol-name (all-module-names)) :test #'string-equal))
(values nil "Step type Module requires a valid module name.")
(values 'module val)))
(t
(values nil (format nil "Step type ~s not a valid type." type))))))
(values nil "Step type not a string.")))
(defun model-trace-enabled (event)
(with-model-eval (if (evt-model event) (evt-model event) (first (mp-models))) ;; just use the first if there isn't one (a break event)
(car (no-output (sgp :v)))))
(defun stepper-pre-hook (event)
(bt:acquire-lock (stepper-control-step-lock *stepper*) t)
(let (type val all next tutor ready)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(setf type (stepper-control-skip-type *stepper*)
val (stepper-control-skip-val *stepper*)
all (stepper-control-step-all *stepper*)
next (stepper-control-next-cmd *stepper*)
tutor (stepper-control-tutoring *stepper*)
ready (stepper-control-ready *stepper*)))
(if (and ready
(or all
(and type ;; running until a specific action
(event-displayed-p event)
(model-trace-enabled event)
(case type
(production
(and (or (eq (evt-action event) 'production-selected)
(eq (evt-action event) 'production-fired))
(string-equal val (symbol-name (production-name (car (evt-params event)))))))
(time
(>= (evt-mstime event) val))
(module
(string-equal val (symbol-name (evt-module event))))))
(and (null type)
(or
(and (event-displayed-p event)
(model-trace-enabled event))
(and tutor
(or
(eq (evt-action event) 'production-selected)
(eq (evt-action event) 'conflict-resolution)
(eq (evt-action event) 'start-retrieval))
)))))
(progn
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(setf (stepper-control-current-event *stepper*) event))
;; wait for step or termination
(let (result)
(setf (stepper-control-step-val *stepper*) nil)
(setf (stepper-control-waiting *stepper*) t)
(dispatch-apply next (format-event event))
(loop
(when (stepper-control-step-val *stepper*)
(setf result (stepper-control-step-val *stepper*))
(setf (stepper-control-waiting *stepper*) nil)
(return))
(bt:condition-wait (stepper-control-step-cv *stepper*) (stepper-control-step-lock *stepper*)))
(setf (stepper-control-waiting *stepper*) nil)
(bt:release-lock (stepper-control-step-lock *stepper*))
result))
(bt:release-lock (stepper-control-step-lock *stepper*)))))
(defun stepper-step (id &optional stop type value)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(let (val result msg
(valid-id (and (stringp id) (stepper-control-open *stepper*)
(string-equal id (stepper-control-open *stepper*))))
)
(if valid-id
(progn
(setf (stepper-control-skip-type *stepper*) nil)
(setf (stepper-control-skip-val *stepper*) nil)
(if stop
(setf val "break" result t msg "")
(if type
(multiple-value-bind (valid-type valid-val) (check-step-type type value)
(if valid-type
(progn
(setf (stepper-control-skip-type *stepper*) valid-type)
(setf (stepper-control-skip-val *stepper*) valid-val)
(setf val t result t msg ""))
(setf result nil msg valid-val)))
(setf val t result t msg ""))))
(setf result nil msg "Invalid id provided to stepper-step"))
(when result
(bt:acquire-lock (stepper-control-step-lock *stepper*) t)
(when (stepper-control-waiting *stepper*)
(setf (stepper-control-step-val *stepper*) val)
(bt:condition-notify (stepper-control-step-cv *stepper*)))
(bt:release-lock (stepper-control-step-lock *stepper*)))
(values result msg))))
(add-act-r-command "step-stepper" 'stepper-step "Advance the stepper control interface when it is waiting. Returns: success error-msg. Params: stepper-id {stop? {step-type step-value}}")
(defun stepper-post-hook (event)
(let (step-event cmd ready)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(setf step-event (stepper-control-current-event *stepper*)
cmd (stepper-control-update-cmd *stepper*)
ready (stepper-control-ready *stepper*))
)
(when (and ready (eq event step-event))
(let ((current-details (cond ((or (eq (evt-action event) 'production-selected)
(eq (evt-action event) 'production-fired))
(list (with-model-eval (evt-model event)
(if (eq (evt-action event) 'production-fired)
;; catch when no saved data
(if (car (stepper-module-cs (get-module stepper)))
(list (car (stepper-module-cs (get-module stepper))))
;; get production named in the event
(list (production-name (first (evt-params event)))))
(stepper-module-cs (get-module stepper))))
(if (eq (evt-action event) 'production-selected) 'production-selected nil)
"Possible Productions" "Production Parameters" "Bindings" "Production"))
((or (eq (evt-action event) 'retrieved-chunk)
(eq (evt-action event) 'retrieval-failure))
(list (with-model-eval (evt-model event)
(stepper-module-rs (get-module stepper)))
nil
"Possible Chunks" "Chunk Parameters" "Retrieval Request" "Chunk"))
((eq (evt-action event) 'conflict-resolution)
(list nil 'conflict-resolution "" "" "" ""))
((eq (evt-action event) 'start-retrieval)
(list nil 'start-retrieval "" "" "" ""))
(t
(list nil nil "" "" "" ""))))
(saved-details (cond ((or (eq (evt-action event) 'production-selected)
(eq (evt-action event) 'production-fired))
(with-model-eval (evt-model event)
(mapcar (lambda (p)
(when p
(let* ((prod (get-production p))
(bindings (when prod
(bt:with-recursive-lock-held ((production-lock prod))
(mapcar (lambda (x)
(list (car x) (cdr x)
(and (find (car x) (production-lhs-buffers prod) :key 'buffer-name->variable) t)))
(production-bindings prod))))))
(list p
(capture-command-output (spp-fct (list p)))
(let ((s (make-string-output-stream)))
(mapcar (lambda (x)
(format s "~a: ~s~%"
(first x) (second x)))
bindings)
(get-output-stream-string s))
(list (printed-production-text p) (printed-production-text p t))
(mapcar (lambda (x) (list (first x)
(if (stringp (second x))
(encode-string (second x))
(second x))
(third x)))
bindings)
))))
(if (eq (evt-action event) 'production-fired)
(list (car (stepper-module-cs (get-module stepper))))
(stepper-module-cs (get-module stepper))))))
((or (eq (evt-action event) 'retrieved-chunk)
(eq (evt-action event) 'retrieval-failure))
(with-model-eval (evt-model event)
(let ((s (get-module stepper)))
(mapcar (lambda (c)
(list
c
(with-parameters (:ans nil) (capture-command-output (sdp-fct (list c))))
(if (stepper-module-rr s) (format nil "+retrieval>~%~a" (stepper-module-rr s)) "")
(printed-chunk c)
nil))
(stepper-module-rs (get-module stepper))))))
((eq (evt-action event) 'conflict-resolution)
(with-model-eval (evt-model event)
(mapcar (lambda (x)
(list (printed-production-side x t)
(let ((w (whynot-text x)))
(aif (search "It fails because:" w)
(let ((ws (list #\return #\space #\newline)))
(string-right-trim ws (string-left-trim ws (subseq w (+ it 17)))))
""))))
(let ((seed (get-parameter-value :seed)))
(prog1
(permute-list (all-productions))
(set-parameter-value :seed seed))))))
((eq (evt-action event) 'start-retrieval)
(with-model-eval (evt-model event)
(let* ((s (get-module stepper))
(request-text
(if (stepper-module-rr s)
(format nil "+retrieval>~%~a" (stepper-module-rr s))
""))
(request-spec (read-from-string (format nil "(~a)" (stepper-module-rr s))))
(matching (no-output (sdm-fct request-spec)))
)
(list request-text
(mapcar (lambda (c)
(list
(let ((ws (list #\return #\newline))
(name (symbol-name c)))
(string-right-trim
ws (string-left-trim
ws (subseq (printed-chunk c) (length name)))))
(when (find c matching) t)))
(no-output (dm)))))))
(t (list "" "" "" nil)))))
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(setf (stepper-control-stepped-event-details *stepper*)
(list (evt-time step-event) (evt-action step-event) (evt-params step-event) saved-details)))
(dispatch-apply-list cmd (cons (format-event event) current-details))))))
(defun update-stepper-info (item)
(if item
(let (event tutor
(name (string->name item)))
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(setf event (stepper-control-stepped-event-details *stepper*))
(setf tutor (stepper-control-tutoring *stepper*)))
(if event
(destructuring-bind (time action params details) event
(declare (ignore time params))
(cond ((or (eq action 'production-selected)
(eq action 'production-fired))
(let ((d (assoc name details)))
(if d
(values
(second d)
(third d)
(if (or (eq action 'production-selected)
tutor)
(first (fourth d))
(second (fourth d)))
(fifth d))
(values "" "" "" nil))))
((or (eq action 'retrieved-chunk)
(eq action 'retrieval-failure))
(let ((d (assoc name details)))
(if d
(values-list (cdr d))
(values "" "" "" nil))))
(t
(values "" "" "" nil))))
(values "" "" "" nil)))
(fourth (stepper-control-stepped-event-details *stepper*))))
(add-act-r-command "update-stepper" 'update-stepper-info "Stepper interface command for getting the detailed information. Returns: strings for the three information panels for the given item. Params: seleted-item")
(defun stepper-rr-hook (request)
(setf (stepper-module-rr (get-module stepper)) (printed-chunk-spec request))
nil)
(defun stepper-rs-hook (set)
(setf (stepper-module-rs (get-module stepper)) (copy-list set))
nil)
(defun stepper-cs-hook (set)
(setf (stepper-module-cs (get-module stepper)) (copy-list set))
nil)
(defun set-stepper-tutoring (id value)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(when (and (stringp id) (stepper-control-open *stepper*)
(string-equal id (stepper-control-open *stepper*)))
(setf (stepper-control-tutoring *stepper*) value)
t)))
(add-act-r-command "set-stepper-tutoring" 'set-stepper-tutoring "Stepper interface command for changing the tutor mode. Params: stepper-id tutoring-value.")
(defun set-stepper-step-all (id value)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(when (and (stringp id) (stepper-control-open *stepper*)
(string-equal id (stepper-control-open *stepper*)))
(setf (stepper-control-step-all *stepper*) value)
t)))
(add-act-r-command "set-stepper-step-all" 'set-stepper-step-all "Stepper interface command for changing the step-all mode. Params: stepper-id step-all-value.")
(defun set-stepper-ready (id)
(bt:with-recursive-lock-held ((stepper-control-lock *stepper*))
(when (and (stringp id) (stepper-control-open *stepper*)
(string-equal id (stepper-control-open *stepper*)))
(setf (stepper-control-ready *stepper*) t))))
(add-act-r-command "set-stepper-ready" 'set-stepper-ready "Stepper interface command for signaling that code which opened a stepper is ready to start stepping. Params: stepper-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
|#
| 48,523 | Common Lisp | .lisp | 824 | 46.656553 | 214 | 0.550336 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4b0bc4aadebe7f8bf5055ebd5cea8cf1c76a1f318eea35a358b53550f0ec925a | 14,141 | [
-1
] |
14,142 | microphone.lisp | asmaloney_ACT-R/other-files/microphone.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 : microphone.lisp
;;; Version : 1.0
;;;
;;; Description : Implement a simple virtual microphone device for models.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2018.03.05 Dan [1.0]
;;; : * Create a device which generates the output-speech signal
;;; : instead of doing it directly from speech module.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Instead of having the speech module directly create the output-speech
;;; signal it seems like the right thing to do is have a device for that both
;;; for consistency and extendability.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; The output-speech signal can be monitored to detect the start of model speech.
;;; It gets two parametes: the current model name and the spoken text.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Keep it very simple - no need for anything other than the interface functions
;;; since there's no state for this.
;;;
;;; Only respond to the start of speech. One could extend that since the speech
;;; module now sends the notice of start & stop for both speak and subvocalize.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
(add-act-r-command "output-speech" nil "Command called when the model performs a speech action which can be monitored. It is passed 2 parameters: model-name and the text spoken. Should not be called directly.")
(defun microphone-interface (device-list features)
(declare (ignore device-list))
(if (and (eq (first features) 'start)
(eq (second features) 'speak))
(schedule-event-now "output-speech" :params (list (current-model) (third features)) :module 'microphone)
;; effectively unnecessary but doing so for completeness
(when (eq (first features) 'check-subvocalize)
nil)))
(add-act-r-command "microphone-interface-fn" 'microphone-interface "Function which can process the speech module's notifications. Do not call directly.")
(define-device "microphone" nil nil "microphone-interface-fn")
#|
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,972 | Common Lisp | .lisp | 84 | 44.428571 | 212 | 0.57272 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e732e7d4f4a40d144256e23b0a90508336c89a4549374befd23372509c19a8d8 | 14,142 | [
-1
] |
14,143 | keyboard.lisp | asmaloney_ACT-R/other-files/keyboard.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 : keyboard.lisp
;;; Version : 3.1
;;;
;;; Description : Implement the virtual keyboard device for models.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2017.01.19 Dan [1.0]
;;; : * Actually put a header on this file after splitting it out
;;; : from the device and device interface code.
;;; 2017.01.20 Dan
;;; : * Finish off the motor command code.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.08 Dan
;;; : * Changed the define-device call since it doesn't
;;; : take keyword parameters now that the internal is the same
;;; : as the remote version.
;;; 2017.02.22 Dan
;;; : * Keyboard key names are now stored in upcase and the key->*
;;; : functions upcase the given value.
;;; 2017.02.27 Dan
;;; : * Schedule "output-key" directly now instead of going through
;;; : the stub function, but still need the stub since human
;;; : input gets routed through that and putting the remote call
;;; : into the interface code would be ugly.
;;; 2017.03.06 Dan
;;; : * Updated the doc string for output-key to indicate that it
;;; : also gets called for real interaction with an exp-window.
;;; : * Specify the model in the schedule-event for the output-key.
;;; : * Don't set the hand's device directly but provide it to the
;;; : point-hand request for motor actions.
;;; 2017.03.08 Dan
;;; : * When a keyboard gets installed only move hands that aren't
;;; : already on a device to it.
;;; 2017.03.15 Dan
;;; : * Fixed a bug in the scheduling of output-key.
;;; 2017.07.14 Dan
;;; : * Fixed some cut-and-paste issues in hand-to-home.
;;; 2017.08.10 Dan [2.0]
;;; : * Instead of a single global keyboard definition, now using a
;;; : component to hold a table of keyboards for each model.
;;; : Update-keyboard-device needs to be called in the context of
;;; : a model and will change that model's keyboard.
;;; : * Update all the access to hand objects to be thread safe.
;;; 2017.08.11 Dan
;;; : * Fixed some typos in the component functions.
;;; 2017.08.23 Dan
;;; : * Don't need the dummy function for output-key now.
;;; 2018.01.03 Dan
;;; : * Fixed a bug with specify-key because it only set the position
;;; : of keys in the array for default keys.
;;; 2018.03.12 Dan
;;; : * Adjusted the device fns to accept the whole device and now
;;; : check that it's a "motor" device before doing anything.
;;; 2018.03.27 Dan
;;; : * Make sure all the hand setting actions use the whole device
;;; : now instead of just "keyboard".
;;; 2018.06.04 Dan
;;; : * Added remote start-hand-at-keypad and start-hand-at-key.
;;; 2018.06.22 Dan
;;; : * Only remote start-hand-at-key accepts a string naming hand.
;;; 2018.07.26 Dan [1.1]
;;; : * Don't worry about completing requests.
;;; 2018.10.04 Dan [2.2]
;;; : * Use notify-interface instead of touching the internals of
;;; : the motor module for some commands (new styles still use a
;;; : little internal knowledge for efficiency).
;;; : * Using the third item in the device list to name the keyboard
;;; : to install, and replacing update-keyboard-device with an
;;; : add-keyboard command that takes a string for the name and
;;; : then the class name as the second item. Of course that
;;; : still requires one to create a keyboard device in Lisp, but
;;; : for now that's better than how things were before...
;;; 2018.10.08 Dan
;;; : * Also adding a set-default-keyboard which specifies the
;;; : keyboard that's installed when no third item provided.
;;; : That is a global change which is unaffected by clear-all!
;;; : * Added a way to extend the notifications which are handled
;;; : by the keyboard through the other-notifications method
;;; : since the keyboards are always Lisp objects at this point.
;;; : * Don't create a keyboard entry in the component for models
;;; : automatically (only when installed).
;;; : * Allow the keyboard to be installed for any device, not just
;;; : motor. Of course, only supports actions for motor by default
;;; : but extensions could be made to handle others.
;;; : * User code all uses notify-interface, but styles still use
;;; : motor module.
;;; 2018.10.16 Dan
;;; : * Hand-to-keypad and hand-to-home need to not set the device.
;;; 2018.01.14 Dan
;;; : * Fixed a bug with start-hand-at-key always printing a warning
;;; : about an invalid hand.
;;; 2019.09.09 Dan
;;; : * Fixed a bug with press-key not warning when there was no
;;; : keyboard device installed.
;;; 2020.03.27 Dan [3.0]
;;; : * Updated to use the new position information that records
;;; : where the hands "will be" when the action starts to get the
;;; : correct feature info.
;;; : * Also added tests to hand-to-home/keypad to ignore if already
;;; : there or going to be there.
;;; : * Point-hand-at-key needs to check for 'standard as the offsets.
;;; : * Press-key checks for home or keypad position before making
;;; : the action and warns if the hand isn't in the right starting
;;; : place (assumes that keys with a loc x > 18 and y > 1 are
;;; : keypad position for now).
;;; 2020.04.20 Dan [3.1]
;;; : * Generalize the possible hand positions on the keyboard and
;;; : include the assumed starting position for the press-key style
;;; : in specify-key.
;;; 2020.08.25 Dan
;;; : * Move the keyboard-component defstruct to before any of the
;;; : accessors are used.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Implement the keyboard as a device under the new PM interface mechanisms.
;;; Create a single default keyboard definition with which any model can interact,
;;; but also specify a component which holds a table of keyboards so each model
;;; can have a different one.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; Virtual-keyboard class and initialization methods.
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Simplify the construction of a keyboard because the three separate methods
;;; that the old code used have always had inconsistencies and/or errors in the
;;; specifications between the methods.
;;;
;;; The motor commands related to keyboards are moved here too since the motor
;;; module itself doesn't "know" about any particular device with which it can
;;; interact. That's a departure from the older versions where the motor
;;; module assumed a keyboard and mouse existed and was built around them.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
;;; A structure to hold a component for storing keyboards
(defstruct keyboard-component (lock (bt:make-lock "keyboard-component")) (table (make-hash-table)) default)
;;;; ---------------------------------------------------------------------- ;;;;
;;;; The virtual keyboard.
(defclass virtual-keyboard ()
((key->cmd-ht :accessor key->cmd-ht
:initform (make-hash-table :test #'equalp))
(key->hand-start-ht :accessor key->hand-start-ht
:initform (make-hash-table :test #'equalp))
(key->loc-ht :accessor key->loc-ht
:initform (make-hash-table :test #'equalp))
(loc->key-array :accessor loc->key-arr :initform nil)
(hand-loc-table :accessor hand-loc-table
:initform (make-hash-table :test #'equalp))
(left-start :accessor left-start :initform nil)
(right-start :accessor right-start :initform nil)))
(defmethod initialize-instance :after ((vk virtual-keyboard) &key)
(setf (loc->key-arr vk) (make-array (keyboard-size vk) :initial-element nil))
(populate-hand-locations vk)
(set-starting-hand-locations vk)
(populate-key-details vk))
;; Instead of building up the three tables (name->press-key-command, position->name,
;; and name->position) with separate methods just use one method that takes all of
;; the components and then enters the information appropriately. This avoids
;; the inconsistencies (and errors) between tables that the old methods often
;; created.
(defgeneric specify-key (keyboard x y names &key default style hand-loc)
(:documentation "Specify the names for keys by location, indicate whether it's the default position for that key, and
if there's a press-key mapping for it indicate the underlying style and features and the assumed hand-location name."))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Subclass the virtual-keyboard and these methods to represent different keyboards.
(defgeneric keyboard-size (keyboard)
(:documentation "Specify the dimensions for the keyboard as a list of columns and rows"))
(defmethod keyboard-size ((k virtual-keyboard))
(list 23 7))
(defgeneric populate-hand-locations (keyboard)
(:documentation "Set all of the desired hand locations in the table"))
(defmethod populate-hand-locations ((k virtual-keyboard))
(setf (gethash 'left-home (hand-loc-table k))
(list (list 'hand 4 4) (list 'index 0 0) (list 'middle -1 0) (list 'ring -2 0) (list 'pinkie -3 0) (list 'thumb 1 2)))
(setf (gethash 'right-home (hand-loc-table k))
(list (list 'hand 7 4) (list 'index 0 0) (list 'middle 1 0) (list 'ring 2 0) (list 'pinkie 3 0) (list 'thumb -1 2)))
(setf (gethash 'keypad (hand-loc-table k))
(list (list 'hand 19 4) (list 'index 0 0) (list 'middle 1 0) (list 'ring 2 0) (list 'pinkie 3 1) (list 'thumb 0 2))))
(defgeneric set-starting-hand-locations (keyboard)
(:documentation "Set the starting hand locations in the table"))
(defmethod set-starting-hand-locations ((k virtual-keyboard))
(setf (left-start k) (gethash 'left-home (hand-loc-table k)))
(setf (right-start k) (gethash 'right-home (hand-loc-table k))))
(defgeneric populate-key-details (keyboard)
(:documentation "Specify all the key information using the specify-key method."))
(defmethod populate-key-details ((k virtual-keyboard))
;; Top row
(specify-key k 0 0 '("ESC" "ESCAPE"))
(specify-key k 2 0 "F1")
(specify-key k 3 0 "f2")
(specify-key k 4 0 "f3")
(specify-key k 5 0 "f4")
(specify-key k 7 0 "F5")
(specify-key k 8 0 "f6")
(specify-key k 9 0 "f7")
(specify-key k 10 0 "f8")
(specify-key k 12 0 "F9")
(specify-key k 13 0 "f10")
(specify-key k 14 0 "f11")
(specify-key k 15 0 "f12")
(specify-key k 17 0 '("f13" "print-screen"))
(specify-key k 18 0 '("f14" "scroll-lock"))
(specify-key k 19 0 '("f15" "pause"))
;; numeric key row
(specify-key k 0 2 '("`" "backquote") :style '(peck-recoil :hand left :finger pinkie :r 2.24 :theta -2.03) :hand-loc 'left-home)
(specify-key k 1 2 "1" :style '(peck-recoil :hand left :finger pinkie :r 2 :theta -1.57) :hand-loc 'left-home)
(specify-key k 2 2 "2" :style '(peck-recoil :hand left :finger ring :r 2 :theta -1.57) :hand-loc 'left-home)
(specify-key k 3 2 "3" :style '(peck-recoil :hand left :finger middle :r 2 :theta -1.57) :hand-loc 'left-home)
(specify-key k 4 2 "4" :style '(peck-recoil :hand left :finger index :r 2 :theta -1.57) :hand-loc 'left-home)
(specify-key k 5 2 "5" :style '(peck-recoil :hand left :finger index :r 2.24 :theta -1.11) :hand-loc 'left-home)
(specify-key k 6 2 "6" :style '(peck-recoil :hand right :finger index :r 2.24 :theta -2.03) :hand-loc 'right-home)
(specify-key k 7 2 "7" :style '(peck-recoil :hand right :finger index :r 2 :theta -1.57) :hand-loc 'right-home)
(specify-key k 8 2 "8" :style '(peck-recoil :hand right :finger middle :r 2 :theta -1.57) :hand-loc 'right-home)
(specify-key k 9 2 "9" :style '(peck-recoil :hand right :finger ring :r 2 :theta -1.57) :hand-loc 'right-home)
(specify-key k 10 2 "0" :style '(peck-recoil :hand right :finger pinkie :r 2 :theta -1.57) :hand-loc 'right-home)
(specify-key k 11 2 '("-" "hyphen") :style '(peck-recoil :hand right :finger pinkie :r 2.24 :theta -1.11) :hand-loc 'right-home)
(specify-key k 12 2 '( "=" "equal") :style '(peck-recoil :hand right :finger pinkie :r 2.83 :theta -0.78) :hand-loc 'right-home)
(specify-key k 13 2 "delete" :style '(peck-recoil :hand right :finger pinkie :r 3.6 :theta -0.59) :hand-loc 'right-home)
(specify-key k 15 2 "help")
(specify-key k 16 2 "home")
(specify-key k 17 2 "pageup")
(specify-key k 19 2 "clear" :style '(peck-recoil :hand right :finger index :r 2 :theta -1.57) :hand-loc 'keypad)
(specify-key k 20 2 '("keypad-=" "keypad-equal") :style '(peck-recoil :hand right :finger middle :r 2 :theta -1.57) :hand-loc 'keypad)
(specify-key k 21 2 '("keypad-/" "keypad-slash" "keypad-divide") :style '(peck-recoil :hand right :finger ring :r 2 :theta -1.57) :hand-loc 'keypad)
(specify-key k 22 2 '("keypad-*" "keypad-asterisk" "keypad-times") :style '(peck-recoil :hand right :finger pinkie :r 3 :theta -1.57) :hand-loc 'keypad)
;; qwerty row
(specify-key k 0 3 "tab" :style '(peck-recoil :hand left :finger pinkie :r 1.41 :theta -2.36) :hand-loc 'left-home)
(specify-key k 1 3 "q" :style '(peck-recoil :hand left :finger pinkie :r 1 :theta -1.57) :hand-loc 'left-home)
(specify-key k 2 3 "w" :style '(peck-recoil :hand left :finger ring :r 1 :theta -1.57) :hand-loc 'left-home)
(specify-key k 3 3 "e" :style '(peck-recoil :hand left :finger middle :r 1 :theta -1.57) :hand-loc 'left-home)
(specify-key k 4 3 "r" :style '(peck-recoil :hand left :finger index :r 1 :theta -1.57) :hand-loc 'left-home)
(specify-key k 5 3 "t" :style '(peck-recoil :hand left :finger index :r 1.41 :theta -0.79) :hand-loc 'left-home)
(specify-key k 6 3 "y" :style '(peck-recoil :hand right :finger index :r 1.41 :theta -2.36) :hand-loc 'right-home)
(specify-key k 7 3 "u" :style '(peck-recoil :hand right :finger index :r 1 :theta -1.57) :hand-loc 'right-home)
(specify-key k 8 3 "i" :style '(peck-recoil :hand right :finger middle :r 1 :theta -1.57) :hand-loc 'right-home)
(specify-key k 9 3 "o" :style '(peck-recoil :hand right :finger ring :r 1 :theta -1.57) :hand-loc 'right-home)
(specify-key k 10 3 "p" :style '(peck-recoil :hand right :finger pinkie :r 1 :theta -1.57) :hand-loc 'right-home)
(specify-key k 11 3 '("[" "left-bracket") :style '(peck-recoil :hand right :finger pinkie :r 1.41 :theta -0.78) :hand-loc 'right-home)
(specify-key k 12 3 '("]" "right-bracket") :style '(peck-recoil :hand right :finger pinkie :r 2.24 :theta -0.46) :hand-loc 'right-home)
(specify-key k 13 3 '("\\" "backslash") :style '(peck-recoil :hand right :finger pinkie :r 3.16 :theta -0.32) :hand-loc 'right-home)
(specify-key k 15 3 '("forward-delete" "del"))
(specify-key k 16 3 "end")
(specify-key k 17 3 "pagedown")
(specify-key k 19 3 "keypad-7" :style '(peck-recoil :hand right :finger index :r 1 :theta -1.57) :hand-loc 'keypad)
(specify-key k 20 3 "keypad-8" :style '(peck-recoil :hand right :finger middle :r 1 :theta -1.57) :hand-loc 'keypad)
(specify-key k 21 3 "keypad-9" :style '(peck-recoil :hand right :finger ring :r 1 :theta -1.57) :hand-loc 'keypad)
(specify-key k 22 3 '("keypad--" "keypad-minus" "keypad-hyphen") :style '(peck-recoil :hand right :finger pinkie :r 2 :theta -1.57) :hand-loc 'keypad)
;; ASDF row
(specify-key k 0 4 "caps-lock" :style '(peck-recoil :hand left :finger pinkie :r 1.0 :theta 3.14) :hand-loc 'left-home)
(specify-key k 1 4 "a" :style '(punch :hand left :finger pinkie) :hand-loc 'left-home)
(specify-key k 2 4 "s" :style '(punch :hand left :finger ring) :hand-loc 'left-home)
(specify-key k 3 4 "d" :style '(punch :hand left :finger middle) :hand-loc 'left-home)
(specify-key k 4 4 "f" :style '(punch :hand left :finger index) :hand-loc 'left-home)
(specify-key k 5 4 "g" :style '(peck-recoil :hand left :finger index :r 1 :theta 0) :hand-loc 'left-home)
(specify-key k 6 4 "h" :style '(peck-recoil :hand right :finger index :r 1 :theta 3.14) :hand-loc 'right-home)
(specify-key k 7 4 "j" :style '(punch :hand right :finger index) :hand-loc 'right-home)
(specify-key k 8 4 "k" :style '(punch :hand right :finger middle) :hand-loc 'right-home)
(specify-key k 9 4 "l" :style '(punch :hand right :finger ring) :hand-loc 'right-home)
(specify-key k 10 4 '(";" "semicolon") :style '(punch :hand right :finger pinkie) :hand-loc 'right-home)
(specify-key k 11 4 '("'" "quote") :style '(peck-recoil :hand right :finger pinkie :r 1 :theta 0) :hand-loc 'right-home)
(specify-key k 12 4 '("return" "newline") :style '(peck-recoil :hand right :finger pinkie :r 2 :theta 0) :hand-loc 'right-home)
(specify-key k 13 4 '("return" "newline") :default nil)
(specify-key k 19 4 "keypad-4" :style '(punch :hand right :finger index) :hand-loc 'keypad)
(specify-key k 20 4 "keypad-5" :style '(punch :hand right :finger middle) :hand-loc 'keypad)
(specify-key k 21 4 "keypad-6" :style '(punch :hand right :finger ring) :hand-loc 'keypad)
(specify-key k 22 4 '("keypad-+" "keypad-plus") :style '(peck-recoil :hand right :finger pinkie :r 1 :theta -1.57) :hand-loc 'keypad)
;; Z row
(specify-key k 0 5 '("shift" "left-shift") :style '(peck-recoil :hand left :finger pinkie :r 1.41 :theta 2.36) :hand-loc 'left-home)
(specify-key k 1 5 "z" :style '(peck-recoil :hand left :finger pinkie :r 1 :theta 1.57) :hand-loc 'left-home)
(specify-key k 2 5 "x" :style '(peck-recoil :hand left :finger ring :r 1 :theta 1.57) :hand-loc 'left-home)
(specify-key k 3 5 "c" :style '(peck-recoil :hand left :finger middle :r 1 :theta 1.57) :hand-loc 'left-home)
(specify-key k 4 5 "v" :style '(peck-recoil :hand left :finger index :r 1 :theta 1.57) :hand-loc 'left-home)
(specify-key k 5 5 "b" :style '(peck-recoil :hand left :finger index :r 1.41 :theta 0.79) :hand-loc 'left-home)
(specify-key k 6 5 "n" :style '(peck-recoil :hand right :finger index :r 1.41 :theta 2.36) :hand-loc 'right-home)
(specify-key k 7 5 "m" :style '(peck-recoil :hand right :finger index :r 1 :theta 1.57) :hand-loc 'right-home)
(specify-key k 8 5 '("," "comma") :style '(peck-recoil :hand right :finger middle :r 1 :theta 1.57) :hand-loc 'right-home)
(specify-key k 9 5 '("." "period" "dot") :style '(peck-recoil :hand right :finger ring :r 1 :theta 1.57) :hand-loc 'right-home)
(specify-key k 10 5 '("/" "slash") :style '(peck-recoil :hand right :finger pinkie :r 1 :theta 1.57) :hand-loc 'right-home)
(specify-key k 11 5 "right-shift" :style '(peck-recoil :hand right :finger pinkie :r 1.41 :theta 0.78) :hand-loc 'right-home)
(specify-key k 12 5 "right-shift" :default nil)
(specify-key k 13 5 "right-shift" :default nil)
(specify-key k 16 5 "up-arrow")
(specify-key k 19 5 "keypad-1" :style '(peck-recoil :hand right :finger index :r 1 :theta 1.57) :hand-loc 'keypad)
(specify-key k 20 5 "keypad-2" :style '(peck-recoil :hand right :finger middle :r 1 :theta 1.57) :hand-loc 'keypad)
(specify-key k 21 5 "keypad-3" :style '(peck-recoil :hand right :finger ring :r 1 :theta 1.57) :hand-loc 'keypad)
(specify-key k 22 5 '("enter" "keypad-enter") :style '(punch :hand right :finger pinkie) :hand-loc 'keypad)
;; space bar row
(specify-key k 0 6 '("control" "left-control") :style '(peck-recoil :hand left :finger pinkie :r 2.24 :theta 2.03) :hand-loc 'left-home)
(specify-key k 1 6 '("option" "left-option") :style '(peck-recoil :hand left :finger pinkie :r 2.0 :theta 1.57) :hand-loc 'left-home)
(specify-key k 2 6 '("command" "left-command") :style '(peck-recoil :hand left :finger ring :r 2.0 :theta 1.57) :hand-loc 'left-home)
(specify-key k 3 6 "space" :default nil)
(specify-key k 4 6 "space" :default nil)
(specify-key k 5 6 "space" :style '(punch :hand left :finger thumb) :hand-loc 'left-home)
(specify-key k 6 6 "space" :default nil)
(specify-key k 7 6 "space" :default nil)
(specify-key k 8 6 "space" :default nil)
(specify-key k 9 6 "space" :default nil)
(specify-key k 10 6 "space" :default nil)
(specify-key k 11 6 "right-command" :style '(peck-recoil :hand right :finger pinkie :r 2.24 :theta 1.11) :hand-loc 'right-home)
(specify-key k 12 6 "right-option" :style '(peck-recoil :hand right :finger pinkie :r 2.83 :theta 0.78) :hand-loc 'right-home)
(specify-key k 13 6 "right-control" :style '(peck-recoil :hand right :finger pinkie :r 3.6 :theta 0.59) :hand-loc 'right-home)
(specify-key k 15 6 "left-arrow")
(specify-key k 16 6 "down-arrow")
(specify-key k 17 6 "right-arrow")
(specify-key k 19 6 "keypad-0" :style '(punch :hand right :finger thumb) :hand-loc 'keypad)
(specify-key k 20 6 "keypad-0" :default nil)
(specify-key k 21 6 '("keypad-." "keypad-dot" "keypad-period") :style '(peck-recoil :hand right :finger ring :r 2 :theta 1.57) :hand-loc 'keypad)
(specify-key k 22 6 '("enter" "keypad-enter") :default nil))
(defgeneric other-notifications (keyboard device features)
(:documentation "Called when the default keyboard can't process a notification"))
(defmethod other-notifications ((k virtual-keyboard) device features)
(print-warning "keyboard device can not process notification from device ~s with features ~s." device features))
;;;;;;; shouldn't need to subclass this method
(defmethod specify-key ((k virtual-keyboard) x y names &key (default t) style hand-loc)
(unless (listp names)
(setf names (list names)))
(if (every 'stringp names)
(progn
(dolist (n (mapcar 'string-upcase names))
(when default
(when (gethash n (key->loc-ht k))
(print-warning "Key name ~s already has a location and that is being overwritten." n))
(setf (gethash n (key->loc-ht k)) (vector x y)))
(when (and default (listp style) style)
(when (gethash n (key->cmd-ht k))
(print-warning "Key name ~s already has a press-key entry which is being overwritten." n))
(setf (gethash n (key->cmd-ht k)) style)
(if (and hand-loc (gethash hand-loc (hand-loc-table k)))
(setf (gethash n (key->hand-start-ht k)) hand-loc)
(print-warning "Key name ~s specifies invalid hand location ~s which is being ignored." n hand-loc))))
(awhen (aref (loc->key-arr k) x y)
(print-warning "Keyboard location ~d,~d already has a name ~s which is being overwritten with ~s."
x y it (first names)))
(setf (aref (loc->key-arr k) x y) (first names)))
(print-warning "Invalid key name found in provided names ~s." names)))
;;; create the default keyboard device for models
(defvar *act-r-virtual-keyboard* (make-instance 'virtual-keyboard))
;;; The methods used to get the info out of the keyboard tables.
;;; LOC-TO-KEY [Method]
;;; Description : Given a location, return the corresponding key name.
;;; : Accessed via the 'virtual keyboard' array.
(defgeneric loc->key (vk loc)
(:documentation "Given a location, return the corresponding key"))
(defmethod loc->key ((vk virtual-keyboard) (loc list))
(aref (loc->key-arr vk) (first loc) (second loc)))
(defmethod loc->key ((vk virtual-keyboard) (loc vector))
(aref (loc->key-arr vk) (px loc) (py loc)))
(defgeneric key->cmd (keyboard key)
(:documentation "Given a key, return the appropriate Motor Module command to type it."))
(defmethod key->cmd ((k virtual-keyboard) key)
(gethash (string-upcase key) (key->cmd-ht k)))
(defgeneric key->hand-start (keyboard key)
(:documentation "Given a key, return the expected starting hand location information."))
(defmethod key->hand-start ((k virtual-keyboard) key)
(gethash (gethash (string-upcase key) (key->hand-start-ht k))
(hand-loc-table k)))
(defgeneric key->loc (keyboard key)
(:documentation "Given a key, return the location vector."))
(defmethod key->loc ((vk virtual-keyboard) key)
(gethash (string-upcase key) (key->loc-ht vk)))
(defgeneric keyboard-hand-location (keyboard location-name)
(:documentation "Given a location name, return the list of coordinates for the hand and fingers."))
(defmethod keyboard-hand-location ((vk virtual-keyboard) location)
(gethash location (hand-loc-table vk)))
;; Create the keyboard device and indicate the function to call
;; when a signal is sent to it.
(defun initialize-keyboard (device-list)
(let ((k-c (get-component keyboard-table)))
(if k-c
(let ((k (if (null (third device-list))
(bt:with-lock-held ((keyboard-component-lock k-c))
(let ((k (aif (keyboard-component-default k-c)
(make-instance it)
*act-r-virtual-keyboard*)))
(setf (gethash (current-model) (keyboard-component-table k-c)) k)))
(let ((k-type (string->name (third device-list))))
(if (subtypep k-type 'virtual-keyboard)
(bt:with-lock-held ((keyboard-component-lock k-c))
(setf (gethash (current-model) (keyboard-component-table k-c)) (make-instance k-type)))
(print-warning "Invalid type ~s provided for installing a keyboard." (third device-list)))))))
(when k
(home-hands k)
t))
(print-warning "No keyboard-table component was found when trying to install a keyboard device."))))
(add-act-r-command "initialize-keyboard" 'initialize-keyboard "Function which sets up a keyboard when it is installed. Do not call directly.")
(defun internal-keyboard-interface (device-list features)
(let ((k (current-keyboard)))
(if k
(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 '(punch peck-recoil peck))) ;; default keyboard actions
(aif (loc->key k l)
(with-model-eval m
(schedule-event-now "output-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 normal actions: ~s" features))
(other-notifications k device-list features)))
(print-warning "No keyboard available for current model."))))
(add-act-r-command "keyboard-interface-fn" 'internal-keyboard-interface "Function which receives the signals for the keyboard device. Do not call directly.")
(define-device "keyboard" "initialize-keyboard" nil "keyboard-interface-fn")
;; This is the command that it evaluates for monitoring purposes.
(add-act-r-command "output-key" nil "Command called when a key on the virtual keyboard is pressed by the model or a real key is pressed in a visible experiment window which can be monitored. It is passed 2 parameters: model-name and key-name. Should not be called directly.")
(defun output-key (model key)
(dispatch-apply "output-key" model key))
;; Create some new motor styles. Styles are defined on the motor module, which
;; means these require motor-module methods, and since it's available using that
;; directly for efficiency. However, a device "should" handle actions through
;; notifications to the interface.
;; Create a press-key style which evaluates the underlying action for the indicated
;; key. Doesn't check hand position so if it's not at the home row then the wrong
;; key will likely be pressed.
(defclass press-key (movement-style)
nil
(:default-initargs
:style-name :PRESS-KEY
:feature-slots '(key)))
(defgeneric press-key (mtr-mod &key key request-spec)
(:documentation "High-level interface to press a key: Look up the command and execute it."))
(defmethod press-key ((mtr-mod motor-module) &key key request-spec)
(if (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(aif (current-keyboard)
(progn
(unless (stringp key)
(setf key (princ-to-string key)))
(let ((command (key->cmd it key)))
(if (null (first command))
(print-warning "No press-key mapping available for key ~s." key)
(let* ((hand-index (position :hand command))
(hand-name (nth (1+ hand-index) command))
(position (hand-position hand-name :current nil))
(device (device-for-hand hand-name :current nil)) ;; will it be on the keyboard?
(home (key->hand-start it key)))
(if (string-equal (second device) "keyboard")
(progn
(unless (and home
(= (second (first home)) (px (hand-pos-loc position)))
(= (third (first home)) (py (hand-pos-loc position)))
(every (lambda (x) (awhen (find (first x) (hand-pos-fingers position) :key 'first)
(and (= (px (second it)) (second x))
(= (py (second it)) (third x)))))
(rest home)))
(if home
(print-warning "Hand not at correct starting position for press-key action.")
(print-warning "No starting position available for key ~s for press-key action.")))
(apply (first command) mtr-mod (append (list :request-spec request-spec) (rest command))))
(print-warning "The ~s hand in a press-key action is not on the keyboard. Press-key action ignored." hand-name))))))
(print-warning "Could not find a keyboard to use for the current model. Press-key action ignored."))
(print-warning "No keyboard device installed for motor module. Press-key action ignored.")))
(extend-manual-requests (press-key key) handle-style-request)
(defclass hand-to-home (movement-style)
nil
(:default-initargs
:style-name :POINT-HAND-AT-KEY
:feature-slots '(hand)))
(defgeneric hand-to-home (mtr-mod &key request-spec hand)
(:documentation "Moves a hand to the home row position"))
(defmethod hand-to-home ((mtr-mod motor-module) &key request-spec hand)
(aif (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(let ((k (current-keyboard)))
(when (null hand)
(setf hand 'right))
(if k
(if (or (eq hand 'right) (eq hand 'left))
(let* ((keyboard-hand (if (eq hand 'left)
(keyboard-hand-location k 'left-home)
(keyboard-hand-location k 'right-home)))
(home-pos (coerce (rest (find 'hand keyboard-hand :key 'first)) 'vector))
(polar (xy-to-polar (hand-loc hand :current nil) home-pos))
(hand-pos (hand-position hand :current nil))
(device (device-for-hand hand :current nil)))
(if (and (= (vr polar) 0)
device
(string-equal (second device) "keyboard")
(every (lambda (x) (awhen (find (first x) (hand-pos-fingers hand-pos) :key 'first)
(and (= (px (second it)) (second x))
(= (py (second it)) (third x)))))
(rest keyboard-hand)))
(model-warning "HAND-TO-HOME requested but hand already is (or will be) at the home position.")
(point-hand mtr-mod :hand hand :r (vr polar) :theta (vtheta polar) :twidth 4.0 :device it
:offsets (remove (find 'hand keyboard-hand :key 'first) keyboard-hand)
:request-spec request-spec)))
(print-warning "Invalid hand ~s in hand-to-home." hand))
(print-warning "Invalid keyboard found cannot move hand to home position.")))
(print-warning "Keyboard device is not installed. Cannot move hand to home position.")))
(extend-manual-requests (hand-to-home hand) handle-partial-style-request)
(defgeneric hand-to-keypad (mtr-mod request)
(:documentation "Moves the right hand to the keypad position"))
(defmethod hand-to-keypad ((mtr-mod motor-module) request)
(aif (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(let ((k (current-keyboard)))
(if k
(let* ((keypad-location (keyboard-hand-location k 'keypad))
(keypad-pos (coerce (rest (find 'hand keypad-location :key 'first)) 'vector))
(polar (xy-to-polar (hand-loc 'right :current nil) keypad-pos))
(hand-pos (hand-position 'right :current nil))
(device (device-for-hand 'right :current nil)))
(if (and (= (vr polar) 0)
device
(string-equal (second device) "keyboard")
(every (lambda (x) (awhen (find (first x) (hand-pos-fingers hand-pos) :key 'first)
(and (= (px (second it)) (second x))
(= (py (second it)) (third x)))))
(rest keypad-location)))
(model-warning "HAND-TO-KEYPAD requested but hand already is (or will be) at the keypad position.")
(point-hand mtr-mod :hand 'right :r (vr polar) :theta (vtheta polar) :twidth 4.0 :device it
:offsets (remove (find 'hand keypad-location :key 'first) keypad-location) :request-spec request)))
(print-warning "Invalid keyboard found cannot move right hand to keypad position.")))
(print-warning "Keyboard device is not installed. Cannot move right hand to keypad position.")))
(extend-manual-requests (hand-to-keypad) handle-simple-command-request)
(defclass point-hand-at-key (movement-style)
nil
(:default-initargs
:style-name :POINT-HAND-AT-KEY
:feature-slots '(hand to-key offsets)))
(defgeneric point-hand-at-key (mtr-mod &key hand to-key offsets request-spec)
(:documentation "Move the hand to a new location, specified by the key at which the index finger should point."))
(defmethod point-hand-at-key ((mtr-mod motor-module) &key hand to-key offsets request-spec)
(aif (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(let ((k (current-keyboard)))
(if k
(progn
(unless (stringp to-key)
(setf to-key (princ-to-string to-key)))
(let ((new-loc (key->loc k to-key)))
(if new-loc
(let* ((polar (xy-to-polar (hand-loc hand :current nil) new-loc))
(keyboard-hand (if (eq hand 'left)
(keyboard-hand-location k 'left-home)
(keyboard-hand-location k 'right-home)))
(target-offsets (if (eq offsets 'standard)
(mapcar (lambda (x)
(list (first x) (px (second x)) (py (second x))))
(case hand
(right
(right-standard-offsets))
(left
(left-standard-offsets))))
(if offsets offsets (rest keyboard-hand))))
(hand-pos (hand-position hand :current nil))
(device (device-for-hand hand :current nil)))
(if (and (= (vr polar) 0)
device
(string-equal (second device) "keyboard")
(every (lambda (x) (awhen (find (first x) (hand-pos-fingers hand-pos) :key 'first)
(and (= (px (second it)) (second x))
(= (py (second it)) (third x)))))
target-offsets))
(model-warning "POINT-HAND-AT-KEY requested but hand already is (or will be) at the requested key position.")
(point-hand mtr-mod :hand hand :r (vr polar) :theta (vtheta polar)
:offsets offsets :request-spec request-spec :device it)))
(print-warning "No key mapping available for key ~s. Point-hand-at-key action ignored." to-key))))
(print-warning "Invalid keyboard found cannot move hand to key.")))
(print-warning "No keyboard device installed for motor module. Point-hand-at-key action ignored.")))
(extend-manual-requests (point-hand-at-key hand to-key offsets) handle-partial-style-request)
;;; User actions for the keyboard go through the motor module's notification interface.
;;; HOME-HANDS [Method]
;;; Date : 97.02.20
;;; Description : Sets the hand and finger locations to the keyboard home row.
(defgeneric home-hands (keyboard &optional force-hand-to-device)
(:documentation "Sets the hand and finger locations to home row locations"))
(defmethod home-hands ((k virtual-keyboard) &optional force-hand-to-device)
(let ((device (find "keyboard" (current-devices "motor") :test 'string-equal :key 'second)))
(when (or force-hand-to-device (null (notify-interface "motor" '(get-hand-device right))))
(let* ((r-home (keyboard-hand-location k 'right-home))
(r-pos (find 'hand r-home :key 'first))
(r-fingers (remove r-pos r-home)))
(notify-interface "motor" (list 'set-hand-device 'right device))
(notify-interface "motor" (list 'set-hand-position 'right (second r-pos) (third r-pos)))
(notify-interface "motor" (append (list 'set-finger-offset 'right) r-fingers))))
(when (or force-hand-to-device (null (notify-interface "motor" '(get-hand-device left))))
(let* ((l-home (keyboard-hand-location k 'left-home))
(l-pos (find 'hand l-home :key 'first))
(l-fingers (remove l-pos l-home)))
(notify-interface "motor" (list 'set-hand-device 'left device))
(notify-interface "motor" (list 'set-hand-position 'left (second l-pos) (third l-pos)))
(notify-interface "motor" (append (list 'set-finger-offset 'left) l-fingers))))))
(defun start-hands-at-home ()
"Start the hands on the home row locations"
(verify-current-model
"No current model. Cannot start hands at home positions."
(unless (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(install-device (list "motor" "keyboard"))
(model-warning "Default keyboard device installed automatically by start-hands-at-home"))
(home-hands (current-keyboard) t)
t))
(add-act-r-command "start-hands-at-home" 'start-hands-at-home "Place the model's hands on the home row positions of a keyboard device (installing one if necessary). No params.")
(defun start-hand-at-key (hand key)
"Start a hand on the indicated key instead of the 'home row' location"
(verify-current-model
"No current model. Cannot start hand at key."
(unless (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(install-device (list "motor" "keyboard"))
(model-warning "Default keyboard device installed automatically by start-hand-at-key."))
(let ((k (current-keyboard)))
(unless (stringp key)
(setf key (princ-to-string key)))
(if (or (eq hand 'right) (eq hand 'left))
(aif (key->loc k key)
(progn
(notify-interface "motor" (list 'set-hand-device hand (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)))
(notify-interface "motor" (list 'set-hand-position hand (px it) (py it))))
(print-warning "Invalid key ~s in start-hand-at-key." key))
(print-warning "Invalid hand ~s in start-hand-at-key." hand)))))
(defun external-start-hand-at-key (hand key)
(start-hand-at-key (string->name hand) key))
(add-act-r-command "start-hand-at-key" 'external-start-hand-at-key "Place the model's indicated hand on the keyboard device with the index finger over the named key. Params: hand key-name")
(defun start-hand-at-keypad ()
"Starts the right hand on the keypad instead of the 'home row' location"
(verify-current-model
"No current model. Cannot start hand at key."
(unless (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)
(install-device (list "motor" "keyboard"))
(model-warning "Default keyboard device installed automatically by start-hand-at-keypad."))
(let* ((k (current-keyboard))
(keypad-loc (keyboard-hand-location k 'keypad))
(pos (find 'hand keypad-loc :key 'first))
(fingers (remove pos keypad-loc)))
(notify-interface "motor" (list 'set-hand-device 'right (find "keyboard" (current-devices "motor") :key 'second :test 'string-equal)))
(notify-interface "motor" (list 'set-hand-position 'right (second pos) (third pos)))
(notify-interface "motor" (append (list 'set-finger-offset 'right) fingers)))))
(add-act-r-command "start-hand-at-keypad" 'start-hand-at-keypad "Place the model's right hand on middle row of the keyboard device's keypad area. No params.")
;;;;;; Create a component for recording the keyboards for each model
(defun clear-keyboard-component (keyboard-component)
(bt:with-lock-held ((keyboard-component-lock keyboard-component))
(clrhash (keyboard-component-table keyboard-component))))
(defun remove-model-keyboard (k-c model)
(bt:with-lock-held ((keyboard-component-lock k-c))
(remhash model (keyboard-component-table k-c))))
(defun set-default-keyboard (class)
(let ((k-c (get-component keyboard-table)))
(if k-c
(if (or (null class) (subtypep class 'virtual-keyboard))
(progn
(bt:with-lock-held ((keyboard-component-lock k-c))
(setf (keyboard-component-default k-c) class))
t)
(print-warning "Set-default-keyboard requires nil or a subclass of virtual-keyboard but given ~s." class))
(print-warning "No keyboard-table component found when calling set-default-keyboard."))))
(defun current-keyboard ()
(awhen (current-model)
(let ((k-c (get-component keyboard-table)))
(when k-c
(bt:with-lock-held ((keyboard-component-lock k-c))
(gethash it (keyboard-component-table k-c)))))))
(define-component keyboard-table :version "3.1" :documentation "Record the keyboards used for each model."
:creation make-keyboard-component
:clear-all clear-keyboard-component
:delete clear-keyboard-component
:delete-model remove-model-keyboard)
#|
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
|# | 46,926 | Common Lisp | .lisp | 696 | 58.173851 | 277 | 0.605665 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6070761d6579bd071143be77eece27411ce40057c2500dbe9f4b493b0d65657d | 14,143 | [
-1
] |
14,144 | system-param-init.lisp | asmaloney_ACT-R/other-files/system-param-init.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 : system-param-init.lisp
;;; Version : 1.0
;;;
;;; Description : Create system parameters that need to reference/use modules
;;; : that aren't available when the code that uses the parameter is
;;; : loaded.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2013.07.31 Dan [1.0]
;;; : * Create the safe-perceptual-buffers parameter here.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; This file provides a place for creating system parameters that have to wait
;;; for other things to be loaded/defined first.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; Nothing, other than the parameters which get defined here, and those are
;;; probably going to be described elsewhere.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
(create-system-parameter :safe-perceptual-buffers
:valid-test (lambda (x)
(and (listp x)
(every (lambda (y)
(find y (buffers)))
x)))
:default-value '(temporal visual-location aural-location)
:warning "a list of buffer names"
:documentation "Perceptual buffers that shouldn't show a style warning when requested without a query"
:handler (simple-system-param-handler *safe-perceptual-buffers*))
#|
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,413 | Common Lisp | .lisp | 78 | 38.474359 | 127 | 0.494443 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 067cb93a6cda6f47d5b9c095c85d831c48819385c88f282b2f58621c24e1fb5d | 14,144 | [
-1
] |
14,145 | mouse.lisp | asmaloney_ACT-R/other-files/mouse.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 : mouse.lisp
;;; Version : 4.0
;;;
;;; Description : Implements a mouse device.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2017.03.02 Dan [1.0]
;;; : * First pass at separating the mouse from the internals of the
;;; : motor module and device-interface as was done for the keyboard.
;;; 2017.03.07 Dan
;;; : * Moved the start-hand-at-mouse command here.
;;; 2017.03.08 Dan
;;; : * The virtual-cursor class isn't something that can be assumed
;;; : by the motor module because that couldn't be provided by an
;;; : external cursor. Instead the cursor has to respond to a
;;; : bunch of signals for that info.
;;; 2017.03.10 Dan
;;; : * Added a remote start-hand-at-mouse command.
;;; 2017.06.08 Dan
;;; : * Initialize-mouse needs to return a true value.
;;; 2017.08.10 Dan [2.0]
;;; : * Like the keyboard, install a component to handle the mouse
;;; : table instead of using a global variable. Now, keep old
;;; : mouse items around and reuse them when switching windows.
;;; 2017.08.17 Dan
;;; : * Start-hand-at-mouse needs to speicify a list when creating
;;; : a default mouse.
;;; 2017.08.23 Dan
;;; : * Don't need the dummy functions for the actions now.
;;; 2018.01.29 Dan
;;; : * Fixed a bug with start-hand-at-mouse because it was assuming
;;; : that the mouse was associated with a visual interface, but
;;; : the one it creates by default is not.
;;; : * Remove-mouse needs to return t to indicate successful removal.
;;; 2018.03.05 Dan
;;; : * Signal-device was renamed to notify-device.
;;; 2018.03.06 Dan [3.0]
;;; : * Reworking it so that it's one mouse per model -- not per
;;; : window which has issues with models sharing a window.
;;; : * Also, reset the mouse positions upon init instead of letting
;;; : them stay where they were.
;;; 2018.03.07 Dan
;;; : * Don't directly communicate with the exp-windows. Instead
;;; : create some signals for init, move, click, and remove.
;;; 2018.03.08 Dan
;;; : * Reworking it yet again after some work on the move-cursor
;;; : request from motor. Actually install a "cursor" and have
;;; : the details indicate whether it's a mouse, joystick1, or
;;; : joystick2 which is then created.
;;; : * Also, don't need the device-hand -- the hand knows where it
;;; : is so don't need to consult the device!
;;; 2018.03.13 Dan
;;; : * Interface fns now get the whole device list and allow a cursor
;;; : to be installed for vision or motor! When installed for vision
;;; : it creates a feature in global coordinates.
;;; 2018.03.16 Dan
;;; : * Warn if start-hand-at-mouse called with :needs-mouse nil.
;;; 2018.03.29 Dan
;;; : * Don't need to ignore a variable in init-cursor-chunk-type-and-chunks
;;; : since it isn't passed in anymore.
;;; 2018.04.26 Dan
;;; : * Only need to create the cursor chunk-type if it doesn't
;;; : already exist.
;;; 2018.05.22 Dan
;;; : * Update the calls to add-visicon-features since the syntax of
;;; : that has changed.
;;; 2018.06.04 Dan
;;; : * Moved set-cursor-position here from the motor module, fixed a
;;; : bug in it, and added remote versions.
;;; 2018.06.13 Dan
;;; : * Set the cursor-pos slots to lists instead of vectors since
;;; : set-hand-location uses lists now too.
;;; 2018.07.26 Dan [3.1]
;;; : * Don't worry about completing requests.
;;; 2018.10.09 Dan [3.2]
;;; : * Removed some unnecessary tests for motor module in top level
;;; : commands.
;;; : * Allow for user defined cursors in the same way as keyboards,
;;; : and add a set-default-cursor and other-notifications method.
;;; : * Allow for custom initialization and don't require install
;;; : to only be for motor and vision interfaces.
;;; 2018.10.10 Dan
;;; : * Instead of setting the default cursor, change it to set-default-mouse
;;; : since the AGI automatically installs a mouse, and that's
;;; : likely the cursor which will be used most often. So, it
;;; : changes the class used when "mouse" is specified.
;;; 2018.10.11 Dan
;;; : * Fixed click-mouse because it was accessing the device of a
;;; : hand without grabbing the lock.
;;; 2018.10.12 Dan
;;; : * Because the type of the "mouse" cursor can change need to
;;; : make sure it's always referenced by 'mouse in the table.
;;; 2019.09.30 Dan
;;; : * Can't allow it to default to a mouse cursor when no detail
;;; : is given because motor then records a device with no detail
;;; : which breaks when something like start-hand-at-mouse checks
;;; : to see if there is a mouse installed.
;;; : * Don't check :needs-mouse for start-hand-at-mouse since it
;;; : already installs a device if needed anyway.
;;; : * Added start-hand-at-joystick1/2 command and hand-to-joystick1/2
;;; : motor actions.
;;; 2019.10.01 Dan [3.3]
;;; : * Always represent cursor positions with three coordinates, and
;;; : use default viewing distance when not provided.
;;; : * Added a click-cursor signal for when it's not a mouse cursor.
;;; : * Use the cursor name for the scheduled event module label
;;; : instead of always using mouse.
;;; : * Set-cursor-position now takes an optional z parameter and
;;; : set-cursor-position-fct can take a 2 or 3 element list as
;;; : the first parameter.
;;; 2020.03.27 Dan [4.0]
;;; : * Fixed bug in external-set-cursor-position because it did not
;;; : include the z parameter.
;;; : * Use the updated hand and device calls to get positions since
;;; : it needs to take into account the pending actions to get the
;;; : features correct.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Create a cursor as its own device under the new interface approach which can
;;; be a mouse, joystick1, or joystick2, and make an instance of an appropriate
;;; cursor device with which a model can interact.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Extend by providing a new class and use that class name as the details.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
;;; The class for a virtual cursor and the provided cursors.
;;; Subclass this to create a custom cursor with the appropriate
;;; values and define a cursor-initialization and other-notifications methods
;;; if needed.
(defclass virtual-cursor ()
((cursor-lock :accessor cursor-lock :initform (bt:make-lock "virtual-cursor"))
(cursor-loc :accessor cursor-loc :initform (list 0 0) :initarg :cursor-loc)
(cursor-pos :accessor cursor-pos :initform (list 0 0) :initarg :cursor-pos)
(initial-loc :accessor initial-loc :initform (list 0 0) :initarg :initial-loc)
(cursor-feature :accessor cursor-feature :initform nil)
(cursor-ptr :accessor cursor-ptr :initform 'pointer)
(cursor-name :accessor cursor-name :initarg :cursor-name)
(cursor-vis-type :accessor cursor-vis-type :initform 'cursor :initarg :cursor-vis-type)
(device-order :accessor device-order :initform 0 :initarg :device-order)
(interfaces :accessor interfaces :initform nil)))
(defclass mouse (virtual-cursor)
()
(:default-initargs
:cursor-name "mouse"
:cursor-pos (list 28 2)))
(defclass joystick1 (virtual-cursor)
()
(:default-initargs
:cursor-name "joystick1"
:cursor-pos (list 28 0)
:device-order 1))
(defclass joystick2 (virtual-cursor)
()
(:default-initargs
:cursor-name "joystick2"
:cursor-pos (list 28 4)
:device-order 2))
(defmethod cursor-initialization ((c virtual-cursor) device)
(declare (ignore device)))
(defmethod other-notifications ((c virtual-cursor) device features)
(print-warning "Cursor device can not process notification from device ~s with features ~s." device features))
(defun default-cursor-distance ()
(round (apply '* (no-output (sgp :viewing-distance :pixels-per-inch)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The cursor device definition
(defun initialize-cursor (device-list)
(let* ((model (current-model))
(interface-name (first device-list))
(details (string->name (third device-list)))
(class (cond ((eq details 'mouse)
(default-cursor-class))
(t details))))
;; can't allow no details to default to mouse because
;; that results in problems with things that check/reference
;; the installed devices for a mouse cursor.
(when (null details)
(print-warning "Cannot install a cursor without specifying the type.")
(return-from initialize-cursor nil))
(unless (subtypep class 'virtual-cursor)
(print-warning "Invalid cursor type ~s provided for installing a cursor." device-list)
(return-from initialize-cursor nil))
(let* ((key (list model details))
(cursor (find-model-cursor key)))
(if cursor
(if (find interface-name (bt:with-lock-held ((cursor-lock cursor)) (interfaces cursor)) :test 'string-equal)
(print-warning "Cursor ~s already installed for the interface ~s in model ~s and only one is allowed." details interface-name model)
(progn
(bt:with-lock-held ((cursor-lock cursor))
(push interface-name (interfaces cursor))
(when (= (length (initial-loc cursor)) 2)
(push-last (default-cursor-distance) (initial-loc cursor)))
(setf (cursor-loc cursor) (initial-loc cursor)))
;; initialization: custom, then default
(cursor-initialization cursor device-list)
(when (string-equal interface-name "vision")
(bt:with-lock-held ((cursor-lock cursor))
(setf (cursor-feature cursor)
(first (add-visicon-features `(isa (visual-location ,(cursor-vis-type cursor))
value ,(cursor-name cursor)
screen-x ,(px (cursor-loc cursor))
screen-y ,(py (cursor-loc cursor))
distance ,(pz (cursor-loc cursor))))))))
t))
(progn
(setf cursor (make-instance class))
(init-cursor-chunk-types-and-chunks (cursor-name cursor))
(bt:with-lock-held ((cursor-lock cursor))
(push interface-name (interfaces cursor))
(when (= (length (initial-loc cursor)) 2)
(push-last (default-cursor-distance) (initial-loc cursor)))
(setf (cursor-loc cursor) (initial-loc cursor)))
(add-cursor key cursor)
;; custom initialization if needed
(cursor-initialization cursor device-list)
;; signal movement to initial position
(evaluate-act-r-command "move-cursor" model (cursor-name cursor) (initial-loc cursor))
;; default initialization
(when (string-equal interface-name "vision")
(bt:with-lock-held ((cursor-lock cursor))
(setf (cursor-feature cursor)
(first (add-visicon-features `(isa (visual-location ,(cursor-vis-type cursor))
value ,(cursor-name cursor)
screen-x ,(px (initial-loc cursor))
screen-y ,(py (initial-loc cursor))
distance ,(pz (cursor-loc cursor))))))))
t)))))
(add-act-r-command "initialize-cursor" 'initialize-cursor "Function which sets up a cursor when it is installed. Do not call directly.")
(defun uninstall-cursor (device-list)
(let* ((model (current-model))
(interface-name (first device-list))
(details (aif (string->name (third device-list)) it 'mouse))
(key (list model details))
(cursor (find-model-cursor key)))
;; If it's not in the table or not on the interface list then just ignore it and call
;; it a success anyway -- shouldn't have gotten here if
;; it wasn't installed...
(when cursor
(bt:with-lock-held ((cursor-lock cursor))
(when (find interface-name (interfaces cursor) :test 'string-equal)
(setf (interfaces cursor) (remove interface-name (interfaces cursor) :test 'string-equal))
(when (string-equal interface-name "vision")
(when (cursor-feature cursor)
(delete-visicon-features (cursor-feature cursor))
(setf (cursor-feature cursor) nil)))
(when (null (interfaces cursor))
(evaluate-act-r-command "delete-cursor" model (cursor-name cursor))
(remove-cursor key)))))
t))
(add-act-r-command "uninstall-cursor" 'uninstall-cursor "Function which cleans up a cursor being uninstalled. Do not call directly.")
(defun internal-cursor-interface (device-list features)
(let* ((model (current-model))
(details (string->name (third device-list)))
(key (list model details))
(cursor (find-model-cursor key)))
(if (not cursor)
(print-warning "Notice sent to cursor ~s but no such cursor could be found for model ~s." device-list model)
(progn
;; The possible signals we'll get are:
;; ((model <>) (style {punch | peck | peck-recoil}) (hand {left | right}) (loc (x,y,{z})))
;; - which indicates a button press
;;
;; ((model <>) (style move-cursor) (hand {left | right}) (loc (x,y,{z})))
;;
;; (set-position x y {z})
;;
;; (current-position)
;;
;; (device-location)
;;
;; (control-order)
;;
;; Do we care where they came from?
;; For now doesn't matter which interface, but may want to
;; change that at some point.
(cond ((eq (first features) 'current-position)
(bt:with-lock-held ((cursor-lock cursor))
(cursor-loc cursor)))
((eq (first features) 'device-location)
(bt:with-lock-held ((cursor-lock cursor))
(coerce (cursor-pos cursor) 'list)))
((eq (first features) 'control-order)
(bt:with-lock-held ((cursor-lock cursor))
(device-order cursor)))
((eq (first features) 'set-position)
(bt:with-lock-held ((cursor-lock cursor))
(setf (cursor-loc cursor)
(list (second features) (third features) (aif (fourth features) it (default-cursor-distance))))
(when (cursor-feature cursor)
(modify-visicon-features (list (cursor-feature cursor) 'screen-x (second features) 'screen-y (third features) 'distance (aif (fourth features) it (default-cursor-distance)))))
(evaluate-act-r-command "move-cursor" model (cursor-name cursor) (cursor-loc cursor))
(cursor-loc cursor)))
(t
(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 '(punch peck peck-recoil move-cursor))) ;; the default notifications
(case s
((punch peck peck-recoil)
(let (mx my xyz)
(bt:with-lock-held ((cursor-lock cursor))
(setf mx (px (cursor-pos cursor))
my (py (cursor-pos cursor))
xyz (cursor-loc cursor)))
(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 ~s cursor click finger position ~s." details l)))))
(when f
;; Is this necessary? shouldn't it always be in the right model?
(with-model-eval m
(if (eq details 'mouse)
(schedule-event-now "click-mouse" :params (list m xyz f) :maintenance t :module 'mouse)
(schedule-event-now "click-cursor" :params (list m (cursor-name cursor) xyz f) :maintenance t :module details))
)))))
(move-cursor
(bt:with-lock-held ((cursor-lock cursor))
(when (= (length l) 2)
(push-last (default-cursor-distance) l))
(setf (cursor-loc cursor) l)
(when (cursor-feature cursor)
(modify-visicon-features (list (cursor-feature cursor) 'screen-x (first l) 'screen-y (second l) 'distance (third l)))))
(with-model-eval m
(schedule-event-now "move-cursor" :params (list m (cursor-name cursor) l) :maintenance t :module details))))
(other-notifications cursor device-list features)))))))))
(add-act-r-command "cursor-interface-fn" 'internal-cursor-interface "Function which receives the signals for all the cursor devices. Do not call directly.")
(define-device "cursor" "initialize-cursor" "uninstall-cursor" "cursor-interface-fn")
;; These are the commands that it evaluates for monitoring purposes.
(add-act-r-command "click-mouse" nil "Command called when a finger presses a button on the virtual mouse or a real mouse click occurs on a visible exp-window which can be monitored. It is passed 3 parameters: model name, location list, and finger name. Should not be called directly.")
(add-act-r-command "click-cursor" nil "Command called when a finger presses a button on a non-mouse cursor which can be monitored. It is passed 4 parameters: model name, cursor name, location list, and finger name. Should not be called directly.")
(add-act-r-command "move-cursor" nil "Command called when a virtual cursor is moved which can be monitored. It is passed 3 parameters: model name, cursor name, and a list of the new x, y, z position. Should not be called directly.")
(add-act-r-command "delete-cursor" nil "Command called when the virtual cursor is uninstalled which can be monitored. It is passed 2 parameters: model name and cursor name. Should not be called directly.")
;; this is needed for real windows to call
(defun click-the-mouse (model location finger)
(handle-evaluate-results (evaluate-act-r-command "click-mouse" model location finger)))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Additional motor actions for a mouse because the general move-cursor
;;;; is used to move it around. Because these are handled by the internal
;;;; extension commands they get passed the motor module so use it instead
;;;; of interface notifications.
;;; CLICK-MOUSE [Method]
;;; Date : 97.02.13
;;; Description : Clicking the mouse is really just a punch with the index finger.
(defgeneric click-mouse (mtr-mod request)
(:documentation "Execute a mouse click operation (a punch with the right hand index finger)"))
(defmethod click-mouse ((mtr-mod motor-module) request)
(let* ((model (current-model))
(mouse (find-model-cursor (list model 'mouse))))
(if mouse
(let ((device (device-for-hand 'right :current nil)))
(if (equalp device (list "motor" "cursor" "mouse"))
(punch mtr-mod :hand 'right :finger 'index :request-spec request)
(model-warning "CLICK-MOUSE requested when hand not at mouse!")))
(model-warning "CLICK-MOUSE requested but no mouse device available."))))
(extend-manual-requests (click-mouse) handle-simple-command-request)
(defgeneric hand-to-cursor (mtr-mod request cursor)
(:documentation "Moves the right hand to the indicated cursor"))
(defmethod hand-to-cursor ((mtr-mod motor-module) request cursor)
(cond ((find (list "motor" "cursor" cursor) (current-devices "motor") :test 'equalp)
(let* ((c (find-model-cursor (list (current-model) (string->name cursor))))
(c-pos (bt:with-lock-held ((cursor-lock c)) (cursor-pos c)))
(h-pos (hand-loc 'right :current nil))
(device (device-for-hand 'right :current nil)))
(if (and (vpt= c-pos h-pos)
(equalp device (list "motor" "cursor" cursor)))
(model-warning "HAND-TO-~:@(~a~) requested but hand already is (or will be) at the ~a device." cursor cursor)
(let ((polar (xy-to-polar h-pos c-pos)))
(point-hand mtr-mod :hand 'right :r (vr polar) :theta (vtheta polar) :twidth 4.0
:device (list "motor" "cursor" cursor)
:offsets 'standard :request-spec request)))))
(t
(model-warning "HAND-TO-~a requested but no ~a device available." cursor cursor))))
(defgeneric hand-to-mouse (mtr-mod request)
(:documentation "Moves the right hand to the mouse"))
(defmethod hand-to-mouse ((mtr-mod motor-module) request)
(hand-to-cursor mtr-mod request "mouse"))
(extend-manual-requests (hand-to-mouse) handle-simple-command-request)
(defgeneric hand-to-joystick1 (mtr-mod request)
(:documentation "Moves the right hand to the joystick1 cursor"))
(defmethod hand-to-joystick1 ((mtr-mod motor-module) request)
(hand-to-cursor mtr-mod request "joystick1"))
(extend-manual-requests (hand-to-joystick1) handle-simple-command-request)
(defgeneric hand-to-joystick2 (mtr-mod request)
(:documentation "Moves the right hand to the joystick2 cursor"))
(defmethod hand-to-joystick2 ((mtr-mod motor-module) request)
(hand-to-cursor mtr-mod request "joystick2"))
(extend-manual-requests (hand-to-joystick2) handle-simple-command-request)
;;; Top level commands
;;; use the notifications or available commands for these instead of the motor
;;; module itself.
(defun start-hand-at-cursor (cursor)
"Starts the right hand on the indicated cursor instead of the 'home row' location"
(verify-current-model
(format nil "No current model. Cannot set hand at ~a." cursor)
(unless (find (list "motor" "cursor" cursor) (current-devices "motor") :test 'equalp)
(model-warning "Installing a default ~a because of start-hand-at-~a." cursor cursor)
(unless (install-device (list "motor" "cursor" cursor))
(model-warning "Could not install a ~a cursor for the motor interface." cursor)
(return-from start-hand-at-cursor nil)))
(let ((c (find-model-cursor (list (current-model) (string->name cursor)))))
(set-hand-location-fct 'right (bt:with-lock-held ((cursor-lock c))(cursor-pos c)) (list "motor" "cursor" cursor))
t)))
(defun start-hand-at-mouse ()
(start-hand-at-cursor "mouse"))
(add-act-r-command "start-hand-at-mouse" 'start-hand-at-mouse "Have the model place its right hand on the mouse before running. No parameters")
(defun start-hand-at-joystick1 ()
(start-hand-at-cursor "joystick1"))
(add-act-r-command "start-hand-at-joystick1" 'start-hand-at-joystick1 "Have the model place its right hand on the joystick1 cursor before running. No parameters")
(defun start-hand-at-joystick2 ()
(start-hand-at-cursor "joystick2"))
(add-act-r-command "start-hand-at-joystick2" 'start-hand-at-joystick2 "Have the model place its right hand on the joystick2 cursor before running. No parameters")
(defmacro set-cursor-position (x y &optional z (cursor-name "mouse"))
"Sets the position of the cursor."
`(if ,(numberp z)
(set-cursor-position-fct ',(list x y z) ,cursor-name)
(set-cursor-position-fct ',(list x y (default-cursor-distance)) ,cursor-name)))
(defun set-cursor-position-fct (xyloc &optional (cursor-name "mouse"))
(verify-current-model
"No current model. Cannot set cursor position."
(if (and (or (listp xyloc) (vectorp xyloc))
(<= 2 (length xyloc) 3))
(progn
(when (= (length xyloc) 2)
(if (listp xyloc)
(push-last (default-cursor-distance) xyloc)
(setf xyloc (list (px xyloc) (py xyloc) (default-cursor-distance)))))
(if (find (list "motor" "cursor" cursor-name) (current-devices "motor") :test 'equalp)
(let ((result (notify-device (list "motor" "cursor" cursor-name) (list 'set-position (elt xyloc 0) (elt xyloc 1) (elt xyloc 2)))))
(if result
result
(print-warning "Failed to set the position ~s for cursor ~s." xyloc cursor-name)))
(print-warning "No cursor device named ~s is currently installed for the motor interface." cursor-name)))
(print-warning "Location for set-cursor-position-fct must be a list of two or three values but ~s provided." xyloc))))
(defun external-set-cursor-position (x y &optional z (cursor-name "mouse"))
(if (numberp z)
(set-cursor-position-fct (list x y z) cursor-name)
(set-cursor-position-fct (list x y) cursor-name)))
(add-act-r-command "set-cursor-position" 'external-set-cursor-position "Set the position of the named virtual cursor. Params: x-pos y-pos {z-pos {cursor-name}}")
(add-act-r-command "set-cursor-position-fct" 'set-cursor-position-fct "Set the position of the named virtual cursor. Params: (x-pos y-pos {z-pos}) {cursor-name}")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Create a component for recording the cursor devices which are created
;;; as needed.
(defstruct cursor-component (lock (bt:make-lock "cursor-component")) (table (make-hash-table :test 'equalp)) (default 'mouse))
(defun set-default-mouse (class)
(let ((c-c (get-component cursor-table)))
(if c-c
(cond ((null class)
(progn
(bt:with-lock-held ((cursor-component-lock c-c))
(setf (cursor-component-default c-c) 'mouse))
t))
((subtypep class 'virtual-cursor)
(progn
(bt:with-lock-held ((cursor-component-lock c-c))
(setf (cursor-component-default c-c) class))
t))
(t
(print-warning "Set-default-mouse requires nil or a subclass of virtual-cursor but given ~s." class)))
(print-warning "No cursor-table component found when calling set-default-mouse."))))
(defun clear-cursor-component (cursor-component)
(bt:with-lock-held ((cursor-component-lock cursor-component))
(clrhash (cursor-component-table cursor-component))))
(defun init-cursor-chunk-types-and-chunks (name)
(when (and (chunk-type-p visual-object)
(not (chunk-type-p cursor)))
(chunk-type (cursor (:include visual-object)) (cursor t)))
(when (stringp name)
(setf name (string->name name)))
(unless (chunk-p cursor)
(define-chunks cursor)
(make-chunk-immutable 'cursor))
(unless (chunk-p-fct name)
(define-chunks-fct (list name))
(make-chunk-immutable name)))
(define-component cursor-table :version "4.0" :documentation "Record the cursor devices that are used."
:creation make-cursor-component
:clear-all clear-cursor-component
:delete clear-cursor-component
:before-reset clear-cursor-component)
;; Accessors for cursor component table
(defun find-model-cursor (key)
(let ((m-c (get-component cursor-table)))
(when m-c
(bt:with-lock-held ((cursor-component-lock m-c))
(gethash key (cursor-component-table m-c))))))
(defun add-cursor (key cursor)
(let ((m-c (get-component cursor-table)))
(when m-c
(bt:with-lock-held ((cursor-component-lock m-c))
(setf (gethash key (cursor-component-table m-c)) cursor)))))
(defun remove-cursor (key)
(let ((m-c (get-component cursor-table)))
(when m-c
(bt:with-lock-held ((cursor-component-lock m-c))
(remhash key (cursor-component-table m-c))))))
(defun default-cursor-class ()
(let ((m-c (get-component cursor-table)))
(when m-c
(bt:with-lock-held ((cursor-component-lock m-c))
(cursor-component-default m-c)))))
#|
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
|#
| 32,201 | Common Lisp | .lisp | 558 | 48.738351 | 286 | 0.593752 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0bbdcd06e5b06eda2199f40dd84239a9e76ed0a4fe8b95b87b273e342cc22343 | 14,145 | [
-1
] |
14,146 | retrieval-history.lisp | asmaloney_ACT-R/other-files/retrieval-history.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 : retrieval-history.lisp
;;; Version : 2.1
;;;
;;; Description : Code to record retrieval history data.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2008.08.14 Dan
;;; : * Initial creation.
;;; 2011.06.22 Dan [1.1]
;;; : * Added another pane to the display which shows the activation
;;; : trace information as saved with the new :sact parameter.
;;; 2012.02.08 Dan
;;; : * Added checks so that trying to get information from an old
;;; : display no longer throws an error.
;;; 2012.02.09 Dan
;;; : * Explicitly close streams made with make-string-output-stream
;;; : to be safe.
;;; 2012.03.21 Dan
;;; : * Use with-parameters instead of saving and setting :cmdt
;;; : explicitly.
;;; 2012.03.27 Dan
;;; : * Fixed dm-history-chunk-display so that it doesn't show
;;; : "History no longer available" when there was a failure.
;;; 2015.05.05 Dan
;;; : * Added a suppress-warnings to the recording of the sdp info
;;; : in dm-retrieval-set-recorder since there might be issues
;;; : with negative Sjis that don't matter in the actual model
;;; : so don't want to see those warnings from the recorder.
;;; 2015.06.09 Dan
;;; : * Record time in ms internally, but still show seconds to the
;;; : user in the list.
;;; 2016.04.22 Dan
;;; : * Start of the work to support the new history tools that
;;; : allow saving data and then displaying that saved data.
;;; : * Now also turn on :sact automatically with :save-dm-history.
;;; 2016.04.28 Dan
;;; : * Use the key from the environment to access the appropriate
;;; : underlying data source.
;;; 2017.08.09 Dan
;;; : * Replacing calls to capture-model-output with the corresponding
;;; : direct output capture functions: printed-chunk-spec, printed-chunk,
;;; : and printed-chunk-activation-trace.
;;; 2017.09.22 Dan [2.0]
;;; : * Making this a history stream and eliminating the parameter
;;; : for enabling it.
;;; 2018.04.18 Dan
;;; : * Adding an optional parameter for the history stream to allow
;;; : getting a single request's data.
;;; 2018.04.27 Dan
;;; : * Moved the retrieval-times processor for the history here.
;;; 2020.01.13 Dan [2.1]
;;; : * Removed the lambdas from the module interface.
;;; : * Use the (:remove <>) option for the hook functions.
;;; 2020.08.27 Dan
;;; : * Switch from (no-output (sgp ...)) to get-parameter and cast
;;; : the result as a real to avoid a warning in SBCL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
(defstruct dm-history-module
history
(lock (bt:make-lock "dm-history-module"))
(alive t))
(defstruct dm-history
time
request
chunks
chunk-texts
params
activation-trace)
(defun dm-request-recorder (request)
(let ((history (get-module retrieval-history))
(block (make-dm-history :time (mp-time-ms) :request (printed-chunk-spec request))))
(bt:with-lock-held ((dm-history-module-lock history))
(push block (dm-history-module-history history))
nil)))
(defun dm-retrieval-set-recorder (set)
(let ((history (get-module retrieval-history))
(best (car set)))
(bt:with-lock-held ((dm-history-module-lock history))
(let ((record (car (dm-history-module-history history))))
(cond ((null set)
(setf (dm-history-chunks record) (list :retrieval-failure)))
((and best (get-parameter-value :esc)
(let ((a (no-output (caar (sdp-fct (list best :last-retrieval-activation))))))
(when (numberp a) ;; will always be true, but testing to avoid an SBCL compiler warning
(< a (the real (get-parameter-value :rt))))))
(setf (dm-history-chunks record) (cons :retrieval-failure set)))
(t
(setf (dm-history-chunks record) set)))
(dolist (x (dm-history-chunks record))
(if (eq x :retrieval-failure)
(progn
(push-last "" (dm-history-chunk-texts record))
(push-last "" (dm-history-activation-trace record))
(push-last "" (dm-history-params record)))
(progn
(push-last (printed-chunk x) (dm-history-chunk-texts record))
(push-last (printed-chunk-activation-trace x (mp-time-ms) t)
(dm-history-activation-trace record))
(let ((s (suppress-warnings (capture-command-output (sdp-fct (list x))))))
(push-last s (dm-history-params record)))))))))
nil)
(defun reset-dm-history-module (module)
(bt:with-lock-held ((dm-history-module-lock module))
(setf (dm-history-module-history module) nil)))
(defun delete-dm-history-module (module)
(bt:with-lock-held ((dm-history-module-lock module))
(setf (dm-history-module-alive module) nil)))
(defun enable-retrieval-history ()
(no-output
(unless (find 'dm-request-recorder (car (sgp :retrieval-request-hook)))
(sgp :retrieval-request-hook dm-request-recorder))
(unless (find 'dm-retrieval-set-recorder (car (sgp :retrieval-set-hook)))
(sgp :retrieval-set-hook dm-retrieval-set-recorder))
(unless (car (sgp :sact))
(sgp :sact t))))
(defun disable-retrieval-history ()
(no-output
(let ((current-hooks (car (sgp :retrieval-request-hook))))
(when (find 'dm-request-recorder current-hooks)
(sgp :retrieval-request-hook (:remove dm-request-recorder)))
(setf current-hooks (car (sgp :retrieval-set-hook)))
(when (find 'dm-retrieval-set-recorder current-hooks)
(sgp :retrieval-set-hook (:remove dm-retrieval-set-recorder))))))
(defun retrieval-history-status (&optional time)
(let ((m (get-module retrieval-history)))
(if m
(bt:with-lock-held ((dm-history-module-lock m))
(no-output
(values
(and (car (sgp :sact))
(find 'dm-request-recorder (car (sgp :retrieval-request-hook)))
(find 'dm-retrieval-set-recorder (car (sgp :retrieval-set-hook)))
t)
(if (numberp time)
(when (find time (dm-history-module-history m) :key 'dm-history-time) t)
(when (dm-history-module-history m) t))
(dm-history-module-alive m))))
(values nil nil nil))))
(defun create-retrieval-history-module (x)
(declare (ignore x))
(make-dm-history-module))
(define-module-fct 'retrieval-history nil nil
:creation 'create-retrieval-history-module
:reset 'reset-dm-history-module
:delete 'delete-dm-history-module
:version "2.1"
:documentation "Module to record retrieval history data.")
(defun get-retrieval-history (&optional time)
(let ((m (get-module retrieval-history)))
(when m
(bt:with-lock-held ((dm-history-module-lock m))
(if (numberp time)
(awhen (find time (dm-history-module-history m) :key 'dm-history-time)
(list (list (dm-history-time it)
(dm-history-request it)
(mapcar 'list
(dm-history-chunks it)
(dm-history-chunk-texts it)
(dm-history-params it)
(dm-history-activation-trace it)))))
(mapcar (lambda (x)
(list (dm-history-time x)
(dm-history-request x)
(mapcar 'list
(dm-history-chunks x)
(dm-history-chunk-texts x)
(dm-history-params x)
(dm-history-activation-trace x))))
(reverse (dm-history-module-history m))))))))
(define-history "retrieval-history" enable-retrieval-history disable-retrieval-history retrieval-history-status get-retrieval-history t)
(defun retrieval-times (history)
(let ((data (json::decode-json-from-string history)))
(mapcar (lambda (x)
(list (first x)
(mapcar 'car (third x))))
data)))
(define-history-processor "retrieval-history" "retrieval-times" retrieval-times)
#|
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
|#
| 10,787 | Common Lisp | .lisp | 230 | 39.569565 | 137 | 0.552494 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 14f9f57406aa4a67cdf2d48c12e96853aad6c958c2752ca7c6d1289248facd11 | 14,146 | [
-1
] |
14,147 | production-history.lisp | asmaloney_ACT-R/other-files/production-history.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 : production-history.lisp
;;; Version : 2.1
;;;
;;; Description : Code to support the production trace tool in the environment.
;;;
;;; Bugs :
;;;
;;; To do : [X] Consider making a module for this to allow configuration
;;; : of the display (colors, widths, restricted productions,
;;; : etc) and provide a simple parameter switch to enable.
;;; : [ ] Draw the links "better" with respect to crossing and
;;; : overlapping.
;;;
;;; ----- History -----
;;; 2008.08.06 Dan
;;; : * Initial creation.
;;; 2008.08.06 Dan
;;; : * Making it a module and doing some optimizing on how it
;;; : stores/creates the data to send because it can't handle
;;; : long runs (zbrodoff tutorial model often results in an
;;; : allocation error).
;;; 2008.08.07 Dan
;;; : * Another stability improvement. It now breaks the grid
;;; : up into smaller updates to send over to the environment
;;; : to avoid having to create one very large string. Slows
;;; : down the displaying, but shouldn't result in any allocation
;;; : issues.
;;; 2008.08.12 Dan
;;; : * Added the :p-history-colors parameter to allow one to
;;; : change the colors used in the grid.
;;; 2011.10.28 Dan [1.1]
;;; : * Adding a different display option for the data - a directed
;;; : graph with the productions as nodes and where a link from A->B
;;; : indicates that B was in the conflict set after A fired.
;;; : * Changed the name of the function used by the previous display
;;; : to production-history-chart-data since the new tool is actually
;;; : a graph.
;;; : * Added parameters for some minor control over the graph display.
;;; 2011.11.17 Dan
;;; : * Added support for another display option in the history graph:
;;; : "Frequencies" which draws the links with widths based on thier
;;; : relative frequencies. The most frequent will be drawn 1/4 of
;;; : the x spacing wide and the rest scaled to that (unless all are
;;; : the same in which case they're all drawn width 1).
;;; 2011.12.06 Dan
;;; : * Adding the extra data to the info sent for the graph so that
;;; : the tcl side can write out a .dot file for the graph.
;;; 2011.12.07 Dan
;;; : * Added the command production-transition-graph which prints
;;; : a DOT representation of the saved production history data
;;; : to the current ACT-R command output stream for the specified
;;; : graph type which can be one of :all, :run, :cycle, :unique-run,
;;; : or :unique-cycle. The graphs correspond to those that are
;;; : shown in the environment tool using the corresponding buttons,
;;; : and when there are multiple subgraphs each has its own cluster
;;; : in the output. This allows one to create the graphs without
;;; : without having the environment connected if an external DOT
;;; : graph viewer is used instead.
;;; 2011.12.22 Dan
;;; : * Added another type of display - utilities.
;;; 2012.02.01 Dan
;;; : * Added a declare and removed unused variables to clean up
;;; : some load time warnings.
;;; 2012.03.12 Dan
;;; : * Save both the current utility and the U(n) value for display
;;; : in the environment production history viewer info.
;;; 2012.03.22 Dan
;;; : * Changed the graph display for runs and utilities so that it
;;; : doesn't show the unchosen links from the end of one session
;;; : to the beginning of the next on the following display (that
;;; : is the dashed links from the previous displays red box to the
;;; : unchosen competitors for the current display's green box).
;;; 2012.04.27 Dan
;;; : * Fixed a bug with displaying the utility graph when there are
;;; : no utility differences.
;;; : * Added an option for hiding the unused productions in the graph
;;; : display.
;;; 2013.01.10 Dan
;;; : * Changed the environment data cache to an equalp hashtable
;;; : since the keys are now a cons of the handler name and the
;;; : window to prevent issues with multi-environment settings.
;;; 2015.06.10 Dan
;;; : * Changed time to use ms instead.
;;; 2016.04.22 Dan
;;; : * Started work to be able to load saved history info. First
;;; : step is adding a function to get the current data because
;;; : that will be used to save current results and since this is
;;; : used for two different purposes it basically needs to save
;;; : the whole module.
;;; 2016.04.28 Dan
;;; : * Updating the interface functions to use the stored history
;;; : info instead of pulling it from the module directly.
;;; : * Depricated the :draw-blank-columns parameter. Only the
;;; : box on the viewer controls that now.
;;; : * Took the cache table out of the module and made it global
;;; : because of the possibility of loading saved data without a
;;; : model present.
;;; 2016.05.16 Dan
;;; : * Send the production text over for the graph display so that
;;; : it can be shown in a window since can't rely on opening a
;;; : procedural viewer since saved data may not match current
;;; : assuming there even is a current model.
;;; 2016.05.26 Dan
;;; : * Send the production name over in the grid column info for
;;; : a more detailed whynot output.
;;; 2017.08.09 Dan
;;; : * Use printed-production-text instead of capturing the pp output.
;;; 2017.09.22 Dan [2.0]
;;; : * Using a history data stream and removing the save-p-history
;;; : parameter.
;;; 2017.09.26 Dan
;;; : * Fixed a bug in the get-p-history-data since the tag is :stop
;;; : not :end.
;;; : * Removed the unneeded parameters.
;;; : * Starting to convert the graph creation code into something
;;; : general that can be returned from a data processor.
;;; 2017.09.27 Dan
;;; : * Added all the processors and just have them return data that's
;;; : still specific to drawing the graph, but in a slightly more
;;; : general list format.
;;; : * Tags all the 'unused' items so they can be hidden when wanted.
;;; : * All the processors work now.
;;; 2017.10.11 Dan
;;; : * Removed the parameters for spacing since it's hard-coded now.
;;; : * Eliminate the unused slots in the module and the global
;;; : variable for the data cache.
;;; 2018.02.28 Dan
;;; : * Updated the calls to define-history-processor to name the
;;; : data stream first.
;;; 2020.01.13 Dan [2.1]
;;; : * Removed the lambdas from the module interface.
;;; : * Use the (:remove <>) option for hook functions.
;;; : * Create functions for the processors.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Open either of the production history tools, "Production Grid" or "Production
;;; Graph" before running the model or record the history "production-history" or
;;; "production-grid".
;;;
;;; For the "Grid" tool, once the model has run click the "Get history" button
;;; at the bottom left corner of the window. It will draw a grid with the rows
;;; being the productions in the model and the columns being the times at which
;;; a conflict-resolution event occurred.
;;;
;;; The cells in the grid are color coded based on what happened during the
;;; conflict resolution event at the time indicated for the column.
;;;
;;; If the production was the one selected the cell will be green.
;;; If the production was in the conflict set, but not selected then the cell
;;; will be orange.
;;; If the production was not in the conflict set then the cell will be red.
;;; If the production did not exist at that time the cell will be white.
;;;
;;; The colors for selected, matched, and mismatched can be changed by clicking
;;; on the color in the tool.
;;;
;;; Placing the cursor over a cell will cause some details for that production
;;; during that conflict resolution event to be printed at the bottom of the
;;; window.
;;;
;;; For the selected and matched cells it will print the utility value for the
;;; production at that time. For the red cells it will print the whynot
;;; information indicating the condition that caused the production to not be
;;; in the conflict set. There is no extra information to print for a white
;;; cell.
;;;
;;; Clicking on the name of a production in the grid will open a new window
;;; showing the production text.
;;;
;;; Clicking a grid in the cell will open a window to display the whynot info or
;;; utility values if it matched.
;;;
;;; For the "Graph" tool, after the model has run click the "get history" button
;;; or select a different radio button to see a different view of the data.
;;; All of the displays are drawn the same way and the common features will be
;;; described before indicating what differs among the choices.
;;;
;;; The display will show all of the productions in the model in boxes. If the
;;; box has a black border then it was selected and fired at some point in the
;;; model's run. If it has a gray border then it was not selected and fired.
;;; If there is a green border around a production then it is the first production
;;; which was selected for the currently displayed information, and if it has
;;; a red border then it was the last production selected for the currently displayed
;;; information.
;;;
;;; An arrow from a production A to production B means that production B was in
;;; the conflict set after production A fired. If the arrow has a solid black line then
;;; production B was selected and fired after A, but if the arrow has a dashed gray
;;; line then it was not selected and fired.
;;;
;;; Clicking on the name of a production in the graph will open a new window showing
;;; the text of the production.
;;;
;;; The "All transitions" button shows the data for all production firings over
;;; the entire run of the model. The "Frequencies" button shows the same data
;;; except that the thickness of the links reflects their relative frequencies.
;;; The most frequent will be 1/4 of :p-history-graph-x wide and the others
;;; scaled appropriately.
;;;
;;; The "Cycles" and "Unique Cycles" buttons show the data broken down into
;;; cycles which occur in the graph (when a loop is formed by a production
;;; eventually firing again after itself). The display will show only one
;;; cycle at a time. The number of cycles which occurred is shown below
;;; the graph and the "-" and "+" buttons can be used to change which cycle
;;; is shown. For "Cycles" all production firings are shown and the cycles
;;; are displayed in temporal order with the model time for the start and end
;;; displayed at the bottom of the window. For the "Unique Cycles" it only
;;; shows one instance of each cycle that occurs and no specific time information
;;; is shown.
;;;
;;; The "Runs" and "Unique Runs" buttons show the data broken down into sections
;;; based on when one of the ACT-R running commands were called. The display will
;;; only one "run" at a time. The number of non-empty runs which occurred is
;;; shown below the graph and the "-" and "+" buttons can be used to change which run
;;; is shown. For "Runs" all production firings are shown and the runs
;;; are displayed in temporal order with the model time for the start and end
;;; of the run displayed at the bottom of the window. For the "Unique Runs" it only
;;; shows one instance of each production graph that occurs in a run and no specific
;;; time information is shown.
;;;
;;; The "Utilities" button breaks the data down into sections based on when the
;;; model receives a reward. Each of the production boxes will be the same width
;;; in this display and may have two additional bars displayed within the box.
;;; A blue bar at the top represents the relative utility of that production before
;;; the reward which ended this section has been applied and a blue bar at the
;;; bottom represents the relative utility of that production after the reward
;;; has been applied. The utility values are scaled so that the range between the
;;; minimum utility across all sections and the maximum utility across all sections
;;; can be displayed. If there is no bottom bar then it means that there was no
;;; reward provided (the last chart may end because the model stopped instead of
;;; because there was a reward provided).
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
(defstruct p-history-module
(lock (bt:make-lock "p-history-module"))
(alive t)
enabled
history
why-not-list
current-data)
(defstruct p-history
time
selected
matched
mismatched
info
tag
reward)
(defun production-history-reward-markers (reward)
(let ((history (get-module production-history)))
(bt:with-lock-held ((p-history-module-lock history))
(push (make-p-history :tag :reward :reward reward :time (mp-time-ms) :info (no-output (spp :name :u))) (p-history-module-history history)))))
(defun production-history-start-markers (ph)
(bt:with-lock-held ((p-history-module-lock ph))
(when (p-history-module-enabled ph)
(push (make-p-history :tag :start :time (mp-time-ms)) (p-history-module-history ph)))))
(defun production-history-stop-markers (ph)
(bt:with-lock-held ((p-history-module-lock ph))
(when (p-history-module-enabled ph)
(push (make-p-history :tag :stop :time (mp-time-ms) :info (no-output (spp :name :u))) (p-history-module-history ph)))))
(defun production-history-recorder (cs)
(let* ((history (get-module production-history))
(best (car cs))
(mismatched (set-difference (all-productions) cs))
(block (make-p-history :mismatched mismatched :time (mp-time-ms))))
(bt:with-lock-held ((p-history-module-lock history))
(no-output
(let ((ut (sgp :ut)))
(when (and best
(or (not (numberp ut))
(and (numberp ut) (>= (caar (spp-fct (list best :utility))) ut))))
(setf (p-history-selected block) best))
(dolist (x cs)
(push (cons x (car (spp-fct (list x :utility :u))))
(p-history-info block)))
(dolist (x mismatched)
(let* ((reason (production-failure-reason x))
(index (position reason (p-history-module-why-not-list history) :test #'string-equal)))
(unless index
(setf index (length (p-history-module-why-not-list history)))
(push-last reason (p-history-module-why-not-list history)))
(push (list x index (caar (spp-fct (list x :u)))) (p-history-info block))))))
(if (p-history-selected block)
(setf (p-history-matched block) (cdr cs))
(setf (p-history-matched block) cs))
(push block (p-history-module-history history))
nil)))
(defstruct (p-history-node (:conc-name phn-)) name color-starts color-ends cycle-starts cycle-ends links utilities)
(defstruct (p-history-link (:conc-name phl-)) target color count cycle from-time to-time)
(defstruct (p-history-display (:conc-name phd-)) name x y color width links starts ends utilities)
(defstruct (p-history-cache (:conc-name phc-)) offsets holes max-loops max height min-u max-u)
(defun parse-production-history-graph (data which)
(let* ((module-data data)
(nodes (mapcar (lambda (x) (make-p-history-node :name x :links nil)) (mapcar 'car (fourth (find "info" module-data :key 'second :test 'string-equal)))))
(loops nil)
(current-loop nil)
(cycle 0)
(top nil)
(previous nil)
(max-color 0)
(max-cycle 0)
(start-time nil)
(min-utility nil)
(max-utility nil)
(stop-utilities nil))
(dolist (x module-data)
(unless (string-equal (second x) "info")
(let ((selected (and (string-equal (second x) "conflict-resolution") (third x)))
(matched (and (string-equal (second x) "conflict-resolution") (fourth x)))
(time (first x)))
(cond ((find which '(:all :freq :color :cycle))
(when (or matched selected)
(when (and (null top) selected)
(dolist (y matched)
(push y top))
(push selected top))
(when (and previous matched)
(dolist (y matched)
(unless (find y (phn-links previous) :key (lambda (z) (when (= (phl-cycle z) cycle) (phl-target z))))
(push (make-p-history-link :target y :cycle cycle :count nil :color -1 :from-time time :to-time time) (phn-links previous)))))
(when selected
(when (find selected current-loop :key 'car :test 'string-equal)
;; completed a loop
(let* ((existing-color (position (cons selected (mapcar 'car current-loop)) loops :test 'equalp))
(color (if existing-color existing-color (length loops))))
(dolist (check (mapcar 'car current-loop))
(dolist (link (phn-links (find check nodes :key 'phn-name :test 'string-equal)))
(when (= -1 (phl-color link))
(setf (phl-color link) color))))
(mapc (lambda (from+time to+time)
(let ((from (car from+time))
(to (car to+time))
(from-time (cdr from+time))
(to-time (cdr from+time)))
(awhen (find to (phn-links (find from nodes :key 'phn-name :test 'string-equal)) :test 'string-equal :key (lambda (z) (if (and (null (phl-count z)) (= (phl-cycle z) cycle)) (phl-target z) "")))
(setf (phn-links (find from nodes :key 'phn-name :test 'string-equal)) (remove it (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
(push (make-p-history-link :target to :color color :count 1 :cycle cycle :from-time from-time :to-time to-time) (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
current-loop (cons (cons selected time) (butlast current-loop)))
(pushnew color (phn-color-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(push (cons cycle (cdar (last current-loop))) (phn-cycle-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(pushnew color (phn-color-ends (find selected nodes :key 'phn-name :test 'string-equal)))
(push (cons cycle time) (phn-cycle-ends (find selected nodes :key 'phn-name :test 'string-equal)))
(when (> cycle max-cycle)
(setf max-cycle cycle))
(when (> color max-color)
(setf max-color color))
(unless existing-color
(push-last (cons selected (mapcar 'car current-loop)) loops)))
(incf cycle)
(setf current-loop nil))
(push (cons selected time) current-loop)
(setf previous (find selected nodes :key 'phn-name :test 'string-equal)))))
((find which '(:run :run-color))
(when (or matched selected
(not (string-equal (second x) "conflict-resolution")))
(when (string-equal (second x) "start")
(setf start-time time))
(when (and (null top) selected)
(dolist (y matched)
(push y top))
(push selected top))
(when (and previous matched)
(dolist (y matched)
(unless (find y (phn-links previous) :test 'string-equal :key (lambda (z) (if (= (phl-cycle z) cycle) (phl-target z) "")))
(push (make-p-history-link :target y :cycle cycle :count nil :color -1 :from-time time :to-time time) (phn-links previous)))))
(when selected
(push (cons selected time) current-loop)
(setf previous (find selected nodes :key 'phn-name :test 'string-equal)))
(when (and current-loop (string-equal "stop" (second x)))
;; completed a loop
(let* ((existing-color (position (mapcar 'car current-loop) loops :test 'equalp))
(color (if existing-color existing-color (length loops))))
(dolist (check (mapcar 'car current-loop))
(dolist (link (phn-links (find check nodes :key 'phn-name :test 'string-equal)))
(when (= -1 (phl-color link))
(setf (phl-color link) color))))
(mapc (lambda (from+time to+time)
(let ((from (car from+time))
(to (car to+time))
(from-time (cdr from+time))
(to-time (cdr to+time)))
(awhen (find to (phn-links (find from nodes :key 'phn-name :test 'string-equal)) :test 'string-equal :key (lambda (z) (if (and (null (phl-count z)) (= (phl-cycle z) cycle)) (phl-target z) "")))
(setf (phn-links (find from nodes :key 'phn-name :test 'string-equal)) (remove it (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
(push (make-p-history-link :target to :color color :count 1 :cycle cycle :from-time from-time :to-time to-time) (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
(cdr current-loop) (butlast current-loop))
(pushnew color (phn-color-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(pushnew (cons cycle start-time) (phn-cycle-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(pushnew color (phn-color-ends (find (caar current-loop) nodes :key 'phn-name :test 'string-equal)))
(push (cons cycle time) (phn-cycle-ends (find (caar current-loop) nodes :key 'phn-name :test 'string-equal)))
(when (> cycle max-cycle)
(setf max-cycle cycle))
(when (> color max-color)
(setf max-color color))
(unless existing-color
(push-last (mapcar 'car current-loop) loops)))
(incf cycle)
(setf current-loop nil)
;; don't want the dashed lines from end of
;; one run going to non-starters for the next
;; loop i.e. matched but not selected.
(setf previous nil))))
(t ;;(find which '(:utility))
(when (or matched selected (not (string-equal (second x) "conflict-resolution")))
(when (and (null top) selected)
(dolist (y matched)
(push y top))
(push selected top))
(when (and previous matched)
(dolist (y matched)
(unless (find y (phn-links previous) :test 'string-equal :key (lambda (z) (if (= (phl-cycle z) cycle) (phl-target z) "")))
(push (make-p-history-link :target y :cycle cycle :count nil :color -1 :from-time time :to-time time) (phn-links previous)))))
(when selected
(push (cons selected time) current-loop)
(setf previous (find selected nodes :key 'phn-name :test 'string-equal)))
(when (string-equal "stop" (second x))
(setf stop-utilities (third x)))
(when (and current-loop (string-equal "reward" (second x)))
;; set the current scores
(dolist (reward (fourth x))
(push-last (cons cycle (second reward)) (phn-utilities (find (first reward) nodes :key 'phn-name :test 'string-equal)))
(when (or (null min-utility) (< (second reward) min-utility))
(setf min-utility (second reward)))
(when (or (null max-utility) (> (second reward) max-utility))
(setf max-utility (second reward))))
;; completed a loop
(let* ()
(mapc (lambda (from+time to+time)
(let ((from (car from+time))
(to (car to+time))
(from-time (cdr from+time))
(to-time (cdr to+time)))
(awhen (find to (phn-links (find from nodes :key 'phn-name :test 'string-equal)) :test 'string-equal :key (lambda (z) (if (and (null (phl-count z)) (= (phl-cycle z) cycle)) (phl-target z) "")))
(setf (phn-links (find from nodes :key 'phn-name :test 'string-equal)) (remove it (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
(push (make-p-history-link :target to :color 0 :count 1 :cycle cycle :from-time from-time :to-time to-time) (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
(cdr current-loop) (butlast current-loop))
(pushnew (cons cycle (cdar (last current-loop))) (phn-cycle-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(push (cons cycle time) (phn-cycle-ends (find (caar current-loop) nodes :key 'phn-name :test 'string-equal)))
(when (> cycle max-cycle)
(setf max-cycle cycle))
;; don't want the dashed lines from end of
;; one loop going to non-starters for the next
;; loop i.e. matched but not selected.
(setf previous nil))
(incf cycle)
(setf current-loop nil))))))))
(when (and (eq which :utility) stop-utilities)
(dolist (reward stop-utilities)
(push-last (cons cycle (second reward)) (phn-utilities (find (first reward) nodes :key 'phn-name :test 'string-equal)))
(when (or (null min-utility) (< (second reward) min-utility))
(setf min-utility (second reward)))
(when (or (null max-utility) (> (second reward) max-utility))
(setf max-utility (second reward)))))
(when (or (> (length current-loop) 0))
(mapc (lambda (from+time to+time)
(let ((from (car from+time))
(to (car to+time))
(from-time (cdr from+time))
(to-time (cdr from+time)))
(push (make-p-history-link :target to :color (length loops) :count 1 :cycle cycle :from-time from-time :to-time to-time) (phn-links (find from nodes :key 'phn-name :test 'string-equal)))))
(cdr current-loop) (butlast current-loop))
(pushnew (length loops) (phn-color-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(push (cons cycle (cdar (last current-loop))) (phn-cycle-starts (find (caar (last current-loop)) nodes :key 'phn-name :test 'string-equal)))
(pushnew (length loops) (phn-color-ends previous))
(push (cons cycle (cdar current-loop)) (phn-cycle-ends previous))
(setf max-color (length loops))
(setf max-cycle cycle))
(list top (when previous (phn-name previous)) nodes (list max-color max-cycle) (list min-utility max-utility))))
(defun filter-links (links which number)
(case which
((:all :freq)
(setf links (remove-duplicates links :key (lambda (x) (cons (phl-target x) (phl-count x))) :test 'equalp))
(remove-if (lambda (x) (and (null (phl-count x)) (find (phl-target x) links :key (lambda (y) (when (phl-count y) (phl-target y))) :test 'string-equal))) links))
((:run :cycle :utility)
(remove-if-not (lambda (x) (= (phl-cycle x) number)) links))
((:run-color :color)
(remove-duplicates (remove-if-not (lambda (x) (= (phl-color x) number)) links) :key 'phl-target :test 'string-equal))))
(defun create-production-graph-coords (module-data which) ; number = generate all, with-labels t, show-unused = t
(let* ((raw-data (json:decode-json-from-string module-data))
(layer-data (parse-production-history-graph raw-data :cycle))
(data (if (find which '(:freq :all :color :cycle)) layer-data (parse-production-history-graph raw-data which)))
(min-u (first (fifth data)))
(max-u (second (fifth data)))
(all-production-names (mapcar 'car (fourth (find "info" raw-data :key 'second :test 'string-equal))))
(unused all-production-names)
(current (car data))
(next nil)
(layers nil)
(start (caar data))
(end (second data))
(max-loops (case which
((:all :freq) 0)
((:run-color :color) (first (fourth data)))
((:run :cycle :utility) (second (fourth data))))))
(while current
(dolist (x current)
(setf unused (remove x unused :test 'string-equal)))
(dolist (x current)
(dolist (y (phn-links (find x (third layer-data) :key 'phn-name :test 'string-equal)))
(when (and (phl-count y) (find (phl-target y) unused :test 'string-equal))
(setf unused (remove (phl-target y) unused :test 'string-equal))
(push (phl-target y) next))))
(push current layers)
(setf current next)
(setf next nil))
(when unused
(push unused layers))
(let ((x-space 40)
(y-space 90)
(max 0)
(cur 0)
(y 65)
(offsets nil)
(widths nil)
(holes nil)
(max-width (* 10 (apply 'max (mapcar 'length all-production-names)))))
(dolist (layer (reverse layers))
(let ((hole (list (round x-space 2))))
(setf cur 0)
(dolist (item layer)
(let ((width (if (eq which :utility) max-width (* 10 (length item)))))
(push (make-p-history-display :name item :links (awhen (find item (third data) :key 'phn-name :test 'string-equal) (phn-links it)) :width width :x (+ cur (round width 2)) :y y
:starts (case which
((:all :freq) (if (eq item start) (list 0) nil))
((:cycle :run :utility) (phn-cycle-starts (find item (third data) :key 'phn-name :test 'string-equal)))
((:color :run-color) (phn-color-starts (find item (third data) :key 'phn-name :test 'string-equal))))
:ends (case which
((:all :freq) (if (string-equal item end) (list 0) nil))
((:cycle :run :utility) (phn-cycle-ends (find item (third data) :key 'phn-name :test 'string-equal)))
((:color :run-color) (phn-color-ends (find item (third data) :key 'phn-name :test 'string-equal))))
:color (if (find item unused :test 'string-equal) "gray" "black")
:utilities (awhen (find item (third data) :key 'phn-name :test 'string-equal) (phn-utilities it)))
offsets) ; (cons item (cons (+ cur (round width 2)) y)) offsets)
(when (= (length hole) 1)
(push (- cur (round x-space 2)) hole))
(push (+ cur width (round x-space 2)) hole)
(incf cur (+ width x-space))))
(decf cur x-space)
(when (> cur max)
(setf max cur))
(push (cons cur y) widths)
(push-last y hole)
(push hole holes)
(incf y (+ 30 y-space))))
(incf max (* 2 x-space))
(setf holes (mapcar (lambda (x) (reverse (cons (- max (round x-space 2)) x))) holes))
(dolist (w widths)
(unless (= (car w) max)
(dolist (o offsets)
(when (= (phd-y o) (cdr w))
(incf (phd-x o) (round (- max (car w)) 2))))
(let ((h (find (cdr w) holes :key 'car)))
(setf holes (cons (concatenate 'list (subseq h 0 2) (mapcar (lambda (x) (+ x (round (- max (car w)) 2))) (subseq (butlast h) 2)) (last h)) (remove h holes))))))
(p-history-display-output raw-data which t offsets holes max-loops max y min-u max-u x-space y-space))))
(defun p-history-display-output (data which with-labels offsets holes max-loops max height min-u max-u x-space y-space)
(let ((min-time -1)
(max-time -1)
(links nil)
(max-link-count 0)
(equal-link-counts t)
(all nil)
(info (find "info" data :key 'second :test 'string-equal)))
(when (and (numberp min-u) (numberp max-u) (= min-u max-u))
(setf min-u (1- min-u))
(setf max-u (1+ max-u)))
(dotimes (number (1+ max-loops))
(setf links nil)
(dolist (o offsets)
(dolist (link (filter-links (phd-links o) which number))
;; for now just using a next closest hole metric for
;; multi-level links but at some point may want to try
;; a shortest path instead or some sort of non-intersecting algorithm
(let* ((target (find (phl-target link) offsets :key 'phd-name :test 'string-equal))
(used (if (string-equal (phd-color target) "black") 1 0))
(link-count (if (find which '(:freq #|:run :run-color if I want to do these too need to filter on color/run as well |#)) (count-if (lambda (x) (string-equal (phl-target x) (phl-target link))) (phd-links o)) nil)))
(when (and (numberp link-count) (> link-count max-link-count))
(unless (zerop max-link-count)
(setf equal-link-counts nil))
(setf max-link-count link-count))
(cond ((string-equal (phd-name o) (phd-name target)) ;; self link
;;; if left end loop on left side
;;; if right end loop on right side
;;; if in middle loop on bottom
(cond ((= (phd-x o) (apply 'min (mapcar 'phd-x (remove-if-not (lambda (xx) (= (phd-y xx) (phd-y o))) offsets)))) ;; left end uses both left sides
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used
(- (phd-x o) (round (phd-width o) 2)) (phd-y o)
(- (phd-x o) (round (phd-width o) 2) 15) (phd-y o)
(- (phd-x o) (round (phd-width o) 2) 15) (+ (phd-y o) 30)
(- (phd-x o) (round (phd-width o) 2) -15) (+ (phd-y o) 30)
(- (phd-x o) (round (phd-width o) 2) -15) (+ (phd-y o) 15)
)
links))
((= (phd-x o) (apply 'max (mapcar 'phd-x (remove-if-not (lambda (xx) (= (phd-y xx) (phd-y o))) offsets)))) ;; right end uses both right sides
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used
(+ (phd-x o) (round (phd-width o) 2)) (phd-y o)
(+ (phd-x o) (round (phd-width o) 2) 15) (phd-y o)
(+ (phd-x o) (round (phd-width o) 2) 15) (+ (phd-y o) 30)
(+ (phd-x o) (round (phd-width o) 2) -15) (+ (phd-y o) 30)
(+ (phd-x o) (round (phd-width o) 2) -15) (+ (phd-y o) 15)
)
links))
(t
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used
(+ (phd-x o) 5) (+ (phd-y o) 15)
(+ (phd-x o) 10) (+ (phd-y o) 25)
(- (phd-x o) 10) (+ (phd-y o) 25)
(- (phd-x o) 5) (+ (phd-y o) 15)
)
links))))
((= (phd-y o) (phd-y target)) ;; same row
;; link bottom right of leftmost to bottom left of rightmost
(if (> (phd-x target) (phd-x o)) ;; left to right
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used
(+ (phd-x o) (round (phd-width o) 2)) (+ (phd-y o) 15)
(+ (+ (phd-x o) (round (phd-width o) 2)) (round (- (- (phd-x target) (round (phd-width target) 2)) (+ (phd-x o) (round (phd-width o) 2))) 2)) (+ (phd-y o) 15 (round y-space 3))
(- (phd-x target) (round (phd-width target) 2)) (+ (phd-y o) 15)
)
links)
;; right to left
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used
(- (phd-x o) (round (phd-width o) 2)) (+ (phd-y o) 15)
(- (- (phd-x o) (round (phd-width o) 2)) (round (- (- (phd-x o) (round (phd-width o) 2)) (+ (phd-x target) (round (phd-width target) 2))) 2)) (+ (phd-y o) 15 (round y-space 3))
(+ (phd-x target) (round (phd-width target) 2)) (+ (phd-y o) 15)
)
links)))
((> (phd-y target) (phd-y o)) ;; forward i.e. down
;; if one layer down draw bottom center to top center directly
;; otherwise draw bottom center to top center going through next closest hole
(if (= (- (phd-y target) (phd-y o)) (+ 30 y-space))
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count
used
(phd-x o) (+ (phd-y o) 15)
(phd-x target) (- (phd-y target) 15)
)
links)
(push (concatenate 'list (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used
(phd-x o) (+ (phd-y o) 15))
(let ((x (phd-x o))
(vals nil))
(dotimes (i (- (/ (- (phd-y target) (phd-y o)) (+ 30 y-space)) 1))
(let* ((y (+ (phd-y o) (* (1+ i) (+ 30 y-space))))
(hs (find y holes :key 'car))
(min max)
(min-x nil))
(dolist (j (cdr hs))
(when (< (abs (- x j)) min)
(setf min (abs (- x j)))
(setf min-x j)))
(push min-x vals)
(push (- y 20) vals) ;; a little slack above and below
(push min-x vals)
(push (+ y 20) vals)
(setf x min-x)))
(reverse vals))
(list (phd-x target) (- (phd-y target) 15))
)
links)))
(t ;; backward i.e. up
;; going up draw from 1/3 left or right of center top to l/r 1/3 from center bottom
;; which left and which right depends on positions
;; if only one level apart then pick both sides based on position of from relative to to
;; - if from left of to then go from left to left otherwise go right to right
;; if multiple levels then
;; if from is leftmost in it's row start and end are both left
;; if from is rightmost in it's row start and end are both right
;; if to is left of from then use left for from and right for to
;; if to is right of from then use right for from and left for to
;; if same column then check which side of screen left start is on
;; if it's on the left use left for both
;; otherwise use right for both
;; all intermediates are based on next closest hole (going up)
(if (= (- (phd-y o) (phd-y target)) (+ 30 y-space))
;; one level up
(if (<= (phd-x o) (phd-x target))
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count
used
(- (phd-x o) (round (phd-width o) 6)) (- (phd-y o) 15)
(- (phd-x target) (round (phd-width target) 6)) (+ (phd-y target) 15) )
links)
(push (list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count
used
(+ (phd-x o) (round (phd-width o) 6)) (- (phd-y o) 15)
(+ (phd-x target) (round (phd-width target) 6)) (+ (phd-y target) 15) )
links))
;; multiple levels
(let ((start-x nil)
(end-x nil))
(cond ((and (= (phd-x o) (apply 'min (mapcar 'phd-x (remove-if-not (lambda (xx) (= (phd-y xx) (phd-y o))) offsets))))
(<= (- (phd-x target) (round (phd-width target) 6)) (round max 2))) ;; left end uses both left sides if target point also on left
(setf start-x (- (phd-x o) (round (phd-width o) 6)))
(setf end-x (- (phd-x target) (round (phd-width target) 6))))
((and (= (phd-x o) (apply 'max (mapcar 'phd-x (remove-if-not (lambda (xx) (= (phd-y xx) (phd-y o))) offsets))))
(>= (+ (phd-x target) (round (phd-width target) 6)) (round max 2))) ;; right end uses both right sides if target also on right
(setf start-x (+ (phd-x o) (round (phd-width o) 6)))
(setf end-x (+ (phd-x target) (round (phd-width target) 6))))
((< (phd-x target) (phd-x o)) ; target is to the left so start on left and end on right
(setf start-x (- (phd-x o) (round (phd-width o) 6)))
(setf end-x (+ (phd-x target) (round (phd-width target) 6))))
((> (phd-x target) (phd-x o)) ; target is to the right so start on right and end on left
(setf start-x (+ (phd-x o) (round (phd-width o) 6)))
(setf end-x (- (phd-x target) (round (phd-width target) 6))))
((< (phd-x o) (round max 2)) ;; same column so use the side of screen to judge and same for both
;; left is left
(setf start-x (- (phd-x o) (round (phd-width o) 6)))
(setf end-x (- (phd-x target) (round (phd-width target) 6))))
(t ;; same column so use the side of screen to judge and same for both
;; right is right
(setf start-x (+ (phd-x o) (round (phd-width o) 6)))
(setf end-x (+ (phd-x target) (round (phd-width target) 6)))))
(push (concatenate 'list
(list (phd-name o) (phd-name target) (if (phl-count link) "black" "gray") link-count used start-x (- (phd-y o) 15))
(let ((x start-x)
(vals nil))
(dotimes (i (- (/ (- (phd-y o) (phd-y target)) (+ 30 y-space)) 1))
(let* ((y (- (phd-y o) (* (1+ i) (+ 30 y-space))))
(hs (find y holes :key 'car))
(min max)
(min-x nil))
(dolist (j (cdr hs))
(when (< (abs (- x j)) min)
(setf min (abs (- x j)))
(setf min-x j)))
(push min-x vals)
(push (+ y 20) vals)
(push min-x vals)
(push (- y 20) vals)
(setf x min-x)))
(reverse vals))
(list end-x (+ (phd-y target) 15))
)
links))))))))
(push-last (append
(let ((results nil))
(dolist (x offsets)
(when with-labels
(push (list "label"
(phd-name x) (phd-x x) (phd-y x)
(- (phd-x x) (round (phd-width x) 2))
(- (phd-y x) 15)
(+ (phd-x x) (round (phd-width x) 2))
(+ (phd-y x) 15)
(if (keywordp (phd-color x)) "black" (phd-color x))
(cadr (assoc (phd-name x) (fourth info) :test 'string-equal)))
results))
(when (eq which :utility)
(awhen (assoc number (phd-utilities x))
(push (list "box" (phd-name x)
(- (phd-x x) (round (phd-width x) 2) -4)
(- (phd-y x) 11)
(+ (- (phd-x x) (round (phd-width x) 2) -4) (floor (* (- (phd-width x) 8) (/ (- (cdr it) min-u) (- max-u min-u)))))
(- (phd-y x) 9)
"blue"
(if (string-equal (phd-color x) "black") 1 0))
results))
(awhen (assoc (1+ number) (phd-utilities x))
(push (list "box" (phd-name x)
(- (phd-x x) (round (phd-width x) 2) -4)
(+ (phd-y x) 11)
(+ (- (phd-x x) (round (phd-width x) 2) -4) (floor (* (- (phd-width x) 8) (/ (- (cdr it) min-u) (- max-u min-u)))))
(+ (phd-y x) 9)
"blue"
(if (string-equal (phd-color x) "black") 1 0))
results)))
(awhen (find number (phd-starts x) :key (if (or (eq which :cycle) (eq which :run) (eq which :utility)) 'car 'identity))
(when (or (eq which :cycle) (eq which :run) (eq which :utility))
(setf min-time (cdr it)))
(push (list "box" (phd-name x)
(- (phd-x x) (round (phd-width x) 2) 2)
(- (phd-y x) 17)
(+ (phd-x x) (round (phd-width x) 2) 2)
(+ (phd-y x) 17)
"green" 1) results))
(awhen (find number (phd-ends x) :key (if (or (eq which :cycle) (eq which :run) (eq which :utility)) 'car 'identity))
(when (or (eq which :cycle) (eq which :run) (eq which :utility))
(setf max-time (cdr it)))
(push (list "box" (phd-name x)
(- (phd-x x) (round (phd-width x) 2) -2)
(- (phd-y x) 13)
(+ (phd-x x) (round (phd-width x) 2) -2)
(+ (phd-y x) 13)
"red" 1) results)))
results)
(mapcar (lambda (x)
(list "link" (first x) (second x) (third x)
(if (or (null (fourth x))
equal-link-counts
(= 1 max-link-count)
(= 0 max-link-count))
1
(let ((max-width x-space))
(max 1 (round (* max-width (/ (fourth x) max-link-count))))))
(fifth x)
(nthcdr 5 x)))
;; because frequency needs to count links there are potentially duplicates but only need
;; to send over one of each...
(remove-duplicates links :test (lambda (x y) (and (eq (first x) (first y)) (eq (second x) (second y)) (eq (third x) (third y))))))
(when (and (or (eq which :cycle) (eq which :run) (eq which :utility))
(> min-time -1) (> max-time -1))
(list
(list "min_time" min-time)
(list "max_time" max-time)))
#| show the holes for debugging
(let ((z nil))
(dolist (x holes)
(mapcar (lambda (y)
(push (format nil "link blue ~d ~d ~d ~d" y (- (car x) 15) y (+ (car x) 15)) z))
(cdr x)))
z)
|#
)
all))
(push (list "size" max height) all)))
;;; A command to allow getting .dot output of the graphs without using the environment.
#|
(defun production-transition-graph (&optional (which :all))
(verify-current-model
"Cannot generate a production transition graph because there is no current model."
(unless (find which '(:all :cycle :run :unique-cycle :unique-run))
(print-warning "Invalid graph type. Must be one of (:all :cycle :run :unique-cycle :unique-run).")
(return-from production-transition-graph))
(when (eq which :unique-cycle)
(setf which :color))
(when (eq which :unique-run)
(setf which :run-color))
(let* ((data (parse-production-history-graph (list (mapcar 'list (all-productions)) (get-module production-history)) which))
(unused (all-productions))
(start (caar data))
(end (second data))
(max-loops (case which
((:all :freq) 0)
((:run-color :color) (1+ (first (fourth data))))
((:run :cycle) (1+ (second (fourth data)))))))
(cond ((eq which :all)
(command-output "digraph \"~s\" {" (current-model))
(command-output " \"~s\" [ color = green ];" start)
(unless (eq start end)
(command-output " \"~s\" [ color = red ];" end))
(dolist (node (third data))
(let* ((transitions (remove-duplicates (phn-links node) :test (lambda (x y) (and (eq (phl-target x) (phl-target y)) (eql (phl-count x) (phl-count y))))))
(links (remove-if (lambda (x) (and (null (phl-count x)) (find (phl-target x) (remove x transitions) :key 'phl-target))) transitions)))
(dolist (link links)
(if (phl-count link)
(progn
(setf unused (remove (phl-target link) unused))
(command-output " \"~s\" -> \"~s\" ;" (phn-name node) (phl-target link)))
(command-output " \"~s\" -> \"~s\" [ color = gray style = dashed ] ;" (phn-name node) (phl-target link))))))
(dolist (node unused)
(command-output " \"~s\" [color = gray] ;" node))
(command-output "}"))
((or (eq which :color) (eq which :run-color))
(command-output "digraph \"~s\" {" (current-model))
(dotimes (i max-loops)
(command-output " subgraph cluster_~d {~% label = \"~a ~d\";" i (if (eq which :color) "unique cycle" "unique run") (1+ i))
(let ((node-names (mapcar (lambda (x) (cons x (new-name-fct x))) (mapcar 'phn-name (third data))))
(start-node (phn-name (find i (third data) :test 'member :key 'phn-color-starts)))
(end-node (phn-name (find i (third data) :test 'member :key 'phn-color-ends)))
(used nil))
(command-output " \"~s\" [ color = green ];" (cdr (assoc start-node node-names)))
(unless (eq start-node end-node)
(command-output " \"~s\" [ color = red ];" (cdr (assoc end-node node-names))))
(pushnew (assoc start-node node-names) used)
(pushnew (assoc end-node node-names) used)
(dolist (node (third data))
(let* ((transitions (remove-duplicates (remove-if-not (lambda (x) (= (phl-color x) i)) (phn-links node)) :test (lambda (x y) (and (eq (phl-target x) (phl-target y)) (eql (phl-count x) (phl-count y))))))
(links (remove-if (lambda (x) (and (null (phl-count x)) (find (phl-target x) (remove x transitions) :key 'phl-target))) transitions)))
(dolist (link links)
(pushnew (assoc (phl-target link) node-names) used)
(if (phl-count link)
(command-output " \"~s\" -> \"~s\" ;" (cdr (assoc (phn-name node) node-names)) (cdr (assoc (phl-target link) node-names)))
(command-output " \"~s\" -> \"~s\" [ color = gray style = dashed ] ;" (cdr (assoc (phn-name node) node-names)) (cdr (assoc (phl-target link) node-names)))))))
(dolist (x used)
(command-output " \"~s\" [ label = \"~s\" ];" (cdr x) (car x)))
(command-output " }")))
(command-output "}"))
((or (eq which :cycle) (eq which :run))
(command-output "digraph \"~s\" {" (current-model))
(dotimes (i max-loops)
(command-output " subgraph cluster_~d {~% label = \"~a ~d\";" i which (1+ i))
(let ((node-names (mapcar (lambda (x) (cons x (new-name-fct x))) (mapcar 'phn-name (third data))))
(start-node (phn-name (find i (third data) :test 'member :key (lambda (y) (mapcar 'car (phn-cycle-starts y))))))
(end-node (phn-name (find i (third data) :test 'member :key (lambda (y) (mapcar 'car (phn-cycle-ends y))))))
(used nil))
(command-output " \"~s\" [ color = green ];" (cdr (assoc start-node node-names)))
(unless (eq start-node end-node)
(command-output " \"~s\" [ color = red ];" (cdr (assoc end-node node-names))))
(pushnew (assoc start-node node-names) used)
(pushnew (assoc end-node node-names) used)
(dolist (node (third data))
(let* ((transitions (remove-duplicates (remove-if-not (lambda (x) (= (phl-cycle x) i)) (phn-links node)) :test (lambda (x y) (and (eq (phl-target x) (phl-target y)) (eql (phl-count x) (phl-count y))))))
(links (remove-if (lambda (x) (and (null (phl-cycle x)) (find (phl-target x) (remove x transitions) :key 'phl-target))) transitions)))
(dolist (link links)
(pushnew (assoc (phl-target link) node-names) used)
(if (phl-count link)
(command-output " \"~s\" -> \"~s\" ;" (cdr (assoc (phn-name node) node-names)) (cdr (assoc (phl-target link) node-names)))
(command-output " \"~s\" -> \"~s\" [ color = gray style = dashed ] ;" (cdr (assoc (phn-name node) node-names)) (cdr (assoc (phl-target link) node-names)))))))
(dolist (x used)
(command-output " \"~s\" [ label = \"~s\" ];" (cdr x) (car x)))
(command-output " }")))
(command-output "}"))))))
|#
(defun reset-p-history-module (module)
(bt:with-lock-held ((p-history-module-lock module))
(setf (p-history-module-history module) nil)
(setf (p-history-module-why-not-list module) nil)))
(defun create-production-history-module (x)
(declare (ignore x))
(make-p-history-module))
(defun delete-production-history-module (x)
(bt:with-lock-held ((p-history-module-lock x))
(setf (p-history-module-alive x) nil)))
(define-module-fct 'production-history nil nil
:creation 'create-production-history-module
:delete 'delete-production-history-module
:reset 'reset-p-history-module
:run-start 'production-history-start-markers
:run-end 'production-history-stop-markers
:version "2.1"
:documentation "Module to record production history for display in the environment.")
(defun get-p-history-data ()
(let ((module (get-module production-history)))
(when module
(bt:with-lock-held ((p-history-module-lock module))
(let (data)
(dolist (x (p-history-module-history module))
(push
(case (p-history-tag x)
(:start (list (p-history-time x) "start"))
(:stop (list (p-history-time x) "stop" (p-history-info x)))
(:reward (list (p-history-time x) "reward" (p-history-reward x) (p-history-info x)))
(t (list (p-history-time x) "conflict-resolution" (p-history-selected x) (p-history-matched x) (p-history-mismatched x) (p-history-info x))))
data))
(push (list 0 "info" (p-history-module-why-not-list module) (mapcar (lambda (x) (list x (printed-production-text x nil))) (all-productions))) data)
data)))))
(defun enable-p-history ()
(no-output
(unless (find 'production-history-recorder (car (sgp :conflict-set-hook)))
(sgp :conflict-set-hook production-history-recorder))
(unless (find 'production-history-reward-markers (car (sgp :reward-notify-hook)))
(sgp :reward-notify-hook production-history-reward-markers)))
(let ((m (get-module production-history)))
(bt:with-lock-held ((p-history-module-lock m))
(setf (p-history-module-enabled m) t))))
(defun disable-p-history ()
(no-output
(let ((old-hooks (car (sgp :conflict-set-hook))))
(when (find 'production-history-recorder old-hooks)
(sgp :conflict-set-hook (:remove production-history-recorder)))
(setf old-hooks (car (sgp :reward-notify-hook)))
(when (find 'production-history-reward-markers old-hooks)
(sgp :reward-notify-hook (:remove production-history-reward-markers)))))
(let ((m (get-module production-history)))
(bt:with-lock-held ((p-history-module-lock m))
(setf (p-history-module-enabled m) nil))))
(defun p-history-status ()
(let ((m (get-module production-history)))
(if m
(bt:with-lock-held ((p-history-module-lock m))
(no-output
(values
(and (find 'production-history-recorder (car (sgp :conflict-set-hook)))
(find 'production-history-reward-markers (car (sgp :reward-notify-hook)))
t)
(when (p-history-module-history m) t)
(p-history-module-alive m))))
(values nil nil nil))))
(define-history "production-history" enable-p-history disable-p-history p-history-status get-p-history-data t)
(defun compute-production-grid (p-data)
(let ((data (json:decode-json-from-string p-data))
(results nil)
(p-list nil))
(dolist (x data)
(case (read-from-string (second x))
(info
(push-last x results)
(setf p-list (mapcar 'first (fourth x))))
(conflict-resolution
(push-last (list (first x)
"conflict-resolution"
(if (third x) t)
(let (r)
(dolist (y p-list)
(push-last (cond ((string-equal y (third x))
(let ((details (find y (sixth x) :key 'first :test 'string-equal)))
(list 0 (second details) (third details))))
((find y (fourth x) :test 'string-equal)
(let ((details (find y (sixth x) :key 'first :test 'string-equal)))
(list 1 (second details) (third details))))
((find y (fifth x) :test 'string-equal)
(let ((details (find y (sixth x) :key 'first :test 'string-equal)))
(list 2 (second details))))
(t
(list -1)))
r))
r))
results))))
results))
(define-history-processor "production-history" "production-grid" compute-production-grid)
(defun production-graph-all (x)
(create-production-graph-coords x :all))
(defun production-graph-freq (x)
(create-production-graph-coords x :freq))
(defun production-graph-cycles (x)
(create-production-graph-coords x :cycle))
(defun production-graph-u-cycles (x)
(create-production-graph-coords x :color))
(defun production-graph-runs (x)
(create-production-graph-coords x :run))
(defun production-graph-u-runs (x)
(create-production-graph-coords x :run-color))
(defun production-graph-utility (x)
(create-production-graph-coords x :utility))
(define-history-processor-fct "production-history" "production-graph-all" 'production-graph-all)
(define-history-processor-fct "production-history" "production-graph-freq" 'production-graph-freq)
(define-history-processor-fct "production-history" "production-graph-cycles" 'production-graph-cycles)
(define-history-processor-fct "production-history" "production-graph-u-cycles" 'production-graph-u-cycles)
(define-history-processor-fct "production-history" "production-graph-runs" 'production-graph-runs)
(define-history-processor-fct "production-history" "production-graph-u-runs" 'production-graph-u-runs)
(define-history-processor-fct "production-history" "production-graph-utility" 'production-graph-utility)
#|
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
|#
| 68,396 | Common Lisp | .lisp | 1,062 | 48.184557 | 228 | 0.523986 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c5285f3b38e938d652b63ec1291da8bc2c33aad064a735e1b922ac97739f1df2 | 14,147 | [
-1
] |
14,148 | env-graphic-trace.lisp | asmaloney_ACT-R/other-files/env-graphic-trace.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 : env-graphic-trace.lisp
;;; Version : 2.0
;;;
;;; Description : Support for a quick and dirty graphic display of the
;;; buffer trace info through the environment connection.
;;;
;;; Bugs :
;;;
;;; To do : [ ] Check that all module state changes get flagged correctly
;;; : for "unusual" modules and situations.
;;;
;;; ----- History -----
;;;
;;; 2007.04.30 Dan
;;; : Initially added it to the archive.
;;; 2007.05.21 Dan
;;; : * Modified the vertical trace to be much faster because
;;; : it sends all the data in one update which the environment
;;; : parses as a list for displaying. Will change the horizontal
;;; : once testing verifies that the vertical is stable like this).
;;; 2007.05.22 Dan
;;; : * Reference the parameters that were added to the buffer trace
;;; : module for display purposes.
;;; : * Made the horizontal trace use the fast transmit mechanism.
;;; : * Fixed the default color list referencing so that it wraps
;;; : around if needed.
;;; 2007.06.06 Dan
;;; : * Added the use of error->clear to the buffer summary parsing
;;; : to better handle requests that occur immediately following
;;; : an error (retrieval failures had some oddities in the trace).
;;; 2007.07.30 Dan
;;; : * Adding a new production parameter called color and then
;;; : using that to set the color in the graphic traces if set to
;;; : a valid color string.
;;; 2011.04.28 Dan
;;; : * Suppress warnings about extending productions at initial load.
;;; 2011.05.31 Dan
;;; : * Moved the color code to a file in support which is required
;;; : now since the BOLD tools use it too.
;;; 2011.06.01 Dan
;;; : * Removed some global vars that are no longer needed.
;;; 2014.05.06 Dan
;;; : * Fixed a bug with parse-trace-list which could happen when
;;; : production breaks cause 'bad' production events to be recorded.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2016.04.29 Dan [2.0]
;;; : * Updating for use with the saved data approach and doing some
;;; : slight reorganizing of the data for the display.
;;; 2016.05.03 Dan
;;; : * Parse-trace-list now returns the trace from the buffers in
;;; : the trace not those set with :save-buffer-trace since it could
;;; : be set to ones that weren't traced.
;;; : * Similarly, it's got to pull the time from the data as well.
;;; : * Also needs color info from productions, but not sure how to
;;; : deal with that yet.
;;; 2016.05.04 Dan
;;; : * Saving production and width info with the buffer trace for
;;; : the environment by simply making a list of the three for
;;; : the new get-environment-buffer-trace.
;;; 2016.05.05 Dan
;;; : * Added the end time to the get-environment-buffer-trace data
;;; : so that it doesn't call mp-time-ms when drawing an unfinished
;;; : rectangle.
;;; : * Adding the buffer name to the rectangle data passed over to
;;; : the environment side.
;;; 2016.05.27 Dan
;;; : * Added an extra 100ms to the end time passed for the graphic
;;; : traces so that what happens at the end should be visible.
;;; 2017.09.29 Dan [3.0]
;;; : * Convert to a history data processor and ignore the colors
;;; : for now -- that gets done on the 'display' side, but should
;;; : have some suggestions in the data passed over since the
;;; : production coloring can result in some nice data visibility.
;;; : Still going to scale the x/y sizes based on how many, but
;;; : could also be scaled on the other side as needed.
;;; 2017.10.02 Dan
;;; : * Changed the size value sent to not include the unnecessary 0.
;;; : * Added the buffer-index in place of a color value.
;;; : * Changed the vertical to use same width for all.
;;; : * Test for the case when there are no buffers to avoid a divide
;;; : by zero error.
;;; : * Sort the buffer list so things are consistent.
;;; 2017.10.03 Dan
;;; : * Moved the buffer-trace data list accessors to the buffer-trace
;;; : file.
;;; 2017.10.04 Dan
;;; : * Use mp-time-ms for end of ongoing actions in parse-trace-list
;;; : since it doesn't get start & end times now.
;;; 2018.02.28 Dan
;;; : * Updated the calls to define-history-processor to name the
;;; : data stream first.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; In the graphic trace the box is drawn when the buffer reports that the
;;; module is busy, whenever a request is sent through the buffer, or whenver a
;;; chunk is placed into the buffer. The request is drawn at the top of the
;;; box and the chunk placed into the buffer is drawn at the bottom (if there is
;;; such a chunk). The one exception to that is 0-time events (visual-location
;;; and goal requests for example). For 0-time events only the chunk name is
;;; shown after the line representing the event in the vertical trace.
;;;
;;; If you place the mouse cursor over a box (or the chunk name if it is outside
;;; of the box like a 0-time event will be) in the trace it will show the start
;;; and stop times for that box in the lower left corner of the display window.
;;;
;;; The "+" and "-" buttons in the control can be used to rescale the image along
;;; the time dimension.
;;;
;;; The "Remove Text" button will erase all of the request and chunk names from
;;; the image. The only way to restore them after that is to redisplay the
;;; whole thing.
;;;
;;; The save button will write the image out to a Postscript file because that's the
;;; easy default available in Tk. There are lots of ps->pdf converters out there
;;; so hopefully that's not an issue for people, but eventually it could be made
;;; to generate something "nicer" if people demand it.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; None (accessed through the environment side viewer).
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Quick and dirty - the rectangle drawing info is actually created on the Lisp
;;; side and pushed to Tk for drawing. A much nicer mechanism would be to just
;;; send the descriptive info so that more display control would be available on
;;; the environment side (like stretching columns or reordering things).
;;; If there's a signifigant demand (and time) at some point this could be made
;;; very nice, but that'll require modifications to the environment server control
;;; code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
;; Give the option to color the productions
(suppress-extension-warnings)
(extend-productions color)
(unsuppress-extension-warnings)
(defun vert-graphic-trace-return (h)
(let* ((d (json:decode-json-from-string h))
(data (parse-trace-list d :vertical)))
(cons (list "size" (+ 100 (br-time (first (last d))))) data)))
(defun hor-graphic-trace-return (h)
(let* ((d (json:decode-json-from-string h))
(data (parse-trace-list d :horizontal)))
(cons (list "size" (+ 100 (br-time (first (last d))))) data)))
(define-history-processor-fct "buffer-trace" "horizontal-graphic-trace" 'hor-graphic-trace-return)
(define-history-processor-fct "buffer-trace" "vertical-graphic-trace" 'vert-graphic-trace-return)
(defstruct gt-rect start end (request "") (chunk "") (notes ""))
(defun parse-trace-list (trace dir)
(let* ((buffers (mapcar 'bs-name (br-buffers (first trace))))
(y 0)
(y-inc (when buffers (min 50 (floor (/ 380 (length buffers))))))
(x-coord 0)
(x-inc (when buffers (min 190 (floor (/ 960 (length buffers))))))
(all-data nil)
(buffer-index 0))
(dolist (x (sort buffers 'string<))
(let ((rects nil)
(current-rect nil))
(dolist (z trace)
(let ((record (find x (br-buffers z) :key 'bs-name :test 'string-equal)))
(cond (current-rect
(awhen (check-bs-chunk-name record)
(setf (gt-rect-chunk current-rect) it))
(awhen (check-bs-notes record)
(setf (gt-rect-notes current-rect) it))
(when (or (null (bs-busy record))
(bs-busy->free record)
(check-bs-request record))
(setf (gt-rect-end current-rect) (br-time z))
(push current-rect rects)
(if (check-bs-request record)
(setf current-rect (make-gt-rect :start (br-time z)
:request (value-bs-request record)))
(setf current-rect nil))))
((bs-busy record)
(if (and (check-bs-request record)
(or (check-bs-chunk-name record)
(and (bs-error record)
(not (bs-error->clear record)))
(bs-busy->free record)))
(push (make-gt-rect :start (br-time z)
:end (br-time z)
:request (value-bs-request record)
:chunk (value-bs-chunk-name record)
:notes (value-bs-notes record))
rects)
(setf current-rect (make-gt-rect :start (br-time z)
:request (value-bs-request record)
:chunk (value-bs-chunk-name record)
:notes (value-bs-notes record)))))
((check-bs-request record)
(push (make-gt-rect :start (br-time z) :end (br-time z)
:request (value-bs-request record)
:chunk (value-bs-chunk-name record)
:notes (value-bs-notes record))
rects))
((check-bs-chunk-name record)
(push (make-gt-rect :start (br-time z) :end (br-time z)
:request (value-bs-request record)
:chunk (value-bs-chunk-name record)
:notes (value-bs-notes record))
rects)))))
(dolist (z rects)
(if (eq dir :horizontal)
(push (list "rectangle" (gt-rect-start z) y (aif (gt-rect-end z) it (mp-time-ms)) (+ y y-inc)
buffer-index #| (aif (and (eq x 'production)
(gt-rect-request z)
(assoc (gt-rect-request z) prod-colors :test 'string-equal))
(if (stringp (cdr it))
(cdr it)
(nth buffer-index color-list))
(nth buffer-index color-list)) |#
(gt-rect-request z)
(gt-rect-chunk z)
(if (gt-rect-notes z)
(format nil "~a" (gt-rect-notes z))
"")
(if (string-equal x "production") (gt-rect-request z) (gt-rect-chunk z))
x)
all-data)
(push (list "rectangle" x-coord (gt-rect-start z)
(+ x-coord x-inc) (aif (gt-rect-end z) it (mp-time-ms))
buffer-index #|(aif (and (eq x 'production)
(gt-rect-request z)
(assoc (gt-rect-request z) prod-colors :test 'string-equal))
(if (stringp (cdr it))
(cdr it)
(nth buffer-index color-list))
(nth buffer-index color-list)) |#
(gt-rect-request z) (gt-rect-chunk z)
(if (gt-rect-notes z)
(format nil "~a" (gt-rect-notes z))
"")
(if (string-equal x "production") (gt-rect-request z) (gt-rect-chunk z))
x)
all-data)))
(if (eq dir :horizontal)
(push (list "label" x (+ y (floor (/ y-inc 2))) buffer-index #|(nth buffer-index color-list)|#) all-data)
(push (list "label" x (+ x-coord (floor (/ x-inc #|(nth buffer-index widths-list)|# 2))) buffer-index #|(nth buffer-index color-list)|# x-inc #|(nth buffer-index widths-list)|#) all-data)))
(incf y y-inc)
(incf x-coord x-inc)
(incf buffer-index))
all-data))
#|
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,528 | Common Lisp | .lisp | 283 | 44.614841 | 199 | 0.529612 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | dc605b29bccb96cf67cf2d1af7408fb5a6284672db32275886f7f20283b27998 | 14,148 | [
-1
] |
14,149 | buffer-history.lisp | asmaloney_ACT-R/other-files/buffer-history.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2008-2011 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 : buffer-history.lisp
;;; Version : 2.1
;;;
;;; Description : Code to support the buffer history tool in the environment.
;;;
;;; Bugs :
;;;
;;; To do : [x] Consider converting the internal time over to milliseconds
;;; : by using buffer-record-ms-time instead of -time-stamp.
;;; : The down side of that is the display for the environment
;;; : should probably still be in seconds.
;;;
;;; ----- History -----
;;; 2008.08.20 Dan
;;; : * Initial creation.
;;; 2011.04.25 Dan
;;; : * Added the "to do" to consider.
;;; 2011.06.20 Dan [1.1]
;;; : * Changed the tool to record all the details everytime, not
;;; : just when there is a "change" to the buffer because some
;;; : changes are below what the buffer trace detects i.e. custom
;;; : queries for modules.
;;; 2011.06.24 Dan
;;; : * Changed the output so that the query info is first so that
;;; : it's easier to watch that for a change in a buffer since it
;;; : will be formatted consistently.
;;; 2013.11.15 Dan
;;; : * Chunk contents are now displayed at time stamps when there
;;; : isn't an "action" on that buffer which was a bug because of
;;; : how the events were recorded and compared.
;;; : * Removed the special :cleared marker for the chunk details
;;; : since it wasn't really being used -- now it's either the
;;; : string of the chunk details or nil if the buffer is empty or
;;; : being cleared at that time.
;;; 2015.06.09 Dan
;;; : * Record time in ms internally, but still show seconds to the
;;; : user in the list.
;;; 2016.04.22 Dan
;;; : * Start of the upgrade to allow saving history info so that it
;;; : can be reloaded for the environment tools.
;;; 2016.04.27 Dan
;;; : * Modify the environment interface functions so that they use
;;; : the indicated underlying data.
;;; 2016.05.04 Dan
;;; : * Just some minor code clean-up in the param function.
;;; 2016.05.06 Dan
;;; : * Fixed an issue with buffers that were cleared and then set
;;; : at the same time -- before the end state showed as empty.
;;; : * Also marked the to do as complete since that happened with
;;; : the 2015.06.09 update.
;;; 2016.05.16 Dan
;;; : * Previous fix actually broke the chunk recording so this now
;;; : gets it right.
;;; 2017.09.28 Dan [2.0]
;;; : * Reworking the buffer history to use the history data stream
;;; : mechanism and to not rely upon the buffer trace recorder.
;;; : Now it will record all the buffer information itself using
;;; : an event hook for all buffers regardless of the :traced-
;;; : buffers setting and it will record the information at the
;;; : start of a time stamp and after each action so that it can
;;; : report start of time stamp, after action, and end of time
;;; : stamp results (where end is start of next if available).
;;; 2018.02.05 Dan
;;; : * Rework this to actually use the internal event structs
;;; : directly since it'll get an id now.
;;; 2018.02.22 Dan
;;; : * Need to protect access to time using meta-p-schedule-lock.
;;; 2020.01.13 Dan [2.1]
;;; : * Removed the lambda from the module interface.
;;; 2021.06.07 Dan
;;; : * Deal with set-buffer-chunk and overwrite-... possibly having
;;; : a chunk-spec as the second parameter.
;;; 2021.10.18 Dan
;;; : * Changed call to buffers to model-buffers instead.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
(defclass buffer-history-module ()
((history-lock :accessor history-lock :initform (bt:make-lock "buffer-history") :allocation :class)
(save-history :accessor save-history :initform nil)
(alive :accessor alive :initform t)
(start-time-data :accessor start-time-data :initform nil)
(recorded-data :accessor recorded-data :initform nil)
(current-data :accessor current-data :initform nil)
(last-time-stamp :accessor last-time-stamp :initform -1 :allocation :class)
(pre-recorder :accessor pre-recorder :initform nil :allocation :class)
(post-recorder :accessor post-recorder :initform nil :allocation :class)
(monitor-count :accessor monitor-count :initform 0 :allocation :class)))
(defvar *top-level-buffer-history-module* (make-instance 'buffer-history-module))
(defun buffer-start-time-recorder (evt)
(bt:with-lock-held ((history-lock *top-level-buffer-history-module*))
(let ((event (get-event-by-id evt)))
(unless (= (last-time-stamp *top-level-buffer-history-module*) (bt:with-recursive-lock-held ((meta-p-schedule-lock (current-mp))) (act-r-event-mstime event)))
(dolist (m (mp-models))
(with-model-eval m
(let ((module (get-module buffer-history)))
(when (save-history module)
(let ((last (start-time-data module)))
(setf (start-time-data module)
(mapcar (lambda (bn)
(list bn
(aif (buffer-read bn) (printed-chunk it) "buffer empty")
(printed-buffer-status bn)))
(model-buffers)))
(unless (= (last-time-stamp module) -1)
(let ((results nil))
(dolist (x (current-data module))
(push-last (concatenate 'list x (cdr (find (first x) last :key 'first)) (cdr (find (first x) (start-time-data module) :key 'first)))
results))
(push-last (list (last-time-stamp module) results) (recorded-data module))))
(setf (current-data module) nil)))))))
(setf (last-time-stamp *top-level-buffer-history-module*) (bt:with-recursive-lock-held ((meta-p-schedule-lock (current-mp))) (act-r-event-mstime event))))))
(defun buffer-event-recorder (evt)
(when (current-model)
(let ((module (get-module buffer-history)))
(bt:with-lock-held ((history-lock module))
(let ((event (get-event-by-id evt)))
(when (save-history module)
(case (act-r-event-action event)
(set-buffer-chunk
(push-last (list (first (act-r-event-params event))
"set-buffer-chunk"
(if (symbolp (second (act-r-event-params event)))
(printed-chunk (second (act-r-event-params event)))
(printed-chunk-spec (second (act-r-event-params event))))
(printed-buffer-status (first (act-r-event-params event))))
(current-data module)))
(clear-buffer
(push-last (list (first (act-r-event-params event)) "clear-buffer" "" (printed-buffer-status (first (act-r-event-params event))))
(current-data module)))
(mod-buffer-chunk
(push-last (list (first (act-r-event-params event)) "mod-buffer-chunk" (printed-chunk-spec (second (act-r-event-params event))) (printed-buffer-status (first (act-r-event-params event))))
(current-data module)))
(overwrite-buffer-chunk
(push-last (list (first (act-r-event-params event))
"overwrite-buffer-chunk"
(if (symbolp (second (act-r-event-params event)))
(printed-chunk (second (act-r-event-params event)))
(printed-chunk-spec (second (act-r-event-params event))))
(printed-buffer-status (first (act-r-event-params event))))
(current-data module)))
(module-request
(push-last (list (first (act-r-event-params event)) "module-request" (printed-chunk-spec (second (act-r-event-params event))) (printed-buffer-status (first (act-r-event-params event))))
(current-data module)))
(module-mod-request
(push-last (list (first (act-r-event-params event)) "module-mod-request" (printed-chunk-spec (second (act-r-event-params event))) (printed-buffer-status (first (act-r-event-params event))))
(current-data module)))
(erase-buffer
(push-last (list (first (act-r-event-params event)) "erase-buffer" "" (printed-buffer-status (first (act-r-event-params event))))
(current-data module))))))))))
(defun reset-buffer-history-module (module)
(bt:with-lock-held ((history-lock module))
(setf (recorded-data module) nil)
(setf (current-data module) nil)
(setf (last-time-stamp module) -1)
(setf (start-time-data module) nil)
(when (save-history module)
(setf (save-history module) nil)
(decf (monitor-count module))
(when (zerop (monitor-count module))
(delete-event-hook (pre-recorder module))
(delete-event-hook (post-recorder module))))))
(defun disable-buffer-history ()
(let ((module (get-module buffer-history)))
(bt:with-lock-held ((history-lock module))
(when (save-history module)
(setf (save-history module) nil)
(decf (monitor-count module))
(when (zerop (monitor-count module))
(delete-event-hook (pre-recorder module))
(delete-event-hook (post-recorder module))))
t)))
(defun delete-buffer-history-module (module)
(bt:with-lock-held ((history-lock module))
(setf (alive module) nil)
(when (save-history module)
(setf (save-history module) nil)
(decf (monitor-count module))
(when (zerop (monitor-count module))
(delete-event-hook (pre-recorder module))
(delete-event-hook (post-recorder module))))
t))
(defun create-buffer-history-module (x)
(declare (ignore x))
(make-instance 'buffer-history-module))
(define-module-fct 'buffer-history nil nil
:creation 'create-buffer-history-module
:reset 'reset-buffer-history-module
:delete 'delete-buffer-history-module
:version "2.1"
:documentation "Module to record buffer change history.")
(defun enable-buffer-history ()
(let ((module (get-module buffer-history)))
(bt:with-lock-held ((history-lock module))
(unless (save-history module)
(setf (save-history module) t)
(when (zerop (monitor-count module))
(setf (pre-recorder module) (add-pre-event-hook 'buffer-start-time-recorder))
(setf (post-recorder module) (add-post-event-hook 'buffer-event-recorder)))
(incf (monitor-count module)))
t)))
(defun buffer-history-status ()
(let ((module (get-module buffer-history)))
(bt:with-lock-held ((history-lock module))
(values (save-history module) (when (or (recorded-data module) (current-data module)) t) (alive module)))))
(defun get-buffer-history ()
(let ((module (get-module buffer-history)))
(if (null (current-data module))
(recorded-data module)
(let ((results nil))
(dolist (x (current-data module))
(push-last (concatenate 'list x (cdr (find (first x) (start-time-data module) :key 'first)) (list "" ""))
results))
(append (recorded-data module) (list (list (last-time-stamp module) results)))))))
(define-history "buffer-history" enable-buffer-history disable-buffer-history buffer-history-status get-buffer-history)
#|
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,191 | Common Lisp | .lisp | 262 | 46.09542 | 205 | 0.564857 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c8fb09f4dfb7748c56102a60245863429372ec128e8d13e773813d0cbeda42da | 14,149 | [
-1
] |
14,150 | high-performance.lisp | asmaloney_ACT-R/tools/high-performance.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 : high-performance.lisp
;;; Version : 1.0
;;;
;;; Description : Add a system parameter that kills the trace (bypasses the
;;; filter tests) for all models and sets the default for some
;;; other parameters that affect speed.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2019.02.15 Dan [1.0]
;;; : * Initial creation.
;;; 2018.03.04 Dan
;;; : * Added visual-movement-tolerance set to 0.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; New system parameter named :high-performance. Can be set to t or nil, and
;;; the default is nil. Can only be changed when there are no models defined.
;;; When set to nil it does not affect the system. Setting it to t should
;;; provide a significant improvement in the time required to run a model, but
;;; at the cost of all trace and diagnostic outputs. When set to t it prevents
;;; all model traces from being displayed without having to check the trace
;;; filters. It also sets the :starting-parameters system parameter like this:
;;;
;;; (:ncnar nil :style-warnings nil :model-warnings nil :cmdt nil :lhst nil
;;; :rhst nil :stable-loc-names nil :visual-movement-tolerance 0)
;;;
;;; because those parameters default to t and when set can slow down the system.
;;;
;;; The setting of :starting-parameters will overwrite any current settings and
;;; it will print a warning if it does so.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; system parameter :high-performance can be set to t or nil.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Uses a simple global variable to store the value which is also the flag for
;;; the scheduler to check, and by not allowing it to be changed when there are
;;; models defined avoids the need for a lock which would basically defeat the
;;; purpose.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
;; Make sure :starting-parameters exists
(require-compiled "CENTRAL-PARAMETERS")
(defun high-performance-param (set-or-get value)
(when set-or-get
(setf *allow-event-output* (not value))
(if value
(progn
(awhen (car (ssp :starting-parameters))
(print-warning "Setting :high-performance will overwrite the current :starting-parameters setting of ~s" it))
(ssp :starting-parameters (:ncnar nil :style-warnings nil :model-warnings nil :cmdt nil :lhst nil :rhst nil :stable-loc-names nil :visual-movement-tolerance 0))
)
(ssp :starting-parameters nil)))
(not *allow-event-output*))
(defun high-performance-test (val)
(and (tornil val)
(zerop (length (mp-models)))))
(create-system-parameter :high-performance
:handler 'high-performance-param
:documentation "Change default value for performance based parameters and disable the trace output."
:valid-test 'high-performance-test
:warning "T or nil and only when no models are defined"
:default-value 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
|#
| 5,030 | Common Lisp | .lisp | 108 | 42.277778 | 171 | 0.574286 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2d9fd242db2bc5da597cf44dcb96a16d7de31cdf3007aa7c415a62007f6bd058 | 14,150 | [
-1
] |
14,151 | retrieval-compilation.lisp | asmaloney_ACT-R/tools/retrieval-compilation.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 : retrieval-compilation.lisp
;;; Version : 3.0
;;;
;;; Description : Production compilation RETRIEVAL style definition.
;;;
;;; Bugs :
;;;
;;; To do :
;;; ----- History -----
;;;
;;; 2010.12.06 Dan
;;; : * Created automatically by build-compilation-type-file.
;;; : * Added the details of the functions.
;;; 2010.12.15 Dan
;;; : * Added module to the mapping functions args list.
;;; 2011.04.28 Dan
;;; : * Removed an unneeded let variable from map-retrieval-buffer.
;;; 2012.04.04 Dan [1.1]
;;; : * Added the whynot reason function.
;;; 2014.05.07 Dan [2.0]
;;; : * Start of conversion to typeless chunks.
;;; : * References to compilation-module-previous are now using a
;;; : structure instead of list.
;;; 2016.11.18 Dan
;;; : * When the buffer is strict harvested in p1 (8 or 24) and p2 has
;;; : a query for buffer empty (16 or 20) then drop that buffer
;;; : empty query from the composed production.
;;; 2018.02.19 Dan
;;; : * P1 = 24 is not the same as p1 = 20 and 28 so it needs its
;;; : own case.
;;; 2018.02.20 Dan
;;; : * When retrieval requests in both functions are composed it
;;; : should always be p2's request which stays, but for some
;;; : reason case p1 = 4 || 12 was keeping p1's. Of course I don't
;;; : know why we allow that anyway, but I guess someone wanted it
;;; : at some point.
;;; 2020.06.22 Dan [3.0]
;;; : * The functions are now all passed the same set of parameters:
;;; : buffer module p1 p1-s p1-index p2 p2-s p2-index
;;; : the p1-s and p2-s are the new "standard" representation that
;;; : can be decomposed with composition-rep-* where * is:
;;; : op -- the character of the operation =,?,!,+,-,*,@
;;; : name -- the symbol naming the buffer or bang action
;;; : token -- the symbol of the production item for op and name
;;; : slots -- list of slot-spec lists
;;; 2020.11.05 Dan
;;; : * Fixed a bug with the dropping of the buffer empty query.
;;; 2020.11.10 Dan
;;; : * Fixed the typo of modfication in the failure strings.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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 MAP-RETRIEVAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"map references from p1 to p2 for retrieval style buffer"
(declare (ignore p1))
;; current specification will only allow this
;; in the case that it's a RHS + or nothing
;; combined with a LHS = or "busy" query.
;;
;; Then, the only time there are mappings are
;; when it's a + followed by an =.
(cond ((and (find p1-index '(4 12 20 28))
(find p2-index '(8 12 24 28)))
;; map variables onto constants of retrieved chunk
(let* ((buffer-variable (intern (concatenate 'string "=" (symbol-name buffer))))
(the-chunk (cdr (assoc buffer-variable (production-bindings p2)))))
(when the-chunk
(let ((mappings (aif (assoc buffer-variable (production-drop-out-buffers-map (production-name p2)))
(list (cons (cdr it) the-chunk))
(list (cons buffer-variable the-chunk)))))
(dolist (request-slot-spec (compose-rep-slots (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(when (chunk-spec-variable-p (spec-slot-name request-slot-spec))
;; Variablized slot needs to be instantiated...
(push (assoc (spec-slot-name request-slot-spec) (previous-production-bindings (compilation-module-previous module))) mappings))
(when (and (eq (spec-slot-op request-slot-spec) '=)
(chunk-spec-variable-p (spec-slot-value request-slot-spec)))
;; Update to handle partial matching
;; get the binding for the action from the first production's
;; instantiation instead of what's retrieved in the buffer
;(push (cons (third condition) (chunk-slot-value-fct the-chunk (second condition))) mappings)
(push (assoc (spec-slot-value request-slot-spec) (previous-production-bindings (compilation-module-previous module))) mappings)))
(dolist (condition-slot-spec (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
;; Bind a variablized slot to its instantiation
(when (chunk-spec-variable-p (spec-slot-name condition-slot-spec))
(push (assoc (spec-slot-name condition-slot-spec) (production-compilation-instan (production-name p2))) mappings))
(when (and (eq (spec-slot-op condition-slot-spec) '=)
(chunk-spec-variable-p (spec-slot-value condition-slot-spec)))
(if (chunk-spec-variable-p (spec-slot-name condition-slot-spec))
;; if the slot name is a variable we need to use the instantiation of
;; that to know what the real slot name was which was pushed onto mappings above
(push (cons (spec-slot-value condition-slot-spec) (chunk-slot-value-fct the-chunk (cdr (assoc (spec-slot-name condition-slot-spec) mappings)))) mappings)
(push (cons (spec-slot-value condition-slot-spec) (chunk-slot-value-fct the-chunk (spec-slot-name condition-slot-spec))) mappings))))
mappings))))
(t
nil)))
(defun COMPOSE-RETRIEVAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
;; This is based on the limited set of conditions that can
;; be composed.
;;
;; The constraints are:
;;
;; The only action that will remain is a
;; request from the second production if such exists
;; or
;; a request from the first if the second doesn't
;; harvest the buffer
;;
;; If the first production doesn't mention the buffer (0)
;; any = condition and any query are used from the second
;; If the first production makes a request without a query (4, 12)
;; any = condition in the first production is used and there
;; are no queries
;; If the first production tests the buffer but doesn't make
;; any queries or requests (8)
;; any = condition in the first is used along with any
;; query from the second except that if the buffer is strict
;; harvested a buffer empty query from p2 is dropped
;; If the first has no = condition but does have queries
;; and is without a request (16)
;; the = condition from the second is used along with
;; the query from the first
;; If the first has both an = condition and a query or a
;; query and a request (20, 24, 28)
;; Both the = condition and query from the first are used
(declare (ignore p1 p2))
(let ((c1 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(c2 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(q1 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(q2 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(a1+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s))))
(case p1-index
(0
(list (append
(when c2
(list c2))
(when q2
(list q2)))
(when a2+
(list a2+))))
((4 12)
(if (find p2-index '(0 16))
(list (when c1 (list c1))
(when a1+ (list a1+)))
(list (when c1 (list c1))
(when a2+ (list a2+)))))
(8
(list (append
(when c1
(list c1))
(if q2
(if (find buffer (compilation-module-no-harvest module))
(list q2)
;; strict harvested so need to ignore a buffer empty query from p2
(let ((slots (compose-rep-slots q2)))
(setf slots (remove '(= buffer empty) slots :test 'equalp))
(if slots
(list (list (first q2) slots)) ;; building a compose-rep explicitly because don't want to destructively modify
nil)))
nil))
(when a2+
(list a2+))))
(16
(list (append
(when c2
(list c2))
(when q1
(list q1)))
(when a2+
(list a2+))))
(24
(list (append (when c1 (list c1)) (when q1 (list q1)))
(when a2+ (list a2+))))
((20 28)
(if (find p2-index '(0 16))
(list (append (when c1 (list c1)) (when q1 (list q1)))
(when a1+ (list a1+)))
(list (append (when c1 (list c1)) (when q1 (list q1)))
(when a2+ (list a2+))))))))
(defun R-B-C1 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Compilation check for queries such that p2 only uses 'buffer empty' or 'state busy'"
(declare (ignore module p1 p1-s p1-index p2 p2-index))
(let ((query (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))))
(every (lambda (x)
(or
(equalp x '(= state busy))
(equalp x '(= buffer empty))))
(compose-rep-slots query))))
(defun R-B-C2 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"queries in p1 and p2 must be the same
NOTE: this doesn't take into account any variables at this time"
(declare (ignore module p1 p1-index p2 p2-index))
(let ((query1 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p1-s))
(compose-rep-slots it)))
(query2 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(compose-rep-slots it))))
(= (length query1) (length query2)
(length (remove-duplicates (append query1 query2) :test 'equal)))))
(defun retrieval-reason (p1-index p2-index failed-function)
(cond ((eql failed-function 'r-b-c1)
"when the first production makes a request and the second does not harvest it the second can only query for state busy or buffer empty.")
((eql failed-function 'r-b-c2)
"the queries in both productions must be the same.")
((> p1-index 30)
"buffer modification actions in first production are not allowed.")
((> p2-index 30)
"buffer modification actions in second production are not allowed.")
(t
(case p1-index
((9 11 13 15 25 27 29)
"buffer modification actions in first production are not allowed.")
((2 6 10 14 18 22 26 30)
"the buffer is explicitly cleared in the first production.")
(t
(case p2-index
((2 6 10 14 18 22 26 30)
"the buffer is explicitly cleared in the second production.")
((9 11 13 15 25 27 29)
"buffer modification actions in second production are not allowed.")
(t
"strict harvesting should have prevented the buffer condition from matching in the second production.")))))))
(define-compilation-type RETRIEVAL ((28 28 T)
(28 24 T)
(28 20 R-B-C1)
(28 16 R-B-C1)
(28 12 T)
(28 8 T)
(28 4 T)
(28 0 T)
(24 20 R-B-C2)
(24 16 R-B-C2)
(24 4 T)
(24 0 T)
(20 28 T)
(20 24 T)
(20 20 R-B-C1)
(20 16 R-B-C1)
(20 12 T)
(20 8 T)
(20 4 T)
(20 0 T)
(16 28 R-B-C2)
(16 24 R-B-C2)
(16 20 R-B-C2)
(16 16 R-B-C2)
(16 12 T)
(16 8 T)
(16 4 T)
(16 0 T)
(12 28 T)
(12 24 T)
(12 20 R-B-C1)
(12 16 R-B-C1)
(12 12 T)
(12 8 T)
(12 4 T)
(12 0 T)
(8 20 T)
(8 16 T)
(8 4 T)
(8 0 T)
(4 28 T)
(4 24 T)
(4 20 R-B-C1)
(4 16 R-B-C1)
(4 12 T)
(4 8 T)
(4 4 T)
(4 0 T)
(0 28 T)
(0 24 T)
(0 20 T)
(0 16 T)
(0 12 T)
(0 8 T)
(0 4 T))
(RETRIEVAL) MAP-RETRIEVAL-BUFFER COMPOSE-RETRIEVAL-BUFFER NIL NIL T retrieval-reason)
#|
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,087 | Common Lisp | .lisp | 314 | 38.55414 | 177 | 0.486795 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 71c8a6b4e489e3d7754e330812a7f9f94190414ae25ca4f1855930edc6b02b4e | 14,151 | [
-1
] |
14,152 | visible-virtual.lisp | asmaloney_ACT-R/tools/visible-virtual.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-2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : visible-virtual.lisp (renamed from env-device.lisp)
;;; Version : 5.0
;;;
;;; Description : No system dependent code.
;;; : This file contains the code that handles passing
;;; : the virtual windows out through Tk - the visible
;;; : virtuals, and the AGI support.
;;; Bugs : [ ] What should happen if a button goes away between when the
;;; : model initiates an action and finishes it?
;;;
;;; Todo :
;;; ----- History -----
;;;
;;; 10/01/2002 Dan
;;; : Added this header.
;;; 10/01/2002 Dan
;;; : Updated version to 1.1 and fixed the packaging
;;; : for building a standalone in ACL.
;;; 12/04/2002 Dan
;;; : Added the definition for *use-environment-window*
;;; : even though it's still not used because it
;;; : does get set by the environment and generates a
;;; : warning.
;;; 01/06/2003 Dan
;;; : Updated it so that the colors were sent out
;;; : properly for all supported colors and so that
;;; : text colors worked.
;;; 4/22/2004 Dan [1.5]
;;; : Added the license info.
;;; -----------------------------------------------------------------------
;;; 2005.04.13 Dan [2.0]
;;; : * Moved over to ACT-R 6.
;;; 2005.06.07 Dan
;;; : * Replaced a call to device-interface with
;;; : current-device-interface.
;;; 2005.06.28 Dan
;;; : * Removed a pm-proc-display call that was still lingering
;;; : in the device-move-cursor-to method.
;;; 2007.07.13 Dan
;;; : * Added the sending of a button's color to the env.
;;; 2010.05.21 Dan
;;; : * Changed the name of the dialog items to add a vv on the
;;; : to avoid interning a name which could shift the names
;;; : for things like visual chunks (text items in particular).
;;; : Doesn't affect performance, just keeps traces consistent
;;; : when shifting between visible and virtual.
;;; -------------------------------------------------------------------------
;;; 2011.05.20 Dan [3.0]
;;; : * Start of a complete overhaul to eliminate most of the
;;; : global variable usage and better encapsulate things so
;;; : that multiple model support can be added.
;;; 2011.11.21 Dan
;;; : * Using model-generated-action instead of *actr-enabled-p*
;;; : to detect when the button needs to be visibly "clicked".
;;; 2012.06.26 Dan
;;; : * Adding a clearattention flag that gets sent and save the
;;; : window used in the visual-fixation-marker slot so that if
;;; : the window changes it can clear the old marker before
;;; : displaying the new one.
;;; 2012.06.27 Dan [3.1]
;;; : * Start the process of supporting multiple windows on the
;;; : environment side.
;;; : - Give the window a unique id using new-symbol instead of
;;; : new-name.
;;; : - Use the symbol-name of the ids instead of the symbol since
;;; : if the window persists across a reset those symbols will
;;; : get uninterned which means they won't match what was
;;; : originally sent.
;;; : - Create the items in the context of the model in which the
;;; : window was created so that the names are guaranteed to be
;;; : unique without having to use new-symbol.
;;; 2012.07.12 Dan
;;; : * Added a custom vw-output method for visible-virtual windows
;;; : because in a multiple model situation the output should
;;; : be based on the owning model's settings instead of whichever
;;; : model (if any) happens to be current.
;;; 2012.08.10 Dan
;;; : * Support more than one fixation ring per window since
;;; : multiple models may be sharing a device by using the
;;; : model name in a tag.
;;; 2012.08.31 Dan
;;; : * Added env-window-click so that I can catch all the user
;;; : clicks on the environment side window and call the
;;; : rpm-window-click-event-handler appropriately.
;;; 2012.09.21 Dan
;;; : * Grabbing the environment lock before sending the updates
;;; : with send-env-window-update.
;;; : * Bad idea - can deadlock things...
;;; 2013.01.10 Dan
;;; : * Env. sends keys over as strings now and uses a function
;;; : named convert-env-key-name-to-char to convert that to a
;;; : character instead of throwing a warning on the read of an
;;; : invalid character. If it's an invalid character it still
;;; : prints a warning, but now that should be more informative.
;;; : * Instead of redefining visible-virtuals-available? here the
;;; : function in the virtual's uwi file now calls check-with-environment-for-visible-virtuals
;;; : which is defined here instead.
;;; 2013.07.18 Dan
;;; : * Fixed a potential bug in vv-click-event-handler because
;;; : the button could be removed between the model's click
;;; : initiation and execution in which case it can't send
;;; : the update to the environment. Probably shouldn't eval
;;; : the action either, but I'm not fixing that now.
;;; 2014.08.29 Dan
;;; : * Changed vv-click-event-handler so that the action can be
;;; : either a function or a symbol naming a function.
;;; 2015.04.29 Dan
;;; : * Changed convert-env-key-name-to-char so that it can handle
;;; : things like space and return.
;;; 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. Then
;;; : pass that over to the environment to use when drawing it
;;; : in add-visual-items-to-rpm-window.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;; 2016.04.01 Dan [3.2]
;;; : * Treat human clicks in the visible virtuals the same as
;;; : model clicks and let the virtual window deal with the
;;; : processing. Avoids a lot of crazyness on the Env. side
;;; : and is consistent with respect to the click event handler.
;;; : This also coincides to a shift on the Env. side of not
;;; : using real buttons in the visible virtual window so that
;;; : cursor and visual attention always show over items.
;;; : * That means that all clicks are handled by the subviews and
;;; : button "clicks" all need to be sent over.
;;; 2016.04.04 Dan [3.3]
;;; : * Actually use the show-focus value to determine a color if
;;; : it's a valid symbol or a string.
;;; 2016.06.08 Dan
;;; : * Change add-visual-items-to-rpm-window method so that it
;;; : only sends a message when it recognizes the item type
;;; : instead of sending a null message when it's a new type
;;; : of item to allow for easier customizing/updating.
;;; : * Add the methods to handle modifying the items. For now
;;; : it takes the simple approach of calling the virtual item
;;; : code to make the changes and then removing and redrawing
;;; : the item in the Env. window.
;;; 2016.08.09 Dan
;;; : * Changed the modify methods to just specify allow-other-keys
;;; : since they don't directly use any of them.
;;; 2017.01.06 Dan
;;; : * Removed vw-output and allow-event-manager.
;;; 2017.01.20 Dan
;;; : * Updated the keypress handler to just call output-key, and
;;; : for now it just passes the raw string received without
;;; : trying to clean that up to match the keyboard names.
;;; 2017.01.23 Dan
;;; : * Added a mapping from my Windows keyboard names to the
;;; : cannonical model keyboard name where applicable.
;;; 2017.01.24 Dan
;;; : * Set one monitoring function for visible virtual experiment
;;; : windows to monitor update-attended-loc so it can draw the
;;; : fixation ring.
;;; 2017.01.30 Dan
;;; : * Add-act-r-command call parameters reordered.
;;; 2017.02.24 Dan
;;; : * Updated visible-virtual-update-loc-monitor because now
;;; : it's a simple monitor which gets the params directly.
;;; 2017.03.02 Dan
;;; : * Updated env-window-click to just call vv-click-handler
;;; : now since that's the appropriate underlying method.
;;; 2017.03.06 Dan
;;; : * Have the user clicks also call click-the-mouse for monitoring.
;;; 2017.03.08 Dan
;;; : * Use the device-move-cursor-to method to send the notice
;;; : to the environment, but doesn't need to do anything else.
;;; 2017.03.16 Dan
;;; : * Added the declaims to avoid compiler warnings.
;;; 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.07 Dan
;;; : * Remove the vv-model slot from the window class and all
;;; : the code that relates to that.
;;; : * Use the window's lock when adding or removing things.
;;; 2017.06.08 Dan
;;; : * Fixed the with-act-r-lock usage since it uses a simpler
;;; : syntax than the underlying with-lock.
;;; 2017.06.13 Dan
;;; : * Determine-exp-window needs the agi component passed in now.
;;; 2017.06.16 Dan
;;; : * Use call-next-method in close-rpm-window.
;;; : * Add a lock to protect the monitor setting.
;;; : * Add a lock to protect the *vv-table*.
;;; : * Change the class from which the dialog items are based
;;; : because they need a lock slot.
;;; 2017.06.19 Dan
;;; : * Adding lock checks around add- and remove- code.
;;; 2017.06.23 Dan
;;; : * Added names for all the locks.
;;; 2017.09.08 Dan [4.0]
;;; : * Update to use the new ACT-R interface instead of the old
;;; : Environment handler mechanisms. This allows for anyone
;;; : to register to receive the updates, and multiple different
;;; : viewers could all be displaying simultaneously.
;;; 2017.09.11 Dan
;;; : * Finished off the update and docs on how it works.
;;; : * Renamed it visible-virtual.lisp and moved it to the
;;; : tools directory.
;;; 2017.09.13 Dan
;;; : * The device-interface doesn't hold the show-focus value
;;; : anymore -- it's in the vision module so changed that to
;;; : just use sgp now.
;;; : * The click option was being sent as the symbol and not a
;;; : lower case string.
;;; : * Fix a bug in close-exp-window which got lost in the
;;; : transition to the new file.
;;; : * Don't need to send the clearattention twice when the
;;; : current window is the same as the previous.
;;; 2017.09.22 Dan
;;; : * Fixed a bug with the modify methods.
;;; 2018.01.17 Dan
;;; : * Apparently reintroduced the bug with text feats differing
;;; : between virtual and visible...
;;; : Set the text-height of the items the same as for virtual
;;; : where it's 10/12ths the font-size and then send the real
;;; : font-size over for displaying.
;;; 2018.01.29 Dan
;;; : * Generalize the add-visual-items-to-rpm-window method so
;;; : that it's easier to add new item types which goes along
;;; : with the generalization that occurred in the environment
;;; : handler.
;;; 2018.03.13 Dan
;;; : * Multiple cursors allowed per window.
;;; 2018.03.15 Dan
;;; : * Simplified the class hierarcy by removing the rpm-...
;;; : classes which aren't needed anymore.
;;; 2018.03.20 Dan
;;; : * Added a slot to the virtual window class for recording
;;; : whether or not the fixation ring is drawn in the window
;;; : since multiple windows can be installed at the same time
;;; : and that prevents a central storage since access order
;;; : isn't guaranteed.
;;; 2018.05.08 Dan
;;; : * Changed check-with-environment-for-visible-virtuals so
;;; : that it removes bad values automatically and prints one
;;; : warning about that instead of a warning everytime.
;;; 2018.06.22 Dan
;;; : * Updated doc strings on remote commands.
;;; 2018.09.12 Dan
;;; : * Only send the check notice once, and don't include a
;;; : useless parameter.
;;; : * Allow a handler to indicate that it isn't going to draw
;;; : but should still be notified when changes occur if it is
;;; : drawn.
;;; : * Keep track of the handlers in the window itself.
;;; : * Don't monitor update-attended-loc -- vision is responsible
;;; : for notifying the device. In general, the AGI shouldn't
;;; : assume anything about the modules in which it is installed.
;;; : * That change means the handler is responsible for checking
;;; : the window bounds to determine whether or not to draw the
;;; : attention ring and whether to remove it or not.
;;; 2018.09.17 Dan
;;; : * Don't need the visible-virtual-update-loc monitor.
;;; : * Moved color->name to misc-utils.
;;; : * Updated the add-virtual-window-handler docs to indicate
;;; : there's an optional parameter now.
;;; 2019.07.09 Dan
;;; : * Fixed the bug where it warned about a visible handler
;;; : being removed but didn't actually remove it.
;;; : * When adding one use string= to test not string-equal
;;; : because command strings are case sensitive.
;;; 2019.08.19 Dan
;;; : * Fixed a typo in remove-virtual-window-handler because it
;;; : had string-= instead of string=.
;;; 2019.11.04 Dan
;;; : * Remove display handlers as soon as they have a failed
;;; : call.
;;; 2020.02.21 Dan [5.0]
;;; : * Remove the clear signal from remove-all-items-from-rpm-window
;;; : since that only gets called for a close and the handler
;;; : can assume the clear action from that...
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Interface protocol
;;;
;;; To display the visible virtual windows the 'client' must first call
;;; the add-virtual-window-handler command providing the name of a command
;;; to call to handle the displaying of the window and items.
;;;
;;; If a client wants to stop displaying the windows it should call
;;; remove-virtual-window-handler with the command that it added.
;;;
;;; The added command will be called with a list of parameters. The first
;;; element in the list will be a string indicating an action. The remaining
;;; elements will be the parameters necessary for performing that action.
;;; The possible actions are:
;;;
;;; check
;;; It will be passed no additional elements. This is called whenever
;;; a new visible-virtual window is about to be created to determine if
;;; there is a client which will display the window. If a client
;;; returns true then it will be sent an open action and all other actions
;;; requested for that window. If no client returns a true value then
;;; a virtual window will be used instead and none of the handlers will
;;; be sent any further notices for this window.
;;;
;;; open
;;; It will be passed 5 additional elements. The first will be the title
;;; for the window which will be used to refer to it for any updates which
;;; occur. The next two will be the x and y coordinate (respectively) for
;;; the location of the window as specified by the upper-left corner. The
;;; last 2 will be the width and height of the window in pixels respectively.
;;;
;;; select
;;; It will be passed one additional parameter which will be the title of
;;; an opened window. This is a request to make that window visible and
;;; "bring it to the front" or whatever the appropriate terminology is for
;;; the appropriate window manager in use.
;;;
;;; close
;;; It will be passed one additional parameter which will be the title of
;;; an opened window. This is a request to close the window and remove it
;;; from view. No further commands will be sent for that window.
;;;
;;; button
;;; It will be passed 8 additional parameters. It is called to add a button
;;; object to a window. The first additional parameter is the title of the
;;; window. The second is a string with a name for this button.
;;; The next two are the x and y position of the upper-left corner of the
;;; button. Then the width and height of the button are provided. That
;;; is followed by the text to display on the button, and finally a color
;;; for the background of the button.
;;;
;;; text
;;; It will be passed 7 additional parameters. It is called to add text
;;; to a window. The first additional parameter is the title of the window.
;;; The second is a string with a name for this text item. The next
;;; two are the x and y position of the upper-left corner of the text. A
;;; string with the text to display is next. That is followed by the color
;;; and font size for the text.
;;;
;;; line
;;; It will be passed 7 additional parameters. It is called to draw a line
;;; on a window. The first additional parameter is the title of the window.
;;; The second is a string with a name for this line. The next
;;; two are the x and y position of one end of the line and then the x and
;;; y position of the other end of the line is given. The final value is
;;; the color for the line.
;;;
;;; remove
;;; It will be passed 2 additional parameters. The first is the title of
;;; a window and the second is the name of the item to be removed from the
;;; window.
;;;
;;; attention
;;; It will be passed 5 additional items. This is called to indicate the
;;; location of a model's visual attention. Typically a circle is drawn
;;; around that location. The first additional parameter is the title of an
;;; opened window and the second is the name of a model. The next 2 are
;;; the x and y coordinates of the attention point, and the last is a string
;;; indicating the name of a color in which any marker should be drawn.
;;; The color value could be anything because it is user specifiable so
;;; it is up to the handler to map that name to an appropriate color if
;;; possible. The default color, which should always be handled properly,
;;; is "red" and a good starting point for other colors to expect are those
;;; which the vision module creates by default for a model: magenta, pink,
;;; brown, dark-green, dark-red, gray, blue, purple, white, dark-cyan,
;;; dark-magenta, dark-blue, light-gray, dark-yellow, yellow, light-blue,
;;; cyan, dark-gray, green, and black.
;;;
;;; clearattention
;;; It will be passed 2 additional items. The first is the title of an
;;; opened window and the second is the name of a model. If the handler
;;; has drawn a visual attention marker in the window for the named model
;;; it should be removed when this is called.
;;;
;;; click
;;; It will be passed 2 additional items. When the model presses a button
;;; that has been added to the window this action will be called with the
;;; title of the window and the id which was given to the button as the
;;; parameters respectively. This is provided so that the handler can
;;; adjust the display of the button in response to the click if desired,
;;; but should not result in additional function calls because the 'action'
;;; of the button is handled by the AGI code itself.
;;;
;;; cursor
;;; It will be passed 5 additional items. When the model moves the mouse
;;; in the window this action will be called with the title of the window,
;;; the name of the model, the x position (local to the window), the y
;;; position (local to the window), and a color name which defaults to black.
;;;
;;; clearcursor
;;; It will be passed 2 additional items. When the model moves the mouse
;;; out of the window this action will be called with the title of the window
;;; and the name of the model respectively.
;;; If the handler wants to send 'real' interactions back to the system then
;;; it can call output-key directly to provide keyboard input. That should
;;; specify a model of "nil" to indicate it was not generated by a model,
;;; and all key names should be converted to the appropriate string for the
;;; model's keyboard for consistency e.g. the '-' key is called "minus" in
;;; Tcl/Tk (the language used for the ACT-R Environment which can be used to
;;; display visible virtual windows) which should be translated to the string
;;; "-" since that is the name that the default keyboard uses. To send mouse
;;; clicks it should call the "visible-virtual-window-mouse-click" command
;;; providing three values: the window's title, the x position of the click,
;;; and the y position of the click where the x,y coordinate are relative to
;;; the window itself not the global screen coordinates i.e. clicking the
;;; upper-left corner of the window would result in a 0,0 click. It should
;;; not perform any actions as a result of the click i.e. calling functions
;;; for button presses (other than perhaps a local function which sends the
;;; click notice to the system) because that should be determined by the
;;; internal window handler code so that all handlers displaying a visible-
;;; virtual window will be updated the same way in response.
;;;
#+: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 t) t) click-the-mouse))
;;; virtual windows which can be sent out to 'handlers' for actual
;;; display -- thus "visible" virtual windows.
;;;
;;; Inherits much of the functionality from the rpm-virtual-window
;;; but needs to send the commands to remote handlers.
(defclass visible-virtual-window (rpm-virtual-window)
((window-fixation-shown :accessor window-fixation-shown :initform nil)
(display-handlers :accessor display-handlers :initform nil :initarg :display-handlers))
)
(defmethod visible-rpm-window ((win visible-virtual-window))
t)
(defclass env-text-vdi (static-text-vdi)
((f-size :accessor f-size :initarg :font-size))
(:default-initargs
:id (string-downcase (symbol-name (new-symbol-fct "VVTEXT")))))
(defclass env-button-vdi (button-vdi)
()
(:default-initargs
:id (string-downcase (symbol-name (new-symbol-fct "VVBUTTON")))))
(defclass env-line-vdi (v-liner)
()
(:default-initargs
:id (string-downcase (symbol-name (new-symbol-fct "VVLINE")))))
(defstruct virtual-window-control
(lock (bt:make-lock "Virtual Window Control"))
handlers)
(defvar *vw-control* (make-virtual-window-control))
(defun add-virtual-window-handler (cmd &optional (displayer? t))
(if (check-act-r-command cmd)
(bt:with-lock-held ((virtual-window-control-lock *vw-control*))
(push (cons cmd displayer?) (virtual-window-control-handlers *vw-control*))
t)
nil))
(defun remove-virtual-window-handler (cmd)
(bt:with-lock-held ((virtual-window-control-lock *vw-control*))
(if (find cmd (virtual-window-control-handlers *vw-control*) :test 'string= :key 'car)
(progn
(setf (virtual-window-control-handlers *vw-control*)
(remove cmd (virtual-window-control-handlers *vw-control*) :test 'string= :key 'car))
t)
nil)))
(add-act-r-command "add-virtual-window-handler" 'add-virtual-window-handler "Add a handler to be notified of AGI visible virtual window updates. Params: interface-cmd {display-handler?}.")
(add-act-r-command "remove-virtual-window-handler" 'remove-virtual-window-handler "Remove a handler from AGI visible virtual window updates. Params: interface-cmd.")
(defmethod send-update-to-handlers ((win visible-virtual-window) params)
(let (remove)
(dolist (x (bt:with-recursive-lock-held ((window-lock win)) (display-handlers win)))
(unless (evaluate-act-r-command x params)
(push x remove)))
(when remove
(bt:with-recursive-lock-held ((window-lock win))
(dolist (x remove)
(setf (display-handlers win) (remove x (display-handlers win))))))))
(defun check-with-environment-for-visible-virtuals ()
"Return whether or not the visible-virtuals are available"
(bt:with-lock-held ((virtual-window-control-lock *vw-control*))
(let ((display nil)(others nil))
(dolist (x (virtual-window-control-handlers *vw-control*) (when display (append display others)))
(if (and (stringp (car x)) (local-or-remote-function-p (car x)))
(if (cdr x)
(when (dispatch-apply (car x) (list "check"))
(push (car x) display))
(push (car x) others))
(progn
(setf (virtual-window-control-handlers *vw-control*) (remove x (virtual-window-control-handlers *vw-control*)))
(print-warning "Virtual window handler ~s removed because no longer valid." (car x))))))))
;; Window control actions
(defmethod initialize-instance :after ((win visible-virtual-window) &key)
(bt:with-recursive-lock-held ((window-lock win))
(setf (window-fixation-shown win) nil)
(dolist (x (display-handlers win))
(dispatch-apply x (list "open" (window-title win) (x-pos win) (y-pos win) (width win) (height win))))))
(defmethod select-rpm-window ((win visible-virtual-window))
(send-update-to-handlers win (list "select" (window-title win))))
(defmethod close-rpm-window ((win visible-virtual-window))
(call-next-method)
(send-update-to-handlers win (list "close" (window-title win))))
;; Model interface actions
(defmethod vv-click-event-handler ((btn env-button-vdi) where)
(declare (ignore where))
(bt:with-recursive-lock-held ((dialog-item-lock btn))
;; Always send the click notice over
(awhen (view-container btn)
(send-update-to-handlers it (list "click" (window-title it) (id btn)))))
;; let the button-vdi method do the real work ...
(call-next-method))
(defmethod device-move-cursor-to ((vw visible-virtual-window) (loc vector))
(bt:with-recursive-lock-held ((window-lock vw))
(let* ((val (get-parameter-value :needs-mouse))
(color (color->name val)))
(if (and (> (length loc) 0) (point-in-vv-p vw loc))
(progn
(send-update-to-handlers vw (list "cursor" (window-title vw) (current-model) (- (px loc) (x-pos vw)) (- (py loc) (y-pos vw)) color))
(pushnew (current-model) (cursor-drawn vw)))
(when (find (current-model) (cursor-drawn vw))
(send-update-to-handlers vw (list "clearcursor" (window-title vw) (current-model)))
(setf (cursor-drawn vw) (remove (current-model) (cursor-drawn vw))))))))
;; Real interaction with the window
(defun visible-virtual-window-mouse-click (win-name x y)
(let ((win (determine-exp-window (agi-component) win-name)))
(if win
(let ((global-x (+ x (x-pos win)))
(global-y (+ y (y-pos win))))
(click-the-mouse nil (list global-x global-y) 'index)
;(vv-handle-click win (vector global-x global-y))
(vector global-x global-y))
(print-warning "Mouse click reported in window ~s at ~s,~s but does not correspond to a valid window." win-name x y))))
(add-act-r-command "visible-virtual-window-mouse-click" 'visible-virtual-window-mouse-click "Report a real mouse click interaction with a visible virtual window. Params: window-title click-x-pos click-y-pos.")
(defmethod env-window-features ((item env-button-vdi))
(list "button" (list (id item)
(x-pos item) (y-pos item) (width item)
(height item) (dialog-item-text item)
(color->name (color item)))))
(defmethod env-window-features ((item env-text-vdi))
(list "text" (list (id item)
(x-pos item) (y-pos item)
(dialog-item-text item)
(color->name (color item))
(round (f-size item)))))
(defmethod env-window-features ((item env-line-vdi))
(list "line" (list (id item)
(x-pos item) (y-pos item)
(width item) (height item)
(color->name (color item)))))
;; Adding window elements
(defmethod add-visual-items-to-rpm-window ((win visible-virtual-window) &rest items)
(bt:with-recursive-lock-held ((window-lock win))
(dolist (item items)
(add-subviews win item)
(let ((details (env-window-features item)))
(send-update-to-handlers win (concatenate 'list (list (first details) (window-title win))
(second details)))))))
(defmethod remove-visual-items-from-rpm-window ((win visible-virtual-window) &rest items)
(bt:with-recursive-lock-held ((window-lock win))
(dolist (item items)
(remove-subviews win item)
(send-update-to-handlers win (list "remove" (window-title win) (id item))))))
(defmethod remove-all-items-from-rpm-window ((win visible-virtual-window))
(call-next-method)
; (send-update-to-handlers win (list "clear" (window-title win)))
)
;; Creating the underlying objects
(defmethod make-button-for-rpm-window ((win visible-virtual-window)
&key (x 0) (y 0) (text "Ok")
(action nil) (height 18) (width 60) (color 'gray))
(make-instance 'env-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 make-static-text-for-rpm-window ((win visible-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 'env-text-vdi
:x-pos x
:y-pos y
:dialog-item-text text
:height height
:width width
:color color
:font-size font-size
: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 make-line-for-rpm-window ((win visible-virtual-window)
start-pt end-pt &optional (color 'black))
(make-instance 'env-line-vdi
:color color
:x-pos (first start-pt)
:y-pos (second start-pt)
:width (first end-pt)
:height (second end-pt)
:lock (window-lock win)))
;;; modify items
(defmethod modify-text-for-rpm-window ((text-item env-text-vdi) &key &allow-other-keys)
"Modify a text item for the rpm window"
(call-next-method)
(bt:with-recursive-lock-held ((dialog-item-lock text-item))
(awhen (view-container text-item) ;; it's on the screen
;; simple approach for the remote handlers -- remove it then add it back
(remove-visual-items-from-rpm-window it text-item)
(add-visual-items-to-rpm-window it text-item))
text-item))
(defmethod modify-line-for-rpm-window ((line env-line-vdi) start-pt end-pt &key &allow-other-keys)
(declare (ignorable start-pt end-pt))
(call-next-method)
(bt:with-recursive-lock-held ((dialog-item-lock line))
(awhen (view-container line) ;; it's on the screen
;; simple approach for the remote handlers -- remove it then add it back
(remove-visual-items-from-rpm-window it line)
(add-visual-items-to-rpm-window it line))
line))
(defmethod modify-button-for-rpm-window ((button-item env-button-vdi) &key &allow-other-keys)
"Modify a button item for the rpm window"
(call-next-method)
(bt:with-recursive-lock-held ((dialog-item-lock button-item))
(awhen (view-container button-item) ;; it's on the screen
;; simple approach for the remote handlers -- remove it then add it back
(remove-visual-items-from-rpm-window it button-item)
(add-visual-items-to-rpm-window it button-item))
button-item))
#|
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
|#
| 35,077 | Common Lisp | .lisp | 646 | 51.078947 | 209 | 0.625448 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a4eb1756709a08893e922ed55c1de3b45842220ee9fcc7a4c9d79f7bc03eadb2 | 14,152 | [
-1
] |
14,153 | environment-loader.lisp | asmaloney_ACT-R/tools/environment-loader.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 : environment-loader.lisp
;;; Version : 3.0
;;;
;;; Description :
;;; : Just use a simple load file to get the environment files loaded.
;;; Bugs :
;;;
;;; Todo :
;;;
;;; ----- History -----
;;;
;;; 05/30/2002 Dan
;;; : Added this header and merged the ACL/MCL loaders
;;; 08/15/2002 Dan
;;; : Added the LispWorks loader.
;;; 10/01/2002 Dan
;;; : Updated version to 1.1 and fixed the packaging
;;; : for building a standalone in ACL.
;;; : Added standalone.lisp to the file list.
;;; 08/15/2003 Dan
;;; : Updated to version 1.3
;;; : Added the loader for CMUCL from Ethan Glasser-Camp at RPI.
;;; 4/22/2004 Dan [1.5]
;;; : Removed the standalone.lisp from the list unless needed.
;;; : Added the license info.
;;; ------------------------------------------------------------------------
;;; 2005.04.12 Dan [2.0]
;;; 2005.08.10 Dan
;;; : * Minor clean-up to remove a warning - wrapped the require
;;; : for ACL in an eval-when
;;; 2007.01.17 Dan
;;; : * Updated for use with SBCL (except that most versions of
;;; : SBCL don't have threads so the environment isn't available
;;; : anyway).
;;; 2010.11.02 Dan
;;; : * Added a hack to skip this for ABCL since it throws an
;;; : error and I haven't created the appropriate uni-file
;;; : additions for it yet anyway.
;;; 2012.09.07 Dan
;;; : * Removed everything using the :ACTR-ENV-ALONE switches and
;;; : some other code that was commented out long ago.
;;; : * Moved the allegro require :sock to uni-files.
;;; 2015.07.28 Dan
;;; : * Updated the logical pathnames to use ACT-R and ACT-R-support.
;;; 2017.09.06 Dan [3.0]
;;; : * Strip out the mcl version and get rid of the files that
;;; : aren't needed any more.
;;; 2017.09.13 Dan
;;; : * Take env-device out of the list.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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)
;;; First, add an environment indicator to the features list
;;; so that I can test for it in the "experiment library" files
;;; of RPM when I move the UWI Tcl-side.
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :actr-environment *features*))
(defparameter *environment-file-list* '("server.lisp"
"environment-cmds.lisp"
"stepper-control.lisp"
))
#+:abcl (setf *environment-file-list* nil)
;;; Finally, just loop over the file list and load them
(dolist (x *environment-file-list*)
(compile-and-load (translate-logical-pathname (format nil "ACT-R:environment;~a" x))))
#|
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
|#
| 4,313 | Common Lisp | .lisp | 93 | 43.774194 | 88 | 0.571191 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 9290564cf8b642215d704078687d41398ab55afcd77201fed2eeedb8c111baa1 | 14,153 | [
-1
] |
14,154 | image-feature.lisp | asmaloney_ACT-R/tools/image-feature.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 : image-feature.lisp
;;; Version : 1.1
;;;
;;; Description : Provides an image item for the virtual windows of the AGI which
;;; can display a .gif through the visible virtual windows.
;;; Bugs :
;;;
;;; Todo :
;;;
;;; ----- History -----
;;; 18.01.31 Dan Bothell
;;; : * This was an example previously, but since it has too much
;;; : "internal" code now it's not suitable as an example and I'm
;;; : just rolling it into the sources. It does however get tied
;;; : in through some extensions I've added which makes it an
;;; : example for me of using those extensions.
;;; 18.03.14 Dan
;;; : * Update the build-vis-locs-for method since that doesn't
;;; : get the vision module any more.
;;; 18.03.19 Dan
;;; : * Add the window position to make visual-location in gloabl
;;; : coordinates not local.
;;; 18.04.27 Dan
;;; : * Copied the code for modifying buttons in here as a reference,
;;; : but not yet adding a modify-image... because it doesn't have
;;; : the subclass for a visible virtual window yet.
;;; 18.05.02 Dan
;;; : * Updated because of new add-visicon-features spec.
;;; 18.06.14 Dan
;;; : * Don't need to double-quote strings for the visicon features.
;;; 18.06.22 Dan
;;; : * Use keyword params instead of optional and options list for
;;; : remote versions.
;;; 18.07.17 Dan
;;; : * Fix a bug with the call to create-image-... in add-image-...
;;; 2018.08.03 Dan
;;; : * Updated the click handler to test things like the button
;;; : handler does.
;;; 2019.08.27 Dan
;;; : * Use new-symbol-fct instead of new-name-fct because it can be
;;; : used when there isn't a current model.
;;; 2021.05.11 Dan
;;; : * Changed reference to GUI directory to gui to avoid issues
;;; : with logical pathnames (particularlly in SBCL).
;;; 2022.03.02 Dan [1.1]
;;; : * Added the :clickable keyword parameter to create-image-...
;;; : and add-image-... so that one can turn off the response to
;;; : clicks if needed, for example when placing other items that
;;; : are clickable (like buttons) overlapping an image.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Create a new virtual dialog item called an image which can be used to draw
;;; .gif files in the visible virtual windows if those images are located in the
;;; gui/AGI-images directory of the Environment.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; Two functions are provided for using them like the other AGI elements:
;;;
;;; create-image-for-exp-window (win text file &key (x 0) (y 0) (width 50) (height 50) (action nil) (clickable t))
;;;
;;; and
;;;
;;; add-image-to-exp-window (win text file &key (x 0) (y 0) (width 50) (height 50) (action nil) (clickable t))
;;;
;;; Win is the window reference (as with other AGI items), text is a string which
;;; will be the value the model sees for attending the item. File should be the
;;; name of a file in the gui/AGI-images directory of the Environment to display
;;; in the visible virtual window. X and y are the coordinates for the upper left
;;; corner of the image in the window. Width and height specify the size of the
;;; image for display purposes and the .gif file will be clipped to fit if
;;; needed (it does not scale, center, or otherwise attempt to fit that space).
;;; If clickable is specified as non-nil (the default) then an action function
;;; can be set, otherwise the image will ignore mouse clicks. Action specifies a
;;; user function to call when the mouse is clicked within the boundaries of the
;;; image, and it can be specified the same way as button actions:
;;; a valid command string, a Lisp function, a symbol naming a Lisp function, or
;;; a list where the first item is a command/function and the remaining items
;;; are values which will be passed to that function. If it is not a list, then
;;; the command/function will be passed two items. The text for the image object
;;; and the relative position within the image where it was clicked as a 2
;;; element list.
;;;
;;;
;;; These calls (assuming there is only one open experiment window):
;;;
;;; (add-image-to-exp-window nil "logo" "smalllogo.gif" :x 10 :y 10 :width 288 :height 142)
;;;
;;; (add-items-to-exp-window win (create-image-for-exp-window nil "brain" "ref-brain.gif" :x 10 :y 160 :width 128 :height 128))
;;;
;;; will result in these visicon features:
;;;
;;; Name Att Loc Height Width Kind Value Size
;;; ---------------- --- -------------- ------ ----- ----- ------- ----------
;;; VISUAL-LOCATION1 NEW ( 74 224 1080) 128 128 IMAGE "brain" 46.0
;;; VISUAL-LOCATION0 NEW (154 81 1080) 142 288 IMAGE "logo" 114.259995
;;;
;;; and these visual chunks for the second item:
;;;
;;; VISUAL-LOCATION0-0-0
;;; KIND IMAGE
;;; VALUE IMAGE
;;; HEIGHT 142
;;; WIDTH 288
;;; DISTANCE 1080
;;; SCREEN-X 154
;;; SCREEN-Y 81
;;; SIZE 114.259995
;;;
;;;
;;; IMAGE0-0
;;; SCREEN-POS VISUAL-LOCATION0-0-0
;;; VALUE "logo"
;;; HEIGHT 142
;;; WIDTH 288
;;; DISTANCE 1080
;;; IMAGE T
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Implemented using the extension mechanisms that I added to the AGI and
;;; Environment visible-virtual window code to make it possible to add new items
;;; without having to redefine things as was needed previously.
;;; This goes along with the 999-image-item.tcl file to provide the corresponding
;;; display support.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
;;; The first step for creating a new virtual feature is to create a subclass
;;; of the virtual-dialog-item and rpm-dialog-item classes. Any new slots
;;; necessary for that class can be added, and it should automatically create
;;; a unique id.
(defclass image-vdi ( virtual-dialog-item)
((file :accessor file :initform nil :initarg :file))
(:default-initargs
:id (string-downcase (symbol-name (new-symbol-fct "IMAGE-VDI"))) ;; make sure it gets a unique name
:handles-click-p t ;; indicate that this item can be clicked on by a model
:action nil))
(defun default-image-action (text position)
(print-warning "Image ~s with no valid action clicked at position ~d,~d at time ~S." text (first position) (second position) (mp-time)))
;;; The function for creating one which handles all the AGI setup necessary for
;;; recording and accessing the underlying object cleanly.
(defun create-image-for-exp-window (win text file &key (x 0) (y 0) (width 50) (height 50) (action nil) (clickable t))
"Creates an image item for the experiment window"
;(when (and win (symbolp win))
; (setf win (symbol-name win)))
; should be more error checking...
(let ((agi (agi-component)))
(multiple-value-bind (window key) (determine-exp-window agi win)
(if window
(let* ((item (make-instance 'image-vdi
:x-pos x
:y-pos y
:dialog-item-text text
:action (when clickable
(if (valid-button-action action)
action
'default-image-action))
:handles-click-p clickable
:height height
:width width
:file file
:lock (window-lock window)))
(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 image item. No image created.")))
(print-warning "No window available for creating an image.")))))
(defun external-create-image-for-exp-window (win text file &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'create-image-for-exp-window '(:x :y :height :width :action :clickable))
(when valid
(apply 'create-image-for-exp-window win text file ol))))
(add-act-r-command "create-image-for-exp-window" 'external-create-image-for-exp-window "Create an image item for the provided experiment window with the features specified. Params: window text file {< x, y, width, height, action, clickable >}.")
(defun add-image-to-exp-window (win text file &key (x 0) (y 0) (width 50) (height 50) (action nil) (clickable t))
"Create and display an image item in the experiment window"
(when (and win (symbolp win))
(setf win (symbol-name win)))
(let ((item-key (create-image-for-exp-window win text file :x x :y y :width width :height height :action action :clickable clickable)))
(if item-key
(if (add-items-to-exp-window win item-key)
item-key
nil)
nil)))
(defun external-add-image-to-exp-window (win text file &optional params)
(multiple-value-bind (valid ol)
(process-options-list params 'add-image-to-exp-window '(:x :y :height :width :action :clickable))
(when valid
(apply 'add-image-to-exp-window win text file ol))))
(add-act-r-command "add-image-to-exp-window" 'external-add-image-to-exp-window "Create an image item for the provided experiment window with the features specified and place it in the window. Params: window text file {<x, y, width, height, action, clickable >}.")
;;; The vv-click-event-handler is the method which must be written
;;; to actually process the click which the model produces. This is
;;; the internal virtual window method that gets called and we use
;;; that to call the action function for the image-vdi item.
(defmethod vv-click-event-handler ((self image-vdi) position)
(if (listp (action-function self))
(cond ((stringp (first (action-function self)))
(multiple-value-bind (success result)
(apply 'evaluate-act-r-command (first (action-function self)) (rest (action-function self)))
(unless success
(print-warning "Image click action ~s reported error ~s." (action-function self) result))))
((or (functionp (first (action-function self)))
(and (symbolp (first (action-function self)))
(fboundp (first (action-function self)))
(not (macro-function (first (action-function self))))))
(apply (first (action-function self)) (rest (action-function self))))
(t
(default-image-action (dialog-item-text self)
(list (- (px position) (x-pos self))
(- (py position) (y-pos self))))))
(cond ((stringp (action-function self))
(multiple-value-bind (success result)
(apply 'evaluate-act-r-command (action-function self) (list (dialog-item-text self)
(list (- (px position) (x-pos self))
(- (py position) (y-pos self)))))
(unless success
(print-warning "Image click action ~s reported error ~s." (action-function self) result))))
((or (functionp (action-function self))
(and (symbolp (action-function self))
(fboundp (action-function self))
(not (macro-function (action-function self)))))
(apply (action-function self) (list (dialog-item-text self)
(list (- (px position) (x-pos self))
(- (py position) (y-pos self))))))
(t
(default-image-action (dialog-item-text self)
(list (- (px position) (x-pos self))
(- (py position) (y-pos self))))))))
;;; The build-vis-locs-for method is typically written for the
;;; whole device, but the virtual windows in ACT-R extend that so
;;; that the device actually calls that method for each of the
;;; items in the window to create the features. It needs to
;;; return the feature list for the visual information desired.
(defmethod build-vis-locs-for ((self image-vdi))
(let* ((top (find-top-level-window self))
(top-xy (bt:with-recursive-lock-held ((window-lock top)) (vector (x-pos top) (y-pos top)))))
(unless (chunk-p image)
(define-chunks (image name image)))
(unless (chunk-type-p image)
(chunk-type (image (:include visual-object)) (image t)))
`((isa (visual-location image)
value (image ,(format nil "~a" (dialog-item-text self)))
screen-x ,(+ (px top-xy) (x-pos self) (round (width self) 2))
screen-y ,(+ (py top-xy) (y-pos self) (round (height self) 2))
width ,(width self)
height ,(height self)))))
;;; This method is used by the extension to the visible-virtual handler
;;; to create the feature list that is sent to the Environment. It
;;; needs an appropriate handler defined to process it (which is in the
;;; 999-image-item.tcl file).
(defmethod env-window-features ((item image-vdi))
(list "image" (list (id item) (x-pos item) (y-pos item)
(file item) (width item) (height item))))
#|
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,664 | Common Lisp | .lisp | 294 | 47.061224 | 263 | 0.596564 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 184c7a2e1d472c982c476a2d830a65625994250b046fac5fc84961a9af1e3d15 | 14,154 | [
-1
] |
14,155 | perceptual-compilation.lisp | asmaloney_ACT-R/tools/perceptual-compilation.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 : perceptual-compilation.lisp
;;; Version : 4.1
;;;
;;; Description : Production compilation PERCEPTUAL style definition.
;;;
;;; Bugs :
;;;
;;; To do :
;;; ----- History -----
;;;
;;; 2010.12.06 Dan
;;; : * Created automatically by build-compilation-type-file.
;;; : * Added the details of the functions.
;;; 2012.04.04 Dan [1.1]
;;; : * Added the whynot reason function.
;;; 2014.05.07 Dan [2.0]
;;; : * Start of conversion to typeless chunks.
;;; 2019.04.26 Dan [3.0]
;;; : * Allow compilation of perceptual buffers when strict harvesting
;;; : is turned off over cases which would be stuffed buffers when
;;; : it is on.
;;; 2020.06.22 Dan [4.0]
;;; : * The functions are now all passed the same set of parameters:
;;; : buffer module p1 p1-s p1-index p2 p2-s p2-index
;;; : the p1-s and p2-s are the new "standard" representation that
;;; : can be decomposed with composition-rep-* where * is:
;;; : op -- the character of the operation =,?,!,+,-,*,@
;;; : name -- the symbol naming the buffer or bang action
;;; : token -- the symbol of the production item for op and name
;;; : slots -- list of slot-spec lists
;;; 2020.11.05 Dan [4.1]
;;; : * Drop buffer empty queries that occur in p2 if the buffer
;;; : was strict harvested from p1 otherwise you end up with a
;;; : production that can't fire since it tests for both there
;;; : being a chunk in the buffer and a query that it's empty.
;;; 2020.11.10 Dan
;;; : * Fixed the typo of modfication in the failure strings.
;;; 2021.02.17 Dan
;;; : * Updated the calls to buffer-condition-union since that needs
;;; : a 4th parameter of bindings that may be needed deal with
;;; : dynamic issues (not needed for perceptual).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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 COMPOSE-PERCEPTUAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore p1 p2 p2-index))
;; This is based on the limited set of conditions that can
;; be composed.
;;
;; There are no buffer modification actions allowed.
;;
;; The constraints are:
;;
;;
;; If the first production doesn't mention the buffer
;; or make a request (0)
;; any = condition, query and action are used from the second
;; If the first production makes a request without a query (4, 12)
;; any = condition in the first production is used, there
;; are no queries and the action from the first is used
;; If the first production tests the buffer but doesn't make
;; any queries or requests (8)
;; any = condition in the first is used along with any
;; query from the second and the action of the second
;; If the first a query and no request (16, 24)
;; any = condition in either (there can be at most 1) is used
;; along with the query from the first and the action
;; of the second
;; If the first has both a query and a request (20, 28)
;; the = condition query and action from the first are used
(let ((c1 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(c2 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(q1 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(q2 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(a1+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s))))
(case p1-index
(0
(list (append
(when c2
(list c2))
(when q2
(list q2)))
(when a2+
(list a2+))))
((4 12)
(list (when c1
(list c1))
(when a1+
(list a1+))))
(8
(list (append
(awhen (buffer-condition-union c1 c2 nil nil)
(list it))
(if q2
(if (find buffer (compilation-module-no-harvest module))
(list q2)
;; strict harvested so need to ignore a buffer empty query from p2
(let ((slots (compose-rep-slots q2)))
(setf slots (remove '(= buffer empty) slots :test 'equalp))
(if slots
(list (list (first q2) slots)) ;; building a compose-rep explicitly because don't want to destructively modify
nil)))
nil))
(when a2+
(list a2+))))
((16 24)
(list (append
(awhen (buffer-condition-union c1 c2 nil nil)
(list it))
(when q1
(list q1)))
(when a2+
(list a2+))))
((20 28)
(list (append
(when c1
(list c1))
(when q1
(list q1)))
(when a1+
(list a1+)))))))
(defun P-B-C1 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Compilation check for queries such that p2 only uses 'buffer empty' or
'state busy'"
(declare (ignore module p1 p1-s p1-index p2 p2-index))
(let ((query (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))))
(every (lambda (x)
(or
(equalp x '(= state busy))
(equalp x '(= buffer empty))))
(compose-rep-slots query))))
(defun P-B-C2 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"queries in p1 and p2 must be the same
NOTE: this doesn't take into account any variables at this time"
(declare (ignore module p1 p1-index p2 p2-index))
(let ((query1 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p1-s))
(compose-rep-slots it)))
(query2 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(compose-rep-slots it))))
(= (length query1) (length query2)
(length (remove-duplicates (append query1 query2) :test 'equal)))))
(defun P-B-C3 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"only if the buffer is not strict harvested"
(declare (ignore p1 p1-s p1-index p2 p2-s p2-index))
(find buffer (compilation-module-no-harvest module)))
(defun P-B-C4 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Not strict harvested and same queries"
(and (p-b-c2 buffer module p1 p1-s p1-index p2 p2-s p2-index) (p-b-c3 buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun perceptual-reason (p1-index p2-index failed-function)
(cond ((eql failed-function 'p-b-c1)
"when the first production makes a request and the second does not harvest it the second can only query for state busy or buffer empty.")
((eql failed-function 'p-b-c2)
"the queries in both productions must be the same.")
((> p1-index 30)
"buffer modification actions in first production are not allowed.")
((> p2-index 30)
"buffer modification actions in second production are not allowed.")
(t
(case p1-index
((9 11 13 15 25 27 29)
"buffer modification actions in first production are not allowed.")
((2 6 10 14 18 22 26 30)
"the buffer is explicitly cleared in the first production.")
(t
(case p2-index
((2 6 10 14 18 22 26 30)
"the buffer is explicitly cleared in the second production.")
((9 11 13 15 25 27 29)
"buffer modification actions in second production are not allowed.")
((4 20)
"both productions make a request.")
(t
(case p1-index
((4 12 20 28)
"the first production makes a request and the second production harvests the chunk.")
(t
"the second production harvests a chunk which is there because of buffer stuffing or because strict harvesting has been disabled.")))))))))
(define-compilation-type PERCEPTUAL ((28 16 P-B-C1)
(28 0 T)
(24 28 P-B-C4)
(24 24 P-B-C4)
(24 20 P-B-C2)
(24 16 P-B-C2)
(24 12 P-B-C3)
(24 8 P-B-C3)
(24 4 T)
(24 0 T)
(20 16 P-B-C1)
(20 0 T)
(16 28 P-B-C2)
(16 24 P-B-C2)
(16 20 P-B-C2)
(16 16 P-B-C2)
(16 12 T)
(16 8 T)
(16 4 T)
(16 0 T)
(12 16 P-B-C1)
(12 0 T)
(8 28 P-B-C3)
(8 24 P-B-C3)
(8 20 T)
(8 16 T)
(8 12 P-B-C3)
(8 8 P-B-C3)
(8 4 T)
(8 0 T)
(4 16 P-B-C1)
(4 0 T)
(0 28 T)
(0 24 T)
(0 20 T)
(0 16 T)
(0 12 T)
(0 8 T)
(0 4 T))
(VISUAL-LOCATION VISUAL AURAL-LOCATION AURAL TEMPORAL) NIL COMPOSE-PERCEPTUAL-BUFFER NIL NIL NIL perceptual-reason)
#|
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
|#
| 12,746 | Common Lisp | .lisp | 255 | 36.227451 | 158 | 0.484675 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 80147f530fa85d340140ed268d27dbe7156eb8d3978c3d0ec25f4ef1abf8ecf3 | 14,155 | [
-1
] |
14,156 | imaginal-compilation.lisp | asmaloney_ACT-R/tools/imaginal-compilation.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 : imaginal-compilation.lisp
;;; Version : 6.0
;;;
;;; Description : Production compilation IMAGINAL style definition.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2010.12.10 Dan
;;; : * Created automatically by build-compilation-type-file.
;;; 2010.12.13 Dan
;;; : * Put the control functions and tests in place.
;;; 2010.12.15 Dan
;;; : * Added module to the mapping functions args list.
;;; 2010.12.20 Dan
;;; : * Added some additional code to handle things better when
;;; : :ppm is enabled -- creates productions that match more closely
;;; : to the same conditions as the original pair did and does
;;; : the "same" thing.
;;; : * Allow subtypes to be composed in the consistency check.
;;; 2011.01.07 Dan
;;; : * Fixed a bug with map-imaginal-buffer since it needs to be a
;;; : let* for ppm to be used.
;;; 2011.04.28 Dan
;;; : * Added some declares to avoid compiler warnings.
;;; 2012.04.04 Dan [1.1]
;;; : * Added the whynot reason function.
;;; 2014.05.07 Dan [2.0]
;;; : * Start of conversion to typeless chunks.
;;; : * Pass the module to constant-value-p.
;;; : * References to compilation-module-previous are now using a
;;; : structure instead of list.
;;; 2016.08.04 Dan [3.0]
;;; : * Updated the compilation type definition with one that was
;;; : created automatically by build-compilation-type-file from the
;;; : new spreadsheet that better handles "safe" compilation based
;;; : on whether the buffer is strict harvested or not. Also added
;;; : some cases which should have been allowed but weren't like 13,40
;;; : where the * in the second can be combined with the + from the
;;; : first and 40,9 which can combine an = with a preceeding * (there
;;; : are some other similar additions but not listing all of them here).
;;; : Those new cases make things more consistent with respect to the
;;; : indicated constraints.
;;; : * Added the code necessary to deal with the new cases and the
;;; : new test functions.
;;; 2020.06.22 Dan [4.0]
;;; : * The functions are now all passed the same set of parameters:
;;; : buffer module p1 p1-s p1-index p2 p2-s p2-index
;;; : the p1-s and p2-s are the new "standard" representation that
;;; : can be decomposed with composition-rep-* where * is:
;;; : op -- the character of the operation =,?,!,+,-,*,@
;;; : name -- the symbol naming the buffer or bang action
;;; : token -- the symbol of the production item for op and name
;;; : slots -- list of slot-spec lists
;;; 2020.11.05 Dan [4.1]
;;; : * Drop buffer empty queries that occur in p2 if the buffer
;;; : was strict harvested from p1 otherwise you end up with a
;;; : production that can't fire since it tests for both there
;;; : being a chunk in the buffer and a query that it's empty.
;;; 2021.02.05 Dan [5.0]
;;; : * Allowing the 9,8 28,8 9,24 25,24 cases to happen if the mod
;;; : in p1 is an empty mod when the buffer is strict harvested
;;; : and then just drop the empty mod.
;;; 2021.02.10 Dan [6.0]
;;; : * There isn't a pre-instantiation step for variablized slots
;;; : now so that needs to be done here instead for both mapping
;;; : and composition.
;;; : * Needs to deal with var->var, const->var, var->const, and
;;; : the possibility of multiple vars being bound to the same
;;; : slot name.
;;; 2021.02.23 Dan
;;; : * Wasn't catching the possible dynamic action to action
;;; : mappings.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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 MAP-IMAGINAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"map references from p1 to p2 for imaginal style buffer"
;; Possible cases:
;; a RHS + to a LHS = (includes when the RHS has both + and =)
;; a RHS = to a LHS =
;; a LHS = with null RHS to a LHS =
;; a RHS * to a LHS =
(declare (ignore p1))
(let* ((ppm (compilation-module-ppm module))
(p1-bindings (previous-production-bindings (compilation-module-previous module)))
(p2-bindings (production-compilation-instan (production-name p2)))
(bindings (when ppm
(append p1-bindings p2-bindings))))
(cond (;; The RHS + to LHS = case
(and (find p1-index '(4 12 13 20 28 29))
(find p2-index '(8 9 12 13 24 25 28 29 40 56)))
;; Map the RHS +'s with the LHS ='s
;; here the slots of interest are just the intersection
;; of the two sets
;;
(let* ((mappings nil)
(original-p1-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(original-p2-rhs-slots (compose-rep-slots (find-if (lambda (x) (and (eq buffer (compose-rep-name x))
(or (char= #\= (compose-rep-op x))
(char= #\* (compose-rep-op x)))))
(second p2-s))))
(p1-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1-slots :key 'spec-slot-name)))
(p2-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-slots :key 'spec-slot-name)))
(p2-rhs-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-rhs-slots :key 'spec-slot-name)))
(p1-slots (instantiate-slot-names
original-p1-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(p2-rhs-slots (instantiate-slot-names
original-p2-rhs-slots
p2-bindings))
(interesting-slots (remove-duplicates (append (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-rhs-slots)))))
(dolist (slot interesting-slots)
(when (or p1-var-slots p2-var-slots p2-rhs-var-slots) ;; there are dynamic slots which may need to be mapped
;; if the same slot is variablized in both or a var slot maps
;; to a constant slot in either direction (multiple options
;; possible as well as multiple variables matching the same slot)
(when (and (rassoc slot p1-var-slots) ;; it's a variable in action and condition both
(rassoc slot p2-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in both actions
(rassoc slot p2-rhs-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 so need to instantiate
(find slot original-p2-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 action so need to instantiate
(find slot original-p2-rhs-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p2-var-slots) ;; it's a variable in p2 and const in p1 so need to instantiate
(find slot original-p1-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p2-var slot) mappings)))
(when (and (rassoc slot p2-rhs-var-slots) ;; it's a variable in p2 action and const in p1 so need to instantiate
(find slot original-p1-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p2-var slot) mappings))))
(dolist (p1slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(;; The RHS = to a LHS = case
(and (find p1-index '(9 25))
(find p2-index '(8 9 12 13 24 25 28 29)))
;; Map the RHS ='s and LHS ='s not in the RHS with
;; the LHS ='s
;; Here the slots of interest are the union of the
;; p1 bits with the RHS superseding the LHS intersected
;; with the LHS of the second one
(let* ((mappings nil)
(original-p1a-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s))))
(original-p1b-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(original-p2-rhs-slots (compose-rep-slots (find-if (lambda (x) (and (eq buffer (compose-rep-name x))
(or (char= #\= (compose-rep-op x))
(char= #\* (compose-rep-op x)))))
(second p2-s))))
(p1-var-slotsa (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1a-slots :key 'spec-slot-name)))
(p1-var-slotsb (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1b-slots :key 'spec-slot-name)))
(p2-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-slots :key 'spec-slot-name)))
(p2-rhs-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-rhs-slots :key 'spec-slot-name)))
(p1-slotsa (instantiate-slot-names
original-p1a-slots
p1-bindings))
(p1-slotsb (instantiate-slot-names
original-p1b-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(p2-rhs-slots (instantiate-slot-names
original-p2-rhs-slots
p2-bindings))
(p1-slots (append (remove-if (lambda (x)
(or (not (eq (spec-slot-op x) '=))
(find (spec-slot-name x) p1-slotsb :key 'spec-slot-name)))
p1-slotsa)
p1-slotsb))
(p1-var-slots (remove-duplicates (append p1-var-slotsa p1-var-slotsb) :test 'equalp))
(interesting-slots (remove-duplicates (append (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-rhs-slots)))))
(dolist (slot interesting-slots)
(when (or p1-var-slots p2-var-slots p2-rhs-var-slots) ;; there are dynamic slots which may need to be mapped
;; if the same slot is variablized in both or a var slot maps
;; to a constant slot in either direction (multiple options
;; possible as well as multiple variables matching the same slot)
(when (and (rassoc slot p1-var-slots) ;; it's a variable in both
(rassoc slot p2-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in both actions
(rassoc slot p2-rhs-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 so need to instantiate
(find slot original-p2-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in p1 and const in p2 action so need to instantiate
(find slot original-p2-rhs-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p2-var-slots) ;; it's a variable in p2 and const in p1 (somewhere) so need to instantiate
(or ;; all p2 vars
(find slot original-p1a-slots :key 'spec-slot-name)
(find slot original-p1b-slots :key 'spec-slot-name)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p2-var slot) mappings)))
(when (and (rassoc slot p2-rhs-var-slots) ;; it's a variable in p2 action and const in p1 so need to instantiate
(find slot original-p1b-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p2-var slot) mappings))))
(dolist (p1slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(;; The RHS * to a LHS = case
(and (find p1-index '(40 56))
(find p2-index '(8 9 24 25 40 56)))
;; Map the RHS *'s and LHS ='s not in the RHS with
;; the LHS ='s
;; Here the slots of interest are the union of the
;; p1 bits with the RHS superseding the LHS intersected
;; with the LHS of the second one
(let* ((mappings nil)
(original-p1a-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s))))
(original-p1b-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\* (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(original-p2-rhs-slots (compose-rep-slots (find-if (lambda (x) (and (eq buffer (compose-rep-name x))
(or (char= #\= (compose-rep-op x))
(char= #\* (compose-rep-op x)))))
(second p2-s))))
(p1-var-slotsa (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1a-slots :key 'spec-slot-name)))
(p1-var-slotsb (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1b-slots :key 'spec-slot-name)))
(p2-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-slots :key 'spec-slot-name)))
(p2-rhs-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-rhs-slots :key 'spec-slot-name)))
(p1-slotsa (instantiate-slot-names
original-p1a-slots
p1-bindings))
(p1-slotsb (instantiate-slot-names
original-p1b-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(p2-rhs-slots (instantiate-slot-names
original-p2-rhs-slots
p2-bindings))
(p1-slots (append (remove-if (lambda (x)
(or (not (eq (spec-slot-op x) '=))
(find (spec-slot-name x) p1-slotsb :key 'spec-slot-name)))
p1-slotsa)
p1-slotsb))
(p1-var-slots (remove-duplicates (append p1-var-slotsa p1-var-slotsb) :test 'equalp))
(interesting-slots (remove-duplicates (append (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-rhs-slots)))))
(dolist (slot interesting-slots)
(when (or p1-var-slots p2-var-slots p2-rhs-var-slots) ;; there are dynamic slots which may need to be mapped
;; if the same slot is variablized in both or a var slot maps
;; to a constant slot in either direction (multiple options
;; possible as well as multiple variables matching the same slot)
(when (and (rassoc slot p1-var-slots) ;; it's a variable in both
(rassoc slot p2-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in both actions
(rassoc slot p2-rhs-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 so need to instantiate
(find slot original-p2-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in p1 and const in p2 action so need to instantiate
(find slot original-p2-rhs-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p2-var-slots) ;; it's a variable in p2 and const in p1 (somewhere) so need to instantiate
(or ;; all p2 vars
(find slot original-p1a-slots :key 'spec-slot-name)
(find slot original-p1b-slots :key 'spec-slot-name)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p2-var slot) mappings)))
(when (and (rassoc slot p2-rhs-var-slots) ;; it's a variable in p2 action and const in p1 so need to instantiate
(find slot original-p1b-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p2-var slot) mappings))))
(dolist (p1slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(;; The LHS = RHS null to a LHS = case
(and (find p1-index '(8 24))
(find p2-index '(8 9 12 13 24 25 28 29 40 56)))
;; Map the LHS ='s with the LHS ='s
;; The slots of interest are the ones at the intersection of the
;; two sets - the mappings are then done for those
;; such that
;; - if it's a variable in both then p2 vars go to p1 vars
;; - if it's a constant in one then it goes from the var to the constant
;; (note that buffer variables are considered constants and not variables)
;; - if it's a constant in both we're in trouble if they aren't equal
;; because how did they fire...
;;
;; When there is more than one option we have to add both but they need to
;; be evaluated in the order of variables before constants (that's handled
;; elsewhere though)
(let* ((mappings nil)
(original-p1-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(p1-slots (instantiate-slot-names
original-p1-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(interesting-slots (intersection (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots))))
(dolist (slot interesting-slots)
;; no dynamic slot issues because can't make assumptions based on conditions alone
(dolist (p1slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(t
nil))))
(defun COMPOSE-IMAGINAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
;; Generally:
;; If the first has a + (4, 12, 13, 20, 28 29) then
;; the conditions are those of the first including a query
;; the actions are the = or * of the first if there is one and
;; the + will be the + of the first (can't be a + in the second)
;; with the = or * of the second unioned in and overriding
;; If the first has no actions (0, 8, 16 24)
;; the buffer conditions are the union of those in the first
;; and those of the second with the query from the first being
;; used if there is one (16 24) otherwise the query from the second
;; is used if there is one
;; the actions are those of the second
;; Otherwise (9 40 25 56)
;; the conditions are the union of those in the first
;; and those from the second that are not set by the
;; actions of the first If there is a query in the first it is
;; used (25 56) otherwise a query from the second is used
;; the actions are the = or * from the first with the = or * from
;; the second unioned in and overriding and
;; the + of the second if there is one
;;
(declare (ignore p1))
(let ((c1 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(c2 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(q1 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(q2 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(a1= (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2= (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s)))
(a1+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s)))
(a1* (find-if (lambda (x) (and (char= #\* (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2* (find-if (lambda (x) (and (char= #\* (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s)))
(bindings (append (previous-production-bindings (compilation-module-previous module))
(production-compilation-instan (production-name p2)))))
(case p1-index
((4 12 13 20 28 29)
(list (append
(when c1
(list c1))
(when q1
(list q1)))
(append
(when (or a1= a1*) ;; can't have both with current description
(if a1=
(list a1=)
(list a1*)))
(cond ((and a1+ a2=)
(awhen (buffer+-union a1+ a2= bindings)
(list it)))
((and a1+ a2*)
(awhen (buffer+-union a1+ a2* bindings)
(list it)))
(a1+
(list a1+))
(t
nil)))))
((0 8 16 24)
(list (append
(awhen (buffer-condition-union c1 c2 a1= bindings)
(list it))
(if q1
(list q1)
(if q2
(if (find buffer (compilation-module-no-harvest module))
(list q2)
;; strict harvested so need to ignore a buffer empty query from p2
(let ((slots (compose-rep-slots q2)))
(setf slots (remove '(= buffer empty) slots :test 'equalp))
(if slots
(list (list (first q2) slots)) ;; building a compose-rep explicitly because don't want to destructively modify
nil)))
nil)
))
(append
(when a2=
(list a2=))
(when a2*
(list a2*))
(when a2+
(list a2+)))))
((9 40 25 56)
(list (append
(awhen (buffer-condition-union c1 c2 (if a1= a1= a1*) bindings)
(list it))
(if q1
(list q1)
(if (and q2 ;; when it's a * followed by a state free query drop the query
(not (and (= p1-index 40) (or (= p2-index 24) (= p2-index 25) (= p2-index 56)))))
(list q2)
nil)))
(append (cond ((and (or (= p2-index 8) (= p2-index 24))
(not (find buffer (compilation-module-no-harvest module))) ;; it is strict harvested
(null (second a1=))) ;; the mod in a1 is a null mod
nil)
((and a1* a2=)
(awhen (buffer=-union a1* a2= bindings)
(list it)))
((or a1= a2=) ;; if there's at least one = union those
(awhen (buffer=-union a1= a2= bindings)
(list it)))
((or a1* a2*) ;; if there's at least one * union those
(awhen (buffer=-union a1* a2* bindings)
(list it)))
(t nil)) ;; can't have other mix of = and * so just ignore
(when a2+
(list a2+))))))))
(defun CHECK-IMAGINAL-CONSISTENCY (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore p1 p2-index))
(case p1-index
((4 12 13 20 28 29) ;; a RHS +
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\+)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
((9 25) ;; a RHS =
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
((40 56) ;; a RHS *
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\*)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
(t
t)))
(defun I-B-C3 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Compilation check queries in p2 for 'state free'"
(declare (ignore module p1 p1-s p1-index p2 p2-index))
;; there can be only one
(let ((query (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))))
(every (lambda (x)
(equalp x '(= state free)))
(compose-rep-slots query))))
(defun I-B-C1 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Compilation check for queries such that p2 only uses 'buffer empty' or 'state busy'"
(declare (ignore module p1 p1-s p1-index p2 p2-index))
(let ((query (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))))
(every (lambda (x)
(or
(equalp x '(= state busy))
(equalp x '(= buffer empty))))
(compose-rep-slots query))))
(defun NO-RHS-IMAGINAL-REF (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Can't compile if the variable naming the buffer is used in the actions of p2"
(declare (ignore module p1 p1-s p1-index p2 p2-index))
(not (recursive-find (intern (concatenate 'string "=" (symbol-name buffer)))
(second p2-s))))
(defun I-B-C4 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(and (i-b-c3 buffer module p1 p1-s p1-index p2 p2-s p2-index)
(no-rhs-imaginal-ref buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun I-B-C2 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"queries in p1 and p2 must be the same
NOTE: this doesn't take into account any variables at this time"
(declare (ignore module p1 p1-index p2 p2-index))
(let ((query1 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p1-s))
(compose-rep-slots it)))
(query2 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(compose-rep-slots it))))
(= (length query1) (length query2)
(length (remove-duplicates (append query1 query2) :test 'equal)))))
(defun I-B-C5 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"only if the buffer is not strict harvested"
(declare (ignore p1 p1-s p1-index p2 p2-s p2-index))
(find buffer (compilation-module-no-harvest module)))
(defun I-B-C6 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Not strict harvested and same queries"
(and (i-b-c5 buffer module p1 p1-s p1-index p2 p2-s p2-index)
(i-b-c2 buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun I-B-C7 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Not strict harvested and no RHS imaginal references"
(and (i-b-c5 buffer module p1 p1-s p1-index p2 p2-s p2-index)
(no-rhs-imaginal-ref buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun I-B-C8 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Not strict harvested and p2 query must be state free"
(and (i-b-c5 buffer module p1 p1-s p1-index p2 p2-s p2-index)
(i-b-c3 buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun I-B-C9 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore p1 p1-index p2 p2-s p2-index))
(or (find buffer (compilation-module-no-harvest module))
(let ((mod (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(and mod (null (second mod))))))
(defun I-B-C10 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Not strict harvested and p2 query must be state free"
(and (i-b-c2 buffer module p1 p1-s p1-index p2 p2-s p2-index)
(i-b-c9 buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun imaginal-reason (p1-index p2-index failed-function)
(cond ((eql failed-function 'no-rhs-imaginal-ref)
"the buffer variable cannot be used in the actions of the second production if there is a request in the first production.")
((eql failed-function 'i-b-c1)
"when the first production makes a request and the second does not harvest it the second can only query for state busy or buffer empty.")
((eql failed-function 'i-b-c2)
"the queries in both productions must be the same.")
((eql failed-function 'i-b-c3)
"when the first production makes a request and the second harvests it the second can only query for state free.")
((eql failed-function 'i-b-c4)
"when the first production makes a request and the second harvests it the second can only query for state free and the buffer variable cannot be used in the actions of the second.")
((eql failed-function 'i-b-c5)
"strict harvesting is enabled for the buffer and either the first production cleared the buffer or the combined production would leave the buffer with a chunk while the original pair would have left it empty.")
((eql failed-function 'i-b-c6)
"either strict harvesting is enabled for the buffer and the combined production would leave the buffer with a chunk while the original pair would have left it empty or the queries in the productions are not the same.")
((eql failed-function 'i-b-c7)
"either strict harvesting is enabled for the buffer and the combined production would leave the buffer with a chunk while the original pair would have left it empty or the buffer variable cannot be used in the actions of the second production if there is a request in the first production.")
((eql failed-function 'i-b-c8)
"either strict harvesting is enabled for the buffer and the combined production would leave the buffer with a chunk while the original pair would have left it empty or the first production makes a request and the second harvests it so it can only query for state free.")
(t
(case p1-index
((2 6 10 11 14 15 42 43 46 47 18 22 26 27 30 31 58 59 63 62)
"the buffer is explicitly cleared in the first production.")
((44 45 60 61)
"the first production makes both a request and a modification request.")
((41 57)
"the first production makes both a modification and a modification request.")
(t
(case p2-index
((2 6 10 11 14 15 42 43 46 47 18 22 26 27 30 31 58 59 63 62)
"the buffer is explicitly cleared in the second production.")
((44 45 60 61)
"the second production makes both a request and a modification request.")
((41 57)
"the second production makes both a modification and a modification request.")
((40 56)
"the first production makes a modification and the second makes a modification request.")
(t
(case p1-index
((4 12 13 20 28 29)
"both productions make requests.")
(t
(case p2-index
((4 12 13 20 28 29)
"the first production makes a modification request and the second makes a request.")
(t
"the first production makes a modification request and the other makes a modification.")))))))))))
(define-compilation-type IMAGINAL ((56 56 I-B-C3)
(56 40 T)
(56 25 I-B-C3)
(56 24 I-B-C8)
(56 16 I-B-C1)
(56 9 T)
(56 8 I-B-C5)
(56 0 T)
(40 56 I-B-C3)
(40 40 T)
(40 25 I-B-C3)
(40 24 I-B-C8)
(40 16 I-B-C1)
(40 9 T)
(40 8 I-B-C5)
(40 0 T)
(29 56 I-B-C4)
(29 40 NO-RHS-IMAGINAL-REF)
(29 25 I-B-C3)
(29 24 I-B-C8)
(29 16 I-B-C1)
(29 9 NO-RHS-IMAGINAL-REF)
(29 8 I-B-C7)
(29 0 T)
(28 56 I-B-C4)
(28 40 NO-RHS-IMAGINAL-REF)
(28 25 I-B-C3)
(28 24 I-B-C8)
(28 16 I-B-C1)
(28 9 NO-RHS-IMAGINAL-REF)
(28 8 I-B-C7)
(28 0 T)
(25 29 I-B-C2)
(25 28 I-B-C2)
(25 25 I-B-C2)
(25 24 I-B-C10)
(25 20 I-B-C2)
(25 16 I-B-C2)
(25 13 T)
(25 12 T)
(25 9 T)
(25 8 I-B-C9)
(25 4 T)
(25 0 T)
(24 56 I-B-C6)
(24 40 I-B-C6)
(24 29 I-B-C6)
(24 28 I-B-C6)
(24 25 I-B-C6)
(24 24 I-B-C6)
(24 20 I-B-C2)
(24 16 I-B-C2)
(24 13 I-B-C5)
(24 12 I-B-C5)
(24 9 I-B-C5)
(24 8 I-B-C5)
(24 4 T)
(24 0 T)
(20 56 I-B-C4)
(20 40 NO-RHS-IMAGINAL-REF)
(20 25 I-B-C3)
(20 24 I-B-C8)
(20 16 I-B-C1)
(20 9 NO-RHS-IMAGINAL-REF)
(20 8 I-B-C7)
(20 0 T)
(16 56 I-B-C2)
(16 40 T)
(16 29 I-B-C2)
(16 28 I-B-C2)
(16 25 I-B-C2)
(16 24 I-B-C2)
(16 20 I-B-C2)
(16 16 I-B-C2)
(16 13 T)
(16 12 T)
(16 9 T)
(16 8 T)
(16 4 T)
(16 0 T)
(13 56 I-B-C4)
(13 40 NO-RHS-IMAGINAL-REF)
(13 25 I-B-C3)
(13 24 I-B-C8)
(13 16 I-B-C1)
(13 9 NO-RHS-IMAGINAL-REF)
(13 8 I-B-C7)
(13 0 T)
(12 56 I-B-C4)
(12 40 NO-RHS-IMAGINAL-REF)
(12 25 I-B-C3)
(12 24 I-B-C8)
(12 16 I-B-C1)
(12 9 NO-RHS-IMAGINAL-REF)
(12 8 I-B-C7)
(12 0 T)
(9 29 T)
(9 28 T)
(9 25 T)
(9 24 I-B-C9)
(9 20 T)
(9 16 T)
(9 13 T)
(9 12 T)
(9 9 T)
(9 8 I-B-C9)
(9 4 T)
(9 0 T)
(8 56 I-B-C5)
(8 40 I-B-C5)
(8 29 I-B-C5)
(8 28 I-B-C5)
(8 25 I-B-C5)
(8 24 I-B-C5)
(8 20 T)
(8 16 T)
(8 13 I-B-C5)
(8 12 I-B-C5)
(8 9 I-B-C5)
(8 8 I-B-C5)
(8 4 T)
(8 0 T)
(4 56 I-B-C4)
(4 40 NO-RHS-IMAGINAL-REF)
(4 25 I-B-C3)
(4 24 I-B-C8)
(4 16 I-B-C1)
(4 9 NO-RHS-IMAGINAL-REF)
(4 8 I-B-C7)
(4 0 T)
(0 56 T)
(0 40 T)
(0 29 T)
(0 28 T)
(0 25 T)
(0 24 T)
(0 20 T)
(0 16 T)
(0 13 T)
(0 12 T)
(0 9 T)
(0 8 T)
(0 4 T)) (IMAGINAL) MAP-IMAGINAL-BUFFER COMPOSE-IMAGINAL-BUFFER CHECK-IMAGINAL-CONSISTENCY T NIL IMAGINAL-REASON)
#|
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
|#
| 58,580 | Common Lisp | .lisp | 839 | 44.244338 | 301 | 0.449164 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 01ac9c8cede2e45c082f8cc4b1726dcf3828d0bed1c2d9cf79790a82a2ec9e13 | 14,156 | [
-1
] |
14,157 | buffer-trace.lisp | asmaloney_ACT-R/tools/buffer-trace.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; 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 : buffer-trace.lisp
;;; Version : 3.1
;;;
;;; Description : Provide a tool that shows what activities are occuring in
;;; : the buffers instead of the current "event" based trace and
;;; : make that information available to the modeler as well if
;;; : desired.
;;;
;;; Bugs :
;;;
;;; To do : [] Watch the :trace-filter parameter and warn if it gets set
;;; : to a function other than disable-event-trace when the buffer
;;; : trace is enabled.
;;; : [] Better monitor the setting/removing of the pre-event hook.
;;;
;;; ----- History -----
;;; 2006.01.26 Dan
;;; : * Initial creation.
;;; 2006.02.07 Dan
;;; : * Fixed an issue with subseq going past the end of the event-details.
;;; 2006.07.18 Dan
;;; : * Changed schedule-maintenance-event-relative to just
;;; : schedule-event-relative because maintenance is now just a
;;; : keyword in all of the scheduling functions.
;;; 2006.09.11 Dan
;;; : * Changed the parameter test for the trace step to just be posnumornil.
;;; 2007.05.18 Dan
;;; : * Added the busy->free flag to the buffer summary records because
;;; : it's possible for a module to be marked as busy during some
;;; : early events and then become free later at the same time
;;; : and that can be useful to know.
;;; 2007.05.22 Dan
;;; : * Added two parameters for use with the graphic trace tools
;;; : in the environment: :buffer-trace-colors and :graphic-column-widths.
;;; : * Took the a1 off the version number.
;;; : * Added the additional slot of notes to the buffer summary
;;; : records and added the command add-buffer-trace-notes
;;; : to allow one to add them to the record.
;;; 2007.06.06 Dan
;;; : * Fixed a bug in the value returned when setting the :traced-buffers
;;; : parameter.
;;; : * Added the error->clear flag to the buffer summary records
;;; : because like busy->free that can be an important transition.
;;; 2011.04.25 Dan
;;; : * Converting to using the ms time internally. The buffer-
;;; : record-time-stamp slot will no longer be a member of the
;;; : structure, but a function with the same name will still
;;; : return the time in seconds. The slot will be buffer-record-
;;; : ms-time and hold an integer count of milliseconds instead.
;;; 2011.06.17 Dan
;;; : * Added an update function and use that to call the trace-hook
;;; : functions instead of doing it in the post hook because that
;;; : is problematic since the first event of the new time has already
;;; : occurred before the hooks get called.
;;; 2011.11.11 Dan
;;; : * Added an optional parameter to get-current-buffer-trace to allow
;;; : the user to clear the history if desired for performance
;;; : purposes.
;;; : * Changed add-buffer-trace-notes to return the notes passed
;;; : instead of the event that gets scheduled and check to make
;;; : sure the buffer is a valid name.
;;; 2013.09.18 Dan
;;; : * Fixing it so that setting the buffer-trace param returns the
;;; : value that was set.
;;; 2014.03.17 Dan [2.0]
;;; : * Changed the query-buffer call to be consistent with the new
;;; : internal code.
;;; 2014.05.28 Dan
;;; : * Changed how the module request summary is recorded since it
;;; : can't be the chunk-type of the spec. Now it's the whole
;;; : spec printed to a single line.
;;; 2014.10.22 Dan
;;; : * When the buffer-trace-step is set only record steps when there's
;;; : a "real" action that's going to occur i.e. if the run would
;;; : end without the step event let it.
;;; 2015.03.18 Dan
;;; : * Fixed the return value from setting :save-buffer-trace so it
;;; : returns t when set to t.
;;; : * Changed the parameter warning strings to remove the final '.'.
;;; 2015.06.04 Dan
;;; : * The :buffer-trace-step parameter was returning an incorrectly
;;; : converted result since it's set in seconds.
;;; 2015.06.05 Dan
;;; : * Use schedule-event-now instead of a realtive 0.
;;; 2016.04.20 Dan
;;; : * Fixed a bug that prevented one from setting :traced-buffers
;;; : to nil.
;;; 2016.06.18 Dan
;;; : * Fixed a bug with the return value of :buffer-trace-hook when it
;;; : gets set.
;;; 2016.06.21 Dan
;;; : * Fixed a bug with the previous fix.
;;; 2017.08.09 Dan
;;; : * Replaced capture-model-output with a call to printed-chunk-spec.
;;; 2017.09.28 Dan [3.0]
;;; : * Transition to the history data stream mechanism and eliminating
;;; : the buffer trace option (for now at least). Also removing all
;;; : of the parameters for the module:
;;; : - GUI based parameters (size and color) because those
;;; : should be options in the GUI
;;; : - buffer-trace and -step since the trace is going away
;;; : - save- and traced- because those now go through the
;;; : general history recording tool
;;; : - trace-hook because nothing else needs it and I doubt anyone
;;; : actually uses it
;;; : * The default is for all buffers to be off now instead of on.
;;; : * Added a lock to protect access.
;;; : * Catch erase-buffer and treat like clear-buffer.
;;; 2017.10.02 Dan
;;; : * Instead of just the + or * at the start of the request details
;;; : for default actions include the buffer and > too e.g. +goal>.
;;; 2017.10.03 Dan
;;; : * Moved the translator/accessor functions for the data lists
;;; : to here from the environment trace processing code.
;;; 2018.02.05 Dan
;;; : * Updated this to use the internal event slot accessors and get
;;; : the real struct since it's going to be passed the id.
;;; 2018.02.22 Dan
;;; : * Protect access to the event time and priority.
;;; 2018.02.28 Dan
;;; : * Fixed a bug in with the last update.
;;; 2018.03.02 Dan
;;; : * Updated define-history-component to -constituent.
;;; 2018.03.16 Dan
;;; : * Meta-p-schedule-lock is recursive.
;;; 2018.03.20 Dan
;;; : * Add a remote version of add-buffer-trace-notes and convert the
;;; : buffer name provided from a string if needed.
;;; 2018.06.22 Dan
;;; : * Only the remote add-buffer-trace-notes allows a string name.
;;; 2018.07.31 Dan
;;; : * Add optional parameters to the buffer-trace history stream
;;; : to allow specifying start and stop times.
;;; 2020.01.14 Dan [3.1]
;;; : * Buffer-trace history constituents can't be lambdas.
;;; 2021.06.07 Dan
;;; : * Deal with set-buffer-chunk and overwrite-... possibly having
;;; : a chunk-spec as the second parameter.
;;; 2021.10.18 Dan
;;; : * Changed call to buffers to model-buffers instead when adding
;;; : notes (still check all at module creation time).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; The following information is recorded at each event of the model and aggregated
;;; over all events at a given time:
;;;
;;; Whether the module is busy
;;; Whether the module transitioned from busy to free at this time
;;; Whether the module is in an error
;;; Whether the buffer is full
;;; Whether the buffer is cleared
;;; Whether the chunk in the buffer is modified
;;;
;;; Whether a request is sent to the module
;;; Whether a new chunk is set in the buffer
;;; Any notes which are recorded using add-buffer-trace-notes.
;;;
;;; For the first 6, if the stated condition is true during any event at the
;;; current time the buffer record will indicate t.
;;;
;;; For the requests, each request overwrites any prior request recorded
;;; at that time. The value recorded is the details string provided for the event
;;; if there was one or a printing of the request's chunk-spec if not.
;;; If a chunk is set into the buffer, then the name of that chunk is recorded,
;;; and only the last setting at a specific time is recorded.
;;; The notes are set to the string specified by add-buffer-trace-notes, but
;;; only the last note at a given time will be saved (they overwrite).
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;;
;;; (defstruct buffer-record ms-time buffers)
;;; (defstruct buffer-summary name cleared busy busy->free error full modified request chunk-name notes)
;;;
;;;
;;; add-buffer-trace-notes
;;;
;;; Takes two parameters which are the name of a buffer and any notes
;;; to set for the buffer summary of that buffer at the current time.
;;;
;;; This can be used to augment the summaries on the fly, and would most likely
;;; be called from an event hook that was watching for something that needed to
;;; be noted.
;;;
;;; There are no restrictions on what can be passed as notes.
;;;
;;; Calling this will create a maintenance event which records the notes at
;;; the current time.
;;;
;;; The graphic trace tools will display the notes when the mouse is placed over
;;; the corresponding box in the trace (the notes will be printed using the Lisp
;;; format string "~a").
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Grown out of Scott's graphic module tracer and the old environment's PERT
;;; style trace. The idea being that instead of looking at the specific actions
;;; of a module one can "watch" the buffers since they're the interface to
;;; the module. As long as a module takes requests through the buffers and
;;; responds to the state queries appropriately it can be monitored.
;;;
;;; The addition of the production buffer was necessary so that the procedural
;;; module could be queried and report "requests" (production firings) like
;;; any other module. It is a bit strange, and not really a buffer of the
;;; theory (note it doesn't end in 'al') but may end up being so as work on
;;; meta-cognitive processing continues - being able to monitor the state
;;; of the prodceural system may be an important thing to 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)
(defclass buffer-trace-module ()
((history-lock :accessor history-lock :initform (bt:make-lock "buffer-trace") :allocation :class)
(btm-enabled :accessor btm-enabled :initform nil)
(alive :accessor alive :initform t)
(btm-traced-buffers :accessor btm-traced-buffers :initform nil)
(btm-current-summary :accessor btm-current-summary :initform nil)
(btm-saved-records :accessor btm-saved-records :initform nil)
(available-buffers :accessor available-buffers :initform nil :allocation :class)
(post-recorder :accessor post-recorder :initform nil :allocation :class)
(monitor-count :accessor monitor-count :initform 0 :allocation :class)))
(defstruct buffer-record
ms-time
buffers)
(defstruct buffer-summary
name
cleared
busy
busy->free
error
error->clear
full
modified
request
chunk-name
notes)
(defun buffer-trace-event-recorder (event)
(let ((btm (get-module buffer-trace)))
(when btm
(bt:with-lock-held ((history-lock btm))
(when (btm-enabled btm)
(let* ((evt (get-event-by-id event))
(e-time (bt:with-recursive-lock-held ((meta-p-schedule-lock (current-mp))) (act-r-event-mstime evt))))
(when (null (btm-current-summary btm))
;; create a new one and set as current
(setf (btm-current-summary btm)
(make-buffer-record :ms-time e-time))
(setf (buffer-record-buffers (btm-current-summary btm))
(mapcar (lambda (x) (make-buffer-summary :name x))
(btm-traced-buffers btm))))
(unless (= (buffer-record-ms-time (btm-current-summary btm)) e-time)
(push-last (btm-current-summary btm) (btm-saved-records btm))
(setf (btm-current-summary btm)
(make-buffer-record :ms-time e-time))
(setf (buffer-record-buffers (btm-current-summary btm))
(mapcar (lambda (x) (make-buffer-summary :name x))
(btm-traced-buffers btm))))
;; Update the records
;; First pull any meaningful info out of the evt itself
(case (act-r-event-action evt)
((set-buffer-chunk overwrite-buffer-chunk)
(let ((bn (car (act-r-event-params evt))))
(awhen (find bn (buffer-record-buffers (btm-current-summary btm)) :key 'buffer-summary-name)
(setf (buffer-summary-chunk-name it)
(if (symbolp (second (act-r-event-params evt)))
(string (second (act-r-event-params evt)))
(format nil "~S" (chunk-spec-to-chunk-def (second (act-r-event-params evt)))))))))
(mod-buffer-chunk
(let ((bn (car (act-r-event-params evt))))
(awhen (find bn (buffer-record-buffers (btm-current-summary btm)) :key 'buffer-summary-name)
(setf (buffer-summary-modified it) t))))
((clear-buffer erase-buffer)
(let ((bn (car (act-r-event-params evt))))
(awhen (find bn (buffer-record-buffers (btm-current-summary btm)) :key 'buffer-summary-name)
(setf (buffer-summary-cleared it) t))))
(module-request
(let ((bn (car (act-r-event-params evt))))
(awhen (find bn (buffer-record-buffers (btm-current-summary btm)) :key 'buffer-summary-name)
(setf (buffer-summary-request it)
(if (and (>= (length (act-r-event-details evt)) 15)
(string-equal "module-request " (subseq (act-r-event-details evt) 0 15)))
(concatenate 'string "+" (symbol-name bn) "> " (printed-chunk-spec (second (act-r-event-params evt)) t))
(act-r-event-details evt))))))
(record-buffer-trace-notes
(let ((bn (car (act-r-event-params evt))))
(awhen (find bn (buffer-record-buffers (btm-current-summary btm)) :key 'buffer-summary-name)
(setf (buffer-summary-notes it)
(second (act-r-event-params evt))))))
(module-mod-request
(let ((bn (car (act-r-event-params evt))))
(awhen (find bn (buffer-record-buffers (btm-current-summary btm)) :key 'buffer-summary-name)
(setf (buffer-summary-request it)
(if (and (>= (length (act-r-event-details evt)) 19)
(string-equal "module-mod-request " (subseq (act-r-event-details evt) 0 19)))
(concatenate 'string "*" (symbol-name bn) "> " (printed-chunk-spec (second (act-r-event-params evt)) t))
(act-r-event-details evt)))))))
;; Now for each one set busy, error, and full
(dolist (x (buffer-record-buffers (btm-current-summary btm)))
(if (query-buffer (buffer-summary-name x) '(state busy))
(setf (buffer-summary-busy x) t)
(when (buffer-summary-busy x)
(setf (buffer-summary-busy->free x) t)))
(if (query-buffer (buffer-summary-name x) '(state error))
(setf (buffer-summary-error x) t)
(when (buffer-summary-error x)
(setf (buffer-summary-error->clear x) t)))
(when (query-buffer (buffer-summary-name x) '(buffer full))
(setf (buffer-summary-full x) t)))))))))
(defun get-current-buffer-trace (&optional (clear nil))
(let ((btm (get-module buffer-trace)))
(when btm
(let ((return (btm-saved-records btm)))
(when clear
(setf (btm-saved-records btm) nil))
return))))
(defun record-buffer-trace-notes (buffer notes)
"Dummy function for recording event"
(declare (ignore buffer notes)))
(defun add-buffer-trace-notes (buffer notes)
(if (and (current-model) (find buffer (model-buffers)))
(progn
(schedule-event-now 'record-buffer-trace-notes
:maintenance t :priority :max
:output nil :params (list buffer notes))
notes)
(if (current-model)
(print-warning "~s does not name a buffer in the current model no notes added." buffer)
(print-warning "No current model so cannot add notes."))))
(defun remote-add-buffer-trace-notes (buffer notes)
(add-buffer-trace-notes (string->name buffer) notes))
(add-act-r-command "add-buffer-trace-notes" 'add-buffer-trace-notes "Command to add notes to the buffer-trace history data. Params: buffer-name note.")
(defun reset-buffer-trace-module (module)
(bt:with-lock-held ((history-lock module))
(setf (btm-current-summary module) nil)
(setf (btm-saved-records module) nil)
(setf (btm-traced-buffers module) nil)
(when (btm-enabled module)
(setf (btm-enabled module) nil)
(decf (monitor-count module))
(when (zerop (monitor-count module))
(delete-event-hook (post-recorder module))))))
(defun delete-buffer-trace-module (module)
(bt:with-lock-held ((history-lock module))
(setf (alive module) nil)
(when (btm-enabled module)
(setf (btm-enabled module) nil)
(decf (monitor-count module))
(when (zerop (monitor-count module))
(delete-event-hook (post-recorder module))))
t))
(defun create-buffer-trace-module (name)
(declare (ignore name))
(let ((m (make-instance 'buffer-trace-module)))
(bt:with-lock-held ((history-lock m))
(dolist (x (buffers))
(let ((buffer x))
(unless (find x (available-buffers m))
(push x (available-buffers m))
(define-history-constituent-fct "buffer-trace" (string buffer)
(eval `(defun ,(read-from-string (concatenate 'string "buffer-trace-enable-" (string buffer))) ()
(enable-buffer-trace-buffer ',buffer)))
(eval `(defun ,(read-from-string (concatenate 'string "buffer-trace-disable-" (string buffer))) ()
(disable-buffer-trace-buffer ',buffer)))
(eval `(defun ,(read-from-string (concatenate 'string "buffer-trace-status-" (string buffer))) ()
(buffer-trace-buffer-status ',buffer)))))))
m)))
(defun enable-buffer-trace-buffer (name)
(let ((module (get-module buffer-trace)))
(bt:with-lock-held ((history-lock module))
(push name (btm-traced-buffers module))
t)))
(defun disable-buffer-trace-buffer (name)
(let ((module (get-module buffer-trace)))
(bt:with-lock-held ((history-lock module))
(setf (btm-traced-buffers module) (remove name (btm-traced-buffers module)))
t)))
(defun buffer-trace-buffer-status (name)
(let ((module (get-module buffer-trace)))
(bt:with-lock-held ((history-lock module))
(values
(when (find name (btm-traced-buffers module)) t)
(when (or (btm-current-summary module) (btm-saved-records module)) t)
(alive module)))))
(define-module-fct 'buffer-trace nil nil
:version "3.1"
:documentation "A module that provides a buffer based history mechanism."
:creation 'create-buffer-trace-module
:reset 'reset-buffer-trace-module
:delete 'delete-buffer-trace-module)
(defun enable-buffer-trace-history ()
(let ((module (get-module buffer-trace)))
(bt:with-lock-held ((history-lock module))
(unless (btm-enabled module)
(setf (btm-enabled module) t)
(when (zerop (monitor-count module))
(setf (post-recorder module) (add-post-event-hook 'buffer-trace-event-recorder)))
(incf (monitor-count module)))
t)))
(defun disable-buffer-trace-history ()
(let ((module (get-module buffer-trace)))
(bt:with-lock-held ((history-lock module))
(when (btm-enabled module)
(setf (btm-enabled module) nil)
(decf (monitor-count module))
(when (zerop (monitor-count module))
(delete-event-hook (post-recorder module))))
t)))
(defun buffer-trace-history-status (&optional start stop)
(let ((module (get-module buffer-trace))
(start-time (if (numberp start) (safe-seconds->ms start) 0))
(stop-time (if (numberp stop) (safe-seconds->ms stop) (mp-time-ms))))
(bt:with-lock-held ((history-lock module))
(values (btm-enabled module)
(when (and (or (btm-current-summary module) (btm-saved-records module))
(some (lambda (x)
(<= start-time (buffer-record-ms-time x) stop-time))
(if (null (btm-current-summary module))
(btm-saved-records module)
(append (btm-saved-records module) (list (btm-current-summary module))))))
t)
(alive module)))))
(defun get-buffer-trace-history (&optional start stop)
(let ((module (get-module buffer-trace))
(start-time (if (numberp start) (safe-seconds->ms start) 0))
(stop-time (if (numberp stop) (safe-seconds->ms stop) (mp-time-ms))))
(mapcan (lambda (x)
(when (<= start-time (buffer-record-ms-time x) stop-time)
(list (list (buffer-record-ms-time x)
(mapcar (lambda (y)
(list (symbol-name (buffer-summary-name y))
(when (buffer-summary-busy y) t)
(when (buffer-summary-cleared y) t)
(when (buffer-summary-busy->free y) t)
(when (buffer-summary-error y) t)
(when (buffer-summary-error->clear y) t)
(when (buffer-summary-full y) t)
(when (buffer-summary-modified y) t)
(aif (buffer-summary-request y) it "")
(aif (buffer-summary-chunk-name y) it "")
(aif (buffer-summary-notes y) it "")))
(buffer-record-buffers x))))))
(if (null (btm-current-summary module))
(btm-saved-records module)
(append (btm-saved-records module) (list (btm-current-summary module)))))))
;; Define accessors to make the transition easier for the code that
;; was accessing the structures before.
(defun br-time (x) (first x))
(defun br-buffers (x) (second x))
(defun bs-name (x) (first x))
(defun bs-busy (x) (second x))
(defun bs-cleared (x) (third x))
(defun bs-busy->free (x) (fourth x))
(defun bs-error (x) (fifth x))
(defun bs-error->clear (x) (sixth x))
(defun bs-full (x) (seventh x))
(defun bs-modified (x) (eighth x))
(defun check-bs-request (x) (let ((y (ninth x))) (and (not (zerop (length y))) y)))
(defun value-bs-request (x) (let ((y (ninth x))) (or y "")))
(defun check-bs-chunk-name (x) (let ((y (tenth x))) (and (not (zerop (length y))) y)))
(defun value-bs-chunk-name (x) (let ((y (tenth x))) (or y "")))
(defun check-bs-notes (x) (let ((y (nth 10 x))) (and (not (zerop (length y))) y)))
(defun value-bs-notes (x) (let ((y (nth 10 x))) (or y "")))
(define-history "buffer-trace" enable-buffer-trace-history disable-buffer-trace-history buffer-trace-history-status get-buffer-trace-history)
#|
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,406 | Common Lisp | .lisp | 501 | 45.538922 | 151 | 0.589663 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4eae09a274c82158efede36b262341d125ea8b474131c198c1c48d73a68c0c17 | 14,157 | [
-1
] |
14,158 | trace-history.lisp | asmaloney_ACT-R/tools/trace-history.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 : trace-history.lisp
;;; Version : 1.0
;;;
;;; Description : Component for recording the event trace -- replaces the
;;; : printing modules :save-trace functionality.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2017.09.19 Dan [1.0]
;;; : * Initial creation as a split from printing module and the
;;; : environment-specific history mechanism.
;;; 2017.09.20 Dan
;;; : * Mark it as non-model based since it uses a component and
;;; : doesn't depend on a current model for tracking things.
;;; : * Accept the optional parameters for the status function as
;;; : well and use those to determine if there's any data which
;;; : matches available.
;;; 2017.09.21 Dan
;;; : * Return a third value of t for the status checks to indicate
;;; : that it's always available.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct trace-history (lock (bt:make-lock "Trace history")) trace event)
(defun remove-trace-history (th)
(bt:with-lock-held ((trace-history-lock th))
(setf (trace-history-trace th) nil)
(when (trace-history-event th)
(delete-event-hook (trace-history-event th))
(setf (trace-history-event th) nil))))
(defun reset-trace-history (th)
(bt:with-lock-held ((trace-history-lock th))
(setf (trace-history-trace th) nil)))
(defun trace-history-recorder (event)
(let ((th (get-component trace-history)))
(bt:with-lock-held ((trace-history-lock th))
(push-last (list (evt-mstime event) (evt-output event) (evt-model event) (format-event event))
(trace-history-trace th)))))
(defun enable-trace-history ()
(let ((th (get-component trace-history)))
(bt:with-lock-held ((trace-history-lock th))
(unless (trace-history-event th)
(setf (trace-history-event th)
(add-post-event-hook 'trace-history-recorder))))))
(defun disable-trace-history ()
(let ((th (get-component trace-history)))
(bt:with-lock-held ((trace-history-lock th))
(when (trace-history-event th)
(delete-event-hook (trace-history-event th))
(setf (trace-history-event th) nil)))))
(defun check-trace-history (&optional start end (detail 'medium) model)
(let ((th (get-component trace-history)))
(bt:with-lock-held ((trace-history-lock th))
(values (when (trace-history-event th) t)
(not (null (check-saved-trace th start end detail model)))
t))))
(define-component trace-history :version "1.0" :documentation "Component for recording trace information"
:creation make-trace-history :before-reset reset-trace-history :clear-all remove-trace-history)
(defun get-saved-trace (&optional s e (d 'medium) m)
(let ((detail (string->name d))
(model (string->name m))
(start (string->name s))
(end (string->name e)))
(cond ((and start (not (numberp start)))
(print-warning "Invalid start for get-saved-trace ~s. Must be a number indicating a time in seconds." start))
((and end (not (numberp end)))
(print-warning "Invalid end for get-saved-trace ~s. Must be a number indicating a time in seconds." end))
((and (numberp start) (numberp end) (< end start))
(print-warning "End time for get-saved-trace must be greater than the start time, but given start=~f and end=~f" start end))
((not (position detail '(t low medium high)))
(print-warning "Invalid detail level for get-saved-trace ~s. Possible values are: t, low, medium, and high." detail))
(t
(let ((th (get-component trace-history)))
(bt:with-lock-held ((trace-history-lock th))
(let* ((s (when (numberp start) (seconds->ms start)))
(e (when (numberp end) (seconds->ms end)))
(full-trace (trace-history-trace th))
(start-index (if s
(aif (position-if (lambda (x) (>= (first x) s)) full-trace)
it
(length full-trace))
0))
(end-index (when e (position-if (lambda (x) (> (first x) e)) full-trace)))
(trace-segment (subseq full-trace start-index end-index)))
(mapcan (lambda (x)
(when (and (or (eq detail t)
(case detail
(low (eq (second x) 'low))
(medium (or (eq (second x) 'low)
(eq (second x) 'medium)))
(high (second x))))
(or (null model)
(or (null (third x)) (eq (third x) model))))
(list x)))
trace-segment))))))))
(defun check-saved-trace (th &optional s e (d 'medium) m)
(let ((detail (string->name d))
(model (string->name m))
(start (string->name s))
(end (string->name e)))
(cond ((and start (not (numberp start)))
(print-warning "Invalid start for check-saved-trace ~s. Must be a number indicating a time in seconds." start))
((and end (not (numberp end)))
(print-warning "Invalid end for check-saved-trace ~s. Must be a number indicating a time in seconds." end))
((and (numberp start) (numberp end) (< end start))
(print-warning "End time for check-saved-trace must be greater than the start time, but given start=~f and end=~f" start end))
((not (position detail '(t low medium high)))
(print-warning "Invalid detail level for check-saved-trace ~s. Possible values are: t, low, medium, and high." detail))
(t
(let* ((s (when (numberp start) (seconds->ms start)))
(e (when (numberp end) (seconds->ms end)))
(full-trace (trace-history-trace th))
(start-index (if s
(aif (position-if (lambda (x) (>= (first x) s)) full-trace)
it
(length full-trace))
0))
(end-index (when e (position-if (lambda (x) (> (first x) e)) full-trace)))
(trace-segment (subseq full-trace start-index end-index)))
(mapcan (lambda (x)
(when (and (or (eq detail t)
(case detail
(low (eq (second x) 'low))
(medium (or (eq (second x) 'low)
(eq (second x) 'medium)))
(high (second x))))
(or (null model)
(or (null (third x)) (eq (third x) model))))
(list x)))
trace-segment))))))
(defun show-saved-trace (&optional start end (detail 'medium) model)
(let ((trace (get-saved-trace start end detail model)))
(dolist (x trace)
(command-output (fourth x)))))
(define-history "trace-history" enable-trace-history disable-trace-history check-trace-history get-saved-trace 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
|#
| 9,754 | Common Lisp | .lisp | 186 | 41.182796 | 136 | 0.51067 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 13ed861e08ab46b1c3681f5cd6aaacc64e1384c729e33ec330a23c83be2ff847 | 14,158 | [
-1
] |
14,159 | goal-compilation.lisp | asmaloney_ACT-R/tools/goal-compilation.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 : goal-compilation.lisp
;;; Version : 6.0
;;;
;;; Description : Production compilation GOAL style definition.
;;;
;;; Bugs :
;;;
;;; To do : [X] Update the functions to properly handle the modification requests.
;;; : [ ] Consider allowing queries: any P1 --> P3 and P2 state free --> null.
;;;
;;; ----- History -----
;;;
;;; 2010.12.06 Dan
;;; : * Created automatically by build-compilation-type-file.
;;; : * Added the details of the functions.
;;; 2010.12.07 Dan
;;; : * Added the appropriate support for modification requests to the
;;; : functions.
;;; 2010.12.15 Dan
;;; : * Added module to the mapping functions args list.
;;; 2010.12.20 Dan
;;; : * Added some additional code to handle things better when
;;; : :ppm is enabled -- creates productions that match more closely
;;; : to the same conditions as the original pair did and does
;;; : the "same" thing.
;;; : * Allow subtypes to be composed in the consistency check.
;;; 2011.04.28 Dan
;;; : * Added some declares to avoid compiler warnings.
;;; 2012.04.04 Dan [1.1]
;;; : * Added the whynot reason function.
;;; 2014.05.07 Dan [2.0]
;;; : * Start of conversion to typeless chunks.
;;; : * Pass the module to constant-value-p.
;;; : * References to compilation-module-previous are now using a
;;; : structure instead of list.
;;; 2014.05.27 Dan
;;; : * Fixed a bug in compose-goal-buffer with the (4 12 13 44)
;;; : case not wrapping c1 in a list.
;;; 2015.08.17 Dan
;;; : * The last update actually broke things for the case where
;;; : there is no condition in c1 and this fixes that.
;;; 2016.08.05 Dan [3.0]
;;; : * Updated the compilation type definition with one that was
;;; : created automatically by build-compilation-type-file from the
;;; : new spreadsheet that better handles "safe" compilation based
;;; : on whether the buffer is strict harvested or not. Also added
;;; : some cases which should have been allowed but weren't where
;;; : an = action with a preceeding * can be put together into a *.
;;; : * Added the code necessary to deal with the new cases and the
;;; : new test functions.
;;; 2020.06.22 Dan [4.0]
;;; : * The functions are now all passed the same set of parameters:
;;; : buffer module p1 p1-s p1-index p2 p2-s p2-index
;;; : the p1-s and p2-s are the new "standard" representation that
;;; : can be decomposed with composition-rep-* where * is:
;;; : op -- the character of the operation =,?,!,+,-,*,@
;;; : name -- the symbol naming the buffer or bang action
;;; : token -- the symbol of the production item for op and name
;;; : slots -- list of slot-spec lists
;;; 2021.02.05 Dan [5.0]
;;; : * Allowing the 9,8 case to happen if the mod in p1 is an empty
;;; : mod when the buffer is strict harvested and then just drop
;;; : the empty mod.
;;; 2021.02.10 Dan [6.0]
;;; : * There isn't a pre-instantiation step for variablized slots
;;; : now so that needs to be done here instead for both mapping
;;; : and composition.
;;; : * Needs to deal with var->var, const->var, var->const, and
;;; : the possibility of multiple vars being bound to the same
;;; : slot name.
;;; 2021.02.23 Dan
;;; : * Wasn't catching the possible action to action mappings for
;;; : dynamic slots, only the action to condition.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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 MAP-GOAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"map references from p1 to p2 for goal style buffer"
;; With the current restricted set of productions
;; that could be composed it's the case that
;; we only need to go from: a RHS + to a
;; LHS = (includes when the RHS has both + and =),
;; from a RHS = to a LHS = or from a LHS = with
;; null RHS to a LHS =.
;;
;; Additionally now we need to consider the
;; RHS * to LHS = (with both + and * on the RHS)
;; and additional instances of the above cases
;; which may include the RHS * options.
(declare (ignore p1))
(let* ((ppm (compilation-module-ppm module))
(p1-bindings (previous-production-bindings (compilation-module-previous module)))
(p2-bindings (production-compilation-instan (production-name p2)))
(bindings (when ppm
(append p1-bindings p2-bindings))))
(cond (;; The RHS + to LHS = case -- also overrides when there's a RHS * in p1
(and (find p1-index '(4 12 13 44))
(find p2-index '(8 9 12 13 40 44)))
;; Map the RHS +'s with the LHS ='s
;; here the slots of interest are just the intersection of the two sets
(let* ((mappings nil)
(original-p1-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(original-p2-rhs-slots (compose-rep-slots (find-if (lambda (x) (and (eq buffer (compose-rep-name x))
(or (char= #\= (compose-rep-op x))
(char= #\* (compose-rep-op x)))))
(second p2-s))))
(p1-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1-slots :key 'spec-slot-name)))
(p2-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-slots :key 'spec-slot-name)))
(p2-rhs-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-rhs-slots :key 'spec-slot-name)))
(p1-slots (instantiate-slot-names
original-p1-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(p2-rhs-slots (instantiate-slot-names
original-p2-rhs-slots
p2-bindings))
(interesting-slots (remove-duplicates (append (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-rhs-slots)))))
(dolist (slot interesting-slots)
(when (or p1-var-slots p2-var-slots p2-rhs-var-slots) ;; there are dynamic slots which may need to be mapped
;; if the same slot is variablized in both or a var slot maps
;; to a constant slot in either direction (multiple options
;; possible as well as multiple variables matching the same slot)
(when (and (rassoc slot p1-var-slots) ;; it's a variable in action and condition both
(rassoc slot p2-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in both actions
(rassoc slot p2-rhs-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 so need to instantiate
(find slot original-p2-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 action so need to instantiate
(find slot original-p2-rhs-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p2-var-slots) ;; it's a variable in p2 and const in p1 so need to instantiate
(find slot original-p1-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p2-var slot) mappings)))
(when (and (rassoc slot p2-rhs-var-slots) ;; it's a variable in p2 action and const in p1 so need to instantiate
(find slot original-p1-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p2-var slot) mappings))))
(dolist (p1slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(;; The RHS = to a LHS = case
(and (find p1-index '(9))
(find p2-index '(8 9 12 13)))
;; Map the RHS ='s and LHS ='s not in the RHS with
;; the LHS ='s
;; Here the slots of interest are the union of the
;; p1 bits with the RHS superseding the LHS intersected
;; with the LHS of the second one
(let* ((mappings nil)
(original-p1a-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s))))
(original-p1b-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(original-p2-rhs-slots (compose-rep-slots (find-if (lambda (x) (and (eq buffer (compose-rep-name x))
(or (char= #\= (compose-rep-op x))
(char= #\* (compose-rep-op x)))))
(second p2-s))))
(p1-var-slotsa (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1a-slots :key 'spec-slot-name)))
(p1-var-slotsb (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1b-slots :key 'spec-slot-name)))
(p2-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-slots :key 'spec-slot-name)))
(p2-rhs-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-rhs-slots :key 'spec-slot-name)))
(p1-slotsa (instantiate-slot-names
original-p1a-slots
p1-bindings))
(p1-slotsb (instantiate-slot-names
original-p1b-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(p2-rhs-slots (instantiate-slot-names
original-p2-rhs-slots
p2-bindings))
(p1-slots (append (remove-if (lambda (x)
(or (not (eq (spec-slot-op x) '=))
(find (spec-slot-name x) p1-slotsb :key 'spec-slot-name)))
p1-slotsa)
p1-slotsb))
(p1-var-slots (remove-duplicates (append p1-var-slotsa p1-var-slotsb) :test 'equalp))
(interesting-slots (remove-duplicates (append (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-rhs-slots)))))
(dolist (slot interesting-slots)
(when (or p1-var-slots p2-var-slots p2-rhs-var-slots) ;; there are dynamic slots which may need to be mapped
;; if the same slot is variablized in both or a var slot maps
;; to a constant slot in either direction (multiple options
;; possible as well as multiple variables matching the same slot)
(when (and (rassoc slot p1-var-slots) ;; it's a variable in both
(rassoc slot p2-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in both actions
(rassoc slot p2-rhs-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 so need to instantiate
(find slot original-p2-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in p1 and const in p2 action so need to instantiate
(find slot original-p2-rhs-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p2-var-slots) ;; it's a variable in p2 and const in p1 (somewhere) so need to instantiate
(or ;; all p2 vars
(find slot original-p1a-slots :key 'spec-slot-name)
(find slot original-p1b-slots :key 'spec-slot-name)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p2-var slot) mappings)))
(when (and (rassoc slot p2-rhs-var-slots) ;; it's a variable in p2 action and const in p1 so need to instantiate
(find slot original-p1b-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p2-var slot) mappings))))
(dolist (p1slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(;; The RHS * to a LHS = case
(and (find p1-index '(40))
(find p2-index '(8 12 40 44)))
;; Map the RHS *'s and LHS ='s not in the RHS with
;; the LHS ='s
;; Here the slots of interest are the union of the
;; p1 bits with the RHS superseding the LHS intersected
;; with the LHS of the second one
(let* ((mappings nil)
(original-p1a-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s))))
(original-p1b-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\* (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(original-p2-rhs-slots (compose-rep-slots (find-if (lambda (x) (and (eq buffer (compose-rep-name x))
(or (char= #\= (compose-rep-op x))
(char= #\* (compose-rep-op x)))))
(second p2-s))))
(p1-var-slotsa (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1a-slots :key 'spec-slot-name)))
(p1-var-slotsb (mapcar (lambda (x) (assoc (spec-slot-name x) p1-bindings)) (remove-if-not 'chunk-spec-variable-p original-p1b-slots :key 'spec-slot-name)))
(p2-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-slots :key 'spec-slot-name)))
(p2-rhs-var-slots (mapcar (lambda (x) (assoc (spec-slot-name x) p2-bindings)) (remove-if-not 'chunk-spec-variable-p original-p2-rhs-slots :key 'spec-slot-name)))
(p1-slotsa (instantiate-slot-names
original-p1a-slots
p1-bindings))
(p1-slotsb (instantiate-slot-names
original-p1b-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(p2-rhs-slots (instantiate-slot-names
original-p2-rhs-slots
p2-bindings))
(p1-slots (append (remove-if (lambda (x)
(or (not (eq (spec-slot-op x) '=))
(find (spec-slot-name x) p1-slotsb :key 'spec-slot-name)))
p1-slotsa)
p1-slotsb))
(p1-var-slots (remove-duplicates (append p1-var-slotsa p1-var-slotsb) :test 'equalp))
(interesting-slots (remove-duplicates (append (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-rhs-slots)))))
(dolist (slot interesting-slots)
(when (or p1-var-slots p2-var-slots p2-rhs-var-slots) ;; there are dynamic slots which may need to be mapped
;; if the same slot is variablized in both or a var slot maps
;; to a constant slot in either direction (multiple options
;; possible as well as multiple variables matching the same slot)
(when (and (rassoc slot p1-var-slots) ;; it's a variable in both
(rassoc slot p2-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in both actions
(rassoc slot p2-rhs-var-slots)) ;; so need to add all the variable to variable mappings
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p1-var p2-var) mappings))))
(when (and (rassoc slot p1-var-slots) ;; it's a variable in p1 and const in p2 so need to instantiate
(find slot original-p2-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slots)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p1-var-slotsb) ;; it's a variable in p1 and const in p2 action so need to instantiate
(find slot original-p2-rhs-slots :key 'spec-slot-name)) ;; all p1 vars
(dolist (p1-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p1-var-slotsb)))
(push (cons p1-var slot) mappings)))
(when (and (rassoc slot p2-var-slots) ;; it's a variable in p2 and const in p1 (somewhere) so need to instantiate
(or ;; all p2 vars
(find slot original-p1a-slots :key 'spec-slot-name)
(find slot original-p1b-slots :key 'spec-slot-name)))
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-var-slots)))
(push (cons p2-var slot) mappings)))
(when (and (rassoc slot p2-rhs-var-slots) ;; it's a variable in p2 action and const in p1 so need to instantiate
(find slot original-p1b-slots :key 'spec-slot-name)) ;; all p2 vars
(dolist (p2-var (mapcar 'car (remove-if-not (lambda (x) (eq (cdr x) slot)) p2-rhs-var-slots)))
(push (cons p2-var slot) mappings))))
(dolist (p1slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (eq (spec-slot-name x) slot)) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(;; The LHS = RHS null to a LHS = case
(and (find p1-index '(8))
(find p2-index '(8 9 12 13 40 44)))
;; Map the LHS ='s with the LHS ='s
;; The slots of interest are the ones at the intersection of the
;; two sets - the mappings are then done for those
;; such that
;; - if it's a variable in both then p2 vars go to p1 vars
;; - if it's a constant in one then it goes from the var to the constant
;; (note that buffer variables are considered constants and not variables)
;; - if it's a constant in both we're in trouble if they aren't equal
;; because how did they fire...
;;
;; When there is more than one option we have to add both but they need to
;; be evaluated in the order of variables before constants (that's handled
;; elsewhere though)
(let* ((mappings nil)
(original-p1-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s))))
(original-p2-slots (compose-rep-slots (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s))))
(p1-slots (instantiate-slot-names
original-p1-slots
p1-bindings))
(p2-slots (instantiate-slot-names
original-p2-slots
p2-bindings))
(interesting-slots (intersection (mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p1-slots)
(mapcan (lambda (x)
(when (eq (spec-slot-op x) '=)
(list (spec-slot-name x))))
p2-slots))))
(dolist (slot interesting-slots)
;; no dynamic slot issues because can't assume anything from just the conditions
(dolist (p1slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p1-slots))
(dolist (p2slots (remove-if-not (lambda (x) (and (eq (spec-slot-op x) '=) (eq (spec-slot-name x) slot))) p2-slots))
(if (constant-value-p (spec-slot-value p2slots) module)
(if ppm
(if (constant-value-p (spec-slot-value p1slots) module)
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings)
(push (find (spec-slot-value p1slots) bindings :key 'car) mappings))
(push (cons (spec-slot-value p1slots) (spec-slot-value p2slots)) mappings))
(push (cons (spec-slot-value p2slots) (spec-slot-value p1slots)) mappings)))))
mappings))
(t
nil))))
(defun COMPOSE-GOAL-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
;; This is based on the limited set of conditions that can
;; be composed.
;;
;; Generally:
;; If the first has a + (4, 12, 13, 44) then
;; the conditions are those of the first
;; the actions are the = or * of the first if there is one and
;; the + will be the + of the first (can't be a + in the second)
;; with the = or * of the second unioned in and overriding
;; If the first has no actions (0, 8)
;; the conditions are the union of those in the first
;; and those of the second
;; the actions are those of the second
;; Otherwise (9 & 40)
;; the conditions are the union of those in the first
;; and those from the second that are not set by the
;; actions of the first
;; the actions are the = or * from the first with the = or * from
;; the second unioned in and overriding and
;; the + of the second if there is one
;;
(declare (ignore p1))
(let* ((c1 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(c2 (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(a1= (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2= (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s)))
(a1+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s)))
(a1* (find-if (lambda (x) (and (char= #\* (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2* (find-if (lambda (x) (and (char= #\* (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s)))
(bindings (append (previous-production-bindings (compilation-module-previous module))
(production-compilation-instan (production-name p2)))))
(case p1-index
((4 12 13 44)
(list (if c1 (list c1) nil)
(append (when (or a1= a1*) ;; can't have both with current description
(if a1=
(list a1=)
(list a1*)))
(cond ((and a1+ a2=)
(awhen (buffer+-union a1+ a2= bindings)
(list it)))
((and a1+ a2*)
(awhen (buffer+-union a1+ a2* bindings)
(list it)))
(a1+
(list a1+))
(t
nil)))))
((0 8)
(list (awhen (buffer-condition-union c1 c2 a1= bindings) ;; a1= is always nil, though so why use it?
(list it))
(append (when a2=
(list a2=))
(when a2*
(list a2*))
(when a2+
(list a2+)))))
((9 40)
(list (awhen (buffer-condition-union c1 c2 (if a1= a1= a1*) bindings)
(list it))
(append
(cond ((and (= p2-index 8)
(not (find buffer (compilation-module-no-harvest module))) ;; it is strict harvested
(null (second a1=))) ;; the mod in a1 is a null mod
nil)
((and a1* a2=)
(awhen (buffer=-union a1* a2= bindings)
(list it)))
((or a1= a2=) ;; if there's at least one = union those
(awhen (buffer=-union a1= a2= bindings)
(list it)))
((or a1* a2*) ;; if there's at least one * union those
(awhen (buffer=-union a1* a2* bindings)
(list it)))
(t nil))
(when a2+
(list a2+))))))))
(defun CHECK-GOAL-CONSISTENCY (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore p1 p2-index))
(case p1-index
((4 12 13) ;; a RHS +
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\+)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
((44) ;; a RHS + with a * that's not considered
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\+)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
((9) ;; a RHS =
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
((40) ;; a RHS *
(check-consistency module (find-if (lambda (x)
(and (char= (compose-rep-op x) #\*)
(eq (compose-rep-name x) buffer)))
(second p1-s))
(previous-production-bindings (compilation-module-previous module))
(find-if (lambda (x)
(and (char= (compose-rep-op x) #\=)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(production-bindings p2)))
(t
t)))
(defun NO-RHS-GOAL-REF (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Can't compile if the variable naming the buffer is used in the actions of p2"
(declare (ignore p1 module p1-s p1-index p2 p2-index))
(not (recursive-find (intern (concatenate 'string "=" (symbol-name buffer)))
(second p2-s))))
(defun NO-GOAL-HARVESTING (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore p1 p1-s p1-index p2 p2-s p2-index))
(find buffer (compilation-module-no-harvest module)))
(defun NO-GOAL-HARVESTING-OR-NULL-MOD (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore p1 p1-index p2 p2-s p2-index))
(or (find buffer (compilation-module-no-harvest module))
(let ((mod (find-if (lambda (x) (and (char= #\= (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s))))
(and mod (null (second mod))))))
(defun G-B-C1 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(and (no-rhs-goal-ref buffer module p1 p1-s p1-index p2 p2-s p2-index)
(no-goal-harvesting buffer module p1 p1-s p1-index p2 p2-s p2-index)))
(defun goal-reason (p1-index p2-index failed-function)
(if failed-function
(cond ((eql failed-function 'no-rhs-goal-ref)
"the buffer variable cannot be used in the actions of the second production if there is a request in the first production.")
((eql failed-function 'no-goal-harvesting)
"the buffer is being strict harvested.")
((eql failed-function 'g-b-c1)
"either the buffer is being strict harvested or the buffer variable is used in the actions of the second production.")
(t
(format nil "unknown reason ~s" failed-function)))
(case p1-index
((2 6 10 11 14 15 42 43 46 47)
"the buffer is explicitly cleared in the first production")
((16 18 20 22 24 25 26 27 28 29 30 31 56 57 58 60 59 61 62 63)
"there are queries of the buffer in the first production")
((41 45)
"the first production makes both a modification and a modification request")
(t
(case p2-index
((2 6 10 11 14 15 42 43 46 47)
"the buffer is explicitly cleared in the second production")
((16 18 20 22 24 25 26 27 28 29 30 31 56 57 58 60 59 61 62 63)
"there are queries of the buffer in the second production")
((41 45)
"the second production makes both a modification and a modification request")
(t
(case p1-index
((4 12 13 44)
"both productions make requests")
(t
"one production makes a modification and the other makes a modification request"))))))))
(define-compilation-type GOAL ((44 40 NO-RHS-GOAL-REF)
(44 9 NO-RHS-GOAL-REF) (44 8 G-B-C1)
(44 0 T) (40 44 T) (40 40 T) (40 13 T)
(40 12 T) (40 9 T)
(40 8 NO-GOAL-HARVESTING) (40 4 T)
(40 0 T) (13 40 NO-RHS-GOAL-REF)
(13 9 NO-RHS-GOAL-REF) (13 8 G-B-C1)
(13 0 T) (12 40 NO-RHS-GOAL-REF)
(12 9 NO-RHS-GOAL-REF) (12 8 G-B-C1)
(12 0 T) (9 13 T) (9 12 T) (9 9 T)
(9 8 NO-GOAL-HARVESTING-OR-NULL-MOD) (9 4 T) (9 0 T)
(8 44 NO-GOAL-HARVESTING)
(8 40 NO-GOAL-HARVESTING)
(8 13 NO-GOAL-HARVESTING)
(8 12 NO-GOAL-HARVESTING)
(8 9 NO-GOAL-HARVESTING)
(8 8 NO-GOAL-HARVESTING) (8 4 T) (8 0 T)
(4 40 NO-RHS-GOAL-REF)
(4 9 NO-RHS-GOAL-REF) (4 8 G-B-C1)
(4 0 T) (0 44 T) (0 40 T) (0 13 T)
(0 12 T) (0 9 T) (0 8 T)
(0 4 T))
(GOAL) MAP-GOAL-BUFFER COMPOSE-GOAL-BUFFER CHECK-GOAL-CONSISTENCY T NIL GOAL-REASON)
#|
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
|#
| 46,917 | Common Lisp | .lisp | 631 | 49.568938 | 180 | 0.473325 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0ddc2b742467c4ca2aa3c04d204821c55269420735f35a911ddad44a44dcce4b | 14,159 | [
-1
] |
14,160 | motor-compilation.lisp | asmaloney_ACT-R/tools/motor-compilation.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 : motor-compilation.lisp
;;; Version : 2.0
;;;
;;; Description : Production compilation MOTOR style definition.
;;;
;;; Bugs :
;;;
;;; To do :
;;; ----- History -----
;;;
;;; 2010.12.06 Dan
;;; : * Created automatically by build-compilation-type-file.
;;; : * Added the details of the functions.
;;; 2010.12.10 Dan
;;; : * Changed m-b-c1 since buffer empty is not a sufficient case
;;; : for safety since the buffer is always empty.
;;; 2012.04.04 Dan [1.1]
;;; : * Added the whynot reason function.
;;; 2012.05.01 Dan
;;; : * Removed a duplicate number from the cases in the whynot function.
;;; 2020.06.22 Dan [2.0]
;;; : * The functions are now all passed the same set of parameters:
;;; : buffer module p1 p1-s p1-index p2 p2-s p2-index
;;; : the p1-s and p2-s are the new "standard" representation that
;;; : can be decomposed with composition-rep-* where * is:
;;; : op -- the character of the operation =,?,!,+,-,*,@
;;; : name -- the symbol naming the buffer or bang action
;;; : token -- the symbol of the production item for op and name
;;; : slots -- list of slot-spec lists
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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 COMPOSE-MOTOR-BUFFER (buffer module p1 p1-s p1-index p2 p2-s p2-index)
(declare (ignore module p1 p2 p2-index))
;; This is based on the limited set of conditions that can
;; be composed.
;;
;; There are no buffer tests or modification actions allowed.
;;
;; The constraints are:
;;
;; If the first production doesn't make a query
;; or make a request (0)
;; any query and action are used from the second
;; If the first production makes a request without a query (4)
;; there is no query and the action from the first is used
;; If the first has a query and no request (16)
;; the query from the first and the action
;; of the second are used
;; If the first has both a query and a request (20)
;; the query and action from the first are used
(let ((q1 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p1-s)))
(q2 (find-if (lambda (x) (and (char= #\? (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (first p2-s)))
(a1+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p1-s)))
(a2+ (find-if (lambda (x) (and (char= #\+ (compose-rep-op x)) (eq buffer (compose-rep-name x)))) (second p2-s))))
(case p1-index
(0
(list (when q2 (list q2))
(when a2+ (list a2+))))
(4
(list nil
(when a1+ (list a1+))))
(16
(list (when q1 (list q1))
(when a2+ (list a2+))))
(20
(list (when q1 (list q1))
(when a1+ (list a1+)))))))
(defun M-B-C1 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"Compilation check for queries such that p2 only uses 'state busy'
since buffer empty is meaningless for motor style buffers"
(declare (ignore module p1 p1-s p1-index p2 p2-index))
;; there can be only one
(let ((query (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))))
(every (lambda (x)
(equalp x '(= state busy)))
(compose-rep-slots query))))
(defun M-B-C2 (buffer module p1 p1-s p1-index p2 p2-s p2-index)
"queries in p1 and p2 must be the same
NOTE: this doesn't take into account any variables at this time"
(declare (ignore module p1 p1-index p2 p2-index))
(let ((query1 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p1-s))
(compose-rep-slots it)))
(query2 (awhen (find-if (lambda (x)
(and (char= (compose-rep-op x) #\?)
(eq (compose-rep-name x) buffer)))
(first p2-s))
(compose-rep-slots it))))
(= (length query1) (length query2)
(length (remove-duplicates (append query1 query2) :test 'equal)))))
(defun motor-reason (p1-index p2-index failed-function)
(cond ((eql failed-function 'm-b-c1)
"when the first production makes a request the second can only query for state busy.")
((eql failed-function 'm-b-c2)
"the queries in both productions must be the same.")
(t
(case p1-index
((8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 40 41 42 44 43 45 46 47 56 57 58 60 59 61 62 63)
"buffer tests in first production are not allowed.")
((2 6 18 22)
"the buffer is explicitly cleared in the first production.")
(t
(case p2-index
((8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 40 41 42 44 43 45 46 47 56 57 58 60 59 61 62 63)
"buffer tests in second production are not allowed.")
((2 6 18 22)
"the buffer is explicitly cleared in the second production.")
(t
"both productions make requests.")))))))
(define-compilation-type MOTOR ((20 16 M-B-C1)
(20 0 T)
(16 20 M-B-C2)
(16 16 M-B-C2)
(16 4 T)
(16 0 T)
(4 16 M-B-C1)
(4 0 T)
(0 20 T)
(0 16 T)
(0 4 T))
:DEFAULT NIL COMPOSE-MOTOR-BUFFER NIL NIL NIL motor-reason)
#|
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,651 | Common Lisp | .lisp | 155 | 40.03871 | 122 | 0.534427 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 62a4fa7e74a58cb0b90dcf0f256d1c5c7349a3ce587e69d30c6f2231330878f8 | 14,160 | [
-1
] |
14,161 | creating-an-image-model.lisp | asmaloney_ACT-R/examples/creating-image-items/creating-an-image-model.lisp | ;;; This model is a simple demonstration of using the image AGI items.
;;; It performs the task created by the creating-an-image.lisp or
;;; creating_an_image.py file.
;;;
;;; The model attends to the items it sees in the window from
;;; top to bottom and for each one moves the mouse to a position
;;; slightly offset from the true location of the item and then
;;; clicks the mouse.
;;;
(clear-all)
(define-model image-testing-model
(sgp :v t :show-focus t :needs-mouse t)
(set-visloc-default screen-y lowest)
(p attend
"attend to anything placed into the visual-location buffer"
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location
!eval! (pprint-chunks-fct (list =visual-location)))
(p attend-and-instan-loc
"Create a new chunk in the imaginal buffer with the location information of the attended item"
=visual>
screen-pos =loc
?imaginal>
state free
==>
+imaginal> =loc
!eval! (pprint-chunks-fct (list =visual)))
(p adjust
"adjust the x,y coordinates in the imaginal buffer"
=imaginal>
screen-x =x
screen-y =y
color =color
==>
!bind! =nx (- =x 5)
!bind! =ny (+ =y 2)
=imaginal>
screen-x =nx
screen-y =ny
color nil)
(p move
"Move the mouse to the location in the imaginal buffer"
=imaginal>
color nil
?manual>
state free
==>
+manual>
isa move-cursor
loc =imaginal
+goal>)
(p click
"Once the mouse is there click it and try to find another feature in the window"
=goal>
?manual>
state free
==>
+manual>
isa click-mouse
+visual-location>
> screen-y current
:nearest current-y
-goal>
-imaginal>))
| 1,855 | Common Lisp | .lisp | 69 | 21.347826 | 99 | 0.632919 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 50a28cb93c3b926e1432f433f0ce6a8f3cb48d09661d6c3a5e5fc2a1c5ee5e04 | 14,161 | [
120712
] |
14,162 | creating-an-image.lisp | asmaloney_ACT-R/examples/creating-image-items/creating-an-image.lisp | ;;; This is the Lisp code to run the task that goes along with the
;;; creating-an-image-model.
;;;
(load-act-r-model "ACT-R:examples;creating-image-items;creating-an-image-model.lisp")
;;; It is a simple demonstration of creating and using the
;;; image AGI item, and it assumes that the smalllogo.gif
;;; and ref-brain.gif files are in the gui/AGI-images directory
;;; if you use a visible window to see the images.
;;;
;;; To run the task call the run-test function. It has one
;;; optional parameter which if provided as any non-nil value
;;; indicates the window should be visible. The default is
;;; to use a virtual window.
(defun click-brain (text pos)
(model-output "Clicked image ~s at ~D ~D" text (first pos) (second pos)))
(add-act-r-command "click-brain" 'click-brain "Example function for image click action. Do not call.")
(defun click-brain-2 (value)
(model-output "Clicked the second brain image given value ~s" value))
(add-act-r-command "click-brain-2" 'click-brain-2 "Example function for image click action with parameters. Do not call.")
(defun run-test (&optional (visible nil))
(reset)
(let ((win (open-exp-window "image test" :visible visible :width 310 :height 420)))
(install-device win)
(start-hand-at-mouse)
(add-image-to-exp-window win "logo" "smalllogo.gif" :x 10 :y 10 :width 288 :height 142)
(add-items-to-exp-window win (create-image-for-exp-window win "brain" "ref-brain.gif" :x 10 :y 160 :width 128 :height 128 :action "click-brain"))
(add-image-to-exp-window win "brain-2" "ref-brain.gif" :x 10 :y 290 :width 128 :height 128 :action (list "click-brain-2" "this string"))
;; run until the vision module processes the new items in the display
(run-n-events 2)
;; print the visicon to see how the new items are represented
(print-visicon)
;; run for up to 5 seconds using real-time if the window is visible
(run 5 visible)))
#|
CG-USER(119): (run-test t)
CG-USER(38): (run-test)
0.000 ------ Stopped because event limit reached
Name Att Loc IMAGE KIND HEIGHT WIDTH VALUE SIZE
---------------- --- -------------- ----- ----- ------ ----- --------- ----------
VISUAL-LOCATION1 NEW (374 524 1080) T IMAGE 128 128 "brain" 46.0
VISUAL-LOCATION2 NEW (374 654 1080) T IMAGE 128 128 "brain-2" 46.0
VISUAL-LOCATION0 NEW (454 381 1080) T IMAGE 142 288 "logo" 114.259995
0.000 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0 NIL
0.000 VISION visicon-update
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED ATTEND
VISUAL-LOCATION0-0
KIND IMAGE
VALUE IMAGE
HEIGHT 142
WIDTH 288
SCREEN-X 454
SCREEN-Y 381
DISTANCE 1080
SIZE 114.259995
0.050 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 PROCEDURAL CLEAR-BUFFER VISUAL
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.135 VISION Encoding-complete VISUAL-LOCATION0-0 NIL
0.135 VISION SET-BUFFER-CHUNK VISUAL IMAGE0
0.135 PROCEDURAL CONFLICT-RESOLUTION
0.185 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-INSTAN-LOC
IMAGE0-0
SCREEN-POS VISUAL-LOCATION0-0
VALUE "logo"
HEIGHT 142
WIDTH 288
IMAGE T
0.185 PROCEDURAL CLEAR-BUFFER VISUAL
0.185 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.185 PROCEDURAL CONFLICT-RESOLUTION
0.385 IMAGINAL SET-BUFFER-CHUNK-FROM-SPEC IMAGINAL
0.385 PROCEDURAL CONFLICT-RESOLUTION
0.435 PROCEDURAL PRODUCTION-FIRED MOVE
0.435 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.435 PROCEDURAL CLEAR-BUFFER MANUAL
0.435 PROCEDURAL CLEAR-BUFFER GOAL
0.435 MOTOR MOVE-CURSOR LOC CHUNK0
0.435 GOAL SET-BUFFER-CHUNK-FROM-SPEC GOAL
0.435 PROCEDURAL CONFLICT-RESOLUTION
0.635 PROCEDURAL CONFLICT-RESOLUTION
0.685 PROCEDURAL CONFLICT-RESOLUTION
0.785 PROCEDURAL CONFLICT-RESOLUTION
0.835 PROCEDURAL CONFLICT-RESOLUTION
0.885 PROCEDURAL PRODUCTION-FIRED CLICK
0.885 PROCEDURAL CLEAR-BUFFER GOAL
0.885 PROCEDURAL CLEAR-BUFFER IMAGINAL
0.885 PROCEDURAL CLEAR-BUFFER MANUAL
0.885 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.885 MOTOR CLICK-MOUSE
0.885 VISION Find-location
0.885 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION1
0.885 PROCEDURAL CONFLICT-RESOLUTION
0.935 PROCEDURAL PRODUCTION-FIRED ATTEND
VISUAL-LOCATION1-0
KIND IMAGE
VALUE IMAGE
HEIGHT 128
WIDTH 128
SCREEN-X 374
SCREEN-Y 524
DISTANCE 1080
SIZE 46.0
0.935 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.935 PROCEDURAL CLEAR-BUFFER VISUAL
0.935 PROCEDURAL CONFLICT-RESOLUTION
1.020 VISION Encoding-complete VISUAL-LOCATION1-0 NIL
1.020 VISION SET-BUFFER-CHUNK VISUAL IMAGE1
1.020 PROCEDURAL CONFLICT-RESOLUTION
1.070 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-INSTAN-LOC
IMAGE1-0
SCREEN-POS VISUAL-LOCATION1-0
VALUE "brain"
HEIGHT 128
WIDTH 128
IMAGE T
1.070 PROCEDURAL CLEAR-BUFFER VISUAL
1.070 PROCEDURAL CLEAR-BUFFER IMAGINAL
1.070 PROCEDURAL CONFLICT-RESOLUTION
1.085 PROCEDURAL CONFLICT-RESOLUTION
#|Warning: Image "logo" with no valid action clicked at position 144,71 at time 1.095. |#
1.095 PROCEDURAL CONFLICT-RESOLUTION
1.185 PROCEDURAL CONFLICT-RESOLUTION
1.270 IMAGINAL SET-BUFFER-CHUNK-FROM-SPEC IMAGINAL
1.270 PROCEDURAL CONFLICT-RESOLUTION
1.320 PROCEDURAL PRODUCTION-FIRED MOVE
1.320 PROCEDURAL CLEAR-BUFFER IMAGINAL
1.320 PROCEDURAL CLEAR-BUFFER MANUAL
1.320 PROCEDURAL CLEAR-BUFFER GOAL
1.320 MOTOR MOVE-CURSOR LOC CHUNK1
1.320 GOAL SET-BUFFER-CHUNK-FROM-SPEC GOAL
1.320 PROCEDURAL CONFLICT-RESOLUTION
1.520 PROCEDURAL CONFLICT-RESOLUTION
1.570 PROCEDURAL CONFLICT-RESOLUTION
1.670 PROCEDURAL CONFLICT-RESOLUTION
1.720 PROCEDURAL CONFLICT-RESOLUTION
1.770 PROCEDURAL PRODUCTION-FIRED CLICK
1.770 PROCEDURAL CLEAR-BUFFER GOAL
1.770 PROCEDURAL CLEAR-BUFFER IMAGINAL
1.770 PROCEDURAL CLEAR-BUFFER MANUAL
1.770 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.770 MOTOR CLICK-MOUSE
1.770 VISION Find-location
1.770 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION2
1.770 PROCEDURAL CONFLICT-RESOLUTION
1.820 PROCEDURAL PRODUCTION-FIRED ATTEND
VISUAL-LOCATION2-0
KIND IMAGE
VALUE IMAGE
HEIGHT 128
WIDTH 128
SCREEN-X 374
SCREEN-Y 654
DISTANCE 1080
SIZE 46.0
1.820 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.820 PROCEDURAL CLEAR-BUFFER VISUAL
1.820 PROCEDURAL CONFLICT-RESOLUTION
1.905 VISION Encoding-complete VISUAL-LOCATION2-0 NIL
1.905 VISION SET-BUFFER-CHUNK VISUAL IMAGE2
1.905 PROCEDURAL CONFLICT-RESOLUTION
1.955 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-INSTAN-LOC
IMAGE2-0
SCREEN-POS VISUAL-LOCATION2-0
VALUE "brain-2"
HEIGHT 128
WIDTH 128
IMAGE T
1.955 PROCEDURAL CLEAR-BUFFER VISUAL
1.955 PROCEDURAL CLEAR-BUFFER IMAGINAL
1.955 PROCEDURAL CONFLICT-RESOLUTION
1.970 PROCEDURAL CONFLICT-RESOLUTION
Clicked image "brain" at 64 64
1.980 PROCEDURAL CONFLICT-RESOLUTION
2.070 PROCEDURAL CONFLICT-RESOLUTION
2.155 IMAGINAL SET-BUFFER-CHUNK-FROM-SPEC IMAGINAL
2.155 PROCEDURAL CONFLICT-RESOLUTION
2.205 PROCEDURAL PRODUCTION-FIRED MOVE
2.205 PROCEDURAL CLEAR-BUFFER IMAGINAL
2.205 PROCEDURAL CLEAR-BUFFER MANUAL
2.205 PROCEDURAL CLEAR-BUFFER GOAL
2.205 MOTOR MOVE-CURSOR LOC CHUNK2
2.205 GOAL SET-BUFFER-CHUNK-FROM-SPEC GOAL
2.205 PROCEDURAL CONFLICT-RESOLUTION
2.405 PROCEDURAL CONFLICT-RESOLUTION
2.455 PROCEDURAL CONFLICT-RESOLUTION
2.555 PROCEDURAL CONFLICT-RESOLUTION
2.605 PROCEDURAL CONFLICT-RESOLUTION
2.655 PROCEDURAL PRODUCTION-FIRED CLICK
2.655 PROCEDURAL CLEAR-BUFFER GOAL
2.655 PROCEDURAL CLEAR-BUFFER IMAGINAL
2.655 PROCEDURAL CLEAR-BUFFER MANUAL
2.655 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.655 MOTOR CLICK-MOUSE
2.655 VISION Find-location
2.655 VISION find-loc-failure
2.655 PROCEDURAL CONFLICT-RESOLUTION
2.805 PROCEDURAL CONFLICT-RESOLUTION
2.855 PROCEDURAL CONFLICT-RESOLUTION
Clicked the second brain image given value "this string"
2.865 PROCEDURAL CONFLICT-RESOLUTION
2.955 PROCEDURAL CONFLICT-RESOLUTION
2.955 ------ Stopped because no events left to process
|#
| 10,226 | Common Lisp | .lisp | 204 | 45.019608 | 149 | 0.59994 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d374f1cf9e03e80710a423173b8f455df5da328efd657600cd6812175fb6f5c8 | 14,162 | [
-1
] |
14,163 | background-model.lisp | asmaloney_ACT-R/examples/creating-image-items/background-model.lisp | ;;; This model is a simple demonstration of using arbitrary
;;; visicon features in conjunction with the image AGI items.
;;; It performs the task created by the background-image.lisp or
;;; background_image.py file.
;;;
;;; The model attends to the items it sees in the window (except
;;; for the background image) from left to right and top to
;;; bottom moving the mouse to each as it goes. It also prints
;;; the visual chunks which it receives.
;;;
(clear-all)
(define-model background
(define-chunks same-line next-line)
(sgp :v t :show-focus t :needs-mouse t)
(p find-start
?goal>
buffer empty
=visual-location>
==>
+goal>
+visual-location>
- kind image
screen-y lowest
screen-x lowest)
(p attend
=goal>
=visual-location>
?visual>
state free
==>
=goal>
state nil
+visual>
cmd move-attention
screen-pos =visual-location
!eval! (pprint-chunks-fct (list =visual-location)))
(p attend-and-move
=visual>
screen-pos =loc
?manual>
state free
==>
+manual>
isa move-cursor
loc =loc
!eval! (pprint-chunks-fct (list =visual)))
(p find-next
=goal>
state nil
?visual-location>
buffer empty
?visual>
state free
buffer empty
?manual>
state free
==>
=goal>
state same-line
+visual-location>
screen-y current
> screen-x current
screen-x lowest
- kind image)
(p next-row
=goal>
state same-line
?visual-location>
buffer failure
==>
=goal>
state next-line
+visual-location>
> screen-y current
screen-y lowest
screen-x lowest
- kind image)
(p no-more
=goal>
state next-line
?visual-location>
buffer failure
==>
-goal>))
| 1,935 | Common Lisp | .lisp | 84 | 16.940476 | 64 | 0.605176 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5dec3d6bad266567680a4f579b9e4a4661353abc8576660adf8b31fecd52e91a | 14,163 | [
348986
] |
14,164 | background-image.lisp | asmaloney_ACT-R/examples/creating-image-items/background-image.lisp | ;;; This is the Lisp code to run the task that goes along with the
;;; background-model.
;;;
(load-act-r-model "ACT-R:examples;creating-image-items;background-model.lisp")
;;; It is a demonstration of creating and using an
;;; image AGI item along with custom visicon features.
;;; It assumes that the ref-brain.gif file is in the
;;; gui/AGI-images directory if you use a visible window
;;; to see the images.
;;;
;;; To run the task call the run-test function. It has one
;;; optional parameter which if provided as any non-nil value
;;; indicates the window should be visible. The default is
;;; to use a virtual window.
(defun run-test (&optional (visible nil))
(reset)
(let ((win (open-exp-window "background test" :visible visible :height 390 :width 390 :x 100 :y 100)))
(install-device win)
(start-hand-at-mouse)
(add-image-to-exp-window win "background" "ref-brain.gif" :x 0 :y 0 :height 390 :width 390)
(dotimes (x 3)
(dotimes (y 3)
(add-visicon-features (list 'screen-x (+ 164 (* x 130))
'screen-y (+ 164 (* y 130))
'height 128
'width 128
'name (list "brain" (format nil "brain-~d" (+ x (* y 3))))))))
;; run until the vision module processes the new items in the display
(run-n-events 2)
;; print the visicon to see how the new items are represented
(print-visicon)
;; run for up to 10 seconds using real-time if the window is visible
(run 10 visible)))
#|
CG-USER(12): (run-test)
0.000 ------ Stopped because event limit reached
Name Att Loc Width Height Size Name Image Kind Value
---------------- --- -------------- ----- ------ ----- --------- ----- ----- ------------
CHUNK0 NEW (164 164 1080) 128 128 46.0 "brain-0"
CHUNK1 NEW (164 294 1080) 128 128 46.0 "brain-3"
CHUNK2 NEW (164 424 1080) 128 128 46.0 "brain-6"
CHUNK3 NEW (294 164 1080) 128 128 46.0 "brain-1"
CHUNK4 NEW (294 294 1080) 128 128 46.0 "brain-4"
CHUNK5 NEW (294 424 1080) 128 128 46.0 "brain-7"
VISUAL-LOCATION0 NEW (295 295 1080) 390 390 419.0 T IMAGE "background"
CHUNK6 NEW (424 164 1080) 128 128 46.0 "brain-2"
CHUNK7 NEW (424 294 1080) 128 128 46.0 "brain-5"
CHUNK8 NEW (424 424 1080) 128 128 46.0 "brain-8"
0.000 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0 NIL
0.000 VISION visicon-update
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED FIND-START
0.050 PROCEDURAL CLEAR-BUFFER GOAL
0.050 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 VISION Find-location
0.050 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK0
0.050 GOAL SET-BUFFER-CHUNK GOAL CHUNK9
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.100 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK0-1
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 164
SCREEN-Y 164
DISTANCE 1080
SIZE 46.0
0.100 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 PROCEDURAL CLEAR-BUFFER VISUAL
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.185 VISION Encoding-complete CHUNK0-1 NIL
0.185 VISION SET-BUFFER-CHUNK VISUAL CHUNK10
0.185 PROCEDURAL CONFLICT-RESOLUTION
0.235 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK10-0
NAME "brain-0"
SCREEN-POS CHUNK0-0
HEIGHT 128
WIDTH 128
0.235 PROCEDURAL CLEAR-BUFFER VISUAL
0.235 PROCEDURAL CLEAR-BUFFER MANUAL
0.235 MOTOR MOVE-CURSOR LOC CHUNK0-0
0.235 PROCEDURAL CONFLICT-RESOLUTION
0.435 PROCEDURAL CONFLICT-RESOLUTION
0.485 PROCEDURAL CONFLICT-RESOLUTION
0.585 PROCEDURAL CONFLICT-RESOLUTION
0.635 PROCEDURAL CONFLICT-RESOLUTION
0.685 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
0.685 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.685 VISION Find-location
0.685 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK3
0.685 PROCEDURAL CONFLICT-RESOLUTION
0.735 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK3-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 294
SCREEN-Y 164
DISTANCE 1080
SIZE 46.0
0.735 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.735 PROCEDURAL CLEAR-BUFFER VISUAL
0.735 PROCEDURAL CONFLICT-RESOLUTION
0.820 VISION Encoding-complete CHUNK3-0 NIL
0.820 VISION SET-BUFFER-CHUNK VISUAL CHUNK11
0.820 PROCEDURAL CONFLICT-RESOLUTION
0.870 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK11-0
NAME "brain-1"
SCREEN-POS CHUNK3-0
HEIGHT 128
WIDTH 128
0.870 PROCEDURAL CLEAR-BUFFER VISUAL
0.870 PROCEDURAL CLEAR-BUFFER MANUAL
0.870 MOTOR MOVE-CURSOR LOC CHUNK3-0
0.870 PROCEDURAL CONFLICT-RESOLUTION
0.970 PROCEDURAL CONFLICT-RESOLUTION
1.020 PROCEDURAL CONFLICT-RESOLUTION
1.120 PROCEDURAL CONFLICT-RESOLUTION
1.170 PROCEDURAL CONFLICT-RESOLUTION
1.220 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
1.220 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.220 VISION Find-location
1.220 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK6
1.220 PROCEDURAL CONFLICT-RESOLUTION
1.270 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK6-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 424
SCREEN-Y 164
DISTANCE 1080
SIZE 46.0
1.270 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.270 PROCEDURAL CLEAR-BUFFER VISUAL
1.270 PROCEDURAL CONFLICT-RESOLUTION
1.355 VISION Encoding-complete CHUNK6-0 NIL
1.355 VISION SET-BUFFER-CHUNK VISUAL CHUNK12
1.355 PROCEDURAL CONFLICT-RESOLUTION
1.405 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK12-0
NAME "brain-2"
SCREEN-POS CHUNK6-0
HEIGHT 128
WIDTH 128
1.405 PROCEDURAL CLEAR-BUFFER VISUAL
1.405 PROCEDURAL CLEAR-BUFFER MANUAL
1.405 MOTOR MOVE-CURSOR LOC CHUNK6-0
1.405 PROCEDURAL CONFLICT-RESOLUTION
1.455 PROCEDURAL CONFLICT-RESOLUTION
1.555 PROCEDURAL CONFLICT-RESOLUTION
1.605 PROCEDURAL CONFLICT-RESOLUTION
1.655 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
1.655 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.655 VISION Find-location
1.655 VISION FIND-LOC-FAILURE
1.655 PROCEDURAL CONFLICT-RESOLUTION
1.705 PROCEDURAL PRODUCTION-FIRED NEXT-ROW
1.705 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.705 VISION Find-location
1.705 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK1
1.705 PROCEDURAL CONFLICT-RESOLUTION
1.755 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK1-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 164
SCREEN-Y 294
DISTANCE 1080
SIZE 46.0
1.755 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.755 PROCEDURAL CLEAR-BUFFER VISUAL
1.755 PROCEDURAL CONFLICT-RESOLUTION
1.840 VISION Encoding-complete CHUNK1-0 NIL
1.840 VISION SET-BUFFER-CHUNK VISUAL CHUNK13
1.840 PROCEDURAL CONFLICT-RESOLUTION
1.890 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK13-0
NAME "brain-3"
SCREEN-POS CHUNK1-0
HEIGHT 128
WIDTH 128
1.890 PROCEDURAL CLEAR-BUFFER VISUAL
1.890 PROCEDURAL CLEAR-BUFFER MANUAL
1.890 MOTOR MOVE-CURSOR LOC CHUNK1-0
1.890 PROCEDURAL CONFLICT-RESOLUTION
1.990 PROCEDURAL CONFLICT-RESOLUTION
2.040 PROCEDURAL CONFLICT-RESOLUTION
2.173 PROCEDURAL CONFLICT-RESOLUTION
2.223 PROCEDURAL CONFLICT-RESOLUTION
2.273 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
2.273 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.273 VISION Find-location
2.273 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK4
2.273 PROCEDURAL CONFLICT-RESOLUTION
2.323 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK4-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 294
SCREEN-Y 294
DISTANCE 1080
SIZE 46.0
2.323 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.323 PROCEDURAL CLEAR-BUFFER VISUAL
2.323 PROCEDURAL CONFLICT-RESOLUTION
2.408 VISION Encoding-complete CHUNK4-0 NIL
2.408 VISION SET-BUFFER-CHUNK VISUAL CHUNK14
2.408 PROCEDURAL CONFLICT-RESOLUTION
2.458 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK14-0
NAME "brain-4"
SCREEN-POS CHUNK4-0
HEIGHT 128
WIDTH 128
2.458 PROCEDURAL CLEAR-BUFFER VISUAL
2.458 PROCEDURAL CLEAR-BUFFER MANUAL
2.458 MOTOR MOVE-CURSOR LOC CHUNK4-0
2.458 PROCEDURAL CONFLICT-RESOLUTION
2.558 PROCEDURAL CONFLICT-RESOLUTION
2.608 PROCEDURAL CONFLICT-RESOLUTION
2.708 PROCEDURAL CONFLICT-RESOLUTION
2.758 PROCEDURAL CONFLICT-RESOLUTION
2.808 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
2.808 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.808 VISION Find-location
2.808 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK7
2.808 PROCEDURAL CONFLICT-RESOLUTION
2.858 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK7-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 424
SCREEN-Y 294
DISTANCE 1080
SIZE 46.0
2.858 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.858 PROCEDURAL CLEAR-BUFFER VISUAL
2.858 PROCEDURAL CONFLICT-RESOLUTION
2.943 VISION Encoding-complete CHUNK7-0 NIL
2.943 VISION SET-BUFFER-CHUNK VISUAL CHUNK15
2.943 PROCEDURAL CONFLICT-RESOLUTION
2.993 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK15-0
NAME "brain-5"
SCREEN-POS CHUNK7-0
HEIGHT 128
WIDTH 128
2.993 PROCEDURAL CLEAR-BUFFER VISUAL
2.993 PROCEDURAL CLEAR-BUFFER MANUAL
2.993 MOTOR MOVE-CURSOR LOC CHUNK7-0
2.993 PROCEDURAL CONFLICT-RESOLUTION
3.043 PROCEDURAL CONFLICT-RESOLUTION
3.143 PROCEDURAL CONFLICT-RESOLUTION
3.193 PROCEDURAL CONFLICT-RESOLUTION
3.243 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
3.243 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
3.243 VISION Find-location
3.243 VISION FIND-LOC-FAILURE
3.243 PROCEDURAL CONFLICT-RESOLUTION
3.293 PROCEDURAL PRODUCTION-FIRED NEXT-ROW
3.293 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
3.293 VISION Find-location
3.293 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK2
3.293 PROCEDURAL CONFLICT-RESOLUTION
3.343 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK2-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 164
SCREEN-Y 424
DISTANCE 1080
SIZE 46.0
3.343 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
3.343 PROCEDURAL CLEAR-BUFFER VISUAL
3.343 PROCEDURAL CONFLICT-RESOLUTION
3.428 VISION Encoding-complete CHUNK2-0 NIL
3.428 VISION SET-BUFFER-CHUNK VISUAL CHUNK16
3.428 PROCEDURAL CONFLICT-RESOLUTION
3.478 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK16-0
NAME "brain-6"
SCREEN-POS CHUNK2-0
HEIGHT 128
WIDTH 128
3.478 PROCEDURAL CLEAR-BUFFER VISUAL
3.478 PROCEDURAL CLEAR-BUFFER MANUAL
3.478 MOTOR MOVE-CURSOR LOC CHUNK2-0
3.478 PROCEDURAL CONFLICT-RESOLUTION
3.578 PROCEDURAL CONFLICT-RESOLUTION
3.628 PROCEDURAL CONFLICT-RESOLUTION
3.761 PROCEDURAL CONFLICT-RESOLUTION
3.811 PROCEDURAL CONFLICT-RESOLUTION
3.861 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
3.861 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
3.861 VISION Find-location
3.861 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK5
3.861 PROCEDURAL CONFLICT-RESOLUTION
3.911 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK5-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 294
SCREEN-Y 424
DISTANCE 1080
SIZE 46.0
3.911 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
3.911 PROCEDURAL CLEAR-BUFFER VISUAL
3.911 PROCEDURAL CONFLICT-RESOLUTION
3.996 VISION Encoding-complete CHUNK5-0 NIL
3.996 VISION SET-BUFFER-CHUNK VISUAL CHUNK17
3.996 PROCEDURAL CONFLICT-RESOLUTION
4.046 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK17-0
NAME "brain-7"
SCREEN-POS CHUNK5-0
HEIGHT 128
WIDTH 128
4.046 PROCEDURAL CLEAR-BUFFER VISUAL
4.046 PROCEDURAL CLEAR-BUFFER MANUAL
4.046 MOTOR MOVE-CURSOR LOC CHUNK5-0
4.046 PROCEDURAL CONFLICT-RESOLUTION
4.146 PROCEDURAL CONFLICT-RESOLUTION
4.196 PROCEDURAL CONFLICT-RESOLUTION
4.296 PROCEDURAL CONFLICT-RESOLUTION
4.346 PROCEDURAL CONFLICT-RESOLUTION
4.396 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
4.396 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
4.396 VISION Find-location
4.396 VISION SET-BUFFER-CHUNK VISUAL-LOCATION CHUNK8
4.396 PROCEDURAL CONFLICT-RESOLUTION
4.446 PROCEDURAL PRODUCTION-FIRED ATTEND
CHUNK8-0
NAME "brain"
HEIGHT 128
WIDTH 128
SCREEN-X 424
SCREEN-Y 424
DISTANCE 1080
SIZE 46.0
4.446 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
4.446 PROCEDURAL CLEAR-BUFFER VISUAL
4.446 PROCEDURAL CONFLICT-RESOLUTION
4.531 VISION Encoding-complete CHUNK8-0 NIL
4.531 VISION SET-BUFFER-CHUNK VISUAL CHUNK18
4.531 PROCEDURAL CONFLICT-RESOLUTION
4.581 PROCEDURAL PRODUCTION-FIRED ATTEND-AND-MOVE
CHUNK18-0
NAME "brain-8"
SCREEN-POS CHUNK8-0
HEIGHT 128
WIDTH 128
4.581 PROCEDURAL CLEAR-BUFFER VISUAL
4.581 PROCEDURAL CLEAR-BUFFER MANUAL
4.581 MOTOR MOVE-CURSOR LOC CHUNK8-0
4.581 PROCEDURAL CONFLICT-RESOLUTION
4.631 PROCEDURAL CONFLICT-RESOLUTION
4.731 PROCEDURAL CONFLICT-RESOLUTION
4.781 PROCEDURAL CONFLICT-RESOLUTION
4.831 PROCEDURAL PRODUCTION-FIRED FIND-NEXT
4.831 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
4.831 VISION Find-location
4.831 VISION FIND-LOC-FAILURE
4.831 PROCEDURAL CONFLICT-RESOLUTION
4.881 PROCEDURAL PRODUCTION-FIRED NEXT-ROW
4.881 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
4.881 VISION Find-location
4.881 VISION FIND-LOC-FAILURE
4.881 PROCEDURAL CONFLICT-RESOLUTION
4.931 PROCEDURAL PRODUCTION-FIRED NO-MORE
4.931 PROCEDURAL CLEAR-BUFFER GOAL
4.931 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
4.931 PROCEDURAL CONFLICT-RESOLUTION
4.931 ------ Stopped because no events left to process
|#
| 17,696 | Common Lisp | .lisp | 382 | 40.311518 | 104 | 0.565732 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e05b501dc1ea95c12cdd41ece893f356007fc23e327894144b45beb3652be875 | 14,164 | [
362514
] |
14,165 | unit-1-together-1-mp.lisp | asmaloney_ACT-R/examples/multiple-models/unit-1-together-1-mp.lisp | ;;; This is all the models of unit1 defined simultaneously
;;; and running in parallel.
;;; Calling run will result in all three models running.
(clear-all)
(define-model count
(sgp :esc t :lf .05 :trace-detail high)
(chunk-type count-order first second)
(chunk-type count-from start end count)
(add-dm
(b ISA count-order first 1 second 2)
(c ISA count-order first 2 second 3)
(d ISA count-order first 3 second 4)
(e ISA count-order first 4 second 5)
(f ISA count-order first 5 second 6)
(first-goal ISA count-from start 2 end 4)
)
(p start
=goal>
ISA count-from
start =num1
count nil
==>
=goal>
count =num1
+retrieval>
ISA count-order
first =num1
)
(P increment
=goal>
ISA count-from
count =num1
- end =num1
=retrieval>
ISA count-order
first =num1
second =num2
==>
=goal>
count =num2
+retrieval>
ISA count-order
first =num2
!output! (=num1)
)
(P stop
=goal>
ISA count-from
count =num
end =num
==>
-goal>
!output! (=num)
)
(goal-focus first-goal)
)
(define-model semantic
(sgp :esc t :lf .05)
(chunk-type property object attribute value)
(chunk-type is-member object category judgment)
(add-dm
(shark isa chunk) (dangerous isa chunk)
(locomotion isa chunk) (swimming isa chunk)
(fish isa chunk) (salmon isa chunk)
(edible isa chunk) (breathe isa chunk)
(gills isa chunk) (animal isa chunk)
(moves isa chunk) (skin isa chunk)
(canary isa chunk) (color isa chunk)
(sings isa chunk) (bird isa chunk)
(ostrich isa chunk) (flies isa chunk)
(height isa chunk) (tall isa chunk)
(wings isa chunk) (flying isa chunk)
(true isa chunk) (false isa chunk)
(p1 ISA property object shark attribute dangerous value true)
(p2 ISA property object shark attribute locomotion value swimming)
(p3 ISA property object shark attribute category value fish)
(p4 ISA property object salmon attribute edible value true)
(p5 ISA property object salmon attribute locomotion value swimming)
(p6 ISA property object salmon attribute category value fish)
(p7 ISA property object fish attribute breathe value gills)
(p8 ISA property object fish attribute locomotion value swimming)
(p9 ISA property object fish attribute category value animal)
(p10 ISA property object animal attribute moves value true)
(p11 ISA property object animal attribute skin value true)
(p12 ISA property object canary attribute color value yellow)
(p13 ISA property object canary attribute sings value true)
(p14 ISA property object canary attribute category value bird)
(p15 ISA property object ostrich attribute flies value false)
(p16 ISA property object ostrich attribute height value tall)
(p17 ISA property object ostrich attribute category value bird)
(p18 ISA property object bird attribute wings value true)
(p19 ISA property object bird attribute locomotion value flying)
(p20 ISA property object bird attribute category value animal)
(g1 ISA is-member object canary category bird judgment nil)
(g2 ISA is-member object canary category animal judgment nil)
(g3 ISA is-member object canary category fish judgment nil))
(p initial-retrieve
=goal>
ISA is-member
object =obj
category =cat
judgment nil
==>
=goal>
judgment pending
+retrieval>
ISA property
object =obj
attribute category
)
(P direct-verify
=goal>
ISA is-member
object =obj
category =cat
judgment pending
=retrieval>
ISA property
object =obj
attribute category
value =cat
==>
=goal>
judgment yes
)
(P chain-category
=goal>
ISA is-member
object =obj1
category =cat
judgment pending
=retrieval>
ISA property
object =obj1
attribute category
value =obj2
- value =cat
==>
=goal>
object =obj2
+retrieval>
ISA property
object =obj2
attribute category
)
(P fail
=goal>
ISA is-member
object =obj1
category =cat
judgment pending
?retrieval>
state error
==>
=goal>
judgment no
)
(goal-focus g1)
)
(define-model addition
(sgp :esc t :lf .05)
(chunk-type count-order first second)
(chunk-type add arg1 arg2 sum count)
(add-dm
(a ISA count-order first 0 second 1)
(b ISA count-order first 1 second 2)
(c ISA count-order first 2 second 3)
(d ISA count-order first 3 second 4)
(e ISA count-order first 4 second 5)
(f ISA count-order first 5 second 6)
(g ISA count-order first 6 second 7)
(h ISA count-order first 7 second 8)
(i ISA count-order first 8 second 9)
(j ISA count-order first 9 second 10)
(second-goal ISA add arg1 5 arg2 2))
(P initialize-addition
=goal>
ISA add
arg1 =num1
arg2 =num2
sum nil
==>
=goal>
sum =num1
count 0
+retrieval>
isa count-order
first =num1
)
(P terminate-addition
=goal>
ISA add
count =num
arg2 =num
sum =answer
==>
=goal>
count nil
)
(P increment-sum
=goal>
ISA add
sum =sum
count =count
- arg2 =count
=retrieval>
ISA count-order
first =sum
second =newsum
==>
=goal>
sum =newsum
+retrieval>
isa count-order
first =count
)
(P increment-count
=goal>
ISA add
sum =sum
count =count
=retrieval>
ISA count-order
first =count
second =newcount
==>
=goal>
count =newcount
+retrieval>
isa count-order
first =sum
)
(goal-focus second-goal)
)
| 6,134 | Common Lisp | .lisp | 234 | 22.012821 | 68 | 0.627494 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a14c51c3c0e71d26dce251cdfcc8af7490e23e1abe15974cfb05cfe98b20bf68 | 14,165 | [
323423
] |
14,166 | multi-model-talking-models.lisp | asmaloney_ACT-R/examples/multiple-models/multi-model-talking-models.lisp | ;;; This file contains three models which can talk to each other
;;; through the system provided by the multi-model-talking code.
(clear-all)
;;; Each model will output what it hears and from whom in
;;; the trace. M2 will start things off by saying "hello"
;;; and M1 will respond to anything which it hears by
;;; saying "back at you". M3 doesn't do anything other
;;; than listen.
;;; These models ignore their own speech by only having
;;; chunks which aren't "location self" stuffed into the
;;; audio-location buffer.
(define-model m1
(chunk-type goal speaker)
(set-audloc-default - location self :attended nil)
(p detected-sound
=aural-location>
isa audio-event
location =who
?aural>
state free
==>
+goal>
speaker =who
+aural>
isa sound
event =aural-location)
(p hear
=goal>
isa goal
speaker =who
=aural>
isa sound
content =x
?vocal>
state free
==>
+vocal>
isa speak
string "Back at you"
!output! (I heard =who say =x))
)
(define-model m2
(chunk-type goal speaker)
(set-audloc-default - location self :attended nil)
(p speak
?goal>
buffer empty
?vocal>
state free
==>
+goal>
speaker self
+vocal>
isa speak
string "Hello")
(p detected-sound
=aural-location>
isa audio-event
location =who
?aural>
state free
==>
+goal>
speaker =who
+aural>
isa sound
event =aural-location)
(p hear
=goal>
isa goal
speaker =who
=aural>
isa sound
content =x
==>
!output! (I heard =who say =x))
)
(define-model m3
(chunk-type goal speaker)
(set-audloc-default - location self :attended nil)
(p detected-sound
=aural-location>
isa audio-event
location =who
?aural>
state free
==>
+goal>
speaker =who
+aural>
isa sound
event =aural-location)
(p hear
=goal>
isa goal
speaker =who
=aural>
isa sound
content =x
==>
!output! (I heard =who say =x))
)
| 2,342 | Common Lisp | .lisp | 102 | 16.833333 | 64 | 0.569858 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1ac1813d5d302643f501ab56480de5087e317b82798e0fc52f99d05f762218eb | 14,166 | [
-1
] |
14,167 | multi-model-talking.lisp | asmaloney_ACT-R/examples/multiple-models/multi-model-talking.lisp | ;;; This file allows models that are running together to hear each
;;; other talking by monitoring the output-speech command from the
;;; microphone device of the speech module.
;;;
;;; To run models using this code just call the test-it function.
;;; That will install a microphone device for all the models,
;;; create a new command, set that command to monitor for speech
;;; output, and run the models.
;;;
;;; There are example models in the multi-model-talking-model file,
;;; and running those models is shown in the comments below.
;;;
;;; This is the key to them hearing each other.
;;; When any model speaks into a microphone device all other models
;;; will hear that with the location being the name of the model
;;; which spoke.
;;; The audio & speech modules take care of a model hearing
;;; itself automatically so don't want to double that up.
(defun relay-speech-output (model string)
;; Let all other models hear this
(dolist (m (mp-models))
(unless (eq model m) ; for everyone but the originator
(with-model-eval m ; make the other model the current-model
;; Create the originating model's name as a simple chunk if
;; it isn't one already to avoid a warning of it being
;; created by default when the sound is generated.
(unless (chunk-p-fct model)
(define-chunks-fct (list model)))
;; Create the sound as a word with location indicating
;; the speaker.
(new-word-sound string (mp-time) model)))))
(defun test-it ()
(reset)
(add-act-r-command "relay-speech-output" 'relay-speech-output "Handle player speak actions")
(monitor-act-r-command "output-speech" "relay-speech-output")
(dolist (m (mp-models))
(with-model-eval m
(install-device '("speech" "microphone"))))
(run 10)
(remove-act-r-command-monitor "output-speech" "relay-speech-output")
(remove-act-r-command "relay-speech-output"))
#|
> (test-it)
0.000 M1 PROCEDURAL CONFLICT-RESOLUTION
0.000 M2 PROCEDURAL CONFLICT-RESOLUTION
0.000 M3 PROCEDURAL CONFLICT-RESOLUTION
0.050 M2 PROCEDURAL PRODUCTION-FIRED SPEAK
0.050 M2 PROCEDURAL CLEAR-BUFFER GOAL
0.050 M2 PROCEDURAL CLEAR-BUFFER VOCAL
0.050 M2 SPEECH SPEAK TEXT Hello
0.050 M2 GOAL SET-BUFFER-CHUNK GOAL CHUNK0
0.050 M2 PROCEDURAL CONFLICT-RESOLUTION
0.200 M2 PROCEDURAL CONFLICT-RESOLUTION
0.250 M2 AUDIO new-sound
0.250 M1 AUDIO new-sound
0.250 M3 AUDIO new-sound
0.250 M2 PROCEDURAL CONFLICT-RESOLUTION
0.250 M1 PROCEDURAL CONFLICT-RESOLUTION
0.250 M3 PROCEDURAL CONFLICT-RESOLUTION
0.500 M2 PROCEDURAL CONFLICT-RESOLUTION
0.550 M1 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT0 NIL
0.550 M3 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT0 NIL
0.550 M2 AUDIO find-sound-failure
0.550 M1 PROCEDURAL CONFLICT-RESOLUTION
0.550 M3 PROCEDURAL CONFLICT-RESOLUTION
0.550 M2 PROCEDURAL CONFLICT-RESOLUTION
0.600 M1 PROCEDURAL PRODUCTION-FIRED DETECTED-SOUND
0.600 M1 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
0.600 M1 PROCEDURAL CLEAR-BUFFER GOAL
0.600 M1 PROCEDURAL CLEAR-BUFFER AURAL
0.600 M3 PROCEDURAL PRODUCTION-FIRED DETECTED-SOUND
0.600 M3 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
0.600 M3 PROCEDURAL CLEAR-BUFFER GOAL
0.600 M3 PROCEDURAL CLEAR-BUFFER AURAL
0.600 M1 AUDIO ATTEND-SOUND AUDIO-EVENT0-0
0.600 M3 AUDIO ATTEND-SOUND AUDIO-EVENT0-0
0.600 M1 GOAL SET-BUFFER-CHUNK GOAL CHUNK0
0.600 M3 GOAL SET-BUFFER-CHUNK GOAL CHUNK0
0.600 M1 PROCEDURAL CONFLICT-RESOLUTION
0.600 M3 PROCEDURAL CONFLICT-RESOLUTION
0.725 M1 AUDIO SET-BUFFER-CHUNK AURAL WORD0
0.725 M3 AUDIO SET-BUFFER-CHUNK AURAL WORD0
0.725 M1 PROCEDURAL CONFLICT-RESOLUTION
0.725 M3 PROCEDURAL CONFLICT-RESOLUTION
0.775 M1 PROCEDURAL PRODUCTION-FIRED HEAR
I HEARD M2 SAY "Hello"
0.775 M1 PROCEDURAL CLEAR-BUFFER AURAL
0.775 M1 PROCEDURAL CLEAR-BUFFER VOCAL
0.775 M3 PROCEDURAL PRODUCTION-FIRED HEAR
I HEARD M2 SAY "Hello"
0.775 M3 PROCEDURAL CLEAR-BUFFER AURAL
0.775 M1 SPEECH SPEAK TEXT Back at you
0.775 M1 PROCEDURAL CONFLICT-RESOLUTION
0.775 M3 PROCEDURAL CONFLICT-RESOLUTION
0.925 M1 PROCEDURAL CONFLICT-RESOLUTION
0.975 M1 AUDIO new-sound
0.975 M2 AUDIO new-sound
0.975 M3 AUDIO new-sound
0.975 M1 PROCEDURAL CONFLICT-RESOLUTION
0.975 M2 PROCEDURAL CONFLICT-RESOLUTION
0.975 M3 PROCEDURAL CONFLICT-RESOLUTION
1.275 M2 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT1 NIL
1.275 M3 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT1 NIL
1.275 M1 AUDIO find-sound-failure
1.275 M1 PROCEDURAL CONFLICT-RESOLUTION
1.275 M2 PROCEDURAL CONFLICT-RESOLUTION
1.275 M3 PROCEDURAL CONFLICT-RESOLUTION
1.325 M2 PROCEDURAL PRODUCTION-FIRED DETECTED-SOUND
1.325 M2 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
1.325 M2 PROCEDURAL CLEAR-BUFFER GOAL
1.325 M2 PROCEDURAL CLEAR-BUFFER AURAL
1.325 M3 PROCEDURAL PRODUCTION-FIRED DETECTED-SOUND
1.325 M3 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
1.325 M3 PROCEDURAL CLEAR-BUFFER GOAL
1.325 M3 PROCEDURAL CLEAR-BUFFER AURAL
1.325 M2 AUDIO ATTEND-SOUND AUDIO-EVENT1-0
1.325 M3 AUDIO ATTEND-SOUND AUDIO-EVENT1-0
1.325 M2 GOAL SET-BUFFER-CHUNK GOAL CHUNK1
1.325 M3 GOAL SET-BUFFER-CHUNK GOAL CHUNK1
1.325 M2 PROCEDURAL CONFLICT-RESOLUTION
1.325 M3 PROCEDURAL CONFLICT-RESOLUTION
1.525 M1 PROCEDURAL CONFLICT-RESOLUTION
1.725 M2 AUDIO SET-BUFFER-CHUNK AURAL WORD1
1.725 M3 AUDIO SET-BUFFER-CHUNK AURAL WORD1
1.725 M2 PROCEDURAL CONFLICT-RESOLUTION
1.725 M3 PROCEDURAL CONFLICT-RESOLUTION
1.775 M2 PROCEDURAL PRODUCTION-FIRED HEAR
I HEARD M1 SAY "Back at you"
1.775 M2 PROCEDURAL CLEAR-BUFFER AURAL
1.775 M3 PROCEDURAL PRODUCTION-FIRED HEAR
I HEARD M1 SAY "Back at you"
1.775 M3 PROCEDURAL CLEAR-BUFFER AURAL
1.775 M2 PROCEDURAL CONFLICT-RESOLUTION
1.775 M3 PROCEDURAL CONFLICT-RESOLUTION
1.775 - ------ Stopped because no events left to process
|#
| 7,663 | Common Lisp | .lisp | 136 | 50.705882 | 94 | 0.59058 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 472162363adcae536338e2b73e44695d6317a5fb5409181c4764f77431ca825b | 14,167 | [
415778
] |
14,168 | style-test-model.lisp | asmaloney_ACT-R/examples/extend-manual-requests/using-a-style/style-test-model.lisp | ;;; This file defines a model which just repeatedly
;;; performs the new-action request defined in
;;; the new-style.lisp file. A trace of the run
;;; is included below.
(clear-all)
(define-model foo
(sgp :trace-detail high)
(p p1
?manual>
state free
==>
+manual>
isa new-action
arg1 1
arg2 2))
#|
CG-USER(114): (run 1)
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.000 PROCEDURAL PRODUCTION-SELECTED P1
0.000 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL MODULE-REQUEST MANUAL
0.050 PROCEDURAL CLEAR-BUFFER MANUAL
0.050 MOTOR NEW-ACTION ARG1 1 ARG2 2
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.200 MOTOR PREPARATION-COMPLETE 0.05
0.200 PROCEDURAL CONFLICT-RESOLUTION
0.250 MOTOR INITIATION-COMPLETE 0.05
0.250 PROCEDURAL CONFLICT-RESOLUTION
0.400 NONE DEMO-PRINT-STYLE-INFO 1 2 0.15 0.3
Features are 1 and 2
0.15 seconds spent in preparation
finishing after 0.3 seconds
0.400 PROCEDURAL CONFLICT-RESOLUTION
0.500 MOTOR FINISH-MOVEMENT 0.05
0.500 PROCEDURAL CONFLICT-RESOLUTION
0.500 PROCEDURAL PRODUCTION-SELECTED P1
0.500 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.550 PROCEDURAL PRODUCTION-FIRED P1
0.550 PROCEDURAL MODULE-REQUEST MANUAL
0.550 PROCEDURAL CLEAR-BUFFER MANUAL
0.550 MOTOR NEW-ACTION ARG1 1 ARG2 2
0.550 MOTOR PREPARATION-COMPLETE 0.55
0.550 PROCEDURAL CONFLICT-RESOLUTION
0.600 MOTOR INITIATION-COMPLETE 0.55
0.600 PROCEDURAL CONFLICT-RESOLUTION
0.750 NONE DEMO-PRINT-STYLE-INFO 1 2 0.0 0.3
Features are 1 and 2
0.0 seconds spent in preparation
finishing after 0.3 seconds
0.750 PROCEDURAL CONFLICT-RESOLUTION
0.850 MOTOR FINISH-MOVEMENT 0.55
0.850 PROCEDURAL CONFLICT-RESOLUTION
0.850 PROCEDURAL PRODUCTION-SELECTED P1
0.850 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.900 PROCEDURAL PRODUCTION-FIRED P1
0.900 PROCEDURAL MODULE-REQUEST MANUAL
0.900 PROCEDURAL CLEAR-BUFFER MANUAL
0.900 MOTOR NEW-ACTION ARG1 1 ARG2 2
0.900 MOTOR PREPARATION-COMPLETE 0.9
0.900 PROCEDURAL CONFLICT-RESOLUTION
0.950 MOTOR INITIATION-COMPLETE 0.9
0.950 PROCEDURAL CONFLICT-RESOLUTION
1.000 ------ Stopped because time limit reached
|#
| 3,034 | Common Lisp | .lisp | 65 | 40.661538 | 71 | 0.559351 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1790c8c9b9d4f4f8b91bf3e8387b9f5965666b41ee4b6ba975e1f7a68e43c76c | 14,168 | [
485924
] |
14,169 | new-style.lisp | asmaloney_ACT-R/examples/extend-manual-requests/using-a-style/new-style.lisp | ;;; This example will create a new manual request called new-action
;;; which has two features named arg1 and arg2. All it is going
;;; to do is print out the arguments provided and timing information
;;; when a request is made .2 seconds after the movement is prepared
;;; and it will spend a total of .3 seconds in the execution stage.
;;; This file creates the new action for the motor module using
;;; extend-manual-requests based on the style mechanism built
;;; into the motor module. It's not necessary for one to use
;;; a style with extend-manual-requests, but doing so eliminates
;;; the need to deal directly with the internal state management
;;; and scheduling of the typical motor module action stages
;;; (preparation, initiation, and execution).
;;; The adding of a new motor module action only needs to be
;;; performed once (not with each model), and a file like this
;;; could be placed into the user-loads directory to have it
;;; loaded automatically with the system.
;;; A style requires a name and a set of features. With the
;;; normal style handling mechanisms each request for an action
;;; that is implemented as a style will require all of the features
;;; to be set to perform the action.
;;; Internally, a style is a CLOS class and there are several
;;; methods which can be defined for a style's class which
;;; control how it operates. Many of the default style
;;; class (movement-style) methods should not be overridden,
;;; but a few are necessary to provide the details for the
;;; new style. The example below will show those that are
;;; necessary for configuring the new style and also some of
;;; the accessors for the movement-style slots which are set
;;; by the default methods which may be useful.
;;; To create a style one calls defstyle. It has two required
;;; parameters: a name for the new style and a list of any
;;; other styles which this style will inherit from. It can take
;;; any number of additional parameters to name the features
;;; of the style. This results in creating a new CLOS class
;;; which is a subclass of the movement-style class and any
;;; other classes provided. The features provided are slots
;;; in that new class and have accessor functions which are the
;;; names of the features.
;;; This creates the new-action style with features arg1 and arg2.
(defstyle new-action () arg1 arg2)
;;; Now, we need to define some methods on the motor-module and
;;; new-action class to control how our new action will perform.
;;; For this example we will not be accessing the motor module
;;; itself because it's implementation is not part of the ACT-R
;;; API. Doing so could be useful to access the parameters in
;;; the motor module, but since that's not part of the API one
;;; will have to look at the implementation of the motor module
;;; to find the details and there are no guarantees that the
;;; motor module's internal details will not change in the future.
;;; If the style will be moving the hand, finger(s), or depends
;;; upon the current position of the hand to generate the features,
;;; then the prepare-features method should be written for the style.
;;; That method should compute the necessary features based on
;;; the expected hand position (not the current position since
;;; it may be in the process of moving), and set the updated-pos
;;; slot of the movement-style to the position where the hand
;;; will be when it finishes execution if it will change.
;;; This example does not require that, but as an example here
;;; is the method for the peck style movement which moves a finger.
;;; The move-a-finger method of the motor module returns the new
;;; position after a finger is moved, and that is being computed
;;; based on the expected position since the :current nil flag is
;;; provided. If that was not provided, or provided as non-nil,
;;; then the current hand position would have been used.
#|
(defmethod prepare-features ((mtr-mod motor-module) (self peck))
(setf (updated-pos self)
(move-a-finger mtr-mod (hand self) (finger self) (r self) (theta self) :current nil)))
|#
;;; The preparation cost for a style action will require the
;;; time to prepare n+1 features where n is the number of features
;;; specified for the style, and the +1 is for the style itself.
;;; When the style action is repeated the feat-differences
;;; method is called to determine how many features can be
;;; shared between the two. It must return a number indicating
;;; how many features to prepare.
;;; After calling feat-differences the fprep-time slot of the
;;; style will be set to the cost of the preparation in seconds.
(defmethod feat-differences ((f1 new-action) (f2 new-action))
(let ((count 0))
(unless (equal (arg1 f1) (arg1 f2))
(incf count))
(unless (equal (arg2 f1) (arg2 f2))
(incf count))
count))
;;; The compute-exec-time method will be called to determine
;;; how long after preparation of the style's action it will take
;;; until the action should be 'executed'. It is called every
;;; time there is a request for the action and thus can change
;;; dynamically based on the features. It must return a number
;;; which is the execution time delay in seconds.
;;; After calling compute-exec-time the style will set the
;;; exec-time slot of the style to the result.
(defmethod compute-exec-time ((m motor-module) (self new-action))
;; We're just setting a fixed cost of .2 seconds
.2)
;;; The compute-finish-time method is called to determine how long
;;; after the preparation of the style's action it will take until
;;; the execution stage should complete and become free again.
;;; It must return a number which is the total execution stage
;;; time in seconds. This is called after the exec-time is set.
;;; After calling compute-finish-time the style will set the
;;; finish-time slot of the style to the result.
(defmethod compute-finish-time ((m motor-module) (self new-action))
;; .1 second longer than the execution time
(+ .1 (exec-time self)))
;;; Once preparation completes for the action the queue-output-events
;;; method is called which should schedule the actions to perform.
;;; The expected time for the actions is the already computed exec-time,
;;; but that is not required.
(defmethod queue-output-events ((m motor-module) (self new-action))
;; Here we are just scheduling an event to print out the details
;; of the request at the execution time.
(schedule-event-relative (exec-time self)
'demo-print-style-info
:params (list (arg1 self) (arg2 self) (fprep-time self) (finish-time self)))
;; If the action were moving the hand then it should schedule that
;; here using the set-hand-position action with the value that was
;; stored in updated-pos by the prepare-features method. Again, this
;; example does not need to do so, but this example is from the peck
;; style movement:
#|
(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)))
|#
)
;;; The function that will be called:
(defun demo-print-style-info (w x y z)
(format t "Features are ~S and ~S~%~s seconds spent in preparation~%finishing after ~f seconds~%" w x y z))
;;; To add the new style use extend-manual-requests and provide the
;;; style name and features as the description of the action and
;;; use the built-in function handle-style-request to process the
;;; requests.
(extend-manual-requests (new-action arg1 arg2) handle-style-request)
| 7,893 | Common Lisp | .lisp | 135 | 54.42963 | 110 | 0.72351 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 46257d738d007d12b56182c40d5b063d142f795f21d502a74363681859fb0a40 | 14,169 | [
101750
] |
14,170 | adjust-visicon-features.lisp | asmaloney_ACT-R/examples/vision-module/adjust-visicon-features.lisp | ;;; This example demonstrates how visual features created using
;;; the add-visicon-features command can be modified and removed from
;;; the visicon, and that those changes automatically trigger an update
;;; by the vision module.
(defun run-example ()
(reset)
;; Add-visicon-features returns a list of names which can be
;; used to update the features which were added to the visicon.
;; The modify-visicon-features command can be used to adjust
;; the location and object representation of an item that was
;; added to the visicon. The delete-visicon-features and
;; delete-all-visicon-features commands can be used to remove
;; items which were added to the visicon.
;; For this example these chunk-types are defined in the model
;; which subclass the standard visual-location and visual-object
;; chunk-types as were used for the new-visicon-features example.
;; (chunk-type (polygon-feature (:include visual-location)) regular)
;; (chunk-type (polygon (:include visual-object)) sides)
(let ((features (add-visicon-features
'(isa (polygon-feature polygon) screen-x 0 screen-y 50
value (polygon "poly1") height 20 width 40
color blue regular (false nil)
sides (nil 7))
'(isa (polygon-feature polygon) screen-x 50 screen-y 70
value (polygon "square") height 30 width 30
color red regular (true nil)
sides (nil 4)))))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; run the model to show the current chunks
(run 10)
;; Modify the first of those features to change the color to green,
;; adjust the x position, and change the number of sides to 8.
;; The parameters for modify-visicon-features are very similar to
;; add except that the list of features must start with the name
;; of the feature to update which was returned from add-visicon-features.
;; One thing to note is that because nil is used in the list of values to
;; indicate that a slot should not be applied to the location or object
;; means that you can't use nil to 'remove' a slot from a feature through
;; a modification.
(modify-visicon-features (list (first features) 'color 'green 'screen-x 5 'sides '(nil 8)))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; run the model to show the updated
(run 10)
;; Modify the second of those features to change the regular value to false and the
;; height to 25
(modify-visicon-features (list (second features) 'height 25 'regular '(false nil)))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; run the model to show the updated
(run 10)
;; delete the second feature. delete-visicon-features takes any number
;; of parameters each of which should be the name of a feature that was
;; returned by add-visicon-feature and those features are removed from
;; the visicon.
(delete-visicon-features (second features))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; run the model to show the updated
(run 10)
;; delete all of the visicon features. delete-all-visicon-features
;; removes all of the features from the visicon.
(delete-all-visicon-features)
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; run the model to show the updated
(run 10)))
;;; The model is very simple in that it just repeatedly finds
;;; a location and then attends to the item there printing
;;; out the chunks in the visual-location and visual buffers
;;; after the corresponding requet completes.
;;; The ordering of the modifications are such that it will
;;; not automatically updated the attended object chunks
;;; since the currently attended item is unchanged in each
;;; case.
(load-act-r-model "ACT-R:examples;vision-module;adjust-visicon-features-model.lisp")
| 4,679 | Common Lisp | .lisp | 87 | 44.367816 | 96 | 0.678889 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 644b5158dd6d16188d87b7c98bd9a8e4ee3f9fbf236832fca8a39ffd5d1228d5 | 14,170 | [
188365
] |
14,171 | dynamic-object-creation.lisp | asmaloney_ACT-R/examples/vision-module/dynamic-object-creation.lisp | ;;; This example shows how one can specify a command to dynamically
;;; create the visual object chunks for features that are added to
;;; the visicon instead of specifying them when they are added.
;;;
;;; There is a device called object-creator which can be installed
;;; for the vision interface with the details of the device being
;;; the command to use. When the model shifts attention to an
;;; item in the visicon if an object-creator device is installed
;;; then the command associated with that device will be passed
;;; the visicon entry id for the item being attended (the value
;;; which was returned when the item was added to the visicon).
;;; If the command returns a chunk it will be the one placed into
;;; the visual buffer as a result of the attention shift. If
;;; it returns any other value then the default mechanism will be
;;; used to create the visual-object chunk, and if that other value
;;; is not nil then a warning will be printed to indicate that an
;;; invalid value was returned.
(defvar *ids* nil)
(defun custom-object-chunk (id)
(when (equalp id (first *ids*))
(first (define-chunks-fct (list (list 'isa 'custom-object 'color 'red 'time (mp-time-ms)))))))
(defun run-example ()
(reset)
;; Here we install our custom function using an object-creator device
(install-device '("vision" "object-creator" custom-object-chunk))
;; Now we add two features to the display, the first of which will
;; have the object created by the custom function and the other by
;; the default mechanism.
(setf *ids* (add-visicon-features '(screen-x 10 screen-y 20)
'(screen-x 100 screen-y 20)))
;; run to give vision module a chance to
;; process those features and then print the
;; visicon.
(run-n-events 3)
(print-visicon)
;; run to have model complete task
(run 1))
;; The model just attends to items and prints out the location and
;; object chunks which it gets.
(load-act-r-model "ACT-R:examples;vision-module;dynamic-object-creation-model.lisp")
| 2,116 | Common Lisp | .lisp | 40 | 48.25 | 99 | 0.714985 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5b0f772ffe4953409f6d7c9e6acc7619c50a52ba82173c47c7394a3b64c7ef62 | 14,171 | [
187656
] |
14,172 | rotational-vision-test-2.lisp | asmaloney_ACT-R/examples/vision-module/rotational-vision-test-2.lisp | ;;; This is a simple example model to show the new options of
;;; clockwise and counterclockwise which can be used with the
;;; :nearest request parameter in a visual-location request.
;;;
;;; The difference between this model and rotational-vision-test-1
;;; is that this model indicates the object around which it will
;;; rotate explicitly using the :center request parameter instead
;;; of using the point set with set-visual-center-point.
;;;
;;; The display is a clock face in an experiment window. The
;;; model finds the marker for the center of the clock (the red
;;; button). Then it finds the top most number (12), attends to
;;; it, and then finds and attends to items clockwise until it
;;; returns to a number it has seen before. Then, it switches
;;; to finding and attending to items counterclockwise until it
;;; again returns to a previously seen number. It then switches
;;; to the reference item outside of the clock (the green button),
;;; and repeats the process.
;;;
;;;
;;;
(clear-all)
(defun run-test ()
(reset)
;; open a visible experiment window and install it as a device.
;; the window has the default width and height of 300 pixels each
;; and default location of 300,300.
;; Installing an AGI window device automatically sets the
;; default center point reference to the center of that window.
(install-device (open-exp-window "Test"))
;; draw the clock face off to one side with a red button in
;; the center and a green button off to the right.
(add-button-to-exp-window nil :x 100 :y 100 :height 25 :width 25 :color 'red)
(add-text-to-exp-window nil "12" :x 100 :y 30 :height 25)
(add-text-to-exp-window nil "1" :x 135 :y 39 :height 25)
(add-text-to-exp-window nil "2" :x 161 :y 65 :height 25)
(add-text-to-exp-window nil "3" :x 170 :y 100 :height 25)
(add-text-to-exp-window nil "4" :x 161 :y 135 :height 25)
(add-text-to-exp-window nil "5" :x 135 :y 161 :height 25)
(add-text-to-exp-window nil "6" :x 100 :y 170 :height 25)
(add-text-to-exp-window nil "7" :x 65 :y 161 :height 25)
(add-text-to-exp-window nil "8" :x 39 :y 135 :height 25)
(add-text-to-exp-window nil "9" :x 30 :y 100 :height 25)
(add-text-to-exp-window nil "10" :x 39 :y 65 :height 25)
(add-text-to-exp-window nil "11" :x 65 :y 39 :height 25)
(add-button-to-exp-window nil :x 250 :y 100 :height 25 :width 25 :color 'green)
(run 15 t))
(define-model test-rotation
(sgp :show-focus t)
(chunk-type goal start dir center-loc current finish color)
(p start
?goal>
buffer empty
==>
-visual-location>
+goal>
isa goal
dir clockwise
color red)
(p find-ref
=goal>
color =c
start nil
center-loc nil
==>
=goal>
color nil
+visual-location>
color =c)
(p attend
=goal>
=visual-location>
?visual>
state free
buffer empty
==>
+visual>
isa move-attention
screen-pos =visual-location)
(p encode-center
=goal>
isa goal
start nil
center-loc nil
dir =dir
=visual>
- color black
screen-pos =loc
==>
=goal>
; we could use either =loc or =visual here because
; either a location or object can be used as the center
center-loc =loc
+visual-location>
kind text
screen-y lowest)
(p encode-and-record
=goal>
isa goal
start nil
center-loc =loc
dir =dir
=visual>
isa text
value =val
==>
=goal>
start =val
current =val
!output! (Attending to =val))
(p encode
=goal>
isa goal
- start =val
- start nil
dir =dir
=visual>
isa text
value =val
==>
=goal>
current =val
!output! (Attending to =val))
(p encode-and-switch-dir
=goal>
isa goal
start =val
dir clockwise
=visual>
isa text
value =val
==>
=goal>
dir counterclockwise
current =val
!output! (Attending to =val))
(p encode-and-switch-ref
=goal>
isa goal
dir counterclockwise
start =val
finish nil
=visual>
isa text
value =val
==>
=goal>
dir clockwise
center-loc nil
start nil
finish t
+visual-location>
color green
!output! (Attending to =val))
(p find-next
=goal>
isa goal
dir =dir
current =val
center-loc =c-loc
?visual-location>
buffer empty
?visual>
buffer empty
state free
==>
+visual-location>
isa visual-location
- value =val
kind text
:nearest =dir
:center =c-loc)
)
| 4,882 | Common Lisp | .lisp | 173 | 22.271676 | 81 | 0.616893 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4e11d315968367427a3ecfc4d061baebba99546f5b04ef27dd3ec7339a194af9 | 14,172 | [
41804
] |
14,173 | customize-visicon-features.lisp | asmaloney_ACT-R/examples/vision-module/customize-visicon-features.lisp | ;;; This example demonstrates the customization options available
;;; when adding visual features. There are currently two customizations
;;; available: the names of the location chunk's position slots can
;;; be changed from the defaults of screen-x, screen-y, and distance
;;; and changing the effective width of the item as needed for computing
;;; the movement times based on Fitts' Law from the default of assuming
;;; it is a rectangle based on the given height and width. Those items
;;; can be changed independently for each feature.
(defun custom-width (feature angle x y)
(model-output "Computing a custom width for feature: ~s being approached at angle ~f from position ~d,~d."
feature angle x y)
(let ((h (chunk-slot-value-fct feature 'height)))
(when (numberp h)
(* 2 h))))
(defun run-example ()
(reset)
;; We will create two items in the display and have the model
;; find them and move the mouse to them to see the difference
;; in timing based on the width function setting.
;;
;; One feature will use the normal visual-location and object
;; chunk-types and the other will use a custom visual-location
;; type defined like this which replaces screen-x, screen-y,
;; and distance with slots named x, y, and z instead.
;;
;; (chunk-type custom-location x y z height width size)
;;
;; The feature with using the standard visual-location slots
;; will include a custom width function to make it act like
;; a circle with twice its given height.
;; Create the command to provide the custom width
(add-act-r-command "custom-width" 'custom-width "Return twice the height of a visual feature.")
(add-visicon-features
'(screen-x 50 screen-y 500 height 20 width 20 :width-fn "custom-width")
'(isa custom-location x 150 y 500 height 20 width 20 :x-slot x :y-slot y :z-slot z))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; run the model to move the cursor to 100,0 as a starting point.
;; and from there move to the left location, back to the start, and then
;; the right location.
(run 10)
(remove-act-r-command "custom-width"))
;;; The model is very simple and it just finds the two locations,
;;; prints them out, and moves the mouse there from a fixed starting
;;; point to see the difference the width function makes.
(load-act-r-model "ACT-R:examples;vision-module;customize-visicon-features-model.lisp")
| 2,595 | Common Lisp | .lisp | 48 | 48.979167 | 109 | 0.718185 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d600a40c64a1a807487bf272d9d912d6d87c6a904adc253f30caad1efcbd6e86 | 14,173 | [
66575
] |
14,174 | tracking.lisp | asmaloney_ACT-R/examples/vision-module/tracking.lisp | #|
There are two example functions here: one which uses the AGI to
display a moving X and one which uses add- & modify- visicon-features
to move an arbitrary feature.
The same model found in tracking-model.lisp performs both tasks.
To run them call either agi-tracking or arbitrary-tracking
respectively to do the task.
|#
(load-act-r-model "ACT-R:examples;vision-module;tracking-model.lisp")
(defvar *y*)
(defvar *x*)
(defun update-agi-feature (f)
(modify-text-for-exp-window f :y (incf *y* 10)))
(defun update-arbitrary-feature (f)
(modify-visicon-features (list f 'screen-x (incf *x* 10))))
(defun agi-tracking ()
(reset)
;; open a window and add the text
(let* ((window (open-exp-window "Moving X" :visible t))
(text (add-text-to-exp-window window "x" :x 10 :y 10)))
(setf *y* 10)
(install-device window)
;; schedule an event to move it
(schedule-periodic-event .5 'update-agi-feature :params (list text)
:maintenance t
:details "moving object"
:initial-delay 1.0)
;; run the model in real time since it's a visible window
(run 3 t)))
(defun arbitrary-tracking ()
(reset)
;; First create the visual-location chunk
(let ((feature (first (add-visicon-features '(screen-x 15 screen-y 20 value "x")))))
(setf *x* 15)
;; schedule an event to move the item
(schedule-periodic-event .5 'update-arbitrary-feature :params (list feature)
:maintenance t
:details "moving object"
:initial-delay 1.0)
;; run the model
(run 3)))
| 1,752 | Common Lisp | .lisp | 41 | 33.609756 | 86 | 0.632779 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 7279fff9fed4016ba0931cf200685a56d6638b4948ad0e1b5b14f8030a3b779c | 14,174 | [
-1
] |
14,175 | set-visloc-default-request.lisp | asmaloney_ACT-R/examples/vision-module/set-visloc-default-request.lisp | ;;; This model demonstrates the visual-location request to change the
;;; specification for the visual-location buffer stuffing in the same
;;; way that the set-visloc-default command can be used by the modeler.
;;;
;;; The request to do so is just like a typical visual-location request
;;; to find a feature, except that it includes a slot named set-visloc-default
;;; with a value of t. The chunk-type set-visloc-default is a subtype of
;;; visual-location and includes that slot as a default value. Therefore
;;; a request which includes 'isa set-visloc-default' can be used instead
;;; of specifying the slot directly, and subtypes of that chunk-type can
;;; be created if desired.
;;;
;;; That request triggers an immediate reprocessing of the visual scene by
;;; the vision module to determine if there is a chunk to be stuffed into
;;; the visual-location buffer given the new specification.
;;;
;;; The visual-scene used here is the same one found in the new-visicon-features
;;; example.
(clear-all)
(defun test-visloc-defaults ()
(reset)
(let ((feats (add-visicon-features '(screen-x 0 screen-y 5 regular true)
'(isa (visual-location oval) screen-x 12 screen-y 20 value (oval "the oval") height 10 width 40 color blue)
'(isa (polygon-feature polygon) screen-x 50 screen-y 50 value (polygon "poly 1") height 20 width 40 color blue regular false sides (nil 7))
'(isa (polygon-feature square) screen-x 10 screen-y 50 value (square "the square") height 30 width 30 color red regular true sides (nil 4))
'(isa (polygon-feature polygon) screen-x 5 screen-y 70 value (polygon "poly 2") height 50 width 45 color green regular false sides (nil 5)))))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; Then just run the model until it's done (takes less than 1 second).
(run 1)))
;;; The model is very simple in that it just repeatedly changes the
;;; defaults for buffer stuffing and then prints out the chunk that
;;; was stuffed into the buffer as a result.
;;;
(define-model set-visloc-default-request-test
(sgp :v t :trace-detail medium)
(chunk-type (polygon-feature (:include visual-location)) regular (poly-feat t))
(chunk-type (polygon (:include visual-object)) sides)
(chunk-type (square (:include polygon)) (square t))
(chunk-type goal step (state task))
(chunk-type wait step (state wait))
;; Define a subtype of the set-visloc-default chunk-type that
;; also inherits from the polygon-feature.
(chunk-type (polygon-visloc-spec (:include polygon-feature)
(:include set-visloc-default)))
;; Define the chunks used in the features and the model
(define-chunks square polygon true false wait task)
(p start
?goal>
buffer empty
==>
+goal>
isa wait
step 0
!output! (The default spec is leftmost :attended new))
(p print-and-advance
"Just print out the chunk in the
visual-location buffer and advance the step"
=goal>
isa wait
step =step
=visual-location>
==>
!bind! =next (1+ =step)
!output! (Here is the chunk in the visual-location buffer)
!eval! (pprint-chunks-fct (list =visual-location))
+goal>
isa goal
step =next)
(p find-oval
=goal>
isa goal
step 1
?visual-location>
buffer empty
==>
+goal>
isa wait
step 1
+visual-location>
isa set-visloc-default
kind oval
!output! (The specification is now kind oval))
(p find-regular
=goal>
isa goal
step 2
?visual-location>
buffer empty
==>
+goal>
isa wait
step 2
;; This shows the use of the subtype to specify
;; new slots and the inclusion of default slots.
+visual-location>
isa polygon-visloc-spec
regular true
!output! (The specification is now for a regular polygon feature))
(p find-on-diagonal
=goal>
isa goal
step 3
?visual-location>
buffer empty
==>
+goal>
isa wait
step 3
;; This shows that the variables allowed in the
;; normal visual-location requests can also be used
;; in specifying the defaults.
+visual-location>
isa set-visloc-default
screen-x &x
screen-y &x
!output! (The specification is now that the x and y coords are equal))
(p restore-default
=goal>
isa goal
step 4
?visual-location>
buffer empty
==>
+goal>
isa wait
step 4
+visual-location>
isa set-visloc-default
screen-x lowest
:attended new
!output! (The specification is now back to default of screen-x lowest :attended new))
)
| 5,077 | Common Lisp | .lisp | 135 | 30.414815 | 179 | 0.653615 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0532a03ec57a0228fed053b9857e159296c51194312d743d6d1586f8f3cafa16 | 14,175 | [
281740
] |
14,176 | new-visicon-features-model.lisp | asmaloney_ACT-R/examples/vision-module/new-visicon-features-model.lisp |
(clear-all)
;;; The model is very simple in that it just repeatedly finds
;;; a location and then attends to the item there printing
;;; out the chunks in the visual-location and visual buffers
;;; after the corresponding requet completes.
;;;
;;; The visual-location requests are specified such that
;;; there will only be one visual-location which matches
;;; the request.
;;;
;;; The productions which make the visual-location requests
;;; describe the new features being used to perform the
;;; request.
(define-model new-visual-features
(sgp :v t :trace-detail low)
(chunk-type (polygon-feature (:include visual-location)) regular)
(chunk-type (polygon (:include visual-object)) sides)
(chunk-type (square (:include polygon)) (sides 4) (square t))
(chunk-type goal step)
;; Do this to avoid the warnings when the chunks are created
(define-chunks true false square polygon)
;; Define this chunk for use in a nearest request
(define-chunks (loc-100x100 isa visual-location screen-x 100 screen-y 100))
(p find-oval
?goal>
buffer empty
==>
+goal>
step 0
;; Start by finding the oval by specifying the
;; kind value which was filled in automatically.
+visual-location>
kind oval)
(p find-regular
=goal>
step 1
?visual-location>
buffer empty
?visual>
buffer empty
state free
==>
;; This request shows using one of the new
;; feature slots.
+visual-location>
screen-x lowest
regular true)
(p find-on-diagonal
=goal>
step 2
?visual-location>
buffer empty
?visual>
buffer empty
state free
==>
;;; This request shows the use of a request variable.
;;; The visual-location requets consider any value
;;; which starts with an & to be a variable in the
;;; same way that a production uses = in the LHS matching.
;;; Thus, this tests that the screen-x and screen-y values
;;; are the same.
;;;
;;; It's important to note that this is only the case
;;; for +visual-location requests - not a general feature
;;; of RHS requests. Other modules could use other variable
;;; indicators if they wanted (or none at all).
+visual-location>
screen-x &x
screen-y &x)
(p find-fewer-sides-than-current
=goal>
isa goal
step 3
?visual-location>
buffer empty
?visual>
buffer empty
state free
==>
;;; This request shows the special marker current
;;; which can be used in any slot.
+visual-location>
< sides current
regular false)
(p find-fewest-sides
=goal>
isa goal
step 4
?visual-location>
buffer empty
?visual>
buffer empty
state free
==>
;; similarly lowest and highest can also
;; be used with any slot having numeric
;; values (features which don't have the slot
;; or have a non-numeric value will be ignored).
+visual-location>
sides lowest)
(p shift-attention
=goal>
=visual-location>
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
!output! (Here is the chunk in the visual-location buffer)
!eval! (pprint-chunks-fct (list =visual-location)))
(p attend-item
=goal>
isa goal
step =step
=visual>
==>
!output! (Here is the chunk in the visual buffer)
!eval! (pprint-chunks-fct (list =visual))
!bind! =next-step (1+ =step)
=goal>
step =next-step)
)
| 3,894 | Common Lisp | .lisp | 124 | 23.717742 | 78 | 0.624585 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ea6b715b580464fa0e3d6bf599dbee5a3c513f44aa6bd92c6a4d6bc559168835 | 14,176 | [
-1
] |
14,177 | customize-visicon-features-model.lisp | asmaloney_ACT-R/examples/vision-module/customize-visicon-features-model.lisp |
(clear-all)
;;; The model is very simple in that it just repeatedly finds
;;; a location and then attends to the item there printing
;;; out the chunks in the visual-location and visual buffers
;;; after the corresponding requet completes.
;;;
;;; The visual-location requests are specified such that
;;; there will only be one visual-location which matches
;;; the request.
;;;
;;; The productions which make the visual-location requests
;;; describe the new features being used to perform the
;;; request.
(define-model custom-visual-features
(sgp :v t :trace-detail high :needs-mouse t)
(install-device '("motor" "cursor" "mouse"))
(start-hand-at-mouse)
(chunk-type custom-location x y z height width size)
(chunk-type goal step)
;; starting location
(define-chunks (start-pos screen-x 100 screen-y 0))
(p start
?goal>
buffer empty
?manual>
state free
==>
+goal>
+visual-location>
< screen-x 100
+manual>
isa move-cursor
loc start-pos)
(p move-to-first-loc
=goal>
step nil
=visual-location>
?manual>
state free
==>
!output! (first location chunk)
!eval! (buffer-chunk visual-location)
=goal>
step 1
+manual>
isa move-cursor
loc =visual-location)
(p return-to-start
=goal>
step 1
?manual>
state free
==>
+visual-location>
> x 100
+manual>
isa move-cursor
loc start-pos
=goal>
step 2)
(p move-to-second-loc
=goal>
step 2
=visual-location>
?manual>
state free
==>
!output! (second location chunk)
!eval! (buffer-chunk visual-location)
=goal>
step 3
+manual>
isa move-cursor
loc =visual-location)) | 1,954 | Common Lisp | .lisp | 74 | 19.22973 | 62 | 0.604086 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b52671669cbf9a933924c39529e08383d67895956f8ad44495cb61066c9cdb36 | 14,177 | [
250939
] |
14,178 | dynamic-object-creation-model.lisp | asmaloney_ACT-R/examples/vision-module/dynamic-object-creation-model.lisp |
(clear-all)
;;; This find visual items and attends to them from left to right
;;; printing out the location and object chunks.
(define-model dynamic-visual-objects
(sgp :v t)
;; chunk-types for the special object chunk
(chunk-type (custom-object (:include visual-object)) time)
(p attend
=visual-location>
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
!output! (location chunk)
!eval! (buffer-chunk visual-location))
(p harvest-and-find-next
=visual>
==>
+visual-location>
>= screen-x current
:attended nil
!output! (object chunk)
!eval! (buffer-chunk visual)))
| 764 | Common Lisp | .lisp | 25 | 22.84 | 66 | 0.633094 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6049fe190aa6f5772be32135f1ef712446a30a2d5949568e91fb10b2dab0e835 | 14,178 | [
-1
] |
14,179 | multi-window.lisp | asmaloney_ACT-R/examples/vision-module/multi-window.lisp | ;;; This example shows that multiple devices can be installed to
;;; the vision interface at the same time. It also shows that the
;;; visicon features created by each exp-window installed are
;;; available simultaneously as well as those from the mouse
;;; cursor. Finally, it shows that the coordinates for all of
;;; the features of the exp-window device and the mouse cursor
;;; are represented in a global coordinate system and not in
;;; the local coordinates of the windows themselves.
(defun run-example ()
(reset)
;; The first window is located at x=0 and y=0 which
;; is fine for virtual windows, but if it were a real
;; window that window would be behind the menu bar
;; at the top of the display under OS X which makes
;; it difficult to interact with. The second window
;; is located at x=200, y=200. The default mouse
;; position is x=0, y=0.
(let ((w1 (open-exp-window "W1" :visible nil :height 100 :width 100 :x 0 :y 0))
(w2 (open-exp-window "W2" :visible nil :height 100 :width 100 :x 200 :y 200)))
;; add text to the same local position in each window.
(add-text-to-exp-window w1 "a" :x 10 :y 10 :color 'red)
(add-text-to-exp-window w2 "a" :x 10 :y 10 :color 'blue)
;; Install both windows and the mouse cursor
(install-device w1)
(install-device w2)
(install-device '("vision" "cursor" "mouse"))
;; Just run the model to have vision module process
;; things and print the visicon.
;; The model doesn't do anything.
(run 1)
(print-visicon)))
;; Load a model which doesn't do anything.
(load "ACT-R:examples;vision-module;multi-window-model.lisp") | 1,728 | Common Lisp | .lisp | 33 | 46.575758 | 87 | 0.688335 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 45f1768163d0a51baf1284a381170a499176b3969b1000f38183c319caefc436 | 14,179 | [
262318
] |
14,180 | new-visicon-features-position-slots.lisp | asmaloney_ACT-R/examples/vision-module/new-visicon-features-position-slots.lisp | ;;; This example demonstrates how one can change the slots used for
;;; the position information in the visual features.
(defun run-example ()
(reset)
;; For this example these chunk-types are defined in the model:
;; (chunk-type real-space x y z size)
;; (chunk-type other-space pos-1 pos-2 pos-3 size value)
;; We will add three features: one using the initial position slots
;; of screen-x, screen-y, and distance, one using the x, y, and z
;; slots, and one using pos-1, pos-2, and pos-3 slots.
(add-visicon-features '(screen-x 0 screen-y 5 distance 1080))
(set-default-vis-loc-slots x y z)
(add-visicon-features '(x 10 y 15 z 1080))
(set-default-vis-loc-slots-fct 'pos-1 'pos-2 'pos-3)
(add-visicon-features '(pos-1 50 pos-2 15 pos-3 1080 value t))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; Then just run the model
(run 10))
;;; The model is very simple in that it just repeatedly finds
;;; unattended locations and attends to them printing
;;; out the chunks in the visual-location and visual buffers
;;; after the corresponding requet completes.
;;;
(load-act-r-model "ACT-R:examples;vision-module;new-visicon-features-position-slots-model.lisp")
| 1,369 | Common Lisp | .lisp | 27 | 44.851852 | 96 | 0.725962 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b6a21cc2e356c827032fda75d5d2c7766ce8ed2ae24256f85de2d4d5ba272ec3 | 14,180 | [
152062
] |
14,181 | new-visicon-features.lisp | asmaloney_ACT-R/examples/vision-module/new-visicon-features.lisp | ;;; This example demonstrates how one can generate new visual features
;;; for a model using the add-visicon-features command which allows one
;;; to specify visual features which have a 1<->1 mapping between locations
;;; and objects.
(defun run-example ()
(reset)
;; Add-visicon-features allows the modeler to specify arbirary
;; visual features for the visicon of a model. Any number of
;; features can be provided at once, and each feature represents
;; an object and its location. The description of those items
;; is provided in much the same way that one specifies a chunk
;; i.e. as slot-value pairs, and internally the vision module
;; uses three chunks to represent that item (the location, the
;; object, and a feature which contains the information that
;; can be 'found' through a visual-location request).
;;
;; All features must have an x and y position which default
;; to being in the screen-x and screen-y slots (see the
;; new-visicon-features-position-slots example for how to change
;; that). The distance (z position) can be specified, but if
;; not the default distance will be included. Similarly, a size
;; (which is measured in degrees of visual angle squared)
;; can be provided, but if not it will be computed from the
;; height and width if specified or set to a default size if
;; those are not provided.
;; When specifying the slot-value pairs to describe a feature
;; the slot must be a valid slot for chunks (or the name isa
;; to declare a chunk-type). The value can be provided as
;; either an explict value or a list of two values. If
;; an explicit value is provided then that value represents
;; the value of that slot for both the location and object
;; except when it is one of the x, y, or z coordinates which
;; are only provided in the location. If a list of values
;; is provided then the first one represents the value of
;; that slot for the visual-location chunk and the second
;; one represents the value of the slot for the object.
;; Either of the items can be specified as nil to indicate
;; that the corresponding chunk should not have that slot.
;; The value for the feature which can be found through the
;; visual-location request is the value for the object if
;; one is provided otherwise it will be the value for the
;; location.
;; The isa specification can also take a list of two values which
;; indicate the chunk-types to specify when creating the chunks
;; for the location and object, which can include default slot
;; values. In addition to that, if a chunk-type is declared for
;; the object and no slot named kind is specified for the feature
;; then the location chunk will include a kind slot with a value
;; that matches the chunk-type declared for the object.
;; For this example these chunk-types are defined in the model
;; which subclass the standard visual-location and visual-object
;; chunk-types.
;; (chunk-type (polygon-feature (:include visual-location)) regular)
;; (chunk-type (polygon (:include visual-object)) sides)
;; (chunk-type (square (:include polygon)) (sides 4) (square t))
;;
;; and the oval type is predefined by the vision module like this:
;;
;; (chunk-type (oval (:include visual-object)) (oval t))
(add-visicon-features '(screen-x 0 screen-y 5 regular true)
'(isa (visual-location oval) screen-x 12 screen-y 20
value (oval "the oval") height 10 width 40
color blue)
'(isa (polygon-feature polygon) screen-x 50 screen-y 50
value (polygon "poly 1") height 20 width 40
color blue regular (false nil)
sides (nil 7))
'(isa (polygon-feature square) screen-x 10 screen-y 50
value (square "the square") height 30 width 30
color red regular (true nil)
sides (nil 4))
'(isa (polygon-feature polygon) screen-x 5 screen-y 70
value (polygon "poly 2") height 50 width 45
color green regular (false nil)
sides (nil 5)))
;; Give the vision module a chance to process the display
;; before printing the visicon.
(run-n-events 3)
(print-visicon)
;; Then just run the model
(run 10))
;;; The model is very simple in that it just repeatedly finds
;;; a location and then attends to the item there printing
;;; out the chunks in the visual-location and visual buffers
;;; after the corresponding requet completes.
;;;
(load-act-r-model "ACT-R:examples;vision-module;new-visicon-features-model.lisp")
| 4,901 | Common Lisp | .lisp | 87 | 48.264368 | 81 | 0.677522 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 8da4b72ef22b476e6f91d96d6da5d2e674d63fcba6e23c663551eff800197b3a | 14,181 | [
412792
] |
14,182 | rotational-vision-test-1.lisp | asmaloney_ACT-R/examples/vision-module/rotational-vision-test-1.lisp | ;;; This is a simple example model to show the new options of
;;; clockwise and counterclockwise which can be used with the
;;; :nearest request parameter in a visual-location request.
;;;
;;; The display is a clock face in an experiment window. The
;;; model finds the top most number (12), attends to it, and
;;; then finds and attends to items clockwise until it returns
;;; to a number it has seen before. Then, it switches to finding
;;; and attending to items counterclockwise until it again
;;; returns to a previously seen number.
(clear-all)
(defun run-test ()
(reset)
;; open a visible experiment window and install it as a device.
;; the window has the default width and height of 300 pixels each
;; and default location of 300,300.
;; Installing an AGI window device automatically sets the
;; default center point reference to the center of that window.
(install-device (open-exp-window "Test"))
;; Draw the clock face, and since there's only one window don't need
;; the window reference.
(add-text-to-exp-window nil "12" :x 150 :y 50 :height 25)
(add-text-to-exp-window nil "1" :x 200 :y 63 :height 25)
(add-text-to-exp-window nil "2" :x 237 :y 100 :height 25)
(add-text-to-exp-window nil "3" :x 250 :y 150 :height 25)
(add-text-to-exp-window nil "4" :x 237 :y 200 :height 25)
(add-text-to-exp-window nil "5" :x 200 :y 237 :height 25)
(add-text-to-exp-window nil "6" :x 150 :y 250 :height 25)
(add-text-to-exp-window nil "7" :x 100 :y 237 :height 25)
(add-text-to-exp-window nil "8" :x 63 :y 200 :height 25)
(add-text-to-exp-window nil "9" :x 50 :y 150 :height 25)
(add-text-to-exp-window nil "10" :x 63 :y 100 :height 25)
(add-text-to-exp-window nil "11" :x 100 :y 63 :height 25)
;; If we wanted to set the reference point directly we
;; would do this to get the same point (window_x + width/2)
;; and (window_y + height/2)
;;
;;(set-visual-center-point 450 450)
(run 10 t))
(define-model test-rotation
(sgp :show-focus t)
(chunk-type goal start dir current)
(p start
?goal>
buffer empty
==>
+visual-location>
isa visual-location
screen-y lowest
+goal>
isa goal
dir clockwise)
(p attend
=goal>
=visual-location>
?visual>
state free
buffer empty
==>
+visual>
isa move-attention
screen-pos =visual-location)
(p encode-and-record
=goal>
isa goal
start nil
dir =dir
=visual>
isa text
value =val
==>
=goal>
start =val
current =val)
(p encode
=goal>
isa goal
- start =val
- start nil
dir =dir
=visual>
isa text
value =val
==>
=goal>
current =val)
(p encode-and-switch
=goal>
isa goal
start =val
dir clockwise
=visual>
isa text
value =val
==>
=goal>
dir counterclockwise
current =val)
(p encode-and-stop
=goal>
isa goal
dir counterclockwise
start =val
=visual>
isa text
value =val
==>
=goal>
dir nil
current =val)
(p find-next
=goal>
isa goal
dir =dir
current =val
?visual-location>
buffer empty
?visual>
buffer empty
state free
==>
+visual-location>
isa visual-location
- value =val
:nearest =dir)
)
| 3,542 | Common Lisp | .lisp | 126 | 22.206349 | 71 | 0.617472 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a55743d651431e8ee80538bc6d7d37b0a7c372e6123f909bd0b8be54895e5781 | 14,182 | [
235377
] |
14,183 | set-attended-coordinates-model.lisp | asmaloney_ACT-R/examples/vision-module/set-attended-coordinates-model.lisp |
(clear-all)
;;; The model is very simple in that it just makes a
;;; request to find the feature nearest to current and
;;; then prints the result.
(define-model set-attended-coordinates-model
(sgp :v t :trace-detail low)
(p start
?goal>
buffer empty
==>
+goal>
+visual-location>
:nearest current)
(p found
=visual-location>
?visual-location>
buffer requested
==>
!eval! (pprint-chunks-fct (list =visual-location)))) | 522 | Common Lisp | .lisp | 19 | 20.947368 | 57 | 0.63125 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | d7b345aaf108058977786482f5f39f61ae255cc030a50585ffc4d6efae5c8688 | 14,183 | [
-1
] |
14,184 | set-attended-coordinates.lisp | asmaloney_ACT-R/examples/vision-module/set-attended-coordinates.lisp | ;;; This example demonstrates how one can set the initial position
;;; of visual attention.
(defun create-features ()
;; just put two locations out there
;; one close to 0,0 the default initial
;; position and one close to 50,50 which
;; is set as the starting point below.
(add-visicon-features '(screen-x 0 screen-y 5 distance 1080)
'(screen-x 60 screen-y 55 distance 1080))
(run-n-events 3)
(print-visicon))
(defun run-example ()
;; with the default initial position
(reset)
(create-features)
(run 10)
;; set the position
(reset)
(create-features)
(attend-visual-coordinates 50 50)
(run 10))
;;; The model is very simple in that it just finds the
;;; location closest to current and prints out the result.
;;;
(load-act-r-model "ACT-R:examples;vision-module;set-attended-coordinates-model.lisp")
| 878 | Common Lisp | .lisp | 25 | 30.96 | 85 | 0.708434 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 1cf1d970f442c8654646fde97a8650438b1e9b8280f88c064ef7645caaac3914 | 14,184 | [
251128
] |
14,185 | new-visicon-features-position-slots-model.lisp | asmaloney_ACT-R/examples/vision-module/new-visicon-features-position-slots-model.lisp |
(clear-all)
;;; The model is very simple in that it just repeatedly finds
;;; a location and then attends to the item there printing
;;; out the chunks in the visual-location and visual buffers
;;; after the corresponding requet completes relying on finsts
;;; markers to stop after attending all of them.
;;;
;;;
(define-model new-visual-feature-slots
(sgp :v t :trace-detail low)
(chunk-type real-space x y z size)
(chunk-type other-space pos-1 pos-2 pos-3 size value)
(p start
?goal>
buffer empty
==>
+goal>
+visual-location>
:attended nil)
(p attend
=visual-location>
?visual-location>
buffer requested
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
!eval! (pprint-chunks-fct (list =visual-location)))
(p harvest
=visual>
==>
+visual-location>
:attended nil
!eval! (pprint-chunks-fct (list =visual)))) | 1,028 | Common Lisp | .lisp | 36 | 22.305556 | 63 | 0.637306 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 74ac721b2c222a927ad7807dc7e31696548f01f6342e225e2a32bb9e0efc9533 | 14,185 | [
9270
] |
14,186 | adjust-visicon-features-model.lisp | asmaloney_ACT-R/examples/vision-module/adjust-visicon-features-model.lisp |
(clear-all)
;;; This model relies on buffer stuffing to detect when
;;; the visual scene changes (the only constraint on the
;;; stuffed chunk is screen-x lowest) and then attends to
;;; an items and prints the location and object chunks.
;;;
;;; The items it attends are prespecified to be the ones
;;; that are changed by the task code for demonstration.
(define-model adjust-visual-features
(sgp :v t)
;; chunk-types for the visual features
(chunk-type (polygon-feature (:include visual-location)) regular)
(chunk-type (polygon (:include visual-object)) sides)
;; simple goal buffer chunk to step through the example
(chunk-type goal step)
;; Do this to avoid the warnings when the chunks are created
(define-chunks true false polygon)
;; stuff the leftmost item
(set-visloc-default screen-x lowest)
(p start
?goal>
buffer empty
=visual-location>
screen-x =x
?visual>
state free
==>
+visual-location>
> screen-x =x
+visual>
isa move-attention
screen-pos =visual-location
!output! (First location chunk)
!eval! (buffer-chunk visual-location))
(p attend-second
?goal>
buffer empty
=visual-location>
=visual>
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
!output! (First object chunk)
!eval! (buffer-chunk visual)
!output! (Second location chunk)
!eval! (buffer-chunk visual-location))
(p show-second
?goal>
buffer empty
=visual>
?visual-location>
buffer empty
==>
!output! (Second object chunk)
!eval! (buffer-chunk visual)
+goal>)
(p first-change
=goal>
step nil
?visual-location>
buffer unrequested
==>
+visual-location>
color green
=goal>
step 1)
(p second-item
=goal>
step 1
?visual-location>
buffer unrequested
==>
+visual-location>
color red
=goal>
step 2)
(p third-item
=goal>
step 2
?visual-location>
buffer unrequested
==>
+visual-location>
color green
=goal>
step 3)
(p fourth-item
=goal>
step 3
?visual-location>
buffer unrequested
==>
+visual-location>
color green
=goal>
step 4)
(p attend
=goal>
=visual-location>
?visual-location>
buffer requested
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
!output! (Current location chunk)
!eval! (buffer-chunk visual-location))
(p report-attended
=goal>
=visual>
==>
!output! (Current object chunk)
!eval! (buffer-chunk visual))
)
| 3,006 | Common Lisp | .lisp | 119 | 17.932773 | 68 | 0.596855 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | eaff1cfc0142e2d8a01235a6c00e7c9090eb48bcb1eb4395da9b0e5c499bf4e1 | 14,186 | [
-1
] |
14,187 | tracking-model.lisp | asmaloney_ACT-R/examples/vision-module/tracking-model.lisp | ;;; This is the model which performs the tracking task to
;;; output the information as it is updated.
(clear-all)
(define-model simple-tracking
(sgp :v t :needs-mouse nil :show-focus t :trace-detail high)
(P attend
"Attend the stuffed location"
=visual-location>
?visual>
state free
?goal>
buffer empty
==>
+goal>
+visual>
isa move-attention
screen-pos =visual-location)
(P track-letter
"Once attended track it"
=goal>
=visual>
?visual>
state free
==>
+visual>
isa start-tracking)
(p report
"Output the info as it updates"
=goal>
=visual-location>
screen-x =x
screen-y =y
=visual>
value =val
==>
!output! (=val is at =x =y))
) | 892 | Common Lisp | .lisp | 37 | 17.081081 | 65 | 0.540964 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 7ac7350fc16218dbc9fe5d0f0fd40e4ad66937f513ba34723f3efe51d3acd62c | 14,187 | [
314401
] |
14,188 | models.lisp | asmaloney_ACT-R/examples/model-task-interfacing/one-window-buttons/models.lisp | (clear-all)
(define-model red-player
(sgp :v t :trace-detail high :needs-mouse t :er t :show-focus red :needs-mouse red)
;; stuff buttons that aren't white or blue
(set-visloc-default kind oval - color white - color blue)
;; Create a chunk with the player color and player label and make it the current goal
(chunk-type play my-color my-number state)
(define-chunks (goal isa play my-color red my-number "1"))
(goal-focus goal)
(define-chunks move read check done click)
(install-device '("motor" "cursor" "mouse"))
(start-hand-at-mouse)
(p my-turn-from-left
=goal>
state nil
my-color red
=visual-location>
screen-x =x
color red
==>
;; cheat and restrict location based on code
!bind! =limit (+ =x 100)
+visual-location>
kind oval
color white
> screen-x =x
< screen-x =limit
=goal>
state move)
(p my-turn-from-right
=goal>
state nil
my-color blue
=visual-location>
screen-x =x
color blue
==>
;; cheat and restrict location based on code
!bind! =limit (- =x 100)
+visual-location>
kind oval
color white
< screen-x =x
>= screen-x =limit
=goal>
state move)
(p game-over
=goal>
state nil
=visual-location>
screen-x =x
screen-y =y
color green
==>
+visual-location>
kind text
screen-x =x
screen-y =y
=goal>
state read)
(p read
=goal>
state read
=visual-location>
?visual>
state free
==>
=goal>
state check
+visual>
isa move-attention
screen-pos =visual-location)
(p yeah
=goal>
state check
my-number =num
=visual>
value =num
==>
!output! (I won)
=goal>
state done)
(p boo
=goal>
state check
my-number =num
=visual>
- value =num
==>
!output! (I lost)
=goal>
state done)
(p move
=goal>
state move
=visual-location>
?manual>
state free
==>
+manual>
cmd move-cursor
loc =visual-location
=goal>
state click)
(p click
=goal>
state click
?manual>
state free
==>
+manual>
cmd click-mouse
=goal>
state nil))
(define-model blue-player
(sgp :v t :trace-detail high :needs-mouse t :er t :show-focus blue :needs-mouse blue)
;; stuff buttons that aren't white or red
(set-visloc-default kind oval - color white - color red)
;; Create a chunk with the player color and player label and make it the current goal
(chunk-type play my-color my-number state)
(define-chunks (goal isa play my-color blue my-number "2"))
(goal-focus goal)
(define-chunks move read check done click)
(install-device '("motor" "cursor" "mouse"))
(start-hand-at-mouse)
(p my-turn-from-left
=goal>
state nil
my-color red
=visual-location>
screen-x =x
color red
==>
;; cheat and restrict location based on code
!bind! =limit (+ =x 100)
+visual-location>
kind oval
color white
> screen-x =x
< screen-x =limit
=goal>
state move)
(p my-turn-from-right
=goal>
state nil
my-color blue
=visual-location>
screen-x =x
color blue
==>
;; cheat and restrict location based on code
!bind! =limit (- =x 100)
+visual-location>
kind oval
color white
< screen-x =x
>= screen-x =limit
=goal>
state move)
(p game-over
=goal>
state nil
=visual-location>
screen-x =x
screen-y =y
color green
==>
+visual-location>
kind text
screen-x =x
screen-y =y
=goal>
state read)
(p read
=goal>
state read
=visual-location>
?visual>
state free
==>
=goal>
state check
+visual>
isa move-attention
screen-pos =visual-location)
(p yeah
=goal>
state check
my-number =num
=visual>
value =num
==>
!output! (I won)
=goal>
state done)
(p boo
=goal>
state check
my-number =num
=visual>
- value =num
==>
!output! (I lost)
=goal>
state done)
(p move
=goal>
state move
=visual-location>
?manual>
state free
==>
+manual>
cmd move-cursor
loc =visual-location
=goal>
state click)
(p click
=goal>
state click
?manual>
state free
==>
+manual>
cmd click-mouse
=goal>
state nil)) | 5,984 | Common Lisp | .lisp | 227 | 14.753304 | 88 | 0.458762 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4654e69c7b720d6ec3a8792a8b65aad0320dcdca8fb663785de8c8d62b2dd1c3 | 14,188 | [
493317
] |
14,189 | game.lisp | asmaloney_ACT-R/examples/model-task-interfacing/one-window-buttons/game.lisp | ;; Play the simple capture game in 1 window with buttons for interaction.
;; Buttons highlight in red or blue to indicate player turn.
;; Set player goal chunks with color, and also set their
;; mouse cursor color to match.
;;
;; When updating the buttons just remove them and add a replacement.
;; global variables for game info
(defvar *current-player*) ;; name of model
(defvar *p1*) ;; player1 name
(defvar *p2*) ;; player2 name
(defvar *game-over*) ;; if true stop the game
(defvar *p1-position*) ;; current player locations, 0-5
(defvar *p2-position*)
(defvar *window*) ;; the interaction window
(defvar *safety-stop*) ;; flag that modeler wants run to stop
(defvar *spaces* (make-list 6 :initial-element nil)) ;; record the button objects
(defun stop-a-run ()
(setf *safety-stop* t))
(defun set-game-over (player)
(setf *game-over* player))
(defun game-over (time)
(or *safety-stop* *game-over* (> time 1000000)))
;; The function to call when a button is pressed.
;; If the current player made the move, update the state.
(defun pick-button (index)
;; Make sure the right player made the action
(when (eq (current-model) *current-player*)
(if (eq *current-player* *p1*)
;; check if it was a valid move -- 1 or 2 spaces forward
(when (and (> index *p1-position*) (<= (- index *p1-position*) 2))
;; update the buttons
;; Remove the previous ones
(remove-items-from-exp-window *window* (nth *p1-position* *spaces*) (nth index *spaces*))
;; old space is now white and blank
(setf (nth *p1-position* *spaces*)
(add-button-to-exp-window *window* :text "" :x (+ 10 (* *p1-position* 40)) :y 10
:action (list 'pick-button *p1-position*) :height 35 :width 35 :color 'white))
(if (>= index *p2-position*)
(progn
;; set the game over after 3 seconds
(schedule-event-relative 3 'set-game-over :params (list *p1*))
;; new space is green to indicate a win
(setf (nth index *spaces*)
(add-button-to-exp-window *window* :text "1" :x (+ 10 (* index 40)) :y 10
:action (list 'pick-button index) :height 35 :width 35 :color 'green)))
(progn ;; update the p1 position and make p2 the current player
;; p1 position is white
(setf (nth index *spaces*)
(add-button-to-exp-window *window* :text "1" :x (+ 10 (* index 40)) :y 10
:action (list 'pick-button index) :height 35 :width 35 :color 'white))
;; set p2 position to be blue
(remove-items-from-exp-window *window* (nth *p2-position* *spaces*))
(setf (nth *p2-position* *spaces*)
(add-button-to-exp-window *window* :text "2" :x (+ 10 (* *p2-position* 40)) :y 10
:action (list 'pick-button *p2-position*) :height 35 :width 35 :color 'blue))
;; update position and player
(setf *p1-position* index)
(setf *current-player* *p2*))))
;; if p2 makes a valid move
(when (and (< index *p2-position*) (<= (- *p2-position* index) 2))
;; update the buttons
;; Remove the previous ones
(remove-items-from-exp-window *window* (nth *p2-position* *spaces*) (nth index *spaces*))
;; old space is now white and blank
(setf (nth *p2-position* *spaces*)
(add-button-to-exp-window *window* :text "" :x (+ 10 (* *p2-position* 40)) :y 10
:action (list 'pick-button *p2-position*) :height 35 :width 35 :color 'white))
(if (<= index *p1-position*)
(progn
;; set the game over after 3 seconds
(schedule-event-relative 3 'set-game-over :params (list *p2*))
;; new space is green to indicate a win
(setf (nth index *spaces*)
(add-button-to-exp-window *window* :text "2" :x (+ 10 (* index 40)) :y 10
:action (list 'pick-button index) :height 35 :width 35 :color 'green)))
(progn ;; update the p2 position and make p1 the current player
;; p2 position is white
(setf (nth index *spaces*)
(add-button-to-exp-window *window* :text "2" :x (+ 10 (* index 40)) :y 10
:action (list 'pick-button index) :height 35 :width 35 :color 'white))
;; set p1 position to be red
(remove-items-from-exp-window *window* (nth *p1-position* *spaces*))
(setf (nth *p1-position* *spaces*)
(add-button-to-exp-window *window* :text "1" :x (+ 10 (* *p1-position* 40)) :y 10
:action (list 'pick-button *p1-position*) :height 35 :width 35 :color 'red))
;; update position and player
(setf *p2-position* index)
(setf *current-player* *p1*)))))))
;; play one round of the game resetting the models
;; before it starts.
(defun play (player1 player2)
(when (every (lambda (x) (find x (mp-models))) (list player1 player2))
(reset)
;; initialize some game info
(setf *p1* player1)
(setf *p2* player2)
(setf *game-over* nil)
(setf *safety-stop* nil)
(setf *current-player* player1)
(setf *p1-position* 0)
(setf *p2-position* 5)
(let ((game-window (open-exp-window "game" :visible t :width 300 :height 100))
(safety-window (open-exp-window "safety" :visible t :width 100 :height 100 :x 100 :y 100)))
(add-button-to-exp-window safety-window :text "STOP" :x 0 :y 0 :action 'stop-a-run :height 80 :width 80 :color 'red)
(setf *window* game-window)
(dolist (m (mp-models)) ;; set all models to use this device
(with-model-eval m
(install-device game-window)))
(dotimes (i 6) ;; create the buttons
(setf (nth i *spaces*) ;; save them for later use
(let ((index i)) ;; need to bind the value of i to use in the action function
(add-button-to-exp-window game-window :text (if (zerop i) "1" (if (= i 5) "2" ""))
:x (+ 10 (* i 40))
:y 10
:action (list 'pick-button index) :height 35 :width 35 :color (if (zerop i) 'red 'white))))))
;; Run ACT-R until the *game-over* variable is non-nil.
(run-until-condition 'game-over t))
;; return the result
*game-over*)
#|
? (play 'red-player 'blue-player)
0.000 RED-PLAYER GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 BLUE-PLAYER GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 BLUE-PLAYER VISION proc-display
0.000 BLUE-PLAYER VISION visicon-update
0.000 RED-PLAYER VISION proc-display
0.000 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0 NIL
0.000 RED-PLAYER VISION visicon-update
0.000 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.000 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED MY-TURN-FROM-LEFT
0.000 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
0.000 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.000 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.050 RED-PLAYER PROCEDURAL PRODUCTION-FIRED MY-TURN-FROM-LEFT
0.050 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.050 RED-PLAYER PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.050 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 RED-PLAYER VISION Find-location
0.050 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION2
0.050 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.050 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED MOVE
0.050 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 RED-PLAYER PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.100 RED-PLAYER PROCEDURAL PRODUCTION-FIRED MOVE
0.100 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.100 RED-PLAYER PROCEDURAL MODULE-REQUEST MANUAL
0.100 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 RED-PLAYER PROCEDURAL CLEAR-BUFFER MANUAL
0.100 RED-PLAYER MOTOR MOVE-CURSOR LOC VISUAL-LOCATION2-0
0.100 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.300 RED-PLAYER MOTOR PREPARATION-COMPLETE 0.1
0.300 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.350 RED-PLAYER MOTOR INITIATION-COMPLETE 0.1
0.350 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.694 RED-PLAYER MOUSE move-cursor RED-PLAYER mouse (368 328 1080)
0.694 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.744 RED-PLAYER MOTOR FINISH-MOVEMENT 0.1
0.744 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.744 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED CLICK
0.744 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
0.744 RED-PLAYER PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.794 RED-PLAYER PROCEDURAL PRODUCTION-FIRED CLICK
0.794 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.794 RED-PLAYER PROCEDURAL MODULE-REQUEST MANUAL
0.794 RED-PLAYER PROCEDURAL CLEAR-BUFFER MANUAL
0.794 RED-PLAYER MOTOR CLICK-MOUSE
0.794 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.944 RED-PLAYER MOTOR PREPARATION-COMPLETE 0.794
0.944 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
0.994 RED-PLAYER MOTOR INITIATION-COMPLETE 0.794
0.994 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.004 RED-PLAYER MOUSE click-mouse RED-PLAYER (368 328 1080) INDEX
1.004 BLUE-PLAYER VISION proc-display
1.004 BLUE-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION11 NIL
1.004 BLUE-PLAYER VISION visicon-update
1.004 RED-PLAYER VISION proc-display
1.004 RED-PLAYER VISION visicon-update
1.004 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.004 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.004 BLUE-PLAYER PROCEDURAL PRODUCTION-SELECTED MY-TURN-FROM-RIGHT
1.004 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
1.004 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
1.054 BLUE-PLAYER PROCEDURAL PRODUCTION-FIRED MY-TURN-FROM-RIGHT
1.054 BLUE-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.054 BLUE-PLAYER PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
1.054 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.054 BLUE-PLAYER VISION Find-location
1.054 BLUE-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION4
1.054 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.054 BLUE-PLAYER PROCEDURAL PRODUCTION-SELECTED MOVE
1.054 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
1.054 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
1.054 BLUE-PLAYER PROCEDURAL QUERY-BUFFER-ACTION MANUAL
1.094 RED-PLAYER MOTOR FINISH-MOVEMENT 0.794
1.094 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.104 BLUE-PLAYER PROCEDURAL PRODUCTION-FIRED MOVE
1.104 BLUE-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.104 BLUE-PLAYER PROCEDURAL MODULE-REQUEST MANUAL
1.104 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.104 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER MANUAL
1.104 BLUE-PLAYER MOTOR MOVE-CURSOR LOC VISUAL-LOCATION4-0
1.104 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.304 BLUE-PLAYER MOTOR PREPARATION-COMPLETE 1.104
1.304 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.354 BLUE-PLAYER MOTOR INITIATION-COMPLETE 1.104
1.354 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.724 BLUE-PLAYER MOUSE move-cursor BLUE-PLAYER mouse (448 328 1080)
1.724 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.774 BLUE-PLAYER MOTOR FINISH-MOVEMENT 1.104
1.774 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.774 BLUE-PLAYER PROCEDURAL PRODUCTION-SELECTED CLICK
1.774 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
1.774 BLUE-PLAYER PROCEDURAL QUERY-BUFFER-ACTION MANUAL
1.824 BLUE-PLAYER PROCEDURAL PRODUCTION-FIRED CLICK
1.824 BLUE-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.824 BLUE-PLAYER PROCEDURAL MODULE-REQUEST MANUAL
1.824 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER MANUAL
1.824 BLUE-PLAYER MOTOR CLICK-MOUSE
1.824 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
1.974 BLUE-PLAYER MOTOR PREPARATION-COMPLETE 1.824
1.974 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.024 BLUE-PLAYER MOTOR INITIATION-COMPLETE 1.824
2.024 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.034 BLUE-PLAYER MOUSE click-mouse BLUE-PLAYER (448 328 1080) INDEX
2.034 BLUE-PLAYER VISION proc-display
2.034 BLUE-PLAYER VISION visicon-update
2.034 RED-PLAYER VISION proc-display
2.034 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION16 NIL
2.034 RED-PLAYER VISION visicon-update
2.034 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.034 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.034 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED MY-TURN-FROM-LEFT
2.034 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.034 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.084 RED-PLAYER PROCEDURAL PRODUCTION-FIRED MY-TURN-FROM-LEFT
2.084 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.084 RED-PLAYER PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
2.084 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.084 RED-PLAYER VISION Find-location
2.084 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION14
2.084 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.084 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED MOVE
2.084 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.084 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.084 RED-PLAYER PROCEDURAL QUERY-BUFFER-ACTION MANUAL
2.124 BLUE-PLAYER MOTOR FINISH-MOVEMENT 1.824
2.124 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.134 RED-PLAYER PROCEDURAL PRODUCTION-FIRED MOVE
2.134 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.134 RED-PLAYER PROCEDURAL MODULE-REQUEST MANUAL
2.134 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.134 RED-PLAYER PROCEDURAL CLEAR-BUFFER MANUAL
2.134 RED-PLAYER MOTOR MOVE-CURSOR LOC VISUAL-LOCATION14-0
2.134 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.334 RED-PLAYER MOTOR PREPARATION-COMPLETE 2.134
2.334 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.384 RED-PLAYER MOTOR INITIATION-COMPLETE 2.134
2.384 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.532 RED-PLAYER MOUSE move-cursor RED-PLAYER mouse (448 328 1080)
2.532 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.582 RED-PLAYER MOTOR FINISH-MOVEMENT 2.134
2.582 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.582 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED CLICK
2.582 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.582 RED-PLAYER PROCEDURAL QUERY-BUFFER-ACTION MANUAL
2.632 RED-PLAYER PROCEDURAL PRODUCTION-FIRED CLICK
2.632 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.632 RED-PLAYER PROCEDURAL MODULE-REQUEST MANUAL
2.632 RED-PLAYER PROCEDURAL CLEAR-BUFFER MANUAL
2.632 RED-PLAYER MOTOR CLICK-MOUSE
2.632 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.782 RED-PLAYER MOTOR PREPARATION-COMPLETE 2.632
2.782 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.832 RED-PLAYER MOTOR INITIATION-COMPLETE 2.632
2.832 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.842 RED-PLAYER MOUSE click-mouse RED-PLAYER (448 328 1080) INDEX
2.842 BLUE-PLAYER VISION proc-display
2.842 BLUE-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION19 NIL
2.842 BLUE-PLAYER VISION visicon-update
2.842 RED-PLAYER VISION proc-display
2.842 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION19 NIL
2.842 RED-PLAYER VISION visicon-update
2.842 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.842 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED GAME-OVER
2.842 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.842 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.842 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.842 BLUE-PLAYER PROCEDURAL PRODUCTION-SELECTED GAME-OVER
2.842 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.842 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.892 RED-PLAYER PROCEDURAL PRODUCTION-FIRED GAME-OVER
2.892 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.892 RED-PLAYER PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
2.892 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.892 BLUE-PLAYER PROCEDURAL PRODUCTION-FIRED GAME-OVER
2.892 BLUE-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.892 BLUE-PLAYER PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
2.892 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.892 RED-PLAYER VISION Find-location
2.892 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION20
2.892 BLUE-PLAYER VISION Find-location
2.892 BLUE-PLAYER VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION20
2.892 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.892 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED READ
2.892 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.892 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.892 RED-PLAYER PROCEDURAL QUERY-BUFFER-ACTION VISUAL
2.892 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.892 BLUE-PLAYER PROCEDURAL PRODUCTION-SELECTED READ
2.892 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
2.892 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.892 BLUE-PLAYER PROCEDURAL QUERY-BUFFER-ACTION VISUAL
2.932 RED-PLAYER MOTOR FINISH-MOVEMENT 2.632
2.942 RED-PLAYER PROCEDURAL PRODUCTION-FIRED READ
2.942 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.942 RED-PLAYER PROCEDURAL MODULE-REQUEST VISUAL
2.942 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.942 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL
2.942 BLUE-PLAYER PROCEDURAL PRODUCTION-FIRED READ
2.942 BLUE-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.942 BLUE-PLAYER PROCEDURAL MODULE-REQUEST VISUAL
2.942 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.942 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL
2.942 RED-PLAYER VISION Move-attention VISUAL-LOCATION20-0 NIL
2.942 BLUE-PLAYER VISION Move-attention VISUAL-LOCATION20-0 NIL
2.942 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
2.942 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
3.027 RED-PLAYER VISION Encoding-complete VISUAL-LOCATION20-0 NIL
3.027 RED-PLAYER VISION SET-BUFFER-CHUNK VISUAL TEXT0
3.027 BLUE-PLAYER VISION Encoding-complete VISUAL-LOCATION20-0 NIL
3.027 BLUE-PLAYER VISION SET-BUFFER-CHUNK VISUAL TEXT0
3.027 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
3.027 RED-PLAYER PROCEDURAL PRODUCTION-SELECTED YEAH
3.027 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
3.027 RED-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL
3.027 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
3.027 BLUE-PLAYER PROCEDURAL PRODUCTION-SELECTED BOO
3.027 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION GOAL
3.027 BLUE-PLAYER PROCEDURAL BUFFER-READ-ACTION VISUAL
3.077 RED-PLAYER PROCEDURAL PRODUCTION-FIRED YEAH
I WON
3.077 RED-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
3.077 RED-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL
3.077 BLUE-PLAYER PROCEDURAL PRODUCTION-FIRED BOO
I LOST
3.077 BLUE-PLAYER PROCEDURAL MOD-BUFFER-CHUNK GOAL
3.077 BLUE-PLAYER PROCEDURAL CLEAR-BUFFER VISUAL
3.077 RED-PLAYER PROCEDURAL CONFLICT-RESOLUTION
3.077 BLUE-PLAYER PROCEDURAL CONFLICT-RESOLUTION
5.842 RED-PLAYER NONE SET-GAME-OVER RED-PLAYER
5.842 - ------ Stopped because condition is true
RED-PLAYER
|#
| 24,138 | Common Lisp | .lisp | 354 | 59.033898 | 131 | 0.590999 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 006f47a2764775d0041851bad61dcdf3124fc1e31ff7014737bf20c152dbbc3f | 14,189 | [
-1
] |
14,190 | models.lisp | asmaloney_ACT-R/examples/model-task-interfacing/no-windows-visual-info/models.lisp |
(clear-all)
;; Create one copy of the model code using defparameter so that
;; it gets updated if we reload -- defvar doesn't re-evaluate the
;; value after the first time it is loaded.
(defparameter *model-code*
;; A list of information just like one would put in a
;; define-model call.
'((sgp :v t :trace-detail high :er t)
(chunk-type (player-loc (:include visual-location)) name position turn result)
(chunk-type (player (:include visual-object)) name position turn result)
(chunk-type goal my-name state)
(define-chunks find play win lose player)
(define-chunks-fct (list (current-model)))
(define-chunks-fct (list (list 'goal 'my-name (current-model))))
(goal-focus goal)
(install-device '("motor" "keyboard"))
(p start
=goal>
my-name =m
state nil
==>
=goal>
state find
!output! (My name is =m)
+visual-location>
name =m
)
(p attend
=goal>
state find
=visual-location>
?visual>
state free
==>
+visual>
isa move-attention
screen-pos =visual-location
=goal>
state play)
(p 1-step
=goal>
state play
=visual>
turn t
position =pos
?manual>
state free
==>
=visual>
!output! (I am at position =pos)
+manual>
isa press-key
key "1")
(p 2-step
=goal>
state play
=visual>
turn t
position =pos
?manual>
state free
==>
=visual>
!output! (I am at position =pos)
+manual>
isa press-key
key "2")
(p result
=goal>
state play
=visual>
result =r
==>
!output! (I =r)
-goal>)))
;; Use the define-model function to create models named
;; model1 and model2 each using the same definition code.
(define-model-fct 'model1 *model-code*)
(define-model-fct 'model2 *model-code*)
| 2,181 | Common Lisp | .lisp | 79 | 18.721519 | 83 | 0.551844 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | bc950f2a322efc56d74092f1c78c780e252def85d06b7fa1b05d84419cffd683 | 14,190 | [
114833
] |
14,191 | game.lisp | asmaloney_ACT-R/examples/model-task-interfacing/no-windows-visual-info/game.lisp | ;; Play the simple capture game with 2 models using no interface, but
;; creating custom visicon features for the model to see.
;; Each model will have two features which it can see. There is one
;; for each player and it contains these features:
#|
While game playing
Name Att Loc Kind Position Name Size Turn
----------- --- ------------ ------ -------- ------ ---- ----
PLAYER-LOC0 NEW ( 0 0 1080) PLAYER 0 MODEL1 1.0 T
PLAYER-LOC1 NEW (100 0 1080) PLAYER 5 MODEL2 1.0
when game over
Name Att Loc Kind Position Name Size Result
----------- --- ------------ ------ -------- ------ ---- ------
PLAYER-LOC0 T ( 0 0 1080) PLAYER 4 MODEL1 1.0 WIN
PLAYER-LOC1 NIL (100 0 1080) PLAYER 4 MODEL2 1.0 LOSE
|#
;; The position value is only available in the visual object chunk.
;; global variables for game info
(defvar *current-player*) ; name of the model
(defvar *p1*) ; player1 model name
(defvar *p2*) ; player2 model name
(defvar *game-over*) ; If true stop the game
(defvar *winner*) ; which player won
(defvar *safety-stop*) ; flag that modeler wants run to stop
(defvar *p1-position*) ; current player spots 0-5
(defvar *p2-position*)
(defvar *p1p1*) ; Record the visual features for each player
(defvar *p1p2*) ; so they can be updated instead of just
(defvar *p2p1*) ; clearing and adding new ones
(defvar *p2p2*)
;; function called for a keypress action which makes the
;; move and updates the visual info if it's a valid move
;; by the current player
(defun make-move (model key)
(when (and (eq *current-player* model)
(or (string-equal key "1") (string-equal key "2")))
(let ((dist (read-from-string key)))
(if (eq model *p1*) ; update the position
(incf *p1-position* dist)
(decf *p2-position* dist)))
(cond ((<= *p2-position* *p1-position*) ; the game is over
(setf *winner* *current-player*)
(schedule-event-relative 3 'set-game-over)
;; update player 1 visual features
(with-model-eval *p1*
(modify-visicon-features (list *p1p1* 'position *p1-position* 'turn nil 'result (if (eq *p1* *winner*) 'win 'lose)))
(modify-visicon-features (list *p1p2* 'position *p2-position* 'turn nil 'result (if (eq *p2* *winner*) 'win 'lose))))
;; update player 2 visual features
(with-model-eval *p2*
(modify-visicon-features (list *p2p1* 'position *p1-position* 'turn nil 'result (if (eq *p1* *winner*) 'win 'lose)))
(modify-visicon-features (list *p2p2* 'position *p2-position* 'turn nil 'result (if (eq *p2* *winner*) 'win 'lose)))))
(t ;; update the game and all visual features
(if (eq *current-player* *p1*)
(setf *current-player* *p2*)
(setf *current-player* *p1*))
(with-model-eval *p1*
(modify-visicon-features (list *p1p1* 'position *p1-position* 'turn (if (eq *current-player* *p1*) t nil)))
(modify-visicon-features (list *p1p2* 'position *p2-position* 'turn (if (eq *current-player* *p2*) t nil))))
(with-model-eval *p2*
(modify-visicon-features (list *p2p1* 'position *p1-position* 'turn (if (eq *current-player* *p1*) t nil)))
(modify-visicon-features (list *p2p2* 'position *p2-position* 'turn (if (eq *current-player* *p2*) t nil))))))))
(defun set-game-over () (setf *game-over* t))
(defun stop-a-run ()
(setf *safety-stop* t))
(defun game-over (time)
(or *safety-stop* *game-over* (> time 1000000)))
;; play one round of the game resetting the models
;; before it starts. Player1 and player2 are the
;; names of the models to run in the indicated
;; position.
(defun play (player1 player2)
(when (every (lambda (x) (find x (mp-models))) (list player1 player2))
(open-exp-window "Safety" :visible t :width 100 :height 100 :x 100 :y 300)
(add-button-to-exp-window "Safety" :text "STOP" :x 0 :y 0 :action 'stop-a-run :height 90 :width 90 :color 'red)
(add-act-r-command "move" 'make-move "Handle player key presses")
(monitor-act-r-command "output-key" "move")
(reset)
(with-model-eval player1
(define-chunks-fct (list player2))
(let ((feats (add-visicon-features `(isa (player-loc player) screen-x 0 screen-y 0 name ,player1 position (nil 0) turn (nil t))
`(isa (player-loc player) screen-x 100 screen-y 0 name ,player2 position (nil 5)))))
(setf *p1p1* (first feats))
(setf *p1p2* (second feats))))
(with-model-eval player2
(define-chunks-fct (list player1))
(let ((feats (add-visicon-features `(isa (player-loc player) screen-x 0 screen-y 0 name ,player1 position (nil 0) turn (nil t))
`(isa (player-loc player) screen-x 100 screen-y 0 name ,player2 position (nil 5)))))
(setf *p2p1* (first feats))
(setf *p2p2* (second feats))))
;; initialize the game information
(setf *p1* player1)
(setf *p2* player2)
(setf *p1-position* 0)
(setf *p2-position* 5)
(setf *game-over* nil)
(setf *current-player* player1)
(setf *safety-stop* nil)
(setf *winner* nil)
(run-until-condition 'game-over)
(remove-act-r-command-monitor "output-key" "move")
(remove-act-r-command "move")
;; return the winner
*winner*))
#|
? (play 'model1 'model2)
0.000 MODEL1 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL2 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL1 VISION proc-display
0.000 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION PLAYER-LOC0 NIL
0.000 MODEL1 VISION visicon-update
0.000 MODEL2 VISION proc-display
0.000 MODEL2 VISION SET-BUFFER-CHUNK VISUAL-LOCATION PLAYER-LOC0 NIL
0.000 MODEL2 VISION visicon-update
0.000 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.000 MODEL1 PROCEDURAL PRODUCTION-SELECTED START
0.000 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.000 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.000 MODEL2 PROCEDURAL PRODUCTION-SELECTED START
0.000 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 MODEL1 PROCEDURAL PRODUCTION-FIRED START
MY NAME IS MODEL1
0.050 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.050 MODEL1 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.050 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 MODEL2 PROCEDURAL PRODUCTION-FIRED START
MY NAME IS MODEL2
0.050 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.050 MODEL2 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.050 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 MODEL1 VISION Find-location
0.050 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION PLAYER-LOC0
0.050 MODEL2 VISION Find-location
0.050 MODEL2 VISION SET-BUFFER-CHUNK VISUAL-LOCATION PLAYER-LOC1
0.050 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL1 PROCEDURAL PRODUCTION-SELECTED ATTEND
0.050 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
0.050 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL2 PROCEDURAL PRODUCTION-SELECTED ATTEND
0.050 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
0.100 MODEL1 PROCEDURAL PRODUCTION-FIRED ATTEND
0.100 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.100 MODEL1 PROCEDURAL MODULE-REQUEST VISUAL
0.100 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL
0.100 MODEL2 PROCEDURAL PRODUCTION-FIRED ATTEND
0.100 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.100 MODEL2 PROCEDURAL MODULE-REQUEST VISUAL
0.100 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL
0.100 MODEL1 VISION Move-attention PLAYER-LOC0-1 NIL
0.100 MODEL2 VISION Move-attention PLAYER-LOC1-0 NIL
0.100 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.100 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.185 MODEL1 VISION Encoding-complete PLAYER-LOC0-1 NIL
0.185 MODEL1 VISION SET-BUFFER-CHUNK VISUAL PLAYER0
0.185 MODEL2 VISION Encoding-complete PLAYER-LOC1-0 NIL
0.185 MODEL2 VISION SET-BUFFER-CHUNK VISUAL PLAYER0
0.185 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.185 MODEL1 PROCEDURAL PRODUCTION-SELECTED 1-STEP
0.185 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.185 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL
0.185 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.185 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.235 MODEL1 PROCEDURAL PRODUCTION-FIRED 1-STEP
I AM AT POSITION 0
0.235 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
0.235 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
0.235 MODEL1 MOTOR PRESS-KEY KEY 1
0.235 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.485 MODEL1 MOTOR PREPARATION-COMPLETE 0.235
0.485 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.535 MODEL1 MOTOR INITIATION-COMPLETE 0.235
0.535 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.635 MODEL1 KEYBOARD output-key MODEL1 1
0.635 MODEL1 VISION proc-display
0.635 MODEL1 VISION visicon-update
0.635 MODEL2 VISION proc-display
0.635 MODEL2 VISION visicon-update
0.635 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.635 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.720 MODEL1 VISION Encoding-complete PLAYER-LOC0-1 NIL
0.720 MODEL1 VISION SET-BUFFER-CHUNK VISUAL PLAYER1 NIL
0.720 MODEL2 VISION Encoding-complete PLAYER-LOC1-0 NIL
0.720 MODEL2 VISION SET-BUFFER-CHUNK VISUAL PLAYER1 NIL
0.720 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.720 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.720 MODEL2 PROCEDURAL PRODUCTION-SELECTED 1-STEP
0.720 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.720 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL
0.720 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.770 MODEL2 PROCEDURAL PRODUCTION-FIRED 1-STEP
I AM AT POSITION 5
0.770 MODEL2 PROCEDURAL MODULE-REQUEST MANUAL
0.770 MODEL2 PROCEDURAL CLEAR-BUFFER MANUAL
0.770 MODEL2 MOTOR PRESS-KEY KEY 1
0.770 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.785 MODEL1 MOTOR FINISH-MOVEMENT 0.235
0.785 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.020 MODEL2 MOTOR PREPARATION-COMPLETE 0.77
1.020 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.070 MODEL2 MOTOR INITIATION-COMPLETE 0.77
1.070 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.170 MODEL2 KEYBOARD output-key MODEL2 1
1.170 MODEL1 VISION proc-display
1.170 MODEL1 VISION visicon-update
1.170 MODEL2 VISION proc-display
1.170 MODEL2 VISION visicon-update
1.170 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.170 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.255 MODEL1 VISION Encoding-complete PLAYER-LOC0-1 NIL
1.255 MODEL1 VISION SET-BUFFER-CHUNK VISUAL PLAYER2 NIL
1.255 MODEL2 VISION Encoding-complete PLAYER-LOC1-0 NIL
1.255 MODEL2 VISION SET-BUFFER-CHUNK VISUAL PLAYER2 NIL
1.255 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.255 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.255 MODEL1 PROCEDURAL PRODUCTION-SELECTED 1-STEP
1.255 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
1.255 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL
1.255 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
1.305 MODEL1 PROCEDURAL PRODUCTION-FIRED 1-STEP
I AM AT POSITION 1
1.305 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
1.305 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
1.305 MODEL1 MOTOR PRESS-KEY KEY 1
1.305 MODEL1 MOTOR PREPARATION-COMPLETE 1.305
1.305 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.320 MODEL2 MOTOR FINISH-MOVEMENT 0.77
1.320 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.355 MODEL1 MOTOR INITIATION-COMPLETE 1.305
1.355 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.455 MODEL1 KEYBOARD output-key MODEL1 1
1.455 MODEL1 VISION proc-display
1.455 MODEL1 VISION visicon-update
1.455 MODEL2 VISION proc-display
1.455 MODEL2 VISION visicon-update
1.455 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.455 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.540 MODEL1 VISION Encoding-complete PLAYER-LOC0-1 NIL
1.540 MODEL1 VISION SET-BUFFER-CHUNK VISUAL PLAYER3 NIL
1.540 MODEL2 VISION Encoding-complete PLAYER-LOC1-0 NIL
1.540 MODEL2 VISION SET-BUFFER-CHUNK VISUAL PLAYER3 NIL
1.540 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.540 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.540 MODEL2 PROCEDURAL PRODUCTION-SELECTED 1-STEP
1.540 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
1.540 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL
1.540 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
1.590 MODEL2 PROCEDURAL PRODUCTION-FIRED 1-STEP
I AM AT POSITION 4
1.590 MODEL2 PROCEDURAL MODULE-REQUEST MANUAL
1.590 MODEL2 PROCEDURAL CLEAR-BUFFER MANUAL
1.590 MODEL2 MOTOR PRESS-KEY KEY 1
1.590 MODEL2 MOTOR PREPARATION-COMPLETE 1.59
1.590 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.605 MODEL1 MOTOR FINISH-MOVEMENT 1.305
1.605 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.640 MODEL2 MOTOR INITIATION-COMPLETE 1.59
1.640 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.740 MODEL2 KEYBOARD output-key MODEL2 1
1.740 MODEL1 VISION proc-display
1.740 MODEL1 VISION visicon-update
1.740 MODEL2 VISION proc-display
1.740 MODEL2 VISION visicon-update
1.740 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.740 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.825 MODEL1 VISION Encoding-complete PLAYER-LOC0-1 NIL
1.825 MODEL1 VISION SET-BUFFER-CHUNK VISUAL PLAYER4 NIL
1.825 MODEL2 VISION Encoding-complete PLAYER-LOC1-0 NIL
1.825 MODEL2 VISION SET-BUFFER-CHUNK VISUAL PLAYER4 NIL
1.825 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.825 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.825 MODEL1 PROCEDURAL PRODUCTION-SELECTED 2-STEP
1.825 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
1.825 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL
1.825 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
1.875 MODEL1 PROCEDURAL PRODUCTION-FIRED 2-STEP
I AM AT POSITION 2
1.875 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
1.875 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
1.875 MODEL1 MOTOR PRESS-KEY KEY 2
1.875 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.890 MODEL2 MOTOR FINISH-MOVEMENT 1.59
1.890 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.025 MODEL1 MOTOR PREPARATION-COMPLETE 1.875
2.025 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.075 MODEL1 MOTOR INITIATION-COMPLETE 1.875
2.075 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.175 MODEL1 KEYBOARD output-key MODEL1 2
2.175 MODEL1 VISION proc-display
2.175 MODEL1 VISION visicon-update
2.175 MODEL2 VISION proc-display
2.175 MODEL2 VISION visicon-update
2.175 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.175 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.260 MODEL1 VISION Encoding-complete PLAYER-LOC0-1 NIL
2.260 MODEL1 VISION SET-BUFFER-CHUNK VISUAL PLAYER5 NIL
2.260 MODEL2 VISION Encoding-complete PLAYER-LOC1-0 NIL
2.260 MODEL2 VISION SET-BUFFER-CHUNK VISUAL PLAYER5 NIL
2.260 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.260 MODEL1 PROCEDURAL PRODUCTION-SELECTED RESULT
2.260 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
2.260 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL
2.260 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.260 MODEL2 PROCEDURAL PRODUCTION-SELECTED RESULT
2.260 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
2.260 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL
2.310 MODEL1 PROCEDURAL PRODUCTION-FIRED RESULT
I WIN
2.310 MODEL1 PROCEDURAL CLEAR-BUFFER GOAL
2.310 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL
2.310 MODEL2 PROCEDURAL PRODUCTION-FIRED RESULT
I LOSE
2.310 MODEL2 PROCEDURAL CLEAR-BUFFER GOAL
2.310 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL
2.310 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.310 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.325 MODEL1 MOTOR FINISH-MOVEMENT 1.875
2.325 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
5.175 MODEL1 NONE SET-GAME-OVER
5.175 - ------ Stopped because condition is true
MODEL1
|#
| 19,948 | Common Lisp | .lisp | 326 | 54.659509 | 133 | 0.59282 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 6edaf881d761c826c45009714e6fa233ed3af0e6e4151cd0bd292a387f55e7cc | 14,191 | [
-1
] |
14,192 | models.lisp | asmaloney_ACT-R/examples/model-task-interfacing/two-windows-buttons/models.lisp |
(clear-all)
(defparameter *model-code*
'((sgp :v t :trace-detail high :needs-mouse t)
(chunk-type play my-color state)
(define-chunks (goal isa play my-color red)
(move) (click))
(goal-focus goal)
(set-visloc-default-fct '(kind oval - color white - color blue))
(install-device '("motor" "cursor" "mouse"))
(start-hand-at-mouse)
(p my-turn
=goal>
state nil
=visual-location>
screen-x =x
color red
==>
!bind! =limit (+ =x 100)
+visual-location>
kind oval
color white
> screen-x =x
< screen-x =limit
=goal>
state move)
(p move
=goal>
state move
=visual-location>
?manual>
state free
==>
+manual>
isa move-cursor
loc =visual-location
=goal>
state click)
(p click
=goal>
state click
?manual>
state free
==>
+manual>
isa click-mouse
=goal>
state nil)
(p game-over
=goal>
=visual-location>
color green
?visual>
state free
==>
-goal>
+visual>
isa move-attention
screen-pos =visual-location)
(p report-win
=visual>
value "1"
==>
!output! (I win))
(p report-lose
=visual>
value "2"
==>
!output! (I lose))))
(define-model-fct 'model1 *model-code*)
(define-model-fct 'model2 *model-code*)
| 1,817 | Common Lisp | .lisp | 70 | 14.4 | 71 | 0.449398 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2650f930814023fde4420299274955ffeed8654bf02095d3d67528802196448d | 14,192 | [
-1
] |
14,193 | game.lisp | asmaloney_ACT-R/examples/model-task-interfacing/two-windows-buttons/game.lisp | ;; Play the simple capture game with each model having its own
;; window and each player plays left->right as red in its own window.
;; global variables
(defvar *current-player*) ;; player name
(defvar *p1*) ;; player 1 name
(defvar *p2*) ;; player 2 name
(defvar *game-over*) ;; stop game when true
(defvar *p1-position*) ;; current player positions
(defvar *p2-position*)
(defvar *p1-win*) ;; windows for each
(defvar *p2-win*)
(defvar *spaces-1* (make-list 6 :initial-element nil)) ;; buttons for each player
(defvar *spaces-2* (make-list 6 :initial-element nil))
(defun stop-a-run ()
(schedule-break-relative 0))
;; The function to call when a button is pressed.
;; If the current player made the move, update the state.
(defun pick-button (model index)
;; if the current player makes the action
(when (eq model *current-player*)
(if (eq *current-player* *p1*)
;; update the boards when player1 makes a valid move
(when (and (> index *p1-position*) (<= (- index *p1-position*) 2))
(if (>= index *p2-position*)
(progn ;; player 1 wins
;; give the models some time to process things before it stops
(schedule-break-relative 3)
(setf *game-over* *p1*)
(remove-items-from-exp-window *p1-win* (nth *p1-position* *spaces-1*) (nth index *spaces-1*))
(remove-items-from-exp-window *p2-win* (nth (- 5 *p1-position*) *spaces-2*) (nth (- 5 index) *spaces-2*))
(add-button-to-exp-window *p1-win* :text "" :x (+ 10 (* *p1-position* 40)) :y 10 :height 35 :width 35 :color 'white)
(add-button-to-exp-window *p1-win* :text "1" :x (+ 10 (* index 40)) :y 10 :height 35 :width 35 :color 'green)
(add-button-to-exp-window *p2-win* :text "" :x (+ 10 (* (- 5 *p1-position*) 40)) :y 10 :height 35 :width 35 :color 'white)
(add-button-to-exp-window *p2-win* :text "2" :x (+ 10 (* (- 5 index) 40)) :y 10 :height 35 :width 35 :color 'green))
(progn ;; non-winning player 1 move
(remove-items-from-exp-window *p1-win* (nth *p1-position* *spaces-1*) (nth index *spaces-1*))
(remove-items-from-exp-window *p2-win* (nth (- 5 *p2-position*) *spaces-2*)
(nth (- 5 *p1-position*) *spaces-2*) (nth (- 5 index) *spaces-2*))
(setf (nth *p1-position* *spaces-1*)
(add-button-to-exp-window *p1-win* :text "" :x (+ 10 (* *p1-position* 40)) :y 10
:height 35 :width 35 :color 'white))
(setf (nth index *spaces-1*)
(add-button-to-exp-window *p1-win* :text "1" :x (+ 10 (* index 40)) :y 10
:height 35 :width 35 :color 'white))
(setf (nth (- 5 *p2-position*) *spaces-2*)
(add-button-to-exp-window *p2-win* :text "1" :x (+ 10 (* (- 5 *p2-position*) 40)) :y 10
:height 35 :width 35 :color 'red))
(setf (nth (- 5 *p1-position*) *spaces-2*)
(add-button-to-exp-window *p2-win* :text "" :x (+ 10 (* (- 5 *p1-position*) 40)) :y 10
:action (list 'pick-button *p2* *p1-position*) :height 35 :width 35 :color 'white))
(setf (nth (- 5 index) *spaces-2*)
(add-button-to-exp-window *p2-win* :text "2" :x (+ 10 (* (- 5 index) 40)) :y 10
:action (list 'pick-button *p2* index) :height 35 :width 35 :color 'white))
(setf *p1-position* index)
(setf *current-player* *p2*))))
;; player 2 makes a valid move
(when (and (< index *p2-position*) (<= (- *p2-position* index) 2))
(if (<= index *p1-position*)
(progn ;; player 2 wins
;; give the models some time to process things before it stops
(schedule-break-relative 3)
(setf *game-over* *p2*)
(remove-items-from-exp-window *p2-win* (nth (- 5 *p2-position*) *spaces-2*) (nth (- 5 index) *spaces-2*))
(remove-items-from-exp-window *p1-win* (nth *p2-position* *spaces-1*) (nth index *spaces-1*))
(add-button-to-exp-window *p2-win* :text "" :x (+ 10 (* (- 5 *p2-position*) 40)) :y 10 :height 35 :width 35 :color 'white)
(add-button-to-exp-window *p2-win* :text "1" :x (+ 10 (* (- 5 index) 40)) :y 10 :height 35 :width 35 :color 'green)
(add-button-to-exp-window *p1-win* :text "" :x (+ 10 (* *p2-position* 40)) :y 10 :height 35 :width 35 :color 'white)
(add-button-to-exp-window *p1-win* :text "2" :x (+ 10 (* index 40)) :y 10 :height 35 :width 35 :color 'green))
(progn ;; non-winning player 2 move
(remove-items-from-exp-window *p2-win* (nth (- 5 *p2-position*) *spaces-2*) (nth (- 5 index) *spaces-2*))
(remove-items-from-exp-window *p1-win* (nth *p2-position* *spaces-1*)
(nth *p1-position* *spaces-1*) (nth index *spaces-1*))
(setf (nth (- 5 *p2-position*) *spaces-2*)
(add-button-to-exp-window *p2-win* :text "" :x (+ 10 (* (- 5 *p2-position*) 40)) :y 10
:height 35 :width 35 :color 'white))
(setf (nth (- 5 index) *spaces-2*)
(add-button-to-exp-window *p2-win* :text "1" :x (+ 10 (* (- 5 index) 40)) :y 10
:height 35 :width 35 :color 'white))
(setf (nth *p2-position* *spaces-1*)
(add-button-to-exp-window *p1-win* :text "" :x (+ 10 (* *p2-position* 40)) :y 10
:action (list 'pick-button *p1* *p2-position*) :height 35 :width 35 :color 'white))
(setf (nth *p1-position* *spaces-1*)
(add-button-to-exp-window *p1-win* :text "1" :x (+ 10 (* *p1-position* 40)) :y 10
:height 35 :width 35 :color 'red))
(setf (nth index *spaces-1*)
(add-button-to-exp-window *p1-win* :text "2" :x (+ 10 (* index 40)) :y 10
:action (list 'pick-button *p1* index) :height 35 :width 35 :color 'white))
(setf *p2-position* index)
(setf *current-player* *p1*)))))))
;; play one round of the game resetting models
;; before it starts. Player1 and player2 are the
;; names of models to run.
(defun play (player1 player2)
(when (every (lambda (x) (find x (mp-models))) (list player1 player2))
(reset)
(setf *p1* player1)
(setf *p2* player2)
(setf *game-over* nil)
(setf *current-player* player1)
(setf *p1-position* 0)
(setf *p2-position* 5)
(let ((p1-window (open-exp-window "player1" :visible t :width 300 :height 100 :x 100 :y 100))
(p2-window (open-exp-window "player2" :visible t :width 300 :height 100 :x 450 :y 100))
(safety-window (open-exp-window "safety" :visible t :width 100 :height 100 :x 100 :y 300)))
(setf *p1-win* p1-window)
(setf *p2-win* p2-window)
(add-button-to-exp-window safety-window :text "STOP" :x 0 :y 0 :action 'stop-a-run :height 80 :width 80 :color 'red)
(dotimes (i 6) ;; create the buttons
(setf (nth i *spaces-1*) ;; save them for later use
(let ((index i)) ;; need to bind the value of i to use in the action function
(add-button-to-exp-window p1-window :text (if (zerop i) "1" (if (= i 5) "2" ""))
:x (+ 10 (* i 40))
:y 10
:action (list 'pick-button player1 index) :height 35 :width 35 :color (if (zerop i) 'red 'white))))
(setf (nth i *spaces-2*) ;; save them for later use
(let ((index i)) ;; need to bind the value of i to use in the action function
(add-button-to-exp-window p2-window :text (if (zerop i) "1" (if (= i 5) "2" ""))
:x (+ 10 (* i 40))
:y 10
:action (list 'pick-button player2 (- 5 index)) :height 35 :width 35 :color 'white))))
(with-model-eval player1 ;; for first player
(install-device p1-window))
(with-model-eval player2 ;; same for player 2 but reverse the button positions
(install-device p2-window))
(run 10000 t)))
*game-over*)
#|
? (play 'model1 'model2)
0.000 MODEL1 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL2 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL1 VISION proc-display
0.000 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION0 NIL
0.000 MODEL1 VISION visicon-update
0.000 MODEL2 VISION proc-display
0.000 MODEL2 VISION visicon-update
0.000 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.000 MODEL1 PROCEDURAL PRODUCTION-SELECTED MY-TURN
0.000 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.000 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.000 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL1 PROCEDURAL PRODUCTION-FIRED MY-TURN
0.050 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.050 MODEL1 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.050 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.050 MODEL1 VISION Find-location
0.050 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION2
0.050 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL1 PROCEDURAL PRODUCTION-SELECTED MOVE
0.050 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.050 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.050 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.100 MODEL1 PROCEDURAL PRODUCTION-FIRED MOVE
0.100 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.100 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
0.100 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.100 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
0.100 MODEL1 MOTOR MOVE-CURSOR LOC VISUAL-LOCATION2-0
0.100 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.300 MODEL1 MOTOR PREPARATION-COMPLETE 0.1
0.300 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.350 MODEL1 MOTOR INITIATION-COMPLETE 0.1
0.350 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.590 MODEL1 MOUSE move-cursor MODEL1 mouse (168 128 1080)
0.590 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.640 MODEL1 MOTOR FINISH-MOVEMENT 0.1
0.640 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.640 MODEL1 PROCEDURAL PRODUCTION-SELECTED CLICK
0.640 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.640 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.690 MODEL1 PROCEDURAL PRODUCTION-FIRED CLICK
0.690 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.690 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
0.690 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
0.690 MODEL1 MOTOR CLICK-MOUSE
0.690 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.840 MODEL1 MOTOR PREPARATION-COMPLETE 0.69
0.840 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.890 MODEL1 MOTOR INITIATION-COMPLETE 0.69
0.890 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.900 MODEL1 MOUSE click-mouse MODEL1 (168 128 1080) INDEX
0.900 MODEL1 VISION proc-display
0.900 MODEL1 VISION visicon-update
0.900 MODEL2 VISION proc-display
0.900 MODEL2 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION8 NIL
0.900 MODEL2 VISION visicon-update
0.900 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.900 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.900 MODEL2 PROCEDURAL PRODUCTION-SELECTED MY-TURN
0.900 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.900 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.950 MODEL2 PROCEDURAL PRODUCTION-FIRED MY-TURN
0.950 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.950 MODEL2 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
0.950 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
0.950 MODEL2 VISION Find-location
0.950 MODEL2 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION3
0.950 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.950 MODEL2 PROCEDURAL PRODUCTION-SELECTED MOVE
0.950 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.950 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
0.950 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
0.990 MODEL1 MOTOR FINISH-MOVEMENT 0.69
0.990 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.000 MODEL2 PROCEDURAL PRODUCTION-FIRED MOVE
1.000 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.000 MODEL2 PROCEDURAL MODULE-REQUEST MANUAL
1.000 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
1.000 MODEL2 PROCEDURAL CLEAR-BUFFER MANUAL
1.000 MODEL2 MOTOR MOVE-CURSOR LOC VISUAL-LOCATION3-0
1.000 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.200 MODEL2 MOTOR PREPARATION-COMPLETE 1.0
1.200 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.250 MODEL2 MOTOR INITIATION-COMPLETE 1.0
1.250 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.651 MODEL2 MOUSE move-cursor MODEL2 mouse (558 128 1080)
1.651 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.701 MODEL2 MOTOR FINISH-MOVEMENT 1.0
1.701 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.701 MODEL2 PROCEDURAL PRODUCTION-SELECTED CLICK
1.701 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
1.701 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
1.751 MODEL2 PROCEDURAL PRODUCTION-FIRED CLICK
1.751 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.751 MODEL2 PROCEDURAL MODULE-REQUEST MANUAL
1.751 MODEL2 PROCEDURAL CLEAR-BUFFER MANUAL
1.751 MODEL2 MOTOR CLICK-MOUSE
1.751 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.901 MODEL2 MOTOR PREPARATION-COMPLETE 1.751
1.901 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.951 MODEL2 MOTOR INITIATION-COMPLETE 1.751
1.951 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.961 MODEL2 MOUSE click-mouse MODEL2 (558 128 1080) INDEX
1.961 MODEL2 VISION proc-display
1.961 MODEL2 VISION visicon-update
1.961 MODEL1 VISION proc-display
1.961 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION12 NIL
1.961 MODEL1 VISION visicon-update
1.961 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.961 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.961 MODEL1 PROCEDURAL PRODUCTION-SELECTED MY-TURN
1.961 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
1.961 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.011 MODEL1 PROCEDURAL PRODUCTION-FIRED MY-TURN
2.011 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.011 MODEL1 PROCEDURAL MODULE-REQUEST VISUAL-LOCATION
2.011 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.011 MODEL1 VISION Find-location
2.011 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION14
2.011 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.011 MODEL1 PROCEDURAL PRODUCTION-SELECTED MOVE
2.011 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
2.011 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.011 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
2.051 MODEL2 MOTOR FINISH-MOVEMENT 1.751
2.051 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.061 MODEL1 PROCEDURAL PRODUCTION-FIRED MOVE
2.061 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.061 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
2.061 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.061 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
2.061 MODEL1 MOTOR MOVE-CURSOR LOC VISUAL-LOCATION14-0
2.061 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.261 MODEL1 MOTOR PREPARATION-COMPLETE 2.061
2.261 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.311 MODEL1 MOTOR INITIATION-COMPLETE 2.061
2.311 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.459 MODEL1 MOUSE move-cursor MODEL1 mouse (248 128 1080)
2.459 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.509 MODEL1 MOTOR FINISH-MOVEMENT 2.061
2.509 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.509 MODEL1 PROCEDURAL PRODUCTION-SELECTED CLICK
2.509 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
2.509 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION MANUAL
2.559 MODEL1 PROCEDURAL PRODUCTION-FIRED CLICK
2.559 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.559 MODEL1 PROCEDURAL MODULE-REQUEST MANUAL
2.559 MODEL1 PROCEDURAL CLEAR-BUFFER MANUAL
2.559 MODEL1 MOTOR CLICK-MOUSE
2.559 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.709 MODEL1 MOTOR PREPARATION-COMPLETE 2.559
2.709 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.759 MODEL1 MOTOR INITIATION-COMPLETE 2.559
2.759 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.769 MODEL1 MOUSE click-mouse MODEL1 (248 128 1080) INDEX
2.769 MODEL1 VISION proc-display
2.769 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION17 NIL
2.769 MODEL1 VISION visicon-update
2.769 MODEL2 VISION proc-display
2.769 MODEL2 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION17 NIL
2.769 MODEL2 VISION visicon-update
2.769 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.769 MODEL1 PROCEDURAL PRODUCTION-SELECTED GAME-OVER
2.769 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
2.769 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.769 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
2.769 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.769 MODEL2 PROCEDURAL PRODUCTION-SELECTED GAME-OVER
2.769 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
2.769 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.769 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
2.819 MODEL1 PROCEDURAL PRODUCTION-FIRED GAME-OVER
2.819 MODEL1 PROCEDURAL MODULE-REQUEST VISUAL
2.819 MODEL1 PROCEDURAL CLEAR-BUFFER GOAL
2.819 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.819 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL
2.819 MODEL2 PROCEDURAL PRODUCTION-FIRED GAME-OVER
2.819 MODEL2 PROCEDURAL MODULE-REQUEST VISUAL
2.819 MODEL2 PROCEDURAL CLEAR-BUFFER GOAL
2.819 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.819 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL
2.819 MODEL1 VISION Move-attention VISUAL-LOCATION17-0 NIL
2.819 MODEL2 VISION Move-attention VISUAL-LOCATION17-0 NIL
2.819 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.819 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.859 MODEL1 MOTOR FINISH-MOVEMENT 2.559
2.859 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.904 MODEL1 VISION Encoding-complete VISUAL-LOCATION17-0 NIL
2.904 MODEL1 VISION SET-BUFFER-CHUNK VISUAL OVAL0
2.904 MODEL2 VISION Encoding-complete VISUAL-LOCATION17-0 NIL
2.904 MODEL2 VISION SET-BUFFER-CHUNK VISUAL OVAL0
2.904 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.904 MODEL2 PROCEDURAL PRODUCTION-SELECTED REPORT-LOSE
2.904 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL
2.904 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.904 MODEL1 PROCEDURAL PRODUCTION-SELECTED REPORT-WIN
2.904 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL
2.954 MODEL2 PROCEDURAL PRODUCTION-FIRED REPORT-LOSE
I LOSE
2.954 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL
2.954 MODEL1 PROCEDURAL PRODUCTION-FIRED REPORT-WIN
I WIN
2.954 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL
2.954 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.954 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
5.769 ------ ------ BREAK-EVENT
MODEL1
|#
| 23,264 | Common Lisp | .lisp | 337 | 57.991098 | 138 | 0.568231 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 498dd6657cb17807cf5795bc424267b5584cd4ee2a4825a97ce87fa3edf85ecc | 14,193 | [
-1
] |
14,194 | models.lisp | asmaloney_ACT-R/examples/model-task-interfacing/no-windows-goal-mod/models.lisp |
(clear-all)
;; Create one copy of the model code using defparameter.
;; The model is told its position in the my-pos slot and
;; can use that to access the value.
(defparameter *model-code*
;; A list of information just like one would put in a
;; define-model call.
'((sgp :v t :trace-detail high :er t)
(chunk-type play my-pos p1 p2 state result)
(define-chunks move win lose p1 p2 game-over)
;; Avoid any warnings about slot usage in the goal
;; buffer since the slots are being set in code
(declare-buffer-usage goal play :all)
(p 1-step
=goal>
my-pos =me
=me =pos
state move
==>
!output! (I am at position =pos)
;; call the function to take the action
!eval! ("make-move" 1)
-goal>)
(p 2-step
=goal>
my-pos =me
=me =pos
state move
==>
!output! (I am at position =pos)
;; call the function to take the action
!eval! ("make-move" 2)
-goal>)
(p result
=goal>
result =r
state game-over
==>
!output! (I =r)
-goal>)))
;; Use the define-model function to create models named
;; model1 and model2 each using the same definition code.
(define-model-fct 'model1 *model-code*)
(define-model-fct 'model2 *model-code*)
| 1,452 | Common Lisp | .lisp | 44 | 24.227273 | 58 | 0.588546 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 568a631c93374bc0a1fc682e4f1cd70cc2a1149306830ea3ba697410753e05f6 | 14,194 | [
207827
] |
14,195 | game.lisp | asmaloney_ACT-R/examples/model-task-interfacing/no-windows-goal-mod/game.lisp | ;; Play the simple capture game with 2 models using no interface.
;; Goal chunk holds all information and state indicates what to do (if set).
;; Creates new goal chunks everytime instead of checking and modifying.
;; (chunk-type play my-pos p1 p2 state result)
;; My-pos is either p1 or p2 to indicate which player
;; p1 and p2 slots hold current position for that player
;; State slot will be move or game-over
;; Result will be win or lose
;;
;; Assumes models interact appropriately so as to not
;; have problems with goal chunks being modified:
;; - only do something on its own turn
;; - stop doing everything once it makes the move
;; global variables for game info
(defvar *current-player*) ; name of the model
(defvar *p1*) ; player1 model name
(defvar *p2*) ; player2 model name
(defvar *game-over*) ; If true stop the game
(defvar *next-move*) ; action made by a player
(defvar *p1-position*) ; current player spots 0-5
(defvar *p2-position*)
;; function called directly by a model to make a move of dist spaces
;; Just schedule a call to a function that actually handles that after
;; everything else the model needs to do at this time.
(defun make-move (dist)
(when (eq (current-model) *current-player*)
(setf *next-move* dist)
(schedule-break-relative 0 :priority :min)))
;; Actually update the models' goal chunks as needed
(defun process-move (dist)
(let ((forfeit nil)
(winner nil))
(if (numberp dist)
(if (eq *current-player* *p1*) ; update the position
(incf *p1-position* dist)
(decf *p2-position* dist))
(setf forfeit *current-player*))
(cond ((or forfeit (<= *p2-position* *p1-position*)) ; the game is over
(if forfeit
(setf winner (if (eq *p1* *current-player*) *p2* *p1*))
(setf winner *current-player*))
(setf *game-over* winner)
;; create new chunks with the results
(with-model-eval *p1*
(goal-focus-fct (first (define-chunks-fct
(list (list 'isa 'play 'my-pos 'p1 'p1 *p1-position* 'p2 *p2-position* 'state 'game-over
'result (if (eq *p1* winner) 'win 'lose)))))))
;; update player 2 goal
(with-model-eval *p2*
(goal-focus-fct (first (define-chunks-fct
(list (list 'isa 'play 'my-pos 'p2 'p1 *p1-position* 'p2 *p2-position* 'state 'game-over
'result (if (eq *p2* winner) 'win 'lose))))))))
((eq *current-player* *p1*) ;; player 1 moved so update player 2 goal
(with-model-eval *p2*
(goal-focus-fct (car (define-chunks-fct
(list (list 'isa 'play 'my-pos 'p2 'p1 *p1-position* 'p2 *p2-position* 'state 'move))))))
(setf *current-player* *p2*))
(t ;; player 2 moved so update player 1 goal
(with-model-eval *p1*
(goal-focus-fct (car (define-chunks-fct
(list (list 'isa 'play 'my-pos 'p1 'p1 *p1-position* 'p2 *p2-position* 'state 'move))))))
(setf *current-player* *p1*)))))
;; play one round of the game resetting the models
;; before it starts. Player1 and player2 are the
;; names of the models to run in the indicated
;; position.
(defun play (player1 player2)
;make sure that both names are valid model names
(when (every (lambda (x) (find x (mp-models))) (list player1 player2))
(add-act-r-command "make-move" 'make-move "Model action function in simple capture game.")
(reset)
; For the players create the goal chunks
(with-model-eval player1
(define-chunks
(goal isa play my-pos p1 p1 0 p2 5 state move))
(goal-focus goal))
(with-model-eval player2
(define-chunks
(goal isa play my-pos p2 p1 0 p2 5))
(goal-focus goal))
;; initialize the game information
(setf *p1* player1)
(setf *p2* player2)
(setf *p1-position* 0)
(setf *p2-position* 5)
(setf *game-over* nil)
(setf *current-player* player1)
(setf *next-move* nil)
(while (not *game-over*)
;; until a move is made which breaks the run
;; or 1000 simulated seconds pass which is a forfeit
(run 1000)
(process-move *next-move*))
;; Give them a chance to process results
(run-full-time 3)
(remove-act-r-command "make-move")
;; return the winner
*game-over*))
#|
? (play 'model1 'model2)
0.000 MODEL1 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL2 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.000 MODEL1 PROCEDURAL PRODUCTION-SELECTED 2-STEP
0.000 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.000 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL1 PROCEDURAL PRODUCTION-FIRED 2-STEP
I AM AT POSITION 0
0.050 MODEL1 PROCEDURAL CLEAR-BUFFER GOAL
0.050 ------ ------ BREAK-EVENT
0.050 MODEL2 GOAL SET-BUFFER-CHUNK GOAL PLAY0 NIL
0.050 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.050 MODEL2 PROCEDURAL PRODUCTION-SELECTED 2-STEP
0.050 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.100 MODEL2 PROCEDURAL PRODUCTION-FIRED 2-STEP
I AM AT POSITION 5
0.100 MODEL2 PROCEDURAL CLEAR-BUFFER GOAL
0.100 ------ ------ BREAK-EVENT
0.100 MODEL1 GOAL SET-BUFFER-CHUNK GOAL PLAY0 NIL
0.100 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.100 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.100 MODEL1 PROCEDURAL PRODUCTION-SELECTED 2-STEP
0.100 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.150 MODEL1 PROCEDURAL PRODUCTION-FIRED 2-STEP
I AM AT POSITION 2
0.150 MODEL1 PROCEDURAL CLEAR-BUFFER GOAL
0.150 ------ ------ BREAK-EVENT
0.150 MODEL1 GOAL SET-BUFFER-CHUNK GOAL PLAY1 NIL
0.150 MODEL2 GOAL SET-BUFFER-CHUNK GOAL PLAY1 NIL
0.150 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.150 MODEL1 PROCEDURAL PRODUCTION-SELECTED RESULT
0.150 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.150 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.150 MODEL2 PROCEDURAL PRODUCTION-SELECTED RESULT
0.150 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.200 MODEL1 PROCEDURAL PRODUCTION-FIRED RESULT
I WIN
0.200 MODEL1 PROCEDURAL CLEAR-BUFFER GOAL
0.200 MODEL2 PROCEDURAL PRODUCTION-FIRED RESULT
I LOSE
0.200 MODEL2 PROCEDURAL CLEAR-BUFFER GOAL
0.200 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.200 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
3.150 - ------ Stopped because time limit reached
MODEL1
|#
| 7,559 | Common Lisp | .lisp | 147 | 42.959184 | 128 | 0.594531 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 42683a7970f817b2cd590e618139af6105d847de10c35c490d347d767e47ebb9 | 14,195 | [
219204
] |
14,196 | models.lisp | asmaloney_ACT-R/examples/model-task-interfacing/one-window-text-talking/models.lisp | (clear-all)
(defparameter *model-code*
'((sgp :v t :trace-detail high :needs-mouse nil :er t)
(chunk-type play my-color my-name state)
(set-audloc-default - location self :attended nil)
(set-visloc-default color green)
(define-chunks move say-done start)
(declare-buffer-usage goal play :all)
(p game-over
=visual-location>
?visual>
state free
==>
+visual>
cmd move-attention
screen-pos =visual-location)
(p winner
=goal>
my-name =name
=visual>
value =name
==>
-goal>
!output! (I am the winner))
(p loser
=goal>
my-name =name
=visual>
- value =name
value =winner
==>
-goal>
!output! (=winner was the winner))
(p hear-something
=goal>
=aural-location>
?aural>
state free
==>
+aural>
event =aural-location)
(p I-start
=goal>
my-name =name
=aural>
content =name
==>
=goal>
state move)
(p other-player-starts
=goal>
my-name =name
=aural>
- content =name
- content "one"
- content "two"
==>
)
(p other-player-went-one
=goal>
=aural>
content "one"
==>
=goal>
state move)
(p other-player-went-two
=goal>
=aural>
content "two"
==>
=goal>
state move)
(p 1-step
=goal>
state move
?vocal>
state free
==>
+vocal>
cmd speak
string "one"
=goal>
state nil)
(p 2-step
=goal>
state move
?vocal>
state free
==>
+vocal>
cmd speak
string "two"
=goal>
state nil)
))
(define-model-fct 'model1 *model-code*)
(define-model-fct 'model2 *model-code*)
| 2,371 | Common Lisp | .lisp | 97 | 12.659794 | 59 | 0.425047 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | ac00c4422b8ebea74d3b72f770feb69036163591086f2f9e22e3977d6bbeadb1 | 14,196 | [
-1
] |
14,197 | game.lisp | asmaloney_ACT-R/examples/model-task-interfacing/one-window-text-talking/game.lisp |
;;; Play the capture game with a simple single interface that
;;; just shows position. Have models say "one" or "two" to indicate
;;; their move and the game says the starting player's name at
;;; the beginning. Show the winner's name in green when game over.
;; global variables
(defvar *current-player*) ;; model name
(defvar *p1*) ;; player names
(defvar *p2*)
(defvar *game-over*) ;; true means stop game
(defvar *p1-position*) ;; player positions
(defvar *p2-position*)
(defvar *p1-text*) ;; text items on the screen
(defvar *p2-text*) ;; for player positions
(defvar *window*) ;; the interface window
(defvar *safety-stop*) ;; flag that modeler wants run to stop
(defun stop-a-run ()
(setf *safety-stop* t))
(defun set-game-over (player)
(setf *game-over* player))
(defun game-over (time)
(or *safety-stop* *game-over* (> time 1000000)))
;; the method that gets called when a model speaks
;; assume that models take turns appropriately
(defun process-moves (model string)
;; Let all other models hear this
(dolist (m (mp-models))
(unless (eq model m) ; for everyone but the originator
(with-model-eval m ; make the other model the current-model
;; Create the originating model's name as a simple chunk if
;; it isn't one already to avoid a warning of it being
;; created by default when the sound is generated.
(unless (chunk-p-fct model)
(define-chunks-fct (list model)))
;; Create the sound as a word with location indicating
;; the speaker.
(new-word-sound string (mp-time) model))))
(let ((move (cond ((string-equal string "one") 1)
((string-equal string "two") 2)
(t 1))))
;; update the position
(if (eq *current-player* *p1*)
(incf *p1-position* move)
(decf *p2-position* move))
(clear-exp-window *window*)
(if (<= *p2-position* *p1-position*)
;; if there's a winner
(progn
;; set the winning player
(schedule-event-relative 3 'set-game-over :params (list *current-player*))
;; display the winner
(add-text-to-exp-window *window* (string *current-player*) :x 60 :y 20 :color 'green :height 30 :width 80 :font-size 20))
(progn
;; not a winner so update the display with the new position
(setf *p1-text* (add-text-to-exp-window *window* (princ-to-string *p1-position*) :x 20 :y 10 :color 'red :height 30 :width 30 :font-size 20))
(setf *p2-text* (add-text-to-exp-window *window* (princ-to-string *p2-position*) :x 140 :y 10 :color 'blue :height 30 :width 30 :font-size 20))
(if (eq *current-player* *p1*)
(setf *current-player* *p2*)
(setf *current-player* *p1*))))))
;; Function to play one game resetting the models
;; before it starts. Player1 and player2 are model
;; names.
(defun play (player1 player2)
(when (every (lambda (x) (find x (mp-models))) (list player1 player2))
(reset)
(with-model-eval player1
;; create a goal chunk with the player's color and name
(define-chunks-fct (list (list 'goal 'isa 'play 'my-color 'red 'my-name (string player1))))
(goal-focus goal)
(set-parameter-value :show-focus 'red))
(with-model-eval player2
;; create a goal chunk with the player's color and name
(define-chunks-fct (list (list 'goal 'isa 'play 'my-color 'blue 'my-name (string player2))))
(goal-focus goal)
(set-parameter-value :show-focus 'blue))
;; initialize some game info
(setf *p1* player1)
(setf *p2* player2)
(setf *game-over* nil)
(setf *current-player* player1)
(setf *safety-stop* nil)
(setf *p1-position* 0)
(setf *p2-position* 5)
(let ((window (open-exp-window "game" :visible t :width 200 :height 100))
(safety-window (open-exp-window "safety" :visible t :width 100 :height 100 :x 100 :y 100)))
(add-button-to-exp-window safety-window :text "STOP" :x 0 :y 0 :action 'stop-a-run :x 80 :y 80 :color 'red)
(setf *window* window)
;; install that as the device for all models
(dolist (m (mp-models))
(with-model-eval m
(install-device window)))
(setf *p1-text* (add-text-to-exp-window window (princ-to-string *p1-position*) :x 20 :y 10 :color 'red :height 30 :width 30 :font-size 20))
(setf *p2-text* (add-text-to-exp-window window (princ-to-string *p2-position*) :x 140 :y 10 :color 'blue :height 30 :width 30 :font-size 20))
(add-act-r-command "process-moves" 'process-moves "Handle player speak actions")
(monitor-act-r-command "output-speech" "process-moves")
;; speak to all models telling them the name
;; of the first player.
(dolist (m (mp-models))
(with-model-eval m
(new-word-sound (string *p1*) 0 'start))))
(run-until-condition 'game-over t)
(remove-act-r-command-monitor "output-speech" "process-moves")
(remove-act-r-command "process-moves"))
*game-over*)
#|
? (play 'model1 'model2)
0.000 MODEL1 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL2 GOAL SET-BUFFER-CHUNK GOAL GOAL NIL
0.000 MODEL1 AUDIO new-sound
0.000 MODEL2 AUDIO new-sound
0.000 MODEL2 VISION proc-display
0.000 MODEL2 VISION visicon-update
0.000 MODEL1 VISION proc-display
0.000 MODEL1 VISION visicon-update
0.000 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.000 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.300 MODEL1 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT0 NIL
0.300 MODEL2 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT0 NIL
0.300 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.300 MODEL1 PROCEDURAL PRODUCTION-SELECTED HEAR-SOMETHING
0.300 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.300 MODEL1 PROCEDURAL BUFFER-READ-ACTION AURAL-LOCATION
0.300 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION AURAL
0.300 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.300 MODEL2 PROCEDURAL PRODUCTION-SELECTED HEAR-SOMETHING
0.300 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.300 MODEL2 PROCEDURAL BUFFER-READ-ACTION AURAL-LOCATION
0.300 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION AURAL
0.350 MODEL1 PROCEDURAL PRODUCTION-FIRED HEAR-SOMETHING
0.350 MODEL1 PROCEDURAL MODULE-REQUEST AURAL
0.350 MODEL1 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
0.350 MODEL1 PROCEDURAL CLEAR-BUFFER AURAL
0.350 MODEL2 PROCEDURAL PRODUCTION-FIRED HEAR-SOMETHING
0.350 MODEL2 PROCEDURAL MODULE-REQUEST AURAL
0.350 MODEL2 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
0.350 MODEL2 PROCEDURAL CLEAR-BUFFER AURAL
0.350 MODEL1 AUDIO ATTEND-SOUND AUDIO-EVENT0-0
0.350 MODEL2 AUDIO ATTEND-SOUND AUDIO-EVENT0-0
0.350 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.350 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.500 MODEL1 AUDIO AUDIO-ENCODING-COMPLETE AUDIO-EVENT0
0.500 MODEL2 AUDIO AUDIO-ENCODING-COMPLETE AUDIO-EVENT0
0.500 MODEL1 AUDIO SET-BUFFER-CHUNK AURAL WORD0
0.500 MODEL2 AUDIO SET-BUFFER-CHUNK AURAL WORD0
0.500 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.500 MODEL1 PROCEDURAL PRODUCTION-SELECTED I-START
0.500 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.500 MODEL1 PROCEDURAL BUFFER-READ-ACTION AURAL
0.500 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.500 MODEL2 PROCEDURAL PRODUCTION-SELECTED OTHER-PLAYER-STARTS
0.500 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
0.500 MODEL2 PROCEDURAL BUFFER-READ-ACTION AURAL
0.550 MODEL1 PROCEDURAL PRODUCTION-FIRED I-START
0.550 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.550 MODEL1 PROCEDURAL CLEAR-BUFFER AURAL
0.550 MODEL2 PROCEDURAL PRODUCTION-FIRED OTHER-PLAYER-STARTS
0.550 MODEL2 PROCEDURAL CLEAR-BUFFER AURAL
0.550 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.550 MODEL1 PROCEDURAL PRODUCTION-SELECTED 2-STEP
0.550 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
0.550 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION VOCAL
0.550 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.600 MODEL1 PROCEDURAL PRODUCTION-FIRED 2-STEP
0.600 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
0.600 MODEL1 PROCEDURAL MODULE-REQUEST VOCAL
0.600 MODEL1 PROCEDURAL CLEAR-BUFFER VOCAL
0.600 MODEL1 SPEECH SPEAK TEXT two
0.600 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.750 MODEL1 SPEECH PREPARATION-COMPLETE 0.6
0.750 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.800 MODEL1 SPEECH INITIATION-COMPLETE 0.6
0.800 MODEL1 AUDIO new-sound
0.800 MODEL1 MICROPHONE output-speech MODEL1 two
0.800 MODEL2 AUDIO new-sound
0.800 MODEL2 VISION proc-display
0.800 MODEL2 VISION visicon-update
0.800 MODEL1 VISION proc-display
0.800 MODEL1 VISION visicon-update
0.800 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
0.800 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
0.950 MODEL1 SPEECH FINISH-MOVEMENT 0.6
0.950 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.100 MODEL2 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT1 NIL
1.100 MODEL1 AUDIO find-sound-failure
1.100 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.100 MODEL2 PROCEDURAL PRODUCTION-SELECTED HEAR-SOMETHING
1.100 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
1.100 MODEL2 PROCEDURAL BUFFER-READ-ACTION AURAL-LOCATION
1.100 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION AURAL
1.100 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.150 MODEL2 PROCEDURAL PRODUCTION-FIRED HEAR-SOMETHING
1.150 MODEL2 PROCEDURAL MODULE-REQUEST AURAL
1.150 MODEL2 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
1.150 MODEL2 PROCEDURAL CLEAR-BUFFER AURAL
1.150 MODEL2 AUDIO ATTEND-SOUND AUDIO-EVENT1-0
1.150 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.225 MODEL2 AUDIO AUDIO-ENCODING-COMPLETE AUDIO-EVENT1
1.225 MODEL2 AUDIO SET-BUFFER-CHUNK AURAL WORD1
1.225 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.225 MODEL2 PROCEDURAL PRODUCTION-SELECTED OTHER-PLAYER-WENT-TWO
1.225 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
1.225 MODEL2 PROCEDURAL BUFFER-READ-ACTION AURAL
1.275 MODEL2 PROCEDURAL PRODUCTION-FIRED OTHER-PLAYER-WENT-TWO
1.275 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.275 MODEL2 PROCEDURAL CLEAR-BUFFER AURAL
1.275 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.275 MODEL2 PROCEDURAL PRODUCTION-SELECTED 2-STEP
1.275 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
1.275 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION VOCAL
1.325 MODEL2 PROCEDURAL PRODUCTION-FIRED 2-STEP
1.325 MODEL2 PROCEDURAL MOD-BUFFER-CHUNK GOAL
1.325 MODEL2 PROCEDURAL MODULE-REQUEST VOCAL
1.325 MODEL2 PROCEDURAL CLEAR-BUFFER VOCAL
1.325 MODEL2 SPEECH SPEAK TEXT two
1.325 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.475 MODEL2 SPEECH PREPARATION-COMPLETE 1.325
1.475 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.525 MODEL2 SPEECH INITIATION-COMPLETE 1.325
1.525 MODEL2 AUDIO new-sound
1.525 MODEL2 MICROPHONE output-speech MODEL2 two
1.525 MODEL1 AUDIO new-sound
1.525 MODEL2 VISION proc-display
1.525 MODEL2 VISION visicon-update
1.525 MODEL1 VISION proc-display
1.525 MODEL1 VISION visicon-update
1.525 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.525 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.675 MODEL2 SPEECH FINISH-MOVEMENT 1.325
1.675 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.825 MODEL1 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT2 NIL
1.825 MODEL2 AUDIO find-sound-failure
1.825 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.825 MODEL1 PROCEDURAL PRODUCTION-SELECTED HEAR-SOMETHING
1.825 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
1.825 MODEL1 PROCEDURAL BUFFER-READ-ACTION AURAL-LOCATION
1.825 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION AURAL
1.825 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
1.875 MODEL1 PROCEDURAL PRODUCTION-FIRED HEAR-SOMETHING
1.875 MODEL1 PROCEDURAL MODULE-REQUEST AURAL
1.875 MODEL1 PROCEDURAL CLEAR-BUFFER AURAL-LOCATION
1.875 MODEL1 PROCEDURAL CLEAR-BUFFER AURAL
1.875 MODEL1 AUDIO ATTEND-SOUND AUDIO-EVENT2-0
1.875 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.950 MODEL1 AUDIO AUDIO-ENCODING-COMPLETE AUDIO-EVENT2
1.950 MODEL1 AUDIO SET-BUFFER-CHUNK AURAL WORD2
1.950 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
1.950 MODEL1 PROCEDURAL PRODUCTION-SELECTED OTHER-PLAYER-WENT-TWO
1.950 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
1.950 MODEL1 PROCEDURAL BUFFER-READ-ACTION AURAL
2.000 MODEL1 PROCEDURAL PRODUCTION-FIRED OTHER-PLAYER-WENT-TWO
2.000 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.000 MODEL1 PROCEDURAL CLEAR-BUFFER AURAL
2.000 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.000 MODEL1 PROCEDURAL PRODUCTION-SELECTED 1-STEP
2.000 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
2.000 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION VOCAL
2.050 MODEL1 PROCEDURAL PRODUCTION-FIRED 1-STEP
2.050 MODEL1 PROCEDURAL MOD-BUFFER-CHUNK GOAL
2.050 MODEL1 PROCEDURAL MODULE-REQUEST VOCAL
2.050 MODEL1 PROCEDURAL CLEAR-BUFFER VOCAL
2.050 MODEL1 SPEECH SPEAK TEXT one
2.050 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.150 MODEL1 SPEECH PREPARATION-COMPLETE 2.05
2.150 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.200 MODEL1 SPEECH INITIATION-COMPLETE 2.05
2.200 MODEL1 AUDIO new-sound
2.200 MODEL1 MICROPHONE output-speech MODEL1 one
2.200 MODEL2 AUDIO new-sound
2.200 MODEL2 VISION proc-display
2.200 MODEL2 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION6 NIL
2.200 MODEL2 VISION visicon-update
2.200 MODEL1 VISION proc-display
2.200 MODEL1 VISION SET-BUFFER-CHUNK VISUAL-LOCATION VISUAL-LOCATION6 NIL
2.200 MODEL1 VISION visicon-update
2.200 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.200 MODEL1 PROCEDURAL PRODUCTION-SELECTED GAME-OVER
2.200 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.200 MODEL1 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
2.200 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.200 MODEL2 PROCEDURAL PRODUCTION-SELECTED GAME-OVER
2.200 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL-LOCATION
2.200 MODEL2 PROCEDURAL QUERY-BUFFER-ACTION VISUAL
2.250 MODEL1 PROCEDURAL PRODUCTION-FIRED GAME-OVER
2.250 MODEL1 PROCEDURAL MODULE-REQUEST VISUAL
2.250 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.250 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL
2.250 MODEL2 PROCEDURAL PRODUCTION-FIRED GAME-OVER
2.250 MODEL2 PROCEDURAL MODULE-REQUEST VISUAL
2.250 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL-LOCATION
2.250 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL
2.250 MODEL1 VISION Move-attention VISUAL-LOCATION6-0 NIL
2.250 MODEL2 VISION Move-attention VISUAL-LOCATION6-0 NIL
2.250 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.250 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.335 MODEL1 VISION Encoding-complete VISUAL-LOCATION6-0 NIL
2.335 MODEL1 VISION SET-BUFFER-CHUNK VISUAL TEXT0
2.335 MODEL2 VISION Encoding-complete VISUAL-LOCATION6-0 NIL
2.335 MODEL2 VISION SET-BUFFER-CHUNK VISUAL TEXT0
2.335 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.335 MODEL1 PROCEDURAL PRODUCTION-SELECTED WINNER
2.335 MODEL1 PROCEDURAL BUFFER-READ-ACTION GOAL
2.335 MODEL1 PROCEDURAL BUFFER-READ-ACTION VISUAL
2.335 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.335 MODEL2 PROCEDURAL PRODUCTION-SELECTED LOSER
2.335 MODEL2 PROCEDURAL BUFFER-READ-ACTION GOAL
2.335 MODEL2 PROCEDURAL BUFFER-READ-ACTION VISUAL
2.350 MODEL1 SPEECH FINISH-MOVEMENT 2.05
2.385 MODEL1 PROCEDURAL PRODUCTION-FIRED WINNER
I AM THE WINNER
2.385 MODEL1 PROCEDURAL CLEAR-BUFFER GOAL
2.385 MODEL1 PROCEDURAL CLEAR-BUFFER VISUAL
2.385 MODEL2 PROCEDURAL PRODUCTION-FIRED LOSER
"MODEL1" WAS THE WINNER
2.385 MODEL2 PROCEDURAL CLEAR-BUFFER GOAL
2.385 MODEL2 PROCEDURAL CLEAR-BUFFER VISUAL
2.385 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.385 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
2.500 MODEL2 AUDIO SET-BUFFER-CHUNK AURAL-LOCATION AUDIO-EVENT3 NIL
2.500 MODEL1 AUDIO find-sound-failure
2.500 MODEL1 PROCEDURAL CONFLICT-RESOLUTION
2.500 MODEL2 PROCEDURAL CONFLICT-RESOLUTION
5.200 MODEL1 NONE SET-GAME-OVER MODEL1
5.200 - ------ Stopped because condition is true
MODEL1
|#
| 19,852 | Common Lisp | .lisp | 324 | 54.685185 | 151 | 0.605772 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2002fef418895e00e01cfe8c5188dd59faad57b0e24bba213713b5c4a891fb02 | 14,197 | [
-1
] |
14,198 | game-of-life.lisp | asmaloney_ACT-R/examples/other/game-of-life.lisp | ;;; This example shows the ACT-R software being used as a general
;;; programming tool instead of as a model of human cognition by
;;; creating a model that encapsulates the rules for a single cell
;;; in Conway's Game of Life and then creating many cells each
;;; using that model to play the game.
;;;
;;; While this isn't the intended purpose of the software, it
;;; does demonstrate some of the more advanced operations of the
;;; software which one may need when creating tasks for cognitive
;;; models. The operations used to run this task include working
;;; with more than one model at a time, creating arbitrary percepts,
;;; modifying AGI elements as the system runs, and using an arbitrary
;;; real-time clock to provide the current time for a model (an
;;; absolute clock instead of an interval clock).
;;;
;;; The default display uses an AGI window to display a grid of buttons
;;; with a red button indicating a cell which is on and a gray button
;;; one which is off. In that display there is also a button labeled
;;; "stop" which if pressed while ACT-R is running will schedule a
;;; break event to stop the run.
;;;
;;;
;;; To run the game call run-game and it requires two parameters which
;;; are the width and height of the board in cells:
;;;
;;; (run-game 10 10)
;;;
;;; That will run the game with a randomly generated starting state
;;; for 10 seconds with one cycle per second displayed (after the
;;; initial initialization of the display and all of the models
;;; which takes a little time).
;;;
;;; On my machine up to about 200 cells can run at a rate of
;;; one update per second with the graphic display through the
;;; ACT-R Environment, but performance will vary for many reasons.
;;;
;;; To continue running it you can just call run-full-time again
;;; with the number of cycles to display (it always uses one cycle
;;; per second of model time) and must include the real-time flag
;;; since the game's real-time clock controls the updating:
;;;
;;; (run-full-time 10 t)
;;;
;;; It's also possible to specify a longer or shorter initial number
;;; of cycles to show using the :cycles keyword parameter:
;;;
;;; (run-game 10 10 :cycles 15)
;;;
;;; Would run the game for 15 cycles before stopping.
;;;
;;; Similarly, the display rate can be changed. The default is to
;;; wait one second per cycle drawn, but specifying the :spc keyword
;;; parameter allows you to change that. This would draw a new
;;; cycle every 2 seconds:
;;;
;;; (run-game 10 10 :spc 2)
;;;
;;; and this would draw 4 new cycles every second (assuming that
;;; the system can run that fast):
;;;
;;; (run-game 10 10 :spc .25)
;;;
;;;
;;; A text only option can also be run by providing the :text
;;; keyword parameter with a true value.
;;;
;;; (run-game 10 10 :text t)
;;;
;;; That will draw the board to the command-trace assuming a fixed
;;; width font with a * for on and space for off:
#|
____________
|** ** |
| * * |
| *** **|
|* * *|
| * * *|
| * |
| ** |
| ** * |
| * * |
| * ** **|
------------
|#
;;; The default game starts with a random distribution
;;; of on cells where the probability of a cell being on
;;; can be specified by the :p parameter to run-game. The
;;; default p is .25:
;;;
;;; (run-game 10 10 :p .5)
;;;
;;; Finally, it is possible to manually configure the starting
;;; board when using the graphic representation by specifying
;;; the :setup parameter as t:
;;;
;;; (run-game 10 10 :setup t)
;;;
;;; When that happens a random board will be generated, but
;;; the user can click on the cells to toggle them. When
;;; you are ready to run the model with the cell configuration
;;; created press the "done" button on the display.
;;; If one wants to setup initial states it can be useful to
;;; also specify :p as 0 or 1 to start with a board that is
;;; either all off or all on respectively.
;;;
;;;
;;; The models which control the cells are provided with
;;; a visual-location chunk that contains their current
;;; state and how many neighbors they have, and they use
;;; buffer stuffing to always get the new chunk when the
;;; game updates. Each must respond vocally saying either
;;; "on" to turn on its cell, "off" to turn its cell off,
;;; or anything else to remain in the same state. Once
;;; all models have spoken their new status the game will
;;; advance the clock to the next cycle once the requested
;;; cycle time has passed (or immediately if it passed
;;; before all the models responced).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The code which implements the models that control the cells.
;;; Specified in a list so that multiple instances of the same
;;; model can easily be generated.
(defparameter *model-code*
'((sgp :v nil)
;; Install a microphone so their speech output can
;; be detected.
(install-device '("speech" "microphone"))
;; Set the constraints for stuffing the visual-location
;; buffer to be any chunk in the visicon since the default
;; is :attended new which means it'd eventually stop stuffing
;; the chunk once it was no longer "new".
(set-visloc-default isa visual-location)
;; Create a new chunk-type for the cell information
;; which will use the x and y slots for position instead
;; of screen-x and screen-y (it will still have a distance
;; and size created by default).
(chunk-type cell state neighbors x y)
;; The productions to encode the rules of the game.
(p lonely
"On with less than 2 neighbors turns off"
=visual-location>
state t
< neighbors 2
?vocal>
state free
==>
+vocal>
isa speak
string "off")
(p overcrowded
"On with more than 3 neighbors turns off"
=visual-location>
state t
> neighbors 3
?vocal>
state free
==>
+vocal>
isa speak
string "off")
(p born
"Off with 3 neighbors turns on"
=visual-location>
state nil
neighbors 3
?vocal>
state free
==>
+vocal>
isa speak
string "on")
(p good
"On with 2 or 3 neighbors stays on (does nothing)"
=visual-location>
state t
>= neighbors 2
<= neighbors 3
?vocal>
state free
==>
+vocal>
isa speak
string "same")
(p remain-dorment
"Off without 3 neighbors stays off"
=visual-location>
state nil
- neighbors 3
?vocal>
state free
==>
+vocal>
isa speak
string "same")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Code to implement the task.
;;;
;;; Structures to hold the details of the board and each cell.
;;; The board holds the overall game info and has a lock for
;;; protecting the contents. The lock is not technically necessary
;;; at this point since all of the code is only called from scheduler
;;; activity after things start running and at this point the
;;; scheduler is a serial system, but it is still the "safe" thing
;;; to do and at some point the scheduler will allow parallel
;;; operations and that could be used to improve the performance
;;; of something like this -- if it is safe to do so.
;;;
(defstruct gol-board height width cells model->cell responses total cycle (lock (bt:make-lock "gol-lock")))
;;; The cell structure holds the current state of the cell, the model's
;;; update for the current cycle, and all of the related items necessay:
;;; the model, visual feature, and button.
(defstruct gol-cell state change button feature model)
;;; Store the board globally for convenience.
(defvar *board*)
;;; Record the model's vocal response as the action to take this step
;;; in the cell along with an indication that the model has made its choice.
(defun process-speech (model string)
(bt:with-lock-held ((gol-board-lock *board*))
(let ((cell (gethash model (gol-board-model->cell *board*))))
(when (or (string-equal string "on") (string-equal string "off"))
(setf (gol-cell-change cell) string))
(pushnew model (gol-board-responses *board*)))))
;;; The main function to run the game.
;;; w and h are width and height of the board in cells.
;;; cycles is how many update cycles to run.
;;; p is the probability that a cell will be on in the initial random state.
;;; setup allows the user to adjust the starting graphic based board.
;;; text indicates that only text output should be displayed.
;;; spc is the seconds per cycle setting -- how long in "real time" should
;;; be spent between cycles (each of which is always 1 second of model
;;; time).
(defun run-game (w h &key (cycles 10) (p .25) (setup nil) (text nil) (spc 1.0))
;; If there're any open windows close them, and delete all models for a clean start.
(close-all-exp-windows)
(clear-all)
;; Create a model for use in creating the game's events, to use for the
;; random state, and to output the text based version of the board.
(define-model game-state (sgp :v nil :cmdt t))
;; setup the initial global game info
(setf *board* (make-gol-board :width w :height h :responses nil :total (* w h) :cycle 1 :cells (make-array (list w h)) :model->cell (make-hash-table)))
;; If it's not a text only display open the window and add the
;; stop button which will schedule an immediate break event to
;; stop a run. Since it's the only open window we don't need
;; to record the reference because all the other GUI calls can
;; specify nil as the reference to use the default window.
(unless text
(open-exp-window "Game of Life" :visible t :width (1+ (* w 21)) :height (+ 55 (* h 21)))
(add-button-to-exp-window nil :text "Stop" :x 0 :y (+ 5 (* h 21))
:action (lambda ()
(schedule-break-relative 0 :details "Game stop button pressed"))
:height 20 :width 75))
;; For each cell instantiate a new model whose name
;; indicates which cell it is, set the initial state of
;; the cell randomly, and create a button for the display
;; if it's not text only. Then record those items so that
;; it's easy to get back to them when needed.
(dotimes (i w)
(dotimes (j h)
(let* ((model (intern (format nil "M-~d-~d" i j)))
(state (< (with-model game-state (act-r-random 1.0)) p))
(button (unless text (add-button-to-exp-window nil :text "" :x (* i 21) :y (* j 21)
:action (when setup (list 'click-button i j))
:height 20 :width 20
:color (if state 'red 'gray))))
(cell (make-gol-cell
:state state
:change nil
:button button
:model model)))
(define-model-fct (intern (format nil "M-~d-~d" i j)) *model-code*)
(setf (gethash model (gol-board-model->cell *board*)) cell)
(setf (aref (gol-board-cells *board*) i j) cell))))
;; Remove any preexisting commands which have the
;; same names as those that we're using here and also
;; remove the monitoring of output-speech (assuming that
;; it's being monitored if our monitoring command is
;; already defined).
(when (check-act-r-command "update-board")
(remove-act-r-command "update-board"))
(when (check-act-r-command "gol-clock")
(remove-act-r-command "gol-clock"))
(when (check-act-r-command "process-speech")
(remove-act-r-command-monitor "output-speech" "process-speech")
(remove-act-r-command "process-speech"))
;; Add commands to update the board, handle the models' speech
;; output, and provide the custom clock, and then monitor the
;; microphone's signal to actually detect the speech output.
(add-act-r-command "update-board" 'update-board "Game of Life cycle update command.")
(add-act-r-command "process-speech" 'process-speech "Game of Life monitor for speech output.")
(add-act-r-command "gol-clock"
(let ((start-time (get-internal-real-time)))
(lambda ()
(bt:with-lock-held ((gol-board-lock *board*))
;; if all the models have responded and the
;; appropriate amount of real time per cycle
;; has passed then advance the clock and record
;; the current real-time.
(when (and (= (gol-board-total *board*) (length (gol-board-responses *board*)))
(>= (get-internal-real-time) (+ start-time (* spc internal-time-units-per-second))))
(incf (gol-board-cycle *board*))
(setf start-time (get-internal-real-time))
(setf (gol-board-responses *board*) nil))
;; Always return the current time as 1ms before the
;; next update so that is as far as the models will
;; run before waiting.
(- (* (gol-board-cycle *board*) 1000) 1))))
"Game of Life custom clock command")
(monitor-act-r-command "output-speech" "process-speech")
;; Install this clock command as an absolute clock i.e. it
;; returns the current time instead of an arbitrary interval
;; which ACT-R then tests, and indicate that its units are
;; milliseconds (1000 units per second).
(mp-real-time-management :mode 'absolute :time-function "gol-clock" :units-per-second 1000)
;; Let the user create a custom starting state for the gui when requeted.
;; Create a button to press when done and just loop until the user
;; presses it, and then remove it and disable all the buttons -- set
;; their action to the AGI default function.
(when (and setup (not text))
(let* ((done nil)
(b (add-button-to-exp-window nil :text "Done" :x 0 :y (+ 30 (* h 21))
:action (lambda () (setf done t))
:height 20 :width 75)))
(while (not done)
(process-events))
(remove-items-from-exp-window nil b))
(dotimes (y (gol-board-height *board*))
(dotimes (x (gol-board-width *board*))
(let ((cell (aref (gol-board-cells *board*) x y)))
(modify-button-for-exp-window (gol-cell-button cell) :action "default-button-action")))))
;; When it's a text display draw the initial board.
(when text
(with-model game-state (draw-board)))
;; Give the models their initial input, and schedule a
;; periodic event for the updates starting at the end
;; of this cycle (1 second).
(generate-model-percepts)
(with-model game-state (schedule-periodic-event 1.0 "update-board" :params (list text) :maintenance t :initial-delay 1.0))
;; Run the game for the requested number of cycles (simulated seconds)
(run-full-time cycles t))
(defun click-button (x y)
(bt:with-lock-held ((gol-board-lock *board*))
(let ((cell (aref (gol-board-cells *board*) x y)))
(cond ((gol-cell-state cell)
(setf (gol-cell-state cell) nil)
(modify-button-for-exp-window (gol-cell-button cell) :color 'gray))
(t
(setf (gol-cell-state cell) t)
(modify-button-for-exp-window (gol-cell-button cell) :color 'red))))))
;;; Function to draw the board to the command-trace using *'s and spaces
;;; with lines around it. Always called from
(defun draw-board ()
(bt:with-lock-held ((gol-board-lock *board*))
(command-output (make-string (+ 2 (gol-board-width *board*)) :initial-element #\_))
(dotimes (y (gol-board-height *board*))
(let ((line (make-string (+ 2 (gol-board-width *board*)) :initial-element #\|)))
(dotimes (x (gol-board-width *board*))
(setf (char line (1+ x)) (if (gol-cell-state (aref (gol-board-cells *board*) x y)) #\* #\space)))
(command-output line)))
(command-output (make-string (+ 2 (gol-board-width *board*)) :initial-element #\-))))
;;; Function to count the number of neighbors of a cell
;;; using a simple check for each adjacent space which exists.
;;; Only called from generate-model-percepts which holds the
;;; lock already.
(defun count-neighbors (x y)
(let ((mx (1- (gol-board-width *board*)))
(my (1- (gol-board-height *board*)))
(count 0))
(when (and (> x 0) (> y 0) (gol-cell-state (aref (gol-board-cells *board*) (1- x) (1- y))))
(incf count))
(when (and (> y 0) (gol-cell-state (aref (gol-board-cells *board*) x (1- y))))
(incf count))
(when (and (< x mx) (> y 0) (gol-cell-state (aref (gol-board-cells *board*) (1+ x) (1- y))))
(incf count))
(when (and (> x 0) (gol-cell-state (aref (gol-board-cells *board*) (1- x) y)))
(incf count))
(when (and (< x mx) (gol-cell-state (aref (gol-board-cells *board*) (1+ x) y)))
(incf count))
(when (and (> x 0) (< y my) (gol-cell-state (aref (gol-board-cells *board*) (1- x) (1+ y))))
(incf count))
(when (and (< y my) (gol-cell-state (aref (gol-board-cells *board*) x (1+ y))))
(incf count))
(when (and (< x mx) (< y my) (gol-cell-state (aref (gol-board-cells *board*) (1+ x) (1+ y))))
(incf count))
count))
;;; The periodic event scheduled to generate the updates.
;;; It updates the board with all of the models' moves
;;; then redraws it and has each model to reprocess the
;;; visual display.
(defun update-board (text)
(bt:with-lock-held ((gol-board-lock *board*))
(dotimes (y (gol-board-height *board*))
(dotimes (x (gol-board-width *board*))
(let ((cell (aref (gol-board-cells *board*) x y)))
(when (gol-cell-change cell)
(if (string-equal "on" (gol-cell-change cell))
(progn
(setf (gol-cell-state cell) t)
(unless text
(modify-button-for-exp-window (gol-cell-button cell) :color 'red)))
(progn
(setf (gol-cell-state cell) nil)
(unless text
(modify-button-for-exp-window (gol-cell-button cell) :color 'gray))))
(setf (gol-cell-change cell) nil))))))
(when text
(draw-board))
(generate-model-percepts))
;;; Function to create a visicon feature for the cell
;;; for each model or modify that feature if one has
;;; already been created. The chunk holds the cell
;;; coordinates in the x and y slots (which are set to
;;; be the position slots). If it is on then the state
;;; slot holds t, otherwise there is no state slot.
;;; The neighbors slot contains the count of neighboring
;;; on cells.
(defun generate-model-percepts ()
(bt:with-lock-held ((gol-board-lock *board*))
(dotimes (y (gol-board-height *board*))
(dotimes (x (gol-board-width *board*))
(let ((cell (aref (gol-board-cells *board*) x y)))
(with-model-eval (gol-cell-model cell)
(if (gol-cell-feature cell)
(modify-visicon-features (list (gol-cell-feature cell) 'state (gol-cell-state cell) 'neighbors (count-neighbors x y)))
(setf (gol-cell-feature cell)
(first (add-visicon-features (list 'isa 'cell 'x x 'y y 'state (gol-cell-state cell) 'neighbors (count-neighbors x y) :x-slot 'x :y-slot 'y)))))))))))
| 20,054 | Common Lisp | .lisp | 426 | 40.018779 | 166 | 0.627265 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | be4609a0ba12c3ab0aefd1a19ca987e7f3c73007ef884a49f5e15fddd7b4a5f2 | 14,198 | [
134451
] |
14,199 | simple-goal-style-model.lisp | asmaloney_ACT-R/examples/creating-modules/internal/simple-goal-style-model.lisp | ;;; This model has three productions which make a
;;; query, request and modification request to test
;;; the new-goal module created by the simple-goal-style.lisp
;;; file.
(clear-all)
(define-model simple-goal-test
(sgp :v t :trace-detail high)
(chunk-type goal-chunk state)
(define-chunks (start isa chunk) (next isa chunk) (done isa chunk))
(p check-it-is-empty
?new-goal>
buffer empty
==>
+new-goal>
isa goal-chunk
state start)
(p note-start
=new-goal>
isa goal-chunk
state start
==>
*new-goal>
state next)
(p finish
=new-goal>
isa goal-chunk
state next
==>
=new-goal>
state done))
#|
Here is an example run of this model along with the buffer-status
and buffer-chunk results after the run
> (run 1)
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.000 PROCEDURAL PRODUCTION-SELECTED CHECK-IT-IS-EMPTY
0.000 PROCEDURAL QUERY-BUFFER-ACTION NEW-GOAL
0.050 PROCEDURAL PRODUCTION-FIRED CHECK-IT-IS-EMPTY
0.050 PROCEDURAL MODULE-REQUEST NEW-GOAL
0.050 PROCEDURAL CLEAR-BUFFER NEW-GOAL
0.050 NEW-GOAL SET-BUFFER-CHUNK-FROM-SPEC NEW-GOAL
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-SELECTED NOTE-START
0.050 PROCEDURAL BUFFER-READ-ACTION NEW-GOAL
0.050 PROCEDURAL QUERY-BUFFER-ACTION NEW-GOAL
0.100 PROCEDURAL PRODUCTION-FIRED NOTE-START
0.100 PROCEDURAL MODULE-MOD-REQUEST NEW-GOAL
0.100 NEW-GOAL MOD-BUFFER-CHUNK NEW-GOAL
0.100 PROCEDURAL CONFLICT-RESOLUTION
0.100 PROCEDURAL PRODUCTION-SELECTED FINISH
0.100 PROCEDURAL BUFFER-READ-ACTION NEW-GOAL
0.150 PROCEDURAL PRODUCTION-FIRED FINISH
0.150 PROCEDURAL MOD-BUFFER-CHUNK NEW-GOAL
0.150 PROCEDURAL CONFLICT-RESOLUTION
0.150 ------ Stopped because no events left to process
0.15
24
NIL
> (buffer-status new-goal)
NEW-GOAL:
buffer empty : NIL
buffer full : T
buffer failure : NIL
buffer requested : T
buffer unrequested : NIL
state free : T
state busy : NIL
state error : NIL
(NEW-GOAL)
> (buffer-chunk new-goal)
NEW-GOAL: NEW-GOAL-CHUNK0
NEW-GOAL-CHUNK0
STATE DONE
(NEW-GOAL-CHUNK0)
|#
| 2,581 | Common Lisp | .lisp | 75 | 29.88 | 77 | 0.605634 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 850fbcddb9d24372a08d5d09894360471ddbbba594341cf15faacb7201934728 | 14,199 | [
-1
] |
14,200 | second-retrieval-buffer-model.lisp | asmaloney_ACT-R/examples/creating-modules/internal/second-retrieval-buffer-model.lisp | ;;; This model is a test of the module that adds a
;;; second retrieval buffer called r2. It simply
;;; adds 2 chunks to DM and has one production which
;;; makes requests to retrieve those chunks using both
;;; the retrieval and r2 buffers.
(clear-all)
(define-model test-r2-buffer
(sgp :v t :esc t)
(add-dm (value 1)
(b1 color blue))
(set-base-levels (b1 1))
(p retrieve
?goal>
buffer empty
==>
+goal>
+retrieval>
value 1
+r2>
color blue))
#|
> (run 2)
0.000 PROCEDURAL CONFLICT-RESOLUTION
0.050 PROCEDURAL PRODUCTION-FIRED RETRIEVE
0.050 PROCEDURAL CLEAR-BUFFER GOAL
0.050 PROCEDURAL CLEAR-BUFFER RETRIEVAL
0.050 PROCEDURAL CLEAR-BUFFER R2
0.050 GOAL SET-BUFFER-CHUNK GOAL CHUNK1
0.050 DECLARATIVE start-retrieval
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.418 SECOND-RETRIEVAL-BUFFER SECOND-RETRIEVAL-BUFFER-RETRIEVED-CHUNK B1
0.418 SECOND-RETRIEVAL-BUFFER SET-BUFFER-CHUNK R2 B1
0.418 PROCEDURAL CONFLICT-RESOLUTION
1.050 DECLARATIVE RETRIEVED-CHUNK CHUNK0
1.050 DECLARATIVE SET-BUFFER-CHUNK RETRIEVAL CHUNK0
1.050 PROCEDURAL CONFLICT-RESOLUTION
1.050 ------ Stopped because no events left to process
1.05
23
NIL
> (buffer-chunk retrieval r2)
RETRIEVAL: CHUNK0-0 [CHUNK0]
CHUNK0-0
VALUE 1
R2: B1-0 [B1]
B1-0
COLOR BLUE
(CHUNK0-0 B1-0)
|# | 1,669 | Common Lisp | .lisp | 49 | 28.55102 | 80 | 0.595852 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e00180bac6c0d99e0aa0299c58c18ac7efdb9a2eee18637e162584b3456ee636 | 14,200 | [
146843
] |
14,201 | demo-model.lisp | asmaloney_ACT-R/examples/creating-modules/internal/demo-model.lisp | ;;; This model simply uses the buffers create and output
;;; from the demo module to show their operation.
(clear-all)
(define-model test-demo-module
(sgp :esc t :create-delay .15 :trace-detail high)
(p p1
?goal>
buffer empty
?create>
state free
buffer empty
==>
+goal>
+create>
isa visual-location
screen-x 10
screen-y 20)
(p p2
=create>
isa visual-location
==>
+output>
isa demo-output
value =create
))
| 542 | Common Lisp | .lisp | 25 | 15.2 | 56 | 0.585657 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 154e2b1c692606db6cb4ce1db6bbc4dfb02b8dd6ab4a2e71112adcb647510577 | 14,201 | [
-1
] |
14,202 | all-components-model.lisp | asmaloney_ACT-R/examples/creating-modules/internal/all-components-model.lisp | ;;; This model runs with the all-components-module and makes
;;; queries and requests of that module to show its components
;;; in action.
;;;
;;; The run-it function will reset the model and then run it
;;; in small sections stopping to print out some query and
;;; buffer content information between sections. It calls
;;; clear-all at the end to delete the model.
(clear-all)
(defun run-it ()
(run .15)
(buffer-status demo1 demo2)
(buffer-chunk demo1 demo2)
(run-until-time .35)
(buffer-status demo2)
(buffer-chunk demo2)
(run-until-time .5)
(buffer-status demo2)
(buffer-chunk demo2)
(run-until-time .65)
(buffer-status demo2)
(buffer-chunk demo2)
(run-until-time .8)
(buffer-status demo2)
(buffer-chunk demo2)
(clear-all))
(define-model test-demo-module
(model-output "Model definition code starts evaluating here")
(sgp :esc t :demo-param .2 :trace-detail high)
(chunk-type state slot (state t))
;; just put some chunk in the goal buffer
(goal-focus free)
(p clear-goal-request-demo1
?demo1>
buffer empty
state free
==>
-goal>
+demo1>
isa state)
(p harvest-demo1-mod-request-demo1
=demo1>
isa state
slot nil
==>
*demo1>
slot 0)
(p make-demo2-request
=demo1>
isa state
slot 0
?demo2>
state free
buffer empty
==>
=demo1>
slot 1
+demo2>
isa create-chunk)
(p mod-request-to-demo2
"This will jam its second time"
=demo1>
isa state
slot 1
=demo2>
isa result
answer nil
?demo2>
detect-jam nil
==>
*demo2>
answer 10)
(p demo2-request-with-request-parameter
=demo1>
isa state
slot 1
=demo2>
isa result
answer =value
==>
=demo1>
slot 2
+demo2>
isa create-chunk
:value 15)
(p invalid-demo2-request
=demo1>
isa state
slot 2
=demo2>
isa result
?demo2>
state free
==>
+demo2>
isa visual-location)
)
#|
; Loading all-components-model.lisp
Creating a demo module for model TEST-DEMO-MODULE
Demo module's primary reset function called.
Demo module's parameter function called with parameter (:ESC)
:esc change noted
Demo module's parameter function called with parameter (:DEMO-PARAM . 0.15)
Demo module's secondary reset function called.
Model definition code starts evaluating here
Demo module's parameter function called with parameter (:ESC . T)
:esc change noted
Demo module's parameter function called with parameter (:DEMO-PARAM . 0.2)
> (run-it)
0.000 GOAL SET-BUFFER-CHUNK GOAL FREE NIL
0.000 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO1 buffer for STATE FREE
Demo module detects that a production will be making a request to the DEMO1 buffer
0.000 PROCEDURAL PRODUCTION-SELECTED CLEAR-GOAL-REQUEST-DEMO1
0.000 PROCEDURAL QUERY-BUFFER-ACTION DEMO1
0.050 PROCEDURAL PRODUCTION-FIRED CLEAR-GOAL-REQUEST-DEMO1
0.050 PROCEDURAL MODULE-REQUEST DEMO1
Request to the DEMO1 buffer:
"= STATE T"
0.050 PROCEDURAL CLEAR-BUFFER GOAL
The demo module detects that the GOAL buffer is clearing chunk GOAL-CHUNK0 which is not storeable
0.050 PROCEDURAL CLEAR-BUFFER DEMO1
0.050 DEMO SET-BUFFER-CHUNK DEMO1 CHUNK0
0.050 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO1 buffer for STATE FREE
0.050 PROCEDURAL PRODUCTION-SELECTED HARVEST-DEMO1-MOD-REQUEST-DEMO1
0.050 PROCEDURAL BUFFER-READ-ACTION DEMO1
0.050 PROCEDURAL QUERY-BUFFER-ACTION DEMO1
0.100 PROCEDURAL PRODUCTION-FIRED HARVEST-DEMO1-MOD-REQUEST-DEMO1
0.100 PROCEDURAL MODULE-MOD-REQUEST DEMO1
A buffer modification request was made to the DEMO1 buffer:
"= SLOT 0".
0.100 DEMO MOD-BUFFER-CHUNK DEMO1
0.100 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO2 buffer for STATE FREE
Demo module detects that a production will be making a request to the DEMO2 buffer
0.100 PROCEDURAL PRODUCTION-SELECTED MAKE-DEMO2-REQUEST
0.100 PROCEDURAL BUFFER-READ-ACTION DEMO1
0.100 PROCEDURAL QUERY-BUFFER-ACTION DEMO2
0.150 PROCEDURAL PRODUCTION-FIRED MAKE-DEMO2-REQUEST
0.150 PROCEDURAL MOD-BUFFER-CHUNK DEMO1
0.150 PROCEDURAL MODULE-REQUEST DEMO2
Request to the DEMO2 buffer:
"= CREATE-CHUNK T"
0.150 PROCEDURAL CLEAR-BUFFER DEMO2
0.150 PROCEDURAL CONFLICT-RESOLUTION
0.150 ------ Stopped because time limit reached
DEMO1:
buffer empty : NIL
buffer full : T
buffer failure : NIL
buffer requested : T
buffer unrequested : NIL
Demo module's query function called to query the DEMO1 buffer for STATE FREE
state free : T
Demo module's query function called to query the DEMO1 buffer for STATE BUSY
state busy : NIL
Demo module's query function called to query the DEMO1 buffer for STATE ERROR
state error : NIL
DEMO2:
buffer empty : T
buffer full : NIL
buffer failure : NIL
buffer requested : NIL
buffer unrequested : NIL
Demo module's query function called to query the DEMO2 buffer for STATE FREE
state free : NIL
Demo module's query function called to query the DEMO2 buffer for STATE BUSY
state busy : T
Demo module's query function called to query the DEMO2 buffer for STATE ERROR
state error : NIL
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM T
detect-jam : NIL
DEMO1: DEMO1-CHUNK0
DEMO1-CHUNK0
STATE T
SLOT 1
DEMO2: NIL
0.250 DEMO SET-BUFFER-CHUNK DEMO2 RESULT0
0.250 DEMO FINISH-DEMO2-REQUEST
0.250 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM NIL
0.250 PROCEDURAL PRODUCTION-SELECTED MOD-REQUEST-TO-DEMO2
0.250 PROCEDURAL BUFFER-READ-ACTION DEMO1
0.250 PROCEDURAL BUFFER-READ-ACTION DEMO2
0.250 PROCEDURAL QUERY-BUFFER-ACTION DEMO2
0.300 PROCEDURAL PRODUCTION-FIRED MOD-REQUEST-TO-DEMO2
0.300 PROCEDURAL MODULE-MOD-REQUEST DEMO2
A buffer modification request was made to the DEMO2 buffer:
"= ANSWER 10".
0.300 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM NIL
0.300 PROCEDURAL PRODUCTION-SELECTED MOD-REQUEST-TO-DEMO2
0.300 PROCEDURAL BUFFER-READ-ACTION DEMO1
0.300 PROCEDURAL BUFFER-READ-ACTION DEMO2
0.300 PROCEDURAL QUERY-BUFFER-ACTION DEMO2
0.350 PROCEDURAL PRODUCTION-FIRED MOD-REQUEST-TO-DEMO2
0.350 PROCEDURAL MODULE-MOD-REQUEST DEMO2
A buffer modification request was made to the DEMO2 buffer:
"= ANSWER 10".
#|Warning: Demo module's demo2 buffer can only process one request at a time. |#
0.350 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM NIL
0.350 ------ Stopped because time limit reached
DEMO2:
buffer empty : NIL
buffer full : T
buffer failure : NIL
buffer requested : T
buffer unrequested : NIL
Demo module's query function called to query the DEMO2 buffer for STATE FREE
state free : NIL
Demo module's query function called to query the DEMO2 buffer for STATE BUSY
state busy : T
Demo module's query function called to query the DEMO2 buffer for STATE ERROR
state error : NIL
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM T
detect-jam : T
DEMO2: DEMO2-CHUNK0 [RESULT0]
DEMO2-CHUNK0
DEMO-RESULT T
0.500 DEMO MOD-BUFFER-CHUNK DEMO2
0.500 DEMO FINISH-DEMO2-REQUEST
0.500 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO2 buffer for STATE FREE
Demo module detects that a production will be making a request to the DEMO2 buffer
0.500 PROCEDURAL PRODUCTION-SELECTED DEMO2-REQUEST-WITH-REQUEST-PARAMETER
0.500 PROCEDURAL BUFFER-READ-ACTION DEMO1
0.500 PROCEDURAL BUFFER-READ-ACTION DEMO2
0.500 PROCEDURAL QUERY-BUFFER-ACTION DEMO2
0.500 ------ Stopped because time limit reached
DEMO2:
buffer empty : NIL
buffer full : T
buffer failure : NIL
buffer requested : T
buffer unrequested : NIL
Demo module's query function called to query the DEMO2 buffer for STATE FREE
state free : T
Demo module's query function called to query the DEMO2 buffer for STATE BUSY
state busy : NIL
Demo module's query function called to query the DEMO2 buffer for STATE ERROR
state error : NIL
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM T
detect-jam : NIL
DEMO2: DEMO2-CHUNK0
DEMO2-CHUNK0
ANSWER 10
DEMO-RESULT T
0.550 PROCEDURAL PRODUCTION-FIRED DEMO2-REQUEST-WITH-REQUEST-PARAMETER
0.550 PROCEDURAL MOD-BUFFER-CHUNK DEMO1
0.550 PROCEDURAL MODULE-REQUEST DEMO2
Request to the DEMO2 buffer:
"= :VALUE 15
= CREATE-CHUNK T"
0.550 PROCEDURAL CLEAR-BUFFER DEMO2
The demo module detects that the DEMO2 buffer is clearing chunk DEMO2-CHUNK0 which is not storeable
0.550 PROCEDURAL CONFLICT-RESOLUTION
0.650 DEMO SET-BUFFER-CHUNK DEMO2 RESULT1
0.650 DEMO FINISH-DEMO2-REQUEST
0.650 PROCEDURAL CONFLICT-RESOLUTION
Demo module's query function called to query the DEMO2 buffer for STATE FREE
Demo module detects that a production will be making a request to the DEMO2 buffer
0.650 PROCEDURAL PRODUCTION-SELECTED INVALID-DEMO2-REQUEST
0.650 PROCEDURAL BUFFER-READ-ACTION DEMO1
0.650 PROCEDURAL BUFFER-READ-ACTION DEMO2
0.650 PROCEDURAL QUERY-BUFFER-ACTION DEMO2
0.650 ------ Stopped because time limit reached
DEMO2:
buffer empty : NIL
buffer full : T
buffer failure : NIL
buffer requested : T
buffer unrequested : NIL
Demo module's query function called to query the DEMO2 buffer for STATE FREE
state free : T
Demo module's query function called to query the DEMO2 buffer for STATE BUSY
state busy : NIL
Demo module's query function called to query the DEMO2 buffer for STATE ERROR
state error : NIL
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM T
detect-jam : NIL
DEMO2: DEMO2-CHUNK0 [RESULT1]
DEMO2-CHUNK0
ANSWER 15
DEMO-RESULT T
0.700 PROCEDURAL PRODUCTION-FIRED INVALID-DEMO2-REQUEST
0.700 PROCEDURAL MODULE-REQUEST DEMO2
Request to the DEMO2 buffer:
""
#|Warning: Invalid request to the demo2 buffer:
"" |#
0.700 PROCEDURAL CLEAR-BUFFER DEMO2
The demo module detects that the DEMO2 buffer is clearing chunk DEMO2-CHUNK0 which is not storeable
0.700 PROCEDURAL CONFLICT-RESOLUTION
0.800 ------ Stopped because time limit reached
DEMO2:
buffer empty : T
buffer full : NIL
buffer failure : NIL
buffer requested : NIL
buffer unrequested : NIL
Demo module's query function called to query the DEMO2 buffer for STATE FREE
state free : T
Demo module's query function called to query the DEMO2 buffer for STATE BUSY
state busy : NIL
Demo module's query function called to query the DEMO2 buffer for STATE ERROR
state error : T
Demo module's query function called to query the DEMO2 buffer for DETECT-JAM T
detect-jam : NIL
DEMO2: NIL
Deletion of demo module called for instance in model TEST-DEMO-MODULE.
NIL
|#
| 12,729 | Common Lisp | .lisp | 315 | 36.44127 | 99 | 0.657535 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a29d8a396089cbc46d06c1886b1694701513f0da239a1ba1bd382bdb4a502161 | 14,202 | [
-1
] |
14,203 | second-retrieval-buffer.lisp | asmaloney_ACT-R/examples/creating-modules/internal/second-retrieval-buffer.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2015 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 : second-retrieval-buffer.lisp
;;; Version : 0.1a
;;;
;;; Description : A module which adds a new buffer that works like the retrieval
;;; : buffer to get chunks from DM using the simulate-retrieval-request
;;; : command.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2015.07.23 Dan
;;; : * Initial creation.
;;; 2018.05.08 Dan
;;; : * Added a lock to proctect things so it's thread safe.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; This example module creates a buffer named r2 which can be used like the
;;; retrieval buffer to retrieve chunks from declarative memory in parallel with
;;; the existing retrieval buffer. It uses the same timing and activation
;;; parameters as the declarative memory module, but that could be changed as
;;; needed (timing being easy to change but activation parameter changes may require
;;; a little more work to either change the declarative parameter and restore
;;; on the fly or add appropriate hooks to modify the calculations).
;;;
;;; The module uses the simulate-retrieval-request command to do the real work,
;;; and sets the seed to reflect the processing which occurred. If the :recently-
;;; retrieved request parameter is provided that will reflect the current set of
;;; finsts in the declarative module, but this request will not change that set
;;; of finsts i.e. the retrievals through this buffer will not be marked with a
;;; finst. If a seprate finst set is needed that would be possible to add here
;;; by keeping a list of finsts in this module itself and then stripping the
;;; parameter from the request before passing it on to simulate-retrieval-request
;;; and filtering the results afterwards based on the requested result. If
;;; however one wants there to be one set of finsts which both this and the
;;; normal retrievals access that would require changing the declarative module
;;; code as well to record the changes (not recommended).
;;;
;;; This module has its own state flags which are independent of those of the
;;; declarative module and retrieval buffer. It will set the buffer failure flag
;;; and state error when no chunk is retrieved. If it is jammed it will still
;;; process the new request and it does not attempt to eliminate the previous
;;; one's result. Thus, both chunks will end up being set in the buffer (assuming
;;; that both were successful retrievals) at the appropriate times based on their
;;; activations and that means the order of the setting depends on the activations
;;; and the second one may overwrite the first before the model can use it. The
;;; busy flag will also clear when the first of the two is "retrieved" resulting
;;; in potentially undetectable jamming since a pending retrieval may still be
;;; scheduled after the busy flag is cleared. Additional logic could be added to
;;; the module to adjust all that, but for simplicity of the example it doesn't
;;; do so.
;;;
;;; This module does not report the activation trace because it suppresses the
;;; output of simulate-retrieval-request, but a parameter could be added to
;;; toggle whether that was suppressed or not. However, it would only be the
;;; "low" trace since that's all simulate-retrieval-request outputs.
;;;
;;; Some of the places where one might want to adjust how this module works are
;;; noted in comments, but those aren't the only changes one could make.
;;;
;;; To use this module this file could be placed into the modules directory of
;;; the distribution before loading.
;;;
;;; This module is provided only as an example and does represent a theoretical
;;; claim that such a capability does or should exist.
;;;
;;; This code is thread safe, with a simple lock used to protect all of the
;;; slots in the module instance.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Standard package checks all automatically loaded ACT-R files should have.
#+: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)
;;; A structure to hold the module's parameter and query flags.
(defstruct second-retrieval-buffer busy error rt lf le esc (lock (bt:make-lock "r2-lock")))
;;; Creation function just returns a new structure.
(defun create-second-retrieval-buffer (model-name)
(declare (ignore model-name))
(make-second-retrieval-buffer))
;;; Reset function just clears the busy and error flags.
(defun second-retrieval-buffer-reset (instance)
(bt:with-lock-held ((second-retrieval-buffer-lock instance))
(setf (second-retrieval-buffer-busy instance) nil)
(setf (second-retrieval-buffer-error instance) nil)))
;;; The query function reports the state flags.
(defun second-retrieval-buffer-query (instance buffer query value)
(bt:with-lock-held ((second-retrieval-buffer-lock instance))
(if (eq query 'state)
(case value
(busy (second-retrieval-buffer-busy instance))
(free (not (second-retrieval-buffer-busy instance)))
(error (second-retrieval-buffer-error instance)))
(model-warning "Invalid query ~a ~a made to the ~a buffer" query value buffer))))
;;; Function to handle the demo module's parameters which are just
;;; being passed from elsewhere since they aren't owned so they'll always
;;; be a cons and not a request for a value. Do the second to ms
;;; conversion on :lf here.
(defun second-retrieval-buffer-params (instance param)
(bt:with-lock-held ((second-retrieval-buffer-lock instance))
(case (car param)
(:esc (setf (second-retrieval-buffer-esc instance) (cdr param)))
(:rt (setf (second-retrieval-buffer-rt instance) (cdr param)))
(:lf (setf (second-retrieval-buffer-lf instance) (seconds->ms (cdr param))))
(:le (setf (second-retrieval-buffer-le instance) (cdr param))))))
;;; The request function
(defun second-retrieval-buffer-request (instance buffer chunk-spec)
(bt:with-lock-held ((second-retrieval-buffer-lock instance))
(when (second-retrieval-buffer-busy instance)
(model-warning "Second-retrieval-buffer received a request while it was still busy."))
;; set the busy flag and clear the error flag
(setf (second-retrieval-buffer-busy instance) t)
(setf (second-retrieval-buffer-error instance) nil)
(multiple-value-bind (results seed)
;; convert the chunk-spec back to a flat list and simulate the retrieval request
(no-output (simulate-retrieval-request-plus-seed-fct (slot-specs-to-chunk-spec-list (chunk-spec-slot-spec chunk-spec))))
;; update the seed value to where it would be after that request happened
(no-output (sgp-fct (list :seed seed)))
;; check that something was retrievable i.e. above the threshold
(if (and (car results) (>= (chunk-activation (car results)) (second-retrieval-buffer-rt instance)))
;; if so schedule an event to set the chunk in the buffer and clear the busy flag
(schedule-event-relative (if (second-retrieval-buffer-esc instance)
;; use the default latency computation from the declarative module
(round (* (second-retrieval-buffer-lf instance)
(exp (* -1 (second-retrieval-buffer-le instance)
(chunk-activation (car results))))))
0)
'second-retrieval-buffer-retrieved-chunk
:time-in-ms t
:module 'second-retrieval-buffer
:destination 'second-retrieval-buffer
:params (list (car results))
:output 'medium)
;; otherwise schedule an event to clear the busy flag and set the failure and error flags
(schedule-event-relative (if (dm-esc dm)
(round (* (second-retrieval-buffer-lf instance)
(exp (* -1 (second-retrieval-buffer-le instance)
(second-retrieval-buffer-rt instance)))))
0)
'second-retrieval-buffer-failure
:time-in-ms t
:module 'second-retrieval-buffer
:destination 'second-retrieval-buffer
:output 'low)))))
(defun second-retrieval-buffer-retrieved-chunk (instance chunk)
(bt:with-lock-held ((second-retrieval-buffer-lock instance))
;; Clear the busy flag
(setf (second-retrieval-buffer-busy instance) nil)
;; Schedule an event to put the chunk into the buffer right now instead of
;; placing it there directly to comply with the guideline that buffer changes
;; should be scheduled.
(schedule-set-buffer-chunk 'r2 chunk 0 :time-in-ms t :module 'second-retrieval-buffer :priority :max)))
(defun second-retrieval-buffer-failure (instance)
(bt:with-lock-held ((second-retrieval-buffer-lock instance))
;; Clear the busy flag and set the buffer failure and error flag.
(setf (second-retrieval-buffer-busy instance) nil)
(setf (second-retrieval-buffer-error instance) t)
(set-buffer-failure 'r2)))
;;; The actual module definition call specifying the components.
(define-module-fct 'second-retrieval-buffer
;; the module has one buffer called r2 which accepts the :recently-retrieved request parameter
(list '(r2 nil (:recently-retrieved)))
;; record parameters from other modules
(list (define-parameter :esc :owner nil)
(define-parameter :lf :owner nil)
(define-parameter :le :owner nil)
(define-parameter :rt :owner nil))
:version "0.1a"
:documentation "Example module with a buffer that accesses DM similar to the retrieval buffer"
:creation 'create-second-retrieval-buffer
:reset 'second-retrieval-buffer-reset
:query 'second-retrieval-buffer-query
:params 'second-retrieval-buffer-params
:request 'second-retrieval-buffer-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
|#
| 11,879 | Common Lisp | .lisp | 207 | 50.487923 | 128 | 0.660343 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | a2efe0d70c8f7ec3f614c80e23dd7ad86309d3dbe4270be917da7f96f4b068b0 | 14,203 | [
61095
] |
14,204 | simple-goal-style.lisp | asmaloney_ACT-R/examples/creating-modules/internal/simple-goal-style.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 : simple-goal-style.lisp
;;; Version : 1.0
;;;
;;; Description : demo goal-style module
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2008.09.26 Dan
;;; : * Put it into the standard code file template.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; This file defines a simple goal-style module called new-goal
;;; which has one buffer also called new-goal and which works
;;; exactly like the default ACT-R goal module and buffer except
;;; that it does not provide commands equivalent to goal-focus
;;; and mod-focus.
;;;
;;; To use this module either place this file into the modules
;;; directory before loading the system, or just load it once
;;; before loading the corresponding model file which uses it.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; These tests should appear at the top of all automatically loaded
;;; ACT-R files to ensure that things go into a specific package when
;;; requested.
#+: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)
;;; This line should be included in any file which uses the
;;; goal-style-query or goal-style-request functions to ensure
;;; that they are available.
(require-compiled "GOAL-STYLE-MODULE" "ACT-R-support:goal-style-module")
(define-module new-goal ;; the module is named new-goal
(new-goal) ;; it has one buffer called new goal
nil ;; it has no parameters
:version "1.0"
:documentation "A module which acts like the goal module"
;; Just specify the goal-style functions for the module's interface
:query goal-style-query
:request goal-style-request
:buffer-mod goal-style-mod-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
|#
| 3,439 | Common Lisp | .lisp | 79 | 41.962025 | 81 | 0.599581 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2246f15d822e8f315cfa1e44ff47a2cadc69958ff4443d69ed6e5f871fc5c596 | 14,204 | [
-1
] |
14,205 | demo-module.lisp | asmaloney_ACT-R/examples/creating-modules/internal/demo-module.lisp | ;;; This module creates 2 buffers called create and output which
;;; take simple requests to create a new chunk or print some
;;; information in the trace. For demonstration of how and
;;; when the module interface commands are called they are all
;;; traced before running the simple demo model as shown in
;;; the comments at the bottom.
;;; This code is not thread safe, but if this module is to be used when there
;;; are any remote systems connected (for example the ACT-R Environment or
;;; a remote connection like the one provided for Python with the ACT-R tutorial)
;;; then it is not safe to use this module if those systems may access its
;;; state or make requests concurrently with a model running e.g. using the
;;; buffer status tool in the Environment or the get-parameter-value remote
;;; command. To protect that, all the code which sets or reads the slot
;;; contents of the module structure would need to be protected appropriately,
;;; and a simple lock around the code which accesses the demo-module's
;;; slots should be sufficient.
(defstruct demo-module delay esc busy)
(defun create-demo-module (model-name)
(declare (ignore model-name))
(make-demo-module))
(defun reset-demo-module (demo)
(declare (ignore demo))
(chunk-type demo-output value (demo-output t)))
(defun delete-demo-module (demo)
(declare (ignore demo)))
(defun demo-module-params (demo param)
(if (consp param)
(case (car param)
(:create-delay
(setf (demo-module-delay demo) (cdr param)))
(:esc
(setf (demo-module-esc demo) (cdr param))))
(case param
(:create-delay
(demo-module-delay demo)))))
(defun demo-module-requests (demo buffer spec)
(if (eq buffer 'create)
(demo-create-chunk demo spec)
(demo-handle-print-out spec)))
(defun demo-handle-print-out (spec)
(let ((output-slot? (chunk-spec-slot-spec spec 'demo-output))
(v1 (chunk-spec-slot-spec spec 'value)))
(if output-slot?
(if v1
(if (= (length v1) 1)
(if (eq (caar v1) '=)
(model-output "Value: ~s" (caddar v1))
(model-warning "Invalid slot modifier ~s in output buffer request" (caar v1)))
(model-warning "Value slot specified multiple times in output buffer request"))
(model-warning "Value slot missing in output buffer request"))
(model-warning "demo-output slot missing in request to output buffer"))))
(defun demo-create-chunk (demo spec)
(if (demo-module-busy demo)
(model-warning "Cannot handle request when busy")
(let ((chunk-def (chunk-spec-to-chunk-def spec)))
(when chunk-def
(let ((delay (if (demo-module-esc demo)
(demo-module-delay demo)
0)))
(setf (demo-module-busy demo) t)
(schedule-set-buffer-chunk 'create spec delay :module 'demo)
(schedule-event-relative delay 'free-demo-module :params (list demo) :module 'demo))))))
(defun free-demo-module (demo)
(setf (demo-module-busy demo) nil))
(defun demo-module-queries (demo buffer query value)
(declare (ignore buffer))
(case query
(state
(case value
(busy (demo-module-busy demo))
(free (not (demo-module-busy demo)))
(error nil)
(t (print-warning "Bad state query to the ~s buffer" buffer))))
(t (print-warning "Invalid query ~s to the ~s buffer" query buffer))))
(define-module-fct 'demo
'(create output)
(list (define-parameter :create-delay
:documentation
"time to create the chunk for the demo module"
:default-value .1
:valid-test 'nonneg
:warning "Non-negative number"
:owner t)
(define-parameter :esc :owner nil))
:request 'demo-module-requests
:query 'demo-module-queries
:version "1.0a1"
:documentation "Demo module for ICCM tutorial"
:creation 'create-demo-module
:reset 'reset-demo-module
:delete 'delete-demo-module
:params 'demo-module-params
)
#|
> (trace demo-module-requests demo-module-queries create-demo-module reset-demo-module delete-demo-module demo-module-params)
(DEMO-MODULE-PARAMS DELETE-DEMO-MODULE RESET-DEMO-MODULE CREATE-DEMO-MODULE DEMO-MODULE-QUERIES
DEMO-MODULE-REQUESTS)
> (reset)
0[5]: (RESET-DEMO-MODULE #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL))
0[5]: returned DEMO-OUTPUT
0[5]: (DEMO-MODULE-PARAMS #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL) (:CREATE-DELAY . 0.1))
0[5]: returned 0.1
0[5]: (DEMO-MODULE-PARAMS #S(DEMO-MODULE :DELAY 0.1 :ESC T :BUSY NIL) (:ESC))
0[5]: returned NIL
0[5]: (DEMO-MODULE-PARAMS #S(DEMO-MODULE :DELAY 0.1 :ESC NIL :BUSY NIL) (:ESC . T))
0[5]: returned T
0[5]: (DEMO-MODULE-PARAMS #S(DEMO-MODULE :DELAY 0.1 :ESC T :BUSY NIL) (:CREATE-DELAY . 0.15))
0[5]: returned 0.15
#|Warning: Production P2 has a condition for buffer CREATE with an isa that provides no tests. |#
T
> (run 1)
0.000 PROCEDURAL CONFLICT-RESOLUTION
0[5]: (DEMO-MODULE-QUERIES #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL) CREATE STATE FREE)
0[5]: returned T
0.000 PROCEDURAL PRODUCTION-SELECTED P1
0.000 PROCEDURAL QUERY-BUFFER-ACTION GOAL
0.000 PROCEDURAL QUERY-BUFFER-ACTION CREATE
0.050 PROCEDURAL PRODUCTION-FIRED P1
0.050 PROCEDURAL MODULE-REQUEST GOAL
0.050 PROCEDURAL MODULE-REQUEST CREATE
0[5]: (DEMO-MODULE-REQUESTS #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL) CREATE #S(ACT-R-CHUNK-SPEC :FILLED-SLOTS 422212465065984 :EMPTY-SLOTS 0 :REQUEST-PARAM-SLOTS 0 :DUPLICATE-SLOTS 0 :EQUAL-SLOTS 422212465065984 :NEGATED-SLOTS 0 :RELATIVE-SLOTS 0 :VARIABLES NIL :SLOT-VARS NIL :DEPENDENCIES NIL :SLOTS (#2=#S(ACT-R-SLOT-SPEC :MODIFIER = :NAME SCREEN-X :VALUE 10 :VARIABLE NIL) #1=#S(ACT-R-SLOT-SPEC :MODIFIER = :NAME SCREEN-Y :VALUE 20 :VARIABLE NIL)) :TESTABLE-SLOTS (#1# #2#) ...))
0[5]: returned 15
0.050 PROCEDURAL CLEAR-BUFFER GOAL
0.050 PROCEDURAL CLEAR-BUFFER CREATE
0.050 GOAL SET-BUFFER-CHUNK-FROM-SPEC GOAL
0.050 PROCEDURAL CONFLICT-RESOLUTION
0.200 DEMO SET-BUFFER-CHUNK-FROM-SPEC CREATE
0.200 DEMO FREE-DEMO-MODULE #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY T)
0.200 PROCEDURAL CONFLICT-RESOLUTION
0[5]: (DEMO-MODULE-QUERIES #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL) OUTPUT STATE FREE)
0[5]: returned T
0.200 PROCEDURAL PRODUCTION-SELECTED P2
0.200 PROCEDURAL BUFFER-READ-ACTION CREATE
0.200 PROCEDURAL QUERY-BUFFER-ACTION OUTPUT
0.250 PROCEDURAL PRODUCTION-FIRED P2
0.250 PROCEDURAL MODULE-REQUEST OUTPUT
0[5]: (DEMO-MODULE-REQUESTS #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL) OUTPUT #S(ACT-R-CHUNK-SPEC :FILLED-SLOTS 604462909807348947091456 :EMPTY-SLOTS 0 :REQUEST-PARAM-SLOTS 0 :DUPLICATE-SLOTS 0 :EQUAL-SLOTS 604462909807348947091456 :NEGATED-SLOTS 0 :RELATIVE-SLOTS 0 :VARIABLES NIL :SLOT-VARS NIL :DEPENDENCIES NIL :SLOTS (#2=#S(ACT-R-SLOT-SPEC :MODIFIER = :NAME VALUE :VALUE CHUNK0 :VARIABLE NIL) #1=#S(ACT-R-SLOT-SPEC :MODIFIER = :NAME DEMO-OUTPUT :VALUE T :VARIABLE NIL)) :TESTABLE-SLOTS (#1# #2#) ...))
Value: CHUNK0
0[5]: returned NIL
0.250 PROCEDURAL CLEAR-BUFFER CREATE
0.250 PROCEDURAL CLEAR-BUFFER OUTPUT
0.250 PROCEDURAL CONFLICT-RESOLUTION
0.250 ------ Stopped because no events left to process
0.25
25
NIL
> (clear-all)
0[5]: (DELETE-DEMO-MODULE #S(DEMO-MODULE :DELAY 0.15 :ESC T :BUSY NIL))
0[5]: returned NIL
NIL
|#
| 7,856 | Common Lisp | .lisp | 151 | 46.384106 | 509 | 0.656816 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b600906d468399ba1f5f32cda2e4da512b9dec2eba756dbb96833e8339c69c4d | 14,205 | [
-1
] |
14,206 | simple.lisp | asmaloney_ACT-R/examples/connections/lisp/simple.lisp | ;; Load quicklisp and the socket and JSON libraries used.
#-:QUICKLISP (eval-when (:compile-toplevel :load-toplevel :execute)
(when (probe-file "~/quicklisp/setup.lisp")
(load "~/quicklisp/setup.lisp"))
(unless (find :quicklisp *features*)
(error "This example requires Quicklisp to load the components necessary for the remote connection.")))
(ql:quickload :usocket)
(ql:quickload :cl-json)
;; a function to send a string to ACT-R followed by the
;; end of message character, and make sure the stream
;; sends the output.
(defun send-actr-message (stream string)
(format stream "~a~c" string (code-char 4))
(finish-output stream))
;; Read from the stream until the end of message character
;; is received and then return the decoded JSON result.
(defun read-actr-message (stream)
(let ((s (make-array 40
:element-type 'character
:adjustable T
:fill-pointer 0)))
(loop
(let ((char (read-char stream nil :done)))
(cond ((eq char :done)
(format *error-output* "External connection closed.")
(return-from read-actr-message nil))
((eq char (code-char 4))
(return-from read-actr-message (json:decode-json-from-string s)))
(t (vector-push-extend char s)))))))
;; Read the ACT-R configuration files for the connection information
(defvar *address* (with-open-file (f (translate-logical-pathname "~/act-r-address.txt") :direction :input)
(read-line f)))
(defvar *port* (with-open-file (f (translate-logical-pathname "~/act-r-port-num.txt") :direction :input)
(read f)))
;; Open the socket
(defvar *socket* (usocket:socket-connect *address* *port* :nodelay :if-supported))
;; Create a variable with the stream which can be read/written for that socket.
(defvar *stream* (usocket:socket-stream *socket*))
;; Set the name for this ACT-R connection
(send-actr-message *stream* "{\"method\":\"set-name\",\"params\":[\"Remote Lisp Example\"],\"id\":null}")
;; Evaluate the "act-r-version" command
(send-actr-message *stream* "{\"method\":\"evaluate\",\"params\":[\"act-r-version\"],\"id\":1}")
;; Read the response and check it for validity.
;; Note, cl-json converts a JSON object into an alist with
;; the car of an item being a keyword that matches the
;; name of an item and the cdr is the value of that
;; name.
(let ((message (read-actr-message *stream*)))
(cond ((and (= (length message) 3)
(assoc :result message)
(assoc :error message)
(assoc :id message))
(let ((id (cdr (assoc :id message)))
(result (cdr (assoc :result message)))
(error (cdr (assoc :error message))))
(cond ((= id 1)
(if result
(format t "ACT-R version is ~s~%" (first result))
(format t "Error: ~s~%" (cdr (assoc :message error)))))
(t
(format t "Unexpected id on return result: ~s~%" id)))))
(t
(format t "Unexpected message from ACT-R: ~s~%" message))))
;; Add the "remote-count" command to ACT-R using "count" as the local name.
(send-actr-message *stream* "{\"method\":\"add\",\"params\":[\"remote-count\",\"count\",\"Count the number of items in a list. Params: list\"],\"id\":null}")
;; Loop forever reading a message from ACT-R and returning
;; the count of items in the provided list or an error message
;; if things are not correct.
(loop
(let ((message (read-actr-message *stream*)))
(cond ((and (= (length message) 3)
(assoc :method message)
(assoc :params message)
(assoc :id message)
(string-equal (cdr (assoc :method message)) "evaluate"))
(let ((params (cdr (assoc :params message)))
(id (cdr (assoc :id message)))
(result nil)
(error nil))
(cond ((and (= (length params) 3)
(string= "count" (first params)))
(if (listp (third params))
(handler-case
(setf result (length (third params)))
((or error condition) (x)
(setf error (format nil "Error: ~s" x))))
(setf error (format nil "Requires a list of parameters but given ~s" (third params)))))
((not (string= "count" (first params)))
(setf error "Only evaluates count command."))
(t
(setf error (format nil "Invalid parameters to count: ~s" params))))
(when id
(if error
(send-actr-message *stream* (format nil "{\"result\":null,\"error\":{\"message\": ~s},\"id\":~a}" error (json:encode-json-to-string id)))
(send-actr-message *stream* (format nil "{\"result\":[~d],\"error\":null,\"id\":~a}" result (json:encode-json-to-string id)))))))
(t (format t "Unexpected message from ACT-R: ~s~%" message))))) | 5,418 | Common Lisp | .lisp | 96 | 43.104167 | 158 | 0.56338 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 65b4575aff0866f3d52f9eadff2bb099ec6c2a84de4351526da473762decab4c | 14,206 | [
359559
] |
14,207 | central-parameters.lisp | asmaloney_ACT-R/support/central-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 : central-parameters.lisp
;;; Version : 2.0
;;;
;;; Description : A module to hold parameters that could be used by more than
;;; one module.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2004.10.17 Dan
;;; : Creation.
;;; 2005.01.09 Dan
;;; : Moved the provide to the end.
;;; 2006.01.17 Dan
;;; : * Updated the version to 1.0 and modified the description.
;;; 2008.07.23 Dan
;;; : * Adding the register-subsymbolic-parameters command and the
;;; : necessary changes to the module to record and verify that.
;;; 2008.07.24 [1.1]
;;; : * Updated the version number because of the change.
;;; 2013.07.16 Dan [1.2]
;;; : * Adding a system parameter :custom-defaults and changing the
;;; : reset to secondary. Setting :custom-defaults to a list of
;;; : parameter-value pairs as acceptable for sgp causes those
;;; : to be set at the start of every model.
;;; 2013.08.06 Dan
;;; : * Renaming custom-defaults to starting-parameters since it
;;; : doesn't actually change the default values and this name
;;; : feels like a better description.
;;; 2014.09.03 Dan
;;; : * When testing the :starting-parameters param names need to
;;; : make sure there is a current meta-process.
;;; 2015.06.05 Dan
;;; : * Use schedule-event-now for initial check.
;;; 2016.09.28 Dan
;;; : * Removed a with-meta-process from test-user-defaults-parameter.
;;; 2017.08.07 Dan
;;; : * Add a lock for the *subsymbolic-parameter-values* variable.
;;; 2017.08.15 Dan
;;; : * Add a lock for the central-parameters parameters.
;;; 2018.04.10 Dan
;;; : * Add a remote version of register-subsymbolic-parameters.
;;; 2018.06.22 Dan
;;; : * Fixed a bug with the remote register-subsymbolic-parameters.
;;; 2019.02.15 Dan
;;; : * If :starting-parameters is set to nil don't try to create
;;; : a model to test the values since there aren't any to check.
;;; 2020.01.10 Dan [1.3]
;;; : * Removed the #' and lambdas from the module interface functions
;;; : since that's not allowed in the general system now.
;;; 2021.10.19 Dan [2.0]
;;; : * Set the :required flag on the module.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Creates a module to hold some of the critical parameters that may
;;; be used by multiple modules:
;;;
;;; :esc Enable Subsymbolic Computation
;;; :ol Optimized Learning
;;; :er Enable Randomness
;;;
;;; Also sets the model parameters to the values provided in the :starting-parameters
;;; system parameter for every model during the secondary reset.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; The three parameters :esc, :ol, and :er and also the system parameter :starting-parameters.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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 *subsymbolic-parameter-values* nil)
(defvar *spv-lock* (bt:make-lock "subsymbolic-parameter-values"))
(defvar *user-default-parameter-list* nil)
(defun test-user-defaults-parameter (params)
(and (listp params)
(evenp (length params))
(or (null params)
(let ((names (let ((i -1)) (mapcan (lambda (x) (incf i) (when (evenp i) (list x))) params))))
(and
(every 'keywordp names)
(if (current-model)
(notany (lambda (y)
(eq :bad-parameter-name (car (no-output (sgp-fct (list y))))))
names)
(let ((name (define-model-fct (gensym) nil))
(res nil))
(with-model-eval name
(setf res (notany (lambda (y)
(eq :bad-parameter-name (car (no-output (sgp-fct (list y))))))
names)))
(delete-model-fct name)
res)))))))
(create-system-parameter :starting-parameters :handler (simple-system-param-handler *user-default-parameter-list*)
:documentation "Parameter settings to apply at the start of every model."
:valid-test 'test-user-defaults-parameter
:warning "A list that is valid for passing to sgp-fct"
:default-value nil)
(defstruct central-parameters
esc ol er (lock (bt:make-lock "central-parameters")))
(defun central-parameters-reset (instance)
(schedule-event-now 'check-for-esc-nil :maintenance t :output nil
:priority :max :params (list instance))
(when *user-default-parameter-list*
(sgp-fct *user-default-parameter-list*)))
(defun check-for-esc-nil (instance)
(when (and (null (bt:with-lock-held ((central-parameters-lock instance)) (central-parameters-esc instance)))
(some (lambda (param)
(let ((current (car (no-output (sgp-fct (list param))))))
(and (not (eq current :BAD-PARAMETER-NAME))
(not (equalp current (get-parameter-default-value param))))))
(bt:with-lock-held (*spv-lock*) *subsymbolic-parameter-values*)))
(model-warning "Subsymbolic parameters have been set but :esc is currently nil.")))
(defun register-subsymbolic-parameters (&rest params)
(bt:with-lock-held (*spv-lock*)
(dolist (param params)
(when (and (valid-parameter-name param)
(not (find param *subsymbolic-parameter-values*)))
(push param *subsymbolic-parameter-values*)))))
(defun remote-register-subsymbolic-parameters (&rest params)
(apply 'register-subsymbolic-parameters (string->name-recursive params)))
(add-act-r-command "register-subsymbolic-parameters" 'remote-register-subsymbolic-parameters "Specify parameters which require :esc to be t so that the system can warn if it is nil when they are used. Params: param-name*")
(defun create-central-params (model-name)
(declare (ignore model-name))
(make-central-parameters))
(defun central-parameters-params (instance param)
(bt:with-lock-held ((central-parameters-lock instance))
(cond ((consp param)
(case (car param)
(:esc (setf (central-parameters-esc instance) (cdr param)))
(:ol (setf (central-parameters-ol instance) (cdr param)))
(:er (setf (central-parameters-er instance) (cdr param)))))
(t
(case param
(:esc (central-parameters-esc instance))
(:ol (central-parameters-ol instance))
(:er (central-parameters-er instance)))))))
(define-module-fct 'central-parameters nil
(list
(define-parameter :esc :owner t :valid-test 'tornil :default-value nil
:warning "either t or nil" :documentation "Enable Subsymbolic Computations")
(define-parameter :er :owner t :valid-test 'tornil :default-value nil
:warning "either t or nil" :documentation "Enable Randomness")
(define-parameter :ol :owner t :valid-test 'posnumorbool
:default-value t :warning "either t, nil, or a positive number"
:documentation "Optimized Learning"))
:version "2.0"
:documentation "a module that maintains parameters used by other modules"
:creation 'create-central-params
:params 'central-parameters-params
:reset (list nil 'central-parameters-reset)
:required t)
(provide "CENTRAL-PARAMETERS")
#|
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
|#
| 9,435 | Common Lisp | .lisp | 196 | 42.938776 | 222 | 0.587131 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5b106d32e68d616027ec96655994fbeafca083c22cdb0a13ae4af6059dc93a10 | 14,207 | [
-1
] |
14,208 | general-pm.lisp | asmaloney_ACT-R/support/general-pm.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-2003 Mike Byrne
;;; Availability: Covered by the GNU LGPL, see LICENSE.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : general-pm.lisp
;;; Version : 6.0
;;;
;;; Description : Base class for the perceptual-motor modules.
;;;
;;; Bugs :
;;;
;;; Todo : [X] Strip out waiting-for-proc-p stuff?
;;;
;;; ----- History -----
;;; 01.07.27 mdb
;;; : Started 5.0 conversion.
;;; 02.01.21 mdb
;;; : Removed obsolete PROC-S function, renamed slot value function
;;; : to be PROC-S. Added INITIAITON-COMPLETE call.
;;; 2002.05.07 mdb [b6]
;;; : Processor wasn't being set to BUSY while preparation was
;;; : ongoing, which made Bad Things (tm) happen. Fixed.
;;; 2002.06.05 mdb
;;; : Added step-hook call in RUN-MODULE to support the environment.
;;; 2002.06.27 mdb [b7]
;;; : Moved CHECK-SPECS here and made it print an actual informative
;;; : warning message. Wild.
;;; 2003.01.21 mdb [2.1.1]
;;; : Updated the DM state a smidge less often.
;;; 2003.02.06 mdb
;;; : Added a VERSION-STRING slot to the base module so each one
;;; : can track version numbers separately, in anticipation of
;;; : some more separate handling under ACT-R 6.0.
;;; 2003.04.30 mdb [2.1.2]
;;; : Fixed bug in prepare-only motor movements not leaving
;;; : processor free.
;;;
;;; 2004.10.20 Dan [First pass at moving things to ACT-R 6]
;;; : Changed name to general-pm and reset version to 1.0a1
;;; : Placed it in with the support code
;;; : modules that use it should have this call in them:
;;; : (require-compiled "GENERAL-PM" "ACT-R6:support;general-pm")
;;; : Flagged my changes with comments starting with DAN
;;; :
;;; : Removed:
;;; : run-module
;;; : new-message
;;; : pm-install-module
;;; : update-dm-state
;;; : print-input-queue
;;; : silent-events
;;; :
;;; : update-module gets called a little differently and if
;;; : possible I'd prefer to remove it.
;;; :
;;; : Renamed reset-module to reset-pm-module
;;; :
;;; : Put the spec class and methods in here
;;; :
;;; : Did not adjust the class definition though some things are
;;; : no longer necessary
;;; 2005.01.07 mdb
;;; : * Changed the class def to remove some obsolete stuff.
;;; : * Added GENERIC-STATE-QUERY method.
;;;
;;; 2005.01.09 Dan
;;; : Moved the provide to the end.
;;; 2005.01.12 Dan
;;; : * Added the old-time and new-time parameters to update-module
;;; : which breaks backward compatibility but makes things
;;; : cleaner for moving the device into a module.
;;; : * Put the state case into the generic-state-query method
;;; 2005.04.23 Dan
;;; : * Removed the stuffed slot from the attn-module class.
;;; : * Added the print-module-status method for displaying the
;;; : query data for a module - a lot like print-module-state.
;;; 2005.05.11 Dan
;;; : * Added the output parameter to queue-command so that I
;;; : can control the detail level for generated events.
;;; : Really, queue-command should be phased out, but for now
;;; : it's easier to just keep it around...
;;; 2005.07.22 Dan
;;; : * Added the last-command reporting to the print-module-status
;;; : and the check to generic-query
;;; : * Added the pm-module-request after method to make sure that
;;; : the last-cmd slot gets set for all modules.
;;; 2005.07.25 Dan
;;; : * Changed the reset method so that last-command starts at none
;;; : which is the same as the value it gets on a clear.
;;; 2005.08.10 Dan
;;; : * Minor clean-up to declare ignored parameters in update-
;;; : module method (can that go away yet?).
;;; : * Also added an ignore to queue-command for sent-by-act.
;;; : * Updated version to 1.0.
;;; 2006.12.18 Dan
;;; : * Took modality out of the print-module-status method.
;;; 2007.01.08 Dan
;;; : * Took the ~% off the end of the jammed warning.
;;; 2007.05.24 Dan
;;; : * Took the source-activation slot out of the attn-module class.
;;; : * Removed the unnecessary partially-clear-attended method stuff.
;;; 2007.02.04 Dan
;;; : * Adjusted preparation-complete so that it only clears the
;;; : processor state if the previous movement initiation has
;;; : passed. Doesn't occur in many situations, but when the
;;; : prepare reqeusts are made it can lead to some unexpected
;;; : free states of the module's processor.
;;; 2010.02.15 Dan
;;; : * Took the :allocation class out of several slots of the
;;; : pm-module class because that could interfere with changing
;;; : things when running multiple models.
;;; 2011.04.26 Dan
;;; : * Removed calls to pm-output and pm-warning, but left them
;;; : in since the old vision code in extras uses pm-output and
;;; : a bunch of the PM modules still use pm-warning.
;;; : * Changed the preparation check and init-stamp to use mp-time-ms.
;;; 2011.05.17 Dan
;;; : * Removed all usage of queue-command.
;;; 2014.04.25 Dan
;;; : * Finally handling the todo that's been there since ACT-R/PM
;;; : with ACT-R 4.0 - remove the waiting-for-proc-p stuff.
;;; : * Removed a lot of unused methods.
;;; : * Removed some old comments and other minor cleanup while I'm
;;; : here.
;;; 2014.05.16 Dan [3.0]
;;; : * Start of the conversion to deal with type-less chunks.
;;; : * Setting the "last-command" for a pm-module checks whether
;;; : it's "isa clear" or has a slot named cmd to get the value.
;;; : If that fails then it calls the pm-module-last-cmd-name
;;; : method for the module with the buffer and chunk-spec.
;;; : * Removed the spec class and corresponding methods since
;;; : audio was the only thing that used it and that's going to
;;; : a chunk-based search now.
;;; 2014.05.30 Dan
;;; : * Added the test-for-clear-request function which can be used
;;; : by the modules to test for "isa clear" or "cmd clear" requests
;;; : based on the default type clear.
;;; 2014.11.07 Dan
;;; : * Added a safety check to test-for-clear-request, now verify that
;;; : the modifier is always =, and cleaned up the logic in how it's
;;; : tested a little bit.
;;; 2015.03.16 Dan
;;; : * Fixed a bug with preparation-complete introduced with the
;;; : 2007.02.24 fix. If a prepare was the first action the model
;;; : performed then (thus a negative init-stamp) it would leave
;;; : the processor busy until some other action cleared it.
;;; 2015.04.21 Dan
;;; : * Attention modules have a new slot: unstuff-loc. Which is
;;; : to be used as a flag for clearing a stuffed buffer after
;;; : some time has passed (value of the slot if not t which
;;; : indicates some module specific default).
;;; : * And there's a method check-unstuff-buffer which can be
;;; : scheduled for an attention module that will check if the
;;; : chunk in the buffer is an unmodified copy of the one which
;;; : was stuffed, or if that chunk no longer exists, just an
;;; : unmodified stuffed chunk, and if that's true then it will
;;; : clear the buffer.
;;; 2015.06.05 Dan
;;; : * Explicitly convert times for scheduled events to ms.
;;; 2015.07.28 Dan
;;; : * Removed the *act-r-6.0-compatibility* hack.
;;; 2015.07.29 Dan
;;; : * Split check-unstuff-buffer into two methods: check-unstuff-buffer
;;; : and unstuff-buffer. The first is now used as a precondition
;;; : in an event and the other schedules the erase action.
;;; : * Added the overstuff-loc slot to the attention module class.
;;; : * Added an unstuff-event slot to the attention module class.
;;; 2015.08.13 Dan
;;; : * Changed rand-time calls to randomize-time.
;;; 2015.09.16 Dan [4.0]
;;; : * The clear method now calls complete-all-module-requests for
;;; : the module after it changes the state back.
;;; : * The clear method now actually uses the feat-prep-time of the
;;; : specific module to schedule the change.
;;; 2015.09.21 Dan
;;; : * Adding a prepare-spec slot to the pm-module class to use
;;; : for storing the spec for later completion since the prepare
;;; : method isn't passed the spec itself.
;;; : * Added the request-spec slot to the movement-style class.
;;; : * Prepare stores the request in the request-spec slot of the
;;; : style from the prepare-spec slot of the module.
;;; : * Preparation-complete method completes the request if it is
;;; : not set to execute now i.e. it was just a prepare.
;;; : * Finish-movement method now also requires the movement-style,
;;; : and it calls complete-spec on the request-spec of that style.
;;; : * Defstyle automatically adds a request-spec keyword param as
;;; : one of the method keys.
;;; : * Execute method now requires the request spec to be able to
;;; : complete it.
;;; 2015.09.23 Dan
;;; : * The defstyle method for movements now completes the request
;;; : in the event that it is jammed.
;;; 2017.01.05 Dan
;;; : * Removed the input-q slot since nothing uses that now.
;;; 2017.08.09 Dan
;;; : * Have print-module-status return the string instead of directly
;;; : outputting the data.
;;; : * Removed reset-pm-module and clear methods on the attn-module
;;; : class because those slots need to be protected and don't want
;;; : to have to deal with recursive locking issues.
;;; : * Also eliminating the set/clear-attended methods for same
;;; : reason.
;;; 2017.08.10 Dan
;;; : * Fixed a bug in how check-unstuff-buffer works because it
;;; : should always require that the chunk was 'stuffed' to avoid
;;; : clearing a chunk a requested chunk that matches the last
;;; : one stuffed.
;;; 2018.01.26 Dan
;;; : * Changed the print-module-status function to omit the extra newline.
;;; 2018.06.01 Dan [5.0]
;;; : * Adding locks to protect the internal states and the
;;; : the preparation-spec.
;;; : * Allow a clear request to happen regardless of the preparation
;;; : state so that it can be used to cancel requests.
;;; : * Removed print-module-state since it's unused.
;;; : * Moved the param-lock here since some general commands need
;;; : it for computing times.
;;; 2018.06.08 Dan
;;; : * Added a remote test-for-clear-request and allow it to take
;;; : a chunk-spec id in addition to a chunk-spec.
;;; 2018.07.26 Dan [5.1]
;;; : * Don't worry about request tracking.
;;; 2019.05.22 Dan
;;; : * The unstuff-buffer function should clear the unstuff-event
;;; : slot of the module as should resetting the module.
;;; 2020.03.20 Dan [6.0]
;;; : * A clear request now also clears the processor state because
;;; : previously it could get stuck busy if there was a pending
;;; : action that was still waiting on execution.
;;; : * Hand positions have been abstracted to a separate struct
;;; : and the hand now holds two such structures. One is where
;;; : the hand is currently and the other is where it will be for
;;; : the purposes of computing the next set of features. That's
;;; : necessary because it may need to compute the next set of
;;; : features before the current action has occurred and it can't
;;; : set the position at the end of feature computation because
;;; : that would be a problem for an action that hasn't yet
;;; : occurred.
;;; : * Added an updated-pos slot to the movement-style class and
;;; : added the new method prepare-features which gets called when
;;; : the request is processed. That method should set the
;;; : updated-pos slot of the movement to a hand-pos struct if
;;; : there will be a change in the hand and/or finger positions
;;; : at execution time. Then in queue-output-events it should
;;; : schedule a set-hand-position action with the updated-pos to
;;; : move the hand (don't need to recompute it).
;;; : * Movement styles now have a request-time slot that gets set
;;; : when instantiated which is used in the preparation complete,
;;; : initiation complete, and finish movement events so that it's
;;; : easy to figure out what's what when overlapping requests
;;; : happen.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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)
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Perceptual/motor Modules base class
;;;; ---------------------------------------------------------------------- ;;;;
;;; PM-MODULE [Class]
;;; Date : 97.01.15, delta 2003.02.06
;;; Description : Base class for the various modules, includes input
;;; : queue and basic state information.
(defclass pm-module ()
((modality-state :accessor mode-s :initform 'FREE :initarg :modality)
(processor-state :accessor proc-s :initform 'FREE :initarg :processor)
(preparation-state :accessor prep-s :initform 'FREE :initarg :preparation)
(execution-state :accessor exec-s :initform 'FREE :initarg :execution)
(state-change-flag :accessor state-change :initarg :state-change :initform nil)
(module-name :accessor my-name :initarg :name :initform nil)
(last-command :accessor last-cmd :initform nil :initarg :last-command)
(last-prep :accessor last-prep :initarg :last-prep :initform nil)
(exec-queue :accessor exec-queue :initarg :exec-queue :initform nil)
(feature-prep-time :accessor feat-prep-time :initarg :feat-prep-time :initform 0.050)
(movement-initiation-time :accessor init-time :initarg :init-time :initform 0.050)
(init-stamp :accessor init-stamp :initarg :init-stamp :initform -0.1)
(burst-time :accessor burst-time :initarg :burst-time :initform 0.050)
(version-string :accessor version-string :initarg :version-string :initform "")
(prepare-spec :accessor prepare-spec :initform "")
(state-lock :accessor state-lock :initform (bt:make-recursive-lock "state-lock"))
(prep-spec-lock :accessor prep-spec-lock :initform (bt:make-lock "prep-spec"))
(param-lock :accessor param-lock :initform (bt:make-recursive-lock "pm-param-lock"))))
;;; CHANGE-STATE [Method]
;;; Date : 97.02.10
;;; Description : Change one or more of a module's state flags.
(defgeneric change-state (module &key proc exec prep last)
(:documentation "Change one or more of a module's state flags."))
(defmethod change-state ((module pm-module) &key proc exec prep last)
(bt:with-recursive-lock-held ((state-lock module))
(when proc (setf (proc-s module) proc))
(when exec (setf (exec-s module) exec))
(when prep (setf (prep-s module) prep))
(when last (setf (last-cmd module) last))
(if (or (eq (proc-s module) 'busy) (eq (exec-s module) 'busy)
(eq (prep-s module) 'busy))
(setf (mode-s module) 'busy)
(setf (mode-s module) 'free))
(setf (state-change module) t)))
;;; CLEAR [Method]
;;; Date : 97.03.03
;;; Description : Clears a module's state, takes one feature prep time.
#| CLEAR is already a generic function in MCL.
(defgeneric clear (module)
(:documentation "Clears a PM module."))
|#
(defmethod clear ((module pm-module))
(bt:with-recursive-lock-held ((state-lock module))
(bt:with-recursive-lock-held ((param-lock module))
; Don't care about current state so that it can cancel
; an ongoing action.
; (when (not (check-jam module))
(change-state module :prep 'busy)
(schedule-event-relative (feat-prep-time module) 'change-state :destination (my-name module) :module (my-name module) :params '(:last none :prep free :proc free))
(setf (last-prep module) nil)
(setf (exec-queue module) nil)
(setf (init-stamp module) -0.1))))
;;; CHECK-JAM [Method]
;;; Date : 97.02.18
;;; Description : Modules can't take certain types of commands if they are
;;; : already busy, and this checks the preparation state of a
;;; : module for just this problem.
(defgeneric check-jam (module)
(:documentation "Returns NIL if the PM module is free, otherwise prints an error message and returns T."))
(defmethod check-jam ((module pm-module))
(bt:with-recursive-lock-held ((state-lock module))
(when (eq (prep-s module) 'busy)
(model-warning "Module ~S jammed at time ~S" (my-name module) (mp-time))
t)))
;;; RESET-PM-MODULE [Method]
;;; Date : 97.02.18
;;; Description : When a module needs to be reset, that means both that all
;;; : state indicators should be set to FREE and the input queue
;;; : should be cleared.
(defgeneric reset-pm-module (module)
(:documentation "Resets a PM module to base state: all flags free, empty input queue."))
(defmethod reset-pm-module ((module pm-module))
(bt:with-recursive-lock-held ((state-lock module))
(setf (proc-s module) 'free)
(setf (exec-s module) 'free)
(setf (prep-s module) 'free)
(setf (mode-s module) 'free)
(setf (last-cmd module) 'none)
(setf (last-prep module) nil)
(setf (exec-queue module) nil)
(setf (init-stamp module) -0.1)))
(defgeneric pm-module-last-cmd-name (module buffer-name chunk-spec)
(:documentation "Determine the name of the last command when it's not 'isa clear' and doesn't have a cmd slot."))
(defmethod pm-module-last-cmd-name ((module pm-module) buffer-name chunk-spec)
(declare (ignorable module buffer-name chunk-spec)))
(defgeneric pm-module-request (module buffer-name chunk-spec)
(:documentation "Handles a request from a buffer."))
;;; This after method is used to make sure that all commands
;;; processed record the command in the module.
(defmethod pm-module-request :after ((module pm-module) buffer-name chunk-spec)
(let ((last-cmd (or (let ((spec (chunk-spec-slot-spec chunk-spec)))
(and (= (length spec) 1)
(eq 'clear (spec-slot-name (first spec)))
(spec-slot-value (first spec))
'clear))
(let ((spec (chunk-spec-slot-spec chunk-spec 'cmd)))
(and (= (length spec) 1)
(spec-slot-value (first spec))))
(pm-module-last-cmd-name module buffer-name chunk-spec))))
(when (and last-cmd (not (eql (last-cmd module) last-cmd)))
(change-state module :last last-cmd))))
;;; PRINT-MODULE-STATUS
(defgeneric print-module-status (module)
(:documentation "Prints the module's state in query form"))
(defmethod print-module-status ((mod pm-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~%"
(eq (proc-s mod) 'free))
(format nil " processor busy : ~S~%"
(eq (proc-s mod) 'busy))
(format nil " execution free : ~S~%"
(eq (exec-s mod) 'free))
(format nil " execution busy : ~S~%"
(eq (exec-s mod) 'busy))
(format nil " last-command : ~S"
(last-cmd mod)))))
(defgeneric check-state (module &key modality preparation
execution processor last-command)
(:documentation "Does a quick test of the state of a PM module, returning T iff all the specified states match."))
(defmethod check-state ((mod pm-module) &key modality preparation
execution processor last-command)
(bt:with-recursive-lock-held ((state-lock mod))
(cond ((and modality (not (eq modality (mode-s mod)))) nil)
((and preparation (not (eq preparation (prep-s mod)))) nil)
((and execution (not (eq execution (exec-s mod)))) nil)
((and processor (not (eq processor (proc-s mod)))) nil)
((and last-command (not (eq last-command (last-cmd mod)))) nil)
(t t))))
(defgeneric generic-state-query (module buffer slot value)
(:documentation "Handles BUSY/FREE tests on STATE, MODALITY, EXECUTION, PREPARATION and PROCESSOR."))
(defmethod generic-state-query ((module pm-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 (model-warning
"Invalid query made of the ~S buffer with slot ~S and value ~S"
buffer slot value))))
(execution
(case value
(busy
(eq (exec-s module) 'busy))
(free
(eq (exec-s module) 'free))
(t (model-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 (model-warning "Invalid query made of the ~S buffer with slot ~S and value ~S"
buffer slot value))))
(processor
(case value
(busy
(eq (proc-s module) 'busy))
(free
(eq (proc-s module) 'free))
(t (model-warning "Invalid query made of the ~S buffer with slot ~S and value ~S"
buffer slot value))))
(last-command
(eql (last-cmd module) value)))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; preparation and execution stuff
;;; Update-prepared
;;;
;;; Set the location for next preparation purposes
;;; now, but don't update the actual location.
(defgeneric update-prepared (module)
(:documentation "Method called when execution is planned for an action to update the location."))
(defmethod update-prepared ((module pm-module))
)
;;; PREPARATION-COMPLETE [Method]
;;; Date : 98.07.22
;;; Description : When movement preparation completes: change the prep
;;; : state, check to see if the movement just prepared wants
;;; : to execute right away, and then possibly execute a
;;; : movement.
(defgeneric preparation-complete (module)
(:documentation "Method to be called when movement preparation is complete."))
(defmethod preparation-complete ((module pm-module))
(bt:with-recursive-lock-held ((state-lock module))
(change-state module :prep 'free)
(when (last-prep module)
(if (exec-immediate-p (last-prep module))
(progn
(setf (exec-queue module)
(append (exec-queue module) (mklist (last-prep module))))
(when (updated-pos (last-prep module))
(update-prepared module)))
(bt:with-recursive-lock-held ((param-lock module))
(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 'FREE)))))
(maybe-execute-movement module)))
;;; MAYBE-EXECUTE-MOVEMENT [Method]
;;; Date : 98.07.22
;;; Description : If there is a movement queued and the motor state is FREE,
;;; : then execute the movment. Also, free the processor state
;;; : with an event if necessary.
(defgeneric maybe-execute-movement (module)
(:documentation "If there are any movements in <module>'s execution queue, execute one."))
(defmethod maybe-execute-movement ((module pm-module))
(bt:with-recursive-lock-held ((state-lock module))
(when (and (exec-queue module) (eq (exec-s module) 'FREE))
(perform-movement module (pop (exec-queue module))))))
;;; PREPARE [Method]
;;; Date : 98.08.21
;;; Description : Build a movement style instance via APPLY, set it to not
;;; : automatically execute itself, and prepare it.
(defgeneric prepare (module &rest params)
(:documentation "Prepare a movement to be executed, but don't execute it. The first of <params> should be the name of a movement style class."))
(defmethod prepare ((module pm-module) &rest params)
(let ((inst (apply #'make-instance params)))
(setf (exec-immediate-p inst) nil)
(setf (request-spec inst) (bt:with-lock-held ((prep-spec-lock module)) (prepare-spec module)))
(prepare-movement module inst)))
;;; EXECUTE [Method]
;;; Date : 98.08.21
;;; Description : Executing the previously prepared command requires
;;; : [1] A previously-prepared command, and
;;; : [2] No command currently being prepared.
;;; : If those are OK, put the current style instance in the
;;; : execution queue and go for it.
(defgeneric execute (module request)
(:documentation "Tells <module> to execute the last movement prepared."))
(defmethod execute ((module pm-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)))))
;;; PM-PREPARE-MOTOR-MTH [Method]
;;; Date : 98.09.24
;;; Description : If RPM is to begin a run with features already prepared,
;;; : this is the method to do it. Create a movement instance,
;;; : kill the exec-immediate, and set the last prepared movement
;;; : to the created movement.
(defgeneric pm-prepare-mvmt-mth (module params)
(:documentation "Create the movement specified in <params>, which should begin with the name of a movement style, and consider it prepared. To be called only at model initialization."))
(defmethod pm-prepare-mvmt-mth ((module pm-module) params)
(let ((inst (apply #'make-instance params)))
(setf (exec-immediate-p inst) nil)
(bt:with-recursive-lock-held ((state-lock module))
(setf (last-prep module) inst))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; MOVEMENT-STYLE class and methods
;;;; ---------------------------------------------------------------------- ;;;;
(defclass movement-style ()
((fprep-time :accessor fprep-time :initform nil :initarg :fprep-time)
(exec-time :accessor exec-time :initform nil :initarg :exec-time)
(finish-time :accessor finish-time :initform nil :initarg :finish-time)
(exec-immediate-p :accessor exec-immediate-p :initform t
:initarg :exec-immediate-p)
(num-features :accessor num-features :initform nil
:initarg :num-features)
(style-name :accessor style-name :initarg :style-name :initform nil)
(feature-slots :accessor feature-slots :initarg :feature-slots
:initform nil)
(request-spec :accessor request-spec :initarg :request-spec :initform nil)
(updated-pos :accessor updated-pos :initform nil)
(request-time :accessor request-time :initform (mp-time))))
;;; PREPARE-MOVEMENT [Method]
;;; Date : 98.07.22
;;; Description : Change the prep state, compute the feature prep time,
;;; : note that we're the last feature the MM has prepared,
;;; : and queue the preparation complete event.
(defgeneric prepare-movement (module movement)
(:documentation "Tell <module> to prepare <movement>."))
(defmethod prepare-movement ((module pm-module) (mvmt movement-style))
(bt:with-recursive-lock-held ((state-lock module))
(change-state module :prep 'BUSY :proc '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)))))
(defgeneric prepare-features (module movement)
(:documentation "Compute the features needed for movement and store position in updated-pos."))
(defmethod prepare-features ((module pm-module) (mvmt movement-style))
)
;;; COMPUTE-PREP-TIME [Method]
;;; Date : 98.07.22
;;; Description : Computing the prep time. If this is a different kind of
;;; : movement or a totall new movement, then just return the
;;; : number of features times the time per feature. If the
;;; : old movement is similar, compute the differences (a
;;; : method for this must be supplied).
(defgeneric compute-prep-time (module movement)
(:documentation "Return the feature preparation time for <movement>."))
(defmethod compute-prep-time ((module pm-module) (mvmt movement-style))
(bt:with-recursive-lock-held ((state-lock module))
(bt:with-recursive-lock-held ((param-lock module))
(if (or (null (last-prep module))
(not (eq (style-name mvmt) (style-name (last-prep module)))))
(* (feat-prep-time module) (num-to-prepare mvmt))
(* (feat-prep-time module)
(feat-differences mvmt (last-prep module)))))))
;;; PERFORM-MOVEMENT [Method]
;;; Date : 98.07.22
;;; Description : Performing a movement has several pieces to it. First,
;;; : bookkeeping (exec state and start time). Next we need
;;; : to compute times. Then, queue the events (movement
;;; : specific) that reflect our output, and finally queue
;;; : the event indicating completion of the movement.
(defgeneric perform-movement (module movement)
(:documentation "Have <module> perform <movement>."))
(defmethod perform-movement ((module pm-module) (mvmt movement-style))
(bt:with-recursive-lock-held ((param-lock module))
(schedule-event-relative (seconds->ms (init-time module)) 'initiation-complete
:time-in-ms t :destination (my-name module) :module (my-name module)
:details (concatenate 'string (symbol-name 'initiation-complete) " "
(princ-to-string (request-time mvmt)))))
(change-state module :proc 'BUSY :exec 'BUSY)
(bt:with-recursive-lock-held ((state-lock module))
(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))
(queue-output-events module mvmt)
(queue-finish-event module mvmt))
(defmethod initiation-complete ((module pm-module))
(change-state module :proc 'FREE))
;;; FINISH-MOVEMENT [Method]
;;; Date : 98.07.22
;;; Description : When a movement completes, FREE the execution state, and
;;; : check to see if there were any movements queued.
(defgeneric finish-movement (module mvmt)
(:documentation "Method called when a movement finishes completely."))
(defmethod finish-movement ((module pm-module) (mvmt movement-style))
(change-state module :exec 'free)
(maybe-execute-movement module))
;;; COMPUTE-FINISH-TIME [Method]
;;; Date : 98.07.22
;;; Description : Default finish time is simply execution time plus the
;;; : burst time--some styles will need to override this.
(defgeneric compute-finish-time (module movement)
(:documentation "Return the finish time of <movement>."))
(defmethod compute-finish-time ((module pm-module) (mvmt movement-style))
"Return the finish time of the movement."
(bt:with-recursive-lock-held ((param-lock module))
(+ (burst-time module) (exec-time mvmt))))
;;; QUEUE-FINISH-EVENT [Method]
;;; Date : 98.07.22
;;; Description : Queue the event that frees the exec of the MM.
(defgeneric queue-finish-event (module movement)
(:documentation "Queue the FINISH-MOVEMENT associated with <movement>."))
(defmethod queue-finish-event ((module pm-module) (mvmt movement-style))
(schedule-event-relative (seconds->ms (finish-time mvmt)) 'finish-movement
:time-in-ms t :destination (my-name module)
:params (list mvmt) :module (my-name module)
:details (concatenate 'string (symbol-name 'finish-movement) " "
(princ-to-string (request-time mvmt)))))
;;; Stubs that require overrides.
(defgeneric compute-exec-time (module movement)
(:documentation "Return the execution time of <movement>."))
(defmethod compute-exec-time ((module pm-module) (mvmt movement-style))
(error "No method defined for COMPUTE-EXEC-TIME."))
(defgeneric queue-output-events (module movement)
(:documentation "Queue the events--not including the FINISH-MOVEMENT--that <movement> will generate."))
(defmethod queue-output-events ((module pm-module) (mvmt movement-style))
(error "No method defined for QUEUE-OUTPUT-EVENTS."))
(defgeneric feat-differences (movement1 movement2)
(:documentation "Return the number of different features that need to be prepared."))
(defmethod feat-differences ((move1 movement-style) (move2 movement-style))
;(declare (ignore move1 move2))
(error "No method defined for FEAT-DIFFERENCES."))
(defgeneric num-possible-feats (movement)
(:documentation "Return the maximum number of features that could possibly need to be prepared."))
(defmethod num-possible-feats ((mvmt movement-style))
(1+ (length (feature-slots mvmt))))
(defgeneric num-to-prepare (movement)
(:documentation "Return the number of features actually needed to prepare <movement>."))
(defmethod num-to-prepare ((mvmt movement-style))
(1+ (length (remove :DUMMY
(remove nil
(mapcar #'(lambda (name)
(slot-value mvmt name))
(feature-slots mvmt)))))))
(defmacro defstyle (name base-class &rest params)
"Macro that defines new motor movement styles. Pass in the name and the base
class [if NIL is passed, it will default to MOVEMENT-STYLE] and the base
parameters. This will create a class and a method for any PM Module for the
class."
`(progn
(defclass ,name (,(if (not base-class) 'movement-style base-class))
,(build-accessors params)
(:default-initargs
:style-name ,(sym->key name)
:feature-slots ',params))
(defmethod ,name ((module pm-module) &key ,@params request-spec)
(unless (or (check-jam module) (check-specs ',name ,@params))
(prepare-movement module
(make-instance ',name :request-spec request-spec
,@(build-initializer params)))))))
(defun check-specs (name &rest specs)
"If there is an invalid specification, return something, else NIL"
(when (member nil specs)
(model-warning "NIL specification passed to a PM command ~S: ~S" name specs)
t))
;;; BUILD-ACCESSORS [Function]
;;; Date : 98.11.02
;;; Description : Helper function for DEFSTYLE.
(defun build-accessors (params)
"From a list of parameters, a list of slot definitions."
(let ((accum nil))
(dolist (param params (nreverse accum))
(push (list param :accessor param :initarg (sym->key param)
:initform nil) accum))))
;;; BUILD-INITIALIZER [Function]
;;; Date : 98.11.02
;;; Description : Helper function for DEFSTYLE.
(defun build-initializer (params)
"From a list of parameters, build a list for the make-instance initializer."
(let ((accum nil))
(dolist (param params (nreverse accum))
(push (sym->key param) accum)
(push param accum))))
;;;; ---------------------------------------------------------------------- ;;;;
;;;; Attentional modules
;;;; ---------------------------------------------------------------------- ;;;;
;;; ATTN-MODULE [Class]
;;; Date : 00.06.09
;;; Description : Class for modules that have attentional capability.
;;; : CURRENTLY-ATTENDED hold the focus object
;;; : object gets
;;; : CURRENT-MARKER denotes the location/event currently attended
(defclass attn-module (pm-module)
((currently-attended :accessor currently-attended
:initarg :currently-attended :initform nil)
(current-marker :accessor current-marker :initarg :current-marker
:initform nil)
;; mdb moved from vision module definition 2005.01.07
(loc-failure :accessor loc-failure :initform nil)
(attend-failure :accessor attend-failure :initform nil)
;; modules can "unstuff" perceptual info if needed
(unstuff-loc :accessor unstuff-loc :initform nil)
(unstuff-event :accessor unstuff-event :initform nil)
(overstuff-loc :accessor overstuff-loc :initform nil)))
(defmethod reset-pm-module :after ((module attn-module))
(setf (unstuff-event module) nil))
(defmethod check-unstuff-buffer ((module attn-module) buffer chunk)
(let ((current (buffer-read buffer)))
(and
current
(query-buffer buffer '(buffer unrequested))
(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)
;; the original is no longer a chunk (deleted or purged)
;; so all that can be tested is whether the chunk in the
;; buffer was copied from some chunk and hasn't been changed
(and (null (chunk-p-fct chunk))
was-copy))))))
(defmethod unstuff-buffer ((module attn-module) buffer chunk)
(declare (ignore chunk))
(setf (unstuff-event module) nil)
(schedule-event-now 'erase-buffer :params (list buffer) :module (my-name module)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Detect the clear requests.
(defun test-for-clear-request (spec)
(if (act-r-chunk-spec-p spec)
(let ((main-spec (chunk-spec-slot-spec spec)))
(and (= (length main-spec) 1)
(eq '= (spec-slot-op (first main-spec)))
(or (and
(eq (spec-slot-name (first main-spec)) 'clear)
(spec-slot-value (first main-spec)))
(and
(eq (spec-slot-name (first main-spec)) 'cmd)
(eq (spec-slot-value (first main-spec)) 'clear)))))
(awhen (id-to-chunk-spec spec)
(test-for-clear-request it))))
(add-act-r-command "test-for-clear-request" 'test-for-clear-request "Determine if a chunk-spec represents the clear request used by many modules. Params: chunk-spec.")
(provide "GENERAL-PM")
#|
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
|#
| 42,398 | Common Lisp | .lisp | 782 | 49.69821 | 187 | 0.61573 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | b81927acc1566a1099bd689e040092d2d12aee380dfec2295f46c4202efaa4f1 | 14,208 | [
-1
] |
14,209 | hirschberg-diff-calculation.lisp | asmaloney_ACT-R/support/hirschberg-diff-calculation.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 : hirschberg-diff-calculation.lisp
;;; Version : 1.0
;;;
;;; Description : Compute optimal alignment between two sequences using the
;;; : Hirschberg algorithm.
;;;
;;; Bugs :
;;;
;;; To do : [-] Really optimize things by not using subseq and instead
;;; : just pass around indexes for the sequences.
;;;
;;; ----- History -----
;;; 2014.06.05 Dan [1.0]
;;; : * Initial creation.
;;; 2014.06.06 Dan
;;; : * Tried an indexes only version, but it didn't seem to be
;;; : much different. I'm guessing that the compilers cheat with
;;; : subseq and don't copy for non-modification uses. So, I've
;;; : left it with the subseq calls since it's easier to read.
;;; : * Coerce the results into string, list, or array based on
;;; : the general types of the initial params.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Compute the alignment between two sequences using the Hirschberg algorithm:
;;;
;;; Hirschberg, D. S. (1975). "A linear space algorithm for computing maximal common
;;; subsequences". Communications of the ACM 18 (6): 341-343.
;;;
;;; Based on the pseudocode from the Wikipedia page:
;;;
;;; <http://en.wikipedia.org/wiki/Hirschberg%27s_algorithm>
;;;
;;; as of 2014.06.05.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; hirschberg (x y &key (strip-ends t) (type 'character) (missing #\-) (key 'identity)
;;; (test 'eql) (ins -2) (del -2) (sub= 2) (sub!= -1) (coerce t)
;;;
;;; Align the sequences x and y and return two values. Those values are vectors
;;; of the same length. The first is a vector of elements from x along with
;;; instances of the 'missing' element and the second is elements from y along
;;; with instances of the 'missing' element. The two vectors indicate the
;;; best alignment of the sequences given the cost values for 'ins'erting
;;; an item, 'del'eting an item, matching an item (sub=), and transforming
;;; two items (sub!=). It assumes that sub= > sub!= > [ins, del] in creating
;;; the alignment.
;;;
;;; Type should specify the type of the elements of the sequences x and y.
;;; Missing should be a value of that type to be used for marking the points
;;; where one sequence has an item the other doesn't.
;;; Key should be a function requiring one parameter. It will be used to transform
;;; an element from a sequence into a value to be tested.
;;; Test should be a function requiring two parameters. It will be passed results
;;; of the key function applied to elements of the sequences for comparing them
;;; i.e. this test is performed to determine if an item from position i in
;;; sequence x matches the item at position j in sequence y:
;;; (funcall test (funcall key (elt x i)) (funcall key (elt y j)))
;;; Strip-ends determines whether the beginning and end of the sequences should
;;; first be tested for equality. If true then it assumes that the best
;;; alignment occurs when all the elements at the beginning of the sequences
;;; which match are aligned and that all of the elements which match at the
;;; ends of the sequence are aligned. This can save a lot of time on large
;;; sequences which have some overlap at either end.
;;; Coerce determines whether or not the resulting sequences are coerced to be
;;; of the same general types as the respective input values. If true then
;;; the results will be coerced into one of string, list, or array based on
;;; the input values. If nil then the results will always be vectors. The
;;; default value is true.
;;;
;;; If either x or y isn't a sequence then it returns nil. It doesn't catch any
;;; other errors in the parameters.
;;;
;;; Here're some example results using the example sequences from the Wikipedia page:
;;;
;;; > (hirschberg "AGTACGCA" "TATGC")
;;; "AGTACGCA"
;;; "--TATGC-"
;;; > (hirschberg (list #\A #\G #\T #\A #\C #\G #\C #\A) "TATGC")
;;; (#\A #\G #\T #\A #\C #\G #\C #\A)
;;; "--TATGC-"
;;; > (hirschberg "AGTACGCA" "TATGC" :coerce nil)
;;; #(#\A #\G #\T #\A #\C #\G #\C #\A)
;;; #(#\- #\- #\T #\A #\T #\G #\C #\-)
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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)
(eval-when (:compile-toplevel :load-toplevel :execute)
(proclaim '(optimize (speed 3) (safety 1) (space 1) (debug 0))))
(defun nwscore (x y &key key test ins del sub= sub!=)
(let* ((m (length x))
(n (length y))
(current)
(previous (make-array (list (1+ n)) :element-type 'fixnum :initial-element 0)))
(dotimes (j n)
(setf (aref previous (1+ j)) (+ (aref previous j) ins)))
(dotimes (i m)
(setf current (make-array (list (1+ n)) :element-type 'fixnum))
(dotimes (j (1+ n))
(let ((result (cond ((zerop j)
(+ (aref previous 0) del))
(t
(max
(+ (aref previous j) del)
(+ (aref current (1- j)) ins)
(+ (aref previous (1- j))
(if (funcall test (funcall key (elt x i)) (funcall key (elt y (1- j))))
sub= sub!=)))))))
(setf (aref current j) result)))
(setf previous current))
current))
(defun partitiony (v1 v2)
(let ((best nil)
(index nil)
(len (length v1)))
(dotimes (i (length v1) index)
(let ((sum (+ (elt v1 i) (elt v2 (- len i 1)))))
(when (or (null best) (> sum best))
(setf best sum
index i))))))
(defun hirschberg (x y &key (strip-ends t) (type 'character) (missing #\-) (key 'identity) (test 'eql) (ins -2) (del -2) (sub= 2) (sub!= -1) (coerce t))
(if (and (subtypep (type-of x) 'sequence)
(subtypep (type-of y) 'sequence))
(multiple-value-bind (z w)
(if strip-ends
(let* ((first-mismatch (do ((i 0 (1+ i)))
((or (= i (length x))
(= i (length y))
(not (funcall test (funcall key (elt x i)) (funcall key (elt y i))))) i)))
(end-match-count (do ((r (1- (length x)))
(o (1- (length y)))
(i 0 (1+ i)))
((or (= i (- (length x) first-mismatch))
(= i (- (length y) first-mismatch))
(not (funcall test (funcall key (elt x (- r i))) (funcall key (elt y (- o i)))))) i))))
(if (= first-mismatch (length x) (length y))
(values x y)
(let ((start (subseq x 0 first-mismatch))
(end (subseq x (- (length x) end-match-count))))
(multiple-value-bind (z w)
(hirschberg-rec (subseq x first-mismatch (- (length x) end-match-count))
(subseq y first-mismatch (- (length y) end-match-count))
:missing missing :type type :key key :test test :ins ins :del del :sub= sub= :sub!= sub!=)
(values (concatenate 'vector start z end) (concatenate 'vector start w end))))))
(hirschberg-rec x y :missing missing :type type :key key :test test :ins ins :del del :sub= sub= :sub!= sub!=))
(if coerce
(values (coerce z (cond ((stringp x) 'string) ((listp x) 'list) (t 'array)))
(coerce w (cond ((stringp y) 'string) ((listp y) 'list) (t 'array))))
(values z w)))
nil))
(defun hirschberg-rec (x y &key type missing key test ins del sub= sub!=)
(let (z w)
(cond ((zerop (length x))
(setf z (make-array (length y) :initial-element missing :element-type type)
w y))
((zerop (length y))
(setf w (make-array (length x) :initial-element missing :element-type type)
z x))
((= 1 (length x))
(let ((pos (position (funcall key (elt x 0)) y :test test :key key)))
(setf w y
z (make-array (length y) :initial-element missing :element-type type))
(if pos
(setf (elt z pos) (elt x 0))
(setf (elt z 0) (elt x 0)))))
((= 1 (length y))
(let ((pos (position (funcall key (elt y 0)) x :test test :key key)))
(setf z x
w (make-array (length x) :initial-element missing :element-type type))
(if pos
(setf (elt w pos) (elt y 0))
(setf (elt w 0) (elt y 0)))))
(t
(let* ((mid (floor (length x) 2))
(xl (subseq x 0 mid))
(xr (subseq x mid))
(scorel (nwscore xl y :key key :test test :ins ins :del del :sub= sub= :sub!= sub!=))
(scorer (nwscore (reverse xr) (reverse y) :key key :test test :ins ins :del del :sub= sub= :sub!= sub!=))
(ymid (partitiony scorel scorer)))
(multiple-value-bind (zl wl)
(hirschberg-rec xl (subseq y 0 ymid) :missing missing :type type :key key :test test :ins ins :del del :sub= sub= :sub!= sub!=)
(multiple-value-bind (zr wr)
(hirschberg-rec xr (subseq y ymid) :missing missing :type type :key key :test test :ins ins :del del :sub= sub= :sub!= sub!=)
(setf z (concatenate 'vector zl zr))
(setf w (concatenate 'vector wl wr)))))))
(values z w)))
(provide "HIRSCHBERG")
#|
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
|#
| 11,897 | Common Lisp | .lisp | 229 | 42.820961 | 153 | 0.521758 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | e9dc1500d13c1798e76e29a18a9f4c6f4a638e6a9aba1fe348c528b5d65b8fb4 | 14,209 | [
-1
] |
14,210 | time-functions.lisp | asmaloney_ACT-R/support/time-functions.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 : time-functions.lisp
;;; Version : 2.0
;;;
;;; Description : Macro to execute code and record the time spent in specified
;;; : functions.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2013.10.31 Dan [1.0]
;;; : * Initial creation.
;;; 2013.11.12 Dan
;;; : * Added (provide "TIME-FUNCTIONS") because it's now in the
;;; : ACT-R support directory.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled
;;; : in the docs.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled doc since it's not needed
;;; : and results in warnings in SBCL.
;;; 2021.04.21 Dan [2.0]
;;; : * Added an alterative version that just records the cumulative
;;; : time and a count instead of the individual ones becasue the
;;; : extra storage requirements may affect the timing.
;;; 2021.06.14 Dan
;;; : * Don't need to pass the function name to create-ctimed-closure.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Execute code and record the time spent in specified functions as measured by
;;; get-internal-real-time.
;;;
;;; When being used with ACT-R, code that needs it can include this:
;;; (require-compiled "TIME-FUNCTIONS")
;;; to make sure it gets loaded.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; time-functions
;;;
;;; Takes a list of function names which may end with a keyword parameter
;;; :save-params that specifies whether or not to record the parameters along
;;; with the times for the recorded functions (the default is nil) and any number
;;; of forms to evaluate.
;;; It returns two values. The first is an alist of the function times recorded
;;; where the function name is the car of an entry and the cdr is either a list
;;; of times if :save-params is nil or a list of lists where each sublist has
;;; the time as the car and the parameters which were passed to the function as
;;; the cdr. The second value returned is the result of evaluating the forms
;;; provided.
;;; Examples found in comment at end of file.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Only records the total time for a recursive function i.e. the time from
;;; the start of the first call until it returns.
;;;
;;; The functions which are being timed are not "thread safe". So this won't
;;; work to time functions which are being run in multiple threads simultaneously.
;;; In particular, if one is using my parallel-* functions this can't be used to
;;; time the functions being run, but it could record the parallel-* function
;;; itself i.e. this would be fine:
;;;
;;; (time-functions (parallel-mapcar)
;;; (parallel-mapcar team 'compute-vals data1)
;;; (parallel-mapcar team 'compute-vals data2)
;;; ...)
;;;
;;; but this would not and may result in errors:
;;;
;;; (time-functions (compute-vals)
;;; (parallel-mapcar team 'compute-vals data1)
;;; (parallel-mapcar team 'compute-vals data2)
;;; ...)
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro create-timed-closure (f c save results)
(let ((start (gensym)))
`(let ((,start nil))
(lambda (&rest rest)
(if ,start
(apply ,c rest)
(unwind-protect
(progn
(setf ,start (get-internal-real-time))
(apply ,c rest))
(progn
(if ,save
(push (cons (- (get-internal-real-time) ,start) rest) (cdr (assoc ,f ,results)))
(push (- (get-internal-real-time) ,start) (cdr (assoc ,f ,results))))
(setf ,start nil))))))))
(defmacro time-functions ((&rest fns) &body body)
(let ((results (gensym))
(old-defs (gensym))
(fn (gensym))
(f (gensym))
(c (gensym))
(save nil))
(when (and (>= (length fns) 2) (eq :save-params (nth (- (length fns) 2) fns)))
(setf save (nth (1- (length fns)) fns))
(setf fns (butlast fns 2)))
`(let ((,results nil)
(,old-defs (mapcan (lambda (x) (when (fboundp x) (list (cons x (fdefinition x))))) ',fns)))
(unwind-protect
(progn
(dolist (,fn ,old-defs)
(let ((,f (car ,fn))
(,c (cdr ,fn)))
(push (cons ,f nil) ,results)
(setf (fdefinition ,f)
(create-timed-closure ,f ,c ,save ,results))
(compile ,f)))
(values ,results (progn ,@body)))
(dolist (,fn ,old-defs)
(setf (fdefinition (car ,fn)) (cdr ,fn)))))))
(defmacro create-ctimed-closure (c results)
(let ((start (gensym)))
`(let ((,start nil))
(lambda (&rest rest)
(if ,start
(apply ,c rest)
(unwind-protect
(progn
(setf ,start (get-internal-real-time))
(apply ,c rest))
(progn
(incf (first ,results))
(incf (second ,results) (- (get-internal-real-time) ,start))
(setf ,start nil))))))))
(defmacro ctime-functions ((&rest fns) &body body)
(let ((results (gensym))
(old-defs (gensym))
(fn (gensym))
(f (gensym))
(c (gensym))
(d (gensym)))
`(let ((,results nil)
(,old-defs (mapcan (lambda (x) (when (fboundp x) (list (cons x (fdefinition x))))) ',fns)))
(unwind-protect
(progn
(dolist (,fn ,old-defs)
(let ((,f (car ,fn))
(,c (cdr ,fn))
(,d (list 0 0)))
(push (cons ,f ,d) ,results)
(setf (fdefinition ,f)
(create-ctimed-closure ,c ,d))
(compile ,f)))
(values ,results (progn ,@body)))
(dolist (,fn ,old-defs)
(setf (fdefinition (car ,fn)) (cdr ,fn)))))))
(provide "TIME-FUNCTIONS")
#| Example:
CG-USER(31): (defun recursive-sleep (n)
(unless (< n 1)
(sleep 1)
(recursive-sleep (1- n))))
RECURSIVE-SLEEP
CG-USER(32): (defun special-sleep (n)
(recursive-sleep n)
n)
SPECIAL-SLEEP
CG-USER(33): (time-functions (special-sleep recursive-sleep :save-params t)
(special-sleep 3)
(special-sleep 2))
((RECURSIVE-SLEEP (2000 2) (3000 3)) (SPECIAL-SLEEP (2000 2) (3000 3)))
2
CG-USER(34): (time-functions (special-sleep recursive-sleep)
(special-sleep 2)
(special-sleep 1))
((RECURSIVE-SLEEP 1000 2000) (SPECIAL-SLEEP 1000 2000))
1
|#
#|
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
|#
| 8,406 | Common Lisp | .lisp | 209 | 34.177033 | 102 | 0.53467 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 382504deb05dadca7f99526ee0cd4a99f07733c90ffc254670fe3abbde99e323 | 14,210 | [
-1
] |
14,211 | uni-files.lisp | asmaloney_ACT-R/support/uni-files.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-2005 Dan Bothell
;;; Availability: Covered by the GNU LGPL, see LGPL.txt
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : uni-files.lisp
;;; Version : 2.2
;;;
;;; Description : Contains the system dependent code for things needed by
;;; : the environment, but now part of support for use by other
;;; : things as needed.
;;; : Defines functions that can open an active socket, start
;;; : a process, kill a process, check a socket and read a line
;;; : from a stream. Also contains any "setup" code necessary
;;; : for a system.
;;; Bugs :
;;;
;;; Todo : Make sure the packaging stuff plays well here...
;;; : [X] Check that the without-interrupts in uni-send-string
;;; : isn't a performance issue (if it's unnecessary in a
;;; : particular Lisp).
;;; : [ ] Scrap that previous one since most Lisps are moving
;;; : to an SMP design which makes without-interrupts useless.
;;; : So, now I need to clean up all the separate lock hacks
;;; : I've got which fake a without-interrupts.
;;; ----- History -----
;;;
;;; 05/21/2002 Dan
;;; : Moved this from server.lisp to better organize things.
;;; 05/22/2002 Dan
;;; : Some MCL fixes to always print in top listener, and
;;; : report errors in a way that doesn't error itself.
;;; 05/24/2002 Dan
;;; : Had to add the uni-process-system-events because of the
;;; : stepper - the only way to "stop" ACT-R is to NOT return
;;; : from a hook, but that's problematic with multiple processes.
;;; 08/15/2002 Dan
;;; : Started the work to add LispWorks support.
;;; 10/01/2002 Dan
;;; : Updated version to 1.1 and fixed the packaging
;;; : for building a standalone in ACL.
;;; : Added the ACL standalone version of uni-run-process.
;;; : Added the uni-wait-for function because the process-wait
;;; : in ACL is much better than looping, and over time I can
;;; : fill in the equivalent for the other systems.
;;; 11/17/2002 Dan
;;; : Added a new version of uni-run-process for openmcl to
;;; : support the standalone version.
;;; 12/05/2002 Dan
;;; : Added create-valid-pathname to hack around an MCL 5 issue
;;; : (the MCL 5 version is in mcl-fix because it's got a special
;;; : macro character which I don't want to define for non-MCL
;;; : Lisps).
;;; : Removed the special uni-wait-for-char for MCL because
;;; : I've figured out how to make the MCL sockets play
;;; : friendly.
;;; 05/15/2003 : Dan
;;; : Realized that I broke the uni-make-socket for ACL < v6
;;; : because the version< test doesn't exist there...
;;; 08/15/2003 Dan
;;; : Updated the version to 1.3.
;;; : Added the support functions necessary for CMUCL from
;;; : Ethan Glasser-Camp at RPI. Made some minor edits to them
;;; : and they seem to work now, though it may not be the best
;;; : situation for the stepper.
;;; : If anybody has a more elegant solution for the
;;; : uni-process-system-events funtion for CMUCL please let me
;;; : know.
;;; : The issue is that while the stepper is active, the Lisp
;;; : running the model is sitting in a loop waiting for the
;;; : stepper. That busy loop needs to do something to:
;;;
;;; : a) allow a "signal" to get in to say it's time to advance
;;; : b) not crush the processor if possible.
;;; :
;;; : Originally, I tried a null function (no code inside) but
;;; : that didn't work well because the Lisp sat busy grinding
;;; : away on that tight loop and never exited or yielded the
;;; : processor. So, as a quick and dirty hack, since I don't
;;; : know enough about CMUCL multiprocessing I've just made it
;;; : a call to sleep for 1 second. That seems to work, but
;;; : does make the stepper window a little less responsive.
;;;
;;; : Also, there are a lot of warnings about unused variables
;;; : in lambda functions printed as it runs, which I don't
;;; : know how to suppress. So, again, if anybody knows the
;;; : switch to turn that off I'd appreciate it. Of course,
;;; : what I really need to do is declare those parameters
;;; : as ignored, but that's going to take a while to do...
;;; :
;;; 12/11/2003 Dan
;;; : Updated version to 1.4
;;; : Just realized that there's a problem with the
;;; : feature test because CMUCL can use the mp::process-wait
;;; : version of the uni-wait-for which seems to address
;;; : some of the stability issues with the stepper, but
;;; : maybe not all of them...
;;; 4/22/2004 Dan [1.5]
;;; : Added the license info.
;;; -----------------------------------------------------------------------
;;; 2005.04.12 Dan [2.0]
;;; : * Moving into ACT-R 6.
;;; : * Placed into the support folder and provided as
;;; : "UNI-FILES".
;;; 2005.04.20 Dan
;;; : * Having problems with Lispworks 4.3.7 on Windows with the
;;; : sending of socket info. Trying some stuff to fix that.
;;; : * Added the require Opentransport for MCL.
;;; 2005.08.10 Dan
;;; : * Addd the packaged-actr check to the uni-run-process
;;; : functions so that they can find the other ACT-R stuff...
;;; 2006.06.08 Dan
;;; : * Realized that uni-wait-for-char has still got environment
;;; : specific code in it so removing that now.
;;; : * Changed uni-process-system-events for CMUCL to use the
;;; : function process-yield instead of sleep - should improve
;;; : performance/responsiveness of the environment now.
;;; 2007.08.03 Dan
;;; : * Fixed a bug in uni-wait-for-char because it was only
;;; : passing one value to uni-report-error if the connection
;;; : dropped.
;;; 2007.08.17 Dan
;;; : * Fixed two problems with the LispWorks code:
;;; : - Took the sleep call out of the uni-send-string and
;;; : instead put it in a without-interrupts. That seemed to
;;; : fix some connection/transmission errors I encountered.
;;; : - Took all the fancy stuff out of uni-report-error because
;;; : it was throwing errors because of that (where did I get
;;; : that from anyway?).
;;; 2007.08.21 Dan
;;; : * Added the without-interrupts call to the other uni-send-
;;; : string versions as well to be safe. Will need to double
;;; : check that there isn't a serious performance hit for that.
;;; 2007.10.04 Dan
;;; : * Adding the SBCL code provided by Marc Halbruegge
;;; : into the distribution.
;;; 2007.12.14 Dan
;;; : * Fixed an issue in the SBCL code - without-interrupts is
;;; : is in the sb-sys package but not the default package.
;;; 2008.01.04 Dan
;;; : * Fixed another bug with the SBCL code. Added an eval-when
;;; : to the require because it throws an error under the
;;; : 1.0.12 Linux version without it...
;;; 2008.01.08 Dan
;;; : * Modified the eval-when for SBCL add both compile and load
;;; : time flags.
;;; 2008.04.08 Dan
;;; : * Added a uni-without-interrupts macro because without-
;;; : interrupts isn't ANSI CL so some implementations may
;;; : not have it or may place it in a different package.
;;; 2008.10.09 Dan
;;; : * Clozure Common Lisp (the new OpenMCL) doesn't have :mcl
;;; : on the features list so updating some of the switches.
;;; 2009.01.06 Dan
;;; : * Crude semiphore/lock code being added for CCL since in
;;; : its native threads mode without-interrupts doesn't actually
;;; : block anything...
;;; : - Will need to abstract that so it works well if there're
;;; : multiple connections i.e. a lock per socket/stream.
;;; : - Other Lisps are likely to need similar work at some point.
;;; 2009.01.21 Dan
;;; : * CMUCL doesn't have a without-interrupts either - it's
;;; : called without-scheduling.
;;; 2009.01.22 Dan
;;; : * Had the wrong feature check in that last update - it's :cmu
;;; : not :cmucl.
;;; 2009.02.20 Dan
;;; : * Added process-allow-schedule to the CCL uni-process-
;;; : system-events to possibly help with issues in the stepper
;;; : for some systems.
;;; : * Also switched it from force-output to finish-output in
;;; : the native threads case to hopefully help as well.
;;; 2009.04.13 Dan
;;; : * Removing the automatic newline on the end of uni-send-stirng
;;; : except for the "old" MCL case since it was a special command
;;; : to do things there and there're probably few people still
;;; : using that now.
;;; 2009.04.14 Dan
;;; : * Minor adjustments to the last update - putting the ACL
;;; : specific uni-send-string back since there seems to be an
;;; : issue with finish-output.
;;; 2009.06.02 Dan
;;; : * Added an extra switch in uni-send-string for MCL so that
;;; : it doesn't get used in RMCL since the "normal" write-line
;;; : works there and ccl::telnet-write
;;; 2010.01.06 Dan [2.1]
;;; : * Both ACL and LispWorks are now (v 8.2 and 6 respectively)
;;; : doing away with without-interrupts so I've added some
;;; : more lock hacks for those to get around that for now.
;;; 2010.09.15 Dan
;;; : * Adding a single process lock that can be used to block
;;; : access to things with uni-process-lock and uni-process-unlock.
;;; : This is basically just a temporary implementation for testing
;;; : and debugging some environment connection issues and eventually
;;; : there will be a uni-make-lock as well and these functions will
;;; : require a lock as a parameter.
;;; 2011.04.14 Dan
;;; : * Added a uni-make-lock and a uni-lock and uni-unlock whch take
;;; : a lock as a parameter. Didn't change the uni-process-*
;;; : functions to avoid breaking any existing code, but eventually
;;; : want to fix the environment code to use this instead.
;;; 2011.04.28 Dan
;;; : * Added a declare to suppress a compile warning.
;;; 2011.09.07 Dan
;;; : * Added a custom uni-wait-for for ccl so that it blocks
;;; : better for use in a standalone version.
;;; 2011.09.13 Dan
;;; : * All the locking functions have been arranged so that the
;;; : defaults only get defined if there isn't one for the
;;; : specific Lisp to avoid compilation warnings.
;;; : * Change the compiler switches for ACL on UNI-PROCESS-SYSTEM-EVENTS
;;; : to also avoid complier warnings.
;;; 2011.10.13 Dan
;;; : * Changed the custom uni-wait-for so that it only applies
;;; : for windows versions of ccl since it seems to hang on some
;;; : Macs.
;;; 2012.01.31 Dan
;;; : * Added a uni-report-error that gets defined even when
;;; : everything else doesn't so that all Lisps have that and
;;; : can report a meaningful error in some places.
;;; 2012.09.07 Dan
;;; : * Removed all the code which was needed with :actr-env-alone.
;;; : * Moved the (require :sock) for ACL here from the environment-
;;; : loader file.
;;; : * Changed uni-run-process so that it always runs in the same
;;; : package as the ACT-R code was loaded into. Previously it
;;; : only forced a package if :packaged-actr was set, but that
;;; : caused issues if some other "non-default" package was set
;;; : since some Lisps run new threads in cl-user by default.
;;; : * The allegro-ide uni-process-system-events now includes the
;;; : cg:: package on process-pending-events so it works right
;;; : when ACT-R is loaded in some other package.
;;; 2014.12.05 Dan
;;; : * Updated the uni-stream-closed function for allegro to
;;; : actually check something.
;;; 2014.12.15 Dan
;;; : * Added some safety checking when SBCL requires sb-bsd-sockets
;;; : because that doesn't seem to work on some of the newer
;;; : Windows builds...
;;; 2015.02.20 Dan [2.2]
;;; : * Changed uni-run-process for CCL so that it binds *standard-output*
;;; : to *terminal-io* instead of the current *standard-output*
;;; : when requested via an optional third parameter to make sure
;;; : output goes to the listener and not AltConsole or /dev/null
;;; : like it can otherwise. That needs to be on a switch because
;;; : the environment spawns a process from a process and that
;;; : second process needs to use its parent's stream since the
;;; : *terminal-io* at that point is the "special place".
;;; : This assumes that the listener in which the thread was
;;; : started is still available -- otherwise it'll again go to
;;; : the "alt" output.
;;; : * Adding the optional parameter for all versions, eventhough
;;; : it's not needed in the others at this point.
;;; 2015.08.10 Dan
;;; : * Adjusting the LispWorks version tests since v7 is now
;;; : available and I'm assuming it works like 6...
;;; 2016.05.31 Dan
;;; : * Using finish-format for anything that goes to *error-
;;; : output*.
;;; 2017.08.08 Dan
;;; : * Removing uni-without-interrupts and just using a lock for
;;; : for the send-string calls (not using the bordeaux threads
;;; : package for locks yet however).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#+: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)
;;; See if this works ...
#+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute)
(require "comm"))
#+(and :mcl (not :openmcl)) (eval-when (:compile-toplevel :load-toplevel :execute)
(require "OPENTRANSPORT"))
#+:sbcl (eval-when (:compile-toplevel :load-toplevel)
(ignore-errors (require 'sb-bsd-sockets))
(unless (find-package "SB-BSD-SOCKETS")
(make-package "SB-BSD-SOCKETS")
(format t "#|WARNING: SB-BSD-SOCKETS package not loaded.|#~%")
(format t "#| ACT-R Environment will not work!|#~%")))
#+:allegro (eval-when (:compile-toplevel :load-toplevel :execute)
(require :sock))
(defparameter *actr-default-package-name* *package*)
;;; The following functions need to be defined for every Lisp with which
;;; The environment is going to be used. Note the ordering of the allegro/
;;; allegro-ide and mcl/openmcl tests - that's important (I could do tests
;;; for the specific systems with ands, nots, and ors, but simple ordering
;;; seems easier).
;;; uni-make-socket
;;; This function takes 2 parameters which are the host and port address of
;;; a passive socket. It should open an active socket to that address and
;;; return a stream for communicating over that connection.
#+:allegro
(defun uni-make-socket (host port)
#+(or :allegro-v5.0.1 :allegro-v5)
(socket:make-socket :remote-host host :remote-port port)
#+(and :ALLEGRO-VERSION>= (version>= 6))
(socket:make-socket :remote-host host :remote-port port :nodelay t)
)
#+(and :mcl (not :openmcl))
(defun uni-make-socket (host port)
(ccl::open-tcp-stream host port))
#+:openmcl
(defun uni-make-socket (host port)
(make-socket :remote-host host :remote-port port))
#+:lispworks
(defun uni-make-socket (host port)
(comm:open-tcp-stream host port))
#+:cmu
(defun uni-make-socket (host port)
(system:make-fd-stream
(extensions:connect-to-inet-socket host port :stream)
:input t :output t))
#+:sbcl
(defun uni-make-socket (host port)
(let* ((sock (make-instance 'sb-bsd-sockets::inet-socket :type :stream :protocol :tcp)))
(sb-bsd-sockets::socket-connect sock (sb-bsd-sockets::make-inet-address host) port)
(let ((stream (sb-bsd-sockets::socket-make-stream sock :input t :output t :buffering :none)))
stream)))
;;; uni-run-process
;;; This function takes 2 parameters. The first is a string which will be
;;; used to name the process and the second is a function that is to be run
;;; in a new process. It creates a new process that runs the specified
;;; function (in the appropriate package) and returns that process.
#+(and :allegro (not :allegro-ide))
(defun uni-run-process (name function &optional special-stream)
(declare (ignore special-stream))
(mp::process-run-function name
#'(lambda ()
(let ((*package* *actr-default-package-name*))
(funcall function)))))
#+:allegro-ide
(defun uni-run-process (name function &optional special-stream)
(declare (ignore special-stream))
(let ((debug-pane *standard-output*))
(mp::process-run-function name
#'(lambda ()
(let ((*standard-output* debug-pane)
(*error-output* debug-pane)
(*package* *actr-default-package-name*))
(funcall function))))))
#+(and :mcl (not :openmcl))
(defun uni-run-process (name function &optional special-stream)
(declare (ignore special-stream))
(let ((front *standard-output*))
(process-run-function (list :name name)
#'(lambda ()
(let ((CCL::*SUPPRESS-COMPILER-WARNINGS* t)
(*standard-output* front)
(*error-output* front)
(*package* *actr-default-package-name*))
(funcall function))))))
#+:openmcl
(defun uni-run-process (name function &optional special-stream)
(let ((front (if special-stream (two-way-stream-output-stream *terminal-io*) *standard-output*)))
(process-run-function (list :name name)
#'(lambda ()
(let ((CCL::*SUPPRESS-COMPILER-WARNINGS* t)
(*standard-output* front)
(*error-output* front)
(*package* *actr-default-package-name*))
(funcall function))))))
#+:lispworks
(defun uni-run-process (name function &optional special-stream)
(declare (ignore special-stream))
(let ((front *standard-output*))
(mp::process-run-function name nil
#'(lambda ()
(let ((*standard-output* front)
(*error-output* front)
(*package* *actr-default-package-name*))
(funcall function))))))
#+:cmu
(defun uni-run-process (name function &optional special-stream)
(declare (ignore special-stream))
(mp:make-process #'(lambda ()
(let ((*package* *actr-default-package-name*))
(funcall function)))
:name name))
#+:sbcl
(defun uni-run-process (name function &optional special-stream)
(declare (ignore special-stream))
(sb-thread:make-thread #'(lambda ()
(let ((*package* *actr-default-package-name*))
(funcall function)))
:name name))
;;; uni-process-kill
;;; This function takes one parameter which is a process and kills that
;;; process.
#+(or :lispworks :allegro)
(defun uni-process-kill (process)
(mp::process-kill process))
#+(or :mcl :openmcl)
(defun uni-process-kill (process)
(process-kill process))
#+:cmu
(defun uni-process-kill (process)
(mp:destroy-process process))
#+:sbcl
(defun uni-process-kill (process)
(sb-thread:terminate-thread process))
;;; uni-wait-for
;;; This function takes one parameter which is a function. It waits until that
;;; function returns true before returning.
#+(or :allegro :cmu)
(defun uni-wait-for (function)
(mp::process-wait "Waiting" function))
#-(or :allegro :cmu)
(defun uni-wait-for (function)
(loop (uni-process-system-events)
(when (funcall function)
(return))))
;;; uni-lock-process and uni-unlock-process
;;; these functions take no parameters and are assumed to lock
;;; and unlock a single lock. A better implementation would be
;;; to also provide a "uni-make-lock" but that's not necessary
;;; right now so just doing this first...
(defvar *uni-actr-lock*)
#+:openmcl-native-threads
(setf *uni-actr-lock* (make-lock "uni-lock"))
#+:lispworks
(setf *uni-actr-lock* (mp::make-lock :name "uni-lock"))
#+(and :allegro :smp)
(setf *uni-actr-lock* (mp::make-process-lock :name "uni-lock"))
#+:openmcl-native-threads
(defun uni-process-lock ()
(grab-lock *uni-actr-lock*))
#+:openmcl-native-threads
(defun uni-process-unlock ()
(release-lock *uni-actr-lock*))
#+:lispworks
(defun uni-process-lock ()
(mp::process-lock *uni-actr-lock*))
#+:lispworks
(defun uni-process-unlock ()
(mp::process-unlock *uni-actr-lock*))
#+(and :allegro :smp)
(defun uni-process-lock ()
(mp::process-lock *uni-actr-lock*))
#+(and :allegro :smp)
(defun uni-process-unlock ()
(mp::process-unlock *uni-actr-lock*))
(unless (fboundp 'uni-process-lock)
(defun uni-process-lock ()))
(unless (fboundp 'uni-process-unlock)
(defun uni-process-unlock ()))
;;;;;;;;;; Adding a uni-make-lock and uni-lock and uni-unlock
;;; functions
#+:openmcl-native-threads
(defun uni-make-lock (name)
(unless (stringp name)
(setf name (string name)))
(make-lock name))
#+:lispworks
(defun uni-make-lock (name)
(unless (stringp name)
(setf name (string name)))
(mp::make-lock :name name))
#+:allegro
(defun uni-make-lock (name)
(unless (stringp name)
(setf name (string name)))
(mp::make-process-lock :name name))
(unless (fboundp 'uni-make-lock)
(defun uni-make-lock (name)
(declare (ignore name))
nil))
#+:openmcl-native-threads
(defun uni-lock (lock)
(grab-lock lock))
#+:openmcl-native-threads
(defun uni-unlock (lock)
(release-lock lock))
#+:lispworks
(defun uni-lock (lock)
(mp::process-lock lock))
#+:lispworks
(defun uni-unlock (lock)
(mp::process-unlock lock))
#+:allegro
(defun uni-lock (lock)
(mp::process-lock lock))
#+:allegro
(defun uni-unlock (lock)
(mp::process-unlock lock))
(unless (fboundp 'uni-lock)
(defun uni-lock (lock)
(declare (ignore lock))))
(unless (fboundp 'uni-unlock)
(defun uni-unlock (lock)
(declare (ignore lock))))
;;; uni-send-string
;;; This function takes two parameters the first is a socket stream
;;; and the second is a string of a message to send. That message is
;;; printed down that stream with a "newline" (CR/LF or whatever is used
;;; by the system) after it and the stream is flushed so that the
;;; line is actually sent.
#+:openmcl-native-threads
(defvar *mcl-environment-lock* (make-read-write-lock))
#+:openmcl-native-threads
(defun uni-send-string (socket string)
(with-write-lock (*mcl-environment-lock*)
(write-string string socket)
(finish-output socket)))
(defvar *environment-lock* (uni-make-lock "environment-write-lock"))
(defun uni-send-string (socket string)
(uni-lock *environment-lock*)
(write-string string socket)
(finish-output socket)
(uni-unlock *environment-lock*))
#| why is acl using force?
#+(and :allegro (not :smp))
(defun uni-send-string (socket string)
(uni-without-interrupts
(write-string string socket)
(force-output socket)))
#+(and :allegro :smp)
(defvar *environment-lock* (mp::make-process-lock))
#+(and :allegro :smp)
(defun uni-send-string (socket string)
(mp::with-process-lock (*environment-lock*)
(write-string string socket)
(force-output socket)))
|#
;;; uni-stream-closed
;;; This function takes one parameter which is a socket stream. It
;;; should return t if that stream has been closed. It's only really
;;; here for MCL right now because the way sockets get handled there doesn't
;;; result in an error on a closed stream, thus the process waiting for
;;; input doesn't ever end.
;;;
#+:allegro
(defun uni-stream-closed (stream)
(or (null stream)
(null (open-stream-p stream))))
#+(and :mcl (not :openmcl))
(defun uni-stream-closed (stream)
(ccl::stream-closed-p stream))
#+:openmcl
(defun uni-stream-closed (stream)
(stream-eofp stream))
#+:cmu
(defun uni-stream-closed (stream)
(not (open-stream-p stream)))
#+:lispworks
;; I don't have this working quite right, but it doesn't
;; matter because it errors out on a read if the other end
;; has closed things down - so it's not really necessary
;; anyway - as with all of them except MCL...
(defun uni-stream-closed (stream)
(declare (ignore stream))
;; problems with (null (comm::socket-stream-socket stream))
nil)
#+:sbcl
(defun uni-stream-closed (stream)
(not (open-stream-p stream)))
;;; uni-socket-read-line
;;; This function takes one parameter which is a stream and reads a
;;; line from it (terminated by some sort of CR/LF depending on the system)
;;; and returns the string containing that line.
;;; I got this function from Scott because in MCL the line endings caused
;;; problems for him and I noticed similar problems. The allegro version
;;; should work for other Lisps.
;;; I've moved to using the ccl provided function in MCL, and perhaps no
;;; longer need the complex function for the other systems, but for now
;;; I'll leave it.
#+(and :mcl (not :openmcl))
(defun uni-socket-read-line (stream)
"Read a CRLF-terminated line"
(ccl::telnet-read-line stream))
#+(or :allegro :lispworks :openmcl)
(defun uni-socket-read-line (stream)
"Read a CRLF-terminated line"
(unless (uni-stream-closed stream)
(do ((line (make-array 10
:element-type 'character
:adjustable T
:fill-pointer 0))
(char (read-char stream nil nil)
(read-char stream nil nil)))
((or (null char)
(and (char= char #\cr)
(char= (peek-char NIL stream) #\lf)))
(when char
(read-char stream nil nil))
line)
(vector-push-extend char line))))
#+:cmu
(defun uni-socket-read-line (stream)
"Read a line terminated by \\n"
(read-line stream nil nil))
#+:sbcl
(defun uni-socket-read-line (stream)
"Read a line terminated by \\n"
(read-line stream nil nil))
;;; uni-report-error
;;; This function takes 2 parameters. The first is a condition and the second
;;; is a string. It prints the string message followed by "Error:" and the
;;; information about the error in the condition to *error-output*.
;;; If there isn't any error info in the condition then "unspecified error"
;;; is displayed.
#-(or :allegro :cmu :sbcl)
(defun uni-report-error (err message)
(finish-format *error-output* "~a~%Error:~a" message err))
#+:allegro
(defun uni-report-error (err message)
(finish-format *error-output* "~a~%Error:~a" message
(if (slot-boundp err 'EXCL::FORMAT-CONTROL)
(apply #'format nil
(simple-condition-format-control err)
(simple-condition-format-arguments err))
"unspecified error")))
#+:cmu
(defun uni-report-error (err message)
(format system:*stderr* "~a~%Error:~a" message err))
#+:sbcl
(defun uni-report-error (err message)
(format sb-sys:*stderr* "~a~%Error:~a" message err))
;;; uni-wait-for-chars
;;; This function takes one parameter which is a socket. It should wait until
;;; there is a character available on that stream before returning, or in
;;; the event of an error just close down the process associated with handling
;;; that socket stream. This assumes that read-char blocks "well".
;;;
;;; In MCL the socket read locks the socket for output which isn't good -
;;; so I've got to resort to a polling loop until I figure out how to 'fix'
;;; that (or just wait until MCL and OS 9 are dead and ignore it...)
;;;
;;; I've resolved that problem with MCL, so the same function should
;;; work for all Lisps (at least all supported at this time).
#-(and :ccl :windows) (defun uni-wait-for-char (stream)
;; first make sure there's a connection
(when (uni-stream-closed stream)
(uni-report-error nil "Connection closed while waiting for a character.~%")
(close stream)
nil)
;; then check it for available data terminating on an error
(multiple-value-bind (value condition)
(ignore-errors (peek-char nil stream t))
(declare (ignore value))
(if (subtypep (type-of condition) 'condition)
(progn
(uni-report-error condition "Failed while waiting for a character")
(close stream)
nil)
t)))
#+(and :ccl :windows) (defun uni-wait-for-char (stream)
;; first make sure there's a connection
(when (uni-stream-closed stream)
(uni-report-error nil "Connection closed while waiting for a character.~%")
(close stream)
nil)
;; then check it for available data terminating on an error
(multiple-value-bind (value condition)
(ignore-errors (process-input-wait (ccl::stream-device stream :input)))
(declare (ignore value))
(if (subtypep (type-of condition) 'condition)
(progn
(uni-report-error condition "Failed while waiting for a character")
(close stream)
nil)
t)))
;;; uni-process-system-events
;;; This function takes no parameters and calls the necessary function
;;; to process events - process-pending-events, event-dispatch, etc. It
;;; gets called in a loop that's just waiting for a signal to exit so that
;;; ACT-R stops when the stepper is open. (do I need to do this in a non-ide
;;; Lisp???
#+(and :allegro (not :allegro-ide))
(defun uni-process-system-events ())
#+:cmu
(defun uni-process-system-events ()
(mp:process-yield))
#+:allegro-ide
(defun uni-process-system-events ()
(cg::process-pending-events))
#+(and :mcl (not :openmcl))
(defun uni-process-system-events ()
(event-dispatch))
#+:openmcl
(defun uni-process-system-events ()
(process-allow-schedule))
#+:lispworks
;;; Not too sure if this is the right function
(defun uni-process-system-events ()
(mp:process-allow-scheduling))
#+:sbcl
(defun uni-process-system-events ()
)
;;; functionify
;;; This function is needed by some Lisp implementations to coerce a lambda
;;; list to a function that can be funcalled (actually, upon further
;;; investigation this is a case where ACL is "overly helpful" because the
;;; spec doesn't say a cons (lambda ...) should be coerced to a function, but
;;; it's doing it for me, though I probably shouldn't take advantage of it).
#+:allegro
(defun functionify (x)
x)
#-:allegro
(defun functionify (x)
(if (consp x) (coerce x 'function) x))
;;; create-valid-pathname
;;; This function is a hack for running with MCL 5.0 in OSX.
;;; It takes a pathname as a string and returns a valid
;;; pathname as a string for Lisp.
;;; The problem is that MCL 5 under OSX still uses Mac pathnames,
;;; but Tcl/Tk under OSX uses Unix pathnames. So, when one opens,
;;; saves, loads, etc from the environment the pathname that
;;; comes over to Lisp is a Unix style name which MCL can't handle.
;;; So, when that's the case I replace the /'s with :'s and tack
;;; the booted drive name onto the front.
;;; Yes, it's a hack, but it seems to do the trick. If any body
;;; has a better solution please let me know.
#-:ccl-5.0
(defun create-valid-pathname (path) path)
(provide "UNI-FILES")
#|
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
|#
| 33,714 | Common Lisp | .lisp | 736 | 42.80163 | 100 | 0.631656 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | bde74b57bf1b9c3669c15e6ebe8e3f2575511ea67f3988062841bfaf8a687df5 | 14,211 | [
-1
] |
14,212 | goal-style-module.lisp | asmaloney_ACT-R/support/goal-style-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 : goal-style-module.lisp
;;; Version : 3.0
;;;
;;; Description : Functions that allow one to easily create a module that
;;; : acts like the basic ACT-R goal module/buffer.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;;
;;; 2004.10.26 Dan
;;; : Initial creation.
;;;
;;; 2004.12.13 Dan
;;; : Added the optional delay to the goal-style-request.
;;; : Made sure line lengths were max 80 chars.
;;; 2005.01.09 Dan
;;; : Moved the provide to the end.
;;; 2005.01.17 Dan
;;; : * Removed the call to format in the scheduling.
;;; 2005.04.23 Dan
;;; : * Updated the query function because it doesn't need to
;;; : respond to "buffer stuffed" anymore.
;;; 2005.08.10 Dan
;;; : * Updated the query function to specify the ignored params.
;;; : * Updated the version to 1.0.
;;; 2006.10.23 Dan
;;; : * Changed the temp goal chunk "clean up" so that it's now
;;; : done with a maintenance event and it also uses the release-name
;;; : command to kill the symbol name in addition to the chunk struct.
;;; 2007.06.18 Dan
;;; : * Removed chunk-spec-to-chunk-def because it's now an official
;;; : command and was moved to the chunk-spec file.
;;; 2008.09.19 Dan
;;; : * Added the goal-style-mod-request function here and gave it
;;; : an optional delay time too.
;;; 2010.12.08 Dan
;;; : * Added a priority to the goal-style-mod-request as an additional
;;; : optional parameter because the modification needs to take place
;;; : prior to the buffer being cleared (whether explicitly or implicitly).
;;; : The default priority is now 20 (since the clearing is 10).
;;; 2013.04.10 Dan
;;; : * Changed the goal-style-mod-request action so that it can also
;;; : extend the chunk-type if there are new slots in a dynamic request.
;;; 2014.03.20 Dan [2.0]
;;; : * Update to work with the typeless chunks.
;;; : * Make the query function a little more careful and actually test
;;; : that the slot is state otherwise print a warning.
;;; : * The mod-request doesn't need to extend the chunk now since that
;;; : will already have happened at the time of the chunk-spec creation.
;;; 2015.07.28 Dan
;;; : * Changed the logical to ACT-R-support in the require-compiled examples.
;;; 2015.12.17 Dan
;;; : * Changed the priority of the clean-up-goal-chunk event scheduled
;;; : by create-new-buffer-chunk to always be :min since that will
;;; : guarantee it happens after and doesn't throw an error for an
;;; : attempt to subtract from a value of :min or :max.
;;; 2017.12.06 Dan
;;; : * Clean-up-goal-chunk can just use purge-chunk since it does
;;; : the delete and release in one call.
;;; 2020.08.26 Dan
;;; : * Removed the path for require-compiled in the examples since
;;; : it's not needed and results in warnings in SBCL.
;;; 2021.06.04 Dan [3.0]
;;; : * Don't need to create a temp chunk and schedule an event to
;;; : delete that now since the spec can be sent directly to
;;; : set-buffer-chunk, and remove create-new-buffer-chunk.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; With these functions one can create a new module whos buffer acts like
;;; the basic goal module/buffer i.e. the module responds to requests by
;;; creating a new chunk and placing it into the buffer and responds to modification
;;; requests by modifying the chunk in the buffer.
;;;
;;; Request:
;;;
;;; A request must be a unique specification of a chunk: no variables are allowed,
;;; only the = modifier, and each slot may be specified at most once.
;;;
;;; The new chunk is placed into the buffer at the same time as the request by,
;;; default, but one can provide a delay on the time it takes to put the
;;; chunk into the buffer by having the module provide its own request function
;;; that calls the goal-style-request function with the optional delay parameter.
;;;
;;; Modification request:
;;;
;;; A modification request must be a valid buffer modification specification:
;;; no variables, only the = modifier, and each slot specified at most once.
;;;
;;; The chunk in the buffer has the specified modifications made to it at the
;;; same time as the modification request by default, but one can provide a
;;; delay on the time it takes to put the chunk into the buffer by having the
;;; module provide its own modification-request function that calls the
;;; goal-style-mod-request function with the optional delay parameter.
;;;
;;; It only responds to the required queries - state {busy, free, error}.
;;;
;;; State free will always return t.
;;; State busy will always return nil.
;;; State error will always return nil.
;;;
;;;
;;; To create a basic goal style module, just place a file into the modules
;;; directory that contains the following (where <...> is replaced
;;; with the value described within 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 "GOAL-STYLE-MODULE")
(define-module <the name of your module here>
(<the name of your buffer here which must be the same as the module name>)
nil
:version "Something about the version of your module"
:documentation "Something about the details of your module"
:query goal-style-query
:request goal-style-request
:buffer-mod goal-style-mod-request)
|#
;;; If one wants a delay on the time it takes to put the chunk into the
;;; buffer then the code would look like this (assuming a fixed delay
;;; time was desired).
;;; Note this shows the use of define-module-fct instead of the macro
;;; for comparison to the previous one. Either version can be used.
#|
#+: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")
(defun my-goal-style-request (instance buffer-name chunk-spec)
(goal-style-request instance buffer-name chunk-spec <delay time>))
(defun my-goal-style-mod-request (instance buffer-name chunk-spec)
(goal-style-mod-request instance buffer-name chunk-spec <delay time>))
(define-module-fct '<the name of your module here>
'(<the name of your buffer here which must be the same as the module name>)
nil
:version "Something about the version of your module"
:documentation "Something about the details of your module"
:query 'goal-style-query
:request 'my-goal-style-request
:buffer-mod 'my-goal-style-mod-request)
|#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; (defun goal-style-query (instance buffer-name slot value)
;;;
;;; This can be used as the query function for a module that will respond to
;;; the required queries in a static manner. It will respond as follows:
;;;
;;; State free will always return t.
;;; State busy will always return nil.
;;; State error will always return nil.
;;;
;;; It ignores the instance and if a slot other than state is specified or a value
;;; other than free, busy, or error is given then it prints a warning and returns nil.
;;;
;;;
;;; (defun goal-style-request (instance buffer-name chunk-spec &optional (delay 0) (priority -1000)))
;;;
;;; This can be used as the request function of a module to allow it to
;;; operate like the goal module i.e. create new chunks in response to a
;;; request. The instance is not used and it is assumed that the module
;;; has the same name as the buffer.
;;; The delay and priority are used to schedule the create-new-buffer-chunk
;;; action. The default priority is lower than any production action to
;;; ensure that all of the production actions at least "start" before
;;; the event to create the new chunk happens.
;;;
;;;
;;; (defun goal-style-mod-request (instance buffer chunk-spec &optional (delay 0) (priority 20))
;;;
;;; This can be used as a modification request function of a module to allow
;;; it to handle modification requests like the goal module does - perform
;;; an immediate modification of the chunk in the buffer. It assumes that
;;; the module and buffer have the same name and the instance of the module
;;; is ignored.
;;; The delay and priority are used to schedule a mod-buffer-chunk
;;; action. The default priority is higher than a production's clearing action
;;; priority (10) to ensure that all of the modification is made before a
;;; -<buffer> action in the production clears it.
;;;
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; 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 goal-style-query (instance buffer-name slot value)
(declare (ignore instance))
;; don't care about the buffer name and only care about slot state
(if (eq slot 'state)
(case value
(busy nil)
(free t)
(error nil)
(t
(print-warning "Unknown query state ~s to ~s buffer" value buffer-name)))
(print-warning "Unknown query ~s ~s to the ~s buffer" slot value buffer-name)))
(defun goal-style-request (instance buffer-name chunk-spec &optional (delay 0) (priority -1000))
(declare (ignore instance))
(if (chunk-spec-to-chunk-def chunk-spec)
(schedule-set-buffer-chunk buffer-name chunk-spec delay
:module buffer-name :priority priority)
(print-warning "Invalid request made of the ~a buffer." buffer-name)))
(defun clean-up-goal-chunk (name)
(purge-chunk-fct name))
(defun goal-style-mod-request (instance buffer chunk-spec &optional (delay 0) (priority 20))
(declare (ignore instance))
(schedule-mod-buffer-chunk buffer chunk-spec delay :module buffer :priority priority))
(provide "GOAL-STYLE-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
|#
| 11,985 | Common Lisp | .lisp | 251 | 45.984064 | 102 | 0.647421 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 42bea637e3cac008eb9a0222f3f8603b696d5572c4b93684cf02fcdc3b146675 | 14,212 | [
-1
] |
14,213 | productions.lisp | asmaloney_ACT-R/support/productions.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2015 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 : productions.lisp
;;; Version : 2.0
;;;
;;; Description : The structure and extension macros for productions and their
;;; : parameters.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2015.09.11 Dan [1.0]
;;; : * Separating this from the procedural module code so that I
;;; : can add parameters there and avoid some warning issues.
;;; 2017.08.11 Dan [2.0]
;;; : * Adding a lock to the structure and grabbing that in the
;;; : parameter creation macros.
;;; : * Removed the conditions and dynamic slots from production
;;; : struct since they are unused.
;;; 2019.02.13 Dan
;;; : * Adding slots to the production structure to hold the mask
;;; : of full buffers, empty buffers, and list of buffer masks.
;;; 2020.08.26 Dan
;;; : * Removing an "if nil ..." from extend-productions since SBCL
;;; : complains about unreachable code.
;;; 2020.11.11 Dan
;;; : * Removed the standard-rep slot from productions because it's
;;; : only used in production compilation so should be a parameter
;;; : added by 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)
(defstruct act-r-production-parameter
"The internal structure of a production parameter"
name default-value default-function accessor)
;; The internal rep. of a production is not considered public
(defstruct (production (:predicate production?))
text name documentation
variables bindings actions
lhs rhs lhs-buffers rhs-buffers
conflict-code
break
disabled
buffer-indices
conflict-val
(parameter-values (make-hash-table :size 23))
constants binds others selection-code implicit
failure-condition
partial-matched-slots
searches search-binds search-others
(buffer-full 0)
(buffer-empty 0)
(buffer-list nil)
(lock (bt:make-recursive-lock "production-struct")))
(defvar *production-parameters-list* nil)
;;; Instead of pre-specifying the paramters for a production
;;; move it to a system like chunks that allows for extending
;;; things "on the fly" so that alternative utility equations
;;; can be tried out without having to muck around with the
;;; base definitions. All changes can then be confined to the
;;; utility-and-reward file.
(defmacro extend-productions (parameter-name &key (default-value nil)(default-function nil))
"Add new parameters to all productions"
(if (or (not (symbolp parameter-name)) (keywordp parameter-name))
(print-warning "~s is not a valid symbol for specifying a production parameter." parameter-name)
(let ((accessor-name (intern (concatenate 'string "PRODUCTION-" (string-upcase parameter-name))))
(setf-name (intern (concatenate 'string "PRODUCTION-" (string-upcase parameter-name) "-SETF"))))
(if (find parameter-name *production-parameters-list* :key 'act-r-production-parameter-name)
(progn
(print-warning "Parameter ~s already defined for productions" 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 (find ',parameter-name *production-parameters-list* :key 'act-r-production-parameter-name)
(setf *production-parameters-list* (remove ',parameter-name *production-parameters-list* :key 'act-r-production-parameter-name)))
(push (make-act-r-production-parameter :name ',parameter-name
:default-value ',default-value
:default-function ',default-function
:accessor ',accessor-name)
*production-parameters-list*)
(defun ,accessor-name (production-name)
(let ((production (get-production production-name)))
(if (production? production)
(bt:with-recursive-lock-held ((production-lock production))
(multiple-value-bind (value exists)
(gethash ',parameter-name (production-parameter-values production))
(if exists
value
(setf (gethash ',parameter-name (production-parameter-values production))
(production-parameter-default
(find ',parameter-name *production-parameters-list*
:key 'act-r-production-parameter-name)
production)))))
(print-warning "~S called with invalid production name." ',accessor-name))))
(defun ,setf-name (production-name new-value)
(let ((production (get-production production-name)))
(if (production? production)
(bt:with-recursive-lock-held ((production-lock production))
(setf (gethash ',parameter-name (production-parameter-values production)) new-value))
(print-warning "Setf of ~S called with invalid production." ',accessor-name))))
(defsetf ,accessor-name ,setf-name)
',accessor-name)))))
(defun production-parameter-default (param production)
"Return a default value for a parameter in a production"
(if (act-r-production-parameter-default-function param)
(funcall (act-r-production-parameter-default-function param) production)
(act-r-production-parameter-default-value param)))
(provide "PRODUCTIONS")
#|
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,992 | Common Lisp | .lisp | 159 | 43.295597 | 142 | 0.590115 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 800f3b739ebb2f69c0c535355d50a777a526f8cfb0a1088992b37c1bf2936dc9 | 14,213 | [
-1
] |
14,214 | ccl-simple-view.lisp | asmaloney_ACT-R/support/ccl-simple-view.lisp | ;;; -*- mode: LISP; Package: CL-USER; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Clayton Stanley
;;; Copyright : (c)2003-7 CMU/Rice U./Mike Byrne, All Rights Reserved
;;; Availability: public domain
;;; Address : Rice University
;;; : Psychology Department
;;; : Houston,TX 77251-1892
;;; : [email protected]
;;; : [email protected]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Filename : ccl-simple-view.lisp
;;; Version : 1.0
;;;
;;; Description : Provides an interface for CCL that allows the implementation to
;;; read in GUI source code written for Macintosh Common Lisp.
;;; This enables task environments written in MCL (e.g., Phaser,
;;; Votebox, NextGen from Mike's lab) to work with CCL with
;;; minimal code modifications
;;;
;;; This file is a concatenation of all bootstrap and feature code
;;; so that the file can be loaded from a base/standard CCL core file.
;;;
;;; The file was built on Tue Nov 25 14:45:28 CST 2014 using GNU Make and Bash.
;;; Editing was done with vim+slimv, and lisp code was auto indented using
;;; vim+slimv's auto-indention algorithm.
;;;
;;; Git commit hash associated with build: 5875c091ec81f54501cf14f844d7c32a9e4a3e01
;;;
;;;
;;;
;;; Bugs : []
;;;
;;; Todo : Lots
;;; :
;;;
;;; ----- History -----
;;; 2012.06.29 cts
;;; : Initial build that allows Votebox MCL GUI to be read in and used by CCL
;;; 2012.08.13 cts
;;; : Release build that works with Votebox, NextGen, and Phaser from Mike's lab
;;; 2013.02.04 cts
;;; : Fixed bug that did not update window position after window moved with
;;; mouse drag. Window position is correctly tracked, and a call to
;;; view-position on the window works correctly both before and after
;;; the window position is moved with a mouse drag on the window pane.
;;; 2013.02.11 cts
;;; : Removed easygui::drawing-view dependency in codebase.
;;; Simplifies OO hierarchy, removes unnecessary cruft, and decreases technical debt
;;; 2013.02.16 cts
;;; : Changes to ensure code is compatible with CCL 1.8 through CCL 1.9rc2
;;; 2013.04.10 cts
;;; : Added feature: You can now change the color of the text shown for button objects
;;; (button-dialog-item, check-box-dialog-item, radio-button-dialog-item) in the usual
;;; MCL way for dialog items (passing :fore-color #color# or :part-color (list :text #color#)
;;; to initialize-instance)
;;; 2013.04.20 cts
;;; : #@ read macro no longer clobbers CCL's original version that created NSString objects.
;;; The #@ read macro now creates MCL points when provided with a list, and an NSString object
;;; when provided with a string.
;;; : Reordered loading a few subcomponent files and renamed a few subcomponent files.
;;; : Removed stray commented out code that is no longer necessary.
;;; : Now spell checking comments and strings in the code.
;;; 2013.05.13 cts
;;; : Added implementation for sequence-dialog-item.
;;; : Added quickdraw functions for paint-polygon and fill-polygon.
;;; : Removed extra cruft from file: no longer including thermometer.lisp since
;;; this library code is not part of the core MCL GUI interface.
;;; : Also removed unused code (all of the pandoric functions) from lol-subset.lisp
;;; : Added MCL's :centered keyword for windows.
;;; : Fixed quickdraw polygon functions to use the polygon provided as input to the function,
;;; instead of using the polygon stored within the view. This change matches the MCL spec.
;;; 2013.06.02 cts
;;; : Added MCL's :top and :bottom list arguments to :view-position for windows
;;; : Enabled :dialog-item-action initarg from MCL spec to work, and map correctly to
;;; :action initarg for CCL spec.
;;; : Cleaned up :parse-mcl-initarg methods. Created a proper generic method signature for the
;;; methods, so that they have the needed flexibility to work in all cases.
;;; : Plugged memory leaks by creating an autorelease pool at the beginning of this file.
;;; This ensures that any autoreleased objects during both compilation and runtime have
;;; a pool to release to. This was only an issue when running CCL via SVN (e.g., with common SLIME setup),
;;; and not via the Clozure CL.app, because the App already has an autorelease pool set up on startup.
;;; 2013.07.31 cts
;;; : Incorporated additional functionality needed for a recent project into the ccl-simple-view library:
;;; -Sequence dialog item now defaults to nil sequence if none specified on init
;;; -menu-view and menu-item objects now set font correctly
;;; : Refactored and simplified image-view code
;;; : Everything works on 10.6.8 - 10.8.4 (newest Mountain Lion install as of testing date)
;;; -required a fix for radio buttons. Clustering did not work on 10.8 prior to fix
;;; : Code-coverage report is now generated for each build.
;;; -Used report to remove stray code and discover/fix a few minor bugs
;;; 2013.09.17 cts
;;; : Swapped cocoa class for editable-text-dialog-item from NSTextField to NSTextView
;;; -Ensures that keypresses on the view that are relayed to view-key-event-handler are accurate
;;; -Allows for more control over keypresses in the view, so that for example, the next responder
;;; can be called when a #\tab is pressed in the view.
;;; : Reworked #\tab presses for UI, so that tabbing moves between all of the views on the window
;;; that can become first responder.
;;; : Reworked #\space presses for buttons, so that if a #\space is pressed when a button is
;;; first responder, then the action for that button fires (i.e., the button is clicked).
;;; : Ensured that the window is always the starting first responder when the view is created.
;;; Afterwards, if the user presses #\tab, then the next responder is activated, and tabbing
;;; then cycles through all available first responders. This is to ensure that no particular view
;;; is the first responder in the simplest case: for a basic window where the user does not
;;; wish to tab between views.
;;; : If tabbing across buttons is enabled at the OS level:
;;; http://superuser.com/questions/473143/how-to-tab-between-buttons-on-an-mac-os-x-dialog-box
;;; then a user can work through most tasks involving editing text views and pressing buttons
;;; using only the keyboard. #\tab to navigate and #\space to select
;;; 2014.02.08 cts
;;; : Implemented :close-box-p initarg for windows, so that the red close button does not display
;;; when this is set to t when initializing the window
;;; : Fixed a bug where incorrect mouse locations were passed to view-click-event-handler for views.
;;; All locations where correct for view-click-event-handlers defined on windows, and for
;;; rpm-window-click-event-handlers (since those are defined on the window).
;;; So this does not apply to act-r models using the act-r device interface (i.e., rpm-window-click-event-handler).
;;; This only applied to view-click-event-handlers defined on views (e.g., buttons).
;;; MCL spec sets location for view-click-event-handler to the mouse click location relative to that
;;; view's local coordinate system, not relative to the window's coordinate system. So if a button
;;; responds to a mouse click that is 10 by 10 pixels within that button's view rectangle, then
;;; the location for view-click-event-handler will by 10 by 10, and not 10 by 10 plus that view's
;;; position within the window for example.
;;; The prior code e.g., passed 10 by 10 plus the view's position to view-click-event-handler, regardless of view type.
;;; 2014.02.10 Dan Bothell
;;; : Swapped the order of grey and gray in rgb-list because ACT-R
;;; uses gray as the color name for things and this:
;;; (system-color->symbol (color-symbol->system-color 'gray))
;;; should return gray. [Since those are basically ACT-R
;;; interface functions they should probably be moved to the uwi
;;; file.]
;;; 2014.02.11 cts
;;; : Added mcl-GUI-layer methods to scroll the mouse up and down. When executed, mouse scroll events
;;; are sent to the OS to relay to the front application, similar to how mouse clicks and keypresses are done.
;;; : Added a guard to ensure that all views are using proper "flipped" MCL-style (top-left to bottom-right) coordinate systems.
;;; 2014.04.09 cts
;;; : Using integers for points when possible, even after converting positions from local to window coordinates, adding
;;; and subtracting points, etc.
;;; 2014.05.02 cts
;;; : Added ability to extend color symbol rgb mapping by turning data structure into a hash table
;;; : Ensured gray is always returned for gray/grey rgb color, regardless of order in the rgb-list.
;;; This is needed since the color data structure is now a hash table and
;;; insertion order is not guaranteed to be consistent in a cl hash table
;;; 2014.10.14 cts
;;; : Code is compatible with ccl-1.8 thru ccl-1.10 on OS X SL thru Mavericks
;;; : Using #/abortModal instead of #/stopModal to close modal dialog windows so
;;; that close requests can be made on any thread, and not just the new modal dialog window thread.
;;; Otherwise, strange things were happening on SL and ML where the modal window would not close after a request when that request
;;; was made on a thread other than the modal dialog's thread (e.g., the REPL ACT-R thread).
;;; In this case, the window did close once the mouse moved or keyboard was pressed after that request was made.
;;; Using #/abortModal instead of #/stopModal ensures that the window closes in all cases tested.
;;; 2014.11.25 cts
;;; : Ensured that image-views are properly sized if the image was provided when the view was created.
;;;
;;; 2015.11.13 Dan Bothell
;;; : Wrapped choose-file-dialog with ensure-defined as suggested by
;;; : Mike Byrne since CCL 1.11 now includes such a function. Also
;;; : did choose-new-file-dialog and choose-directory-dialog to be
;;; : safe.
;;; 2015.11.18 Dan Bothell
;;; : Removed a spurious - which was accidentally added with the last
;;; : update, but didn't break anything.
;;; 2016.06.16 Dan Bothell
;;; : Changed rgb->color-symbol because there are more pairs in the list than
;;; : just gray and grey. Always returns the same result each time for each of
;;; : the current 8 pairs but any new pairs may return mixed results unless
;;; : additional changes are made to rgb->color-symbol (or some other fix is
;;; : implemented, like another table preferences).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ----------------------------------------------------------------------
; Begin file: build/pre-code.lisp
; ----------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :cocoa)
(require :easygui)
(ccl::create-autorelease-pool))
; ----------------------------------------------------------------------
; End file: build/pre-code.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: bincarbon/sv-language-layer.lisp
; ----------------------------------------------------------------------
(defmacro %ensure-defined (form)
(destructuring-bind (symb name (&rest arglist) &body body) form
(declare (ignore arglist body))
(unless
(funcall
(case symb
(defun #'fboundp)
(defgeneric #'fboundp)
(defmacro #'macro-function)
(defvar #'boundp))
name)
form)))
(defmacro ensure-defined (&body body)
`(eval-when (:compile-toplevel :load-toplevel :execute)
,@(mapcar (lambda (form)
`(%ensure-defined ,form))
body)))
(defmacro with-continue (&body body)
`(handler-bind ((error #'continue))
,@body))
(provide :sv-language-layer)
; ----------------------------------------------------------------------
; End file: bincarbon/sv-language-layer.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: bincarbon/lol-subset.lisp
; ----------------------------------------------------------------------
;; Antiweb (C) Doug Hoyte
;; This is a "production" version of LOL with bug-fixes
;; and new features in the spirit of the book.
;; See http://letoverlambda.com
;; This is the source code for the book
;; _Let_Over_Lambda_ by Doug Hoyte.
;; This code is (C) 2002-2008, Doug Hoyte.
;;
;; You are free to use, modify, and re-distribute
;; this code however you want, except that any
;; modifications must be clearly indicated before
;; re-distribution. There is no warranty,
;; expressed nor implied.
;;
;; Attribution of this code to me, Doug Hoyte, is
;; appreciated but not necessary. If you find the
;; code useful, or would like documentation,
;; please consider buying the book!
;;
;; 2012-06-29: Clayton Stanley. I took only a subset
;; of Doug Hoyte's LOL production code, which is included
;; below. I did not modify any code within this subset,
;; except to change a few &rest to &body keywords in macro definitions,
;; so that slimv could handle auto-indenting properly. The behavior
;; of the code 'was not changed'.
(require :sv-language-layer)
(eval-when (:compile-toplevel :load-toplevel :execute)
(ensure-defined
(defun mkstr (&rest args)
(with-output-to-string (s)
(dolist (a args) (princ a s))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun symb (&rest args)
(values (intern (apply #'mkstr args)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun group (source n)
(if (zerop n) (error "zero length"))
(labels ((rec (source acc)
(let ((rest (nthcdr n source)))
(if (consp rest)
(rec rest (cons
(subseq source 0 n)
acc))
(nreverse
(cons source acc))))))
(if source (rec source nil) nil))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(ensure-defined
(defun flatten (lis)
"Takes a nested list and makes in into a single-level list"
(declare (list lis))
(labels ((rec (lis acc)
(cond ((null lis) acc)
((atom lis) (cons lis acc))
(t (rec (car lis) (rec (cdr lis) acc))))))
(rec lis nil)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun g!-symbol-p (s)
(and (symbolp s)
(> (length (symbol-name s)) 2)
(string= (symbol-name s)
"G!"
:start1 0
:end1 2))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmacro defmacro/g! (name args &body body)
(let ((syms (remove-duplicates
(remove-if-not #'g!-symbol-p
(flatten body)))))
`(defmacro ,name ,args
(let ,(mapcar
(lambda (s)
`(,s (gensym ,(subseq
(symbol-name s)
2))))
syms)
,@body)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun o!-symbol-p (s)
(and (symbolp s)
(> (length (symbol-name s)) 2)
(string= (symbol-name s)
"O!"
:start1 0
:end1 2))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun o!-symbol-to-g!-symbol (s)
(symb "G!"
(subseq (symbol-name s) 2))))
(defmacro defmacro! (name args &body body)
(let* ((os (remove-if-not #'o!-symbol-p args))
(gs (mapcar #'o!-symbol-to-g!-symbol os)))
`(defmacro/g! ,name ,args
`(let ,(mapcar #'list (list ,@gs) (list ,@os))
,(progn ,@body)))))
;; Graham's alambda
(defmacro alambda (parms &body body)
`(labels ((self ,parms ,@body))
#'self))
;; Graham's aif
(ensure-defined
(defmacro aif (test then &optional else)
`(let ((it ,test))
(if it ,then ,else))))
(provide :lol-subset)
; ----------------------------------------------------------------------
; End file: bincarbon/lol-subset.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: bincarbon/sv-utilities.lisp
; ----------------------------------------------------------------------
(require :sv-language-layer)
(require :lol-subset)
(ensure-defined
(defmacro push-to-end (item place)
"analogous to the push macro; just places 'item' at the end of 'place', instead of the front"
`(setf ,place (nconc ,place (list ,item)))))
(defun spin-for-fct (ms-delay)
(without-interrupts
(let ((start (internal-real-time->ms
(get-internal-real-time))))
(loop until (< ms-delay (- (internal-real-time->ms
(get-internal-real-time))
start))))))
(defun internal-real-time->ms (&optional (internal-real-time (get-internal-real-time)))
(* 1000
(/ internal-real-time
internal-time-units-per-second)))
(defun file-string (path)
"Sucks up an entire file from PATH into a freshly-allocated string returning two values: the string and the number of bytes read."
(if path
(with-open-file (s path)
(let* ((len (file-length s))
(data (make-string len)))
(values data (read-sequence data s))))))
(ensure-defined
(defmacro awhen (test-form &body body)
`(aif ,test-form
(progn ,@body))))
(defmacro! acond (&rest clauses)
"works just like cond, but stores the value of each condition as 'it', which is accessible in the code following the condition"
(if clauses
(let ((cl1 (car clauses)))
`(let ((,g!sym ,(car cl1)))
(if ,g!sym
(let ((it ,g!sym))
(declare (ignorable it))
,@(cdr cl1))
(acond ,@(cdr clauses)))))))
(ensure-defined
(defmacro while (test &body body)
"loops through body, evaluating test each time until test returns false"
`(do ()
((not ,test))
,@body)))
(defmacro aand (&rest args)
(cond ((null args) t)
((null (cdr args)) (car args))
(t `(aif ,(car args) (aand ,@(cdr args))))))
(defmacro! guard ((guard &rest errstr) &body body)
(let ((errstr (if errstr
errstr
(list "guard ~a failed" `',guard))))
`(let* ((it (multiple-value-list (progn ,@body)))
(it1 (first it)))
(declare (ignorable it it1))
(assert ,guard nil ,@errstr)
(apply #'values it))))
(defmacro! with-shadow ((fname fun) &body body)
"Shadow the function named fname with fun
Any call to fname within body will use fun, instead of the default function for fname.
This macro is intentionally unhygienic:
fun-orig is the anaphor, and can be used in body to access the shadowed function"
`(let ((fun-orig))
(cond ((fboundp ',fname)
(setf fun-orig (symbol-function ',fname))
(setf (symbol-function ',fname) ,fun)
(unwind-protect (progn ,@body)
(setf (symbol-function ',fname) fun-orig)))
(t
(setf (symbol-function ',fname) ,fun)
(unwind-protect (progn ,@body)
(fmakunbound ',fname))))))
(defmethod getf-include-key (place key)
(aif (getf place key)
(list key it)))
(defmethod getf-include-key (place (keys list))
(loop for key in keys
append (getf-include-key place key)))
(provide :sv-utilities)
; ----------------------------------------------------------------------
; End file: bincarbon/sv-utilities.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: bincarbon/logger.lisp
; ----------------------------------------------------------------------
#-:clozure (error "This file only works with Clozure Common Lisp and not RMCL")
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :cocoa)
(require :easygui))
(defparameter *sv-log-level* 0)
(defun get-cur-timestring ()
(multiple-value-bind (second minute hour date month year day-of-week dst-p tz) (get-decoded-time)
(declare (ignore day-of-week dst-p tz))
(let ((ms (floor (mod (internal-real-time->ms) 1000))))
(format nil "~a-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d:~a" year month date hour minute second ms))))
(defun sv-log (&rest args)
(#_NSLog
(objc:make-nsstring
(with-output-to-string (strm)
(format strm "sv-log: ~a: on thread ~a: " (get-cur-timestring) *current-process*)
(unwind-protect (apply #'format strm args)
(fresh-line strm))))))
(defun sv-log-n (log-level &rest args)
(when (<= log-level *sv-log-level*)
(apply #'sv-log args)))
; ----------------------------------------------------------------------
; End file: bincarbon/logger.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: easygui/patches.lisp
; ----------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(shadowing-import 'easygui:cocoa-ref)
(shadowing-import 'easygui:dcc)
(shadowing-import 'easygui::running-on-main-thread))
(defclass easygui::cocoa-extension-mixin ()
((easygui::easygui-view :initarg :eg-view :reader easygui::easygui-view-of)
(easygui::flipped :initarg :flipped :initform easygui::*screen-flipped*)))
; Providing a keyword argument to allow negative points
(defun easygui::point (x y &key (allow-negative-p t))
(unless allow-negative-p
(assert (>= x 0))
(assert (>= y 0)))
(make-instance 'easygui::eg-point :x x :y y))
; Patching the function to provide a keyword argument that allows for negative mouse coordinates
(defun easygui::view-mouse-position (view &key (allow-negative-position-p nil))
(let* ((w (cocoa-ref (easygui::easygui-window-of view)))
(mouselocation (dcc (#/mouseLocationOutsideOfEventStream w)))
(cview (if (typep view 'window) (easygui::content-view view) view))
(nspt (dcc (#/convertPoint:fromView: (cocoa-ref cview) mouselocation NIL))))
;; TODO: check point is inside bounds, lest negative coordinates
(easygui:point (ns:ns-point-x nspt)
(ns:ns-point-y nspt)
:allow-negative-p allow-negative-position-p)))
; I think I found a bug in these two methods in the easygui package, so redefining them here with correct setNeedsDisplay: call
(defmethod (setf easygui::view-position) (point (self easygui::view))
(running-on-main-thread ()
(setf (slot-value self 'easygui::position) point)
(when (slot-value self 'easygui::frame-inited-p)
(dcc (#/setFrame: (cocoa-ref self) (easygui::view-content-rect self)))
(dcc (#/setNeedsDisplay: (cocoa-ref self) t)))))
(defmethod (setf easygui::view-size) (point (self easygui::view))
(running-on-main-thread ()
(setf (slot-value self 'easygui::size) point)
(when (slot-value self 'easygui::frame-inited-p)
(dcc (#/setFrame: (cocoa-ref self) (easygui::view-content-rect self)))
(dcc (#/setNeedsDisplay: (cocoa-ref self) t)))))
; I wanted to instantiate my own extended contained-view class, but I didn't see an easy way to do this given the current
; easygui code. So adding a contained-view-specifically slot to the mixin class, defaulting it to the contained-view class
; defined in easygui. If you want to instantiate a different class for the contained view, just overwrite this default.
(defclass easygui::content-view-mixin ()
((easygui::content-view :initarg :content-view)
(easygui::objc-content-view-accessor :reader easygui::objc-content-view-accessor :initarg :objc-content-view-accessor :initform #'#/contentView)
(easygui::flipped :initarg :flipped :initform easygui::*screen-flipped*)
(easygui::contained-view-specifically :initarg :contained-view-specifically :initform 'easygui::contained-view)))
(defmethod easygui::content-view ((view easygui::content-view-mixin))
(assert (eql (cocoa-ref (slot-value view 'easygui::content-view))
(dcc (funcall (easygui::objc-content-view-accessor view) (cocoa-ref view)))))
(slot-value view 'easygui::content-view))
; Added code to instantiate the contained view class that is stored as a slot on the mixin object
(defmethod easygui::initialize-view :after ((view easygui::content-view-mixin))
(unless (slot-boundp view 'easygui::content-view)
(let ((containee (make-instance (slot-value view 'easygui::contained-view-specifically)
:cocoa-ref (dcc (#/contentView (cocoa-ref view)))
:view-nick-name 'easygui::%CONTENT-OF-CONTENT-VIEW%
:flipped (slot-value view 'easygui::flipped))))
(setf (slot-value view 'easygui::content-view) containee
(slot-value containee 'easygui::parent) view))))
; Redefining to use the &body body pairing instead of &rest body, so that Slime auto indenting works properly
(defmacro easygui::running-on-this-thread ((&key (waitp t)) &body body)
;; The purpose of this trivial macro is to mark places where it is thought possible that
;; it may be preferable to use running-on-main-thread.
(declare (ignore waitp))
`(progn ,@body))
; Radio buttons in 10.8 require being enclosed within an NSMatrix.
; If not (default easygui implementation), each one is assigned to the
; same virtual NSMatrix, which means they are all part of the same cluster,
; which means that the common lisp clustering implementation breaks since
; Cocoa is now forcing all radio buttons to be part of the same cluster.
; The fix is to use NSSwitchButton Cocoa functionality for radio buttons,
; but use NSRadioButton images (for selected and deselected) for the implementation.
; Another approach would have been to embed each radio button in its own NSMatrix,
; but this required much more code than the image switching technique, and it messed up the overall
; easygui design, since the cocoa-ref of a radio-button object would have been an NSMatrix,
; which breaks the view-text and (setf view-text) mixin methods, as well as auto sizing the
; view to the text it contains on init, etc. So, I went with the simple image switching hack.
(let ((alternate-radio-button-image)
(radio-button-image)
(radio-button))
(defmethod easygui::initialize-view :after ((self easygui::radio-button-view))
(labels ((init-images ()
(setf radio-button (make-instance 'easygui::cocoa-button))
(#/setButtonType: radio-button #$NSRadioButton)
(setf radio-button-image (#/image radio-button))
(setf alternate-radio-button-image (#/alternateImage radio-button))))
(when (cocoa-ref self)
(unless radio-button
(init-images))
(dcc (#/setButtonType: (cocoa-ref self) #$NSSwitchButton))
(dcc (#/setImage: (cocoa-ref self) radio-button-image))
(dcc (#/setAlternateImage: (cocoa-ref self) alternate-radio-button-image))
(when (slot-value self 'easygui::selected) (easygui::radio-button-select self))
(setf (slot-value (cocoa-ref self) 'easygui::easygui-view) self)))))
; ----------------------------------------------------------------------
; End file: easygui/patches.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: easygui/extensions.lisp
; ----------------------------------------------------------------------
(defun round-if-integer (double)
(if (equalp double (round double))
(round double)
double))
(defun easygui::point-from-ns-point (point)
(easygui::point
(round-if-integer (ns:ns-point-x point))
(round-if-integer (ns:ns-point-y point))
:allow-negative-p t))
; easygui by default starts position 0,0 at bottom left, going to the right and up for positive values
; This flips the screen vertically, so that it matches MCL's default. That is, position 0,0 is at top left
(setf easygui::*screen-flipped* t)
(setf easygui::*debug-cocoa-calls* nil)
(setf easygui::*report-flipping-errors* t)
; There are particular window configurations that keep the window from becoming key or main (borderless windows for example).
; And this causes odd behavior for these types of windows (can't select the win when using command `, window is backgrounded behind
; the listener window after a dialog window opens and closes).
;
; For the time being, there are no types of cocoa windows that should not be able to become key or main. So until customization is
; needed, override these methods for cocoa windows and allow everyone the ability to become key and main.
(objc:defmethod (#/canBecomeKeyWindow #>BOOL) ((self easygui::cocoa-window))
#$YES)
(objc:defmethod (#/canBecomeMainWindow #>BOOL) ((self easygui::cocoa-window))
#$YES)
; ----------------------------------------------------------------------
; Extend the Objective C cocoa-drawing-view in the easygui package with a view that does not monitor mouse movement or clicks
;
; lisp->objective c class name mapping: drawing-overlay-view->cocoa-drawing-overlay-view
; ----------------------------------------------------------------------
; Create the objective c class
(defclass easygui::cocoa-drawing-overlay-view (easygui::cocoa-drawing-view)
()
(:metaclass ns:+ns-object))
; And create the lisp equivalent class
; And register the objective c extension and lisp class to the easygui package, so that it instantiates a
; cocoa-drawing-overlay-view object in the cocoa-ref slot when a drawing-overlay-view lisp object is instantiated
(defclass easygui::overlay-view (easygui::view)
()
(:default-initargs :specifically 'easygui::cocoa-drawing-overlay-view))
; Add the hook method in objective c that will cause the new class to not respond to mouse activity
(objc:defmethod #/hitTest: ((self easygui::cocoa-drawing-overlay-view) (point :<NSP>oint))
ccl:+null-ptr+)
; ----------------------------------------------------------------------
; Use a consuming-view class to say that all subviews within an instance of that class will not respond to mouse clicks.
;
; This is to work around the differences in first responders between MCL and CCL. MCL looks down the view hierarchy for the first responder
; (breadth first), CCL looks down the hierarchy for the deepest responder (depth first). In order
; to simulate breadth first by stopping at a particular view in the tree (and not inspecting that view's
; subviews), create an instance of the consuming-view class.
; ----------------------------------------------------------------------
(defclass easygui::cocoa-drawing-consuming-view (easygui::cocoa-drawing-view)
()
(:metaclass ns:+ns-object))
(defclass easygui::consuming-view (easygui::view)
()
(:default-initargs :specifically 'easygui::cocoa-drawing-consuming-view))
; Override hitTest; if a view (or one of its subviews) returns a non-nil value
; for the default hitTest call, then return self; this suppresses subviews of
; self from responding to mouse clicks
;
; Reference this URL for call-next-method syntax in objc:defmethod macro:
; http://clozure.com/pipermail/openmcl-devel/2008-November/008645.html
(objc:defmethod #/hitTest: ((self easygui::cocoa-drawing-consuming-view) (point :<NSP>oint))
(let ((ret (call-next-method point)))
(if (not (equal ccl:+null-ptr+ ret))
self
ccl:+null-ptr+)))
; ----------------------------------------------------------------------
; Providing a view container to hold and display images.
; ----------------------------------------------------------------------
(defclass easygui::cocoa-image-view (easygui::cocoa-extension-mixin ns:ns-image-view)
()
(:metaclass ns:+ns-object))
(defmacro define-is-flipped-method (class)
`(objc::defmethod (#/isFlipped :<BOOL>) ((self ,class))
(handler-case (if (slot-value self 'easygui::flipped) #$YES #$NO)
(simple-error (condition)
(when easygui::*report-flipping-errors* (format t "'isFlipped ~s' ignores error~%" self))
(values (if easygui::*screen-flipped* #$YES #$NO) condition)))))
(define-is-flipped-method easygui::cocoa-image-view)
(defclass easygui::image-view (easygui::view)
()
(:default-initargs :specifically 'easygui::cocoa-image-view))
(defclass easygui::cocoa-clickable-image-view (easygui::cocoa-image-view)
()
(:metaclass ns:+ns-object))
(defclass easygui::clickable-image-view (easygui::image-view)
()
(:default-initargs :specifically 'easygui::cocoa-clickable-image-view))
(easygui::define-useful-mouse-event-handling-routines easygui::cocoa-clickable-image-view)
(easygui::define-useful-mouse-event-handling-routines easygui::cocoa-contained-view)
(easygui::define-useful-mouse-event-handling-routines easygui::cocoa-mouseable-text-field)
(defmethod easygui::click-location ((cocoa-self ns:ns-view) (the-event ns:ns-event))
(let* ((ns-point (#/locationInWindow the-event)))
(let* ((ns-converted-point (#/convertPoint:fromView: cocoa-self ns-point nil)))
(let ((where (easygui::point-from-ns-point ns-converted-point)))
where))))
(objc:defmethod (#/mouseDown: :void) ((self easygui::cocoa-button) the-event)
(call-next-method the-event)
(let ((click-location (easygui::click-location self the-event)))
(unless (ccl:%null-ptr-p (#/window self)) ; Could be nil if view or view parent was removed when :dialog-item-action fired
(when (#/isVisible (#/window self)) ; Check for if window is closed and run loop hasn't refreshed
(easygui::mouse-down (easygui::easygui-view-of self) :location click-location)))))
; ----------------------------------------------------------------------
; Providing a mixin class that keeps a view from implicitly redrawing each
; time a subview is added to the display
; ----------------------------------------------------------------------
(defclass easygui::static-view-mixin ()
())
(defmethod easygui::set-needs-display ((view easygui::static-view-mixin) flag)
(declare (ignore flag))
(values))
(defmethod easygui::invalidate-view ((view easygui::static-view-mixin) &optional total)
(declare (ignore total))
(mapc #'easygui::invalidate-view (easygui:view-subviews view)))
; ----------------------------------------------------------------------
; Creating MCL's top-level simple-view class
;
; In order to implement MCL's top-level simple-view class, I needed a cocoa view class that was capable of drawing to the display
; (since simple-view can do this in MCL). Cocoa-drawing-view in easygui seemed like the appropriate class for this. However, the
; default lisp class (drawing-view) for this class did a bit more than a top-level simple-view class should do. It tracks mouse movement,
; which was a problem because a cocoa window class should not track movement, MCL's window class inherits from simple-view, so there were
; many collisions with window class being a subclass of drawing-view. So the current fix is to define a simple-view class that inherits
; only from the easygui view top-level class, but associate that class with cocoa-drawing-view. So make-instance 'simple-view will
; create a simple-view object, and instantiate a cocoa-drawing-view object for that view. This allows window to be a subclass of simple-view,
; simple-view objects to draw to the display, and little code modification/extension to easygui since we're leveraging the objective c methods
; on cocoa-drawing-view.
; ----------------------------------------------------------------------
(defclass easygui::simple-view (easygui::view)
((easygui::flipped :initform easygui::*screen-flipped* :initarg :flipped :reader easygui::flipped-p))
(:default-initargs :specifically 'easygui::cocoa-drawing-view))
; This section is the additional code required to have a simple-view object behave mostly like a drawing-view type object,
; but without inheriting from drawing-view. Sort of a workaround to avoid the drawing-view mouse-tracking methods, since those aren't mixins (yet).
(defmethod easygui::link-cocoa-view ((cocoa-view t) view)
(declare (ignore view))
(values))
(defmethod easygui::link-cocoa-view ((cocoa-view easygui::cocoa-extension-mixin) view)
(setf (slot-value cocoa-view 'easygui::easygui-view) view))
(defmethod easygui::initialize-view :after ((view easygui::simple-view))
(easygui::link-cocoa-view (easygui:cocoa-ref view) view))
; This keeps the setDrawsBackground attribute on the Cocoa object in sync with the
; current background color (is it transparent or not).
(defmethod easygui:set-back-color :after ((view easygui::background-coloring-mixin) (new-color ns:ns-color) &optional redisplay-p)
(setf (slot-value view 'easygui::drawsbackground)
(if (equal (#/clearColor ns:ns-color) new-color) nil t))
(#/setDrawsBackground: (cocoa-ref view) (slot-value view 'easygui::drawsbackground))
(when redisplay-p
(easygui:invalidate-view view)))
(defmethod easygui::cocoa-win-p ((win t))
nil)
(defmethod easygui::cocoa-win-p ((win easygui::cocoa-window))
(cond ((slot-boundp win 'easygui::easygui-window)
t)
(t
(sv-log "not yet a cocoa win ~a" win)
nil)))
(defmethod easygui::size-to-fit ((view easygui::view))
(let ((frame (#/frame (cocoa-ref view))))
(setf (slot-value view 'easygui::size)
(easygui:point (ns:ns-rect-width frame)
(ns:ns-rect-height frame)))))
; Extending this method; patching it so that the view-size slot is initialized after
; the view is drawn, if it wasn't already.
(defmethod easygui::add-1-subview :around ((view easygui::simple-view) (super-view easygui::simple-view))
"Correctly initialize view positions"
(unwind-protect (call-next-method)
(with-slots (easygui::position easygui::size easygui::frame-inited-p) view
(unless (slot-boundp view 'easygui::size)
(easygui::size-to-fit view))
(easygui::set-needs-display view t)
(unless (easygui::view-subviews-busy super-view) (easygui::set-needs-display super-view t)))))
; Isolating the code to convert a vertical coordinate if the screen is flipped. Using just this part in ccl-simple-view.lisp
(defun easygui::convert-if-screen-flipped (y height)
(if easygui::*screen-flipped*
(- (easygui::screen-height) height y)
y))
(defmethod easygui::window-hide ((window easygui::window))
(easygui::running-on-this-thread ()
(let ((cwin (cocoa-ref window)))
(unless (easygui::window-hidden window)
(setf (slot-value window 'easygui::hidden) t)
(unless (dcc (#/isMiniaturized cwin))
(dcc (#/miniaturize: cwin cwin))))
(when (dcc (#/isFlushWindowDisabled cwin))
(dcc (#/enableFlushWindow cwin))
(dcc (#/flushWindow cwin)))
window)))
(defclass easygui::cocoa-matrix (easygui::cocoa-extension-mixin ns:ns-matrix)
()
(:metaclass ns:+ns-object))
(defclass easygui::cocoa-text-field-cell (easygui::cocoa-extension-mixin ns:ns-text-field-cell)
()
(:metaclass ns:+ns-object))
(defun easygui::screen-width nil
(easygui::running-on-this-thread ()
(ns:ns-rect-width (dcc (#/frame (#/objectAtIndex: (#/screens ns:ns-screen) 0))))))
; Default makeKeyAndOrderFront: zeros views with negative coordinates. This behavior is
; undesirable, and does not match the MCL spec. The fix is to ensure the views desired coordinates
; (even if negative) are set for the window by changing the window's position to those coordinates
; after the default makeKeyAndOrderFront: method is called
(objc:defmethod (#/makeKeyAndOrderFront: :void) ((cocoa-win easygui::cocoa-window) (id :id))
(call-next-method id)
(let ((win (easygui::easygui-window-of cocoa-win)))
(setf (easygui::view-position win) (easygui::view-position win))))
; All cocoa windows will auto recalculate the key view loop, since this works most of the time, and isn't computed in the inner loop of a program
; http://stackoverflow.com/questions/4271115/how-should-i-subclass-nswindow-initialization-in-objective-c
; FIXME: Calling #'call-next-method within this method causes a compile-time segfault in the testing environment when a custom ccl app is built using ccl-1.9 on OS X Mavericks.
; Still works fine on OS X Mavericks and ccl-1.9 when the custom app isn't built, and still works in 10.6 and 10.8 when the custom app is built.
; so not worrying about this, yet. The fix is probably to do away with or modify the custom app building, as that was a hack anyways. CTS: 2014-04-08
(objc:defmethod (#/initWithContentRect:styleMask:backing:defer: :id) ((cocoa-win easygui::cocoa-window) (content-rect :<NSR>ECT) (style-mask :<NSUI>NTEGER)
(backing :<NSB>ACKING<S>TORE<T>YPE) (defer :<BOOL>))
(unwind-protect (call-next-method content-rect style-mask backing defer)
(#/setAutorecalculatesKeyViewLoop: cocoa-win #$YES)))
; Class definitions for ns-text-view base cocoa class
(defclass easygui::cocoa-text-view (easygui::cocoa-extension-mixin ns:ns-text-view)
()
(:metaclass ns:+ns-object))
(defclass easygui::cocoa-scroll-view (easygui::cocoa-extension-mixin ns:ns-scroll-view)
()
(:metaclass ns:+ns-object))
; NSTextView uses #/string and #/setString methods, which are different from #/title (title-mixin) and #/stringValue (string-value-mixin) methods,
; so creating an additional mixin when dealing with text objects that inherit from NSTextView
(defclass easygui::view-text-via-string-mixin ()
())
(defmethod easygui::view-text ((view easygui::view-text-via-string-mixin))
(objc:lisp-string-from-nsstring (#/string (cocoa-ref view))))
(defmethod (setf easygui::view-text) (new-text (view easygui::view-text-via-string-mixin))
(#/setString: (cocoa-ref view) (objc:make-nsstring new-text))
new-text)
; ----------------------------------------------------------------------
; End file: easygui/extensions.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: bincarbon/resources.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Some functions to create and manage resource data for CCL
;
; If images or sounds are needed for your application, these functions can
; be used to manage those resources. Usual getters/setters/creators are available:
;
; #'create-resource: Creates an image or sound resource, given a path to that file
; #'add-resource: Adds a created resource to the pool
; #'get-resource-val: Retrieves a resource's value from the pool
;
; Note that a form of lazy evaluation is used to alloc the resources only when needed
; That is, each resource is alloc'd the first time it's retrieved, 'not' when it's created, or
; added to the pool. If you want to alloc all resources currently in the pool (for pre-caching),
; call #'alloc-resources
#-:clozure (error "This file only works with Clozure Common Lisp and not RMCL")
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :cocoa))
(defun init-pool ()
(make-hash-table :test #'equalp))
(defparameter *resource-pool* (init-pool))
(defvar *resource-types* nil)
(defun print-pool (&optional (pool *resource-pool*))
(maphash (lambda (key val)
(format t "~a->~a~%" key val))
pool))
(defun get-pool-as-lst (&optional (pool *resource-pool*))
(loop for value being the hash-values of pool using (hash-key key)
collect (cons key value)))
(defclass resource ()
((val :accessor val :initarg :val)
(type :accessor type :initarg :type)
(alloc-fn :accessor alloc-fn :initarg :alloc-fn)))
(defmacro when-bound ((name instance))
`(if (slot-boundp ,instance ',name)
(,name ,instance)
'slot-unbound))
(defmethod print-object ((obj resource) stream)
(print-unreadable-object (obj stream :identity t :type t)
(format stream "val->~a,alloc-fun->~a~%"
(when-bound (val obj))
(when-bound (alloc-fn obj)))))
(defmethod alloc-resource ((obj resource))
(unless (slot-boundp obj 'val)
(setf (val obj) (funcall (alloc-fn obj))))
obj)
(defun alloc-resources (&optional (pool *resource-pool*))
(maphash
(lambda (key val)
(declare (ignore key))
(alloc-resource val))
pool))
(defmethod get-val ((obj resource))
(alloc-resource obj)
(val obj))
(defun resource-present-p (id &optional type (pool *resource-pool*))
(let ((possible-types
(if type
(list type)
*resource-types*))
(out))
(dolist (type possible-types)
(multiple-value-bind (resource present-p) (gethash (get-key id type) pool)
(when present-p
(push resource out))))
(when out
(unless (eq (length out) 1)
(error "multiple resources with id ~a present in pool ~a~%" id pool))
(values t (first out)))))
(defun get-resource (id &optional type (pool *resource-pool*))
(multiple-value-bind (present-p resource) (resource-present-p id type pool)
(unless present-p
(error "resource with id ~a not present in pool ~a~%" id pool))
resource))
(defun get-resource-val (id &optional type (pool *resource-pool*))
(get-val (get-resource id type pool)))
(defun get-id (resource &optional (pool *resource-pool*))
(declare (ignore resource pool))
(error "write this when needed"))
(defun get-key (id type)
(format nil "~a.~a" id type))
(defun add-resource (resource id &optional (pool *resource-pool*))
(sv-log "adding resource with key ~a" (get-key id (type resource)))
(when (resource-present-p id (type resource) pool)
(sv-log "adding resource with key ~a and overwriting resource with same key that is already present~%"
(get-key id (type resource))))
(setf (gethash (get-key id (type resource)) pool) resource))
(defun remove-resource (resource &optional (pool *resource-pool*))
(declare (ignore resource pool))
(error "write this when needed"))
(defmethod create-resource ((type (eql 'image)) path)
(make-instance
'resource
:alloc-fn
(lambda ()
(#/initWithContentsOfFile:
(#/alloc ns:ns-image)
(objc:make-nsstring path)))))
(defmethod create-resource ((type (eql 'sound)) path)
(make-instance
'resource
:alloc-fn
(lambda ()
(#/initWithContentsOfFile:byReference:
(#/alloc ns:ns-sound)
(objc:make-nsstring path)
nil))))
(defmethod create-resource :around (type path)
(declare (ignore path))
(let ((res (call-next-method)))
(pushnew type *resource-types*)
(setf (type res) type)
res))
; I am requiring all objective-c/lisp functions to not ever use ns-arrays as inputs or outputs
; This slows down computation time b/c conversions have to be done within each function, but it
; makes each one much easier to use in a lisp environment (keep lisp types for inputs and outputs).
;
; I am not doing this for ns-mutable string; I'm putting up with doing the conversion on that one when
; needed. It also would be problematic to convert the type of anything that can be placed within an ns-array.
; Done this way, where the containers (arrays/lists) are converted, but not the containees, the container
; conversion functions do not have to do any type conversion or type checking.
(defmacro! do-array ((varsym array &optional ret) &body body)
`(loop for ,g!i below (#/count ,array)
for ,varsym = (#/objectAtIndex: ,array ,g!i)
do (progn ,@body)
,@(if ret `(finally (return ,ret)))))
(defun ns-array->list (ns-array)
(let ((out))
(do-array (item ns-array out)
(push-to-end item out))))
(defun list->ns-array (lst)
(let ((out (#/array ns:ns-mutable-array)))
(dolist (item lst out)
(#/addObject: out item))))
(defun contents-of-directory (dir)
(ns-array->list
(#/contentsOfDirectoryAtPath:error:
(#/defaultManager ns:ns-file-manager)
(objc:make-nsstring dir)
ccl:+null-ptr+)))
(defun remove-if-not-predicate (lst predicate)
(ns-array->list
(#/filteredArrayUsingPredicate:
(list->ns-array lst)
(#/predicateWithFormat:
ns:ns-predicate
(objc:make-nsstring predicate)))))
(defun remove-if-not-image (lst)
(union
(remove-if-not-predicate lst "self ENDSWITH '.tiff'")
(remove-if-not-predicate lst "self ENDSWITH '.png'")))
(defun remove-if-not-sound (lst)
(remove-if-not-predicate lst "self ENDSWITH '.aif'"))
(defun open-resource-folder (dir)
(let ((dir (if (pathnamep dir)
(directory-namestring dir)
dir)))
(let ((dir (format nil "~a/" (string-right-trim (list #\/) dir))))
(loop for (type filter-fun) in (list (list 'image #'remove-if-not-image)
(list 'sound #'remove-if-not-sound))
do (dolist (image-name (funcall filter-fun (contents-of-directory dir)))
(let* ((image-name-lisp-str (objc:lisp-string-from-nsstring image-name))
(image-name-no-ext (#/stringByDeletingPathExtension image-name))
(res (create-resource type (format nil "~a~a" dir image-name-lisp-str))))
(add-resource res (objc:lisp-string-from-nsstring image-name-no-ext))))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(provide :resources))
; ----------------------------------------------------------------------
; End file: bincarbon/resources.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: bincarbon/mcl-ccl-colors.lisp
; ----------------------------------------------------------------------
#-:clozure (error "This file only works with Clozure Common Lisp and not RMCL")
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :cocoa)
(require :easygui))
; ----------------------------------------------------------------------
; Defining color-symbol->system-color and system-color->symbol for CCL.
;
; These functions may have been in the base CCL distribution, but I couldn't find them.
; So I searched online for a table of color names -> RGB mappings, threw that
; data into a bash shell, cleaned up the text, and then pasted it here. A few lisp
; parentheses were wrapped around that, which turned the data into a lexical closure.
; ----------------------------------------------------------------------
(defparameter *color-table* (make-hash-table :test #'eq))
(defun add-color-symbol-mapping (symb rgb-lst)
(setf (gethash symb *color-table*) rgb-lst))
(let ((rgb-list
(list
'Grey (list 84 84 84)
'gray (list 190 190 190)
'grey (list 190 190 190)
'LightGray (list 211 211 211)
'Light-Gray (list 211 211 211)
'LightSlateGrey (list 119 136 153)
'dark-gray (list 169 169 169)
'SlateGray (list 112 128 144)
'black (list 0 0 0)
'AliceBlue (list 240 248 255)
'BlueViolet (list 138 43 226)
'CadetBlue (list 95 158 160)
'CadetBlue (list 95 158 160)
'CornflowerBlue (list 100 149 237)
'DarkSlateBlue (list 72 61 139)
'DarkTurquoise (list 0 206 209)
'DeepSkyBlue (list 0 191 255)
'DodgerBlue (list 30 144 255)
'LightBlue (list 173 216 230)
'Light-Blue (list 173 216 230)
'LightCyan (list 224 255 255)
'LightSkyBlue (list 135 206 250)
'LightSlateBlue (list 132 112 255)
'LightSteelBlue (list 176 196 222)
'Aquamarine (list 112 219 147)
'MediumBlue (list 0 0 205)
'MediumSlateBlue (list 123 104 238)
'MediumTurquoise (list 72 209 204)
'MidnightBlue (list 25 25 112)
'NavyBlue (list 0 0 128)
'PaleTurquoise (list 175 238 238)
'PowderBlue (list 176 224 230)
'RoyalBlue (list 65 105 225)
'SkyBlue (list 135 206 235)
'SlateBlue (list 106 90 205)
'SteelBlue (list 70 130 180)
'aquamarine (list 127 255 212)
'azure (list 240 255 255)
'blue (list 0 0 255)
'aqua (list 0 255 255)
'cyan (list 0 255 255)
'navy (list 0 0 128)
'teal (list 0 128 128)
'turquoise (list 64 224 208)
'DarkSlateGray (list 47 79 79)
'Iris (list 3 180 200)
'RosyBrown (list 188 143 143)
'SaddleBrown (list 139 69 19)
'SandyBrown (list 244 164 96)
'beige (list 245 245 220)
'brown (list 165 42 42)
'brown (list 166 42 42)
'burlywood (list 222 184 135)
'chocolate (list 210 105 30)
'peru (list 205 133 63)
'tan (list 210 180 140)
'Sienna (list 142 107 35)
'Tan (list 219 147 112)
'DarkGreen (list 0 100 0)
'dark-green (list 0 100 0)
'DarkKhaki (list 189 183 107)
'DarkOliveGreen (list 85 107 47)
'olive (list 128 128 0)
'DarkSeaGreen (list 143 188 143)
'ForestGreen (list 34 139 34)
'GreenYellow (list 173 255 47)
'LawnGreen (list 124 252 0)
'LightSeaGreen (list 32 178 170)
'LimeGreen (list 50 205 50)
'MediumSeaGreen (list 60 179 113)
'MediumSpringGreen (list 0 250 154)
'MintCream (list 245 255 250)
'OliveDrab (list 107 142 35)
'PaleGreen (list 152 251 152)
'SpringGreen (list 0 255 127)
'YellowGreen (list 154 205 50)
'chartreuse (list 127 255 0)
'green (list 0 255 0)
'green (list 0 128 0)
'lime (list 0 255 0)
'khaki (list 240 230 140)
'DarkOrange (list 255 140 0)
'DarkSalmon (list 233 150 122)
'LightCoral (list 240 128 128)
'LightSalmon (list 255 160 122)
'PeachPuff (list 255 218 185)
'bisque (list 255 228 196)
'coral (list 255 127 0)
'coral (list 255 127 80)
'honeydew (list 240 255 240)
'orange (list 255 165 0)
'salmon (list 250 128 114)
'sienna (list 160 82 45)
'Orange (list 255 127 0)
'DeepPink (list 255 20 147)
'HotPink (list 255 105 180)
'IndianRed (list 205 92 92)
'LightPink (list 255 182 193)
'MediumVioletRed (list 199 21 133)
'MistyRose (list 255 228 225)
'OrangeRed (list 255 69 0)
'PaleVioletRed (list 219 112 147)
'VioletRed (list 208 32 144)
'firebrick (list 178 34 34)
'pink (list 255 192 203)
'Flesh (list 245 204 176)
'Feldspar (list 209 146 117)
'red (list 255 0 0)
'tomato (list 255 99 71)
'Firebrick (list 142 35 35)
'Pink (list 188 143 143)
'Salmon (list 111 66 66)
'Scarlet (list 140 23 23)
'DarkOrchid (list 153 50 204)
'DarkViolet (list 148 0 211)
'LavenderBlush (list 255 240 245)
'MediumOrchid (list 186 85 211)
'MediumPurple (list 147 112 219)
'lavender (list 230 230 250)
'magenta (list 255 0 255)
'fuchsia (list 255 0 255)
'maroon (list 176 48 96)
'orchid (list 218 112 214)
'Orchid (list 219 112 219)
'plum (list 221 160 221)
'purple (list 160 32 240)
'purple (list 128 0 128)
'thistle (list 216 191 216)
'violet (list 238 130 238)
'Maroon (list 128 0 0)
'Plum (list 234 173 234)
'Thistle (list 216 191 216)
'Turquoise (list 173 234 234)
'Violet (list 79 47 79)
'AntiqueWhite (list 250 235 215)
'FloralWhite (list 255 250 240)
'GhostWhite (list 248 248 255)
'NavajoWhite (list 255 222 173)
'OldLace (list 253 245 230)
'WhiteSmoke (list 245 245 245)
'gainsboro (list 220 220 220)
'ivory (list 255 255 240)
'linen (list 250 240 230)
'seashell (list 255 245 238)
'snow (list 255 250 250)
'wheat (list 245 222 179)
'white (list 255 255 255)
'Quartz (list 217 217 243)
'Wheat (list 216 216 191)
'BlanchedAlmond (list 255 235 205)
'DarkGoldenrod (list 184 134 11)
'LemonChiffon (list 255 250 205)
'LightGoldenrod (list 238 221 130)
'LightGoldenrodYellow (list 250 250 210)
'LightYellow (list 255 255 224)
'PaleGoldenrod (list 238 232 170)
'PapayaWhip (list 255 239 213)
'cornsilk (list 255 248 220)
'goldenrod (list 218 165 32)
'moccasin (list 255 228 181)
'yellow (list 255 255 0)
'gold (list 255 215 0)
'Goldenrod (list 219 219 112)
'copper (list 184 115 51)
'brass (list 181 166 66)
'bronze (list 140 120 83)
'CSS (list 204 153 0)
'gold (list 205 127 50)
'silver (list 230 232 250))))
(loop for item on rgb-list by #'cddr
do (destructuring-bind (cur-symb cur-rgb) (list (first item) (second item))
(add-color-symbol-mapping cur-symb cur-rgb))))
(defun color-symbol->rgb (symb)
(gethash symb *color-table*))
(defun rgb->color-symbol (rgb)
(let ((res-symb
(loop for cur-symb being the hash-keys of *color-table* using (hash-value cur-rgb)
when (equal cur-rgb rgb) collect cur-symb)))
(ecase (length res-symb)
(0 nil)
(1 (first res-symb))
(2 #| This doesn't work because there are other pairs
in the color table: pink&rosybrown, navyblue&navy,aqua&cyan,lightgray$light-gray,lightblue&light-blue,magenta&fuchsia,darkgreen&dark-green
(progn
(guard ((null (set-difference (list 'gray 'grey) res-symb))))
'gray)))))|#
(cond ((find 'gray res-symb)
'gray)
((find 'pink res-symb)
'pink)
((find 'navy res-symb)
'navy)
((find 'cyan res-symb)
'cyan)
((find 'light-gray res-symb)
'light-gray)
((find 'light-blue res-symb)
'light-blue)
((find 'magenta res-symb)
'magenta)
((find 'dark-green res-symb)
'dark-green)
(t (first res-symb)))))))
(defun color-symbol->system-color (symb)
(destructuring-bind (red green blue) (color-symbol->rgb symb)
(make-color red green blue)))
(defun system-color->symbol (color)
(let ((red (easygui:rgb-red color))
(green (easygui:rgb-green color))
(blue (easygui:rgb-blue color)))
(rgb->color-symbol (list red green blue))))
(defun make-color (red green blue &optional (opacity 1.0))
(easygui:make-rgb :red red :green green :blue blue :opacity opacity))
(defun color-red (color)
(easygui:rgb-red color))
(defun color-green (color)
(easygui:rgb-green color))
(defun color-blue (color)
(easygui:rgb-blue color))
(defun color-opacity (color)
(easygui:rgb-opacity color))
(defun mcl-color-red (color &optional (component (logand (the fixnum (lsh color -16)) #xff)))
"Returns the red portion of the color"
(declare (fixnum component))
(the fixnum (+ (the fixnum (ash component 8)) component)))
(defun mcl-color-green (color &optional (component (logand (the fixnum (lsh color -8)) #xff)))
"Returns the green portion of the color"
(declare (fixnum component))
(the fixnum (+ (the fixnum (ash component 8)) component)))
(defun mcl-color-blue (color &optional (component (logand color #xff)))
"Returns the blue portion of the color"
(declare (fixnum component))
(the fixnum (+ (the fixnum (ash component 8)) component)))
(defun mcl-color-values (color)
"Given an encoded color, returns the red, green, and blue components"
(values
(ceiling (* (/ (float (mcl-color-red color)) (float 65535)) 255))
(ceiling (* (/ (float (mcl-color-green color)) (float 65535)) 255))
(ceiling (* (/ (float (mcl-color-blue color)) (float 65535)) 255))))
(defun mcl-color->system-color (color)
"Converts an MCL color to a CCL system color"
(etypecase color
(integer (multiple-value-bind (r g b) (mcl-color-values color)
(make-color r g b)))
(ns:ns-color color)))
(defparameter *black-color* (color-symbol->system-color 'black))
(defparameter *red-color* (color-symbol->system-color 'red))
(defparameter *light-gray-pattern* (color-symbol->system-color 'gray))
(defparameter *green-color* (color-symbol->system-color 'green))
(defparameter *blue-color* (color-symbol->system-color 'blue))
(defparameter *dark-green-color* (color-symbol->system-color 'DarkGreen))
(defparameter *white-color* (color-symbol->system-color 'white))
(defparameter *gray-color* (mcl-color->system-color 8421504))
(defparameter *yellow-color* (color-symbol->system-color 'yellow))
(defparameter *orange-color* (mcl-color->system-color 16737282))
(eval-when (:compile-toplevel :load-toplevel :execute)
(provide :mcl-ccl-colors))
; ----------------------------------------------------------------------
; End file: bincarbon/mcl-ccl-colors.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: actr6/devices/ccl/share.lisp
; ----------------------------------------------------------------------
(require :resources)
(require :mcl-ccl-colors)
; These are shorthand guard macros for usual cases. Only use these if you quickly want to add
; a guard statement with minimal useful error messages. Otherwise, use the guard macro and
; provide a more meaningful error message
(defmacro guard-!null-ptr (&body body)
`(guard ((not (equal it1 ccl:+null-ptr+)) "null ptr returned when evaling form ~a" ',body)
(progn ,@body)))
(defmacro guard-!nil (&body body)
`(guard (it1 "nil returned when evaling form ~a" ',body)
(progn ,@body)))
(defmacro guard-nil (&body body)
`(guard ((null it1) "~a returned when evaling form ~a; expected nil" it1 ',body)
(progn ,@body)))
(defmacro guard-t-or-nil (&body body)
`(guard ((or (eq it1 nil) (eq it1 t)) "~a returned when evaling form ~a: expected t or nil" it1 ',body)
(progn ,@body)))
(defmacro! return-time-ms (&body body)
`(let ((,g!ctime (get-internal-real-time)))
,@body
(* (/ (- (get-internal-real-time) ,g!ctime) internal-time-units-per-second)
1000)))
; ----------------------------------------------------------------------
; Building class definitions to match MCL's GUI class hierarchy
;
; Most of the class definitions used by MCL are available in CCL using
; the easygui package. However, a few of the slot initargs in the easygui
; package do not match up with MCL initargs. So for these, use mixin
; classes that override initargs in easygui with initargs that match
; MCL's spec.
; ----------------------------------------------------------------------
(defconstant $tejustleft :left)
(defconstant $tejustcenter :center)
(defconstant $tejustright :right)
(defparameter *screen-width* (easygui::screen-width))
(defparameter *screen-height* (easygui::screen-height))
(defclass view-text-via-title-mixin (easygui::view-text-via-title-mixin)
((easygui::text :initarg :window-title)))
(defclass view-text-via-button-title-mixin (view-text-via-title-mixin)
())
(defclass view-text-via-stringvalue-mixin (easygui::view-text-via-stringvalue-mixin)
())
(defclass view-text-mixin (easygui::view-text-mixin)
((text-justification :accessor text-justification :initarg :text-justification))
(:default-initargs :text-justification $tejustleft))
(defparameter *fred-default-font-spec* '("Monaco" 9 :SRCOR :PLAIN (:COLOR-INDEX 0)))
(defclass view-mixin (easygui::view)
((easygui::size :initarg :view-size)
(easygui::position :initarg :view-position :initform (make-point 0 0))
(temp-view-subviews :initarg :view-subviews)
(easygui::foreground :initform (color-symbol->system-color 'black))
(easygui::background :initform (make-color 0 0 0 0.0)))
(:default-initargs :view-font *fred-default-font-spec*))
; MCL allows for subviews to be passed at object initialization. I tried shadowing the 'easygui::subviews :initargs symbol
; with :view-subviews, so that MCL code cleanly initialized easygui's subviews slot, but it turns out that this slot isn't always
; where the subviews are supposed to go. If the view is a window, then the subviews go as subviews under the content-view slot.
; easygui handles all of this in their add-subviews method, so the technique here is to use a temp slot on the view-mixin class,
; make that :initarg :view-subviews, and then on object initialization, take any provided subviews and call easygui's add-subviews method
; on them. Then clear the temp slot. It's a hack, but it seems to work, and requires minimal code additions and still uses
; easygui's add-subviews machinery, etc.
(defmethod initialize-instance :after ((view view-mixin) &key)
(when (slot-boundp view 'temp-view-subviews)
(apply #'add-subviews view (slot-value view 'temp-view-subviews))
(slot-makunbound view 'temp-view-subviews)))
; Try to keep the class hierarchy of the public interface the same as it is for MCL.
; So, simple-view is top; then view (allows subviews); then types that inherit from view,
; like, window, dialog stuff, etc.
(defclass simple-view (easygui::simple-view view-mixin output-stream pen-mixin)
((bezier-path :accessor bezier-path :initform nil)
(direction :initarg :direction :initform :output)
(wptr :initarg :wptr :initform nil)
(help-spec :initarg :help-spec :initform nil)
(view-scroll-position :initarg :view-scroll-position :initform (make-point 0 0))))
(defmethod view-default-size ((view simple-view))
(make-point 100 100))
(defmethod parse-mcl-initargs (&rest list)
(loop for (keyword val . rest) in list
when val append (apply #'parse-mcl-initarg keyword val rest)))
; easygui expects the font slot to be initialized with an ns-font type. However, MCL uses the
; same slot name and expects the font slot to be initialized with a font spec as a list.
; So in order to make it so that the font slot is correct for easygui, shadow the :view-font
; initarg if it is provided by the equivalent ns-font value
(defmethod initialize-instance :around ((view simple-view) &rest args &key back-color view-font view-size view-position view-scroll-position)
(let ((accum (parse-mcl-initargs
(list :back-color back-color)
(list :view-font view-font)
(list :view-size view-size)
(list :view-position view-position)
(list :view-scroll-position view-scroll-position))))
(apply #'call-next-method view (nconc accum args))))
(defmethod initialize-instance :after ((view simple-view) &key)
(guard ((cocoa-is-flipped (cocoa-ref view))))
(guard ((slot-value view 'easygui::flipped)))
(with-slots (direction wptr view-scroll-position) view
(guard ((eq direction :output) "only :output for direction slot is allowed"))
(guard ((eq wptr nil) "only nil for wptr slot is allowed"))
(guard ((points-equal-p view-scroll-position
(make-point 0 0)) "non-(0,0) view-scroll-position is not currently implemented"))))
(defmethod cocoa-is-flipped :around ((self easygui::cocoa-extension-mixin))
(and (slot-value self 'easygui::flipped)
(call-next-method)))
(defmethod cocoa-is-flipped ((self ns:ns-view))
(#/isFlipped self))
(defmethod cocoa-is-flipped ((self t))
t)
; Parsing MCL initarg lists, and converting to CCL/Easygui equivalents
(defun make-font (name pt)
(guard ((not (equal it1 ccl:+null-ptr+)) "font not found for font-name ~a" name)
(#/fontWithName:size: ns:ns-font
(objc:make-nsstring name)
pt)))
(defun color-lst->color (lst)
(destructuring-bind (type val) lst
(ecase type
(:color (mcl-color->system-color val))
(:color-index
(unless (eq val 0)
(error "need to support this")
; Default, so return nil
())))))
(defmethod parse-mcl-initarg ((keyword (eql :view-font)) font-lst &key)
(let ((name) (pt) (color))
(dolist (atom font-lst)
(etypecase atom
(string (setf name atom))
(integer (setf pt atom))
; FIXME; Parse these style and transfer mode values
(keyword ())
(list (setf color (color-lst->color atom)))))
(nconc
(list :view-font (make-font name pt))
(if color
(list :fore-color color)))))
(defmethod parse-mcl-initarg ((keyword (eql :back-color)) back-color &key)
(list :back-color (mcl-color->system-color back-color)))
(defmethod parse-mcl-initarg ((keyword (eql :view-size)) view-size &key)
(list :view-size (mcl-point->system-point view-size)))
(defmethod parse-mcl-initarg ((keyword (eql :view-position)) view-position &key size)
(list :view-position
(if size
(parse-view-position-argument view-position size)
(mcl-point->system-point view-position))))
(defmethod parse-view-position-argument ((keyword (eql :centered)) size)
(destructuring-bind (sizex sizey) (as-list (mcl-point->system-point size))
(make-point (/ (- *screen-width* sizex) 2)
(/ (- *screen-height* sizey) 2))))
(defmethod parse-view-position-argument ((keyword list) size)
(guard ((eq t easygui::*screen-flipped*)))
(destructuring-bind (keyword offset) keyword
(destructuring-bind (x y) (as-list (parse-view-position-argument :centered size))
(destructuring-bind (sizex sizey) (as-list (mcl-point->system-point size))
(ecase keyword
(:top (setf y offset))
(:bottom (setf y (- *screen-height*
(+ sizey offset))))
(:left (setf x offset))
(:right (setf x (- *screen-width*
(+ sizex offset)))))
(make-point x y)))))
(defmethod parse-view-position-argument ((keyword easygui::eg-point) size)
(declare (ignore size))
keyword)
(defmethod parse-view-position-argument ((keyword integer) size)
(declare (ignore size))
keyword)
(defmethod parse-mcl-initarg ((keyword (eql :view-scroll-position)) view-scroll-position &key)
(list :view-scroll-position (mcl-point->system-point view-scroll-position)))
(defclass view (simple-view)
()
(:documentation "Top-level class for views"))
(defclass contained-view (easygui::contained-view view)
((easygui::background :initform (color-symbol->system-color 'white))))
(defclass static-view-mixin (easygui::static-view-mixin) ())
(defclass window (easygui:window view-text-via-title-mixin view)
((grow-icon-p :initform nil :initarg :grow-icon-p :reader grow-icon-p)
(grow-box-p :initarg :grow-box-p)
(theme-background :initarg :theme-background)
(window-show :initarg :window-show)
(window-type :initarg :window-type)
(easygui::closable-p :initarg :close-box-p)
(maintenance-thread :accessor maintenance-thread)
(initialized-p :accessor initialized-p :initform nil)
(easygui::background :initform (color-symbol->system-color 'white))
(close-requested-p :accessor close-requested-p :initform nil)
(sema-finished-close :accessor sema-finished-close :initform (make-semaphore))
(sema-request-close :accessor sema-request-close :initform (make-semaphore))
(window-do-first-click :initarg :window-do-first-click :initform nil)
(window-other-attributes :initarg :window-other-attributes :initform 0)
(process :initarg :process :initform nil)
(auto-position :initarg :auto-position :initform nil))
(:default-initargs
:view-position (make-point 200 200)
:view-size (make-point 200 200)
:contained-view-specifically 'contained-view))
(defun process-active-p (p)
(ccl::process-active-p p))
(defmethod initialize-instance :after ((win window) &key)
(with-slots (window-do-first-click window-other-attributes process auto-position) win
(guard ((null window-do-first-click) "non-nil window-do-first-click not currently implemented"))
(guard ((eq 0 window-other-attributes) "non-zero window-other-attributes not currently implemented"))
(guard ((null process) "process slot should be nil"))
(guard ((member auto-position (list nil :noAutoCenter)) "auto-position not currently implemented")))
(let ((started-sema (make-semaphore)))
(setf (maintenance-thread win)
(process-run-function
(format nil "maintenance thread for win ~a" win)
(lambda ()
(setf (initialized-p win) t)
(ccl::create-autorelease-pool)
(signal-semaphore started-sema)
(while (wptr win)
(cond ((close-requested-p win)
(sv-log "closing ~a on thread ~a~%" win *current-process*)
(funcall (window-close-fct win) win)
(signal-semaphore (sema-finished-close win)))
((aand (front-window) (eq win it))
(window-null-event-handler win)))
(timed-wait-on-semaphore (sema-request-close win) .1)))))
(guard-!nil
(timed-wait-on-semaphore started-sema 1))))
; Give each window a maintenance thread. In that thread,
; periodically check if the window is the frontmost window.
; If it is, call window-null-event-handler on the window.
; I took a sample of the refresh rate of MCL's
; calls to window-null-event-handler, and it
; was around 100ms. So using that rate here.
(defmethod initialize-instance :around ((win window) &rest args &key view-position view-size)
(let ((accum (when (and view-position view-size)
(parse-mcl-initarg :view-position view-position :size view-size))))
(apply #'call-next-method win (nconc accum args))))
(objc:defmethod (#/close :void) ((self easygui::cocoa-window))
(let ((win (easygui::easygui-window-of self)))
(slot-makunbound win 'easygui::ref)
(call-next-method)))
(defparameter *window-null-event-handler-lock* (make-lock "window-null-event-handler-lock"))
(defmethod window-null-event-handler ((win window))
())
(defmethod window-null-event-handler :around ((win window))
(cond ((try-lock *window-null-event-handler-lock*)
(unwind-protect (call-next-method)
(release-lock *window-null-event-handler-lock*)))
(t
(sv-log "not calling null-event-handler for win ~a because another null-event-handler is active~%" win))))
(defmethod window-close ((win window))
(unless (wptr win)
(sv-log "Attempting to close window ~a which is already closed" win)
(return-from window-close nil))
(when (close-requested-p win)
(sv-log "Already requested for window ~a to be closed" win)
(return-from window-close nil))
(setf (close-requested-p win) t)
(signal-semaphore (sema-request-close win))
(sv-log "requesting to close win ~a on thread ~a~%" win *current-process*)
(let ((time
(return-time-ms
(timed-wait-on-semaphore (sema-finished-close win) .5))))
(sv-log "waited for ~,2f ms before win ~a was closed by maintenance thread~%" time win)))
(defclass static-contained-view (static-view-mixin contained-view) ())
(defclass static-window (static-view-mixin window)
()
(:default-initargs :contained-view-specifically 'static-contained-view))
; You could return easygui::perform-close (which calls #/performClose:), but this doesn't close the window when the window doesn't have a close box.
; So to keep things simple, bypass easygui's perform-close method (so bypass #/performClose:) and go directly to #/close.
(defmethod window-close-fct ((win window))
(lambda (win) (#/close (cocoa-ref win))))
(defclass windoid (window)
((easygui::level :initform 1)
(easygui::resizable-p :initform nil)
(easygui::minimizable-p :initform nil)
(easygui::closable-p :initform nil)))
(defclass borderless-window (window)
((easygui::resizable-p :initform nil)
(easygui::minimizable-p :initform nil)
(easygui::closable-p :initform nil)
(easygui::style :initform #$NSBorderlessWindowMask)))
(defmethod windoid-p ((win t))
nil)
(defmethod windoid-p ((win windoid))
t)
(defclass simple-overlay-view (easygui::overlay-view view)
()
(:documentation "Top-level class for views that do not monitor mouse clicks and mouse movement"))
(defclass consuming-view (easygui::consuming-view view)
())
(defclass liner (view)
((liner-type :reader liner-type :initarg :liner-type)
(easygui::foreground :reader color :initarg :color)))
(defclass dialog (window)
()
(:default-initargs
:window-title "Untitled Dialog"
:window-type :document))
(defclass color-dialog (dialog)
()
(:documentation "Top-level class for windows"))
(defclass action-view-mixin (easygui::action-view-mixin) ())
(defmethod initialize-instance :around ((view action-view-mixin) &rest args &key action)
(let ((accum (parse-mcl-initargs (list :action action :view view))))
(apply #'call-next-method view (nconc accum args))))
(defmethod parse-mcl-initarg ((keyword (eql :action)) action &key view)
(guard ((not (null view)) "view must associated with an action"))
(list :action
(lambda ()
(sv-log-n 1 "calling action for ~a" view)
(funcall action)
(sv-log-n 1 "finished calling action for ~a" view))))
(defclass dialog-item (view view-text-mixin action-view-mixin)
((easygui::dialog-item-enabled-p :initarg :enabled-p)
(part-color-list :reader part-color-list :initarg :part-color-list)
(dialog-item-handle :accessor dialog-item-handle :initarg :dialog-item-handle :initform nil)
(dialog-item-action :accessor dialog-item-action :initarg :dialog-item-action :initform nil)
(allow-tabs :reader allow-tabs :initarg :allow-tabs :initform nil)
(compress-text :accessor compress-text :initarg :compress-text :initform nil))
(:default-initargs
:view-font '("Lucida Grande" 13 :SRCCOPY :PLAIN (:COLOR-INDEX 0))))
; easygui's action slot takes a lambda with zero arguments. MCL's dialog-item-action slots take a lambda
; with the object/view as an argument. So to enable this feature, wrap a :dialog-item-action
; initarg function in a closure that takes zero arguments, and assign that clozure to the :action initarg
(defmethod initialize-instance :around ((view dialog-item) &rest args &key dialog-item-action)
(let ((accum (parse-mcl-initargs
(list :dialog-item-action dialog-item-action :view view))))
(apply #'call-next-method view (nconc accum args))))
(defmethod parse-mcl-initarg ((keyword (eql :dialog-item-action)) action &key view)
(guard ((not (null view)) "dialog item action must be associated with a view"))
(list :action (lambda () (funcall action view))))
(defmethod initialize-instance :before ((view dialog-item) &key text)
(guard ((null text) "Do not use :text initarg; use :dialog-item-text instead")))
(defmethod initialize-instance :after ((view dialog-item) &key)
(guard ((null (dialog-item-handle view)) "Not utilizing dialog-item-handle"))
(guard ((null (compress-text view)) "Not utilizing compress-text"))
(size-to-fit view)
(when (slot-boundp view 'part-color-list)
(loop for (part color) in (group (part-color-list view) 2)
do (set-part-color view part (mcl-color->system-color color)))))
; Note that the :specifically initarg says what cocoa view class to associate with an instance of the object.
; These really should have been specified in the easygui package, alongside each easygui class definition IMHO, but they weren't.
; Most of the easygui package uses a global easygui::*view-class-to-ns-class-map* variable that contains mappings of lisp
; classes to cocoa view classes, but I found using this flat mapping to be problematic with clos hierarchies.
; Easygui also provides a :specifically method to overrule the easygui::*view-class-to-ns-class-map* variable, and I like this better,
; so I'm using it. The benefits of the :specifically method are:
; [1] cocoa view class mappings are explicitly written, and contained within each clos class definition.
; [2] As the clos classes are extended, the :specifically values are inherited/over-ridden in the usual way.
(defclass button-dialog-item (easygui:push-button-view view-text-via-button-title-mixin easygui::text-fonting-mixin dialog-item)
((easygui::default-button-p :initarg :default-button)
(cancel-button :initarg :cancel-button))
(:default-initargs :specifically 'easygui::cocoa-button :text-justification $tejustcenter))
(defmethod get-mutable-title ((view view-text-via-title-mixin))
(let ((attributed-title (guard-!null-ptr (#/attributedTitle (cocoa-ref view)))))
(let ((mutable-title (#/alloc ns:ns-mutable-attributed-string)))
(#/initWithAttributedString: mutable-title attributed-title))))
(defmethod add-to-attributed-title ((view view-text-via-title-mixin) name val)
(let* ((mutable-title (get-mutable-title view))
(title-range (ns:make-ns-range 0 (#/length mutable-title))))
(#/addAttribute:value:range: mutable-title name val title-range)
(#/setAttributedTitle: (cocoa-ref view) mutable-title)))
(defmethod set-fore-color :before ((view view-text-via-button-title-mixin) (color ns:ns-color))
(add-to-attributed-title view #$NSForegroundColorAttributeName color))
(defmethod initialize-instance :after ((view view-text-via-button-title-mixin) &key)
(set-fore-color view (slot-value view 'easygui::foreground)))
(defclass default-button-dialog-item (button-dialog-item)
()
(:default-initargs :dialog-item-text "OK" :default-button t :cancel-button nil))
(defclass static-text-dialog-item (easygui:static-text-view view-text-via-stringvalue-mixin dialog-item)
((bordered-p :reader bordered-p)
(text-truncation :initarg :text-truncation :reader text-truncation :initform #$NSLineBreakByTruncatingTail)
(easygui::drawsbackground :initform nil))
(:default-initargs :specifically 'easygui::cocoa-mouseable-text-field))
(defmethod initialize-instance :around ((view static-text-dialog-item) &rest args &key text-truncation)
(let ((accum (parse-mcl-initargs (list :text-truncation text-truncation))))
(apply #'call-next-method view (nconc accum args))))
; Default line break mode is to wrap and not tighten. Cocoa has a TighteningFactorForTruncation value that is set to .05.
; And that threshold default is fine, but it doesn't kick in (tighten the text) unless the cell is set to truncate.
(defmethod initialize-instance :after ((view static-text-dialog-item) &key)
(awhen (text-truncation view)
(#/setLineBreakMode: (#/cell (cocoa-ref view)) it)))
(defmethod parse-mcl-initarg ((keyword (eql :text-truncation)) val &key)
(list
:text-truncation
(etypecase val
(keyword (ecase val
(:end #$NSLineBreakByTruncatingTail)))
(integer val))))
; Cocoa doesn't automatically determine the value of drawsbackground dependent on the background color.
; If the back color is clear, drawsbackground should be nil, otherwise t. So if a back-color is passed in
; as an initform, and that color is not clear, inform easygui that the background should be drawn by passing
; a t for :draws-background keyword.
(defmethod initialize-instance :around ((view easygui::background-coloring-mixin) &rest args &key back-color)
(if (and back-color
(not (equalp (color-opacity (mcl-color->system-color back-color))
0)))
(apply #'call-next-method view :draws-background t args)
(call-next-method)))
(defmethod (setf bordered-p) (bordered-p (view static-text-dialog-item))
(unwind-protect (setf (slot-value view 'bordered-p) bordered-p)
(#/setBordered: (easygui:cocoa-ref view) (if bordered-p #$YES #$NO))))
(defclass scroll-bar-dialog-item (easygui::content-view-mixin dialog-item)
((scrollee :accessor scrollee :initarg :scrollee)
(scrollee-class :initarg :scrollee-class)
(v-scroll-p :reader v-scroll-p :initarg :v-scroll-p))
(:default-initargs
:v-scroll-p t
:specifically 'easygui::cocoa-scroll-view
:objc-content-view-accessor #'#/documentView))
(defclass editable-text-dialog-item (easygui::editable-mixin easygui::mouse-tracking-mixin scroll-bar-dialog-item)
((allow-returns :initarg :allow-returns)
(draw-outline :initarg :draw-outline))
(:default-initargs
:v-scroll-p nil
:scrollee-class 'inner-text-view))
(defclass inner-text-view (dialog-item easygui::view-text-via-string-mixin easygui::text-coloring-mixin easygui::text-fonting-mixin)
()
(:default-initargs
:specifically 'easygui::cocoa-text-view))
(defmethod initialize-instance :around ((view scroll-bar-dialog-item) &rest args &key scrollee scrollee-class)
(setf (scrollee view)
(if scrollee
scrollee
(apply #'make-instance
scrollee-class
(getf-include-key args (list :view-size :allow-tabs :view-font :dialog-item-text :text-justification)))))
; Not removing :view-size, since the content-view-mixin should make use of this information as well, if available
(mapc (lambda (indicator) (remf args indicator))
(list :allow-tabs :view-font :dialog-item-text :text-justification))
(apply #'call-next-method view :content-view (scrollee view) args))
(defmethod easygui::initialize-view :after ((view scroll-bar-dialog-item))
(let ((content-view (slot-value view 'easygui::content-view)))
(#/setDocumentView: (cocoa-ref view) (cocoa-ref content-view))
(#/setBorderType: (cocoa-ref view) #$NSBezelBorder)
(setf (slot-value content-view 'easygui::parent) view)))
(defmethod initialize-instance :after ((view scroll-bar-dialog-item) &key v-scroll-p)
(when v-scroll-p
(#/setHasVerticalScroller: (cocoa-ref view) #$YES)))
; I couldn't get #/sizeToFit to work for NSTextView objects, so doing things manually in this case
; http://stackoverflow.com/questions/2654580/how-to-resize-nstextview-according-to-its-content
(defmethod size-to-fit ((view inner-text-view))
(when (and (slot-boundp view 'easygui::text)
(not (slot-boundp view 'easygui::size)))
(easygui::running-on-main-thread ()
(#/setFrameSize: (cocoa-ref view) (ns:make-ns-size 100000 10000)) ; Needed so that #/usedRectForTextContainer: doesn't return a size 0 frame; not sure why
(let ((container (#/textContainer (cocoa-ref view))))
(let ((manager (#/layoutManager (cocoa-ref view))))
(#/ensureLayoutForTextContainer: manager container)
(let ((frame (#/usedRectForTextContainer: manager container))) ; The frame will be the size required to fit all of the view's current text
(#/setFrameSize: (cocoa-ref view)
(ns:make-ns-size (ns:ns-rect-width frame)
(ns:ns-rect-height frame)))
(easygui::size-to-fit view)))))))
(defmethod size-to-fit ((view editable-text-dialog-item))
(when (and (not (slot-boundp view 'easygui::size))
(slot-boundp (content-view view) 'easygui::size))
(set-view-size view (add-points (make-point 5 5) (view-size (content-view view))))))
(defmethod size-to-fit ((view dialog-item))
(when (and (slot-boundp view 'easygui::text)
(not (slot-boundp view 'easygui::size)))
(#/sizeToFit (cocoa-ref view))
(easygui::size-to-fit view)))
(defmethod cocoa-text-view ((view editable-text-dialog-item))
(cocoa-ref (content-view view)))
(defclass radio-button-dialog-item (easygui:radio-button-view view-text-via-button-title-mixin dialog-item)
((easygui::cluster :initarg :radio-button-cluster)
(easygui::selected :initarg :radio-button-pushed-p))
(:default-initargs :specifically 'easygui::cocoa-button))
(defclass check-box-dialog-item (easygui:check-box-view view-text-via-button-title-mixin dialog-item)
((easygui::text :initform ""))
(:default-initargs :specifically 'easygui::cocoa-button))
(defclass table-dialog-item (view-text-via-stringvalue-mixin dialog-item)
())
(defclass sequence-dialog-item (table-dialog-item)
((table-sequence :reader table-sequence :initarg :table-sequence)
(columns :reader columns :initform 1)
(table-print-function :accessor table-print-function :initarg :table-print-function :initform nil)
(rows :reader rows)
(cell-size :reader cell-size :initarg :cell-size)
(table-hscrollp :reader table-hscrollp :initarg :table-hscrollp :initform nil)
(table-vscrollp :reader table-vscrollp :initarg :table-vscrollp :initform t)
(selection-type :initarg :selection-type))
(:default-initargs
:specifically 'easygui::cocoa-matrix
:table-sequence ()))
(defmethod (setf rows) (new-rows (view sequence-dialog-item))
(with-slots (columns rows) view
(unwind-protect (setf rows new-rows)
(#/renewRows:columns: (cocoa-ref view) rows columns))))
(defmethod set-cell-size ((view sequence-dialog-item) h &optional v)
(destructuring-bind (h v) (canonicalize-point h v)
(with-slots (cell-size) view
(unwind-protect (setf cell-size (make-point h v))
(#/setCellSize: (cocoa-ref view)
(ns:make-ns-size h v))))))
(defmethod cell-contents ((view sequence-dialog-item) h &optional v)
(destructuring-bind (h v) (canonicalize-point h v)
(guard ((eq h 0)))
(nth v (table-sequence view))))
(defmethod set-table-sequence ((view sequence-dialog-item) new-sequence)
(with-slots (table-sequence table-print-function) view
(with-accessors ((view-font view-font)) view
(setf (rows view) (length new-sequence))
(unwind-protect (setf table-sequence new-sequence)
(loop for item in new-sequence
for index from 0
with cell-array = (#/cells (cocoa-ref view))
for cell = (#/objectAtIndex: cell-array index)
do (#/setTitle: cell
(objc::make-nsstring (funcall table-print-function item nil)))
when view-font do (#/setFont: cell view-font))))))
(defmethod selected-cells ((view sequence-dialog-item))
(let ((selected-cells))
(do-array (cell (#/selectedCells (cocoa-ref view)) selected-cells)
(push-to-end (get-location-of-cell view cell)
selected-cells))))
(defmethod get-location-of-cell ((view sequence-dialog-item) (cell ns:ns-cell))
(rlet ((rownum #>NSInteger)
(colnum #>NSInteger))
(#/getRow:column:ofCell: (cocoa-ref view) rownum colnum cell)
(make-point (pref colnum #>NSInteger)
(pref rownum #>NSInteger))))
(defmethod initialize-instance :after ((view sequence-dialog-item) &key)
(let ((cocoa-matrix (cocoa-ref view))
(prototype (make-instance 'easygui::cocoa-text-field-cell)))
(with-slots (table-hscrollp table-vscrollp columns) view
(guard (table-vscrollp "Sequence dialog item must allow vertical scrolling"))
(guard ((not table-hscrollp) "Sequence dialog item must not allow horizontal scrolling"))
(guard ((eq columns 1) "Only supporting a single column currently")))
(unless (table-print-function view)
(setf (table-print-function view)
(lambda (item strm) (format strm "~a" item))))
(unless (slot-boundp view 'cell-size)
(setf (slot-value view 'cell-size)
(make-point (point-h (view-size view)) 20)))
(#/setPrototype: cocoa-matrix prototype)
(#/setMode: cocoa-matrix #$NSListModeMatrix)
(#/setIntercellSpacing: cocoa-matrix (ns:make-ns-size 0 0))
(set-cell-size view (cell-size view))
(set-table-sequence view (table-sequence view))))
(defclass image-view (easygui::image-view view)
((pict-id :reader pict-id :initarg :pict-id)))
(defmethod size-to-fit ((view image-view))
(let ((view-size
(cond ((not (slot-boundp view 'easygui::size))
(let ((ns-size (#/size (#/image (cocoa-ref view)))))
(destructuring-bind (width height) (as-list ns-size)
(make-point width height))))
(t
(view-size view)))))
(set-view-size view view-size)))
(defmethod initialize-instance :after ((view image-view) &key)
(when (slot-boundp view 'pict-id)
(setf (pict-id view) (pict-id view)))
(size-to-fit view))
(defmethod (setf easygui::view-size) :after (size (view image-view))
(destructuring-bind (width height) (as-list size)
(#/setSize: (#/image (cocoa-ref view)) (ns:make-ns-size width height))))
(defmethod (setf pict-id) (pict-id (view image-view))
(unwind-protect (setf (slot-value view 'pict-id) pict-id)
(#/setImage: (easygui:cocoa-ref view) (get-resource-val pict-id 'image))))
(defclass back-image-view (image-view) ())
(defclass clickable-image-view (easygui::clickable-image-view image-view) ())
(defclass icon-dialog-item (clickable-image-view dialog-item view)
((pict-id :reader icon :initarg :icon)
(easygui::view-text :initarg :view-text)))
; Place all images in the background (behind all other views). Do this by
; specializing on the add-1-subview method in the easygui package. And call
; cocoa's method for adding a subview that is behind all other views
(defmethod easygui::add-1-subview ((view back-image-view) (super-view view))
(setf (slot-value view 'easygui::parent) super-view)
(push view (slot-value super-view 'easygui::subviews))
(#/addSubview:positioned:relativeTo:
(easygui:cocoa-ref super-view)
(easygui:cocoa-ref view)
#$NSWindowBelow
nil))
(provide :icon-dialog-item)
(defun make-dialog-item (class position size text &optional action &rest attributes)
(apply #'make-instance class
(nconc
(list
:view-position position
:view-size size
:dialog-item-text text)
(if action (list :dialog-item-action action))
attributes)))
(defclass menu-view (easygui::menu-view view view-text-via-title-mixin easygui::text-fonting-mixin easygui::decline-menu-mixin)
((easygui::text :initarg :menu-title)
(default-item :initarg :default-item :initform 1)
(auto-update-default :initarg :auto-update-default)
(item-display :initarg :item-display))
(:default-initargs :specifically 'easygui::cocoa-pop-up-button))
; FIXME: menu-item-checked isn't being used at all; default-item from menu-view determines which item is checked. Is it worth the time
; to use this slot, and make it so that the char rendered for the checked item can be changed, or also that multiple items can be checked,
; etc.?
(defclass menu-item (easygui::menu-item-view view view-text-via-title-mixin easygui::text-fonting-mixin action-view-mixin easygui::decline-menu-mixin)
((easygui::text :initarg :menu-item-title)
(style :initarg :style)
(menu-item-checked :initarg :menu-item-checked :initform nil))
(:default-initargs :specifically 'easygui::cocoa-menu-item))
(defmethod initialize-instance :around ((view menu-view) &rest args &key default-item menu-items)
(if menu-items
(apply #'call-next-method view :selection (nth (1- default-item) menu-items) args)
(call-next-method)))
(defclass pop-up-menu (easygui::pop-up-menu menu-view) ())
; ----------------------------------------------------------------------
; Building methods that allow CCL to understand basic MCL drawing commands
; Many of the functions/methods for basic MCL drawing are available in CCL's
; easygui package. For the functions, import them into the current package.
; For the methods, add a generic method to the current CCL package
; that calls the generic method in the easygui package. Don't import the
; generic functions from the easygui package, because this will cause
; symbol collisions for the generic methods in the current package that are
; already defined (might be because they are an act-r interface method, or
; because they are an already-defined CCL method)
; ----------------------------------------------------------------------
(defun point-h (pt)
(easygui:point-x pt))
(defun point-v (pt)
(easygui:point-y pt))
(defun point-x (pt)
(easygui:point-x pt))
(defun point-y (pt)
(easygui:point-y pt))
(ccl::register-character-name "UpArrow" #\U+F700)
(ccl::register-character-name "DownArrow" #\U+F701)
(ccl::register-character-name "BackArrow" #\U+F702)
(ccl::register-character-name "ForwardArrow" #\U+F703)
(ccl::register-character-name "CheckMark" #\t)
(defparameter *arrow-cursor* (#/arrowCursor ns:ns-cursor))
(defparameter *crosshair-cursor* (#/crosshairCursor ns:ns-cursor))
(defparameter *i-beam-cursor* (#/IBeamCursor ns:ns-cursor))
(defparameter *black-pattern* 'black-pattern-fixme)
(defun make-point (x y)
(easygui::point x y :allow-negative-p t))
(defmethod add-points ((p1 easygui::eg-point) (p2 easygui::eg-point))
(make-point
(+ (point-x p1) (point-x p2))
(+ (point-y p1) (point-y p2))))
(defmethod subtract-points ((p1 easygui::eg-point) (p2 easygui::eg-point))
(make-point
(- (point-x p1) (point-x p2))
(- (point-y p1) (point-y p2))))
(defmethod as-list ((p easygui::eg-point))
(list (point-h p)
(point-v p)))
(defmethod as-list ((r ns:ns-range))
(list (ns:ns-range-location r)
(ns:ns-range-length r)))
(defmethod as-list ((r ns:ns-rect))
(list (ns:ns-rect-width r)
(ns:ns-rect-height r)
(ns:ns-rect-x r)
(ns:ns-rect-y r)))
(defmethod as-list ((s ns:ns-size))
(list (ns:ns-size-width s)
(ns:ns-size-height s)))
(defmethod points-equal-p ((p1 easygui::eg-point) (p2 easygui::eg-point))
(destructuring-bind (x1 y1) (as-list p1)
(destructuring-bind (x2 y2) (as-list p2)
(and (eq x1 x2)
(eq y1 y2)))))
; This reverse engineering was done entirely by pattern matching.
; I need to learn more about how bit shifting works if I want to
; be completely confident that this implementation is correct.
(defun mcl-point-h (pt)
(logand (lsh pt 0) #xffff))
(defun mcl-point-v (pt)
(logand (lsh pt -16) #xffff))
(defun mcl-point->system-point (mcl-point)
(etypecase mcl-point
(integer (make-point
(mcl-point-h mcl-point)
(mcl-point-v mcl-point)))
(easygui::eg-point mcl-point)))
(defmethod point-string ((point easygui::eg-point))
(format nil "#@(~a ~a)" (point-x point) (point-y point)))
(defmethod add-subviews ((view simple-view) &rest subviews)
(when subviews
(apply #'easygui:add-subviews view subviews)))
(defmethod remove-subviews ((view simple-view) &rest subviews)
(when subviews
(apply #'easygui:remove-subviews view subviews)))
(defmethod subviews ((view simple-view) &optional subview-type)
(declare (ignore subview-type))
(easygui:view-subviews view))
(defmethod view-subviews ((view simple-view))
(easygui:view-subviews view))
(defmethod view-named (name (view simple-view))
(acond ((easygui:view-named name view)
it)
(t
(sv-log "no subview with view-nick-name ~a found in ~a" name view)
nil)))
(defmethod find-named-sibling ((view simple-view) name)
(let ((container (view-container view)))
(and container (view-named name container))))
(defmethod view-nick-name ((view simple-view))
(easygui:view-nick-name view))
(defmethod window-select ((win window))
(easygui:window-show win))
(defmethod window-show ((win window))
(easygui:window-show win))
(defmethod window-hide ((win window))
(easygui::window-hide win))
(defmethod window-shown-p ((window window))
(not (easygui::window-hidden window)))
(defun find-window (title &optional class)
(let ((title (format nil "~a" title)))
(do-array (cocoa-win (#/windows (#/sharedApplication ns:ns-application)))
(when (easygui::cocoa-win-p cocoa-win)
(let* ((wintitle (objc:lisp-string-from-nsstring (#/title cocoa-win)))
(clos-win (easygui::easygui-window-of cocoa-win))
(winclass (class-name (class-of clos-win)))
(prefix (subseq wintitle 0 (min (length wintitle) (length title)))))
(when (string-equal prefix title)
(when (or (not class) (eq class winclass))
(return-from find-window clos-win)))))))
nil)
(defun front-window (&key class include-invisibles include-windoids)
(guard ((null include-invisibles)))
(when class
(when (symbolp class)
(setq class (find-class class)))
(when (class-inherit-from-p class (find-class 'windoid))
(setq include-windoids t)))
(let ((wins (gui::windows)))
(dolist (win wins)
(when (easygui::cocoa-win-p win)
(let ((wob (easygui::easygui-window-of win)))
(when (and wob
(initialized-p wob)
(or include-windoids
(not (windoid-p wob)))
(or (null class)
(inherit-from-p wob class)))
(return wob)))))))
(defun inherit-from-p (ob parent)
(ccl::inherit-from-p ob parent))
(defun class-inherit-from-p (class parent-class)
(flet ((get-class (value)
(if (symbolp value) (find-class value nil) value)))
(let ((pclass (get-class parent-class)))
(memq pclass
(ccl::%inited-class-cpl (get-class class))))))
;FIXME: This looks very strange. Prob related to Phaser's floating window
(defun ccl::window-bring-to-front (w &optional (wptr (wptr w)))
#-:sv-dev (declare (ignore wptr))
nil)
(defmethod set-window-layer ((window window) new-layer &optional include-invisibles)
#-:sv-dev (declare (ignore new-layer include-invisibles))
'fixme)
(defmethod window-title ((view window))
;TODO: Maybe use easygui:view-text method here?
(easygui::window-title view))
(defmethod dialog-item-text ((view view-text-mixin))
(easygui:view-text view))
(defmethod set-dialog-item-text ((view view-text-mixin) text)
(easygui::running-on-main-thread ()
(setf (easygui:view-text view) text)))
(defmethod easygui::view-text ((view editable-text-dialog-item))
(easygui::view-text (content-view view)))
(defmethod (setf easygui::view-text) (new-text (view editable-text-dialog-item))
(setf (easygui::view-text (content-view view)) new-text))
(defmethod text-just ((view view-text-mixin))
(text-justification view))
(defun convert-justification (justification)
(let ((mapping (list (cons $tejustleft #$NSLeftTextAlignment)
(cons nil #$NSLeftTextAlignment)
(cons $tejustcenter #$NSCenterTextAlignment)
(cons $tejustright #$NSRightTextAlignment))))
(guard (it1 "No mapping found for justification ~a" justification)
(cdr (assoc justification mapping)))))
(defmethod set-text-justification ((view view-text-mixin) justification)
(#/setAlignment: (easygui:cocoa-ref view) (convert-justification justification))
(setf (text-justification view) justification))
(defmethod initialize-instance :after ((view view-text-mixin) &key)
(when (slot-boundp view 'text-justification)
(set-text-justification view (text-justification view))))
(defmethod selection-range ((view easygui::content-view-mixin))
(selection-range (content-view view)))
(defmethod selection-range ((view simple-view))
(destructuring-bind (start length) (as-list (#/selectedRange (cocoa-ref view)))
(values start (+ start length))))
(defmethod set-selection-range ((view easygui::content-view-mixin) &optional position cursorpos)
(set-selection-range (content-view view) position cursorpos))
(defmethod set-selection-range ((view view-text-mixin) &optional position cursorpos)
(destructuring-bind (position cursorpos) (if position
(list position cursorpos)
(list 0 0))
(easygui::running-on-main-thread ()
(#/setSelectedRange: (cocoa-ref view)
(ns:make-ns-range position (- cursorpos position))))))
(defmethod set-selection-range :after ((view editable-text-dialog-item) &optional position cursorpos)
(declare (ignore position cursorpos))
(easygui::running-on-main-thread ()
(#/becomeFirstResponder (cocoa-ref view))))
(defmethod dialog-item-enable ((view action-view-mixin))
(easygui:set-dialog-item-enabled-p view t))
(defmethod dialog-item-disable ((view action-view-mixin))
(easygui:set-dialog-item-enabled-p view nil))
; FIXME: What now to do about these, since etdi is a text-view, which is not an NSControl
(defmethod dialog-item-enable ((view editable-text-dialog-item))
())
(defmethod dialog-item-disable ((view editable-text-dialog-item))
())
(defmethod check-box-check ((item check-box-dialog-item))
(easygui:check-box-check item nil))
(defmethod check-box-uncheck ((item check-box-dialog-item))
(easygui:check-box-uncheck item nil))
(defmethod check-box-checked-p ((item check-box-dialog-item))
(easygui:check-box-checked-p item))
(defmethod radio-button-unpush ((item radio-button-dialog-item))
(easygui:radio-button-deselect item))
(defmethod radio-button-push ((item radio-button-dialog-item))
(easygui:radio-button-select item))
(defmethod radio-button-pushed-p ((item radio-button-dialog-item))
(easygui:radio-button-selected-p item))
(defmethod view-position ((view simple-view))
(easygui:view-position view))
(defmethod view-position :before ((window window))
(let ((frame (#/frame (cocoa-ref window))))
(let ((position
(make-point
(ns:ns-rect-x frame)
(easygui::convert-if-screen-flipped
(ns:ns-rect-y frame)
(point-y (view-size window))))))
(setf (slot-value window 'easygui::position) position))))
(defmethod view-global-position ((view simple-view))
(local-to-global view (make-point 0 0)))
(defmethod view-center ((view simple-view))
(destructuring-bind (x y) (as-list (view-position view))
(destructuring-bind (sizex sizey) (as-list (view-size view))
(make-point (+ x (/ sizex 2))
(+ y (/ sizey 2))))))
(defmethod view-global-center ((view simple-view))
(local-to-global
view
(subtract-points (view-center view) (view-position view))))
; FIXME: This seems to work properly, but I don't currently understand why,
; or what view-origin is supposed to do in MCL
(defmethod view-origin ((view simple-view))
(let ((bounds (#/bounds (cocoa-ref view))))
(make-point (ns:ns-rect-x bounds)
(ns:ns-rect-y bounds))))
(defmethod origin ((view simple-view))
(view-origin view))
(defmethod set-origin ((view simple-view) h &optional v)
(destructuring-bind (h v) (canonicalize-point h v)
(#/setBoundsOrigin: (cocoa-ref view) (ns:make-ns-point h v))))
; Note that this is MCL's arglist spec. The erase-p isn't needed for CCL,
; but it should be kept here so that MCL code calling invalidate-view still works.
(defmethod invalidate-view ((view simple-view) &optional erase-p)
(declare (ignore erase-p))
(easygui:invalidate-view view))
; FIXME: What is validate-view supposed to do differently than invalidate-view?
; And is that difference already handled within cocoa?
(defmethod validate-view ((view simple-view))
(invalidate-view view))
(defun canonicalize-point (x y)
(cond (y (list x y))
(t (list (point-h x) (point-v x)))))
(defmethod set-view-position ((view simple-view) x &optional (y nil))
(destructuring-bind (x y) (canonicalize-point x y)
(let ((pos (make-point x y)))
(setf (easygui:view-position view) pos))))
(defmethod set-view-size ((view simple-view) x &optional (y nil))
(destructuring-bind (x y) (canonicalize-point x y)
(let ((size (make-point x y)))
(setf (easygui:view-size view) size))))
(defmethod view-size ((view simple-view))
(easygui:view-size view))
(defmethod width ((view simple-view))
(point-h (view-size view)))
(defmethod height ((view simple-view))
(point-v (view-size view)))
(defmethod view-container ((view simple-view))
(easygui:view-container view))
(defmethod view-window ((view simple-view))
(easygui::easygui-window-of view))
(defmethod content-view ((view easygui::content-view-mixin))
(easygui:content-view view))
(defmethod content-view ((view simple-view))
view)
; Other MCL drawing methods are not available in the easygui package.
; For these, move down a layer below easygui, and implement the functionality
; using CCL's Objective C bridge. Most bridge calls will have #/ or #_ reader
; macros in the expression
; A few with- macros to handle setup/teardown, and make programming a bit easier
; This one uses Doug Hoyte's "defmacro!" and ",g!" syntax to easily handle unwanted variable capture.
(defmacro! with-graphics-context (&body body)
"Any changes to the graphics environment by body, will be valid only in body"
`(let ((,g!context (#/currentContext ns:ns-graphics-context)))
(unwind-protect (progn
(#/saveGraphicsState ,g!context)
,@body)
(#/restoreGraphicsState ,g!context))))
; ----------------------------------------------------------------------
; Section to handle current focused view and font focused view.
;
; The dynamic variables are used to keep track of any views that are focused in the dynamic environment.
; Code could call with-focused-view explicitly, or a view might become focused because code called paint-rect
; and passed a view to that function. The goal is to have the code do the right thing and try to
; figure out which view has focus. If it can't figure this out, then an exception will be thrown.
; These can be seen where the guard macros are used.
; ----------------------------------------------------------------------
(defparameter *current-graphics-context-stroke-color* nil)
(defmacro! with-fore-color (o!color &body body)
`(progn
(guard ((eq (type-of ,g!color) 'ns:ns-color) "color ~a is not a system color" ,g!color) ())
(let ((*current-graphics-context-stroke-color* ,g!color))
(with-graphics-context
(#/set ,g!color)
,@body))))
(defmacro with-fallback-fore-color (color &body body)
`(if (null *current-graphics-context-stroke-color*)
(with-fore-color ,color
,@body)
(progn ,@body)))
(defmacro with-window-fallback-fore-color (view &body body)
`(with-fallback-fore-color (get-fore-color (view-window ,view))
,@body))
(defparameter *current-focused-view* nil)
(defparameter *current-font-view* nil)
(defparameter *current-graphics-context-font* nil)
(defmacro! with-focused-view (o!view &body body)
"Any changes to the graphics environment by body will be directed to the view object"
`(let ((*current-focused-view* (content-view ,g!view)))
(easygui:with-focused-view (easygui:cocoa-ref (content-view ,g!view))
,@body)))
(defmacro! with-font-view (o!view &body body)
`(let ((*current-font-view* ,g!view))
,@body))
(defmacro! with-font-focused-view (o!view &body body)
`(with-font-view ,g!view
(with-focused-view ,g!view
,@body)))
(defmacro with-fallback-focused-view (view &body body)
`(if (null *current-focused-view*)
(with-focused-view ,view
,@body)
(progn ,@body)))
(defmacro with-fallback-font-view (view &body body)
`(if (null *current-font-view*)
(with-font-view ,view
,@body)
(progn ,@body)))
(defmacro! with-fallback-font-focused-view (o!view &body body)
`(with-fallback-font-view ,g!view
(with-fallback-focused-view ,g!view
,@body)))
(defmacro with-window-of-focused-view-fallback-fore-color (&body body)
`(with-window-fallback-fore-color (guard-!nil *current-focused-view*)
,@body))
(defmacro with-font-view-fallback-font (&body body)
`(let ((*current-graphics-context-font* (view-font (guard-!nil *current-font-view*))))
,@body))
(defmethod wptr ((view window))
(slot-boundp view 'easygui::ref))
(defmethod local-to-global ((win window) local-pos)
(let ((eg-point (add-points (view-position win) local-pos)))
eg-point))
(defmethod local-to-global ((view simple-view) local-pos)
(let* ((ns-converted-point (#/convertPoint:fromView:
(cocoa-ref (content-view (view-window view)))
(ns:make-ns-point (point-h local-pos) (point-v local-pos))
(cocoa-ref view))))
(let ((eg-point (easygui::point-from-ns-point ns-converted-point)))
eg-point)))
(defmethod part-color ((view view-text-mixin) (part (eql :text)))
(declare (ignore part))
(get-fore-color view))
(defmethod set-part-color ((view dialog-item) (part (eql :body)) new-color)
(set-back-color view new-color))
(defmethod set-part-color ((view dialog-item) (part (eql :text)) new-color)
(set-fore-color view new-color))
; FIXME: Keep this as a compiler warning until you figure out how to color a border with Cocoa
(defmethod set-part-color ((view dialog-item) (part (eql :frame)) new-color)
#-:sv-dev (declare (ignore new-color))
(setf (bordered-p view) t))
(defmethod get-fore-color ((view simple-view))
(easygui:get-fore-color view))
(defmethod get-back-color ((view view))
(easygui:get-back-color view))
(defmethod set-fore-color ((view simple-view) new-color)
(easygui:set-fore-color view new-color))
(defmethod set-back-color ((view simple-view) new-color)
(easygui:set-back-color view new-color))
; FIXME: What does this do? Keep as compiler warning until you figure it out
(defmethod window-update-cursor ((window window) point)
#-:sv-dev (declare (ignore point))
nil)
; Handling mouse movement/interaction
(defmethod easygui::mouse-down :after ((view simple-view) &key location &allow-other-keys)
(let ((win (guard-!nil
(guard-!null-ptr
(view-window view)))))
(let ((global-location (local-to-global view location)))
(view-click-event-handler view location)
(view-click-event-handler win global-location)
(post-view-click-event-handler win global-location))))
(defmethod post-view-click-event-handler ((view window) position)
(declare (ignore position))
(values))
(defmethod view-click-event-handler :around ((device simple-view) position)
(declare (ignore position))
(sv-log-n 1 "starting view-click-event-handler for ~a" device)
(unwind-protect (call-next-method)
(sv-log-n 1 "ending view-click-event-handler for ~a" device)))
(defmethod view-click-event-handler ((device simple-view) position)
(declare (ignore position))
; Default primary method is to do nothing
(values))
(objc:defmethod (#/reflectScrolledClipView: :void) ((self easygui::cocoa-scroll-view) (clip :ID))
(call-next-method clip)
(let ((view (easygui::easygui-view-of self)))
(view-scroll-event-handler view)
(let ((win (#/window self)))
(unless (ccl:%null-ptr-p win)
(let ((win (easygui::easygui-window-of win)))
(view-scroll-event-handler win)
(post-view-scroll-event-handler win))))))
(defmethod view-scroll-event-handler ((view simple-view))
())
(defmethod post-view-scroll-event-handler ((view simple-view))
())
(defmethod view-mouse-position ((view simple-view))
(easygui:view-mouse-position view :allow-negative-position-p t))
(defparameter *default-scroll-speed* 5)
(defun create-scroll-event (speed)
(let ((event
(#_CGEventCreateScrollWheelEvent
ccl:+null-ptr+
#$kCGScrollEventUnitLine
1
speed)))
event))
(defun scroll-mouse-up (&optional (speed *default-scroll-speed*))
(guard ((>= speed 0)))
(let ((event (create-scroll-event speed)))
(#_CGEventPost 0 event)
(#_CFRelease event)))
(defun scroll-mouse-down (&optional (speed *default-scroll-speed*))
(guard ((>= speed 0)))
(let ((event (create-scroll-event (* -1 speed))))
(#_CGEventPost 0 event)
(#_CFRelease event)))
(defun create-mouse-event (event pos)
(#_CGEventCreateMouseEvent
ccl:+null-ptr+
event
pos
0))
(defun left-mouse-up (pos)
(let ((event
(create-mouse-event #$NSLeftMouseUp pos)))
(sv-log-n 1 "posting mouse-up event ~a" event)
(#_CGEventPost 0 event)
(sv-log-n 1 "releasing mouse-up event ~a" event)
(#_CFRelease event)))
(defun left-mouse-down (pos)
(let ((event
(create-mouse-event #$NSLeftMouseDown pos)))
(sv-log-n 1 "posting mouse-down event ~a" event)
(#_CGEventPost 0 event)
(sv-log-n 1 "releasing mouse-down event ~a" event)
(#_CFRelease event)))
; It takes roughly 1 ms for an event to hit the application's run loop, so sleep for 50x
; longer than this, to make extra extra sure that the event has hit the run loop before returning.
(defun left-mouse-click (pos &optional (delay t))
(sv-log-n 1 "starting left mouse click")
(easygui::running-on-main-thread ()
(let ((pos (easygui::ns-point-from-point pos)))
(left-mouse-down pos)
(left-mouse-up pos)))
(sv-log-n 1 "sleeping so that mouse click enters nsrun loop")
(when delay (spin-for-fct 50))
(sv-log-n 1 "ending left mouse click"))
; Handling keyboard interaction
(defun create-keyboard-event (event key)
(let ((key (format nil "~a" key)))
(guard ((eq (length key) 1) "key: ~a is not a single character; not supporting command/control key events" key) ())
(let ((ret (#_CGEventCreateKeyboardEvent
ccl:+null-ptr+
0
event)))
(#_CGEventKeyboardSetUnicodeString
ret
(length key)
(#/cStringUsingEncoding: (objc:make-nsstring key) #$NSUTF8StringEncoding))
ret)))
(defun keypress-down (key)
(let ((event
(create-keyboard-event #$YES key)))
(sv-log-n 1 "posting keypress-down event ~a" event)
(#_CGEventPost 0 event)
(sv-log-n 1 "releasing keypress-down event ~a" event)
(#_CFRelease event)))
(defun keypress-up (key)
(let ((event
(create-keyboard-event #$NO key)))
(sv-log-n 1 "posting keypress-up event ~a" event)
(#_CGEventPost 0 event)
(sv-log-n 1 "releasing keypress-up event ~a" event)
(#_CFRelease event)))
; Same sleep time here.
(defun keypress (key &optional (delay t))
(sv-log-n 1 "starting keypress")
(easygui::running-on-main-thread ()
(keypress-down key)
(keypress-up key))
(sv-log-n 1 "sleeping so that keypress enters nsrun loop")
(when delay (spin-for-fct 50))
(sv-log-n 1 "ending keypress"))
; Relay keypress events in editable text views to the view and the window, after allowing the text field to handle the keypress properly.
; http://stackoverflow.com/questions/2484072/how-can-i-make-the-tab-key-move-focus-out-of-a-nstextview
(objc:defmethod (#/doCommandBySelector: :void) ((cocoa-self easygui::cocoa-text-view) (selector :<SEL>))
(unless (cond ((ccl::%ptr-eql selector (ccl::@selector #/insertTab:))
(select-next-key-view (easygui::easygui-view-of cocoa-self)))
((ccl::%ptr-eql selector (ccl::@selector #/insertBacktab:))
(select-prev-key-view (easygui::easygui-view-of cocoa-self))))
(call-next-method selector)))
(defmethod select-next-key-view ((view dialog-item))
(unless (allow-tabs view)
(select-next-key-view (view-window view))))
(defmethod select-next-key-view ((win window))
(unwind-protect t
(#/selectNextKeyView: (cocoa-ref win) ccl:+null-ptr+)))
(defmethod select-prev-key-view ((view dialog-item))
(unless (allow-tabs view)
(select-prev-key-view (view-window view))))
(defmethod select-prev-key-view ((win window))
(unwind-protect t
(#/selectPreviousKeyView: (cocoa-ref win) ccl:+null-ptr+)))
; http://superuser.com/questions/473143/how-to-tab-between-buttons-on-an-mac-os-x-dialog-box
; Tabbing does not cycle through buttons by default, but this can be changed in system preferences
; If this is changed and an NSButton becomes key, then (currently) the NSButton does not respond by pressing a tab.
; As a workaround subclass the #/keyDown: method and explicitly cycle through previous and next views if tab or backtab is pressed.
; I wouldn't think that you would need to explicitly write this method, but I can't find the setting/issue with the NSButtons
; to make this behavior default.
; I could not get #/setKeyEquivalent: to work for NSButtons, so as a workaround,
; explicitly call #/performClick: when the user presses the #\space key.
; This allows the user to navigate the UI by using the keyboard only, and also
; press buttons with the keyboard. The #\space as the action button seems to be
; the fairly consistent technique across OS X Cocoa apps and web-browser apps
(defparameter *view-of-keypress* nil)
(objc:defmethod (#/keyDown: :void) ((cocoa-self easygui::cocoa-button) the-event)
(let ((*view-of-keypress* (easygui::easygui-view-of cocoa-self)))
(unwind-protect (call-next-method the-event)
(let* ((str (objc:lisp-string-from-nsstring (#/charactersIgnoringModifiers the-event)))
(char (char str 0)))
(case char
(#\tab (select-next-key-view (easygui::easygui-view-of cocoa-self)))
(#\^Y (select-prev-key-view (easygui::easygui-view-of cocoa-self)))
(#\space (#/performClick: cocoa-self ccl:+null-ptr+)))))))
(objc:defmethod (#/keyDown: :void) ((cocoa-self easygui::cocoa-text-view) the-event)
(call-next-method the-event)
(handle-keypress-in-editable-text
(view-container
(easygui::easygui-view-of cocoa-self))
the-event))
(defmethod handle-keypress-in-editable-text ((view dialog-item) the-event)
(let ((*view-of-keypress* view))
(#/keyDown: (#/window (cocoa-ref view)) the-event)))
; #/keyDown: method on cocoa-window calls easygui::view-key-event-handler on the window (see views.lisp in easygui)
; The default first responder when the window is created is the reference to the window
; If the user presses the #\tab key, select the next key view in the responder loop
; This technique usually does the right thing, for instance, it will select the top-most
; editable text in the view after the first tab press
(defmethod easygui::view-key-event-handler :after ((device window) key)
(when (eq key #\tab)
(when (equal (cocoa-ref device) (#/firstResponder (cocoa-ref device)))
(select-next-key-view device)))
(when *view-of-keypress*
(view-key-event-handler *view-of-keypress* key))
(view-key-event-handler device key)
(post-view-key-event-handler device key))
(defmethod post-view-key-event-handler ((device window) key)
(declare (ignore key))
(values))
(defmethod view-key-event-handler :around ((device simple-view) key)
(declare (ignore key))
(sv-log-n 1 "starting view-key-event-handler")
(unwind-protect (call-next-method)
(sv-log-n 1 "ending view-key-event-handler")))
(defmethod view-key-event-handler ((device simple-view) key)
(declare (ignore key))
; Default primary method on the window is to do nothing
(values))
; MCL's Pen
(defclass pen-mixin ()
((pen-mode :accessor pen-mode)
(pen-size :accessor pen-size)
(pen-position :accessor pen-position :initform (make-point 0 0))
(pen-pattern :accessor pen-pattern)))
(defmethod initialize-instance :after ((view pen-mixin) &key)
(pen-normal view))
(defmethod set-pen-mode ((view simple-view) newmode)
(setf (pen-mode view) newmode))
(defmethod set-pen-pattern ((view simple-view) newpattern)
(setf (pen-pattern view) newpattern))
(defmethod set-pen-size ((view simple-view) h &optional v)
(destructuring-bind (h v) (canonicalize-point h v)
(setf (pen-size view) (make-point h v))))
(defmethod pen-normal ((view simple-view))
(setf (pen-mode view) :patCopy)
(setf (pen-size view) (make-point 1 1))
(setf (pen-pattern view) *black-pattern*))
; ----------------------------------------------------------------------
; Triggering MCL's view-draw-contents method on a Cocoa redraw of views.
;
; CCL's Objective C bridge provides an interface to define objective c
; methods. Use this to define a method that will be called any time
; an object on the screen needs to be redrawn. This will in turn call
; view-draw-contents in CCL, which means that the way to describe how an
; object is drawn in CCL is the same way that it is in MCL: Add a view-draw-contents
; method that dispatches on the object type, and code to draw that type of object
; to the display
; ----------------------------------------------------------------------
; Note that Cocoa focuses the view before calling #/drawRect, so there's no reason to have a
; with-focused-view inside of the lisp code. But in order for the with-fallback-focused-view stuff to
; work, it needs to know that a view is already focused. So just set the global var to the view
; in order to do this.
(objc:defmethod (#/drawRect: :void) ((self easygui::cocoa-drawing-view) (rect :<NSR>ect))
(let* ((view (easygui::easygui-view-of self))
(*current-focused-view* view))
(easygui::dcc
(view-draw-contents view))))
; Drawing methods
(defmacro with-rectangle-arg ((var left &optional top right bottom) &body body)
`(let ((,var (make-rect :from-mcl-spec ,left ,top ,right ,bottom)))
,@body))
(defmethod make-rect ((mode (eql :from-mcl-spec)) &rest args)
(destructuring-bind (left top right bottom) args
(destructuring-bind (left top right bottom) (canonicalize-rect left top right bottom)
(destructuring-bind (startx starty width height) (list left top (- right left) (- bottom top))
(ns:make-ns-rect startx starty width height)))))
(defun canonicalize-rect (left top right bottom)
(cond (bottom (list left top right bottom))
(top (list (point-h left)
(point-v left)
(point-h top)
(point-v top)))
(t (list (ns:ns-rect-x left)
(ns:ns-rect-y left)
(+ (ns:ns-rect-x left) (ns:ns-rect-width left))
(+ (ns:ns-rect-y left) (ns:ns-rect-height left))))))
(defmethod view-draw-contents ((view simple-view))
())
(defmethod get-start ((view liner))
(get-start-using-liner-type view (liner-type view)))
(defmethod get-end ((view liner))
(get-end-using-liner-type view (liner-type view)))
(defmethod get-start-using-liner-type ((view liner) (liner-type (eql 'bu)))
(make-point 0 (point-y (view-size view))))
(defmethod get-start-using-liner-type ((view liner) (liner-type (eql 'td)))
(make-point 0 0))
(defmethod get-end-using-liner-type ((view liner) (liner-type (eql 'bu)))
(make-point (point-x (view-size view)) 0))
(defmethod get-end-using-liner-type ((view liner) (liner-type (eql 'td)))
(view-size view))
(defmethod view-draw-contents ((view liner))
(move-to view (get-start view))
(with-fore-color (get-fore-color view)
(line-to view (get-end view))))
; Drawing commands on windows are directed to the window's content view.
; This is achieved by having with-focused-view focus on the window's content
; view (if it's a window), and also by specializing on the accessors that are
; used when drawing. The window's pen-position and bezier-path are never used;
; instead, those are directed to the content view of the window.
;
; Another approach would have been to write a specialized method for the window
; for each public drawing method, and have that method call the method with the
; same name on the window's content view, but this would require adding a
; window-specialized method for each public drawing method. So instead I looked
; at what accessors the public methods are using, and specialized on those, so that
; the necessary code changes for drawing to window's content view could be isolated
; in the few methods below. Adding/removing this functionality can be archived by
; adding/deleting the few methods here.
(defmethod pen-position ((view window))
(pen-position (content-view view)))
(defmethod (setf pen-position) (new (view window))
(setf (pen-position (content-view view)) new))
(defmethod bezier-path ((view window))
(bezier-path (content-view view)))
(defmethod (setf bezier-path) (new (view window))
(setf (bezier-path (content-view view)) new))
; Actual drawing methods
(defmethod move-to ((view simple-view) x &optional (y nil))
(with-fallback-focused-view view
(destructuring-bind (x y) (canonicalize-point x y)
(qd-move-to x y))))
(defmethod qd-move-to ((val1 (eql :long)) (val2 easygui::eg-point))
(destructuring-bind (endx endy) (as-list val2)
(qd-move-to endx endy)))
(defmethod qd-move-to ((x number) (y number))
(let ((view *current-focused-view*))
(unless (points-equal-p (pen-position view) (make-point x y))
(let ((position (make-point x y)))
(when (bezier-path view)
(#/moveToPoint: (bezier-path view) (ns:make-ns-point x y)))
(setf (pen-position view) position)))))
(defmethod line ((view simple-view) x &optional (y nil))
(with-fallback-focused-view view
(destructuring-bind (x y) (canonicalize-point x y)
(line-to view (add-points
(pen-position view)
(make-point x y))))))
(defmethod line-to ((view simple-view) x &optional (y nil))
(with-fallback-focused-view view
(destructuring-bind (endx endy) (canonicalize-point x y)
(qd-line-to endx endy))))
(defmethod qd-line-to ((val1 (eql :long)) (val2 easygui::eg-point))
(destructuring-bind (endx endy) (as-list val2)
(qd-line-to endx endy)))
(defmethod qd-line-to ((endx number) (endy number))
(let ((view *current-focused-view*))
(unless (points-equal-p (pen-position view) (make-point endx endy))
(destructuring-bind (startx starty) (list (point-x (pen-position view))
(point-y (pen-position view)))
(when (bezier-path view)
(#/lineToPoint: (bezier-path view) (ns:make-ns-point endx endy)))
(setf (pen-position view) (make-point endx endy))
(with-window-of-focused-view-fallback-fore-color
(#/strokeLineFromPoint:toPoint:
ns:ns-bezier-path
(ns:make-ns-point startx starty)
(ns:make-ns-point endx endy)))))))
(defmethod frame-oval ((view simple-view) left &optional top right bottom)
(let* ((rect (make-rect :from-mcl-spec left top right bottom))
(path (#/bezierPathWithOvalInRect: ns:ns-bezier-path rect)))
(with-fallback-focused-view view
(with-window-of-focused-view-fallback-fore-color
(#/stroke path)))))
(defmethod paint-oval ((view simple-view) left &optional top right bottom)
(with-fallback-focused-view view
(fill-oval view (pen-pattern view) left top right bottom)))
(defmethod fill-oval ((view simple-view) pattern left &optional top right bottom)
#-:sv-dev (declare (ignore pattern))
(let* ((rect (make-rect :from-mcl-spec left top right bottom)))
(with-fallback-focused-view view
(qd-paint-oval rect))))
(defmethod qd-paint-oval ((rect ns:ns-rect))
(let ((path (#/bezierPathWithOvalInRect: ns:ns-bezier-path rect)))
(with-window-of-focused-view-fallback-fore-color
(#/fill path))))
(defmethod frame-rect ((view simple-view) left &optional top right bottom)
(let* ((rect (make-rect :from-mcl-spec left top right bottom)))
(with-fallback-focused-view view
(qd-frame-rect rect))))
(defmethod qd-frame-rect ((rect ns:ns-rect))
(with-window-of-focused-view-fallback-fore-color
(#/strokeRect: ns:ns-bezier-path rect)))
(defmethod paint-rect ((view simple-view) left &optional top right bottom)
(with-fallback-focused-view view
(fill-rect view (pen-pattern view) left top right bottom)))
(defmethod fill-rect ((view simple-view) pattern left &optional top right bottom)
(with-fallback-focused-view view
(let* ((rect (make-rect :from-mcl-spec left top right bottom)))
(qd-paint-rect rect pattern))))
(defmethod qd-paint-rect ((rect ns:ns-rect) &optional pattern)
#-:sv-dev (declare (ignore pattern))
(with-window-of-focused-view-fallback-fore-color
(#/fillRect: ns:ns-bezier-path rect)))
(defmethod erase-rect ((view simple-view) left &optional top right bottom)
(let* ((rect (make-rect :from-mcl-spec left top right bottom)))
(with-fallback-focused-view view
(with-fore-color (get-back-color (content-view view))
(qd-paint-rect rect)))))
(defmethod start-polygon ((view simple-view))
(setf (bezier-path view) (#/bezierPath ns:ns-bezier-path))
(#/retain (bezier-path view))
(#/moveToPoint: (bezier-path view)
(easygui::ns-point-from-point (pen-position view))))
(defun pattern->system-color (pattern)
(color-symbol->system-color
(guard-!nil
(cond ((eq pattern *black-pattern*) 'black)))))
(defmethod paint-polygon ((view simple-view) polygon)
(with-fallback-focused-view view
(fill-polygon view (pen-pattern view) polygon)))
(defmethod erase-polygon ((view simple-view) polygon)
(with-fallback-focused-view view
(with-fore-color (get-back-color (content-view view))
(fill-polygon view (pen-pattern view) polygon))))
(defmethod fill-polygon ((view simple-view) pattern polygon)
#-:sv-dev (declare (ignore pattern))
(with-fallback-focused-view view
(with-window-of-focused-view-fallback-fore-color
(#/fill polygon))))
(defmethod frame-polygon ((view simple-view) polygon)
(with-fallback-focused-view view
(with-window-of-focused-view-fallback-fore-color
(#/stroke polygon))))
(defmethod kill-polygon ((polygon ns:ns-bezier-path))
(#/release polygon)
(setf polygon nil))
(defmethod get-polygon ((view simple-view))
(prog1 (bezier-path view)
(start-polygon view)))
; FIXME: Currently it's expected that a format call to a view is done only once per view-draw-contents. So write
; a single string to the view, etc. But CCL calls write-char when the string has a negative sign at the beginning.
; So the current workaround is to keep a dynamic variable around that keeps track of all of this, and throw in a few
; guard statements to make sure that things are being called in a way that won't break the formatting.
(defparameter *stream-prefix-char* nil)
(defmethod stream-write-char ((v simple-view) char)
(guard ((null *stream-prefix-char*) "expecting only a single prefix char before the string; prefix was ~a; new char is ~a" *stream-prefix-char* char) ())
(setf *stream-prefix-char* char))
(defun draw-string (string)
(with-window-of-focused-view-fallback-fore-color
(with-font-view-fallback-font
(let ((dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
*current-graphics-context-font* #$NSFontAttributeName
*current-graphics-context-stroke-color* #$NSForegroundColorAttributeName
ccl:+null-ptr+))
(pt (pen-position *current-focused-view*)))
(unwind-protect (#/drawAtPoint:withAttributes: string
(ns:make-ns-point
(point-h pt)
; To mimic MCL positioning, I had to subtract of the ascend pixels from the y position of the pen
(- (point-v pt)
(first (multiple-value-list (font-info *current-graphics-context-font*)))))
dict)
(setf *stream-prefix-char* nil))))))
(defmethod stream-write-string ((v simple-view) string &optional start end)
(with-fallback-font-focused-view v
(let* ((string
(objc:make-nsstring
(format nil "~a~a" (aif *stream-prefix-char* it "")
(if start
(subseq string start end)
string)))))
(draw-string string))))
; Handling fonts and string width/height in pixels
(defmethod view-font ((view easygui::content-view-mixin))
(view-font (content-view view)))
(defmethod view-font ((view simple-view))
(guard-!null-ptr
(guard-!nil
(easygui:view-font view))))
(defun font-info (font-spec)
(values (guard-!null-ptr (#/ascender font-spec))
(abs (guard-!null-ptr (#/descender font-spec)))))
(defun get-dict-for-font (font)
(#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
font #$NSFontAttributeName
ccl:+null-ptr+))
(defun string-width (str font)
(let* ((dict (get-dict-for-font font))
(attr (#/initWithString:attributes: (#/alloc ns:ns-attributed-string)
(objc:make-nsstring str)
dict))
(size (#/size attr)))
(ns:ns-size-width size)))
(defun font-point (font)
(#/pointSize font))
(defun font-name (font)
(objc:lisp-string-from-nsstring (#/fontName font)))
; Miscellaneous wrappers
; Provide the :quickdraw package on *modules*. Keeps from having to comment out the (require :quickdraw) lines in the MCL code.
; Also since the file here implements the quickdraw interface, it makes since to announce that the quickdraw library is available to use.
(provide :quickdraw)
; To implement event-dispatch for Clozure, send a dummy function over to
; the main Cocoa thread to be evaluated, and block until that function is
; processed. This guarantees that all current event code in the Cocoa run loop
; has been processed before event-dispatch returns.
(defun event-dispatch ()
(sv-log-n 1 "starting event dispatch")
(let ((time
(return-time-ms
(unless (eq ccl::*current-process* ccl::*initial-process*)
(dotimes (i 2)
(let ((sema (make-semaphore)))
(gui::queue-for-gui
(lambda ()
(signal-semaphore sema))
:at-start nil)
(wait-on-semaphore sema nil "semaphore event-dispatch wait")))))))
(sv-log-n 1 "ending event dispatch after ~,2f ms" time)))
(defparameter *current-dialog-directory* nil)
(defun get-directory-with-fallback (directory)
(setf *current-dialog-directory*
(acond (directory it)
(*current-dialog-directory* it)
(*load-truename* (directory-namestring it))
(t nil))))
; It turns out that objc functions are defined in the symbol table. So in order to set the title of
; the panel that is opened in the dialog, dynamically shadow the #/openPanel objc function.
; And in that shadowed function, call the original, and then set the title of the resulting panel to prompt
(defun make-panel-and-set-prompt (fun-orig prompt)
(lambda (&rest args)
(let ((panel (apply fun-orig args)))
(when prompt
(#/setTitle: panel (objc:make-nsstring prompt)))
panel)))
(ensure-defined
(defun choose-file-dialog (&key directory mac-file-type button-string prompt file)
(with-shadow (#/openPanel (make-panel-and-set-prompt fun-orig prompt))
(gui::cocoa-choose-file-dialog :directory (get-directory-with-fallback directory)
:file-types (aif mac-file-type (os-type->extensions it))
:file file
:button-string button-string))))
; FIXME: Write this
(defun os-type->extensions (os-type)
#-:sv-dev (declare (ignore os-type))
())
; And use the shadowing technique here.
(ensure-defined
(defun choose-new-file-dialog (&key directory mac-file-type button-string prompt file)
#-:sv-dev (declare (ignore button-string))
(with-shadow (#/savePanel (make-panel-and-set-prompt fun-orig prompt))
(gui::cocoa-choose-new-file-dialog :directory (get-directory-with-fallback directory)
:file-types (aif mac-file-type (os-type->extensions it))
:file file))))
; And here as well. Except in this case latch into the #/setTitle: method, since that is being used in the
; cocoa-choose-directory-dialog function.
(defun set-title-and-use-prompt (fun-orig prompt)
(lambda (panel string)
(funcall fun-orig
panel
(aif prompt
(objc:make-nsstring it)
string))))
(ensure-defined
(defun choose-directory-dialog (&key directory prompt)
(with-shadow (#/setTitle: (set-title-and-use-prompt fun-orig prompt))
(gui::cocoa-choose-directory-dialog :directory (get-directory-with-fallback directory)))))
(labels ((gen-dict-for-immutable-attr (bool)
(#/dictionaryWithObject:forKey: ns:ns-dictionary
(#/numberWithBool: ns:ns-number bool)
#$NSFileImmutable))
(set-immutable-attr (path bool)
(#/setAttributes:ofItemAtPath:error: (#/defaultManager ns:ns-file-manager)
(gen-dict-for-immutable-attr bool)
(objc:make-nsstring path)
ccl:+null-ptr+)))
(defun file-locked-p (path)
(let ((dict (guard-!null-ptr
(#/attributesOfItemAtPath:error: (#/defaultManager ns:ns-file-manager)
(objc:make-nsstring path)
ccl:+null-ptr+))))
(guard-t-or-nil
(#/boolValue
(#/objectForKey: dict (objc:make-nsstring "NSFileImmutable"))))))
(defun lock-file (path)
(let ((path (namestring path)))
(unless (file-locked-p path)
(guard-!nil
(set-immutable-attr path #$YES)))))
(defun unlock-file (path)
(let ((path (namestring path)))
(when (file-locked-p path)
(guard-!nil
(set-immutable-attr path #$NO))))))
; FIXME: Write this
(defun set-mac-file-creator (path mac-file-creator)
(declare (ignore path mac-file-creator))
t)
; FIXME: And maybe write this
(defun set-mac-file-type (path mac-file-type)
(declare (ignore path mac-file-type))
t)
(defparameter *current-cursor* *arrow-cursor*)
(defmethod set-cursor ((cursor ns:ns-cursor))
(unwind-protect (setf *current-cursor* cursor)
(awhen (front-window)
(sv-log "setting cursor for window ~a to ~a" it cursor)
(#/invalidateCursorRectsForView: (cocoa-ref it)
(cocoa-ref (content-view it))))))
(objc:defmethod (#/resetCursorRects :void) ((self easygui::cocoa-contained-view))
(call-next-method)
(#/addCursorRect:cursor: self
(#/bounds self)
*current-cursor*))
; Another option here is to call #/currentCursor on ns-cursor class, but since
; *current-cursor* is (currently) the current cursor for all windows of the application,
; just use this.
(defmethod window-cursor ((window window))
*current-cursor*)
(defmethod color ((cursor ns:ns-cursor))
(guard-!nil
(cond ((eq cursor *i-beam-cursor*) *black-color*)
((eq cursor *arrow-cursor*) *black-color*)
((eq cursor *crosshair-cursor*) *black-color*))))
(defmethod create-resource ((type (eql 'cursor)) id)
(make-instance
'resource
:alloc-fn
(lambda ()
(#/initWithImage:hotSpot: (#/alloc ns:ns-cursor)
(get-resource-val id 'image)
(#/hotSpot *arrow-cursor*)))))
(defmethod get-cursor :before (id)
(unless (resource-present-p id 'cursor)
(add-resource
(create-resource 'cursor id)
id)))
(defmethod get-cursor (id)
(get-resource-val id 'cursor))
(defun hide-cursor ()
(#_CGDisplayHideCursor
(#_CGMainDisplayID)))
(defun show-cursor ()
(#_CGDisplayShowCursor
(#_CGMainDisplayID)))
; Running on main GUI thread is required for the menubar functions. Otherwise Cocoa crashes fairly often when these are called.
(defun hide-menubar ()
(easygui::running-on-main-thread ()
(#/setPresentationOptions: (#/sharedApplication ns:ns-application)
(logior
#$NSApplicationPresentationHideDock
#$NSApplicationPresentationHideMenuBar))))
(defun show-menubar ()
(easygui::running-on-main-thread ()
(#/setPresentationOptions: (#/sharedApplication ns:ns-application)
#$NSApplicationPresentationDefault)))
(defun beep ()
(#_NSBeep))
; ----------------------------------------------------------------------
; Manipulate the read table so that MCL's #@(a b) make-point shorthand works.
;
; CCL does not support this by default, and the objective-c bridge uses #@ to make an NSString.
; So the #@ read macro defined below performs both tasks: If a list is passed, it
; will convert the points in the list to a point representation. If a string is
; passed, it will call the CCL default read function for #@
;
; Examples:
; #@"a string" -> #<NS-CONSTANT-STRING "hello"
; #@(5 4) -> #<EG-POINT (5.00/4.00)>)
; ----------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *nonhacked-readtable* (copy-readtable))
(set-dispatch-macro-character
#\# #\@
(defun |#@-reader| (stream char arg)
(let ((first-char (peek-char nil stream)))
(ecase first-char
(#\( (unless *read-suppress*
`(make-point ,@(read stream))))
(#\" (funcall (get-dispatch-macro-character #\# #\@ *nonhacked-readtable*)
stream char arg)))))))
; ----------------------------------------------------------------------
; Manipulate reader functionality so that references to foreign functions that no longer exist can
; be defined as native functions, while keeping the same access syntax
;
; I did not want to have to modify the source code in the Phaser task where all of these carbon foreign
; functions were used. CCL does not support the carbon framework, as far as I can tell. So in order to
; trick CCL into thinking that these foreign functions are defined, add a bit of a 'before' section of
; code to the load-external-function call. If the symbol name of the external function being loaded is
; in the list of function names that are being defined natively, then just return the symbol that maps
; to that function in the function symbol table. Otherwise, call the usual load-external-function function,
; and have CCL do the standard thing to try to find the foreign function
; ----------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *load-external-function-orig* #'ccl::load-external-function)
(with-continue
(defun ccl::load-external-function (sym query)
(let* ((fun-names (list "showmenubar" "hidemenubar" "getcursor" "showcursor" "ShowCursor" "hidecursor" "HideCursor"
"paintrect" "PaintRect" "framerect" "drawstring" "moveto" "MoveTo" "lineto" "PaintOval"))
(the-package (find-package :X86-Darwin64))
(fun-syms (mapcar (lambda (name)
(intern name the-package))
fun-names)))
(if (member sym fun-syms)
sym
(funcall *load-external-function-orig* sym query))))))
; Use the same approach to define foreign constants that MCL uses that no longer exist for CCL
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *load-os-constant-orig* #'ccl::load-os-constant)
(with-continue
(defun ccl::load-os-constant (sym &optional query)
(let* ((con-names (list "tejustleft" "tejustcenter" "tejustright" "crossCursor"))
(the-package (find-package :X86-Darwin64))
(con-syms (mapcar (lambda (name)
(intern name the-package))
con-names)))
(if (member sym con-syms)
sym
(funcall *load-os-constant-orig* sym query))))))
; All of the functions being natively defined are here
(defun X86-Darwin64::|showmenubar| ()
(show-menubar))
(defun X86-Darwin64::|hidemenubar| ()
(hide-menubar))
(defun X86-Darwin64::|getcursor| (id)
(get-cursor id))
(defun X86-Darwin64::|showcursor| ()
(show-cursor))
(defun X86-Darwin64::|ShowCursor| ()
(show-cursor))
(defun X86-Darwin64::|hidecursor| ()
(hide-cursor))
(defun X86-Darwin64::|HideCursor| ()
(hide-cursor))
(defun X86-Darwin64::|paintrect| (rect)
(qd-paint-rect rect))
(defun X86-Darwin64::|PaintRect| (rect)
(qd-paint-rect rect))
(defun X86-Darwin64::|framerect| (rect)
(qd-frame-rect rect))
(defun X86-Darwin64::|drawstring| (str)
(draw-string str))
(defun X86-Darwin64::|lineto| (x y)
(qd-line-to x y))
(defun X86-Darwin64::|moveto| (x y)
(qd-move-to x y))
(defun X86-Darwin64::|MoveTo| (x y)
(qd-move-to x y))
(defun X86-DARWIN64::|PaintOval| (rect)
(qd-paint-oval rect))
; And the constants are here
(defparameter X86-Darwin64::|tejustleft| $tejustleft)
(defparameter X86-Darwin64::|tejustcenter| $tejustcenter)
(defparameter X86-Darwin64::|tejustright| $tejustright)
(defparameter X86-Darwin64::|crossCursor| *crosshair-cursor*)
; ----------------------------------------------------------------------
; End file: actr6/devices/ccl/share.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: rmcl/level-1/l1-init.lisp
; ----------------------------------------------------------------------
(defparameter *menubar-bottom* 38) ;the location of the line under the menu bar.
(defparameter *modal-dialog-on-top* nil)
; ----------------------------------------------------------------------
; End file: rmcl/level-1/l1-init.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: rmcl/lib/color.lisp
; ----------------------------------------------------------------------
(defparameter *tool-back-color* 15658734)
; ----------------------------------------------------------------------
; End file: rmcl/lib/color.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: rmcl/lib/dialogs.lisp
; ----------------------------------------------------------------------
; FIXME: Is there any way not to use a global for this? The problem is that *modal-dialog-ret* is
; set on a different thread than the modal dialog thread, so the cleanest way that I've
; found to communicate between threads is to use a shared global
(defparameter *modal-dialog-ret* nil)
; Use #/abortModal and not #/stopModal
; https://groups.google.com/forum/#!msg/wx-commits-diffs/fB0pl10Kw90/jZtHXQkkVxEJ
(defun stop-modal ()
(#/abortModal (#/sharedApplication ns:ns-application))
)
; Form could be (values ...), which is why this is a macro. Don't eval form
; until it's wrapped in a multiple-value-list call
(defmacro return-from-modal-dialog (form)
`(progn
(sv-log "returning from modal dialog with form ~a" ',form)
(guard ((null *modal-dialog-ret*)
"modal dialog system on thread ~a in inconsistent state; about to set val; but it's already set as ~a"
*current-process*
*modal-dialog-ret*) ())
(setf *modal-dialog-ret* (cons :return (multiple-value-list ,form)))
(stop-modal)
(pop *modal-dialog-on-top*)
(values)))
(defmethod modal-dialog ((dialog window) &optional (close-on-exit t))
(push dialog *modal-dialog-on-top*)
(guard ((null *modal-dialog-ret*)
"modal dialog system on thread ~a in inconsistent state; val should be clear at this point, but it's set as ~a"
*current-process*
*modal-dialog-ret*) ())
(guard ((null *modal-dialog-ret*) "modal dialog system in inconsistent state; aborting"))
(#/runModalForWindow: (#/sharedApplication ns:ns-application) (cocoa-ref dialog))
(unwind-protect (apply #'values (cdr *modal-dialog-ret*))
(when close-on-exit
(window-close dialog))
(guard (*modal-dialog-ret* "modal dialog system in inconsistent state; ret should be nil but it's ~a; aborting" *modal-dialog-ret*))
(setf *modal-dialog-ret* nil)))
(defmethod find-subview-of-type ((view easygui::view) subview-type)
(dolist (sub (view-subviews view) nil)
(when (typep sub subview-type)
(return sub))))
; ----------------------------------------------------------------------
; End file: rmcl/lib/dialogs.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: rmcl/lib/ccl-menus.lisp
; ----------------------------------------------------------------------
(defun return-cancel (i)
(declare (ignore i))
(return-from-modal-dialog :cancel))
(defclass string-dialog (dialog)
((allow-empty-strings :initform nil :initarg :allow-empty-strings)))
(defclass get-string-dialog (string-dialog)())
(defmethod set-view-size ((dialog get-string-dialog) h &optional v)
(declare (ignore h v))
(let* ((old-size (view-size dialog)))
(call-next-method)
(let* ((new-size (view-size dialog))
(hdelta (make-point (- (point-h old-size)(point-h new-size)) 0))
(subs (view-subviews dialog))
(len (length subs)))
(dotimes (i len)
(let ((sub (elt subs i)))
(if (typep sub 'button-dialog-item)
(set-view-position sub (subtract-points (view-position sub) hdelta))
(if (typep sub 'editable-text-dialog-item)
(set-view-size sub (subtract-points (view-size sub) hdelta)))))))))
;; could be prettier, need a set-view-size method - move buttons, resize editable-text - done
; 140 x 80 is about minimum useful size - neg size is invisible
(with-continue
(defun get-string-from-user (message
&key
initial-string
(size #@(365 100))
(position '(:bottom 140))
(ok-text "OK")
(cancel-text "Cancel")
(modeless nil)
(window-title "")
(window-type :document-with-grow)
(back-color *tool-back-color*)
(allow-empty-strings nil)
(action-function #'identity)
cancel-function
(theme-background t)
&aux dialog (delta 0) (message-len 0) message-item)
(when (not initial-string) (setq initial-string ""))
(if t (setq delta 20)(setq delta 10))
(when message
(setq message-item (make-instance 'static-text-dialog-item
:text-truncation :end
:view-position (make-point 6 (- (point-v size) 54 delta))
:dialog-item-text message))
(let* ((msize (view-size message-item))
(mh (point-h msize))) ;; would be nice if static text had a truncate option -now it does
(setq mh (min mh (- (point-h size) 100)))
(set-view-size message-item (make-point mh (point-v msize))))
(setq message-len (+ 6 (point-h (view-size message-item)))))
(flet ((act-on-text (item)
(let ((e-item
(find-subview-of-type (view-container item)
'editable-text-dialog-item)))
(funcall action-function (dialog-item-text e-item)))))
(setq dialog (make-instance
'get-string-dialog
:view-position position
:view-size size
:close-box-p (if modeless t nil)
:grow-box-p t
:window-type window-type
:window-title window-title
:window-show nil
:back-color back-color
:theme-background theme-background
:allow-empty-strings allow-empty-strings
:view-subviews
(list
(make-dialog-item
'default-button-dialog-item
(make-point (- (point-h size) 74)
(- (point-v size) 20 delta))
#@(62 25)
ok-text
(if (not modeless)
#'(lambda (item)
(return-from-modal-dialog (act-on-text item)))
#'act-on-text))
(make-dialog-item 'button-dialog-item
(make-point (- (point-h size) 154)
(- (point-v size) 20 delta))
#@(70 25)
cancel-text
(or cancel-function
#'(lambda (item)
(if (not modeless)
(return-from-modal-dialog :cancel)
(window-close (view-window item)))))
:cancel-button t)
(make-dialog-item 'editable-text-dialog-item
(make-point (+ 6 message-len) (- (point-v size) 54 delta))
(make-point (- (point-h size) delta message-len) 23)
initial-string))))
(when message (add-subviews dialog message-item))
(update-default-button dialog)
(cond ((not modeless)
(modal-dialog dialog))
(t (window-show dialog)
dialog)))))
(defmethod update-default-button ((obj string-dialog)) ())
; need close box if modal nil
(defun message-dialog (message &key (ok-text "OK")
(size #@(335 100))
(modal t) ; if not modal its callers job to select
(title "Warning")
window-type
(on-ok-click
#'(lambda (item)
(declare (ignore item))
(return-from-modal-dialog t)))
(back-color *tool-back-color*)
(theme-background t)
(position (list :top (+ *menubar-bottom* 10))))
(let* ((message-width (- (point-h size) 85))
(new-dialog
(make-instance
'dialog
:view-position position
:view-size size
:window-title title
:window-type (or window-type (if modal :movable-dialog :document))
:close-box-p (if modal nil t)
:window-show nil
:back-color back-color
:theme-background theme-background
:view-subviews
`(,(make-instance
'static-text-dialog-item
:dialog-item-text message
:text-truncation #$NSLineBreakByWordWrapping
:view-size (make-point
message-width
(- (point-v size)
30)))
,@(if modal
(list (make-dialog-item
'default-button-dialog-item
(subtract-points size #@(75 35))
#@(62 25)
ok-text
on-ok-click)))))))
(if modal
(modal-dialog new-dialog)
new-dialog)))
(defclass select-dialog (window) ())
(with-continue
(defun select-item-from-list (the-list &key (window-title "Select an Item")
(selection-type :single)
table-print-function
(action-function #'identity)
(default-button-text "OK")
(sequence-item-class 'sequence-dialog-item)
(view-size (make-point 400 (+ 80 (* (length the-list) 20))))
(view-position '(:top 90) pos-p)
(theme-background t)
dialog-class
modeless
(help-spec 14086)
(list-spec 14087)
(button-spec 14088))
"Displays the elements of a list, and returns the item chosen by the user"
(let (debutton dialog)
(flet ((act-on-items (item)
(let ((s-item (find-subview-of-type (view-container item)
'sequence-dialog-item)))
(funcall action-function
(mapcar #'(lambda (c) (cell-contents s-item c))
(selected-cells s-item))))))
(when (and dialog-class (not pos-p) modeless)
(let ((w (front-window :class 'select-dialog))) ; or dialog-class?
(when w (setq view-position (add-points (view-position w) #@(15 15))))))
(setq debutton
(make-instance
'default-button-dialog-item
:dialog-item-text default-button-text
:dialog-item-enabled-p the-list
:help-spec button-spec
:dialog-item-action
(cond
((not modeless)
#'(lambda (item)
(return-from-modal-dialog (act-on-items item))))
(t
#'act-on-items ))))
(let* ((bsize (view-default-size debutton))
bpos)
(setq bsize (make-point (max 60 (point-h bsize)) (point-v bsize))
bpos (make-point (- (point-h view-size) 25 (point-h bsize))
(- (point-v view-size) 7 (point-v bsize))))
(set-view-size debutton bsize)
(set-view-position debutton bpos)
(setq dialog
(make-instance
(or dialog-class 'select-dialog)
:window-type :document-with-grow
:close-box-p (if modeless t nil)
:window-title window-title
:view-size view-size
:view-position view-position
:window-show nil ;modeless
:back-color *tool-back-color*
:theme-background theme-background
:help-spec help-spec
:view-subviews
(list*
(make-instance
sequence-item-class
:view-position #@(4 4)
:view-size (make-point (- (point-h view-size) 8)
(+ 50 (- (point-v view-size) (point-v bsize) 20)))
;:table-hscrollp nil
:table-sequence the-list
:table-print-function table-print-function
:selection-type selection-type
:help-spec list-spec)
debutton
(if (not modeless)
(list
(make-dialog-item 'button-dialog-item
(make-point (- (point-h bpos) 80)
(point-v bpos))
(make-point (if t #|(osx-p)|# 74 60) (point-v bsize))
"Cancel"
#'return-cancel
:cancel-button t
:help-spec 15012))
nil))))
;(when the-list (cell-select sdi (index-to-cell sdi 0))) ; let arrow-dialog-item do this
(cond (modeless ; select first then show is prettier
(window-show dialog)
dialog)
(t ;(#_changewindowattributes (wptr dialog) 0 #$kWindowCollapseBoxAttribute)
(modal-dialog dialog))))))))
; ----------------------------------------------------------------------
; End file: rmcl/lib/ccl-menus.lisp
; ----------------------------------------------------------------------
; ----------------------------------------------------------------------
; Begin file: build/post-code.lisp
; ----------------------------------------------------------------------
(provide "CCL-SIMPLE-VIEW")
; ----------------------------------------------------------------------
; End file: build/post-code.lisp
; ----------------------------------------------------------------------
| 167,035 | Common Lisp | .lisp | 3,239 | 45.011115 | 176 | 0.636296 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | dbd995dfa8632022ae407f8951310205997c12a8a5ea2e94aed43d5c1620424e | 14,214 | [
-1
] |
14,215 | single-threaded.lisp | asmaloney_ACT-R/support/single-threaded.lisp | ;;; -*- mode: LISP; Syntax: COMMON-LISP; Base: 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Author : Dan Bothell
;;; Copyright : (c) 2019 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 : single-threaded.lisp
;;; Version : 2.0
;;;
;;; Description : No-op all the lock actions.
;;;
;;; Bugs :
;;;
;;; To do :
;;;
;;; ----- History -----
;;; 2019.04.09 Dan
;;; : * Created this to provide a fast single threaded version.
;;; 2019.04.17 Dan
;;; : * Didn't add the acquire/release-recursive-lock functions.
;;; 2019.05.29 Dan [2.0]
;;; : * Actually define the packages and all the Quicklisp library
;;; : functions used in the code so I can skip Quicklisp for the
;;; : single-threaded version.
;;; 2019.05.30 Dan
;;; : * Remove the jsown package and stub.
;;; 2019.11.12 Dan
;;; : * The stubs for acquire-lock and acquire-recursive-lock need
;;; : to return t otherwise it looks like a failure.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; General Docs:
;;;
;;; Allows the ACT-R code to compile and run properly while ignoring all of the
;;; locking actions and other Quicklisp library code. This of course means that
;;; the code is no longer thread safe.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Public API:
;;;
;;; None.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Design Choices:
;;;
;;; Just make the lock based actions no-ops by redefining the functions and
;;; macros from the :bordeaux-threads package with dummies.
;;;
;;; Create dummy stubs for all the other functions referenced in the code.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Make sure not to start the dispatcher
(pushnew :standalone *features*)
;; define the packages which would come from Quicklisp loads
(defpackage :bordeaux-threads
(:nicknames :bt)
(:use :cl)
(:export
:make-lock
:acquire-lock
:release-lock
:with-lock-held
:make-recursive-lock
:acquire-recursive-lock
:release-recursive-lock
:with-recursive-lock-held
:make-condition-variable
:condition-notify
:condition-wait
:make-thread
:threadp
:thread-alive-p
:destroy-thread
:thread-yield))
(defpackage :usocket
(:use :cl)
(:export
:socket-stream
:socket-close
:socket-listen
:socket-accept
:ip=))
(defpackage :json
(:nicknames :cl-json)
(:use :cl)
(:export
:*lisp-identifier-name-to-json*
:encode-json-to-string
:decode-json-from-string
:decode-json-from-source))
;; In each one define dummy versions of the things used.
(in-package :json)
(defparameter +json-lisp-symbol-tokens+ nil)
(defvar *json-output* nil)
(defvar *lisp-identifier-name-to-json* nil)
(defun write-json-string (&rest x) (declare (ignore x)))
(defun encode-json-to-string (s &rest x) (declare (ignore x)) s)
(defun decode-json-from-string (s &rest x) (declare (ignore x)) s)
(defun decode-json-from-source (s &rest x) (declare (ignore s x)))
(defgeneric encode-json (object &optional stream))
(defmethod encode-json (x &optional s)
(declare (ignorable x s)))
(in-package :usocket)
(defun socket-stream (&rest x) (declare (ignore x)))
(defun socket-close (&rest x) (declare (ignore x)))
(defun socket-listen (&rest x) (declare (ignore x)))
(defun socket-accept (&rest x) (declare (ignore x)))
(defun ip= (&rest x) (declare (ignore x)))
(defun get-peer-port (&rest x) (declare (ignore x)))
(defun get-peer-address (&rest x) (declare (ignore x)))
(defun split-sequence (&rest x) (declare (ignore x)))
(defun get-hosts-by-name (&rest x) (declare (ignore x)))
(defun get-host-name (&rest x) (declare (ignore x)))
(defun vector-quad-to-dotted-quad (&rest x) (declare (ignore x)))
(defun usocket-p (&rest x) (declare (ignore x)))
(define-condition address-in-use-error () ())
(in-package :bordeaux-threads)
(defmacro with-lock-held ((place) &body body)
(declare (ignore place))
`(progn
,@body))
(defmacro with-recursive-lock-held ((place &key timeout) &body body)
(declare (ignore place timeout))
`(progn
,@body))
(defun make-lock (&optional x) (declare (ignore x)))
(defun make-recursive-lock (&optional x) (declare (ignore x)))
(defun acquire-lock (l &optional w) (declare (ignore l w)) t)
(defun release-lock (l) (declare (ignore l)))
(defun acquire-recursive-lock (l) (declare (ignore l)) t)
(defun release-recursive-lock (l) (declare (ignore l)))
(defun make-condition-variable (&rest x) (declare (ignore x)))
(defun condition-notify (&rest x) (declare (ignore x)))
(defun condition-wait (&rest x) (declare (ignore x)))
(defun make-thread (&rest x) (declare (ignore x)))
(defun threadp (&rest x) (declare (ignore x)))
(defun thread-alive-p (&rest x) (declare (ignore x)))
(defun destroy-thread (&rest x) (declare (ignore x)))
(defun thread-yield (&rest x) (declare (ignore x)))
;; Switch back to the original package for loading ACT-R
#+: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)
#|
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,725 | Common Lisp | .lisp | 167 | 37.08982 | 81 | 0.602374 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 375ad2ea00bb35c279a7fde548d269b95aafd7eaeefc4c77b967528580740cae | 14,215 | [
-1
] |
14,216 | pm-issues.lisp | asmaloney_ACT-R/tutorial/lisp/pm-issues.lisp | ; ACT-R tutorial unit 3 code for a simple task to
; investigate potential perceptual and motor issues
; with models.
(load-act-r-model "ACT-R:tutorial;unit3;perceptual-motor-issues-model.lisp")
(defvar *response* nil)
(defvar *response-time* nil)
(defun respond-to-key-press (model key)
(declare (ignore model))
(unless *response-time* (setf *response-time* (get-time)))
(push (string key) *response*))
(defun pm-issues-task (&optional which)
(reset)
(let* ((alphabet (list "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"))
(letter (first (permute-list alphabet)))
(task (if (or (string-equal which "next") (string-equal which "previous"))
which
(if (zerop (act-r-random 2)) "next" "previous")))
(time (+ 1500 (act-r-random 1000)))
(window (open-exp-window "Simple task")))
(push "z" alphabet)
(install-device window)
(add-act-r-command "pm-issues-response" 'respond-to-key-press
"Perceptual-motor issues task response")
(monitor-act-r-command "output-key" "pm-issues-response")
(add-text-to-exp-window window letter :x 130 :y 150)
(add-act-r-command "pm-issue-display" 'display-prompt
"Perceptual-motor issues task prompt display")
(schedule-event-relative time "pm-issue-display" :params (list window task) :time-in-ms t :output 'medium)
(setf *response* nil)
(setf *response-time* nil)
(run 10 t)
(remove-act-r-command "pm-issue-display")
(remove-act-r-command-monitor "output-key" "pm-issues-response")
(remove-act-r-command "pm-issues-response")
(list task (and (= (length *response*) 2)
(< time *response-time*)
(string-equal (car (last *response*)) letter)
(or (and (string-equal task "next") (search (reverse *response*) alphabet :test 'string-equal))
(and (string-equal task "previous") (search *response* alphabet :test 'string-equal)))
t))))
(defun display-prompt (window prompt)
(clear-exp-window)
(add-text-to-exp-window window prompt :x 125 :y 150))
| 2,356 | Common Lisp | .lisp | 45 | 41.688889 | 116 | 0.599372 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | cd9f7fafa4b339ce5e11cba94c1574e6e5ece092dc163883169c44fa43ccc9ce | 14,216 | [
-1
] |
14,217 | unit2.lisp | asmaloney_ACT-R/tutorial/lisp/unit2.lisp | ; ACT-R tutorial unit 2 assignment task.
; This experiment opens a window, displays 3 characters
; with two being the same and one different, waits for a
; keypress, and then reports whether the key that was
; pressed matches the different letter or not.
; Load the corresponding tutorial model
(load-act-r-model "ACT-R:tutorial;unit2;unit2-assignment-model.lisp")
; Create a variable to store the key that was pressed.
(defvar *response* nil)
; This is the function which we will have ACT-R call when
; a key is pressed in the experiment window which is signaled
; by the output-key action.
; That action provides two parameters to the function called.
; The first is the name of the model that performed the keypress
; or nil if it wasn't generated by a model, and the second
; is a string with the name of the key that was pressed.
(defun respond-to-key-press (model key)
(declare (ignore model))
; just store the key that was pressed in the response variable
(setf *response* key))
; This is the function that runs the experiment for either a
; person or a model. It has one optional parameter which if
; provided as a non-nil value will run a person.
; If it is not provided or nil is specified then it will run
; the model.
(defun unit2-experiment (&optional human)
; Reset the ACT-R system and any models that are defined to
; their initial states.
(reset)
; Create variable for the items needed to run the exeperiment:
; items - a randomized list of letter strings which is randomized
; using the ACT-R function permute_list
; target - the first string from the randomized list which will be the
; one that is different in the display
; foil - the second item from the list which will be displayed
; twice
; window - the ACT-R window device list returned by using the ACT-R
; function open-exp-window to create a new window for
; displaying the experiment
; text# - three text items that will hold the letters to be
; displayed all initialized to the foil letter to start
; index - a random value from 0-2 generated from the act-r-random
; function which is used to determine which of the three
; text variables will be set to the target
(let* ((items (permute-list '("B" "C" "D" "F" "G" "H" "J" "K" "L" "M" "N"
"P" "Q" "R" "S" "T" "V" "W" "X" "Y" "Z")))
(target (first items))
(foil (second items))
(window (open-exp-window "Letter difference"))
(text1 foil)
(text2 foil)
(text3 foil)
(index (act-r-random 3)))
; Set the randomly chosen item to be the target letter
(case index
(0 (setf text1 target))
(1 (setf text2 target))
(2 (setf text3 target)))
; display the three letters in the window
(add-text-to-exp-window window text1 :x 125 :y 75)
(add-text-to-exp-window window text2 :x 75 :y 175)
(add-text-to-exp-window window text3 :x 175 :y 175)
; Set the response value to nil to remove any value it may
; have from a previous run of the experiment.
(setf *response* nil)
; Create a command in ACT-R that corresponds to our respond-to-key-press
; function so that ACT-R is able to use the function.
(add-act-r-command "unit2-key-press" 'respond-to-key-press
"Assignment 2 task output-key monitor")
; Monitor the output-key action so that when an output-key happens
; our function is called.
(monitor-act-r-command "output-key" "unit2-key-press")
; Here is where we actually "run" the experiment.
; It either waits for a person to press a key or runs ACT-R
; for up to 10 seconds giving the model a chance to do the
; experiment.
(if human
; If a person is doing the task then for safety
; we make sure there is a visible window that they
; can use to do the task, and if so, loop until the
; response variable is not nil calling the ACT-R
; process-events function to allow the system a
; chance to handle any interactions.
(if (visible-virtuals-available?)
(while (null *response*)
(process-events)))
(progn
; If it is not a human then use install-device so that
; the features in the window will be seen by the model
; (that will also automatically provide the model with
; access to a virtual keyboard and mouse). Then use
; the ACT-R run function to run the model for up to 10
; seconds in real-time mode.
(install-device window)
(run 10 t)))
; To avoid any issues with our function for keypresses in this
; experiment interfering with other experiments we should stop
; monitoring output-key and then remove our command.
(remove-act-r-command-monitor "output-key" "unit2-key-press")
(remove-act-r-command "unit2-key-press")
; If the response matches the target return True otherwise
; return False.
(if (string-equal *response* target)
t
nil)))
| 5,275 | Common Lisp | .lisp | 105 | 43.390476 | 76 | 0.675617 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 5bb9bad57c4eb6de6b3180e1ab6626b7d418850c7b1027eebdd6f545289480b0 | 14,217 | [
-1
] |
14,218 | grouped.lisp | asmaloney_ACT-R/tutorial/lisp/grouped.lisp | ; ACT-R tutorial unit 5 grouped task.
; This is a simple example task to show partial matching.
; It simply runs the model and records values that the
; model provides and returns the list of provided values
; in the order provided after the run.
; Load the corresponding model for the task.
(load-act-r-model "ACT-R:tutorial;unit5;grouped-model.lisp")
; Create a varaiable to hold the values from the model
(defvar *response* nil)
; The recall function creates a command for
; the record-response function, clears the response
; list, runs the model, and returns the response list
; in the order provided by the model.
(defun grouped-recall ()
(add-act-r-command "grouped-response" 'record-response "Response recording function for the tutorial grouped model.")
(setf *response* nil)
(reset)
(run 20)
(remove-act-r-command "grouped-response")
(reverse *response*))
; Store a value provided by the model on the response list
(defun record-response (value)
(push value *response*))
| 1,003 | Common Lisp | .lisp | 23 | 41.652174 | 119 | 0.770576 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 61a15a966e086a3d7a2666beb63eb6232cbb8e66274dc726669a36f8c2fe55b1 | 14,218 | [
-1
] |
14,219 | remote-actr-connection.lisp | asmaloney_ACT-R/tutorial/lisp/remote-actr-connection.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 : dispatcher-client.lisp
;;; Version : 2.1
;;;
;;; Description : * Code to connect to the remote interface ACT-R and provide the
;;; : modeling commands necessary to run the remote tutorial model tasks.
;;;
;;; Bugs : *
;;;
;;; To do : * they're macros but they do result in evaluating the parameters.
;;;
;;; ----- History -----
;;; 2016.11.22 Dan
;;; : * To pass symbols back and forth for now going to use an object
;;; : in the JSON arrays of the form {"name":"<symbol-name>"}.
;;; : Adding modifications to the encoding and decoding to handle
;;; : that automatically.
;;; 2016.11.23 Dan
;;; : * Added a format function for printing the error messages so
;;; : that ACL and CCL will show all the details (may need to add
;;; : additional Lisps as well as needed).
;;; : * Added the cleaner encode-json symbol method which only does
;;; : the symbol->object when a variable is set.
;;; 2016.11.29 Dan
;;; : * The start-echoing-all-act-r-output command now makes sure
;;; : the client has the "echo" command set because if it has to
;;; : restart for some reason it won't still be there.
;;; 2016.12.01 Dan
;;; : * Don't attempt to do any fancy encoding/decoding for symbols
;;; : now -- let it use the default camel case stuff for decoding
;;; : because at this point the only thing converted to symbols
;;; : will be the object slot names which have fixed values.
;;; : However, the lisp symbol to string needs to not use the
;;; : camel case converter otherwise something like visual-location
;;; : gets converted to "visualLocation" which is bad...
;;; 2016.12.02 Dan
;;; : * Changed how the print-error-message function handles things
;;; : for ACL and CCL to just write the error message because
;;; : that seems to work better across different error/condition
;;; : types.
;;; 2016.12.09 Dan
;;; : * Use the new check method to determine if the remote-echo
;;; : command exists and whether or not this client owns it.
;;; 2017.01.23 Dan
;;; : * Add functions for the ACT-R commands which send the evaluate
;;; : action out and then parse the return results based on success.
;;; 2017.01.24 Dan
;;; : * Echo the output by default.
;;; 2017.01.25 Dan
;;; : * Added act-r-random and print-visicon functions.
;;; 2017.01.30 Dan
;;; : * Permute-list actually permutes the indices and then creates
;;; : a new list using those because the list itself could contain
;;; : Lisp objects that can't be passed through the JSON serializer.
;;; 2017.02.02 Dan
;;; : * Added the run-full-time function.
;;; 2017.02.03 Dan
;;; : * Added penable and pdisable.
;;; 2017.02.06 Dan
;;; : * Fixed goal-focus because it didn't need to be applied.
;;; 2017.02.07 Dan
;;; : * Added buffer-read and clear-buffer.
;;; 2017.02.08 Dan
;;; : * Better catch errors with encoding a result so that it still
;;; : sends the message with an error notice.
;;; : * Change the output monitor since it's now a simple monitor.
;;; : * Added define-chunks, pprint-chunks, chunk-slot-value, mod-focus,
;;; : mod-chunk, and set-chunk-slot-value commands.
;;; 2017.02.09 Dan
;;; : * Added set-buffer-chunk and add-line-to-exp-window.
;;; 2017.02.15 Dan
;;; : * For the remote functions that differentate a macro from a
;;; : function in the ACT-R code, include a -fct version which
;;; : takes the same form as the real -fct.
;;; : * Added chunk-p and chunk-p-fct.
;;; : * Added extend-possible-slots.
;;; : * Added add-dm.
;;; 2017.02.16 Dan
;;; : * Added add-dm-fct.
;;; : * Evaluate incoming commands in separate threads because otherwise
;;; : there's a nasty deadlock if a command results in calling other
;;; : commands in this client (which can easily happen for something like
;;; : an ACT-R warning being printed during evaluation of a command).
;;; : * Added model-output.
;;; 2017.02.22 Dan
;;; : * Added the schedule-simple-event and schedule-simple-event-relative
;;; : commands.
;;; 2017.02.23 Dan
;;; : * Added whynot-dm and whynot-dm-fct commands.
;;; : * Added mp-show-queue command.
;;; : * Added print-dm-finsts.
;;; 2017.02.24 Dan
;;; : * Added run-until-condition.
;;; 2017.03.10 Dan
;;; : * Added start-hand-at-mouse, modify-line-for-exp-window,
;;; : add-button-to-exp-window, remove-items-from-exp-window.
;;; : * Fixed a bug with sending requests because the incf of the
;;; : id value wasn't protected by a lock.
;;; 2017.03.13 Dan
;;; : * Added an spp command.
;;; : * Added no-output and hide-output macros along with the underlying
;;; : start-echoing-act-r-output/stop-echoing-act-r-output and
;;; : show-act-r-output/hide-act-r-output pairs.
;;; : * Added a copy-chunk and copy-chunk-fct.
;;; 2017.03.14 Dan
;;; : * Have the remote spp-fct not use apply so things are taken out
;;; : of the list so the dispatcher's one collects them again...
;;; : * Added encode-keyword-names because the default encoding will
;;; : strip the : off in what it sends which isn't good for something
;;; : like spp.
;;; 2017.04.06 Dan [1.1]
;;; : * The only method that comes over now is evaluate and its
;;; : first two parameters are the command name and the model name,
;;; : and when sending an evaluate the second parameter needs to be
;;; : a model name or nil.
;;; 2017.07.12 Dan
;;; : * Adding the while macro so it'll work in other than ACL.
;;; 2017.07.13 Dan
;;; : * Added the general-output trace monitoring and the act-r-output
;;; : command.
;;; 2017.12.05 Dan
;;; : * Updated with more of the remote commands.
;;; : * Added the check for quicklisp instead of always trying to
;;; : load the setup file.
;;; : * Fixed some things that should be macros to line up with the
;;; : server so that the tutorial tasks can be run from the client.
;;; : * Convert string return values back to symbols for everything.
;;; 2017.12.06 Dan
;;; : * Added the chunk-spec related commands.
;;; 2017.12.18 Dan
;;; : * Added mp-time and mp-time-ms.
;;; 2018.03.14 Dan
;;; : * Use get-new-command-name to set the echo command's name.
;;; 2019.05.21 Dan [2.0]
;;; : * Read the connection values from the files in the ~ directory.
;;; : * Send the set-name call to be "Remote Lisp connection".
;;; 2019.05.22 Dan
;;; : * Starting to update this so it can run all of the current
;;; : tutorial models.
;;; : That means the ACT-R macros really need to be macros since
;;; : the .lisp files don't use strings when referring to names.
;;; 2019.06.20 Dan [2.1]
;;; : * Add include/exclude -model-trace functions to control
;;; : whether that's echoed. By default all echoed, but for the
;;; : standalone it will exclude-model-trace.
;;; : * Fixed a typo with first attempt...
;;; 2019.06.27 Dan
;;; : * Don't reload the libraries if it's the standalone since
;;; : they're already in the image.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#-:QUICKLISP (eval-when (:compile-toplevel :load-toplevel :execute)
(unless (find :standalone *features*)
(when (probe-file "~/quicklisp/setup.lisp")
(load "~/quicklisp/setup.lisp"))
(unless (find :quicklisp *features*)
(error "This version of ACT-R requires Quicklisp to load the components necessary for the remote connection."))))
#-:standalone (ql:quickload :bordeaux-threads)
#-:standalone (ql:quickload :usocket)
#-:standalone (ql:quickload :cl-json)
(defparameter *default-package* *package*)
(defvar *dispatcher*)
;;; push-last
;;;
;;; (defmacro push-last (item place)
;;;
;;; item anything
;;; place a Lisp place
;;;
;;; push-last postpends item to the list that is stored in place and stores the
;;; resulting list in place.
;;;
;;; returns place.
;;;
(define-modify-macro act-r_nconcf (&rest args) nconc)
(defmacro push-last (item place)
`(act-r_nconcf ,place (list ,item)))
#-(or :allegro-ide (and :allegro-version>= (version>= 6)))
(defmacro while (test &body body)
`(do ()
((not ,test))
,@body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ACL and CCL don't seem to print the text provided in an error
;;; call normally so create a special format function so that the
;;; created error strings can be more informative.
#-(or :acl :ccl) (defun cl-user::print-error-message (stream error colon-p atsign-p &optional (width 0) padchar commachar)
(declare (ignore colon-p atsign-p width padchar commachar))
(format stream "~s" error))
#+(or :acl :ccl) (defun cl-user::print-error-message (stream error colon-p atsign-p &optional (width 0) padchar commachar)
(declare (ignore colon-p atsign-p width padchar commachar))
(format stream "#<~a " (type-of error))
(write error :stream stream :escape nil)
(format stream ">"))
(defun decode-string (s)
(if (stringp s)
(if (char= #\' (char s 0) (char s (1- (length s))))
(subseq s 1 (1- (length s)))
(string->name s))
s))
(defun string->name (s)
(if (stringp s)
(if (eq (char s 0) #\:)
(intern (string-upcase (subseq s 1)) :keyword)
(let ((n (ignore-errors (read-from-string s))))
(if (numberp n)
n
(intern (string-upcase s)))))
s))
(defun string->name-recursive (s)
(if (stringp s)
(if (eq (char s 0) #\:)
(intern (string-upcase (subseq s 1)) :keyword)
(let ((n (ignore-errors (read-from-string s))))
(if (numberp n)
n
(intern (string-upcase s)))))
(if (listp s)
(mapcar 'string->name-recursive s)
s)))
(setf json:*lisp-identifier-name-to-json* 'identity)
;;; Client side connection
;;; Basically the same setup as server, but here the command table is referenced directly
;;; when an evaluate method is received.
(defstruct client-dispatcher
(action-lock (bt:make-lock "client-action-lock"))
(action-cv (bt:make-condition-variable :name "client-cv"))
(stream-lock (bt:make-lock "stream-lock"))
stream
socket
(command-lock (bt:make-lock "dispatcher-command-lock"))
(command-table (make-hash-table :test 'equalp))
action-list
action-thread
input-thread
(requests-lock (bt:make-lock "dispatcher-requests-lock"))
pending-requests
(id-lock (bt:make-lock "dispatcher-id-lock"))
(id 0))
(defstruct client-action name parameters id model)
(defstruct client-request (lock (bt:make-lock)) (cv (bt:make-condition-variable)) id success result complete)
(defun add-client-command (name function)
(handler-case
(progn
(unless (and (stringp name)
(or (functionp function)
(and (symbolp function)
(fboundp function))))
(progn
(format *error-output* "Invalid parameters when trying to add commmand ~s for function ~s" name function)
(return-from add-client-command nil)))
(bt:with-lock-held ((client-dispatcher-command-lock *dispatcher*))
(if (gethash name (client-dispatcher-command-table *dispatcher*))
(format *error-output* "~s already names a command in the table" name)
(setf (gethash name (client-dispatcher-command-table *dispatcher*)) function))))
((or error condition) (x)
(format *error-output* "Error ~/print-error-message/ occurred while trying to add command ~s" x name))))
(defvar *current-act-r-model* nil)
(defun send-command-to-act-r (command-name &rest parameters)
(if (stringp command-name)
(let ((p (make-client-request)))
(bt:with-lock-held ((client-dispatcher-id-lock *dispatcher*))
(setf (client-request-id p) (incf (client-dispatcher-id *dispatcher*)))
(push p (client-dispatcher-pending-requests *dispatcher*)))
(bt:acquire-lock (client-request-lock p))
(handler-case
(progn
(bt:with-lock-held ((client-dispatcher-stream-lock *dispatcher*))
(format (client-dispatcher-stream *dispatcher*) "{\"method\": ~s, \"params\": ~a, \"id\": ~d}~c" command-name
(json:encode-json-to-string parameters) (client-request-id p) (code-char 4))
(force-output (client-dispatcher-stream *dispatcher*)))
(loop
(when (client-request-complete p)
(bt:with-lock-held ((client-dispatcher-requests-lock *dispatcher*))
(setf (client-dispatcher-pending-requests *dispatcher*) (remove p (client-dispatcher-pending-requests *dispatcher*))))
(return-from send-command-to-act-r (values-list (append (list (client-request-success p)) (if (listp (client-request-result p))
(client-request-result p)
(list (client-request-result p)))))))
(bt:condition-wait (client-request-cv p) (client-request-lock p))))
(error (x)
(format *error-output* "Error ~/print-error-message/ while trying to send command." x))))
(values nil (format nil "Command-name for send-command-to-act-r must be a string but given ~s" command-name))))
(defun evaluate-act-r-command (&rest parameters)
(let ((result (multiple-value-list (apply 'send-command-to-act-r "evaluate" (cons (first parameters) (cons *current-act-r-model* (cdr parameters)))))))
(if (first result)
(values-list (mapcar 'string->name-recursive (rest result)))
(dolist (x (rest result) nil)
(format *error-output* x)))))
(defun evaluate-act-r-command-decoded (&rest parameters)
(let ((result (multiple-value-list (apply 'send-command-to-act-r "evaluate" (cons (first parameters) (cons *current-act-r-model* (cdr parameters)))))))
(if (first result)
(values-list (mapcar 'decode-string-names (rest result)))
(dolist (x (rest result) nil)
(format *error-output* x)))))
(defun start-des-client (&optional (host "127.0.0.1") (remote-port 2650))
(let ((socket (handler-case (usocket:socket-connect host remote-port :nodelay :if-supported)
(error (x) (progn
(format *error-output* "Error ~/print-error-message/ occurred while trying to open a socket connection to host ~s port ~s" x host remote-port)
nil)))))
(if socket
(let* ((dispatcher
(make-client-dispatcher
:socket socket
:stream (usocket:socket-stream socket))))
(setf *dispatcher* dispatcher)
(setf (client-dispatcher-input-thread dispatcher)
(bt:make-thread (lambda ()
(let ((*package* *default-package*))
(unwind-protect
(process-client-input dispatcher)
(progn
;; Things we've received and not initiated should just be removed
(bt:with-lock-held ((client-dispatcher-action-lock dispatcher))
(setf (client-dispatcher-action-list dispatcher) nil))
;; things we've sent but haven't received need to return an error result
(dolist (x (client-dispatcher-pending-requests dispatcher))
(bt:with-lock-held ((client-request-lock x))
(setf (client-request-success x) nil)
(setf (client-request-result x) "Connection terminated")
(setf (client-request-complete x) t))
(bt:condition-notify (client-request-cv x)))
(ignore-errors (usocket:socket-close (client-dispatcher-socket dispatcher)))))))))
(setf (client-dispatcher-action-thread dispatcher)
(bt:make-thread (lambda ()
(let ((*package* *default-package*))
(dispatcher-process-client-actions dispatcher)))))
t)
nil)))
(defun process-action-thread (dispatcher command a)
(let ((result (if command
(multiple-value-list (handler-case
(values-list (cons t (let ((*current-act-r-model* (client-action-model a)))(multiple-value-list (apply command (client-action-parameters a))))))
(error (e) (let ((m (format nil "Error ~/print-error-message/ while applying ~s to ~s." e (client-action-name a) (client-action-parameters a))))
(format *error-output* m)
(values nil m)))
(condition (c) (let ((m (format nil "Condition ~/print-error-message/ while applying ~s to ~s." c (client-action-name a) (client-action-parameters a))))
(format *error-output* m)
(values nil m)))))
(list nil "Invalid command name"))))
(when (client-action-id a)
(let* ((success (car result))
(res (handler-case
(json:encode-json-to-string (cdr result))
(error ()
(format nil "Unable to encode return result ~s in JSON" (cdr result))
(setf success nil))))
(json-result (if success
(format nil "{\"result\": ~a, \"error\": null, \"id\": ~s}~c" res (client-action-id a) (code-char 4))
(format nil "{\"result\": null, \"error\": {\"message\": ~a}, \"id\": ~s}~c" res (client-action-id a) (code-char 4)))))
(handler-case
(bt:with-lock-held ((client-dispatcher-stream-lock dispatcher))
(format (client-dispatcher-stream dispatcher) json-result)
(force-output (client-dispatcher-stream dispatcher)))
((or error condition) (x)
(format *error-output* "Error ~/print-error-message/ while trying to return results of evaluating a command." x)))))))
(defun dispatcher-process-client-actions (dispatcher)
(bt:acquire-lock (client-dispatcher-action-lock dispatcher) t)
(loop
(dolist (a (client-dispatcher-action-list dispatcher))
(let ((action a)
(command (bt:with-lock-held ((client-dispatcher-command-lock dispatcher))
(gethash (client-action-name a) (client-dispatcher-command-table dispatcher)))))
(bt:make-thread (lambda ()
(process-action-thread dispatcher command action)))))
(setf (client-dispatcher-action-list dispatcher) nil)
(bt:condition-wait (client-dispatcher-action-cv dispatcher) (client-dispatcher-action-lock dispatcher))))
(defun process-client-input (dispatcher)
(handler-case
(let ((s (make-array 40
:element-type 'character
:adjustable T
:fill-pointer 0)))
(loop
(let ((char (read-char (client-dispatcher-stream dispatcher) nil :done)))
(cond ((eq char :done)
(format *error-output* "External connection closed.")
(return))
((eq (char-code char) 4)
(let ((message (handler-case (json:decode-json-from-string s)
((or error condition) (x)
(format *error-output* "Problem encountered decoding JSON string ~s: ~/print-error-message/. Connection terminated" s x)
(return-from process-client-input nil)))))
(cond ((and (= (length message) 3)
(assoc :method message)
(assoc :params message)
(assoc :id message)
(string-equal (cdr (assoc :method message)) "evaluate"))
(let* ((params (cdr (assoc :params message)))
(action (make-client-action :name (first params) :model (second params) :parameters (cddr params) :id (cdr (assoc :id message)))))
(bt:with-lock-held ((client-dispatcher-action-lock dispatcher))
(push-last action (client-dispatcher-action-list dispatcher)))
(bt:condition-notify (client-dispatcher-action-cv dispatcher))))
((and (= (length message) 3)
(assoc :result message)
(assoc :error message)
(assoc :id message))
(let ((id (cdr (assoc :id message)))
(result (cdr (assoc :result message)))
(error (cdr (assoc :error message))))
(let (p)
(bt:with-lock-held ((client-dispatcher-requests-lock dispatcher))
(setf p (find id (client-dispatcher-pending-requests dispatcher) :key 'client-request-id :test 'equalp))
(when p (setf (client-dispatcher-pending-requests dispatcher) (remove p (client-dispatcher-pending-requests dispatcher)))))
(if p
(progn
(bt:with-lock-held ((client-request-lock p))
(setf (client-request-success p) (if result t nil))
(setf (client-request-result p) (if result result (let ((messages (cdr (assoc :message error))))
(if messages
messages
(list "No error messages received.")))))
(setf (client-request-complete p) t))
(bt:condition-notify (client-request-cv p)))
(progn
(format *error-output* "Returned result has an id that does not match a pending request ~s" s)
(return-from process-client-input nil))))))
(t
(format *error-output* "Invalid message received ~s terminating connection" s)
(return-from process-client-input nil))))
(setf (fill-pointer s) 0))
(t (vector-push-extend char s))))))
((or error condition) (x)
(usocket:socket-close (client-dispatcher-socket dispatcher))
(format *error-output* "Error ~/print-error-message/ occurred in process-client-input. Connection terminated." x))))
;; Read the ACT-R configuration files for the connection information
(defvar *address* (ignore-errors (with-open-file (f (translate-logical-pathname "~/act-r-address.txt") :direction :input)
(read-line f))))
(defvar *port* (ignore-errors (with-open-file (f (translate-logical-pathname "~/act-r-port-num.txt") :direction :input)
(read f))))
(start-des-client *address* *port*)
(send-command-to-act-r "set-name" "Remote Lisp connection")
(defvar *current-stream* nil)
(defvar *trace-command-name* nil)
(defvar *include-model-trace* t)
(defun exclude-model-trace ()
(when *include-model-trace*
(setf *include-model-trace* nil)
(when *trace-command-name*
(send-command-to-act-r "remove-monitor" "model-trace" *trace-command-name*))))
(defun include-model-trace ()
(unless *include-model-trace*
(setf *include-model-trace* t)
(when *trace-command-name*
(send-command-to-act-r "monitor" "model-trace" *trace-command-name*))))
(defun echo-trace-stream (string)
(format *current-stream* string))
(add-client-command "echo" 'echo-trace-stream)
(defun start-echoing-act-r-output ()
(setf *current-stream* *standard-output*)
(if *trace-command-name*
(format *error-output* "ACT-R output is already being displayed.")
(let ((name (evaluate-act-r-command "get-new-command-name" "remote-echo")))
(unless (gethash "echo" (client-dispatcher-command-table *dispatcher*))
(add-client-command "echo" 'echo-trace-stream))
(if name
(progn
(setf *trace-command-name* name)
(send-command-to-act-r "add" *trace-command-name* "echo")
(send-command-to-act-r "monitor" "model-trace" *trace-command-name*)
(send-command-to-act-r "monitor" "command-trace" *trace-command-name*)
(send-command-to-act-r "monitor" "warning-trace" *trace-command-name*)
(send-command-to-act-r "monitor" "general-trace" *trace-command-name*)
t)
(progn
(setf *trace-command-name* nil)
(format *error-output* "Could not get ACT-R command information and cannot echo trace.")
nil)))))
(defun stop-echoing-act-r-output ()
(setf *current-stream* nil)
(if *trace-command-name*
(progn
(send-command-to-act-r "remove-monitor" "model-trace" *trace-command-name*)
(send-command-to-act-r "remove-monitor" "command-trace" *trace-command-name*)
(send-command-to-act-r "remove-monitor" "warning-trace" *trace-command-name*)
(send-command-to-act-r "remove-monitor" "general-trace" *trace-command-name*)
(send-command-to-act-r "remove" *trace-command-name*)
(setf *trace-command-name* nil)
t)
(format *error-output* "ACT-R trace not currently being echoed so it cannot be stopped.")))
(defun hide-act-r-output ()
(if *current-stream*
(progn
(setf *current-stream* nil)
t)
(format *error-output* "ACT-R output already being hidden.")))
(defun show-act-r-output ()
(if *current-stream*
(format *error-output* "ACT-R output is not currently hidden.")
(progn
(setf *current-stream* *standard-output*)
t)))
;;; Macros to handle turning off/hiding output
(defmacro no-output (&body commands)
`(unwind-protect
(progn
(stop-echoing-act-r-output)
,@commands)
(start-echoing-act-r-output)))
(defmacro hide-output (&body commands)
`(unwind-protect
(progn
(hide-act-r-output)
,@commands)
(show-act-r-output)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Echo the output by default
(start-echoing-act-r-output)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Anything that needs to pass keywords has to be in a string first because the
;;; default JSON encoding will mess that up e.g. (spp :u) wouldn't work as-is.
;;; So, for commands where that's important, like spp, do a quick re-encoding
;;; to convert keywords to strings (leave everything else alone).
(defun encode-keyword-names (sn)
(cond ((keywordp sn)
(write-to-string sn))
((listp sn)
(mapcar 'encode-keyword-names sn))
(t
sn)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Add functions for the ACT-R commands instead of always calling evaluate.
(defun current-model ()
(if *current-act-r-model*
*current-act-r-model*
(evaluate-act-r-command "current-model")))
(defun set-current-model (name)
(let ((models (evaluate-act-r-command "mp-models")))
(if (find name models :test 'string-equal)
(setf *current-act-r-model* name)
(format t "~s is not one of the currently available models: ~s~%" name models))))
(defun reset ()
(evaluate-act-r-command "reset"))
(defun reload (&optional compile)
(evaluate-act-r-command "reload" compile))
(defun run (time &optional real-time)
(evaluate-act-r-command "run" time real-time))
(defun run-full-time (time &optional real-time)
(evaluate-act-r-command "run-full-time" time real-time))
(defun run-until-time (time &optional real-time)
(evaluate-act-r-command "run-until-time" time real-time))
(defun run-n-events (count &optional real-time)
(evaluate-act-r-command "run-n-events" count real-time))
(defun run-until-condition (condition &optional real-time)
(evaluate-act-r-command "run-until-condition" condition real-time))
(defmacro buffer-chunk (&rest buffers)
`(apply 'evaluate-act-r-command "buffer-chunk" ',buffers))
(defun buffer-chunk-fct (buffers)
(apply 'evaluate-act-r-command "buffer-chunk" buffers))
(defmacro whynot (&rest productions)
`(apply 'evaluate-act-r-command "whynot" ',productions))
(defun whynot-fct (productions)
(apply 'evaluate-act-r-command "whynot" productions))
(defmacro whynot-dm (&rest chunks)
`(apply 'evaluate-act-r-command "whynot-dm" ',chunks))
(defun whynot-dm-fct (chunks)
(apply 'evaluate-act-r-command "whynot-dm" chunks))
(defmacro penable (&rest productions)
`(apply 'evaluate-act-r-command "penable" ',productions))
(defun penable-fct (productions)
(apply 'evaluate-act-r-command "penable" productions))
(defmacro pdisable (&rest productions)
`(apply 'evaluate-act-r-command "pdisable" ',productions))
(defun pdisable-fct (productions)
(apply 'evaluate-act-r-command "pdisable" productions))
(defun load-act-r-model (file-name)
(evaluate-act-r-command "load-act-r-model" file-name))
(defun load-act-r-code (file-name)
(evaluate-act-r-command "load-act-r-code" file-name))
(defmacro goal-focus (&optional chunk-name)
`(evaluate-act-r-command "goal-focus" ',chunk-name))
(defun goal-focus-fct (&optional chunk-name)
(evaluate-act-r-command "goal-focus" chunk-name))
(defun clear-exp-window (&optional window)
(evaluate-act-r-command "clear-exp-window" window))
(defun permute-list (list)
(let ((indexes (make-list (length list)))
(result (make-list (length list))))
(dotimes (i (length list))
(setf (nth i indexes) i))
(let ((new-indexes (evaluate-act-r-command "permute-list" indexes)))
(dotimes (i (length list))
(setf (nth i result) (nth (nth i new-indexes) list))))
result))
(defun open-exp-window (title &key (visible t) (width 300) (height 300) (x 300) (y 300))
(evaluate-act-r-command "open-exp-window" title (list (list "visible" visible)
(list "width" width)
(list "height" height)
(list "x" x)
(list "y" y))))
(defun add-text-to-exp-window (window text &key (x 0) (y 0) (color 'black) (height 20) (width 75) (font-size 12))
(evaluate-act-r-command "add-text-to-exp-window" window text (list (list "x" x)
(list "y" y)
(list "color" color)
(list "height" height)
(list "width" width)
(list "font-size" font-size))))
(defun add-button-to-exp-window (window &key (text "") (x 0) (y 0) (color 'gray) (height 20) (width 75) action)
(evaluate-act-r-command "add-button-to-exp-window" window (list (list "x" x)
(list "y" y)
(list "color" color)
(list "height" height)
(list "width" width)
(list "text" text)
(list "action" action))))
(defun remove-items-from-exp-window (window &rest items)
(apply 'evaluate-act-r-command "remove-items-from-exp-window" (cons window items)))
(defun process-events ()
(bt:thread-yield))
(defun install-device (device-list)
(evaluate-act-r-command "install-device" device-list))
(defmacro print-warning (warning-string &rest params)
`(evaluate-act-r-command "print-warning" (format nil "~@?" ,warning-string ,@params)))
(defmacro model-output (model-string &rest params)
`(evaluate-act-r-command "model-output" (format nil "~@?" ,model-string ,@params)))
(defmacro act-r-output (output-string &rest params)
`(evaluate-act-r-command "act-r-output" (format nil "~@?" ,output-string ,@params)))
(defun add-act-r-command (name function &optional (documentation "No documentation provided.") (single-instance t) local-name)
(let ((current (gethash name (client-dispatcher-command-table *dispatcher*))))
(if (and current (eq current function))
(print-warning (format nil "Command ~s already exists locally and is being reused." name))
(if current
(progn
(print-warning (format nil "Command ~s exists locally, but with a different function. Replacing prior function." name))
(setf (gethash name (client-dispatcher-command-table *dispatcher*)) function))
(setf (gethash name (client-dispatcher-command-table *dispatcher*)) function)))
(let ((result (multiple-value-list (send-command-to-act-r "add" name name documentation single-instance local-name))))
(if (first result)
(values-list (rest result))
(dolist (x (rest result) nil)
(format *error-output* x))))))
(defun monitor-act-r-command (act-r-command local-command)
(let ((result (multiple-value-list (send-command-to-act-r "monitor" act-r-command local-command))))
(if (first result)
(values-list (rest result))
(dolist (x (rest result) nil)
(format *error-output* x)))))
(defun remove-act-r-command-monitor (act-r-command local-command)
(let ((result (multiple-value-list (send-command-to-act-r "remove-monitor" act-r-command local-command))))
(if (first result)
(values-list (rest result))
(dolist (x (rest result) nil)
(format *error-output* x)))))
(defun remove-act-r-command (name)
(let ((current (gethash name (client-dispatcher-command-table *dispatcher*))))
(if current
(remhash name (client-dispatcher-command-table *dispatcher*))
(print-warning (format nil "Command ~s does not exist locally." name)))
(let ((result (multiple-value-list (send-command-to-act-r "remove" name))))
(if (first result)
(values-list (rest result))
(dolist (x (rest result) nil)
(format *error-output* x))))))
(defun act-r-random (value)
(evaluate-act-r-command "act-r-random" value))
(defun print-visicon ()
(evaluate-act-r-command "print-visicon"))
(defun mean-deviation (results data &optional (output t))
(evaluate-act-r-command "mean-deviation" results data output))
(defun correlation (results data &optional (output t))
(evaluate-act-r-command "correlation" results data output))
(defun get-time (&optional (model-time t))
(evaluate-act-r-command "get-time" model-time))
(defmacro buffer-status (&rest buffers)
`(apply 'evaluate-act-r-command "buffer-status" ',buffers))
(defun buffer-status-fct (buffers)
(apply 'evaluate-act-r-command "buffer-status" buffers))
(defun buffer-read (buffer-name)
(evaluate-act-r-command "buffer-read" buffer-name))
(defun clear-buffer (buffer-name)
(evaluate-act-r-command "clear-buffer" buffer-name))
(defun new-tone-sound (freq duration &optional onset time-in-ms)
(evaluate-act-r-command "new-tone-sound" freq duration onset time-in-ms))
(defun new-word-sound (word &optional onset (location 'external) time-in-ms)
(evaluate-act-r-command "new-word-sound" word onset location time-in-ms))
(defun new-digit-sound (digit &optional onset time-in-ms)
(evaluate-act-r-command "new-digit-sound" digit onset time-in-ms))
(defun encode-string-names (sn)
(cond ((null sn)
nil)
((or (symbolp sn) (numberp sn))
sn)
((stringp sn)
(format nil "'~a'" sn))
((listp sn)
(mapcar 'encode-string-names sn))
(t
(error "Invalid item ~s found when encoding strings." sn))))
(defmacro define-chunks (&rest chunk-definitions)
`(apply 'evaluate-act-r-command "define-chunks" (encode-string-names ',chunk-definitions)))
(defun define-chunks-fct (chunk-definitions)
(apply 'evaluate-act-r-command "define-chunks" (encode-string-names chunk-definitions)))
(defmacro add-dm (&rest chunk-definitions)
`(evaluate-act-r-command "add-dm-fct" (encode-string-names ',chunk-definitions)))
(defun add-dm-fct (chunk-definitions)
(evaluate-act-r-command "add-dm-fct" (encode-string-names chunk-definitions)))
(defmacro pprint-chunks (&rest chunks)
`(apply 'evaluate-act-r-command "pprint-chunks" ',chunks))
(defun pprint-chunks-fct (chunks)
(apply 'evaluate-act-r-command "pprint-chunks" chunks))
(defun decode-string-names (sn)
(cond ((null sn)
nil)
((or (symbolp sn) (numberp sn))
sn)
((stringp sn)
(decode-string sn))
((listp sn)
(mapcar 'decode-string-names sn))
(t
(error "Invalid item ~s found when parsing strings into ACT-R elements." sn))))
(defmacro chunk-slot-value (chunk-name slot-name)
`(evaluate-act-r-command-decoded "chunk-slot-value" ',chunk-name ',slot-name))
(defun chunk-slot-value-fct (chunk-name slot-name)
(evaluate-act-r-command-decoded "chunk-slot-value" chunk-name slot-name))
(defmacro set-chunk-slot-value (chunk-name slot-name new-value)
`(evaluate-act-r-command-decoded "set-chunk-slot-value" ',chunk-name ',slot-name (encode-string-names ',new-value)))
(defun set-chunk-slot-value-fct (chunk-name slot-name new-value)
(evaluate-act-r-command-decoded "set-chunk-slot-value" chunk-name slot-name (encode-string-names new-value)))
(defmacro mod-focus (&rest modifications)
`(apply 'evaluate-act-r-command "mod-focus" (encode-string-names ',modifications)))
(defun mod-focus-fct (modifications)
(apply 'evaluate-act-r-command "mod-focus" (encode-string-names modifications)))
(defmacro mod-chunk (chunk-name &rest modifications)
`(apply 'evaluate-act-r-command "mod-chunk" ',chunk-name (encode-string-names ',modifications)))
(defun mod-chunk-fct (chunk-name modifications)
(apply 'evaluate-act-r-command "mod-chunk" chunk-name (encode-string-names modifications)))
(defmacro chunk-p (chunk-name?)
`(evaluate-act-r-command "chunk-p" ',chunk-name?))
(defun chunk-p-fct (chunk-name?)
(evaluate-act-r-command "chunk-p" chunk-name?))
(defmacro copy-chunk (chunk-name?)
`(evaluate-act-r-command "copy-chunk" ',chunk-name?))
(defun copy-chunk-fct (chunk-name?)
(evaluate-act-r-command "copy-chunk" chunk-name?))
(defun extend-possible-slots (slot-name &optional (warn t))
(evaluate-act-r-command "extend-possible-slots" slot-name warn))
(defun set-buffer-chunk (buffer-name chunk-name &optional (requested t))
(evaluate-act-r-command "set-buffer-chunk" buffer-name chunk-name requested))
(defun add-line-to-exp-window (window start end &optional color)
(if color
(evaluate-act-r-command "add-line-to-exp-window" window start end color)
(evaluate-act-r-command "add-line-to-exp-window" window start end)))
(defun modify-line-for-exp-window (line start end &optional color)
(if color
(evaluate-act-r-command "modify-line-for-exp-window" line start end color)
(evaluate-act-r-command "modify-line-for-exp-window" line start end)))
(defun start-hand-at-mouse ()
(evaluate-act-r-command "start-hand-at-mouse"))
(defun schedule-event (time action &key params (module :NONE) (priority 0) maintenance destination details (output t) time-in-ms precondition)
(evaluate-act-r-command "schedule-event" time action (list (list "params" params)
(list "module" module)
(list "priority" (encode-keyword-names priority))
(list "maintenance" maintenance)
(list "destination" destination)
(list "details" details)
(list "output" output)
(list "time-in-ms" time-in-ms)
(list "precondition" precondition))))
(defun schedule-event-now (action &key params (module :NONE) (priority 0) maintenance destination details (output t) precondition)
(evaluate-act-r-command "schedule-event-now" action (list (list "params" params)
(list "module" module)
(list "priority" (encode-keyword-names priority))
(list "maintenance" maintenance)
(list "destination" destination)
(list "details" details)
(list "output" output)
(list "precondition" precondition))))
(defun schedule-event-relative (time-delay action &key params (module :NONE) (priority 0) maintenance destination details (output t) time-in-ms precondition)
(evaluate-act-r-command "schedule-event-relative" time-delay action (list (list "params" params)
(list "module" module)
(list "priority" (encode-keyword-names priority))
(list "maintenance" maintenance)
(list "destination" destination)
(list "details" details)
(list "output" output)
(list "time-in-ms" time-in-ms)
(list "precondition" precondition))))
(defun schedule-event-after-module (after-module action &key params (module :NONE) maintenance destination details (output t) precondition dynamic (delay t) include-maintenance)
(evaluate-act-r-command "schedule-event-after-module" after-module action (list (list "params" params)
(list "module" module)
(list "maintenance" maintenance)
(list "destination" destination)
(list "details" details)
(list "output" output)
(list "precondition" precondition)
(list "dynamic" dynamic)
(list "delay" delay)
(list "include-maintenance" include-maintenance))))
(defun schedule-break-relative (time-delay &key (priority :max) details time-in-ms)
(evaluate-act-r-command "schedule-break-relative" time-delay (list (list "priority" (encode-keyword-names priority))
(list "details" details)
(list "time-in-ms" time-in-ms))))
(defun mp-show-queue (&optional mark-traced?)
(evaluate-act-r-command "mp-show-queue" mark-traced?))
(defun print-dm-finsts ()
(evaluate-act-r-command "print-dm-finsts"))
(defmacro spp (&rest params)
`(apply 'evaluate-act-r-command "spp" (encode-keyword-names ',params)))
(defun spp-fct (params)
(evaluate-act-r-command "spp" (encode-keyword-names params)))
(defun mp-models ()
(evaluate-act-r-command "mp-models"))
(defun all-productions ()
(evaluate-act-r-command "all-productions"))
(defun buffers()
(evaluate-act-r-command "buffers"))
(defun printed-visicon ()
(evaluate-act-r-command "printed-visicon"))
(defun printed-audicon ()
(evaluate-act-r-command "printed-audicon"))
(defun print-audicon ()
(evaluate-act-r-command "print-audicon"))
(defun printed-parameter-details (param)
(evaluate-act-r-command "printed-parameter-details" (encode-keyword-names param)))
(defun sorted-module-names ()
(evaluate-act-r-command "sorted-module-names"))
(defun modules-parameters (module)
(evaluate-act-r-command "modules-parameters" (encode-keyword-names module)))
(defun modules-with-parameters ()
(evaluate-act-r-command "modules-with-parameters"))
(defun used-production-buffers ()
(evaluate-act-r-command "used-production-buffers"))
(defun record-history (&rest names)
(evaluate-act-r-command "record-history" names))
(defun stop-recording-history (&rest names)
(evaluate-act-r-command "stop-recording-history" names))
(defun get-history-data (name &rest params)
(evaluate-act-r-command "get-history-data" name params))
(defun process-history-data (name &optional file data-params processor-params)
(evaluate-act-r-command "process-history-data" name file data-params processor-params))
(defun save-history-data (name file &optional comment &rest params)
(evaluate-act-r-command "save-history-data" name file comment params))
(defmacro dm (&rest params)
`(if ',params
(dm-fct ',params)
(evaluate-act-r-command "dm")))
(defun dm-fct (params)
(apply 'evaluate-act-r-command (push "dm" params)))
(defmacro sdm (&rest params)
`(if ',params
(sdm-fct ',params)
(evaluate-act-r-command "sdm")))
(defun sdm-fct (params)
(apply 'evaluate-act-r-command (cons "sdm" (encode-string-names params))))
(defmacro sgp (&rest parameters)
`(sgp-fct ',parameters))
(defun sgp-fct (parameters)
(if (every 'keywordp parameters)
(mapcar 'get-parameter-value (encode-keyword-names parameters))
(if (evenp (length parameters))
(let (v)
(while parameters
(push-last (set-parameter-value (encode-keyword-names (pop parameters)) (pop parameters)) v))
v)
(print-warning "Sgp requires either all keywords naming parameters or an even number of items."))))
(defun get-parameter-value (param)
(evaluate-act-r-command-decoded "get-parameter-value" (encode-keyword-names param)))
(defun set-parameter-value (param value)
(evaluate-act-r-command-decoded "set-parameter-value" (encode-keyword-names param) (encode-string-names value)))
(defun get-system-parameter-value (param)
(evaluate-act-r-command-decoded "get-system-parameter-value" (encode-keyword-names param)))
(defun set-system-parameter-value (param value)
(evaluate-act-r-command-decoded "set-system-parameter-value" (encode-keyword-names param) (encode-string-names value)))
(defmacro sdp (&rest params)
`(if ',params
(sdp-fct ',params)
(evaluate-act-r-command "sdp")))
(defun sdp-fct (params)
(apply 'evaluate-act-r-command (cons "sdp" (encode-keyword-names params))))
(defmacro simulate-retrieval-request (&rest params)
`(evaluate-act-r-command "simulate-retrieval-request" (encode-string-names ',params)))
(defun simulate-retrieval-request-fct (params)
(evaluate-act-r-command "simulate-retrieval-request" (encode-string-names params)))
(defun saved-activation-history ()
(evaluate-act-r-command "saved-activation-history"))
(defun print-activation-trace (time &optional (ms t))
(evaluate-act-r-command "print-activation-trace" time ms))
(defmacro print-chunk-activation-trace (chunk time &optional (ms t))
`(evaluate-act-r-command "print-chunk-activation-trace" ',chunk ,time ,ms))
(defun print-chunk-activation-trace-fct (chunk time &optional (ms t))
(evaluate-act-r-command "print-chunk-activation-trace" chunk time ms))
(defmacro pp (&rest names)
`(if ',names
(pp-fct ',names)
(evaluate-act-r-command "pp")))
(defun pp-fct (names)
(apply 'evaluate-act-r-command (push "pp" names)))
(defun trigger-reward (reward &optional maintenance)
(evaluate-act-r-command "trigger-reward" reward maintenance))
(defmacro define-chunk-spec (&rest spec)
`(apply 'evaluate-act-r-command (cons "define-chunk-spec" (encode-keyword-names (encode-string-names ',spec)))))
(defun define-chunk-spec-fct (spec)
(apply 'evaluate-act-r-command (cons "define-chunk-spec" (encode-keyword-names (encode-string-names spec)))))
(defun release-chunk-spec (chunk-spec)
(evaluate-act-r-command "release-chunk-spec-id" chunk-spec))
(defun chunk-spec-to-chunk-def (chunk-spec)
(evaluate-act-r-command-decoded "chunk-spec-to-chunk-def" chunk-spec))
(defun schedule-set-buffer-chunk (buffer chunk time &key (module :NONE) (priority 0) (output 'low) time-in-ms (requested t))
(evaluate-act-r-command "schedule-set-buffer-chunk" buffer chunk time
(list (list "module" module)
(list "priority" priority)
(list "output" output)
(list "time-in-ms" time-in-ms)
(list "requested" requested))))
(defun schedule-mod-buffer-chunk (buffer mod-list-or-spec time &key (module :NONE) (priority 0) (output 'low) time-in-ms)
(evaluate-act-r-command "schedule-mod-buffer-chunk" buffer (encode-string-names mod-list-or-spec) time
(list (list "module" module)
(list "priority" priority)
(list "output" output)
(list "time-in-ms" time-in-ms))))
(defun undefine-module (name)
(evaluate-act-r-command "undefine-module" name))
(defun delete-chunk (name)
(evaluate-act-r-command "delete-chunk" name))
(defun purge-chunk (name)
(evaluate-act-r-command "purge-chunk" name))
(defun define-module (name buffer-list parameters
&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))
(evaluate-act-r-command "define-module" name buffer-list parameters
(list (list "version" version)
(list "documentation" documentation)
(list "creation" creation)
(list "reset" reset)
(list "query" query)
(list "request" request)
(list "buffer-mod" buffer-mod)
(list "params" params)
(list "delete" delete)
(list "notify-on-clear" notify-on-clear)
(list "update" update)
(list "warning" warning)
(list "search" search)
(list "offset" offset)
(list "run-start" run-start)
(list "run-end" run-end))))
(defmacro command-output (output-string &rest params)
`(evaluate-act-r-command "command-output" (format nil "~@?" ,output-string ,@params)))
(defun chunk-copied-from (chunk-name)
(evaluate-act-r-command "chunk-copied-from" chunk-name))
(defun mp-time ()
(evaluate-act-r-command "mp-time"))
(defun mp-time-ms ()
(evaluate-act-r-command "mp-time-ms"))
(defun predict-bold-response (&optional start end output)
(if (null start)
(evaluate-act-r-command "predict-bold-response")
(if (null end)
(evaluate-act-r-command "predict-bold-response" start)
(if (null output)
(evaluate-act-r-command "predict-bold-response" start end)
(evaluate-act-r-command "predict-bold-response" start end output)))))
(defmacro pbreak (&rest params)
`(apply 'evaluate-act-r-command "pbreak" ',params))
(defun pbreak-fct (params)
(apply 'evaluate-act-r-command "pbreak" params))
(defmacro punbreak (&rest params)
`(apply 'evaluate-act-r-command "punbreak" ',params))
(defun punbreak-fct (params)
(apply 'evaluate-act-r-command "punbreak" params))
(defun create-image-for-exp-window (window text file &key (x 0) (y 0) (height 50) (width 50) action)
(evaluate-act-r-command "create-image-for-exp-window" window text file (list (list "x" x)
(list "y" y)
(list "height" height)
(list "width" width)
(list "action" action))))
(defun add-image-to-exp-window (window text file &key (x 0) (y 0) (height 50) (width 50) action)
(evaluate-act-r-command "add-image-to-exp-window" window text file (list (list "x" x)
(list "y" y)
(list "height" height)
(list "width" width)
(list "action" action))))
(defun add-items-to-exp-window (window &rest items)
(apply 'evaluate-act-r-command "add-items-to-exp-window" window items))
(defun add-visicon-features (&rest features)
(apply 'evaluate-act-r-command "add-visicon-features" (encode-string-names features)))
(defun delete-visicon-features (&rest features)
(apply 'evaluate-act-r-command "delete-visicon-features" features))
(defun delete-all-visicon-features ()
(evaluate-act-r-command "delete-all-visicon-features"))
(defun modify-visicon-features (&rest features)
(apply 'evaluate-act-r-command "modify-visicon-features" (encode-string-names features)))
(defun running ()
(evaluate-act-r-command "act-r-running-p"))
#|
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
|# | 60,068 | Common Lisp | .lisp | 1,021 | 45.365328 | 196 | 0.563722 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 46058520dd0202eb7cde14ab0431788816d5b84d8a06794b4166be94bf64e2b7 | 14,219 | [
486677
] |
14,220 | subitize.lisp | asmaloney_ACT-R/tutorial/lisp/subitize.lisp | ; ACT-R tutorial unit3 subitize experiment.
; This experiment displays a number of Xs on
; the screen and the participant must respond
; with how many are there. A human participant
; must press a key from 0-9 (where 0 represents
; 10 items) but a model must speak the count
; (which is how the original experiment was
; performed). The time of the response and its
; correctness are recorded.
; Load the corresponding ACT-R starting model.
(load-act-r-model "ACT-R:tutorial;unit3;subitize-model.lisp")
; Define some global variables to hold the response
; given and the time it occurred.
(defvar *response* nil)
(defvar *response-time* nil)
; A variable holding the data from the original experiment
(defvar *subitize-exp-data* '(.6 .65 .7 .86 1.12 1.5 1.79 2.13 2.15 2.58))
; Two functions for converting an integer to a string
; as either the word e.g. "one" or the digits e.g. "1"
; for comparison to the response given by a model (spoken)
; or a person (keypress).
(defun number-to-word (n)
(format nil "~r" n))
(defun number-to-string (n)
(if (= n 10)
"0"
(princ-to-string n)))
; The subitize-trial function presents one trial of the task.
; It requires one parameter which is the number of items to
; present (should be an integer from 1-10), and has an optional
; parameter which indicates whether it is the model or a person
; performing the task. It returns a list with the time it took
; the participant to respond and t if the response was correct
; or the list (30 nil) if the response was incorrect or no
; response was provided.
(defun subitize-trial (n &optional human)
; Reset ACT-R and all models to initial state
(reset)
; create some local variables to perform the trial:
; points: is a list of randomized x,y coordinates to display the Xs
; from the generate-points function
; window: an experiment window created to display the task
; start: the current time at the start of the trial
; as given by the ACT-R get-time function which
; needs to be provided whether it is the model or
; a person doing the task to get the appropriate time
; answer: a variable to hold the correct answer for the trial
(let ((points (generate-points n))
(window (open-exp-window "Subitizing Experiment"))
(start (get-time (if human nil t)))
answer)
; Display an x at each of the points
(dolist (point points)
(add-text-to-exp-window window "x" :x (first point) :y (second point)))
; clear the response variables
(setf *response* nil)
(setf *response-time* nil)
; Run the trial
(if human
(when (visible-virtuals-available?)
; If a human is doing the task and there is a visible
; window available for them to interact with then
; add a command and monitor the output-key action
(add-act-r-command "subitize-response" 'respond-to-key-press
"Subitize task human response")
(monitor-act-r-command "output-key" "subitize-response")
; Set the correct answer string for a key press
(setf answer (number-to-string n))
; Wait until there is a response
(while (null *response*)
(process-events))
; Stop monitoring output-key and remove the command
(remove-act-r-command-monitor "output-key" "subitize-response")
(remove-act-r-command "subitize-response"))
(progn
; If a model is doing the task add a command and monitor
; the output-speech action
(add-act-r-command "subitize-response" 'record-model-speech
"Subitize task model response")
(monitor-act-r-command "output-speech" "subitize-response")
; Set the correct answer string for a spoken response
(setf answer (number-to-word n))
; Tell the model to interact with the created window
(install-device window)
; Run the model for up to 30 seconds in real time mode
(run 30 t)
; Stop monitoring output-speech and remove the command
(remove-act-r-command-monitor "output-speech" "subitize-response")
(remove-act-r-command "subitize-response")))
; If a response is given and it matches the correct answer
; then return a list with the time since the trial started
; in seconds and t, otherwise return a list of 30 and nil
(if (and *response* (string-equal answer *response*))
(list (/ (- *response-time* start) 1000.0) t)
(list 30 nil))))
; Subitize-experiment takes one optional parameter which indicates
; whether it is a human or model performing the task. Then it
; presents a trial for each of the counts from 1-10 in a randomized
; order, and passes the results to report-data sorted by item count.
(defun subitize-experiment (&optional human)
(let (results)
(dolist (items (permute-list '(10 9 8 7 6 5 4 3 2 1)))
(push (list items (subitize-trial items human)) results))
(setf results (sort results '< :key 'car))
(report-data (mapcar 'second results))))
; Report-data compares the times in the provided data to
; the original experiment data and then passes it to print-results
; for output.
(defun report-data (data)
(let ((rts (mapcar 'first data)))
(correlation rts *subitize-exp-data*)
(mean-deviation rts *subitize-exp-data*)
(print-results data)))
; Print-results outputs a table with the times and correctness
; values from the current experiment along with the data from
; the origial experiment.
(defun print-results (data)
(format t "Items Current Participant Original Experiment~%")
(dotimes (i (length data))
(format t "~3d ~5,2f (~3s) ~5,2f~%"
(1+ i) (car (nth i data)) (second (nth i data))
(nth i *subitize-exp-data*))))
; The next three functions: generate-points, new-distinct-point, and
; too-close are used to generate a list of random x,y lists for the
; coordinates to display the Xs so that they are within the bounds of
; the window and non-overlapping.
(defun generate-points (n)
(let ((points nil))
(dotimes (i n points)
(push (new-distinct-point points) points))))
(defun new-distinct-point (points)
(do ((new-point (list (+ (act-r-random 240) 20) (+ (act-r-random 240) 20))
(list (+ (act-r-random 240) 20) (+ (act-r-random 240) 20))))
((not (too-close new-point points)) new-point)))
(defun too-close (new-point points)
(some (lambda (a) (and (< (abs (- (car new-point) (car a))) 40)
(< (abs (- (cadr new-point) (cadr a))) 40)))
points))
; Respond-to-key-press is monitoring output-key to record
; the current time and key pressed when a human is performing
; the task.
(defun respond-to-key-press (model key)
(declare (ignore model))
(setf *response-time* (get-time nil))
(setf *response* key))
; Record-model-speech is monitoring output-speech to record
; the current time and word spoken when a model is performing
; the task.
(defun record-model-speech (model string)
(declare (ignore model))
(setf *response-time* (get-time t))
(setf *response* string))
| 7,472 | Common Lisp | .lisp | 152 | 42.434211 | 78 | 0.682875 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 8ca9c444caa0b2d814251b0c8d83f6dc804780cad9a336ac60de6d65e736396d | 14,220 | [
-1
] |
14,221 | sperling.lisp | asmaloney_ACT-R/tutorial/lisp/sperling.lisp | ; ACT-R tutorial unit 3 demonstration task.
; The sperling experiment displays a block of 12
; letters in the window, with 3 lines of 4 letters
; per line for a brief time. After the display has
; been presented a tone sound is generated to indicate
; which row of letters must be reported (the timing of
; the tone relative to the initial display of the
; letters is variable). After the letters go away
; the participant must press the keys to indicate which
; letters were in the target row, and press the spacebar
; to indicate completion.
; Load the corresponding tutorial model
(load-act-r-model "ACT-R:tutorial;unit3;sperling-model.lisp")
; Define some global variables: *responses* holds the list of
; keys pressed by the participant, *show-responses* indicates
; whether or not to print out the responses provided after a
; trial is run, and *sperling-exp-data* holds the results of
; the original experiment (number of correct responses from
; the target row based on the delay of the tone) for
; comparison to the model's performance.
(defvar *responses* nil)
(defparameter *show-responses* t)
(defvar *sperling-exp-data* '(3.03 2.40 2.03 1.50))
; The sperling-trial function runs a single trial of the task
; and returns the number of correct responses. It requires one
; parameter which is the time in seconds to delay the tone
; after the items have been presented.
(defun sperling-trial (onset-time)
; Reset ACT-R and all models to initial state
(reset)
; create some local variables to perform the trial:
; letters: is a randomized list of letter strings
; answers: will be the list of letters in the target row
; row: a random number from 0-2 indicating which row will
; be the target
; window: an experiment window created to display the task
; freq: will be set to the frequency of the tone to present
(let* ((letters (permute-list '("B" "C" "D" "F" "G" "H" "J"
"K" "L" "M" "N" "P" "Q" "R"
"S" "T" "V" "W" "X" "Y" "Z")))
(answers nil)
(row (act-r-random 3))
(window (open-exp-window "Sperling Experiment" :visible t))
freq)
; Show the first 12 letters from the list in the window in
; three rows of four and record which ones are in the target
; row in the answers variable.
(dotimes (i 3)
(dotimes (j 4)
(let ((txt (nth (+ j (* i 4)) letters)))
(when (= i row)
(push txt answers))
(add-text-to-exp-window window txt :x (+ 75 (* j 50)) :y (+ 100 (* i 50))))))
; Tell the model to interact with that window
(install-device window)
; Set the freq variable based on which row is the target
(case row
(0
(setf freq 2000))
(1
(setf freq 1000))
(2
(setf freq 500)))
; Create a tone with frequency freq for .5 seconds
; starting at the indicated onset-time
(new-tone-sound freq .5 onset-time)
; To simulate the persistent visual memory for the model
; we will not clear the display until after a randomly
; chosen time between .9 and 1.1 seconds has passed.
; This is done by scheduling the clear-exp-window command
; to be called after that amount of time has passed.
(schedule-event-relative (+ 900 (act-r-random 200)) "clear-exp-window" :params (list window) :time-in-ms t)
; clear the response variable
(setf *responses* nil)
; Add a command for our respond-to-key-press function so that
; ACT-R can call it.
(add-act-r-command "sperling-response" 'respond-to-key-press
"Sperling task key press response monitor")
; Monitor the output-key action so that our respond-to-key-press
; function is called when a key is pressed.
(monitor-act-r-command "output-key" "sperling-response")
; Run the model for up to 30 seconds in real time mode.
(run 30 t)
; Stop monitoring the output-key action and remove our command.
(remove-act-r-command-monitor "output-key" "sperling-response")
(remove-act-r-command "sperling-response")
; If the *show-responses* variable is non-nil then print out
; the correct answers and the responses that were provided
(when *show-responses*
(format t "~%~%answers: ~S~%responses: ~S~%" answers *responses*))
; Call the compute-score function to determine the number of
; correct responses and return the result.
(compute-score answers)))
; The compute-score function counts how many of the correct answers
; were provided by the participant and returns that number.
(defun compute-score (answers)
(let ((score 0))
(dolist (x answers score)
(when (member x *responses* :test 'string-equal)
(incf score)))))
; This function is the one that will be called when the participant
; presses a key, and it just records the result in the *responses*
; list unless it is the space bar.
(defun respond-to-key-press (model key)
(declare (ignore model))
(unless (string-equal key "space")
(push key *responses*)))
; The report-data function takes a list of the average number of items
; reported in the target row ordered by onset delay. It compares those
; to the original experiment's data based on correlation and mean deviation
; then calls print-results to display the data.
(defun report-data (data)
(correlation data *sperling-exp-data*)
(mean-deviation data *sperling-exp-data*)
(print-results data))
; The print-results function takes a list of the average target row data
; and prints that in a table along with the original experiment's data.
(defun print-results (data)
(format t "~%Condition Current Participant Original Experiment~%")
(do ((condition '(0.00 0.15 0.30 1.00) (cdr condition))
(temp1 data (cdr temp1))
(temp2 *sperling-exp-data* (cdr temp2)))
((null temp1))
(format t " ~4,2F sec. ~6,2F ~6,2F~%"
(car condition) (car temp1) (car temp2))))
; The one-block function runs a trial of the experiment at each
; of the experiment's tone onset conditions in a random order.
; It returns a list of the correct answer counts in the order
; of onset duration (lowest first).
(defun one-block ()
(let ((result nil))
(dolist (x (permute-list '(0.0 .15 .30 1.0)))
(push (cons x (sperling-trial x)) result))
(mapcar 'cdr (sort result '< :key 'car))))
; The sperling-experiment function takes one required parameter which
; is the number of blocks to run in the experiment (where each block
; is one trial at each of the 4 possible onset times). It collects
; the data over blocks, averages the results, and passes that to the
; report-data function for display.
(defun sperling-experiment (n)
(let ((results (list 0 0 0 0)))
(dotimes (i n)
(setf results (mapcar '+ results (one-block))))
(report-data (mapcar (lambda (x) (/ x n)) results))))
| 7,108 | Common Lisp | .lisp | 144 | 43.597222 | 111 | 0.690077 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 234191603460628bfca762bfc6d695da9a9e3ddeada057250af45a7ef71a3a56 | 14,221 | [
-1
] |
14,222 | ul-issues.lisp | asmaloney_ACT-R/tutorial/lisp/ul-issues.lisp | ; ACT-R tutorial unit7 task for investigating utility
; learning modeling issues.
(defun present-choose ()
(goal-focus initial-goal)
(schedule-event-relative 5 "utility-learning-issues-show-result"
:params (list (if (< (act-r-random 1.0) .6) 'a (if (> (act-r-random 1.0) .5) 'b nil)))
:output 'medium))
(defun show-result (choice)
(mod-chunk-fct 'response (list 'answer choice))
(set-buffer-chunk 'imaginal 'response)
(schedule-event-relative 2 "utility-learning-issues-choose" :output 'medium))
(add-act-r-command "utility-learning-issues-choose" 'present-choose "Function to change model's goal for utility learning issues model")
(add-act-r-command "utility-learning-issues-show-result" 'show-result "Function to set the model's imaginal buffer for utility learning issues model")
(defun finished ()
(remove-act-r-command "utility-learning-issues-choose")
(remove-act-r-command "utility-learning-issues-show-result"))
(load-act-r-model "ACT-R:tutorial;unit7;utility-learning-issues-model.lisp") | 1,092 | Common Lisp | .lisp | 17 | 57.705882 | 151 | 0.708255 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 227698ed02b27db279dba045c8749ebb00813356ce9f7bc766adaad03dfe2e6d | 14,222 | [
-1
] |
14,223 | zbrodoff.lisp | asmaloney_ACT-R/tutorial/lisp/zbrodoff.lisp | ; ACT-R tutorial unit 4 zbrodoff task.
; This experiment presents participants with alpha-arithmetic
; problems like "A + 2 = C" which they must respond to by
; pressing k if the problem is correct or d if it is not.
; The code runs the control condition from the paper:
;
; Zbrodoff, N. J. (1995). Why is 9 + 7 harder than 2 + 3?
; Strength and interference as explanations of the problem-size
; effect. Memory & Cognition, 23 (6), 689-700.
;
; That condition presents problems with addends of 2, 3, and 4
; with equal frequency in blocks of 192 trials where half of the
; trials in a block are correct and half are false. The
; data for comparison is the average response time by block
; and addend for correct answers (including both true and
; false problems).
; Load the corresponding model for the task
(load-act-r-model "ACT-R:tutorial;unit4;zbrodoff-model.lisp")
; Global variables to hold the trials to present, the results that have
; been collected, and the original data for comparison.
(defvar *trials*)
(defvar *results*)
(defvar *zbrodoff-control-data* '(1.84 2.46 2.82 1.21 1.45 1.42 1.14 1.21 1.17))
; Also create a variable to indicate whether it will be a model or person.
; This is done to keep the number of parameters needed to run the functions
; smaller since one may want a visible window for either a person or model
; and this avoids having to specify both who is running and whether the window
; should be shown.
(defparameter *run-model* t)
; Because the data collection for this task is a little more involved
; we're going to record the trials in a structure to keep everything
; together and organized instead of just a list of items as has been
; done for other experiments. This will also allow us to store all of
; the information needed to present a trial together so that we can
; create them all in advance which can be useful when running in an
; event-driven style. A trial will hold the block number, the addend
; value, the text of the problem to display, the correct answer, whether
; the window should be visible or not, whether the response from the
; participant was correct, the time the trial started, and the response
; time.
(defstruct trial block addend text answer visible correct start time)
; The construct-trial function takes a block number, a list of the items
; which describe the problem to present, and an optional parameter to
; indicate whether or not the window should be visible. It creates
; and returns a trial structure containing the appropriate information.
(defun construct-trial (block problem &optional visible)
(destructuring-bind (addend1 addend2 sum answer) problem
(make-trial :block block
:addend addend2
:text (format nil "~a + ~a = ~a" addend1 addend2 sum)
:answer answer
:visible visible)))
; The present-trial function takes one parameter which is a trial
; structure and an optional parameter which indicates whether or not
; to open a new window for this trial (since this task is running
; continuously it will run faster if it uses the same window repeatedly,
; but because the same code is used to run it for a variety of
; different situations it needs to know when to start over with a
; new display).
(defun present-trial (trial &optional (new-window t))
(if new-window
; If a new window is requested it opens one using
; the visible status indicated in the trial and
; if the model is performing the task it installs
; that window device for the model.
(let ((w (open-exp-window "Alpha-arithmetic Experiment" :visible (trial-visible trial))))
(when *run-model*
(install-device w)))
; otherwise it just clears the current window
(clear-exp-window))
; add the text from the trial to the window and set the
; start time in the trial structure.
(add-text-to-exp-window nil (trial-text trial) :x 100 :y 150)
(setf (trial-start trial) (get-time *run-model*)))
; The respond-to-key-press function will be set up to monitor
; the output-key actions, and thus will be called with two parameters
; when a key is pressed: the name of the model that pressed the key
; (or nil if it is a person) and the string naming the key that was
; pressed.
; Unlike the previous tasks, since this one is event-driven we will
; actually do more than just record the key and time in this function.
; It will also present the next trial if there is one so that the
; model can continue to run in the task until it is complete.
(defun respond-to-key-press (model key)
(declare (ignore model))
; Remove the current trial from the list, and then set the response time
; and correctness in the structure before adding it to the results list.
(let ((trial (pop *trials*)))
(setf (trial-time trial) (/ (- (get-time *run-model*) (trial-start trial)) 1000.0))
(setf (trial-correct trial) (string-equal (trial-answer trial) key))
(push trial *results*))
; If there are any trials left to present then present the first of them now.
(when *trials*
(present-trial (first *trials*) nil)))
; The collect-responses function takes no parameters and runs all of
; the trials available.
(defun collect-responses ()
; record how many trials need to be run
(let ((total (length *trials*)))
; Create a command for respond-to-key-press and monitor output-key.
(add-act-r-command "zbrodoff-response" 'respond-to-key-press
"Zbrodoff task key press response monitor")
(monitor-act-r-command "output-key" "zbrodoff-response")
; present the first trial
(present-trial (first *trials*))
; If it's a model doing the task run for 10s per trial,
; and if it's a person loop until there are as many results
; as there were trials to run.
(if *run-model*
(run (* 10 total))
(if (visible-virtuals-available?)
(while (< (length *results*) total)
(process-events))))
; stop monitoring and remove the command
(remove-act-r-command-monitor "output-key" "zbrodoff-response")
(remove-act-r-command "zbrodoff-response")))
; The zbrodoff-problem function takes 4 required parameters.
; The first three are the strings of the elements of the problem
; to present e.g. "A" "2" "C" to preset "A + 2 = C". The fourth
; is a string with the key press that will be a correct response
; which is "k" if the problem is correct and "d" if the problem
; is not correct. The optional parameter can be specified as true
; to have the window displayed, but if not provided defaults to
; not showing the window for a model and showing it for a person.
; It clears the current results, creates a list with the single
; trial specified and runs the task for that trial and displays
; the results.
(defun zbrodoff-problem (addend1 addend2 sum answer &optional (visible (not *run-model*)))
(setf *results* nil)
(setf *trials* (list (construct-trial 1 (list addend1 addend2 sum answer) visible)))
(collect-responses)
(analyze-results))
; Zbrodoff-set and zbrodoff-block are similar to zbrodoff-problem
; except that instead of presenting a single trial they present
; a full set (24 trials) or block (192 trials) of items.
(defun zbrodoff-set (&optional (visible (not *run-model*)))
(setf *results* nil)
(setf *trials* (create-set 1 visible))
(collect-responses)
(analyze-results))
(defun zbrodoff-block (&optional (visible (not *run-model*)))
(setf *results* nil)
(dotimes (i 8)
(setf *trials* (append *trials* (create-set 1 visible))))
(collect-responses)
(analyze-results))
; Zbrodoff-experiment has two optioal parameters. The first is
; whether or not to show the window which defaults to not shown
; if it's a model or shown for a person, and the second is whether
; or not to display the results after the experiment is run (the
; default is to show them).
; It resets the model, generates three blocks of trials, runs
; those trials, and reports the results.
(defun zbrodoff-experiment (&optional (visible (not *run-model*)) (show t))
(reset)
(setf *trials* nil)
(dotimes (j 3)
(dotimes (i 8)
(setf *trials* (append *trials* (create-set (+ j 1) visible)))))
(setf *results* nil)
(collect-responses)
(analyze-results show))
; Zbrodoff-compare takes one required parameter which is the number
; of times to run a model through the full experiment. It runs
; the model that many times and averages the results of those
; runs which it compares to the original data for the task and
; then displays the results.
(defun zbrodoff-compare (n)
(let ((results nil))
(dotimes (i n)
(push (zbrodoff-experiment nil nil) results))
(let ((rts (mapcar (lambda (x) (/ x (length results)))
(apply 'mapcar '+ (mapcar 'first results))))
(counts (mapcar (lambda (x) (truncate x (length results)))
(apply 'mapcar '+ (mapcar 'second results)))))
(correlation rts *zbrodoff-control-data*)
(mean-deviation rts *zbrodoff-control-data*)
(print-analysis rts counts '(1 2 3) '("2" "3" "4") '(64 64 64)))))
; Analyze-results takes one optional parameter which
; indicates whether or not to print the results in addition
; to averaging the times by addend and block and returning
; the averaged results and counts of correct items in a list.
(defun analyze-results (&optional (show t))
(let* ((blocks (sort (remove-duplicates (mapcar 'trial-block *results*)) '<))
(addends (sort (remove-duplicates (mapcar 'trial-addend *results*)
:test 'string-equal)
'string<))
(counts nil)
(rts nil)
(total-counts (mapcar (lambda (x)
(/ (count x *results*
:key 'trial-addend
:test 'string=)
(length blocks)))
addends)))
(dolist (x blocks)
(dolist (y addends)
(let ((data (mapcar 'trial-time
(remove-if-not (lambda (z)
(and (trial-correct z)
(string= y (trial-addend z))
(= x (trial-block z))))
*results*))))
(push (length data) counts)
(push (/ (apply '+ data) (max 1 (length data))) rts))))
(when show
(print-analysis (reverse rts) (reverse counts) blocks addends total-counts))
(list (reverse rts) (reverse counts))))
; print-analysis displays a table with the data items provided.
(defun print-analysis (rts counts blocks addends totals)
(format t "~% ")
(dotimes (addend (length addends))
(format t " ~6@a (~2d)" (nth addend addends) (nth addend totals)))
(dotimes (block (length blocks))
(format t "~%Block ~2d" (nth block blocks))
(dotimes (addend (length addends))
(format t " ~6,3f (~2d)" (nth (+ addend (* block (length addends))) rts)
(nth (+ addend (* block (length addends))) counts))))
(terpri))
; This varaible holds the problems to be presented
; in one set of the task -- 4 problems with each addend
; in a correct equation and 4 problems with each addend
; in an incorrect equation.
(defvar *data-set* '(("a" "2" "c" "k")("d" "2" "f" "k")
("b" "3" "e" "k")("e" "3" "h" "k")
("c" "4" "g" "k")("f" "4" "j" "k")
("a" "2" "d" "d")("d" "2" "g" "d")
("b" "3" "f" "d")("e" "3" "i" "d")
("c" "4" "h" "d")("f" "4" "k" "d")
("a" "2" "c" "k")("d" "2" "f" "k")
("b" "3" "e" "k")("e" "3" "h" "k")
("c" "4" "g" "k")("f" "4" "j" "k")
("a" "2" "d" "d")("d" "2" "g" "d")
("b" "3" "f" "d")("e" "3" "i" "d")
("c" "4" "h" "d")("f" "4" "k" "d")))
; Create-set takes a block number and whether the items
; should be visible and returns a randomized list of
; trial structures representing one set of data with
; those conditions.
(defun create-set (block visible)
(mapcar (lambda (x)
(construct-trial block x visible))
(permute-list *data-set*)))
| 12,551 | Common Lisp | .lisp | 243 | 44.786008 | 95 | 0.66037 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | be5e55b32e7a7f0ff4b4c090452925854fecc5dbe0ad271371d7d90a71cfa3fc | 14,223 | [
-1
] |
14,224 | demo2.lisp | asmaloney_ACT-R/tutorial/lisp/demo2.lisp | ; ACT-R tutorial unit 2 demo2 task.
; This experiment opens a window, displays a character,
; waits for a keypress, clears the window after there
; is a keypress, and then reports the key that was pressed.
; Start by loading the corresponding tutorial model
(load-act-r-model "ACT-R:tutorial;unit2;demo2-model.lisp")
; Create a variable to store the key that was pressed.
(defvar *response* nil)
; This is the function which we will have ACT-R call when
; a key is pressed in the experiment window which is signaled
; by the output-key action.
; That action provides two parameters to the function called.
; The first is the name of the model that performed the keypress
; or nil if it wasn't generated by a model, and the second
; is a string with the name of the key that was pressed.
(defun respond-to-key-press (model key)
; we aren't using the model so declare that to avoid warnings
(declare (ignore model))
; store the key that was pressed in the *response* variable
(setf *response* key)
; call the AGI command that clears the window
(clear-exp-window))
; This is the function that runs the experiment for either a
; person or a model. It has one optional parameter which if
; provided as a true value (anything not nil) will run a person.
; If it is not provided or nil is specified then it will run the
; ACT-R model.
(defun demo2-experiment (&optional human)
; Reset the ACT-R system and any models that are defined to
; their initial states.
(reset)
; Create three variable:
; items - a randomized list of letter strings which is randomized
; using the ACT-R function permute-list
; text1 - the first string from the randomized list which will be the
; one presented in the experiment
; window - the ACT-R window device list returned by using the ACT-R
; function open-exp-window to create a new window for
; displaying the experiment
(let* ((items (permute-list '("B" "C" "D" "F" "G" "H" "J" "K" "L" "M" "N"
"P" "Q" "R" "S" "T" "V" "W" "X" "Y" "Z")))
(text1 (first items))
(window (open-exp-window "Letter recognition")))
; display the text1 item in the window that was opened
(add-text-to-exp-window window text1 :x 125 :y 150)
; These next two function calls are how we tell ACT-R that it should
; call our respond-to-key-press function when there is a keypress
; in the experiment.
; First we need to create a command in ACT-R that corresponds
; to our function so that ACT-R is able to use the function.
(add-act-r-command "demo2-key-press" 'respond-to-key-press
"Demo2 task output-key monitor")
; Then, we use that command which we created to 'monitor'
; the output-key action which is triggered by keypress in the
; experiment window of ACT-R so that when an output-key happens
; our function is called.
(monitor-act-r-command "output-key" "demo2-key-press")
; Set the *response* value to nil to remove any value it may
; have from a previous run of the experiment.
(setf *response* nil)
; Here is where we actually "run" the experiment.
; It either waits for a person to press a key or runs ACT-R
; for up to 10 seconds giving the model a chance to do the
; experiment.
(if human
; If a person is doing the task then for safety
; we make sure there is a visible window that they
; can use to do the task, and if so, loop until the
; *response* variable is non-nil calling the
; process-events function to allow the system a
; chance to handle any interactions.
(when (visible-virtuals-available?)
(while (null *response*)
(process-events)))
; If it is not a human then use install-device so that
; the features in the window will be seen by the model
; (that will also automatically provide the model with
; access to a virtual keyboard and mouse). Then use
; the ACT-R run function to run the model for up to 10
; seconds in real-time mode.
(progn
(install-device window)
(run 10 t)))
; To avoid any issues with our function for keypresses in this
; experiment interfering with other experiments we should stop
; monitoring output-key and then remove our command.
(remove-act-r-command-monitor "output-key" "demo2-key-press")
(remove-act-r-command "demo2-key-press")
; return the result of the keypress
*response*))
| 4,704 | Common Lisp | .lisp | 90 | 45.522222 | 76 | 0.691239 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 2ffb5bd5162a16487edf36964a6413b932ac3da708db348d065577c6e4687209 | 14,224 | [
-1
] |
14,225 | choice.lisp | asmaloney_ACT-R/tutorial/lisp/choice.lisp |
(load-act-r-model "ACT-R:tutorial;unit6;choice-model.lisp")
(defvar *unit6-choice-data* '(0.664 0.778 0.804 0.818))
(defvar *response* nil)
(defun respond-to-key-press (model key)
(declare (ignore model))
(setf *response* key))
(defun choice-person ()
(when (visible-virtuals-available?)
(let ((window (open-exp-window "Choice Experiment" :visible t)))
(add-act-r-command "choice-response" 'respond-to-key-press "Choice task key response")
(monitor-act-r-command "output-key" "choice-response")
(add-text-to-exp-window window "choose" :x 50 :y 100)
(setf *response* nil)
(while (null *response*)
(process-events))
(clear-exp-window window)
(add-text-to-exp-window window (if (< (act-r-random 1.0) .9) "heads" "tails") :x 50 :y 100)
(let ((start (get-time nil)))
(while (< (- (get-time nil) start) 1000)
(process-events)))
(remove-act-r-command-monitor "output-key" "choice-response")
(remove-act-r-command "choice-response")
*response*)))
(defun choice-model ()
)
(defun choice-data (n)
)
| 1,193 | Common Lisp | .lisp | 27 | 35.62963 | 97 | 0.642193 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 4670cfd604d40b15536dc8012e7a069da90ba7f23aeb67c65f33161c7395ccc7 | 14,225 | [
491435
] |
14,226 | tutor-model.lisp | asmaloney_ACT-R/tutorial/unit1/tutor-model.lisp | (clear-all)
(define-model tutor-model
(sgp :esc t :lf .05 :trace-detail medium)
;; Add Chunk-types here
;; Add Chunks here
;; Add productions here
(goal-focus goal)
) | 185 | Common Lisp | .lisp | 8 | 19.875 | 41 | 0.742138 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | c99138704269d99098c8411ab95583d71dbea6f6efc7dcde4b7bc4615d15a1a5 | 14,226 | [
-1
] |
14,227 | count.lisp | asmaloney_ACT-R/tutorial/unit1/count.lisp | (clear-all)
(define-model count
(sgp :esc t :lf .05 :trace-detail high)
(chunk-type number number next)
(chunk-type count-from start end count)
(add-dm
(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)
(first-goal ISA count-from start two end four))
(goal-focus first-goal)
(p start
=goal>
ISA count-from
start =num1
count nil
==>
=goal>
ISA count-from
count =num1
+retrieval>
ISA number
number =num1
)
(p increment
=goal>
ISA count-from
count =num1
- end =num1
=retrieval>
ISA number
number =num1
next =num2
==>
=goal>
ISA count-from
count =num2
+retrieval>
ISA number
number =num2
!output! (=num1)
)
(p stop
=goal>
ISA count-from
count =num
end =num
=retrieval>
ISA number
number =num
==>
-goal>
!output! (=num)
)
)
| 1,212 | Common Lisp | .lisp | 57 | 16.877193 | 48 | 0.539267 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 06574ccee301fe27de4832d09ac8274653c4b3b3f55ba14a725588d6b17887ba | 14,227 | [
264898
] |
14,228 | semantic.lisp | asmaloney_ACT-R/tutorial/unit1/semantic.lisp | (clear-all)
(define-model semantic
(sgp :esc t :lf .05)
(chunk-type property object attribute value)
(chunk-type is-member object category judgment)
(add-dm
(shark) (dangerous) (locomotion) (swimming) (fish)
(salmon) (edible) (breathe) (gills) (animal)
(moves) (skin) (canary) (color) (sings) (bird)
(ostrich) (flies) (height) (tall) (wings) (flying)
(true) (false)
(p1 ISA property object shark attribute dangerous value true)
(p2 ISA property object shark attribute locomotion value swimming)
(p3 ISA property object shark attribute category value fish)
(p4 ISA property object salmon attribute edible value true)
(p5 ISA property object salmon attribute locomotion value swimming)
(p6 ISA property object salmon attribute category value fish)
(p7 ISA property object fish attribute breathe value gills)
(p8 ISA property object fish attribute locomotion value swimming)
(p9 ISA property object fish attribute category value animal)
(p10 ISA property object animal attribute moves value true)
(p11 ISA property object animal attribute skin value true)
(p12 ISA property object canary attribute color value yellow)
(p13 ISA property object canary attribute sings value true)
(p14 ISA property object canary attribute category value bird)
(p15 ISA property object ostrich attribute flies value false)
(p16 ISA property object ostrich attribute height value tall)
(p17 ISA property object ostrich attribute category value bird)
(p18 ISA property object bird attribute wings value true)
(p19 ISA property object bird attribute locomotion value flying)
(p20 ISA property object bird attribute category value animal)
(g1 ISA is-member object canary category bird)
(g2 ISA is-member object canary category animal)
(g3 ISA is-member object canary category fish))
(p initial-retrieve
=goal>
ISA is-member
object =obj
category =cat
judgment nil
==>
=goal>
judgment pending
+retrieval>
ISA property
object =obj
attribute category
)
(P direct-verify
=goal>
ISA is-member
object =obj
category =cat
judgment pending
=retrieval>
ISA property
object =obj
attribute category
value =cat
==>
=goal>
judgment yes
)
(P chain-category
=goal>
ISA is-member
object =obj1
category =cat
judgment pending
=retrieval>
ISA property
object =obj1
attribute category
value =obj2
- value =cat
==>
=goal>
object =obj2
+retrieval>
ISA property
object =obj2
attribute category
)
(P fail
=goal>
ISA is-member
object =obj1
category =cat
judgment pending
?retrieval>
buffer failure
==>
=goal>
judgment no
)
(goal-focus g1)
)
| 2,971 | Common Lisp | .lisp | 97 | 26.42268 | 68 | 0.6822 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 69978203058c0af45f5ebc33d1b3d6013c9889d12b0cf619159a8b7bff3afd65 | 14,228 | [
443521
] |
14,229 | broken-addition.lisp | asmaloney_ACT-R/tutorial/unit1/broken-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 eight)
(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)
(test-goal ISA add arg1 zero arg2 zero))
(P initialize-addition
=goal>
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 =num2
summ =answer
==>
=goal>
ISA add
count nil
)
(P increment-sum
=goal>
ISA add
sum =sum
count =count
=retrieval>
ISA number
number =sum
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
next =newsum
==>
=goal>
ISA add
sum =newsum
+retrieval>
ISA number
number =count
)
| 1,713 | Common Lisp | .lisp | 78 | 17.397436 | 43 | 0.544109 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 197c69309d929f02c9455ba30458dbb39344c1fa13f62adadb50597f0ac32323 | 14,229 | [
181482
] |
14,230 | tutor-model-solution.lisp | asmaloney_ACT-R/tutorial/unit1/tutor-model-solution.lisp | (clear-all)
(define-model tutor-model
(sgp :esc t :lf .05 :trace-detail medium)
;; Add Chunk-types here
(chunk-type addition-fact addend1 addend2 sum)
(chunk-type add-pair one1 ten1 one2 ten2 ten-ans one-ans carry)
;; Add Chunks here
(add-dm
(fact17 isa addition-fact addend1 1 addend2 7 sum 8)
(fact34 isa addition-fact addend1 3 addend2 4 sum 7)
(fact67 isa addition-fact addend1 6 addend2 7 sum 13)
(fact103 isa addition-fact addend1 10 addend2 3 sum 13)
(goal isa add-pair ten1 3 one1 6 ten2 4 one2 7))
;; Add productions here
(p start-pair
=goal>
ISA add-pair
one1 =num1
one2 =num2
one-ans nil
==>
=goal>
one-ans busy
+retrieval>
ISA addition-fact
addend1 =num1
addend2 =num2)
(p add-ones
=goal>
ISA add-pair
one-ans busy
one1 =num1
one2 =num2
=retrieval>
ISA addition-fact
addend1 =num1
addend2 =num2
sum =sum
==>
=goal>
one-ans =sum
carry busy
+retrieval>
ISA addition-fact
addend1 10
sum =sum)
(p process-carry
=goal>
ISA add-pair
ten1 =num1
ten2 =num2
carry busy
one-ans =ones
=retrieval>
ISA addition-fact
addend1 10
sum =ones
addend2 =remainder
==>
=goal>
carry 1
ten-ans busy
one-ans =remainder
+retrieval>
ISA addition-fact
addend1 =num1
addend2 =num2)
(p no-carry
=goal>
ISA add-pair
ten1 =num1
ten2 =num2
one-ans =ones
carry busy
?retrieval>
buffer failure
==>
=goal>
carry nil
ten-ans busy
+retrieval>
ISA addition-fact
addend1 =num1
addend2 =num2)
(p add-tens-done
=goal>
ISA add-pair
ten-ans busy
carry nil
=retrieval>
ISA addition-fact
sum =sum
==>
=goal>
ten-ans =sum)
(p add-tens-carry
=goal>
ISA add-pair
carry 1
ten-ans busy
=retrieval>
ISA addition-fact
sum =sum
==>
=goal>
carry nil
+retrieval>
ISA addition-fact
addend1 1
addend2 =sum)
(goal-focus goal)
)
| 1,998 | Common Lisp | .lisp | 112 | 14.017857 | 63 | 0.665238 | asmaloney/ACT-R | 6 | 0 | 0 | LGPL-2.1 | 9/19/2024, 11:27:13 AM (Europe/Amsterdam) | 0ec264862197f53566eaf6d23a042ee7b0d1681cac59a5c483c7ecf895785fd4 | 14,230 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.