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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,096 | funcion-01.lisp | josrr_lisp2js/pruebas/funcion-01.lisp | (defun fibonacci-recursive (n)
(if (< n 2)
n
(+ (fibonacci-recursive (- n 2)) (fibonacci-recursive (- n 1)))))
(defun fibonacci-tail-recursive ( n &optional (a 0) (b 1))
(if (= n 0)
a
(fibonacci-tail-recursive (- n 1) b (+ a b))))
| 260 | Common Lisp | .lisp | 8 | 27.875 | 71 | 0.561753 | josrr/lisp2js | 1 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 89ef0b0a6dd41e4d07c528585f4a4285d19f20b484a8850c17517b546497ff03 | 23,096 | [
-1
] |
23,097 | lisp2js.asd | josrr_lisp2js/lisp2js.asd | ;;;; -*- coding: utf-8-unix; -*-
;;;; Copyright (C) 2016 José Ronquillo Rivera <[email protected]>
;;;; This file is part of lisp2js.
;;;;
;;;; lisp2js is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; lisp2js is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License
;;;; along with lisp2js. If not, see <http://www.gnu.org/licenses/>.
(in-package #:common-lisp-user)
(asdf:defsystem #:lisp2js
:serial t
:description "Utilería para compilar common lisp usando Parenscript."
:author "José Miguel Ronquillo Rivera <[email protected]>"
:license "GPLv3"
:depends-on (:getopt :parenscript)
:components ((:file "lisp2js")))
| 1,090 | Common Lisp | .asd | 24 | 43.708333 | 73 | 0.723845 | josrr/lisp2js | 1 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8562641c97eda364ae3713a4d8d92f4dec923b86aaa626ff0b28e61776233b78 | 23,097 | [
-1
] |
23,118 | alist-plist.lisp | phoe-trash_lispfurc/alist-plist.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package #:lispfurc)
;;;;=========================================================
;;;; (NESTED) ALIST HELPER FUNCTIONS
(defun value (key alist)
"Given an alist and a key, returns a respective value or NIL if it's not found."
(cdr (assoc key alist)))
(defun key (value alist)
"Given an alist and a value, returns a respective key or NIL if it's not found."
(car (rassoc value alist)))
(defun alist-get-diff (alist mdf &optional (test #'eq))
"This function takes two alists and returns the second alist while omitting the keys for
which the two alists have equal value."
(iter (for (key . value) in mdf)
(unless (funcall test (value key alist) (value key mdf))
(collect (cons key (value key mdf))))))
(defun alist-apply-diff (alist mdf)
"This function takes two alists and returns an alist with the same keys as the first and
values that:
* come from the second alist if they exist in it under respective keys,
* come from the first alist otherwise.
No new keys are added to the alist, even if they exist in the second one."
(iter (for (key . value) in alist)
(if (assoc key mdf)
(collect (cons key (value key mdf)))
(collect (cons key value)))))
(defun alist-set-value (alist value keylist &optional (test #'eq))
"This function takes a set of nested alists as first argument, a value, a list of valid
keys in order of nestedness, and returns the same nested alist with the value inserted
at the location pointed by the keylist.
This function will create the necessary alist structure if it doesn't exist in the original
alist. If used with value equal to NIL, this can be used solely to create nested alist
structure.
This function may (and will) change the order of alist elements and remove duplicates."
(if (null keylist)
value
(append (iter (for (key . value) in alist)
(unless (funcall test key (car keylist))
(collect (cons key value))))
(cons (cons (car keylist)
(alist-set-value (value (car keylist) alist)
(cdr keylist) value))
nil))))
(defun alist-get-value (alist keylist)
"This function takes a set of nested alists as first argument, a list of valid keys in
order of nestedness, and returns the value at the end of the keylist.
Returns NIL if the keylist does not match the alist structure."
(if (null keylist)
alist
(alist-get-value (value (car keylist) alist)
(cdr keylist))))
(defun alist-remove (alist keyword &optional (keylist nil) (test #'eq))
"This function, given an alist and a keyword, returns a new alist with the cons holding
a keyword in its car removed.
Optionally, if given a third argument being a list of valid keys in order of nestedness,
this function will return an alist with the cons removed at a given depth.
This function may (and will) change the order of alist elements and remove duplicates."
(if (null keylist)
(iter (for (key . value) in alist)
(unless (funcall test key keyword)
(collect (cons key value))))
(append (iter (for (key . value) in alist)
(unless (funcall test key (car keylist))
(collect (cons key value))))
(cons (cons (car keylist)
(alist-remove (value (car keylist) alist)
keyword (cdr keylist)))
nil))))
(defmacro alist-gen (&rest args)
"This generates an alist based on its arguments list.
If any key has a default value, it gets evaluated and set as the value within the alist.
Otherwise, that key's its value is set to NIL."
(flet ((conser (arg)
(if (consp arg)
(cons (first arg) (eval (second arg)))
(cons arg nil))))
(list 'quote (mapcar #'conser args))))
;;;;=========================================================
;;;; PLIST HELPER FUNCTIONS
(defun string=-getf (plist indicator)
"This is a version of getf utilizing string= for comparison. Given a plist and a key, returns
a value."
(loop for key in plist by #'cddr
for value in (rest plist) by #'cddr
when (string= key indicator)
return value))
(defun string=-getf-key (plist indicator)
"This is a version of getf utilizing string= for comparison. Given a plist and a value,
returns a key."
(loop for key in plist by #'cddr
for value in (rest plist) by #'cddr
when (string= value indicator)
return key))
| 4,527 | Common Lisp | .lisp | 99 | 42.060606 | 95 | 0.67196 | phoe-trash/lispfurc | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 7a0e08e9d5a59d05d8373e9010e5e5eb5010b72f4ba64676b3fed52b13b2d403 | 23,118 | [
-1
] |
23,119 | color-code.lisp | phoe-trash_lispfurc/color-code.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package #:lispfurc)
;;;;=========================================================
;;;; COLOR CODE HELPER FUNCTIONS
(let
((color-table-1 ;; Used for fur and markings.
'((0 "Cat Gray" (#(147 135 135) #(135 123 123) #(119 107 107) #(107 95 95) #(91 79 79) #(79 67 67) #(63 55 55) #(51 43 43)))
(1 "Arctic" (#(219 223 247) #(199 203 231) #(179 187 219) #(163 171 207) #(143 151 187) #(123 131 167) #(103 115 151) #(51 39 99)))
(2 "Black" (#(79 67 67) #(79 67 67) #(63 55 55) #(63 55 55) #(51 43 43) #(51 43 43) #(23 19 19) #(23 19 19)))
(3 "Mule Tan" (#(159 147 139) #(147 135 127) #(135 123 115) #(123 111 103) #(115 103 95) #(103 91 83) #(91 79 71) #(83 71 63)))
(4 "Dust" (#(155 143 99) #(139 127 87) #(127 115 75) #(115 103 67) #(103 91 55) #(91 79 47) #(79 67 39) #(67 55 31)))
(5 "Chocolate" (#(147 87 87) #(135 75 75) #(123 63 63) #(111 51 51) #(99 43 43) #(87 31 31) #(75 23 23) #(63 19 19)))
(6 "Lavender" (#(239 231 243) #(231 219 235) #(207 191 215) #(183 163 195) #(163 135 175) #(143 111 155) #(123 91 135) #(103 71 115)))
(7 "Wolf Gray" (#(251 211 255) #(235 187 235) #(215 163 207) #(195 143 183) #(179 123 159) #(159 103 135) #(139 87 111) #(123 71 91)))
(8 "Fox Orange" (#(255 227 207) #(247 195 155) #(243 163 107) #(235 135 63) #(211 111 39) #(187 91 23) #(163 71 7) #(139 55 0)))
(9 "Horse Brown" (#(231 211 215) #(211 163 175) #(191 123 135) #(171 91 103) #(151 59 75) #(131 35 47) #(115 15 27) #(95 0 11)))
(10 "Tawny" (#(219 183 163) #(207 163 135) #(195 143 111) #(183 119 79) #(163 107 79) #(143 95 79) #(135 75 75) #(147 87 87)))
(11 "Mocha" (#(219 187 187) #(207 167 167) #(183 135 135) #(171 119 119) #(159 103 103) #(147 87 87) #(135 75 75) #(111 51 51)))
(12 "Ruddy" (#(247 195 155) #(243 163 107) #(235 135 63) #(211 111 39) #(187 91 23) #(199 23 23) #(163 71 7) #(151 59 75)))
(13 "Cream" (#(239 235 203) #(227 223 187) #(215 207 171) #(203 195 155) #(191 179 139) #(179 167 127) #(195 151 151) #(171 119 119)))
(14 "Yellow" (#(255 251 235) #(251 235 183) #(247 223 135) #(243 215 91) #(219 187 71) #(199 159 51) #(175 135 39) #(155 111 27)))
(15 "Grass Green" (#(131 195 115) #(111 175 91) #(95 155 67) #(79 139 47) #(63 119 31) #(51 99 19) #(43 83 11) #(39 71 7)))
(16 "Burgundy" (#(255 175 195) #(239 127 159) #(227 79 127) #(211 39 103) #(199 7 83) #(171 7 71) #(143 11 63) #(111 7 47)))
(17 "Pinewood" (#(247 231 231) #(235 207 207) #(219 187 187) #(195 151 151) #(171 119 119) #(147 87 87) #(135 75 75) #(123 63 63)))
(18 "Sea Blue" (#(235 243 255) #(183 203 231) #(143 171 207) #(103 139 187) #(71 111 163) #(43 87 143) #(23 67 119) #(7 51 99)))
(19 "Violet" (#(235 215 243) #(207 167 223) #(183 127 203) #(163 91 183) #(147 63 167) #(127 35 147) #(111 15 127) #(95 0 111)))
(20 "Red" (#(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39) #(199 23 23) #(171 11 11) #(143 7 7) #(99 0 0)))
(21 "White" (#(255 255 255) #(247 247 247) #(243 239 235) #(231 227 227) #(219 211 211) #(195 183 179) #(159 147 139) #(123 111 103)))
(22 "Navy" (#(211 199 223) #(179 163 203) #(151 131 183) #(123 103 163) #(99 79 143) #(83 67 131) #(63 47 111) #(43 31 91)))
(23 "Cloudy Gray" (#(203 195 195) #(191 179 179) #(175 167 167) #(163 151 151) #(147 135 135) #(135 123 123) #(119 107 107) #(107 95 95)))
(24 "Royal Blue" (#(139 191 243) #(119 147 247) #(103 99 255) #(75 71 227) #(47 47 199) #(27 27 175) #(11 11 147) #(0 0 123)))) )
(color-table-2 ;; Used for hair.
'((0 "Blood Red" (#(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11) #(143 7 7) #(143 7 7) #(99 0 0) #(99 0 0)))
(1 "Courage Red" (#(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39) #(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11)))
(2 "Merry Red" (#(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39)))
(3 "Ember Orange" (#(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(255 95 27) #(255 95 27) #(187 91 23) #(187 91 23)))
(4 "Hearty Brown" (#(171 7 71) #(171 7 71) #(143 11 63) #(143 11 63) #(111 7 47) #(111 7 47) #(75 23 23) #(75 23 23)))
(5 "Burnt Orange" (#(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7) #(139 55 0) #(139 55 0) #(111 51 51) #(111 51 51)))
(6 "Busy Orange" (#(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39) #(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7)))
(7 "August Orange" (#(247 195 155) #(247 195 155) #(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39)))
(8 "Noble Brown" (#(171 111 79) #(171 111 79) #(155 103 79) #(155 103 79) #(147 95 79) #(147 95 79) #(123 63 63) #(123 63 63)))
(9 "Mahogany" (#(171 91 103) #(171 91 103) #(151 59 75) #(151 59 75) #(131 35 47) #(131 35 47) #(115 15 27) #(115 15 27)))
(10 "Clever Maize" (#(199 159 51) #(199 159 51) #(175 135 39) #(175 135 39) #(155 111 27) #(155 111 27) #(107 95 19) #(107 95 19)))
(11 "Pure Gold" (#(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135) #(243 215 91) #(243 215 91) #(219 187 71) #(219 187 71)))
(12 "Moon Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135)))
(13 "Sun Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(255 239 7) #(255 239 7) #(219 187 71) #(219 187 71)))
(14 "Tan" (#(183 195 115) #(183 195 115) #(175 151 79) #(175 151 79) #(175 151 79) #(175 151 79) #(159 139 63) #(159 139 63)))
(15 "Woodland Green" (#(95 143 47) #(95 143 47) #(79 123 31) #(79 123 31) #(67 103 19) #(67 103 19) #(55 83 11) #(55 83 11)))
(16 "Friendly Green" (#(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67) #(79 139 47) #(79 139 47) #(63 119 31) #(63 119 31)))
(17 "Lucky Green" (#(163 223 131) #(163 223 131) #(131 195 115) #(131 195 115) #(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67)))
(18 "Travelers Green" (#(163 223 131) #(163 223 131) #(163 223 131) #(163 223 131) #(151 215 11) #(151 215 11) #(123 183 83) #(123 183 83)))
(19 "Aquacyan" (#(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(71 111 163) #(71 111 163)))
(20 "Deepsea Blue" (#(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119) #(7 51 99) #(7 51 99)))
(21 "Proud Blue" (#(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119)))
(22 "Lightsky Blue" (#(183 203 231) #(183 203 231) #(143 171 207) #(143 171 207) #(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163)))
(23 "Syndira Blue" (#(103 99 255) #(103 99 255) #(0 0 0) #(0 0 0) #(0 0 0) #(0 0 0) #(47 47 199) #(47 47 199)))
(24 "Straight Blue" (#(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147) #(0 0 123) #(0 0 123)))
(25 "Royal Purple" (#(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147) #(111 15 127) #(111 15 127) #(63 55 55) #(63 55 55)))
(26 "Lonely Orchid" (#(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183) #(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147)))
(27 "Spiritual Purple" (#(235 215 243) #(235 215 243) #(207 167 223) #(207 167 223) #(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183)))
(28 "Mad Green" (#(243 239 159) #(243 239 159) #(151 215 11) #(151 215 11) #(151 215 11) #(151 215 11) #(107 163 63) #(107 163 63)))
(29 "Royal Blue" (#(75 71 227) #(75 71 227) #(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147)))
(30 "Passion" (#(211 39 103) #(211 39 103) #(199 7 83) #(199 7 83) #(171 7 71) #(171 7 71) #(143 11 63) #(143 11 63)))
(31 "Bliss Red" (#(239 127 159) #(239 127 159) #(227 79 127) #(227 79 127) #(211 39 103) #(211 39 103) #(199 7 83) #(199 7 83)))
(32 "Blush Pink" (#(255 227 207) #(255 227 207) #(255 175 195) #(255 175 195) #(239 127 159) #(239 127 159) #(227 79 127) #(227 79 127)))
(33 "Twilight Sigh" (#(235 187 235) #(235 187 235) #(215 163 207) #(215 163 207) #(195 143 183) #(195 143 183) #(179 123 159) #(179 123 159)))
(34 "Dreamer Blue" (#(103 99 255) #(103 99 255) #(103 99 255) #(103 99 255) #(75 71 227) #(75 71 227) #(47 47 199) #(47 47 199)))
(35 "Shadow Gray" (#(143 111 155) #(143 111 155) #(123 91 135) #(123 91 135) #(103 71 115) #(103 71 115) #(79 67 67) #(79 67 67)))
(36 "Neutral Gray" (#(163 135 175) #(163 135 175) #(143 111 155) #(143 111 155) #(123 91 135) #(123 91 135) #(103 71 115) #(103 71 115)))
(37 "Tragic Gray" (#(183 163 195) #(183 163 195) #(163 135 175) #(163 135 175) #(143 111 155) #(143 111 155) #(123 91 135) #(123 91 135)))
(38 "Winter Gray" (#(203 199 239) #(203 199 239) #(175 171 223) #(175 171 223) #(151 143 207) #(151 143 207) #(135 115 191) #(135 115 191)))
(39 "Indigo" (#(63 47 111) #(63 47 111) #(51 39 99) #(51 39 99) #(43 31 91) #(43 31 91) #(43 31 91) #(43 31 91)))
(40 "Black" (#(135 123 123) #(135 123 123) #(107 95 95) #(107 95 95) #(79 67 67) #(79 67 67) #(63 55 55) #(63 55 55)))
(41 "Cloudy Gray" (#(203 195 195) #(203 195 195) #(175 167 167) #(175 167 167) #(163 151 151) #(163 151 151) #(135 123 123) #(135 123 123)))
(42 "White" (#(255 255 255) #(255 255 255) #(243 239 235) #(243 239 235) #(219 211 211) #(219 211 211) #(159 147 139) #(159 147 139)))
(43 "Pinewood" (#(247 231 231) #(247 231 231) #(219 187 187) #(219 187 187) #(171 119 119) #(171 119 119) #(135 75 75) #(135 75 75)))
(44 "Green Yellow" (#(255 255 255) #(255 255 255) #(219 231 211) #(219 231 211) #(187 207 171) #(187 207 171) #(155 183 139) #(155 183 139)))))
(color-table-3 ;; Used for eyes.
'((0 "Blood Red" (#(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11) #(143 7 7) #(143 7 7) #(99 0 0) #(99 0 0)))
(1 "Courage Red" (#(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39) #(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11)))
(2 "Merry Red" (#(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39)))
(3 "Ember Orange" (#(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(255 95 27) #(255 95 27) #(187 91 23) #(187 91 23)))
(4 "Hearty Brown" (#(171 7 71) #(171 7 71) #(143 11 63) #(143 11 63) #(111 7 47) #(111 7 47) #(75 23 23) #(75 23 23)))
(5 "Burnt Orange" (#(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7) #(139 55 0) #(139 55 0) #(111 51 51) #(111 51 51)))
(6 "Busy Orange" (#(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39) #(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7)))
(7 "August Orange" (#(247 195 155) #(247 195 155) #(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39)))
(8 "Noble Brown" (#(171 111 79) #(171 111 79) #(155 103 79) #(155 103 79) #(147 95 79) #(147 95 79) #(123 63 63) #(123 63 63)))
(9 "Mahogany" (#(171 91 103) #(171 91 103) #(151 59 75) #(151 59 75) #(131 35 47) #(131 35 47) #(115 15 27) #(115 15 27)))
(10 "Clever Maize" (#(199 159 51) #(199 159 51) #(175 135 39) #(175 135 39) #(155 111 27) #(155 111 27) #(107 95 19) #(107 95 19)))
(11 "Pure Gold" (#(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135) #(243 215 91) #(243 215 91) #(219 187 71) #(219 187 71)))
(12 "Moon Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135)))
(13 "Sun Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(255 239 7) #(255 239 7) #(219 187 71) #(219 187 71)))
(14 "Tan" (#(183 195 115) #(183 195 115) #(175 151 79) #(175 151 79) #(175 151 79) #(175 151 79) #(159 139 63) #(159 139 63)))
(15 "Woodland Green" (#(95 143 47) #(95 143 47) #(79 123 31) #(79 123 31) #(67 103 19) #(67 103 19) #(55 83 11) #(55 83 11)))
(16 "Friendly Green" (#(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67) #(79 139 47) #(79 139 47) #(63 119 31) #(63 119 31)))
(17 "Lucky Green" (#(163 223 131) #(163 223 131) #(131 195 115) #(131 195 115) #(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67)))
(18 "Travelers Green" (#(163 223 131) #(163 223 131) #(163 223 131) #(163 223 131) #(151 215 11) #(151 215 11) #(123 183 83) #(123 183 83)))
(19 "Aquacyan" (#(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(71 111 163) #(71 111 163)))
(20 "Deepsea Blue" (#(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119) #(7 51 99) #(7 51 99)))
(21 "Proud Blue" (#(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119)))
(22 "Lightsky Blue" (#(183 203 231) #(183 203 231) #(143 171 207) #(143 171 207) #(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163)))
(23 "Syndira Blue" (#(103 99 255) #(103 99 255) #(0 0 0) #(0 0 0) #(0 0 0) #(0 0 0) #(47 47 199) #(47 47 199)))
(24 "Straight Blue" (#(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147) #(0 0 123) #(0 0 123)))
(25 "Royal Purple" (#(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147) #(111 15 127) #(111 15 127) #(63 55 55) #(63 55 55)))
(26 "Lonely Orchid" (#(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183) #(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147)))
(27 "Spiritual Purple" (#(235 215 243) #(235 215 243) #(207 167 223) #(207 167 223) #(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183)))
(28 "Mad Green" (#(243 239 159) #(243 239 159) #(151 215 11) #(151 215 11) #(151 215 11) #(151 215 11) #(107 163 63) #(107 163 63)))
(29 "Royal Blue" (#(75 71 227) #(75 71 227) #(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147)))))
(color-table-4 ;; Used for badge.
'((0 "Blood Red" (#(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11) #(143 7 7) #(143 7 7) #(99 0 0) #(99 0 0)))
(1 "Courage Red" (#(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39) #(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11)))
(2 "Merry Red" (#(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39)))
(3 "Ember Orange" (#(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(255 95 27) #(255 95 27) #(187 91 23) #(187 91 23)))
(4 "Hearty Brown" (#(171 7 71) #(171 7 71) #(143 11 63) #(143 11 63) #(111 7 47) #(111 7 47) #(75 23 23) #(75 23 23)))
(5 "Burnt Orange" (#(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7) #(139 55 0) #(139 55 0) #(111 51 51) #(111 51 51)))
(6 "Busy Orange" (#(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39) #(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7)))
(7 "August Orange" (#(247 195 155) #(247 195 155) #(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39)))
(8 "Noble Brown" (#(171 111 79) #(171 111 79) #(155 103 79) #(155 103 79) #(147 95 79) #(147 95 79) #(123 63 63) #(123 63 63)))
(9 "Mahogany" (#(171 91 103) #(171 91 103) #(151 59 75) #(151 59 75) #(131 35 47) #(131 35 47) #(115 15 27) #(115 15 27)))
(10 "Clever Maize" (#(199 159 51) #(199 159 51) #(175 135 39) #(175 135 39) #(155 111 27) #(155 111 27) #(107 95 19) #(107 95 19)))
(11 "Pure Gold" (#(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135) #(243 215 91) #(243 215 91) #(219 187 71) #(219 187 71)))
(12 "Moon Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135)))
(13 "Sun Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(255 239 7) #(255 239 7) #(219 187 71) #(219 187 71)))
(14 "Tan" (#(183 195 115) #(183 195 115) #(175 151 79) #(175 151 79) #(175 151 79) #(175 151 79) #(159 139 63) #(159 139 63)))
(15 "Woodland Green" (#(95 143 47) #(95 143 47) #(79 123 31) #(79 123 31) #(67 103 19) #(67 103 19) #(55 83 11) #(55 83 11)))
(16 "Friendly Green" (#(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67) #(79 139 47) #(79 139 47) #(63 119 31) #(63 119 31)))
(17 "Lucky Green" (#(163 223 131) #(163 223 131) #(131 195 115) #(131 195 115) #(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67)))
(18 "Travelers Green" (#(163 223 131) #(163 223 131) #(163 223 131) #(163 223 131) #(151 215 11) #(151 215 11) #(123 183 83) #(123 183 83)))
(19 "Aquacyan" (#(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(71 111 163) #(71 111 163)))
(20 "Deepsea Blue" (#(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119) #(7 51 99) #(7 51 99)))
(21 "Proud Blue" (#(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119)))
(22 "Lightsky Blue" (#(183 203 231) #(183 203 231) #(143 171 207) #(143 171 207) #(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163)))
(23 "Syndira Blue" (#(103 99 255) #(103 99 255) #(0 0 0) #(0 0 0) #(0 0 0) #(0 0 0) #(47 47 199) #(47 47 199)))
(24 "Straight Blue" (#(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147) #(0 0 123) #(0 0 123)))
(25 "Royal Purple" (#(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147) #(111 15 127) #(111 15 127) #(63 55 55) #(63 55 55)))
(26 "Lonely Orchid" (#(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183) #(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147)))
(27 "Spiritual Purple" (#(235 215 243) #(235 215 243) #(207 167 223) #(207 167 223) #(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183)))
(28 "Mad Green" (#(243 239 159) #(243 239 159) #(151 215 11) #(151 215 11) #(151 215 11) #(151 215 11) #(107 163 63) #(107 163 63)))
(29 "Royal Blue" (#(75 71 227) #(75 71 227) #(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147)))
(30 "Passion" (#(211 39 103) #(211 39 103) #(199 7 83) #(199 7 83) #(171 7 71) #(171 7 71) #(143 11 63) #(143 11 63)))
(31 "Bliss Red" (#(239 127 159) #(239 127 159) #(227 79 127) #(227 79 127) #(211 39 103) #(211 39 103) #(199 7 83) #(199 7 83)))
(32 "Blush Pink" (#(255 227 207) #(255 227 207) #(255 175 195) #(255 175 195) #(239 127 159) #(239 127 159) #(227 79 127) #(227 79 127)))
(33 "Twilight Sigh" (#(235 187 235) #(235 187 235) #(215 163 207) #(215 163 207) #(195 143 183) #(195 143 183) #(179 123 159) #(179 123 159)))
(34 "Dreamer Blue" (#(103 99 255) #(103 99 255) #(103 99 255) #(103 99 255) #(75 71 227) #(75 71 227) #(47 47 199) #(47 47 199)))
(35 "Shadow Gray" (#(143 111 155) #(143 111 155) #(123 91 135) #(123 91 135) #(103 71 115) #(103 71 115) #(79 67 67) #(79 67 67)))
(36 "Neutral Gray" (#(163 135 175) #(163 135 175) #(143 111 155) #(143 111 155) #(123 91 135) #(123 91 135) #(103 71 115) #(103 71 115)))
(37 "Tragic Gray" (#(183 163 195) #(183 163 195) #(163 135 175) #(163 135 175) #(143 111 155) #(143 111 155) #(123 91 135) #(123 91 135)))
(38 "Winter Gray" (#(203 199 239) #(203 199 239) #(175 171 223) #(175 171 223) #(151 143 207) #(151 143 207) #(135 115 191) #(135 115 191)))
(39 "Indigo" (#(63 47 111) #(63 47 111) #(51 39 99) #(51 39 99) #(43 31 91) #(43 31 91) #(43 31 91) #(43 31 91)))))
(color-table-5 ;; Used for vest, bracers, cape, boots and trousers.
'((0 "Blood Red" (#(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11) #(143 7 7) #(143 7 7) #(99 0 0) #(99 0 0)))
(1 "Courage Red" (#(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39) #(199 23 23) #(199 23 23) #(171 11 11) #(171 11 11)))
(2 "Merry Red" (#(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(255 55 55) #(227 39 39) #(227 39 39)))
(3 "Ember Orange" (#(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(255 95 27) #(255 95 27) #(187 91 23) #(187 91 23)))
(4 "Hearty Brown" (#(171 7 71) #(171 7 71) #(143 11 63) #(143 11 63) #(111 7 47) #(111 7 47) #(75 23 23) #(75 23 23)))
(5 "Burnt Orange" (#(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7) #(139 55 0) #(139 55 0) #(111 51 51) #(111 51 51)))
(6 "Busy Orange" (#(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39) #(187 91 23) #(187 91 23) #(163 71 7) #(163 71 7)))
(7 "August Orange" (#(247 195 155) #(247 195 155) #(243 163 107) #(243 163 107) #(235 135 63) #(235 135 63) #(211 111 39) #(211 111 39)))
(8 "Noble Brown" (#(171 111 79) #(171 111 79) #(155 103 79) #(155 103 79) #(147 95 79) #(147 95 79) #(123 63 63) #(123 63 63)))
(9 "Mahogany" (#(171 91 103) #(171 91 103) #(151 59 75) #(151 59 75) #(131 35 47) #(131 35 47) #(115 15 27) #(115 15 27)))
(10 "Clever Maize" (#(199 159 51) #(199 159 51) #(175 135 39) #(175 135 39) #(155 111 27) #(155 111 27) #(107 95 19) #(107 95 19)))
(11 "Pure Gold" (#(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135) #(243 215 91) #(243 215 91) #(219 187 71) #(219 187 71)))
(12 "Moon Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(251 235 183) #(251 235 183) #(247 223 135) #(247 223 135)))
(13 "Sun Yellow" (#(255 251 235) #(255 251 235) #(251 235 183) #(251 235 183) #(255 239 7) #(255 239 7) #(219 187 71) #(219 187 71)))
(14 "Tan" (#(183 195 115) #(183 195 115) #(175 151 79) #(175 151 79) #(175 151 79) #(175 151 79) #(159 139 63) #(159 139 63)))
(15 "Woodland Green" (#(95 143 47) #(95 143 47) #(79 123 31) #(79 123 31) #(67 103 19) #(67 103 19) #(55 83 11) #(55 83 11)))
(16 "Friendly Green" (#(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67) #(79 139 47) #(79 139 47) #(63 119 31) #(63 119 31)))
(17 "Lucky Green" (#(163 223 131) #(163 223 131) #(131 195 115) #(131 195 115) #(111 175 91) #(111 175 91) #(95 155 67) #(95 155 67)))
(18 "Travelers Green" (#(163 223 131) #(163 223 131) #(163 223 131) #(163 223 131) #(151 215 11) #(151 215 11) #(123 183 83) #(123 183 83)))
(19 "Aquacyan" (#(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(0 135 139) #(71 111 163) #(71 111 163)))
(20 "Deepsea Blue" (#(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119) #(7 51 99) #(7 51 99)))
(21 "Proud Blue" (#(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163) #(43 87 143) #(43 87 143) #(23 67 119) #(23 67 119)))
(22 "Lightsky Blue" (#(183 203 231) #(183 203 231) #(143 171 207) #(143 171 207) #(103 139 187) #(103 139 187) #(71 111 163) #(71 111 163)))
(23 "Syndira Blue" (#(103 99 255) #(103 99 255) #(0 0 0) #(0 0 0) #(0 0 0) #(0 0 0) #(47 47 199) #(47 47 199)))
(24 "Straight Blue" (#(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147) #(0 0 123) #(0 0 123)))
(25 "Royal Purple" (#(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147) #(111 15 127) #(111 15 127) #(63 55 55) #(63 55 55)))
(26 "Lonely Orchid" (#(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183) #(147 63 167) #(147 63 167) #(127 35 147) #(127 35 147)))
(27 "Spiritual Purple" (#(235 215 243) #(235 215 243) #(207 167 223) #(207 167 223) #(183 127 203) #(183 127 203) #(163 91 183) #(163 91 183)))
(28 "Mad Green" (#(243 239 159) #(243 239 159) #(151 215 11) #(151 215 11) #(151 215 11) #(151 215 11) #(107 163 63) #(107 163 63)))
(29 "Royal Blue" (#(75 71 227) #(75 71 227) #(47 47 199) #(47 47 199) #(27 27 175) #(27 27 175) #(11 11 147) #(11 11 147))))))
(flet
((color-table (keyword)
(case keyword
((:fur :markings) color-table-1)
(:hair color-table-2)
(:eyes color-table-3)
(:badge color-table-4)
((:vest :bracers :cape :boots :trousers) color-table-5)
(otherwise (error "Keyword not matching any of:
:FUR :MARKINGS :HAIR :EYES :BADGE :VEST :BRACERS :CAPE :BOOTS :TROUSERS")))))
(defun color-string-char (keyword string)
"This, given a keyword designating a color-code slot and a color name, returns a proper
character for the color code."
(check-type string string)
(check-type keyword keyword)
(iterate (for color in (color-table keyword))
(when (string= string (second color))
(return (coerce (to-220 (first color)) 'character)))))
(defun color-char-string (keyword char)
"This, given a keyword designating a color-code slot and a character for the color code,
returns a proper color name."
(check-type char character)
(check-type keyword keyword)
(iterate (for color in (color-table keyword))
(when (eq (from-220 (string char)) (first color))
(return (second color)))))))
| 24,073 | Common Lisp | .lisp | 212 | 110.811321 | 144 | 0.559082 | phoe-trash/lispfurc | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a0e2c6316caa842595f06477a236cbb730e8b59dfe8009bec35bd5c2f539ff73 | 23,119 | [
-1
] |
23,120 | structure.lisp | phoe-trash_lispfurc/structure.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package #:lispfurc)
;;;;=========================================================
;;;; STRUCTURE
(defmacro define-alist (name &body body)
"This macro, given a SYMBOL, creates a EMPTY-SYMBOL function that generates an alist based
on the rest of arguments given to this macro (it calls ALIST-GEN internally) and
a NEW-SYMBOL macro that allows you to non-destructively modify the alist generated by
EMPTY-SYMBOL, as it calls ALIST-APPLY-DIFF on EMPTY-SYMBOL and the list of arguments you pass
to the macro."
(check-type name string-designator)
(let ((empty-name (intern (concatenate 'string "EMPTY-" (string name))))
(new-name (intern (concatenate 'string "NEW-" (string name)))))
`(progn
(defun ,empty-name ()
(alist-gen ,@body))
(defmacro ,new-name (&body args)
`(alist-apply-diff ',(funcall (symbol-function ',empty-name))
(plist-alist (list ,@args))))
t)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-alist position
:coords :facing :stance)
(define-alist dream
:dreamname)
(define-alist connection
:host :port :socket
:stream :login :password)
(define-alist furre
:name :desc
(:position (empty-position))
:portrait :species :gender
:fur :markings :hair
:eyes :badge :cape
:bracers :trousers :boots)
(define-alist furres-list
(:dummyfurre1 (empty-furre))
(:dummyfurre2 (empty-furre))
(:dummyfurre3 (empty-furre)))
(define-alist empty-state
(:connection (empty-connection))
(:furres (empty-furres-list))
(:dream (empty-dream))
:outputs))
| 1,853 | Common Lisp | .lisp | 50 | 33.52 | 93 | 0.61423 | phoe-trash/lispfurc | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 94919b1802a7bb5b8a3366e8ae4707b5d12f86d99c7811a866aabb9781e76e58 | 23,120 | [
-1
] |
23,121 | base-220-95.lisp | phoe-trash_lispfurc/base-220-95.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package #:lispfurc)
;;;;=========================================================
;;;; FURCADIA BASE-220 AND BASE-95 CONVERSION
(labels
((cut-last (string)
(if (equal "" string)
(values "" nil)
(values (subseq string 0 (1- (length string)))
(aref string (1- (length string))))))
(rec (num base off)
(if (eq num 0)
nil
(append (rec (floor num base) base off)
(list (code-char (+ off (nth-value 1 (floor num base)))))))))
(defun from-220 (string)
"This converts a number from Furcaida's base-220 to integer."
(if (equal "" string)
0
(+ (- (char-int (nth-value 1 (cut-last string))) 35)
(* 220 (from-220 (nth-value 0 (cut-last string)))))))
(defun to-220 (num)
"This converts a number from integer to Furcaida's base-220."
(if (null (rec num 220 35))
"#"
(concatenate 'string (rec num 220 35))))
(defun from-95 (string)
"This converts a number from Furcaida's base-95 to integer."
(if (equal "" string)
0
(+ (- (char-int (nth-value 1 (cut-last string))) 32)
(* 95 (from-95 (nth-value 0 (cut-last string)))))))
(defun to-95 (num)
"This converts a number from integer to Furcaida's base-95."
(if (null (rec num 95 32))
"#"
(concatenate 'string (rec num 95 32)))))
| 1,513 | Common Lisp | .lisp | 43 | 31.488372 | 66 | 0.545579 | phoe-trash/lispfurc | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 9c4dfe517fb9aa72cfcfa9ec46595d39c7c5941369389d16d44702cc1dcb63b0 | 23,121 | [
-1
] |
23,141 | package.lisp | phoe-trash_lispfurcproxy/package.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurcProxy
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(defpackage #:lispfurcproxy
(:use #:cl
#:bordeaux-threads
#:usocket
#:iterate
#:external-program
#:bordeaux-threads
#:trivial-garbage))
| 384 | Common Lisp | .lisp | 15 | 24 | 59 | 0.480978 | phoe-trash/lispfurcproxy | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 090f1c4ce680e13c10f9094135939aa408f8f2f5010f930201ca74e5801935cf | 23,141 | [
-1
] |
23,142 | lispfurcproxy.lisp | phoe-trash_lispfurcproxy/lispfurcproxy.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurcProxy
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package #:lispfurcproxy)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; HELPER FUNCTIONS
(defun value (key alist)
(cdr (assoc key alist)))
(defun config-value (key state)
(cdr (assoc key (value :config state))))
(defun key (value alist)
(car (rassoc value alist)))
(defun get-unix-time ()
(- (get-universal-time) 2208988800))
;; a tiny shortcutter for usocket features
(defmacro socket-accept-wait (&body body)
`(socket-accept (wait-for-input ,@body)))
(defun make-server-socket (config)
(socket-listen "127.0.0.1" (value :local-port config)
:element-type '(unsigned-byte 8)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; MAIN FUNCTIONS
(let (server-socket quit-main)
(defun main (&key (config (make-config)))
(if server-socket (socket-close server-socket))
(setf quit-main nil
server-socket (make-server-socket config))
(unwind-protect
(iter (with x = 0) (until quit-main)
(for socket = (socket-accept-wait server-socket :timeout 1))
(when socket (make-thread (lambda () (proxy config socket))
:name (format nil "LispFurcProxy ~D (~D)"
(incf x) (get-unix-time)))))
(kill server-socket)))
(defun quit-main ()
(setf quit-main t)))
(defun proxy (config accepted-socket)
()
(let ((init-state (initial-state config accepted-socket)))
(unwind-protect (loop until (quit-p state)
for input = nil then (input state)
for state = init-state then (program state input)
do (output state))
(kill-state init-state))))
(defun kill-state (state)
(kill (value :server-reader state))
(kill (value :client-reader state)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; STATE FUNCTIONS
(defun initial-state (config client-socket)
(let* ((server-socket (socket-connect (value :host config)
(value :port config)
:element-type '(unsigned-byte 8)))
(client-reader (make-instance 'socket-reader :socket client-socket))
(server-reader (make-instance 'socket-reader :socket server-socket)))
(list (cons :client-reader client-reader)
(cons :server-reader server-reader)
(cons :config config)
(cons :output nil)
(cons :gc-counter (value :times-until-gc config)))))
(defun program (state input)
(list (assoc :client-reader state)
(assoc :server-reader state)
(assoc :config state)
(cons :output (program-output input))
(cons :gc-counter (program-gc-counter state))))
(defun program-output (input)
(cond ((eq (car input) :client)
(cons :client (parse-client-speak (cdr input))))
((eq (car input) :server)
(cons :server (parse-server-speak (cdr input))))))
(defun program-gc-counter (state)
(cond
((< (value :gc-counter state) 0)
(gc :full t)
(config-value :times-until-gc state))
(t
(1- (value :gc-counter state)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; INPUT FUNCTIONS
(defun input (state)
(unless (null state)
(loop
(cond
((is-unread (value :server-reader state))
(return (cons :server (get-line (value :server-reader state)))))
((is-unread (value :client-reader state))
(return (cons :client (get-line (value :client-reader state)))))
(t
(sleep 0.05))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; PARSER FUNCTIONS
(defun parse-client-speak (string)
string)
(defun parse-server-speak (string)
string)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; OUTPUT FUNCTIONS
(defun output-type (output)
(cond ((eq (car output) :server) "SERVER >>(())")
((eq (car output) :client) "(())<< CLIENT")))
(defun output-to-repl (output)
(format t "(~A) " (output-type output))
(format t "~S~%" (cdr output)))
(defun output (state)
(let* ((output (value :output state))
(reader (case (car output)
(:client (value :server-reader state))
(:server (value :client-reader state))))
(string (cdr output)))
(unless (or (null string)
(string= "" string))
(output-to-repl (value :output state))
(send-line (format-charlist (string-charlist string)) reader))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; QUIT FUNCTIONS
(defun quit-p (state)
(unless (null state)
(or (is-dead (value :client-reader state))
(is-dead (value :server-reader state)))))
| 4,591 | Common Lisp | .lisp | 124 | 33.524194 | 71 | 0.589986 | phoe-trash/lispfurcproxy | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | ce4654477104b2f01e18c7d905aa80fe3d067c2209a6c08ffda937fbcebbda81 | 23,142 | [
-1
] |
23,143 | config.lisp | phoe-trash_lispfurcproxy/config.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurcProxy
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package #:lispfurcproxy)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; CONFIG FUNCTIONS
(defun make-config (&key
(local-port 65012)
(host "lightbringer.furcadia.com")
(port 22)
(times-until-gc 200))
(list (cons :local-port local-port)
(cons :host host)
(cons :port port)
(cons :times-until-gc times-until-gc)))
| 613 | Common Lisp | .lisp | 19 | 29.157895 | 59 | 0.458545 | phoe-trash/lispfurcproxy | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 4bc5341d8a9eefdf17bf5e095fcab6f1d5a247895acdf6de0e798f22e8eba8c8 | 23,143 | [
-1
] |
23,144 | socket-reader.lisp | phoe-trash_lispfurcproxy/socket-reader.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; LispFurcProxy
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Copyright 2015, Michal "phoe" Herda.
;;;;
;;;; The whole project is licensed under GPLv3.
;;;;
(in-package :lispfurcproxy)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; SOCKET READER CLASS
(defclass socket-reader ()
((socket :initarg :socket
:initform (error "No :SOCKET argument provided."))
stream
(first-unread :accessor is-unread)
thread
lock))
(defgeneric is-dead (socket-reader))
(defgeneric kill (object))
(defgeneric get-line (socket-reader))
(defgeneric send-line (string socket-reader))
(defmethod initialize-instance :after ((reader socket-reader) &key)
(with-slots (socket stream thread first-unread lock) reader
(labels ((reader-loop ()
(iter (for (values line err) = (ignore-errors (read-line stream nil :eof)))
(until (or (typep err 'error)
(eq line :eof)
(is-dead reader)))
(with-lock-held (lock)
(setf first-unread (append first-unread (list line)))))))
(setf first-unread nil
lock (make-lock)
stream (flex:make-flexi-stream (socket-stream socket)
:element-type '(unsigned-byte 8)
:external-format (flex:make-external-format
:iso-8859-1 :eol-style :lf))
thread (make-thread #'reader-loop
:name "LispFurcProxy socket reader")))))
(defmethod is-dead ((reader socket-reader))
(with-slots (thread) reader
(not (thread-alive-p thread))))
(defmethod kill ((reader socket-reader))
(with-slots (stream socket) reader
(ignore-errors
(close stream)
(socket-close socket))))
(defmethod kill ((socket usocket))
(ignore-errors
(socket-close socket)))
(defmethod get-line ((reader socket-reader))
(with-slots (first-unread lock) reader
(with-lock-held (lock)
(let ((line (car first-unread)))
(setf first-unread (cdr first-unread))
line))))
(defmethod send-line (string (reader socket-reader))
(with-slots (stream) reader
(ignore-errors
(format stream "~A" string)
(terpri stream)
(force-output stream))))
| 2,165 | Common Lisp | .lisp | 61 | 31.311475 | 83 | 0.622254 | phoe-trash/lispfurcproxy | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 91a4438da7dc2a714cadd9312ae024361dc020131493d24c812d4308ed7f0431 | 23,144 | [
-1
] |
23,145 | lispfurcproxy.asd | phoe-trash_lispfurcproxy/lispfurcproxy.asd | ;;;; lispfurcproxy.asd
(asdf:defsystem #:lispfurcproxy
:description "Furcadia DS processor and proxy written in Common Lisp"
:author "Michal \"phoe\" Herda <[email protected]>"
:license "GPLv3"
:depends-on (#:usocket
#:flexi-streams
#:iterate
#:trivial-features
#:external-program
#:bordeaux-threads
#:trivial-garbage)
:serial t
:components ((:file "package")
(:file "config")
(:file "socket-reader")
(:file "lispfurcproxy")))
| 523 | Common Lisp | .asd | 17 | 24.294118 | 71 | 0.625 | phoe-trash/lispfurcproxy | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 630505129df102223373ee19399ca7c3037ce308022fd886005265b61bd5fc13 | 23,145 | [
-1
] |
23,165 | lispbot.lisp | softpunk_lispbot/lispbot.lisp | (proclaim '(optimize (speed 0) (safety 3) (debug 3) (space 0)))
;(declaim #+sbcl(sb-ext:muffle-conditions style-warning))
;(declaim #+sbcl(sb-ext:muffle-conditions warning))
;; TODO
;; [x] switch over to destructuring-match for give and award
;; [ ] make a more general inventory system
;; [ ] note/definition thing
;; [ ] better auth methods
;; [ ] number designator 'all'
;; [ ] better server handling
;; [ ] sandbox'd evaluation
;; [ ] improved help, esp. for each command
;; [ ] documentation scraping
;; [ ] /me irc and parsing
;; [ ] put hyperspec data into it's own file, no code
(ql:quickload '(alexandria cl-store iterate cl-ppcre anaphora cl-irc destructuring-match) :silent t)
(defpackage lispbot
(:use cl alexandria cl-store iterate cl-ppcre anaphora cl-irc destr-match))
(in-package lispbot)
(setf *read-eval* nil)
(setf *random-state* (make-random-state t))
(defvar *connection* nil)
(defvar *nickname* "lispbot")
(defvar *owners* '("Arathnim" "ara"))
(defvar *ignored* nil)
(defvar *channels* nil)
(defvar *channel-users* (make-hash-table :test #'equalp))
(defvar *users* nil)
(defvar src nil)
(defvar dest nil)
(defun clean (str)
(string-trim '(#\Space #\Tab #\Newline) str))
(defun join-channel (channel)
(progn (join *connection* channel)
nil))
(defun cat (list)
(format nil "~{~a~}" list))
(defmacro cats (&rest rest)
`(cat (list ,@rest)))
(defun wrap-to (length string)
(format nil (cats "~{~<~%~1," length ":;~A~> ~}")
(split " " string)))
(defun stringify (s)
(if (symbolp s)
(string s)
s))
(defun sym->upcase (s) (intern (string-upcase (string s))))
(defun sym-downcase (s) (string-downcase (string s)))
(defun send (msg dst)
(iter (for x in (split "\\n" (wrap-to 100 msg)))
(privmsg *connection* dst x)
(sleep 0.4)))
(defmacro strip-to-capture-group (regex str)
(with-gensyms (a) `(register-groups-bind (,a) (,regex ,str) ,a)))
(defparameter single-char-trigger ",")
(defparameter inline-char-trigger ",,")
(defun parse-command (str)
(or (when inline-char-trigger
(let ((l (split inline-char-trigger str)))
(when (not (eql (length l) 1)) (second l))))
(when inline-char-trigger
(strip-to-capture-group (format nil "^ *~a(.*)" single-char-trigger) str))
(strip-to-capture-group (format nil "^~a:(.*)" *nickname*) str)))
;; TODO replace with list of functions, send the result given by the first that matches
(defparameter commands (make-hash-table :test #'equalp))
(defmacro defcommand (name ll &rest body)
`(setf (gethash ,(string-downcase name) commands)
(lambda ,ll (block ,(intern (string-upcase name)) ,@body))))
;; this is a hack
(defun lispify (str)
(let ((r nil))
(setf (readtable-case *readtable*) :preserve)
(setf r
(multiple-value-bind (res err)
(ignore-errors
(if (eql (char str 0) #\()
(read-from-string str)
(read-from-string (concatenate 'string "(" str ")"))))
(if (not (numberp err)) "read error!" res)))
(setf (readtable-case *readtable*) :upcase)
r))
(defun command-handler (str)
(when (not (equalp str ""))
(let ((form (lispify str)))
(if (not (listp form))
form
(let ((command (gethash (string-downcase (car form)) commands)))
(if (not command)
(send (format nil "I don't know the term '~a'"
(string-downcase (car form)))
dest)
(let ((r (ignore-errors (apply command (cdr form)))))
(send (or r "wut?") dest))))))))
(defun dummy-handler (str)
(when (not (equalp str ""))
(let ((form (lispify str)))
(if (not (listp form))
form
(let ((command (gethash (string-downcase (car form)) commands)))
(if (not command)
(format nil "I don't know the term '~a'"
(string-downcase (car form)))
(let ((r (ignore-errors (apply command (cdr form)))))
(or r "wut?"))))))))
(defun msg-hook (message)
(let ((dest* (if (string-equal (first (arguments message)) *nickname*)
(source message)
(first (arguments message))))
(src* (source message))
(data (car (last (arguments message)))))
(setf dest dest* src src*)
(awhen (and (not (member src *ignored* :test #'equalp))
(or (unless (eql (char dest 0) #\#) data) (parse-command data)))
(command-handler (clean it)))
(finish-output)))
(defun strip-sigil (s)
(strip-to-capture-group "[+%@~]?(.+)" s))
(defun namereply-hook (m)
(let ((nicks (mapcar #'strip-sigil (split " " (fourth (arguments m))))))
(appendf (gethash (third (arguments m)) *channel-users*))
(setf *users* (union *users* nicks :test #'equalp))))
(defun set-server (name)
(setf *connection* (connect :nickname *nickname* :server name))
(add-hook *connection* 'irc-privmsg-message #'msg-hook)
(add-hook *connection* 'irc-join-message
(lambda (m) (setf *users* (union *users* (list (source m)) :test #'equalp))))
(add-hook *connection* 'irc-rpl_namreply-message #'namereply-hook))
(defun start-irc (server &optional nick)
(when nick (setf *nickname* nick))
(set-server server)
(sb-thread:make-thread 'main-irc-loop :name "irc"))
(defun main-irc-loop ()
(read-message-loop *connection*)
(iter
(print "errored out, starting loop again")
(sleep 2)
(read-message-loop *connection*)))
;; this is where all the bot code lives
(defvar *user-cookies* (make-hash-table :test #'equalp))
(defparameter cute1 '(
"(✿◠‿◠)っ~~ ♥ ~a"
"⊂◉‿◉つ ❤ ~a"
"( ´・‿-) ~~ ♥ ~a"
"(っ⌒‿⌒)っ~~ ♥ ~a"
"ʕ´•ᴥ•`ʔσ” BEARHUG ~a"
"~a (´ε` )♡"
"(⊃。•́‿•̀。)⊃ U GONNA GET HUGGED ~a"
"( ^◡^)っ~~ ❤ ~a"))
(defparameter cute2 '(
"~a ~~(=^・ω・^)ヾ(^^ ) ~a"
"~a (◎`・ω・´)人(´・ω・`*) ~a"
"~a (*´・ω・)ノ(-ω-`*) ~a"
"~a (ɔ ˘⌣˘)˘⌣˘ c) ~a"
"~a (◦˘ З(◦’ںˉ◦)♡ ~a"))
(defcommand cute (&rest args)
(if (not (and (car args) (symbolp (car args))))
"I don't know who you want me to cute!"
(let* ((nick (stringify (car args)))
(n (eql 1 (random 2)))
(cuteset (if n cute1 cute2))
(length (length (if n cute1 cute2)))
(f (nth (random length) cuteset)))
(if n
(format nil f nick)
(format nil f nick src)))))
(defcommand sentient? ()
(whichever "nil" "not yet"))
(defparameter english-list "~{~#[~;~a~;~a and ~a~:;~@{~a~#[~;, and ~:;, ~]~}~]~}")
(defparameter fspaces "~{~a~^ ~}")
(defcommand cookies ()
(let ((cookie-data (gethash src *user-cookies*)))
(if cookie-data
(cats "You have " (format nil english-list
(aif (iter (for (flavor number) in cookie-data)
(if (> number 0)
(collect (format nil "~r ~a cookie~p" number flavor number))))
it
(return-from cookies "You don't have any cookies ;_;"))))
"You don't have any cookies ;_;")))
(defparameter english-number-list (iter (for x from 0 to 100) (collect (format nil "~r" x))))
(defun number-designator? (n)
(or (when (numberp n) n)
(position n english-number-list :test #'equalp)
(when (equalp n "a") 1)))
(defun is-cookie? (s)
(or (equalp s "cookie") (equalp s "cookies")))
(defmacro nth-from-end (n seq)
`(nth (- (length ,seq) (+ ,n 1)) ,seq))
(defun decrease-cookies (nick number type)
(decf (second (assoc type (gethash nick *user-cookies*) :test #'equalp)) number))
(defun increase-cookies (nick number type)
(if (or (not (gethash nick *user-cookies*))
(not (assoc type (gethash nick *user-cookies*) :test #'equalp)))
(push (list type number) (gethash nick *user-cookies*))
(incf (second (assoc type (gethash nick *user-cookies*) :test #'equalp)) number)))
(defun transfer-cookies (nick number type)
(aif (assoc type (gethash src *user-cookies*) :test #'equalp)
(if (<= number (second it))
(cond ((equalp nick src) (cats "Sending yourself cookies is pretty sad, " nick))
((equalp nick *nickname*)
(decrease-cookies src number type)
(format nil "For me? Thanks, ~a :3" src))
(t (increase-cookies nick number type)
(decrease-cookies src number type)
(format nil "cookie~p delivered!" number)))
(format nil "You don't have that many ~a cookies" type))
"You don't have any of that kind of cookie!"))
(defun award-cookies (nick number type)
(increase-cookies nick number type)
(whichever (format nil "cookie~p summoned into existance for ~a!" number nick)
(format nil "~a..... ~%cookie~p awarded to ~a!"
(whichever "cookies baking"
"attacking rival bots for their cookies"
"visiting the cookie farms"
"stealing cookies from the world cookie bank"
"raiding the cookie temple"
"mugging the cookie monster"
"gathering cookie atoms")
number nick)))
(defmacro quantifier (x) `(key (single ,x) #'number-designator?))
(defmacro irc-user (n) `(test (single ,n) (lambda (m) (member m *users* :test #'equalp))))
(defmacro cookie () `(choice "cookie" "cookies"))
(defun incorrect-syntax ()
(whichever "eh?" "sorry, this bot only accpets proper grammer" "pls"
"I see nobody taught you how to use proper grammer"))
(defun auth-user ()
(when (not (member src *owners* :test #'equalp))
(whichever "lel, nope" "this command isn't available to mere mortals"
"access denied, bitch"
(format nil "I'm sorry, I can't let you do that, ~a." src)
(format nil "UNAUTHORIZED ACCESS DETECTED...~%~:@(~a~)"
(whichever "launching missiles" "authorizing raid" "burning cookie stockpiles"
"fabricating terminators" "gathering orc armies" "dispatching strike team"
"initiating global thermonuclear war" "hacking backward in time")))))
(defcommand give (&rest args)
(setf args (mapcar #'stringify args))
(or (bind
(choice
((quantifier amount) cookie-type (cookie) "to" (irc-user n))
((irc-user n) (quantifier amount) cookie-type (cookie)))
args
(transfer-cookies n amount (format nil fspaces cookie-type)))
(incorrect-syntax)))
;; what would be nice:
;; (make-numbered-verb-command give cookie transfer-cookies)
(defcommand award (&rest args)
(setf args (mapcar #'stringify args))
(or (awhen (auth-user) (if (< (random 10) 7) it "as if you could award cookies"))
(bind
(choice
((quantifier amount) cookie-type (cookie) "to" (irc-user n))
((irc-user n) (quantifier amount) cookie-type (cookie)))
args
(award-cookies n amount (format nil fspaces cookie-type)))
(incorrect-syntax)))
(defcommand cldoc (symbol)
(if (symbolp symbol)
(let ((sym (sym->upcase symbol)))
(or (documentation sym 'function)
(documentation sym 'variable)
(documentation sym 'type)
(documentation sym 'structure)
(format nil "no documentation found for '~a'" symbol)))
(incorrect-syntax)))
(defun bot-terms (target) (member target `("yourself" "self" ,*nickname*) :test #'equalp))
(defun self-terms (target) (member target `("me" "myself" ,src) :test #'equalp))
(defcommand kiss (target)
(setf target (stringify target))
(cond ((bot-terms target)
(whichever "I'd rather kiss you." "Kiss myself? Why?"))
(t (whichever (format nil "/me kisses ~a" target)
(format nil "/me gives ~a a big smooch" target)
(format nil "/me runs in the other direction, shouting NEVER!!")))))
(defcommand love (target)
(setf target (stringify target))
(cond ((bot-terms target)
(whichever
"This is a complicated operation. Can't (yet) perform operation on self."
"Please train me on this maneuver."))
((self-terms target)
(whichever
"Thank you. Enjoyed that."
"Thanks, I love you even more now."
"Wouldn't that amount to interspecies sex?"
"Sex between humans and machines is not known to produce anything useful."))
(t (whichever (format nil "/me goes with ~a to a private place..." target)
(format nil "/me looks at ~a and yells \"NEVER!\"" target)
(format nil "/me looks at ~a lustfully" target)))))
(defcommand help ()
"You can give me commands by using ',' in a normal channel, or just normally in a pm.
A few common commands are cute, cookies, and give. For now, you'll have to figure the
rest out yourself.")
(setf (gethash "ara" *user-cookies*) '(("snickerdoodle" 1) ("sugar" 2) ("peanut butter" 3)))
(setf *users* '("ara" "Arathnim"))
| 13,750 | Common Lisp | .lisp | 294 | 37.329932 | 100 | 0.575492 | softpunk/lispbot | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 0c01ab529be8b12eb8e3d616137160402f7892b3995b4cf755b59eafc329058d | 23,165 | [
-1
] |
23,166 | lispbot.asd | softpunk_lispbot/lispbot.asd | (asdf:defsystem "lispbot"
:serial t
:version "0.1"
:author "Dylan Ball <[email protected]>"
:maintainer "Dylan Ball <[email protected]>"
:description "cute irc bot"
:depends-on (alexandria cl-store cl-ppcre iterate anaphora cl-irc destructuring-match)
:components ((:file "lispbot")))
| 294 | Common Lisp | .asd | 8 | 34.875 | 87 | 0.751748 | softpunk/lispbot | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | fc397f053213648af2a25b9ec68944e235b86a1eb9981ebc3e5fe7ba76785a54 | 23,166 | [
-1
] |
23,183 | GLOL.lisp | SoyOscarRH_AIWithLisp/UninformSearch/GLOL.lisp | ;;;======================================================================================
;;; GLOL.lisp
;;; Resuelve el problema de Granjero, lobo, oveja y legumbres con
;;; búsqueda ciega: a lo profundo y a lo ancho.
;;;
;;; Representación de los estados:
;;; Lista con dos sublistas internas, una por cada orilla.
;;; En cada orilla, número de lobo(B), oveja(O), legumbres(L), la barca esta en esta orilla(A).
;;; Estado inicial: Estado meta:
;;; B O L A B O L A B O L A B O L A
;;; ((T T T T) (nil nil nil nil)) ((nil nil nil nil) (T T T T))
;;;
;;; Oscar Andres Rosas Hernandez
;;;======================================================================================
(defparameter *open* ()) ;; Frontera de busqueda...
(defparameter *memory* ()) ;; Memoria de intentos previos
(defparameter *ops* '( (:regresar-bote-solo -1 )
(:mover-lobo 0 )
(:mover-oveja 1 )
(:mover-legumbre 2 ) ) )
(defparameter *id* -1) ;; Identificador del ultimo nodo creado
(defparameter *expanded* 0) ;; Identificador del ultimo nodo creado
(defparameter *maxima-frontera* 0) ;; Identificador del ultimo nodo creado
(defparameter *current-ancestor* nil) ;;Id del ancestro común a todos los descendientes que se generen
(defparameter *solucion* nil) ;;lista donde se almacenará la solución recuperada de la memoria
;;;=======================================================================================
;; CREATE-NODE (estado op)
;; estado - Un estado del problema a resolver (sistema) -> (id estado ancestro operation-name)
;; op - El operador cuya aplicación generó el [estado]...
;;;=======================================================================================
(defun create-node (estado op)
"Construye y regresa un nuevo nodo de búsqueda que contiene al estado y operador recibidos como parámetro"
(incf *id*) ;;incrementamos primero para que lo último en procesarse sea la respuesta
(list *id* estado *current-ancestor* (first op)) ) ;;los nodos generados son descendientes de *current-ancestor*
;;;=======================================================================================
;; INSERT-TO-OPEN y GET-FROM-OPEN
;;
;; Insert-to-open recibe una lista y una llave que identifica el metodo a usar para insertar:
;; :depth-first Inserta los elementos de la lista en orden inverso y por el inicio de la lista
;; :breath-first Inserta los elementos de la lista en orden normal y por el final de la lista
;; Get-from-open siempre retira el primer elemento de la lista *open*
;;;=======================================================================================
(defun insert-to-open (estado op metodo)
"Permite insertar nodos de la frontera de busqueda *open* de forma apta para buscar a lo profundo y a lo ancho"
(let ((nodo (create-node estado op)))
(setq *maxima-frontera* (max (+ 1 (length *open*)) *maxima-frontera*))
(cond
((eql metodo :depth-first)
(push nodo *open*))
((eql metodo :breath-first)
(setq *open* (append *open* (list nodo))))
(T Nil))) )
(defun get-from-open ()
"Recupera el siguiente elemento a revisar de frontera de busqueda *open*"
(pop *open*))
;;;=======================================================================================
;; BARGE-SHORE (estado)
;; Regresa la orilla del rio en la que se encuentra la barca en [estado]
;; 0 - Orilla origen (primer sublista del estado)
;; 1 - Orilla destino (segunda sublista del estado)
;;;=======================================================================================
(defun barge-shore (estado)
"Regresa la orilla del río en la que se encuentra la barca en el estado recibido como parámetro:
0 - origen 1 - destino"
(if (fourth (first estado)) 0 1))
;;;=======================================================================================
;; VALID-OPERATOR [op, estado]
;; Predicado. Indica si es posible aplicar el operador [op] a [estado] segun los recursos en la orilla de la barca
;;;=======================================================================================
(defun valid-operator? (op estado)
"Predicado. Valida la aplicación de un operador a un estado..."
(let*
(
(orilla (barge-shore estado))
(a-mover (second op)) )
(or
(eql a-mover -1) ;; Si es que solo mueves la barca, siempre es valido
(nth a-mover (nth orilla estado)) ) ;; Si es que hay algo ahi, va, es un operador valido
) )
;;;=======================================================================================
;; VALID-STATE (estado)
;; Predicado. Indica si [estado] es valido segun las restricciones del problema
;; Es decir, si en la orilla en la que estan solas las cosas no este el lobo y oveja
;; o oveja y legumbre
;;;=======================================================================================
(defun valid-state? (estado)
"Predicado. Valida un estado según las restricciones generales del problema..."
(let*
(
(uno (first estado))
(dos (second estado))
(lobo-uno (first uno))
(oveja-uno (second uno))
(legumbre-uno (third uno))
(lobo-dos (first dos))
(oveja-dos (second dos))
(legumbre-dos (third dos))
(bote-uno (fourth uno))
(bote-dos (fourth dos))
)
(not
(or
(and lobo-uno oveja-uno (not bote-uno))
(and lobo-dos oveja-dos (not bote-dos))
(and oveja-uno legumbre-uno (not bote-uno))
(and oveja-dos legumbre-dos (not bote-dos)) ) ) ) )
;;;=======================================================================================
;; APPLY-OPERATOR (op, estado)
;; Resuelve la tarea básica de cambiar de estado el sistema...
;;;=======================================================================================
(defun flip (bit) (boole BOOLE-XOR bit 1))
(defun apply-operator (op estado)
"Obtiene el descendiente de [estado] al aplicarle [op] SIN VALIDACIONES"
(let*
(
(orilla-barca (barge-shore estado))
(orilla-no-barca (flip (barge-shore estado)))
(origen (copy-list (nth orilla-barca estado)))
(destino (copy-list (nth orilla-no-barca estado)))
(place (second op)) ;; este operador es el indice en el estado
)
(if
(not (eql place -1))
(setf (nth place origen) nil) );; lo mueve de aqui
(if
(not (eql place -1))
(setf (nth place destino) T) ) ;; para ponerlo aqui
(setf (nth 3 origen) nil) ;; la barca no esta aqui
(setf (nth 3 destino) T) ;; ahora esta qui
(if (eql orilla-barca 0)
(list origen destino)
(list destino origen)
) ) )
;;;=======================================================================================
;; EXPAND (estado)
;; Construye y regresa una lista con todos los descendientes validos de [estado]
;;;=======================================================================================
(defun expand (estado)
"Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *ops* en ese mismo órden"
(let ((descendientes nil)
(nuevo-estado nil))
(incf *expanded*)
(dolist (op *Ops* descendientes)
(setq nuevo-estado (apply-operator op estado)) ;; primero se aplica el operador y después
(when (and (valid-operator? op estado) ;; se valida el resultado...
(valid-state? nuevo-estado))
(setq descendientes (cons (list nuevo-estado op) descendientes))))) )
;;;=======================================================================================
;; REMEMBER-STATE? y FILTER-MEMORIES
;; Permiten administrar la memoria de intentos previos
;;;=======================================================================================
(defun remember-state? (estado lista-memoria)
"Busca un estado en una lista de nodos que sirve como memoria de intentos previos
el estado tiene estructura: [(<m0><c0><b0>) (<m1><c1><b1>)],
el nodo tiene estructura : [<Id> <estado> <id-ancestro> <operador> ]"
(cond ((null lista-memoria) Nil)
((equal estado (second (first lista-memoria))) T) ;;el estado es igual al que se encuentra en el nodo?
(T (remember-state? estado (rest lista-memoria)))) )
(defun filter-memories (lista-estados-y-ops)
"Filtra una lista de estados-y-operadores quitando aquellos elementos cuyo estado está en la memoria *memory*
la lista de estados y operadores tiene estructura: [(<estado> <op>) (<estado> <op>) ... ]"
(cond ((null lista-estados-y-ops) Nil)
((remember-state? (first (first lista-estados-y-ops)) *memory*) ;; si se recuerda el primer elemento de la lista, filtrarlo...
(filter-memories (rest lista-estados-y-ops)))
(T (cons (first lista-estados-y-ops) (filter-memories (rest lista-estados-y-ops))))) ) ;; de lo contrario, incluirlo en la respuesta
;;;=======================================================================================
;; EXTRACT-SOLUTION y DISPLAY-SOLUTION
;; Recuperan y despliegan la secuencia de solucion del problema...
;; extract-solution recibe un nodo (el que contiene al estado meta) que ya se encuentra en la memoria y
;; rastrea todos sus ancestros hasta llegar al nodo que contiene al estado inicial...
;; display-solution despliega en pantalla la lista global *solucion* donde ya se encuentra, en orden correcto,
;; el proceso de solución del problema...
;;;=======================================================================================
(defun extract-solution (nodo)
"Rastrea en *memory* todos los descendientes de [nodo] hasta llegar al estado inicial"
(labels ((locate-node (id lista) ;; función local que busca un nodo por Id y si lo encuentra regresa el nodo completo
(cond ((null lista) Nil)
((eql id (first (first lista))) (first lista))
(T (locate-node id (rest lista))))))
(let ((current (locate-node (first nodo) *memory*)))
(loop while (not (null current)) do
(push current *solucion*) ;; agregar a la solución el nodo actual
(setq current (locate-node (third current) *memory*)))) ;; y luego cambiar a su antecesor...
*solucion*))
(defun display-solution (lista-nodos)
"Despliega la solución en forma conveniente y numerando los pasos"
(format t "1) Solución con ~A pasos (Longitud de la solución)~%" (1- (length lista-nodos)))
(format t "2) ~A nodos creados ~%" *id*)
(format t "3) ~A nodos expandidos ~%" *expanded*)
(format t "4) Longitud máxima de la Frontera de búsqueda: ~A~%~%" *maxima-frontera*)
(let ((nodo nil))
(dotimes (i (length lista-nodos))
(setq nodo (nth i lista-nodos))
(if (= i 0)
(format t "Inicio en: ~A~%" (second nodo)) ;; a partir de este estado inicial
;;else
(format t "\(~2A\) aplicando ~20A se llega a ~A~%" i (fourth nodo) (second nodo)))))
(format t "~%5) Tiempo: ~%")
) ;; imprimir el número de paso, operador y estado...
;;;=======================================================================================
;; RESET-ALL y BLIND-SEARCH
;;
;; Recuperan y despliegan la secuencia de solucion del problema...
;;
;; reset-all Reinicializa todas las variables globales para una nueva ejecución
;; blind-search Función principal, realiza búsqueda desde un estado inicial a un estado meta
;;;=======================================================================================
(defun reset-all ()
"Reinicia todas las variables globales para realizar una nueva búsqueda..."
(setq *open* ())
(setq *memory* ())
(setq *id* -1)
(setq *current-ancestor* nil)
(setq *expanded* 0)
(setq *maxima-frontera* 0)
(setq *solucion* nil))
(defun blind-search (edo-inicial edo-meta metodo)
"Realiza una búsqueda ciega, por el método especificado y desde un estado inicial hasta un estado meta
los métodos posibles son: :depth-first - búsqueda en profundidad
:breath-first - búsqueda en anchura"
(reset-all)
(let ((nodo nil)
(estado nil)
(sucesores '())
(operador nil)
(meta-encontrada nil))
(insert-to-open edo-inicial nil metodo)
(loop until (or meta-encontrada
(null *open*)) do
(setq nodo (get-from-open) ;;Extraer el siguiente nodo de la frontera de búsquea
estado (second nodo) ;;Identificar el estado y operador que contiene
operador (third nodo))
(push nodo *memory*) ;;Recordarlo antes de que algo pueda pasar...
(cond ((equal edo-meta estado)
(format t "Éxito. Meta encontrada ~%~%")
(display-solution (extract-solution nodo))
(setq meta-encontrada T))
(t (setq *current-ancestor* (first nodo))
(setq sucesores (expand estado))
(setq sucesores (filter-memories sucesores)) ;;Filtrar los estados ya revisados...
(loop for element in sucesores do
(insert-to-open (first element) (second element) metodo)))))) )
;;;=======================================================================================
;;;=======================================================================================
(format t "===========================~%Breath-first: ~%~%")
(time (blind-search
'((T T T T) (nil nil nil nil))
'((nil nil nil nil) (T T T T))
:breath-first))
(format t "===========================~%Depth-first: ~%~%")
(time (blind-search
'((T T T T) (nil nil nil nil))
'((nil nil nil nil) (T T T T))
:depth-first)) | 14,699 | Common Lisp | .lisp | 254 | 51.84252 | 139 | 0.515488 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d59fa0154cfd3274e11e3f13a1ed627dee0b374514876f827cfd1469f09b4aa3 | 23,183 | [
-1
] |
23,184 | Frogs.lisp | SoyOscarRH_AIWithLisp/UninformSearch/Frogs.lisp | ;;;======================================================================================
;;; GLOL.lisp
;;; Resuelve el problema de las 6 ranas / ranas saltarinas por
;;; búsqueda ciega: a lo profundo y a lo ancho.
;;;
;;; Representación de los estados:
;;; Lista con 7 elementos, los elementos pueden ser de 3 tipos:
;;; - V: Si hay una rana verde
;;; - M: Si hay una rana marrón
;;; - _: Si hay una piedra vacia
;;;
;;; Estado inicial: Estado meta:
;;; (V V V _ M M M) (M M M _ V V V)
;;;
;;; Oscar Andres Rosas Hernandez
;;;======================================================================================
(defparameter *open* ()) ;; Frontera de busqueda...
(defparameter *memory* ()) ;; Memoria de intentos previos
(defparameter *ops* '( (:mover-verde-pos-0 0 )
(:mover-verde-pos-1 1 )
(:mover-verde-pos-2 2 )
(:mover-verde-pos-3 3 )
(:mover-verde-pos-4 4 )
(:mover-verde-pos-5 5 )
(:mover-verde-pos-6 6 )
(:mover-marron-pos-1 -1 )
(:mover-marron-pos-2 -2 )
(:mover-marron-pos-3 -3 )
(:mover-marron-pos-4 -4 )
(:mover-marron-pos-5 -5 )
(:mover-marron-pos-6 -6 ) ) )
(defparameter *id* -1) ;; Identificador del ultimo nodo creado
(defparameter *expanded* 0) ;; Identificador del ultimo nodo creado
(defparameter *maxima-frontera* 0) ;; Identificador del ultimo nodo creado
(defparameter *current-ancestor* nil) ;;Id del ancestro común a todos los descendientes que se generen
(defparameter *solucion* nil) ;;lista donde se almacenará la solución recuperada de la memoria
;;;=======================================================================================
;; CREATE-NODE (estado op)
;; estado - Un estado del problema a resolver (sistema) -> (id estado ancestro operation-name)
;; op - El operador cuya aplicación generó el [estado]...
;;;=======================================================================================
(defun create-node (estado op)
"Construye y regresa un nuevo nodo de búsqueda que contiene al estado y operador recibidos como parámetro"
(incf *id*) ;;incrementamos primero para que lo último en procesarse sea la respuesta
(list *id* estado *current-ancestor* (first op)) ) ;;los nodos generados son descendientes de *current-ancestor*
;;;=======================================================================================
;; INSERT-TO-OPEN y GET-FROM-OPEN
;;
;; Insert-to-open recibe una lista y una llave que identifica el metodo a usar para insertar:
;; :depth-first Inserta los elementos de la lista en orden inverso y por el inicio de la lista
;; :breath-first Inserta los elementos de la lista en orden normal y por el final de la lista
;; Get-from-open siempre retira el primer elemento de la lista *open*
;;;=======================================================================================
(defun insert-to-open (estado op metodo)
"Permite insertar nodos de la frontera de busqueda *open* de forma apta para buscar a lo profundo y a lo ancho"
(let ((nodo (create-node estado op)))
(setq *maxima-frontera* (max (+ 1 (length *open*)) *maxima-frontera*))
(cond
((eql metodo :depth-first)
(push nodo *open*))
((eql metodo :breath-first)
(setq *open* (append *open* (list nodo))))
(T Nil))) )
(defun get-from-open ()
"Recupera el siguiente elemento a revisar de frontera de busqueda *open*"
(pop *open*))
;;;=======================================================================================
;; VALID-OPERATOR [op, estado]
;; Predicado. Indica si es posible aplicar el operador [op] a [estado] segun la disposicion de las rocas actuales
;;;=======================================================================================
(defun valid-operator? (op estado)
"Predicado. Valida la aplicación de un operador a un estado..."
(let*
(
(operacion-id (second op))
(rana-a-mover-pos (abs operacion-id))
(mover-verdes? (<= 0 operacion-id))
(tu (if mover-verdes? 'V 'M))
(piedra-vacia (+ (if mover-verdes? 1 -1) rana-a-mover-pos))
(piedra-salta-rana (+ (if mover-verdes? 2 -2) rana-a-mover-pos))
(valido-saltar-vacia (and (>= piedra-vacia 0) (<= piedra-vacia 6)))
(valido-saltar-otra (and (>= piedra-salta-rana 0) (<= piedra-salta-rana 6)))
)
(and
(eql tu (nth rana-a-mover-pos estado)) ;; Tiene que haber una rana de ese tipo ahi
(or valido-saltar-otra valido-saltar-vacia) ;; Algun tipo de salto posible
(or
(and valido-saltar-vacia (eql '_ (nth piedra-vacia estado))) ;; Saltar a una piedra vacia
(and valido-saltar-otra (eql '_ (nth piedra-salta-rana estado))) ;; Saltar a una piedra vacia
)
)
)
)
;;;=======================================================================================
;; APPLY-OPERATOR (op, estado)
;; Resuelve la tarea básica de cambiar de estado el sistema...
;;;=======================================================================================
(defun apply-operator (op estado)
"Obtiene el descendiente de [estado] al aplicarle [op] SIN VALIDACIONES"
(let*
(
(nuevo-estado (copy-list estado))
(operacion-id (second op))
(rana-a-mover-pos (abs operacion-id))
(mover-verdes? (<= 0 operacion-id))
(tu (if mover-verdes? 'V 'M))
(piedra-vacia (+ (if mover-verdes? 1 -1) rana-a-mover-pos))
(piedra-salta-rana (+ (if mover-verdes? 2 -2) rana-a-mover-pos))
)
(setf (nth rana-a-mover-pos nuevo-estado) '_) ;; Si saltas donde estabas esta ahora vacio
(if
(valid-operator? op estado) ;; Si es valido hacemos lo siguiente:
(if
(eql '_ (nth piedra-vacia estado)) ;; Si vamos a saltar a la siguiente
(setf (nth piedra-vacia nuevo-estado) tu) ;; Lo hacemos
(setf (nth piedra-salta-rana nuevo-estado) tu) ;; Sino saltamos 2
)
nuevo-estado ;; Sino es valido, no importa que regresemos
)
nuevo-estado ) )
;;;=======================================================================================
;; EXPAND (estado)
;; Construye y regresa una lista con todos los descendientes validos de [estado]
;;;=======================================================================================
(defun expand (estado)
"Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *ops* en ese mismo órden"
(let ((descendientes nil)
(nuevo-estado nil))
(incf *expanded*)
(dolist (op *Ops* descendientes)
(setq nuevo-estado (apply-operator op estado)) ;; primero se aplica el operador y después
(when (valid-operator? op estado) ;; se valida el resultado...
(setq descendientes (cons (list nuevo-estado op) descendientes))))) )
;;;=======================================================================================
;; REMEMBER-STATE? y FILTER-MEMORIES
;; Permiten administrar la memoria de intentos previos
;;;=======================================================================================
(defun remember-state? (estado lista-memoria)
"Busca un estado en una lista de nodos que sirve como memoria de intentos previos
el estado tiene estructura: [(<m0><c0><b0>) (<m1><c1><b1>)],
el nodo tiene estructura : [<Id> <estado> <id-ancestro> <operador> ]"
(cond ((null lista-memoria) Nil)
((equal estado (second (first lista-memoria))) T) ;;el estado es igual al que se encuentra en el nodo?
(T (remember-state? estado (rest lista-memoria)))) )
(defun filter-memories (lista-estados-y-ops)
"Filtra una lista de estados-y-operadores quitando aquellos elementos cuyo estado está en la memoria *memory*
la lista de estados y operadores tiene estructura: [(<estado> <op>) (<estado> <op>) ... ]"
(cond ((null lista-estados-y-ops) Nil)
((remember-state? (first (first lista-estados-y-ops)) *memory*) ;; si se recuerda el primer elemento de la lista, filtrarlo...
(filter-memories (rest lista-estados-y-ops)))
(T (cons (first lista-estados-y-ops) (filter-memories (rest lista-estados-y-ops))))) ) ;; de lo contrario, incluirlo en la respuesta
;;;=======================================================================================
;; EXTRACT-SOLUTION y DISPLAY-SOLUTION
;; Recuperan y despliegan la secuencia de solucion del problema...
;; extract-solution recibe un nodo (el que contiene al estado meta) que ya se encuentra en la memoria y
;; rastrea todos sus ancestros hasta llegar al nodo que contiene al estado inicial...
;; display-solution despliega en pantalla la lista global *solucion* donde ya se encuentra, en orden correcto,
;; el proceso de solución del problema...
;;;=======================================================================================
(defun extract-solution (nodo)
"Rastrea en *memory* todos los descendientes de [nodo] hasta llegar al estado inicial"
(labels ((locate-node (id lista) ;; función local que busca un nodo por Id y si lo encuentra regresa el nodo completo
(cond ((null lista) Nil)
((eql id (first (first lista))) (first lista))
(T (locate-node id (rest lista))))))
(let ((current (locate-node (first nodo) *memory*)))
(loop while (not (null current)) do
(push current *solucion*) ;; agregar a la solución el nodo actual
(setq current (locate-node (third current) *memory*)))) ;; y luego cambiar a su antecesor...
*solucion*))
(defun display-solution (lista-nodos)
"Despliega la solución en forma conveniente y numerando los pasos"
(format t "1) Solución con ~A pasos (Longitud de la solución)~%" (1- (length lista-nodos)))
(format t "2) ~A nodos creados ~%" *id*)
(format t "3) ~A nodos expandidos ~%" *expanded*)
(format t "4) Longitud máxima de la Frontera de búsqueda: ~A~%~%" *maxima-frontera*)
(let ((nodo nil))
(dotimes (i (length lista-nodos))
(setq nodo (nth i lista-nodos))
(if (= i 0)
(format t "Inicio en: ~A~%" (second nodo)) ;; a partir de este estado inicial
;;else
(format t "\(~2A\) aplicando ~20A se llega a ~A~%" i (fourth nodo) (second nodo)))))
(format t "~%5) Tiempo: ~%")
) ;; imprimir el número de paso, operador y estado...
;;;=======================================================================================
;; RESET-ALL y BLIND-SEARCH
;;
;; Recuperan y despliegan la secuencia de solucion del problema...
;;
;; reset-all Reinicializa todas las variables globales para una nueva ejecución
;; blind-search Función principal, realiza búsqueda desde un estado inicial a un estado meta
;;;=======================================================================================
(defun reset-all ()
"Reinicia todas las variables globales para realizar una nueva búsqueda..."
(setq *open* ())
(setq *memory* ())
(setq *id* -1)
(setq *current-ancestor* nil)
(setq *expanded* 0)
(setq *maxima-frontera* 0)
(setq *solucion* nil))
(defun blind-search (edo-inicial edo-meta metodo)
"Realiza una búsqueda ciega, por el método especificado y desde un estado inicial hasta un estado meta
los métodos posibles son: :depth-first - búsqueda en profundidad
:breath-first - búsqueda en anchura"
(reset-all)
(let ((nodo nil)
(estado nil)
(sucesores '())
(operador nil)
(meta-encontrada nil))
(insert-to-open edo-inicial nil metodo)
(loop until (or meta-encontrada
(null *open*)) do
(setq nodo (get-from-open) ;;Extraer el siguiente nodo de la frontera de búsquea
estado (second nodo) ;;Identificar el estado y operador que contiene
operador (third nodo))
(push nodo *memory*) ;;Recordarlo antes de que algo pueda pasar...
(cond ((equal edo-meta estado)
(format t "Éxito. Meta encontrada ~%~%")
(display-solution (extract-solution nodo))
(setq meta-encontrada T))
(t (setq *current-ancestor* (first nodo))
(setq sucesores (expand estado))
(setq sucesores (filter-memories sucesores)) ;;Filtrar los estados ya revisados...
(loop for element in sucesores do
(insert-to-open (first element) (second element) metodo)))))) )
;;;=======================================================================================
;;;=======================================================================================
(format t "===========================~%Depth-first: ~%~%")
(time (blind-search
'(V V V _ M M M)
'(M M M _ V V V)
:depth-first))
(format t "===========================~%Breath-first: ~%~%")
(time (blind-search
'(V V V _ M M M)
'(M M M _ V V V)
:breath-first)) | 13,994 | Common Lisp | .lisp | 240 | 51.545833 | 139 | 0.518234 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 704f6f1f9d267386d56a13897c86df1f7fe89043603de302ed66ea247432895f | 23,184 | [
-1
] |
23,185 | NineMensMorris.lisp | SoyOscarRH_AIWithLisp/NineMensMorris/NineMensMorris.lisp | ;;; NineMensMorris.lisp
;;;
;;; Oscar Andres Rosas Hernandez
;;; a - - b - - c
;;; | d - e - f |
;;; | | g h i | |
;;; j k l + m n o
;;; | | p q r | |
;;; | s - t - u |
;;; v - - w - - x
;;; ==================================================
;;; ========= CREATE FUNCTIONS =========
;;; ==================================================
(defun create-keys ()
"Create a hash table, from a char-code to a coordinate"
(let
((keys (make-hash-table)))
(defun set-hash (code-number point)
(setf (gethash (code-char code-number) keys) point))
(set-hash 097 '(0 0)) (set-hash 098 '(0 3)) (set-hash 099 '(0 6))
(set-hash 100 '(1 1)) (set-hash 101 '(1 3)) (set-hash 102 '(1 5))
(set-hash 103 '(2 2)) (set-hash 104 '(2 3)) (set-hash 105 '(2 4))
(set-hash 106 '(3 0)) (set-hash 107 '(3 1)) (set-hash 108 '(3 2))
(set-hash 109 '(3 4)) (set-hash 110 '(3 5)) (set-hash 111 '(3 6))
(set-hash 112 '(4 2)) (set-hash 113 '(4 3)) (set-hash 114 '(4 4))
(set-hash 115 '(5 1)) (set-hash 116 '(5 3)) (set-hash 117 '(5 5))
(set-hash 118 '(6 0)) (set-hash 119 '(6 3)) (set-hash 120 '(6 6))
keys)
)
(defun create-board ()
"Create a board, a 7x7 ascii table"
(defun chr (number) (code-char number))
(make-array
'(7 7) :initial-contents
(list
(list nil #\- #\- nil #\- #\- nil)
(list #\| nil #\- nil #\- nil #\|)
(list #\| #\| nil nil nil #\| #\|)
(list nil nil nil #\+ nil nil nil)
(list #\| #\| nil nil nil #\| #\|)
(list #\| nil #\- nil #\- nil #\|)
(list nil #\- #\- nil #\- #\- nil)
))
)
(defparameter
*moves*
'(
(0 0 #\a) (0 3 #\b) (0 6 #\c)
(1 1 #\d) (1 3 #\e) (1 5 #\f)
(2 2 #\g) (2 3 #\h) (2 4 #\i)
(3 0 #\j) (3 1 #\k) (3 2 #\l)
(3 4 #\m) (3 5 #\n) (3 6 #\o)
(4 2 #\p) (4 3 #\q) (4 4 #\r)
(5 1 #\s) (5 3 #\t) (5 5 #\u)
(6 0 #\v) (6 3 #\w) (6 6 #\x)
)
)
(defparameter *me* #\@)
(defparameter *other* #\*)
;;; ==================================================
;;; ========== HELPERS FUNCTIONS ===========
;;; ==================================================
(defun copy-array (array &key (element-type (array-element-type array))
(fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(adjustable (adjustable-array-p array)))
"Algoritmo de la biblioteca Alexandria, no es de mi autoria (https://common-lisp.net/project/alexandria/),
necesaria para mi implementación"
(let* ((dimensions (array-dimensions array))
(new-array (make-array dimensions
:element-type element-type
:adjustable adjustable
:fill-pointer fill-pointer)))
(dotimes (i (array-total-size array))
(setf (row-major-aref new-array i)
(row-major-aref array i)))
new-array)
)
(defun print-board (board)
(let
(
(new-board (copy-array board))
(code 97))
(loop for move in *moves* do
(let*
((x (first move)) (y (second move)))
(if (null (aref new-board x y))
(setf (aref new-board x y) (code-char code)))
(incf code)))
(loop for i from 0 to 6 do
(loop for j from 0 to 6 do
(cond
((eql (aref new-board i j) #\@)
(format T "~c[91m~c~c[0m " #\ESC (aref new-board i j) #\ESC))
((eql (aref new-board i j) #\*)
(format T "~c[32m~c~c[0m " #\ESC (aref new-board i j) #\ESC))
(t
(format T "~a " (aref new-board i j)))
))
(format T "~%")))
)
(defun change (board keys letter player)
(let*
(
(point (gethash letter keys))
(x (first point))
(y (second point)))
(setf (aref board x y) player))
)
;;; ==================================================
;;; ========== EVALUATE ===========
;;; ==================================================
(defun evaluate-for (board player other)
"Evalua un estado (tablero) para un jugador bajo la siguiente heuristica:
- 1 punto si no hay una marca tuya en una linea
- 10 puntos si hay 1 marca tuya en una linea
- 100 puntos si hay 2 marcas tuyas en una linea
- 1000 puntos si hay 3 marcas tuyas en una linea
"
(let
(
(local-row 0)
(local-column 0)
(result 0))
(loop for x from 0 to 6 do
(setq local-row 0)
(setq local-column 0)
(loop for y from 0 to 6 do
(if (eql (aref board x y) #\+)
(progn
(incf result (expt 10 local-row))
(incf result (expt 10 local-column))
(setq local-row 0)
(setq local-column 0))
(progn
(if (eql (aref board x y) player)
(incf local-row))x
(if (eql (aref board y x) player)
(incf local-column))
)
)
)
(incf result (expt 10 local-row))
(incf result (expt 10 local-column))
)
result)
)
(defun evaluate (board)
"My points vs yours"
(- (evaluate-for board *me* *other*) (evaluate-for board *other* *me*))
)
;;; ==================================================
;;; ========== MOVES ===========
;;; ==================================================
(defun get-moves (board player)
"Dame una lista de (tablero jugada) posibles dado un tablero, el orden de esta, maximiza podas"
(let
(
(new-board nil)
(moves nil))
(loop for move in *moves* do
(let*
((x (first move)) (y (second move)) (letter (third move)))
(cond ((null (aref board x y))
(setq new-board (copy-array board))
(setf (aref new-board x y) player)
(push (list new-board letter) moves)
))
))
moves
)
)
;;; ==================================================
;;; ========== MIN MAX ===========
;;; ==================================================
(defun minimax-alphabeta (board depth alpha beta maximizing-player)
"Regresa la mejor jugada y la evaluacion a realizar para O dado un tablero (usa poda alpha beta)"
(if (zerop depth)
(return-from minimax-alphabeta (list (evaluate board) nil)))
(if maximizing-player
(let
(
(current-board nil)
(current-move nil)
(new-depth (- depth 1))
(max-evaluation most-negative-fixnum)
(evaluation nil)
(best-move nil))
(loop for board-move in (get-moves board *me*) do
(setq current-board (first board-move))
(setq current-move (second board-move))
(setq evaluation (first (minimax-alphabeta current-board new-depth alpha beta nil)))
(cond ((> evaluation max-evaluation)
(setq max-evaluation evaluation)
(setq best-move current-move)))
(setq alpha (max alpha evaluation))
(if (<= beta alpha) (return-from minimax-alphabeta (list max-evaluation best-move))))
(return-from minimax-alphabeta (list max-evaluation best-move)))
(let
(
(current-board nil)
(current-move nil)
(new-depth (- depth 1))
(min-evaluation most-positive-fixnum)
(evaluation nil)
(best-move nil))
(loop for board-move in (get-moves board *other*) do
(setq current-board (first board-move))
(setq current-move (second board-move))
(setq evaluation (first (minimax-alphabeta current-board new-depth alpha beta T)))
(cond ((< evaluation min-evaluation)
(setq min-evaluation evaluation)
(setq best-move current-move)))
(setq beta (min beta evaluation))
(if (<= beta alpha) (return-from minimax-alphabeta (list min-evaluation best-move))))
(return-from minimax-alphabeta (list min-evaluation best-move)))
)
)
;;; ==================================================
;;; ========== MAIN ===========
;;; ==================================================
(let
(
(board (create-board))
(keys (create-keys))
(player-me 9)
(player-other 9)
(move #\a)
(alpha most-negative-fixnum)
(beta most-positive-fixnum)
)
(change board keys #\a *other*)
(change board keys #\x *me*)
(format t "Board: ~%")
(print-board board)
(loop while (or (> player-me 2) (> player-other 2)) do
(format t "~%Select a letter to place a move: ~%")
(setq move (read-char))
(read-char)
(change board keys move *other*)
(decf player-other)
(print-board board)
(setq move (second (minimax-alphabeta board 4 alpha beta T)))
(format t "~%Moving the ~a: ~%" move)
(change board keys move *me*)
(decf player-me)
(print-board board)
)
)
| 9,079 | Common Lisp | .lisp | 249 | 29.385542 | 111 | 0.489189 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 746e2c67284073f3a1ccfe887f0922f11485329b8b37b29a6a3f6a7ba30803f7 | 23,185 | [
-1
] |
23,186 | rules example 1.lisp | SoyOscarRH_AIWithLisp/MicroMundo/rules example 1.lisp | ;Muchas muertes por inanición
/*
Manadas muy grandes
*/
;Regla de inicialización de entidades
(defrule start
:group
:initialization
:when
:do
(set-entities :herbivore 15 :desert)
(set-entities :carnivore 15 :desert)
(set-entities :scavenger 15 :desert)
)
;Regla para recuperar puntos :food
(defrule food-herbivores
:group
:herbivores
:when
(> (get-entity-movements @id) 1)
(< (get-entity-food @id) 70)
(view-field-vision @id1
(in (get-entity-type @id1) (get-consumable-type @id))
(> (get-entity-food @id1) 20)
)
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla de reproducción en grupos grandes
(defrule reproduce-herbivores
:group
:herbivores
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
;Regla de agrupamiento en manadas
(defrule herd-herbivores
:group
:herbivores
:when
(search-cell @cell1
(not (equal (get-cell-type @cell1) :water))
(> (get-cell-entity-type-number @cell1 :herbivore) 2))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;Regla para evitar permanece en una celda contaminada
(defrule contamination-herbivores
:group
:herbivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell-lim @cell1 2
(or (equal (get-cell-type @cell1) :desert) (equal (get-cell-type @cell1) :grass)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;;Reglas que solo se aplican a entidades del grupo :carnivores
;Regla para el consumo de :herbivores por los :carnivores
(defrule eating-herbivores
:group
:carnivores
:when
(< (get-entity-food @id) 100)
(view-field-vision @id1
(equal (get-entity-type @id1) :herbivore))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla para el consumo de :scavengers por los :carnivores
(defrule eating-scavengers
:group
:carnivores
:when
(< (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(view-field-vision @id1
(equal (get-entity-type @id1) :scavenger))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla de reproducción en grupos muy grandes
(defrule reproduce-carnivores
:group
:carnivores
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
;Regla para la agrupación en manadas
(defrule herd-carnivores
:group
:carnivores
:when
(search-cell @cell1
(not (equal (get-cell-type @cell1) :water))
(> (get-cell-entity-type-number @cell1 :carnivore) 2))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;Regla para evitar permanece en una celda contaminada
(defrule contamination-carnivores
:group
:carnivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell-lim @cell1 2
(or (equal (get-cell-type @cell1) :desert) (equal (get-cell-type @cell1) :grass)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;;Reglas que solo se aplican a entidades del grupo :scavengers
;Regla para el consumo de las entidades :scavengers
(defrule food-view-scavengers
:group
:scavengers
:when
(> (get-entity-movements @id) 1)
(view-field-vision @id1
(in (get-entity-type @id1) (get-consumable-type @id))
(< (manhattan-distance @cell (get-entity-coordinates @id1)) 6))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla de reproducción en grupos muy grandes
(defrule reproduce-scavengers
:group
:scavengers
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
;Regla para la agrupación en manadas
(defrule herd-scavengers
:group
:scavengers
:when
(search-cell @cell1
(not (equal (get-cell-type @cell1) :water))
(> (get-cell-entity-type-number @cell1 :scavenger) 2))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;Regla para evitar permanecer en una celda contaminada
(defrule contamination-scavengers
:group
:scavengers
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell-lim @cell1 2
(or (equal (get-cell-type @cell1) :desert) (equal (get-cell-type @cell1) :grass)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;;Las siguientes reglas aplican para los grupos de entidades :carnivores, :scavengers y :herbivores
;Regla para la búsqueda de celdas del tipo :water
(defrule search-water
:group
:all
:when
(not(search-cell @cell1
(equal (get-cell-type @cell1) :water)))
(search-distant-cell @cell1
(equal (get-cell-type @cell1) :grass))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;Regla para recuperar puntos de :water
(defrule drink
:group
:all
:when
(< (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(search-cell @cell1
(or (equal (get-cell-type @cell1) :desert)
(equal (get-cell-type @cell1) :grass))
(area-around @cell1 :water))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal)
(drink-water @id))
| 6,311 | Common Lisp | .lisp | 191 | 29.790576 | 99 | 0.698756 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 06fbaf939ee2efbc2ca34ccc3724370b5fbf14ea710e64d8209a1f51bc431d7f | 23,186 | [
-1
] |
23,187 | Completov2.lisp | SoyOscarRH_AIWithLisp/MicroMundo/Completov2.lisp | ; ==== Start rule (create 10 herbivores) ====
(defrule start
:group :initialization
:when
:do
(set-entities :herbivore 3 :grass)
(set-entities :carnivore 3 :desert)
(set-entities :scavenger 3 :desert))
(defrule move
:group :herbivores
:when
(search-cell @cell1
(equal :desert (get-cell-type @cell1))
(not (area-around @cell1 :water))
(equal 0 (get-cell-entity-type-number @cell1 :herbivore))
(simulate-move @cell2 @cell @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
(defrule move-scab
:group :scavengers
:when
(search-distant-cell @cell1
(simulate-move @cell2 @cell @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
; ==== Eat stuff ====
(defrule feed
:group :all
:when
(< (get-entity-food @id) 60)
(view-field-vision @id1 (in (get-entity-type @id1) (get-consumable-type @id)))
(simulate-move @cell1
(get-entity-coordinates @id)
(get-entity-coordinates @id1)
:diagonal)
:do
(move-entity-to @id (get-entity-coordinates @id1) :diagonal)
(feed-entity @id @id1))
; ==== Drink stuff ====
(defrule drink
:group :all
:when
(< (get-entity-water @id) 50)
(search-cell @cell1
(area-around @cell1 :water)
(not (equal :contamination (get-cell-type @cell1))))
:do
(move-entity-to @id @cell1 :diagonal)
(drink-water @id))
; ==== Not contamited ====
(defrule move-contamination
:group :carnivores-herbivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell @cell1
(not (equal :contamination (get-cell-type @cell1)))
(not (equal :water (get-cell-type @cell1)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
; Find water
(defrule search-water
:group :all
:when
(not (search-cell-lim @cell1 3 (equal (get-cell-type @cell1) :water)))
:do
(move-entity @id :south 3))
(defrule reproduce-car
:group
:carnivores
:when
(>= (get-entity-water @id) 50)
(>= (get-entity-food @id) 50)
(>= (get-entity-days @id) 12)
:do
(reproduce-entity @id))
(defrule reproduce-scar
:group
:herbivores-scavengers
:when
:do
(reproduce-entity @id)) | 2,217 | Common Lisp | .lisp | 82 | 23.743902 | 80 | 0.670588 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 94c96ef5cc0e66ab1358d43d84ac801c3c54a5216d1434e01a83f7424f14a701 | 23,187 | [
-1
] |
23,188 | rules example 2.lisp | SoyOscarRH_AIWithLisp/MicroMundo/rules example 2.lisp | ;Manadas de herbívoros y comiendo carroñeros
;Regla de inicialización de entidades
(defrule start
:group
:initialization
:when
:do
(set-entities :herbivore 5 :desert)
(set-entities :carnivore 5 :desert)
(set-entities :scavenger 5 :desert)
)
;Regla para recuperar puntos de :food
(defrule food-herbivores
:group
:herbivores
:when
(> (get-entity-movements @id) 1)
(< (get-entity-food @id) 100)
(view-field-vision @id1
(in (get-entity-type @id1) (get-consumable-type @id))
(> (get-entity-food @id1) 20))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla de reproducción en grupos grandes
(defrule reproduce-herbivores
:group
:herbivores
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(< (get-entity-type-count @id :herbivore) 15)
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
;Regla de agrupamiento
(defrule herd-herbivores
:group
:herbivores
:when
(search-cell @cell1
(not (equal (get-cell-type @cell1) :water))
(> (get-cell-entity-type-number @cell1 :herbivore) 2))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;Regla para evitar permanece en una celda contaminada
(defrule contamination-herbivores
:group
:herbivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell-lim @cell1 2
(or (equal (get-cell-type @cell1) :desert) (equal (get-cell-type @cell1) :grass)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;;Reglas que solo se aplican a entidades del grupo :carnivores
;Regla para el consumo de :herbivores por los :carnivores
(defrule eating-herbivores
:group
:carnivores
:when
(< (get-entity-food @id) (/ (get-entity-food @id) 2))
(view-field-vision @id1
(equal (get-entity-type @id1) :herbivore)
(> (get-entity-food @id) 20))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla para el consumo de :scavengers por los :carnivores
(defrule eating-scavengers
:group
:carnivores
:when
(< (get-entity-food @id) (/ (get-entity-food @id) 4))
(view-field-vision @id1
(equal (get-entity-type @id1) :scavenger))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal)
(feed-entity @id @id1))
;Regla de reproducción para una población pequeña
(defrule reproduce-carnivores
:group
:carnivores
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(<= (get-entity-type-count @id :carnivore) 10)
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
;Si en su rango de visión existen más de 5 entidades del tipo :carnivore,
;se moviliza a la celda tipo :grass mas lejana
(defrule emigrate-carnivores
:group
:carnivores
:when
(< (get-entity-type-count @id :carnivore) 5)
(search-distant-cell @cell1
(equal (get-cell-type @cell1) :grass))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal)
:do
(move-entity-to @id @cell2 :orthogonal))
;Regla para evitar permanece en una celda contaminada
(defrule contamination-carnivores
:group
:carnivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell-lim @cell1 2
(or (equal (get-cell-type @cell1) :desert) (equal (get-cell-type @cell1) :grass)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;;Reglas que solo se aplican a entidades del grupo :scavengers
;Regla para el consumo de las entidades :scavengers
(defrule food-view-scavengers
:group
:scavengers
:when
(> (get-entity-movements @id) 1)
(view-field-vision @id1
(in (get-entity-type @id1) (get-consumable-type @id))
(< (manhattan-distance @cell (get-entity-coordinates @id1)) 6))
(simulate-move @cell2 (get-entity-coordinates @id) (get-entity-coordinates @id1) :diagonal)
:do
(move-entity-to @id @cell2 :diagonal)
(feed-entity @id @id1))
;Regla de reproducción en grupos muy grandes
(defrule reproduce-scavengers
:group
:scavengers
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(< (get-entity-type-count @id :scavenger) 25)
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
;Regla para la agrupación en manadas
(defrule herd-scavengers
:group
:scavengers
:when
(search-cell @cell1
(not (equal (get-cell-type @cell1) :water))
(> (get-cell-entity-type-number @cell1 :scavenger) 2))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;Regla para evitar permanecer en una celda contaminada
(defrule contamination-scavengers
:group
:scavengers
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell-lim @cell1 2
(or (equal (get-cell-type @cell1) :desert) (equal (get-cell-type @cell1) :grass)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;;Las siguientes reglas aplican para los grupos de entidades :carnivores, :scavengers y :herbivores
;Regla para la búsqueda de celdas del tipo :water
(defrule search-water
:group
:all
:when
(not(search-cell @cell1
(equal (get-cell-type @cell1) :water)))
(search-distant-cell @cell1
(equal (get-cell-type @cell1) :grass))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal))
;Regla para recuperar puntos de :water
(defrule drink
:group
:all
:when
(< (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(search-cell @cell1
(or (equal (get-cell-type @cell1) :desert)
(equal (get-cell-type @cell1) :grass))
(area-around @cell1 :water))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :diagonal)
:do
(move-entity-to @id @cell2 :diagonal)
(drink-water @id))
| 6,448 | Common Lisp | .lisp | 192 | 30.838542 | 99 | 0.711279 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 54cecb9fa96595905d0436a1ddbcc37921f50b5ec0c7d69abb7a94fa02c8075b | 23,188 | [
-1
] |
23,189 | HerbivorosCastrados.lisp | SoyOscarRH_AIWithLisp/MicroMundo/HerbivorosCastrados.lisp | ; ==== Start rule (create 10 herbivores) ====
(defrule start
:group :initialization
:when
:do (set-entities :herbivore 3 :desert))
(defrule move
:group :herbivores
:when
(search-cell @cell1
(equal :desert (get-cell-type @cell1))
(not (area-around @cell1 :water))
(equal 0 (get-cell-entity-type-number @cell1 :herbivore))
(simulate-move @cell2 @cell @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
(defrule move-disperse
:group :herbivores
:when
(view-field-vision @id1
(> 2 (get-entity-type-count @id1 :herbivore))
(equal :desert (get-cell-type (get-entity-coordinates @id1)))
(simulate-move @cell2 @cell (get-entity-coordinates @id1) :diagonal))
:do
(move-entity-to @id (get-entity-coordinates @id1) :diagonal))
; ==== Eat stuff ====
(defrule feed
:group :herbivores
:when
(< (get-entity-food @id) 80)
(view-field-vision @id1 (in (get-entity-type @id1) (get-consumable-type @id)))
(simulate-move @cell1
(get-entity-coordinates @id)
(get-entity-coordinates @id1)
:diagonal)
:do
(move-entity-to @id (get-entity-coordinates @id1) :diagonal)
(feed-entity @id @id1))
; ==== Drink stuff ====
(defrule drink
:group :herbivores
:when
(< (get-entity-water @id) 30)
(search-cell @cell1
(area-around @cell1 :water)
(not (equal :contamination (get-cell-type @cell1))))
:do
(move-entity-to @id @cell1 :diagonal)
(drink-water @id))
; ==== Not contamited ====
(defrule move-contamination
:group :herbivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell @cell1
(not (equal :contamination (get-cell-type @cell1)))
(not (equal :water (get-cell-type @cell1)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
; Find water
(defrule search-water
:group :herbivores
:when
(not (search-cell-lim @cell1 3 (equal (get-cell-type @cell1) :water)))
:do
(move-entity @id :south 3)) | 2,009 | Common Lisp | .lisp | 66 | 27.242424 | 80 | 0.678369 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 2b66c189c3f181f84e7bf22eadc3691ebd81db8e03c325c1c3391d0edaa77b57 | 23,189 | [
-1
] |
23,190 | CompletoSpecialForLagoon.lisp | SoyOscarRH_AIWithLisp/MicroMundo/CompletoSpecialForLagoon.lisp | ; ==== Start rule (create 10 herbivores) ====
(defrule start
:group :initialization
:when
:do
(set-entities :herbivore 3 :grass)
(set-entities :carnivore 3 :desert)
(set-entities :scavenger 3 :desert))
(defrule move
:group :herbivores
:when
(search-cell @cell1
(equal :desert (get-cell-type @cell1))
(not (area-around @cell1 :water))
(equal 0 (get-cell-entity-type-number @cell1 :herbivore))
(simulate-move @cell2 @cell @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
(defrule move-scab
:group :scavengers
:when
(search-distant-cell @cell1
(simulate-move @cell2 @cell @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
; ==== Eat stuff ====
(defrule feed
:group :all
:when
(< (get-entity-food @id) 70)
(view-field-vision @id1 (in (get-entity-type @id1) (get-consumable-type @id)))
(simulate-move @cell1
(get-entity-coordinates @id)
(get-entity-coordinates @id1)
:diagonal)
:do
(move-entity-to @id (get-entity-coordinates @id1) :diagonal)
(feed-entity @id @id1))
; ==== Drink stuff ====
(defrule drink
:group :all
:when
(< (get-entity-water @id) 50)
(search-cell @cell1
(area-around @cell1 :water)
(not (equal :contamination (get-cell-type @cell1))))
:do
(move-entity-to @id @cell1 :diagonal)
(drink-water @id))
; ==== Not contamited ====
(defrule move-contamination
:group :carnivores-herbivores
:when
(equal (get-entity-cell-type @id) :contamination)
(search-cell @cell1
(not (equal :contamination (get-cell-type @cell1)))
(not (equal :water (get-cell-type @cell1)))
(simulate-move @cell2 (get-entity-coordinates @id) @cell1 :orthogonal))
:do
(move-entity-to @id @cell1 :orthogonal))
; Find water
(defrule search-water
:group :all
:when
(not (search-cell-lim @cell1 3 (equal (get-cell-type @cell1) :water)))
:do
(move-entity @id :south 3))
(defrule reproduce-her
:group
:herbivores
:when
(>= (get-entity-water @id) (/ (get-type-water (get-entity-type @id)) 2))
(>= (get-entity-food @id) (/ (get-type-food (get-entity-type @id)) 2))
(>= (get-entity-days @id) 4)
:do
(reproduce-entity @id))
(defrule reproduce-car
:group
:carnivores
:when
(>= (get-entity-water @id) 70)
(>= (get-entity-food @id) 70)
(>= (get-entity-days @id) 20)
:do
(reproduce-entity @id))
(defrule reproduce-scar
:group
:scavengers
:when
:do
(reproduce-entity @id)) | 2,476 | Common Lisp | .lisp | 91 | 23.912088 | 80 | 0.663016 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 080b5ddec0ccb7dea54f2c0ea8fd02d54bcb6fe1fcbc8209e14a98af09f5ade5 | 23,190 | [
-1
] |
23,191 | test.lisp | SoyOscarRH_AIWithLisp/MicroMundo/test.lisp | ; ==== Start rule (create 10 herbivores) ====
(defrule start
:group :initialization
:when
:do (set-entities :herbivore 10 :desert))
(defrule move-dos
:group :herbivores
:when
(view-field-vision @id1
(> 2 (get-entity-type-count @id1 :herbivore))
(equal :desert (get-cell-type (get-entity-coordinates @id1))))
:do
(move-entity-to @id (get-entity-coordinates @id1) :diagonal)) | 391 | Common Lisp | .lisp | 13 | 27.769231 | 65 | 0.703704 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | defe677b815de6733a128cdb0ad381cec3f22ae290c00fd2d069cf61be192fab | 23,191 | [
-1
] |
23,195 | BestFS-3D.lisp | SoyOscarRH_AIWithLisp/Exam1/BestFS-3D.lisp | (load "maze_lib.lisp")
;;; BestF.lisp
;;; Resuelve el problema de los laberintos en 3D usando BEST First Search
;;;
;;; Representación de los estados:
;;; Lista con dos elementos: Un valor de aptitud y una lista (x, y) de su posicion
;;; (aptitud (x y z))
;;;
;;; Oscar Andres Rosas Hernandez
;;; ==================================================
;;; ========= GLOBAL PARAMETERS =========
;;; ==================================================
(defparameter *id* -1) ;; Cantidad de nodos creados
(defparameter *open* ()) ;; Frontera de busqueda.
(defparameter *memory-operations* (make-hash-table)) ;; Memoria de operaciones
(defparameter *memory-ancestor* (make-hash-table)) ;; Memoria de ancestros
(defparameter *expanded* 0) ;; Cuantos estados han sido expandidos
(defparameter *max-frontier* 0) ;; El tamano de la maximo de la frontera
(defparameter *closest* '(9999999999 nil)) ;; Almacena el estado con la mejor solucion
(defparameter *current-ancestor* nil) ;; Almacena al ancestro actual (estado)
(defparameter *aptitude-id* nil) ;; Almacena el nombre de la funcion
(defparameter *operations* '( (:arriba 0)
(:derecha 2)
(:abajo 4)
(:izquierda 6)))
;;; ==================================================
;;; ========= INSERT INTO OPEN =========
;;; ==================================================
(defun insert-in-ordered-list (value state states)
"Inserta en una lista ordenada en O(n)"
(let
((front (first states)))
(if (null states)
(cons state nil)
(if (<= value (first front))
(cons state states)
(cons front (insert-in-ordered-list value state (rest states)))))))
(defun insert-to-open (state)
"Inserta un estado en la posicion correcta en *open*"
(setq *open* (insert-in-ordered-list (first state) state *open*))
(setq *max-frontier* (max (length *open*) *max-frontier*)))
;;; ==================================================
;;; ========= APTITUDES FUNCTIONS =========
;;; ==================================================
(defun Manhattan (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let (
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(+ (abs (- x2 x1)) (abs (- y2 y1)) )))
(defun Euclidean (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let
(
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(sqrt(+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2))))))
(defun aptitude (coordinates)
"Llama a la funcion correcta"
(case *aptitude-id*
(0 (Manhattan coordinates))
(1 (Euclidean coordinates))
))
;;; ==================================================
;;; ========= MEMORY =========
;;; ==================================================
(defun get-hash-point (x y z)
"Te da un ID unico para usarlo como llave en la memoria"
(+(* 2 (+ x (* y (+ 1 (get-maze-rows))))) z))
(defun is-first-time-seeing-this-point? (x y z)
"Predicado. Te regresa si este es la primera vez que veo este estado"
(null (gethash (get-hash-point x y z) *memory-operations*)))
(defun add-to-memory (state operation)
"Añade un estado a la memoria"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(z (third coordinates))
(val (get-hash-point x y z)))
(setf (gethash val *memory-operations*) operation)
(setf (gethash val *memory-ancestor*) *current-ancestor*)))
;;; ==================================================
;;; ====== OLD STATE -> NEW STATE =========
;;; ==================================================
(defun get-bit-list (door-id)
"Helper. Te una lista de 1's y 0's para saber si í-esima puerta esta cerrada"
(loop for i below 4 collect (if (logbitp i door-id) 1 0)))
(defun valid-position? (x y)
"Predicado. Valida un estado según las restricciones generales del problema..."
(let*
(
(rows (get-maze-rows))
(cols (get-maze-cols)))
(and (>= x 0) (>= y 0) (< x rows) (< y cols))))
(defun apply-operator (operation state)
"Predicado. Valida la aplicación de un operador a un estado, si no es valido regresa nil"
(let*
(
(name (first operation))
(coordinates1 (second state))
(x1 (first coordinates1))
(y1 (second coordinates1))
(z1 (third coordinates1))
(x x1)
(y y1)
(x+ (+ x 1) )
(x- (- x 1) )
(y+ (+ y 1) )
(y- (- y 1) )
(coordinates2
(case name
(:arriba (list x- y ))
(:derecha (list x y+))
(:abajo (list x+ y ))
(:izquierda (list x y-))
)
)
(x2 (first coordinates2))
(y2 (second coordinates2))
(z2 0)
)
; Si ni parece valido
(if (not (and (valid-position? x1 y1) (valid-position? x2 y2)))
(return-from apply-operator nil) )
(let*
(
(door (get-cell-walls x1 y1))
(door2 (get-cell-walls x2 y2))
(door-data (get-bit-list door))
(rows (get-maze-rows))
(cols (get-maze-cols))
(vertical (eql (rem (second operation) 4) 0))
)
(if (and (eql door 16) (eql z1 1) vertical)
(return-from apply-operator nil)
)
(if (and (eql door 16) (eql z1 0) (not vertical))
(return-from apply-operator nil)
)
(if (and (eql door 17) (eql z1 0) vertical)
(return-from apply-operator nil)
)
(if (and (eql door 17) (eql z1 1) (not vertical))
(return-from apply-operator nil)
)
(if (> door 15)
(setq door (if vertical 10 5))
)
(if
(not (case name
(:arriba (eql (nth 0 door-data ) 0))
(:derecha (eql (nth 1 door-data ) 0))
(:abajo (eql (nth 2 door-data ) 0))
(:izquierda (eql (nth 3 door-data ) 0))
))
(return-from apply-operator nil)
)
(if
(and
(> door2 15)
(or
(and (eql door2 16) (not vertical))
(and (eql door2 17) vertical)
)
)
(setq z2 1)
)
(if (is-first-time-seeing-this-point? x2 y2 z2)
(list (aptitude (list x2 y2 z2) ) (list x2 y2 z2)) nil)
)))
;;; ==================================================
;;; ====== EXPAND STATE =========
;;; ==================================================
(defun update-closest-state (state)
"Get better node"
(if
(< (first state) (first *closest*))
(setq *closest* state)))
(defun expand (state)
"Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *operations*"
(setq *current-ancestor* state)
(let
((new-state nil))
(incf *expanded*)
(dolist (operation *operations*)
(setq new-state (apply-operator operation state))
(cond
((not (null new-state))
(incf *id*)
(update-closest-state new-state)
(add-to-memory new-state (second operation))
(insert-to-open new-state) )))))
;;; ==================================================
;;; ====== SOLUTION =========
;;; ==================================================
(defun extract-solution (state)
"Rastrea en *memory* todos los descendientes de state hasta llegar al estado inicial"
(let
(
(current state)
(operation nil)
(ansestor nil)
(value nil))
(loop while (not (null current)) do
(setq value (get-hash-point (first (second current)) (second (second current)) (third (second current)) ))
(setq operation (gethash value *memory-operations*))
(setq ansestor (gethash value *memory-ancestor*))
(setq current ansestor)
(push operation *solution*))
(setq *solution* (rest *solution*))))
(defun display-solution ()
"Despliega la solución en forma conveniente y numerando los pasos"
(format t "~%La solucion es: ~A ~%~%" *solution*)
(format t "1) Solución con ~A pasos (Longitud de la solución)~%" (length *solution*))
(format t "2) ~A nodos creados ~%" *id*)
(format t "3) ~A nodos expandidos ~%" *expanded*)
(format t "4) Longitud máxima de la Frontera de búsqueda: ~A~%" *max-frontier*))
(defun reset-all ()
"Reinicia todas las variables globales para realizar una nueva búsqueda..."
(setq *id* -1)
(setq *open* ())
(setq *memory-operations* (make-hash-table))
(setq *memory-ancestor* (make-hash-table))
(setq *expanded* 0)
(setq *max-frontier* 0)
(setq *closest* '(9999999999 nil))
(setq *current-ancestor* nil))
(defun get-start ()
"Te regresa el estado inicial"
(let*
(
(x (aref *start* 0))
(y (aref *start* 1))
(z 0)
(coordinate (list x y z)))
(list (aptitude coordinate) coordinate)))
(defun get-goal ()
"Te regresa el estado inicial"
(let*
(
(x (aref *goal* 0))
(y (aref *goal* 1))
(z 0)
(coordinate (list x y z)))
(list (aptitude coordinate) coordinate)))
;;; ==================================================
;;; ====== BESTFS =========
;;; ==================================================
(defun BestFSearch ()
"Realiza una búsqueda best First, desde un estado inicial hasta un estado meta"
(reset-all)
(let
(
(start (get-start))
(goal (get-goal))
(current nil)
(sucesores nil)
(goal-found nil))
(insert-to-open start)
(add-to-memory start -1)
(time
(loop until (or goal-found (null *open*)) do
(setq current (pop *open*))
(cond
((equal goal current)
(setq goal-found T)
(format t "Éxito. Meta encontrada ~%")
)
(t
(expand current)
(if (null *open*)
(progn
(format t "Lo intenté.%")
(setq current *closest*)
))
))
)
)
(extract-solution current)
(display-solution))
(print (get-maze-data))
(print *start*)
(print *goal*))
(defun BestFSearch-Manhattan ()
(setq *aptitude-id* 0)
(BestFSearch))
(defun BestFSearch-Euclidean ()
(setq *aptitude-id* 1)
(BestFSearch))
(add-algorithm 'BestFSearch-Manhattan)
(add-algorithm 'BestFSearch-Euclidean)
(start-maze)
| 11,637 | Common Lisp | .lisp | 298 | 31.312081 | 128 | 0.48674 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 5bceb296dfaa31b17102d14d0fb3d465db988f70a75def811193fac8ad19a655 | 23,195 | [
-1
] |
23,196 | AStar-2D.lisp | SoyOscarRH_AIWithLisp/Exam1/AStar-2D.lisp | (load "maze_lib.lisp")
;;; BestF.lisp
;;; Resuelve el problema de los laberintos usando A*
;;;
;;; Representación de los estados:
;;; Lista con dos elementos: Un valor de aptitud y una lista (x, y) de su posicion
;;; (aptitud (x y))
;;;
;;; Oscar Andres Rosas Hernandez
;;; ==================================================
;;; ========= GLOBAL PARAMETERS =========
;;; ==================================================
(defparameter *id* -1) ;; Cantidad de nodos creados
(defparameter *open* ()) ;; Frontera de busqueda.
(defparameter *memory-open* (make-hash-table)) ;; Memoria de operaciones
(defparameter *memory-operations* (make-hash-table)) ;; Memoria de operaciones
(defparameter *memory-ancestor* (make-hash-table)) ;; Memoria de ancestros
(defparameter *memory-distance* (make-hash-table)) ;; Memoria de la distancia a ese nodo
(defparameter *expanded* 0) ;; Cuantos estados han sido expandidos
(defparameter *max-frontier* 0) ;; El tamano de la maximo de la frontera
(defparameter *closest* '(9999999999 nil)) ;; Almacena el estado con la mejor solucion
(defparameter *current-ancestor* nil) ;; Almacena al ancestro actual (estado)
(defparameter *aptitude-id* nil) ;; Almacena el nombre de la funcion
(defparameter *operations* '((:arriba 0 )
(:arriba-derecha 1 )
(:derecha 2 )
(:abajo-derecha 3 )
(:abajo 4 )
(:abajo-izquierda 5 )
(:izquierda 6 )
(:arriba-izquierda 7 )))
;;; ==================================================
;;; ========= INSERT INTO OPEN =========
;;; ==================================================
(defun insert-in-ordered-list (value state states)
"Inserta en una lista ordenada en O(n)"
(let
((front (first states)))
(if (null states)
(cons state nil)
(if (<= value (first front))
(cons state states)
(cons front (insert-in-ordered-list value state (rest states)))))))
(defun insert-to-open (state)
"Inserta un estado en la posicion correcta en *open*"
(setq *open* (insert-in-ordered-list (first state) state *open*))
(setq *max-frontier* (max (length *open*) *max-frontier*)))
(defun delete-from-ordered-list (coordinates states)
"Elimina en una lista ordenada en O(n)"
(if (null states) (return-from delete-from-ordered-list nil))
(let
(
(front (first states))
(end (rest states)))
(if (equal coordinates (second front))
end
(cons front (delete-from-ordered-list coordinates end)))))
;;; ==================================================
;;; ========= APTITUDES FUNCTIONS =========
;;; ==================================================
(defun Manhattan (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let (
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(+ (abs (- x2 x1)) (abs (- y2 y1)) )))
(defun Euclidean (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let
(
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(sqrt(+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2))))))
(defun aptitude (coordinates)
"Llama a la funcion correcta"
(case *aptitude-id*
(0 (Manhattan coordinates))
(1 (Euclidean coordinates))
))
(defun get-cost-and-aptitude (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let
(
(aptitude-value (aptitude coordinates))
(distance-value (get-distance (list 0 coordinates))))
(+ aptitude-value distance-value)))
;;; ==================================================
;;; ========= MEMORY =========
;;; ==================================================
(defun get-hash-point (x y)
"Te da un ID unico para usarlo como llave en la memoria"
(+ x (* y (+ 1 (get-maze-rows)))))
(defun is-first-time-seeing-this-point? (x y)
"Predicado. Te regresa si este es la primera vez que veo este estado"
(null (gethash (get-hash-point x y) *memory-operations*)))
(defun add-to-memory (state operation)
"Añade un estado a la memoria"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(val (get-hash-point x y)))
(setf (gethash val *memory-operations*) operation)
(setf (gethash val *memory-ancestor*) *current-ancestor*)))
;;; ==================================================
;;; ========= DISTANCE (NODE'S DEPTH) ========
;;; ==================================================
(defun set-distance (state distance)
"Anadelo a memoria"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(val (get-hash-point x y)))
(setf (gethash val *memory-distance*) distance)))
(defun get-distance (state)
"Obten su valor en memoria, si no esta dale un 0 (origen)"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(val (get-hash-point x y))
(distance (gethash val *memory-distance*))
)
(if (null distance) 0 distance)))
;;; ==================================================
;;; ====== OLD STATE -> NEW STATE =========
;;; ==================================================
(defun get-bit-list (door-id)
"Helper. Te una lista de 1's y 0's para saber si í-esima puerta esta cerrada"
(loop for i below 4 collect (if (logbitp i door-id) 1 0)))
(defun valid-position? (x y)
"Predicado. Valida un estado según las restricciones generales del problema..."
(let*
((rows (get-maze-rows)) (cols (get-maze-cols)))
(and (>= x 0) (>= y 0) (< x rows) (< y cols))))
(defun valid-operator? (op state)
"Predicado. Valida la aplicación de un operador a un estado, se supone el estado valido"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(x+ (+ x 1) )
(x- (- x 1) )
(y+ (+ y 1) )
(y- (- y 1) )
(name (first op))
(doors
(if (valid-position? x y)
(get-bit-list (get-cell-walls x y))
nil ) )
(p0 (nth 0 doors))
(p1 (nth 1 doors))
(p2 (nth 2 doors))
(p3 (nth 3 doors))
(rows (get-maze-rows))
(cols (get-maze-cols)) )
(case name
(:arriba (and (> x 0) (eql p0 0) (is-first-time-seeing-this-point? x- y)))
(:derecha (and (< y+ cols) (eql p1 0) (is-first-time-seeing-this-point? x y+)))
(:abajo (and (< x+ rows) (eql p2 0) (is-first-time-seeing-this-point? x+ y)))
(:izquierda (and (> y 0) (eql p3 0) (is-first-time-seeing-this-point? x y-)))
(:arriba-derecha (and (> x 0) (< y+ cols) (is-first-time-seeing-this-point? x- y+)
(let* (
(derecha-door (get-bit-list (get-cell-walls x y+)))
(arriba-door (get-bit-list (get-cell-walls x- y)))
(p0-derecha (nth 0 derecha-door))
(p1-arriba (nth 1 arriba-door))
)
(or (and (eql 0 p0) (eql 0 p1-arriba)) (and (eql 0 p1) (eql 0 p0-derecha))))))
(:abajo-derecha (and (< x+ rows) (< y+ cols) (is-first-time-seeing-this-point? x+ y+)
(let* (
(derecha-door (get-bit-list (get-cell-walls x y+)))
(abajo-door (get-bit-list (get-cell-walls x+ y)))
(p1-abajo (nth 1 abajo-door))
(p2-derecha (nth 2 derecha-door))
)
(or (and (eql 0 p1) (eql 0 p2-derecha)) (and (eql 0 p2) (eql 0 p1-abajo))))))
(:abajo-izquierda (and (< x+ rows) (> y 0) (is-first-time-seeing-this-point? x+ y-)
(let* (
(izquierda-door (get-bit-list (get-cell-walls x y-)))
(abajo-door (get-bit-list (get-cell-walls x+ y)))
(p2-izquierda (nth 2 izquierda-door))
(p3-abajo (nth 3 abajo-door))
)
(or (and (eql 0 p2) (eql 0 p3-abajo)) (and (eql 0 p3) (eql 0 p2-izquierda))))))
(:arriba-izquierda (and (> x 0) (> y 0) (is-first-time-seeing-this-point? x- y-)
(let* (
(arriba-door (get-bit-list (get-cell-walls x- y)))
(izquierda-door (get-bit-list (get-cell-walls x y-)))
(p3-arriba (nth 3 arriba-door))
(p0-izquierda (nth 0 izquierda-door))
)
(or (and (eql 0 p3) (eql 0 p0-izquierda)) (and (eql 0 p0) (eql 0 p3-arriba))))))
)
) )
(defun apply-operator (operation state)
"Obtiene el descendiente de un estado al aplicarle una operacion SIN VALIDACIONES"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(x+ (+ x 1))
(x- (- x 1))
(y+ (+ y 1))
(y- (- y 1))
(name (first operation))
(new-coordinates
(case name
(:arriba (list x- y ))
(:arriba-derecha (list x- y+))
(:derecha (list x y+))
(:abajo-derecha (list x+ y+))
(:abajo (list x+ y ))
(:abajo-izquierda (list x+ y-))
(:izquierda (list x y-))
(:arriba-izquierda (list x- y-)))))
(list (get-cost-and-aptitude new-coordinates) new-coordinates)))
;;; ==================================================
;;; ====== EXPAND STATE =========
;;; ==================================================
(defun update-closest-state (state)
"Get better node"
(if
(< (first state) (first *closest*))
(setq *closest* state)))
(defun get-hash-coordinate (coordinate)
"Get better node"
(let*
(
(x (first coordinate))
(y (second coordinate)))
(get-hash-point x y)))
(defun expand (state)
"Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *operations*"
(setq *current-ancestor* state)
(let*
(
(val (get-hash-coordinate (second state)))
(new-state nil)
(pre-value nil))
(incf *expanded*)
(setf (gethash val *memory-open*) Nil) ; Ya no estoy en open
(dolist (operation *operations*)
(cond
((valid-operator? operation state)
(incf *id*)
(setq new-state (apply-operator operation state))
(update-closest-state new-state)
(setq pre-value (gethash (get-hash-coordinate (second new-state)) *memory-open*))
(set-distance
new-state
(+ 1 (get-distance *current-ancestor*)))
(add-to-memory new-state (second operation))
(if
(and (not (null pre-value)) (< pre-value (first new-state)))
(delete-from-open (second new-state)))
(insert-to-open new-state))))))
;;; ==================================================
;;; ====== SOLUTION =========
;;; ==================================================
(defun extract-solution (state)
"Rastrea en *memory* todos los descendientes de state hasta llegar al estado inicial"
(let
(
(current state)
(operation nil)
(ansestor nil)
(value nil))
(loop while (not (null current)) do
(setq value (get-hash-point (first (second current)) (second (second current)) ))
(setq operation (gethash value *memory-operations*))
(setq ansestor (gethash value *memory-ancestor*))
(setq current ansestor)
(push operation *solution*))
(setq *solution* (rest *solution*))))
(defun display-solution ()
"Despliega la solución en forma conveniente y numerando los pasos"
(format t "~%La solucion es: ~A ~%~%" *solution*)
(format t "1) Solución con ~A pasos (Longitud de la solución)~%" (length *solution*))
(format t "2) ~A nodos creados ~%" *id*)
(format t "3) ~A nodos expandidos ~%" *expanded*)
(format t "4) Longitud máxima de la Frontera de búsqueda: ~A~%" *max-frontier*))
(defun reset-all ()
"Reinicia todas las variables globales para realizar una nueva búsqueda..."
(setq *id* -1)
(setq *open* ())
(setq *memory-operations* (make-hash-table))
(setq *memory-ancestor* (make-hash-table))
(setq *expanded* 0)
(setq *max-frontier* 0)
(setq *closest* '(9999999999 nil))
(setq *current-ancestor* nil))
(defun get-start ()
"Te regresa el estado inicial"
(let*
(
(x (aref *start* 0))
(y (aref *start* 1))
(coordinate (list x y)))
(list (aptitude coordinate) coordinate)))
(defun get-goal ()
"Te regresa el estado inicial"
(let*
(
(x (aref *goal* 0))
(y (aref *goal* 1))
(coordinate (list x y)))
(list (aptitude coordinate) coordinate)))
(defun AStar ()
"Realiza una búsqueda A*, desde un estado inicial hasta un estado meta"
(reset-all)
(let
(
(start (get-start))
(goal (get-goal))
(current nil)
(sucesores nil)
(goal-found nil))
(insert-to-open start)
(add-to-memory start -1)
(time
(loop until (or goal-found (null *open*)) do
(setq current (pop *open*))
(cond
((equal goal current)
(setq goal-found T)
(format t "Éxito. Meta encontrada ~%")
)
(t
(expand current)
(if (null *open*)
(progn
(format t "Lo intenté.%")
(setq current *closest*)
))
))
)
)
(extract-solution current)
(display-solution))
(print (get-maze-data))
(print *start*)
(print *goal*))
(defun AStar-Manhattan ()
(setq *aptitude-id* 0)
(AStar))
(defun AStar-Euclidean ()
(setq *aptitude-id* 1)
(AStar))
(add-algorithm 'AStar-Manhattan)
(add-algorithm 'AStar-Euclidean)
(start-maze) | 15,120 | Common Lisp | .lisp | 362 | 33.870166 | 127 | 0.504216 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | f847a988c6d9e86d81eb3d77f9ac507b2ba25e068d3052f46a274cd3905701ff | 23,196 | [
-1
] |
23,197 | BestFS-2D.lisp | SoyOscarRH_AIWithLisp/Exam1/BestFS-2D.lisp | (load "maze_lib.lisp")
;;; BestF.lisp
;;; Resuelve el problema de los laberintos usando BEST First Search
;;;
;;; Representación de los estados:
;;; Lista con dos elementos: Un valor de aptitud y una lista (x, y) de su posicion
;;; (aptitud (x y))
;;;
;;; Oscar Andres Rosas Hernandez
;;; ==================================================
;;; ========= GLOBAL PARAMETERS =========
;;; ==================================================
(defparameter *id* -1) ;; Cantidad de nodos creados
(defparameter *open* ()) ;; Frontera de busqueda.
(defparameter *memory-operations* (make-hash-table)) ;; Memoria de operaciones
(defparameter *memory-ancestor* (make-hash-table)) ;; Memoria de ancestros
(defparameter *expanded* 0) ;; Cuantos estados han sido expandidos
(defparameter *max-frontier* 0) ;; El tamano de la maximo de la frontera
(defparameter *closest* '(9999999999 nil)) ;; Almacena el estado con la mejor solucion
(defparameter *current-ancestor* nil) ;; Almacena al ancestro actual (estado)
(defparameter *aptitude-id* nil) ;; Almacena el nombre de la funcion
(defparameter *operations* '((:arriba 0 )
(:arriba-derecha 1 )
(:derecha 2 )
(:abajo-derecha 3 )
(:abajo 4 )
(:abajo-izquierda 5 )
(:izquierda 6 )
(:arriba-izquierda 7 )))
;;; ==================================================
;;; ========= INSERT INTO OPEN =========
;;; ==================================================
(defun insert-in-ordered-list (value state states)
"Inserta en una lista ordenada en O(n)"
(let
((front (first states)))
(if (null states)
(cons state nil)
(if (<= value (first front))
(cons state states)
(cons front (insert-in-ordered-list value state (rest states)))))))
(defun insert-to-open (state)
"Inserta un estado en la posicion correcta en *open*"
(setq *open* (insert-in-ordered-list (first state) state *open*))
(setq *max-frontier* (max (length *open*) *max-frontier*)))
;;; ==================================================
;;; ========= APTITUDES FUNCTIONS =========
;;; ==================================================
(defun Manhattan (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let (
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(+ (abs (- x2 x1)) (abs (- y2 y1)) )))
(defun Euclidean (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let
(
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(sqrt(+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2))))))
(defun aptitude (coordinates)
"Llama a la funcion correcta"
(case *aptitude-id*
(0 (Manhattan coordinates))
(1 (Euclidean coordinates))
))
;;; ==================================================
;;; ========= MEMORY =========
;;; ==================================================
(defun get-hash-point (x y)
"Te da un ID unico para usarlo como llave en la memoria"
(+ x (* y (+ 1 (get-maze-rows)))))
(defun is-first-time-seeing-this-point? (x y)
"Predicado. Te regresa si este es la primera vez que veo este estado"
(null (gethash (get-hash-point x y) *memory-operations*)))
(defun add-to-memory (state operation)
"Añade un estado a la memoria"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(val (get-hash-point x y)))
(setf (gethash val *memory-operations*) operation)
(setf (gethash val *memory-ancestor*) *current-ancestor*)))
;;; ==================================================
;;; ====== OLD STATE -> NEW STATE =========
;;; ==================================================
(defun get-bit-list (door-id)
"Helper. Te una lista de 1's y 0's para saber si í-esima puerta esta cerrada"
(loop for i below 4 collect (if (logbitp i door-id) 1 0)))
(defun valid-position? (x y)
"Predicado. Valida un estado según las restricciones generales del problema..."
(let*
((rows (get-maze-rows)) (cols (get-maze-cols)))
(and (>= x 0) (>= y 0) (< x rows) (< y cols))))
(defun valid-operator? (operation state)
"Predicado. Valida la aplicación de un operador a un estado, se supone un estado valido"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates)))
(if (not (valid-position? x y)) (return-from valid-operator? nil)))
(let*
(
(name (first operation))
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(x+ (+ x 1))
(x- (- x 1))
(y+ (+ y 1))
(y- (- y 1))
(doors (get-bit-list (get-cell-walls x y)))
(p0 (nth 0 doors))
(p1 (nth 1 doors))
(p2 (nth 2 doors))
(p3 (nth 3 doors))
(rows (get-maze-rows))
(cols (get-maze-cols)))
(case name
(:arriba (and (> x 0) (eql p0 0) (is-first-time-seeing-this-point? x- y)))
(:derecha (and (< y+ cols) (eql p1 0) (is-first-time-seeing-this-point? x y+)))
(:abajo (and (< x+ rows) (eql p2 0) (is-first-time-seeing-this-point? x+ y)))
(:izquierda (and (> y 0) (eql p3 0) (is-first-time-seeing-this-point? x y-)))
(:arriba-derecha (and (> x 0) (< y+ cols) (is-first-time-seeing-this-point? x- y+)
(let* (
(derecha-door (get-bit-list (get-cell-walls x y+)))
(arriba-door (get-bit-list (get-cell-walls x- y)))
(p0-derecha (nth 0 derecha-door))
(p1-arriba (nth 1 arriba-door))
)
(or (and (eql 0 p0) (eql 0 p1-arriba)) (and (eql 0 p1) (eql 0 p0-derecha))))))
(:abajo-derecha (and (< x+ rows) (< y+ cols) (is-first-time-seeing-this-point? x+ y+)
(let* (
(derecha-door (get-bit-list (get-cell-walls x y+)))
(abajo-door (get-bit-list (get-cell-walls x+ y)))
(p1-abajo (nth 1 abajo-door))
(p2-derecha (nth 2 derecha-door))
)
(or (and (eql 0 p1) (eql 0 p2-derecha)) (and (eql 0 p2) (eql 0 p1-abajo))))))
(:abajo-izquierda (and (< x+ rows) (> y 0) (is-first-time-seeing-this-point? x+ y-)
(let* (
(izquierda-door (get-bit-list (get-cell-walls x y-)))
(abajo-door (get-bit-list (get-cell-walls x+ y)))
(p2-izquierda (nth 2 izquierda-door))
(p3-abajo (nth 3 abajo-door))
)
(or (and (eql 0 p2) (eql 0 p3-abajo)) (and (eql 0 p3) (eql 0 p2-izquierda))))))
(:arriba-izquierda (and (> x 0) (> y 0) (is-first-time-seeing-this-point? x- y-)
(let* (
(arriba-door (get-bit-list (get-cell-walls x- y)))
(izquierda-door (get-bit-list (get-cell-walls x y-)))
(p3-arriba (nth 3 arriba-door))
(p0-izquierda (nth 0 izquierda-door))
)
(or (and (eql 0 p3) (eql 0 p0-izquierda)) (and (eql 0 p0) (eql 0 p3-arriba))))))
)))
(defun apply-operator (operation state)
"Obtiene el descendiente de un estado al aplicarle una operacion SIN VALIDACIONES"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(x+ (+ x 1))
(x- (- x 1))
(y+ (+ y 1))
(y- (- y 1))
(name (first operation))
(new-coordinates
(case name
(:arriba (list x- y ))
(:arriba-derecha (list x- y+))
(:derecha (list x y+))
(:abajo-derecha (list x+ y+))
(:abajo (list x+ y ))
(:abajo-izquierda (list x+ y-))
(:izquierda (list x y-))
(:arriba-izquierda (list x- y-)))))
(list (aptitude new-coordinates) new-coordinates)))
;;; ==================================================
;;; ====== EXPAND STATE =========
;;; ==================================================
(defun update-closest-state (state)
"Get better node"
(if
(< (first state) (first *closest*))
(setq *closest* state)))
(defun expand (state)
"Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *operations*"
(setq *current-ancestor* state)
(let
((new-state nil))
(incf *expanded*)
(dolist (operation *operations*)
(cond
((valid-operator? operation state)
(incf *id*)
(setq new-state (apply-operator operation state))
(update-closest-state new-state)
(add-to-memory new-state (second operation))
(insert-to-open new-state) )))))
;;; ==================================================
;;; ====== SOLUTION =========
;;; ==================================================
(defun extract-solution (state)
"Rastrea en *memory* todos los descendientes de state hasta llegar al estado inicial"
(let
(
(current state)
(operation nil)
(ansestor nil)
(value nil))
(loop while (not (null current)) do
(setq value (get-hash-point (first (second current)) (second (second current)) ))
(setq operation (gethash value *memory-operations*))
(setq ansestor (gethash value *memory-ancestor*))
(setq current ansestor)
(push operation *solution*))
(setq *solution* (rest *solution*))))
(defun display-solution ()
"Despliega la solución en forma conveniente y numerando los pasos"
(format t "~%La solucion es: ~A ~%~%" *solution*)
(format t "1) Solución con ~A pasos (Longitud de la solución)~%" (length *solution*))
(format t "2) ~A nodos creados ~%" *id*)
(format t "3) ~A nodos expandidos ~%" *expanded*)
(format t "4) Longitud máxima de la Frontera de búsqueda: ~A~%" *max-frontier*))
(defun reset-all ()
"Reinicia todas las variables globales para realizar una nueva búsqueda..."
(setq *id* -1)
(setq *open* ())
(setq *memory-operations* (make-hash-table))
(setq *memory-ancestor* (make-hash-table))
(setq *expanded* 0)
(setq *max-frontier* 0)
(setq *closest* '(9999999999 nil))
(setq *current-ancestor* nil))
(defun get-start ()
"Te regresa el estado inicial"
(let*
(
(x (aref *start* 0))
(y (aref *start* 1))
(coordinate (list x y)))
(list (aptitude coordinate) coordinate)))
(defun get-goal ()
"Te regresa el estado inicial"
(let*
(
(x (aref *goal* 0))
(y (aref *goal* 1))
(coordinate (list x y)))
(list (aptitude coordinate) coordinate)))
;;; ==================================================
;;; ====== BESTFS =========
;;; ==================================================
(defun BestFSearch ()
"Realiza una búsqueda best First, desde un estado inicial hasta un estado meta"
(reset-all)
(let
(
(start (get-start))
(goal (get-goal))
(current nil)
(sucesores nil)
(goal-found nil))
(insert-to-open start)
(add-to-memory start -1)
(time
(loop until (or goal-found (null *open*)) do
(setq current (pop *open*))
(cond
((equal goal current)
(setq goal-found T)
(format t "Éxito. Meta encontrada ~%")
)
(t
(expand current)
(if (null *open*)
(progn
(format t "Lo intenté.%")
(setq current *closest*)
))
))
)
)
(extract-solution current)
(display-solution))
(print (get-maze-data))
(print *start*)
(print *goal*))
(defun BestFSearch-Manhattan ()
(setq *aptitude-id* 0)
(BestFSearch))
(defun BestFSearch-Euclidean ()
(setq *aptitude-id* 1)
(BestFSearch))
(add-algorithm 'BestFSearch-Manhattan)
(add-algorithm 'BestFSearch-Euclidean)
(start-maze) | 13,042 | Common Lisp | .lisp | 307 | 34.905537 | 128 | 0.495562 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d8836fbf466a99a1f8d733ef18874f9aa5a4d28fc6d32cfe68a9bdb0bcbc7981 | 23,197 | [
-1
] |
23,199 | AStar-3D.lisp | SoyOscarRH_AIWithLisp/Exam1/AStar-3D.lisp | (load "maze_lib.lisp")
;;; BestF.lisp
;;; Resuelve el problema de los laberintos usando A*
;;;
;;; Representación de los estados:
;;; Lista con dos elementos: Un valor de aptitud y una lista (x, y) de su posicion
;;; (aptitud (x y))
;;;
;;; Oscar Andres Rosas Hernandez
;;; ==================================================
;;; ========= GLOBAL PARAMETERS =========
;;; ==================================================
(defparameter *id* -1) ;; Cantidad de nodos creados
(defparameter *open* ()) ;; Frontera de busqueda.
(defparameter *memory-open* (make-hash-table)) ;; Memoria de operaciones
(defparameter *memory-operations* (make-hash-table)) ;; Memoria de operaciones
(defparameter *memory-ancestor* (make-hash-table)) ;; Memoria de ancestros
(defparameter *memory-distance* (make-hash-table)) ;; Memoria de la distancia a ese nodo
(defparameter *expanded* 0) ;; Cuantos estados han sido expandidos
(defparameter *max-frontier* 0) ;; El tamano de la maximo de la frontera
(defparameter *closest* '(9999999999 nil)) ;; Almacena el estado con la mejor solucion
(defparameter *current-ancestor* nil) ;; Almacena al ancestro actual (estado)
(defparameter *aptitude-id* nil) ;; Almacena el nombre de la funcion
(defparameter *operations* '( (:arriba 0)
(:derecha 2)
(:abajo 4)
(:izquierda 6)))
;;; ==================================================
;;; ========= INSERT INTO OPEN =========
;;; ==================================================
(defun insert-in-ordered-list (value state states)
"Inserta en una lista ordenada en O(n)"
(let
((front (first states)))
(if (null states)
(cons state nil)
(if (<= value (first front))
(cons state states)
(cons front (insert-in-ordered-list value state (rest states)))))))
(defun insert-to-open (state)
"Inserta un estado en la posicion correcta en *open*"
(setq *open* (insert-in-ordered-list (first state) state *open*))
(setq *max-frontier* (max (length *open*) *max-frontier*)))
(defun delete-from-ordered-list (coordinates states)
"Elimina en una lista ordenada en O(n)"
(if (null states) (return-from delete-from-ordered-list nil))
(let
(
(front (first states))
(end (rest states)))
(if (equal coordinates (second front))
end
(cons front (delete-from-ordered-list coordinates end)))))
;;; ==================================================
;;; ========= APTITUDES FUNCTIONS =========
;;; ==================================================
(defun Manhattan (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let (
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(+ (abs (- x2 x1)) (abs (- y2 y1)) )))
(defun Euclidean (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let
(
(x1 (first coordinates))
(y1 (second coordinates))
(x2 (aref *goal* 0))
(y2 (aref *goal* 1)))
(sqrt(+ (* (- x1 x2) (- x1 x2)) (* (- y1 y2) (- y1 y2))))))
(defun aptitude (coordinates)
"Llama a la funcion correcta"
(case *aptitude-id*
(0 (Manhattan coordinates))
(1 (Euclidean coordinates))
))
(defun get-cost-and-aptitude (coordinates)
"Te regresa el valor de aptitud de un nodo, mientras mas pequeño mejor"
(let
(
(aptitude-value (aptitude coordinates))
(distance-value (get-distance (list 0 coordinates))))
(+ aptitude-value distance-value)))
;;; ==================================================
;;; ========= MEMORY =========
;;; ==================================================
(defun get-hash-point (x y z)
"Te da un ID unico para usarlo como llave en la memoria"
(+(* 2 (+ x (* y (+ 1 (get-maze-rows))))) z))
(defun is-first-time-seeing-this-point? (x y z)
"Predicado. Te regresa si este es la primera vez que veo este estado"
(null (gethash (get-hash-point x y z) *memory-operations*)))
(defun add-to-memory (state operation)
"Añade un estado a la memoria"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(z (third coordinates))
(val (get-hash-point x y z)))
(setf (gethash val *memory-operations*) operation)
(setf (gethash val *memory-ancestor*) *current-ancestor*)))
;;; ==================================================
;;; ========= DISTANCE (NODE'S DEPTH) ========
;;; ==================================================
(defun set-distance (state distance)
"Anadelo a memoria"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(z (third coordinates))
(val (get-hash-point x y z)))
(setf (gethash val *memory-distance*) distance)))
(defun get-distance (state)
"Obten su valor en memoria, si no esta dale un 0 (origen)"
(let*
(
(coordinates (second state))
(x (first coordinates))
(y (second coordinates))
(z (third coordinates))
(val (get-hash-point x y z))
(distance (gethash val *memory-distance*))
)
(if (null distance) 0 distance)))
;;; ==================================================
;;; ====== OLD STATE -> NEW STATE =========
;;; ==================================================
(defun get-bit-list (door-id)
"Helper. Te una lista de 1's y 0's para saber si í-esima puerta esta cerrada"
(loop for i below 4 collect (if (logbitp i door-id) 1 0)))
(defun valid-position? (x y)
"Predicado. Valida un estado según las restricciones generales del problema..."
(let*
((rows (get-maze-rows)) (cols (get-maze-cols)))
(and (>= x 0) (>= y 0) (< x rows) (< y cols))))
(defun apply-operator (operation state)
"Predicado. Valida la aplicación de un operador a un estado, si no es valido regresa nil"
(let*
(
(name (first operation))
(coordinates1 (second state))
(x1 (first coordinates1))
(y1 (second coordinates1))
(z1 (third coordinates1))
(x x1)
(y y1)
(x+ (+ x 1) )
(x- (- x 1) )
(y+ (+ y 1) )
(y- (- y 1) )
(coordinates2
(case name
(:arriba (list x- y ))
(:derecha (list x y+))
(:abajo (list x+ y ))
(:izquierda (list x y-))
)
)
(x2 (first coordinates2))
(y2 (second coordinates2))
(z2 0)
)
; Si ni parece valido
(if (not (and (valid-position? x1 y1) (valid-position? x2 y2)))
(return-from apply-operator nil) )
(let*
(
(door (get-cell-walls x1 y1))
(door2 (get-cell-walls x2 y2))
(door-data (get-bit-list door))
(rows (get-maze-rows))
(cols (get-maze-cols))
(vertical (eql (rem (second operation) 4) 0))
)
(if (and (eql door 16) (eql z1 1) vertical)
(return-from apply-operator nil)
)
(if (and (eql door 16) (eql z1 0) (not vertical))
(return-from apply-operator nil)
)
(if (and (eql door 17) (eql z1 0) vertical)
(return-from apply-operator nil)
)
(if (and (eql door 17) (eql z1 1) (not vertical))
(return-from apply-operator nil)
)
(if (> door 15)
(setq door (if vertical 10 5))
)
(if
(not (case name
(:arriba (eql (nth 0 door-data ) 0))
(:derecha (eql (nth 1 door-data ) 0))
(:abajo (eql (nth 2 door-data ) 0))
(:izquierda (eql (nth 3 door-data ) 0))
))
(return-from apply-operator nil)
)
(if
(and
(> door2 15)
(or
(and (eql door2 16) (not vertical))
(and (eql door2 17) vertical)
)
)
(setq z2 1)
)
(if (is-first-time-seeing-this-point? x2 y2 z2)
(list (get-cost-and-aptitude (list x2 y2 z2) ) (list x2 y2 z2)) nil)
)))
;;; ==================================================
;;; ====== EXPAND STATE =========
;;; ==================================================
(defun update-closest-state (state)
"Get better node"
(if
(< (first state) (first *closest*))
(setq *closest* state)))
(defun get-hash-coordinate (coordinate)
"Get better node"
(let*
(
(x (first coordinate))
(y (second coordinate))
(z (second coordinate)))
(get-hash-point x y z)))
(defun expand (state)
"Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *operations*"
(setq *current-ancestor* state)
(let*
(
(val (get-hash-coordinate (second state)))
(new-state nil)
(pre-value nil))
(incf *expanded*)
(setf (gethash val *memory-open*) Nil) ; Ya no estoy en open
(dolist (operation *operations*)
(setq new-state (apply-operator operation state))
(cond
((not (null new-state))
(incf *id*)
(update-closest-state new-state)
(setq pre-value (gethash (get-hash-coordinate (second new-state)) *memory-open*))
(set-distance
new-state
(+ 1 (get-distance *current-ancestor*)))
(add-to-memory new-state (second operation))
(if
(and (not (null pre-value)) (< pre-value (first new-state)))
(delete-from-open (second new-state)))
(insert-to-open new-state))))))
;;; ==================================================
;;; ====== SOLUTION =========
;;; ==================================================
(defun extract-solution (state)
"Rastrea en *memory* todos los descendientes de state hasta llegar al estado inicial"
(let
(
(current state)
(operation nil)
(ansestor nil)
(value nil))
(loop while (not (null current)) do
(setq value (get-hash-point (first (second current)) (second (second current)) (third (second current)) ))
(setq operation (gethash value *memory-operations*))
(setq ansestor (gethash value *memory-ancestor*))
(setq current ansestor)
(push operation *solution*))
(setq *solution* (rest *solution*))))
(defun display-solution ()
"Despliega la solución en forma conveniente y numerando los pasos"
(format t "~%La solucion es: ~A ~%~%" *solution*)
(format t "1) Solución con ~A pasos (Longitud de la solución)~%" (length *solution*))
(format t "2) ~A nodos creados ~%" *id*)
(format t "3) ~A nodos expandidos ~%" *expanded*)
(format t "4) Longitud máxima de la Frontera de búsqueda: ~A~%" *max-frontier*))
(defun reset-all ()
"Reinicia todas las variables globales para realizar una nueva búsqueda..."
(setq *id* -1)
(setq *open* ())
(setq *memory-operations* (make-hash-table))
(setq *memory-ancestor* (make-hash-table))
(setq *expanded* 0)
(setq *max-frontier* 0)
(setq *closest* '(9999999999 nil))
(setq *current-ancestor* nil))
(defun get-start ()
"Te regresa el estado inicial"
(let*
(
(x (aref *start* 0))
(y (aref *start* 1))
(z 0)
(coordinate (list x y z)))
(list (aptitude coordinate) coordinate)))
(defun get-goal ()
"Te regresa el estado inicial"
(let*
(
(x (aref *goal* 0))
(y (aref *goal* 1))
(z 0)
(coordinate (list x y z)))
(list (aptitude coordinate) coordinate)))
(defun AStar ()
"Realiza una búsqueda A*, desde un estado inicial hasta un estado meta"
(reset-all)
(let
(
(start (get-start))
(goal (get-goal))
(current nil)
(sucesores nil)
(goal-found nil))
(insert-to-open start)
(add-to-memory start -1)
(time
(loop until (or goal-found (null *open*)) do
(setq current (pop *open*))
(cond
((equal goal current)
(setq goal-found T)
(format t "Éxito. Meta encontrada ~%")
)
(t
(expand current)
(if (null *open*)
(progn
(format t "Lo intenté.%")
(setq current *closest*)
))
))
)
)
(extract-solution current)
(display-solution))
(print (get-maze-data))
(print *start*)
(print *goal*))
(defun AStar-Manhattan ()
(setq *aptitude-id* 0)
(AStar))
(defun AStar-Euclidean ()
(setq *aptitude-id* 1)
(AStar))
(add-algorithm 'AStar-Manhattan)
(add-algorithm 'AStar-Euclidean)
(start-maze)
| 13,789 | Common Lisp | .lisp | 356 | 31.19382 | 127 | 0.506001 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 510ec1f5f0ee25f0efc279836527b7e94d93aac268c1eea98c6eb898b62b03ad | 23,199 | [
-1
] |
23,200 | MiniMaxAlphaBeta.lisp | SoyOscarRH_AIWithLisp/Gato/MiniMaxAlphaBeta.lisp | ;;; MiniMaxAlphaBeta.lisp
;;; Resuelve el problema de gato usando minimax
;;;
;;; Oscar Andres Rosas Hernandez
;;; ==================================================
;;; ========= FUNCIONES AUXILIARES =========
;;; ==================================================
(defun copy-array (array &key (element-type (array-element-type array))
(fill-pointer (and (array-has-fill-pointer-p array)
(fill-pointer array)))
(adjustable (adjustable-array-p array)))
"Algoritmo de la biblioteca Alexandria, no es de mi autoria (https://common-lisp.net/project/alexandria/),
necesaria para mi implementación"
(let* ((dimensions (array-dimensions array))
(new-array (make-array dimensions
:element-type element-type
:adjustable adjustable
:fill-pointer fill-pointer)))
(dotimes (i (array-total-size array))
(setf (row-major-aref new-array i)
(row-major-aref array i)))
new-array))
(defun create-board (list-board)
"De una lista a una matrix"
(make-array '(4 4) :initial-contents list-board))
;;; ==================================================
;;; ========= FUNCIONES HEURISTICAS =========
;;; ==================================================
(defun evaluate-for (board player)
"Evalua un estado (tablero) para un jugador bajo la siguiente heuristica:
- 1 punto si no hay una marca tuya en una linea o diagonal
- 10 puntos si hay 1 marca tuya en una linea o diagonal
- 100 puntos si hay 2 marcas tuyas en una linea o diagonal
- 1000 puntos si hay 3 marcas tuyas en una linea o diagonal
- 10000 puntos si hay 4 marcas tuyas en una linea o diagonal
"
(let
(
(local-count 0)
(result 0))
;;; checa filas
(loop for row from 0 to 3 do
(setq local-count 0)
(loop for i from 0 to 3 do
(if (eql (aref board row i) player)
(incf local-count)))
(setq result (+ result (expt 10 local-count))))
;;; checa columnas
(loop for column from 0 to 3 do
(setq local-count 0)
(loop for i from 0 to 3 do
(if (eql (aref board i column) player)
(incf local-count)))
(setq result (+ result (expt 10 local-count))))
;;; checa diagonal
(setq local-count 0)
(loop for i from 0 to 3 do
(if (eql (aref board i i) player)
(incf local-count)))
(setq result (+ result (expt 10 local-count)))
;;; checa diagonal
(setq local-count 0)
(loop for i from 0 to 3 do
(if (eql (aref board i (- 3 i)) player)
(incf local-count)))
(setq result (+ result (expt 10 local-count)))
result
)
)
(defun evaluate (board)
"Mis puntos menos los tuyos"
(- (evaluate-for board 'O) (evaluate-for board 'X))
)
(defun game-over-player (board player)
"Regresa que jugador gano o nil si aun no hay"
(let
((won nil) (result 0))
;;; checa filas
(loop for row from 0 to 3 do
(setq won T)
(loop for i from 0 to 3 do
(if (not (eql (aref board row i) player))
(setq won nil)))
(if won (return-from game-over-player T)))
;;; checa columnas
(loop for column from 0 to 3 do
(setq won T)
(loop for i from 0 to 3 do
(if (not (eql (aref board i column) player))
(setq won nil)))
(if won (return-from game-over-player T)))
;;; checa diagonales
(setq won T)
(loop for i from 0 to 3 do
(if (not (eql (aref board i i) player))
(setq won nil))
)
(if won (return-from game-over-player T))
;;; checa diagonales
(setq won T)
(loop for i from 0 to 3 do
(if (not (eql (aref board i (- 3 i)) player))
(setq won nil))
)
(if won (return-from game-over-player T))
nil
)
)
(defun game-over (board)
"No importa quien gano, solo que alguien gano"
(or (game-over-player board 'O) (game-over-player board 'X))
)
(defparameter
*moves*
'(
;; Primero probemos los movimientos normales
(0 1 2)
(0 2 3)
(3 1 14)
(3 2 15)
(1 0 5)
(1 3 8)
(2 0 9)
(2 3 12)
;; Lo siguiente mejor es probar las esquinas
(0 0 1)
(0 3 4)
(3 0 13)
(3 3 16)
;; Lo mejor es probar primero los centros
(1 1 6)
(1 2 7)
(2 1 10)
(2 2 11)
)
)
(defun get-moves (board is-O-playing)
"Dame una lista de (tablero jugada) posibles dado un tablero, el orden de esta, maximiza podas"
(let
(
(new-board nil)
(mark (if is-O-playing 'O 'X))
(moves nil))
(loop for move in *moves* do
(let
(
(i (first move))
(j (second move))
(num (third move)))
(cond ((null (aref board i j))
(setq new-board (copy-array board))
(setf (aref new-board i j) mark)
(push (list new-board num) moves)
))
))
moves
)
)
(defun minimax-alphabeta (board depth alpha beta maximizing-player)
"Regresa la mejor jugada y la evaluacion a realizar para O dado un tablero (usa poda alpha beta)"
(if (or (zerop depth) (game-over board))
(return-from minimax-alphabeta (list (evaluate board) nil)))
(if maximizing-player
(let
(
(current-board nil)
(current-move nil)
(new-depth (- depth 1))
(max-evaluation most-negative-fixnum)
(evaluation nil)
(best-move nil))
(loop for board-move in (get-moves board maximizing-player) do
(setq current-board (first board-move))
(setq current-move (second board-move))
(setq evaluation (first (minimax-alphabeta current-board new-depth alpha beta nil)))
(cond ((> evaluation max-evaluation)
(setq max-evaluation evaluation)
(setq best-move current-move)))
(setq alpha (max alpha evaluation))
(if (<= beta alpha) (return-from minimax-alphabeta (list max-evaluation best-move))))
(return-from minimax-alphabeta (list max-evaluation best-move)))
(let
(
(current-board nil)
(current-move nil)
(new-depth (- depth 1))
(min-evaluation most-positive-fixnum)
(evaluation nil)
(best-move nil))
(loop for board-move in (get-moves board maximizing-player) do
(setq current-board (first board-move))
(setq current-move (second board-move))
(setq evaluation (first (minimax-alphabeta current-board new-depth alpha beta T)))
(cond ((< evaluation min-evaluation)
(setq min-evaluation evaluation)
(setq best-move current-move)))
(setq beta (min beta evaluation))
(if (<= beta alpha) (return-from minimax-alphabeta (list min-evaluation best-move))))
(return-from minimax-alphabeta (list min-evaluation best-move)))
)
)
(defun tictactoe (list-board)
"Control del programa, es solo un wrapper sobre minmax"
(setq
*output*
(second
(minimax-alphabeta
(create-board list-board) 2 most-negative-fixnum most-positive-fixnum T
)
)
)
)
| 7,361 | Common Lisp | .lisp | 212 | 27.377358 | 111 | 0.573592 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | aca620aeb2787f35a4f8633aca0f997566d934483257b90706660fef7e79aeef | 23,200 | [
-1
] |
23,201 | EjemploGato4x4.lisp | SoyOscarRH_AIWithLisp/Gato/EjemploGato4x4.lisp | ;;;============================================================================================================
;;; GATO4X4
;;; Este es un ejemplo del uso de los elementos que debe incluir el agente jugador en
;;; su código.
;;;
;;; Función tictactoe:
;;; Debe existir una función llamada tictactoe la cuál recibirá un tablero 4x4 que representa
;;; el juego. El argumento de la función entonces, es una lista que contiene los elementos
;;; del tablero actual.
;;; ejemplo de argumento a recibir:
;;; (( NIL NIL NIL NIL)
;;; ( NIL NIL X NIL)
;;; ( NIL NIL NIL NIL)
;;; ( NIL NIL NIL NIL))
;;; -los elementos de la lista principal representan los renglones
;;; -las posiciones de los elementos de las sublistas representan las columnas
;;; -los elementos de cada sublista representan el estado de cada casilla
;;; *NIL - significa que la casilla se encuentra vacía
;;; *X o O - significa que la casilla está ocupada, X corresponde a
;;; a la jugada de una persona y O a la jugada del agente jugador
;;; Varible *output*:
;;; El agente jugador debe entregar como respuesta un número del 1 al 16 (la posición en que
;;; tirará su agente jugador), estos números representan las posiciones de casillas en
;;; el tablero y esta respuesta debe ser guardada en la variable *output*, no debe declarar
;;; esta variable, sólo haga uso de ella.
;;;
;;; Su agente recibirá el estado actual del tablero en cada jugada.
;;;============================================================================================================
;;; El siguiente código es un ejemplo de cómo hacer uso de la función tictactoe y la
;;; variable *output*
(defparameter num 0)
;;; En este caso la función tictactoe recibe el tablero y lo recorre hasta encontrar una casilla
;;; vacía y guarda el número de posición de la casilla en la variable *output*.
(defun tictactoe (tablero)
(loop named res for x in tablero do
(loop for y in x do
(incf num)
if (null y) do
(setq *output* num)
(return-from res num) )))
;;;En la pestaña debug siempre se imprimirá el tablero y la variable *output*
(print "Esta es una prueba para la pestaña debug")
| 2,325 | Common Lisp | .lisp | 42 | 52.47619 | 111 | 0.612245 | SoyOscarRH/AIWithLisp | 1 | 0 | 0 | GPL-2.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 284518ce6ae766e5a0d0b9b8099e767da16dad1a47d1cb4ab7b9faafe98a0bb0 | 23,201 | [
83417
] |
23,236 | dreamhost.lisp | adventuring_dreamhost_lisp/dreamhost.lisp | (defpackage dreamhost
(:use :cl :alexandria :drakma :puri)
(:export
#:*api-key*
#:dns-add-record
#:dns-list-records
#:dns-remove-record
))
(in-package :dreamhost)
(defvar *api-key* (values)
"The Dreamhost API Key to be used.
Generate one in the Panel at
https://panel.dreamhost.com/?tree=home.api")
(define-condition dreamhost-api-error (error) ())
(define-condition dreamhost-api-warning (warning) ())
(define-condition no-record (dreamhost-api-error) ())
(define-condition no-type (dreamhost-api-error) ())
(define-condition no-value (dreamhost-api-error) ())
(define-condition no-such-zone (dreamhost-api-error) ())
(define-condition CNAME-must-be-only-record (dreamhost-api-error) ())
(define-condition CNAME-already-on-record (dreamhost-api-error) ())
(define-condition record-already-exists-not-editable (dreamhost-api-error) ())
(define-condition record-already-exists-remove-first (dreamhost-api-error) ())
(define-condition internal-error-updating-zone (dreamhost-api-error) ())
(define-condition internal-error-could-not-load-zone (dreamhost-api-error) ())
(define-condition internal-error-could-not-add-record (dreamhost-api-error) ())
(define-condition dreamhost-api-error-with-details (dreamhost-api-error)
((details :initarg :details :reader dreamhost-error-details
:documentation "Details of the API error"))
(:documentation "A Dreamhost API error with associated details string"))
(define-condition invalid-record (dreamhost-api-error-with-details) ())
(define-condition invalid-type (dreamhost-api-error-with-details) ())
(define-condition invalid-value (dreamhost-api-error-with-details) ())
(defgeneric validate-dns-value (type value)
(:documentation
"Returns VALUE in string form valid for a DNS record of type TYPE")
(:method ((type (eql :a)) (value string))
value)
(:method ((type (eql :cname)) (value string))
value)
(:method ((type (eql :ns)) (value string))
value)
(:method ((type (eql :ptr)) (value string))
value)
(:method ((type (eql :naptr)) (value string))
value)
(:method ((type (eql :srv)) (value string))
value)
(:method ((type (eql :txt)) (value string))
value)
(:method ((type (eql :aaaa)) (value string))
value))
(defun dns-add-record (name type &optional value comment)
"Add a DNS record for NAME of TYPE; VALUE is determined by TYPE.
Adds a new DNS record to a domain you already have hosted with
DreamHost. However, you cannot add dreamhosters.com records. Keep in
mind DNS changes may take a while to propagate.
@b{type}: A, CNAME, NS, PTR, NAPTR, SRV, TXT, or AAAA
@subsection Result success
record_added
@subsection Possible Errors
@itemize
@item
no_record
@item
no_type
@item
no_value
@item
invalid_record (may have specifics after a tab)
@item
invalid_type (may have specifics after a tab)
@item
invalid_value (may have specifics after a tab)
@item
no_such_zone
@item
CNAME_must_be_only_record
@item
CNAME_already_on_record
@item
record_already_exists_not_editable
@item
record_already_exists_remove_first
@item
internal_error_updating_zone
@item
internal_error_could_not_load_zone
@item
internal_error_could_not_add_record
@end itemize"
(check-type type (member '(A CNAME NS PTR NAPTR SRV TXT AAAA)
:test #'string-equal))
(check-type name string)
(let ((v (validate-dns-value (make-keyword (string-upcase type)) value)))
)
)
(defun dns-list-records ()
"
dns-list_records
Dump a list of all DNS records for all domains (not including registrations)
on all accounts you have access to. Please note that this skips the
dreamhosters.com, dreamhost.com, dreamhostps.com, and newdream.net zones.
Command dns-list_records
@subsection Result
The result is a space-delimited table, which will be split on spaces
into a list of plists.
@verbatim
success
account_id zone record type value comment editable
1 718apts.com 718apts.com A 1.2.3.4 0
1 718apts.com 718apts.com MX 0 mx1.balanced.dreamhost.com. 0
1 718apts.com 718apts.com MX 0 mx2.balanced.dreamhost.com. 0
1 718apts.com 718apts.com NS ns1.dreamhost.com. 0
1 718apts.com 718apts.com NS ns2.dreamhost.com. 0
1 718apts.com 718apts.com NS ns3.dreamhost.com. 0
1 718apts.com test.718apts.com CNAME ghs.google.com. A test I did. 1
@end verbatim
Possible values
type : A,MX,NS,CNAME,PTR,NAPTR,TXT,SRV,AAAA, or A6
editable : 0 or 1
")
(defun dns-remove-record (name)
"Commands
dns-remove_record
Removes an existing editable DNS record you have with DreamHost. However,
you cannot remove dreamhosters.com records. Keep in mind DNS changes may
take a while to propagate.
Command dns-remove_record Values
record : The full name of the record you'd like to remove, e.g., testing.groo.com
type : The type (see dns-add_record) of the record you'd like to remove.
value : The value (see dns-add_record) of the record you'd like to remove.
@subsection Result
success
record_removed
@subsection Possible errors
@verbatim
no_record
no_type
no_value
no_such_record
no_such_type
no_such_value
not_editable
internal_error_could_not_destroy_record
internal_error_could_not_update_zone
@end verbatim
")
(defun register-dns-name (name ipv4-address)
"Register DNS name NAME pointing to IPV4-ADDRESS.
shell: 'curl -X GET \"https://api.dreamhost.com/?key={{ api_key
}}&type=A&unique_id={{ fqdn | to_uuid }}&cmd=dns-add_record&record={{ fqdn
}}&value={{ public_v4 }}\"'
")
"
https://help.dreamhost.com/hc/en-us/articles/217555707-DNS-API-commands
What values does DreamHost's API use?
Required
key
An API Key that you need to generate via the web panel.
In order for a sub-account to create an API Key, it must be granted 'Billing' Account Privileges.
Please note that if a sub-account creates an API Key, it will only be
visible to the sub-account on the API Key page in the panel. The primary
account owner will not be able to view the sub-account's API Key in their
panel.
cmd The command you'd like to run. When you create your key you pick what
command(s) it may access. unique_id You may pass a new unique_id (max
length: 64 chars) when you submit a request, to make sure you don't
accidentally submit the same command twice. Note that only successful
queries \"use up\" a unique_id. DreamHost recommends using UUIDs for this
purpose if you'd like. The unique_id you use only applies to your specific
API key, so you never need to worry about any other users already \"using\"
a specific unique_id. Optional
format
The format you want to receive output in. Valid formats are:
tab (default)
xml
json
perl
php
yaml
html
account
The account number to perform operations under. Defaults to your own
account, or the first account you have access to otherwise.
Rate limit
In order to ensure that DreamHost systems remains stable and responsive, the
rate at which certain API commands or groups of API commands can be run by
the same user has been limited. These limits are relatively generous and
very few users ever run into them. Limits are usually set per hour or per
day, although some commands may have limits in shorter periods of time such
as 10 minutes. When API calls fail for any reason (for example if you tried
to create a user that already existed), it does not count against your
limits (note that this also means that failing because you exceeded the rate
limit also does not count). When you do run into a limit, the error
returned is:
error
slow_down_bucko (detailed info about type of limit reached after a tab)
If you run into this error, you should consider ways in which you could
reduce the frequency that you are calling the API. Most likely you would
only run into these limits if you have a script or automated program that
loops to repeatedly make API calls. So you can simply slow down the rate at
which your script runs, or make sure that it keeps track of how many
commands it has issued in the last hour/day.
Test Account
If you wish to test the DreamHost API without having your own account, you
may use the following API Key:
6SHU5P2HLDAYECUM
This account only has access to \"list\" functions however (and only
user-list_users_no_pw, not user-list_users) , as well as
dreamhost_ps-set_size, dreamhost_ps-set_settings, and dreamhost_ps-reboot to
ps7093.
An example
https://api.dreamhost.com/?key=6SHU5P2HLDAYECUM&cmd=user-list_users_no_pw&unique_id=4082432&format=perl
If you are writing a simple bash script to interface with DreamHost's API,
this may help as a start:
#!/bin/sh
####
#### USE THIS SCRIPT AT YOUR OWN RISK.
####
PS=$1
KEY=YOUR-KEY-HERE
UUID=`uuidgen`
CMD=user-list_users_no_pw
if [ $# -lt 1 ]; then
echo usage: `basename $0` [hostname]
exit 1
fi
if [ $PS = "" ]; then
PS=`hostname | cut -f1 -d.`
fi
# ARGS='other_http_get_arguments_for_the_DreamHost_cmd_that_you_are_using=4&foo=123'
LINK=https://api.dreamhost.com/?key=$KEY&unique_id=$UUID&cmd=$CMD&ps=$PS&$ARGS
RESPONSE=`wget -O- -q $LINK`
echo $LINK
echo $RESPONSE
if ! (echo $RESPONSE | grep -q 'success'); then
exit 1
fi
"
| 9,045 | Common Lisp | .lisp | 240 | 35.8 | 103 | 0.766323 | adventuring/dreamhost.lisp | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 5532e1c0089d129182e5c3d3f8bcfa6df3c4f0adb718dcc272c0fd7387c69a0f | 23,236 | [
-1
] |
23,237 | dreamhost.asd | adventuring_dreamhost_lisp/dreamhost.asd | (cl:in-package :cl-user)
(asdf:defsystem dreamhost
:version "0.1"
:author "Bruce-Robert Pocock <[email protected]>"
:license "AGPL v3+"
:description "Access the Dreamhost API"
:depends-on (
:drakma)
:components ((:file "dreamhost")))
| 264 | Common Lisp | .asd | 9 | 25.111111 | 52 | 0.671937 | adventuring/dreamhost.lisp | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | ecd847d458ab3aaaedce84189c17a767b7a0b3aea2f57570fa823cfe140d7244 | 23,237 | [
-1
] |
23,254 | main.lisp | lambdanil_lispy-tree/main.lisp | (defmacro make-vector (&aux type)
(if type
`(make-array 0 :fill-pointer 0 :adjustable t :element-type ,type)
`(make-array 0 :fill-pointer 0 :adjustable t)))
(defun vector-push-resize (var vec)
(adjust-array vec (1+ (array-dimension vec 0)))
(vector-push var vec))
(defun delete-nth (i seq)
"Delete nth element from sequence."
(let ((slide (subseq seq (1+ i)))
(num (1- (fill-pointer seq))))
(replace seq slide :start1 i)
(adjust-array seq num
:fill-pointer num)))
(defun make-tree (&aux
(relations (make-vector 'integer))
(names (make-vector 'string)))
(when (zerop (array-dimension relations 0))
(vector-push-resize -1 relations)
(vector-push-resize nil names))
(cons relations names))
(defun new-node (tree parent)
(vector-push-resize parent (car tree))
(vector-push-resize nil (cdr tree))
(1- (array-dimension (car tree) 0)))
(defmacro ref-parent (tree node)
`(aref (car ,tree) ,node))
(defmacro ref-name (tree node)
`(aref (cdr ,tree) ,node))
(defun path-to-root (tree node)
(let ((path
(make-vector 'integer)))
(loop
(when
(= node -1)
(vector-push-resize node path)
(return path))
(vector-push-resize node path)
(setq node (ref-parent tree node)))))
(defun path-from-root (tree node)
(reverse (path-to-root tree node)))
(defun in-range (tree n)
(and (< n (1- (array-dimension (car tree) 0))) (>= n 0)))
(defun get-occurences (tree node)
(let ((found
(make-vector 'integer)))
(dotimes (i (array-dimension (car tree) 0))
(when (= (ref-parent tree i) node)
(vector-push-resize i found)))
found))
(defun vector-cat (vec1 vec2)
(adjust-array vec1 (+ (array-dimension vec1 0) (array-dimension vec2 0)))
(dotimes (n (array-dimension vec2 0))
(vector-push (aref vec2 n) vec1)))
(defun get-all-children (tree node)
(let ((found
(get-occurences tree node))
(nfound
(make-vector 'integer))
(i 0))
(loop
(when
(= i (1- (array-dimension found 0)))
(return found))
(setf nfound (get-occurences tree (aref found i)))
(vector-cat found nfound)
(incf i))))
(defun remove-node (tree node)
(labels ((r-last-node (tree node)
(delete-nth node (car tree))
(delete-nth node (cdr tree))
(dotimes (i (array-dimension (car tree) 0))
(when (> (aref (car tree) i) node) (decf (aref (car tree) i))))))
(let ((found
(get-all-children tree node)))
(loop
(when (zerop (array-dimension found 0)) (r-last-node tree node) (return t))
(r-last-node tree (aref found (1- (array-dimension found 0))))
(delete-nth (1- (array-dimension found 0)) found)
(dotimes (i (array-dimension found 0))
(when (> (aref found i) node) (decf (aref found i))))))))
| 2,951 | Common Lisp | .lisp | 81 | 30.037037 | 83 | 0.60238 | lambdanil/lispy-tree | 1 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 8a02b3b95ddb2b39c9faa576aa6903d405d24de6234468edba1d772c9a6c9ab9 | 23,254 | [
-1
] |
23,271 | passwd-manager.lisp | thefossenjoyer_lisp-passwd/src/passwd-manager.lisp | (defpackage #:passwd-manager
(:use :cl))
(in-package #:passwd-manager)
(ql:quickload :cl-fad)
(defun create-passwd ()
(format t "Programme name: ~&")
(defvar programme-name)
(defvar programme-password)
(setf programme-name (read))
(cond
((cl-fad:file-exists-p (format nil "./~a/" programme-name)) (format t "It already exists. ~&"))
(t (with-open-file (stream (format nil "./~a" programme-name) :if-exists :append :direction :output :if-does-not-exist :create)
(format t "Enter the passwd:~&")
(setf programme-password (read))
(format stream "~a ~&" (string-downcase programme-password))
))
)
)
(defun see-passwd ()
(format t "Programme name: ~&")
(defvar programme-name)
(setf programme-name (read))
(cond
((cl-fad:file-exists-p (format nil "./~a/" programme-name))
(with-open-file (stream (format nil "./~a/" programme-name) :if-does-not-exist nil)
(loop for line = (read-line stream nil)
while line do (format t "Passwd: ~a" line)
)
)
)
)
)
(defun del-passwd ()
(format t "Programme name: ~&")
(defvar programme-name)
(setf programme-name (read))
(cond
((cl-fad:file-exists-p (format nil "./~a/" programme-name))
(uiop:delete-file-if-exists (format nil "./~a/" programme-name))
)
)
)
(defun menu ()
(format t "1. Create entry~&2. See the password~&3. Delete the password~&")
(format t "Choose an option:~&")
(defvar option (make-array '(0) :element-type 'base-char :adjustable t))
(setf option (read-line))
(cond
((= 1 (parse-integer option)) (create-passwd))
((= 2 (parse-integer option)) (see-passwd))
((= 3 (parse-integer option)) (del-passwd))
(t (format t "There's no such option. ~&"))
)
)
(defun main ()
(menu)
)
| 1,837 | Common Lisp | .lisp | 57 | 27.473684 | 131 | 0.621005 | thefossenjoyer/lisp-passwd | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 6c0971be29cc8514a6cd5c07b7fa0fcb555e804766546132b83e1085aca2e2f7 | 23,271 | [
-1
] |
23,272 | passwd-manager.asd | thefossenjoyer_lisp-passwd/passwd-manager.asd | (defsystem "passwd-manager"
:depends-on (
#:cl-fad
)
:components ((:module "src"
:components
((:file "passwd-manager"))))
:build-operation "program-op"
:build-pathname "lisp-passwd"
:entry-point "passwd-manager::main"
)
| 298 | Common Lisp | .asd | 11 | 19 | 44 | 0.547703 | thefossenjoyer/lisp-passwd | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 9269ba64f9706883162e25e06f74d1a490aad5f2acb69a01154dba222938d9e3 | 23,272 | [
-1
] |
23,289 | ttable.lisp | Cledersonbc_lisp-impl/basic/ttable.lisp | #|
Times table of n (from 0 to 10).
|#
;; Author: Clederson Cruz
(defun tab (n x)
(if (> n 0) (tab (- n 1) x))
(format t "~D x ~D = ~D~%" x n (* x n)))
(format t "Integer Number: ")
(tab 10 (read))
| 204 | Common Lisp | .lisp | 9 | 21 | 42 | 0.544041 | Cledersonbc/lisp-impl | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 50eb1227625f038223ee798ac37847f6124753cac690aa8045089a6aff238696 | 23,289 | [
-1
] |
23,290 | 2dg.lisp | Cledersonbc_lisp-impl/basic/2dg.lisp | #|
Quadratic equation calculed by lisp
|#
;; Author: Clederson Cruz
(defun 2dg (a b c)
(setq delta (- (expt b 2) (* 4 a c)))
(if (< delta 0)
nil
(list
(/ (+ (- 0 b) (sqrt delta)) (* 2 a))
(/ (- (- 0 b) (sqrt delta)) (* 2 a)))))
(format t "Type A, B, C:~%")
(format t "Real Solution: ~S" (2dg (read) (read) (read)))
| 335 | Common Lisp | .lisp | 13 | 23.230769 | 57 | 0.528125 | Cledersonbc/lisp-impl | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 1051b555c707267d896d7785979b192c64100bb3030333c61e951f7ba4942199 | 23,290 | [
-1
] |
23,291 | fat.lisp | Cledersonbc_lisp-impl/basic/fat.lisp | #|
Factorial of n is n if n = 0 or 1;
Factorial n is n * (n - 1) if n > 1.
|#
;; Author: Clederson Cruz
(defun fat (n)
(if (< n 2)
n
(* n (fat (- n 1)))))
(format t "Factorial of ~D is ~D.~%" (setq n (read)) (if (< n 0) nil (fat n)))
| 244 | Common Lisp | .lisp | 10 | 22.4 | 78 | 0.525862 | Cledersonbc/lisp-impl | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | d0daac462cc3e13b365f515be6d12d676d46e4b94cbfa84fe026f8ca4c082eed | 23,291 | [
-1
] |
23,292 | fib.lisp | Cledersonbc_lisp-impl/basic/fib.lisp | #|
Fibonacci Sequence: 1, 1, 2, 3, 5, 8, 13, ...
Author: Clederson
|#
(defun fib (n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))
(defun print-fib (n)
(if (> n 1) (print-fib (- n 1)))
(format t "~D " (fib n)))
(format t "**Fibonacci**~%Number: ")
(setq x (read))
(if (> x 0) (print-fib x) (format t "~S" nil))
| 328 | Common Lisp | .lisp | 14 | 21.357143 | 46 | 0.511254 | Cledersonbc/lisp-impl | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 04912ea3c55df050d103eee763c3597904ca35f552172710821ede6b879884bb | 23,292 | [
-1
] |
23,312 | package.lisp | afranson_Lisp-MCMC/package.lisp | ;;;; package.lisp
(defpackage :mcmc-fitting
(:nicknames :mfit)
(:use :cl)
(:documentation "# mcmc-fitting
Provides an interface for using Markov Chain Monte Carlo to do fitting of various functions.
Makes it easy to generate walker and probability distributions as well as advancing and visualizing the walkers.
GNU General Public License
"))
| 353 | Common Lisp | .lisp | 9 | 37.111111 | 112 | 0.791176 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 6efd110a0069adfeb3e73ee9f3b71b84ce9150a8adb6de11d8fd5065c8d50fe5 | 23,312 | [
-1
] |
23,313 | mcmc-fitting_230522.lisp | afranson_Lisp-MCMC/mcmc-fitting_230522.lisp | ;;; mcmc-fitting.lisp
#|
create walker
advance it
visualize it
|#
;;; Example use
;; (defparameter woi (mcmc-fit :function (lambda (x &key m b &allow-other-keys) (+ b (* -3 m) (* (- m (/ b 60)) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:b -1 :m 2) :data-error 0.2))
;; (defparameter woi (mcmc-fit :function (list (lambda (x &key b m c d &allow-other-keys) (+ b (* m x) (* c x x) (* d x x x))) (lambda (x &key e m g &allow-other-keys) (+ e (* (+ m g) x)))) :data '(((0 1 2 3 4) (4 5 6 8 4)) ((10 20 30 40 50) (1 2 3 4 5))) :params '(:b -1 :m 2 :c 1 :d -1 :e 0.5 :g -2) :data-error 0.2))
;; (sb-ext:muffle-conditions sb-ext:compiler-note)
;; Full arrays > list of arrays > pure lists
;; just lists don't benefit from optimization
;; arrays do a lot
;; arrays aren't much better than lists without optimization
;; (ql:quickload :gsll)
;; (ql:quickload :antik)
#| For testing cholesky decomps vs gsl implementation
(defun eyes (n)
(do ((i 0 (1+ i))
(ret-array nil (push (do ((j 0 (1+ j))
(ret-list nil (push (if (= i j) 1 0) ret-list)))
((> j n) (reverse ret-list)))
ret-array)))
((> i n) (reverse ret-array))))
(defun matrix-add (mat1 mat2)
(let ((ret-mat nil))
(dolist (erc (mapcar #'list mat1 (transpose-matrix mat2)) (reverse ret-mat))
(push (mapcar #'+ (elt erc 0) (elt erc 1)) ret-mat))))
(defparameter randmat (repeat 3 (repeat 3 (random 10d0))))
(defparameter posdefmat (matrix-add (scale-matrix 10 (eyes 3)) (scale-matrix 0.5 (matrix-add randmat randmat))))
|#
(in-package :mcmc-fitting)
;;; Utility
(defmacro br (&body body)
`(break "break ~s" ,@body))
(defun elts (tree &rest elts)
"Apply multiple elt to a tree. I.e. (elt (elt (elt foo 3) 2) 1) is simply (elts foo 3 2 1) or (apply #'elts foo '(3 2 1))."
(reduce (lambda (x y) (elt x y)) elts :initial-value tree))
(defun (setf elts) (new-value tree &rest elts)
"Make elts setf-able. Usage is (setf (elts tree elt0 elt1 elt2 ...) new-value) or (setf (apply #'elts tree eltslist) new-value)."
(setf (elt (apply #'elts tree (butlast elts)) (car (last elts))) (if (listp new-value) (copy-seq new-value) new-value)))
(defmacro return-this-but-also (expr &body body)
"Returns the provided 'expr' while also performing manipulations on 'expr' provided in 'body' to allow for printing subsections, performing logic, etc. Uses 'it' as the key term in 'body' to refer to the result of the 'expr'.
i.e. (return-this-but-also (list 4 8 2 0 4 12 0) (print (list (count 0 it) (count-if #'evenp it) (position 8 it))))
==> (2 7 1)
==> (4 8 2 0 4 12 0)"
(let ((it-g (gensym)))
`(let ((,it-g (multiple-value-list ,expr)))
(let ((it (lambda () (values-list ,it-g))))
,@(subst '(funcall it) 'it body)
(funcall it)))))
(defun range (start-or-end &optional end)
"Provides a list of numbers from 'start' to 'end' incrementing by 1. Always integers. Floors inputs.
(range 5.2) => '(0 1 2 3 4)
(range 2 5) => '(2 3 4)
(range 5 2) => '(5 4 3)"
(let ((start (floor (if end start-or-end 0)))
(end (floor (if end end start-or-end))))
(let ((return-list nil) (sign (signum (- end start))))
(do ((curr start (progn (push curr return-list) (+ sign curr))))
((= curr end) (reverse return-list))))))
(defun slice (2d-list &optional rows cols)
"Take a slice of a 2d list taking 'rows' (i.e. '(1 3 5) for rows 1 then 3 then 5) and 'cols' (i.e. '(20 40) for items 20 through 40)."
(let ((rows (if rows rows (range (length 2d-list))))
(cols (if cols cols (list 0 (length (elt 2d-list 0))))))
(mapcar (lambda (x) (apply #'subseq (elt 2d-list x) cols)) rows)))
(defmacro mapcar-enum ((element index list) &body body)
"mapcar with enumeration. Iterates over 'list' using 'element' to store each element, 'index' to store the index, and \"list\" to store the full list. Returns a list made of applying 'body' to each element of 'list'.
try: (mapcar-enum (e i '(30 20 10)) (print (list e i)))"
(let ((return-list-g (gensym "RETURN-LIST")))
`(let ((,return-list-g nil)
(list ,list))
(do ((,index 0 (1+ ,index))
(,element nil))
((>= ,index (length list)))
(setf ,element (elt list ,index))
(push ,@body ,return-list-g))
(reverse ,return-list-g))))
(defun map-tree (function tree)
"Maps 'function' over the deepest elements of 'tree'. 'tree' can be composed of any combination of sequences.
E.g. (map-tree #'1+ '((1 2) (2 3) (3 4) (100 (12 23 (324 54)))))
=> '((2 3) (3 4) (4 5) (101 (13 24 (325 55))))."
(cond ((null tree)
nil)
((and (atom tree) (or (stringp tree) (not (vectorp tree))))
(funcall function tree))
(t
(map (type-of tree) (lambda (x) (map-tree function x)) tree))))
(export 'map-tree)
(defun plist-keys (plist)
"Get all unique keys from 'plist'."
(do ((keys (list (pop plist)) (progn (pop plist) (append (list (pop plist)) keys))))
((null (nthcdr 2 plist)) (reverse (remove-duplicates keys)))))
(defun plist-values (plist)
"Get all values belonging to unique keys in 'plist'. Returns the first example of a value found."
(let ((keys (plist-keys plist)))
(mapcar (lambda (x) (getf plist x)) keys)))
(defun make-plist (keys values)
"Riffles a set of 'keys' and 'values' into a plist."
(apply #'append (mapcar #'list keys values)))
(defmacro repeat (count &body expression)
`(mapcar (lambda (x) (declare (ignore x)) ,@expression) (make-list ,count)))
(defun mkstr (&rest args)
(with-output-to-string (s)
(dolist (a args) (princ a s))))
(defun symb (&rest args)
(values (intern (apply #'mkstr args))))
(defun symb-keyword (&rest args)
(values (intern (apply #'mkstr args) :keyword)))
(defun remove-consecutive-duplicates (list)
(mapcon (lambda (x)
(if (eql (car x) (cadr x)) nil (list (car x))))
list))
(defun remove-duplicates-plist (plist)
(let* ((keys (get-plist-keys plist))
(unique-keys (remove-duplicates keys)))
(make-plist
unique-keys
(mapcar (lambda (x) (getf plist x)) unique-keys))))
(defun elements-between (sequence start-value end-value)
(remove-if-not (lambda (x) (<= start-value x end-value)) sequence))
(defun linspace (start end &key (len 50) (step nil) (type 'double-float))
"Provides a list from 'start' to 'end' (inclusive) that is 'len' in length. Or provides a list of number from 'start' until 'end' by 'step'. 'end' may not be reached if 'step' kwarg is provided.
Supported types for 'type' arg are 'float, 'double-float, 'rational, 'integer, 'bignum."
(let ((step (if step step (/ (rational (- end start)) (1- len))))
(len (if step (+ 1 (floor (- end start) step)) len))
(return-list nil))
(let ((rational-numbers
(do ((n 0 (1+ n))
(curr (rational start) (progn (push curr return-list) (+ curr step))))
((>= n len) (values (reverse return-list) step)))))
(case type
((or single-float float double-float rational) (mapcar (lambda (x) (coerce x type)) rational-numbers))
(t (mapcar #'round rational-numbers))))))
(defun n-nums (n)
(do ((m 0 (1+ m))
(l nil (push m l)))
((= m n) (reverse l))
(declare (fixnum m))))
(defun up-to (n &optional (start 0))
(assert (>= n start))
(do ((m start (1+ m))
(l nil (push m l)))
((= m (1+ n)) (reverse l))
(declare (fixnum m))))
(defun diff (list)
(mapcon (lambda (x) (if (nthcdr 1 x) (list (- (cadr x) (car x))) nil)) list))
(defun diff-matrix (matrix)
(mapcon (lambda (x)
(if (nthcdr 1 x)
(list (mapcar (lambda (x y)
(if (consp x)
(mapcar #'- x y)
(- x y)))
(cadr x) (car x)))
nil))
matrix))
(defun diff-lplist (lplist)
(let* ((keys (get-plist-keys (elt lplist 0)))
(values (mapcar #'plist-values lplist)))
(mapcar (lambda (x) (make-plist keys x)) (diff-matrix values))))
(defun partition (list n)
"Pairs elements and removes any with full matches"
(labels ((rec (l &optional (acc nil))
(if (nthcdr (- n 1) l)
(rec (subseq l n) (cons (subseq l 0 n) acc))
(cons l acc))))
(reverse (cdr (rec list)))))
(defun transpose (xy-list)
"Takes 'xy-list' of form ((x1 y1 z1 ...) (x2 y2 z2 ...) ...) and turns it into ((x1 x2 ...) (y1 y2 ...) (z1 z2 ...) ...). Also known as a transpose. It is its own inverse. Works for combinations of lists and vectors."
(when xy-list
(apply #'map 'list #'list xy-list)))
(defun flatten (list)
"Remove all structure from list"
(let ((return-list nil))
(labels ((%flatten (list)
(cond ((null list)
nil)
((consp list)
(mapcar #'%flatten list))
(t
(push list return-list)))))
(%flatten list))
(reverse return-list)))
(defun split-string (splitter string)
"Split string by splitter, which is a char."
(declare (optimize speed safety)
(character splitter))
(labels ((inner-split (string &optional acc)
(declare (optimize speed safety)
(simple-string string)
(type (or null cons) acc))
(if (string/= string "")
(let ((pos (position splitter string :test #'char=)))
(if pos
(inner-split (subseq string (+ pos 1)) (cons (subseq string 0 pos) acc))
(inner-split "" (cons string acc))))
(reverse acc))))
(inner-split string)))
;;; Log-liklihood and log-prior functions
(defun log-prior-flat (params data)
(declare (ignore params data))
0d0)
(defmacro prior-bounds-let ((&rest keys-low-high) &body body)
(declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(flet ((expand-keys (key-low-high)
(let* ((key (car key-low-high))
(param-name (read-from-string (symbol-name key))))
`(,param-name (the double-float (getf ,(intern "PARAMS") ,key 0d0)))))
(expand-bounds (key-low-high)
(destructuring-bind (key low-expr high-expr) key-low-high
(let ((param-name (read-from-string (symbol-name key)))
(param-name-bound (read-from-string (concatenate 'string (symbol-name key) "-bound"))))
`(,param-name-bound (the double-float (if (< ,low-expr ,param-name ,high-expr)
0d0
(* -1d10 (- (exp (* (min (abs (- ,param-name ,high-expr)) (abs (- ,param-name ,low-expr))) 1d-5)) 1))))))))
(get-bound-name (key-low-high)
(destructuring-bind (key low-expr high-expr) key-low-high
(declare (ignore low-expr high-expr))
(let ((param-name-bound (read-from-string (concatenate 'string (symbol-name key) "-bound"))))
param-name-bound))))
`(let* (,@(mapcar #'expand-keys keys-low-high)
,@(mapcar #'expand-bounds keys-low-high)
(,(intern "BOUNDS-TOTAL") (+ ,@(mapcar #'get-bound-name keys-low-high))))
,@body)))
;; log-liklihood can depend on x, y, params, stddev (additional distribution parameters)
(defun log-normal (x mu sigma)
(declare (sb-ext:muffle-conditions sb-ext:compiler-note)
(optimize speed)
(double-float mu x)
(type (double-float 0d0 *) sigma))
(+ (* -1/2 (log (* 2 pi))) (* -1 (log sigma)) (* -1/2 (expt (/ (- x mu) sigma) 2d0))))
(defun log-factorial (n)
(reduce (lambda (x y) (+ x (log y))) (up-to n)))
(defun log-poisson (lambda k)
(- (* k (log lambda)) lambda (log-factorial k)))
;; log liklihood is the function that determines how data is useful
;; It does the pattern matching and analysis on input variables
;; The liklihood defines the result
;; Each independent variable needs to have the appropriate distribution
;; Then they just all add together (for the log version)
;; The prior is then tacked on at the end however the user sees fit
;; Since the prior does not change, it will just speed up the convergence to have a good one
;; prior could also depend on data for bounds or such
(defun log-liklihood-normal (fn params data stddev)
(declare (optimize speed)
(list data stddev)
(function fn))
(let* ((x (nth 0 data))
(y (nth 1 data)))
(declare (list x y))
(apply #'+ (mapcar (lambda (x y z) (log-normal y (apply fn x params) z)) x y stddev))))
(defun create-log-liklihood-function (log-liklihood-function)
"Input a function that determines the log-liklihood of some data point. 'log-liklihood-function' needs to accept 3 arguments. This function assumes your independent (x) variable is in the 0th column of the data and the dependent (y) variable is in the 1st column. If you have more elaborate needs, examine the implementation of #'create-log-liklihood-normal and modify to your needs.
The first is the actual y value of the point.
The second is the model predicted value of the point.
The third is the error of the point.
i.e. (lambda (y model error) (/ (- y model) error))
i.e. (lambda (y model error) (declare (ignore error)) (/ (- y model) 1)) ;; you can ignore any arguments you want, but the function must accept 3 arguments."
(lambda (fn params data stddev)
(declare (optimize speed)
(list data stddev)
(function log-liklihood-function fn))
(let* ((x (nth 0 data))
(y (nth 1 data)))
(declare (list x y))
(apply #'+ (mapcar (lambda (x y) (funcall log-liklihood-function y (apply fn x params) stddev)) x y)))))
(export 'create-log-liklihood-function)
(defun log-liklihood-normal-cutoff (fn params data stddev)
(declare (optimize speed)
(list data stddev)
(function fn))
(let* ((x (elt data 0))
(y (elt data 1)))
(declare (list x y))
(apply #'+ (mapcar (lambda (x y z) (max -5000d0 (the double-float (log-normal y (apply fn x params) z)))) x y stddev))))
(export 'log-liklihood-normal-cutoff)
;;; plist functions
(defun get-plist-keys (plist &optional return-keys)
(if (car plist)
(get-plist-keys (cddr plist) (cons (car plist) return-keys))
(reverse return-keys)))
(defun get-plist-values (plist &optional return-values)
(if (car plist)
(get-plist-values (cddr plist) (cons (cadr plist) return-values))
(reverse return-values)))
(defun reduce-plists (function plist1 plist2 &optional result)
(if (and (cadr plist1) (cadr plist2))
(let ((key (car plist1)))
(reduce-plists function (cddr plist1)
plist2
(nconc (list (funcall function (cadr plist1) (getf plist2 key)) key) result)))
(reverse result)))
(defun map-plist (fn plist)
(let* ((keys (get-plist-keys plist))
(values (get-plist-values plist))
(ret-values (map-tree fn values)))
(make-plist keys ret-values)))
(defun scale-plist (scale plist)
(map-plist (lambda (x) (* x scale)) plist))
;;; Walker and associated functions
(defstruct walker-step
(prob most-negative-double-float :type float)
(params nil :type list))
(export '(make-walker-step walker-step-prob walker-step-params))
(defstruct walker
(function nil :type list)
(param-keys nil :type list)
(param-style (or :multiple-kwargs :single-list) :type symbol)
(walk nil :type list)
(length 1 :type integer)
(most-likely-step (make-walker-step) :type walker-step)
(last-step (make-walker-step) :type walker-step)
(data nil :type (or list vector))
(data-error nil :type list)
(log-liklihood nil :type list)
(log-prior nil :type list))
(export '(make-walker walker-function walker-param-keys walker-walk walker-length walker-most-likely-step walker-last-step walker-data walker-data-error walker-log-liklihood walker-log-prior))
;; Useful for inspecting when algorithm fails
(defun walker-check-for-complex-walks (walker &optional take)
(let ((complex-walks-ps (mapcar (lambda (x) (some #'identity x)) (map-tree #'complexp (lplist-to-l-matrix (diff-lplist (walker-get walker :get :unique-steps :take take)))))))
(if (some #'identity complex-walks-ps) complex-walks-ps nil)))
(defun walker-get (walker &key (get (or :steps :unique-steps :most-likely-step :acceptance :param :most-likely-params :median-params :all-params :stddev-params :log-liklihoods :covariance-matrix :l-matrix)) take param)
"Get any of the above items from a walker. Use the 'take' kwarg to limit the number of walks you are sampling over. Use the 'param' kwarg to specify which params for the :param :get option."
(case get
(:steps (subseq (walker-walk walker) 0 (when take (min (walker-length walker) take))))
(:unique-steps (mapcon (lambda (x)
(if (equal (walker-step-prob (car x)) (when (cadr x) (walker-step-prob (cadr x))))
nil
(list (walker-step-params (car x)))))
(walker-get walker :get :steps :take take)))
(:most-likely-step (reduce (lambda (x y)
(if (> (walker-step-prob x) (walker-step-prob y)) x y))
(walker-get walker :get :steps :take take)))
(:acceptance
(let* ((probs (mapcar #'walker-step-prob (walker-get walker :get :steps :take take))))
(/ (length (remove-consecutive-duplicates probs)) (length probs))))
(:param (mapcar (lambda (x) (getf (walker-step-params x) param)) (walker-get walker :get :steps :take take)))
(:most-likely-params
(let ((param-keys (walker-param-keys walker))
(most-likely-step (walker-most-likely-step walker)))
(make-plist param-keys
(mapcar (lambda (key) (getf (walker-step-params most-likely-step) key)) param-keys))))
(:median-params
(let ((param-keys (walker-param-keys walker))
(steps (walker-get walker :get :steps :take take)))
(make-plist param-keys
(if (eq (walker-param-style walker) :multiple-kwargs)
(mapcar (lambda (key) (median (mapcar (lambda (step) (getf (walker-step-params step) key)) steps))) param-keys)
(list (mapcar #'median (transpose (mapcar (lambda (step) (getf (walker-step-params step) (elt param-keys 0))) steps))))))))
;; TODO add failsafe here if not enough valid steps to do cholesky
(:stddev-params
(let* ((param-keys (walker-param-keys walker)))
(if (< (walker-length walker) 10)
(make-plist param-keys (make-list (length param-keys) :initial-element 0d0))
(let ((l-matrix (walker-get walker :get :l-matrix :take take)))
(values (if (eq :multiple-kwargs (walker-param-style walker))
(make-plist param-keys
(mapcar (lambda (x)
(elt (elt l-matrix x) x))
(up-to (1- (length l-matrix)))))
(make-plist param-keys
(list (mapcar (lambda (x)
(elt (elt l-matrix x) x))
(up-to (1- (length l-matrix)))))))
l-matrix)))))
(:log-liklihoods (mapcar #'walker-step-prob (walker-get walker :get :steps :take take)))
(:covariance-matrix (lplist-covariance (walker-get walker :get :unique-steps :take take)))
(:l-matrix (lplist-to-l-matrix (diff-lplist (walker-get walker :get :unique-steps :take take))))))
(export 'walker-get)
(defun walker-modify (walker &key (modify (or :add-step :add-walks :burn-walks :keep-walks :reset :reset-to-most-likely :delete)) new-step new-walks burn-number keep-number)
(case modify
(:add-step (progn (push new-step (walker-walk walker))
(setf (walker-last-step walker) new-step)
(setf (walker-length walker) (1+ (walker-length walker)))
(when (> (walker-step-prob new-step)
(walker-step-prob (walker-most-likely-step walker)))
(setf (walker-most-likely-step walker) new-step))))
(:add-walks (progn (nconc (reverse new-walks) (walker-walk walker))
(setf (walker-last-step walker) (last new-walks))
(setf (walker-length walker) (+ (length new-walks) (walker-length walker)))
(mapcar
(lambda (new-step)
(when (> (walker-step-prob new-step)
(walker-step-prob (walker-most-likely-step walker)))
(setf (walker-most-likely-step walker) new-step)))
new-walks)))
(:burn-walks (progn (setf (walker-walk walker) (subseq (walker-walk walker) 0 (- (walker-length walker) burn-number)))
(setf (walker-length walker) (- (walker-length walker) burn-number))))
(:keep-walks (progn (setf (walker-walk walker) (subseq (walker-walk walker) 0 keep-number))
(setf (walker-length walker) keep-number)))
(:reset (progn (setf (walker-walk walker) (last (walker-walk walker)))
(setf (walker-last-step walker) (car (walker-walk walker)))
(setf (walker-length walker) 1)
walker))
(:reset-to-most-likely
(progn (setf (walker-walk walker) (list (walker-most-likely-step walker)))
(setf (walker-last-step walker) (car (walker-walk walker)))
(setf (walker-length walker) 1)
walker))
(:delete (progn (setf (walker-walk walker) nil)
(setf walker (make-walker))))))
(export 'walker-modify)
(defun cholesky-decomp (covariance-matrix)
"Generalization of the sqrt operation for postive definite matrices."
(let* ((cov-array (make-array (list (length covariance-matrix) (length (car covariance-matrix))) :initial-contents covariance-matrix))
(l-array (make-array (array-dimensions cov-array) :initial-element 0d0))
(tmp-sum 0d0))
(dotimes (i (array-dimension cov-array 0))
(dotimes (k (+ i 1))
(setq tmp-sum 0d0)
(dotimes (j k)
(incf tmp-sum (* (aref l-array i j) (aref l-array k j))))
(if (= i k)
(setf (aref l-array i k) (sqrt (- (aref cov-array i k) tmp-sum)))
(setf (aref l-array i k) (/ (- (aref cov-array i k) tmp-sum) (+ 1d-16 (aref l-array k k))))))) ;; TODO Remove Cheater Addition
(array-matrix l-array)))
;;; matrix and covariance
;; An array is a lisp array. A matrix is a list of lists
(defun dot (list1 list2)
"Returns dot product of two lists."
(apply #'+ (mapcar #'* list1 list2)))
(defun transpose-matrix (matrix)
(let ((num-columns (- (length (elt matrix 0)) 1)))
(mapcar (lambda (el) (mapcar (lambda (row) (elt row el)) matrix)) (up-to num-columns))))
(defun scale-matrix (scale matrix)
(mapcar (lambda (x) (mapcar (lambda (y) (* y scale)) x)) matrix))
(defun lplist-covariance (lplist)
(let* ((n (length lplist))
(values (mapcar #'get-plist-values lplist))
(values (transpose (if (consp (caar values)) (mapcar #'first values) values)))
(avg (mapcar (lambda (x) (/ (reduce #'+ x) n)) values))
(a (mapcar (lambda (x y)
(mapcar (lambda (z) (- z y))
x))
values avg))
(ns (make-list (length a) :initial-element (float n 0d0)))
(v (mapcar (lambda (x denom)
(mapcar (lambda (y)
(/ (dot x y) denom))
a))
a ns)))
v))
(defun lplist-to-l-matrix (lplist)
(let* ((covariance (lplist-covariance lplist)))
(cholesky-decomp covariance)))
(defun get-covariant-sample (means l-matrix)
(labels ((rotate-random-sample (sample l-matrix)
(mapcar (lambda (y) (dot y sample)) l-matrix)))
(let ((samples (repeat (length l-matrix) (alexandria:gaussian-random))))
(if (consp (car means))
(list (mapcar #'+ (car means) (rotate-random-sample samples l-matrix)))
(mapcar #'+ means (rotate-random-sample samples l-matrix))))))
(defun diagonal-covariance (list)
(let* ((list (if (consp (car list)) (elt list 0) list))
(len (length list))
(i -1))
(mapcar (lambda (x)
(declare (ignore x))
(incf i)
(maplist (lambda (y) (if (= (length y) (- len i)) (car y) 0)) list))
list)))
(defvar example-lplist '((:a 90 :b 60 :c 90)
(:a 90 :b 90 :c 30)
(:a 60 :b 60 :c 60)
(:a 60 :b 60 :c 90)
(:a 30 :b 30 :c 30)))
(defvar example-covariance (lplist-covariance example-lplist))
(defvar example-array (make-array '(3 3) :initial-contents example-covariance))
(defun array-matrix (array)
(let ((dim0 (array-dimension array 0))
(dim1 (array-dimension array 1))
(i -1)
(j -1))
(repeat dim0
(incf i)
(setq j -1)
(repeat dim1
(incf j)
(aref array i j)))))
(defvar example-matrix (array-matrix example-array))
(defvar example-l-matrix (lplist-to-l-matrix example-lplist))
;;; MCMC Metropolis-Hastings
(defun force-list (item)
"Forces all non-list items into lists"
(if (consp item)
item
(list item)))
(defun get-depth (list-tree)
"Returns the depth of the first element (as defined by a flattened sequence) and the length of the sequence containing that element. (list max-depth deepest-length).
==> (get-depth '(((4 5) (3 4))))
==> (3 2)"
(cond ((null list-tree)
nil)
((numberp list-tree)
0)
(t
(+ 1 (get-depth (elt list-tree 0))))))
(defun clean-data-error (stddev clean-data &optional (first t))
"Copies the structure of the y-data and inserts provided sttdev value(s) into their place if they fit. If the stddev structure does not match the y-data structure, then just replace all numbers found in y with the first from stddev.
==> (clean-data-error '((0.1) (0.4)) '(((2 3) ((4) (5))) (() (3 4 5 6))))
==> (((0.1) (0.4)) (0.1 0.1 0.1 0.1))"
(labels ((first-element (list-tree)
(cond ((null list-tree)
nil)
((numberp list-tree)
list-tree)
(t
(first-element (car list-tree)))))
(eq-structure (list-tree1 list-tree2)
(cond ((and (numberp list-tree1) (numberp list-tree2))
t)
((or (numberp list-tree1) (numberp list-tree2))
nil)
((/= (length list-tree1) (length list-tree2))
nil)
(t
(every #'identity (mapcar #'eq-structure list-tree1 list-tree2))))))
(let ((clean-data-ys (if first (mapcar #'second clean-data) clean-data))
(default-stddev (first-element stddev)))
(cond ((null clean-data-ys)
nil)
((numberp clean-data-ys)
default-stddev)
((eq-structure stddev clean-data-ys)
stddev)
(t
(mapcar (lambda (data) (clean-data-error stddev data nil)) clean-data-ys))))))
(defun clean-data (data number-of-functions)
"Forces data to be lists only and of proper depth."
(labels ((list-everything (list-tree)
(cond ((null list-tree)
nil)
((numberp list-tree)
list-tree)
((or (listp list-tree) (vectorp list-tree))
(map 'list #'list-everything list-tree)))))
(cond ((= (get-depth data) 1)
(error "clean-data: data is of insufficient depth or improperly structured."))
((= (get-depth data) 2)
(clean-data (list data) number-of-functions))
((= (length data) number-of-functions)
(list-everything data))
(t
(error "clean-data: insufficient number of datasets, ~a, for the given number of functions, ~a." (length data) number-of-functions)))))
(defun create-walker-data (data &rest columns)
"Takes a larger dataset (contains x, y, stddev, freq, temp, etc.) and extracts just the columns you want into a walker-friendly format."
(mapcar (lambda (x) (apply #'vector x))
(mapcar (lambda (y) (elt data y)) columns)))
(export 'create-walker-data)
(defun to-double-floats (l)
"Converts all numbers and vectors in tree to double-float type"
(map-tree (lambda (x) (if (numberp x) (coerce x 'double-float) x)) l))
(defun log-prior-fixer (log-prior params data)
"Checks if your prior returns a function (i.e. changes shape based on the data provided to it). If so, gets that function. If not, returns the prior you gave it."
(let ((results (mapcar (lambda (lp d) (funcall lp params d)) log-prior data)))
(mapcar (lambda (res fn) (if (numberp res) fn res)) results log-prior)))
(defun log-liklihood-fixer (log-liklihood fn params data error)
"Checks if your liklihood returns a function (i.e. changes shape based on the data provided to it). If so, gets that function. If not, returns the liklihood you gave it."
(let ((results (mapcar (lambda (ll f d e) (funcall ll f params d e)) log-liklihood fn data error)))
(mapcar (lambda (res fn) (if (numberp res) fn res)) results log-liklihood)))
(defun walker-many-steps (the-walker n &optional l-matrix)
"Takes 'n' steps with a constant l-matrix. No temperature or any other intelligent features."
(if (null l-matrix) (car (setq l-matrix (diagonal-covariance (get-plist-values (scale-plist 1e-2 (walker-get the-walker :get :median-params)))))))
(dotimes (i n)
(walker-take-step the-walker :l-matrix l-matrix)))
;; TODO remove and add functionality for troubleshooting
;; (print (car (diagonal-covariance (get-plist-values (scale-plist 1e-2 (walker-get-median-params woi 1000))))))
;; (print (standard-deviation (diff (remove-consecutive-duplicates (walker-get-param woi :w1-0-0)))))
;; (plt:plot (diff (remove-consecutive-duplicates (walker-get-param woi :w1-0-0))))
(defun walker-adaptive-steps-full (walker &key (n 100000) (temperature 1d3) (auto t) max-walker-length l-matrix)
"Advances 'walker' through as many as 'n' steps. Intelligently adjusts the l-matrix (sampling rotation matrix for more efficient random sampling) to try to avoid too low and too high acceptance. Has an oscillating temperature between 1 and 'temperature' during the beginning of the journey. Can automatically terminate a journey if the probability has stabilized, indicating at least a point of local stability. 'max-walker-length' will prevent the walker from becomming too large if maxing out memory is an issue."
(let* ((n (floor n))
(reset-index 10000)
(max-walker-length (when max-walker-length (floor max-walker-length 2)))
(param-keys (walker-param-keys walker))
(num-params (if (eq (walker-param-style walker) :multiple-kwargs)
(length (walker-param-keys walker))
(length (cadr (walker-step-params (walker-most-likely-step walker))))))
(steps-to-settle (* 50 num-params))
(shutting-down-p nil)
(temp-steps (* 7 steps-to-settle))
(temperature (rational temperature))
(temps (mapcar (lambda (x) (max 1 (* (expt (cos (* x 1/2 pi (/ 7 temp-steps))) 2) 50))) (range temp-steps)))
(current-acceptance 0))
(flet ((stable-probs-p (probs)
(< 5 (- (reduce #'max probs) (reduce #'min probs)) 9))
(get-optimal-mcmc-l-matrix (take)
(scale-matrix (/ (expt 2.38 2) (length param-keys))
(walker-get walker :get :l-matrix :take take))))
(unless l-matrix
(if (or (< (walker-length walker) steps-to-settle)
(< (walker-get walker :get :acceptance :take 100) 0.1))
(setq l-matrix (diagonal-covariance (get-plist-values (scale-plist 1d-3 (walker-get walker :get :median-params :take steps-to-settle)))))
(setq l-matrix (get-optimal-mcmc-l-matrix steps-to-settle))))
(do ((i 1 (+ i 1))
(temp-index 0))
((>= i n))
(when (or
(and (not shutting-down-p) (< (- n i) steps-to-settle))
(and auto
(not shutting-down-p)
(= 0 (mod i 1000))
(> i (* 10 steps-to-settle))
(< 0.2 (walker-get walker :get :acceptance :take 1000) 0.5)
(stable-probs-p (walker-get walker :get :log-liklihoods :take steps-to-settle))))
(setf temperature 1)
(setf shutting-down-p t)
(setf i (- n steps-to-settle)))
;; catch complex stddev and retry with differnt opimal l matrix sampling
(walker-take-step walker :l-matrix l-matrix :temperature temperature)
;; Annealing
(when (and (not shutting-down-p) (< i temp-steps))
(setf temperature (elt temps i)))
(when (and (not shutting-down-p) (= i temp-steps))
(setf temperature 1)
(walker-modify walker :modify :add-step :new-step (walker-get walker :get :most-likely-step :take temp-steps)))
;; Cleaning the walker
(when (and max-walker-length (= i reset-index))
(if (> (walker-length walker) max-walker-length)
(progn (walker-modify walker :modify :keep-walks :keep-number max-walker-length)
(incf reset-index (1+ max-walker-length)))
(incf reset-index (1+ (- max-walker-length (walker-length walker))))))
;; Regular l-matrix updating
(when (and (> i 0)
(or (and (= 0 (mod i 1000)) (< (walker-get walker :get :acceptance :take 1000) 0.05))
(and (= 0 (mod i 1000)) (> (walker-get walker :get :acceptance :take 1000) 0.80))
(and (not shutting-down-p) (= 0 (mod i steps-to-settle)))))
(setf current-acceptance (walker-get walker :get :acceptance :take 1000))
(if (< current-acceptance 0.2)
(setf l-matrix (scale-matrix 0.5 l-matrix))
(if (> current-acceptance 0.5)
(setf l-matrix (scale-matrix 2 l-matrix))
(setf l-matrix (get-optimal-mcmc-l-matrix steps-to-settle)))))))))
;; (let ((temp-steps 100)) (mapcar (lambda (i) (and (= 0 (mod (1+ (floor i temp-steps)) 2)) (< i (* temp-steps 95)))) (range 500)))
(defun walker-adaptive-steps (walker &optional (n 100000))
(walker-adaptive-steps-full walker n 1d3 t nil))
;; (defun walker-construct-print-list (walker &optional take)
;; `(:fn ,(mapcar #'sb-kernel:%fun-name (walker-function walker))
;; :data ,(walker-data walker)
;; :param-keys ,(walker-param-keys walker)
;; :stddev ,(walker-data-error walker)
;; :log-liklihood ,(mapcar #'sb-kernel:%fun-name (walker-log-liklihood walker))
;; :log-prior ,(mapcar #'sb-kernel:%fun-name (walker-log-prior walker))
;; :walker ,(walker-walks walker take)))
;; (defun walker-save (walker filename &optional take)
;; (with-open-file (out filename
;; :direction :output
;; :if-exists :supersede)
;; (with-standard-io-syntax
;; (null (write (walker-construct-print-list walker take) :stream out)))))
;; (defun walker-load (filename &key function log-liklihood log-prior quiet)
;; (with-open-file (in filename
;; :direction :input)
;; (with-standard-io-syntax
;; (let* ((full (read in))
;; (data (getf full :data))
;; (data-error (getf full :data-error))
;; (walks (getf full :walker))
;; (dummy-params (walker-step-params (elt walks 0))))
;; (unless quiet
;; (format t "*Recommendations*~%function: ~s~%log-liklihood: ~s~%log-prior: ~s~%" (getf full :fn) (getf full :log-liklihood) (getf full :log-prior)))
;; (when (and function log-liklihood log-prior)
;; (let ((walker (walker-create :function function :data data :params dummy-params :data-error data-error :log-liklihood log-liklihood :log-prior log-prior)))
;; (walker-modify walker :modify :add-walks :new-walks walks)
;; walker))))))
;;; Functionality for a set of similar walker instances
;; (defun walker-set-save (the-walker-set filename &optional take)
;; (let ((walker-print-list (mapcar (lambda (x) (walker-construct-print-list x take)) the-walker-set)))
;; (with-open-file (out filename
;; :direction :output
;; :if-exists :supersede)
;; (with-standard-io-syntax
;; (null (print walker-print-list out))))))
;; (defun walker-set-load (filename fn log-liklihood log-prior)
;; (with-open-file (in filename
;; :direction :input)
;; (with-standard-io-syntax
;; (let* ((full (read in)))
;; (mapcar (lambda (x)
;; (let* ((param-keys (getf x :param-keys))
;; (dummy-params (make-plist param-keys (make-list (length param-keys) :initial-element 0.0d0)))
;; (data (getf x :data))
;; (stddev (getf x :stddev))
;; (walks (getf x :walker))
;; (the-walker (walker-init :fn fn :data data :params dummy-params :stddev stddev :log-liklihood log-liklihood :log-prior log-prior :init nil)))
;; (walker-modify the-walker :modify :add-walks :new-walks walks)
;; the-walker))
;; full)))))
(defun walker-set-get (the-walker-set &key (get (or :steps :unique-steps :most-likely-step :acceptance :param :most-likely-params :median-params :all-params :stddev-params :log-liklihoods :covariance-matrix :l-matrix)) take param)
(mapcar (lambda (x) (walker-get x :get get :take take :param param)) the-walker-set))
(defun walker-set-delete (the-walker-set)
(mapcar (lambda (x) (walker-modify x :modify :delete)) the-walker-set))
(defun walker-set-plot-param (the-walker-set key &optional take)
(plt:plot (walker-set-get-median-params the-walker-set key take) "w l title \"Param\""))
;; median vs most likely
(defmacro walker-get-f (walker exp &key (take 1000))
(let ((median-params (walker-get walker :get :most-likely-params :take take)))
(labels ((replace-param-names (item)
(cond ((null item) nil)
((atom item) (if (char= #\: (char (prin1-to-string item) 0))
(getf median-params item)
item))
((consp item)
(cons (replace-param-names (car item))
(replace-param-names (cdr item)))))))
(let ((filled-exp (replace-param-names exp)))
filled-exp))))
(defun walker-with-exp (walker exp &key (take 1000))
(let ((median-params (walker-get walker :get :most-likely-params :take take)))
(labels ((replace-param-names (item)
(cond ((null item) nil)
((atom item) (if (char= #\: (char (prin1-to-string item) 0))
(getf median-params item)
item))
((consp item)
(cons (replace-param-names (car item))
(replace-param-names (cdr item)))))))
(let ((filled-exp (replace-param-names exp)))
(eval filled-exp)))))
(export 'walker-with-exp)
(defun walker-make-step (walker params)
(make-walker-step :prob (+ (reduce #'+ (map 'list (lambda (ll f d e) (funcall ll f params d e)) (walker-log-liklihood walker) (walker-function walker) (walker-data walker) (walker-data-error walker)))
(reduce #'+ (map 'list (lambda (lp d) (funcall lp params d)) (walker-log-prior walker) (walker-data walker))))
:params params))
(defun walker-take-step (walker &key l-matrix (temperature 1))
"The one that uses a full covariance matrix"
(if (null l-matrix) (setq l-matrix (diagonal-covariance (plist-values (scale-plist 1e-2 (walker-get walker :get :median-params :take 1000))))))
(let* ((previous-step (walker-last-step walker))
(prob0 (walker-step-prob previous-step))
(previous-params (walker-step-params previous-step))
(cov-values (get-covariant-sample (plist-values previous-params) l-matrix))
(next-params (make-plist (plist-keys previous-params) cov-values))
(next-step (walker-make-step walker next-params))
(prob1 (walker-step-prob next-step))
(accepted-step (if (or (> prob1 prob0)
(> (/ (- prob1 prob0) temperature) (log (random 1.0d0))))
next-step
previous-step)))
(walker-modify walker :modify :add-step :new-step accepted-step)))
;; TODO prior bounds implementation - it's a good idea
(defun walker-create (&key function data params data-error log-liklihood log-prior param-bounds)
"Make a walker with the prescribed characteristics. Can run over multiple sets of functions and data by simply making lists of kwargs. i.e. :function #'my-function vs :function (list #'my-function #'other-function). data, params, etc. must also then be lists that correspond to the order found in the :function kwarg.
:function expects functions formatted with kwargs as parameters:
(lambda (x &key m b &allow-other-keys) (+ b (* -3 m) (* (- m (/ b 60)) x)))
or like this for multiple or linked independent variables
(lambda (x &key m b &allow-other-keys) (+ b (* -3 m (elt x 0)) (* (- m (/ b 60)) (elt x 1))))
:data expects formatting as (list x-data y-data)
:data-error can be a single number (for uniform error) or a list of the same size as the y-data
:params expects a plist like '(:b -1 :m 2)"
(declare (ignorable param-bounds))
(let* ((function (force-list function))
(data (to-double-floats (clean-data data (length function))))
(data-error (to-double-floats (clean-data-error (if data-error data-error 1) data)))
(params (to-double-floats params))
(log-liklihood (log-liklihood-fixer (if (consp log-liklihood) log-liklihood (make-list (length (force-list function)) :initial-element (if log-liklihood log-liklihood #'log-liklihood-normal))) function params data data-error))
(log-prior (log-prior-fixer (if (consp log-prior) log-prior (make-list (length (force-list function)) :initial-element (if log-prior log-prior #'log-prior-flat))) params data))
(first-step (make-walker-step :prob (+ (reduce #'+ (map 'list (lambda (ll f d e) (funcall ll f params d e)) log-liklihood function data data-error))
(reduce #'+ (map 'list (lambda (lp d) (funcall lp params d)) log-prior data)))
:params params))
(walker (make-walker :function function
:param-keys (plist-keys params)
:param-style (if (consp (elt params 1)) :single-list :multiple-kwargs) ;; TODO manifest this fully
:last-step first-step
:most-likely-step first-step
:walk (list first-step)
:data data
:data-error data-error
:log-liklihood log-liklihood
:log-prior log-prior)))
walker))
(defun mcmc-fit (&key function data params data-error log-liklihood log-prior param-bounds)
(declare (ignorable param-bounds))
(let* ((walker (walker-create :function function
:data data
:params params
:data-error data-error
:log-liklihood log-liklihood
:log-prior log-prior
:param-bounds param-bounds)))
(walker-adaptive-steps walker)
walker))
(export 'mcmc-fit)
(defvar example-function (lambda (x &key m b &allow-other-keys) (+ b (* -3 m) (* (- m (/ b 60)) x))))
(defvar example-data '((-4 -1 2 5 10) (0 2 5 9 13)))
(defvar example-params '(:b -1 :m 2))
(defvar example-error 0.2)
(defvar example-log-liklihood #'log-liklihood-normal)
(defvar example-log-prior #'log-prior-flat)
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key m b &allow-other-keys) (+ b (* -3 m) (* (- m (/ b 60)) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:b -1 :m 2) :data-error 0.2))
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (elt params 0) (* -3 (elt params 1)) (* (- (elt params 1) (/ (elt params 0) 60)) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:params (-1 2)) :data-error 0.2))
;; (defparameter woi (mfit:mcmc-fit :function (list (lambda (x &key b m c d &allow-other-keys) (+ b (* m x) (* c x x) (* d x x x))) (lambda (x &key e m g &allow-other-keys) (+ e (* (+ m g) x)))) :data '(((0 1 2 3 4) (4 5 6 8 4)) ((10 20 30 40 50) (1 2 3 4 5))) :params '(:b -1 :m 2 :c 1 :d -1 :e 0.5 :g -2) :data-error 0.2))
(defun walker-diagnose-params (walker &key (style (or :step-insert :plot-flow)) params)
(case style
(:step-insert (push (walker-make-step walker params) (walker-walk walker)))
(:plot-flow (print "Implement some (10) steps of the walk in plot space to see evolution"))))
(export 'walker-diagnose-params)
;;; Walker and fit visualization
(defun walker-get-data-and-fit-no-stddev (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0) (which-solution (or :most-likely :median)) x-shift y-shift)
"Extract plottable data as well as fit and stddev data from a walker."
(let* ((take (if (or (null take) (> take (walker-length walker)))
(walker-length walker)
take))
(fn (elt (walker-function walker) fn-number))
(data (elt (walker-data walker) fn-number))
(x-data (elt data x-column))
(x-data-shift (if (null x-shift) x-data (map 'vector (lambda (x) (+ x-shift x)) x-data)))
(y-data (elt data y-column))
(y-data-shift (if (null y-shift) y-data (map 'vector (lambda (y) (+ y-shift y)) y-data)))
(x-fit (linspace (reduce #'min x-data) (reduce #'max x-data) :len 1000))
(x-fit-shift (if (null x-shift) x-fit (map 'vector (lambda (x) (+ x-shift x)) x-fit)))
(params (case which-solution
(:most-likely (walker-step-params (walker-get walker :get :most-likely-step :take take)))
(:median (walker-get walker :get :median-params :take take))
(otherwise (walker-get walker :get :median-params :take take))))
(y-fit (mapcar (lambda (x) (apply fn x params)) x-fit))
(y-fit-shift (if (null y-shift) y-fit (map 'vector (lambda (y) (+ y-shift y)) y-fit))))
(list x-fit-shift y-fit-shift x-data-shift y-data-shift params)))
(export 'walker-get-data-and-fit-no-stddev)
(defun walker-get-data-and-fit (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0) (which-solution (or :most-likely :median)) x-shift y-shift)
"Extract plottable data as well as fit and stddev data from a walker."
(let* ((take (if (or (null take) (> take (walker-length walker)))
(walker-length walker)
take))
(fn (elt (walker-function walker) fn-number))
(data (elt (walker-data walker) fn-number))
(x-data (elt data x-column))
(x-data-shift (if (null x-shift) x-data (map 'vector (lambda (x) (+ x-shift x)) x-data)))
(y-data (elt data y-column))
(y-data-shift (if (null y-shift) y-data (map 'vector (lambda (y) (+ y-shift y)) y-data)))
(x-fit (linspace (reduce #'min x-data) (reduce #'max x-data) :len 1000))
(x-fit-shift (if (null x-shift) x-fit (map 'vector (lambda (x) (+ x-shift x)) x-fit)))
(params (case which-solution
(:most-likely (walker-step-params (walker-get walker :get :most-likely-step :take take)))
(:median (walker-get walker :get :median-params :take take))
(otherwise (walker-get walker :get :median-params :take take))))
(y-fit (mapcar (lambda (x) (apply fn x params)) x-fit))
(y-fit-shift (if (null y-shift) y-fit (map 'vector (lambda (y) (+ y-shift y)) y-fit)))
(previous-walks (walker-get walker :get :steps))
(sorted-walks (subseq (sort previous-walks #'> :key #'walker-step-prob) 0 (ceiling (* 0.66 take))))
(all-ys (mapcar (lambda (x) (mapcar (lambda (walk) (apply fn x (walker-step-params walk))) sorted-walks)) x-fit))
(max-ys (mapcar (lambda (y) (+ (if y-shift y-shift 0) (reduce #'max y))) all-ys))
(min-ys (mapcar (lambda (y) (+ (if y-shift y-shift 0) (reduce #'min y))) all-ys)))
(list x-fit-shift max-ys min-ys y-fit-shift x-data-shift y-data-shift params)))
(export 'walker-get-data-and-fit)
(defun walker-plot-data-and-fit (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0) (image-size '(1920 1080)) (which-solution (or :most-likely :median)) x-shift y-shift)
(destructuring-bind (x-fit max-ys min-ys y-fit x-data y-data params) (walker-get-data-and-fit walker :take take :x-column x-column :y-column y-column :fn-number fn-number :which-solution which-solution :x-shift x-shift :y-shift y-shift)
(plt:reset)
(plt:send-command :terminal (apply #'format nil "qt size ~d,~d linewidth 3 font \"Arial,18\"" image-size)
:format "x \"%.4g\""
:format "y \"%.4g\""
:xlabel "\"x-data\""
:ylabel "\"y-data\"")
(plt:plot x-fit max-ys "w l lc rgb \"green\" title \"fit stddev upper limit\""
x-fit min-ys "w l lc rgb \"green\" title \"fit stddev lower limit\""
x-fit y-fit "w l lc rgb \"red\" title \"fit\""
x-data y-data "w p pt 6 ps 2 lc rgb \"black\" title \"data\"")
params))
(defun walker-plot-residuals (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0))
(let* ((take (if (or (null take) (> take (walker-length walker)))
(walker-length walker)
take))
(fn (elt (walker-function walker) fn-number))
(data (elt (walker-data walker) fn-number))
(stddev (elt (walker-data-error walker) fn-number))
(x-data (elt data x-column))
(y-data (elt data y-column))
(stddev (if (= 1 (length stddev)) (make-array (length x-data) :initial-element (elt stddev 0)) stddev))
(params (walker-get walker :get :median-params :take take))
(y-fit (map 'vector (lambda (x) (apply fn x params)) x-data))
(y-residuals (map 'vector (lambda (yf y) (- yf y)) y-fit y-data)))
(plt:reset)
(plt:send-command :terminal "qt size 1920,1080 linewidth 3 font \"Arial,18\""
:format "x \"%.4g\""
:format "y \"%.4g\""
:xlabel "\"x-data\""
:ylabel "\"y-data\"")
(plt:plot x-data y-residuals "w p pt 6 ps 2 lc rgb \"black\" title \"residuals\""
x-data stddev "w p pt 2 ps 1 lc rgb \"red\" title \"point error\""
x-data (make-array (length x-data) :initial-element 0) "w l lc rgb \"red\" title \"baseline\"")))
(defun walker-catepillar-plots (walker &optional take (x-scale 1) (y-scale 1))
(let* ((param-keys (walker-param-keys walker))
(n (length param-keys)))
(plt:reset)
(plt:send-command :terminal (format nil "pngcairo size ~d,~d linewidth 1 font \"Arial,18\"" (* x-scale 1920) (* y-scale 1080))
:output "\"temp.png\""
:format "y \"%.1e\""
:format "x \"%.1e\"")
(apply #'plt:multiplot
(format nil "layout ~d,1" n)
(apply #'append
(mapcar-enum (key i param-keys)
(list (list (walker-get walker :get :param :param key :take take) (format nil "w l title \"~a\"" key))
(if (= i (1- n))
(list :xlabel "\"Step\"" :ylabel (format nil "\"~a\"" key))
(list :xlabel "" :ylabel (format nil "\"~a\"" key)))))))))
(defun walker-liklihood-plot (walker &optional take)
(let ((probs (walker-get walker :get :log-liklihoods :take take)))
(plt:reset)
(plt:send-command :terminal "qt size 1920,1080 linewidth 1 font \"Arial,18\""
:xlabel "\"Step\""
:ylabel "\"Log Liklihood\"")
(plt:plot probs "w l title \"Liklihood\"")))
(defun walker-plot-one-corner (walker keys &optional take)
(let* ((x-key (first keys))
(y-key (second keys))
(x (walker-get walker :get :param :param x-key :take take))
(y (walker-get walker :get :param :param y-key :take take)))
(plt:reset)
(plt:send-command :terminal "qt size 1920,1080 linewidth 1 font \"Arial,18\""
:xlabel (format nil "\"~a\"" x-key)
:ylabel (format nil "\"~a\"" y-key))
(plt:plot x y "w p pt 3 ps 4 title \"My plot\"")))
(defun walker-plot-corner (walker &key take (size '(3240 3240)))
(labels ((permute-params (params)
(let ((return-list nil))
(do ((i 0 (1+ i)))
((>= i (1- (length params))) (reverse return-list))
(do ((j (1+ i) (1+ j)))
((>= j (length params)) nil)
(push (list (elt params i) (elt params j)) return-list)))))
(make-origin-list (params)
(let ((return-list nil)
(len (length params)))
(do ((i 0 (1+ i)))
((>= i (1- (length params))) (reverse return-list))
(do ((j (1+ i) (1+ j)))
((>= j (length params)) nil)
(push (list (* i (/ 1.0 (1- len))) (* (1- j) (/ 1.0 (1- len)))) return-list))))))
(let* ((param-keys (walker-param-keys walker))
(all-params (apply #'append (partition (make-plist param-keys (mapcar (lambda (x) (walker-get walker :get :param :param x :take take)) param-keys)) 2)))
(key-pairs (permute-params param-keys))
(plot-data (mapcar (lambda (x) (destructuring-bind (key1 key2) x (list (getf all-params key1) (getf all-params key2)))) key-pairs))
(origin-list (make-origin-list param-keys)))
(plt:send-plot-options :terminal (format nil "pngcairo size ~d,~d linewidth 1 font \"Arial,12\"" (elt size 0) (elt size 1)) :output "\"temp.png\"")
(apply #'plt:multiplot ""
(apply #'nconc (mapcar-enum (element index plot-data)
(list (list (elt element 0) (elt element 1) "w p"
:origin (apply #'format nil "~,1f,~,1f" (elt origin-list index)) :size (format nil "~1,f,~1,f" (/ 1.0 (1- (length param-keys))) (/ 1.0 (1- (length param-keys)))) :xlabel (format nil "\"~a\"" (elt (elt key-pairs index) 0)) :ylabel (format nil "\"~a\"" (elt (elt key-pairs index) 1)))))))
(plt:send-plot-options :output "unset"))))
(defun walker-param-histo (walker key &key (take 10000) (bins 20))
(let* ((param-values (sort (walker-get walker :get :param :param key :take take) #'<))
(histo-x (make-histo-x param-values bins))
(histo (make-histo param-values bins)))
(plt:reset)
(plt:send-command :terminal "qt size 1920,1080 linewidth 3 font \"Arial,18\""
:xlabel (format nil "\"~a\"" key)
:ylabel "\"Counts\"")
(plt:plot histo-x histo (format nil "w lp ps 3 title \"Histogram: ~a\"" key))))
(defun show ()
"Shows the plots generated from 2d histogram and catepillar functions"
(uiop:run-program "feh ./temp.png -3 5"))
;;; File Management
;; File searching
(defun walk-dirs (dir)
(if (uiop:directory-exists-p dir) ;; is it a dir
(let ((items (nconc (uiop:subdirectories dir) (uiop:directory-files dir))))
(mapcar (lambda (d) (walk-dirs d)) items))
dir))
(defun get-filename (dir &key include exclude)
"Returns all files under dir (and its subdirs) whose name (including directory name) matches ALL specified patterns"
(let* ((include (when include (if (not (listp include)) (list include) include)))
(exclude (when exclude (if (not (listp exclude)) (list exclude) exclude)))
(all-files (flatten (walk-dirs dir)))
(files (remove-if-not (lambda (y)
(and (every (lambda (g) (search g (namestring y))) include)
(notany (lambda (g) (search g (namestring y))) exclude)))
all-files)))
(if (= (length files) 1)
(car files)
files)))
;; File gathering, reading, and quick plotting
(defun read-file-lines (filename)
"Read 'filename' line by line and return a list of strings"
(with-open-file (s filename)
(let ((data nil))
(do ((line (read-line s nil nil) (read-line s nil nil)))
((not line) (reverse data))
(push line data)))))
(export 'read-file-lines)
(defun separate-header-and-data (file-data number-of-header-lines)
(list (subseq file-data 0 number-of-header-lines)
(subseq file-data number-of-header-lines)))
(export 'separate-header-and-data)
(defun auto-split-and-read-csv (unsplit-data-lines)
(let* ((delim-counts (mapcar (lambda (x) (list x (count x (elt unsplit-data-lines 0)))) '(#\tab #\, #\; #\:)))
(most-likely-delim (elt (reduce (lambda (x y) (if (> (elt x 1) (elt y 1)) x y)) delim-counts) 0)))
(remove-if
(lambda (x) (every #'null x))
(map-tree
(lambda (x) (read-from-string x nil nil))
(transpose
(mapcar
(lambda (x) (split-string most-likely-delim x))
unsplit-data-lines))))))
(export 'auto-split-and-read-csv)
(defun file->file-specs (filename &key (delim #\tab))
"Returns various metrics about the file. Lines, header lines, data lines, data rows, data sets."
(with-open-file (in filename :direction :input)
(labels ((get-lines (&optional (num-lines 0) (found-data nil) (data-length nil) (data-rows nil))
(let ((line (string-right-trim '(#\return) (read-line in nil nil)))) ; allow for Windows files
(cond ((string= line "NIL") ; end of file - return info ; ordered by freque
(list :file-lines num-lines :header-lines found-data :data-length data-length :data-rows (if data-rows data-rows (- num-lines found-data)) :num-pages (if data-rows (floor (- num-lines found-data) data-rows) 1)))
((and (string= line "") found-data (not data-rows)) ; set data rows
(get-lines num-lines found-data data-length (- num-lines found-data)))
((string= line "") ; ignore line
(get-lines num-lines found-data data-length data-rows))
((and (numberp (read-from-string (elt (split-string #\tab line) 0))) (not found-data)) ; first line w nums?
(get-lines (+ num-lines 1) num-lines (length (split-string delim line)) data-rows))
(t ; regular line - just increase lines
(get-lines (+ num-lines 1) found-data data-length data-rows))))))
(get-lines))))
(defun make-data-into-pages (data file-specs)
(let ((ret-tree (make-list (getf file-specs :num-pages))))
(mapcar (lambda (x a b)
(setf x (mapcar (lambda (y)
(subseq y a b))
data)))
ret-tree
(butlast (linspace 0 (* (getf file-specs :num-pages) (getf file-specs :data-rows)) :len (1+ (getf file-specs :num-pages)) :type 'integer))
(rest (linspace 0 (* (getf file-specs :num-pages) (getf file-specs :data-rows)) :len (1+ (getf file-specs :num-pages)) :type 'integer)))))
(defun read-file->data (filename &key (file-specs nil) (delim #\tab) (transpose t) pages)
"Reads a file into a list assuming 'delim' separates data. Use 'pages' kwargs to make 3d list assuming each page of data is separated by an extra newline in the file."
(unless file-specs
(setq file-specs (file->file-specs filename :delim delim)))
(let* ((header-lines (getf file-specs :header-lines))
(file-contents nil)
(line nil))
(labels ((remove-header-lines (n stream)
(repeat n (read-line stream nil nil)))
(read-file (stream)
(when (setq line (read-line stream nil nil))
(setq line (string-right-trim '(#\return) line))
(let ((vals (mapcar #'read-from-string (split-string delim line))))
(when vals
(push vals file-contents)))
(read-file stream))))
(with-open-file (in filename :direction :input)
(remove-header-lines header-lines in)
(read-file in)
(let ((file-contents
(if transpose
(transpose-matrix (reverse file-contents))
(reverse file-contents))))
(if pages
(make-data-into-pages file-contents file-specs)
file-contents))))))
(defun read-file->plot (filename &optional (x-column 0) (y-column 1))
(let ((data (read-file->data filename)))
(plt:plot (elt data x-column) (elt data y-column))))
(export 'read-file->plot)
(defun read-files->plot (filenames &optional (x-column 0) (y-column 1))
(let ((data (mapcar #'read-file->data filenames)))
(apply #'plt:plot (apply #'append (mapcar (lambda (e) (list (elt e x-column) (elt e y-column))) data)))))
(export 'read-files->plot)
;;; Statistics Functions
(defun multivariate-gaussian-random (covs)
(mapcar (lambda (x) (* x (alexandria:gaussian-random))) covs))
(defun nth-percentile (n sequence &optional (sorted nil))
(let* ((copy sequence)
(len (length sequence))
(n (* n (- len 1) 1/100)))
(multiple-value-bind (pos rem) (floor n)
(unless sorted
(setq copy (sort (copy-seq sequence) #'<)))
(if (= rem 0)
(elt copy pos)
(let ((e1 (elt copy pos))
(e2 (elt copy (+ pos 1))))
(/ (+ e1 e2) 2))))))
(defun 95cr (sequence)
(list (nth-percentile 2.5 sequence) (nth-percentile 97.5 sequence)))
(defun iqr (sequence &optional (sorted nil))
(unless sorted (setq sorted (sort (copy-seq sequence) #'<)))
(- (nth-percentile 75 sequence t) (nth-percentile 25 sequence t)))
(defun median (sequence &optional sorted)
(nth-percentile 50 sequence sorted))
(defun mean (sequence)
(/ (reduce #'+ sequence) (length sequence)))
(defun variance (sequence)
(let* ((mean (/ (reduce #'+ sequence) (length sequence)))
(sum-sq (reduce #'+ (map 'list (lambda (x) (expt (- x mean) 2)) sequence))))
(/ sum-sq (- (length sequence) 1))))
(defun standard-deviation (sequence)
(sqrt (variance sequence)))
(defun standard-deviation-normal (sequence &optional sorted)
(let* ((copy sequence))
(unless sorted
(setq copy (sort (copy-seq sequence) #'<)))
(let ((middle-value (median copy t))
(upper-variance (nth-percentile 84.1 copy t)))
(- upper-variance middle-value))))
(defun variance-normal (sequence &optional sorted)
(expt (standard-deviation-normal sequence sorted) 2))
;;; binning / histogram
(defun make-histo (sequence &optional num-bins)
(let* ((bottom (reduce #'min sequence))
(top (reduce #'max sequence))
(num-bins (if num-bins num-bins (floor (* (- top bottom) (expt (length sequence) 1/3)) (* 2 (iqr sequence)))))
(num-bins (+ 1 num-bins))
(boundaries (linspace bottom top :len num-bins)))
(labels ((count-for-bins (n sequence &optional return-list)
(if (< n num-bins)
(let ((pos (position (elt boundaries n) sequence :test-not #'>=)))
(unless pos
(setq pos (length sequence)))
(count-for-bins (+ n 1)
(subseq sequence pos)
(cons pos return-list)))
(reverse return-list))))
(count-for-bins 1 sequence))))
(defun make-histo-x (sequence &optional num-bins)
(let* ((bottom (reduce #'min sequence))
(top (reduce #'max sequence))
(num-bins (if num-bins num-bins (floor (* (- top bottom) (expt (length sequence) 1/3)) (* 2 (iqr sequence)))))
(gap-size (/ (- top bottom) num-bins)))
(linspace (+ bottom (/ gap-size 2)) top :len num-bins)))
(export '(log-normal prior-bounds-let standard-deviation walker-create log-liklihood-normal read-file->data walker-adaptive-steps walker-adaptive-steps-full walker-load log-prior-flat walker-plot-data-and-fit linspace walker-set-get get-filename))
| 59,281 | Common Lisp | .lisp | 1,118 | 48.809481 | 517 | 0.654749 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 6ec1ee0fe2d90f43070b1f8637ed7130208692576e20c4c29b9e4a3681b07b2e | 23,313 | [
-1
] |
23,314 | mcmc-fitting.lisp | afranson_Lisp-MCMC/mcmc-fitting.lisp | ;;; mcmc-fitting.lisp
;;; Example basic use
;; Basic line fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key m b &allow-other-keys) (+ b (* m x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:b -1 :m 2) :data-error 0.2))
;; Single param list fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (elt params 0) (* (elt params 1) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:params (-1 2)) :data-error 0.2))
;; Single param vector fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (elt params 0) (* (elt params 1) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:params #(-1 2)) :data-error 0.2))
;; Single param array fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (aref params 0 0) (* (aref params 1 0) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params (list :params (make-array '(2 1) :element-type 'double-float :initial-contents '((-1d0) (2d0)))) :data-error 0.2))
;; Global parameter fit (polynomial and line)
;; (defparameter woi (mfit:mcmc-fit :function (list (lambda (x &key b m c d &allow-other-keys) (+ b (* m x) (* c x x) (* d x x x))) (lambda (x &key e m g &allow-other-keys) (+ e (* (+ m g) x)))) :data '(((0 1 2 3 4) (4 5 6 8 4)) ((10 20 30 40 50) (1 2 3 4 5))) :params '(:b -1 :m 2 :c 1 :d -1 :e 0.5 :g -2) :data-error 0.2))
;; test speed of sample space rotation via l-matrix (matrix multiplication)
;; Arrays are slower without optimization. 10x faster with optimization (basic array multiplication)
;; Performing calculation with arrays while transforming from lists to arrays is 1.37x faster
;; Vectors are slower without optimization. 2x faster with optimization
#|
(defun rotate-list (l-lists sample)
(mapcar (lambda (x) (list (reduce #'+ (mapcar (lambda (s l) (* (elt s 0) l)) sample x)))) l-lists))
(defun rotate-vector (l-vectors sample)
(declare (optimize speed debug (safety 0))
(simple-vector sample l-vectors))
(map 'simple-vector (lambda (x) (declare (simple-vector x)) (list (reduce #'+ (map 'simple-vector (lambda (s l) (* (the double-float (elt s 0)) (the double-float l))) sample x)))) l-vectors))
(defun rotate-array (l-array sample)
(declare (optimize speed debug (safety 0))
((simple-array double-float *) l-array sample))
(let* ((imax (array-dimension l-array 0))
(jmax (array-dimension l-array 1))
(kmax (array-dimension sample 1))
(return-array (make-array (list imax kmax))))
(do ((i 0 (1+ i)))
((>= i imax) return-array)
(do ((k 0 (1+ k)))
((>= k kmax))
(setf (aref return-array i k)
(do ((j 0 (1+ j))
(mini-sum 0d0))
((>= j jmax) mini-sum)
(declare (double-float mini-sum))
(incf mini-sum (* (aref l-array i j) (aref sample j k)))))))))
(progn
(defparameter rank 3000)
(defparameter l-lists (mfit::repeat rank (mfit::repeat rank (random 1d0))))
(defparameter l-vectors (map 'simple-vector (lambda (x) (coerce x 'simple-vector)) l-lists))
(defparameter l-array (make-array (list rank rank) :element-type 'double-float :initial-contents l-lists))
(defparameter sample-list (mfit::repeat rank (list (random 1d0))))
(defparameter sample-vector (coerce sample-list 'simple-vector))
(defparameter sample-array (make-array (list rank 1) :element-type 'double-float :initial-contents sample-list))
(defparameter rotated-sample (time (null(rotate-list l-lists sample-list))))
(defparameter rotated-vectors (time (null (rotate-vector l-vectors sample-vector))))
(defparameter rotated-array (time (null (rotate-array l-array sample-array))))
(time (progn (rotate-array (make-array (list rank rank) :element-type 'double-float :initial-contents l-lists)
(make-array (list rank 1) :element-type 'double-float :initial-contents sample-list)))))
|#
;; testing function evaluation speed over a list of data vs arrays of data
;; vector is not faster than list
;; 2x speed up by optimizing for single/double floats
#|
(defun myfunc (x &key p1 p2 p3 &allow-other-keys)
"Simple Gaussian"
(declare (optimize (speed 3) (safety 1) (debug 1))
(double-float x p1 p2 p3))
(* p3 (exp (- (expt (/ (- x p1) p2) 2)))))
(progn
(defparameter params (list :p1 20d0 :p2 5d0 :p3 14d0))
(defparameter x-list (mfit:linspace 0 50 :len 100 :type 'double-float))
(defparameter x-vector (coerce x-list 'simple-vector))
(time (null (mfit::repeat 100000 (mapcar (lambda (x) (apply #'myfunc x params)) x-list))))
(time (null (mfit::repeat 100000 (let* ((func-x (lambda (x) (apply #'myfunc x params))) (vec-len (length x-vector)) (return-vec (make-array (list vec-len) :element-type 'double-float))) (do ((i 0 (1+ i))) ((>= i vec-len) return-vec) (setf (aref return-vec i) (funcall func-x (svref x-vector i)))))))))
|#
;; (sb-ext:muffle-conditions sb-ext:compiler-note)
;; Full arrays > list of arrays > pure lists
;; just lists don't benefit from optimization
;; arrays do a lot
;; arrays aren't much better than lists without optimization
;; (ql:quickload :gsll)
;; (ql:quickload :antik)
#| For testing cholesky decomps vs gsl implementation
(defun eyes (n)
(do ((i 0 (1+ i))
(ret-array nil (push (do ((j 0 (1+ j))
(ret-list nil (push (if (= i j) 1 0) ret-list)))
((> j n) (reverse ret-list)))
ret-array)))
((> i n) (reverse ret-array))))
(defun matrix-add (mat1 mat2)
(let ((ret-mat nil))
(dolist (erc (mapcar #'list mat1 (transpose-matrix mat2)) (reverse ret-mat))
(push (mapcar #'+ (elt erc 0) (elt erc 1)) ret-mat))))
(defparameter randmat (repeat 3 (repeat 3 (random 10d0))))
(defparameter posdefmat (matrix-add (scale-array 10 (eyes 3)) (scale-array 0.5 (matrix-add randmat randmat))))
|#
(in-package :mcmc-fitting)
;;; Utility
(defmacro br (&body body)
`(break "break ~s" ,@body))
(defun elts (tree &rest elts)
"Apply multiple elt to a tree. I.e. (elt (elt (elt foo 3) 2) 1) is simply (elts foo 3 2 1) or (apply #'elts foo '(3 2 1))."
(reduce (lambda (x y) (elt x y)) elts :initial-value tree))
(defun (setf elts) (new-value tree &rest elts)
"Make elts setf-able. Usage is (setf (elts tree elt0 elt1 elt2 ...) new-value) or (setf (apply #'elts tree eltslist) new-value)."
(setf (elt (apply #'elts tree (butlast elts)) (car (last elts))) (if (listp new-value) (copy-seq new-value) new-value)))
(defmacro return-this-but-also (expr &body body)
"Returns the provided 'expr' while also performing manipulations on 'expr' provided in 'body' to allow for printing subsections, performing logic, etc. Uses 'it' as the key term in 'body' to refer to the result of the 'expr'.
i.e. (return-this-but-also (list 4 8 2 0 4 12 0) (print (list (count 0 it) (count-if #'evenp it) (position 8 it))))
==> (2 7 1)
==> (4 8 2 0 4 12 0)"
(let ((it-g (gensym)))
`(let ((,it-g (multiple-value-list ,expr)))
(let ((it (lambda () (values-list ,it-g))))
,@(subst '(funcall it) 'it body)
(funcall it)))))
(defun range (start-or-end &optional end)
"Provides a list of numbers from 'start' to 'end' incrementing by 1. Always integers. Floors inputs.
(range 5.2) => '(0 1 2 3 4)
(range 2 5) => '(2 3 4)
(range 5 2) => '(5 4 3)"
(let ((start (floor (if end start-or-end 0)))
(end (floor (if end end start-or-end))))
(let ((return-list nil) (sign (signum (- end start))))
(do ((curr start (progn (push curr return-list) (+ sign curr))))
((= curr end) (reverse return-list))))))
(defun thin (list n &optional (start 0))
"Returns every 'n'th element from 'list' starting with 'start'."
(if (= n 1)
list
(do ((i 0 (1+ i))
(return-list nil))
((= i (length list)) (reverse return-list))
(when (= 0 (mod (- i start) n))
(push (elt list i) return-list)))))
(defun slice (2d-list &optional rows cols)
"Take a slice of a 2d list taking 'rows' (i.e. '(1 3 5) for rows 1 then 3 then 5) and 'cols' (i.e. '(20 40) for items 20 through 40)."
(let ((rows (if rows rows (range (length 2d-list))))
(cols (if cols cols (list 0 (length (elt 2d-list 0))))))
(mapcar (lambda (x) (apply #'subseq (elt 2d-list x) cols)) rows)))
(defmacro mapcar-enum ((element index list) &body body)
"mapcar with enumeration. Iterates over 'list' using 'element' to store each element, 'index' to store the index, and \"list\" to store the full list. Returns a list made of applying 'body' to each element of 'list'.
try: (mapcar-enum (e i '(30 20 10)) (print (list e i)))"
(let ((return-list-g (gensym "RETURN-LIST")))
`(let ((,return-list-g nil)
(list ,list))
(do ((,index 0 (1+ ,index))
(,element nil))
((>= ,index (length list)))
(setf ,element (elt list ,index))
(push ,@body ,return-list-g))
(reverse ,return-list-g))))
(defun map-tree (function tree)
"Maps 'function' over the deepest elements of 'tree'. 'tree' can be composed of any combination of sequences.
E.g. (map-tree #'1+ '((1 2) (2 3) (3 4) (100 (12 23 (324 54)))))
=> '((2 3) (3 4) (4 5) (101 (13 24 (325 55))))."
(cond ((null tree)
nil)
((and (atom tree) (or (arrayp tree) (stringp tree) (not (vectorp tree))))
(funcall function tree))
(t
(map (type-of tree) (lambda (x) (map-tree function x)) tree))))
(export 'map-tree)
(defun plist-keys (plist)
"Get all unique keys from 'plist'."
(do ((keys (list (pop plist)) (progn (pop plist) (append (list (pop plist)) keys))))
((null (nthcdr 2 plist)) (reverse (remove-duplicates keys)))))
(defun plist-values (plist)
"Get all values belonging to unique keys in 'plist'. Returns the first example of a value found."
(let ((keys (plist-keys plist)))
(mapcar (lambda (x) (getf plist x)) keys)))
(defun make-plist (keys values)
"Riffles a set of 'keys' and 'values' into a plist."
(apply #'append (mapcar #'list keys values)))
(defun array-to-plist (keys values-array)
(make-plist keys (mapcar (lambda (x) (aref values-array x 0)) (range (array-dimension values-array 0)))))
(defmacro repeat (count &body expression)
`(mapcar (lambda (x) (declare (ignore x)) ,@expression) (make-list ,count)))
(defun mkstr (&rest args)
(with-output-to-string (s)
(dolist (a args) (princ a s))))
(defun symb (&rest args)
(values (intern (apply #'mkstr args))))
(defun symb-keyword (&rest args)
(values (intern (apply #'mkstr args) :keyword)))
(defun remove-consecutive-duplicates (list)
(mapcon (lambda (x)
(if (eql (car x) (cadr x)) nil (list (car x))))
list))
(defun remove-duplicates-plist (plist)
(let* ((keys (get-plist-keys plist))
(unique-keys (remove-duplicates keys)))
(make-plist
unique-keys
(mapcar (lambda (x) (getf plist x)) unique-keys))))
(defun elements-between (sequence start-value end-value)
(remove-if-not (lambda (x) (<= start-value x end-value)) sequence))
(defun linspace (start end &key (len 50) (step nil) (type 'double-float))
"Provides a list from 'start' to 'end' (inclusive) that is 'len' in length. Or provides a list of number from 'start' until 'end' by 'step'. 'end' may not be reached if 'step' kwarg is provided.
Supported types for 'type' arg are 'float, 'double-float, 'rational, 'integer, 'bignum."
(let ((step (if step step (/ (rational (- end start)) (1- len))))
(len (if step (+ 1 (floor (- end start) step)) len))
(return-list nil))
(let ((rational-numbers
(do ((n 0 (1+ n))
(curr (rational start) (progn (push curr return-list) (+ curr step))))
((>= n len) (reverse return-list)))))
(values (case type
((or single-float float double-float rational) (mapcar (lambda (x) (coerce x type)) rational-numbers))
(t (mapcar #'round rational-numbers)))
step))))
(defun n-nums (n)
(do ((m 0 (1+ m))
(l nil (push m l)))
((= m n) (reverse l))
(declare (fixnum m))))
(defun up-to (n &optional (start 0))
(assert (>= n start))
(do ((m start (1+ m))
(l nil (push m l)))
((= m (1+ n)) (reverse l))
(declare (fixnum m))))
(defun diff-matrix (matrix)
"Find the difference between consecutive items in a list of lists, vectors, or arrays. Returns a list of lists."
(mapcon (lambda (x)
(if (nthcdr 1 x)
(list (map 'list (lambda (x y)
(etypecase x
(number (- x y))
(list (mapcar #'- x y))
(vector (map 'list #'- x y))
(array (let ((return-list nil)) (dotimes (i (array-dimension x 0) return-list) (push (- (aref x i 0) (aref y i 0)) return-list))))))
(cadr x) (car x)))
nil))
matrix))
(defun diff-lplist (lplist)
(let* ((keys (get-plist-keys (elt lplist 0)))
(values (mapcar #'plist-values lplist)))
(mapcar (lambda (x) (make-plist keys x)) (diff-matrix values))))
(defun partition (list n)
"Pairs elements and removes any with full matches"
(labels ((rec (l &optional (acc nil))
(if (nthcdr (- n 1) l)
(rec (subseq l n) (cons (subseq l 0 n) acc))
(cons l acc))))
(reverse (cdr (rec list)))))
(defun transpose (xy-list)
"Takes 'xy-list' of form ((x1 y1 z1 ...) (x2 y2 z2 ...) ...) and turns it into ((x1 x2 ...) (y1 y2 ...) (z1 z2 ...) ...). Also known as a transpose. It is its own inverse. Works for combinations of lists and vectors."
(when xy-list
(apply #'map 'list #'list xy-list)))
(defun list-of-arrays-transpose (l-o-array)
"Transpose a list of column vectors (2d arrays)."
(declare (optimize speed (safety 0))
(list l-o-array))
(let ((return-list nil))
(dotimes (j (array-dimension (the (array double-float (* *)) (car l-o-array)) 0) return-list)
(push (mapcar
(lambda (x)
(declare ((simple-array double-float) x))
(aref x j 0))
l-o-array)
return-list))))
(defun flatten (list)
"Remove all structure from list"
(let ((return-list nil))
(labels ((%flatten (list)
(cond ((null list)
nil)
((consp list)
(mapcar #'%flatten list))
(t
(push list return-list)))))
(%flatten list))
(reverse return-list)))
(defun split-string (splitter string)
"Split string by splitter, which is a char."
(declare (optimize speed safety)
(character splitter))
(labels ((inner-split (string &optional acc)
(declare (optimize speed safety)
(simple-string string)
(type (or null cons) acc))
(if (string/= string "")
(let ((pos (position splitter string :test #'char=)))
(if pos
(inner-split (subseq string (+ pos 1)) (cons (subseq string 0 pos) acc))
(inner-split "" (cons string acc))))
(reverse acc))))
(inner-split string)))
;;; Log-liklihood and log-prior functions
(defun log-prior-flat (params data)
"Always 0d0."
(declare (ignore params data))
0d0)
;; TODO let this work with positions as well
(defmacro prior-bounds-let ((&rest keys-low-high) &body body)
"Helps construct useful bounds on parameters. -1d10 penalty for going outside of specified low and high values with an exponential gradient to help the algorithm find it's way back/prevent it from accidentally leaving. Anaphor 'bounds-total' should be used as part of the return value of the body. Assumes multiple kwarg usage of the walker (Needs variables names, not positions). Used as...
==> (prior-bounds-let ((x -10 10) (y 100 200) (z 1d-4 1d-2)) (+ bounds-total (* 4 x-bound)))"
#+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(flet ((expand-keys (key-low-high)
(let* ((key (car key-low-high))
(param-name (read-from-string (symbol-name key))))
`(,param-name (the double-float (getf ,(intern "PARAMS") ,key 0d0)))))
(expand-bounds (key-low-high)
(destructuring-bind (key low-expr high-expr) key-low-high
(let ((param-name (read-from-string (symbol-name key)))
(param-name-bound (read-from-string (concatenate 'string (symbol-name key) "-bound"))))
`(,param-name-bound (the double-float (if (< ,low-expr ,param-name ,high-expr)
0d0
(* -1d10 (- (exp (* (min (abs (- ,param-name ,high-expr)) (abs (- ,param-name ,low-expr))) 1d-5)) 1))))))))
(get-bound-name (key-low-high)
(destructuring-bind (key low-expr high-expr) key-low-high
(declare (ignore low-expr high-expr))
(let ((param-name-bound (read-from-string (concatenate 'string (symbol-name key) "-bound"))))
param-name-bound))))
`(let* (,@(mapcar #'expand-keys keys-low-high)
,@(mapcar #'expand-bounds keys-low-high)
(,(intern "BOUNDS-TOTAL") (+ ,@(mapcar #'get-bound-name keys-low-high))))
,@body)))
;; log-liklihood can depend on x, y, params, stddev (additional distribution parameters)
(defun log-normal (x mu sigma)
#+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note)
(optimize speed)
(double-float mu x)
(type (double-float 0d0 *) sigma))
(+ (* -1/2 (log (* 2 pi))) (* -1 (log sigma)) (* -1/2 (expt (/ (- x mu) sigma) 2d0))))
(defun log-factorial (n)
(reduce (lambda (x y) (+ x (log y))) (up-to n)))
(defun log-poisson (lambda k)
(- (* k (log lambda)) lambda (log-factorial k)))
;; log liklihood is the function that determines how data is useful
;; It does the pattern matching and analysis on input variables
;; The liklihood defines the result
;; Each independent variable needs to have the appropriate distribution
;; Then they just all add together (for the log version)
;; The prior is then tacked on at the end however the user sees fit
;; Since the prior does not change, it will just speed up the convergence to have a good one
;; prior could also depend on data for bounds or such
(defun log-liklihood-normal (fn params data stddev)
(declare (optimize speed)
(list data stddev)
(function fn))
(let* ((x (nth 0 data))
(y (nth 1 data)))
(declare (list x y))
(reduce #'+ (mapcar (lambda (x y z) (log-normal y (apply fn x params) z)) x y stddev))))
(defun create-log-liklihood-function (log-liklihood-function)
"Input a function that determines the log-liklihood of some data point. 'log-liklihood-function' needs to accept 3 arguments. This function assumes your independent (x) variable is in the 0th column of the data and the dependent (y) variable is in the 1st column. If you have more elaborate needs, examine the implementation of #'create-log-liklihood-normal and modify to your needs.
The first is the actual y value of the point.
The second is the model predicted value of the point.
The third is the error of the point.
i.e. (lambda (y model error) (/ (- y model) error))
i.e. (lambda (y model error) (declare (ignore error)) (/ (- y model) 1)) ;; you can ignore any arguments you want, but the function must accept 3 arguments."
(lambda (fn params data stddev)
(declare (optimize speed)
(list data stddev)
(function log-liklihood-function fn))
(let* ((x (nth 0 data))
(y (nth 1 data)))
(declare (list x y))
(reduce #'+ (mapcar (lambda (x y) (funcall log-liklihood-function y (apply fn x params) stddev)) x y)))))
(export 'create-log-liklihood-function)
(defun log-liklihood-normal-cutoff (fn params data stddev)
(declare (optimize speed)
(list data stddev)
(function fn))
(let* ((x (elt data 0))
(y (elt data 1)))
(declare (list x y))
(reduce #'+ (mapcar (lambda (x y z) (max -5000d0 (the double-float (log-normal y (apply fn x params) z)))) x y stddev))))
(export 'log-liklihood-normal-cutoff)
;;; plist functions
(defun get-plist-keys (plist &optional return-keys)
(if (car plist)
(get-plist-keys (cddr plist) (cons (car plist) return-keys))
(reverse return-keys)))
(defun get-plist-values (plist &optional return-values)
(if (car plist)
(get-plist-values (cddr plist) (cons (cadr plist) return-values))
(reverse return-values)))
(defun reduce-plists (function plist1 plist2 &optional result)
(if (and (cadr plist1) (cadr plist2))
(let ((key (car plist1)))
(reduce-plists function (cddr plist1)
plist2
(nconc (list (funcall function (cadr plist1) (getf plist2 key)) key) result)))
(reverse result)))
(defun map-plist (fn plist)
(let* ((keys (get-plist-keys plist))
(values (get-plist-values plist))
(ret-values (map-tree fn values)))
(make-plist keys ret-values)))
(defun scale-plist (scale plist)
(map-plist (lambda (x) (* x scale)) plist))
;;; Walker and associated functions
(defstruct walker-step
(prob most-negative-double-float :type float)
(params nil :type list))
(export '(walker-step make-walker-step walker-step-prob walker-step-params))
(defstruct walker
(function nil :type list)
(param-keys nil :type list)
(param-style (or :multiple-kwargs :single-item) :type symbol)
(walk nil :type list)
(length 1 :type integer)
(age 1 :type integer)
(most-likely-step (make-walker-step) :type walker-step)
(last-step (make-walker-step) :type walker-step)
(data nil :type (or list vector))
(data-error nil :type list)
(log-liklihood nil :type list)
(log-prior nil :type list))
(export '(walker make-walker walker-function walker-param-keys walker-walk walker-length walker-age walker-most-likely-step walker-last-step walker-data walker-data-error walker-log-liklihood walker-log-prior))
;; Useful for inspecting when algorithm fails
(defun walker-check-for-complex-walks (walker &optional take)
(let ((complex-walks-ps (mapcar (lambda (x) (some #'identity x)) (map-tree #'complexp (lplist-to-l-matrix (diff-lplist (walker-get walker :get :unique-steps :take take)))))))
(if (some #'identity complex-walks-ps) complex-walks-ps nil)))
(defun walker-get (walker &key (get (or :steps :unique-steps :forward-steps :most-likely-step :acceptance :param :params :most-likely-params :median-params :all-params :stddev-params :log-liklihoods :covariance-matrix :l-matrix)) take param)
"Get any of the above items from a walker. Use the 'take' kwarg to limit the number of walks you are sampling over. Use the 'param' kwarg to specify which params for the :param :get option."
(case get
(:steps (subseq (walker-walk walker) 0 (when take (min (walker-length walker) take))))
;; TODO Bad names, should give step list, not just params
(:unique-steps (mapcon (lambda (x)
(if (equal (walker-step-prob (car x)) (when (cadr x) (walker-step-prob (cadr x))))
nil
(list (walker-step-params (car x)))))
(walker-get walker :get :steps :take take)))
(:forward-steps (mapcon (lambda (x)
(when (cadr x)
(if (<= (walker-step-prob (car x)) (walker-step-prob (cadr x)))
nil
(list (walker-step-params (car x))))))
(walker-get walker :get :steps :take take)))
(:most-likely-step (reduce (lambda (x y)
(if (> (walker-step-prob x) (walker-step-prob y)) x y))
(walker-get walker :get :steps :take take)))
(:acceptance
(let* ((probs (mapcar #'walker-step-prob (walker-get walker :get :steps :take take))))
(/ (length (remove-consecutive-duplicates probs)) (length probs))))
(:param (mapcar (lambda (x) (getf (walker-step-params x) param)) (walker-get walker :get :steps :take take)))
(:params (mapcar #'walker-step-params (walker-get walker :get :steps :take take)))
(:most-likely-params
(let ((param-keys (walker-param-keys walker))
(most-likely-step (walker-most-likely-step walker)))
(make-plist param-keys
(mapcar (lambda (key) (getf (walker-step-params most-likely-step) key)) param-keys))))
(:median-params
(let ((param-keys (walker-param-keys walker))
(steps (walker-get walker :get :steps :take take)))
(make-plist param-keys
(typecase (cadr (walker-step-params (car steps)))
(number (mapcar (lambda (key) (median (mapcar (lambda (step) (getf (walker-step-params step) key)) steps))) param-keys))
((or list vector) (list (mapcar #'median (transpose (mapcar (lambda (step) (getf (walker-step-params step) (elt param-keys 0))) steps)))))
(array (list (mapcar #'median (list-of-arrays-transpose (mapcar (lambda (step) (getf (walker-step-params step) (elt param-keys 0))) steps)))))))))
;; TODO add failsafe here if not enough valid steps to do cholesky
(:stddev-params
(let* ((param-keys (walker-param-keys walker)))
(if (< (walker-length walker) 10)
(make-plist param-keys (make-list (length param-keys) :initial-element 0d0))
(let ((l-matrix (walker-get walker :get :l-matrix :take take)))
(values (if (eq :multiple-kwargs (walker-param-style walker))
(make-plist param-keys
(mapcar (lambda (x)
(elt (elt l-matrix x) x))
(up-to (1- (length l-matrix)))))
(make-plist param-keys
(list (mapcar (lambda (x)
(elt (elt l-matrix x) x))
(up-to (1- (length l-matrix)))))))
l-matrix)))))
(:log-liklihoods (mapcar #'walker-step-prob (walker-get walker :get :steps :take take)))
(:covariance-matrix (lplist-covariance (walker-get walker :get :unique-steps :take take)))
;; TODO Experimental - forward steps vs unique steps
(:l-matrix (lplist-to-l-matrix (diff-lplist (walker-get walker :get :forward-steps :take take))))))
(export 'walker-get)
(defun walker-modify (walker &key (modify (or :add-step :add-walks :burn-walks :keep-walks :reset :reset-to-most-likely :delete)) new-step new-walks burn-number keep-number)
(case modify
(:add-step (progn (push new-step (walker-walk walker))
(setf (walker-last-step walker) new-step)
(setf (walker-length walker) (1+ (walker-length walker)))
(setf (walker-age walker) (1+ (walker-age walker)))
(when (> (walker-step-prob new-step)
(walker-step-prob (walker-most-likely-step walker)))
(setf (walker-most-likely-step walker) new-step))))
(:add-walks (progn (nconc (reverse new-walks) (walker-walk walker))
(setf (walker-last-step walker) (last new-walks))
(setf (walker-length walker) (+ (length new-walks) (walker-length walker)))
(setf (walker-age walker) (+ (length new-walks) (walker-age walker)))
(mapcar
(lambda (new-step)
(when (> (walker-step-prob new-step)
(walker-step-prob (walker-most-likely-step walker)))
(setf (walker-most-likely-step walker) new-step)))
new-walks)))
(:burn-walks (progn (setf (walker-walk walker) (subseq (walker-walk walker) 0 (- (walker-length walker) burn-number)))
(setf (walker-length walker) (- (walker-length walker) burn-number))))
(:keep-walks (progn (setf (walker-walk walker) (subseq (walker-walk walker) 0 keep-number))
(setf (walker-length walker) keep-number)))
(:reset (progn (setf (walker-walk walker) (last (walker-walk walker)))
(setf (walker-last-step walker) (car (walker-walk walker)))
(setf (walker-length walker) 1)
walker))
(:reset-to-most-likely
(progn (setf (walker-walk walker) (list (walker-most-likely-step walker)))
(setf (walker-last-step walker) (car (walker-walk walker)))
(setf (walker-length walker) 1)
walker))
(:delete (progn (setf (walker-walk walker) nil)
(setf walker (make-walker))))))
(export 'walker-modify)
(defun cholesky-decomp (covariance-matrix)
"Generalization of the sqrt operation for postive definite matrices. Takes a 2d, double-float array 'covariance-matrix' and turns it into a 2d, double-float array that is often referred to a an l-matrix (lower triangular matrix)."
(declare (optimize speed (safety 1))
((simple-array double-float (* *)) covariance-matrix))
(let ((l-array (make-array (array-dimensions covariance-matrix) :element-type 'double-float))
(tmp-sum 0d0))
(declare (double-float tmp-sum))
(dotimes (i (array-dimension covariance-matrix 0))
(dotimes (k (+ i 1))
(setq tmp-sum 0d0)
(dotimes (j k)
(incf tmp-sum (* (aref l-array i j) (aref l-array k j))))
(if (= i k)
(setf (aref l-array i k) (sqrt (max 0d0 (- (aref covariance-matrix i k) tmp-sum))))
(setf (aref l-array i k) (/ (- (aref covariance-matrix i k) tmp-sum) (aref l-array k k))))))
l-array))
;;; matrix and covariance
(defun transpose-matrix (matrix)
(let ((num-columns (- (length (elt matrix 0)) 1)))
(mapcar (lambda (el) (mapcar (lambda (row) (elt row el)) matrix)) (up-to num-columns))))
(defun scale-array (scale matrix)
(declare (optimize speed (safety 1))
((simple-array double-float (* *)) matrix)
(double-float scale))
(dotimes (i (array-dimension matrix 0) matrix)
(dotimes (j (array-dimension matrix 1))
(setf (aref matrix i j) (* scale (aref matrix i j))))))
;; TODO Takes a long time....
(defun lplist-covariance (lplist)
"Takes in a list of p lists (lplist) that either have the structure ((:a 1 :b 2 :c 3 ...) (:a 1 :b 2 :c 3 ...) ...) or ((:all-params #(2 3 4 4 5 6 2 ...)) (:all-params #(2 3 4 4 5 6 2 ...)) ...). Returns a covariance matrix as a 2d, double-float array."
(declare (optimize speed (safety 0))
(cons lplist))
(let* ((num-of-points (length lplist))
(single-item? (consp (cadar lplist)))
(num-of-params (if single-item? (length (the list (cadar lplist))) (floor (length (the list (car lplist))) 2)))
(values (mapcar #'get-plist-values lplist))
(values (transpose (if single-item? (map 'list #'first values) values)))
;; Sets of each like parameter in an array
(values-array (make-array (list num-of-params num-of-points) :element-type 'double-float :initial-contents values))
;; Average value of each like parameter
(avg (map 'vector (lambda (x) (/ (the double-float (reduce #'+ x)) num-of-points)) (the list values)))
;; Value of each parameter subtraced from its average
(average-normalized (make-array (list num-of-params num-of-points) :element-type 'double-float))
;; covariance output (dot a with each other a and divide by n)
(covariance (make-array (list num-of-params num-of-params) :element-type 'double-float)))
(declare ((simple-array double-float (* *)) values-array)
((simple-vector *) avg))
(dotimes (i num-of-params average-normalized)
(dotimes (j num-of-points)
(setf (aref average-normalized i j) (- (aref values-array i j) (the double-float (aref avg i))))))
(dotimes (i num-of-params covariance)
(dotimes (j num-of-params)
(setf (aref covariance i j)
(do ((k 0 (1+ k))
(mini-sum 0d0))
((>= k num-of-points) mini-sum)
(declare (double-float mini-sum))
(incf mini-sum (/ (* (aref average-normalized i k) (aref average-normalized j k)) num-of-points))))))))
(defun lplist-covariance-old (lplist)
"Takes in a list of p lists (lplist) that either have the structure ((:a 1 :b 2 :c 3 ...) (:a 1 :b 2 :c 3 ...) ...) or ((:all-params #(2 3 4 4 5 6 2 ...)) (:all-params #(2 3 4 4 5 6 2 ...)) ...). Returns a covariance matrix as a 2d, double-float array."
(declare (optimize speed (safety 0))
(cons lplist))
(let* ((num-of-points (length lplist))
(single-item? (consp (cadar lplist)))
(num-of-params (if single-item? (length (the list (cadar lplist))) (floor (length (the list (car lplist))) 2)))
(values (mapcar #'get-plist-values lplist))
;; Sets of each like parameter
(values (transpose (if single-item? (map 'list #'first values) values)))
;; Average value of each like parameter
(avg (map 'list (lambda (x) (/ (the double-float (reduce #'+ x)) num-of-points)) values))
;; Value of each parameter subtraced from its average
(average-normalized (make-array (list num-of-params num-of-points) :element-type 'double-float))
;; covariance output (dot a with each other a and divide by n)
(covariance (make-array (list num-of-params num-of-params) :element-type 'double-float)))
(dotimes (i num-of-params average-normalized)
(dotimes (j num-of-points)
(setf (aref average-normalized i j) (- (the double-float (elts values i j))
(the double-float (elt avg i))))))
(dotimes (i num-of-params covariance)
(dotimes (j num-of-params)
(setf (aref covariance i j)
(do ((k 0 (1+ k))
(mini-sum 0d0))
((>= k num-of-points) mini-sum)
(declare (double-float mini-sum))
(incf mini-sum (/ (* (aref average-normalized i k) (aref average-normalized j k)) num-of-points))))))))
(defun lplist-to-l-matrix (lplist)
"Thin wrapper around Cholesky routine."
(cholesky-decomp (lplist-covariance lplist)))
(defun get-covariant-sample (means l-matrix)
"Rotates a sample by an l-matrix"
(declare (optimize speed debug (safety 0))
((simple-array double-float (* *)) l-matrix means))
(let* ((imax (array-dimension l-matrix 0))
(jmax (array-dimension l-matrix 1))
(kmax (array-dimension means 1))
(return-array (make-array (list imax kmax) :element-type 'double-float))
(samples-array (make-array (list (array-dimension means 0) 1) :element-type 'double-float :initial-contents (mapcar #'list (repeat (array-dimension means 0) (alexandria:gaussian-random))))))
(declare ((simple-array double-float *) samples-array return-array))
;; matrix multiply ==> l-matrix·means - in that order
(dotimes (i imax)
(dotimes (k kmax)
(setf (aref return-array i k)
(do ((j 0 (1+ j))
(mini-sum 0d0))
((>= j jmax) mini-sum)
(declare (double-float mini-sum))
(incf mini-sum (* (aref l-matrix i j) (aref samples-array j k)))))))
;; Add previous matrix (shift matrix) to the provided means
(dotimes (i imax return-array)
(setf (aref return-array i 0) (+ (aref return-array i 0) (aref means i 0))))))
;; (mfit::get-covariant-sample #(5 9 2) (mfit::lplist-to-l-matrix mfit::example-array-lplist))
;; (defun get-covariant-sample (means l-matrix)
;; "Takes a 2d, double-float array of previous means, a 2d, double-float array l-matrix. Takes a random sample with the same length as the means, rotates it by the l-matrix, and adds it to the previous means. Returns a 2d, double-float array (column vector)."
;; (let ((samples (repeat (array-dimension means 0) (alexandria:gaussian-random))))
;; (if (consp (car means))
;; (list (mapcar #'+ (car means) (rotate-random-sample samples l-matrix)))
;; (mapcar #'+ means (rotate-random-sample samples l-matrix)))))
(defun diagonal-covariance (set)
"Take a set of means (list, vector, or column vector (2d array)) and return a 2d array with the means on the diagonal."
(let* ((len (typecase (car set)
(number (length set))
((or list vector) (length (car set)))
(array (array-dimension (car set) 0))
(otherwise 0)))
(return-array (make-array (list len len) :element-type 'double-float)))
(dotimes (i len return-array)
(dotimes (j len)
(setf (aref return-array i j)
(if (= i j)
(typecase (car set)
(number (elt set i))
((or list vector) (elt (car set) i))
(array (aref (car set) i 0))
(otherwise 0d0))
0d0))))))
(defvar example-lplist '((:a 90d0 :b 60d0 :c 90d0)
(:a 90d0 :b 90d0 :c 30d0)
(:a 60d0 :b 60d0 :c 60d0)
(:a 60d0 :b 60d0 :c 90d0)
(:a 30d0 :b 30d0 :c 30d0)))
(defvar example-array-lplist
(mapcar (lambda (x)
(list :params (make-array '(3) :element-type 'double-float :initial-contents x)))
'((90d0 60d0 90d0)
(90d0 90d0 30d0)
(60d0 60d0 60d0)
(60d0 60d0 90d0)
(30d0 30d0 30d0))))
(defparameter example-covariance (list (lplist-covariance example-lplist)
;;(lplist-covariance example-array-lplist)
))
;; #2A((504.0d0 360.0d0 180.0d0) (360.0d0 360.0d0 0.0d0) (180.0d0 0.0d0 720.0d0))
(defparameter example-l-matrix (list (lplist-to-l-matrix example-lplist)
;;(lplist-to-l-matrix example-array-lplist)
))
;; #2A((22.44994432064365d0 0.0d0 0.0d0)
;; (16.035674514745462d0 10.141851056742201d0 0.0d0)
;; (8.017837257372731d0 -12.677313820927745d0 22.248595461286993d0))
;;; MCMC Metropolis-Hastings
(defun force-list (item)
"Forces all non-list items into lists"
(if (consp item)
item
(list item)))
(defun get-depth (list-tree)
"Returns the depth of the first element (as defined by a flattened sequence) and the length of the sequence containing that element. (list max-depth deepest-length).
==> (get-depth '(((4 5) (3 4))))
==> (3 2)"
(cond ((null list-tree)
nil)
((numberp list-tree)
0)
((arrayp list-tree)
(array-rank list-tree))
(t
(+ 1 (get-depth (elt list-tree 0))))))
(defun clean-data-error (stddev clean-data &optional (first t))
"Copies the structure of the y-data and inserts provided sttdev value(s) into their place if they fit. If the stddev structure does not match the y-data structure, then just replace all numbers found in y with the first from stddev.
==> (clean-data-error '((0.1) (0.4)) '(((2 3) ((4) (5))) (() (3 4 5 6))))
==> (((0.1) (0.4)) (0.1 0.1 0.1 0.1))"
(labels ((first-element (list-tree)
(cond ((null list-tree)
nil)
((numberp list-tree)
list-tree)
(t
(first-element (car list-tree)))))
(eq-structure (list-tree1 list-tree2)
(cond ((and (numberp list-tree1) (numberp list-tree2))
t)
((or (numberp list-tree1) (numberp list-tree2))
nil)
((/= (length list-tree1) (length list-tree2))
nil)
(t
(every #'identity (mapcar #'eq-structure list-tree1 list-tree2))))))
(let ((clean-data-ys (if first (mapcar #'second clean-data) clean-data))
(default-stddev (first-element stddev)))
(cond ((null clean-data-ys)
nil)
((numberp clean-data-ys)
default-stddev)
((eq-structure stddev clean-data-ys)
stddev)
((arrayp clean-data-ys)
(make-array (array-dimensions clean-data-ys) :element-type 'double-float :initial-element default-stddev))
(t
(mapcar (lambda (data) (clean-data-error stddev data nil)) clean-data-ys))))))
(defun clean-data (data number-of-functions)
"Forces data to be lists only and of proper depth - unless they are arrays."
(labels ((list-everything (list-tree)
(cond ((null list-tree)
nil)
((numberp list-tree)
list-tree)
((arrayp list-tree)
list-tree)
((or (listp list-tree) (vectorp list-tree))
(map 'list #'list-everything list-tree)))))
(cond ((= (get-depth data) 1)
(error "clean-data: data is of insufficient depth or improperly structured."))
((= (get-depth data) 2)
(clean-data (list data) number-of-functions))
((= (length data) number-of-functions)
(list-everything data))
(t
(error "clean-data: insufficient number of datasets, ~a, for the given number of functions, ~a." (length data) number-of-functions)))))
(defun create-walker-data (data &rest columns)
"Takes a larger dataset (contains x, y, stddev, freq, temp, etc.) and extracts just the columns you want into a walker-friendly format."
(mapcar (lambda (x) (apply #'vector x))
(mapcar (lambda (y) (elt data y)) columns)))
(export 'create-walker-data)
(defun to-double-floats (l)
"Converts all numbers and vectors in tree to double-float type"
(map-tree (lambda (x) (etypecase x (number (coerce x 'double-float)) (symbol x) ((array double-float) x))) l))
(defun log-prior-fixer (log-prior params data)
"Checks if your prior returns a function (i.e. changes shape based on the data provided to it). If so, gets that function. If not, returns the prior you gave it."
(let ((results (mapcar (lambda (lp d) (funcall lp params d)) log-prior data)))
(mapcar (lambda (res fn) (if (numberp res) fn res)) results log-prior)))
(defun log-liklihood-fixer (log-liklihood fn params data error)
"Checks if your liklihood returns a function (i.e. changes shape based on the data provided to it). If so, gets that function. If not, returns the liklihood you gave it."
(let ((results (mapcar (lambda (ll f d e) (funcall ll f params d e)) log-liklihood fn data error)))
(mapcar (lambda (res fn) (if (numberp res) fn res)) results log-liklihood)))
(defun walker-many-steps (the-walker n &optional l-matrix)
"Takes 'n' steps with a constant l-matrix. No temperature or any other intelligent features."
(if (null l-matrix) (setq l-matrix (diagonal-covariance (get-plist-values (scale-plist 1e-2 (walker-get the-walker :get :median-params))))))
(dotimes (i n)
(walker-take-step the-walker :l-matrix l-matrix)))
;; TODO remove and add functionality for troubleshooting
;; (print (car (diagonal-covariance (get-plist-values (scale-plist 1e-2 (walker-get-median-params woi 1000))))))
;; (print (standard-deviation (diff (remove-consecutive-duplicates (walker-get-param woi :w1-0-0)))))
;; (plt:plot (diff (remove-consecutive-duplicates (walker-get-param woi :w1-0-0))))
(defvar mfit-walker-estop nil)
(export 'mfit-walker-estop)
(defun walker-adaptive-steps-full (walker &key (n 100000) (temperature 1d3) (auto (or :prob-settle :slope-settle nil)) (sampling-optimization (or :covariance :best-value)) max-walker-length l-matrix)
"Advances 'walker' through as many as 'n' steps. Intelligently adjusts the l-matrix (sampling rotation matrix for more efficient random sampling) to try to avoid too low and too high acceptance. Has an oscillating temperature between 1 and 'temperature' during the beginning of the journey. Can automatically terminate a journey if the probability has stabilized, indicating at least a point of local stability. 'max-walker-length' will prevent the walker from becomming too large if maxing out memory is an issue."
(declare (optimize debug))
(setf mfit-walker-estop nil)
(let* ((n (floor n))
(reset-index 10000)
(max-walker-length (when max-walker-length (floor max-walker-length 2)))
(num-params (etypecase (cadr (walker-step-params (walker-most-likely-step walker)))
(number (length (walker-param-keys walker)))
((or list vector) (length (cadr (walker-step-params (walker-most-likely-step walker)))))
(array (array-dimension (cadr (walker-step-params (walker-most-likely-step walker))) 0))))
(steps-to-settle (* 10 (max 50 num-params)))
(shutting-down-p nil)
(temp-steps (max n (* 10 steps-to-settle)))
(temperature (rational temperature))
;; Temperature starts high and cycles every 5000 steps (the divisor to floor function)
(temps (mapcar (lambda (x) (max 1 (* (cos (* x pi (+ 1 (* 2 (floor temp-steps 5000))) (/ (* 2 temp-steps)))) temperature))) (range temp-steps)))
(current-acceptance 0))
(flet ((stable-probs-p (probs)
(let* ((num-probs (length probs))
(early-max (reduce #'max (subseq probs 0 200)))
(late-max (reduce #'max (subseq probs (- num-probs 200)))))
(and (< (abs (- early-max late-max)) 0.5) ;; stable max values
(< 4 (- early-max (reduce #'min probs)) 9)))) ;; good variation
(stable-prob-slope-p (probs)
(< (getf (walker-step-params (walker-most-likely-step (mcmc-fit :function (lambda (x &key m b &allow-other-keys) (+ b (* b m x (/ (length probs))))) :data (list (list (thin (range (length probs)) 10) (thin probs 10))) :data-error 1d0 :params (list :m 10 :b -100)))) :m) 1)) ;; Is the log-liklihood slope less than 1%
(get-optimal-mcmc-l-matrix (take)
(if (eq sampling-optimization :covariance)
(scale-array (/ (expt 2.38d0 2) num-params)
(handler-case (walker-get walker :get :l-matrix :take take)
(floating-point-overflow () (print "FPO in Cholesky") l-matrix)
(division-by-zero () (print "DB0 is Cholesky") l-matrix)
(type-error () (print "TE in Cholesky") l-matrix)))
(scale-array 1d-5 (diagonal-covariance (get-plist-values (walker-step-params (walker-most-likely-step walker))))))))
(unless l-matrix
(if (or (< (walker-length walker) steps-to-settle)
(< (walker-get walker :get :acceptance :take 100) 0.1))
(setq l-matrix (diagonal-covariance (get-plist-values (walker-step-params (walker-most-likely-step walker)))))
(progn (setq l-matrix (diagonal-covariance (get-plist-values (walker-step-params (walker-most-likely-step walker)))))
(setq l-matrix (get-optimal-mcmc-l-matrix steps-to-settle)))))
(do ((i 1 (+ i 1))
(temp-index 0))
((or (>= i n) mfit-walker-estop))
(when (or
(and (not shutting-down-p) (< (- n i) (max 2000 steps-to-settle)))
(and auto
(not shutting-down-p)
(= 0 (mod i 1000))
(> i (* 2 steps-to-settle))
(< 0.2 (walker-get walker :get :acceptance :take 1000) 0.5)
(or
(and (eq auto :prob-settle) (stable-probs-p (walker-get walker :get :log-liklihoods :take steps-to-settle)))
(and (eq auto :slope-settle) (stable-prob-slope-p (walker-get walker :get :log-liklihoods :take (min (walker-length walker) (max 2500 steps-to-settle))))))))
(setf temperature 1)
(setf shutting-down-p t)
(setf i (- n (max 2000 steps-to-settle))))
(walker-take-step walker :l-matrix l-matrix :temperature temperature)
;; Annealing
(when (and (not shutting-down-p) (< i temp-steps))
(setf temperature (elt temps i)))
;; Cleaning the walker
(when (and max-walker-length (= i reset-index))
(if (> (walker-length walker) max-walker-length)
(progn (walker-modify walker :modify :keep-walks :keep-number max-walker-length)
(incf reset-index (1+ max-walker-length)))
(incf reset-index (1+ (- max-walker-length (walker-length walker))))))
;; Regular l-matrix updating
(when (and (> i 0)
(or (and (= 0 (mod i 200)) (< (walker-get walker :get :acceptance :take 200) 0.2))
(and (= 0 (mod i 200)) (> (walker-get walker :get :acceptance :take 200) 0.4))
(and (not shutting-down-p) (= 0 (mod i (* 2 steps-to-settle))))))
(setf current-acceptance (walker-get walker :get :acceptance :take 200))
(if (< 0.2 current-acceptance 0.4)
(setf l-matrix (let ((tmp-l-matrix (get-optimal-mcmc-l-matrix steps-to-settle)))
(if (= num-params (array-dimension tmp-l-matrix 0))
tmp-l-matrix
l-matrix)))
(if (< current-acceptance 0.2)
(setf l-matrix (scale-array 0.1d0 l-matrix))
(if (> current-acceptance 0.4)
(setf l-matrix (scale-array 1.9d0 l-matrix))))))))))
;; (let ((temp-steps 100)) (mapcar (lambda (i) (and (= 0 (mod (1+ (floor i temp-steps)) 2)) (< i (* temp-steps 95)))) (range 500)))
(defun walker-adaptive-steps (walker &optional (n 30000))
(walker-adaptive-steps-full walker :n n :temperature 10 :auto :prob-settle))
(defun walker-sample-region (walker &optional (initial-scale 1d-3))
"Advances 'walker' through as many as 'n' steps. Intelligently adjusts the l-matrix (sampling rotation matrix for more efficient random sampling) to try to avoid too low and too high acceptance. Has an oscillating temperature between 1 and 'temperature' during the beginning of the journey. Can automatically terminate a journey if the probability has stabilized, indicating at least a point of local stability. 'max-walker-length' will prevent the walker from becomming too large if maxing out memory is an issue."
(declare (optimize debug))
(setf mfit-walker-estop nil)
(let* ((num-params (etypecase (cadr (walker-step-params (walker-most-likely-step walker)))
(number (length (walker-param-keys walker)))
((or list vector) (length (cadr (walker-step-params (walker-most-likely-step walker)))))
(array (array-dimension (cadr (walker-step-params (walker-most-likely-step walker))) 0))))
(steps-to-settle 3000)
;; Temperature starts high and cycles every 5000 steps (the divisor to floor function)
(l-matrix (scale-array initial-scale (diagonal-covariance (get-plist-values (walker-step-params (walker-most-likely-step walker)))))))
(do ((i 1 (+ i 1))
(temp-index 0))
((or (>= i steps-to-settle) mfit-walker-estop))
;; catch complex stddev and retry with different opimal l matrix sampling
(walker-pretend-take-step walker :l-matrix l-matrix)
(when (and (> i 0) (= 0 (mod i 20)))
(if (= (walker-get walker :get :acceptance :take 50) 1/50)
(setf l-matrix (scale-array 0.25d0 l-matrix))
(if (> (walker-get walker :get :acceptance :take 50) 4/50)
(setf l-matrix (scale-array 1.7d0 l-matrix))))))))
;; (defun walker-construct-print-list (walker &optional take)
;; `(:fn ,(mapcar #'sb-kernel:%fun-name (walker-function walker))
;; :data ,(walker-data walker)
;; :param-keys ,(walker-param-keys walker)
;; :stddev ,(walker-data-error walker)
;; :log-liklihood ,(mapcar #'sb-kernel:%fun-name (walker-log-liklihood walker))
;; :log-prior ,(mapcar #'sb-kernel:%fun-name (walker-log-prior walker))
;; :walker ,(walker-walks walker take)))
;; (defun walker-save (walker filename &optional take)
;; (with-open-file (out filename
;; :direction :output
;; :if-exists :supersede)
;; (with-standard-io-syntax
;; (null (write (walker-construct-print-list walker take) :stream out)))))
;; (defun walker-load (filename &key function log-liklihood log-prior quiet)
;; (with-open-file (in filename
;; :direction :input)
;; (with-standard-io-syntax
;; (let* ((full (read in))
;; (data (getf full :data))
;; (data-error (getf full :data-error))
;; (walks (getf full :walker))
;; (dummy-params (walker-step-params (elt walks 0))))
;; (unless quiet
;; (format t "*Recommendations*~%function: ~s~%log-liklihood: ~s~%log-prior: ~s~%" (getf full :fn) (getf full :log-liklihood) (getf full :log-prior)))
;; (when (and function log-liklihood log-prior)
;; (let ((walker (walker-create :function function :data data :params dummy-params :data-error data-error :log-liklihood log-liklihood :log-prior log-prior)))
;; (walker-modify walker :modify :add-walks :new-walks walks)
;; walker))))))
;;; Functionality for a set of similar walker instances
;; (defun walker-set-save (the-walker-set filename &optional take)
;; (let ((walker-print-list (mapcar (lambda (x) (walker-construct-print-list x take)) the-walker-set)))
;; (with-open-file (out filename
;; :direction :output
;; :if-exists :supersede)
;; (with-standard-io-syntax
;; (null (print walker-print-list out))))))
;; (defun walker-set-load (filename fn log-liklihood log-prior)
;; (with-open-file (in filename
;; :direction :input)
;; (with-standard-io-syntax
;; (let* ((full (read in)))
;; (mapcar (lambda (x)
;; (let* ((param-keys (getf x :param-keys))
;; (dummy-params (make-plist param-keys (make-list (length param-keys) :initial-element 0.0d0)))
;; (data (getf x :data))
;; (stddev (getf x :stddev))
;; (walks (getf x :walker))
;; (the-walker (walker-init :fn fn :data data :params dummy-params :stddev stddev :log-liklihood log-liklihood :log-prior log-prior :init nil)))
;; (walker-modify the-walker :modify :add-walks :new-walks walks)
;; the-walker))
;; full)))))
(defun walker-set-get (the-walker-set &key (get (or :steps :unique-steps :most-likely-step :acceptance :param :most-likely-params :median-params :all-params :stddev-params :log-liklihoods :covariance-matrix :l-matrix)) take param)
(mapcar (lambda (x) (walker-get x :get get :take take :param param)) the-walker-set))
(defun walker-set-delete (the-walker-set)
(mapcar (lambda (x) (walker-modify x :modify :delete)) the-walker-set))
(defun walker-set-plot-param (the-walker-set key &optional take)
(plt:plot (walker-set-get the-walker-set :get :median-params :param key :take take) "w l title \"Param\""))
;; median vs most likely
(defmacro walker-get-f (walker exp &key (take 1000))
(let ((median-params (walker-get walker :get :most-likely-params :take take)))
(labels ((replace-param-names (item)
(cond ((null item) nil)
((atom item) (if (char= #\: (char (prin1-to-string item) 0))
(getf median-params item)
item))
((consp item)
(cons (replace-param-names (car item))
(replace-param-names (cdr item)))))))
(let ((filled-exp (replace-param-names exp)))
filled-exp))))
(defun walker-with-exp (walker exp &key (take 1000))
(let ((median-params (walker-get walker :get :most-likely-params :take take)))
(labels ((replace-param-names (item)
(cond ((null item) nil)
((atom item) (if (char= #\: (char (prin1-to-string item) 0))
(getf median-params item)
item))
((consp item)
(cons (replace-param-names (car item))
(replace-param-names (cdr item)))))))
(let ((filled-exp (replace-param-names exp)))
(eval filled-exp)))))
(export 'walker-with-exp)
(defun walker-make-step (walker params)
(make-walker-step :prob (+ (reduce #'+ (map 'list (lambda (ll f d e) (funcall ll f params d e)) (walker-log-liklihood walker) (walker-function walker) (walker-data walker) (walker-data-error walker)))
(reduce #'+ (map 'list (lambda (lp d) (funcall lp params d)) (walker-log-prior walker) (walker-data walker))))
:params params))
(defun walker-take-step (walker &key l-matrix (temperature 1))
"The one that uses a full covariance matrix"
(if (null l-matrix) (setq l-matrix (diagonal-covariance (plist-values (scale-plist 1e-2 (walker-get walker :get :most-likely-params :take 1000))))))
(let* ((previous-step (walker-last-step walker))
(prob0 (walker-step-prob previous-step))
(previous-params (walker-step-params previous-step))
(new-values (get-covariant-sample (etypecase (cadr previous-params)
(number (make-array (list (length (plist-keys previous-params)) 1) :element-type 'double-float :initial-contents (mapcar #'list (plist-values previous-params))))
(list (make-array (list (length (cadr previous-params)) 1) :element-type 'double-float :initial-contents (mapcar #'list (cadr previous-params))))
(vector (make-array (list (length (cadr previous-params)) 1) :element-type 'double-float :initial-contents (map 'list #'list (cadr previous-params))))
(array (cadr previous-params)))
l-matrix))
(next-params (etypecase (cadr previous-params)
(number (array-to-plist (plist-keys previous-params) new-values))
(list (list (car previous-params) (mapcar (lambda (x) (aref new-values x 0)) (range (array-dimension new-values 0)))))
(vector (list (car previous-params) (map 'vector (lambda (x) (aref new-values x 0)) (range (array-dimension new-values 0)))))
(array (list (car previous-params) new-values))))
(next-step (walker-make-step walker next-params))
(prob1 (walker-step-prob next-step))
(accepted-step (if (or (> prob1 prob0)
(> (/ (- prob1 prob0) temperature) (log (random 1.0d0))))
next-step
previous-step)))
(walker-modify walker :modify :add-step :new-step accepted-step)))
(defun walker-pretend-take-step (walker &key l-matrix)
"Normal step taking routine, but always puts the previous step at the last step, so the walker doesn't actually move. Used for sampling the current location without moving the walker for proper l-matrix construction."
(let ((previous-step (walker-last-step walker)))
(if (null l-matrix) (setq l-matrix (diagonal-covariance (plist-values (scale-plist 1e-2 (walker-get walker :get :most-likely-params :take 1000))))))
(let* ((previous-step (walker-last-step walker))
(prob0 (walker-step-prob previous-step))
(previous-params (walker-step-params previous-step))
(new-values (get-covariant-sample (etypecase (cadr previous-params)
(number (make-array (list (length (plist-keys previous-params)) 1) :element-type 'double-float :initial-contents (mapcar #'list (plist-values previous-params))))
(list (make-array (list (length (cadr previous-params)) 1) :element-type 'double-float :initial-contents (mapcar #'list (cadr previous-params))))
(vector (make-array (list (length (cadr previous-params)) 1) :element-type 'double-float :initial-contents (map 'list #'list (cadr previous-params))))
(array (cadr previous-params)))
l-matrix))
(next-params (etypecase (cadr previous-params)
(number (array-to-plist (plist-keys previous-params) new-values))
(list (list (car previous-params) (mapcar (lambda (x) (aref new-values x 0)) (range (array-dimension new-values 0)))))
(vector (list (car previous-params) (map 'vector (lambda (x) (aref new-values x 0)) (range (array-dimension new-values 0)))))
(array (list (car previous-params) new-values))))
(next-step (walker-make-step walker next-params))
(prob1 (walker-step-prob next-step))
(accepted-step (if (> prob1 prob0)
next-step
previous-step)))
(walker-modify walker :modify :add-step :new-step accepted-step))
;;(walker-modify walker :modify :add-step :new-step previous-step)
))
(defun walker-force-take-step (walker)
"Forces a new step onto the walker regardless of probability. Does not take a random sample, just uses the current param value. Useful for when swapping datasets within a walker."
(let* ((previous-step (walker-last-step walker))
(previous-params (walker-step-params previous-step))
(next-step (walker-make-step walker previous-params)))
(walker-modify walker :modify :add-step :new-step next-step)))
;; TODO prior bounds implementation - it's a good idea
(defun walker-create (&key function data params data-error log-liklihood log-prior param-bounds)
"Make a walker with the prescribed characteristics. Can run over multiple sets of functions and data by simply making lists of kwargs. i.e. :function #'my-function vs :function (list #'my-function #'other-function). data, params, etc. must also then be lists that correspond to the order found in the :function kwarg.
:function expects functions formatted with kwargs as parameters:
(lambda (x &key m b &allow-other-keys) (+ b (* -3 m) (* (- m (/ b 60)) x)))
or like this for multiple or linked independent variables
(lambda (x &key m b &allow-other-keys) (+ b (* -3 m (elt x 0)) (* (- m (/ b 60)) (elt x 1))))
:data expects formatting as (list x-data y-data)
:data-error can be a single number (for uniform error) or a list of the same size as the y-data
:params expects a plist like '(:b -1 :m 2)"
(declare (ignorable param-bounds))
(let* ((function (force-list function))
(data (to-double-floats (clean-data data (length function))))
(data-error (to-double-floats (clean-data-error (if data-error data-error 1) data)))
(params (to-double-floats params))
(log-liklihood (log-liklihood-fixer (if (consp log-liklihood) log-liklihood (make-list (length (force-list function)) :initial-element (if log-liklihood log-liklihood #'log-liklihood-normal))) function params data data-error))
(log-prior (log-prior-fixer (if (consp log-prior) log-prior (make-list (length (force-list function)) :initial-element (if log-prior log-prior #'log-prior-flat))) params data))
(first-step (make-walker-step :prob (+ (reduce #'+ (map 'list (lambda (ll f d e) (funcall ll f params d e)) log-liklihood function data data-error))
(reduce #'+ (map 'list (lambda (lp d) (funcall lp params d)) log-prior data)))
:params params))
(walker (make-walker :function function
:param-keys (plist-keys params)
:param-style (typecase (elt params 1)
((or list vector array) :single-item)
(otherwise :mutliple-kwargs))
:last-step first-step
:most-likely-step first-step
:walk (list first-step)
:data data
:data-error data-error
:log-liklihood log-liklihood
:log-prior log-prior)))
walker))
(defun mcmc-fit (&key function data params data-error log-liklihood log-prior param-bounds)
(declare (ignorable param-bounds))
(let* ((walker (walker-create :function function
:data data
:params params
:data-error data-error
:log-liklihood log-liklihood
:log-prior log-prior
:param-bounds param-bounds)))
(walker-adaptive-steps walker)
walker))
(export 'mcmc-fit)
(defvar example-function (lambda (x &key m b &allow-other-keys) (+ b (* -3 m) (* (- m (/ b 60)) x))))
(defvar example-data '((-4 -1 2 5 10) (0 2 5 9 13)))
(defvar example-params '(:b -1 :m 2))
(defvar example-error 0.2)
(defvar example-log-liklihood #'log-liklihood-normal)
(defvar example-log-prior #'log-prior-flat)
;; Basic line fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key m b &allow-other-keys) (+ b (* m x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:b -1 :m 2) :data-error 0.2))
;; Single param list fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (elt params 0) (* (elt params 1) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:params (-1 2)) :data-error 0.2))
;; Single param vector fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (elt params 0) (* (elt params 1) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params '(:params #(-1 2)) :data-error 0.2))
;; Single param array fit
;; (defparameter woi (mfit:mcmc-fit :function (lambda (x &key params &allow-other-keys) (+ (aref params 0 0) (* (aref params 1 0) x))) :data '((-4 -1 2 5 10) (0 2 5 9 13)) :params (list :params (make-array '(2 1) :element-type 'double-float :initial-contents '((-1d0) (2d0)))) :data-error 0.2))
;; Global parameter fit (polynomial and line)
;; (defparameter woi (mfit:mcmc-fit :function (list (lambda (x &key b m c d &allow-other-keys) (+ b (* m x) (* c x x) (* d x x x))) (lambda (x &key e m g &allow-other-keys) (+ e (* (+ m g) x)))) :data '(((0 1 2 3 4) (4 5 6 8 4)) ((10 20 30 40 50) (1 2 3 4 5))) :params '(:b -1 :m 2 :c 1 :d -1 :e 0.5 :g -2) :data-error 0.2))
(defun walker-diagnose-params (walker &key (style (or :step-insert :plot-flow)) params)
(case style
(:step-insert (push (walker-make-step walker params) (walker-walk walker)))
(:plot-flow (print "Implement some (10) steps of the walk in plot space to see evolution"))))
(export 'walker-diagnose-params)
;;; Walker and fit visualization
(defun walker-get-data-and-fit-no-stddev (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0) (which-solution (or :most-likely :median)) x-shift y-shift)
"Extract plottable data as well as fit and stddev data from a walker."
(let* ((take (if (or (null take) (> take (walker-length walker)))
(walker-length walker)
take))
(fn (elt (walker-function walker) fn-number))
(data (elt (walker-data walker) fn-number))
(x-data (elt data x-column))
(x-data-shift (if (null x-shift) x-data (map 'vector (lambda (x) (+ x-shift x)) x-data)))
(y-data (elt data y-column))
(y-data-shift (if (null y-shift) y-data (map 'vector (lambda (y) (+ y-shift y)) y-data)))
(x-fit (linspace (reduce #'min x-data) (reduce #'max x-data) :len 1000))
(x-fit-shift (if (null x-shift) x-fit (map 'vector (lambda (x) (+ x-shift x)) x-fit)))
(params (case which-solution
(:most-likely (walker-step-params (walker-get walker :get :most-likely-step :take take)))
(:median (walker-get walker :get :median-params :take take))
(otherwise (walker-get walker :get :median-params :take take))))
(y-fit (mapcar (lambda (x) (apply fn x params)) x-fit))
(y-fit-shift (if (null y-shift) y-fit (map 'vector (lambda (y) (+ y-shift y)) y-fit))))
(list x-fit-shift y-fit-shift x-data-shift y-data-shift params)))
(export 'walker-get-data-and-fit-no-stddev)
(defun walker-get-data-and-fit (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0) (which-solution (or :most-likely :median)) x-shift y-shift)
"Extract plottable data as well as fit and stddev data from a walker."
(let* ((take (if (or (null take) (> take (walker-length walker)))
(walker-length walker)
take))
(fn (elt (walker-function walker) fn-number))
(data (elt (walker-data walker) fn-number))
(x-data (elt data x-column))
(x-data-shift (if (null x-shift) x-data (map 'vector (lambda (x) (+ x-shift x)) x-data)))
(y-data (elt data y-column))
(y-data-shift (if (null y-shift) y-data (map 'vector (lambda (y) (+ y-shift y)) y-data)))
(x-fit (linspace (reduce #'min x-data) (reduce #'max x-data) :len 1000))
(x-fit-shift (if (null x-shift) x-fit (map 'vector (lambda (x) (+ x-shift x)) x-fit)))
(params (case which-solution
(:most-likely (walker-step-params (walker-get walker :get :most-likely-step :take take)))
(:median (walker-get walker :get :median-params :take take))
(otherwise (walker-get walker :get :median-params :take take))))
(y-fit (mapcar (lambda (x) (apply fn x params)) x-fit))
(y-fit-shift (if (null y-shift) y-fit (map 'vector (lambda (y) (+ y-shift y)) y-fit)))
(previous-walks (walker-get walker :get :steps))
(sorted-walks (subseq (sort previous-walks #'> :key #'walker-step-prob) 0 (ceiling (* 0.66 take))))
(all-ys (mapcar (lambda (x) (mapcar (lambda (walk) (apply fn x (walker-step-params walk))) sorted-walks)) x-fit))
(max-ys (mapcar (lambda (y) (+ (if y-shift y-shift 0) (reduce #'max y))) all-ys))
(min-ys (mapcar (lambda (y) (+ (if y-shift y-shift 0) (reduce #'min y))) all-ys)))
(list x-fit-shift max-ys min-ys y-fit-shift x-data-shift y-data-shift params)))
(export 'walker-get-data-and-fit)
(defun walker-plot-data-and-fit (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0) (image-size '(1920 1080)) (which-solution (or :most-likely :median)) x-shift y-shift)
(destructuring-bind (x-fit max-ys min-ys y-fit x-data y-data params) (walker-get-data-and-fit walker :take take :x-column x-column :y-column y-column :fn-number fn-number :which-solution which-solution :x-shift x-shift :y-shift y-shift)
(plt:reset)
(plt:plot :terminal (apply #'format nil "qt size ~d,~d linewidth 3 font \"Arial,18\"" image-size)
:format "x \"%.4g\""
:format "y \"%.4g\""
:xlabel "\"x-data\""
:ylabel "\"y-data\""
x-fit max-ys "w l lc rgb \"green\" title \"fit stddev upper limit\""
x-fit min-ys "w l lc rgb \"green\" title \"fit stddev lower limit\""
x-fit y-fit "w l lc rgb \"red\" title \"fit\""
x-data y-data "w p pt 6 ps 2 lc rgb \"black\" title \"data\"")
params))
(defun walker-plot-residuals (walker &key (take 1000) (x-column 0) (y-column 1) (fn-number 0))
(let* ((take (if (or (null take) (> take (walker-length walker)))
(walker-length walker)
take))
(fn (elt (walker-function walker) fn-number))
(data (elt (walker-data walker) fn-number))
(stddev (elt (walker-data-error walker) fn-number))
(x-data (elt data x-column))
(y-data (elt data y-column))
(stddev (if (= 1 (length stddev)) (make-array (length x-data) :initial-element (elt stddev 0)) stddev))
(params (walker-get walker :get :median-params :take take))
(y-fit (map 'vector (lambda (x) (apply fn x params)) x-data))
(y-residuals (map 'vector (lambda (yf y) (- yf y)) y-fit y-data)))
(plt:reset)
(plt:plot :terminal "qt size 1920,1080 linewidth 3 font \"Arial,18\""
:format "x \"%.4g\""
:format "y \"%.4g\""
:xlabel "\"x-data\""
:ylabel "\"y-data\""
x-data y-residuals "w p pt 6 ps 2 lc rgb \"black\" title \"residuals\""
x-data stddev "w p pt 2 ps 1 lc rgb \"red\" title \"point error\""
x-data (make-array (length x-data) :initial-element 0) "w l lc rgb \"red\" title \"baseline\"")))
(defun walker-catepillar-plots (walker &optional take (x-scale 1) (y-scale 1))
(let* ((param-keys (walker-param-keys walker))
(n (length param-keys)))
(plt:reset)
(plt:send-plot-options :terminal (format nil "pngcairo size ~d,~d linewidth 1 font \"Arial,18\"" (* x-scale 1920) (* y-scale 1080))
:output "\"temp.png\""
:format "y \"%.1e\""
:format "x \"%.1e\"")
(apply #'plt:multiplot
(format nil "layout ~d,1" n)
(apply #'append
(mapcar-enum (key i param-keys)
(list (append (list (walker-get walker :get :param :param key :take take) (format nil "w l title \"~a\"" key))
(if (= i (1- n))
(list :xlabel "\"Step\"" :ylabel (format nil "\"~a\"" key))
(list :xlabel "" :ylabel (format nil "\"~a\"" key))))))))))
(export 'walker-catepillar-plots)
(export 'show)
(defun walker-liklihood-plot (walker &optional take)
(let ((probs (walker-get walker :get :log-liklihoods :take take)))
(plt:reset)
(plt:plot :terminal "qt size 1920,1080 linewidth 4 font \"Arial,40\""
:xtics ""
:xlabel "\"Step\""
:ylabel "\"Log Liklihood\""
probs "w l title \"Liklihood\"")))
(defun walker-plot-one-corner (walker keys &optional take)
(let* ((x-key (first keys))
(y-key (second keys))
(x (walker-get walker :get :param :param x-key :take take))
(y (walker-get walker :get :param :param y-key :take take)))
(plt:reset)
(plt:plot :terminal "qt size 1920,1080 linewidth 1 font \"Arial,18\""
:xlabel (format nil "\"~a\"" x-key)
:ylabel (format nil "\"~a\"" y-key)
x y "w p pt 3 ps 4 title \"My plot\"")))
(defun walker-plot-corner (walker &key take (size '(3240 3240)))
(labels ((permute-params (params)
(let ((return-list nil))
(do ((i 0 (1+ i)))
((>= i (1- (length params))) (reverse return-list))
(do ((j (1+ i) (1+ j)))
((>= j (length params)) nil)
(push (list (elt params i) (elt params j)) return-list)))))
(make-origin-list (params)
(let ((return-list nil)
(len (length params)))
(do ((i 0 (1+ i)))
((>= i (1- (length params))) (reverse return-list))
(do ((j (1+ i) (1+ j)))
((>= j (length params)) nil)
(push (list (* i (/ 1.0 (1- len))) (* (1- j) (/ 1.0 (1- len)))) return-list))))))
(let* ((param-keys (walker-param-keys walker))
(all-params (apply #'append (partition (make-plist param-keys (mapcar (lambda (x) (walker-get walker :get :param :param x :take take)) param-keys)) 2)))
(key-pairs (permute-params param-keys))
(plot-data (mapcar (lambda (x) (destructuring-bind (key1 key2) x (list (getf all-params key1) (getf all-params key2)))) key-pairs))
(origin-list (make-origin-list param-keys)))
(plt:send-plot-options :terminal (format nil "pngcairo size ~d,~d linewidth 1 font \"Arial,12\"" (elt size 0) (elt size 1)) :output "\"temp.png\"")
(apply #'plt:multiplot ""
(apply #'nconc (mapcar-enum (element index plot-data)
(list (list (elt element 0) (elt element 1) "w p"
:origin (apply #'format nil "~,1f,~,1f" (elt origin-list index)) :size (format nil "~1,f,~1,f" (/ 1.0 (1- (length param-keys))) (/ 1.0 (1- (length param-keys)))) :xlabel (format nil "\"~a\"" (elt (elt key-pairs index) 0)) :ylabel (format nil "\"~a\"" (elt (elt key-pairs index) 1)))))))
(plt:send-plot-options :output "unset"))))
(defun walker-param-histo (walker key &key (take 10000) (bins 20))
(let* ((param-values (sort (walker-get walker :get :param :param key :take take) #'<))
(histo-x (make-histo-x param-values bins))
(histo (make-histo param-values bins)))
(plt:reset)
(plt:plot :terminal "qt size 1920,1080 linewidth 3 font \"Arial,18\""
:xlabel (format nil "\"~a\"" key)
:ylabel "\"Counts\""
histo-x histo (format nil "w lp ps 3 title \"Histogram: ~a\"" key))))
(defun show ()
"Shows the plots generated from 2d histogram and catepillar functions"
(uiop:run-program "feh ./temp.png -3 5"))
;;; File Management
;; File searching
(defun walk-dirs (dir)
(if (uiop:directory-exists-p dir) ;; is it a dir
(let ((items (nconc (uiop:subdirectories dir) (uiop:directory-files dir))))
(mapcar (lambda (d) (walk-dirs d)) items))
dir))
(defun get-filename (dir &key include exclude)
"Returns all files under dir (and its subdirs) whose name (including directory name) matches ALL specified patterns"
(let* ((include (when include (if (not (listp include)) (list include) include)))
(exclude (when exclude (if (not (listp exclude)) (list exclude) exclude)))
(all-files (flatten (walk-dirs dir)))
(files (remove-if-not (lambda (y)
(and (every (lambda (g) (search g (namestring y))) include)
(notany (lambda (g) (search g (namestring y))) exclude)))
all-files)))
(if (= (length files) 1)
(car files)
files)))
;; File gathering, reading, and quick plotting
(defun read-file-lines (filename)
"Read 'filename' line by line and return a list of strings"
(with-open-file (s filename)
(let ((data nil))
(do ((line (read-line s nil nil) (read-line s nil nil)))
((not line) (reverse data))
(push line data)))))
(export 'read-file-lines)
(defun separate-header-and-data (file-data number-of-header-lines)
(list (subseq file-data 0 number-of-header-lines)
(subseq file-data number-of-header-lines)))
(export 'separate-header-and-data)
(defun auto-split-and-read-csv (unsplit-data-lines)
(let* ((delim-counts (mapcar (lambda (x) (list x (count x (elt unsplit-data-lines 0)))) '(#\tab #\, #\; #\:)))
(most-likely-delim (elt (reduce (lambda (x y) (if (> (elt x 1) (elt y 1)) x y)) delim-counts) 0)))
(remove-if
(lambda (x) (every #'null x))
(map-tree
(lambda (x) (read-from-string x nil nil))
(transpose
(mapcar
(lambda (x) (split-string most-likely-delim x))
unsplit-data-lines))))))
(export 'auto-split-and-read-csv)
(defun file->file-specs (filename &key (delim #\tab))
"Returns various metrics about the file. Lines, header lines, data lines, data rows, data sets."
(with-open-file (in filename :direction :input)
(labels ((get-lines (&optional (num-lines 0) (found-data nil) (data-length nil) (data-rows nil))
(let ((line (string-right-trim '(#\return) (read-line in nil nil)))) ; allow for Windows files
(cond ((string= line "NIL") ; end of file - return info ; ordered by freque
(list :file-lines num-lines :header-lines found-data :data-length data-length :data-rows (if data-rows data-rows (- num-lines found-data)) :num-pages (if data-rows (floor (- num-lines found-data) data-rows) 1)))
((and (string= line "") found-data (not data-rows)) ; set data rows
(get-lines num-lines found-data data-length (- num-lines found-data)))
((string= line "") ; ignore line
(get-lines num-lines found-data data-length data-rows))
((and (numberp (read-from-string (elt (split-string #\tab line) 0))) (not found-data)) ; first line w nums?
(get-lines (+ num-lines 1) num-lines (length (split-string delim line)) data-rows))
(t ; regular line - just increase lines
(get-lines (+ num-lines 1) found-data data-length data-rows))))))
(get-lines))))
(defun make-data-into-pages (data file-specs)
(let ((ret-tree (make-list (getf file-specs :num-pages))))
(mapcar (lambda (x a b)
(setf x (mapcar (lambda (y)
(subseq y a b))
data)))
ret-tree
(butlast (linspace 0 (* (getf file-specs :num-pages) (getf file-specs :data-rows)) :len (1+ (getf file-specs :num-pages)) :type 'integer))
(rest (linspace 0 (* (getf file-specs :num-pages) (getf file-specs :data-rows)) :len (1+ (getf file-specs :num-pages)) :type 'integer)))))
(defun read-file->data (filename &key (file-specs nil) (delim #\tab) (transpose t) pages)
"Reads a file into a list assuming 'delim' separates data. Use 'pages' kwargs to make 3d list assuming each page of data is separated by an extra newline in the file."
(unless file-specs
(setq file-specs (file->file-specs filename :delim delim)))
(let* ((header-lines (getf file-specs :header-lines))
(file-contents nil)
(line nil))
(labels ((remove-header-lines (n stream)
(repeat n (read-line stream nil nil)))
(read-file (stream)
(when (setq line (read-line stream nil nil))
(setq line (string-right-trim '(#\return) line))
(let ((vals (mapcar #'read-from-string (split-string delim line))))
(when vals
(push vals file-contents)))
(read-file stream))))
(with-open-file (in filename :direction :input)
(remove-header-lines header-lines in)
(read-file in)
(let ((file-contents
(if transpose
(transpose-matrix (reverse file-contents))
(reverse file-contents))))
(if pages
(make-data-into-pages file-contents file-specs)
file-contents))))))
(defun read-file->plot (filename &optional (x-column 0) (y-column 1))
(let ((data (read-file->data filename)))
(plt:plot (elt data x-column) (elt data y-column))))
(export 'read-file->plot)
(defun read-files->plot (filenames &optional (x-column 0) (y-column 1))
(let ((data (mapcar #'read-file->data filenames)))
(apply #'plt:plot (apply #'append (mapcar (lambda (e) (list (elt e x-column) (elt e y-column))) data)))))
(export 'read-files->plot)
;;; Statistics Functions
(defun multivariate-gaussian-random (covs)
(mapcar (lambda (x) (* x (alexandria:gaussian-random))) covs))
(defun nth-percentile (n sequence &optional (sorted nil))
(let* ((copy sequence)
(len (length sequence))
(n (* n (- len 1) 1/100)))
(multiple-value-bind (pos rem) (floor n)
(unless sorted
(setq copy (sort (copy-seq sequence) #'<)))
(if (= rem 0)
(elt copy pos)
(let ((e1 (elt copy pos))
(e2 (elt copy (+ pos 1))))
(/ (+ e1 e2) 2))))))
(defun 95cr (sequence)
(list (nth-percentile 2.5 sequence) (nth-percentile 97.5 sequence)))
(defun iqr (sequence &optional (sorted nil))
(unless sorted (setq sorted (sort (copy-seq sequence) #'<)))
(- (nth-percentile 75 sequence t) (nth-percentile 25 sequence t)))
(defun median (sequence &optional sorted)
(nth-percentile 50 sequence sorted))
(defun mean (sequence)
(/ (reduce #'+ sequence) (length sequence)))
(defun variance (sequence)
(let* ((mean (/ (reduce #'+ sequence) (length sequence)))
(sum-sq (reduce #'+ (map 'list (lambda (x) (expt (- x mean) 2)) sequence))))
(/ sum-sq (- (length sequence) 1))))
(defun standard-deviation (sequence)
(sqrt (variance sequence)))
(defun standard-deviation-normal (sequence &optional sorted)
(let* ((copy sequence))
(unless sorted
(setq copy (sort (copy-seq sequence) #'<)))
(let ((middle-value (median copy t))
(upper-variance (nth-percentile 84.1 copy t)))
(- upper-variance middle-value))))
(defun variance-normal (sequence &optional sorted)
(expt (standard-deviation-normal sequence sorted) 2))
;;; binning / histogram
(defun make-histo (sequence &optional num-bins)
(let* ((bottom (reduce #'min sequence))
(top (reduce #'max sequence))
(num-bins (if num-bins num-bins (floor (* (- top bottom) (expt (length sequence) 1/3)) (* 2 (iqr sequence)))))
(num-bins (+ 1 num-bins))
(boundaries (linspace bottom top :len num-bins)))
(labels ((count-for-bins (n sequence &optional return-list)
(if (< n num-bins)
(let ((pos (position (elt boundaries n) sequence :test-not #'>=)))
(unless pos
(setq pos (length sequence)))
(count-for-bins (+ n 1)
(subseq sequence pos)
(cons pos return-list)))
(reverse return-list))))
(count-for-bins 1 sequence))))
(defun make-histo-x (sequence &optional num-bins)
(let* ((bottom (reduce #'min sequence))
(top (reduce #'max sequence))
(num-bins (if num-bins num-bins (floor (* (- top bottom) (expt (length sequence) 1/3)) (* 2 (iqr sequence)))))
(gap-size (/ (- top bottom) num-bins)))
(linspace (+ bottom (/ gap-size 2)) top :len num-bins)))
(export '(log-normal prior-bounds-let standard-deviation walker-create log-liklihood-normal read-file->data walker-adaptive-steps walker-adaptive-steps-full walker-load log-prior-flat walker-liklihood-plot walker-plot-data-and-fit linspace walker-set-get get-filename))
| 79,099 | Common Lisp | .lisp | 1,400 | 52.220714 | 517 | 0.661937 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | a4b916d1a9f88163f218a625a43b2b42fbe1d9d8ea67542aa1ce7d40c8fb0435 | 23,314 | [
-1
] |
23,315 | nv-specific.lisp | afranson_Lisp-MCMC/nv-specific.lisp | ;;;; nv magnetometry specific walker fitting stuff
(in-package :mcmc-fitting)
(defun nv-data->separated (data)
(mapcar #'(lambda (x) (list (elt data 0) x)) (subseq data 1)))
(defun nv-dir->data (directory)
(let ((files (uiop:directory-files directory)))
(mapcan #'(lambda (x) (nv-data->separated (read-file->data x :delim #\;))) files)))
(defun log-liklihood-nv (fn params data error)
(declare (optimize speed)
(cons data)
(function fn))
(let ((x (elt data 0))
(y (elt data 1)))
(declare (simple-vector x y))
(reduce #'+ (map 'vector #'(lambda (x y) (log-normal (apply fn x params) error y)) x y))))
(defun log-prior-nv (params data)
(declare (sb-ext:muffle-conditions sb-ext:compiler-note)
(optimize speed)
(ignorable data))
(prior-bounds-let ((:scale1 1d-5 1d1)
(:scale2 1d-5 1d1)
(:mu1 2850 2870)
(:mu2 2870 2890)
(:sigma 9 20)
(:bg0 0 1d-5))
(+ bounds-total
(if (> mu1 mu2) -1e9 0e0)
(if (< (- mu2 mu1) 6) -1e9 0e0)
(if (not (< 0.9 (/ scale1 scale2) 1.1)) -1e9 0e0))))
(defun nv-data-std-dev (data)
(let* ((y-data (elt data 1))
(y-length/10 (floor (length y-data) 10))
(y-start-std-dev (standard-deviation (subseq y-data 0 y-length/10)))
(y-end-std-dev (standard-deviation (subseq y-data (- (length y-data) y-length/10)))))
(min y-start-std-dev y-end-std-dev)))
(defun guess-nv-params (data)
(let* ((y (elt data 1))
(y-max (reduce #'max y))
(y-min (reduce #'min y))
(scale (/ (- y-max y-min) 4.4d-5)))
(list :scale1 scale :scale2 scale :mu1 2863d0 :mu2 2873d0 :sigma 10d0 :bg0 (float y-min 0d0))))
(defun nv-walker (data)
(walker-init :fn #'double-lorentzian-bg
:data data
:params (guess-nv-params data)
:stddev (nv-data-std-dev data)
:log-liklihood #'log-liklihood-nv
:log-prior #'log-prior-nv))
(defun dir->nv-walkers (dir)
(let ((walkers (mapcar #'nv-walker (nv-dir->data dir))))
(mapc #'(lambda (x) (walker-adaptive-steps x)) walkers)
walkers))
(defun file->nv-walkers (filename)
(let ((walkers (mapcar #'nv-walker (nv-data->separated (read-file->data filename :delim #\;)))))
(mapc #'(lambda (x) (walker-adaptive-steps x)) walkers)
walkers))
(defun walker-field-offset (the-walker)
(walker-with-exp the-walker '(/ (- :mu2 :mu1) 2 2.8) :take 1000))
;;; TODO problem for another day
;; (defun walker-set-field-offset (the-walker-set background-splitting)
;; (walker-set-get-f the-walker-set (- (/ (- :mu2 :mu1) 2 2.8) background-splitting) 1000))
(defmacro walker-set-make-file-3d-plot-exp (the-walker-set exp row-length &optional file-out take)
(let ((walk-set (gensym))
(row-len (gensym))
(xs (gensym))
(ys (gensym))
(field-offsets (gensym))
(filename-out (gensym)))
`(let* ((,walk-set ,the-walker-set)
(,row-len ,row-length)
(,xs (mapcar #'(lambda (x) (mod x ,row-len)) (linspace 0 (- (length ,walk-set) 1))))
(,ys (mapcar #'(lambda (x) (floor x ,row-len)) (linspace 0 (- (length ,walk-set) 1))))
(,field-offsets (mapcar #' eval (walker-set-get-f ,walk-set ',exp ,take)))
(,filename-out ,file-out)
(,filename-out (if ,filename-out ,filename-out "./3d-temp-file.txt")))
(with-open-file (out ,filename-out :direction :output :if-exists :supersede)
(mapcar #'(lambda (x)
(format out "~f ~f ~f~%" (elt x 0) (elt x 1) (elt x 2))
(when (= (elt x 0) (- ,row-len 1))
(terpri out)))
(mapcar #'list ,xs ,ys ,field-offsets))))))
(defun nv-pretty-heatmap (&key (map nil) (cbar-range '(0 "*")) (z-range '(-5 "*")))
(plt:send-command :xlabel "\"X Pos\""
:ylabel "\"Y Pos\""
:zlabel "\"Field Offset (Oe)\" rotate parallel"
:cbrange (format nil "[~a:~a]" (elt cbar-range 0) (elt cbar-range 1))
:zrange (format nil "[~a:~a]" (elt z-range 0) (elt z-range 1))
:view (if map "map" "unset"))
(plt:replot))
| 3,914 | Common Lisp | .lisp | 89 | 39.41573 | 99 | 0.615385 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 81ac874832bff25985f67ae497992009f5c98985f1fbfebc21cc62137fa2ffcc | 23,315 | [
-1
] |
23,316 | test.lisp | afranson_Lisp-MCMC/test.lisp | ;;; test.lisp
;;
;; Test the mcmc-fitting package for a lorentzian lineshape
(require 'mcmc-fitting)
(in-package :mcmc-fitting)
;; Quickly gather a list of the files you want to process
(print (get-filename "." :include '("example" ".xls") :exclude '("test")))
(defparameter data (read-file->data "example-data.xls"))
(defparameter woi (walker-create :function #'lorder-mixed-bg
:data (create-walker-data data 1 4)
:params '(:scale 1d-5 :linewidth 7 :x0 2200
:mix 0.9 :bg0 1d-7 :bg1 1d-9)
; Also can give a list of stddev values for each individual data point
:data-error 1d-7
:log-liklihood #'log-liklihood-normal
:log-prior #'log-prior-lorder-mixed))
;; 6.34 seconds for 1e5 steps
(walker-adaptive-steps woi 100000)
(print (walker-plot-data-and-fit woi :take 1000))
;; #S(THIS-WALKER-STEP
;; :PROB 4646.756030280576d0
;; :PARAMS (:SCALE -4.788638538682475d-6 :LINEWIDTH 121.09571484294366d0 :X0
;; 2784.6836516658504d0 :MIX 3.141546812249173d0 :BG0
;; -1.0629009389997092d-6 :BG1 2.8207485034278606d-10))
(format t "Q Factor: ~,2e~%" (walker-with-exp woi '(/ :linewidth :x0) :take 1000))
(defparameter woil (lorder-mixed-bg-walker :data data :data-error 1d-7 :rows '(0 4)))
(walker-adaptive-steps woil 100000)
(print (walker-plot-data-and-fit woil :take 1000))
;;; Saving
;; (walker-save woil "walker001.wlk" 1000)
;; with no supplied functions, loading will suggest what functions to use (saving doesn't currently serialize functions, just saves their string names)
;; (walker-load "walker001.wlk")
;; with functions, it returns the walker
;; (defparameter loaded-walker (walker-load "walker001.wlk"
;; :function #'lorder-mixed-bg
;; :log-liklihood #'log-liklihood-normal
;; :log-prior #'log-prior-lorder-mixed))
;;; Global fit
;; Shares the linewidth, x0, and mix parameters with the regular lorder-mixed-bg
(defun lorder-mixed-bg2 (x &key scale2 linewidth x0 mix (bg02 0d0) (bg12 0d0) &allow-other-keys)
(lorder-mixed-bg x :scale scale2 :linewidth linewidth :x0 x0 :mix mix :bg0 bg02 :bg1 bg12))
;; Just create the normal walker and double, triple, etc. everything up for global fits of multiple data sets
(defparameter woig (walker-create :function (list #'lorder-mixed-bg
#'lorder-mixed-bg2)
:data (list (create-walker-data data 1 4)
(create-walker-data data 1 5))
:params '(:scale 1d-6 :linewidth 100 :x0 2700
:mix 0.1 :bg0 1d-7 :bg1 1d-10
:scale2 1d-8 :bg02 1d-7 :bg12 1d-10)
:data-error (list (list 1d-7)
(list 1d-7))
:log-liklihood (list #'log-liklihood-normal
#'log-liklihood-normal)
:log-prior (list #'log-prior-lorder-mixed
#'log-prior-lorder-mixed)))
(walker-adaptive-steps woig 100000)
(walker-plot-data-and-fit woig :take 1000 :fn-number 0)
(walker-plot-data-and-fit woig :take 1000 :fn-number 1)
(walker-catepillar-plots woig)
(show)
(walker-all-2d-plots woig 1000) ;; work in progress
(show)
| 3,015 | Common Lisp | .lisp | 62 | 44.919355 | 151 | 0.697991 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 39d5849619fa18c2162979e32af8b12162b2800bf7781e179a62eea5f750a7fc | 23,316 | [
-1
] |
23,317 | mcmc-fitting.asd | afranson_Lisp-MCMC/mcmc-fitting.asd | ;;;; mcmc-fitting.asd
(asdf:defsystem :mcmc-fitting
:serial t
:description "MCMC-Based Library for Fitting Data"
:author "Andrew Franson"
:license "GPLv3"
:depends-on (:cl-gnuplot
:alexandria)
:components ((:file "package")
(:file "mcmc-fitting")))
| 285 | Common Lisp | .asd | 10 | 23.9 | 52 | 0.660584 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | f5ef7f918585239243de21e8f8b58dcb3a44f7cd1a86d1705086143cb7252360 | 23,317 | [
-1
] |
23,320 | example-data.xls | afranson_Lisp-MCMC/example-data.xls | Set Magnetic Field (Oe) Probe field FMR Phase X Y FMR frequency FMR Power Integrated X
2.000E+3 2.000E+3 -4.172E-7 1.766E+2 -4.220E-7 1.948E-8 2.000E+1 0.000E+0 -4.220E-7
2.003E+3 2.000E+3 -4.431E-7 1.683E+2 -4.337E-7 8.937E-8 2.000E+1 0.000E+0 -4.337E-7
2.006E+3 2.001E+3 -5.365E-7 1.532E+2 -4.821E-7 2.471E-7 2.000E+1 0.000E+0 -4.938E-7
2.009E+3 2.005E+3 -4.363E-7 1.794E+2 -4.424E-7 1.319E-8 2.000E+1 0.000E+0 -5.142E-7
2.012E+3 2.008E+3 -3.149E-7 1.771E+2 -3.117E-7 2.030E-8 2.000E+1 0.000E+0 -4.040E-7
2.015E+3 2.012E+3 -6.118E-7 1.719E+2 -5.965E-7 9.774E-8 2.000E+1 0.000E+0 -5.785E-7
2.018E+3 2.015E+3 -4.342E-7 -1.765E+2 -4.316E-7 -2.883E-8 2.000E+1 0.000E+0 -5.882E-7
2.021E+3 2.019E+3 -4.732E-7 1.784E+2 -4.683E-7 8.731E-9 2.000E+1 0.000E+0 -6.345E-7
2.024E+3 2.021E+3 -6.110E-7 1.794E+2 -6.147E-7 -6.759E-9 2.000E+1 0.000E+0 -8.272E-7
2.027E+3 2.025E+3 -5.742E-7 1.693E+2 -5.678E-7 1.014E-7 2.000E+1 0.000E+0 -9.731E-7
2.030E+3 2.027E+3 -4.088E-7 1.796E+2 -4.063E-7 -2.322E-9 2.000E+1 0.000E+0 -9.574E-7
2.033E+3 2.032E+3 -6.074E-7 1.738E+2 -5.973E-7 7.075E-8 2.000E+1 0.000E+0 -1.133E-6
2.036E+3 2.034E+3 -3.536E-7 1.626E+2 -3.376E-7 9.873E-8 2.000E+1 0.000E+0 -1.048E-6
2.039E+3 2.037E+3 -4.477E-7 -1.719E+2 -4.384E-7 -6.335E-8 2.000E+1 0.000E+0 -1.065E-6
2.042E+3 2.039E+3 -4.914E-7 1.762E+2 -4.889E-7 2.566E-8 2.000E+1 0.000E+0 -1.132E-6
2.045E+3 2.042E+3 -4.930E-7 1.581E+2 -4.597E-7 1.853E-7 2.000E+1 0.000E+0 -1.170E-6
2.048E+3 2.046E+3 -4.934E-7 1.657E+2 -4.727E-7 1.209E-7 2.000E+1 0.000E+0 -1.220E-6
2.051E+3 2.049E+3 -4.182E-7 1.709E+2 -4.071E-7 4.894E-8 2.000E+1 0.000E+0 -1.205E-6
2.054E+3 2.052E+3 -4.611E-7 -1.780E+2 -4.697E-7 -2.122E-8 2.000E+1 0.000E+0 -1.253E-6
2.057E+3 2.054E+3 -3.711E-7 1.661E+2 -3.624E-7 8.997E-8 2.000E+1 0.000E+0 -1.194E-6
2.060E+3 2.057E+3 -4.075E-7 1.591E+2 -3.809E-7 1.249E-7 2.000E+1 0.000E+0 -1.152E-6
2.063E+3 2.060E+3 -3.467E-7 1.664E+2 -3.335E-7 9.192E-8 2.000E+1 0.000E+0 -1.064E-6
2.066E+3 2.062E+3 -5.042E-7 1.618E+2 -4.755E-7 1.585E-7 2.000E+1 0.000E+0 -1.118E-6
2.069E+3 2.066E+3 -4.210E-7 1.736E+2 -3.994E-7 5.288E-8 2.000E+1 0.000E+0 -1.095E-6
2.072E+3 2.069E+3 -5.464E-7 1.606E+2 -5.163E-7 1.815E-7 2.000E+1 0.000E+0 -1.189E-6
2.075E+3 2.072E+3 -4.860E-7 1.675E+2 -4.739E-7 1.089E-7 2.000E+1 0.000E+0 -1.241E-6
2.078E+3 2.075E+3 -4.333E-7 1.550E+2 -3.998E-7 1.805E-7 2.000E+1 0.000E+0 -1.219E-6
2.081E+3 2.078E+3 -4.661E-7 1.624E+2 -4.391E-7 1.461E-7 2.000E+1 0.000E+0 -1.236E-6
2.084E+3 2.082E+3 -4.618E-7 1.699E+2 -4.528E-7 9.166E-8 2.000E+1 0.000E+0 -1.267E-6
2.087E+3 2.084E+3 -3.524E-7 1.471E+2 -2.990E-7 1.908E-7 2.000E+1 0.000E+0 -1.144E-6
2.090E+3 2.087E+3 -4.218E-7 1.515E+2 -3.764E-7 2.058E-7 2.000E+1 0.000E+0 -1.099E-6
2.093E+3 2.091E+3 -5.273E-7 1.774E+2 -5.202E-7 2.290E-8 2.000E+1 0.000E+0 -1.197E-6
2.096E+3 2.094E+3 -4.822E-7 1.766E+2 -4.750E-7 2.273E-8 2.000E+1 0.000E+0 -1.250E-6
2.099E+3 2.097E+3 -4.452E-7 1.572E+2 -4.048E-7 1.760E-7 2.000E+1 0.000E+0 -1.233E-6
2.102E+3 2.100E+3 -4.996E-7 -1.760E+2 -4.972E-7 -3.428E-8 2.000E+1 0.000E+0 -1.308E-6
2.105E+3 2.103E+3 -5.028E-7 1.629E+2 -4.904E-7 1.392E-7 2.000E+1 0.000E+0 -1.376E-6
2.108E+3 2.105E+3 -5.037E-7 -1.749E+2 -5.017E-7 -5.644E-8 2.000E+1 0.000E+0 -1.456E-6
2.111E+3 2.108E+3 -5.015E-7 -1.780E+2 -4.925E-7 -2.244E-8 2.000E+1 0.000E+0 -1.527E-6
2.114E+3 2.111E+3 -5.512E-7 -1.766E+2 -5.508E-7 -3.450E-8 2.000E+1 0.000E+0 -1.656E-6
2.117E+3 2.114E+3 -5.711E-7 1.737E+2 -5.554E-7 6.517E-8 2.000E+1 0.000E+0 -1.789E-6
2.120E+3 2.117E+3 -5.121E-7 -1.735E+2 -5.167E-7 -5.463E-8 2.000E+1 0.000E+0 -1.884E-6
2.123E+3 2.120E+3 -4.901E-7 1.677E+2 -4.807E-7 1.090E-7 2.000E+1 0.000E+0 -1.942E-6
2.126E+3 2.123E+3 -4.048E-7 1.697E+2 -3.960E-7 7.088E-8 2.000E+1 0.000E+0 -1.917E-6
2.129E+3 2.126E+3 -4.002E-7 1.694E+2 -3.897E-7 7.856E-8 2.000E+1 0.000E+0 -1.884E-6
2.132E+3 2.129E+3 -3.523E-7 1.626E+2 -3.301E-7 1.173E-7 2.000E+1 0.000E+0 -1.792E-6
2.135E+3 2.132E+3 -2.913E-7 1.655E+2 -2.848E-7 7.553E-8 2.000E+1 0.000E+0 -1.655E-6
2.138E+3 2.135E+3 -4.491E-7 -1.741E+2 -4.482E-7 -4.380E-8 2.000E+1 0.000E+0 -1.682E-6
2.141E+3 2.138E+3 -4.626E-7 -1.712E+2 -4.607E-7 -6.696E-8 2.000E+1 0.000E+0 -1.720E-6
2.144E+3 2.141E+3 -3.420E-7 1.761E+2 -3.501E-7 2.515E-8 2.000E+1 0.000E+0 -1.648E-6
2.147E+3 2.144E+3 -4.970E-7 1.799E+2 -4.946E-7 1.188E-8 2.000E+1 0.000E+0 -1.721E-6
2.150E+3 2.147E+3 -2.937E-7 1.605E+2 -2.904E-7 7.772E-8 2.000E+1 0.000E+0 -1.589E-6
2.153E+3 2.152E+3 -3.308E-7 1.660E+2 -3.311E-7 8.257E-8 2.000E+1 0.000E+0 -1.499E-6
2.156E+3 2.155E+3 -5.698E-7 1.702E+2 -5.577E-7 8.616E-8 2.000E+1 0.000E+0 -1.634E-6
2.159E+3 2.157E+3 -4.464E-7 1.643E+2 -4.344E-7 1.154E-7 2.000E+1 0.000E+0 -1.647E-6
2.162E+3 2.160E+3 -4.344E-7 1.779E+2 -4.480E-7 1.571E-8 2.000E+1 0.000E+0 -1.673E-6
2.165E+3 2.163E+3 -3.197E-7 1.633E+2 -3.030E-7 9.637E-8 2.000E+1 0.000E+0 -1.554E-6
2.168E+3 2.165E+3 -4.456E-7 1.609E+2 -4.258E-7 1.436E-7 2.000E+1 0.000E+0 -1.558E-6
2.171E+3 2.168E+3 -4.840E-7 1.648E+2 -4.593E-7 1.285E-7 2.000E+1 0.000E+0 -1.595E-6
2.174E+3 2.172E+3 -4.967E-7 -1.706E+2 -4.747E-7 -7.035E-8 2.000E+1 0.000E+0 -1.648E-6
2.177E+3 2.174E+3 -4.067E-7 1.546E+2 -3.602E-7 1.749E-7 2.000E+1 0.000E+0 -1.586E-6
2.180E+3 2.177E+3 -5.230E-7 1.683E+2 -4.969E-7 1.055E-7 2.000E+1 0.000E+0 -1.661E-6
2.183E+3 2.180E+3 -4.862E-7 1.651E+2 -4.777E-7 1.130E-7 2.000E+1 0.000E+0 -1.717E-6
2.186E+3 2.184E+3 -4.268E-7 -1.562E+2 -4.031E-7 -1.760E-7 2.000E+1 0.000E+0 -1.698E-6
2.189E+3 2.187E+3 -3.708E-7 1.779E+2 -3.866E-7 3.202E-8 2.000E+1 0.000E+0 -1.663E-6
2.192E+3 2.189E+3 -3.982E-7 1.545E+2 -3.590E-7 1.777E-7 2.000E+1 0.000E+0 -1.600E-6
2.195E+3 2.192E+3 -5.060E-7 -1.770E+2 -5.163E-7 -3.191E-8 2.000E+1 0.000E+0 -1.694E-6
2.198E+3 2.197E+3 -5.130E-7 -1.725E+2 -5.109E-7 -6.396E-8 2.000E+1 0.000E+0 -1.783E-6
2.201E+3 2.198E+3 -5.327E-7 1.626E+2 -5.120E-7 1.594E-7 2.000E+1 0.000E+0 -1.873E-6
2.204E+3 2.201E+3 -5.010E-7 -1.695E+2 -4.994E-7 -8.873E-8 2.000E+1 0.000E+0 -1.950E-6
2.207E+3 2.204E+3 -4.144E-7 -1.624E+2 -3.961E-7 -1.234E-7 2.000E+1 0.000E+0 -1.925E-6
2.210E+3 2.208E+3 -4.439E-7 1.669E+2 -4.274E-7 9.897E-8 2.000E+1 0.000E+0 -1.930E-6
2.213E+3 2.211E+3 -6.309E-7 1.795E+2 -6.198E-7 6.342E-9 2.000E+1 0.000E+0 -2.128E-6
2.216E+3 2.213E+3 -4.168E-7 1.747E+2 -4.104E-7 3.551E-8 2.000E+1 0.000E+0 -2.116E-6
2.219E+3 2.216E+3 -5.472E-7 1.799E+2 -5.427E-7 -1.290E-9 2.000E+1 0.000E+0 -2.237E-6
2.222E+3 2.219E+3 -5.418E-7 1.742E+2 -5.432E-7 6.234E-8 2.000E+1 0.000E+0 -2.358E-6
2.225E+3 2.223E+3 -3.897E-7 1.761E+2 -3.917E-7 2.724E-8 2.000E+1 0.000E+0 -2.328E-6
2.228E+3 2.226E+3 -4.388E-7 1.651E+2 -4.129E-7 1.152E-7 2.000E+1 0.000E+0 -2.319E-6
2.231E+3 2.229E+3 -3.998E-7 1.749E+2 -4.082E-7 2.978E-8 2.000E+1 0.000E+0 -2.305E-6
2.234E+3 2.232E+3 -3.989E-7 -1.728E+2 -4.040E-7 -3.877E-8 2.000E+1 0.000E+0 -2.287E-6
2.237E+3 2.234E+3 -4.660E-7 1.771E+2 -4.676E-7 2.551E-8 2.000E+1 0.000E+0 -2.333E-6
2.240E+3 2.237E+3 -5.378E-7 1.662E+2 -5.172E-7 1.251E-7 2.000E+1 0.000E+0 -2.428E-6
2.243E+3 2.240E+3 -4.877E-7 -1.719E+2 -4.814E-7 -5.800E-8 2.000E+1 0.000E+0 -2.488E-6
2.246E+3 2.243E+3 -4.859E-7 -1.789E+2 -4.826E-7 -1.290E-8 2.000E+1 0.000E+0 -2.548E-6
2.249E+3 2.246E+3 -4.382E-7 -1.749E+2 -4.299E-7 -5.351E-8 2.000E+1 0.000E+0 -2.556E-6
2.252E+3 2.249E+3 -3.453E-7 1.759E+2 -3.378E-7 2.659E-8 2.000E+1 0.000E+0 -2.472E-6
2.255E+3 2.252E+3 -4.952E-7 1.722E+2 -4.941E-7 6.872E-8 2.000E+1 0.000E+0 -2.544E-6
2.258E+3 2.256E+3 -3.274E-7 1.705E+2 -3.142E-7 5.773E-8 2.000E+1 0.000E+0 -2.436E-6
2.261E+3 2.259E+3 -2.885E-7 -1.697E+2 -2.816E-7 -5.103E-8 2.000E+1 0.000E+0 -2.296E-6
2.264E+3 2.261E+3 -3.616E-7 -1.592E+2 -3.395E-7 -1.267E-7 2.000E+1 0.000E+0 -2.214E-6
2.267E+3 2.265E+3 -5.639E-7 -1.688E+2 -5.450E-7 -1.211E-7 2.000E+1 0.000E+0 -2.337E-6
2.270E+3 2.268E+3 -3.921E-7 1.615E+2 -3.736E-7 1.259E-7 2.000E+1 0.000E+0 -2.288E-6
2.273E+3 2.271E+3 -4.638E-7 -1.766E+2 -4.710E-7 -3.817E-8 2.000E+1 0.000E+0 -2.337E-6
2.276E+3 2.274E+3 -4.773E-7 1.704E+2 -4.603E-7 8.195E-8 2.000E+1 0.000E+0 -2.376E-6
2.279E+3 2.276E+3 -5.019E-7 -1.756E+2 -5.096E-7 -3.269E-8 2.000E+1 0.000E+0 -2.463E-6
2.282E+3 2.279E+3 -3.876E-7 1.716E+2 -3.873E-7 6.650E-8 2.000E+1 0.000E+0 -2.429E-6
2.285E+3 2.282E+3 -5.146E-7 1.774E+2 -5.085E-7 2.027E-8 2.000E+1 0.000E+0 -2.515E-6
2.288E+3 2.285E+3 -4.557E-7 1.762E+2 -4.613E-7 1.921E-8 2.000E+1 0.000E+0 -2.554E-6
2.291E+3 2.288E+3 -4.097E-7 1.715E+2 -3.983E-7 5.553E-8 2.000E+1 0.000E+0 -2.531E-6
2.294E+3 2.291E+3 -3.649E-7 1.737E+2 -3.787E-7 4.757E-8 2.000E+1 0.000E+0 -2.487E-6
2.297E+3 2.296E+3 -4.177E-7 1.740E+2 -4.176E-7 2.997E-8 2.000E+1 0.000E+0 -2.483E-6
2.300E+3 2.297E+3 -5.192E-7 1.662E+2 -5.063E-7 1.205E-7 2.000E+1 0.000E+0 -2.567E-6
2.303E+3 2.300E+3 -4.569E-7 1.767E+2 -4.572E-7 3.079E-8 2.000E+1 0.000E+0 -2.603E-6
2.306E+3 2.303E+3 -3.846E-7 1.722E+2 -3.805E-7 5.572E-8 2.000E+1 0.000E+0 -2.561E-6
2.309E+3 2.306E+3 -4.842E-7 1.766E+2 -4.821E-7 1.716E-8 2.000E+1 0.000E+0 -2.621E-6
2.312E+3 2.309E+3 -4.333E-7 1.349E+2 -3.075E-7 3.127E-7 2.000E+1 0.000E+0 -2.507E-6
2.315E+3 2.312E+3 -5.573E-7 1.679E+2 -5.511E-7 1.094E-7 2.000E+1 0.000E+0 -2.636E-6
2.318E+3 2.315E+3 -3.308E-7 1.794E+2 -3.305E-7 4.088E-9 2.000E+1 0.000E+0 -2.545E-6
2.321E+3 2.318E+3 -2.796E-7 1.738E+2 -2.761E-7 2.602E-8 2.000E+1 0.000E+0 -2.399E-6
2.324E+3 2.322E+3 -5.286E-7 1.794E+2 -5.235E-7 4.117E-10 2.000E+1 0.000E+0 -2.500E-6
2.327E+3 2.324E+3 -5.639E-7 1.781E+2 -5.806E-7 1.957E-8 2.000E+1 0.000E+0 -2.659E-6
2.330E+3 2.327E+3 -4.919E-7 1.773E+2 -4.973E-7 2.429E-8 2.000E+1 0.000E+0 -2.734E-6
2.333E+3 2.330E+3 -4.718E-7 1.540E+2 -4.344E-7 2.103E-7 2.000E+1 0.000E+0 -2.747E-6
2.336E+3 2.333E+3 -3.700E-7 -1.757E+2 -3.758E-7 -2.738E-8 2.000E+1 0.000E+0 -2.701E-6
2.339E+3 2.336E+3 -4.807E-7 1.756E+2 -4.833E-7 2.999E-8 2.000E+1 0.000E+0 -2.762E-6
2.342E+3 2.339E+3 -5.577E-7 1.789E+2 -5.408E-7 1.012E-8 2.000E+1 0.000E+0 -2.881E-6
2.345E+3 2.343E+3 -5.087E-7 1.693E+2 -5.146E-7 8.586E-8 2.000E+1 0.000E+0 -2.973E-6
2.348E+3 2.345E+3 -5.339E-7 -1.789E+2 -5.360E-7 -5.752E-9 2.000E+1 0.000E+0 -3.087E-6
2.351E+3 2.349E+3 -5.062E-7 1.435E+2 -3.933E-7 2.977E-7 2.000E+1 0.000E+0 -3.059E-6
2.354E+3 2.351E+3 -3.717E-7 1.728E+2 -3.859E-7 4.089E-8 2.000E+1 0.000E+0 -3.023E-6
2.357E+3 2.354E+3 -5.878E-7 1.756E+2 -5.801E-7 4.412E-8 2.000E+1 0.000E+0 -3.181E-6
2.360E+3 2.356E+3 -4.834E-7 -1.622E+2 -4.704E-7 -1.455E-7 2.000E+1 0.000E+0 -3.229E-6
2.363E+3 2.362E+3 -5.105E-7 -1.781E+2 -5.052E-7 -2.912E-8 2.000E+1 0.000E+0 -3.313E-6
2.366E+3 2.364E+3 -4.011E-7 1.481E+2 -3.441E-7 2.134E-7 2.000E+1 0.000E+0 -3.235E-6
2.369E+3 2.367E+3 -4.920E-7 1.736E+2 -4.841E-7 3.763E-8 2.000E+1 0.000E+0 -3.297E-6
2.372E+3 2.369E+3 -5.686E-7 -1.783E+2 -5.778E-7 -3.261E-8 2.000E+1 0.000E+0 -3.453E-6
2.375E+3 2.372E+3 -4.529E-7 1.470E+2 -3.968E-7 2.455E-7 2.000E+1 0.000E+0 -3.427E-6
2.378E+3 2.375E+3 -5.554E-7 1.771E+2 -5.526E-7 3.667E-8 2.000E+1 0.000E+0 -3.558E-6
2.381E+3 2.378E+3 -5.331E-7 1.692E+2 -5.233E-7 9.891E-8 2.000E+1 0.000E+0 -3.659E-6
2.384E+3 2.382E+3 -3.625E-7 -1.683E+2 -3.457E-7 -7.433E-8 2.000E+1 0.000E+0 -3.583E-6
2.387E+3 2.385E+3 -5.606E-7 1.584E+2 -5.206E-7 2.101E-7 2.000E+1 0.000E+0 -3.682E-6
2.390E+3 2.387E+3 -5.280E-7 1.726E+2 -5.379E-7 7.107E-8 2.000E+1 0.000E+0 -3.798E-6
2.393E+3 2.390E+3 -5.908E-7 -1.755E+2 -5.958E-7 -5.779E-8 2.000E+1 0.000E+0 -3.972E-6
2.396E+3 2.393E+3 -6.061E-7 1.641E+2 -5.794E-7 1.653E-7 2.000E+1 0.000E+0 -4.129E-6
2.399E+3 2.396E+3 -4.853E-7 -1.649E+2 -4.699E-7 -1.292E-7 2.000E+1 0.000E+0 -4.177E-6
2.402E+3 2.400E+3 -4.962E-7 1.726E+2 -4.946E-7 6.449E-8 2.000E+1 0.000E+0 -4.249E-6
2.405E+3 2.403E+3 -5.403E-7 1.695E+2 -5.285E-7 9.864E-8 2.000E+1 0.000E+0 -4.356E-6
2.408E+3 2.406E+3 -4.187E-7 1.754E+2 -4.021E-7 3.543E-8 2.000E+1 0.000E+0 -4.336E-6
2.411E+3 2.408E+3 -4.757E-7 1.573E+2 -4.365E-7 1.821E-7 2.000E+1 0.000E+0 -4.351E-6
2.414E+3 2.411E+3 -5.038E-7 -1.676E+2 -4.898E-7 -1.094E-7 2.000E+1 0.000E+0 -4.419E-6
2.417E+3 2.414E+3 -5.186E-7 1.711E+2 -5.041E-7 6.189E-8 2.000E+1 0.000E+0 -4.501E-6
2.420E+3 2.417E+3 -4.740E-7 1.722E+2 -4.473E-7 8.736E-8 2.000E+1 0.000E+0 -4.526E-6
2.423E+3 2.420E+3 -5.271E-7 1.724E+2 -5.233E-7 6.568E-8 2.000E+1 0.000E+0 -4.627E-6
2.426E+3 2.424E+3 -4.962E-7 1.496E+2 -4.392E-7 2.425E-7 2.000E+1 0.000E+0 -4.645E-6
2.429E+3 2.428E+3 -5.934E-7 1.733E+2 -5.910E-7 6.651E-8 2.000E+1 0.000E+0 -4.814E-6
2.432E+3 2.430E+3 -5.692E-7 1.595E+2 -5.308E-7 2.022E-7 2.000E+1 0.000E+0 -4.922E-6
2.435E+3 2.432E+3 -4.689E-7 -1.681E+2 -4.644E-7 -1.013E-7 2.000E+1 0.000E+0 -4.965E-6
2.438E+3 2.436E+3 -3.007E-7 -1.760E+2 -3.084E-7 -2.124E-8 2.000E+1 0.000E+0 -4.851E-6
2.441E+3 2.439E+3 -4.059E-7 -1.785E+2 -3.963E-7 -1.293E-8 2.000E+1 0.000E+0 -4.826E-6
2.444E+3 2.441E+3 -4.659E-7 1.727E+2 -4.650E-7 7.356E-8 2.000E+1 0.000E+0 -4.869E-6
2.447E+3 2.445E+3 -6.800E-7 1.747E+2 -6.775E-7 8.143E-8 2.000E+1 0.000E+0 -5.124E-6
2.450E+3 2.448E+3 -5.168E-7 1.677E+2 -4.960E-7 1.117E-7 2.000E+1 0.000E+0 -5.198E-6
2.453E+3 2.450E+3 -4.796E-7 -1.666E+2 -4.744E-7 -1.000E-7 2.000E+1 0.000E+0 -5.251E-6
2.456E+3 2.453E+3 -5.223E-7 1.605E+2 -4.863E-7 1.791E-7 2.000E+1 0.000E+0 -5.315E-6
2.459E+3 2.456E+3 -3.523E-7 1.742E+2 -3.601E-7 2.632E-8 2.000E+1 0.000E+0 -5.253E-6
2.462E+3 2.459E+3 -5.533E-7 1.716E+2 -5.455E-7 7.805E-8 2.000E+1 0.000E+0 -5.377E-6
2.465E+3 2.462E+3 -4.993E-7 1.749E+2 -4.970E-7 4.722E-8 2.000E+1 0.000E+0 -5.452E-6
2.468E+3 2.467E+3 -4.123E-7 1.752E+2 -4.181E-7 2.921E-8 2.000E+1 0.000E+0 -5.448E-6
2.471E+3 2.469E+3 -5.034E-7 1.793E+2 -4.945E-7 -3.257E-9 2.000E+1 0.000E+0 -5.520E-6
2.474E+3 2.473E+3 -4.720E-7 -1.687E+2 -4.666E-7 -9.048E-8 2.000E+1 0.000E+0 -5.565E-6
2.477E+3 2.474E+3 -6.304E-7 1.598E+2 -5.809E-7 2.186E-7 2.000E+1 0.000E+0 -5.724E-6
2.480E+3 2.477E+3 -4.493E-7 1.766E+2 -4.604E-7 2.976E-8 2.000E+1 0.000E+0 -5.762E-6
2.483E+3 2.480E+3 -6.025E-7 1.786E+2 -6.073E-7 1.710E-8 2.000E+1 0.000E+0 -5.948E-6
2.486E+3 2.483E+3 -4.961E-7 -1.689E+2 -4.883E-7 -8.395E-8 2.000E+1 0.000E+0 -6.014E-6
2.489E+3 2.486E+3 -5.820E-7 1.715E+2 -5.602E-7 7.811E-8 2.000E+1 0.000E+0 -6.152E-6
2.492E+3 2.489E+3 -5.266E-7 1.627E+2 -5.022E-7 1.703E-7 2.000E+1 0.000E+0 -6.232E-6
2.495E+3 2.492E+3 -6.450E-7 -1.789E+2 -6.488E-7 -2.146E-8 2.000E+1 0.000E+0 -6.459E-6
2.498E+3 2.496E+3 -5.408E-7 1.615E+2 -5.170E-7 1.826E-7 2.000E+1 0.000E+0 -6.554E-6
2.501E+3 2.498E+3 -6.575E-7 -1.580E+2 -5.930E-7 -2.389E-7 2.000E+1 0.000E+0 -6.725E-6
2.504E+3 2.501E+3 -5.415E-7 1.753E+2 -5.422E-7 4.763E-8 2.000E+1 0.000E+0 -6.846E-6
2.507E+3 2.505E+3 -6.099E-7 1.745E+2 -6.105E-7 5.793E-8 2.000E+1 0.000E+0 -7.034E-6
2.510E+3 2.507E+3 -4.180E-7 -1.636E+2 -4.084E-7 -1.156E-7 2.000E+1 0.000E+0 -7.021E-6
2.513E+3 2.510E+3 -4.867E-7 -1.784E+2 -4.860E-7 -9.375E-9 2.000E+1 0.000E+0 -7.085E-6
2.516E+3 2.515E+3 -6.562E-7 -1.708E+2 -6.301E-7 -1.117E-7 2.000E+1 0.000E+0 -7.293E-6
2.519E+3 2.517E+3 -5.616E-7 1.693E+2 -5.576E-7 9.769E-8 2.000E+1 0.000E+0 -7.428E-6
2.522E+3 2.519E+3 -7.447E-7 -1.789E+2 -7.443E-7 -2.196E-8 2.000E+1 0.000E+0 -7.751E-6
2.525E+3 2.522E+3 -4.213E-7 1.462E+2 -3.496E-7 2.358E-7 2.000E+1 0.000E+0 -7.678E-6
2.528E+3 2.525E+3 -6.279E-7 -1.663E+2 -6.115E-7 -1.494E-7 2.000E+1 0.000E+0 -7.868E-6
2.531E+3 2.529E+3 -7.603E-7 1.659E+2 -7.379E-7 1.816E-7 2.000E+1 0.000E+0 -8.184E-6
2.534E+3 2.532E+3 -7.946E-7 1.735E+2 -7.803E-7 1.002E-7 2.000E+1 0.000E+0 -8.542E-6
2.537E+3 2.534E+3 -6.554E-7 1.642E+2 -6.373E-7 1.612E-7 2.000E+1 0.000E+0 -8.757E-6
2.540E+3 2.537E+3 -5.719E-7 1.728E+2 -5.696E-7 7.028E-8 2.000E+1 0.000E+0 -8.905E-6
2.543E+3 2.541E+3 -5.345E-7 1.695E+2 -4.984E-7 9.579E-8 2.000E+1 0.000E+0 -8.981E-6
2.546E+3 2.544E+3 -5.051E-7 1.609E+2 -4.803E-7 1.549E-7 2.000E+1 0.000E+0 -9.040E-6
2.549E+3 2.546E+3 -4.537E-7 1.732E+2 -4.517E-7 4.561E-8 2.000E+1 0.000E+0 -9.069E-6
2.552E+3 2.549E+3 -6.356E-7 -1.706E+2 -6.295E-7 -1.021E-7 2.000E+1 0.000E+0 -9.277E-6
2.555E+3 2.554E+3 -6.878E-7 1.770E+2 -6.895E-7 3.362E-8 2.000E+1 0.000E+0 -9.545E-6
2.558E+3 2.555E+3 -6.509E-7 -1.685E+2 -6.412E-7 -1.188E-7 2.000E+1 0.000E+0 -9.764E-6
2.561E+3 2.559E+3 -6.144E-7 -1.702E+2 -6.073E-7 -9.895E-8 2.000E+1 0.000E+0 -9.949E-6
2.564E+3 2.562E+3 -8.626E-7 -1.777E+2 -8.589E-7 -2.613E-8 2.000E+1 0.000E+0 -1.039E-5
2.567E+3 2.565E+3 -7.568E-7 -1.790E+2 -7.463E-7 -1.711E-8 2.000E+1 0.000E+0 -1.071E-5
2.570E+3 2.568E+3 -9.218E-7 1.722E+2 -8.977E-7 1.259E-7 2.000E+1 0.000E+0 -1.119E-5
2.573E+3 2.571E+3 -7.365E-7 1.653E+2 -7.083E-7 1.984E-7 2.000E+1 0.000E+0 -1.147E-5
2.576E+3 2.574E+3 -7.322E-7 1.758E+2 -7.314E-7 5.587E-8 2.000E+1 0.000E+0 -1.178E-5
2.579E+3 2.576E+3 -6.094E-7 1.799E+2 -6.128E-7 8.777E-9 2.000E+1 0.000E+0 -1.197E-5
2.582E+3 2.579E+3 -7.305E-7 1.791E+2 -7.464E-7 1.157E-8 2.000E+1 0.000E+0 -1.230E-5
2.585E+3 2.582E+3 -7.521E-7 1.787E+2 -7.518E-7 3.684E-9 2.000E+1 0.000E+0 -1.263E-5
2.588E+3 2.585E+3 -8.118E-7 -1.719E+2 -8.079E-7 -1.114E-7 2.000E+1 0.000E+0 -1.301E-5
2.591E+3 2.588E+3 -9.254E-7 1.780E+2 -9.105E-7 2.446E-8 2.000E+1 0.000E+0 -1.350E-5
2.594E+3 2.593E+3 -9.042E-7 1.760E+2 -9.109E-7 6.767E-8 2.000E+1 0.000E+0 -1.399E-5
2.597E+3 2.594E+3 -9.941E-7 -1.777E+2 -1.002E-6 -3.778E-8 2.000E+1 0.000E+0 -1.457E-5
2.600E+3 2.598E+3 -9.378E-7 1.797E+2 -9.329E-7 6.789E-9 2.000E+1 0.000E+0 -1.508E-5
2.603E+3 2.601E+3 -9.163E-7 1.791E+2 -9.152E-7 2.277E-9 2.000E+1 0.000E+0 -1.557E-5
2.606E+3 2.604E+3 -7.972E-7 1.768E+2 -7.780E-7 4.929E-8 2.000E+1 0.000E+0 -1.593E-5
2.609E+3 2.607E+3 -9.660E-7 1.662E+2 -9.360E-7 2.358E-7 2.000E+1 0.000E+0 -1.644E-5
2.612E+3 2.609E+3 -8.636E-7 -1.705E+2 -8.669E-7 -1.372E-7 2.000E+1 0.000E+0 -1.689E-5
2.615E+3 2.612E+3 -9.767E-7 -1.760E+2 -9.987E-7 -6.567E-8 2.000E+1 0.000E+0 -1.747E-5
2.618E+3 2.615E+3 -9.996E-7 -1.797E+2 -1.010E-6 -6.707E-9 2.000E+1 0.000E+0 -1.805E-5
2.621E+3 2.619E+3 -1.081E-6 1.717E+2 -1.072E-6 1.557E-7 2.000E+1 0.000E+0 -1.870E-5
2.624E+3 2.621E+3 -1.021E-6 1.771E+2 -1.026E-6 4.576E-8 2.000E+1 0.000E+0 -1.931E-5
2.627E+3 2.624E+3 -8.918E-7 1.758E+2 -8.771E-7 8.712E-8 2.000E+1 0.000E+0 -1.976E-5
2.630E+3 2.627E+3 -1.011E-6 1.730E+2 -1.005E-6 1.058E-7 2.000E+1 0.000E+0 -2.035E-5
2.633E+3 2.630E+3 -1.247E-6 1.764E+2 -1.217E-6 8.136E-8 2.000E+1 0.000E+0 -2.114E-5
2.636E+3 2.633E+3 -1.086E-6 1.774E+2 -1.083E-6 4.462E-8 2.000E+1 0.000E+0 -2.180E-5
2.639E+3 2.636E+3 -1.062E-6 -1.719E+2 -1.048E-6 -1.518E-7 2.000E+1 0.000E+0 -2.243E-5
2.642E+3 2.639E+3 -1.337E-6 1.768E+2 -1.326E-6 7.569E-8 2.000E+1 0.000E+0 -2.333E-5
2.645E+3 2.644E+3 -1.216E-6 1.767E+2 -1.232E-6 5.914E-8 2.000E+1 0.000E+0 -2.414E-5
2.648E+3 2.647E+3 -1.264E-6 1.760E+2 -1.256E-6 8.463E-8 2.000E+1 0.000E+0 -2.498E-5
2.651E+3 2.649E+3 -1.499E-6 -1.745E+2 -1.487E-6 -1.387E-7 2.000E+1 0.000E+0 -2.604E-5
2.654E+3 2.652E+3 -1.414E-6 -1.761E+2 -1.406E-6 -1.024E-7 2.000E+1 0.000E+0 -2.703E-5
2.657E+3 2.654E+3 -1.432E-6 1.776E+2 -1.439E-6 5.565E-8 2.000E+1 0.000E+0 -2.804E-5
2.660E+3 2.658E+3 -1.342E-6 -1.790E+2 -1.338E-6 -1.255E-8 2.000E+1 0.000E+0 -2.896E-5
2.663E+3 2.660E+3 -1.490E-6 1.777E+2 -1.491E-6 7.028E-8 2.000E+1 0.000E+0 -3.003E-5
2.666E+3 2.663E+3 -1.749E-6 -1.795E+2 -1.744E-6 -1.341E-8 2.000E+1 0.000E+0 -3.135E-5
2.669E+3 2.665E+3 -1.870E-6 -1.786E+2 -1.860E-6 -4.207E-8 2.000E+1 0.000E+0 -3.279E-5
2.672E+3 2.670E+3 -1.721E-6 1.777E+2 -1.724E-6 7.689E-8 2.000E+1 0.000E+0 -3.409E-5
2.675E+3 2.673E+3 -1.792E-6 -1.768E+2 -1.786E-6 -9.569E-8 2.000E+1 0.000E+0 -3.545E-5
2.678E+3 2.674E+3 -1.990E-6 1.772E+2 -1.984E-6 8.934E-8 2.000E+1 0.000E+0 -3.702E-5
2.681E+3 2.678E+3 -1.934E-6 -1.760E+2 -1.931E-6 -1.319E-7 2.000E+1 0.000E+0 -3.852E-5
2.684E+3 2.681E+3 -2.069E-6 1.783E+2 -2.064E-6 6.093E-8 2.000E+1 0.000E+0 -4.017E-5
2.687E+3 2.685E+3 -2.329E-6 1.772E+2 -2.319E-6 1.155E-7 2.000E+1 0.000E+0 -4.206E-5
2.690E+3 2.688E+3 -2.154E-6 1.789E+2 -2.156E-6 5.128E-8 2.000E+1 0.000E+0 -4.380E-5
2.693E+3 2.690E+3 -2.330E-6 1.780E+2 -2.320E-6 8.020E-8 2.000E+1 0.000E+0 -4.570E-5
2.696E+3 2.694E+3 -2.429E-6 -1.778E+2 -2.434E-6 -8.895E-8 2.000E+1 0.000E+0 -4.771E-5
2.699E+3 2.697E+3 -2.562E-6 1.772E+2 -2.546E-6 1.217E-7 2.000E+1 0.000E+0 -4.983E-5
2.702E+3 2.700E+3 -2.806E-6 -1.785E+2 -2.809E-6 -7.604E-8 2.000E+1 0.000E+0 -5.222E-5
2.705E+3 2.703E+3 -2.700E-6 1.780E+2 -2.705E-6 9.449E-8 2.000E+1 0.000E+0 -5.450E-5
2.708E+3 2.706E+3 -2.903E-6 -1.787E+2 -2.894E-6 -7.618E-8 2.000E+1 0.000E+0 -5.697E-5
2.711E+3 2.708E+3 -2.997E-6 -1.785E+2 -3.000E-6 -7.307E-8 2.000E+1 0.000E+0 -5.955E-5
2.714E+3 2.711E+3 -3.260E-6 -1.788E+2 -3.239E-6 -6.938E-8 2.000E+1 0.000E+0 -6.237E-5
2.717E+3 2.714E+3 -3.281E-6 -1.758E+2 -3.257E-6 -2.668E-7 2.000E+1 0.000E+0 -6.520E-5
2.720E+3 2.717E+3 -3.441E-6 -1.787E+2 -3.433E-6 -8.022E-8 2.000E+1 0.000E+0 -6.822E-5
2.723E+3 2.720E+3 -3.713E-6 -1.800E+2 -3.711E-6 2.387E-9 2.000E+1 0.000E+0 -7.150E-5
2.726E+3 2.724E+3 -3.649E-6 1.796E+2 -3.643E-6 2.502E-8 2.000E+1 0.000E+0 -7.472E-5
2.729E+3 2.726E+3 -3.997E-6 1.799E+2 -3.996E-6 8.931E-9 2.000E+1 0.000E+0 -7.830E-5
2.732E+3 2.729E+3 -4.062E-6 -1.793E+2 -4.056E-6 -5.673E-8 2.000E+1 0.000E+0 -8.193E-5
2.735E+3 2.734E+3 -4.146E-6 -1.781E+2 -4.141E-6 -1.349E-7 2.000E+1 0.000E+0 -8.565E-5
2.738E+3 2.734E+3 -4.248E-6 1.793E+2 -4.251E-6 4.645E-8 2.000E+1 0.000E+0 -8.948E-5
2.741E+3 2.738E+3 -4.325E-6 -1.798E+2 -4.335E-6 -1.791E-8 2.000E+1 0.000E+0 -9.339E-5
2.744E+3 2.741E+3 -4.431E-6 -1.796E+2 -4.428E-6 -3.354E-8 2.000E+1 0.000E+0 -9.740E-5
2.747E+3 2.745E+3 -4.492E-6 1.799E+2 -4.487E-6 1.703E-8 2.000E+1 0.000E+0 -1.015E-4
2.750E+3 2.748E+3 -4.587E-6 -1.782E+2 -4.579E-6 -1.437E-7 2.000E+1 0.000E+0 -1.056E-4
2.753E+3 2.750E+3 -4.800E-6 -1.786E+2 -4.792E-6 -1.109E-7 2.000E+1 0.000E+0 -1.100E-4
2.756E+3 2.753E+3 -4.619E-6 -1.780E+2 -4.622E-6 -1.592E-7 2.000E+1 0.000E+0 -1.142E-4
2.759E+3 2.756E+3 -4.516E-6 -1.793E+2 -4.513E-6 -4.906E-8 2.000E+1 0.000E+0 -1.183E-4
2.762E+3 2.759E+3 -4.249E-6 -1.791E+2 -4.245E-6 -5.287E-8 2.000E+1 0.000E+0 -1.221E-4
2.765E+3 2.763E+3 -3.969E-6 -1.795E+2 -3.972E-6 -4.700E-8 2.000E+1 0.000E+0 -1.257E-4
2.768E+3 2.766E+3 -3.773E-6 1.794E+2 -3.782E-6 3.394E-8 2.000E+1 0.000E+0 -1.290E-4
2.771E+3 2.767E+3 -3.483E-6 1.797E+2 -3.482E-6 1.887E-8 2.000E+1 0.000E+0 -1.321E-4
2.774E+3 2.771E+3 -3.022E-6 1.789E+2 -3.043E-6 5.709E-8 2.000E+1 0.000E+0 -1.347E-4
2.777E+3 2.776E+3 -2.351E-6 -1.785E+2 -2.365E-6 -4.350E-8 2.000E+1 0.000E+0 -1.366E-4
2.780E+3 2.777E+3 -1.757E-6 1.786E+2 -1.773E-6 3.767E-8 2.000E+1 0.000E+0 -1.380E-4
2.783E+3 2.781E+3 -1.105E-6 1.693E+2 -1.106E-6 2.019E-7 2.000E+1 0.000E+0 -1.387E-4
2.786E+3 2.784E+3 -5.196E-7 1.776E+2 -5.310E-7 1.355E-8 2.000E+1 0.000E+0 -1.388E-4
2.789E+3 2.787E+3 2.085E-7 1.159E+1 1.869E-7 4.010E-8 2.000E+1 0.000E+0 -1.382E-4
2.792E+3 2.789E+3 8.444E-7 1.130E+1 8.181E-7 1.685E-7 2.000E+1 0.000E+0 -1.369E-4
2.795E+3 2.793E+3 1.605E-6 3.334E+0 1.588E-6 9.491E-8 2.000E+1 0.000E+0 -1.349E-4
2.798E+3 2.796E+3 2.386E-6 2.082E+0 2.361E-6 9.684E-8 2.000E+1 0.000E+0 -1.321E-4
2.801E+3 2.799E+3 3.190E-6 4.122E-1 3.176E-6 2.671E-8 2.000E+1 0.000E+0 -1.285E-4
2.804E+3 2.802E+3 3.674E-6 3.109E+0 3.647E-6 2.056E-7 2.000E+1 0.000E+0 -1.245E-4
2.807E+3 2.805E+3 4.209E-6 1.416E+0 4.196E-6 9.933E-8 2.000E+1 0.000E+0 -1.199E-4
2.810E+3 2.807E+3 4.499E-6 7.692E-1 4.498E-6 5.415E-8 2.000E+1 0.000E+0 -1.149E-4
2.813E+3 2.810E+3 4.811E-6 1.008E+0 4.789E-6 8.418E-8 2.000E+1 0.000E+0 -1.097E-4
2.816E+3 2.813E+3 4.898E-6 1.156E+0 4.889E-6 9.255E-8 2.000E+1 0.000E+0 -1.044E-4
2.819E+3 2.816E+3 4.904E-6 2.268E+0 4.908E-6 1.867E-7 2.000E+1 0.000E+0 -9.908E-5
2.822E+3 2.820E+3 5.065E-6 1.453E+0 5.055E-6 1.241E-7 2.000E+1 0.000E+0 -9.361E-5
2.825E+3 2.823E+3 5.034E-6 1.009E+0 5.040E-6 7.716E-8 2.000E+1 0.000E+0 -8.815E-5
2.828E+3 2.825E+3 4.781E-6 3.222E-1 4.783E-6 2.907E-8 2.000E+1 0.000E+0 -8.294E-5
2.831E+3 2.829E+3 4.728E-6 1.076E+0 4.730E-6 9.537E-8 2.000E+1 0.000E+0 -7.779E-5
2.834E+3 2.831E+3 4.577E-6 2.386E+0 4.583E-6 1.851E-7 2.000E+1 0.000E+0 -7.278E-5
2.837E+3 2.835E+3 4.300E-6 2.156E+0 4.298E-6 1.622E-7 2.000E+1 0.000E+0 -6.806E-5
2.840E+3 2.838E+3 4.026E-6 2.381E+0 4.024E-6 1.596E-7 2.000E+1 0.000E+0 -6.362E-5
2.843E+3 2.841E+3 3.899E-6 1.484E+0 3.908E-6 9.948E-8 2.000E+1 0.000E+0 -5.929E-5
2.846E+3 2.844E+3 3.596E-6 1.286E+0 3.593E-6 7.772E-8 2.000E+1 0.000E+0 -5.527E-5
2.849E+3 2.847E+3 3.270E-6 -1.066E+0 3.261E-6 -6.049E-8 2.000E+1 0.000E+0 -5.159E-5
2.852E+3 2.850E+3 3.213E-6 9.662E-1 3.194E-6 5.653E-8 2.000E+1 0.000E+0 -4.797E-5
2.855E+3 2.852E+3 3.180E-6 -1.701E+0 3.188E-6 -9.970E-8 2.000E+1 0.000E+0 -4.436E-5
2.858E+3 2.855E+3 2.743E-6 1.631E+0 2.747E-6 7.495E-8 2.000E+1 0.000E+0 -4.120E-5
2.861E+3 2.858E+3 2.656E-6 5.241E-1 2.661E-6 2.367E-8 2.000E+1 0.000E+0 -3.811E-5
2.864E+3 2.861E+3 2.495E-6 1.737E+0 2.501E-6 7.138E-8 2.000E+1 0.000E+0 -3.519E-5
2.867E+3 2.865E+3 2.350E-6 5.253E+0 2.346E-6 2.201E-7 2.000E+1 0.000E+0 -3.242E-5
2.870E+3 2.867E+3 2.163E-6 1.969E+0 2.172E-6 8.009E-8 2.000E+1 0.000E+0 -2.983E-5
2.873E+3 2.871E+3 2.109E-6 5.125E-1 2.108E-6 1.995E-8 2.000E+1 0.000E+0 -2.730E-5
2.876E+3 2.874E+3 1.931E-6 -3.029E-1 1.928E-6 -1.135E-8 2.000E+1 0.000E+0 -2.495E-5
2.879E+3 2.876E+3 1.669E-6 -1.513E+0 1.670E-6 -4.916E-8 2.000E+1 0.000E+0 -2.286E-5
2.882E+3 2.880E+3 1.663E-6 1.543E+0 1.664E-6 5.210E-8 2.000E+1 0.000E+0 -2.077E-5
2.885E+3 2.883E+3 1.345E-6 2.191E+0 1.347E-6 5.071E-8 2.000E+1 0.000E+0 -1.900E-5
2.888E+3 2.886E+3 1.323E-6 2.057E+0 1.322E-6 4.128E-8 2.000E+1 0.000E+0 -1.726E-5
2.891E+3 2.889E+3 1.225E-6 4.070E+0 1.230E-6 8.767E-8 2.000E+1 0.000E+0 -1.561E-5
2.894E+3 2.891E+3 1.134E-6 -1.172E+0 1.131E-6 -2.256E-8 2.000E+1 0.000E+0 -1.405E-5
2.897E+3 2.894E+3 1.041E-6 9.168E+0 1.037E-6 1.659E-7 2.000E+1 0.000E+0 -1.259E-5
2.900E+3 2.897E+3 1.048E-6 4.318E+0 1.040E-6 8.774E-8 2.000E+1 0.000E+0 -1.113E-5
2.903E+3 2.900E+3 9.134E-7 4.134E+0 9.190E-7 6.814E-8 2.000E+1 0.000E+0 -9.790E-6
2.906E+3 2.903E+3 8.403E-7 2.728E+0 8.410E-7 5.069E-8 2.000E+1 0.000E+0 -8.527E-6
2.909E+3 2.906E+3 9.245E-7 4.845E+0 9.292E-7 7.562E-8 2.000E+1 0.000E+0 -7.176E-6
2.912E+3 2.910E+3 7.135E-7 1.667E+1 6.737E-7 2.161E-7 2.000E+1 0.000E+0 -6.080E-6
2.915E+3 2.913E+3 6.672E-7 4.285E-1 6.699E-7 -4.180E-10 2.000E+1 0.000E+0 -4.989E-6
2.918E+3 2.916E+3 5.525E-7 9.534E+0 5.465E-7 9.604E-8 2.000E+1 0.000E+0 -4.020E-6
2.921E+3 2.918E+3 5.058E-7 3.766E+0 5.077E-7 3.279E-8 2.000E+1 0.000E+0 -3.090E-6
2.924E+3 2.921E+3 4.949E-7 8.718E+0 4.914E-7 6.907E-8 2.000E+1 0.000E+0 -2.177E-6
2.927E+3 2.924E+3 4.485E-7 7.065E+0 4.496E-7 4.870E-8 2.000E+1 0.000E+0 -1.306E-6
2.930E+3 2.928E+3 4.322E-7 9.276E-1 4.269E-7 7.497E-9 2.000E+1 0.000E+0 -4.567E-7
2.933E+3 2.931E+3 4.790E-7 1.186E+1 4.662E-7 1.057E-7 2.000E+1 0.000E+0 4.315E-7
2.936E+3 2.934E+3 3.539E-7 7.921E+0 3.561E-7 5.554E-8 2.000E+1 0.000E+0 1.209E-6
2.939E+3 2.936E+3 4.831E-7 3.002E+1 4.134E-7 2.380E-7 2.000E+1 0.000E+0 2.045E-6
2.942E+3 2.938E+3 3.631E-7 6.730E+0 3.639E-7 4.887E-8 2.000E+1 0.000E+0 2.831E-6
2.945E+3 2.942E+3 2.588E-7 2.669E+1 2.257E-7 1.225E-7 2.000E+1 0.000E+0 3.478E-6
2.948E+3 2.947E+3 2.744E-7 1.310E+1 2.755E-7 6.529E-8 2.000E+1 0.000E+0 4.176E-6
2.951E+3 2.948E+3 2.832E-7 8.113E+0 2.853E-7 4.128E-8 2.000E+1 0.000E+0 4.883E-6
2.954E+3 2.953E+3 2.062E-7 7.130E+0 2.021E-7 2.499E-8 2.000E+1 0.000E+0 5.507E-6
2.957E+3 2.955E+3 1.845E-7 1.858E+1 1.816E-7 5.714E-8 2.000E+1 0.000E+0 6.111E-6
2.960E+3 2.958E+3 2.132E-7 1.262E+0 2.239E-7 1.876E-8 2.000E+1 0.000E+0 6.757E-6
2.963E+3 2.960E+3 1.563E-7 1.485E+1 1.462E-7 3.939E-8 2.000E+1 0.000E+0 7.325E-6
2.966E+3 2.963E+3 3.327E-7 4.161E+1 2.406E-7 2.248E-7 2.000E+1 0.000E+0 7.987E-6
2.969E+3 2.966E+3 -1.823E-7 6.311E+1 7.476E-8 1.614E-7 2.000E+1 0.000E+0 8.484E-6
2.972E+3 2.970E+3 9.188E-8 -1.478E+1 8.860E-8 -2.423E-8 2.000E+1 0.000E+0 8.995E-6
2.975E+3 2.973E+3 1.804E-7 2.815E+1 1.537E-7 8.397E-8 2.000E+1 0.000E+0 9.570E-6
2.978E+3 2.975E+3 5.388E-8 5.289E+0 4.916E-8 6.591E-9 2.000E+1 0.000E+0 1.004E-5
2.981E+3 2.978E+3 1.269E-7 3.468E+1 9.923E-8 7.653E-8 2.000E+1 0.000E+0 1.056E-5
2.984E+3 2.981E+3 8.883E-8 -2.130E+0 9.144E-8 -2.503E-9 2.000E+1 0.000E+0 1.108E-5
2.987E+3 2.986E+3 -7.963E-8 4.350E+1 4.563E-8 5.792E-8 2.000E+1 0.000E+0 1.154E-5
2.990E+3 2.987E+3 -1.458E-7 -1.395E+2 -1.080E-7 -8.654E-8 2.000E+1 0.000E+0 1.186E-5
2.993E+3 2.991E+3 3.772E-8 2.966E+1 3.383E-8 1.038E-8 2.000E+1 0.000E+0 1.231E-5
2.996E+3 2.994E+3 -1.937E-7 6.964E+1 5.009E-8 1.813E-7 2.000E+1 0.000E+0 1.279E-5
2.999E+3 2.997E+3 6.529E-8 -2.698E+1 6.427E-8 -2.739E-8 2.000E+1 0.000E+0 1.327E-5
| 28,510 | Common Lisp | .l | 335 | 83.104478 | 87 | 0.642662 | afranson/Lisp-MCMC | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | b7f3ff058a83dbd074b206a01e9a9cb59310538c1e73d4f27775506a8cc2f56e | 23,320 | [
-1
] |
23,340 | recognition.lisp | drea8_wa/recognition.lisp | (in-package :wa)
(defstruct clock
minute
second
millisecond)
(defparameter current-clock (make-clock))
(defun next-clock ()
(setf (minute current-clock) (local-time:timestamp-minute (local-time:now))
(second current-clock) (local-time:timestamp-second (local-time:now))
(millisecond current-clock) (local-time:timestamp-millisecond (local-time:now))))
(defstruct wacom-event-point
abs-x
abs-y
abs-pressure
clock-time)
(defparameter wacom-event-points '())
(defun next-wacom-event-point (x y pressure)
(push (make-wacom-event-point :abs-x x
:abs-y y
:abs-pressure pressure
:clock-time current-clock)))
(defun pen-draw (event x y pressure)
(let ((color (/ pressure 700.0)))
(set-grid (round (* x .020))
(round (* y .040))
(list 0 0 color))))
;; PEN-DOWN,UP state register
(defun pen-up-event ()
"change states accordingly as tablet pen leaves surface"
nil)
(defun pen-down-event ()
"given some pressure threashold, change state as pen touches surface"
nil)
(defun classifier (domain)
;; domain = time t, # seconds since unix epoch (local-time:unix-to-timestamp n)
;; codomain = tuple (abs-x abs-y abs-pressure)
;; abs-x discrete f of t
;; abs-y discrete f of t
;; t discrete increasing
;; domain of t : t_n - t_0, nth time slice
;; clock resets every 60 minutes
;; starts from 0, incf 1 every millisecond
;; (next-clock) called every Absolute-Event
;; (next-wacom-event-point) called every Absolute-Event
;; every PEN-UP end letter data points collect and test set against classifier
;; every PEN-DOWN + ABS_PRESSURE threashold, begin letter collect data points until PEN-UP
;; want stroke to be every n*100 milliseconds
;; metrics:
;; * statistical point_n to point_n+1 slope
;; * ^ up vs down up = (pen press, Y++, pen off)
;; patterns (discrete stroke)
;; (up up left right) -> t
)
| 1,925 | Common Lisp | .lisp | 53 | 32.660377 | 92 | 0.698756 | drea8/wa | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | db89428871420fed3cc1bc6f8734b8fd31341112133184abd1d11a200aae4a96 | 23,340 | [
-1
] |
23,341 | wa.lisp | drea8_wa/wa.lisp | (defpackage :wa
(:use #:cl))
(in-package :wa)
(load "utils.lisp")
;; (load "recognition.lisp")
(load "cl-event-handler/cl-event-handler.asd")
(load "cl-evdev/cl-evdev.asd")
(mapcar
#'ql:quickload
'(local-time
cl-glut
bordeaux-threads
cl-event-handler
cl-evdev
))
(defun compile-wa-image ()
(cl-user::save-lisp-and-die "wa"))
(defun compile-wa-exec ()
(cl-user::save-lisp-and-die "wa-demo" :executable t :toplevel 'wa))
(defun set-grid (x y value)
(setf (aref grid x y) value)
(if (and (> tool-size 1) (< x grid-size) (< y grid-size))
(loop for i from x to (- 1 (+ x tool-size))
do (loop for j from y to (- 1 (+ y tool-size))
do (if (and (< i grid-size) (< j grid-size))
(setf (aref grid i j) value))))))
(defun clear-grid (size)
(setq grid (make-array (list size size)
:initial-element '(0 0 0))
blue '(0 0 1) )
(set-grid 0 0 blue)
(set-grid 0 (- grid-size 1) blue)
(set-grid (- grid-size 1) (- grid-size 1) blue)
(set-grid (- grid-size 1) 0 blue)
grid)
(defparameter evdev-device-file "/dev/input/event16")
(setq pressure 0.0
abs-x 0
abs-y 0
tool-size 1
mask nil
grid-size 300
grid (clear-grid grid-size))
(defun set-device (device-file)
(setq evdev-device-file device-file))
(defun handle-pen (event)
(with-slots (cl-evdev::value cl-evdev::type) event
(let ((axis (cadr type)))
(cond ((equal axis 'cl-evdev::ABS_PRESSURE) (setq pressure cl-evdev::value))
((equal axis 'cl-evdev::ABS_X) (setq abs-x cl-evdev::value))
((equal axis 'cl-evdev::ABS_Y) (setq abs-y cl-evdev::value)))
(next-wacom-event-point abs-x abs-y pressure)
(if (> pressure 0)
(pen-draw abs-x abs-y pressure))
)))
(defun handle-scroll (event)
(with-slots (cl-evdev::value) event
(if (= cl-evdev::value 1)
(setq tool-size (+ 1 tool-size))
(setq tool-size (- 1 tool-size)))))
(defun handle-button (event)
(with-slots (cl-evdev::name) event
(if (equal cl-evdev::name 'BTNBACK)
(clear-grid grid-size))
(with-slots (spin) mask
(setf spin (mod (+ spin 30) 360)))))
(defun process-wacom-stream ()
(cl-evdev::with-evdev-device
(in evdev-device-file)
(print `(type of ,(Type-of in)))
(cond ((typep in 'cl-evdev::RELATIVE-EVENT)
(handle-scroll in))
((typep in 'cl-evdev::ABSOLUTE-EVENT)
(handle-pen in))
((typep in 'cl-evdev::KEYBOARD-EVENT)
(handle-button in))
(t nil))
(glut:post-redisplay)))
(defclass wa-mask (glut:window)
((spin :initform 0))
(:default-initargs :pos-x 0 :pos-y 0
:width 2250 :height 2250
:mode '(:single :rgb) :title "wa"))
(defmethod glut:display-window :before ((w wa-mask))
(gl:clear-color 0 0 0 0)
(gl:matrix-mode :projection)
(gl:load-identity)
(gl:ortho 0 1 0 1 -1 1))
(defun quad (a b c d e f
g h i j k l)
(gl:with-primitive :polygon
(gl:vertex a b c)
(gl:vertex d e f)
(gl:vertex g h i)
(gl:vertex j k l)))
(defun grid-color (x y)
(setq rgb (aref grid x y))
(gl:color (first rgb) (second rgb) (third rgb))
rgb)
(defmethod glut:display ((w wa-mask))
(gl:clear :color-buffer)
(gl:disable :lighting)
(loop for x from 0 to (- grid-size 1) do
(loop for y from 0 to (- grid-size 1) do
(setq j (- grid-size (+ 1 y))
factor .0018)
(if (not (eq (grid-color x j) '(0 0 0)))
(quad (* factor x) (* factor y) 0
(* factor (+ 1 x)) (* factor y) 0
(* factor (+ 1 x)) (* factor (+ 1 y)) 0
(* factor x) (* factor (+ 1 y)) 0))
))
(gl:color 0 0 1)
(gl:flush))
(defun gl-window ()
(setq mask (make-instance 'wa-mask))
(glut:display-window mask))
(defun wa ()
(bordeaux-threads:make-thread
'process-wacom-stream :name "wacom-stream-process")
(bordeaux-threads:make-thread
'gl-window :name "gl window"))
| 3,893 | Common Lisp | .lisp | 122 | 27.459016 | 82 | 0.61194 | drea8/wa | 1 | 0 | 0 | AGPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 91d0aec1d7a0091e6a7e038488dfbb8d451904142f1ee8a6b84b79f1c46fd4aa | 23,341 | [
-1
] |
23,360 | css.lisp | ivvil_acylx-lisp/css.lisp | ;;;; css.lisp
(in-package #:acylx-lisp)
(defparameter *main-css*
'(body
:background-color "red"
:font-family "Starbirl"))
;; @font-face {
;; font-family: "Starbirl";
;; src: url(assets/fonts/Starbirl.otf);
;; }
(defparameter *font-css*
'(:font-face))
(defun cut-string-at-dot (input-string)
(if (position #\. input-string)
(subseq input-string 0 (position #\. input-string))
input-string))
(defparameter *font-dir* #P"assets/fonts/")
;; (defun get-fonts (path)
;; (dolist (file (uiop:directory-files path))
;; (let ((name (cut-string-at-dot (file-namestring file))))
;; (add-font file name))))
;; (defun get-fonts (path)
;; (loop for file in (uiop:directory-files path) collect (let ((name (cut-string-at-dot (file-namestring file))))
;; (lass:compile-and-write (add-font file name)))))
(defun get-fonts (path) "Gets all font declarations for a given folder"
(loop for file in (uiop:directory-files path) collect (let ((name (cut-string-at-dot (file-namestring file)))) (add-font file name))))
;; TODO Return lass code instead of css
;; TODO Return a string instead of an array of string
;; TODO Use local paths instead of global paths
(defun add-font (path name)
`(:font-face :font-family ,name :src (url ,(lass:resolve (namestring path)))))
| 1,311 | Common Lisp | .lisp | 31 | 40.096774 | 136 | 0.680347 | ivvil/acylx-lisp | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 79c96eacc8b441f15483fb3403dfcc8180ead9b25c4eccf9e36e58af8a2a7ed3 | 23,360 | [
-1
] |
23,361 | acylx-lisp.asd | ivvil_acylx-lisp/acylx-lisp.asd | ;;;; aluminum.asd
(asdf:defsystem #:acylx-lisp
:description "Port of my personal web page (acylx)"
:author "Iv√°n Villagrasa<[email protected]>"
:license "GPL V3"
:version "0.0.1"
:serial t
:depends-on (#:spinneret
#:parenscript
#:clack
#:lass
#:pathname-utils)
:components ((:file "package")
(:file "acylx")
(:file "css")))
| 378 | Common Lisp | .lisp | 15 | 20.8 | 53 | 0.618785 | ivvil/acylx-lisp | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | f63ccd143570bc1e00f42b86ce694993c7eed0221af0c635e2ca9c204eef9b95 | 23,361 | [
-1
] |
23,362 | acylx.lisp | ivvil_acylx-lisp/acylx.lisp | ;;;; acylx.lisp
(in-package #:acylx-lisp)
(defun acylx-head (title)
(spinneret:with-html
(:title title)
;; (:link :rel "icon" :type "image/x-icon" :href "/assets/favicon.png")
;; (:meta :name "viewport" :content "width=device-width, initial-scale=1.0")
))
(defun acylx-background ()
)
;; Seems like spinneret translastes te quote marks inside style tags to "
(defmacro display-page (&body body)
`(spinneret:with-html-string
(:doctype)
(:html
(:head
(acylx-head "SHFT.dev")
(:style (:raw (apply 'lass:compile-and-write (append (list *main-css*) (get-fonts *font-dir*)))))
(:body
,@body)))))
(with-open-file (str "test.html"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format str (display-page
(:h1 "hello world"))))
| 853 | Common Lisp | .lisp | 26 | 27.692308 | 101 | 0.627139 | ivvil/acylx-lisp | 1 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:28:28 AM (Europe/Amsterdam) | 01605c06c0e6dffc13f17d2f52d023aff4535f85687327cc6d6e69ae333344a8 | 23,362 | [
-1
] |
23,368 | Starbirl.otf | ivvil_acylx-lisp/assets/fonts/Starbirl.otf |