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 &quot; (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
Ä`OS/2B›l´Ï`cmap› ›Lcvt p Ä94fpgmû6 9Hgasp9 glyfZDÌP/RheadÖÀh2§6hhea*02‹$hmtxû R3àlocafl%÷ê4à∆maxpΩ+5P name:y^N5p¥postÏ ∆8$ÊprephF»úG`ßËêö3ö3—fHL @~ö˛fÕ¥¢ö dH~†≠~ˇˇ †≠~ˇˇˇ‰ˇ„ˇcˇc¸††À  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`att GNUhväô±€Û'T¶±æ’›Ùˇ  ,'A√TPLJIFDCBA?<;:98542/,*'%#"ª∞ßâX  ‡Z $ Ø™òçg^ Á écÂ’íeL5"%ò(&"ö`^Y.!&q#)ëãäÜV=;8.#}yxk$.(!¯ÚÔ‡«¬35'"˘—Œªπ 6>È⁄æ46L∫≤õx ˚ƒ|ˇ`Ï„î◊¿2*Ÿƒµ5”3$–6Ë4 KK∞ PX@≤"%&$"r'&!%&p,)!#$)r.#$#.$Ä523253Ä73>03p6>406r?iA@   g   g  j/%"%j!#.!#j-+*($B12$1h>62>W<D:C82=;94024i00Y00b0RK∞PX@≥"%&%"&Ä'&!%&p,)!#$)r.#$#.$Ä523253Ä73>03p6>406r?iA@   g   g  j/%"%j!#.!#j-+*($B12$1h>62>W<D:C82=;94024i00Y00b0RK∞PX@¥"%&%"&Ä'&!%&p,)!#!)#Ä.#$#.$Ä523253Ä73>03p6>406r?iA@   g   g  j/%"%j!#.!#j-+*($B12$1h>62>W<D:C82=;94024i00Y00b0RK∞PX@µ"%&%"&Ä'&!%&!~,)!#!)#Ä.#$#.$Ä523253Ä73>03p6>406r?iA@   g   g  j/%"%j!#.!#j-+*($B12$1h>62>W<D:C82=;94024i00Y00b0RK∞PX@∂"%&%"&Ä'&!%&!~,)!#!)#Ä.#$#.$Ä523253Ä73>23>~6>406r?iA@   g   g  j/%"%j!#.!#j-+*($B12$1h>62>W<D:C82=;94024i00Y00b0R@∑"%&%"&Ä'&!%&!~,)!#!)#Ä.#$#.$Ä523253Ä73>23>~6>4>64Ä?iA@   g   g  j/%"%j!#.!#j-+*($B12$1h>62>W<D:C82=;94024i00Y00b0RYYYYYAôııfifißßããVV   ıˇıˇ˚˙fiÙfiÙÏÎÊ›‹À ∑∂≥≤߱߯¨©¢üéçâáÅ~|zwvnljhda\ZPMIF?>32,*#!  ˝¸˘˜ıÙfl›‘”Œ »∆¬ø∑¥Æ´¢üãôãôóïàáÇÄzyvutsrqponmjiVhVh E+3 + &=%63!3'&+ 72"4732#'''7&#"'77"'4475432743&#63&56;353#5##73#3#''3#563&##"'4;;275737+"'56;63363#&#'#3+3253253#&#&#575##"'##543'7#63+3#3+"5732#"5%365&'#%32=4#32754';6="54347#"'47&+;2767&+"'547&+"57&+"3256325273256;327'#+&=76=4'"4#65&+"!32765$#3#3#3#732#'#&5774'5473##5#72;#'54;47'#56;2#&=433+535#5273#3#&=3274'#'32754'#"§ OÂ|˛‡¬¬ ˛±Â| ¬˛~∞åt^∆äû ˛Ù»X     < ˛p   4Xh@,,(LÉ4  ! x  #$g  ,$  \0\H$((,8T0$@˛@(† ¸† 3(LK  @H}'<!3i<L "/(# @,<) $8(D(D6 4TW9#-8<D<)$ E-˝•À ˚≈˛ ˆL( ,@((00d (   L L  $$  X  t˛‘ª¡(˛∆ÍÄ,ª¡(:ÍÄ˝¸dT‰q      * ~   '0$\ \  T%  00( 40(0(  H  (  T0*$,˛‘D (¯%$ 7:¨5Ø $˛˘ u(,∆ <Ñ]' $ †hl < $%)ö D ‡0îÏÃD<   44   8,    x,@)_M_N+!7!ê8˝®8Xê˛pêdѸ|p Ÿx@_N+!!!!»˝®UXg˝®UX X˝®XyxB@?  h  g MN+37!!!!!!7#!7!!7!!7!#3-»X,9˛‘,8˛‘˝®»˝®˛‘8,˛‘9,Xs»»∞»»˛p»˛p»»»»ê»ê»˝®»ˇ8ï@ÜK∞ PX@0pq  g _M _ N@.ÖÜ  g _M _ NY@+!!7!!7!!7!!!!#337#˝®˝D8º˝DºXº8˝Dº~˚ydddd»»êdÑ»»˛pd¸|Ëd˛ dˇú˘x 7@4h_M_N  + !!!%!!!!|%X˝Ò¸.˛‹˝®;˝®8X≥˝®8XÑÙ¸|˛ Ñdê˙àêNxsK∞ PX@(r h_M_ N@)Ä h_M_ NY@ +1!!!7!3#3!7!≈∞8˝®ºXd8dd8˙¿º˝Dx˛pd»»˛pd˛pêdp x@_N+!!»˝®UX XˇÚˇúW‹"@gW_O+!!!!Ç,8¸|·Ñ8˛‘,˛p@˛pˇÚˇúW‹)@&gW_O+!!!Vq˛‘8Ñ·¸|8, ê˘¿êp x@_N+!!»˝®UX XF»æ∞ )@&ÖÜW`P+!!!!!! Ù8˛ *˝®*˛ 8Ù+XÑ˛p˛‘,ê,ˇ‰ˇ8êê@W_O+!!<˝®TX»XFÙæÑ@W_O+!!ܢ¿8@Ùêêê@_N+)!X˝®8Xêˇú˘x#@ hMN+ !!!|%X˝Ò¸.˛‹˝®ÑÙ¸|˛ Ñïx%@"_M_N+!!!¸‡U Â≈¯0≈Ë˝®Ë˙àxçx@_MN+!!!Ş 8L≈˝®Ëê˙àïx )@&g_M_N+!!!7!!!êx8¯0~x˙à8–˙àê˛pÑdê¸|ïx /@,g_M_N +1!7!!7!!8x˙à8x˙à8–≈êdêdê˙à*2x #@ hMN+!!!3#!!≈XcºcXcd8d*˝®*˙Ïx˝Dº˝D˛p˛‘,ïx /@,g_M_N +1!7!!!!8x˙à–8˙àx~êdÑ˛pd¸|ïx /@,g_M_N  +!7!!!!ê ¸‡˝b≈–8˙àx~êd˛ x˛pd¸|ˇú˘x )@&g_MN + !!7!!˛‹˝®“;˙÷84˝ÒÙ˛ Ñdê¸|ïx /@,g_M_N  +!!!7!!¸‡ ¸ö ¸‡˝b≈–≈Ëd˛ d˛ x˙àïx /@,g_M_N  +!!!7!!¸‡ ˙ 8x˙à–≈Ëd¸|êdÑ˙àË@g_N+)!7!!X˝®8X ˝®8Xê‡êˇ‰ˇ8Ë&@#ÄÑW_O+!!7!!<˝®TX ˝®8X»X‡êˇÚˇúW‹"@gW_O+!!!!Ç,8¸|·Ñ8˛‘,˛p@˛p»È∞"@gW_O+%!!7!!\˘¿8@˘¿9@»ê»êˇÚˇúW‹)@&gW_O+!!!Vq˛‘8Ñ·¸|8, ê˘¿êïx 8@5g_M_N  +!!!!7ê8˝®8U8–¯08xê˛pêXê¸|êdïx )@&g_M_N+!!!!!7!êx8¯0≈–˙Ï8º¸‡ê˛px¸|êdïx +@(g_MN  +!!!!!¸‡+ ª≈˝®*¸‡*˝®≈˲‘º˙à,˛‘xïx /@,g_M_N  +!!!7!!¸‡ ¸ö ¸‡˝b≈–≈Ëd˛ d˛ x˙àïx@_M_N+!!!!êx8¯0≈–8˙àê˛px˛p˘x%@"_M_N+!! !/¸∂Uıt˛s¯î≈Ë˝®Ë˙àxïx )@&g_M_N+!!!!!!êx8¯0≈–8˙àx8˙àê˛px˛pd˛pïx )@&g_MN +!!!!ï8˙àx8˙àF˝®≈x˛pd˛p˛ xïx /@,g_M_N +!!7!!!ï8˙àU ˝D8~¯0≈x˛p˝®dê¸|xïx '@$hMN +!!!!!ûF˝®≈XG GX≈˝®FÙ˛ x˛ Ù˙àÙx@MN+)!X˝®≈Xxïx"@ÄM`N+)!!!–¯0pX8 çX ˛pˢx -@* LhMN +!!!!!ûF˝®≈XGÆX˛q ˝®êÙ˛ x˛ Ù˝D˝DÙ@x(@%ÄM`N+1!!!≈Xç 8Xpx¸긇ïx @_MN+)#!#!!–˝®çdç˝®çdç˝®≈–˸˸xïx )@&_M`N +!!3!!Âç˝®≈çdçX≈˙Ïç˸x¸Ë˙àËïx%@"_M_N+!!!¸‡U Â≈¯0≈Ë˝®Ë˙àxïx )@&g_MN  +!!!!¸‡ ü˙àF˝®≈ËdÙ¸|˛ xˇ8ïxhK∞ PX@%rq_M`N@%ÄÜ_M`NY@ +!37!3!!7!¸‡UdXdÂ≈˝D˝®˝D≈Ë˝®»»Ë˙à»»xïx -@*g_MN  +!!#!!!¸‡ ü÷ê˝®ê˝∂F˝®≈ËdÙ¸|˛ Ù˛ xïx /@,g_M_N +1!7!!!!8x˙à–8˙àx~êdÑ˛pd¸|bïx ,@)Ä_MN +!!!#!Â+˝®c–c˝®+dç˝®ç˲‘º˝D,¸Ëïx@M`N+!!!!≈Xç çX≈¯0x¸Ë˙àa˘x!@M`N+ !!!ÖX˛s¯¯XêË˙àx¸ïx @M`N+!3!3!!≈XçdçXçdçX≈¯0x¸˸Ë˙àˇú˘x (@% LgMN+!!!!!!L˝≈˛„˝®é…Xê;X˛q ˝®Ù˛ ºº˛ Ù˝D˝Da˘x $@!W_MN+!!!!!!Q+%X˝Ò˛pF˝®F˛p˛ÔXÑÙ¸|˛ ÙÑïx )@&g_M_N+!!!7!!!êx8¯0~x˙à8–˙àê˛pÑdê¸|ˇÚˇúW‹"@gW_O+!!!!Ç,8¸|·Ñ8˛‘,˛p@˛pa4x@hMN+!!!!Q—˝®ò¸.˛ÔXѸ|ÙÑˇÚˇúW‹)@&gW_O+!!!Vq˛‘8Ñ·¸|8, ê˘¿êp x ±dD@W_O+±D!!»˝®UX Xê ±dD@W_O+±D)!–¯08–êp x ±dD@W_O+±D!!»˝®UX Xïx +@(g_MN  +!!!!!¸‡+ ª≈˝®*¸‡*˝®≈˲‘º˙à,˛‘xïx /@,g_M_N  +!!!7!!¸‡ ¸ö ¸‡˝b≈–≈Ëd˛ d˛ x˙àïx@_M_N+!!!!êx8¯0≈–8˙àê˛px˛p˘x%@"_M_N+!! !/¸∂Uıt˛s¯î≈Ë˝®Ë˙àxïx )@&g_M_N+!!!!!!êx8¯0≈–8˙àx8˙àê˛px˛pd˛pïx )@&g_MN +!!!!ï8˙àx8˙àF˝®≈x˛pd˛p˛ xïx /@,g_M_N +!!7!!!ï8˙àU ˝D8~¯0≈x˛p˝®dê¸|xïx '@$hMN +!!!!!ûF˝®≈XG GX≈˝®FÙ˛ x˛ Ù˙àÙx@MN+)!X˝®≈Xxïx"@ÄM`N+)!!!–¯0pX8 çX ˛pˢx -@* LhMN +!!!!!ûF˝®≈XGÆX˛q ˝®êÙ˛ x˛ Ù˝D˝DÙ@x(@%ÄM`N+1!!!≈Xç 8Xpx¸긇ïx @_MN+)#!#!!–˝®çdç˝®çdç˝®≈–˸˸xïx )@&_M`N +!!3!!Âç˝®≈çdçX≈˙Ïç˸x¸Ë˙àËïx%@"_M_N+!!!¸‡U Â≈¯0≈Ë˝®Ë˙àxïx )@&g_MN  +!!!!¸‡ ü˙àF˝®≈ËdÙ¸|˛ xˇ8ïxhK∞ PX@%rq_M`N@%ÄÜ_M`NY@ +!37!3!!7!¸‡UdXdÂ≈˝D˝®˝D≈Ë˝®»»Ë˙à»»xïx -@*g_MN  +!!#!!!¸‡ ü÷ê˝®ê˝∂F˝®≈ËdÙ¸|˛ Ù˛ xïx /@,g_M_N +1!7!!!!8x˙à–8˙àx~êdÑ˛pd¸|bïx ,@)Ä_MN +!!!#!Â+˝®c–c˝®+dç˝®ç˲‘º˝D,¸Ëïx@M`N+!!!!≈Xç çX≈¯0x¸Ë˙àa˘x!@M`N+ !!!ÖX˛s¯¯XêË˙àx¸ïx @M`N+!3!3!!≈XçdçXçdçX≈¯0x¸˸Ë˙àˇú˘x (@% LgMN+!!!!!!L˝≈˛„˝®é…Xê;X˛q ˝®Ù˛ ºº˛ Ù˝D˝Da˘x $@!W_MN+!!!!!!Q+%X˝Ò˛pF˝®F˛p˛ÔXÑÙ¸|˛ ÙÑïx )@&g_M_N+!!!7!!!êx8¯0~x˙à8–˙àê˛pÑdê¸|Fˇú‹ ,@)ggW_O+!!#3!!J,8¸|T»8»UÑ8˛‘,˛pXêX˛px@MN+)!X˝®≈XxˇÚˇú ‹ 3@0ggW_O +!!3#!Vq˛‘8ÑU»8»T¸|8, ê˝®˛p˝®êFÙæÑ ±dD@W_O+±D!!ܢ¿8@Ùêî£∏Í_<ı÷·Yä÷Ì'kˇúˇ8˘@¥˛^fi4ˇúˇ;˘b‹¸¸ºxp444ˇú4ºpˡÚˡÚºp§Fºˇ‰§Fº4ˇú4∞ç444*444ˇú44ººˇ‰ˡÚ§ˡÚ4444444444º44444444444b44a44ˇú4a4ˡÚ4aˡÚºp4ºp44444444º44444444444b44a44ˇú4a4∞Fº∞ˇÚ§F````é≤Ü *BjñƇ˙  . X Ç ¢ ‘  6 h û Œ  < ` ä ≤ ⁄  @ r ¶ fi  0 b ê ƒ ˆ4lîæJ¢⁄ @då∏ Rz†ÃÏ *^ñºËH|Æ∆Ï$Lv®“Z탯Dp®ÿ <Tä©b-äÁç' ä l l | *ä ¥ rƒ 6 4F z ÄÄ *Typeface by Chequered Ink. © 2018. All Rights ReservedStarbirlRegularStarbirl:Version 1.00StarbirlVersion 1.00;April 6, 2018;FontCreator 11.5.0.2421 64-bitStarbirlStarbirl by Chequered Ink.NALThis font was created using FontCreator 11.5 from High-Logic.comhttp://chequered.ink/ˇ'ñb  !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`aˇˇêêxxxxxx∞, ∞UXEY K∏QK∞SZX∞4∞(Y`f äUX∞%aπcc#b!!∞Y∞C#D≤C`B-∞,∞ `f-∞,#!#!-∞, d≥BC∞C ``B±CB±%C∞CTx ∞ #∞CCad∞Px≤C`B∞!e!∞CC≤B ∞C#B≤C`B#∞PXeY≤C`B-∞,∞+∞CX#!#!∞CC#∞PXeY d ∞¿P∞&Z≤( CEcE∞EX!∞%YR[X!#!äX ∞PPX!∞@Y ∞8PX!∞8YY ± CEcEad∞(PX!± CEcE ∞0PX!∞0Y ∞¿PX f ääa ∞ PX` ∞ PX!∞ ` ∞6PX!∞6``YYY∞%∞ Cc∞RX∞K∞ PX!∞ CK∞PX!∞Ka∏c∞ Cc∏bYYdaY∞+YY#∞PXeYY d∞C#BY-∞, E ∞%ad ∞CPX∞#B∞#B!!Y∞`-∞,#!#!∞+ d±bB ∞#B∞EX± CEc± C∞`Ec∞*! ∞C ä ä∞+±0%∞&QX`PaRYX#Y!Y ∞@SX∞+!∞@Y#∞PXeY-∞,∞ C+≤C`B-∞,∞ #B# ∞#Ba∞bf∞c∞`∞*-∞ , E ∞Cc∏b ∞PX∞@`Yf∞c`D∞`-∞ ,≤ CEB*!≤C`B-∞ ,∞C#D≤C`B-∞ , E ∞+#∞C∞%` Eä#a d ∞ PX!∞∞0PX∞ ∞@YY#∞PXeY∞%#aDD∞`-∞ , E ∞+#∞C∞%` Eä#a d∞$PX∞∞@Y#∞PXeY∞%#aDD∞`-∞, ∞#B≥ EPX!#!Y*!-∞,±E∞daD-∞,∞` ∞CJ∞PX ∞#BY∞CJ∞RX ∞#BY-∞, ∞bf∞c ∏cä#a∞C` ä` ∞#B#-∞,KTX±dDY$∞ e#x-∞,KQXKSX±dDY!Y$∞e#x-∞,±CUX±C∞aB∞+Y∞C∞%B±%B±%B∞# ∞%PX±C`∞%Bää ä#a∞*!#∞a ä#a∞*!±C`∞%B∞%a∞*!Y∞CG∞CG`∞b ∞PX∞@`Yf∞c ∞Cc∏b ∞PX∞@`Yf∞c`±#D∞C∞>≤C`B-∞,±ETX∞#B E∞#B∞ #∞`B ∞#B `∞a∑BBBä` ∞C`∞#B±+∞ã+"Y-∞,±+-∞,±+-∞,±+-∞,±+-∞,±+-∞,±+-∞,±+-∞,±+-∞,±+-∞,± +-∞+,# ∞bf∞c∞`KTX# .∞]!!Y-∞,,# ∞bf∞c∞`KTX# .∞q!!Y-∞-,# ∞bf∞c∞&`KTX# .∞r!!Y-∞ ,∞+±ETX∞#B E∞#B∞ #∞`B `∞aµBBä`±+∞ã+"Y-∞!,± +-∞",± +-∞#,± +-∞$,± +-∞%,± +-∞&,± +-∞',± +-∞(,± +-∞),± +-∞*,± +-∞., <∞`-∞/, `∞` C#∞`C∞%a∞`∞.*!-∞0,∞/+∞/*-∞1, G ∞Cc∏b ∞PX∞@`Yf∞c`#a8# äUX G ∞Cc∏b ∞PX∞@`Yf∞c`#a8!Y-∞2,±ETX±EB∞∞1*±EX0Y"Y-∞3,∞+±ETX±EB∞∞1*±EX0Y"Y-∞4, 5∞`-∞5,±EB∞Ec∏b ∞PX∞@`Yf∞c∞+∞Cc∏b ∞PX∞@`Yf∞c∞+∞¥D>#8±4*!-∞6, < G ∞Cc∏b ∞PX∞@`Yf∞c`∞Ca8-∞7,.<-∞8, < G ∞Cc∏b ∞PX∞@`Yf∞c`∞Ca∞Cc8-∞9,±% . G∞#B∞%IääG#G#a Xb!Y∞#B≤8*-∞:,∞∞#B∞%∞%G#G#a± B∞ C+eä.# <ä8-∞;,∞∞#B∞%∞% .G#G#a ∞#B± B∞ C+ ∞`PX ∞@QX≥  ≥&YBB# ∞ C ä#G#G#a#F`∞C∞b ∞PX∞@`Yf∞c` ∞+ ääa ∞C`d#∞CadPX∞Ca∞C`Y∞%∞b ∞PX∞@`Yf∞ca# ∞&#Fa8#∞ CF∞%∞ CG#G#a` ∞C∞b ∞PX∞@`Yf∞c`# ∞+#∞C`∞+∞%a∞%∞b ∞PX∞@`Yf∞c∞&a ∞%`d#∞%`dPX!#!Y# ∞&#Fa8Y-∞<,∞∞#B ∞& .G#G#a#<8-∞=,∞∞#B ∞ #B F#G∞+#a8-∞>,∞∞#B∞%∞%G#G#a∞TX. <#!∞%∞%G#G#a ∞%∞%G#G#a∞%∞%I∞%aπcc# Xb!Yc∏b ∞PX∞@`Yf∞c`#.# <ä8#!Y-∞?,∞∞#B ∞ C .G#G#a `∞ `f∞b ∞PX∞@`Yf∞c# <ä8-∞@,# .F∞%F∞CXPRYX <Y.±0+-∞A,# .F∞%F∞CXRPYX <Y.±0+-∞B,# .F∞%F∞CXPRYX <Y# .F∞%F∞CXRPYX <Y.±0+-∞C,∞:+# .F∞%F∞CXPRYX <Y.±0+-∞D,∞;+ä <∞#Bä8# .F∞%F∞CXPRYX <Y.±0+∞C.∞0+-∞E,∞∞%∞& F#Ga∞ #B.G#G#a∞ C+# < .#8±0+-∞F,± %B∞∞%∞% .G#G#a ∞#B± B∞ C+ ∞`PX ∞@QX≥  ≥&YBB# G∞C∞b ∞PX∞@`Yf∞c` ∞+ ääa ∞C`d#∞CadPX∞Ca∞C`Y∞%∞b ∞PX∞@`Yf∞ca∞%Fa8# <#8! F#G∞+#a8!Y±0+-∞G,±:+.±0+-∞H,±;+!# <∞#B#8±0+∞C.∞0+-∞I,∞ G∞#B≤.∞6*-∞J,∞ G∞#B≤.∞6*-∞K,±∞7*-∞L,∞9*-∞M,∞E# . Fä#a8±0+-∞N,∞ #B∞M+-∞O,≤F+-∞P,≤F+-∞Q,≤F+-∞R,≤F+-∞S,≤G+-∞T,≤G+-∞U,≤G+-∞V,≤G+-∞W,≥C+-∞X,≥C+-∞Y,≥C+-∞Z,≥C+-∞[,≥C+-∞\,≥C+-∞],≥C+-∞^,≥C+-∞_,≤E+-∞`,≤E+-∞a,≤E+-∞b,≤E+-∞c,≤H+-∞d,≤H+-∞e,≤H+-∞f,≤H+-∞g,≥D+-∞h,≥D+-∞i,≥D+-∞j,≥D+-∞k,≥D+-∞l,≥D+-∞m,≥D+-∞n,≥D+-∞o,±<+.±0+-∞p,±<+∞@+-∞q,±<+∞A+-∞r,∞±<+∞B+-∞s,±<+∞@+-∞t,±<+∞A+-∞u,∞±<+∞B+-∞v,±=+.±0+-∞w,±=+∞@+-∞x,±=+∞A+-∞y,±=+∞B+-∞z,±=+∞@+-∞{,±=+∞A+-∞|,±=+∞B+-∞},±>+.±0+-∞~,±>+∞@+-∞,±>+∞A+-∞Ä,±>+∞B+-∞Å,±>+∞@+-∞Ç,±>+∞A+-∞É,±>+∞B+-∞Ñ,±?+.±0+-∞Ö,±?+∞@+-∞Ü,±?+∞A+-∞á,±?+∞B+-∞à,±?+∞@+-∞â,±?+∞A+-∞ä,±?+∞B+-∞ã,≤ EPX∞≤EX#!!YYB+∞e∞$Px±EX0Y-K∏»RX±éY∞πcp±B≤*±B≥  *±B≥ *±B∫@ *± B∫@ *πD±$àQX∞@àXπdD±(àQX∏àXπDY±'àQX∫Ä@àcTXπDYYYYY≥*∏ˇÖ∞ç±D≥dDD
18,440
Common Lisp
.l
53
346.641509
6,432
0.212476
ivvil/acylx-lisp
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f7d93e833b567e111eb1a7047295036a26f425fc8786f815f94e9eb06545aa92
23,368
[ -1 ]
23,383
package.lisp
pocket7878_LisPod/package.lisp
;;; -* Mode: Lisp; Package: COMMON-LISP-USER -*- ;;; Lispod: A simple Podcast manager written in Common Lisp. ;;; Copyright (C) 2010 Masato Sogame ([email protected]) ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <http://www.gnu.org/licenses/>. (cl:defpackage :lispod (:use :clim :clim-lisp :drakma :cl-ppcre) (:export #:lispod))
961
Common Lisp
.lisp
19
49.263158
76
0.706383
pocket7878/LisPod
1
0
2
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9990849a4780780591303e13df0f72dfcf7b5d7f560532cdbfe8d3ce5c57f1cf
23,383
[ -1 ]
23,384
lispod.lisp
pocket7878_LisPod/lispod.lisp
;;; -* Mode: Lisp; Package: COMMON-LISP-USER -*- ;;; Lispod: A simple Podcast manager written in Common Lisp. ;;; Copyright (C) 2010 Masato Sogame ([email protected]) ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <http://www.gnu.org/licenses/>. (cl:in-package :lispod) (defun html-tag-remover (str) (regex-replace-all "<.*?>" str "")) (defun get-specific-length-of-list (n lst) (labels ((%fn (n lst acc) (if (or (zerop n) (null lst)) acc (%fn (1- n) (cdr lst) (cons (car lst) acc))))) (nreverse (%fn n lst nil)))) ;;Podcast class (defclass Podcast () ((name :initarg :name :initform "" :accessor name) (url :initarg :url :initform "" :accessor url))) (defmethod get-cast-file-url-list ((cast Podcast)) (mapcar #'(lambda (x) (multiple-value-bind (matchstring groups) (scan-to-strings "<enclosure.*?url=\"(.*?)\".*?/>" x) (declare (ignore matchstring)) (aref groups 0))) (all-matches-as-strings "<enclosure.*?/>" (http-request (url cast))))) (defmethod get-latest-cast ((p Podcast)) (car (get-cast-file-url-list p))) ;;Container class of podcast (defclass Podcast-container () ((podcasts :initarg :podcasts :initform nil :accessor podcasts))) ;;Constructor with rc file (defun make-podcast-container () (let ((rc-file-contents (with-open-file (fp "~/.lispod" :if-does-not-exist :create :direction :input) (read fp nil))) (new-instance (make-instance 'Podcast-container))) (loop for cast-data in rc-file-contents do (add-podcast new-instance (make-instance 'Podcast :name (car cast-data) :url (cadr cast-data)))) new-instance)) (defmethod add-podcast ((pc Podcast-container) (pd Podcast)) (setf (podcasts pc) (cons pd (podcasts pc)))) (defmethod remove-podcast ((pc Podcast-container) (pd Podcast)) (setf (podcasts pc) (remove-if #'(lambda (x) (eq pd x)) (podcasts pc)))) (defmethod get-all-cast-file-url-list ((pc Podcast-container)) (mapcar #'(lambda (x) (get-cast-file-url-list x)) (podcasts pc))) (defmethod get-all-latest-cast-file-url-list ((pc Podcast-container)) (mapcar #'(lambda (x) (get-latest-cast x)) (podcasts pc))) ;;Progress bar (defclass progress-bar () ((total :initform 0 :initarg :total :accessor total) (current :initform 0 :initarg :current :accessor current))) (defgeneric print-bar (pg stream)) (defmethod print-bar ((pg progress-bar) stream) (with-slots (current total) pg (format stream "~5,1f%: ~A>" (float (* 100 (/ current total))) (make-string (* 4 (floor (* 100 (/ current total)) 10)) :initial-element #\=)))) (defgeneric set-value (pg value)) (defmethod set-value ((pg progress-bar) value) (setf (current pg) value)) (defgeneric set-total (pg value)) (defmethod set-total ((pg progress-bar) value) (setf (total pg) value)) ;;View for list of podcast (defclass podcast-list-view (view) ()) (defparameter *podcast-list-view* (make-instance 'podcast-list-view)) ;;View for podcast cast list or some (defclass podcast-view (view) ((%podcast :initarg :podcast :reader podcast) (%num :initarg :num :reader num))) ;;View for downloading progress (defclass download-view (view) ((%url :initarg :url :reader url) (%file-path :initarg :file-path :reader file-path))) (define-application-frame lispod-main () ((my-podcast :initform (make-podcast-container) :accessor my-podcast)) (:menu-bar menubar-command-table) (:pointer-documentation t) (:panes (app :application :height 400 :width 600 :display-function 'display-application :default-view *podcast-list-view*) (int :interactor :height 200 :width 600)) (:layouts (default (vertically () app int)))) (defgeneric display-pane-with-view (frame pane view)) (defun display-application (frame pane) (display-pane-with-view frame pane (stream-default-view pane))) (defmethod display-pane-with-view (frame pane (view podcast-list-view)) (let ((podcasts (podcasts (my-podcast frame)))) (loop for cast in podcasts do (with-output-as-presentation (pane cast 'Podcast) (with-output-as-presentation (pane (name cast) 'name-of-podcast) (format pane "~A" (name cast))) (format pane "") (with-output-as-presentation (pane (url cast) 'url) (format pane " ~A~%" (url cast))))))) (defmethod display-pane-with-view (frame pane (view podcast-view)) (let ((podcast (podcast view)) (num (num view))) (with-output-as-presentation (pane (name podcast) 'name-of-podcast) (format pane "Name: ~A~%" (name podcast))) (loop for url in (get-specific-length-of-list num (get-cast-file-url-list podcast)) do (with-output-as-presentation (pane url 'url) (format pane "~A~%" url))))) (defmethod display-pane-with-view (frame pane (view download-view)) (let ((url (url view)) (file-path (file-path view))) (with-open-file (out file-path :direction :output :if-exists :overwrite :if-does-not-exist :create :element-type '(unsigned-byte 8)) (let ((v (make-array 2048 :element-type '(unsigned-byte 8))) (total-size nil) (downloaded-byte 0) (pgbar (make-instance 'progress-bar))) (multiple-value-bind (input num headers) (http-request url :want-stream t) (declare (ignore num)) (setq total-size (parse-integer (header-value :content-length headers))) (when (not (null total-size)) (set-total pgbar total-size)) (loop for size = (read-sequence v input) until (zerop size) do (progn (when (not (null total-size)) (incf downloaded-byte size) (set-value pgbar downloaded-byte) (window-clear (get-frame-pane frame 'app)) (format pane "Downloading...~%") (format pane "URL: ~A~%" url) (format pane "Save To: ~A~%" file-path) (format pane "~A~%" (print-bar pgbar nil)) (finish-output)) (write-sequence v out :end size)))))))) (defun lispod (&key (new-process nil) (process-name "LisPod")) (let ((app-frame (make-application-frame 'lispod-main))) (flet ((run () (run-frame-top-level app-frame))) (if new-process (clim-sys:make-process #'run :name process-name) (run))))) (define-lispod-main-command (com-quit :name t :keystroke (#\q :meta)) () (when (not (null (podcasts (my-podcast *application-frame*)))) (with-open-file (out "~/.lispod" :direction :output :if-exists :supersede :if-does-not-exist :create) (format out "~A" (generate-pretty-print-list (my-podcast *application-frame*))))) (frame-exit *application-frame*)) (define-lispod-main-command (com-change-url :name t) ((pd 'Podcast) (url 'url)) (setf (url pd) url)) (define-lispod-main-command (com-change-name :name t) ((pd 'Podcast) (name 'name-of-podcast)) (setf (name pd) name)) (define-presentation-type name-of-podcast () :inherit-from 'string) (define-presentation-type url () :inherit-from 'string) (define-presentation-type file-path () :inherit-from 'pathname) (define-lispod-main-command (com-add-podcast :name t) ((name 'name-of-podcast) (url 'url)) (add-podcast (my-podcast *application-frame*) (make-instance 'Podcast :name name :url url))) (define-lispod-main-command (com-remove-podcast :name t) ((pd 'Podcast :gesture :select)) (remove-podcast (my-podcast *application-frame*) pd)) (define-lispod-main-command (com-show-all :name t) () (setf (stream-default-view *standard-output*) *podcast-list-view*)) (define-lispod-main-command (com-show-podcast :name t) ((pd 'Podcast) (num 'integer)) (setf (stream-default-view *standard-output*) (make-instance 'podcast-view :podcast pd :num num))) (define-lispod-main-command (com-download :name t) ((url 'url) (file-name 'file-path :default (user-homedir-pathname) :insert-default t)) (setf (stream-default-view *standard-output*) (make-instance 'download-view :url url :file-path file-name))) (define-lispod-main-command (com-save-podcast-list :name t) ((file-path 'file-path :default (user-homedir-pathname) :insert-default t)) (when (not (null (podcasts (my-podcast *application-frame*)))) (with-open-file (out file-path :direction :output :if-exists :overwrite :if-does-not-exist :create) (format out "~A" (generate-pretty-print-list (my-podcast *application-frame*)))))) (defmethod equal-data ((pd1 Podcast) (pd2 Podcast)) (and (string= (name pd1) (name pd2)) (string= (url pd1) (url pd2)))) (define-lispod-main-command (com-load-podcast-list :name t) ((file-path 'file-path :default (user-homedir-pathname) :insert-default t)) (let ((rc-file-contents (with-open-file (fp file-path :direction :input) (when fp (read fp nil))))) (setf (podcasts (my-podcast *application-frame*)) (remove-duplicates (append (mapcar #'(lambda (cast-data) (make-instance 'Podcast :name (car cast-data) :url (cadr cast-data))) rc-file-contents) (podcasts (my-podcast *application-frame*))) :test #'equal-data)))) ;;Generate pretty-print list of podcast (defmethod generate-pretty-print-list ((pd Podcast-container)) (reverse (loop for cast in (podcasts pd) collect (list (write-to-string (name cast)) (write-to-string (url cast)))))) (make-command-table 'lispod-file-menu :errorp nil :menu '(("Save" :command com-save-podcast-list) ("Load" :command com-load-podcast-list) ("Quit" :command com-quit))) (make-command-table 'lispod-edit-menu :errorp nil :menu '(("Change Name" :command com-change-name) ("Change URL" :command com-change-url) ("Add Podcast" :command com-add-podcast) ("Remove Podcast" :command com-remove-podcast))) (make-command-table 'menubar-command-table :errorp nil :menu '(("File" :menu lispod-file-menu) ("Edit" :menu lispod-edit-menu)))
10,658
Common Lisp
.lisp
256
36.933594
93
0.665636
pocket7878/LisPod
1
0
2
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1db46d1cbc9d0097ecd444715fc82747e3c92b48d922388b383fb8e0f11e16ee
23,384
[ -1 ]
23,385
lispod.asd
pocket7878_LisPod/lispod.asd
;;; -* Mode: Lisp; Package: COMMON-LISP-USER -*- ;;; Lispod: A simple Podcast manager written in Common Lisp. ;;; Copyright (C) 2010 Masato Sogame ([email protected]) ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <http://www.gnu.org/licenses/>. (asdf:defsystem :lispod :name "lispod" :version "1.1" :maintainer "Masato Sogame" :author "Masato Sogame <[email protected]>" :description "Podcast manager" :depends-on (:mcclim :drakma :cl-ppcre) :serial t :components ((:file "package") (:file "lispod")))
1,155
Common Lisp
.asd
27
40.925926
76
0.705151
pocket7878/LisPod
1
0
2
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6967bd9bf3ed09a9414dafd71113e2067cbe51cb39864ec960df907994ba3ada
23,385
[ -1 ]
23,403
composite.lisp
innaky_lisp-scripts/composite.lisp
(defparameter *water* "/home/innaky/water.png") (defparameter *external-dir* "/home/innaky/output-dir/") (defmacro cc-s (&rest strs) "Simple macro for concatenate strings." `(concatenate 'string ,@strs)) (defun gnu (bin &rest args) "A beautiful function for connect lisp with the OS. For more variants check the documentation of Mr. François-René Rideau: https://github.com/fare/inferior-shell#exported-functionality" (inferior-shell:run/lines (list* bin args))) (defun output-dir () (gnu "mkdir" *water*)) (defun directory-p (filepath) (pathnamep (cl-fad:directory-exists-p filepath))) (defun path-to-str (lst-true-paths) "Tranform from true path to string path" (mapcar #'(lambda (filepath) (namestring filepath)) lst-true-paths)) (defun only-paths (lst-true-paths) "Filter the true paths, return a list of directories true paths." (remove-if-not #'directory-p lst-true-paths)) (defun get-insides (lst-directory-str-path) "List the files inside of the second directories level." (mapcar #'(lambda (directory-str-path) (path-to-str (cl-fad:list-directory directory-str-path))) lst-directory-str-path)) (defun get-filename (str-filepath) "From the str path, get the filename." (car (last (cl-ppcre:split "/" str-filepath)))) (defun get-base-dirname (str-filepath) "From the str path, get the directory name of second level." (second (reverse (cl-ppcre:split "/" str-filepath)))) (defun file-exists-p (filepath) "Check if a file exists." (pathnamep (probe-file filepath))) (defun make-base-dir (str-filepath) "Make the external directory for save the transformated images." (let ((file-output (cc-s *external-dir* (get-base-dirname str-filepath)))) (if (file-exists-p file-output) (format t "Processing the file: ~A~%" str-filepath) (gnu "mkdir" "-p" (cc-s *external-dir* (get-base-dirname str-filepath)))))) (defun out-file-generator (str-filepath) "Str path of the external file, necessary for `composite'." (let ((base-dir (get-base-dirname str-filepath)) (filename (get-filename str-filepath))) (cc-s *external-dir* base-dir "/" filename))) (defun small-composite (str-filepath) "Make the external directory for save the transformated images and run `composite' for the file." (make-base-dir str-filepath) (gnu "composite" *water* str-filepath (out-file-generator str-filepath))) (defun lst-composite-run (lst-str-paths) "Apply `composite' over a list of files of a directory." (mapc #'(lambda (str-path) (small-composite str-path)) lst-str-paths)) (defun composite-run (list-of-lst-str-paths) "Apply composite over all images in the all directories." (mapc #'(lambda (lst-str-paths) (lst-composite-run lst-str-paths)) list-of-lst-str-paths))
2,779
Common Lisp
.lisp
67
38.492537
88
0.724304
innaky/lisp-scripts
1
0
1
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2e1ced64a578806b40b03b91ea3edb74b847edd0d5a0e0bd99c017b9deccc345
23,403
[ -1 ]
23,404
hide.lisp
innaky_lisp-scripts/hide.lisp
(ql:quickload '(cl-fad cl-ppcre)) (defparameter *characters* (concatenate 'string "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789")) (defun random-elem (lst) (aref lst (random (length lst)))) (defun random-string (&optional (length 15)) "Build a random string, the default is a string with 15 letters" (if (equal length 0) nil (cons (random-elem *characters*) (random-string (- length 1))))) (defun concatenate-elems-of-lst (lst-of-strings) "Receive a list of strings and return the words concatenated in a string." (if (equal nil lst-of-strings) nil (concatenate 'string (car lst-of-strings) (concatenate-elems-of-lst (cdr lst-of-strings))))) (defun base-path (one-file-path) "Build the base-path of the `one-file-path'." (reverse (cdr (reverse (cdr (mapcar #'(lambda (elem) (concatenate 'string "/" elem)) (cl-ppcre:split "/" one-file-path))))))) (defun hide (db-file directory-to-hide) (with-open-file (stream db-file :direction :output :if-does-not-exist :create :if-exists :supersede) (mapc #'(lambda (one-file-path) (let ((random-name (concatenate 'string (concatenate-elems-of-lst (base-path (namestring one-file-path))) "/" (random-string)))) (format stream "~A~%" (concatenate 'string (namestring one-file-path) " " random-name)) (rename-file one-file-path random-name))) (cl-fad:list-directory directory-to-hide)))) (defparameter *files* nil) (defun charge (db-file) (with-open-file (stream db-file) (when stream (loop for line = (read-line stream nil) while line do (push line *files*))))) (defun unhide () (mapcar #'(lambda (line) (let ((line-file (cl-ppcre:split " " line))) (rename-file (cadr line-file) (car line-file)))) *files*))
1,865
Common Lisp
.lisp
52
31.096154
76
0.660754
innaky/lisp-scripts
1
0
1
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
bd4daa83a623045a55dc473534f649079746863b23d21c014de608d463541898
23,404
[ -1 ]
23,422
run-date-tests.lisp
namoamitabha_study-lisp-unit/run-date-tests.lisp
(load "lisp-unit") (load "date") (load "date-tests") ;; (in-package :date-tests) ;; (run-tests) (lisp-unit:run-tests :all :date-tests)
140
Common Lisp
.lisp
6
21.5
38
0.674419
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
415d8d1ea3cc626db6468eee76bd5e997299c1d66bc6c7b8a57ca16d4c9be637
23,422
[ -1 ]
23,423
my-max.lisp
namoamitabha_study-lisp-unit/my-max.lisp
(defun my-max (a b) (if (> a b) a b))
40
Common Lisp
.lisp
2
18
19
0.473684
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a9bd29fac8affd047853fb375fc8aeb115108c87004802d8c65fb0a6b3ccc53c
23,423
[ 488333 ]
23,424
date.lisp
namoamitabha_study-lisp-unit/date.lisp
(defpackage :date (:use :common-lisp) (:export :date->string :string->date)) (in-package :date) (defun date->string (date) (print date)) (defun string->date (string) (print string))
193
Common Lisp
.lisp
8
21.75
40
0.692308
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
782eadadc556c9b0f53cd850aaff611427639b3f3a6763ff666adc4a735ecab1
23,424
[ -1 ]
23,425
tag-tests.lisp
namoamitabha_study-lisp-unit/tag-tests.lisp
(defun add-integer (integer1 integer2) "Add 2 integer numbers" (check-type integer1 integer) (check-type integer2 integer) (+ integer1 integer2)) (defun subtract-integer (integer1 integer2) "Subtract 2 integer numbers" (check-type integer1 integer) (check-type integer2 integer) (- integer1 integer2)) (define-test add-integer "Test add-integer for values and errors." (:tag :add :integer) (assert-eql 3 (add-integer 1 2)) (assert-error 'type-error (add-integer 1.0 2)) (assert-error 'type-error (add-integer 1 2.0))) (define-test subtract-integer "Test subtract-integer for values and errors." (:tag :subtract :integer) (assert-eql 1 (subtract-integer 3 2)) (assert-error 'type-error (subtract-integer 3.0 2)) (assert-error 'type-error (subtract-integer 2 3.0))) (defun add-float (float1 float2) "Add 2 floating point numbers" (check-type float1 float) (check-type float2 float) (+ float1 float2)) (defun subtract-float (float1 float2) "Subtract 2 floating point numbers" (check-type float1 float) (check-type float2 float) (- float1 float2)) (define-test add-float "Test add-float for values and errors." (:tag :add :float) (assert-eql 3.0 (add-float 1.0 2.0)) (assert-error 'type-error (add-float 1.0 2)) (assert-error 'type-error (add-float 1 2.0))) (define-test subtract-float "Test subtract-float for values and errors." (:tag :subtract :float) (assert-eql 1.0 (subtract-float 3.0 2.0)) (assert-error 'type-error (subtract-float 3.0 2)) (assert-error 'type-error (subtract-float 2 3.0))) (defun add-complex (complex1 complex2) "Add 2 complex numbers" (check-type complex1 complex) (check-type complex2 complex) (+ complex1 complex2)) (defun subtract-complex (complex1 complex2) "Subtract 2 complex numbers" (check-type complex1 complex) (check-type complex2 complex) (- complex1 complex2)) (define-test add-complex "Test add-complex for values and errors." (:tag :add :complex) (assert-eql #C(3 5) (add-complex #C(1 2) #C(2 3))) (assert-error 'type-error (add-integer #C(1 2) 3)) (assert-error 'type-error (add-integer 1 #C(2 3)))) (define-test subtract-complex "Test subtract-complex for values and errors." (:tag :subtract :complex) (assert-eql #C(1 2) (subtract-complex #C(3 5) #C(2 3))) (assert-error 'type-error (subtract-integer #C(3 5) 2)) (assert-error 'type-error (subtract-integer 2 #C(2 3))))
2,429
Common Lisp
.lisp
66
34
58
0.718537
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e987e282d2e6ba710b8d9f5922dac7227a896f917c62a8a2b683eca6ed088e2a
23,425
[ -1 ]
23,426
my-max-test.lisp
namoamitabha_study-lisp-unit/my-max-test.lisp
(define-test test-my-max (assert-equal 5 (my-max 2 5)) (assert-equal 4 (my-max 1 4))) (define-test negative-test-my-max (assert-equal 3 (my-max 3 5))) (define-test failure-test-my-max (assert-equal 2 (my-max 3 2))) (define-test assert-true-test (assert-true t)) (define-test assert-true-test (assert-true nil)) (defun my-sqrt (n) (/ n 2)) (define-test test-loop-assertion (dotimes (i 5) (assert-equal i (my-sqrt (* i i)) i)))
450
Common Lisp
.lisp
15
27.4
42
0.678322
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a6c6fe8beb4bf06da4ce718171c44e54dd2fe422625d50d73a48af761425fc3b
23,426
[ -1 ]
23,427
run-my-max-tests.lisp
namoamitabha_study-lisp-unit/run-my-max-tests.lisp
(load "lisp-unit") (use-package :lisp-unit) (setq *print-failures* t) (load "my-max") (load "my-max-test") (run-tests) (print-errors *)
142
Common Lisp
.lisp
7
18.428571
25
0.689922
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c596007f864dcd03323203b429eb993e0c5bc48c41893effa7950c68b220a750
23,427
[ -1 ]
23,428
run-tag-tests.lisp
namoamitabha_study-lisp-unit/run-tag-tests.lisp
(load "lisp-unit") (use-package :lisp-unit) (load "tag-tests") (setq *print-summary* t) (run-tags '(:integer)) (run-tags '(:subtract))
140
Common Lisp
.lisp
6
21.5
24
0.682171
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
511c9648fe40c2b9666ec0a5e6018c94121e741c4721c36229328845af911ec5
23,428
[ -1 ]
23,429
date-tests.lisp
namoamitabha_study-lisp-unit/date-tests.lisp
(defpackage :date-tests (:use :common-lisp :lisp-unit :date)) (in-package :date-tests) (setq *print-failures* t) (define-test test-date->string (assert-equal 2 (date->string 2)) (assert-equal 5 (date->string 5))) (define-test test-string->date (assert-equal 2 (string->date 2)) (assert-equal 3 (string->date 4))) ;;(print-errors *)
347
Common Lisp
.lisp
11
29.181818
39
0.697885
namoamitabha/study-lisp-unit
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7e48fb722e70652107c8d664a3099b525908c1b2e493a02de4b350db3dd29990
23,429
[ -1 ]
23,453
an_evolution.lisp
codepony_an_evolution_lisp/an_evolution.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# ;; At first load all the needed files. This was made to have a better structured source-code. (load "define.lisp") (load "move-turn.lisp") (load "reproduce.lisp") (load "eat-sick.lisp") (load "typ-age-count-statistic.lisp") (load "sex.lisp") (load "fire.lisp") (load "update-world.lisp") (load "draw-world.lisp") (load "move-spec.lisp") (load "debug.lisp") (defun startup () "Gives a short introduction of the program and starts the UI." (format t "~%type `info' to get info about the program and the map itself") (format t "~%type in a number of days you want to simulate or just press ENTER for 1 day") (format t "~%type `quit' to exit") (format t "~%type `source' to get the link to the source code.") (format t "~%type `lightning' to emulate a lightning-bolt hitting a plant to produce fire, and see the world burn.~%") (format t "~%type `debug' to switch debug state") (evolution)) (defun evolution () "Main function, also provides user interaction." (statistic) (setf *tmp-eaten-plants* 0) (setf *tmp-eaten-animals* 0) (setf *tmp-animals-born* 0) (setf *tmp-logic-moves* 0) (draw-world) (fresh-line) ;; Waits for user INPUT => if 'quit' = exit evolution: (let ((str (read-line))) (cond ((equal str "quit") (format t "~%Good Bye") ;; Uncomment this before building Because saying good-bye is always fine: ;; (exit) ) ((equal str "debug") (when (member :ael *dbg-ids*) (format t "~%Debugging is now off.") (undebug :ael) (evolution)) (format t "~%Debugging is now on.") (setdebug :ael) (evolution)) ((equal str "info") (format t "~%This programm is licensed under the AGPL.") (format t "~%An P shows a herbivore.") (format t "~%An M shows an omnivore.") (format t "~%An F shows a carnivore.") (format t "~%An * shows a plant.") (format t "~%A # shows a fire burning.~%") (evolution)) ((equal str "source") (format t "~%Look at the source here: https://github.com/codepony/an_evolution.lisp~%") (evolution)) ((equal str "lightning") (if (> (hash-table-count *plants*) 0) (setfire) (format t "~%There are no plants to burn.~%")) (evolution)) ;; Gets the integer out of str, let's you type in other chars after it. => :junk-allowed: (t (let ((x (parse-integer str :junk-allowed t))) (if x (loop for i below x do (update-world) ;; x - Number of days. @ all 100 days inserts a dot: if (zerop (mod i 100)) ;; If you type in 1000 the 1000 won't be printed: do (format t "~a~%" i)) ;; if there is no INPUT (or no right one) => simulates only 1 day: (update-world)) ;;recursive function: (evolution))))))
4,056
Common Lisp
.lisp
85
36.929412
120
0.572114
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
24a74adfdff59b114f10b449381ea01bb9ac31fad442668482f63088751492a7
23,453
[ -1 ]
23,454
draw-world.lisp
codepony_an_evolution_lisp/draw-world.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun draw-world () "Draws the world as output, with coordinates fetched for each object." (loop for y below (+ *height* 1) do (progn (fresh-line) ;; Marks left side of the world: (princ "|") (loop for x below (+ *width* 1) do (princ (let ((animal-found nil) (print-type nil)) ;; Checking for different animals in a very special way: (mapcar (lambda (animal) (when (and (= (animal-x animal) x) (= (animal-y animal) y)) (setf animal-found t) (setf print-type (case (animal-typ animal) ((omnivore) #\M) ((herbivore) #\P) ((carnivore) #\F) ((none) #\X) )))) *animals*) ;; Printing the symbols to the map: (if (not animal-found) (cond ((some (lambda (fire) (and (= (fire-x fire) x) (= (fire-y fire) y))) *fires*) #\#) ;; Fire, plants, "nothing": ((gethash (cons x y) *plants*) #\*) ;; In the case there are no animals: (t #\space)) ;; Else, print the animal: print-type)))) ;; Marks right side of the world: (princ "|"))))
3,002
Common Lisp
.lisp
49
32.55102
92
0.39219
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4a05dd31c91a9071cc8190cd321db04cba749bd0bc72d05dece6496c1c43214d
23,454
[ -1 ]
23,455
sex.lisp
codepony_an_evolution_lisp/sex.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun givesex (animal) "Giving a sex to the animals based on the sum of genes decides the sex of the animal" (if (oddp (apply '+ (animal-genes animal))) (setf (animal-sex animal) 'f) (setf (animal-sex animal) 'm))) (defun havesex (animal) "Same types will reproduce of course When there is any omnivore, the child-typ will be random. Carnivores & herbivores can't have sex." (let ((child-typ 'none) (success nil)) (let ((pos (cons (animal-x animal) (animal-y animal))) (gena (animal-genes animal)) (agea (animal-age animal)) (typa (animal-typ animal)) (sexa (animal-sex animal))) (mapc (lambda (animal) (let ((posa (cons (animal-x animal) (animal-y animal))) (ageb (animal-age animal)) (genb (animal-genes animal)) (typb (animal-typ animal)) (sexb (animal-sex animal))) (when (and (not (equal sexa sexb))(equal pos posa) (> agea 5) (> ageb 5) (not (equal gena genb)) (evenp (+ (car gena) (car genb)))) (when (and (not (equal typa 'omnivore)) (equal typa typb) (not (equal typb 'omnivore))) (setf child-typ typa) (setf success t) (sexeff gena genb)) (when (or (and (equal typa 'carnivore) (equal typb 'herbivore)) (and (equal typa 'herbivore) (equal typb 'carnivore))) (setf success nil)) (when (or (equal typa 'omnivore) (equal typb 'omnivore)) (setf child-typ 'none) (setf success t) (sexeff gena genb)) (when (and success (equal sexb 'f)) (setf (animal-ctyp animal) child-typ) (setf (animal-preg animal) 1) (setf (animal-cfact animal) *efficiency*) (setf *efficiency* 0))))) *animals*)) (when (and success (equal (animal-sex animal) 'f)) (dbg :ael "Sex was successful and a new ~a will be born soon.~%" child-typ) (setf (animal-ctyp animal) child-typ) (setf (animal-cfact animal) *efficiency*) (setf *efficiency* 0) (setf (animal-preg animal) 1)))) (defparameter *efficiency* 0) (defun sexeff (gena genb) "Let the genes tell how efficient sex is" (let ((gendiff 0)) (loop for i below (length gena) do (when (not (equal (nth i gena) (nth i genb))) (incf gendiff)) (setf *efficiency* (/ (1+ gendiff) (1+ (length gena)))))))
3,238
Common Lisp
.lisp
58
46.396552
180
0.620581
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3b50919ae1b4816c95f617e5e4f57005bf67f4216208d553dbd2a6b44d311cf2
23,455
[ -1 ]
23,456
reproduce.lisp
codepony_an_evolution_lisp/reproduce.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun reproduce (animal) "Manages the whole reproduction, have a look at the source to understand how it works exactly" (let ((e (animal-energy animal)) (reproduction-energy 80)) (when (and (>= e reproduction-energy) (or (<= *counter* 5) (and (>= (animal-daysp animal) 5) (> (animal-cfact animal) 0)))) ;; Looses half of its energy to its child (setf (animal-energy animal) (ash e -1)) ;; Copy structure from parent to child !!!!WARNING!!! this will do so called 'Shallow Copy' (wrong copy) (let ((animal-nu (copy-structure animal)) ;; Copies complete list => to get rid of these shallows: (genes (copy-list (animal-genes animal))) (mutation (random 8))) (setf (nth mutation genes) (max 1 (+ (nth mutation genes) (random 3) -1))) (let ((mutatwo (random 8))) (setf (nth mutatwo genes) (max 1 (+ (nth mutatwo genes) (random 3) -1)))) (setf (animal-genes animal-nu) genes) (setf (animal-age animal-nu) 0) (setf (animal-typ animal-nu) (animal-ctyp animal-nu)) ;; Randomly create Omnivores my 1/3 chance of getting one: (when (= (random 3) 2) (setf (animal-typ animal-nu) 'omnivore)) ;; when there are many animals number of carnivores should raise: (when (and (>= *counter* 10) (= (random 3) 2)) (setf (animal-typ animal-nu) 'carnivore)) (setf (animal-sex animal-nu) 'n) (setf (animal-preg animal-nu) 0) (setf (animal-cfact animal-nu) 0) (setf (animal-ctyp animal-nu) 'none) (setf (animal-daysp animal-nu) 0) ;; NOT - setting (animal-sick animal) because should be the same as parent (when (> (animal-cfact animal) 0) ;; Added 50 because sexeff is mostly low: (setf (animal-energy animal-nu) (+ (round (* (animal-cfact animal) (animal-energy animal-nu))) 50 ))) (setf (animal-preg animal) 0) (setf (animal-cfact animal) 0) (setf (animal-ctyp animal) 'none) ;; Resets the mother: (setf (animal-daysp animal) 0) (push animal-nu *animals*) (dbg :ael "A new animal (~a) was born.~%" (animal-typ animal-nu)) (incf *animals-born*) (incf *tmp-animals-born*)))))
3,092
Common Lisp
.lisp
57
45.947368
127
0.63264
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
61a9573ea06c44ac4f5ba536e624277799435fed09bf987d5dcb1cb16205ca88
23,456
[ -1 ]
23,457
debug.lisp
codepony_an_evolution_lisp/debug.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# ;; Simple Debugging function to generate some extra output (defvar *dbg-ids* nil "Identifiers used by dbg") (defun dbg (id format-string &rest args) "Print debugging info if (DEBUG ID) has been specified" (when (member id *dbg-ids*) (fresh-line *debug-io*) (apply #'format *debug-io* format-string args))) (defun setdebug (&rest ids) "Start debug output on the given ids" (setf *dbg-ids* (union ids *dbg-ids*))) (defun undebug (&rest ids) "Stops dbg on given ids or when nil given stop all" (setf *dbg-ids* (if (null ids) nil (set-difference *dbg-ids* ids)))) (defun dbg-indent (id indent format-string &rest args) "Print indented debugging info if (DEBUG ID) is set" (when (member id *dbg-ids*) (format *debug-io* "~&~V@T~?" (* 2 indent) format-string args)))
1,591
Common Lisp
.lisp
32
45.375
76
0.713824
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f02ee453d14d3f08aa4669bfcfd6354f32f24db902554590bd0742ce9b5c9f26
23,457
[ -1 ]
23,458
move-turn.lisp
codepony_an_evolution_lisp/move-turn.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun move (animal) "This makes a random movement possible." (let ((dir (animal-dir animal)) (x (animal-x animal)) (y (animal-y animal))) (setf (animal-x animal) (mod (+ x (cond ((and (>= dir 2) (< dir 5)) 1) ((or (= dir 1) (= dir 5)) 0) (t -1)) *width*) *width*)) (setf (animal-y animal) (mod (+ y (cond ((and (>= dir 0) (< dir 3)) -1) ((or (= dir 4) (< dir 7)) 1) (t 0)) *height*) *height*)) (decf (animal-energy animal)))) (defun turn (animal) "Change of direction (animals) As you can see the direction is based on their genes" (let ((x (random (apply #'+ (animal-genes animal))))) (labels ((angle (genes x) (let ((xnu (- x (car genes)))) (if (< xnu 0) 0 (1+ (angle (cdr genes) xnu)))))) (setf (animal-dir animal) (mod (+ (animal-dir animal) (angle (animal-genes animal) x)) 8)))))
2,115
Common Lisp
.lisp
45
32.555556
76
0.504128
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
12b5edb615a6104e5f375355be89b0a4e3457d9d65f702769c285834758a59ea
23,458
[ -1 ]
23,459
define.lisp
codepony_an_evolution_lisp/define.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# ;; define world: (defparameter *width-org* (- 45 20)) (defparameter *height-org* (- 15 5)) ;; Resetting this because of the dynamic map-size: (defvar *width* *width-org*) (defvar *height* *height-org*) ;; Coordinates of the Jungle (Middle of the map) '(x y width height): (defparameter *jungle* '(22 5 10 10)) ;; One plant gives an animal 80 days of energy: (defparameter *plant-energy* 80) ;; Global Statistics: (defvar *animals-eaten* 0) (defvar *plants-eaten* 0) ;; Because 1st animal won't be counted else: (defvar *animals-born* 1) (defvar *tmp-animals-born* 0) (defvar *tmp-eaten-plants* 0) (defvar *tmp-eaten-animals* 0) (defvar *tmp-logic-moves* 0) (defvar *logic-moves* 0) ;; Growing plants: (defparameter *plants* (make-hash-table :test #'equal)) (defun random-plant (left top width height) "Creates random coordinates for a new plant and adds it to the hash table." (let ((pos (cons (+ left (random width)) (+ top (random height))))) (setf (gethash pos *plants*) t))) (defun add-plants () "Every day this function creates 2 plants => one in the jungle and one out The jungle will be higher populated as the rest of the world because it's smaller." (apply #'random-plant *jungle*) (random-plant 0 0 *width* *height*)) ;; Define the fire here (defstruct fire x y lifet) ;; empty list, because no fire on startup: (defvar *fires* (list)) (defparameter *animal-energy* 100) ;; Creating animals: (defstruct animal x y energy dir typ sex preg daysp ctyp cfact age sick genes) ;; Defines structure of the animals: (defparameter *animals* (list (make-animal :x (ash *width* -1) :y (ash *height* -1) :energy 900 :dir 0 :typ 'omnivore :sex 'n ;; First animal is pregnant to reproduce on startup: :preg 1 ;; Days pregnant: :daysp 0 ;; child-typ: :ctyp 'omnivore ;; For first run it's 100% - energy-factor based on genes cal. in (sexeff): :cfact 1 :age 0 :sick nil :genes (loop repeat 8 collecting (1+ (random 10))))))
2,927
Common Lisp
.lisp
73
35.60274
86
0.678206
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b8aabd6317fbc0a74eeec9e7dffc1d4836ae198099ec4929ce8f8ffc93a20477
23,459
[ -1 ]
23,460
fire.lisp
codepony_an_evolution_lisp/fire.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun setfire () " Sets fire to a random plant" (format t "~%A lightning hits a plant~%") ;; Loops are great: (let ((key-list (loop for key being the hash-keys of *plants* collect key))) ;; getting a random plant: (let ((choosen-plant (nth (random (hash-table-count *plants*)) key-list))) (let ((xfire (car choosen-plant)) (yfire (cdr choosen-plant))) (remhash choosen-plant *plants*) (let ((fire-nu (make-fire :x xfire :y yfire :lifet 0))) (push fire-nu *fires*)))))) (defun spreadfire (fire) "Test every field around the fire if there is a plant. ( 8 - cases) Spreading the fire on other plants It's still not perfect - sorry but I really hope it works" (let ((xfire (+ (fire-x fire) 1)) (yfire (fire-y fire))) (testfire xfire yfire) (when (> xfire *width*) (setf xfire 0) (testfire xfire yfire))) (let ((xfire (+ (fire-x fire) 1)) (yfire (+ (fire-y fire) 1))) (testfire xfire yfire) (when (> xfire *width*) (setf xfire 0) (testfire xfire yfire)) (when (> yfire *height*) (setf yfire 0) (testfire xfire yfire))) (let ((xfire (fire-x fire)) (yfire (+ (fire-y fire) 1))) (testfire xfire yfire) (when (> yfire *height*) (setf yfire 0) (testfire xfire yfire))) (let ((xfire (- (fire-x fire) 1)) (yfire (+ (fire-y fire) 1))) (testfire xfire yfire) (when (< xfire 0) (setf xfire *width*) (testfire xfire yfire)) (when (> yfire *height*) (setf yfire 0) (testfire xfire yfire))) (let ((xfire (- (fire-x fire) 1)) (yfire (fire-y fire))) (testfire xfire yfire) (when (< xfire 0) (setf xfire *width*) (testfire xfire yfire))) (let ((xfire (- (fire-x fire) 1)) (yfire (- (fire-y fire) 1))) (testfire xfire yfire) (when (< xfire 0) (setf xfire *width*) (testfire xfire yfire)) (when (< yfire 0) (setf yfire *height*) (testfire xfire yfire))) (let ((xfire (+ (fire-x fire) 1)) (yfire (- (fire-y fire) 1))) (testfire xfire yfire) (when (> xfire *width*) (setf xfire 0) (testfire xfire yfire)) (when (< yfire 0) (setf yfire *height*) (testfire xfire yfire))) (let ((xfire (fire-x fire)) (yfire (- (fire-y fire) 1))) (testfire xfire yfire) (when (< yfire 0) (setf yfire *height*) (testfire xfire yfire)))) (defun testfire (xfire yfire) "Testing if fire spreads" (when (gethash (cons xfire yfire) *plants*) (let ((newfire (make-fire :x xfire :y yfire :lifet 0))) (push newfire *fires*) (remhash (cons xfire yfire) *plants*)))) (defun burn (animal) "Killing an animal, if it touches the fire" (mapc (lambda (fire) (when (and (equal (animal-x animal) (fire-x fire)) (equal (animal-y animal) (fire-y fire))) (dbg :ael "A ~a was burned successfully~%" (animal-typ animal)) (setf (animal-energy animal) 0))) *fires*))
3,727
Common Lisp
.lisp
94
34.329787
101
0.631666
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1f98610509c0395fc46ab58e63fb8217774e91297ba61730da85123fa22131a3
23,460
[ -1 ]
23,461
eat-sick.lisp
codepony_an_evolution_lisp/eat-sick.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun eatp (animal) "Food for omnivores and herbivores (or checking if there is a plant) No need to do this for carnivores" (let ((pos (cons (animal-x animal) (animal-y animal)))) (when (gethash pos *plants*) (dbg :ael "A plant was eaten by an ~a~%" (animal-typ animal)) ;; The older they get, the less energy they will get. It's that easy: (incf (animal-energy animal) (round (- *plant-energy* (* 0.1 (animal-age animal))))) (incf *tmp-eaten-plants*) (incf *plants-eaten*) ;; Chance of 1/5 to change the sick-status by eating plants: (if (= (random 5) 4) (dbg :ael "An animal got sick.") (setf (animal-sick animal) (not (animal-sick animal)))) (remhash pos *plants*)))) (defun eat-new (animal) "Let the carnivores eat Functions should be logical to understand - Same pos = eat it Age of the victim must be > 5 to be eaten. Otherwise Parents would kill their children. Added genes here, because self-eating got a problem." (let ((success nil) (energy-loose 0) (damage 0) (sick-victim 0)) (let ((posa (cons (animal-x animal) (animal-y animal)))(gena (animal-genes animal)) (agea (animal-age animal)) (energya (animal-energy animal))) (mapc (lambda (animal) (let ((posb (cons (animal-x animal) (animal-y animal))) (ageb (animal-age animal)) (genb (animal-genes animal)) (energyb (animal-energy animal))) (when (and (equal posa posb) (or (equal (animal-typ animal) 'omnivore) (equal (animal-typ animal) 'herbivore)) (> agea 5) (not (equal gena genb)) (oddp (+ (car gena) (car genb)))) (when (equal (animal-typ animal) 'herbivore) (setf energy-loose (+ ageb (round (* 0.5 energya)) (round (* 0.2 energyb)))) (setf damage (+ agea (round (* 1/3 energyb)) (round (* 0.1 energya))))) (when (equal (animal-typ animal) 'omnivore) (setf energy-loose (+ ageb (round (* 0.75 energya)) (round (* 0.2 energyb)))) (setf damage (+ agea (round (* 2/3 energyb)) (round (* 0.1 energya))))) (when (>= energy-loose energyb) (incf *tmp-eaten-animals*) (incf *animals-eaten*) (setf success t) (when (equal (animal-sick animal) T) (setf sick-victim 1)) (setf (animal-energy animal) 0)) (when (not (>= energy-loose energyb)) (dbg :ael "The animal lost some energy in the fight~%") (setf success nil) (decf (animal-energy animal) energy-loose))))) *animals*)) (decf (animal-energy animal) damage) (when success (dbg :ael "The animal successfully killed an other one and ate it~%") ;; Same as we do with the plants. higher age => less energy: (incf (animal-energy animal) (round (- *animal-energy* (* 0.1 (animal-age animal))))) (when (= sick-victim 1) (dbg :ael "The ~a got ill from eating a sick animal.~%" (animal-typ animal)) (setf (animal-sick animal) T))))) (defun issick (animal) "Checks if animal is sick" (when (equal (animal-sick animal) T) (setf (animal-energy animal) (round (* (animal-energy animal) 0.95)))))
4,059
Common Lisp
.lisp
69
50.014493
194
0.624937
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9ee8d62368bff4107005bf46c904e6647a334e36753f7f6d2bffc678a66225c1
23,461
[ -1 ]
23,462
move-spec.lisp
codepony_an_evolution_lisp/move-spec.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# ;; Logical thinking for moving | Version 1.3.2 ;; x == width | y == height (just to remember) ;; Plants are saved like (x . y) (defvar *isfire* (make-array 8)) (defvar *isplant* (make-array 8)) (defvar *isanimal* (make-array 8)) (defun move-logic (animal) "Creates a moves that has some checking behind it, and is not random" ;; Coordinates we need to find direct neighbours: (let ((ismoved nil) (posx (animal-x animal)) (posy (animal-y animal))) (lookaround posx posy) ;; Makes 3 lists with pos, where something is: (let ((firelist (list)) (animallist (list)) (plantlist (list))) (loop for x from 0 to 7 do (if (not (equal (aref *isfire* x) nil)) (setf firelist (cons firelist (cons (aref *isfire* x) ())))) (if (not (equal (aref *isplant* x) nil)) (setf plantlist (cons plantlist (cons (aref *isplant* x) ())))) (if (not (equal (aref *isanimal* x) nil)) (setf animallist (cons animallist (cons (aref *isanimal* x) ()))))) ;; because otherwise it would be (NIL (x y)..): (setf firelist (cdr firelist)) (setf plantlist (cdr plantlist)) (setf animallist (cdr animallist)) (cond ((> (length firelist) 0) (let ((workwith (nth (random (length firelist)) firelist))) (if (> (car workwith) posx) (setf (animal-x animal) (- (animal-x animal) 1))) (if (< (car workwith) posx) (setf (animal-x animal) (+ (animal-x animal) 1))) (if (< (cadr workwith) posy) (setf (animal-y animal) (+ (animal-y animal) 1))) (if (> (cadr workwith) posy) (setf (animal-y animal) (- (animal-y animal) 1)))) (dbg :ael "A logic move was done because of fire.~%") (setf ismoved t) (incf *tmp-logic-moves*) (incf *logic-moves*)) ((and (> (length plantlist) 0) (or (equal (animal-typ animal) 'herbivore) (equal (animal-typ animal) 'omnivore)) (equal ismoved nil)) (let ((workwith (nth (random (length plantlist)) plantlist))) (setf (animal-x animal) (car workwith)) (setf (animal-y animal) (cadr workwith))) (dbg :ael "A logic move was done because of a plant to eat.~%") (setf ismoved t) (incf *tmp-logic-moves*) (incf *logic-moves*)) ((and (> (length animallist) 0) (equal ismoved nil)) (let ((workwith (nth (random (length animallist)) animallist))) (if (and (equal (animal-typ animal) "herbivore") (not (equal (caddr workwith) "herbivore"))) (progn (if (> (car workwith) posx) (setf (animal-x animal) (- (animal-x animal) 1))) (if (< (car workwith) posx) (setf (animal-x animal) (+ (animal-x animal) 1))) (if (< (cadr workwith) posy) (setf (animal-y animal) (+ (animal-y animal) 1))) (if (> (cadr workwith) posy) (setf (animal-y animal) (- (animal-y animal) 1))) (dbg :ael "A herbivore moved away from an enemy.~%") (setf ismoved t) (incf *tmp-logic-moves*) (incf *logic-moves*)) (if (not (equal (animal-typ animal) (caddr workwith))) (progn (setf (animal-x animal) (car workwith)) (setf (animal-y animal) (cadr workwith)) (dbg :ael "An animal moved to another, because it is hungry and needs to fight.~%") (setf ismoved t)(incf *tmp-logic-moves*) (incf *logic-moves*)) (progn (move animal)))))) ((equal ismoved nil) (move animal)))))) (defun lookaround (x y) "Simple function that calls checkfortarget(x y) with any coordinate around an animal" (let ((xlook (+ x 1)) (ylook y) (check 0)) (checkfortarget xlook ylook check) (when (> xlook *width*) (setf xlook 0) (checkfortarget xlook ylook check))) (let ((xlook (+ x 1)) (ylook (+ y 1)) (check 1)) (checkfortarget xlook ylook check) (when (> xlook *width*) (setf xlook 0) (checkfortarget xlook ylook check)) (when (> ylook *height*) (setf ylook 0) (checkfortarget xlook ylook check))) (let ((xlook x) (ylook (+ y 1)) (check 2)) (checkfortarget xlook ylook check) (when (> ylook *height*) (setf ylook 0) (checkfortarget xlook ylook check))) (let ((xlook (- x 1)) (ylook (+ y 1)) (check 3)) (checkfortarget xlook ylook check) (when (< xlook 0) (setf xlook *width*) (checkfortarget xlook ylook check)) (when (> ylook *height*) (setf ylook 0) (checkfortarget xlook ylook check))) (let ((xlook (- x 1)) (ylook y) (check 4)) (checkfortarget xlook ylook check) (when (< xlook 0) (setf xlook *width*) (checkfortarget xlook ylook check))) (let ((xlook (- x 1)) (ylook (- y 1)) (check 5)) (checkfortarget xlook ylook check) (when (< xlook 0) (setf xlook *width*) (checkfortarget xlook ylook check)) (when (< ylook 0) (setf ylook *height*) (checkfortarget xlook ylook check))) (let ((xlook (+ x 1)) (ylook (- y 1)) (check 6)) (checkfortarget xlook ylook check) (when (> xlook *width*) (setf xlook 0) (checkfortarget xlook ylook check)) (when (< ylook 0) (setf ylook *height*) (checkfortarget xlook ylook check))) (let ((xlook x) (ylook (- y 1)) (check 7)) (checkfortarget xlook ylook check) (when (< ylook 0) (setf ylook *height*) (checkfortarget xlook ylook check)))) (defun checkfortarget (xlook ylook check) "Function to check for targets around animals" (if (gethash (cons xlook ylook) *plants*) (setf (aref *isplant* check) (cons xlook (cons ylook ()))) (setf (aref *isplant* check) nil)) (let ((ischecked nil)) (mapc (lambda (animal) (if (and (= (animal-x animal) xlook) (= (animal-y animal) ylook)) (progn (setf (aref *isanimal* check) (cons xlook (cons ylook (cons (animal-typ animal) ())))) (setf ischecked check)))) *animals*) (if (equal ischecked nil) (setf (aref *isanimal* check) nil))) (let ((ischecked nil)) (mapc (lambda (fire) (if (and (= (fire-x fire) xlook) (= (fire-y fire) ylook)) (progn (setf (aref *isfire* check) (cons xlook (cons ylook ()))) (setf ischecked check)))) *fires*) (if (equal ischecked nil) (setf (aref *isfire* check) nil))))
7,317
Common Lisp
.lisp
164
36.786585
140
0.595321
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6bc43f980eafb2c9c31400b4eb896585654190b81a355bb78f829a7f6c32b5fe
23,462
[ -1 ]
23,463
update-world.lisp
codepony_an_evolution_lisp/update-world.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun update-world () " Simulates a day in our world" ;; Removes dead animals from world: (setf *animals* (remove-if (lambda (animal) (<= (animal-energy animal) 0)) *animals*)) ;; Removes fire, if it's out burned (after 10 days): (setf *fires* (remove-if (lambda (fire) (>= (fire-lifet fire) 10)) *fires*)) (setf *counter* 0) ;; Ugly fix because of cnt animal: (mapc (lambda (animal) (cnt) ) *animals*) ;; When all animals got "removed", the player looses the game: (when (<= *counter* 0) (format t "The Game Is Over ~% AUTOMATIC RESET") (exit)) (resizemap) (mapc (lambda (animal) (turn animal) (move-logic animal) ;; Give parents & children 5 days to live together and/or have the time to run away: ;; At the age of 200 days, an animal won't be able to kill others anymore: (when (and (> (animal-age animal) 5) (or (equal (animal-typ animal) 'omnivore) (equal (animal-typ animal) 'carnivore)) (< (animal-age animal) 200)) (eat-new animal)) (when (or (equal (animal-typ animal) 'omnivore) (equal (animal-typ animal) 'herbivore)) (eatp animal)) (when (and (> (animal-age animal) 5) (equal (animal-sex animal) 'n)) (givesex animal)) (when (> (animal-age animal) 5) (havesex animal)) (when (= (animal-preg animal)1) (incf (animal-daysp animal))) (reproduce animal) (older animal) (typ animal) (burn animal) (issick animal)) *animals*) (mapc (lambda (fire) (spreadfire fire) (incf (fire-lifet fire))) *fires*) (add-plants)) (defun resizemap () "Making a simple dynamic map size" (setf *width* (+ *width-org* (round (/ *counter* 10)))) (setf *height* (+ *height-org* (round (/ *counter* 30)))))
2,796
Common Lisp
.lisp
64
35.15625
158
0.604335
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c64d5fe830aa0582c25977435c7bde58e6c3dff1dce5375f61f1fe2c7ec8710e
23,463
[ -1 ]
23,464
typ-age-count-statistic.lisp
codepony_an_evolution_lisp/typ-age-count-statistic.lisp
#| an_evolution.lisp version git-current Copyright (C) 2013 @d3f (http://identi.ca/d3f) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. |# (defun older (animal) "Manages the age of animals" (incf (animal-age animal)) (decf (animal-energy animal)) ;; Getting an energy-boot once in the life-time: (if (equal (animal-age animal) 75) (incf (animal-energy animal) 150))) (defun typ (animal) "Manages the types of animals - Carnivores, herbivores and omnivores" (let ((typ (animal-typ animal))) (when (equal typ 'none) (let ((typset (random 3))) (when (= typset 0) (setf (animal-typ animal) 'omnivore)) (when (= typset 1) (setf (animal-typ animal) 'herbivore)) (when (= typset 2) (setf (animal-typ animal) 'carnivore)))))) (defvar *counter* 1) (defun cnt () "Count alive animals" (incf *counter*)) (defun statistic () "Calculates and prints the statistics" (format t "~%Number of animals alive: ~a" *counter*) (format t "~%Number of eaten plants this round: ~a" *tmp-eaten-plants*) (format t "~%Number of eaten plants: ~a" *plants-eaten*) (format t "~%Number of eaten animals this round: ~a" *tmp-eaten-animals*) (format t "~%Number of eaten animals: ~a" *animals-eaten*) (format t "~%Number of born animals this round: ~a" *tmp-animals-born*) (format t "~%Number of born animals: ~a" *animals-born*) (format t "~%Number of logic-moves this round: ~a" *tmp-logic-moves*) (format t "~%Number of logic-moves: ~a" *logic-moves*) (format t "~%~%"))
2,194
Common Lisp
.lisp
48
41.166667
76
0.685272
codepony/an_evolution.lisp
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c9b940499a41ff18066db9c0018d70e045c30a5610ec0a3582c24caff4e1e12e
23,464
[ -1 ]
23,492
practical-common-lisp.asd
cccons_practical-common-lisp/practical-common-lisp.asd
(asdf:defsystem #:practical-common-lisp :description "Implementation of projects from the Practical Common Lisp book by Peter Seibel" :author "Cameron V Chaparro <[email protected]>" :license "GPLv3" :serial t :pathname "src/" :components ((:module "ch03" :components ((:file "ch03"))) (:module "ch08" :components ((:file "ch08"))) (:module "ch09" :components ((:file "ch09"))) (:module "ch15" :components ((:file "ch15")))))
608
Common Lisp
.lisp
18
22.5
95
0.501695
cccons/practical-common-lisp
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7b9b4c0bfa7b841e64a2723ca8ce4cccd3d5195408a37b8af5a21edf6719ea84
23,492
[ -1 ]
23,493
ch15.lisp
cccons_practical-common-lisp/src/ch15/ch15.lisp
(defpackage #:ch15 (:use #:common-lisp) (:export #:list-directory #:file-exists-p #:directory-pathname-p #:file-pathname-p #:pathname-as-directory #:pathname-as-file #:walk-directory #:directory-p #:file-p)) (in-package :ch15) (defun component-present-p (value) (and value (not (eql value nil)))) (defun directory-pathname-p (p) (and (not (component-present-p (pathname-name p))) (not (component-present-p (pathname-type p))) p)) (defun pathname-as-directory (name) (let ((pathname (pathname name))) (when (wild-pathname-p pathname) (error "Can't reliably convert wild pathnames.")) (if (not (directory-pathname-p pathname)) (make-pathname :directory (append (or (pathname-directory pathname) (list :relative)) (list (file-namestring pathname))) :name nil :type nil :defaults pathname) pathname))) (defun directory-wildcard (dirname) (make-pathname :name :wild :type #-clisp :wild #+clisp nil :defaults (pathname-as-directory dirname))) (defun list-directory (dirname) (when (wild-pathname-p dirname) (error "Can only list concrete directory names.")) (let ((wildcard (directory-wildcard dirname))) #+(or sbcl cmu lispworks) (directory wildcard) #+openmcl (directory wildcard :directories t) #+allegro (directory wildcard :directories-are-files nil) #+clisp (nconc (directory wildcard) (directory (clisp-subdirectories-wildcard wildcard))) #-(or sbcl cmu lispworks openmcl allegro clisp) (error "list-directory not implemented"))) #+clisp (defun clisp-subdirectories-wildcard (wildcard) (make-pathname :directory (append (pathname-directory wildcard) (list :wild)) :name nil :type nil :defaults wildcard)) (defun file-exists-p (pathname) #+(or sbcl lispworks openmcl) (probe-file pathname) #+(or allegro cmu) (or (probe-file (pathname-as-directory pathname)) (probe-file pathname)) #+clisp (or (ignore-errors (probe-file (pathname-as-file pathname))) (ignore-errors (let ((directory-form (pathname-as-file pathname))) (when (ext:probe-directory directory-form) directory-form)))) #-(or sbcl lispworks openmcl allegro cmu clisp) (error "file-exists-p not implemented")) (defun pathname-as-file (name) (let ((pathname (pathname name))) (when (wild-pathname-p pathname) (error "Can't reliably convert wild pathnames.")) (if (directory-pathname-p name) (let* ((directory (pathname-directory pathname)) (name-and-type (pathname (first (last directory))))) (make-pathname :directory (butlast directory) :name (pathname-name name-and-type) :type (pathname-type name-and-type) :defaults pathname)) pathname))) (defun walk-directory (dirname fn &key directories (test (constantly t))) (labels ((walk (name) (cond ((directory-pathname-p name) (when (and directories (funcall test name)) (funcall fn name)) (dolist (x (list-directory name)) (walk x))) ((funcall test name) (funcall fn name))))) (walk (pathname-as-directory dirname))))
3,399
Common Lisp
.lisp
90
30.388889
94
0.635176
cccons/practical-common-lisp
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9bcf58f517baa99baed2d5f3ab4a76bf3f6d7777f9b309e2758f78fc671e60cd
23,493
[ -1 ]
23,494
ch08.lisp
cccons_practical-common-lisp/src/ch08/ch08.lisp
(defpackage #:ch08 (:use #:cl) (:export #:primep #:next-prime #:do-primes #:with-gensyms)) (in-package #:ch08) (defun primep (number) (when (> number 1) (loop for fac from 2 to (isqrt number) never (zerop (mod number fac))))) (defun next-prime (number) (loop for n from number when (primep n) return n)) (defmacro do-primes ((var start end) &body body) (with-gensyms (ending-value-name) `(do ((,var (next-prime ,start) (next-prime (1+ ,var))) (,ending-value-name ,end)) ((> ,var ,ending-value-name)) ,@body))) (defmacro with-gensyms ((&rest names) &body body) `(let ,(loop for n in names collect `(,n (gensym))) ,@body))
689
Common Lisp
.lisp
22
27.227273
76
0.620846
cccons/practical-common-lisp
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f0041cf8a61ccabaa1893f08a182f543a0fe793b9174ecb765e3b39a9c27faee
23,494
[ -1 ]
23,495
ch09.lisp
cccons_practical-common-lisp/src/ch09/ch09.lisp
(defpackage #:ch09 (:use #:cl #:ch08) (:export #:deftest #:check #:combine-results #:report-result)) (defvar *test-name* nil) (defmacro deftest (name parameters &body body) `(defun ,name ,parameters (let ((*test-name* (append *test-name* (list ',name)))) ,@body))) (defmacro check (&body forms) `(combine-results ,@(loop for f in forms collect `(report-result ,f ',f)))) (defmacro combine-results (&body forms) (ch08:with-gensyms (result) `(let ((,result t)) ,@(loop for f in forms collect `(unless ,f (setf ,result nil))) ,result))) (defun report-result (result form) (format t "~:[fail~;pass~] ... ~a: ~a~%" result *test-name* form) result)
716
Common Lisp
.lisp
24
25.791667
70
0.621543
cccons/practical-common-lisp
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7631ef6474772f9287eb08e7ad0bc07b9b8e12f7f1d589b39e3177a87bfde4c1
23,495
[ -1 ]
23,516
sketch.lisp
obsfx_common-lisp-sketches/sketch.lisp
;;; Common Lisp Sketches ; function definition (defun print-line (output) (format t "output -> ~A~%" output)) (print-line "Hello World") ; function definition with key parameters and default values (defun distance (&key (x 0) (y 0)) (sqrt (+ (* x x) (* y y)))) (print-line (distance)) (print-line (distance :x 3 :y 4)) ; multiple value return (defun vector2d (x y) (values x y)) (defvar *vector* (multiple-value-bind (x y) (vector2d 5 1) (list x y))) ; get first element of list (print-line "--------") (print-line (nth 0 *vector*)) (print-line (nth 1 *vector*)) (print-line (car *vector*)) (print-line (cdr *vector*)) (print-line "--------") ; car ; It takes a list as argument, and returns its first element. ; ; cdr ; It takes a list as argument, and returns a list without the first element ; ; cons ; It takes two arguments, an element and a list and returns a list with the element inserted at the first place. ; ; list ; It takes any number of arguments and returns a list with the arguments as member elements of the list. ; ; append ; It merges two or more list into one. ; ; last ; It takes a list and returns a list containing the last element. ; ; member ; It takes two arguments of which the second must be a list, if the first argument is a member of the second argument, and then it returns the remainder of the list beginning with the first argument. ; ; reverse ; It takes a list and returns a list with the top elements in reverse order. (defun multiply (numbers) (if (> (length numbers) 0) (* (car numbers) (multiply (cdr numbers))) 1)) (print-line (multiply (list 2 4 8 10 20))) ; local variables (print-line "--------") (let ((x 1) (y 2) (z 3)) (print-line (multiply (list x y z)))) ; define variables whose initial values depend on previous variables (print-line "--------") (let* ((x 1) (y (+ x 2)) (z (+ x 4))) (print-line (multiply (list x y z)))) ; lexical -> static ; Dynamic variables are sort of like global variables, but more useful: they are dynamically scoped. You define them either with defvar or defparameter, the differences being: ; defparameter requires an initial value, defvar does not. ; defparameter variables are changed when code is reloaded with a new initial value, defvar variables are not. (print-line "--------") (defparameter *defp* "defparameter") (defun print-globalvar () (print-line *defp*)) (print-globalvar) (let ((*defp* "defparameter reloaded in local")) (print-globalvar)) (defvar *defv* "defvar") (defun print-globalvar () (print-line *defv*)) (print-globalvar) (let ((*defv* "defvar reloaded in local")) (print-globalvar)) (defparameter *defp* "defparameter reloaded in global") (defvar *defv* "defvar reloaded in global") (print-line *defp*) (print-line *defv*) ; modifying list (defparameter numbers (list 1 2 3 4)) (setf (nth 2 numbers) 80) (print-line numbers) ; https://lispmethods.com/symbols.html ; Essentially, symbols are objects, and, to ; access them, you either need a reference to them in memory, ; or you need to know their string name and “home package”. ; (setq bla 10) is roughly equivalent to (set 'bla 10), and can be ; thought of as “set quoted”. It sets the value of the symbol bla, ; rather than the value of the symbol stored in bla. This is an ; oversimplification, as SET won’t work on lexically scoped variables, ; while SETQ will. Have a look at their CLHS pages for more precise detail. ; https://stackoverflow.com/a/13213772/13615958 ; LAMBDA is a macro. It expands (lambda ...) to (function (lambda ...)), ; which is the equivalent of #'(lambda ...)). ; ; The macro saves you a bit of writing/reading, that's all. In the first ; version of Common Lisp (CLtL1) there was no LAMBDA macro. It has been added ; later and is now a part of ANSI Common Lisp, ; The FUNCTION special operator ; FUNCTION is a special operator. It expects a function name or a lambda ; expression. Thus the name or the lambda expression are not evaluated. ; In fact lambda expressions can't be evaluated at all. Inside FUNCTION, ; the lambda expression is not a macro form and thus will not be expanded again. ; The purpose of FUNCTION is to return the corresponding function object ; which is denoted by the name or by the lambda expression. It returns ; the function object as a value. With this special operator one can access ; the function object from global functions and lexical functions. ; progn ; The general purpose special operator progn is used for evaluating zero ; or more forms. (defun progn-test () (progn (print-line "test") (print-line "test2") (print-line "test3"))) ; hex to integer (print-line (parse-integer "5E" :radix 16)) ; integer to hex (print-line (write-to-string 60 :base 16)) ; getting argv for SBCL (defparameter argv *posix-argv*) ; reading file line by line (with-open-stream (stream "./sketch.lisp" :if-does-not-exist nil) (if stream (loop for line = (read-line stream nil nil) while line collect line))) ; reading file byte by byte (with-open-stream (stream "./sketch.lisp" :element-type '(unsigned-byte 8) :if-does-not-exist nil) (if stream (loop for byte = (read-byte stream nil nil) while byte collect byte))) ; check var exist (if (boundp 'test-var) (print-line "variable defined") (print-line "undefined variable"))
5,490
Common Lisp
.lisp
150
33.853333
199
0.709348
obsfx/common-lisp-sketches
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
df0ad8f018d173775c460037d6ad53d23cc000fe4c3883ae0b7489d95557b406
23,516
[ -1 ]
23,533
temp.lisp
jordan4ibanez_Common-Lisp-Adventure/temp.lisp
;; To list. ;; TODO: THIS IS CAUSING AN ERROR!!! ;; TODO: This error is from the getters and setters not loading into memory ; (defgeneric to-list(vec)) ; (defmethod to-list((vec vec2)) ; (list (get-x vec) (get-y vec))) ; (defmethod to-list((vec vec3)) ; (list (get-x vec) (get-y vec) (get-z vec))) ; (defmethod to-list((vec vec4)) ; (list (get-x vec) (get-y vec) (get-z vec) (get-w vec))) ;; TODO: END ERROR!!! ; ;; NOTE: This is where macros begin in this file. ; ;; Remove a bunch of boilerplate functions. ; (defmacro boilerplate-vec-operations (fun-name operation vector-type) ; `(progn ; (defmethod ,fun-name((vec integer) (operator integer)) (print "hi")) ; (defmethod ,fun-name((vec ,vector-type) (operator ,vector-type)) ; (new-vec-from-list (loop for x in (to-list vec) for y in (to-list operator) collect (,operation x y)))) ; (defmethod ,fun-name((vec ,vector-type) (operator float)) ; (new-vec-from-list (loop for x in (to-list vec) collect (,operation x operator)))) ; (defmethod ,fun-name((vec ,vector-type) (operator integer)) ; (new-vec-from-list (loop for x in (to-list vec) collect (,operation x (float operator))))))) ; ;; Note: This has been reduces to simplified types because this file might ; ;; end up a few ten thousand lines long if I don't hold back. ; ;; This is an unholy procedure ; ; (loop for fun-name in '(mul add div sub) for operation in '(* + / -) do ; ; (eval `(init-generic ,fun-name)) ; ; (loop for vector-type in '(vec2 vec3 vec4) do ; ; (eval `(boilerplate-vec-operations ,fun-name ,operation ,vector-type)))) ; ; ;; Invert (Vec * -1). Useful for random things. Wordy alternative to (mul vec -1) ; ; (defgeneric invert(vector)) ; ; (defmethod invert((vector1 vec2)) ; ; (mul vector1 -1)) ; ; (defmethod invert((vector1 vec3)) ; ; (mul vector1 -1)) ; ; (defmethod invert((vector1 vec4)) ; ; (mul vector1 -1)) ; ; (defvar my-var (new-vec 0 0))
2,001
Common Lisp
.lisp
38
51.289474
115
0.643407
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
71a8bdd693903405becc825f18603ee0d040f9966849a5dfc7291f683680f74c
23,533
[ -1 ]
23,534
main.lisp
jordan4ibanez_Common-Lisp-Adventure/main.lisp
;; Auto load all this when compiling. (eval-when (:compile-toplevel :load-toplevel :execute) (ql:quickload :cl-glfw3) (use-package :cl-glfw3) (ql:quickload :cl-opengl) (use-package :cl-opengl) (ql:quickload :trivial-main-thread) (use-package :trivial-main-thread) (ql:quickload :str) (use-package :str) (ql:quickload :infix-math) (use-package :infix-math) ;; Load up super-load. (ql:quickload :super-loader) (use-package :super-loader)) ;; Now jump into another eval-when to enable usage of eval-when (eval-when (:compile-toplevel :load-toplevel :execute) ;; Now step into local packages. (super-load "game-systems/cloml") ;; Legacy learning things. DEFINITELY should be systems. (load "game-systems/delta-time.lisp") (use-package :delta-time) (load "game-systems/entity.lisp") (use-package :entity) (load "game-systems/internal-opengl.lisp") (use-package :internal-opengl) (load "game-systems/window.lisp") (use-package :window)) ;;TODO: this is my todo ;;tt 1.) we gotta make a render api pipline ;;tt 2.) implement shaders into the game ;;tt 3.) render a triangle! ;;tt 4.) make the triangle spin ;; Pushes a new item to the end of a list. (defun push-last(the-item the-listy) (push the-item (cdr (last the-listy)))) ;; (defvar cool-test (new-vec 3 3 3)) (defun game-initialize () (setf %gl:*gl-get-proc-address* #'get-proc-address) (set-key-callback 'window:quit-on-escape) (set-window-size-callback 'update-viewport) ;; (gl:clear-color 0 0 0 0) (set-viewport 600 400) ;; Every time the REPL reloads this, it creates a new shader in the C context (igl:game-new-shader "main" "shaders/vert.vert" "shaders/frag.frag") (igl:game-new-shader-uniform "main" "cameraMatrix") (igl:game-use-shader "main") (format t "Hello, yes I am initialized!~%")) ;; Game update function. ;;note: Testing of window clear color (defvar scalar-thing 0.0) (defvar scalar-multiplier 0.25) (defvar up t) (defvar enable-flashing-debug t) ;;WARNING: This crashes if you don't wait exactly one game cycle. ;;TODO: Figure out why? ;;note: Now it's not doing it anymore, is it a driver issue or what? ;; (defvar waited-one-frame t) (defun game-update() (delta:calculate-delta-time) (if enable-flashing-debug (let ((dtime (* (delta:get-delta) scalar-multiplier))) (if up (progn (setf scalar-thing (+ scalar-thing dtime)) (if (>= scalar-thing 1.0) (progn (setf scalar-thing 1.0) (setf up nil)))) (progn (setf scalar-thing (- scalar-thing dtime)) (if (<= scalar-thing 0.0) (progn (setf scalar-thing 0.0) (setf up t))))) ;; (print scalar-thing) (window:set-clear-color-scalar scalar-thing))) (if (delta:fps-update) (window:set-title (format nil "My Cool Game | FPS: ~a" (get-fps))))) ;; (print (new-vec-from-list (loop for x in (to-list (new-vec 1 2 3)) collect (* x 2)))) ;; (window:set-clear-color 0.5 0.5 0.5) ;; (window:clear-color 1.0 1.0 1.0 1.0) ;; This is run every frame of the game. (defun game-tick-procedure() (poll-events) (game-update) (render) (swap-buffers)) (defun main-loop() ;; Graphics calls on OS X must occur in the main thread (with-body-in-main-thread () (with-init-window (:title "Window test" :width 600 :height 400) (game-initialize) (loop until (window-should-close-p) do (game-tick-procedure))))) (defun run() (sb-int:with-float-traps-masked (:invalid) (main-loop))) (run)
3,636
Common Lisp
.lisp
99
32.030303
88
0.659007
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
55d9314a4df60c20bc400e81358a3f63f92b5a24e31c8da58cc394e7d40218c7
23,534
[ -1 ]
23,535
macro.lisp
jordan4ibanez_Common-Lisp-Adventure/macro.lisp
;; Now this is just absurd. ;; Combo runner for setters & getters, automatically inferred based on vector width. (defmacro getters-and-setters() (cons 'progn (loop for axis in '(x y z w) for count in '(1 2 3 4) nconc ;; nconc is a flat list for future reference. (let ((fun-name-get (intern (string-upcase (format nil "get-~a" axis)))) (fun-name-set (intern (string-upcase (format nil "set-~a" axis))))) `(defgeneric ,fun-name-get (vec)) `(defgeneric ,fun-name-set (vec new-value)) (loop for vec-type in '(vec2 vec3 vec4) nconc (let ((slot-call (intern (string-upcase (format nil "~a-~a" vec-type axis))))) (if (<= count (vec-type-component-amount vec-type)) (progn `( (defmethod ,fun-name-get ((vec ,vec-type)) (,slot-call vec)) (defmethod ,fun-name-set ((vec ,vec-type)(new-value float)) (setf (,slot-call vec) new-value)) (defmethod ,fun-name-set ((vec ,vec-type)(new-value integer)) (setf (,slot-call vec) (float new-value)))))))))))) ;; Get number of components in the vector. (defgeneric get-components (vec)) (defmacro vector-sizes () (cons 'progn (loop for vec-type in '(vec2 vec3 vec4) for return-val in '(2 3 4) :collect `(defmethod get-components ((vec ,vec-type)) ,return-val)))) ; `(init-get-components ,vec-type ,return-val))) (vector-sizes) ;; Allows initializing raw generics from code. (defmacro init-generic (fun-name) `(progn (defgeneric ,fun-name(vec operator))))
1,798
Common Lisp
.lisp
27
50.296296
112
0.541243
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9d7b021724b396216aed2e49810b1c10c12862ae3c827d4a4e32d0ed2ad33f28
23,535
[ -1 ]
23,536
super-load.lisp
jordan4ibanez_Common-Lisp-Adventure/super-load.lisp
;; Thanks to ICan'tThinkOfAGoodName in the Lisp Discord for helping out with making this work on Windows! ; (defpackage #:super-loader ; (:nicknames :loadenstein3d) ; (:use :cl)) ; (in-package :super-loader) (export '( super-load )) (defun super-load(relative-path) "Loads an asdf system based on the relative path of the current working directory (root of project). This function is primarily aimed at game dev. You can use this to load your project specific local systems in a traditional Java/Lua/Python-like manor. The folder which encapsulates your system must match the name of your system. The .asd file which identifies your system much match the name of your system. Arg: relative-path is a list of strings. Pretend each space is walking into a new folder. Example: (super-load \"game-things/my-cool-system\") Now system :my-cool-system has been loaded, packages contained inside of it are freely available." ;; Note, Windows systems use "/" for file hierarchy. (let ((old-relative-path relative-path)) ;; This is why you don't have to append "/" to your string! (setq relative-path (concatenate 'string relative-path "/")) (handler-case (let ((system-name (car (last (pathname-directory relative-path)))) (real-path (truename relative-path))) (let ((asd-file-name (concatenate 'string system-name ".asd"))) (let ((completed-asd-path (merge-pathnames real-path asd-file-name))) (progn (asdf:load-asd completed-asd-path) (quicklisp:quickload system-name) (use-package (intern (string-upcase system-name))))))) (error () (error (format nil "super-load, ERROR! System (~a) was not found in:~%~a~%(Did you make a typo?)" (car (last (split-sequence:split-sequence #\/ old-relative-path))) (concatenate 'string (format nil "~a" (uiop:getcwd)) old-relative-path)))))))
1,964
Common Lisp
.lisp
34
51.205882
106
0.681535
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
081d9ad5da2755723fad71e5053355b63134eafbd63c65c6688f2c2c9849ac4c
23,536
[ -1 ]
23,537
delta-time.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/delta-time.lisp
(defpackage #:delta-time (:nicknames :delta) (:use :cl :cl-glfw3)) (in-package :delta-time) (export '(get-delta get-fps fps-update calculate-delta-time)) ;; Standard lispy way to get time in whatever the system resolution is. (defun get-floating-time() (float (get-internal-real-time))) ;; Standard lispy way to get the time units. (system time resolution) (defun get-floating-time-units() (float internal-time-units-per-second)) ;; Simple time calculation. Also wrappers in FPS calculation. (defvar old-time 0.0);;(get-floating-time)) (defvar delta-time 0.0) (defvar frame-time-accumulator 0.0) (defvar fps-accumulator 0) (defvar fps 0) (defvar fps-updated nil) ;; Wrapper function because mutability of delta-time is probably extremely bad. (defun get-delta() delta-time) (defun get-fps() fps) (defun fps-update() fps-updated) ;; Simple FPS calculation procedure. (defun calculate-fps() (setq frame-time-accumulator (+ frame-time-accumulator (get-delta))) (setq fps-accumulator (+ fps-accumulator 1)) ;; Do a fps & fps update. Update flag for frame. (cond ((>= frame-time-accumulator 1.0) (progn (setq fps fps-accumulator) (setq fps-accumulator 0) (setq frame-time-accumulator (- frame-time-accumulator 1.0)) (setq fps-updated t))) ;; Else there's no update, reset flag. (t (progn) (setq fps-updated nil)))) ;; Deprecated delta time calculation. Calculates to seconds. ;; DO NOT USE THIS, IT'S NOT CROSS PLATFORM! ; ;; Also it's been ransacked to only work as a double check to the current calculation. ; (defvar deprecated-delta-time 0.0) ; (defvar deprecated-old-time 0.0) ; (defun deprecated-glfw-calculate-delta-time() ; (let ((current-time (glfw:get-time))) ; (setq deprecated-delta-time (- current-time deprecated-old-time)) ; (setq deprecated-old-time current-time)) ; deprecated-delta-time) ;; This is a test in place method for utilizing built in functionality ;; Don't use this anywhere besides in update portion of main loop. (defun calculate-delta-time() (let ((current-time (get-floating-time))) (setq delta-time (/ (- current-time old-time) (get-floating-time-units))) ;; Uncomment this program to test against glfw3! (you also gotta uncomment the other function) ; (format t "BEGIN TEST:~%GLFW: ~a~%CL: ~a~%END TEST~%" (deprecated-glfw-calculate-delta-time) delta-time) (setq old-time current-time)) (calculate-fps))
2,517
Common Lisp
.lisp
61
37.491803
112
0.703522
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
26c5e18017c3834aa45bde65d77fafd14d38e8d342bf8cf0e7201dc1ae8c40b8
23,537
[ -1 ]
23,538
window.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/window.lisp
(defpackage #:window (:use :cl :cl-glfw3 :cl-opengl :cloml)) (in-package :window) (export '(render set-viewport quit-on-escape update-viewport pass-through-update-viewport set-title set-clear-color-scalar set-clear-color)) (defvar *window-size* (new-vec 0 0)) (defvar *clear-color* (new-vec 0 0 0 1)) ;; You have to reload the game to make this re-initialize unfortunately. (def-key-callback quit-on-escape (window key scancode action mod-keys) (declare (ignore window scancode mod-keys)) (when (and (eq key :escape) (eq action :press)) (set-window-should-close)) (when (and (eq key :e) (eq action :press)) (print "cool")) (when t (print (format *standard-output* "~a | ~a" key action)))) (defun render () (if *clear-color* (progn (gl:clear-color (get-x *clear-color*) (get-y *clear-color*) (get-z *clear-color*) (get-w *clear-color*)) ) (print "ERROR!!! CLEAR COLOR DOES NOT EXIST!")) ;; (print *clear-color*) (gl:clear :color-buffer) ;;note: This is just a debugging test, I don't recommend raw pushing matrices to your gl program lmao. (gl:with-pushed-matrix ;; (gl:color 0.1 0.1 0.1) (gl:rect -25 -25 25 25))) (defun set-title (new-title) (glfw:set-window-title new-title)) (defun set-viewport (width height) (gl:viewport 0 0 width height)) ;; (gl:matrix-mode :projection) ;; (gl:load-identity) ;; (gl:ortho -50 50 -50 50 -1 1) ;; (gl:matrix-mode :modelview) ;; (gl:load-identity)) (defun set-clear-color-scalar (scalar) (setf *clear-color* (new-vec scalar scalar scalar 1.0))) (defun set-clear-color (r g b) (setf *clear-color* (new-vec r g b 1.0))) ;; So we shove it into a custom thing WOOOO! (defun pass-through-update-viewport(w h) (format t "window resized to ~a, ~a~%" w h) (set-viewport w h)) ;; ^ ;; | ;; (Code generator) You have to reload the game to make this re-initialize unfortunately. (def-window-size-callback update-viewport (window w h) (declare (ignore window)) (pass-through-update-viewport w h))
2,104
Common Lisp
.lisp
57
32.719298
112
0.661736
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e3d696ee4cdee4845068fe0d7d1f2580f18ddc436084a171d086d1f9e86d88c6
23,538
[ -1 ]
23,539
entity.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/entity.lisp
;; Package in lisp is namespace in C++ and...package in java ;; System is like a library, organizes a bunch of files together. ;; So, namespace test-package I suppose. (defpackage #:entity (:nicknames :ent) (:use :cl :delta-time :cloml)) (in-package :entity) (export '( entity )) (defclass entity () ((id :initarg :id :accessor id) (pos :initform :pos :accessor pos)))
437
Common Lisp
.lisp
17
20.705882
65
0.622276
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
924601bdea95b61ceeeb143c81847966ed57452532c21865e5f8c2d8a6a3a662
23,539
[ -1 ]
23,540
internal-opengl.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/internal-opengl.lisp
(defpackage #:internal-opengl (:nicknames :igl) (:use :cl :cl-glfw3 :cl-opengl :str)) (in-package :internal-opengl) (export '(game-new-shader game-use-shader game-get-shader game-delete-shader game-has-shader game-new-shader-uniform)) ;; This is one of my java packages translated to lisp, might be sloppy! (defstruct shader (name nil :type string) (program-id -1 :type integer) (uniforms (make-hash-table :test 'equal) :type hash-table)) ;; This is so make-shader still exists as longhand. (defun game-make-shader (name program-id) "Optional constructor bolt on function for shaders." (make-shader :name name :program-id program-id)) ;; Holds all the shaders (defvar *shaders* (make-hash-table :test 'equal)) (defun game-get-shader (shader-name) (gethash shader-name *shaders*)) (defun game-get-shader-program-id (shader-name) (shader-program-id (game-get-shader shader-name))) (defun game-get-shader-uniforms (shader-name) "Returns the hash table of the shader's uniforms" (shader-uniforms (game-get-shader shader-name))) (defun game-new-shader-uniform (shader-name uniform-name) (let* ((program-id (game-get-shader-program-id shader-name)) (uniform-location (gl:get-uniform-location program-id uniform-name))) (if (< uniform-location 0) (error (format t "ERROR! Shader (~a) uniform (~a) does not exist! Got (~a)!~%" shader-name uniform-name uniform-location)) (format t "Shader (~a) uniform (~a) at location (~a)~%" shader-name uniform-name uniform-location)) (setf (gethash uniform-name (game-get-shader-uniforms shader-name)) uniform-location))) (defun game-get-shader-uniform (shader-name uniform-name) "Returns the uniform's location" (gethash uniform-name (game-get-shader-uniforms shader-name))) (defun game-delete-shader (shader-name) (remhash shader-name *shaders*)) (defun game-has-shader (shader-name) (if (game-get-shader shader-name) t nil)) ;; (defclass Shader direct-superclasses direct-slots) ;; (error "~A does not exist" 'test) ;; (print *shaders*) ;; (setf (gethash 'cool *shaders*) 23) ;; (loop for i from 1 to 10 do ;; (format t "hi ~a~%" i)) ;; That was surprisingly easy ;; (print ;; (str:from-file ;; (truename "shaders/frag.frag"))) ;; GL shader ;;note: for some reason this does not works ;; (print gl:fragment-shader) ;;note: So this is how we get access to frag shader type ;; (print 'fragment-shader) ;; A helper function to turn the shader file location into a string (defun shader-location-to-string (location) (str:from-file (truename location))) ;; So this is the constructor function for creating a new shader (defun game-new-shader (shader-name vert-source-code-location frag-source-code-location) ;; Automatically refresh the shader in the current OpenGL context for REPL. ;; Because: Shader is now stale, the OpenGL context is a different pointer. (if (game-has-shader shader-name) (progn (format t "WARNING! Overwriting shader (~a)!~%" shader-name) (game-delete-shader shader-name))) (let ((vert (gl:create-shader :vertex-shader)) (vert-code (shader-location-to-string vert-source-code-location)) (frag (gl:create-shader :fragment-shader)) (frag-code (shader-location-to-string frag-source-code-location)) (program-id 0)) ;; Assign shader source components. (gl:shader-source vert vert-code) (gl:shader-source frag frag-code) ;; Compile shader source. (gl:compile-shader vert) (gl:compile-shader frag) ;; Now bring our actual program into existence (setf program-id (gl:create-program)) ;; Now attach the components. (gl:attach-shader program-id vert) (gl:attach-shader program-id frag) ;; Now link the program (gl:link-program program-id) ;; And if we didn't get an error, create an object from the shader and store it for further use! (setf (gethash shader-name *shaders*) (game-make-shader shader-name program-id)) (format t "New shader (~a) created!~%" shader-name))) ;; (defun game-create-uniform (shader-name uniform-name) ;; (let* ((program-id (game-get-shader-program-id shader-name)) ;; (location (gl:get-uniform-location ))))) ;; (format t "~a~%" (gethash "main" *shaders*)) ;; (if (gethash "main" *shaders*) ;; "Key exists" ;; "Key does not exist") ;; (defun print-hash-entry (key value) ;; (format t "The value associated with the key ~S is ~S~%" key value)) ;; (maphash #'print-hash-entry *shaders*) (defun game-use-shader (shader-name) (if (game-has-shader shader-name) (progn (format t "Using shader (~a)~%" shader-name) (let ((shader-struct (game-get-shader shader-name))) (format t "~a~%" shader-struct) (gl:use-program (shader-program-id shader-struct)))) (format t "ERROR: Tried to use non-existent shader! (~a) does not exist!" shader-name)))
5,012
Common Lisp
.lisp
113
40.017699
130
0.688578
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f74fa500cb20012def308a7f76769feaa25b8e08c5be1bf72c05f9aaa21d5e7d
23,540
[ -1 ]
23,541
game-math.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/cloml/game-math.lisp
; (defpackage #:game-math ; (:nicknames :gm) ; (:use :cl)) (in-package :cloml) (export '(pi-half fma cos-from-sin)) (defconstant pi-half (/ pi 2.0)) (defconstant pi-2 (* pi 2.0)) (defun fma (x y z) (+ (* x y) z)) (defun cos-from-sin (sin angle) (let ((cos (sqrt (- 1.0 (* sin sin)))) (a (+ angle pi-half))) (let ((b (* (- a (/ a pi-2)) pi2))) (if (< b 0.0) (setf b (+ b pi2))) (if (>= b pi) (* cos -1.0)) cos)))
492
Common Lisp
.lisp
19
20.894737
46
0.465812
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1539b8c02e74844452d37ddd17c7fb7dd3bd7a0fd2b93b05428fd64bb5400d81
23,541
[ -1 ]
23,542
vector.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/cloml/vector.lisp
;; A quick note. ;; Anyone that says to write any of this out as a macro: ;; ;; This is easier to understand and maintain for myself. ;; I am doing this for fun. And macroing this does not feel fun at all. ;; If you would like to implement this as a macro, see "macro.lisp" in ;; the root directory. That should get you started. ;;TODO: Translate JOML. (in-package :cloml) (export '( vec2 vec3 vec4 new-vec blank-vec clone-vec clone-into-vec new-vec-from-list new-list-from-vec vec-type-component-amount print-vec get-x get-y get-z get-w set-x set-y set-z set-w set-vec2 set-vec3 set-vec4 add sub mul div vec2-add vec3-add vec4-add vec2-sub vec3-sub vec4-sub vec2-mul vec3-mul vec4-mul vec2-div vec3-div vec4-div add-new sub-new mul-new div-new vec2-add-new vec3-add-new vec4-add-new vec2-sub-new vec3-sub-new vec4-sub-new vec2-mul-new vec3-mul-new vec4-mul-new vec2-div-new vec3-div-new vec4-div-new inv)) ;; Base structures. Data containers, do not need OOP flexibility. (defstruct vec2 (x 0.0 :type float) (y 0.0 :type float)) (defstruct vec3 (x 0.0 :type float) (y 0.0 :type float) (z 0.0 :type float)) (defstruct vec4 (x 0.0 :type float) (y 0.0 :type float) (z 0.0 :type float) (w 0.0 :type float)) ;; Constructor with auto dispatch. Just dumps integers into floating point. (defun new-vec (x y &optional z w) (cond ((not (null w)) (make-vec4 :x (float x) :y (float y) :z (float z) :w (float w))) ((not (null z)) (make-vec3 :x (float x) :y (float y) :z (float z))) (t (make-vec2 :x (float x) :y (float y))))) (defgeneric blank-vec (size) (:documentation "Create a new vec initialized to 0.0 for all components.") (:method ((size integer)) (cond ((eq size 2) (make-vec2 :x 0.0 :y 0.0)) ((eq size 3) (make-vec3 :x 0.0 :y 0.0 :z 0.0)) ((eq size 4) (make-vec4 :x 0.0 :y 0.0 :z 0.0 :w 0.0))))) ;; Simple vec cloning utility. Creates a new vec. (defgeneric clone-vec (vec) (:documentation "Clone a vector. Creates a new vec.") (:method ((vec vec2)) (new-vec (get-x vec) (get-y vec))) (:method ((vec vec3)) (new-vec (get-x vec) (get-y vec) (get-z vec))) (:method ((vec vec4)) (new-vec (get-x vec) (get-y vec) (get-z vec) (get-w vec)))) ;; Clones one vector INTO another. ;; So (clone-into-vec A B) A will take all the values of B. (defgeneric clone-into-vec (vec other) (:documentation "Clones a vector into another. (clone-into-vec A B) A takes on all values of B. Chainable.") (:method ((vec vec2) (other vec2)) (set-x vec (get-x other)) (set-y vec (get-y other)) vec) (:method ((vec vec3) (other vec3)) (set-x vec (get-x other)) (set-y vec (get-y other)) (set-z vec (get-z other)) vec) (:method ((vec vec4) (other vec4)) (set-x vec (get-x other)) (set-y vec (get-y other)) (set-z vec (get-z other)) (set-w vec (get-w other)) vec)) ;; Constructor with auto dispatch for lists. Just dumps integers into floating point. (defun new-vec-from-list (input-list) (cond ((= (length input-list) 2) (make-vec2 :x (float (nth 0 input-list)) :y (float (nth 1 input-list)))) ((= (length input-list) 3) (make-vec3 :x (float (nth 0 input-list)) :y (float (nth 1 input-list)) :z (float (nth 2 input-list)))) ((= (length input-list) 4) (make-vec4 :x (float (nth 0 input-list)) :y (float (nth 1 input-list)) :z (float (nth 2 input-list)) :w (float (nth 3 input-list)))))) ;; Creates a list from a vector. (defun new-list-from-vec (vec) (cond ((eql (type-of vec) 'vec2) (list (get-x vec) (get-y vec))) ((eql (type-of vec) 'vec3) (list (get-x vec) (get-y vec) (get-z vec))) ((eql (type-of vec) 'vec4) (list (get-x vec) (get-y vec) (get-z vec) (get-w vec))))) ;; Pass it 'vec2 'vec3 or 'vec4 and you get 2 3 or 4. (defun vec-type-component-amount (vec-type) (cond ((eql vec-type 'vec2) 2) ((eql vec-type 'vec3) 3) ((eql vec-type 'vec4) 4) (t 0))) ;; Vector printer. (defgeneric print-vec (vec) (:documentation "Prints out a vector.") (:method ((vec vec2)) (format t "vec2(~a, ~a)" (vec2-x vec) (vec2-y vec))) (:method ((vec vec3)) (format t "vec3(~a, ~a, ~a)" (vec3-x vec) (vec3-y vec) (vec3-z vec))) (:method ((vec vec4)) (format t "vec4(~a, ~a, ~a, ~a)" (vec4-x vec) (vec4-y vec) (vec4-z vec) (vec4-w vec)))) ;; OOP getter methods. (defgeneric get-x (vec) (:documentation "Get X component of vec2 vec3 vec4.") (:method ((vec vec2)) (vec2-x vec)) (:method ((vec vec3)) (vec3-x vec)) (:method ((vec vec4)) (vec4-x vec))) (defgeneric get-y (vec) (:documentation "Get Y component of vec2 vec3 vec4.") (:method ((vec vec2)) (vec2-y vec)) (:method ((vec vec3)) (vec3-y vec)) (:method ((vec vec4)) (vec4-y vec))) (defgeneric get-z (vec) (:documentation "Get Z component of vec3 vec4.") (:method ((vec vec3)) (vec3-z vec)) (:method ((vec vec4)) (vec4-z vec))) (defgeneric get-w (vec) (:documentation "Get W component of vec4.") (:method ((vec vec4)) (vec4-z vec))) ;; OOP setter methods. ;; Returns the modified vector. (defgeneric set-x (vec new-value) (:documentation "Set X component of vec2 vec3 vec4. Returns the modified vector.") ;; Float. (:method ((vec vec2) (new-value float)) (setf (vec2-x vec) new-value) vec) (:method ((vec vec3) (new-value float)) (setf (vec3-x vec) new-value) vec) (:method ((vec vec4) (new-value float)) (setf (vec4-x vec) new-value) vec) ;; Integer. (:method ((vec vec2) (new-value integer)) (setf (vec2-x vec) (float new-value)) vec) (:method ((vec vec3) (new-value integer)) (setf (vec3-x vec) (float new-value)) vec) (:method ((vec vec4) (new-value integer)) (setf (vec4-x vec) (float new-value)) vec)) (defgeneric set-y (vec new-value) (:documentation "Set Y component of vec2 vec3 vec4. Returns the modified vector.") ;; Float. (:method ((vec vec2) (new-value float)) (setf (vec2-y vec) new-value) vec) (:method ((vec vec3) (new-value float)) (setf (vec3-y vec) new-value) vec) (:method ((vec vec4) (new-value float)) (setf (vec4-y vec) new-value) vec) ;;Integer (:method ((vec vec2) (new-value integer)) (setf (vec2-y vec) (float new-value)) vec) (:method ((vec vec3) (new-value integer)) (setf (vec3-y vec) (float new-value)) vec) (:method ((vec vec4) (new-value integer)) (setf (vec4-y vec) (float new-value)) vec)) (defgeneric set-z (vec new-value) (:documentation "Set Z component of vec3 vec4. Returns the modified vector.") ;; Float. (:method ((vec vec3) (new-value float)) (setf (vec3-z vec) new-value) vec) (:method ((vec vec4) (new-value float)) (setf (vec4-z vec) new-value) vec) ;; Integer. (:method ((vec vec3) (new-value integer)) (setf (vec3-z vec) (float new-value)) vec) (:method ((vec vec4) (new-value integer)) (setf (vec4-z vec) (float new-value)) vec)) (defgeneric set-w (vec new-value) (:documentation "Set W component of vec3 vec4. Returns the modified vector.") ;; Float. (:method ((vec vec4) (new-value float)) (setf (vec4-w vec) new-value) vec) ;; Integer. (:method ((vec vec4) (new-value integer)) (setf (vec4-w vec) (float new-value)) vec)) ;;! Specialty setters ;; Useful for messing with REPL or maybe you want to do something special? (defgeneric set-vec2 (vec x y) (:documentation "Set the values of a vec2. \"vec\" is mutated during this procedure! Chainable.") (:method ((vec vec2) (x float) (y float)) (set-x vec x) (set-y vec y) vec) (:method ((vec vec2) (x integer) (y integer)) (set-x vec (float x)) (set-y vec (float y)) vec)) (defgeneric set-vec3 (vec x y z) (:documentation "Set the values of a vec3. \"vec\" is mutated during this procedure! Chainable.") (:method ((vec vec3) (x float) (y float) (z float)) (set-x vec x) (set-y vec y) (set-z vec z) vec) (:method ((vec vec2) (x integer) (y integer) (z integer)) (set-x vec (float x)) (set-y vec (float y)) (set-z vec (float z)) vec)) (defgeneric set-vec4 (vec x y z w) (:documentation "Set the values of a vec4. \"vec\" is mutated during this procedure! Chainable.") (:method ((vec vec4) (x float) (y float) (z float) (w float)) (set-x vec x) (set-y vec y) (set-z vec z) (set-w vec w) vec) (:method ((vec vec2) (x integer) (y integer) (z integer) (w integer)) (set-x vec (float x)) (set-y vec (float y)) (set-z vec (float z)) (set-w vec (float w)) vec)) ;;! Mutable operations. ;; Note: All mutable methods return input to allow chaining. ;; I think I've seen this before, hmm. ;; Vec is explicitly returned for readability. (defgeneric add (vec other) (:documentation "Add a vector to other vector of same type or a number. \"vec\" is mutated during this procedure! Chainable.") ;; Vec + Vec. (:method ((vec vec2) (other vec2)) (set-x vec (+ (get-x vec) (get-x other))) (set-y vec (+ (get-y vec) (get-y other))) vec) (:method ((vec vec3) (other vec3)) (set-x vec (+ (get-x vec) (get-x other))) (set-y vec (+ (get-y vec) (get-y other))) (set-z vec (+ (get-z vec) (get-z other))) vec) (:method ((vec vec4) (other vec4)) (set-x vec (+ (get-x vec) (get-x other))) (set-y vec (+ (get-y vec) (get-y other))) (set-z vec (+ (get-z vec) (get-z other))) (set-w vec (+ (get-w vec) (get-w other))) vec) ;; Vec + scalar float. (:method ((vec vec2) (other float)) (set-x vec (+ (get-x vec) other)) (set-y vec (+ (get-y vec) other)) vec) (:method ((vec vec3) (other float)) (set-x vec (+ (get-x vec) other)) (set-y vec (+ (get-y vec) other)) (set-z vec (+ (get-z vec) other)) vec) (:method ((vec vec4) (other float)) (set-x vec (+ (get-x vec) other)) (set-y vec (+ (get-y vec) other)) (set-z vec (+ (get-z vec) other)) (set-w vec (+ (get-w vec) other)) vec) ;; Vec + scalar integer. (:method ((vec vec2) (other integer)) (set-x vec (+ (get-x vec) (float other))) (set-y vec (+ (get-y vec) (float other))) vec) (:method ((vec vec3) (other integer)) (set-x vec (+ (get-x vec) (float other))) (set-y vec (+ (get-y vec) (float other))) (set-z vec (+ (get-z vec) (float other))) vec) (:method ((vec vec4) (other integer)) (set-x vec (+ (get-x vec) (float other))) (set-y vec (+ (get-y vec) (float other))) (set-z vec (+ (get-z vec) (float other))) (set-w vec (+ (get-w vec) (float other))) vec)) (defgeneric sub (vec other) (:documentation "Subtract a vector to other vector of same type or a number. \"vec\" is mutated during this procedure! Chainable.") ;; Vec - Vec. (:method ((vec vec2) (other vec2)) (set-x vec (- (get-x vec) (get-x other))) (set-y vec (- (get-y vec) (get-y other))) vec) (:method ((vec vec3) (other vec3)) (set-x vec (- (get-x vec) (get-x other))) (set-y vec (- (get-y vec) (get-y other))) (set-z vec (- (get-z vec) (get-z other))) vec) (:method ((vec vec4) (other vec4)) (set-x vec (- (get-x vec) (get-x other))) (set-y vec (- (get-y vec) (get-y other))) (set-z vec (- (get-z vec) (get-z other))) (set-w vec (- (get-w vec) (get-w other))) vec) ;; Vec - scalar float. (:method ((vec vec2) (other float)) (set-x vec (- (get-x vec) other)) (set-y vec (- (get-y vec) other)) vec) (:method ((vec vec3) (other float)) (set-x vec (- (get-x vec) other)) (set-y vec (- (get-y vec) other)) (set-z vec (- (get-z vec) other)) vec) (:method ((vec vec4) (other float)) (set-x vec (- (get-x vec) other)) (set-y vec (- (get-y vec) other)) (set-z vec (- (get-z vec) other)) (set-w vec (- (get-w vec) other)) vec) ;; Vec - scalar integer. (:method ((vec vec2) (other integer)) (set-x vec (- (get-x vec) (float other))) (set-y vec (- (get-y vec) (float other))) vec) (:method ((vec vec3) (other integer)) (set-x vec (- (get-x vec) (float other))) (set-y vec (- (get-y vec) (float other))) (set-z vec (- (get-z vec) (float other))) vec) (:method ((vec vec4) (other integer)) (set-x vec (- (get-x vec) (float other))) (set-y vec (- (get-y vec) (float other))) (set-z vec (- (get-z vec) (float other))) (set-w vec (- (get-w vec) (float other))) vec)) (defgeneric mul (vec other) (:documentation "Multiply a vector to other vector of same type or a number. \"vec\" is mutated during this procedure! Chainable.") ;; Vec * Vec. (:method ((vec vec2) (other vec2)) (set-x vec (* (get-x vec) (get-x other))) (set-y vec (* (get-y vec) (get-y other))) vec) (:method ((vec vec3) (other vec3)) (set-x vec (* (get-x vec) (get-x other))) (set-y vec (* (get-y vec) (get-y other))) (set-z vec (* (get-z vec) (get-z other))) vec) (:method ((vec vec4) (other vec4)) (set-x vec (* (get-x vec) (get-x other))) (set-y vec (* (get-y vec) (get-y other))) (set-z vec (* (get-z vec) (get-z other))) (set-w vec (* (get-w vec) (get-w other))) vec) ;; Vec * scalar float. (:method ((vec vec2) (other float)) (set-x vec (* (get-x vec) other)) (set-y vec (* (get-y vec) other)) vec) (:method ((vec vec3) (other float)) (set-x vec (* (get-x vec) other)) (set-y vec (* (get-y vec) other)) (set-z vec (* (get-z vec) other)) vec) (:method ((vec vec4) (other float)) (set-x vec (* (get-x vec) other)) (set-y vec (* (get-y vec) other)) (set-z vec (* (get-z vec) other)) (set-w vec (* (get-w vec) other)) vec) ;; Vec * scalar integer. (:method ((vec vec2) (other integer)) (set-x vec (* (get-x vec) (float other))) (set-y vec (* (get-y vec) (float other))) vec) (:method ((vec vec3) (other integer)) (set-x vec (* (get-x vec) (float other))) (set-y vec (* (get-y vec) (float other))) (set-z vec (* (get-z vec) (float other))) vec) (:method ((vec vec4) (other integer)) (set-x vec (* (get-x vec) (float other))) (set-y vec (* (get-y vec) (float other))) (set-z vec (* (get-z vec) (float other))) (set-w vec (* (get-w vec) (float other))) vec)) (defgeneric div (vec other) (:documentation "Divide a vector to other vector of same type or a number. \"vec\" is mutated during this procedure! Chainable.") ;; Vec / Vec. (:method ((vec vec2) (other vec2)) (set-x vec (/ (get-x vec) (get-x other))) (set-y vec (/ (get-y vec) (get-y other))) vec) (:method ((vec vec3) (other vec3)) (set-x vec (/ (get-x vec) (get-x other))) (set-y vec (/ (get-y vec) (get-y other))) (set-z vec (/ (get-z vec) (get-z other))) vec) (:method ((vec vec4) (other vec4)) (set-x vec (/ (get-x vec) (get-x other))) (set-y vec (/ (get-y vec) (get-y other))) (set-z vec (/ (get-z vec) (get-z other))) (set-w vec (/ (get-w vec) (get-w other))) vec) ;; Vec / scalar float. (:method ((vec vec2) (other float)) (set-x vec (/ (get-x vec) other)) (set-y vec (/ (get-y vec) other)) vec) (:method ((vec vec3) (other float)) (set-x vec (/ (get-x vec) other)) (set-y vec (/ (get-y vec) other)) (set-z vec (/ (get-z vec) other)) vec) (:method ((vec vec4) (other float)) (set-x vec (/ (get-x vec) other)) (set-y vec (/ (get-y vec) other)) (set-z vec (/ (get-z vec) other)) (set-w vec (/ (get-w vec) other)) vec) ;; Vec / scalar integer. (:method ((vec vec2) (other integer)) (set-x vec (/ (get-x vec) (float other))) (set-y vec (/ (get-y vec) (float other))) vec) (:method ((vec vec3) (other integer)) (set-x vec (/ (get-x vec) (float other))) (set-y vec (/ (get-y vec) (float other))) (set-z vec (/ (get-z vec) (float other))) vec) (:method ((vec vec4) (other integer)) (set-x vec (/ (get-x vec) (float other))) (set-y vec (/ (get-y vec) (float other))) (set-z vec (/ (get-z vec) (float other))) (set-w vec (/ (get-w vec) (float other))) vec)) ;;* Mutable type specific generic operations. ;;* Unfortunately, due to mixed typing, I have to make these functions. ;;* There's probably a better way to do this part though. (defun vec2-add (vec x y) "Add a numeric x y value to a vec2. \"vec\" is mutated during this procedure! Chainable." (set-x vec (+ (get-x vec) (float x))) (set-y vec (+ (get-y vec) (float y))) vec) (defun vec3-add (vec x y z) "Add a numeric x y z value to a vec3. \"vec\" is mutated during this procedure! Chainable." (set-x vec (+ (get-x vec) (float x))) (set-y vec (+ (get-y vec) (float y))) (set-z vec (+ (get-z vec) (float z))) vec) (defun vec4-add (vec x y z w) "Add a numeric x y z w value to a vec4. \"vec\" is mutated during this procedure! Chainable." (set-x vec (+ (get-x vec) (float x))) (set-y vec (+ (get-y vec) (float y))) (set-z vec (+ (get-z vec) (float z))) (set-w vec (+ (get-w vec) (float w))) vec) (defun vec2-sub (vec x y) "Subtract a numeric x y value from a vec2. \"vec\" is mutated during this procedure! Chainable." (set-x vec (- (get-x vec) (float x))) (set-y vec (- (get-y vec) (float y))) vec) (defun vec3-sub (vec x y z) "Subtract a numeric x y z value from a vec3. \"vec\" is mutated during this procedure! Chainable." (set-x vec (- (get-x vec) (float x))) (set-y vec (- (get-y vec) (float y))) (set-z vec (- (get-z vec) (float z))) vec) (defun vec4-sub (vec x y z w) "Subtract a numeric x y z w value from a vec4. \"vec\" is mutated during this procedure! Chainable." (set-x vec (- (get-x vec) (float x))) (set-y vec (- (get-y vec) (float y))) (set-z vec (- (get-z vec) (float z))) (set-w vec (- (get-w vec) (float w))) vec) (defun vec2-mul (vec x y) "Multiply a vec2 by a numeric x y value. \"vec\" is mutated during this procedure! Chainable." (set-x vec (* (get-x vec) (float x))) (set-y vec (* (get-y vec) (float y))) vec) (defun vec3-mul (vec x y z) "Multiply a vec3 by a numeric x y z value. \"vec\" is mutated during this procedure! Chainable." (set-x vec (* (get-x vec) (float x))) (set-y vec (* (get-y vec) (float y))) (set-z vec (* (get-z vec) (float z))) vec) (defun vec4-mul (vec x y z w) "Multiply a vec4 by a numeric x y z w value. \"vec\" is mutated during this procedure! Chainable." (set-x vec (* (get-x vec) (float x))) (set-y vec (* (get-y vec) (float y))) (set-z vec (* (get-z vec) (float z))) (set-w vec (* (get-w vec) (float w))) vec) (defun vec2-div (vec x y) "Divide a vec2 by a numeric x y value. \"vec\" is mutated during this procedure! Chainable." (set-x vec (/ (get-x vec) (float x))) (set-y vec (/ (get-y vec) (float y))) vec) (defun vec3-div (vec x y z) "Divide a vec3 by a numeric x y z value. \"vec\" is mutated during this procedure! Chainable." (set-x vec (/ (get-x vec) (float x))) (set-y vec (/ (get-y vec) (float y))) (set-z vec (/ (get-z vec) (float z))) vec) (defun vec4-div (vec x y z w) "Divide a vec4 by a numeric x y z w value. \"vec\" is mutated during this procedure! Chainable." (set-x vec (/ (get-x vec) (float x))) (set-y vec (/ (get-y vec) (float y))) (set-z vec (/ (get-z vec) (float z))) (set-w vec (/ (get-w vec) (float w))) vec) ;;! Immutable operations. (defgeneric add-new (vec other) (:documentation "Add a vector to other vector of same type or a number. Returns a NEW vector!") ;; Vec + Vec. (:method ((vec vec2) (other vec2)) (new-vec (+ (get-x vec) (get-x other)) (+ (get-y vec) (get-y other)))) (:method ((vec vec3) (other vec3)) (new-vec (+ (get-x vec) (get-x other)) (+ (get-y vec) (get-y other)) (+ (get-z vec) (get-z other)))) (:method ((vec vec4) (other vec4)) (new-vec (+ (get-x vec) (get-x other)) (+ (get-y vec) (get-y other)) (+ (get-z vec) (get-z other)) (+ (get-w vec) (get-w other)))) ;; Vec + scalar float. (:method ((vec vec2) (other float)) (new-vec (+ (get-x vec) other) (+ (get-y vec) other))) (:method ((vec vec3) (other float)) (new-vec (+ (get-x vec) other) (+ (get-y vec) other) (+ (get-z vec) other))) (:method ((vec vec4) (other float)) (new-vec (+ (get-x vec) other) (+ (get-y vec) other) (+ (get-z vec) other) (+ (get-w vec) other))) ;; Vec + scalar integer. (:method ((vec vec2) (other integer)) (new-vec (+ (get-x vec) (float other)) (+ (get-y vec) (float other)))) (:method ((vec vec3) (other integer)) (new-vec (+ (get-x vec) (float other)) (+ (get-y vec) (float other)) (+ (get-z vec) (float other)))) (:method ((vec vec4) (other integer)) (new-vec (+ (get-x vec) (float other)) (+ (get-y vec) (float other)) (+ (get-z vec) (float other)) (+ (get-w vec) (float other))))) (defgeneric sub-new (vec other) (:documentation "Subtract a vector to other vector of same type or a number. Returns a NEW vector!") ;; Vec - Vec. (:method ((vec vec2) (other vec2)) (new-vec (- (get-x vec) (get-x other)) (- (get-y vec) (get-y other)))) (:method ((vec vec3) (other vec3)) (new-vec (- (get-x vec) (get-x other)) (- (get-y vec) (get-y other)) (- (get-z vec) (get-z other)))) (:method ((vec vec4) (other vec4)) (new-vec (- (get-x vec) (get-x other)) (- (get-y vec) (get-y other)) (- (get-z vec) (get-z other)) (- (get-w vec) (get-w other)))) ;; Vec - scalar float. (:method ((vec vec2) (other float)) (new-vec (- (get-x vec) other) (- (get-y vec) other))) (:method ((vec vec3) (other float)) (new-vec (- (get-x vec) other) (- (get-y vec) other) (- (get-z vec) other))) (:method ((vec vec4) (other float)) (new-vec (- (get-x vec) other) (- (get-y vec) other) (- (get-z vec) other) (- (get-w vec) other))) ;; Vec - scalar integer. (:method ((vec vec2) (other integer)) (new-vec (- (get-x vec) (float other)) (- (get-y vec) (float other)))) (:method ((vec vec3) (other integer)) (new-vec (- (get-x vec) (float other)) (- (get-y vec) (float other)) (- (get-z vec) (float other)))) (:method ((vec vec4) (other integer)) (new-vec (- (get-x vec) (float other)) (- (get-y vec) (float other)) (- (get-z vec) (float other)) (- (get-w vec) (float other))))) (defgeneric mul-new (vec other) (:documentation "Multiply a vector to other vector of same type or a number. Returns a NEW vector!") ;; Vec * Vec. (:method ((vec vec2) (other vec2)) (new-vec (* (get-x vec) (get-x other)) (* (get-y vec) (get-y other)))) (:method ((vec vec3) (other vec3)) (new-vec (* (get-x vec) (get-x other)) (* (get-y vec) (get-y other)) (* (get-z vec) (get-z other)))) (:method ((vec vec4) (other vec4)) (new-vec (* (get-x vec) (get-x other)) (* (get-y vec) (get-y other)) (* (get-z vec) (get-z other)) (* (get-w vec) (get-w other)))) ;; Vec * scalar float. (:method ((vec vec2) (other float)) (new-vec (* (get-x vec) other) (* (get-y vec) other))) (:method ((vec vec3) (other float)) (new-vec (* (get-x vec) other) (* (get-y vec) other) (* (get-z vec) other))) (:method ((vec vec4) (other float)) (new-vec (* (get-x vec) other) (* (get-y vec) other) (* (get-z vec) other) (* (get-w vec) other))) ;; Vec * scalar integer. (:method ((vec vec2) (other integer)) (new-vec (* (get-x vec) (float other)) (* (get-y vec) (float other)))) (:method ((vec vec3) (other integer)) (new-vec (* (get-x vec) (float other)) (* (get-y vec) (float other)) (* (get-z vec) (float other)))) (:method ((vec vec4) (other integer)) (new-vec (* (get-x vec) (float other)) (* (get-y vec) (float other)) (* (get-z vec) (float other)) (* (get-w vec) (float other))))) (defgeneric div-new (vec other) (:documentation "Divide a vector to other vector of same type or a number. Returns a NEW vector!") ;; Vec / Vec. (:method ((vec vec2) (other vec2)) (new-vec (/ (get-x vec) (get-x other)) (/ (get-y vec) (get-y other)))) (:method ((vec vec3) (other vec3)) (new-vec (/ (get-x vec) (get-x other)) (/ (get-y vec) (get-y other)) (/ (get-z vec) (get-z other)))) (:method ((vec vec4) (other vec4)) (new-vec (/ (get-x vec) (get-x other)) (/ (get-y vec) (get-y other)) (/ (get-z vec) (get-z other)) (/ (get-w vec) (get-w other)))) ;; Vec / scalar float. (:method ((vec vec2) (other float)) (new-vec (/ (get-x vec) other) (/ (get-y vec) other))) (:method ((vec vec3) (other float)) (new-vec (/ (get-x vec) other) (/ (get-y vec) other) (/ (get-z vec) other))) (:method ((vec vec4) (other float)) (new-vec (/ (get-x vec) other) (/ (get-y vec) other) (/ (get-z vec) other) (/ (get-w vec) other))) ;; Vec / scalar integer. (:method ((vec vec2) (other integer)) (new-vec (/ (get-x vec) (float other)) (/ (get-y vec) (float other)))) (:method ((vec vec3) (other integer)) (new-vec (/ (get-x vec) (float other)) (/ (get-y vec) (float other)) (/ (get-z vec) (float other)))) (:method ((vec vec4) (other integer)) (new-vec (/ (get-x vec) (float other)) (/ (get-y vec) (float other)) (/ (get-z vec) (float other)) (/ (get-w vec) (float other))))) ;;* Immutable type specific generic operations. ;;* Unfortunately, due to mixed typing, I have to make these functions. ;;* There's probably a better way to do this part though. (defun vec2-add-new (vec x y) "Add a vec2 by a numeric x y value. Returns a new vec2" (new-vec (+ (get-x vec) (float x)) (+ (get-y vec) (float y)))) (defun vec3-add-new (vec x y z) "Add a vec3 by a numeric x y z value. Returns a new vec3" (new-vec (+ (get-x vec) (float x)) (+ (get-y vec) (float y)) (+ (get-z vec) (float z)))) (defun vec4-add-new (vec x y z w) "Add a vec4 by a numeric x y z w value. Returns a new vec4" (new-vec (+ (get-x vec) (float x)) (+ (get-y vec) (float y)) (+ (get-z vec) (float z)) (+ (get-w vec) (float w)))) (defun vec2-sub-new (vec x y) "Subtract a numeric x y value from a vec2. Returns a new vec2" (new-vec (- (get-x vec) (float x)) (- (get-y vec) (float y)))) (defun vec3-sub-new (vec x y z) "Subtract a numeric x y z value from a vec2. Returns a new vec3" (new-vec (- (get-x vec) (float x)) (- (get-y vec) (float y)) (- (get-z vec) (float z)))) (defun vec4-sub-new (vec x y z w) "Subtract a numeric x y z w value from a vec2. Returns a new vec4" (new-vec (- (get-x vec) (float x)) (- (get-y vec) (float y)) (- (get-z vec) (float z)) (- (get-w vec) (float w)))) (defun vec2-mul-new (vec x y) "Multiply a vec2 by a numeric x y value. Returns a new vec2" (new-vec (* (get-x vec) (float x)) (* (get-y vec) (float y)))) (defun vec3-mul-new (vec x y z) "Multiply a vec3 by a numeric x y z value. Returns a new vec3" (new-vec (* (get-x vec) (float x)) (* (get-y vec) (float y)) (* (get-z vec) (float z)))) (defun vec4-mul-new (vec x y z w) "Multiply a vec4 by a numeric x y z w value. Returns a new vec4" (new-vec (* (get-x vec) (float x)) (* (get-y vec) (float y)) (* (get-z vec) (float z)) (* (get-w vec) (float w)))) (defun vec2-div-new (vec x y) "Divide a vec2 by a numeric x y value. Returns a new vec2" (new-vec (/ (get-x vec) (float x)) (/ (get-y vec) (float y)))) (defun vec3-div-new (vec x y z) "Divide a vec3 by a numeric x y z value. Returns a new vec3" (new-vec (/ (get-x vec) (float x)) (/ (get-y vec) (float y)) (/ (get-z vec) (float z)))) (defun vec4-div-new (vec x y z w) "Divide a vec4 by a numeric x y z w value. Returns a new vec4" (new-vec (/ (get-x vec) (float x)) (/ (get-y vec) (float y)) (/ (get-z vec) (float z)) (/ (get-w vec) (float w)))) (defgeneric inv (vec) (:documentation "Inverts a vec.") (:method ((vec vec2)) (mul vec -1) vec) (:method ((vec vec3)) (mul vec -1) vec) (:method ((vec vec4)) (mul vec -1) vec))
28,785
Common Lisp
.lisp
880
28.385227
169
0.57808
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f92f6b2bd7abd54636899440e311c2cd979977d80273c76e12b283a69e1f7284
23,542
[ -1 ]
23,543
matrix.lisp
jordan4ibanez_Common-Lisp-Adventure/game-systems/cloml/matrix.lisp
(in-package :cloml) ;; This is quite the monster list here. (export '(new-mat4 new-mat4-raw ;; This was organized like this so this file isn't a mile long. get-m00 get-m01 get-m02 get-m03 get-m10 get-m11 get-m12 get-m13 get-m20 get-m21 get-m22 get-m23 get-m30 get-m31 get-m32 get-m33 set-m00 set-m01 set-m02 set-m03 set-m10 set-m11 set-m12 set-m13 set-m20 set-m21 set-m22 set-m23 set-m30 set-m31 set-m32 set-m33 set-mat4-raw mat4-identity set-mat4 clone-mat4 mat4-set-transposed mat4-set-translation-raw mat4-set-translation mat4-set-rotation-raw mat4-set-rotation)) ;; This is JOML mat4f translated (as best as I can.) ;; This package is going to use a lot of shorthand variable names. ;; This is so I don't end up breaking my fingers trying to type it all. ;; Also, some of this may look like "why the hell are you doing it like that?". ;; I'm translating it, dumbness may be changed later on. ;; 6 bits. (defconstant plane-nx 0) (defconstant plane-px 1) (defconstant plane-ny 2) (defconstant plane-py 3) (defconstant plane-nz 4) (defconstant plane-pz 5) ;; 8 bits. (defconstant corner-nxnynz 0) (defconstant corner-pxnynz 1) (defconstant corner-pxpynz 2) (defconstant corner-nxpynz 3) (defconstant corner-pxnypz 4) (defconstant corner-nxnypz 5) (defconstant corner-nxpypz 6) (defconstant corner-pxpypz 7) ;; Bitshifted constants. ;;TODO NOTE: 1 is (1 << 1) | -1 is (1 >> 1) in Dlang! ;; (defconstant property-perspective (ash 1 0)) ;; (defconstant property-affine (ash 1 1)) ;; (defconstant property-identity (ash 1 2)) ;; (defconstant property-translation (ash 1 3)) ;; (defconstant property-orthonormal (ash 1 4)) (defstruct mat4 ;; (properties (logior (logior (logior property-orthonormal property-translation) property-affine) property-identity) :type integer) (m00 1.0 :type float)(m01 0.0 :type float)(m02 0.0 :type float)(m03 0.0 :type float) (m10 0.0 :type float)(m11 1.0 :type float)(m12 0.0 :type float)(m13 0.0 :type float) (m20 0.0 :type float)(m21 0.0 :type float)(m22 1.0 :type float)(m23 0.0 :type float) (m30 0.0 :type float)(m31 0.0 :type float)(m32 0.0 :type float)(m33 1.0 :type float)) ;; m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33 (defun new-mat4 () (new-mat4-raw 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1)) ;; I suppose this function is for when you really hate yourself. (defun new-mat4-raw (m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33) (make-mat4 :m00 (float m00) :m01 (float m01) :m02 (float m02) :m03 (float m03) :m10 (float m10) :m11 (float m11) :m12 (float m12) :m13 (float m13) :m20 (float m20) :m21 (float m21) :m22 (float m22) :m23 (float m23) :m30 (float m30) :m31 (float m31) :m32 (float m32) :m33 (float m33))) ;;Basic getters. (defun get-m00 (mat) "Get 0X0 in a mat4" (mat4-m00 mat)) (defun get-m01 (mat) "Get 0X1 in a mat4" (mat4-m01 mat)) (defun get-m02 (mat) "Get 0X2 in a mat4" (mat4-m02 mat)) (defun get-m03 (mat) "Get 0X3 in a mat4" (mat4-m03 mat)) (defun get-m10 (mat) "Get 1X0 in a mat4" (mat4-m10 mat)) (defun get-m11 (mat) "Get 1X1 in a mat4" (mat4-m11 mat)) (defun get-m12 (mat) "Get 1X2 in a mat4" (mat4-m12 mat)) (defun get-m13 (mat) "Get 1X3 in a mat4" (mat4-m13 mat)) (defun get-m20 (mat) "Get 2X0 in a mat4" (mat4-m20 mat)) (defun get-m21 (mat) "Get 2X1 in a mat4" (mat4-m21 mat)) (defun get-m22 (mat) "Get 2X2 in a mat4" (mat4-m22 mat)) (defun get-m23 (mat) "Get 2X3 in a mat4" (mat4-m23 mat)) (defun get-m30 (mat) "Get 3X0 in a mat4" (mat4-m30 mat)) (defun get-m31 (mat) "Get 3X1 in a mat4" (mat4-m31 mat)) (defun get-m32 (mat) "Get 3X2 in a mat4" (mat4-m32 mat)) (defun get-m33 (mat) "Get 3X3 in a mat4" (mat4-m33 mat)) ;; Basic setters. (defun set-m00 (mat v) "Set 0X0 in a mat4." (setf (mat4-m00 mat) (float v)) mat) (defun set-m01 (mat v) "Set 0X1 in a mat4." (setf (mat4-m01 mat) (float v)) mat) (defun set-m02 (mat v) "Set 0X2 in a mat4." (setf (mat4-m02 mat) (float v)) mat) (defun set-m03 (mat v) "Set 0X3 in a mat4." (setf (mat4-m03 mat) (float v)) mat) (defun set-m10 (mat v) "Set 1X0 in a mat4." (setf (mat4-m10 mat) (float v)) mat) (defun set-m11 (mat v) "Set 1X1 in a mat4." (setf (mat4-m11 mat) (float v)) mat) (defun set-m12 (mat v) "Set 1X2 in a mat4." (setf (mat4-m12 mat) (float v)) mat) (defun set-m13 (mat v) "Set 1X3 in a mat4." (setf (mat4-m13 mat) (float v)) mat) (defun set-m20 (mat v) "Set 2X0 in a mat4." (setf (mat4-m20 mat) (float v)) mat) (defun set-m21 (mat v) "Set 2X1 in a mat4." (setf (mat4-m21 mat) (float v)) mat) (defun set-m22 (mat v) "Set 2X2 in a mat4." (setf (mat4-m22 mat) (float v)) mat) (defun set-m23 (mat v) "Set 2X3 in a mat4." (setf (mat4-m23 mat) (float v)) mat) (defun set-m30 (mat v) "Set 3X0 in a mat4." (setf (mat4-m30 mat) (float v)) mat) (defun set-m31 (mat v) "Set 3X1 in a mat4." (setf (mat4-m31 mat) (float v)) mat) (defun set-m32 (mat v) "Set 3X2 in a mat4." (setf (mat4-m32 mat) (float v)) mat) (defun set-m33 (mat v) "Set 3X3 in a mat4." (setf (mat4-m33 mat) (float v)) mat) (defun set-mat4-raw (mat m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33) (set-m00 mat m00) (set-m01 mat m01) (set-m02 mat m02) (set-m03 mat m03) (set-m10 mat m10) (set-m11 mat m11) (set-m12 mat m12) (set-m13 mat m13) (set-m20 mat m20) (set-m21 mat m21) (set-m22 mat m22) (set-m23 mat m23) (set-m30 mat m30) (set-m31 mat m31) (set-m32 mat m32) (set-m33 mat m33) mat) (defun mat4-identity (mat) (set-m00 mat 1.0) (set-m01 mat 0.0) (set-m02 mat 0.0) (set-m03 mat 0.0) (set-m10 mat 0.0) (set-m11 mat 1.0) (set-m12 mat 0.0) (set-m13 mat 0.0) (set-m20 mat 0.0) (set-m21 mat 0.0) (set-m22 mat 1.0) (set-m23 mat 0.0) (set-m30 mat 0.0) (set-m31 mat 0.0) (set-m32 mat 0.0) (set-m33 mat 1.0) mat) (defun set-mat4 (mat other) (set-m00 mat (get-m00 other)) (set-m01 mat (get-m01 other)) (set-m02 mat (get-m02 other)) (set-m03 mat (get-m03 other)) (set-m10 mat (get-m10 other)) (set-m11 mat (get-m11 other)) (set-m12 mat (get-m12 other)) (set-m13 mat (get-m13 other)) (set-m20 mat (get-m20 other)) (set-m21 mat (get-m21 other)) (set-m22 mat (get-m22 other)) (set-m23 mat (get-m23 other)) (set-m30 mat (get-m30 other)) (set-m31 mat (get-m31 other)) (set-m32 mat (get-m32 other)) (set-m33 mat (get-m33 other))) (defun clone-mat4 (mat) (let ((clone-of-mat (new-mat4))) (set-m00 clone-of-mat (get-m00 mat)) (set-m01 clone-of-mat (get-m01 mat)) (set-m02 clone-of-mat (get-m02 mat)) (set-m03 clone-of-mat (get-m03 mat)) (set-m10 clone-of-mat (get-m10 mat)) (set-m11 clone-of-mat (get-m11 mat)) (set-m12 clone-of-mat (get-m12 mat)) (set-m13 clone-of-mat (get-m13 mat)) (set-m20 clone-of-mat (get-m20 mat)) (set-m21 clone-of-mat (get-m21 mat)) (set-m22 clone-of-mat (get-m22 mat)) (set-m23 clone-of-mat (get-m23 mat)) (set-m30 clone-of-mat (get-m30 mat)) (set-m31 clone-of-mat (get-m31 mat)) (set-m32 clone-of-mat (get-m32 mat)) (set-m33 clone-of-mat (get-m33 mat)) clone-of-mat)) (defun mat4-set-transposed (mat) (let ((nm10 (get-m01 mat)) (nm12 (get-m21 mat)) (nm13 (get-m31 mat)) (nm20 (get-m02 mat)) (nm21 (get-m12 mat)) (nm30 (get-m03 mat)) (nm31 (get-m13 mat)) (nm32 (get-m23 mat))) (set-mat4-raw mat (get-m00 mat) (get-m10 mat) (get-m20 mat) (get-m30 mat) nm10 (get-m11 mat) nm12 nm13 nm20 nm21 (get-m22 mat) (get-m32 mat) nm30 nm31 nm32 (get-m33 mat)))) (defun mat4-set-translation-raw (mat x y z) (set-m30 mat x) (set-m31 mat y) (set-m32 mat z)) (defun mat4-set-translation (mat vec) (mat4-set-translation-raw mat (get-x vec) (get-y vec) (get-z vec))) ;; This is gonna be a bit complicated (defun mat4-set-rotation-raw (mat angle-x angle-y angle-z) ;; Climb the tower (let ((sin-x (sin angle-x)) (sin-y (sin angle-y)) (sin-z (sin angle-z))) (let ((cos-x (cos-from-sin sin-x angle-x)) (cos-y (cos-from-sin sin-y angle-y)) (cos-z (cos-from-sin sin-z angle-z)) (m-sin-x (* sin-x -1.0)) (m-sin-y (* sin-y -1.0)) (m-sin-z (* sin-y -1.0))) (let (;; rotate X (nm11 cos-x) (nm12 sin-x) (nm21 m-sin-x) (nm22 cos-x)) (let (;; rotate Y (nm00 cos-y) (nm01 (* nm21 m-sin-y)) (nm02 (* nm22 m-sin-y))) (set-m20 mat sin-y) (set-m21 mat (* nm21 cos-y)) (set-m22 mat (* nm22 cos-y)) ;;rotate Z (set-m00 mat (* nm00 cos-z)) (set-m01 mat (+ (* nm01 cos-z) (* nm11 sin-z))) (set-m02 mat (+ (* nm02 cos-z) (* nm12 sin-z))) (set-m10 mat (* nm00 m-sin-z)) (set-m11 mat (+ (* nm01 m-sin-z) (* nm11 cos-z))) (set-m12 mat (+ (* nm02 m-sin-z) (* nm12 cos-z))))))) mat) (defun mat4-set-rotation (mat vec) (mat4-set-rotation-raw mat (get-x vec) (get-y vec) (get-z vec)))
9,465
Common Lisp
.lisp
302
26.731788
143
0.611904
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6a0b52bf98f6c64a372713bffa874ff7b81b28bc42c97055b6d57c2f8e791e6f
23,543
[ -1 ]
23,544
interesting-things.lisp
jordan4ibanez_Common-Lisp-Adventure/old-code/interesting-things.lisp
;;hmmm very interesting, we can also just do work on things in global state like C. ;; REPL really doesn't like resetting the vars lmao. (defvar *global-thing* 1.0) (dotimes (number 100) (setq *global-thing* (+ *global-thing* 1.1)) (print *global-thing*)) (let ((my-cool-vector (make-array 0 :fill-pointer 0 :adjustable t))) (dotimes (number 10) (vector-push-extend (* number 3) my-cool-vector)) (print my-cool-vector)) ;; Java wrappered notes ; note: (not X) where X is a (func) or boolean (setf *random-state* (make-random-state t)) ; for (int number = 10; number < 10; number++) {scope} (dotimes (number 10) ; if (1 == random(0,1)) {scope} (if (eq 1 (random 2)) (print "cool") ;else (print "not cool") ) (if (>= 10 (random 50)) (print "test")) )
796
Common Lisp
.lisp
24
30.208333
83
0.651436
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d7521903d13d1845725600a8b95069b0532684e0ad77f28fccdf3339ff77b942
23,544
[ -1 ]
23,545
cloml.asd
jordan4ibanez_Common-Lisp-Adventure/game-systems/cloml/cloml.asd
;;;; cloml.asd (asdf:defsystem "cloml" ; :serial t :description "JOML translated to lisp the best I can." :author "jordan4ibanez" :version "0.0.0" :license "GPLV3" ; :depends-on (#:cffi #:alexandria) :components ((:file "package") (:file "vector") (:file "matrix" :depends-on ("vector")) (:file "game-math")))
369
Common Lisp
.asd
12
24.833333
56
0.579832
jordan4ibanez/Common-Lisp-Adventure
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a720a59ee98525455ff48300eb13e36255fa1991c09f9bc5544f56befb9787e8
23,545
[ -1 ]
23,574
robot.lisp
karlosz_common-lisp-wpilib/examples/robot.lisp
;;;; Basic robot code (defpackage basic-robot (:use #:cl #:wpilib/iterative-robot)) (in-package #:basic-robot) (defclass my-robot (wpilib:iterative-robot) ((robot-drive :reader robot-drive :initarg :robot-drive) (stick :reader stick :initarg :stick))) (defmethod autonomous-periodic ((robot my-robot) (joystick xbox-joystick)) (drive (robot-drive robot) 0 0)) (defmethod autonomous-periodic ((robot my-robot) (joystick code-joystick)) (drive (robot-drive robot) 0 0)) (defmethod teleop-periodic ((robot my-robot)) (defun robot-main () (wpilib:run (make-instance 'my-robot :robot-drive (wpilib:make-robot-drive 0 1) :stick (wpilib:make-joystick 1))))
740
Common Lisp
.lisp
16
40.375
74
0.668061
karlosz/common-lisp-wpilib
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a7b7a52c2025a98c4fc6daafaff12878b6eb392d8b8480e526f8d65c0c6a84fc
23,574
[ -1 ]
23,575
functions.lisp
karlosz_common-lisp-wpilib/hal/functions.lisp
;;;; frc-hal.lisp (in-package #:frc-hal) (define-foreign-library libhalathena (t (:default "libHALAthena"))) (use-foreign-library libhalathena) ;;; Semaphore.hpp (cffi:defcfun ("initializeMutexNormal" initializeMutexNormal) :pointer) (cffi:defcfun ("deleteMutex" deleteMutex) :void (sem :pointer)) (cffi:defcfun ("takeMutex" takeMutex) :void (sem :pointer)) (cffi:defcfun ("tryTakeMutex" tryTakeMutex) :pointer (sem :pointer)) (cffi:defcfun ("giveMutex" giveMutex) :void (sem :pointer)) (cffi:defcfun ("initializeMultiWait" initializeMultiWait) :pointer) (cffi:defcfun ("deleteMultiWait" deleteMultiWait) :void (sem :pointer)) (cffi:defcfun ("takeMultiWait" takeMultiWait) :void (sem :pointer) (m :pointer)) (cffi:defcfun ("giveMultiWait" giveMultiWait) :void (sem :pointer)) ;;; HAL (cffi:defcfun ("getPort" getPort) :pointer (pin :pointer)) (cffi:defcfun ("getPortWithModule" getPortWithModule) :pointer (module :pointer) (pin :pointer)) (cffi:defcfun ("freePort" freePort) :void (port :pointer)) (cffi:defcfun ("getHALErrorMessage" getHALErrorMessage) :string (code :pointer)) (cffi:defcfun ("getFPGAVersion" getFPGAVersion) :pointer (status :pointer)) (cffi:defcfun ("getFPGARevision" getFPGARevision) :pointer (status :pointer)) (cffi:defcfun ("getFPGATime" getFPGATime) :pointer (status :pointer)) (cffi:defcfun ("getFPGAButton" getFPGAButton) :pointer (status :pointer)) (cffi:defcfun ("HALSetErrorData" HALSetErrorData) :int (errors :string) (errorsLength :int) (wait_ms :int)) (cffi:defcfun ("HALSendError" HALSendError) :int (isError :int) (errorCode :pointer) (isLVCode :int) (details :string) (location :string) (callStack :string) (printMsg :int)) (cffi:defcfun ("HALGetControlWord" HALGetControlWord) :int (data :pointer)) (cffi:defcfun ("HALGetAllianceStation" HALGetAllianceStation) :int (allianceStation :pointer)) (cffi:defcfun ("HALGetJoystickAxes" HALGetJoystickAxes) :int (joystickNum :pointer) (axes :pointer)) (cffi:defcfun ("HALGetJoystickPOVs" HALGetJoystickPOVs) :int (joystickNum :pointer) (povs :pointer)) (cffi:defcfun ("HALGetJoystickButtons" HALGetJoystickButtons) :int (joystickNum :pointer) (buttons :pointer)) (cffi:defcfun ("HALGetJoystickDescriptor" HALGetJoystickDescriptor) :int (joystickNum :pointer) (desc :pointer)) (cffi:defcfun ("HALGetJoystickIsXbox" HALGetJoystickIsXbox) :int (joystickNum :pointer)) (cffi:defcfun ("HALGetJoystickType" HALGetJoystickType) :int (joystickNum :pointer)) (cffi:defcfun ("HALGetJoystickName" HALGetJoystickName) :string (joystickNum :pointer)) (cffi:defcfun ("HALGetJoystickAxisType" HALGetJoystickAxisType) :int (joystickNum :pointer) (axis :pointer)) (cffi:defcfun ("HALSetJoystickOutputs" HALSetJoystickOutputs) :int (joystickNum :pointer) (outputs :pointer) (leftRumble :pointer) (rightRumble :pointer)) (cffi:defcfun ("HALGetMatchTime" HALGetMatchTime) :int (matchTime :pointer)) (cffi:defcfun ("HALSetNewDataSem" HALSetNewDataSem) :void (sem :pointer)) (cffi:defcfun ("HALGetSystemActive" HALGetSystemActive) :pointer (status :pointer)) (cffi:defcfun ("HALGetBrownedOut" HALGetBrownedOut) :pointer (status :pointer)) (cffi:defcfun ("HALInitialize" HALInitialize) :int (mode :int)) (cffi:defcfun ("HALNetworkCommunicationObserveUserProgramStarting" HALNetworkCommunicationObserveUserProgramStarting) :void) (cffi:defcfun ("HALNetworkCommunicationObserveUserProgramDisabled" HALNetworkCommunicationObserveUserProgramDisabled) :void) (cffi:defcfun ("HALNetworkCommunicationObserveUserProgramAutonomous" HALNetworkCommunicationObserveUserProgramAutonomous) :void) (cffi:defcfun ("HALNetworkCommunicationObserveUserProgramTeleop" HALNetworkCommunicationObserveUserProgramTeleop) :void) (cffi:defcfun ("HALNetworkCommunicationObserveUserProgramTest" HALNetworkCommunicationObserveUserProgramTest) :void) (cffi:defcfun ("HALReport" HALReport) :pointer (resource :pointer) (instanceNumber :pointer) (context :pointer) (feature :string)) ;;; Accelerometer (cffi:defcfun ("setAccelerometerActive" setAccelerometerActive) :void (arg0 :pointer)) (cffi:defcfun ("setAccelerometerRange" setAccelerometerRange) :void (arg0 :pointer ;;AccelerometerRange )) (cffi:defcfun ("getAccelerometerX" getAccelerometerX) :double) (cffi:defcfun ("getAccelerometerY" getAccelerometerY) :double) (cffi:defcfun ("getAccelerometerZ" getAccelerometerZ) :double) ;;;; Analog ;;; Output (cffi:defcfun ("initializeAnalogOutputPort" initializeAnalogOutputPort) :pointer (port_pointer :pointer) (status :pointer)) (cffi:defcfun ("freeAnalogOutputPort" freeAnalogOutputPort) :void (analog_port_pointer :pointer)) (cffi:defcfun ("setAnalogOutput" setAnalogOutput) :void (analog_port_pointer :pointer) (voltage :double) (status :pointer)) (cffi:defcfun ("getAnalogOutput" getAnalogOutput) :double (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("checkAnalogOutputChannel" checkAnalogOutputChannel) :pointer (pin :pointer)) ;;;Input (cffi:defcfun ("initializeAnalogInputPort" initializeAnalogInputPort) :pointer (port_pointer :pointer) (status :pointer)) (cffi:defcfun ("freeAnalogInputPort" freeAnalogInputPort) :void (analog_port_pointer :pointer)) (cffi:defcfun ("checkAnalogModule" checkAnalogModule) :pointer (module :pointer)) (cffi:defcfun ("checkAnalogInputChannel" checkAnalogInputChannel) :pointer (pin :pointer)) (cffi:defcfun ("setAnalogSampleRate" setAnalogSampleRate) :void (samplesPerSecond :double) (status :pointer)) (cffi:defcfun ("getAnalogSampleRate" getAnalogSampleRate) :float (status :pointer)) (cffi:defcfun ("setAnalogAverageBits" setAnalogAverageBits) :void (analog_port_pointer :pointer) (bits :pointer) (status :pointer)) (cffi:defcfun ("getAnalogAverageBits" getAnalogAverageBits) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("setAnalogOversampleBits" setAnalogOversampleBits) :void (analog_port_pointer :pointer) (bits :pointer) (status :pointer)) (cffi:defcfun ("getAnalogOversampleBits" getAnalogOversampleBits) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogValue" getAnalogValue) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogAverageValue" getAnalogAverageValue) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogVoltsToValue" getAnalogVoltsToValue) :pointer (analog_port_pointer :pointer) (voltage :double) (status :pointer)) (cffi:defcfun ("getAnalogVoltage" getAnalogVoltage) :float (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogAverageVoltage" getAnalogAverageVoltage) :float (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogLSBWeight" getAnalogLSBWeight) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogOffset" getAnalogOffset) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("isAccumulatorChannel" isAccumulatorChannel) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("initAccumulator" initAccumulator) :void (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("resetAccumulator" resetAccumulator) :void (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("setAccumulatorCenter" setAccumulatorCenter) :void (analog_port_pointer :pointer) (center :pointer) (status :pointer)) (cffi:defcfun ("setAccumulatorDeadband" setAccumulatorDeadband) :void (analog_port_pointer :pointer) (deadband :pointer) (status :pointer)) (cffi:defcfun ("getAccumulatorValue" getAccumulatorValue) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAccumulatorCount" getAccumulatorCount) :pointer (analog_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAccumulatorOutput" getAccumulatorOutput) :void (analog_port_pointer :pointer) (value :pointer) (count :pointer) (status :pointer)) (cffi:defcfun ("initializeAnalogTrigger" initializeAnalogTrigger) :pointer (port_pointer :pointer) (index :pointer) (status :pointer)) (cffi:defcfun ("cleanAnalogTrigger" cleanAnalogTrigger) :void (analog_trigger_pointer :pointer) (status :pointer)) (cffi:defcfun ("setAnalogTriggerLimitsRaw" setAnalogTriggerLimitsRaw) :void (analog_trigger_pointer :pointer) (lower :pointer) (upper :pointer) (status :pointer)) (cffi:defcfun ("setAnalogTriggerLimitsVoltage" setAnalogTriggerLimitsVoltage) :void (analog_trigger_pointer :pointer) (lower :double) (upper :double) (status :pointer)) (cffi:defcfun ("setAnalogTriggerAveraged" setAnalogTriggerAveraged) :void (analog_trigger_pointer :pointer) (useAveragedValue :pointer) (status :pointer)) (cffi:defcfun ("setAnalogTriggerFiltered" setAnalogTriggerFiltered) :void (analog_trigger_pointer :pointer) (useFilteredValue :pointer) (status :pointer)) (cffi:defcfun ("getAnalogTriggerInWindow" getAnalogTriggerInWindow) :pointer (analog_trigger_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogTriggerTriggerState" getAnalogTriggerTriggerState) :pointer (analog_trigger_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAnalogTriggerOutput" getAnalogTriggerOutput) :pointer (analog_trigger_pointer :pointer) (type :pointer ;;AnalogTriggerType ) (status :pointer)) ;;; Compressor (cffi:defcfun ("initializeCompressor" initializeCompressor) :pointer (module :pointer)) (cffi:defcfun ("checkCompressorModule" checkCompressorModule) :pointer (module :pointer)) (cffi:defcfun ("getCompressor" getCompressor) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("setClosedLoopControl" setClosedLoopControl) :void (pcm_pointer :pointer) (value :pointer) (status :pointer)) (cffi:defcfun ("getClosedLoopControl" getClosedLoopControl) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getPressureSwitch" getPressureSwitch) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorCurrent" getCompressorCurrent) :float (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorCurrentTooHighFault" getCompressorCurrentTooHighFault) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorCurrentTooHighStickyFault" getCompressorCurrentTooHighStickyFault) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorShortedStickyFault" getCompressorShortedStickyFault) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorShortedFault" getCompressorShortedFault) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorNotConnectedStickyFault" getCompressorNotConnectedStickyFault) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCompressorNotConnectedFault" getCompressorNotConnectedFault) :pointer (pcm_pointer :pointer) (status :pointer)) (cffi:defcfun ("clearAllPCMStickyFaults" clearAllPCMStickyFaults) :void (pcm_pointer :pointer) (status :pointer)) ;;; Digital (cffi:defcfun ("initializeDigitalPort" initializeDigitalPort) :pointer (port_pointer :pointer) (status :pointer)) (cffi:defcfun ("freeDigitalPort" freeDigitalPort) :void (digital_port_pointer :pointer)) (cffi:defcfun ("checkPWMChannel" checkPWMChannel) :pointer (digital_port_pointer :pointer)) (cffi:defcfun ("checkRelayChannel" checkRelayChannel) :pointer (digital_port_pointer :pointer)) (cffi:defcfun ("setPWM" setPWM) :void (digital_port_pointer :pointer) (value :unsigned-short) (status :pointer)) (cffi:defcfun ("allocatePWMChannel" allocatePWMChannel) :pointer (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("freePWMChannel" freePWMChannel) :void (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getPWM" getPWM) :unsigned-short (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("latchPWMZero" latchPWMZero) :void (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("setPWMPeriodScale" setPWMPeriodScale) :void (digital_port_pointer :pointer) (squelchMask :pointer) (status :pointer)) (cffi:defcfun ("allocatePWM" allocatePWM) :pointer (status :pointer)) (cffi:defcfun ("freePWM" freePWM) :void (pwmGenerator :pointer) (status :pointer)) (cffi:defcfun ("setPWMRate" setPWMRate) :void (rate :double) (status :pointer)) (cffi:defcfun ("setPWMDutyCycle" setPWMDutyCycle) :void (pwmGenerator :pointer) (dutyCycle :double) (status :pointer)) (cffi:defcfun ("setPWMOutputChannel" setPWMOutputChannel) :void (pwmGenerator :pointer) (pin :pointer) (status :pointer)) (cffi:defcfun ("setRelayForward" setRelayForward) :void (digital_port_pointer :pointer) (on :pointer) (status :pointer)) (cffi:defcfun ("setRelayReverse" setRelayReverse) :void (digital_port_pointer :pointer) (on :pointer) (status :pointer)) (cffi:defcfun ("getRelayForward" getRelayForward) :pointer (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getRelayReverse" getRelayReverse) :pointer (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("allocateDIO" allocateDIO) :pointer (digital_port_pointer :pointer) (input :pointer) (status :pointer)) (cffi:defcfun ("freeDIO" freeDIO) :void (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("setDIO" setDIO) :void (digital_port_pointer :pointer) (value :short) (status :pointer)) (cffi:defcfun ("getDIO" getDIO) :pointer (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getDIODirection" getDIODirection) :pointer (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("pulse" pulse) :void (digital_port_pointer :pointer) (pulseLength :double) (status :pointer)) (cffi:defcfun ("isPulsing" isPulsing) :pointer (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("isAnyPulsing" isAnyPulsing) :pointer (status :pointer)) (cffi:defcfun ("setFilterSelect" setFilterSelect) :void (digital_port_pointer :pointer) (filter_index :int) (status :pointer)) (cffi:defcfun ("getFilterSelect" getFilterSelect) :int (digital_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("setFilterPeriod" setFilterPeriod) :void (filter_index :int) (value :pointer) (status :pointer)) (cffi:defcfun ("getFilterPeriod" getFilterPeriod) :pointer (filter_index :int) (status :pointer)) (cffi:defcfun ("initializeCounter" initializeCounter) :pointer (mode :pointer ;;Mode ) (index :pointer) (status :pointer)) (cffi:defcfun ("freeCounter" freeCounter) :void (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterAverageSize" setCounterAverageSize) :void (counter_pointer :pointer) (size :pointer) (status :pointer)) (cffi:defcfun ("setCounterUpSource" setCounterUpSource) :void (counter_pointer :pointer) (pin :pointer) (analogTrigger :pointer) (status :pointer)) (cffi:defcfun ("setCounterUpSourceEdge" setCounterUpSourceEdge) :void (counter_pointer :pointer) (risingEdge :pointer) (fallingEdge :pointer) (status :pointer)) (cffi:defcfun ("clearCounterUpSource" clearCounterUpSource) :void (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterDownSource" setCounterDownSource) :void (counter_pointer :pointer) (pin :pointer) (analogTrigger :pointer) (status :pointer)) (cffi:defcfun ("setCounterDownSourceEdge" setCounterDownSourceEdge) :void (counter_pointer :pointer) (risingEdge :pointer) (fallingEdge :pointer) (status :pointer)) (cffi:defcfun ("clearCounterDownSource" clearCounterDownSource) :void (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterUpDownMode" setCounterUpDownMode) :void (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterExternalDirectionMode" setCounterExternalDirectionMode) :void (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterSemiPeriodMode" setCounterSemiPeriodMode) :void (counter_pointer :pointer) (highSemiPeriod :pointer) (status :pointer)) (cffi:defcfun ("setCounterPulseLengthMode" setCounterPulseLengthMode) :void (counter_pointer :pointer) (threshold :double) (status :pointer)) (cffi:defcfun ("getCounterSamplesToAverage" getCounterSamplesToAverage) :pointer (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterSamplesToAverage" setCounterSamplesToAverage) :void (counter_pointer :pointer) (samplesToAverage :int) (status :pointer)) (cffi:defcfun ("resetCounter" resetCounter) :void (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCounter" getCounter) :pointer (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCounterPeriod" getCounterPeriod) :double (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterMaxPeriod" setCounterMaxPeriod) :void (counter_pointer :pointer) (maxPeriod :double) (status :pointer)) (cffi:defcfun ("setCounterUpdateWhenEmpty" setCounterUpdateWhenEmpty) :void (counter_pointer :pointer) (enabled :pointer) (status :pointer)) (cffi:defcfun ("getCounterStopped" getCounterStopped) :pointer (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("getCounterDirection" getCounterDirection) :pointer (counter_pointer :pointer) (status :pointer)) (cffi:defcfun ("setCounterReverseDirection" setCounterReverseDirection) :void (counter_pointer :pointer) (reverseDirection :pointer) (status :pointer)) (cffi:defcfun ("initializeEncoder" initializeEncoder) :pointer (port_a_module :pointer) (port_a_pin :pointer) (port_a_analog_trigger :pointer) (port_b_module :pointer) (port_b_pin :pointer) (port_b_analog_trigger :pointer) (reverseDirection :pointer) (index :pointer) (status :pointer)) (cffi:defcfun ("freeEncoder" freeEncoder) :void (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("resetEncoder" resetEncoder) :void (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("getEncoder" getEncoder) :pointer (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("getEncoderPeriod" getEncoderPeriod) :double (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("setEncoderMaxPeriod" setEncoderMaxPeriod) :void (encoder_pointer :pointer) (maxPeriod :double) (status :pointer)) (cffi:defcfun ("getEncoderStopped" getEncoderStopped) :pointer (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("getEncoderDirection" getEncoderDirection) :pointer (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("setEncoderReverseDirection" setEncoderReverseDirection) :void (encoder_pointer :pointer) (reverseDirection :pointer) (status :pointer)) (cffi:defcfun ("setEncoderSamplesToAverage" setEncoderSamplesToAverage) :void (encoder_pointer :pointer) (samplesToAverage :pointer) (status :pointer)) (cffi:defcfun ("getEncoderSamplesToAverage" getEncoderSamplesToAverage) :pointer (encoder_pointer :pointer) (status :pointer)) (cffi:defcfun ("setEncoderIndexSource" setEncoderIndexSource) :void (encoder_pointer :pointer) (pin :pointer) (analogTrigger :pointer) (activeHigh :pointer) (edgeSensitive :pointer) (status :pointer)) (cffi:defcfun ("getLoopTiming" getLoopTiming) :pointer (status :pointer)) (cffi:defcfun ("spiInitialize" spiInitialize) :void (port :pointer) (status :pointer)) (cffi:defcfun ("spiTransaction" spiTransaction) :pointer (port :pointer) (dataToSend :pointer) (dataReceived :pointer) (size :pointer)) (cffi:defcfun ("spiWrite" spiWrite) :pointer (port :pointer) (dataToSend :pointer) (sendSize :pointer)) (cffi:defcfun ("spiRead" spiRead) :pointer (port :pointer) (buffer :pointer) (count :pointer)) (cffi:defcfun ("spiClose" spiClose) :void (port :pointer)) (cffi:defcfun ("spiSetSpeed" spiSetSpeed) :void (port :pointer) (speed :pointer)) (cffi:defcfun ("spiSetOpts" spiSetOpts) :void (port :pointer) (msb_first :int) (sample_on_trailing :int) (clk_idle_high :int)) (cffi:defcfun ("spiSetChipSelectActiveHigh" spiSetChipSelectActiveHigh) :void (port :pointer) (status :pointer)) (cffi:defcfun ("spiSetChipSelectActiveLow" spiSetChipSelectActiveLow) :void (port :pointer) (status :pointer)) (cffi:defcfun ("spiGetHandle" spiGetHandle) :pointer (port :pointer)) (cffi:defcfun ("spiSetHandle" spiSetHandle) :void (port :pointer) (handle :pointer)) (cffi:defcfun ("spiInitAccumulator" spiInitAccumulator) :void (port :pointer) (period :pointer) (cmd :pointer) (xfer_size :pointer) (valid_mask :pointer) (valid_value :pointer) (data_shift :pointer) (data_size :pointer) (is_signed :pointer) (big_endian :pointer) (status :pointer)) (cffi:defcfun ("spiFreeAccumulator" spiFreeAccumulator) :void (port :pointer) (status :pointer)) (cffi:defcfun ("spiResetAccumulator" spiResetAccumulator) :void (port :pointer) (status :pointer)) (cffi:defcfun ("spiSetAccumulatorCenter" spiSetAccumulatorCenter) :void (port :pointer) (center :pointer) (status :pointer)) (cffi:defcfun ("spiSetAccumulatorDeadband" spiSetAccumulatorDeadband) :void (port :pointer) (deadband :pointer) (status :pointer)) (cffi:defcfun ("spiGetAccumulatorLastValue" spiGetAccumulatorLastValue) :pointer (port :pointer) (status :pointer)) (cffi:defcfun ("spiGetAccumulatorValue" spiGetAccumulatorValue) :pointer (port :pointer) (status :pointer)) (cffi:defcfun ("spiGetAccumulatorCount" spiGetAccumulatorCount) :pointer (port :pointer) (status :pointer)) (cffi:defcfun ("spiGetAccumulatorAverage" spiGetAccumulatorAverage) :double (port :pointer) (status :pointer)) (cffi:defcfun ("spiGetAccumulatorOutput" spiGetAccumulatorOutput) :void (port :pointer) (value :pointer) (count :pointer) (status :pointer)) (cffi:defcfun ("i2CInitialize" i2CInitialize) :void (port :pointer) (status :pointer)) (cffi:defcfun ("i2CTransaction" i2CTransaction) :pointer (port :pointer) (deviceAddress :pointer) (dataToSend :pointer) (sendSize :pointer) (dataReceived :pointer) (receiveSize :pointer)) (cffi:defcfun ("i2CWrite" i2CWrite) :pointer (port :pointer) (deviceAddress :pointer) (dataToSend :pointer) (sendSize :pointer)) (cffi:defcfun ("i2CRead" i2CRead) :pointer (port :pointer) (deviceAddress :pointer) (buffer :pointer) (count :pointer)) (cffi:defcfun ("i2CClose" i2CClose) :void (port :pointer)) ;;; Interrupts (cffi:defcfun ("initializeInterrupts" initializeInterrupts) :pointer (interruptIndex :pointer) (watcher :pointer) (status :pointer)) (cffi:defcfun ("cleanInterrupts" cleanInterrupts) :void (interrupt_pointer :pointer) (status :pointer)) (cffi:defcfun ("waitForInterrupt" waitForInterrupt) :pointer (interrupt_pointer :pointer) (timeout :double) (ignorePrevious :pointer) (status :pointer)) (cffi:defcfun ("enableInterrupts" enableInterrupts) :void (interrupt_pointer :pointer) (status :pointer)) (cffi:defcfun ("disableInterrupts" disableInterrupts) :void (interrupt_pointer :pointer) (status :pointer)) (cffi:defcfun ("readRisingTimestamp" readRisingTimestamp) :double (interrupt_pointer :pointer) (status :pointer)) (cffi:defcfun ("readFallingTimestamp" readFallingTimestamp) :double (interrupt_pointer :pointer) (status :pointer)) (cffi:defcfun ("requestInterrupts" requestInterrupts) :void (interrupt_pointer :pointer) (routing_module :pointer) (routing_pin :pointer) (routing_analog_trigger :pointer) (status :pointer)) (cffi:defcfun ("attachInterruptHandler" attachInterruptHandler) :void (interrupt_pointer :pointer) (handler :pointer) (param :pointer) (status :pointer)) (cffi:defcfun ("setInterruptUpSourceEdge" setInterruptUpSourceEdge) :void (interrupt_pointer :pointer) (risingEdge :pointer) (fallingEdge :pointer) (status :pointer)) ;;; Notifier (cffi:defcfun ("initializeNotifier" initializeNotifier) :pointer (process :pointer) (param :pointer) (status :pointer)) (cffi:defcfun ("cleanNotifier" cleanNotifier) :void (notifier_pointer :pointer) (status :pointer)) (cffi:defcfun ("getNotifierParam" getNotifierParam) :pointer (notifier_pointer :pointer) (status :pointer)) (cffi:defcfun ("updateNotifierAlarm" updateNotifierAlarm) :void (notifier_pointer :pointer) (triggerTime :pointer) (status :pointer)) (cffi:defcfun ("stopNotifierAlarm" stopNotifierAlarm) :void (notifier_pointer :pointer) (status :pointer)) ;;; PDP (cffi:defcfun ("initializePDP" initializePDP) :void (module :pointer)) (cffi:defcfun ("getPDPTemperature" getPDPTemperature) :double (module :pointer) (status :pointer)) (cffi:defcfun ("getPDPVoltage" getPDPVoltage) :double (module :pointer) (status :pointer)) (cffi:defcfun ("getPDPChannelCurrent" getPDPChannelCurrent) :double (module :pointer) (channel :pointer) (status :pointer)) (cffi:defcfun ("getPDPTotalCurrent" getPDPTotalCurrent) :double (module :pointer) (status :pointer)) (cffi:defcfun ("getPDPTotalPower" getPDPTotalPower) :double (module :pointer) (status :pointer)) (cffi:defcfun ("getPDPTotalEnergy" getPDPTotalEnergy) :double (module :pointer) (status :pointer)) (cffi:defcfun ("resetPDPTotalEnergy" resetPDPTotalEnergy) :void (module :pointer) (status :pointer)) (cffi:defcfun ("clearPDPStickyFaults" clearPDPStickyFaults) :void (module :pointer) (status :pointer)) ;;; Power (cffi:defcfun ("getVinVoltage" getVinVoltage) :float (status :pointer)) (cffi:defcfun ("getVinCurrent" getVinCurrent) :float (status :pointer)) (cffi:defcfun ("getUserVoltage6V" getUserVoltage6V) :float (status :pointer)) (cffi:defcfun ("getUserCurrent6V" getUserCurrent6V) :float (status :pointer)) (cffi:defcfun ("getUserActive6V" getUserActive6V) :pointer (status :pointer)) (cffi:defcfun ("getUserCurrentFaults6V" getUserCurrentFaults6V) :int (status :pointer)) (cffi:defcfun ("getUserVoltage5V" getUserVoltage5V) :float (status :pointer)) (cffi:defcfun ("getUserCurrent5V" getUserCurrent5V) :float (status :pointer)) (cffi:defcfun ("getUserActive5V" getUserActive5V) :pointer (status :pointer)) (cffi:defcfun ("getUserCurrentFaults5V" getUserCurrentFaults5V) :int (status :pointer)) (cffi:defcfun ("getUserVoltage3V3" getUserVoltage3V3) :float (status :pointer)) (cffi:defcfun ("getUserCurrent3V3" getUserCurrent3V3) :float (status :pointer)) (cffi:defcfun ("getUserActive3V3" getUserActive3V3) :pointer (status :pointer)) (cffi:defcfun ("getUserCurrentFaults3V3" getUserCurrentFaults3V3) :int (status :pointer)) ;;; Solenoid (cffi:defcfun ("initializeSolenoidPort" initializeSolenoidPort) :pointer (port_pointer :pointer) (status :pointer)) (cffi:defcfun ("freeSolenoidPort" freeSolenoidPort) :void (solenoid_port_pointer :pointer)) (cffi:defcfun ("checkSolenoidModule" checkSolenoidModule) :pointer (module :pointer)) (cffi:defcfun ("getSolenoid" getSolenoid) :pointer (solenoid_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getAllSolenoids" getAllSolenoids) :pointer (solenoid_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("setSolenoid" setSolenoid) :void (solenoid_port_pointer :pointer) (value :pointer) (status :pointer)) (cffi:defcfun ("getPCMSolenoidBlackList" getPCMSolenoidBlackList) :int (solenoid_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getPCMSolenoidVoltageStickyFault" getPCMSolenoidVoltageStickyFault) :pointer (solenoid_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("getPCMSolenoidVoltageFault" getPCMSolenoidVoltageFault) :pointer (solenoid_port_pointer :pointer) (status :pointer)) (cffi:defcfun ("clearAllPCMStickyFaults_sol" clearAllPCMStickyFaults_sol) :void (solenoid_port_pointer :pointer) (status :pointer))
28,120
Common Lisp
.lisp
774
33.661499
128
0.777171
karlosz/common-lisp-wpilib
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e1907229c166240a5c8b486e2080a26c633510f1f83e15ae46b0c6fdcef436cf
23,575
[ -1 ]
23,576
test.lisp
karlosz_common-lisp-wpilib/hal/test.lisp
(in-package #:frc-hal) (defvar *status-code-ptr* (foreign-alloc :int32)) (defclass dio-port () ((%channel :reader dio-port-channel :initarg :channel) (%pointer :reader dio-port-pointer :initarg :pointer) (%direction :accessor dio-port-direction :initarg :direction))) (defun make-dio-port (channel direction) "Takes a channel and direction, where input is either :OUTPUT or :INPUT." (unless (<= 0 channel 25) (error "Not a port number between 0 and 26.")) (make-instance 'dio-port :channel channel :pointer (let ((pointer (initializedigitalport (getport channel) *status-code-ptr*))) (allocatedio pointer (ecase direction (:output nil) (:input t)) *status-code-ptr*) pointer) :direction direction)) (defun read-dio-port (dio-port) (unless (eq (dio-port-direction dio-port) :input) (error "Not input direction dio-port.")) (getdio (dio-port-pointer dio-port) *status-code-ptr*)) (defun write-dio-port (new-value dio-port) (unless (eq dio-port-direction :output) (error "not output direction dio-port.")) (config-dio-port (dio-port-channel dio) nil) (setdio dio-port (if new-value 1 0) *status-code-ptr*)) (defun clear-status () (setf (mem-ref *status-code-ptr* :int32) 0)) (defun get-status () (mem-ref *status-code-ptr* :int32)) (defun print-status () (let ((status (get-status))) (if (not (zerop status)) (print (gethalerrormessage status))))) (defmacro check-status (&body code) `(progn (clear-status) (let ((result (progn ,@code))) (print-status) result)))
1,835
Common Lisp
.lisp
45
31.444444
75
0.587872
karlosz/common-lisp-wpilib
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d138690c9f3d48c0a2a6188ed8a388d561b99b164041c7d9353aeac1b83a1712
23,576
[ -1 ]
23,577
frc-hal.asd
karlosz_common-lisp-wpilib/hal/frc-hal.asd
;;;; frc-hal.asd (asdf:defsystem #:frc-hal :description "Hal bindings" :author "Your Name <[email protected]>" :license "Specify license here" :serial t :depends-on (#:cffi) :components ((:file "package") (:file "functions") (:file "test")))
289
Common Lisp
.asd
10
23.6
45
0.607914
karlosz/common-lisp-wpilib
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0fc6997182c296ce854bb0f8aebba5e4db7357e307531ff42caaa20b2a9f23e9
23,577
[ -1 ]
23,579
roborio-install.sh
karlosz_common-lisp-wpilib/roborio-install.sh
#!/bin/bash ## This install script installs this library onto the roboRIO. ## Run this script every time the version in source control changes ## on the host machine function gethelp { echo "Usage: roborio-install.sh [-p port] [-d dir] [-l user@hostname]" echo "Default behaviour is to upload the working directory to [email protected]:22" } ARGS=$(getopt -o hp:d:l: --long --help -- "$@") if [ $? -ne 0 ]; then gethelp exit 1 fi PORT=22 DIR=$(pwd) HOST="[email protected]" eval set -- "$ARGS" while true; do case "$1" in -h|--help) gethelp; exit 0 ;; -p) PORT="$2"; shift 2 ;; -d) DIR="$2"; shift 2 ;; -l) HOST="$2"; shift 2 ;; --) shift; break ;; esac done if [ "$@" ]; then gethelp exit 1 fi BOTDIR=${DIR##*/} ssh -p$PORT $HOST "rm -rf $BOTDIR" scp -rpq -P$PORT $DIR $HOST:$BOTDIR
852
Common Lisp
.l
34
22.764706
99
0.651048
karlosz/common-lisp-wpilib
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
960f79985f172433f3d1224f656c53abe66ef90b0d5e1f513ab6cc53bd17a176
23,579
[ -1 ]
23,598
chapter-11.lisp
namoamitabha_study-common-lisp/successful-lisp/chapter-11.lisp
(let ((e 1)) (defun closure-1 () e)) (closure-1) (let ((e 1)) (defun closure-1 () e) (setq e 7) (defun closure-2 () e)) (let ((counter 0)) (defun counter-next () (incf counter)) (defun counter-reset () (setq counter 0))) (let ((fns ())) (dotimes (i 3) (push #'(lambda () i) fns)) (mapcar #'funcall fns)) (let ((fns ())) (dotimes (i 3) (let ((i i)) (push #'(lambda () i) fns))) (mapcar #'funcall fns)) (defun nil-nth (n l) (setf (nth n l) nil) 1) (defparameter *my-list* (list 1 2 3 4)) (nil-nth 1 *my-list*) *my-list* (defun nil-nth (n l) (let ((tmp)) (if (zerop n) (setq tmp (cons nil (rest l))) (setq tmp (cons (car l) (nil-nth (1- n) (rest l))))) (print tmp) tmp)) (defparameter *my-list* (list 1 2 3 4)) (nil-nth 1 *my-list*) *my-list* ;;******************** (defparameter list1 (list 1 2 3)) (defparameter list2 (list 4 5 6)) (append list1 list2) (nconc list1 list2) ;;******************** (defparameter *my-list* (list 1 2 3 4)) (rplacd *my-list* (cdr (cdr *my-list*))) (let ((l (list 1))) (rplacd l l) l) (let ((l (list 2))) (rplaca l l) l) ;;******************** (defparameter *my-list* (list 1 2 3 4)) (delete 3 *my-list*) (delete 1 *my-list*) (defparameter *stack* ()) (push 3 *stack*) (push 2 *stack*) (push 1 *stack*) (pop *stack*) *stack* ;;******************** (defun stomp-a-constant () (let ((l '(1 2 3))) (print l) (setf (second l) nil) l)) (stomp-a-constant) (stomp-a-constant)
1,498
Common Lisp
.lisp
69
19.231884
53
0.553508
namoamitabha/study-common-lisp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
db55a94cfdb0f3845a55917306cd216cdfd194d85d4646809174d4f16ee3beac
23,598
[ -1 ]
23,599
util1.lisp
namoamitabha_study-common-lisp/successful-lisp/util1.lisp
(defpackage util1 (:export init func1 func2) (:use common-lisp)) (in-package util1) (defun init () 'util1-init) (defun func1 () 'util1-func1) (defun func2 () 'util1-func2)
180
Common Lisp
.lisp
7
23.571429
29
0.710059
namoamitabha/study-common-lisp
1
0
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
707f0e9d94575d53c29737d9611f94aec2a1e487d83d6c13e2f37561693fab93
23,599
[ 390014 ]